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