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