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