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