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