1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.jvm;
  27 
  28 import java.io.*;
  29 import java.net.URI;
  30 import java.net.URISyntaxException;
  31 import java.nio.CharBuffer;
  32 import java.nio.file.ClosedFileSystemException;
  33 import java.util.Arrays;
  34 import java.util.EnumSet;
  35 import java.util.HashMap;
  36 import java.util.HashSet;
  37 import java.util.Map;
  38 import java.util.Set;
  39 import java.util.function.IntFunction;
  40 
  41 import javax.lang.model.element.Modifier;
  42 import javax.lang.model.element.NestingKind;
  43 import javax.tools.JavaFileManager;
  44 import javax.tools.JavaFileObject;
  45 
  46 import com.sun.tools.javac.code.Source.Feature;
  47 import com.sun.tools.javac.code.Type.ClassType.Flavor;
  48 import com.sun.tools.javac.comp.Annotate;
  49 import com.sun.tools.javac.comp.Annotate.AnnotationTypeCompleter;
  50 import com.sun.tools.javac.code.*;
  51 import com.sun.tools.javac.code.Directive.*;
  52 import com.sun.tools.javac.code.Lint.LintCategory;
  53 import com.sun.tools.javac.code.Scope.WriteableScope;
  54 import com.sun.tools.javac.code.Symbol.*;
  55 import com.sun.tools.javac.code.Symtab;
  56 import com.sun.tools.javac.code.Type.*;
  57 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  58 import com.sun.tools.javac.file.BaseFileManager;
  59 import com.sun.tools.javac.file.PathFileObject;
  60 import com.sun.tools.javac.jvm.ClassFile.Version;
  61 import com.sun.tools.javac.jvm.PoolConstant.NameAndType;
  62 import com.sun.tools.javac.main.Option;
  63 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  64 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  65 import com.sun.tools.javac.util.*;
  66 import com.sun.tools.javac.util.DefinedBy.Api;
  67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  68 
  69 import static com.sun.tools.javac.code.Flags.*;
  70 import static com.sun.tools.javac.code.Kinds.Kind.*;
  71 
  72 import com.sun.tools.javac.code.Scope.LookupKind;
  73 
  74 import static com.sun.tools.javac.code.TypeTag.ARRAY;
  75 import static com.sun.tools.javac.code.TypeTag.CLASS;
  76 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
  77 import static com.sun.tools.javac.jvm.ClassFile.*;
  78 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
  79 
  80 import static com.sun.tools.javac.main.Option.PARAMETERS;
  81 
  82 /** This class provides operations to read a classfile into an internal
  83  *  representation. The internal representation is anchored in a
  84  *  ClassSymbol which contains in its scope symbol representations
  85  *  for all other definitions in the classfile. Top-level Classes themselves
  86  *  appear as members of the scopes of PackageSymbols.
  87  *
  88  *  <p><b>This is NOT part of any supported API.
  89  *  If you write code that depends on this, you do so at your own risk.
  90  *  This code and its internal interfaces are subject to change or
  91  *  deletion without notice.</b>
  92  */
  93 public class ClassReader {
  94     /** The context key for the class reader. */
  95     protected static final Context.Key<ClassReader> classReaderKey = new Context.Key<>();
  96 
  97     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
  98 
  99     private final Annotate annotate;
 100 
 101     /** Switch: verbose output.
 102      */
 103     boolean verbose;
 104 
 105     /** Switch: allow modules.
 106      */
 107     boolean allowModules;
 108 
 109     /** Switch: allow primitive classes.
 110      */
 111     boolean allowPrimitiveClasses;
 112 
 113     /** Switch: allow sealed
 114      */
 115     boolean allowSealedTypes;
 116 
 117     /** Switch: allow records
 118      */
 119     boolean allowRecords;
 120 
 121    /** Lint option: warn about classfile issues
 122      */
 123     boolean lintClassfile;
 124 
 125     /** Switch: preserve parameter names from the variable table.
 126      */
 127     public boolean saveParameterNames;
 128 
 129     /**
 130      * The currently selected profile.
 131      */
 132     public final Profile profile;
 133 
 134     /** The log to use for verbose output
 135      */
 136     final Log log;
 137 
 138     /** The symbol table. */
 139     Symtab syms;
 140 
 141     Types types;
 142 
 143     /** The name table. */
 144     final Names names;
 145 
 146     /** Access to files
 147      */
 148     private final JavaFileManager fileManager;
 149 
 150     /** Factory for diagnostics
 151      */
 152     JCDiagnostic.Factory diagFactory;
 153 
 154     DeferredCompletionFailureHandler dcfh;
 155 
 156     /**
 157      * Support for preview language features.
 158      */
 159     Preview preview;
 160 
 161     /** The current scope where type variables are entered.
 162      */
 163     protected WriteableScope typevars;
 164 
 165     private List<InterimUsesDirective> interimUses = List.nil();
 166     private List<InterimProvidesDirective> interimProvides = List.nil();
 167 
 168     /** The path name of the class file currently being read.
 169      */
 170     protected JavaFileObject currentClassFile = null;
 171 
 172     /** The class or method currently being read.
 173      */
 174     protected Symbol currentOwner = null;
 175 
 176     /** The module containing the class currently being read.
 177      */
 178     protected ModuleSymbol currentModule = null;
 179 
 180     /** The buffer containing the currently read class file.
 181      */
 182     ByteBuffer buf = new ByteBuffer(INITIAL_BUFFER_SIZE);
 183 
 184     /** The current input pointer.
 185      */
 186     protected int bp;
 187 
 188     /** The pool reader.
 189      */
 190     PoolReader poolReader;
 191 
 192     /** The major version number of the class file being read. */
 193     int majorVersion;
 194     /** The minor version number of the class file being read. */
 195     int minorVersion;
 196 
 197     /** A table to hold the constant pool indices for method parameter
 198      * names, as given in LocalVariableTable attributes.
 199      */
 200     int[] parameterNameIndices;
 201 
 202     /**
 203      * A table to hold the access flags of the method parameters.
 204      */
 205     int[] parameterAccessFlags;
 206 
 207     /**
 208      * A table to hold annotations for method parameters.
 209      */
 210     ParameterAnnotations[] parameterAnnotations;
 211 
 212     /**
 213      * A holder for parameter annotations.
 214      */
 215     static class ParameterAnnotations {
 216         List<CompoundAnnotationProxy> proxies;
 217 
 218         void add(List<CompoundAnnotationProxy> newAnnotations) {
 219             if (proxies == null) {
 220                 proxies = newAnnotations;
 221             } else {
 222                 proxies = proxies.prependList(newAnnotations);
 223             }
 224         }
 225     }
 226 
 227     /**
 228      * Whether or not any parameter names have been found.
 229      */
 230     boolean haveParameterNameIndices;
 231 
 232     /** Set this to false every time we start reading a method
 233      * and are saving parameter names.  Set it to true when we see
 234      * MethodParameters, if it's set when we see a LocalVariableTable,
 235      * then we ignore the parameter names from the LVT.
 236      */
 237     boolean sawMethodParameters;
 238 
 239     /**
 240      * The set of attribute names for which warnings have been generated for the current class
 241      */
 242     Set<Name> warnedAttrs = new HashSet<>();
 243 
 244     /**
 245      * The prototype @Target Attribute.Compound if this class is an annotation annotated with
 246      * @Target
 247      */
 248     CompoundAnnotationProxy target;
 249 
 250     /**
 251      * The prototype @Repeatable Attribute.Compound if this class is an annotation annotated with
 252      * @Repeatable
 253      */
 254     CompoundAnnotationProxy repeatable;
 255 
 256     /** Get the ClassReader instance for this invocation. */
 257     public static ClassReader instance(Context context) {
 258         ClassReader instance = context.get(classReaderKey);
 259         if (instance == null)
 260             instance = new ClassReader(context);
 261         return instance;
 262     }
 263 
 264     /** Construct a new class reader. */
 265     protected ClassReader(Context context) {
 266         context.put(classReaderKey, this);
 267         annotate = Annotate.instance(context);
 268         names = Names.instance(context);
 269         syms = Symtab.instance(context);
 270         types = Types.instance(context);
 271         fileManager = context.get(JavaFileManager.class);
 272         if (fileManager == null)
 273             throw new AssertionError("FileManager initialization error");
 274         diagFactory = JCDiagnostic.Factory.instance(context);
 275         dcfh = DeferredCompletionFailureHandler.instance(context);
 276 
 277         log = Log.instance(context);
 278 
 279         Options options = Options.instance(context);
 280         verbose         = options.isSet(Option.VERBOSE);
 281 
 282         Source source = Source.instance(context);
 283         preview = Preview.instance(context);
 284         allowModules     = Feature.MODULES.allowedInSource(source);
 285         allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source);
 286         allowRecords = Feature.RECORDS.allowedInSource(source);
 287         allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source);
 288 
 289         saveParameterNames = options.isSet(PARAMETERS);
 290 
 291         profile = Profile.instance(context);
 292 
 293         typevars = WriteableScope.create(syms.noSymbol);
 294 
 295         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
 296 
 297         initAttributeReaders();
 298     }
 299 
 300     /** Add member to class unless it is synthetic.
 301      */
 302     private void enterMember(ClassSymbol c, Symbol sym) {
 303         // Synthetic members are not entered -- reason lost to history (optimization?).
 304         // Lambda methods must be entered because they may have inner classes (which reference them)
 305         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
 306             c.members_field.enter(sym);
 307     }
 308 
 309 /************************************************************************
 310  * Error Diagnoses
 311  ***********************************************************************/
 312 
 313     public ClassFinder.BadClassFile badClassFile(String key, Object... args) {
 314         return new ClassFinder.BadClassFile (
 315             currentOwner.enclClass(),
 316             currentClassFile,
 317             diagFactory.fragment(key, args),
 318             diagFactory,
 319             dcfh);
 320     }
 321 
 322     public ClassFinder.BadEnclosingMethodAttr badEnclosingMethod(Symbol sym) {
 323         return new ClassFinder.BadEnclosingMethodAttr (
 324             currentOwner.enclClass(),
 325             currentClassFile,
 326             diagFactory.fragment(Fragments.BadEnclosingMethod(sym)),
 327             diagFactory,
 328             dcfh);
 329     }
 330 
 331 /************************************************************************
 332  * Buffer Access
 333  ***********************************************************************/
 334 
 335     /** Read a character.
 336      */
 337     char nextChar() {
 338         char res = buf.getChar(bp);
 339         bp += 2;
 340         return res;
 341     }
 342 
 343     /** Read a byte.
 344      */
 345     int nextByte() {
 346         return buf.getByte(bp++) & 0xFF;
 347     }
 348 
 349     /** Read an integer.
 350      */
 351     int nextInt() {
 352         int res = buf.getInt(bp);
 353         bp += 4;
 354         return res;
 355     }
 356 
 357 /************************************************************************
 358  * Constant Pool Access
 359  ***********************************************************************/
 360 
 361     /** Read module_flags.
 362      */
 363     Set<ModuleFlags> readModuleFlags(int flags) {
 364         Set<ModuleFlags> set = EnumSet.noneOf(ModuleFlags.class);
 365         for (ModuleFlags f : ModuleFlags.values()) {
 366             if ((flags & f.value) != 0)
 367                 set.add(f);
 368         }
 369         return set;
 370     }
 371 
 372     /** Read resolution_flags.
 373      */
 374     Set<ModuleResolutionFlags> readModuleResolutionFlags(int flags) {
 375         Set<ModuleResolutionFlags> set = EnumSet.noneOf(ModuleResolutionFlags.class);
 376         for (ModuleResolutionFlags f : ModuleResolutionFlags.values()) {
 377             if ((flags & f.value) != 0)
 378                 set.add(f);
 379         }
 380         return set;
 381     }
 382 
 383     /** Read exports_flags.
 384      */
 385     Set<ExportsFlag> readExportsFlags(int flags) {
 386         Set<ExportsFlag> set = EnumSet.noneOf(ExportsFlag.class);
 387         for (ExportsFlag f: ExportsFlag.values()) {
 388             if ((flags & f.value) != 0)
 389                 set.add(f);
 390         }
 391         return set;
 392     }
 393 
 394     /** Read opens_flags.
 395      */
 396     Set<OpensFlag> readOpensFlags(int flags) {
 397         Set<OpensFlag> set = EnumSet.noneOf(OpensFlag.class);
 398         for (OpensFlag f: OpensFlag.values()) {
 399             if ((flags & f.value) != 0)
 400                 set.add(f);
 401         }
 402         return set;
 403     }
 404 
 405     /** Read requires_flags.
 406      */
 407     Set<RequiresFlag> readRequiresFlags(int flags) {
 408         Set<RequiresFlag> set = EnumSet.noneOf(RequiresFlag.class);
 409         for (RequiresFlag f: RequiresFlag.values()) {
 410             if ((flags & f.value) != 0)
 411                 set.add(f);
 412         }
 413         return set;
 414     }
 415 
 416 /************************************************************************
 417  * Reading Types
 418  ***********************************************************************/
 419 
 420     /** The unread portion of the currently read type is
 421      *  signature[sigp..siglimit-1].
 422      */
 423     byte[] signature;
 424     int sigp;
 425     int siglimit;
 426     boolean sigEnterPhase = false;
 427 
 428     /** Convert signature to type, where signature is a byte array segment.
 429      */
 430     Type sigToType(byte[] sig, int offset, int len) {
 431         signature = sig;
 432         sigp = offset;
 433         siglimit = offset + len;
 434         return sigToType();
 435     }
 436 
 437     /** Convert signature to type, where signature is implicit.
 438      */
 439     Type sigToType() {
 440         switch ((char) signature[sigp]) {
 441         case 'T':
 442             sigp++;
 443             int start = sigp;
 444             while (signature[sigp] != ';') sigp++;
 445             sigp++;
 446             return sigEnterPhase
 447                 ? Type.noType
 448                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
 449         case '+': {
 450             sigp++;
 451             Type t = sigToType();
 452             return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass);
 453         }
 454         case '*':
 455             sigp++;
 456             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
 457                                     syms.boundClass);
 458         case '-': {
 459             sigp++;
 460             Type t = sigToType();
 461             return new WildcardType(t, BoundKind.SUPER, syms.boundClass);
 462         }
 463         case 'B':
 464             sigp++;
 465             return syms.byteType;
 466         case 'C':
 467             sigp++;
 468             return syms.charType;
 469         case 'D':
 470             sigp++;
 471             return syms.doubleType;
 472         case 'F':
 473             sigp++;
 474             return syms.floatType;
 475         case 'I':
 476             sigp++;
 477             return syms.intType;
 478         case 'J':
 479             sigp++;
 480             return syms.longType;
 481         case 'Q':
 482         case 'L':
 483             {
 484                 // int oldsigp = sigp;
 485                 Type t = classSigToType();
 486                 if (sigp < siglimit && signature[sigp] == '.')
 487                     throw badClassFile("deprecated inner class signature syntax " +
 488                                        "(please recompile from source)");
 489                 /*
 490                 System.err.println(" decoded " +
 491                                    new String(signature, oldsigp, sigp-oldsigp) +
 492                                    " => " + t + " outer " + t.outer());
 493                 */
 494                 return t;
 495             }
 496         case 'S':
 497             sigp++;
 498             return syms.shortType;
 499         case 'V':
 500             sigp++;
 501             return syms.voidType;
 502         case 'Z':
 503             sigp++;
 504             return syms.booleanType;
 505         case '[':
 506             sigp++;
 507             return new ArrayType(sigToType(), syms.arrayClass);
 508         case '(':
 509             sigp++;
 510             List<Type> argtypes = sigToTypes(')');
 511             Type restype = sigToType();
 512             List<Type> thrown = List.nil();
 513             while (sigp < siglimit && signature[sigp] == '^') {
 514                 sigp++;
 515                 thrown = thrown.prepend(sigToType());
 516             }
 517             // if there is a typevar in the throws clause we should state it.
 518             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
 519                 if (l.head.hasTag(TYPEVAR)) {
 520                     l.head.tsym.flags_field |= THROWS;
 521                 }
 522             }
 523             return new MethodType(argtypes,
 524                                   restype,
 525                                   thrown.reverse(),
 526                                   syms.methodClass);
 527         case '<':
 528             typevars = typevars.dup(currentOwner);
 529             Type poly = new ForAll(sigToTypeParams(), sigToType());
 530             typevars = typevars.leave();
 531             return poly;
 532         default:
 533             throw badClassFile("bad.signature",
 534                                Convert.utf2string(signature, sigp, 10));
 535         }
 536     }
 537 
 538     byte[] signatureBuffer = new byte[0];
 539     int sbp = 0;
 540     /** Convert class signature to type, where signature is implicit.
 541      */
 542     Type classSigToType() {
 543         byte prefix = signature[sigp];
 544         if (prefix != 'L' && prefix != 'Q')
 545             throw badClassFile("bad.class.signature",
 546                                Convert.utf2string(signature, sigp, 10));
 547         sigp++;
 548         Type outer = Type.noType;
 549         Name name;
 550         ClassType.Flavor flavor;
 551         int startSbp = sbp;
 552 
 553         while (true) {
 554             final byte c = signature[sigp++];
 555             switch (c) {
 556 
 557             case ';': {         // end
 558                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
 559                                                          startSbp,
 560                                                          sbp - startSbp));
 561 
 562                 // We are seeing QFoo; or LFoo; The name itself does not shine any light on default val-refness
 563                 flavor = prefix == 'L' ? Flavor.L_TypeOf_X : Flavor.Q_TypeOf_X;
 564                 try {
 565                     if (outer == Type.noType) {
 566                         ClassType et = (ClassType) t.erasure(types);
 567                         // Todo: This spews out more objects than before, i.e no reuse with identical flavor
 568                         return new ClassType(et.getEnclosingType(), List.nil(), et.tsym, et.getMetadata(), flavor);
 569                     }
 570                     return new ClassType(outer, List.nil(), t, TypeMetadata.EMPTY, flavor);
 571                 } finally {
 572                     sbp = startSbp;
 573                 }
 574             }
 575 
 576             case '<':           // generic arguments
 577                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
 578                                                          startSbp,
 579                                                          sbp - startSbp));
 580                 // We are seeing QFoo; or LFoo; The name itself does not shine any light on default val-refness
 581                 flavor = prefix == 'L' ? Flavor.L_TypeOf_X : Flavor.Q_TypeOf_X;
 582                 outer = new ClassType(outer, sigToTypes('>'), t, TypeMetadata.EMPTY, flavor) {
 583                         boolean completed = false;
 584                         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 585                         public Type getEnclosingType() {
 586                             if (!completed) {
 587                                 completed = true;
 588                                 tsym.apiComplete();
 589                                 Type enclosingType = tsym.type.getEnclosingType();
 590                                 if (enclosingType != Type.noType) {
 591                                     List<Type> typeArgs =
 592                                         super.getEnclosingType().allparams();
 593                                     List<Type> typeParams =
 594                                         enclosingType.allparams();
 595                                     if (typeParams.length() != typeArgs.length()) {
 596                                         // no "rare" types
 597                                         super.setEnclosingType(types.erasure(enclosingType));
 598                                     } else {
 599                                         super.setEnclosingType(types.subst(enclosingType,
 600                                                                            typeParams,
 601                                                                            typeArgs));
 602                                     }
 603                                 } else {
 604                                     super.setEnclosingType(Type.noType);
 605                                 }
 606                             }
 607                             return super.getEnclosingType();
 608                         }
 609                         @Override
 610                         public void setEnclosingType(Type outer) {
 611                             throw new UnsupportedOperationException();
 612                         }
 613                     };
 614                 switch (signature[sigp++]) {
 615                 case ';':
 616                     if (sigp < siglimit && signature[sigp] == '.') {
 617                         // support old-style GJC signatures
 618                         // The signature produced was
 619                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
 620                         // rather than say
 621                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
 622                         // so we skip past ".Lfoo/Outer$"
 623                         sigp += (sbp - startSbp) + // "foo/Outer"
 624                             3;  // ".L" and "$"
 625                         signatureBuffer[sbp++] = (byte)'$';
 626                         break;
 627                     } else {
 628                         sbp = startSbp;
 629                         return outer;
 630                     }
 631                 case '.':
 632                     signatureBuffer[sbp++] = (byte)'$';
 633                     break;
 634                 default:
 635                     throw new AssertionError(signature[sigp-1]);
 636                 }
 637                 continue;
 638 
 639             case '.':
 640                 //we have seen an enclosing non-generic class
 641                 if (outer != Type.noType) {
 642                     t = enterClass(names.fromUtf(signatureBuffer,
 643                                                  startSbp,
 644                                                  sbp - startSbp));
 645                     // We are seeing QFoo; or LFoo; The name itself does not shine any light on default val-refness
 646                     flavor = prefix == 'L' ? Flavor.L_TypeOf_X : Flavor.Q_TypeOf_X;
 647                     outer = new ClassType(outer, List.nil(), t, TypeMetadata.EMPTY, flavor);
 648                 }
 649                 signatureBuffer[sbp++] = (byte)'$';
 650                 continue;
 651             case '/':
 652                 signatureBuffer[sbp++] = (byte)'.';
 653                 continue;
 654             default:
 655                 signatureBuffer[sbp++] = c;
 656                 continue;
 657             }
 658         }
 659     }
 660 
 661     /** Convert (implicit) signature to list of types
 662      *  until `terminator' is encountered.
 663      */
 664     List<Type> sigToTypes(char terminator) {
 665         List<Type> head = List.of(null);
 666         List<Type> tail = head;
 667         while (signature[sigp] != terminator)
 668             tail = tail.setTail(List.of(sigToType()));
 669         sigp++;
 670         return head.tail;
 671     }
 672 
 673     /** Convert signature to type parameters, where signature is a byte
 674      *  array segment.
 675      */
 676     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
 677         signature = sig;
 678         sigp = offset;
 679         siglimit = offset + len;
 680         return sigToTypeParams();
 681     }
 682 
 683     /** Convert signature to type parameters, where signature is implicit.
 684      */
 685     List<Type> sigToTypeParams() {
 686         List<Type> tvars = List.nil();
 687         if (signature[sigp] == '<') {
 688             sigp++;
 689             int start = sigp;
 690             sigEnterPhase = true;
 691             while (signature[sigp] != '>')
 692                 tvars = tvars.prepend(sigToTypeParam());
 693             sigEnterPhase = false;
 694             sigp = start;
 695             while (signature[sigp] != '>')
 696                 sigToTypeParam();
 697             sigp++;
 698         }
 699         return tvars.reverse();
 700     }
 701 
 702     /** Convert (implicit) signature to type parameter.
 703      */
 704     Type sigToTypeParam() {
 705         int start = sigp;
 706         while (signature[sigp] != ':') sigp++;
 707         Name name = names.fromUtf(signature, start, sigp - start);
 708         TypeVar tvar;
 709         if (sigEnterPhase) {
 710             tvar = new TypeVar(name, currentOwner, syms.botType);
 711             typevars.enter(tvar.tsym);
 712         } else {
 713             tvar = (TypeVar)findTypeVar(name);
 714         }
 715         List<Type> bounds = List.nil();
 716         boolean allInterfaces = false;
 717         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
 718             sigp++;
 719             allInterfaces = true;
 720         }
 721         while (signature[sigp] == ':') {
 722             sigp++;
 723             bounds = bounds.prepend(sigToType());
 724         }
 725         if (!sigEnterPhase) {
 726             types.setBounds(tvar, bounds.reverse(), allInterfaces);
 727         }
 728         return tvar;
 729     }
 730 
 731     /** Find type variable with given name in `typevars' scope.
 732      */
 733     Type findTypeVar(Name name) {
 734         Symbol s = typevars.findFirst(name);
 735         if (s != null) {
 736             return s.type;
 737         } else {
 738             if (readingClassAttr) {
 739                 // While reading the class attribute, the supertypes
 740                 // might refer to a type variable from an enclosing element
 741                 // (method or class).
 742                 // If the type variable is defined in the enclosing class,
 743                 // we can actually find it in
 744                 // currentOwner.owner.type.getTypeArguments()
 745                 // However, until we have read the enclosing method attribute
 746                 // we don't know for sure if this owner is correct.  It could
 747                 // be a method and there is no way to tell before reading the
 748                 // enclosing method attribute.
 749                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
 750                 missingTypeVariables = missingTypeVariables.prepend(t);
 751                 // System.err.println("Missing type var " + name);
 752                 return t;
 753             }
 754             throw badClassFile("undecl.type.var", name);
 755         }
 756     }
 757 
 758 /************************************************************************
 759  * Reading Attributes
 760  ***********************************************************************/
 761 
 762     protected enum AttributeKind { CLASS, MEMBER }
 763 
 764     protected abstract class AttributeReader {
 765         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
 766             this.name = name;
 767             this.version = version;
 768             this.kinds = kinds;
 769         }
 770 
 771         protected boolean accepts(AttributeKind kind) {
 772             if (kinds.contains(kind)) {
 773                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
 774                     return true;
 775 
 776                 if (lintClassfile && !warnedAttrs.contains(name)) {
 777                     JavaFileObject prev = log.useSource(currentClassFile);
 778                     try {
 779                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null,
 780                                     Warnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion));
 781                     } finally {
 782                         log.useSource(prev);
 783                     }
 784                     warnedAttrs.add(name);
 785                 }
 786             }
 787             return false;
 788         }
 789 
 790         protected abstract void read(Symbol sym, int attrLen);
 791 
 792         protected final Name name;
 793         protected final ClassFile.Version version;
 794         protected final Set<AttributeKind> kinds;
 795     }
 796 
 797     protected Set<AttributeKind> CLASS_ATTRIBUTE =
 798             EnumSet.of(AttributeKind.CLASS);
 799     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
 800             EnumSet.of(AttributeKind.MEMBER);
 801     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
 802             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
 803 
 804     protected Map<Name, AttributeReader> attributeReaders = new HashMap<>();
 805 
 806     private void initAttributeReaders() {
 807         AttributeReader[] readers = {
 808             // v45.3 attributes
 809 
 810             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
 811                 protected void read(Symbol sym, int attrLen) {
 812                     if (allowPrimitiveClasses) {
 813                         if (sym.isConstructor()  && ((MethodSymbol) sym).type.getParameterTypes().size() == 0) {
 814                             int code_length = buf.getInt(bp + 4);
 815                             if ((code_length == 1 && buf.getByte( bp + 8) == (byte) ByteCodes.return_) ||
 816                                     (code_length == 5 && buf.getByte(bp + 8) == ByteCodes.aload_0 &&
 817                                         buf.getByte( bp + 9) == (byte) ByteCodes.invokespecial &&
 818                                                 buf.getByte( bp + 12) == (byte) ByteCodes.return_)) {
 819                                     sym.flags_field |= EMPTYNOARGCONSTR;
 820                             }
 821                         }
 822                     }
 823                     if (saveParameterNames)
 824                         ((MethodSymbol)sym).code = readCode(sym);
 825                     else
 826                         bp = bp + attrLen;
 827                 }
 828             },
 829 
 830             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
 831                 protected void read(Symbol sym, int attrLen) {
 832                     Object v = poolReader.getConstant(nextChar());
 833                     // Ignore ConstantValue attribute if field not final.
 834                     if ((sym.flags() & FINAL) == 0) {
 835                         return;
 836                     }
 837                     VarSymbol var = (VarSymbol) sym;
 838                     switch (var.type.getTag()) {
 839                        case BOOLEAN:
 840                        case BYTE:
 841                        case CHAR:
 842                        case SHORT:
 843                        case INT:
 844                            checkType(var, Integer.class, v);
 845                            break;
 846                        case LONG:
 847                            checkType(var, Long.class, v);
 848                            break;
 849                        case FLOAT:
 850                            checkType(var, Float.class, v);
 851                            break;
 852                        case DOUBLE:
 853                            checkType(var, Double.class, v);
 854                            break;
 855                        case CLASS:
 856                            if (var.type.tsym == syms.stringType.tsym) {
 857                                checkType(var, String.class, v);
 858                            } else {
 859                                throw badClassFile("bad.constant.value.type", var.type);
 860                            }
 861                            break;
 862                        default:
 863                            // ignore ConstantValue attribute if type is not primitive or String
 864                            return;
 865                     }
 866                     if (v instanceof Integer intVal && !var.type.getTag().checkRange(intVal)) {
 867                         throw badClassFile("bad.constant.range", v, var, var.type);
 868                     }
 869                     var.setData(v);
 870                 }
 871 
 872                 void checkType(Symbol var, Class<?> clazz, Object value) {
 873                     if (!clazz.isInstance(value)) {
 874                         throw badClassFile("bad.constant.value", value, var, clazz.getSimpleName());
 875                     }
 876                 }
 877             },
 878 
 879             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
 880                 protected void read(Symbol sym, int attrLen) {
 881                     Symbol s = sym.owner.kind == MDL ? sym.owner : sym;
 882 
 883                     s.flags_field |= DEPRECATED;
 884                 }
 885             },
 886 
 887             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
 888                 protected void read(Symbol sym, int attrLen) {
 889                     int nexceptions = nextChar();
 890                     List<Type> thrown = List.nil();
 891                     for (int j = 0; j < nexceptions; j++)
 892                         thrown = thrown.prepend(poolReader.getClass(nextChar()).type);
 893                     if (sym.type.getThrownTypes().isEmpty())
 894                         sym.type.asMethodType().thrown = thrown.reverse();
 895                 }
 896             },
 897 
 898             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
 899                 protected void read(Symbol sym, int attrLen) {
 900                     ClassSymbol c = (ClassSymbol) sym;
 901                     if (currentModule.module_info == c) {
 902                         //prevent entering the classes too soon:
 903                         skipInnerClasses();
 904                     } else {
 905                         readInnerClasses(c);
 906                     }
 907                 }
 908             },
 909 
 910             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
 911                 protected void read(Symbol sym, int attrLen) {
 912                     int newbp = bp + attrLen;
 913                     if (saveParameterNames && !sawMethodParameters) {
 914                         // Pick up parameter names from the variable table.
 915                         // Parameter names are not explicitly identified as such,
 916                         // but all parameter name entries in the LocalVariableTable
 917                         // have a start_pc of 0.  Therefore, we record the name
 918                         // indices of all slots with a start_pc of zero in the
 919                         // parameterNameIndices array.
 920                         // Note that this implicitly honors the JVMS spec that
 921                         // there may be more than one LocalVariableTable, and that
 922                         // there is no specified ordering for the entries.
 923                         int numEntries = nextChar();
 924                         for (int i = 0; i < numEntries; i++) {
 925                             int start_pc = nextChar();
 926                             int length = nextChar();
 927                             int nameIndex = nextChar();
 928                             int sigIndex = nextChar();
 929                             int register = nextChar();
 930                             if (start_pc == 0) {
 931                                 // ensure array large enough
 932                                 if (register >= parameterNameIndices.length) {
 933                                     int newSize =
 934                                             Math.max(register + 1, parameterNameIndices.length + 8);
 935                                     parameterNameIndices =
 936                                             Arrays.copyOf(parameterNameIndices, newSize);
 937                                 }
 938                                 parameterNameIndices[register] = nameIndex;
 939                                 haveParameterNameIndices = true;
 940                             }
 941                         }
 942                     }
 943                     bp = newbp;
 944                 }
 945             },
 946 
 947             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
 948                 protected void read(Symbol sym, int attrLen) {
 949                     ClassSymbol c = (ClassSymbol) sym;
 950                     Name n = poolReader.getName(nextChar());
 951                     c.sourcefile = new SourceFileObject(n);
 952                     // If the class is a toplevel class, originating from a Java source file,
 953                     // but the class name does not match the file name, then it is
 954                     // an auxiliary class.
 955                     String sn = n.toString();
 956                     if (c.owner.kind == PCK &&
 957                         sn.endsWith(".java") &&
 958                         !sn.equals(c.name.toString()+".java")) {
 959                         c.flags_field |= AUXILIARY;
 960                     }
 961                 }
 962             },
 963 
 964             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
 965                 protected void read(Symbol sym, int attrLen) {
 966                     sym.flags_field |= SYNTHETIC;
 967                 }
 968             },
 969 
 970             // standard v49 attributes
 971 
 972             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
 973                 protected void read(Symbol sym, int attrLen) {
 974                     int newbp = bp + attrLen;
 975                     readEnclosingMethodAttr(sym);
 976                     bp = newbp;
 977                 }
 978             },
 979 
 980             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
 981                 protected void read(Symbol sym, int attrLen) {
 982                     if (sym.kind == TYP) {
 983                         ClassSymbol c = (ClassSymbol) sym;
 984                         readingClassAttr = true;
 985                         try {
 986                             ClassType ct1 = (ClassType)c.type;
 987                             Assert.check(c == currentOwner);
 988                             ct1.typarams_field = poolReader.getName(nextChar())
 989                                     .map(ClassReader.this::sigToTypeParams);
 990                             ct1.supertype_field = sigToType();
 991                             ListBuffer<Type> is = new ListBuffer<>();
 992                             while (sigp != siglimit) is.append(sigToType());
 993                             ct1.interfaces_field = is.toList();
 994                         } finally {
 995                             readingClassAttr = false;
 996                         }
 997                     } else {
 998                         List<Type> thrown = sym.type.getThrownTypes();
 999                         sym.type = poolReader.getType(nextChar());
1000                         //- System.err.println(" # " + sym.type);
1001                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1002                             sym.type.asMethodType().thrown = thrown;
1003                         if (sym.kind == MTH  && sym.name == names.init && sym.owner.isPrimitiveClass()) {
1004                             sym.type = new MethodType(sym.type.getParameterTypes(),
1005                                     syms.voidType,
1006                                     sym.type.getThrownTypes(),
1007                                     syms.methodClass);
1008                         }
1009 
1010                     }
1011                 }
1012             },
1013 
1014             // v49 annotation attributes
1015 
1016             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1017                 protected void read(Symbol sym, int attrLen) {
1018                     attachAnnotationDefault(sym);
1019                 }
1020             },
1021 
1022             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1023                 protected void read(Symbol sym, int attrLen) {
1024                     attachAnnotations(sym);
1025                 }
1026             },
1027 
1028             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1029                 protected void read(Symbol sym, int attrLen) {
1030                     readParameterAnnotations(sym);
1031                 }
1032             },
1033 
1034             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1035                 protected void read(Symbol sym, int attrLen) {
1036                     attachAnnotations(sym);
1037                 }
1038             },
1039 
1040             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1041                 protected void read(Symbol sym, int attrLen) {
1042                     readParameterAnnotations(sym);
1043                 }
1044             },
1045 
1046             // additional "legacy" v49 attributes, superseded by flags
1047 
1048             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1049                 protected void read(Symbol sym, int attrLen) {
1050                     sym.flags_field |= ANNOTATION;
1051                 }
1052             },
1053 
1054             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1055                 protected void read(Symbol sym, int attrLen) {
1056                     sym.flags_field |= BRIDGE;
1057                 }
1058             },
1059 
1060             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1061                 protected void read(Symbol sym, int attrLen) {
1062                     sym.flags_field |= ENUM;
1063                 }
1064             },
1065 
1066             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1067                 protected void read(Symbol sym, int attrLen) {
1068                     sym.flags_field |= VARARGS;
1069                 }
1070             },
1071 
1072             new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1073                 protected void read(Symbol sym, int attrLen) {
1074                     attachTypeAnnotations(sym);
1075                 }
1076             },
1077 
1078             new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1079                 protected void read(Symbol sym, int attrLen) {
1080                     attachTypeAnnotations(sym);
1081                 }
1082             },
1083 
1084             // The following attributes for a Code attribute are not currently handled
1085             // StackMapTable
1086             // SourceDebugExtension
1087             // LineNumberTable
1088             // LocalVariableTypeTable
1089 
1090             // standard v52 attributes
1091 
1092             new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
1093                 protected void read(Symbol sym, int attrlen) {
1094                     int newbp = bp + attrlen;
1095                     if (saveParameterNames) {
1096                         sawMethodParameters = true;
1097                         int numEntries = nextByte();
1098                         parameterNameIndices = new int[numEntries];
1099                         parameterAccessFlags = new int[numEntries];
1100                         haveParameterNameIndices = true;
1101                         int index = 0;
1102                         for (int i = 0; i < numEntries; i++) {
1103                             int nameIndex = nextChar();
1104                             int flags = nextChar();
1105                             if ((flags & (Flags.MANDATED | Flags.SYNTHETIC)) != 0) {
1106                                 continue;
1107                             }
1108                             parameterNameIndices[index] = nameIndex;
1109                             parameterAccessFlags[index] = flags;
1110                             index++;
1111                         }
1112                     }
1113                     bp = newbp;
1114                 }
1115             },
1116 
1117             // standard v53 attributes
1118 
1119             new AttributeReader(names.Module, V53, CLASS_ATTRIBUTE) {
1120                 @Override
1121                 protected boolean accepts(AttributeKind kind) {
1122                     return super.accepts(kind) && allowModules;
1123                 }
1124                 protected void read(Symbol sym, int attrLen) {
1125                     if (sym.kind == TYP && sym.owner.kind == MDL) {
1126                         ModuleSymbol msym = (ModuleSymbol) sym.owner;
1127                         ListBuffer<Directive> directives = new ListBuffer<>();
1128 
1129                         Name moduleName = poolReader.peekModuleName(nextChar(), names::fromUtf);
1130                         if (currentModule.name != moduleName) {
1131                             throw badClassFile("module.name.mismatch", moduleName, currentModule.name);
1132                         }
1133 
1134                         Set<ModuleFlags> moduleFlags = readModuleFlags(nextChar());
1135                         msym.flags.addAll(moduleFlags);
1136                         msym.version = optPoolEntry(nextChar(), poolReader::getName, null);
1137 
1138                         ListBuffer<RequiresDirective> requires = new ListBuffer<>();
1139                         int nrequires = nextChar();
1140                         for (int i = 0; i < nrequires; i++) {
1141                             ModuleSymbol rsym = poolReader.getModule(nextChar());
1142                             Set<RequiresFlag> flags = readRequiresFlags(nextChar());
1143                             if (rsym == syms.java_base && majorVersion >= V54.major) {
1144                                 if (flags.contains(RequiresFlag.TRANSITIVE)) {
1145                                     throw badClassFile("bad.requires.flag", RequiresFlag.TRANSITIVE);
1146                                 }
1147                                 if (flags.contains(RequiresFlag.STATIC_PHASE)) {
1148                                     throw badClassFile("bad.requires.flag", RequiresFlag.STATIC_PHASE);
1149                                 }
1150                             }
1151                             nextChar(); // skip compiled version
1152                             requires.add(new RequiresDirective(rsym, flags));
1153                         }
1154                         msym.requires = requires.toList();
1155                         directives.addAll(msym.requires);
1156 
1157                         ListBuffer<ExportsDirective> exports = new ListBuffer<>();
1158                         int nexports = nextChar();
1159                         for (int i = 0; i < nexports; i++) {
1160                             PackageSymbol p = poolReader.getPackage(nextChar());
1161                             Set<ExportsFlag> flags = readExportsFlags(nextChar());
1162                             int nto = nextChar();
1163                             List<ModuleSymbol> to;
1164                             if (nto == 0) {
1165                                 to = null;
1166                             } else {
1167                                 ListBuffer<ModuleSymbol> lb = new ListBuffer<>();
1168                                 for (int t = 0; t < nto; t++)
1169                                     lb.append(poolReader.getModule(nextChar()));
1170                                 to = lb.toList();
1171                             }
1172                             exports.add(new ExportsDirective(p, to, flags));
1173                         }
1174                         msym.exports = exports.toList();
1175                         directives.addAll(msym.exports);
1176                         ListBuffer<OpensDirective> opens = new ListBuffer<>();
1177                         int nopens = nextChar();
1178                         if (nopens != 0 && msym.flags.contains(ModuleFlags.OPEN)) {
1179                             throw badClassFile("module.non.zero.opens", currentModule.name);
1180                         }
1181                         for (int i = 0; i < nopens; i++) {
1182                             PackageSymbol p = poolReader.getPackage(nextChar());
1183                             Set<OpensFlag> flags = readOpensFlags(nextChar());
1184                             int nto = nextChar();
1185                             List<ModuleSymbol> to;
1186                             if (nto == 0) {
1187                                 to = null;
1188                             } else {
1189                                 ListBuffer<ModuleSymbol> lb = new ListBuffer<>();
1190                                 for (int t = 0; t < nto; t++)
1191                                     lb.append(poolReader.getModule(nextChar()));
1192                                 to = lb.toList();
1193                             }
1194                             opens.add(new OpensDirective(p, to, flags));
1195                         }
1196                         msym.opens = opens.toList();
1197                         directives.addAll(msym.opens);
1198 
1199                         msym.directives = directives.toList();
1200 
1201                         ListBuffer<InterimUsesDirective> uses = new ListBuffer<>();
1202                         int nuses = nextChar();
1203                         for (int i = 0; i < nuses; i++) {
1204                             Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper);
1205                             uses.add(new InterimUsesDirective(srvc));
1206                         }
1207                         interimUses = uses.toList();
1208 
1209                         ListBuffer<InterimProvidesDirective> provides = new ListBuffer<>();
1210                         int nprovides = nextChar();
1211                         for (int p = 0; p < nprovides; p++) {
1212                             Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper);
1213                             int nimpls = nextChar();
1214                             ListBuffer<Name> impls = new ListBuffer<>();
1215                             for (int i = 0; i < nimpls; i++) {
1216                                 impls.append(poolReader.peekClassName(nextChar(), this::classNameMapper));
1217                             provides.add(new InterimProvidesDirective(srvc, impls.toList()));
1218                             }
1219                         }
1220                         interimProvides = provides.toList();
1221                     }
1222                 }
1223 
1224                 private Name classNameMapper(byte[] arr, int offset, int length) {
1225                     return names.fromUtf(ClassFile.internalize(arr, offset, length));
1226                 }
1227             },
1228 
1229             new AttributeReader(names.ModuleResolution, V53, CLASS_ATTRIBUTE) {
1230                 @Override
1231                 protected boolean accepts(AttributeKind kind) {
1232                     return super.accepts(kind) && allowModules;
1233                 }
1234                 protected void read(Symbol sym, int attrLen) {
1235                     if (sym.kind == TYP && sym.owner.kind == MDL) {
1236                         ModuleSymbol msym = (ModuleSymbol) sym.owner;
1237                         msym.resolutionFlags.addAll(readModuleResolutionFlags(nextChar()));
1238                     }
1239                 }
1240             },
1241 
1242             new AttributeReader(names.Record, V58, CLASS_ATTRIBUTE) {
1243                 @Override
1244                 protected boolean accepts(AttributeKind kind) {
1245                     return super.accepts(kind) && allowRecords;
1246                 }
1247                 protected void read(Symbol sym, int attrLen) {
1248                     if (sym.kind == TYP) {
1249                         sym.flags_field |= RECORD;
1250                     }
1251                     int componentCount = nextChar();
1252                     ListBuffer<RecordComponent> components = new ListBuffer<>();
1253                     for (int i = 0; i < componentCount; i++) {
1254                         Name name = poolReader.getName(nextChar());
1255                         Type type = poolReader.getType(nextChar());
1256                         RecordComponent c = new RecordComponent(name, type, sym);
1257                         readAttrs(c, AttributeKind.MEMBER);
1258                         components.add(c);
1259                     }
1260                     ((ClassSymbol) sym).setRecordComponents(components.toList());
1261                 }
1262             },
1263             new AttributeReader(names.PermittedSubclasses, V59, CLASS_ATTRIBUTE) {
1264                 @Override
1265                 protected boolean accepts(AttributeKind kind) {
1266                     return super.accepts(kind) && allowSealedTypes;
1267                 }
1268                 protected void read(Symbol sym, int attrLen) {
1269                     if (sym.kind == TYP) {
1270                         ListBuffer<Symbol> subtypes = new ListBuffer<>();
1271                         int numberOfPermittedSubtypes = nextChar();
1272                         for (int i = 0; i < numberOfPermittedSubtypes; i++) {
1273                             subtypes.add(poolReader.getClass(nextChar()));
1274                         }
1275                         ((ClassSymbol)sym).permitted = subtypes.toList();
1276                     }
1277                 }
1278             },
1279             new AttributeReader(names.JavaFlags, V61, CLASS_ATTRIBUTE) {
1280                 @Override
1281                 protected boolean accepts(AttributeKind kind) {
1282                     return super.accepts(kind) && allowPrimitiveClasses;
1283                 }
1284                 protected void read(Symbol sym, int attrLen) {
1285                     if (sym.kind == TYP) {
1286                         int extendedFlags = nextChar();
1287                         if ((extendedFlags & ACC_REF_DEFAULT) != 0)
1288                         ((ClassSymbol)sym).flags_field |= REFERENCE_FAVORING;
1289                     }
1290                 }
1291             }
1292         };
1293 
1294         for (AttributeReader r: readers)
1295             attributeReaders.put(r.name, r);
1296     }
1297 
1298     protected void readEnclosingMethodAttr(Symbol sym) {
1299         // sym is a nested class with an "Enclosing Method" attribute
1300         // remove sym from it's current owners scope and place it in
1301         // the scope specified by the attribute
1302         sym.owner.members().remove(sym);
1303         ClassSymbol self = (ClassSymbol)sym;
1304         ClassSymbol c = poolReader.getClass(nextChar());
1305         NameAndType nt = optPoolEntry(nextChar(), poolReader::getNameAndType, null);
1306 
1307         if (c.members_field == null || c.kind != TYP)
1308             throw badClassFile("bad.enclosing.class", self, c);
1309 
1310         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1311         if (nt != null && m == null)
1312             throw badEnclosingMethod(self);
1313 
1314         self.name = simpleBinaryName(self.flatname, c.flatname) ;
1315         self.owner = m != null ? m : c;
1316         if (self.name.isEmpty())
1317             self.fullname = names.empty;
1318         else
1319             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1320 
1321         if (m != null) {
1322             ((ClassType)sym.type).setEnclosingType(m.type);
1323         } else if ((self.flags_field & STATIC) == 0) {
1324             ((ClassType)sym.type).setEnclosingType(c.type);
1325         } else {
1326             ((ClassType)sym.type).setEnclosingType(Type.noType);
1327         }
1328         enterTypevars(self, self.type);
1329         if (!missingTypeVariables.isEmpty()) {
1330             ListBuffer<Type> typeVars =  new ListBuffer<>();
1331             for (Type typevar : missingTypeVariables) {
1332                 typeVars.append(findTypeVar(typevar.tsym.name));
1333             }
1334             foundTypeVariables = typeVars.toList();
1335         } else {
1336             foundTypeVariables = List.nil();
1337         }
1338     }
1339 
1340     // See java.lang.Class
1341     private Name simpleBinaryName(Name self, Name enclosing) {
1342         if (!self.startsWith(enclosing)) {
1343             throw badClassFile("bad.enclosing.method", self);
1344         }
1345 
1346         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1347         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1348             throw badClassFile("bad.enclosing.method", self);
1349         int index = 1;
1350         while (index < simpleBinaryName.length() &&
1351                isAsciiDigit(simpleBinaryName.charAt(index)))
1352             index++;
1353         return names.fromString(simpleBinaryName.substring(index));
1354     }
1355 
1356     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1357         if (nt == null)
1358             return null;
1359 
1360         MethodType type = nt.type.asMethodType();
1361 
1362         for (Symbol sym : scope.getSymbolsByName(nt.name)) {
1363             if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type))
1364                 return (MethodSymbol)sym;
1365         }
1366 
1367         if (nt.name != names.init)
1368             // not a constructor
1369             return null;
1370         if ((flags & INTERFACE) != 0)
1371             // no enclosing instance
1372             return null;
1373         if (nt.type.getParameterTypes().isEmpty())
1374             // no parameters
1375             return null;
1376 
1377         // A constructor of an inner class.
1378         // Remove the first argument (the enclosing instance)
1379         nt = new NameAndType(nt.name, new MethodType(nt.type.getParameterTypes().tail,
1380                                  nt.type.getReturnType(),
1381                                  nt.type.getThrownTypes(),
1382                                  syms.methodClass));
1383         // Try searching again
1384         return findMethod(nt, scope, flags);
1385     }
1386 
1387     /** Similar to Types.isSameType but avoids completion */
1388     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1389         List<Type> types1 = types.erasure(mt1.getParameterTypes())
1390             .prepend(types.erasure(mt1.getReturnType()));
1391         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1392         while (!types1.isEmpty() && !types2.isEmpty()) {
1393             if (types1.head.tsym != types2.head.tsym)
1394                 return false;
1395             types1 = types1.tail;
1396             types2 = types2.tail;
1397         }
1398         return types1.isEmpty() && types2.isEmpty();
1399     }
1400 
1401     /**
1402      * Character.isDigit answers <tt>true</tt> to some non-ascii
1403      * digits.  This one does not.  <b>copied from java.lang.Class</b>
1404      */
1405     private static boolean isAsciiDigit(char c) {
1406         return '0' <= c && c <= '9';
1407     }
1408 
1409     /** Read member attributes.
1410      */
1411     void readMemberAttrs(Symbol sym) {
1412         readAttrs(sym, AttributeKind.MEMBER);
1413     }
1414 
1415     void readAttrs(Symbol sym, AttributeKind kind) {
1416         char ac = nextChar();
1417         for (int i = 0; i < ac; i++) {
1418             Name attrName = poolReader.getName(nextChar());
1419             int attrLen = nextInt();
1420             AttributeReader r = attributeReaders.get(attrName);
1421             if (r != null && r.accepts(kind))
1422                 r.read(sym, attrLen);
1423             else  {
1424                 bp = bp + attrLen;
1425             }
1426         }
1427     }
1428 
1429     private boolean readingClassAttr = false;
1430     private List<Type> missingTypeVariables = List.nil();
1431     private List<Type> foundTypeVariables = List.nil();
1432 
1433     /** Read class attributes.
1434      */
1435     void readClassAttrs(ClassSymbol c) {
1436         readAttrs(c, AttributeKind.CLASS);
1437     }
1438 
1439     /** Read code block.
1440      */
1441     Code readCode(Symbol owner) {
1442         nextChar(); // max_stack
1443         nextChar(); // max_locals
1444         final int  code_length = nextInt();
1445         bp += code_length;
1446         final char exception_table_length = nextChar();
1447         bp += exception_table_length * 8;
1448         readMemberAttrs(owner);
1449         return null;
1450     }
1451 
1452 /************************************************************************
1453  * Reading Java-language annotations
1454  ***********************************************************************/
1455 
1456     /**
1457      * Save annotations.
1458      */
1459     List<CompoundAnnotationProxy> readAnnotations() {
1460         int numAttributes = nextChar();
1461         ListBuffer<CompoundAnnotationProxy> annotations = new ListBuffer<>();
1462         for (int i = 0; i < numAttributes; i++) {
1463             annotations.append(readCompoundAnnotation());
1464         }
1465         return annotations.toList();
1466     }
1467 
1468     /** Attach annotations.
1469      */
1470     void attachAnnotations(final Symbol sym) {
1471         attachAnnotations(sym, readAnnotations());
1472     }
1473 
1474     /**
1475      * Attach annotations.
1476      */
1477     void attachAnnotations(final Symbol sym, List<CompoundAnnotationProxy> annotations) {
1478         if (annotations.isEmpty()) {
1479             return;
1480         }
1481         ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>();
1482         for (CompoundAnnotationProxy proxy : annotations) {
1483             if (proxy.type.tsym.flatName() == syms.proprietaryType.tsym.flatName())
1484                 sym.flags_field |= PROPRIETARY;
1485             else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) {
1486                 if (profile != Profile.DEFAULT) {
1487                     for (Pair<Name, Attribute> v : proxy.values) {
1488                         if (v.fst == names.value && v.snd instanceof Attribute.Constant constant) {
1489                             if (constant.type == syms.intType && ((Integer) constant.value) > profile.value) {
1490                                 sym.flags_field |= NOT_IN_PROFILE;
1491                             }
1492                         }
1493                     }
1494                 }
1495             } else if (proxy.type.tsym.flatName() == syms.previewFeatureInternalType.tsym.flatName()) {
1496                 sym.flags_field |= PREVIEW_API;
1497                 setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE);
1498             } else if (proxy.type.tsym.flatName() == syms.valueBasedInternalType.tsym.flatName()) {
1499                 Assert.check(sym.kind == TYP);
1500                 sym.flags_field |= VALUE_BASED;
1501             } else {
1502                 if (proxy.type.tsym == syms.annotationTargetType.tsym) {
1503                     target = proxy;
1504                 } else if (proxy.type.tsym == syms.repeatableType.tsym) {
1505                     repeatable = proxy;
1506                 } else if (proxy.type.tsym == syms.deprecatedType.tsym) {
1507                     sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION);
1508                     setFlagIfAttributeTrue(proxy, sym, names.forRemoval, DEPRECATED_REMOVAL);
1509                 }  else if (proxy.type.tsym == syms.previewFeatureType.tsym) {
1510                     sym.flags_field |= PREVIEW_API;
1511                     setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE);
1512                 }  else if (proxy.type.tsym == syms.valueBasedType.tsym && sym.kind == TYP) {
1513                     sym.flags_field |= VALUE_BASED;
1514                 }
1515                 proxies.append(proxy);
1516             }
1517         }
1518         annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1519     }
1520     //where:
1521         private void setFlagIfAttributeTrue(CompoundAnnotationProxy proxy, Symbol sym, Name attribute, long flag) {
1522             for (Pair<Name, Attribute> v : proxy.values) {
1523                 if (v.fst == attribute && v.snd instanceof Attribute.Constant constant) {
1524                     if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) {
1525                         sym.flags_field |= flag;
1526                     }
1527                 }
1528             }
1529         }
1530 
1531     /** Read parameter annotations.
1532      */
1533     void readParameterAnnotations(Symbol meth) {
1534         int numParameters = buf.getByte(bp++) & 0xFF;
1535         if (parameterAnnotations == null) {
1536             parameterAnnotations = new ParameterAnnotations[numParameters];
1537         } else if (parameterAnnotations.length != numParameters) {
1538             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1539         }
1540         for (int pnum = 0; pnum < numParameters; pnum++) {
1541             if (parameterAnnotations[pnum] == null) {
1542                 parameterAnnotations[pnum] = new ParameterAnnotations();
1543             }
1544             parameterAnnotations[pnum].add(readAnnotations());
1545         }
1546     }
1547 
1548     void attachTypeAnnotations(final Symbol sym) {
1549         int numAttributes = nextChar();
1550         if (numAttributes != 0) {
1551             ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>();
1552             for (int i = 0; i < numAttributes; i++)
1553                 proxies.append(readTypeAnnotation());
1554             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
1555         }
1556     }
1557 
1558     /** Attach the default value for an annotation element.
1559      */
1560     void attachAnnotationDefault(final Symbol sym) {
1561         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1562         final Attribute value = readAttributeValue();
1563 
1564         // The default value is set later during annotation. It might
1565         // be the case that the Symbol sym is annotated _after_ the
1566         // repeating instances that depend on this default value,
1567         // because of this we set an interim value that tells us this
1568         // element (most likely) has a default.
1569         //
1570         // Set interim value for now, reset just before we do this
1571         // properly at annotate time.
1572         meth.defaultValue = value;
1573         annotate.normal(new AnnotationDefaultCompleter(meth, value));
1574     }
1575 
1576     Type readTypeOrClassSymbol(int i) {
1577         return readTypeToProxy(i);
1578     }
1579     Type readTypeToProxy(int i) {
1580         if (currentModule.module_info == currentOwner) {
1581             return new ProxyType(i);
1582         } else {
1583             return poolReader.getType(i);
1584         }
1585     }
1586 
1587     CompoundAnnotationProxy readCompoundAnnotation() {
1588         Type t;
1589         if (currentModule.module_info == currentOwner) {
1590             int cpIndex = nextChar();
1591             t = new ProxyType(cpIndex);
1592         } else {
1593             t = readTypeOrClassSymbol(nextChar());
1594         }
1595         int numFields = nextChar();
1596         ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>();
1597         for (int i=0; i<numFields; i++) {
1598             Name name = poolReader.getName(nextChar());
1599             Attribute value = readAttributeValue();
1600             pairs.append(new Pair<>(name, value));
1601         }
1602         return new CompoundAnnotationProxy(t, pairs.toList());
1603     }
1604 
1605     TypeAnnotationProxy readTypeAnnotation() {
1606         TypeAnnotationPosition position = readPosition();
1607         CompoundAnnotationProxy proxy = readCompoundAnnotation();
1608 
1609         return new TypeAnnotationProxy(proxy, position);
1610     }
1611 
1612     TypeAnnotationPosition readPosition() {
1613         int tag = nextByte(); // TargetType tag is a byte
1614 
1615         if (!TargetType.isValidTargetTypeValue(tag))
1616             throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
1617 
1618         TargetType type = TargetType.fromTargetTypeValue(tag);
1619 
1620         switch (type) {
1621         // instanceof
1622         case INSTANCEOF: {
1623             final int offset = nextChar();
1624             final TypeAnnotationPosition position =
1625                 TypeAnnotationPosition.instanceOf(readTypePath());
1626             position.offset = offset;
1627             return position;
1628         }
1629         // new expression
1630         case NEW: {
1631             final int offset = nextChar();
1632             final TypeAnnotationPosition position =
1633                 TypeAnnotationPosition.newObj(readTypePath());
1634             position.offset = offset;
1635             return position;
1636         }
1637         // constructor/method reference receiver
1638         case CONSTRUCTOR_REFERENCE: {
1639             final int offset = nextChar();
1640             final TypeAnnotationPosition position =
1641                 TypeAnnotationPosition.constructorRef(readTypePath());
1642             position.offset = offset;
1643             return position;
1644         }
1645         case METHOD_REFERENCE: {
1646             final int offset = nextChar();
1647             final TypeAnnotationPosition position =
1648                 TypeAnnotationPosition.methodRef(readTypePath());
1649             position.offset = offset;
1650             return position;
1651         }
1652         // local variable
1653         case LOCAL_VARIABLE: {
1654             final int table_length = nextChar();
1655             final int[] newLvarOffset = new int[table_length];
1656             final int[] newLvarLength = new int[table_length];
1657             final int[] newLvarIndex = new int[table_length];
1658 
1659             for (int i = 0; i < table_length; ++i) {
1660                 newLvarOffset[i] = nextChar();
1661                 newLvarLength[i] = nextChar();
1662                 newLvarIndex[i] = nextChar();
1663             }
1664 
1665             final TypeAnnotationPosition position =
1666                     TypeAnnotationPosition.localVariable(readTypePath());
1667             position.lvarOffset = newLvarOffset;
1668             position.lvarLength = newLvarLength;
1669             position.lvarIndex = newLvarIndex;
1670             return position;
1671         }
1672         // resource variable
1673         case RESOURCE_VARIABLE: {
1674             final int table_length = nextChar();
1675             final int[] newLvarOffset = new int[table_length];
1676             final int[] newLvarLength = new int[table_length];
1677             final int[] newLvarIndex = new int[table_length];
1678 
1679             for (int i = 0; i < table_length; ++i) {
1680                 newLvarOffset[i] = nextChar();
1681                 newLvarLength[i] = nextChar();
1682                 newLvarIndex[i] = nextChar();
1683             }
1684 
1685             final TypeAnnotationPosition position =
1686                     TypeAnnotationPosition.resourceVariable(readTypePath());
1687             position.lvarOffset = newLvarOffset;
1688             position.lvarLength = newLvarLength;
1689             position.lvarIndex = newLvarIndex;
1690             return position;
1691         }
1692         // exception parameter
1693         case EXCEPTION_PARAMETER: {
1694             final int exception_index = nextChar();
1695             final TypeAnnotationPosition position =
1696                 TypeAnnotationPosition.exceptionParameter(readTypePath());
1697             position.setExceptionIndex(exception_index);
1698             return position;
1699         }
1700         // method receiver
1701         case METHOD_RECEIVER:
1702             return TypeAnnotationPosition.methodReceiver(readTypePath());
1703         // type parameter
1704         case CLASS_TYPE_PARAMETER: {
1705             final int parameter_index = nextByte();
1706             return TypeAnnotationPosition
1707                 .typeParameter(readTypePath(), parameter_index);
1708         }
1709         case METHOD_TYPE_PARAMETER: {
1710             final int parameter_index = nextByte();
1711             return TypeAnnotationPosition
1712                 .methodTypeParameter(readTypePath(), parameter_index);
1713         }
1714         // type parameter bound
1715         case CLASS_TYPE_PARAMETER_BOUND: {
1716             final int parameter_index = nextByte();
1717             final int bound_index = nextByte();
1718             return TypeAnnotationPosition
1719                 .typeParameterBound(readTypePath(), parameter_index,
1720                                     bound_index);
1721         }
1722         case METHOD_TYPE_PARAMETER_BOUND: {
1723             final int parameter_index = nextByte();
1724             final int bound_index = nextByte();
1725             return TypeAnnotationPosition
1726                 .methodTypeParameterBound(readTypePath(), parameter_index,
1727                                           bound_index);
1728         }
1729         // class extends or implements clause
1730         case CLASS_EXTENDS: {
1731             final int type_index = nextChar();
1732             return TypeAnnotationPosition.classExtends(readTypePath(),
1733                                                        type_index);
1734         }
1735         // throws
1736         case THROWS: {
1737             final int type_index = nextChar();
1738             return TypeAnnotationPosition.methodThrows(readTypePath(),
1739                                                        type_index);
1740         }
1741         // method parameter
1742         case METHOD_FORMAL_PARAMETER: {
1743             final int parameter_index = nextByte();
1744             return TypeAnnotationPosition.methodParameter(readTypePath(),
1745                                                           parameter_index);
1746         }
1747         // type cast
1748         case CAST: {
1749             final int offset = nextChar();
1750             final int type_index = nextByte();
1751             final TypeAnnotationPosition position =
1752                 TypeAnnotationPosition.typeCast(readTypePath(), type_index);
1753             position.offset = offset;
1754             return position;
1755         }
1756         // method/constructor/reference type argument
1757         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: {
1758             final int offset = nextChar();
1759             final int type_index = nextByte();
1760             final TypeAnnotationPosition position = TypeAnnotationPosition
1761                 .constructorInvocationTypeArg(readTypePath(), type_index);
1762             position.offset = offset;
1763             return position;
1764         }
1765         case METHOD_INVOCATION_TYPE_ARGUMENT: {
1766             final int offset = nextChar();
1767             final int type_index = nextByte();
1768             final TypeAnnotationPosition position = TypeAnnotationPosition
1769                 .methodInvocationTypeArg(readTypePath(), type_index);
1770             position.offset = offset;
1771             return position;
1772         }
1773         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: {
1774             final int offset = nextChar();
1775             final int type_index = nextByte();
1776             final TypeAnnotationPosition position = TypeAnnotationPosition
1777                 .constructorRefTypeArg(readTypePath(), type_index);
1778             position.offset = offset;
1779             return position;
1780         }
1781         case METHOD_REFERENCE_TYPE_ARGUMENT: {
1782             final int offset = nextChar();
1783             final int type_index = nextByte();
1784             final TypeAnnotationPosition position = TypeAnnotationPosition
1785                 .methodRefTypeArg(readTypePath(), type_index);
1786             position.offset = offset;
1787             return position;
1788         }
1789         // We don't need to worry about these
1790         case METHOD_RETURN:
1791             return TypeAnnotationPosition.methodReturn(readTypePath());
1792         case FIELD:
1793             return TypeAnnotationPosition.field(readTypePath());
1794         case UNKNOWN:
1795             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
1796         default:
1797             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type);
1798         }
1799     }
1800 
1801     List<TypeAnnotationPosition.TypePathEntry> readTypePath() {
1802         int len = nextByte();
1803         ListBuffer<Integer> loc = new ListBuffer<>();
1804         for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
1805             loc = loc.append(nextByte());
1806 
1807         return TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
1808 
1809     }
1810 
1811     /**
1812      * Helper function to read an optional pool entry (with given function); this is used while parsing
1813      * InnerClasses and EnclosingMethod attributes, as well as when parsing supertype descriptor,
1814      * as per JVMS.
1815      */
1816     <Z> Z optPoolEntry(int index, IntFunction<Z> poolFunc, Z defaultValue) {
1817         return (index == 0) ?
1818                 defaultValue :
1819                 poolFunc.apply(index);
1820     }
1821 
1822     Attribute readAttributeValue() {
1823         char c = (char) buf.getByte(bp++);
1824         switch (c) {
1825         case 'B':
1826             return new Attribute.Constant(syms.byteType, poolReader.getConstant(nextChar()));
1827         case 'C':
1828             return new Attribute.Constant(syms.charType, poolReader.getConstant(nextChar()));
1829         case 'D':
1830             return new Attribute.Constant(syms.doubleType, poolReader.getConstant(nextChar()));
1831         case 'F':
1832             return new Attribute.Constant(syms.floatType, poolReader.getConstant(nextChar()));
1833         case 'I':
1834             return new Attribute.Constant(syms.intType, poolReader.getConstant(nextChar()));
1835         case 'J':
1836             return new Attribute.Constant(syms.longType, poolReader.getConstant(nextChar()));
1837         case 'S':
1838             return new Attribute.Constant(syms.shortType, poolReader.getConstant(nextChar()));
1839         case 'Z':
1840             return new Attribute.Constant(syms.booleanType, poolReader.getConstant(nextChar()));
1841         case 's':
1842             return new Attribute.Constant(syms.stringType, poolReader.getName(nextChar()).toString());
1843         case 'e':
1844             return new EnumAttributeProxy(readTypeToProxy(nextChar()), poolReader.getName(nextChar()));
1845         case 'c':
1846             return new ClassAttributeProxy(readTypeOrClassSymbol(nextChar()));
1847         case '[': {
1848             int n = nextChar();
1849             ListBuffer<Attribute> l = new ListBuffer<>();
1850             for (int i=0; i<n; i++)
1851                 l.append(readAttributeValue());
1852             return new ArrayAttributeProxy(l.toList());
1853         }
1854         case '@':
1855             return readCompoundAnnotation();
1856         default:
1857             throw new AssertionError("unknown annotation tag '" + c + "'");
1858         }
1859     }
1860 
1861     interface ProxyVisitor extends Attribute.Visitor {
1862         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1863         void visitClassAttributeProxy(ClassAttributeProxy proxy);
1864         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1865         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1866     }
1867 
1868     static class EnumAttributeProxy extends Attribute {
1869         Type enumType;
1870         Name enumerator;
1871         public EnumAttributeProxy(Type enumType, Name enumerator) {
1872             super(null);
1873             this.enumType = enumType;
1874             this.enumerator = enumerator;
1875         }
1876         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1877         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1878         public String toString() {
1879             return "/*proxy enum*/" + enumType + "." + enumerator;
1880         }
1881     }
1882 
1883     static class ClassAttributeProxy extends Attribute {
1884         Type classType;
1885         public ClassAttributeProxy(Type classType) {
1886             super(null);
1887             this.classType = classType;
1888         }
1889         public void accept(Visitor v) { ((ProxyVisitor)v).visitClassAttributeProxy(this); }
1890         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1891         public String toString() {
1892             return "/*proxy class*/" + classType + ".class";
1893         }
1894     }
1895 
1896     static class ArrayAttributeProxy extends Attribute {
1897         List<Attribute> values;
1898         ArrayAttributeProxy(List<Attribute> values) {
1899             super(null);
1900             this.values = values;
1901         }
1902         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1903         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1904         public String toString() {
1905             return "{" + values + "}";
1906         }
1907     }
1908 
1909     /** A temporary proxy representing a compound attribute.
1910      */
1911     static class CompoundAnnotationProxy extends Attribute {
1912         final List<Pair<Name,Attribute>> values;
1913         public CompoundAnnotationProxy(Type type,
1914                                       List<Pair<Name,Attribute>> values) {
1915             super(type);
1916             this.values = values;
1917         }
1918         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1919         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1920         public String toString() {
1921             StringBuilder buf = new StringBuilder();
1922             buf.append("@");
1923             buf.append(type.tsym.getQualifiedName());
1924             buf.append("/*proxy*/{");
1925             boolean first = true;
1926             for (List<Pair<Name,Attribute>> v = values;
1927                  v.nonEmpty(); v = v.tail) {
1928                 Pair<Name,Attribute> value = v.head;
1929                 if (!first) buf.append(",");
1930                 first = false;
1931                 buf.append(value.fst);
1932                 buf.append("=");
1933                 buf.append(value.snd);
1934             }
1935             buf.append("}");
1936             return buf.toString();
1937         }
1938     }
1939 
1940     /** A temporary proxy representing a type annotation.
1941      */
1942     static class TypeAnnotationProxy {
1943         final CompoundAnnotationProxy compound;
1944         final TypeAnnotationPosition position;
1945         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1946                 TypeAnnotationPosition position) {
1947             this.compound = compound;
1948             this.position = position;
1949         }
1950     }
1951 
1952     class AnnotationDeproxy implements ProxyVisitor {
1953         private ClassSymbol requestingOwner;
1954 
1955         AnnotationDeproxy(ClassSymbol owner) {
1956             this.requestingOwner = owner;
1957         }
1958 
1959         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1960             // also must fill in types!!!!
1961             ListBuffer<Attribute.Compound> buf = new ListBuffer<>();
1962             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1963                 buf.append(deproxyCompound(l.head));
1964             }
1965             return buf.toList();
1966         }
1967 
1968         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1969             Type annotationType = resolvePossibleProxyType(a.type);
1970             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>();
1971             for (List<Pair<Name,Attribute>> l = a.values;
1972                  l.nonEmpty();
1973                  l = l.tail) {
1974                 MethodSymbol meth = findAccessMethod(annotationType, l.head.fst);
1975                 buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1976             }
1977             return new Attribute.Compound(annotationType, buf.toList());
1978         }
1979 
1980         MethodSymbol findAccessMethod(Type container, Name name) {
1981             CompletionFailure failure = null;
1982             try {
1983                 for (Symbol sym : container.tsym.members().getSymbolsByName(name)) {
1984                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1985                         return (MethodSymbol) sym;
1986                 }
1987             } catch (CompletionFailure ex) {
1988                 failure = ex;
1989             }
1990             // The method wasn't found: emit a warning and recover
1991             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1992             try {
1993                 if (lintClassfile) {
1994                     if (failure == null) {
1995                         log.warning(Warnings.AnnotationMethodNotFound(container, name));
1996                     } else {
1997                         log.warning(Warnings.AnnotationMethodNotFoundReason(container,
1998                                                                             name,
1999                                                                             failure.getDetailValue()));//diagnostic, if present
2000                     }
2001                 }
2002             } finally {
2003                 log.useSource(prevSource);
2004             }
2005             // Construct a new method type and symbol.  Use bottom
2006             // type (typeof null) as return type because this type is
2007             // a subtype of all reference types and can be converted
2008             // to primitive types by unboxing.
2009             MethodType mt = new MethodType(List.nil(),
2010                                            syms.botType,
2011                                            List.nil(),
2012                                            syms.methodClass);
2013             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
2014         }
2015 
2016         Attribute result;
2017         Type type;
2018         Attribute deproxy(Type t, Attribute a) {
2019             Type oldType = type;
2020             try {
2021                 type = t;
2022                 a.accept(this);
2023                 return result;
2024             } finally {
2025                 type = oldType;
2026             }
2027         }
2028 
2029         // implement Attribute.Visitor below
2030 
2031         public void visitConstant(Attribute.Constant value) {
2032             // assert value.type == type;
2033             result = value;
2034         }
2035 
2036         public void visitClass(Attribute.Class clazz) {
2037             result = clazz;
2038         }
2039 
2040         public void visitEnum(Attribute.Enum e) {
2041             throw new AssertionError(); // shouldn't happen
2042         }
2043 
2044         public void visitCompound(Attribute.Compound compound) {
2045             throw new AssertionError(); // shouldn't happen
2046         }
2047 
2048         public void visitArray(Attribute.Array array) {
2049             throw new AssertionError(); // shouldn't happen
2050         }
2051 
2052         public void visitError(Attribute.Error e) {
2053             throw new AssertionError(); // shouldn't happen
2054         }
2055 
2056         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
2057             // type.tsym.flatName() should == proxy.enumFlatName
2058             Type enumType = resolvePossibleProxyType(proxy.enumType);
2059             TypeSymbol enumTypeSym = enumType.tsym;
2060             VarSymbol enumerator = null;
2061             CompletionFailure failure = null;
2062             try {
2063                 for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) {
2064                     if (sym.kind == VAR) {
2065                         enumerator = (VarSymbol)sym;
2066                         break;
2067                     }
2068                 }
2069             }
2070             catch (CompletionFailure ex) {
2071                 failure = ex;
2072             }
2073             if (enumerator == null) {
2074                 if (failure != null) {
2075                     log.warning(Warnings.UnknownEnumConstantReason(currentClassFile,
2076                                                                    enumTypeSym,
2077                                                                    proxy.enumerator,
2078                                                                    failure.getDiagnostic()));
2079                 } else {
2080                     log.warning(Warnings.UnknownEnumConstant(currentClassFile,
2081                                                              enumTypeSym,
2082                                                              proxy.enumerator));
2083                 }
2084                 result = new Attribute.Enum(enumTypeSym.type,
2085                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
2086             } else {
2087                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
2088             }
2089         }
2090 
2091         @Override
2092         public void visitClassAttributeProxy(ClassAttributeProxy proxy) {
2093             Type classType = resolvePossibleProxyType(proxy.classType);
2094             result = new Attribute.Class(types, classType);
2095         }
2096 
2097         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
2098             int length = proxy.values.length();
2099             Attribute[] ats = new Attribute[length];
2100             Type elemtype = types.elemtype(type);
2101             int i = 0;
2102             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
2103                 ats[i++] = deproxy(elemtype, p.head);
2104             }
2105             result = new Attribute.Array(type, ats);
2106         }
2107 
2108         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
2109             result = deproxyCompound(proxy);
2110         }
2111 
2112         Type resolvePossibleProxyType(Type t) {
2113             if (t instanceof ProxyType proxyType) {
2114                 Assert.check(requestingOwner.owner.kind == MDL);
2115                 ModuleSymbol prevCurrentModule = currentModule;
2116                 currentModule = (ModuleSymbol) requestingOwner.owner;
2117                 try {
2118                     return proxyType.resolve();
2119                 } finally {
2120                     currentModule = prevCurrentModule;
2121                 }
2122             } else {
2123                 return t;
2124             }
2125         }
2126     }
2127 
2128     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Runnable {
2129         final MethodSymbol sym;
2130         final Attribute value;
2131         final JavaFileObject classFile = currentClassFile;
2132 
2133         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
2134             super(currentOwner.kind == MTH
2135                     ? currentOwner.enclClass() : (ClassSymbol)currentOwner);
2136             this.sym = sym;
2137             this.value = value;
2138         }
2139 
2140         @Override
2141         public void run() {
2142             JavaFileObject previousClassFile = currentClassFile;
2143             try {
2144                 // Reset the interim value set earlier in
2145                 // attachAnnotationDefault().
2146                 sym.defaultValue = null;
2147                 currentClassFile = classFile;
2148                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
2149             } finally {
2150                 currentClassFile = previousClassFile;
2151             }
2152         }
2153 
2154         @Override
2155         public String toString() {
2156             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
2157         }
2158     }
2159 
2160     class AnnotationCompleter extends AnnotationDeproxy implements Runnable {
2161         final Symbol sym;
2162         final List<CompoundAnnotationProxy> l;
2163         final JavaFileObject classFile;
2164 
2165         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
2166             super(currentOwner.kind == MTH
2167                     ? currentOwner.enclClass() : (ClassSymbol)currentOwner);
2168             if (sym.kind == TYP && sym.owner.kind == MDL) {
2169                 this.sym = sym.owner;
2170             } else {
2171                 this.sym = sym;
2172             }
2173             this.l = l;
2174             this.classFile = currentClassFile;
2175         }
2176 
2177         @Override
2178         public void run() {
2179             JavaFileObject previousClassFile = currentClassFile;
2180             try {
2181                 currentClassFile = classFile;
2182                 List<Attribute.Compound> newList = deproxyCompoundList(l);
2183                 for (Attribute.Compound attr : newList) {
2184                     if (attr.type.tsym == syms.deprecatedType.tsym) {
2185                         sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION);
2186                         Attribute forRemoval = attr.member(names.forRemoval);
2187                         if (forRemoval instanceof Attribute.Constant constant) {
2188                             if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) {
2189                                 sym.flags_field |= DEPRECATED_REMOVAL;
2190                             }
2191                         }
2192                     }
2193                 }
2194                 if (sym.annotationsPendingCompletion()) {
2195                     sym.setDeclarationAttributes(newList);
2196                 } else {
2197                     sym.appendAttributes(newList);
2198                 }
2199             } finally {
2200                 currentClassFile = previousClassFile;
2201             }
2202         }
2203 
2204         @Override
2205         public String toString() {
2206             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
2207         }
2208     }
2209 
2210     class TypeAnnotationCompleter extends AnnotationCompleter {
2211 
2212         List<TypeAnnotationProxy> proxies;
2213 
2214         TypeAnnotationCompleter(Symbol sym,
2215                 List<TypeAnnotationProxy> proxies) {
2216             super(sym, List.nil());
2217             this.proxies = proxies;
2218         }
2219 
2220         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
2221             ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
2222             for (TypeAnnotationProxy proxy: proxies) {
2223                 Attribute.Compound compound = deproxyCompound(proxy.compound);
2224                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
2225                 buf.add(typeCompound);
2226             }
2227             return buf.toList();
2228         }
2229 
2230         @Override
2231         public void run() {
2232             JavaFileObject previousClassFile = currentClassFile;
2233             try {
2234                 currentClassFile = classFile;
2235                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
2236                 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
2237             } finally {
2238                 currentClassFile = previousClassFile;
2239             }
2240         }
2241     }
2242 
2243 
2244 /************************************************************************
2245  * Reading Symbols
2246  ***********************************************************************/
2247 
2248     /** Read a field.
2249      */
2250     VarSymbol readField() {
2251         long flags = adjustFieldFlags(nextChar());
2252         Name name = poolReader.getName(nextChar());
2253         Type type = poolReader.getType(nextChar());
2254         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
2255         readMemberAttrs(v);
2256         return v;
2257     }
2258 
2259     /** Read a method.
2260      */
2261     MethodSymbol readMethod() {
2262         long flags = adjustMethodFlags(nextChar());
2263         Name name = poolReader.getName(nextChar());
2264         Type type = poolReader.getType(nextChar());
2265         if (currentOwner.isInterface() &&
2266                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
2267             if (majorVersion > Version.V52.major ||
2268                     (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) {
2269                 if ((flags & (STATIC | PRIVATE)) == 0) {
2270                     currentOwner.flags_field |= DEFAULT;
2271                     flags |= DEFAULT | ABSTRACT;
2272                 }
2273             } else {
2274                 //protect against ill-formed classfiles
2275                 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface",
2276                                    Integer.toString(majorVersion),
2277                                    Integer.toString(minorVersion));
2278             }
2279         }
2280         if (name == names.init && ((flags & STATIC) != 0)) {
2281             flags &= ~STATIC;
2282             type = new MethodType(type.getParameterTypes(),
2283                     syms.voidType,
2284                     type.getThrownTypes(),
2285                     syms.methodClass);
2286         }
2287         validateMethodType(name, type);
2288         if (name == names.init && currentOwner.hasOuterInstance()) {
2289             // Sometimes anonymous classes don't have an outer
2290             // instance, however, there is no reliable way to tell so
2291             // we never strip this$n
2292             // ditto for local classes. Local classes that have an enclosing method set
2293             // won't pass the "hasOuterInstance" check above, but those that don't have an
2294             // enclosing method (i.e. from initializers) will pass that check.
2295             boolean local = !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE);
2296             if (!currentOwner.name.isEmpty() && !local)
2297                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
2298                                       type.getReturnType(),
2299                                       type.getThrownTypes(),
2300                                       syms.methodClass);
2301         }
2302         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
2303         if (types.isSignaturePolymorphic(m)) {
2304             m.flags_field |= SIGNATURE_POLYMORPHIC;
2305         }
2306         if (saveParameterNames)
2307             initParameterNames(m);
2308         Symbol prevOwner = currentOwner;
2309         currentOwner = m;
2310         try {
2311             readMemberAttrs(m);
2312         } finally {
2313             currentOwner = prevOwner;
2314         }
2315         validateMethodType(name, m.type);
2316         setParameters(m, type);
2317 
2318         if ((flags & VARARGS) != 0) {
2319             final Type last = type.getParameterTypes().last();
2320             if (last == null || !last.hasTag(ARRAY)) {
2321                 m.flags_field &= ~VARARGS;
2322                 throw badClassFile("malformed.vararg.method", m);
2323             }
2324         }
2325 
2326         return m;
2327     }
2328 
2329     void validateMethodType(Name name, Type t) {
2330         if ((!t.hasTag(TypeTag.METHOD) && !t.hasTag(TypeTag.FORALL)) ||
2331             (name == names.init && !t.getReturnType().hasTag(TypeTag.VOID))) {
2332             throw badClassFile("method.descriptor.invalid", name);
2333         }
2334     }
2335 
2336     private List<Type> adjustMethodParams(long flags, List<Type> args) {
2337         if (args.isEmpty()) {
2338             return args;
2339         }
2340         boolean isVarargs = (flags & VARARGS) != 0;
2341         if (isVarargs) {
2342             Type varargsElem = args.last();
2343             ListBuffer<Type> adjustedArgs = new ListBuffer<>();
2344             for (Type t : args) {
2345                 adjustedArgs.append(t != varargsElem ?
2346                     t :
2347                     ((ArrayType)t).makeVarargs());
2348             }
2349             args = adjustedArgs.toList();
2350         }
2351         return args.tail;
2352     }
2353 
2354     /**
2355      * Init the parameter names array.
2356      * Parameter names are currently inferred from the names in the
2357      * LocalVariableTable attributes of a Code attribute.
2358      * (Note: this means parameter names are currently not available for
2359      * methods without a Code attribute.)
2360      * This method initializes an array in which to store the name indexes
2361      * of parameter names found in LocalVariableTable attributes. It is
2362      * slightly supersized to allow for additional slots with a start_pc of 0.
2363      */
2364     void initParameterNames(MethodSymbol sym) {
2365         // make allowance for synthetic parameters.
2366         final int excessSlots = 4;
2367         int expectedParameterSlots =
2368                 Code.width(sym.type.getParameterTypes()) + excessSlots;
2369         if (parameterNameIndices == null
2370                 || parameterNameIndices.length < expectedParameterSlots) {
2371             parameterNameIndices = new int[expectedParameterSlots];
2372         } else
2373             Arrays.fill(parameterNameIndices, 0);
2374         haveParameterNameIndices = false;
2375         sawMethodParameters = false;
2376     }
2377 
2378     /**
2379      * Set the parameters for a method symbol, including any names and
2380      * annotations that were read.
2381      *
2382      * <p>The type of the symbol may have changed while reading the
2383      * method attributes (see the Signature attribute). This may be
2384      * because of generic information or because anonymous synthetic
2385      * parameters were added.   The original type (as read from the
2386      * method descriptor) is used to help guess the existence of
2387      * anonymous synthetic parameters.
2388      */
2389     void setParameters(MethodSymbol sym, Type jvmType) {
2390         // If we get parameter names from MethodParameters, then we
2391         // don't need to skip.
2392         int firstParam = 0;
2393         if (!sawMethodParameters) {
2394             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
2395             // the code in readMethod may have skipped the first
2396             // parameter when setting up the MethodType. If so, we
2397             // make a corresponding allowance here for the position of
2398             // the first parameter.  Note that this assumes the
2399             // skipped parameter has a width of 1 -- i.e. it is not
2400             // a double width type (long or double.)
2401             if (sym.name == names.init && currentOwner.hasOuterInstance()) {
2402                 // Sometimes anonymous classes don't have an outer
2403                 // instance, however, there is no reliable way to tell so
2404                 // we never strip this$n
2405                 if (!currentOwner.name.isEmpty())
2406                     firstParam += 1;
2407             }
2408 
2409             if (sym.type != jvmType) {
2410                 // reading the method attributes has caused the
2411                 // symbol's type to be changed. (i.e. the Signature
2412                 // attribute.)  This may happen if there are hidden
2413                 // (synthetic) parameters in the descriptor, but not
2414                 // in the Signature.  The position of these hidden
2415                 // parameters is unspecified; for now, assume they are
2416                 // at the beginning, and so skip over them. The
2417                 // primary case for this is two hidden parameters
2418                 // passed into Enum constructors.
2419                 int skip = Code.width(jvmType.getParameterTypes())
2420                         - Code.width(sym.type.getParameterTypes());
2421                 firstParam += skip;
2422             }
2423         }
2424         Set<Name> paramNames = new HashSet<>();
2425         ListBuffer<VarSymbol> params = new ListBuffer<>();
2426         int nameIndex = firstParam;
2427         int annotationIndex = 0;
2428         for (Type t: sym.type.getParameterTypes()) {
2429             VarSymbol param = parameter(nameIndex, t, sym, paramNames);
2430             params.append(param);
2431             if (parameterAnnotations != null) {
2432                 ParameterAnnotations annotations = parameterAnnotations[annotationIndex];
2433                 if (annotations != null && annotations.proxies != null
2434                         && !annotations.proxies.isEmpty()) {
2435                     annotate.normal(new AnnotationCompleter(param, annotations.proxies));
2436                 }
2437             }
2438             nameIndex += sawMethodParameters ? 1 : Code.width(t);
2439             annotationIndex++;
2440         }
2441         if (parameterAnnotations != null && parameterAnnotations.length != annotationIndex) {
2442             throw badClassFile("bad.runtime.invisible.param.annotations", sym);
2443         }
2444         Assert.checkNull(sym.params);
2445         sym.params = params.toList();
2446         parameterAnnotations = null;
2447         parameterNameIndices = null;
2448         parameterAccessFlags = null;
2449     }
2450 
2451 
2452     // Returns the name for the parameter at position 'index', either using
2453     // names read from the MethodParameters, or by synthesizing a name that
2454     // is not on the 'exclude' list.
2455     private VarSymbol parameter(int index, Type t, MethodSymbol owner, Set<Name> exclude) {
2456         long flags = PARAMETER;
2457         Name argName;
2458         if (parameterAccessFlags != null && index < parameterAccessFlags.length
2459                 && parameterAccessFlags[index] != 0) {
2460             flags |= parameterAccessFlags[index];
2461         }
2462         if (parameterNameIndices != null && index < parameterNameIndices.length
2463                 && parameterNameIndices[index] != 0) {
2464             argName = optPoolEntry(parameterNameIndices[index], poolReader::getName, names.empty);
2465             flags |= NAME_FILLED;
2466         } else {
2467             String prefix = "arg";
2468             while (true) {
2469                 argName = names.fromString(prefix + exclude.size());
2470                 if (!exclude.contains(argName))
2471                     break;
2472                 prefix += "$";
2473             }
2474         }
2475         exclude.add(argName);
2476         return new ParamSymbol(flags, argName, t, owner);
2477     }
2478 
2479     /**
2480      * skip n bytes
2481      */
2482     void skipBytes(int n) {
2483         bp = bp + n;
2484     }
2485 
2486     /** Skip a field or method
2487      */
2488     void skipMember() {
2489         bp = bp + 6;
2490         char ac = nextChar();
2491         for (int i = 0; i < ac; i++) {
2492             bp = bp + 2;
2493             int attrLen = nextInt();
2494             bp = bp + attrLen;
2495         }
2496     }
2497 
2498     void skipInnerClasses() {
2499         int n = nextChar();
2500         for (int i = 0; i < n; i++) {
2501             nextChar();
2502             nextChar();
2503             nextChar();
2504             nextChar();
2505         }
2506     }
2507 
2508     /** Enter type variables of this classtype and all enclosing ones in
2509      *  `typevars'.
2510      */
2511     protected void enterTypevars(Symbol sym, Type t) {
2512         if (t.getEnclosingType() != null) {
2513             if (!t.getEnclosingType().hasTag(TypeTag.NONE)) {
2514                 enterTypevars(sym.owner, t.getEnclosingType());
2515             }
2516         } else if (sym.kind == MTH && !sym.isStatic()) {
2517             enterTypevars(sym.owner, sym.owner.type);
2518         }
2519         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) {
2520             typevars.enter(xs.head.tsym);
2521         }
2522     }
2523 
2524     protected ClassSymbol enterClass(Name name) {
2525         return syms.enterClass(currentModule, name);
2526     }
2527 
2528     protected ClassSymbol enterClass(Name name, TypeSymbol owner) {
2529         return syms.enterClass(currentModule, name, owner);
2530     }
2531 
2532     /** Read contents of a given class symbol `c'. Both external and internal
2533      *  versions of an inner class are read.
2534      */
2535     void readClass(ClassSymbol c) {
2536         ClassType ct = (ClassType)c.type;
2537 
2538         // allocate scope for members
2539         c.members_field = WriteableScope.create(c);
2540 
2541         // prepare type variable table
2542         typevars = typevars.dup(currentOwner);
2543         if (ct.getEnclosingType().hasTag(CLASS))
2544             enterTypevars(c.owner, ct.getEnclosingType());
2545 
2546         // read flags, or skip if this is an inner class
2547         long f = nextChar();
2548         long flags = adjustClassFlags(f);
2549         if ((flags & MODULE) == 0) {
2550             if (c.owner.kind == PCK || c.owner.kind == ERR) c.flags_field = flags;
2551             // read own class name and check that it matches
2552             currentModule = c.packge().modle;
2553             ClassSymbol self = poolReader.getClass(nextChar());
2554             if (c != self) {
2555                 throw badClassFile("class.file.wrong.class",
2556                                    self.flatname);
2557             }
2558         } else {
2559             if (majorVersion < Version.V53.major) {
2560                 throw badClassFile("anachronistic.module.info",
2561                         Integer.toString(majorVersion),
2562                         Integer.toString(minorVersion));
2563             }
2564             c.flags_field = flags;
2565             if (c.owner.kind != MDL) {
2566                 throw badClassFile("module.info.definition.expected");
2567             }
2568             currentModule = (ModuleSymbol) c.owner;
2569             int this_class = nextChar();
2570             // temp, no check on this_class
2571         }
2572 
2573         // class attributes must be read before class
2574         // skip ahead to read class attributes
2575         int startbp = bp;
2576         nextChar();
2577         char interfaceCount = nextChar();
2578         bp += interfaceCount * 2;
2579         char fieldCount = nextChar();
2580         for (int i = 0; i < fieldCount; i++) skipMember();
2581         char methodCount = nextChar();
2582         for (int i = 0; i < methodCount; i++) skipMember();
2583         readClassAttrs(c);
2584 
2585         if (c.permitted != null && !c.permitted.isEmpty()) {
2586             c.flags_field |= SEALED;
2587         }
2588 
2589         // reset and read rest of classinfo
2590         bp = startbp;
2591         int n = nextChar();
2592         if ((flags & MODULE) != 0 && n > 0) {
2593             throw badClassFile("module.info.invalid.super.class");
2594         }
2595         if (ct.supertype_field == null)
2596             ct.supertype_field =
2597                     optPoolEntry(n, idx -> poolReader.getClass(idx).erasure(types), Type.noType);
2598         n = nextChar();
2599         List<Type> is = List.nil();
2600         for (int i = 0; i < n; i++) {
2601             Type _inter = poolReader.getClass(nextChar()).erasure(types);
2602             is = is.prepend(_inter);
2603         }
2604         if (ct.interfaces_field == null)
2605             ct.interfaces_field = is.reverse();
2606 
2607         Assert.check(fieldCount == nextChar());
2608         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2609         Assert.check(methodCount == nextChar());
2610         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2611         if (c.isRecord()) {
2612             for (RecordComponent rc: c.getRecordComponents()) {
2613                 rc.accessor = lookupMethod(c, rc.name, List.nil());
2614             }
2615         }
2616         typevars = typevars.leave();
2617     }
2618 
2619     private MethodSymbol lookupMethod(TypeSymbol tsym, Name name, List<Type> argtypes) {
2620         for (Symbol s : tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
2621             if (types.isSameTypes(s.type.getParameterTypes(), argtypes)) {
2622                 return (MethodSymbol) s;
2623             }
2624         }
2625         return null;
2626     }
2627 
2628     /** Read inner class info. For each inner/outer pair allocate a
2629      *  member class.
2630      */
2631     void readInnerClasses(ClassSymbol c) {
2632         int n = nextChar();
2633         for (int i = 0; i < n; i++) {
2634             nextChar(); // skip inner class symbol
2635             int outerIdx = nextChar();
2636             int nameIdx = nextChar();
2637             ClassSymbol outer = optPoolEntry(outerIdx, poolReader::getClass, null);
2638             Name name = optPoolEntry(nameIdx, poolReader::getName, names.empty);
2639             if (name == null) name = names.empty;
2640             long flags = adjustClassFlags(nextChar());
2641             if (outer != null) { // we have a member class
2642                 if (name == names.empty)
2643                     name = names.one;
2644                 ClassSymbol member = enterClass(name, outer);
2645                 if ((flags & STATIC) == 0) {
2646                     ((ClassType)member.type).setEnclosingType(outer.type);
2647                     if (member.erasure_field != null)
2648                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2649                 }
2650                 if (c == outer) {
2651                     member.flags_field = flags;
2652                     enterMember(c, member);
2653                 }
2654             }
2655         }
2656     }
2657 
2658     /** Read a class definition from the bytes in buf.
2659      */
2660     private void readClassBuffer(ClassSymbol c) throws IOException {
2661         int magic = nextInt();
2662         if (magic != JAVA_MAGIC)
2663             throw badClassFile("illegal.start.of.class.file");
2664 
2665         minorVersion = nextChar();
2666         majorVersion = nextChar();
2667         int maxMajor = Version.MAX().major;
2668         int maxMinor = Version.MAX().minor;
2669         boolean previewClassFile =
2670                 minorVersion == ClassFile.PREVIEW_MINOR_VERSION;
2671         if (majorVersion > maxMajor ||
2672             majorVersion * 1000 + minorVersion <
2673             Version.MIN().major * 1000 + Version.MIN().minor) {
2674             if (majorVersion == (maxMajor + 1) && !previewClassFile)
2675                 log.warning(Warnings.BigMajorVersion(currentClassFile,
2676                                                      majorVersion,
2677                                                      maxMajor));
2678             else
2679                 throw badClassFile("wrong.version",
2680                                    Integer.toString(majorVersion),
2681                                    Integer.toString(minorVersion),
2682                                    Integer.toString(maxMajor),
2683                                    Integer.toString(maxMinor));
2684         }
2685 
2686         if (previewClassFile) {
2687             if (!preview.isEnabled()) {
2688                 log.error(preview.disabledError(currentClassFile, majorVersion));
2689             } else {
2690                 preview.warnPreview(c.classfile, majorVersion);
2691             }
2692         }
2693 
2694         poolReader = new PoolReader(this, names, syms);
2695         bp = poolReader.readPool(buf, bp);
2696         if (signatureBuffer.length < bp) {
2697             int ns = Integer.highestOneBit(bp) << 1;
2698             signatureBuffer = new byte[ns];
2699         }
2700         readClass(c);
2701     }
2702 
2703     public void readClassFile(ClassSymbol c) {
2704         currentOwner = c;
2705         currentClassFile = c.classfile;
2706         warnedAttrs.clear();
2707         filling = true;
2708         target = null;
2709         repeatable = null;
2710         try {
2711             bp = 0;
2712             buf.reset();
2713             buf.appendStream(c.classfile.openInputStream());
2714             readClassBuffer(c);
2715             if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2716                 List<Type> missing = missingTypeVariables;
2717                 List<Type> found = foundTypeVariables;
2718                 missingTypeVariables = List.nil();
2719                 foundTypeVariables = List.nil();
2720                 interimUses = List.nil();
2721                 interimProvides = List.nil();
2722                 filling = false;
2723                 ClassType ct = (ClassType)currentOwner.type;
2724                 ct.supertype_field =
2725                     types.subst(ct.supertype_field, missing, found);
2726                 ct.interfaces_field =
2727                     types.subst(ct.interfaces_field, missing, found);
2728                 ct.typarams_field =
2729                     types.substBounds(ct.typarams_field, missing, found);
2730                 for (List<Type> types = ct.typarams_field; types.nonEmpty(); types = types.tail) {
2731                     types.head.tsym.type = types.head;
2732                 }
2733             } else if (missingTypeVariables.isEmpty() !=
2734                        foundTypeVariables.isEmpty()) {
2735                 Name name = missingTypeVariables.head.tsym.name;
2736                 throw badClassFile("undecl.type.var", name);
2737             }
2738 
2739             if ((c.flags_field & Flags.ANNOTATION) != 0) {
2740                 c.setAnnotationTypeMetadata(new AnnotationTypeMetadata(c, new CompleterDeproxy(c, target, repeatable)));
2741             } else {
2742                 c.setAnnotationTypeMetadata(AnnotationTypeMetadata.notAnAnnotationType());
2743             }
2744 
2745             if (c == currentModule.module_info) {
2746                 if (interimUses.nonEmpty() || interimProvides.nonEmpty()) {
2747                     Assert.check(currentModule.isCompleted());
2748                     currentModule.usesProvidesCompleter =
2749                             new UsesProvidesCompleter(currentModule, interimUses, interimProvides);
2750                 } else {
2751                     currentModule.uses = List.nil();
2752                     currentModule.provides = List.nil();
2753                 }
2754             }
2755         } catch (IOException | ClosedFileSystemException ex) {
2756             throw badClassFile("unable.to.access.file", ex.toString());
2757         } catch (ArrayIndexOutOfBoundsException ex) {
2758             throw badClassFile("bad.class.file", c.flatname);
2759         } finally {
2760             interimUses = List.nil();
2761             interimProvides = List.nil();
2762             missingTypeVariables = List.nil();
2763             foundTypeVariables = List.nil();
2764             filling = false;
2765         }
2766     }
2767 
2768     /** We can only read a single class file at a time; this
2769      *  flag keeps track of when we are currently reading a class
2770      *  file.
2771      */
2772     public boolean filling = false;
2773 
2774 /************************************************************************
2775  * Adjusting flags
2776  ***********************************************************************/
2777 
2778     long adjustFieldFlags(long flags) {
2779         return flags;
2780     }
2781 
2782     long adjustMethodFlags(long flags) {
2783         if ((flags & ACC_BRIDGE) != 0) {
2784             flags &= ~ACC_BRIDGE;
2785             flags |= BRIDGE;
2786         }
2787         if ((flags & ACC_VARARGS) != 0) {
2788             flags &= ~ACC_VARARGS;
2789             flags |= VARARGS;
2790         }
2791         return flags;
2792     }
2793 
2794     long adjustClassFlags(long flags) {
2795         if ((flags & ACC_MODULE) != 0) {
2796             flags &= ~ACC_MODULE;
2797             flags |= MODULE;
2798         }
2799         if ((flags & ACC_PRIMITIVE) != 0) {
2800             flags &= ~ACC_PRIMITIVE;
2801             if (allowPrimitiveClasses) {
2802                 flags |= PRIMITIVE_CLASS;
2803             }
2804         }
2805         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2806     }
2807 
2808     /**
2809      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2810      * The attribute is only the last component of the original filename, so is unlikely
2811      * to be valid as is, so operations other than those to access the name throw
2812      * UnsupportedOperationException
2813      */
2814     private static class SourceFileObject implements JavaFileObject {
2815 
2816         /** The file's name.
2817          */
2818         private final Name name;
2819 
2820         public SourceFileObject(Name name) {
2821             this.name = name;
2822         }
2823 
2824         @Override @DefinedBy(Api.COMPILER)
2825         public URI toUri() {
2826             try {
2827                 return new URI(null, name.toString(), null);
2828             } catch (URISyntaxException e) {
2829                 throw new PathFileObject.CannotCreateUriError(name.toString(), e);
2830             }
2831         }
2832 
2833         @Override @DefinedBy(Api.COMPILER)
2834         public String getName() {
2835             return name.toString();
2836         }
2837 
2838         @Override @DefinedBy(Api.COMPILER)
2839         public JavaFileObject.Kind getKind() {
2840             return BaseFileManager.getKind(getName());
2841         }
2842 
2843         @Override @DefinedBy(Api.COMPILER)
2844         public InputStream openInputStream() {
2845             throw new UnsupportedOperationException();
2846         }
2847 
2848         @Override @DefinedBy(Api.COMPILER)
2849         public OutputStream openOutputStream() {
2850             throw new UnsupportedOperationException();
2851         }
2852 
2853         @Override @DefinedBy(Api.COMPILER)
2854         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2855             throw new UnsupportedOperationException();
2856         }
2857 
2858         @Override @DefinedBy(Api.COMPILER)
2859         public Reader openReader(boolean ignoreEncodingErrors) {
2860             throw new UnsupportedOperationException();
2861         }
2862 
2863         @Override @DefinedBy(Api.COMPILER)
2864         public Writer openWriter() {
2865             throw new UnsupportedOperationException();
2866         }
2867 
2868         @Override @DefinedBy(Api.COMPILER)
2869         public long getLastModified() {
2870             throw new UnsupportedOperationException();
2871         }
2872 
2873         @Override @DefinedBy(Api.COMPILER)
2874         public boolean delete() {
2875             throw new UnsupportedOperationException();
2876         }
2877 
2878         @Override @DefinedBy(Api.COMPILER)
2879         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2880             return true; // fail-safe mode
2881         }
2882 
2883         @Override @DefinedBy(Api.COMPILER)
2884         public NestingKind getNestingKind() {
2885             return null;
2886         }
2887 
2888         @Override @DefinedBy(Api.COMPILER)
2889         public Modifier getAccessLevel() {
2890             return null;
2891         }
2892 
2893         /**
2894          * Check if two file objects are equal.
2895          * SourceFileObjects are just placeholder objects for the value of a
2896          * SourceFile attribute, and do not directly represent specific files.
2897          * Two SourceFileObjects are equal if their names are equal.
2898          */
2899         @Override
2900         public boolean equals(Object other) {
2901             if (this == other)
2902                 return true;
2903             return (other instanceof SourceFileObject sourceFileObject)
2904                     && name.equals(sourceFileObject.name);
2905         }
2906 
2907         @Override
2908         public int hashCode() {
2909             return name.hashCode();
2910         }
2911     }
2912 
2913     private class CompleterDeproxy implements AnnotationTypeCompleter {
2914         ClassSymbol proxyOn;
2915         CompoundAnnotationProxy target;
2916         CompoundAnnotationProxy repeatable;
2917 
2918         public CompleterDeproxy(ClassSymbol c, CompoundAnnotationProxy target,
2919                 CompoundAnnotationProxy repeatable)
2920         {
2921             this.proxyOn = c;
2922             this.target = target;
2923             this.repeatable = repeatable;
2924         }
2925 
2926         @Override
2927         public void complete(ClassSymbol sym) {
2928             Assert.check(proxyOn == sym);
2929             Attribute.Compound theTarget = null, theRepeatable = null;
2930             AnnotationDeproxy deproxy;
2931 
2932             try {
2933                 if (target != null) {
2934                     deproxy = new AnnotationDeproxy(proxyOn);
2935                     theTarget = deproxy.deproxyCompound(target);
2936                 }
2937 
2938                 if (repeatable != null) {
2939                     deproxy = new AnnotationDeproxy(proxyOn);
2940                     theRepeatable = deproxy.deproxyCompound(repeatable);
2941                 }
2942             } catch (Exception e) {
2943                 throw new CompletionFailure(sym,
2944                                             () -> ClassReader.this.diagFactory.fragment(Fragments.ExceptionMessage(e.getMessage())),
2945                                             dcfh);
2946             }
2947 
2948             sym.getAnnotationTypeMetadata().setTarget(theTarget);
2949             sym.getAnnotationTypeMetadata().setRepeatable(theRepeatable);
2950         }
2951     }
2952 
2953     private class ProxyType extends Type {
2954 
2955         private final Name name;
2956 
2957         public ProxyType(int index) {
2958             super(syms.noSymbol, TypeMetadata.EMPTY);
2959             this.name = poolReader.getName(index);
2960         }
2961 
2962         @Override
2963         public TypeTag getTag() {
2964             return TypeTag.NONE;
2965         }
2966 
2967         @Override
2968         public Type cloneWithMetadata(TypeMetadata metadata) {
2969             throw new UnsupportedOperationException();
2970         }
2971 
2972         public Type resolve() {
2973             return name.map(ClassReader.this::sigToType);
2974         }
2975 
2976         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2977         public String toString() {
2978             return "<ProxyType>";
2979         }
2980 
2981     }
2982 
2983     private static final class InterimUsesDirective {
2984         public final Name service;
2985 
2986         public InterimUsesDirective(Name service) {
2987             this.service = service;
2988         }
2989 
2990     }
2991 
2992     private static final class InterimProvidesDirective {
2993         public final Name service;
2994         public final List<Name> impls;
2995 
2996         public InterimProvidesDirective(Name service, List<Name> impls) {
2997             this.service = service;
2998             this.impls = impls;
2999         }
3000 
3001     }
3002 
3003     private final class UsesProvidesCompleter implements Completer {
3004         private final ModuleSymbol currentModule;
3005         private final List<InterimUsesDirective> interimUsesCopy;
3006         private final List<InterimProvidesDirective> interimProvidesCopy;
3007 
3008         public UsesProvidesCompleter(ModuleSymbol currentModule, List<InterimUsesDirective> interimUsesCopy, List<InterimProvidesDirective> interimProvidesCopy) {
3009             this.currentModule = currentModule;
3010             this.interimUsesCopy = interimUsesCopy;
3011             this.interimProvidesCopy = interimProvidesCopy;
3012         }
3013 
3014         @Override
3015         public void complete(Symbol sym) throws CompletionFailure {
3016             ListBuffer<Directive> directives = new ListBuffer<>();
3017             directives.addAll(currentModule.directives);
3018             ListBuffer<UsesDirective> uses = new ListBuffer<>();
3019             for (InterimUsesDirective interim : interimUsesCopy) {
3020                 UsesDirective d = new UsesDirective(syms.enterClass(currentModule, interim.service));
3021                 uses.add(d);
3022                 directives.add(d);
3023             }
3024             currentModule.uses = uses.toList();
3025             ListBuffer<ProvidesDirective> provides = new ListBuffer<>();
3026             for (InterimProvidesDirective interim : interimProvidesCopy) {
3027                 ListBuffer<ClassSymbol> impls = new ListBuffer<>();
3028                 for (Name impl : interim.impls) {
3029                     impls.append(syms.enterClass(currentModule, impl));
3030                 }
3031                 ProvidesDirective d = new ProvidesDirective(syms.enterClass(currentModule, interim.service),
3032                                                             impls.toList());
3033                 provides.add(d);
3034                 directives.add(d);
3035             }
3036             currentModule.provides = provides.toList();
3037             currentModule.directives = directives.toList();
3038         }
3039     }
3040 }