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