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 sealed
 109      */
 110     boolean allowSealedTypes;
 111 
 112     /** Switch: allow records
 113      */
 114     boolean allowRecords;
 115 
 116    /** Lint option: warn about classfile issues
 117      */
 118     boolean lintClassfile;
 119 
 120     /** Switch: preserve parameter names from the variable table.
 121      */
 122     public boolean saveParameterNames;
 123 
 124     /**
 125      * The currently selected profile.
 126      */
 127     public final Profile profile;
 128 
 129     /** The log to use for verbose output
 130      */
 131     final Log log;
 132 
 133     /** The symbol table. */
 134     Symtab syms;
 135 
 136     Types types;
 137 
 138     /** The name table. */
 139     final Names names;
 140 
 141     /** Access to files
 142      */
 143     private final JavaFileManager fileManager;
 144 
 145     /** Factory for diagnostics
 146      */
 147     JCDiagnostic.Factory diagFactory;
 148 
 149     DeferredCompletionFailureHandler dcfh;
 150 
 151     /**
 152      * Support for preview language features.
 153      */
 154     Preview preview;
 155 
 156     /** The current scope where type variables are entered.
 157      */
 158     protected WriteableScope typevars;
 159 
 160     private List<InterimUsesDirective> interimUses = List.nil();
 161     private List<InterimProvidesDirective> interimProvides = List.nil();
 162 
 163     /** The path name of the class file currently being read.
 164      */
 165     protected JavaFileObject currentClassFile = null;
 166 
 167     /** The class or method currently being read.
 168      */
 169     protected Symbol currentOwner = null;
 170 
 171     /** The module containing the class currently being read.
 172      */
 173     protected ModuleSymbol currentModule = null;
 174 
 175     /** The buffer containing the currently read class file.
 176      */
 177     ByteBuffer buf = new ByteBuffer(INITIAL_BUFFER_SIZE);
 178 
 179     /** The current input pointer.
 180      */
 181     protected int bp;
 182 
 183     /** The pool reader.
 184      */
 185     PoolReader poolReader;
 186 
 187     /** The major version number of the class file being read. */
 188     int majorVersion;
 189     /** The minor version number of the class file being read. */
 190     int minorVersion;
 191 
 192     /** A table to hold the constant pool indices for method parameter
 193      * names, as given in LocalVariableTable attributes.
 194      */
 195     int[] parameterNameIndices;
 196 
 197     /**
 198      * A table to hold 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         allowSealedTypes = Feature.SEALED.allowedInSource(source);
 276         allowRecords = Feature.RECORDS.allowedInSource(source);
 277 
 278         saveParameterNames = options.isSet(PARAMETERS);
 279 
 280         profile = Profile.instance(context);
 281 
 282         typevars = WriteableScope.create(syms.noSymbol);
 283 
 284         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
 285 
 286         initAttributeReaders();
 287     }
 288 
 289     /** Add member to class unless it is synthetic.
 290      */
 291     private void enterMember(ClassSymbol c, Symbol sym) {
 292         // Synthetic members are not entered -- reason lost to history (optimization?).
 293         // Lambda methods must be entered because they may have inner classes (which reference them)
 294         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
 295             c.members_field.enter(sym);
 296     }
 297 
 298 /************************************************************************
 299  * Error Diagnoses
 300  ***********************************************************************/
 301 
 302     public ClassFinder.BadClassFile badClassFile(String key, Object... args) {
 303         return new ClassFinder.BadClassFile (
 304             currentOwner.enclClass(),
 305             currentClassFile,
 306             diagFactory.fragment(key, args),
 307             diagFactory,
 308             dcfh);
 309     }
 310 
 311     public ClassFinder.BadEnclosingMethodAttr badEnclosingMethod(Symbol sym) {
 312         return new ClassFinder.BadEnclosingMethodAttr (
 313             currentOwner.enclClass(),
 314             currentClassFile,
 315             diagFactory.fragment(Fragments.BadEnclosingMethod(sym)),
 316             diagFactory,
 317             dcfh);
 318     }
 319 
 320 /************************************************************************
 321  * Buffer Access
 322  ***********************************************************************/
 323 
 324     /** Read a character.
 325      */
 326     char nextChar() {
 327         char res = buf.getChar(bp);
 328         bp += 2;
 329         return res;
 330     }
 331 
 332     /** Read a byte.
 333      */
 334     int nextByte() {
 335         return buf.getByte(bp++) & 0xFF;
 336     }
 337 
 338     /** Read an integer.
 339      */
 340     int nextInt() {
 341         int res = buf.getInt(bp);
 342         bp += 4;
 343         return res;
 344     }
 345 
 346 /************************************************************************
 347  * Constant Pool Access
 348  ***********************************************************************/
 349 
 350     /** Read module_flags.
 351      */
 352     Set<ModuleFlags> readModuleFlags(int flags) {
 353         Set<ModuleFlags> set = EnumSet.noneOf(ModuleFlags.class);
 354         for (ModuleFlags f : ModuleFlags.values()) {
 355             if ((flags & f.value) != 0)
 356                 set.add(f);
 357         }
 358         return set;
 359     }
 360 
 361     /** Read resolution_flags.
 362      */
 363     Set<ModuleResolutionFlags> readModuleResolutionFlags(int flags) {
 364         Set<ModuleResolutionFlags> set = EnumSet.noneOf(ModuleResolutionFlags.class);
 365         for (ModuleResolutionFlags f : ModuleResolutionFlags.values()) {
 366             if ((flags & f.value) != 0)
 367                 set.add(f);
 368         }
 369         return set;
 370     }
 371 
 372     /** Read exports_flags.
 373      */
 374     Set<ExportsFlag> readExportsFlags(int flags) {
 375         Set<ExportsFlag> set = EnumSet.noneOf(ExportsFlag.class);
 376         for (ExportsFlag f: ExportsFlag.values()) {
 377             if ((flags & f.value) != 0)
 378                 set.add(f);
 379         }
 380         return set;
 381     }
 382 
 383     /** Read opens_flags.
 384      */
 385     Set<OpensFlag> readOpensFlags(int flags) {
 386         Set<OpensFlag> set = EnumSet.noneOf(OpensFlag.class);
 387         for (OpensFlag f: OpensFlag.values()) {
 388             if ((flags & f.value) != 0)
 389                 set.add(f);
 390         }
 391         return set;
 392     }
 393 
 394     /** Read requires_flags.
 395      */
 396     Set<RequiresFlag> readRequiresFlags(int flags) {
 397         Set<RequiresFlag> set = EnumSet.noneOf(RequiresFlag.class);
 398         for (RequiresFlag f: RequiresFlag.values()) {
 399             if ((flags & f.value) != 0)
 400                 set.add(f);
 401         }
 402         return set;
 403     }
 404 
 405 /************************************************************************
 406  * Reading Types
 407  ***********************************************************************/
 408 
 409     /** The unread portion of the currently read type is
 410      *  signature[sigp..siglimit-1].
 411      */
 412     byte[] signature;
 413     int sigp;
 414     int siglimit;
 415     boolean sigEnterPhase = false;
 416 
 417     /** Convert signature to type, where signature is a byte array segment.
 418      */
 419     Type sigToType(byte[] sig, int offset, int len) {
 420         signature = sig;
 421         sigp = offset;
 422         siglimit = offset + len;
 423         return sigToType();
 424     }
 425 
 426     /** Convert signature to type, where signature is implicit.
 427      */
 428     Type sigToType() {
 429         switch ((char) signature[sigp]) {
 430         case 'T':
 431             sigp++;
 432             int start = sigp;
 433             while (signature[sigp] != ';') sigp++;
 434             sigp++;
 435             return sigEnterPhase
 436                 ? Type.noType
 437                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
 438         case '+': {
 439             sigp++;
 440             Type t = sigToType();
 441             return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass);
 442         }
 443         case '*':
 444             sigp++;
 445             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
 446                                     syms.boundClass);
 447         case '-': {
 448             sigp++;
 449             Type t = sigToType();
 450             return new WildcardType(t, BoundKind.SUPER, syms.boundClass);
 451         }
 452         case 'B':
 453             sigp++;
 454             return syms.byteType;
 455         case 'C':
 456             sigp++;
 457             return syms.charType;
 458         case 'D':
 459             sigp++;
 460             return syms.doubleType;
 461         case 'F':
 462             sigp++;
 463             return syms.floatType;
 464         case 'I':
 465             sigp++;
 466             return syms.intType;
 467         case 'J':
 468             sigp++;
 469             return syms.longType;
 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')
 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             new AttributeReader(names.PermittedSubtypes, V57, CLASS_ATTRIBUTE) {
1196                 @Override
1197                 protected boolean accepts(AttributeKind kind) {
1198                     return super.accepts(kind) && allowSealedTypes;
1199                 }
1200                 protected void read(Symbol sym, int attrLen) {
1201                     if (sym.kind == TYP) {
1202                         ClassType sealed = (ClassType)sym.type;
1203                         ListBuffer<Type> subtypes = new ListBuffer<>();
1204                         int numberOfPermittedSubtypes = nextChar();
1205                         for (int i = 0; i < numberOfPermittedSubtypes; i++) {
1206                             Type ct = poolReader.getClass(nextChar()).erasure(types);
1207                             subtypes.add(ct);
1208                         }
1209                         sealed.permitted = subtypes.toList();
1210                     }
1211                 }
1212             },
1213 
1214             new AttributeReader(names.Record, V57, CLASS_ATTRIBUTE) {
1215                 @Override
1216                 protected boolean accepts(AttributeKind kind) {
1217                     return super.accepts(kind) && allowRecords;
1218                 }
1219                 protected void read(Symbol sym, int attrLen) {
1220                     if (sym.kind == TYP) {
1221                         sym.flags_field |= RECORD;
1222                     }
1223                     bp = bp + attrLen;
1224                 }
1225             }
1226         };
1227 
1228         for (AttributeReader r: readers)
1229             attributeReaders.put(r.name, r);
1230     }
1231 
1232     protected void readEnclosingMethodAttr(Symbol sym) {
1233         // sym is a nested class with an "Enclosing Method" attribute
1234         // remove sym from it's current owners scope and place it in
1235         // the scope specified by the attribute
1236         sym.owner.members().remove(sym);
1237         ClassSymbol self = (ClassSymbol)sym;
1238         ClassSymbol c = poolReader.getClass(nextChar());
1239         NameAndType nt = optPoolEntry(nextChar(), poolReader::getNameAndType, null);
1240 
1241         if (c.members_field == null || c.kind != TYP)
1242             throw badClassFile("bad.enclosing.class", self, c);
1243 
1244         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1245         if (nt != null && m == null)
1246             throw badEnclosingMethod(self);
1247 
1248         self.name = simpleBinaryName(self.flatname, c.flatname) ;
1249         self.owner = m != null ? m : c;
1250         if (self.name.isEmpty())
1251             self.fullname = names.empty;
1252         else
1253             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1254 
1255         if (m != null) {
1256             ((ClassType)sym.type).setEnclosingType(m.type);
1257         } else if ((self.flags_field & STATIC) == 0) {
1258             ((ClassType)sym.type).setEnclosingType(c.type);
1259         } else {
1260             ((ClassType)sym.type).setEnclosingType(Type.noType);
1261         }
1262         enterTypevars(self, self.type);
1263         if (!missingTypeVariables.isEmpty()) {
1264             ListBuffer<Type> typeVars =  new ListBuffer<>();
1265             for (Type typevar : missingTypeVariables) {
1266                 typeVars.append(findTypeVar(typevar.tsym.name));
1267             }
1268             foundTypeVariables = typeVars.toList();
1269         } else {
1270             foundTypeVariables = List.nil();
1271         }
1272     }
1273 
1274     // See java.lang.Class
1275     private Name simpleBinaryName(Name self, Name enclosing) {
1276         if (!self.startsWith(enclosing)) {
1277             throw badClassFile("bad.enclosing.method", self);
1278         }
1279 
1280         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1281         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1282             throw badClassFile("bad.enclosing.method", self);
1283         int index = 1;
1284         while (index < simpleBinaryName.length() &&
1285                isAsciiDigit(simpleBinaryName.charAt(index)))
1286             index++;
1287         return names.fromString(simpleBinaryName.substring(index));
1288     }
1289 
1290     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1291         if (nt == null)
1292             return null;
1293 
1294         MethodType type = nt.type.asMethodType();
1295 
1296         for (Symbol sym : scope.getSymbolsByName(nt.name)) {
1297             if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type))
1298                 return (MethodSymbol)sym;
1299         }
1300 
1301         if (nt.name != names.init)
1302             // not a constructor
1303             return null;
1304         if ((flags & INTERFACE) != 0)
1305             // no enclosing instance
1306             return null;
1307         if (nt.type.getParameterTypes().isEmpty())
1308             // no parameters
1309             return null;
1310 
1311         // A constructor of an inner class.
1312         // Remove the first argument (the enclosing instance)
1313         nt = new NameAndType(nt.name, new MethodType(nt.type.getParameterTypes().tail,
1314                                  nt.type.getReturnType(),
1315                                  nt.type.getThrownTypes(),
1316                                  syms.methodClass));
1317         // Try searching again
1318         return findMethod(nt, scope, flags);
1319     }
1320 
1321     /** Similar to Types.isSameType but avoids completion */
1322     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1323         List<Type> types1 = types.erasure(mt1.getParameterTypes())
1324             .prepend(types.erasure(mt1.getReturnType()));
1325         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1326         while (!types1.isEmpty() && !types2.isEmpty()) {
1327             if (types1.head.tsym != types2.head.tsym)
1328                 return false;
1329             types1 = types1.tail;
1330             types2 = types2.tail;
1331         }
1332         return types1.isEmpty() && types2.isEmpty();
1333     }
1334 
1335     /**
1336      * Character.isDigit answers <tt>true</tt> to some non-ascii
1337      * digits.  This one does not.  <b>copied from java.lang.Class</b>
1338      */
1339     private static boolean isAsciiDigit(char c) {
1340         return '0' <= c && c <= '9';
1341     }
1342 
1343     /** Read member attributes.
1344      */
1345     void readMemberAttrs(Symbol sym) {
1346         readAttrs(sym, AttributeKind.MEMBER);
1347     }
1348 
1349     void readAttrs(Symbol sym, AttributeKind kind) {
1350         char ac = nextChar();
1351         for (int i = 0; i < ac; i++) {
1352             Name attrName = poolReader.getName(nextChar());
1353             int attrLen = nextInt();
1354             AttributeReader r = attributeReaders.get(attrName);
1355             if (r != null && r.accepts(kind))
1356                 r.read(sym, attrLen);
1357             else  {
1358                 bp = bp + attrLen;
1359             }
1360         }
1361     }
1362 
1363     private boolean readingClassAttr = false;
1364     private List<Type> missingTypeVariables = List.nil();
1365     private List<Type> foundTypeVariables = List.nil();
1366 
1367     /** Read class attributes.
1368      */
1369     void readClassAttrs(ClassSymbol c) {
1370         readAttrs(c, AttributeKind.CLASS);
1371     }
1372 
1373     /** Read code block.
1374      */
1375     Code readCode(Symbol owner) {
1376         nextChar(); // max_stack
1377         nextChar(); // max_locals
1378         final int  code_length = nextInt();
1379         bp += code_length;
1380         final char exception_table_length = nextChar();
1381         bp += exception_table_length * 8;
1382         readMemberAttrs(owner);
1383         return null;
1384     }
1385 
1386 /************************************************************************
1387  * Reading Java-language annotations
1388  ***********************************************************************/
1389 
1390     /**
1391      * Save annotations.
1392      */
1393     List<CompoundAnnotationProxy> readAnnotations() {
1394         int numAttributes = nextChar();
1395         ListBuffer<CompoundAnnotationProxy> annotations = new ListBuffer<>();
1396         for (int i = 0; i < numAttributes; i++) {
1397             annotations.append(readCompoundAnnotation());
1398         }
1399         return annotations.toList();
1400     }
1401 
1402     /** Attach annotations.
1403      */
1404     void attachAnnotations(final Symbol sym) {
1405         attachAnnotations(sym, readAnnotations());
1406     }
1407 
1408     /**
1409      * Attach annotations.
1410      */
1411     void attachAnnotations(final Symbol sym, List<CompoundAnnotationProxy> annotations) {
1412         if (annotations.isEmpty()) {
1413             return;
1414         }
1415         ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>();
1416         for (CompoundAnnotationProxy proxy : annotations) {
1417             if (proxy.type.tsym.flatName() == syms.proprietaryType.tsym.flatName())
1418                 sym.flags_field |= PROPRIETARY;
1419             else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) {
1420                 if (profile != Profile.DEFAULT) {
1421                     for (Pair<Name, Attribute> v : proxy.values) {
1422                         if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
1423                             Attribute.Constant c = (Attribute.Constant)v.snd;
1424                             if (c.type == syms.intType && ((Integer)c.value) > profile.value) {
1425                                 sym.flags_field |= NOT_IN_PROFILE;
1426                             }
1427                         }
1428                     }
1429                 }
1430             } else {
1431                 if (proxy.type.tsym == syms.annotationTargetType.tsym) {
1432                     target = proxy;
1433                 } else if (proxy.type.tsym == syms.repeatableType.tsym) {
1434                     repeatable = proxy;
1435                 } else if (proxy.type.tsym == syms.deprecatedType.tsym) {
1436                     sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION);
1437                     for (Pair<Name, Attribute> v : proxy.values) {
1438                         if (v.fst == names.forRemoval && v.snd instanceof Attribute.Constant) {
1439                             Attribute.Constant c = (Attribute.Constant)v.snd;
1440                             if (c.type == syms.booleanType && ((Integer)c.value) != 0) {
1441                                 sym.flags_field |= DEPRECATED_REMOVAL;
1442                             }
1443                         }
1444                     }
1445                 }
1446                 proxies.append(proxy);
1447             }
1448         }
1449         annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1450     }
1451 
1452     /** Read parameter annotations.
1453      */
1454     void readParameterAnnotations(Symbol meth) {
1455         int numParameters = buf.getByte(bp++) & 0xFF;
1456         if (parameterAnnotations == null) {
1457             parameterAnnotations = new ParameterAnnotations[numParameters];
1458         } else if (parameterAnnotations.length != numParameters) {
1459             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1460         }
1461         for (int pnum = 0; pnum < numParameters; pnum++) {
1462             if (parameterAnnotations[pnum] == null) {
1463                 parameterAnnotations[pnum] = new ParameterAnnotations();
1464             }
1465             parameterAnnotations[pnum].add(readAnnotations());
1466         }
1467     }
1468 
1469     void attachTypeAnnotations(final Symbol sym) {
1470         int numAttributes = nextChar();
1471         if (numAttributes != 0) {
1472             ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>();
1473             for (int i = 0; i < numAttributes; i++)
1474                 proxies.append(readTypeAnnotation());
1475             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
1476         }
1477     }
1478 
1479     /** Attach the default value for an annotation element.
1480      */
1481     void attachAnnotationDefault(final Symbol sym) {
1482         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1483         final Attribute value = readAttributeValue();
1484 
1485         // The default value is set later during annotation. It might
1486         // be the case that the Symbol sym is annotated _after_ the
1487         // repeating instances that depend on this default value,
1488         // because of this we set an interim value that tells us this
1489         // element (most likely) has a default.
1490         //
1491         // Set interim value for now, reset just before we do this
1492         // properly at annotate time.
1493         meth.defaultValue = value;
1494         annotate.normal(new AnnotationDefaultCompleter(meth, value));
1495     }
1496 
1497     Type readTypeOrClassSymbol(int i) {
1498         // support preliminary jsr175-format class files
1499         if (poolReader.hasTag(i, CONSTANT_Class))
1500             return poolReader.getClass(i).type;
1501         return readTypeToProxy(i);
1502     }
1503     Type readTypeToProxy(int i) {
1504         if (currentModule.module_info == currentOwner) {
1505             return new ProxyType(i);
1506         } else {
1507             return poolReader.getType(i);
1508         }
1509     }
1510 
1511     CompoundAnnotationProxy readCompoundAnnotation() {
1512         Type t;
1513         if (currentModule.module_info == currentOwner) {
1514             int cpIndex = nextChar();
1515             t = new ProxyType(cpIndex);
1516         } else {
1517             t = readTypeOrClassSymbol(nextChar());
1518         }
1519         int numFields = nextChar();
1520         ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>();
1521         for (int i=0; i<numFields; i++) {
1522             Name name = poolReader.getName(nextChar());
1523             Attribute value = readAttributeValue();
1524             pairs.append(new Pair<>(name, value));
1525         }
1526         return new CompoundAnnotationProxy(t, pairs.toList());
1527     }
1528 
1529     TypeAnnotationProxy readTypeAnnotation() {
1530         TypeAnnotationPosition position = readPosition();
1531         CompoundAnnotationProxy proxy = readCompoundAnnotation();
1532 
1533         return new TypeAnnotationProxy(proxy, position);
1534     }
1535 
1536     TypeAnnotationPosition readPosition() {
1537         int tag = nextByte(); // TargetType tag is a byte
1538 
1539         if (!TargetType.isValidTargetTypeValue(tag))
1540             throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
1541 
1542         TargetType type = TargetType.fromTargetTypeValue(tag);
1543 
1544         switch (type) {
1545         // instanceof
1546         case INSTANCEOF: {
1547             final int offset = nextChar();
1548             final TypeAnnotationPosition position =
1549                 TypeAnnotationPosition.instanceOf(readTypePath());
1550             position.offset = offset;
1551             return position;
1552         }
1553         // new expression
1554         case NEW: {
1555             final int offset = nextChar();
1556             final TypeAnnotationPosition position =
1557                 TypeAnnotationPosition.newObj(readTypePath());
1558             position.offset = offset;
1559             return position;
1560         }
1561         // constructor/method reference receiver
1562         case CONSTRUCTOR_REFERENCE: {
1563             final int offset = nextChar();
1564             final TypeAnnotationPosition position =
1565                 TypeAnnotationPosition.constructorRef(readTypePath());
1566             position.offset = offset;
1567             return position;
1568         }
1569         case METHOD_REFERENCE: {
1570             final int offset = nextChar();
1571             final TypeAnnotationPosition position =
1572                 TypeAnnotationPosition.methodRef(readTypePath());
1573             position.offset = offset;
1574             return position;
1575         }
1576         // local variable
1577         case LOCAL_VARIABLE: {
1578             final int table_length = nextChar();
1579             final int[] newLvarOffset = new int[table_length];
1580             final int[] newLvarLength = new int[table_length];
1581             final int[] newLvarIndex = new int[table_length];
1582 
1583             for (int i = 0; i < table_length; ++i) {
1584                 newLvarOffset[i] = nextChar();
1585                 newLvarLength[i] = nextChar();
1586                 newLvarIndex[i] = nextChar();
1587             }
1588 
1589             final TypeAnnotationPosition position =
1590                     TypeAnnotationPosition.localVariable(readTypePath());
1591             position.lvarOffset = newLvarOffset;
1592             position.lvarLength = newLvarLength;
1593             position.lvarIndex = newLvarIndex;
1594             return position;
1595         }
1596         // resource variable
1597         case RESOURCE_VARIABLE: {
1598             final int table_length = nextChar();
1599             final int[] newLvarOffset = new int[table_length];
1600             final int[] newLvarLength = new int[table_length];
1601             final int[] newLvarIndex = new int[table_length];
1602 
1603             for (int i = 0; i < table_length; ++i) {
1604                 newLvarOffset[i] = nextChar();
1605                 newLvarLength[i] = nextChar();
1606                 newLvarIndex[i] = nextChar();
1607             }
1608 
1609             final TypeAnnotationPosition position =
1610                     TypeAnnotationPosition.resourceVariable(readTypePath());
1611             position.lvarOffset = newLvarOffset;
1612             position.lvarLength = newLvarLength;
1613             position.lvarIndex = newLvarIndex;
1614             return position;
1615         }
1616         // exception parameter
1617         case EXCEPTION_PARAMETER: {
1618             final int exception_index = nextChar();
1619             final TypeAnnotationPosition position =
1620                 TypeAnnotationPosition.exceptionParameter(readTypePath());
1621             position.setExceptionIndex(exception_index);
1622             return position;
1623         }
1624         // method receiver
1625         case METHOD_RECEIVER:
1626             return TypeAnnotationPosition.methodReceiver(readTypePath());
1627         // type parameter
1628         case CLASS_TYPE_PARAMETER: {
1629             final int parameter_index = nextByte();
1630             return TypeAnnotationPosition
1631                 .typeParameter(readTypePath(), parameter_index);
1632         }
1633         case METHOD_TYPE_PARAMETER: {
1634             final int parameter_index = nextByte();
1635             return TypeAnnotationPosition
1636                 .methodTypeParameter(readTypePath(), parameter_index);
1637         }
1638         // type parameter bound
1639         case CLASS_TYPE_PARAMETER_BOUND: {
1640             final int parameter_index = nextByte();
1641             final int bound_index = nextByte();
1642             return TypeAnnotationPosition
1643                 .typeParameterBound(readTypePath(), parameter_index,
1644                                     bound_index);
1645         }
1646         case METHOD_TYPE_PARAMETER_BOUND: {
1647             final int parameter_index = nextByte();
1648             final int bound_index = nextByte();
1649             return TypeAnnotationPosition
1650                 .methodTypeParameterBound(readTypePath(), parameter_index,
1651                                           bound_index);
1652         }
1653         // class extends or implements clause
1654         case CLASS_EXTENDS: {
1655             final int type_index = nextChar();
1656             return TypeAnnotationPosition.classExtends(readTypePath(),
1657                                                        type_index);
1658         }
1659         // throws
1660         case THROWS: {
1661             final int type_index = nextChar();
1662             return TypeAnnotationPosition.methodThrows(readTypePath(),
1663                                                        type_index);
1664         }
1665         // method parameter
1666         case METHOD_FORMAL_PARAMETER: {
1667             final int parameter_index = nextByte();
1668             return TypeAnnotationPosition.methodParameter(readTypePath(),
1669                                                           parameter_index);
1670         }
1671         // type cast
1672         case CAST: {
1673             final int offset = nextChar();
1674             final int type_index = nextByte();
1675             final TypeAnnotationPosition position =
1676                 TypeAnnotationPosition.typeCast(readTypePath(), type_index);
1677             position.offset = offset;
1678             return position;
1679         }
1680         // method/constructor/reference type argument
1681         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: {
1682             final int offset = nextChar();
1683             final int type_index = nextByte();
1684             final TypeAnnotationPosition position = TypeAnnotationPosition
1685                 .constructorInvocationTypeArg(readTypePath(), type_index);
1686             position.offset = offset;
1687             return position;
1688         }
1689         case METHOD_INVOCATION_TYPE_ARGUMENT: {
1690             final int offset = nextChar();
1691             final int type_index = nextByte();
1692             final TypeAnnotationPosition position = TypeAnnotationPosition
1693                 .methodInvocationTypeArg(readTypePath(), type_index);
1694             position.offset = offset;
1695             return position;
1696         }
1697         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: {
1698             final int offset = nextChar();
1699             final int type_index = nextByte();
1700             final TypeAnnotationPosition position = TypeAnnotationPosition
1701                 .constructorRefTypeArg(readTypePath(), type_index);
1702             position.offset = offset;
1703             return position;
1704         }
1705         case METHOD_REFERENCE_TYPE_ARGUMENT: {
1706             final int offset = nextChar();
1707             final int type_index = nextByte();
1708             final TypeAnnotationPosition position = TypeAnnotationPosition
1709                 .methodRefTypeArg(readTypePath(), type_index);
1710             position.offset = offset;
1711             return position;
1712         }
1713         // We don't need to worry about these
1714         case METHOD_RETURN:
1715             return TypeAnnotationPosition.methodReturn(readTypePath());
1716         case FIELD:
1717             return TypeAnnotationPosition.field(readTypePath());
1718         case UNKNOWN:
1719             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
1720         default:
1721             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type);
1722         }
1723     }
1724 
1725     List<TypeAnnotationPosition.TypePathEntry> readTypePath() {
1726         int len = nextByte();
1727         ListBuffer<Integer> loc = new ListBuffer<>();
1728         for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
1729             loc = loc.append(nextByte());
1730 
1731         return TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
1732 
1733     }
1734 
1735     /**
1736      * Helper function to read an optional pool entry (with given function); this is used while parsing
1737      * InnerClasses and EnclosingMethod attributes, as well as when parsing supertype descriptor,
1738      * as per JVMS.
1739      */
1740     <Z> Z optPoolEntry(int index, IntFunction<Z> poolFunc, Z defaultValue) {
1741         return (index == 0) ?
1742                 defaultValue :
1743                 poolFunc.apply(index);
1744     }
1745 
1746     Attribute readAttributeValue() {
1747         char c = (char) buf.getByte(bp++);
1748         switch (c) {
1749         case 'B':
1750             return new Attribute.Constant(syms.byteType, poolReader.getConstant(nextChar()));
1751         case 'C':
1752             return new Attribute.Constant(syms.charType, poolReader.getConstant(nextChar()));
1753         case 'D':
1754             return new Attribute.Constant(syms.doubleType, poolReader.getConstant(nextChar()));
1755         case 'F':
1756             return new Attribute.Constant(syms.floatType, poolReader.getConstant(nextChar()));
1757         case 'I':
1758             return new Attribute.Constant(syms.intType, poolReader.getConstant(nextChar()));
1759         case 'J':
1760             return new Attribute.Constant(syms.longType, poolReader.getConstant(nextChar()));
1761         case 'S':
1762             return new Attribute.Constant(syms.shortType, poolReader.getConstant(nextChar()));
1763         case 'Z':
1764             return new Attribute.Constant(syms.booleanType, poolReader.getConstant(nextChar()));
1765         case 's':
1766             return new Attribute.Constant(syms.stringType, poolReader.getName(nextChar()).toString());
1767         case 'e':
1768             return new EnumAttributeProxy(readTypeToProxy(nextChar()), poolReader.getName(nextChar()));
1769         case 'c':
1770             return new ClassAttributeProxy(readTypeOrClassSymbol(nextChar()));
1771         case '[': {
1772             int n = nextChar();
1773             ListBuffer<Attribute> l = new ListBuffer<>();
1774             for (int i=0; i<n; i++)
1775                 l.append(readAttributeValue());
1776             return new ArrayAttributeProxy(l.toList());
1777         }
1778         case '@':
1779             return readCompoundAnnotation();
1780         default:
1781             throw new AssertionError("unknown annotation tag '" + c + "'");
1782         }
1783     }
1784 
1785     interface ProxyVisitor extends Attribute.Visitor {
1786         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1787         void visitClassAttributeProxy(ClassAttributeProxy proxy);
1788         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1789         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1790     }
1791 
1792     static class EnumAttributeProxy extends Attribute {
1793         Type enumType;
1794         Name enumerator;
1795         public EnumAttributeProxy(Type enumType, Name enumerator) {
1796             super(null);
1797             this.enumType = enumType;
1798             this.enumerator = enumerator;
1799         }
1800         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1801         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1802         public String toString() {
1803             return "/*proxy enum*/" + enumType + "." + enumerator;
1804         }
1805     }
1806 
1807     static class ClassAttributeProxy extends Attribute {
1808         Type classType;
1809         public ClassAttributeProxy(Type classType) {
1810             super(null);
1811             this.classType = classType;
1812         }
1813         public void accept(Visitor v) { ((ProxyVisitor)v).visitClassAttributeProxy(this); }
1814         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1815         public String toString() {
1816             return "/*proxy class*/" + classType + ".class";
1817         }
1818     }
1819 
1820     static class ArrayAttributeProxy extends Attribute {
1821         List<Attribute> values;
1822         ArrayAttributeProxy(List<Attribute> values) {
1823             super(null);
1824             this.values = values;
1825         }
1826         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1827         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1828         public String toString() {
1829             return "{" + values + "}";
1830         }
1831     }
1832 
1833     /** A temporary proxy representing a compound attribute.
1834      */
1835     static class CompoundAnnotationProxy extends Attribute {
1836         final List<Pair<Name,Attribute>> values;
1837         public CompoundAnnotationProxy(Type type,
1838                                       List<Pair<Name,Attribute>> values) {
1839             super(type);
1840             this.values = values;
1841         }
1842         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1843         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1844         public String toString() {
1845             StringBuilder buf = new StringBuilder();
1846             buf.append("@");
1847             buf.append(type.tsym.getQualifiedName());
1848             buf.append("/*proxy*/{");
1849             boolean first = true;
1850             for (List<Pair<Name,Attribute>> v = values;
1851                  v.nonEmpty(); v = v.tail) {
1852                 Pair<Name,Attribute> value = v.head;
1853                 if (!first) buf.append(",");
1854                 first = false;
1855                 buf.append(value.fst);
1856                 buf.append("=");
1857                 buf.append(value.snd);
1858             }
1859             buf.append("}");
1860             return buf.toString();
1861         }
1862     }
1863 
1864     /** A temporary proxy representing a type annotation.
1865      */
1866     static class TypeAnnotationProxy {
1867         final CompoundAnnotationProxy compound;
1868         final TypeAnnotationPosition position;
1869         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1870                 TypeAnnotationPosition position) {
1871             this.compound = compound;
1872             this.position = position;
1873         }
1874     }
1875 
1876     class AnnotationDeproxy implements ProxyVisitor {
1877         private ClassSymbol requestingOwner;
1878 
1879         AnnotationDeproxy(ClassSymbol owner) {
1880             this.requestingOwner = owner;
1881         }
1882 
1883         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1884             // also must fill in types!!!!
1885             ListBuffer<Attribute.Compound> buf = new ListBuffer<>();
1886             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1887                 buf.append(deproxyCompound(l.head));
1888             }
1889             return buf.toList();
1890         }
1891 
1892         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1893             Type annotationType = resolvePossibleProxyType(a.type);
1894             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>();
1895             for (List<Pair<Name,Attribute>> l = a.values;
1896                  l.nonEmpty();
1897                  l = l.tail) {
1898                 MethodSymbol meth = findAccessMethod(annotationType, l.head.fst);
1899                 buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1900             }
1901             return new Attribute.Compound(annotationType, buf.toList());
1902         }
1903 
1904         MethodSymbol findAccessMethod(Type container, Name name) {
1905             CompletionFailure failure = null;
1906             try {
1907                 for (Symbol sym : container.tsym.members().getSymbolsByName(name)) {
1908                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1909                         return (MethodSymbol) sym;
1910                 }
1911             } catch (CompletionFailure ex) {
1912                 failure = ex;
1913             }
1914             // The method wasn't found: emit a warning and recover
1915             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1916             try {
1917                 if (lintClassfile) {
1918                     if (failure == null) {
1919                         log.warning(Warnings.AnnotationMethodNotFound(container, name));
1920                     } else {
1921                         log.warning(Warnings.AnnotationMethodNotFoundReason(container,
1922                                                                             name,
1923                                                                             failure.getDetailValue()));//diagnostic, if present
1924                     }
1925                 }
1926             } finally {
1927                 log.useSource(prevSource);
1928             }
1929             // Construct a new method type and symbol.  Use bottom
1930             // type (typeof null) as return type because this type is
1931             // a subtype of all reference types and can be converted
1932             // to primitive types by unboxing.
1933             MethodType mt = new MethodType(List.nil(),
1934                                            syms.botType,
1935                                            List.nil(),
1936                                            syms.methodClass);
1937             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1938         }
1939 
1940         Attribute result;
1941         Type type;
1942         Attribute deproxy(Type t, Attribute a) {
1943             Type oldType = type;
1944             try {
1945                 type = t;
1946                 a.accept(this);
1947                 return result;
1948             } finally {
1949                 type = oldType;
1950             }
1951         }
1952 
1953         // implement Attribute.Visitor below
1954 
1955         public void visitConstant(Attribute.Constant value) {
1956             // assert value.type == type;
1957             result = value;
1958         }
1959 
1960         public void visitClass(Attribute.Class clazz) {
1961             result = clazz;
1962         }
1963 
1964         public void visitEnum(Attribute.Enum e) {
1965             throw new AssertionError(); // shouldn't happen
1966         }
1967 
1968         public void visitCompound(Attribute.Compound compound) {
1969             throw new AssertionError(); // shouldn't happen
1970         }
1971 
1972         public void visitArray(Attribute.Array array) {
1973             throw new AssertionError(); // shouldn't happen
1974         }
1975 
1976         public void visitError(Attribute.Error e) {
1977             throw new AssertionError(); // shouldn't happen
1978         }
1979 
1980         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1981             // type.tsym.flatName() should == proxy.enumFlatName
1982             Type enumType = resolvePossibleProxyType(proxy.enumType);
1983             TypeSymbol enumTypeSym = enumType.tsym;
1984             VarSymbol enumerator = null;
1985             CompletionFailure failure = null;
1986             try {
1987                 for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) {
1988                     if (sym.kind == VAR) {
1989                         enumerator = (VarSymbol)sym;
1990                         break;
1991                     }
1992                 }
1993             }
1994             catch (CompletionFailure ex) {
1995                 failure = ex;
1996             }
1997             if (enumerator == null) {
1998                 if (failure != null) {
1999                     log.warning(Warnings.UnknownEnumConstantReason(currentClassFile,
2000                                                                    enumTypeSym,
2001                                                                    proxy.enumerator,
2002                                                                    failure.getDiagnostic()));
2003                 } else {
2004                     log.warning(Warnings.UnknownEnumConstant(currentClassFile,
2005                                                              enumTypeSym,
2006                                                              proxy.enumerator));
2007                 }
2008                 result = new Attribute.Enum(enumTypeSym.type,
2009                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
2010             } else {
2011                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
2012             }
2013         }
2014 
2015         @Override
2016         public void visitClassAttributeProxy(ClassAttributeProxy proxy) {
2017             Type classType = resolvePossibleProxyType(proxy.classType);
2018             result = new Attribute.Class(types, classType);
2019         }
2020 
2021         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
2022             int length = proxy.values.length();
2023             Attribute[] ats = new Attribute[length];
2024             Type elemtype = types.elemtype(type);
2025             int i = 0;
2026             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
2027                 ats[i++] = deproxy(elemtype, p.head);
2028             }
2029             result = new Attribute.Array(type, ats);
2030         }
2031 
2032         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
2033             result = deproxyCompound(proxy);
2034         }
2035 
2036         Type resolvePossibleProxyType(Type t) {
2037             if (t instanceof ProxyType) {
2038                 Assert.check(requestingOwner.owner.kind == MDL);
2039                 ModuleSymbol prevCurrentModule = currentModule;
2040                 currentModule = (ModuleSymbol) requestingOwner.owner;
2041                 try {
2042                     return ((ProxyType) t).resolve();
2043                 } finally {
2044                     currentModule = prevCurrentModule;
2045                 }
2046             } else {
2047                 return t;
2048             }
2049         }
2050     }
2051 
2052     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Runnable {
2053         final MethodSymbol sym;
2054         final Attribute value;
2055         final JavaFileObject classFile = currentClassFile;
2056 
2057         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
2058             super(currentOwner.kind == MTH
2059                     ? currentOwner.enclClass() : (ClassSymbol)currentOwner);
2060             this.sym = sym;
2061             this.value = value;
2062         }
2063 
2064         @Override
2065         public void run() {
2066             JavaFileObject previousClassFile = currentClassFile;
2067             try {
2068                 // Reset the interim value set earlier in
2069                 // attachAnnotationDefault().
2070                 sym.defaultValue = null;
2071                 currentClassFile = classFile;
2072                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
2073             } finally {
2074                 currentClassFile = previousClassFile;
2075             }
2076         }
2077 
2078         @Override
2079         public String toString() {
2080             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
2081         }
2082     }
2083 
2084     class AnnotationCompleter extends AnnotationDeproxy implements Runnable {
2085         final Symbol sym;
2086         final List<CompoundAnnotationProxy> l;
2087         final JavaFileObject classFile;
2088 
2089         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
2090             super(currentOwner.kind == MTH
2091                     ? currentOwner.enclClass() : (ClassSymbol)currentOwner);
2092             if (sym.kind == TYP && sym.owner.kind == MDL) {
2093                 this.sym = sym.owner;
2094             } else {
2095                 this.sym = sym;
2096             }
2097             this.l = l;
2098             this.classFile = currentClassFile;
2099         }
2100 
2101         @Override
2102         public void run() {
2103             JavaFileObject previousClassFile = currentClassFile;
2104             try {
2105                 currentClassFile = classFile;
2106                 List<Attribute.Compound> newList = deproxyCompoundList(l);
2107                 for (Attribute.Compound attr : newList) {
2108                     if (attr.type.tsym == syms.deprecatedType.tsym) {
2109                         sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION);
2110                         Attribute forRemoval = attr.member(names.forRemoval);
2111                         if (forRemoval instanceof Attribute.Constant) {
2112                             Attribute.Constant c = (Attribute.Constant) forRemoval;
2113                             if (c.type == syms.booleanType && ((Integer) c.value) != 0) {
2114                                 sym.flags_field |= DEPRECATED_REMOVAL;
2115                             }
2116                         }
2117                     }
2118                 }
2119                 if (sym.annotationsPendingCompletion()) {
2120                     sym.setDeclarationAttributes(newList);
2121                 } else {
2122                     sym.appendAttributes(newList);
2123                 }
2124             } finally {
2125                 currentClassFile = previousClassFile;
2126             }
2127         }
2128 
2129         @Override
2130         public String toString() {
2131             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
2132         }
2133     }
2134 
2135     class TypeAnnotationCompleter extends AnnotationCompleter {
2136 
2137         List<TypeAnnotationProxy> proxies;
2138 
2139         TypeAnnotationCompleter(Symbol sym,
2140                 List<TypeAnnotationProxy> proxies) {
2141             super(sym, List.nil());
2142             this.proxies = proxies;
2143         }
2144 
2145         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
2146             ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
2147             for (TypeAnnotationProxy proxy: proxies) {
2148                 Attribute.Compound compound = deproxyCompound(proxy.compound);
2149                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
2150                 buf.add(typeCompound);
2151             }
2152             return buf.toList();
2153         }
2154 
2155         @Override
2156         public void run() {
2157             JavaFileObject previousClassFile = currentClassFile;
2158             try {
2159                 currentClassFile = classFile;
2160                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
2161                 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
2162             } finally {
2163                 currentClassFile = previousClassFile;
2164             }
2165         }
2166     }
2167 
2168 
2169 /************************************************************************
2170  * Reading Symbols
2171  ***********************************************************************/
2172 
2173     /** Read a field.
2174      */
2175     VarSymbol readField() {
2176         long flags = adjustFieldFlags(nextChar());
2177         Name name = poolReader.getName(nextChar());
2178         Type type = poolReader.getType(nextChar());
2179         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
2180         readMemberAttrs(v);
2181         return v;
2182     }
2183 
2184     /** Read a method.
2185      */
2186     MethodSymbol readMethod() {
2187         long flags = adjustMethodFlags(nextChar());
2188         Name name = poolReader.getName(nextChar());
2189         Type type = poolReader.getType(nextChar());
2190         if (currentOwner.isInterface() &&
2191                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
2192             if (majorVersion > Version.V52.major ||
2193                     (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) {
2194                 if ((flags & (STATIC | PRIVATE)) == 0) {
2195                     currentOwner.flags_field |= DEFAULT;
2196                     flags |= DEFAULT | ABSTRACT;
2197                 }
2198             } else {
2199                 //protect against ill-formed classfiles
2200                 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface",
2201                                    Integer.toString(majorVersion),
2202                                    Integer.toString(minorVersion));
2203             }
2204         }
2205         if (name == names.init && currentOwner.hasOuterInstance()) {
2206             // Sometimes anonymous classes don't have an outer
2207             // instance, however, there is no reliable way to tell so
2208             // we never strip this$n
2209             // ditto for local classes. Local classes that have an enclosing method set
2210             // won't pass the "hasOuterInstance" check above, but those that don't have an
2211             // enclosing method (i.e. from initializers) will pass that check.
2212             boolean local = !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE);
2213             if (!currentOwner.name.isEmpty() && !local)
2214                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
2215                                       type.getReturnType(),
2216                                       type.getThrownTypes(),
2217                                       syms.methodClass);
2218         }
2219         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
2220         if (types.isSignaturePolymorphic(m)) {
2221             m.flags_field |= SIGNATURE_POLYMORPHIC;
2222         }
2223         if (saveParameterNames)
2224             initParameterNames(m);
2225         Symbol prevOwner = currentOwner;
2226         currentOwner = m;
2227         try {
2228             readMemberAttrs(m);
2229         } finally {
2230             currentOwner = prevOwner;
2231         }
2232         setParameters(m, type);
2233 
2234         if ((flags & VARARGS) != 0) {
2235             final Type last = type.getParameterTypes().last();
2236             if (last == null || !last.hasTag(ARRAY)) {
2237                 m.flags_field &= ~VARARGS;
2238                 throw badClassFile("malformed.vararg.method", m);
2239             }
2240         }
2241 
2242         return m;
2243     }
2244 
2245     private List<Type> adjustMethodParams(long flags, List<Type> args) {
2246         if (args.isEmpty()) {
2247             return args;
2248         }
2249         boolean isVarargs = (flags & VARARGS) != 0;
2250         if (isVarargs) {
2251             Type varargsElem = args.last();
2252             ListBuffer<Type> adjustedArgs = new ListBuffer<>();
2253             for (Type t : args) {
2254                 adjustedArgs.append(t != varargsElem ?
2255                     t :
2256                     ((ArrayType)t).makeVarargs());
2257             }
2258             args = adjustedArgs.toList();
2259         }
2260         return args.tail;
2261     }
2262 
2263     /**
2264      * Init the parameter names array.
2265      * Parameter names are currently inferred from the names in the
2266      * LocalVariableTable attributes of a Code attribute.
2267      * (Note: this means parameter names are currently not available for
2268      * methods without a Code attribute.)
2269      * This method initializes an array in which to store the name indexes
2270      * of parameter names found in LocalVariableTable attributes. It is
2271      * slightly supersized to allow for additional slots with a start_pc of 0.
2272      */
2273     void initParameterNames(MethodSymbol sym) {
2274         // make allowance for synthetic parameters.
2275         final int excessSlots = 4;
2276         int expectedParameterSlots =
2277                 Code.width(sym.type.getParameterTypes()) + excessSlots;
2278         if (parameterNameIndices == null
2279                 || parameterNameIndices.length < expectedParameterSlots) {
2280             parameterNameIndices = new int[expectedParameterSlots];
2281         } else
2282             Arrays.fill(parameterNameIndices, 0);
2283         haveParameterNameIndices = false;
2284         sawMethodParameters = false;
2285     }
2286 
2287     /**
2288      * Set the parameters for a method symbol, including any names and
2289      * annotations that were read.
2290      *
2291      * <p>The type of the symbol may have changed while reading the
2292      * method attributes (see the Signature attribute). This may be
2293      * because of generic information or because anonymous synthetic
2294      * parameters were added.   The original type (as read from the
2295      * method descriptor) is used to help guess the existence of
2296      * anonymous synthetic parameters.
2297      */
2298     void setParameters(MethodSymbol sym, Type jvmType) {
2299         // If we get parameter names from MethodParameters, then we
2300         // don't need to skip.
2301         int firstParam = 0;
2302         if (!sawMethodParameters) {
2303             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
2304             // the code in readMethod may have skipped the first
2305             // parameter when setting up the MethodType. If so, we
2306             // make a corresponding allowance here for the position of
2307             // the first parameter.  Note that this assumes the
2308             // skipped parameter has a width of 1 -- i.e. it is not
2309             // a double width type (long or double.)
2310             if (sym.name == names.init && currentOwner.hasOuterInstance()) {
2311                 // Sometimes anonymous classes don't have an outer
2312                 // instance, however, there is no reliable way to tell so
2313                 // we never strip this$n
2314                 if (!currentOwner.name.isEmpty())
2315                     firstParam += 1;
2316             }
2317 
2318             if (sym.type != jvmType) {
2319                 // reading the method attributes has caused the
2320                 // symbol's type to be changed. (i.e. the Signature
2321                 // attribute.)  This may happen if there are hidden
2322                 // (synthetic) parameters in the descriptor, but not
2323                 // in the Signature.  The position of these hidden
2324                 // parameters is unspecified; for now, assume they are
2325                 // at the beginning, and so skip over them. The
2326                 // primary case for this is two hidden parameters
2327                 // passed into Enum constructors.
2328                 int skip = Code.width(jvmType.getParameterTypes())
2329                         - Code.width(sym.type.getParameterTypes());
2330                 firstParam += skip;
2331             }
2332         }
2333         Set<Name> paramNames = new HashSet<>();
2334         ListBuffer<VarSymbol> params = new ListBuffer<>();
2335         int nameIndex = firstParam;
2336         int annotationIndex = 0;
2337         for (Type t: sym.type.getParameterTypes()) {
2338             VarSymbol param = parameter(nameIndex, t, sym, paramNames);
2339             params.append(param);
2340             if (parameterAnnotations != null) {
2341                 ParameterAnnotations annotations = parameterAnnotations[annotationIndex];
2342                 if (annotations != null && annotations.proxies != null
2343                         && !annotations.proxies.isEmpty()) {
2344                     annotate.normal(new AnnotationCompleter(param, annotations.proxies));
2345                 }
2346             }
2347             nameIndex += sawMethodParameters ? 1 : Code.width(t);
2348             annotationIndex++;
2349         }
2350         if (parameterAnnotations != null && parameterAnnotations.length != annotationIndex) {
2351             throw badClassFile("bad.runtime.invisible.param.annotations", sym);
2352         }
2353         Assert.checkNull(sym.params);
2354         sym.params = params.toList();
2355         parameterAnnotations = null;
2356         parameterNameIndices = null;
2357     }
2358 
2359 
2360     // Returns the name for the parameter at position 'index', either using
2361     // names read from the MethodParameters, or by synthesizing a name that
2362     // is not on the 'exclude' list.
2363     private VarSymbol parameter(int index, Type t, MethodSymbol owner, Set<Name> exclude) {
2364         long flags = PARAMETER;
2365         Name argName;
2366         if (parameterNameIndices != null && index < parameterNameIndices.length
2367                 && parameterNameIndices[index] != 0) {
2368             argName = optPoolEntry(parameterNameIndices[index], poolReader::getName, names.empty);
2369             flags |= NAME_FILLED;
2370         } else {
2371             String prefix = "arg";
2372             while (true) {
2373                 argName = names.fromString(prefix + exclude.size());
2374                 if (!exclude.contains(argName))
2375                     break;
2376                 prefix += "$";
2377             }
2378         }
2379         exclude.add(argName);
2380         return new ParamSymbol(flags, argName, t, owner);
2381     }
2382 
2383     /**
2384      * skip n bytes
2385      */
2386     void skipBytes(int n) {
2387         bp = bp + n;
2388     }
2389 
2390     /** Skip a field or method
2391      */
2392     void skipMember() {
2393         bp = bp + 6;
2394         char ac = nextChar();
2395         for (int i = 0; i < ac; i++) {
2396             bp = bp + 2;
2397             int attrLen = nextInt();
2398             bp = bp + attrLen;
2399         }
2400     }
2401 
2402     void skipInnerClasses() {
2403         int n = nextChar();
2404         for (int i = 0; i < n; i++) {
2405             nextChar();
2406             nextChar();
2407             nextChar();
2408             nextChar();
2409         }
2410     }
2411 
2412     /** Enter type variables of this classtype and all enclosing ones in
2413      *  `typevars'.
2414      */
2415     protected void enterTypevars(Symbol sym, Type t) {
2416         if (t.getEnclosingType() != null) {
2417             if (!t.getEnclosingType().hasTag(TypeTag.NONE)) {
2418                 enterTypevars(sym.owner, t.getEnclosingType());
2419             }
2420         } else if (sym.kind == MTH && !sym.isStatic()) {
2421             enterTypevars(sym.owner, sym.owner.type);
2422         }
2423         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) {
2424             typevars.enter(xs.head.tsym);
2425         }
2426     }
2427 
2428     protected ClassSymbol enterClass(Name name) {
2429         return syms.enterClass(currentModule, name);
2430     }
2431 
2432     protected ClassSymbol enterClass(Name name, TypeSymbol owner) {
2433         return syms.enterClass(currentModule, name, owner);
2434     }
2435 
2436     /** Read contents of a given class symbol `c'. Both external and internal
2437      *  versions of an inner class are read.
2438      */
2439     void readClass(ClassSymbol c) {
2440         ClassType ct = (ClassType)c.type;
2441 
2442         // allocate scope for members
2443         c.members_field = WriteableScope.create(c);
2444 
2445         // prepare type variable table
2446         typevars = typevars.dup(currentOwner);
2447         if (ct.getEnclosingType().hasTag(CLASS))
2448             enterTypevars(c.owner, ct.getEnclosingType());
2449 
2450         // read flags, or skip if this is an inner class
2451         long f = nextChar();
2452         long flags = adjustClassFlags(f);
2453         if ((flags & MODULE) == 0) {
2454             if (c.owner.kind == PCK || c.owner.kind == ERR) c.flags_field = flags;
2455             // read own class name and check that it matches
2456             currentModule = c.packge().modle;
2457             ClassSymbol self = poolReader.getClass(nextChar());
2458             if (c != self) {
2459                 throw badClassFile("class.file.wrong.class",
2460                                    self.flatname);
2461             }
2462         } else {
2463             if (majorVersion < Version.V53.major) {
2464                 throw badClassFile("anachronistic.module.info",
2465                         Integer.toString(majorVersion),
2466                         Integer.toString(minorVersion));
2467             }
2468             c.flags_field = flags;
2469             currentModule = (ModuleSymbol) c.owner;
2470             int this_class = nextChar();
2471             // temp, no check on this_class
2472         }
2473 
2474         // class attributes must be read before class
2475         // skip ahead to read class attributes
2476         int startbp = bp;
2477         nextChar();
2478         char interfaceCount = nextChar();
2479         bp += interfaceCount * 2;
2480         char fieldCount = nextChar();
2481         for (int i = 0; i < fieldCount; i++) skipMember();
2482         char methodCount = nextChar();
2483         for (int i = 0; i < methodCount; i++) skipMember();
2484         readClassAttrs(c);
2485 
2486         if (ct.permitted != null && !ct.permitted.isEmpty()) {
2487             c.flags_field |= SEALED;
2488             c.flags_field &= ~FINAL;
2489         }
2490 
2491         // reset and read rest of classinfo
2492         bp = startbp;
2493         int n = nextChar();
2494         if ((flags & MODULE) != 0 && n > 0) {
2495             throw badClassFile("module.info.invalid.super.class");
2496         }
2497         if (ct.supertype_field == null)
2498             ct.supertype_field =
2499                     optPoolEntry(n, idx -> poolReader.getClass(idx).erasure(types), Type.noType);
2500         n = nextChar();
2501         List<Type> is = List.nil();
2502         for (int i = 0; i < n; i++) {
2503             Type _inter = poolReader.getClass(nextChar()).erasure(types);
2504             is = is.prepend(_inter);
2505         }
2506         if (ct.interfaces_field == null)
2507             ct.interfaces_field = is.reverse();
2508 
2509         Assert.check(fieldCount == nextChar());
2510         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2511         Assert.check(methodCount == nextChar());
2512         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2513 
2514         typevars = typevars.leave();
2515     }
2516 
2517     /** Read inner class info. For each inner/outer pair allocate a
2518      *  member class.
2519      */
2520     void readInnerClasses(ClassSymbol c) {
2521         int n = nextChar();
2522         for (int i = 0; i < n; i++) {
2523             nextChar(); // skip inner class symbol
2524             int outerIdx = nextChar();
2525             int nameIdx = nextChar();
2526             ClassSymbol outer = optPoolEntry(outerIdx, poolReader::getClass, null);
2527             Name name = optPoolEntry(nameIdx, poolReader::getName, names.empty);
2528             if (name == null) name = names.empty;
2529             long flags = adjustClassFlags(nextChar());
2530             if (outer != null) { // we have a member class
2531                 if (name == names.empty)
2532                     name = names.one;
2533                 ClassSymbol member = enterClass(name, outer);
2534                 if ((flags & STATIC) == 0) {
2535                     ((ClassType)member.type).setEnclosingType(outer.type);
2536                     if (member.erasure_field != null)
2537                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2538                 }
2539                 if (c == outer) {
2540                     member.flags_field = flags;
2541                     enterMember(c, member);
2542                 }
2543             }
2544         }
2545     }
2546 
2547     /** Read a class definition from the bytes in buf.
2548      */
2549     private void readClassBuffer(ClassSymbol c) throws IOException {
2550         int magic = nextInt();
2551         if (magic != JAVA_MAGIC)
2552             throw badClassFile("illegal.start.of.class.file");
2553 
2554         minorVersion = nextChar();
2555         majorVersion = nextChar();
2556         int maxMajor = Version.MAX().major;
2557         int maxMinor = Version.MAX().minor;
2558         if (majorVersion > maxMajor ||
2559             majorVersion * 1000 + minorVersion <
2560             Version.MIN().major * 1000 + Version.MIN().minor) {
2561             if (majorVersion == (maxMajor + 1))
2562                 log.warning(Warnings.BigMajorVersion(currentClassFile,
2563                                                      majorVersion,
2564                                                      maxMajor));
2565             else
2566                 throw badClassFile("wrong.version",
2567                                    Integer.toString(majorVersion),
2568                                    Integer.toString(minorVersion),
2569                                    Integer.toString(maxMajor),
2570                                    Integer.toString(maxMinor));
2571         }
2572 
2573         if (minorVersion == ClassFile.PREVIEW_MINOR_VERSION) {
2574             if (!preview.isEnabled()) {
2575                 log.error(preview.disabledError(currentClassFile, majorVersion));
2576             } else {
2577                 preview.warnPreview(c.classfile, majorVersion);
2578             }
2579         }
2580 
2581         poolReader = new PoolReader(this, names, syms);
2582         bp = poolReader.readPool(buf, bp);
2583         if (signatureBuffer.length < bp) {
2584             int ns = Integer.highestOneBit(bp) << 1;
2585             signatureBuffer = new byte[ns];
2586         }
2587         readClass(c);
2588     }
2589 
2590     public void readClassFile(ClassSymbol c) {
2591         currentOwner = c;
2592         currentClassFile = c.classfile;
2593         warnedAttrs.clear();
2594         filling = true;
2595         target = null;
2596         repeatable = null;
2597         try {
2598             bp = 0;
2599             buf.reset();
2600             buf.appendStream(c.classfile.openInputStream());
2601             readClassBuffer(c);
2602             if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2603                 List<Type> missing = missingTypeVariables;
2604                 List<Type> found = foundTypeVariables;
2605                 missingTypeVariables = List.nil();
2606                 foundTypeVariables = List.nil();
2607                 interimUses = List.nil();
2608                 interimProvides = List.nil();
2609                 filling = false;
2610                 ClassType ct = (ClassType)currentOwner.type;
2611                 ct.supertype_field =
2612                     types.subst(ct.supertype_field, missing, found);
2613                 ct.interfaces_field =
2614                     types.subst(ct.interfaces_field, missing, found);
2615                 ct.typarams_field =
2616                     types.substBounds(ct.typarams_field, missing, found);
2617                 for (List<Type> types = ct.typarams_field; types.nonEmpty(); types = types.tail) {
2618                     types.head.tsym.type = types.head;
2619                 }
2620             } else if (missingTypeVariables.isEmpty() !=
2621                        foundTypeVariables.isEmpty()) {
2622                 Name name = missingTypeVariables.head.tsym.name;
2623                 throw badClassFile("undecl.type.var", name);
2624             }
2625 
2626             if ((c.flags_field & Flags.ANNOTATION) != 0) {
2627                 c.setAnnotationTypeMetadata(new AnnotationTypeMetadata(c, new CompleterDeproxy(c, target, repeatable)));
2628             } else {
2629                 c.setAnnotationTypeMetadata(AnnotationTypeMetadata.notAnAnnotationType());
2630             }
2631 
2632             if (c == currentModule.module_info) {
2633                 if (interimUses.nonEmpty() || interimProvides.nonEmpty()) {
2634                     Assert.check(currentModule.isCompleted());
2635                     currentModule.usesProvidesCompleter =
2636                             new UsesProvidesCompleter(currentModule, interimUses, interimProvides);
2637                 } else {
2638                     currentModule.uses = List.nil();
2639                     currentModule.provides = List.nil();
2640                 }
2641             }
2642         } catch (IOException | ClosedFileSystemException ex) {
2643             throw badClassFile("unable.to.access.file", ex.toString());
2644         } catch (ArrayIndexOutOfBoundsException ex) {
2645             throw badClassFile("bad.class.file", c.flatname);
2646         } finally {
2647             interimUses = List.nil();
2648             interimProvides = List.nil();
2649             missingTypeVariables = List.nil();
2650             foundTypeVariables = List.nil();
2651             filling = false;
2652         }
2653     }
2654 
2655     /** We can only read a single class file at a time; this
2656      *  flag keeps track of when we are currently reading a class
2657      *  file.
2658      */
2659     public boolean filling = false;
2660 
2661 /************************************************************************
2662  * Adjusting flags
2663  ***********************************************************************/
2664 
2665     long adjustFieldFlags(long flags) {
2666         return flags;
2667     }
2668 
2669     long adjustMethodFlags(long flags) {
2670         if ((flags & ACC_BRIDGE) != 0) {
2671             flags &= ~ACC_BRIDGE;
2672             flags |= BRIDGE;
2673         }
2674         if ((flags & ACC_VARARGS) != 0) {
2675             flags &= ~ACC_VARARGS;
2676             flags |= VARARGS;
2677         }
2678         return flags;
2679     }
2680 
2681     long adjustClassFlags(long flags) {
2682         if ((flags & ACC_MODULE) != 0) {
2683             flags &= ~ACC_MODULE;
2684             flags |= MODULE;
2685         }
2686         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2687     }
2688 
2689     /**
2690      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2691      * The attribute is only the last component of the original filename, so is unlikely
2692      * to be valid as is, so operations other than those to access the name throw
2693      * UnsupportedOperationException
2694      */
2695     private static class SourceFileObject implements JavaFileObject {
2696 
2697         /** The file's name.
2698          */
2699         private final Name name;
2700 
2701         public SourceFileObject(Name name) {
2702             this.name = name;
2703         }
2704 
2705         @Override @DefinedBy(Api.COMPILER)
2706         public URI toUri() {
2707             try {
2708                 return new URI(null, name.toString(), null);
2709             } catch (URISyntaxException e) {
2710                 throw new PathFileObject.CannotCreateUriError(name.toString(), e);
2711             }
2712         }
2713 
2714         @Override @DefinedBy(Api.COMPILER)
2715         public String getName() {
2716             return name.toString();
2717         }
2718 
2719         @Override @DefinedBy(Api.COMPILER)
2720         public JavaFileObject.Kind getKind() {
2721             return BaseFileManager.getKind(getName());
2722         }
2723 
2724         @Override @DefinedBy(Api.COMPILER)
2725         public InputStream openInputStream() {
2726             throw new UnsupportedOperationException();
2727         }
2728 
2729         @Override @DefinedBy(Api.COMPILER)
2730         public OutputStream openOutputStream() {
2731             throw new UnsupportedOperationException();
2732         }
2733 
2734         @Override @DefinedBy(Api.COMPILER)
2735         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2736             throw new UnsupportedOperationException();
2737         }
2738 
2739         @Override @DefinedBy(Api.COMPILER)
2740         public Reader openReader(boolean ignoreEncodingErrors) {
2741             throw new UnsupportedOperationException();
2742         }
2743 
2744         @Override @DefinedBy(Api.COMPILER)
2745         public Writer openWriter() {
2746             throw new UnsupportedOperationException();
2747         }
2748 
2749         @Override @DefinedBy(Api.COMPILER)
2750         public long getLastModified() {
2751             throw new UnsupportedOperationException();
2752         }
2753 
2754         @Override @DefinedBy(Api.COMPILER)
2755         public boolean delete() {
2756             throw new UnsupportedOperationException();
2757         }
2758 
2759         @Override @DefinedBy(Api.COMPILER)
2760         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2761             return true; // fail-safe mode
2762         }
2763 
2764         @Override @DefinedBy(Api.COMPILER)
2765         public NestingKind getNestingKind() {
2766             return null;
2767         }
2768 
2769         @Override @DefinedBy(Api.COMPILER)
2770         public Modifier getAccessLevel() {
2771             return null;
2772         }
2773 
2774         /**
2775          * Check if two file objects are equal.
2776          * SourceFileObjects are just placeholder objects for the value of a
2777          * SourceFile attribute, and do not directly represent specific files.
2778          * Two SourceFileObjects are equal if their names are equal.
2779          */
2780         @Override
2781         public boolean equals(Object other) {
2782             if (this == other)
2783                 return true;
2784 
2785             if (!(other instanceof SourceFileObject))
2786                 return false;
2787 
2788             SourceFileObject o = (SourceFileObject) other;
2789             return name.equals(o.name);
2790         }
2791 
2792         @Override
2793         public int hashCode() {
2794             return name.hashCode();
2795         }
2796     }
2797 
2798     private class CompleterDeproxy implements AnnotationTypeCompleter {
2799         ClassSymbol proxyOn;
2800         CompoundAnnotationProxy target;
2801         CompoundAnnotationProxy repeatable;
2802 
2803         public CompleterDeproxy(ClassSymbol c, CompoundAnnotationProxy target,
2804                 CompoundAnnotationProxy repeatable)
2805         {
2806             this.proxyOn = c;
2807             this.target = target;
2808             this.repeatable = repeatable;
2809         }
2810 
2811         @Override
2812         public void complete(ClassSymbol sym) {
2813             Assert.check(proxyOn == sym);
2814             Attribute.Compound theTarget = null, theRepeatable = null;
2815             AnnotationDeproxy deproxy;
2816 
2817             try {
2818                 if (target != null) {
2819                     deproxy = new AnnotationDeproxy(proxyOn);
2820                     theTarget = deproxy.deproxyCompound(target);
2821                 }
2822 
2823                 if (repeatable != null) {
2824                     deproxy = new AnnotationDeproxy(proxyOn);
2825                     theRepeatable = deproxy.deproxyCompound(repeatable);
2826                 }
2827             } catch (Exception e) {
2828                 throw new CompletionFailure(sym,
2829                                             () -> ClassReader.this.diagFactory.fragment(Fragments.ExceptionMessage(e.getMessage())),
2830                                             dcfh);
2831             }
2832 
2833             sym.getAnnotationTypeMetadata().setTarget(theTarget);
2834             sym.getAnnotationTypeMetadata().setRepeatable(theRepeatable);
2835         }
2836     }
2837 
2838     private class ProxyType extends Type {
2839 
2840         private final Name name;
2841 
2842         public ProxyType(int index) {
2843             super(syms.noSymbol, TypeMetadata.EMPTY);
2844             this.name = poolReader.getName(index);
2845         }
2846 
2847         @Override
2848         public TypeTag getTag() {
2849             return TypeTag.NONE;
2850         }
2851 
2852         @Override
2853         public Type cloneWithMetadata(TypeMetadata metadata) {
2854             throw new UnsupportedOperationException();
2855         }
2856 
2857         public Type resolve() {
2858             return name.map(ClassReader.this::sigToType);
2859         }
2860 
2861         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2862         public String toString() {
2863             return "<ProxyType>";
2864         }
2865 
2866     }
2867 
2868     private static final class InterimUsesDirective {
2869         public final Name service;
2870 
2871         public InterimUsesDirective(Name service) {
2872             this.service = service;
2873         }
2874 
2875     }
2876 
2877     private static final class InterimProvidesDirective {
2878         public final Name service;
2879         public final List<Name> impls;
2880 
2881         public InterimProvidesDirective(Name service, List<Name> impls) {
2882             this.service = service;
2883             this.impls = impls;
2884         }
2885 
2886     }
2887 
2888     private final class UsesProvidesCompleter implements Completer {
2889         private final ModuleSymbol currentModule;
2890         private final List<InterimUsesDirective> interimUsesCopy;
2891         private final List<InterimProvidesDirective> interimProvidesCopy;
2892 
2893         public UsesProvidesCompleter(ModuleSymbol currentModule, List<InterimUsesDirective> interimUsesCopy, List<InterimProvidesDirective> interimProvidesCopy) {
2894             this.currentModule = currentModule;
2895             this.interimUsesCopy = interimUsesCopy;
2896             this.interimProvidesCopy = interimProvidesCopy;
2897         }
2898 
2899         @Override
2900         public void complete(Symbol sym) throws CompletionFailure {
2901             ListBuffer<Directive> directives = new ListBuffer<>();
2902             directives.addAll(currentModule.directives);
2903             ListBuffer<UsesDirective> uses = new ListBuffer<>();
2904             for (InterimUsesDirective interim : interimUsesCopy) {
2905                 UsesDirective d = new UsesDirective(syms.enterClass(currentModule, interim.service));
2906                 uses.add(d);
2907                 directives.add(d);
2908             }
2909             currentModule.uses = uses.toList();
2910             ListBuffer<ProvidesDirective> provides = new ListBuffer<>();
2911             for (InterimProvidesDirective interim : interimProvidesCopy) {
2912                 ListBuffer<ClassSymbol> impls = new ListBuffer<>();
2913                 for (Name impl : interim.impls) {
2914                     impls.append(syms.enterClass(currentModule, impl));
2915                 }
2916                 ProvidesDirective d = new ProvidesDirective(syms.enterClass(currentModule, interim.service),
2917                                                             impls.toList());
2918                 provides.add(d);
2919                 directives.add(d);
2920             }
2921             currentModule.provides = provides.toList();
2922             currentModule.directives = directives.toList();
2923         }
2924     }
2925 }