src/share/classes/com/sun/tools/javac/jvm/ClassReader.java

Wed, 09 Oct 2013 13:09:31 +0200

author
jlahoda
date
Wed, 09 Oct 2013 13:09:31 +0200
changeset 2099
1b469fd31e35
parent 2047
5f915a0c9615
child 2133
19e8eebfbe52
permissions
-rw-r--r--

8025087: Annotation processing api returns default modifier for interface static method
Summary: ClassReader must not set Flags.DEFAULT for interface static methods
Reviewed-by: vromero, jjg

     1 /*
     2  * Copyright (c) 1999, 2013, 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  */
    26 package com.sun.tools.javac.jvm;
    28 import java.io.*;
    29 import java.net.URI;
    30 import java.net.URISyntaxException;
    31 import java.nio.CharBuffer;
    32 import java.util.Arrays;
    33 import java.util.EnumSet;
    34 import java.util.HashMap;
    35 import java.util.HashSet;
    36 import java.util.Map;
    37 import java.util.Set;
    38 import javax.lang.model.SourceVersion;
    39 import javax.tools.JavaFileObject;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileManager.Location;
    42 import javax.tools.StandardJavaFileManager;
    44 import static javax.tools.StandardLocation.*;
    46 import com.sun.tools.javac.comp.Annotate;
    47 import com.sun.tools.javac.code.*;
    48 import com.sun.tools.javac.code.Lint.LintCategory;
    49 import com.sun.tools.javac.code.Type.*;
    50 import com.sun.tools.javac.code.Symbol.*;
    51 import com.sun.tools.javac.code.Symtab;
    52 import com.sun.tools.javac.file.BaseFileObject;
    53 import com.sun.tools.javac.util.*;
    54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.TypeTag.CLASS;
    59 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    60 import static com.sun.tools.javac.jvm.ClassFile.*;
    61 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
    63 import static com.sun.tools.javac.main.Option.*;
    65 /** This class provides operations to read a classfile into an internal
    66  *  representation. The internal representation is anchored in a
    67  *  ClassSymbol which contains in its scope symbol representations
    68  *  for all other definitions in the classfile. Top-level Classes themselves
    69  *  appear as members of the scopes of PackageSymbols.
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class ClassReader {
    77     /** The context key for the class reader. */
    78     protected static final Context.Key<ClassReader> classReaderKey =
    79         new Context.Key<ClassReader>();
    81     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
    83     Annotate annotate;
    85     /** Switch: verbose output.
    86      */
    87     boolean verbose;
    89     /** Switch: check class file for correct minor version, unrecognized
    90      *  attributes.
    91      */
    92     boolean checkClassFile;
    94     /** Switch: read constant pool and code sections. This switch is initially
    95      *  set to false but can be turned on from outside.
    96      */
    97     public boolean readAllOfClassFile = false;
    99     /** Switch: read GJ signature information.
   100      */
   101     boolean allowGenerics;
   103     /** Switch: read varargs attribute.
   104      */
   105     boolean allowVarargs;
   107     /** Switch: allow annotations.
   108      */
   109     boolean allowAnnotations;
   111     /** Switch: allow simplified varargs.
   112      */
   113     boolean allowSimplifiedVarargs;
   115    /** Lint option: warn about classfile issues
   116      */
   117     boolean lintClassfile;
   119     /** Switch: allow default methods
   120      */
   121     boolean allowDefaultMethods;
   123     /** Switch: preserve parameter names from the variable table.
   124      */
   125     public boolean saveParameterNames;
   127     /**
   128      * Switch: cache completion failures unless -XDdev is used
   129      */
   130     private boolean cacheCompletionFailure;
   132     /**
   133      * Switch: prefer source files instead of newer when both source
   134      * and class are available
   135      **/
   136     public boolean preferSource;
   138     /**
   139      * The currently selected profile.
   140      */
   141     public final Profile profile;
   143     /** The log to use for verbose output
   144      */
   145     final Log log;
   147     /** The symbol table. */
   148     Symtab syms;
   150     Types types;
   152     /** The name table. */
   153     final Names names;
   155     /** Force a completion failure on this name
   156      */
   157     final Name completionFailureName;
   159     /** Access to files
   160      */
   161     private final JavaFileManager fileManager;
   163     /** Factory for diagnostics
   164      */
   165     JCDiagnostic.Factory diagFactory;
   167     /** Can be reassigned from outside:
   168      *  the completer to be used for ".java" files. If this remains unassigned
   169      *  ".java" files will not be loaded.
   170      */
   171     public SourceCompleter sourceCompleter = null;
   173     /** A hashtable containing the encountered top-level and member classes,
   174      *  indexed by flat names. The table does not contain local classes.
   175      */
   176     private Map<Name,ClassSymbol> classes;
   178     /** A hashtable containing the encountered packages.
   179      */
   180     private Map<Name, PackageSymbol> packages;
   182     /** The current scope where type variables are entered.
   183      */
   184     protected Scope typevars;
   186     /** The path name of the class file currently being read.
   187      */
   188     protected JavaFileObject currentClassFile = null;
   190     /** The class or method currently being read.
   191      */
   192     protected Symbol currentOwner = null;
   194     /** The buffer containing the currently read class file.
   195      */
   196     byte[] buf = new byte[INITIAL_BUFFER_SIZE];
   198     /** The current input pointer.
   199      */
   200     protected int bp;
   202     /** The objects of the constant pool.
   203      */
   204     Object[] poolObj;
   206     /** For every constant pool entry, an index into buf where the
   207      *  defining section of the entry is found.
   208      */
   209     int[] poolIdx;
   211     /** The major version number of the class file being read. */
   212     int majorVersion;
   213     /** The minor version number of the class file being read. */
   214     int minorVersion;
   216     /** A table to hold the constant pool indices for method parameter
   217      * names, as given in LocalVariableTable attributes.
   218      */
   219     int[] parameterNameIndices;
   221     /**
   222      * Whether or not any parameter names have been found.
   223      */
   224     boolean haveParameterNameIndices;
   226     /** Set this to false every time we start reading a method
   227      * and are saving parameter names.  Set it to true when we see
   228      * MethodParameters, if it's set when we see a LocalVariableTable,
   229      * then we ignore the parameter names from the LVT.
   230      */
   231     boolean sawMethodParameters;
   233     /**
   234      * The set of attribute names for which warnings have been generated for the current class
   235      */
   236     Set<Name> warnedAttrs = new HashSet<Name>();
   238     /**
   239      * Completer that delegates to the complete-method of this class.
   240      */
   241     private final Completer thisCompleter = new Completer() {
   242         @Override
   243         public void complete(Symbol sym) throws CompletionFailure {
   244             ClassReader.this.complete(sym);
   245         }
   246     };
   249     /** Get the ClassReader instance for this invocation. */
   250     public static ClassReader instance(Context context) {
   251         ClassReader instance = context.get(classReaderKey);
   252         if (instance == null)
   253             instance = new ClassReader(context, true);
   254         return instance;
   255     }
   257     /** Initialize classes and packages, treating this as the definitive classreader. */
   258     public void init(Symtab syms) {
   259         init(syms, true);
   260     }
   262     /** Initialize classes and packages, optionally treating this as
   263      *  the definitive classreader.
   264      */
   265     private void init(Symtab syms, boolean definitive) {
   266         if (classes != null) return;
   268         if (definitive) {
   269             Assert.check(packages == null || packages == syms.packages);
   270             packages = syms.packages;
   271             Assert.check(classes == null || classes == syms.classes);
   272             classes = syms.classes;
   273         } else {
   274             packages = new HashMap<Name, PackageSymbol>();
   275             classes = new HashMap<Name, ClassSymbol>();
   276         }
   278         packages.put(names.empty, syms.rootPackage);
   279         syms.rootPackage.completer = thisCompleter;
   280         syms.unnamedPackage.completer = thisCompleter;
   281     }
   283     /** Construct a new class reader, optionally treated as the
   284      *  definitive classreader for this invocation.
   285      */
   286     protected ClassReader(Context context, boolean definitive) {
   287         if (definitive) context.put(classReaderKey, this);
   289         names = Names.instance(context);
   290         syms = Symtab.instance(context);
   291         types = Types.instance(context);
   292         fileManager = context.get(JavaFileManager.class);
   293         if (fileManager == null)
   294             throw new AssertionError("FileManager initialization error");
   295         diagFactory = JCDiagnostic.Factory.instance(context);
   297         init(syms, definitive);
   298         log = Log.instance(context);
   300         Options options = Options.instance(context);
   301         annotate = Annotate.instance(context);
   302         verbose        = options.isSet(VERBOSE);
   303         checkClassFile = options.isSet("-checkclassfile");
   305         Source source = Source.instance(context);
   306         allowGenerics    = source.allowGenerics();
   307         allowVarargs     = source.allowVarargs();
   308         allowAnnotations = source.allowAnnotations();
   309         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   310         allowDefaultMethods = source.allowDefaultMethods();
   312         saveParameterNames = options.isSet("save-parameter-names");
   313         cacheCompletionFailure = options.isUnset("dev");
   314         preferSource = "source".equals(options.get("-Xprefer"));
   316         profile = Profile.instance(context);
   318         completionFailureName =
   319             options.isSet("failcomplete")
   320             ? names.fromString(options.get("failcomplete"))
   321             : null;
   323         typevars = new Scope(syms.noSymbol);
   325         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
   327         initAttributeReaders();
   328     }
   330     /** Add member to class unless it is synthetic.
   331      */
   332     private void enterMember(ClassSymbol c, Symbol sym) {
   333         // Synthetic members are not entered -- reason lost to history (optimization?).
   334         // Lambda methods must be entered because they may have inner classes (which reference them)
   335         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
   336             c.members_field.enter(sym);
   337     }
   339 /************************************************************************
   340  * Error Diagnoses
   341  ***********************************************************************/
   344     public class BadClassFile extends CompletionFailure {
   345         private static final long serialVersionUID = 0;
   347         public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
   348             super(sym, createBadClassFileDiagnostic(file, diag));
   349         }
   350     }
   351     // where
   352     private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
   353         String key = (file.getKind() == JavaFileObject.Kind.SOURCE
   354                     ? "bad.source.file.header" : "bad.class.file.header");
   355         return diagFactory.fragment(key, file, diag);
   356     }
   358     public BadClassFile badClassFile(String key, Object... args) {
   359         return new BadClassFile (
   360             currentOwner.enclClass(),
   361             currentClassFile,
   362             diagFactory.fragment(key, args));
   363     }
   365 /************************************************************************
   366  * Buffer Access
   367  ***********************************************************************/
   369     /** Read a character.
   370      */
   371     char nextChar() {
   372         return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
   373     }
   375     /** Read a byte.
   376      */
   377     int nextByte() {
   378         return buf[bp++] & 0xFF;
   379     }
   381     /** Read an integer.
   382      */
   383     int nextInt() {
   384         return
   385             ((buf[bp++] & 0xFF) << 24) +
   386             ((buf[bp++] & 0xFF) << 16) +
   387             ((buf[bp++] & 0xFF) << 8) +
   388             (buf[bp++] & 0xFF);
   389     }
   391     /** Extract a character at position bp from buf.
   392      */
   393     char getChar(int bp) {
   394         return
   395             (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
   396     }
   398     /** Extract an integer at position bp from buf.
   399      */
   400     int getInt(int bp) {
   401         return
   402             ((buf[bp] & 0xFF) << 24) +
   403             ((buf[bp+1] & 0xFF) << 16) +
   404             ((buf[bp+2] & 0xFF) << 8) +
   405             (buf[bp+3] & 0xFF);
   406     }
   409     /** Extract a long integer at position bp from buf.
   410      */
   411     long getLong(int bp) {
   412         DataInputStream bufin =
   413             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   414         try {
   415             return bufin.readLong();
   416         } catch (IOException e) {
   417             throw new AssertionError(e);
   418         }
   419     }
   421     /** Extract a float at position bp from buf.
   422      */
   423     float getFloat(int bp) {
   424         DataInputStream bufin =
   425             new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
   426         try {
   427             return bufin.readFloat();
   428         } catch (IOException e) {
   429             throw new AssertionError(e);
   430         }
   431     }
   433     /** Extract a double at position bp from buf.
   434      */
   435     double getDouble(int bp) {
   436         DataInputStream bufin =
   437             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   438         try {
   439             return bufin.readDouble();
   440         } catch (IOException e) {
   441             throw new AssertionError(e);
   442         }
   443     }
   445 /************************************************************************
   446  * Constant Pool Access
   447  ***********************************************************************/
   449     /** Index all constant pool entries, writing their start addresses into
   450      *  poolIdx.
   451      */
   452     void indexPool() {
   453         poolIdx = new int[nextChar()];
   454         poolObj = new Object[poolIdx.length];
   455         int i = 1;
   456         while (i < poolIdx.length) {
   457             poolIdx[i++] = bp;
   458             byte tag = buf[bp++];
   459             switch (tag) {
   460             case CONSTANT_Utf8: case CONSTANT_Unicode: {
   461                 int len = nextChar();
   462                 bp = bp + len;
   463                 break;
   464             }
   465             case CONSTANT_Class:
   466             case CONSTANT_String:
   467             case CONSTANT_MethodType:
   468                 bp = bp + 2;
   469                 break;
   470             case CONSTANT_MethodHandle:
   471                 bp = bp + 3;
   472                 break;
   473             case CONSTANT_Fieldref:
   474             case CONSTANT_Methodref:
   475             case CONSTANT_InterfaceMethodref:
   476             case CONSTANT_NameandType:
   477             case CONSTANT_Integer:
   478             case CONSTANT_Float:
   479             case CONSTANT_InvokeDynamic:
   480                 bp = bp + 4;
   481                 break;
   482             case CONSTANT_Long:
   483             case CONSTANT_Double:
   484                 bp = bp + 8;
   485                 i++;
   486                 break;
   487             default:
   488                 throw badClassFile("bad.const.pool.tag.at",
   489                                    Byte.toString(tag),
   490                                    Integer.toString(bp -1));
   491             }
   492         }
   493     }
   495     /** Read constant pool entry at start address i, use pool as a cache.
   496      */
   497     Object readPool(int i) {
   498         Object result = poolObj[i];
   499         if (result != null) return result;
   501         int index = poolIdx[i];
   502         if (index == 0) return null;
   504         byte tag = buf[index];
   505         switch (tag) {
   506         case CONSTANT_Utf8:
   507             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   508             break;
   509         case CONSTANT_Unicode:
   510             throw badClassFile("unicode.str.not.supported");
   511         case CONSTANT_Class:
   512             poolObj[i] = readClassOrType(getChar(index + 1));
   513             break;
   514         case CONSTANT_String:
   515             // FIXME: (footprint) do not use toString here
   516             poolObj[i] = readName(getChar(index + 1)).toString();
   517             break;
   518         case CONSTANT_Fieldref: {
   519             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   520             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   521             poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
   522             break;
   523         }
   524         case CONSTANT_Methodref:
   525         case CONSTANT_InterfaceMethodref: {
   526             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   527             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   528             poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
   529             break;
   530         }
   531         case CONSTANT_NameandType:
   532             poolObj[i] = new NameAndType(
   533                 readName(getChar(index + 1)),
   534                 readType(getChar(index + 3)), types);
   535             break;
   536         case CONSTANT_Integer:
   537             poolObj[i] = getInt(index + 1);
   538             break;
   539         case CONSTANT_Float:
   540             poolObj[i] = new Float(getFloat(index + 1));
   541             break;
   542         case CONSTANT_Long:
   543             poolObj[i] = new Long(getLong(index + 1));
   544             break;
   545         case CONSTANT_Double:
   546             poolObj[i] = new Double(getDouble(index + 1));
   547             break;
   548         case CONSTANT_MethodHandle:
   549             skipBytes(4);
   550             break;
   551         case CONSTANT_MethodType:
   552             skipBytes(3);
   553             break;
   554         case CONSTANT_InvokeDynamic:
   555             skipBytes(5);
   556             break;
   557         default:
   558             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   559         }
   560         return poolObj[i];
   561     }
   563     /** Read signature and convert to type.
   564      */
   565     Type readType(int i) {
   566         int index = poolIdx[i];
   567         return sigToType(buf, index + 3, getChar(index + 1));
   568     }
   570     /** If name is an array type or class signature, return the
   571      *  corresponding type; otherwise return a ClassSymbol with given name.
   572      */
   573     Object readClassOrType(int i) {
   574         int index =  poolIdx[i];
   575         int len = getChar(index + 1);
   576         int start = index + 3;
   577         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   578         // by the above assertion, the following test can be
   579         // simplified to (buf[start] == '[')
   580         return (buf[start] == '[' || buf[start + len - 1] == ';')
   581             ? (Object)sigToType(buf, start, len)
   582             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   583                                                            len)));
   584     }
   586     /** Read signature and convert to type parameters.
   587      */
   588     List<Type> readTypeParams(int i) {
   589         int index = poolIdx[i];
   590         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   591     }
   593     /** Read class entry.
   594      */
   595     ClassSymbol readClassSymbol(int i) {
   596         return (ClassSymbol) (readPool(i));
   597     }
   599     /** Read name.
   600      */
   601     Name readName(int i) {
   602         return (Name) (readPool(i));
   603     }
   605 /************************************************************************
   606  * Reading Types
   607  ***********************************************************************/
   609     /** The unread portion of the currently read type is
   610      *  signature[sigp..siglimit-1].
   611      */
   612     byte[] signature;
   613     int sigp;
   614     int siglimit;
   615     boolean sigEnterPhase = false;
   617     /** Convert signature to type, where signature is a byte array segment.
   618      */
   619     Type sigToType(byte[] sig, int offset, int len) {
   620         signature = sig;
   621         sigp = offset;
   622         siglimit = offset + len;
   623         return sigToType();
   624     }
   626     /** Convert signature to type, where signature is implicit.
   627      */
   628     Type sigToType() {
   629         switch ((char) signature[sigp]) {
   630         case 'T':
   631             sigp++;
   632             int start = sigp;
   633             while (signature[sigp] != ';') sigp++;
   634             sigp++;
   635             return sigEnterPhase
   636                 ? Type.noType
   637                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   638         case '+': {
   639             sigp++;
   640             Type t = sigToType();
   641             return new WildcardType(t, BoundKind.EXTENDS,
   642                                     syms.boundClass);
   643         }
   644         case '*':
   645             sigp++;
   646             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   647                                     syms.boundClass);
   648         case '-': {
   649             sigp++;
   650             Type t = sigToType();
   651             return new WildcardType(t, BoundKind.SUPER,
   652                                     syms.boundClass);
   653         }
   654         case 'B':
   655             sigp++;
   656             return syms.byteType;
   657         case 'C':
   658             sigp++;
   659             return syms.charType;
   660         case 'D':
   661             sigp++;
   662             return syms.doubleType;
   663         case 'F':
   664             sigp++;
   665             return syms.floatType;
   666         case 'I':
   667             sigp++;
   668             return syms.intType;
   669         case 'J':
   670             sigp++;
   671             return syms.longType;
   672         case 'L':
   673             {
   674                 // int oldsigp = sigp;
   675                 Type t = classSigToType();
   676                 if (sigp < siglimit && signature[sigp] == '.')
   677                     throw badClassFile("deprecated inner class signature syntax " +
   678                                        "(please recompile from source)");
   679                 /*
   680                 System.err.println(" decoded " +
   681                                    new String(signature, oldsigp, sigp-oldsigp) +
   682                                    " => " + t + " outer " + t.outer());
   683                 */
   684                 return t;
   685             }
   686         case 'S':
   687             sigp++;
   688             return syms.shortType;
   689         case 'V':
   690             sigp++;
   691             return syms.voidType;
   692         case 'Z':
   693             sigp++;
   694             return syms.booleanType;
   695         case '[':
   696             sigp++;
   697             return new ArrayType(sigToType(), syms.arrayClass);
   698         case '(':
   699             sigp++;
   700             List<Type> argtypes = sigToTypes(')');
   701             Type restype = sigToType();
   702             List<Type> thrown = List.nil();
   703             while (signature[sigp] == '^') {
   704                 sigp++;
   705                 thrown = thrown.prepend(sigToType());
   706             }
   707             // if there is a typevar in the throws clause we should state it.
   708             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
   709                 if (l.head.hasTag(TYPEVAR)) {
   710                     l.head.tsym.flags_field |= THROWS;
   711                 }
   712             }
   713             return new MethodType(argtypes,
   714                                   restype,
   715                                   thrown.reverse(),
   716                                   syms.methodClass);
   717         case '<':
   718             typevars = typevars.dup(currentOwner);
   719             Type poly = new ForAll(sigToTypeParams(), sigToType());
   720             typevars = typevars.leave();
   721             return poly;
   722         default:
   723             throw badClassFile("bad.signature",
   724                                Convert.utf2string(signature, sigp, 10));
   725         }
   726     }
   728     byte[] signatureBuffer = new byte[0];
   729     int sbp = 0;
   730     /** Convert class signature to type, where signature is implicit.
   731      */
   732     Type classSigToType() {
   733         if (signature[sigp] != 'L')
   734             throw badClassFile("bad.class.signature",
   735                                Convert.utf2string(signature, sigp, 10));
   736         sigp++;
   737         Type outer = Type.noType;
   738         int startSbp = sbp;
   740         while (true) {
   741             final byte c = signature[sigp++];
   742             switch (c) {
   744             case ';': {         // end
   745                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   746                                                          startSbp,
   747                                                          sbp - startSbp));
   749                 try {
   750                     return (outer == Type.noType) ?
   751                             t.erasure(types) :
   752                             new ClassType(outer, List.<Type>nil(), t);
   753                 } finally {
   754                     sbp = startSbp;
   755                 }
   756             }
   758             case '<':           // generic arguments
   759                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   760                                                          startSbp,
   761                                                          sbp - startSbp));
   762                 outer = new ClassType(outer, sigToTypes('>'), t) {
   763                         boolean completed = false;
   764                         @Override
   765                         public Type getEnclosingType() {
   766                             if (!completed) {
   767                                 completed = true;
   768                                 tsym.complete();
   769                                 Type enclosingType = tsym.type.getEnclosingType();
   770                                 if (enclosingType != Type.noType) {
   771                                     List<Type> typeArgs =
   772                                         super.getEnclosingType().allparams();
   773                                     List<Type> typeParams =
   774                                         enclosingType.allparams();
   775                                     if (typeParams.length() != typeArgs.length()) {
   776                                         // no "rare" types
   777                                         super.setEnclosingType(types.erasure(enclosingType));
   778                                     } else {
   779                                         super.setEnclosingType(types.subst(enclosingType,
   780                                                                            typeParams,
   781                                                                            typeArgs));
   782                                     }
   783                                 } else {
   784                                     super.setEnclosingType(Type.noType);
   785                                 }
   786                             }
   787                             return super.getEnclosingType();
   788                         }
   789                         @Override
   790                         public void setEnclosingType(Type outer) {
   791                             throw new UnsupportedOperationException();
   792                         }
   793                     };
   794                 switch (signature[sigp++]) {
   795                 case ';':
   796                     if (sigp < signature.length && signature[sigp] == '.') {
   797                         // support old-style GJC signatures
   798                         // The signature produced was
   799                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   800                         // rather than say
   801                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   802                         // so we skip past ".Lfoo/Outer$"
   803                         sigp += (sbp - startSbp) + // "foo/Outer"
   804                             3;  // ".L" and "$"
   805                         signatureBuffer[sbp++] = (byte)'$';
   806                         break;
   807                     } else {
   808                         sbp = startSbp;
   809                         return outer;
   810                     }
   811                 case '.':
   812                     signatureBuffer[sbp++] = (byte)'$';
   813                     break;
   814                 default:
   815                     throw new AssertionError(signature[sigp-1]);
   816                 }
   817                 continue;
   819             case '.':
   820                 //we have seen an enclosing non-generic class
   821                 if (outer != Type.noType) {
   822                     t = enterClass(names.fromUtf(signatureBuffer,
   823                                                  startSbp,
   824                                                  sbp - startSbp));
   825                     outer = new ClassType(outer, List.<Type>nil(), t);
   826                 }
   827                 signatureBuffer[sbp++] = (byte)'$';
   828                 continue;
   829             case '/':
   830                 signatureBuffer[sbp++] = (byte)'.';
   831                 continue;
   832             default:
   833                 signatureBuffer[sbp++] = c;
   834                 continue;
   835             }
   836         }
   837     }
   839     /** Convert (implicit) signature to list of types
   840      *  until `terminator' is encountered.
   841      */
   842     List<Type> sigToTypes(char terminator) {
   843         List<Type> head = List.of(null);
   844         List<Type> tail = head;
   845         while (signature[sigp] != terminator)
   846             tail = tail.setTail(List.of(sigToType()));
   847         sigp++;
   848         return head.tail;
   849     }
   851     /** Convert signature to type parameters, where signature is a byte
   852      *  array segment.
   853      */
   854     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   855         signature = sig;
   856         sigp = offset;
   857         siglimit = offset + len;
   858         return sigToTypeParams();
   859     }
   861     /** Convert signature to type parameters, where signature is implicit.
   862      */
   863     List<Type> sigToTypeParams() {
   864         List<Type> tvars = List.nil();
   865         if (signature[sigp] == '<') {
   866             sigp++;
   867             int start = sigp;
   868             sigEnterPhase = true;
   869             while (signature[sigp] != '>')
   870                 tvars = tvars.prepend(sigToTypeParam());
   871             sigEnterPhase = false;
   872             sigp = start;
   873             while (signature[sigp] != '>')
   874                 sigToTypeParam();
   875             sigp++;
   876         }
   877         return tvars.reverse();
   878     }
   880     /** Convert (implicit) signature to type parameter.
   881      */
   882     Type sigToTypeParam() {
   883         int start = sigp;
   884         while (signature[sigp] != ':') sigp++;
   885         Name name = names.fromUtf(signature, start, sigp - start);
   886         TypeVar tvar;
   887         if (sigEnterPhase) {
   888             tvar = new TypeVar(name, currentOwner, syms.botType);
   889             typevars.enter(tvar.tsym);
   890         } else {
   891             tvar = (TypeVar)findTypeVar(name);
   892         }
   893         List<Type> bounds = List.nil();
   894         boolean allInterfaces = false;
   895         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   896             sigp++;
   897             allInterfaces = true;
   898         }
   899         while (signature[sigp] == ':') {
   900             sigp++;
   901             bounds = bounds.prepend(sigToType());
   902         }
   903         if (!sigEnterPhase) {
   904             types.setBounds(tvar, bounds.reverse(), allInterfaces);
   905         }
   906         return tvar;
   907     }
   909     /** Find type variable with given name in `typevars' scope.
   910      */
   911     Type findTypeVar(Name name) {
   912         Scope.Entry e = typevars.lookup(name);
   913         if (e.scope != null) {
   914             return e.sym.type;
   915         } else {
   916             if (readingClassAttr) {
   917                 // While reading the class attribute, the supertypes
   918                 // might refer to a type variable from an enclosing element
   919                 // (method or class).
   920                 // If the type variable is defined in the enclosing class,
   921                 // we can actually find it in
   922                 // currentOwner.owner.type.getTypeArguments()
   923                 // However, until we have read the enclosing method attribute
   924                 // we don't know for sure if this owner is correct.  It could
   925                 // be a method and there is no way to tell before reading the
   926                 // enclosing method attribute.
   927                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   928                 missingTypeVariables = missingTypeVariables.prepend(t);
   929                 // System.err.println("Missing type var " + name);
   930                 return t;
   931             }
   932             throw badClassFile("undecl.type.var", name);
   933         }
   934     }
   936 /************************************************************************
   937  * Reading Attributes
   938  ***********************************************************************/
   940     protected enum AttributeKind { CLASS, MEMBER };
   941     protected abstract class AttributeReader {
   942         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   943             this.name = name;
   944             this.version = version;
   945             this.kinds = kinds;
   946         }
   948         protected boolean accepts(AttributeKind kind) {
   949             if (kinds.contains(kind)) {
   950                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   951                     return true;
   953                 if (lintClassfile && !warnedAttrs.contains(name)) {
   954                     JavaFileObject prev = log.useSource(currentClassFile);
   955                     try {
   956                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   957                                 name, version.major, version.minor, majorVersion, minorVersion);
   958                     } finally {
   959                         log.useSource(prev);
   960                     }
   961                     warnedAttrs.add(name);
   962                 }
   963             }
   964             return false;
   965         }
   967         protected abstract void read(Symbol sym, int attrLen);
   969         protected final Name name;
   970         protected final ClassFile.Version version;
   971         protected final Set<AttributeKind> kinds;
   972     }
   974     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   975             EnumSet.of(AttributeKind.CLASS);
   976     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   977             EnumSet.of(AttributeKind.MEMBER);
   978     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   979             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   981     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   983     private void initAttributeReaders() {
   984         AttributeReader[] readers = {
   985             // v45.3 attributes
   987             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   988                 protected void read(Symbol sym, int attrLen) {
   989                     if (readAllOfClassFile || saveParameterNames)
   990                         ((MethodSymbol)sym).code = readCode(sym);
   991                     else
   992                         bp = bp + attrLen;
   993                 }
   994             },
   996             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   997                 protected void read(Symbol sym, int attrLen) {
   998                     Object v = readPool(nextChar());
   999                     // Ignore ConstantValue attribute if field not final.
  1000                     if ((sym.flags() & FINAL) != 0)
  1001                         ((VarSymbol) sym).setData(v);
  1003             },
  1005             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1006                 protected void read(Symbol sym, int attrLen) {
  1007                     sym.flags_field |= DEPRECATED;
  1009             },
  1011             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1012                 protected void read(Symbol sym, int attrLen) {
  1013                     int nexceptions = nextChar();
  1014                     List<Type> thrown = List.nil();
  1015                     for (int j = 0; j < nexceptions; j++)
  1016                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
  1017                     if (sym.type.getThrownTypes().isEmpty())
  1018                         sym.type.asMethodType().thrown = thrown.reverse();
  1020             },
  1022             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
  1023                 protected void read(Symbol sym, int attrLen) {
  1024                     ClassSymbol c = (ClassSymbol) sym;
  1025                     readInnerClasses(c);
  1027             },
  1029             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1030                 protected void read(Symbol sym, int attrLen) {
  1031                     int newbp = bp + attrLen;
  1032                     if (saveParameterNames && !sawMethodParameters) {
  1033                         // Pick up parameter names from the variable table.
  1034                         // Parameter names are not explicitly identified as such,
  1035                         // but all parameter name entries in the LocalVariableTable
  1036                         // have a start_pc of 0.  Therefore, we record the name
  1037                         // indicies of all slots with a start_pc of zero in the
  1038                         // parameterNameIndicies array.
  1039                         // Note that this implicitly honors the JVMS spec that
  1040                         // there may be more than one LocalVariableTable, and that
  1041                         // there is no specified ordering for the entries.
  1042                         int numEntries = nextChar();
  1043                         for (int i = 0; i < numEntries; i++) {
  1044                             int start_pc = nextChar();
  1045                             int length = nextChar();
  1046                             int nameIndex = nextChar();
  1047                             int sigIndex = nextChar();
  1048                             int register = nextChar();
  1049                             if (start_pc == 0) {
  1050                                 // ensure array large enough
  1051                                 if (register >= parameterNameIndices.length) {
  1052                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1053                                     parameterNameIndices =
  1054                                             Arrays.copyOf(parameterNameIndices, newSize);
  1056                                 parameterNameIndices[register] = nameIndex;
  1057                                 haveParameterNameIndices = true;
  1061                     bp = newbp;
  1063             },
  1065             new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
  1066                 protected void read(Symbol sym, int attrlen) {
  1067                     int newbp = bp + attrlen;
  1068                     if (saveParameterNames) {
  1069                         sawMethodParameters = true;
  1070                         int numEntries = nextByte();
  1071                         parameterNameIndices = new int[numEntries];
  1072                         haveParameterNameIndices = true;
  1073                         for (int i = 0; i < numEntries; i++) {
  1074                             int nameIndex = nextChar();
  1075                             int flags = nextChar();
  1076                             parameterNameIndices[i] = nameIndex;
  1079                     bp = newbp;
  1081             },
  1084             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1085                 protected void read(Symbol sym, int attrLen) {
  1086                     ClassSymbol c = (ClassSymbol) sym;
  1087                     Name n = readName(nextChar());
  1088                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1089                     // If the class is a toplevel class, originating from a Java source file,
  1090                     // but the class name does not match the file name, then it is
  1091                     // an auxiliary class.
  1092                     String sn = n.toString();
  1093                     if (c.owner.kind == Kinds.PCK &&
  1094                         sn.endsWith(".java") &&
  1095                         !sn.equals(c.name.toString()+".java")) {
  1096                         c.flags_field |= AUXILIARY;
  1099             },
  1101             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1102                 protected void read(Symbol sym, int attrLen) {
  1103                     // bridge methods are visible when generics not enabled
  1104                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1105                         sym.flags_field |= SYNTHETIC;
  1107             },
  1109             // standard v49 attributes
  1111             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1112                 protected void read(Symbol sym, int attrLen) {
  1113                     int newbp = bp + attrLen;
  1114                     readEnclosingMethodAttr(sym);
  1115                     bp = newbp;
  1117             },
  1119             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1120                 @Override
  1121                 protected boolean accepts(AttributeKind kind) {
  1122                     return super.accepts(kind) && allowGenerics;
  1125                 protected void read(Symbol sym, int attrLen) {
  1126                     if (sym.kind == TYP) {
  1127                         ClassSymbol c = (ClassSymbol) sym;
  1128                         readingClassAttr = true;
  1129                         try {
  1130                             ClassType ct1 = (ClassType)c.type;
  1131                             Assert.check(c == currentOwner);
  1132                             ct1.typarams_field = readTypeParams(nextChar());
  1133                             ct1.supertype_field = sigToType();
  1134                             ListBuffer<Type> is = new ListBuffer<Type>();
  1135                             while (sigp != siglimit) is.append(sigToType());
  1136                             ct1.interfaces_field = is.toList();
  1137                         } finally {
  1138                             readingClassAttr = false;
  1140                     } else {
  1141                         List<Type> thrown = sym.type.getThrownTypes();
  1142                         sym.type = readType(nextChar());
  1143                         //- System.err.println(" # " + sym.type);
  1144                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1145                             sym.type.asMethodType().thrown = thrown;
  1149             },
  1151             // v49 annotation attributes
  1153             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1154                 protected void read(Symbol sym, int attrLen) {
  1155                     attachAnnotationDefault(sym);
  1157             },
  1159             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1160                 protected void read(Symbol sym, int attrLen) {
  1161                     attachAnnotations(sym);
  1163             },
  1165             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1166                 protected void read(Symbol sym, int attrLen) {
  1167                     attachParameterAnnotations(sym);
  1169             },
  1171             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1172                 protected void read(Symbol sym, int attrLen) {
  1173                     attachAnnotations(sym);
  1175             },
  1177             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1178                 protected void read(Symbol sym, int attrLen) {
  1179                     attachParameterAnnotations(sym);
  1181             },
  1183             // additional "legacy" v49 attributes, superceded by flags
  1185             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1186                 protected void read(Symbol sym, int attrLen) {
  1187                     if (allowAnnotations)
  1188                         sym.flags_field |= ANNOTATION;
  1190             },
  1192             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1193                 protected void read(Symbol sym, int attrLen) {
  1194                     sym.flags_field |= BRIDGE;
  1195                     if (!allowGenerics)
  1196                         sym.flags_field &= ~SYNTHETIC;
  1198             },
  1200             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1201                 protected void read(Symbol sym, int attrLen) {
  1202                     sym.flags_field |= ENUM;
  1204             },
  1206             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1207                 protected void read(Symbol sym, int attrLen) {
  1208                     if (allowVarargs)
  1209                         sym.flags_field |= VARARGS;
  1211             },
  1213             new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1214                 protected void read(Symbol sym, int attrLen) {
  1215                     attachTypeAnnotations(sym);
  1217             },
  1219             new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1220                 protected void read(Symbol sym, int attrLen) {
  1221                     attachTypeAnnotations(sym);
  1223             },
  1226             // The following attributes for a Code attribute are not currently handled
  1227             // StackMapTable
  1228             // SourceDebugExtension
  1229             // LineNumberTable
  1230             // LocalVariableTypeTable
  1231         };
  1233         for (AttributeReader r: readers)
  1234             attributeReaders.put(r.name, r);
  1237     /** Report unrecognized attribute.
  1238      */
  1239     void unrecognized(Name attrName) {
  1240         if (checkClassFile)
  1241             printCCF("ccf.unrecognized.attribute", attrName);
  1246     protected void readEnclosingMethodAttr(Symbol sym) {
  1247         // sym is a nested class with an "Enclosing Method" attribute
  1248         // remove sym from it's current owners scope and place it in
  1249         // the scope specified by the attribute
  1250         sym.owner.members().remove(sym);
  1251         ClassSymbol self = (ClassSymbol)sym;
  1252         ClassSymbol c = readClassSymbol(nextChar());
  1253         NameAndType nt = (NameAndType)readPool(nextChar());
  1255         if (c.members_field == null)
  1256             throw badClassFile("bad.enclosing.class", self, c);
  1258         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1259         if (nt != null && m == null)
  1260             throw badClassFile("bad.enclosing.method", self);
  1262         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1263         self.owner = m != null ? m : c;
  1264         if (self.name.isEmpty())
  1265             self.fullname = names.empty;
  1266         else
  1267             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1269         if (m != null) {
  1270             ((ClassType)sym.type).setEnclosingType(m.type);
  1271         } else if ((self.flags_field & STATIC) == 0) {
  1272             ((ClassType)sym.type).setEnclosingType(c.type);
  1273         } else {
  1274             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1276         enterTypevars(self);
  1277         if (!missingTypeVariables.isEmpty()) {
  1278             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1279             for (Type typevar : missingTypeVariables) {
  1280                 typeVars.append(findTypeVar(typevar.tsym.name));
  1282             foundTypeVariables = typeVars.toList();
  1283         } else {
  1284             foundTypeVariables = List.nil();
  1288     // See java.lang.Class
  1289     private Name simpleBinaryName(Name self, Name enclosing) {
  1290         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1291         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1292             throw badClassFile("bad.enclosing.method", self);
  1293         int index = 1;
  1294         while (index < simpleBinaryName.length() &&
  1295                isAsciiDigit(simpleBinaryName.charAt(index)))
  1296             index++;
  1297         return names.fromString(simpleBinaryName.substring(index));
  1300     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1301         if (nt == null)
  1302             return null;
  1304         MethodType type = nt.uniqueType.type.asMethodType();
  1306         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1307             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1308                 return (MethodSymbol)e.sym;
  1310         if (nt.name != names.init)
  1311             // not a constructor
  1312             return null;
  1313         if ((flags & INTERFACE) != 0)
  1314             // no enclosing instance
  1315             return null;
  1316         if (nt.uniqueType.type.getParameterTypes().isEmpty())
  1317             // no parameters
  1318             return null;
  1320         // A constructor of an inner class.
  1321         // Remove the first argument (the enclosing instance)
  1322         nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
  1323                                  nt.uniqueType.type.getReturnType(),
  1324                                  nt.uniqueType.type.getThrownTypes(),
  1325                                  syms.methodClass));
  1326         // Try searching again
  1327         return findMethod(nt, scope, flags);
  1330     /** Similar to Types.isSameType but avoids completion */
  1331     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1332         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1333             .prepend(types.erasure(mt1.getReturnType()));
  1334         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1335         while (!types1.isEmpty() && !types2.isEmpty()) {
  1336             if (types1.head.tsym != types2.head.tsym)
  1337                 return false;
  1338             types1 = types1.tail;
  1339             types2 = types2.tail;
  1341         return types1.isEmpty() && types2.isEmpty();
  1344     /**
  1345      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1346      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1347      */
  1348     private static boolean isAsciiDigit(char c) {
  1349         return '0' <= c && c <= '9';
  1352     /** Read member attributes.
  1353      */
  1354     void readMemberAttrs(Symbol sym) {
  1355         readAttrs(sym, AttributeKind.MEMBER);
  1358     void readAttrs(Symbol sym, AttributeKind kind) {
  1359         char ac = nextChar();
  1360         for (int i = 0; i < ac; i++) {
  1361             Name attrName = readName(nextChar());
  1362             int attrLen = nextInt();
  1363             AttributeReader r = attributeReaders.get(attrName);
  1364             if (r != null && r.accepts(kind))
  1365                 r.read(sym, attrLen);
  1366             else  {
  1367                 unrecognized(attrName);
  1368                 bp = bp + attrLen;
  1373     private boolean readingClassAttr = false;
  1374     private List<Type> missingTypeVariables = List.nil();
  1375     private List<Type> foundTypeVariables = List.nil();
  1377     /** Read class attributes.
  1378      */
  1379     void readClassAttrs(ClassSymbol c) {
  1380         readAttrs(c, AttributeKind.CLASS);
  1383     /** Read code block.
  1384      */
  1385     Code readCode(Symbol owner) {
  1386         nextChar(); // max_stack
  1387         nextChar(); // max_locals
  1388         final int  code_length = nextInt();
  1389         bp += code_length;
  1390         final char exception_table_length = nextChar();
  1391         bp += exception_table_length * 8;
  1392         readMemberAttrs(owner);
  1393         return null;
  1396 /************************************************************************
  1397  * Reading Java-language annotations
  1398  ***********************************************************************/
  1400     /** Attach annotations.
  1401      */
  1402     void attachAnnotations(final Symbol sym) {
  1403         int numAttributes = nextChar();
  1404         if (numAttributes != 0) {
  1405             ListBuffer<CompoundAnnotationProxy> proxies =
  1406                 new ListBuffer<CompoundAnnotationProxy>();
  1407             for (int i = 0; i<numAttributes; i++) {
  1408                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1409                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1410                     sym.flags_field |= PROPRIETARY;
  1411                 else if (proxy.type.tsym == syms.profileType.tsym) {
  1412                     if (profile != Profile.DEFAULT) {
  1413                         for (Pair<Name,Attribute> v: proxy.values) {
  1414                             if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
  1415                                 Attribute.Constant c = (Attribute.Constant) v.snd;
  1416                                 if (c.type == syms.intType && ((Integer) c.value) > profile.value) {
  1417                                     sym.flags_field |= NOT_IN_PROFILE;
  1422                 } else
  1423                     proxies.append(proxy);
  1425             annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
  1429     /** Attach parameter annotations.
  1430      */
  1431     void attachParameterAnnotations(final Symbol method) {
  1432         final MethodSymbol meth = (MethodSymbol)method;
  1433         int numParameters = buf[bp++] & 0xFF;
  1434         List<VarSymbol> parameters = meth.params();
  1435         int pnum = 0;
  1436         while (parameters.tail != null) {
  1437             attachAnnotations(parameters.head);
  1438             parameters = parameters.tail;
  1439             pnum++;
  1441         if (pnum != numParameters) {
  1442             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1446     void attachTypeAnnotations(final Symbol sym) {
  1447         int numAttributes = nextChar();
  1448         if (numAttributes != 0) {
  1449             ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>();
  1450             for (int i = 0; i < numAttributes; i++)
  1451                 proxies.append(readTypeAnnotation());
  1452             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
  1456     /** Attach the default value for an annotation element.
  1457      */
  1458     void attachAnnotationDefault(final Symbol sym) {
  1459         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1460         final Attribute value = readAttributeValue();
  1462         // The default value is set later during annotation. It might
  1463         // be the case that the Symbol sym is annotated _after_ the
  1464         // repeating instances that depend on this default value,
  1465         // because of this we set an interim value that tells us this
  1466         // element (most likely) has a default.
  1467         //
  1468         // Set interim value for now, reset just before we do this
  1469         // properly at annotate time.
  1470         meth.defaultValue = value;
  1471         annotate.normal(new AnnotationDefaultCompleter(meth, value));
  1474     Type readTypeOrClassSymbol(int i) {
  1475         // support preliminary jsr175-format class files
  1476         if (buf[poolIdx[i]] == CONSTANT_Class)
  1477             return readClassSymbol(i).type;
  1478         return readType(i);
  1480     Type readEnumType(int i) {
  1481         // support preliminary jsr175-format class files
  1482         int index = poolIdx[i];
  1483         int length = getChar(index + 1);
  1484         if (buf[index + length + 2] != ';')
  1485             return enterClass(readName(i)).type;
  1486         return readType(i);
  1489     CompoundAnnotationProxy readCompoundAnnotation() {
  1490         Type t = readTypeOrClassSymbol(nextChar());
  1491         int numFields = nextChar();
  1492         ListBuffer<Pair<Name,Attribute>> pairs =
  1493             new ListBuffer<Pair<Name,Attribute>>();
  1494         for (int i=0; i<numFields; i++) {
  1495             Name name = readName(nextChar());
  1496             Attribute value = readAttributeValue();
  1497             pairs.append(new Pair<Name,Attribute>(name, value));
  1499         return new CompoundAnnotationProxy(t, pairs.toList());
  1502     TypeAnnotationProxy readTypeAnnotation() {
  1503         TypeAnnotationPosition position = readPosition();
  1504         CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1506         return new TypeAnnotationProxy(proxy, position);
  1509     TypeAnnotationPosition readPosition() {
  1510         int tag = nextByte(); // TargetType tag is a byte
  1512         if (!TargetType.isValidTargetTypeValue(tag))
  1513             throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
  1515         TypeAnnotationPosition position = new TypeAnnotationPosition();
  1516         TargetType type = TargetType.fromTargetTypeValue(tag);
  1518         position.type = type;
  1520         switch (type) {
  1521         // instanceof
  1522         case INSTANCEOF:
  1523         // new expression
  1524         case NEW:
  1525         // constructor/method reference receiver
  1526         case CONSTRUCTOR_REFERENCE:
  1527         case METHOD_REFERENCE:
  1528             position.offset = nextChar();
  1529             break;
  1530         // local variable
  1531         case LOCAL_VARIABLE:
  1532         // resource variable
  1533         case RESOURCE_VARIABLE:
  1534             int table_length = nextChar();
  1535             position.lvarOffset = new int[table_length];
  1536             position.lvarLength = new int[table_length];
  1537             position.lvarIndex = new int[table_length];
  1539             for (int i = 0; i < table_length; ++i) {
  1540                 position.lvarOffset[i] = nextChar();
  1541                 position.lvarLength[i] = nextChar();
  1542                 position.lvarIndex[i] = nextChar();
  1544             break;
  1545         // exception parameter
  1546         case EXCEPTION_PARAMETER:
  1547             position.exception_index = nextChar();
  1548             break;
  1549         // method receiver
  1550         case METHOD_RECEIVER:
  1551             // Do nothing
  1552             break;
  1553         // type parameter
  1554         case CLASS_TYPE_PARAMETER:
  1555         case METHOD_TYPE_PARAMETER:
  1556             position.parameter_index = nextByte();
  1557             break;
  1558         // type parameter bound
  1559         case CLASS_TYPE_PARAMETER_BOUND:
  1560         case METHOD_TYPE_PARAMETER_BOUND:
  1561             position.parameter_index = nextByte();
  1562             position.bound_index = nextByte();
  1563             break;
  1564         // class extends or implements clause
  1565         case CLASS_EXTENDS:
  1566             position.type_index = nextChar();
  1567             break;
  1568         // throws
  1569         case THROWS:
  1570             position.type_index = nextChar();
  1571             break;
  1572         // method parameter
  1573         case METHOD_FORMAL_PARAMETER:
  1574             position.parameter_index = nextByte();
  1575             break;
  1576         // type cast
  1577         case CAST:
  1578         // method/constructor/reference type argument
  1579         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
  1580         case METHOD_INVOCATION_TYPE_ARGUMENT:
  1581         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
  1582         case METHOD_REFERENCE_TYPE_ARGUMENT:
  1583             position.offset = nextChar();
  1584             position.type_index = nextByte();
  1585             break;
  1586         // We don't need to worry about these
  1587         case METHOD_RETURN:
  1588         case FIELD:
  1589             break;
  1590         case UNKNOWN:
  1591             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
  1592         default:
  1593             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
  1596         { // See whether there is location info and read it
  1597             int len = nextByte();
  1598             ListBuffer<Integer> loc = new ListBuffer<>();
  1599             for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
  1600                 loc = loc.append(nextByte());
  1601             position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
  1604         return position;
  1607     Attribute readAttributeValue() {
  1608         char c = (char) buf[bp++];
  1609         switch (c) {
  1610         case 'B':
  1611             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1612         case 'C':
  1613             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1614         case 'D':
  1615             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1616         case 'F':
  1617             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1618         case 'I':
  1619             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1620         case 'J':
  1621             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1622         case 'S':
  1623             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1624         case 'Z':
  1625             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1626         case 's':
  1627             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1628         case 'e':
  1629             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1630         case 'c':
  1631             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1632         case '[': {
  1633             int n = nextChar();
  1634             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1635             for (int i=0; i<n; i++)
  1636                 l.append(readAttributeValue());
  1637             return new ArrayAttributeProxy(l.toList());
  1639         case '@':
  1640             return readCompoundAnnotation();
  1641         default:
  1642             throw new AssertionError("unknown annotation tag '" + c + "'");
  1646     interface ProxyVisitor extends Attribute.Visitor {
  1647         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1648         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1649         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1652     static class EnumAttributeProxy extends Attribute {
  1653         Type enumType;
  1654         Name enumerator;
  1655         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1656             super(null);
  1657             this.enumType = enumType;
  1658             this.enumerator = enumerator;
  1660         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1661         @Override
  1662         public String toString() {
  1663             return "/*proxy enum*/" + enumType + "." + enumerator;
  1667     static class ArrayAttributeProxy extends Attribute {
  1668         List<Attribute> values;
  1669         ArrayAttributeProxy(List<Attribute> values) {
  1670             super(null);
  1671             this.values = values;
  1673         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1674         @Override
  1675         public String toString() {
  1676             return "{" + values + "}";
  1680     /** A temporary proxy representing a compound attribute.
  1681      */
  1682     static class CompoundAnnotationProxy extends Attribute {
  1683         final List<Pair<Name,Attribute>> values;
  1684         public CompoundAnnotationProxy(Type type,
  1685                                       List<Pair<Name,Attribute>> values) {
  1686             super(type);
  1687             this.values = values;
  1689         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1690         @Override
  1691         public String toString() {
  1692             StringBuilder buf = new StringBuilder();
  1693             buf.append("@");
  1694             buf.append(type.tsym.getQualifiedName());
  1695             buf.append("/*proxy*/{");
  1696             boolean first = true;
  1697             for (List<Pair<Name,Attribute>> v = values;
  1698                  v.nonEmpty(); v = v.tail) {
  1699                 Pair<Name,Attribute> value = v.head;
  1700                 if (!first) buf.append(",");
  1701                 first = false;
  1702                 buf.append(value.fst);
  1703                 buf.append("=");
  1704                 buf.append(value.snd);
  1706             buf.append("}");
  1707             return buf.toString();
  1711     /** A temporary proxy representing a type annotation.
  1712      */
  1713     static class TypeAnnotationProxy {
  1714         final CompoundAnnotationProxy compound;
  1715         final TypeAnnotationPosition position;
  1716         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1717                 TypeAnnotationPosition position) {
  1718             this.compound = compound;
  1719             this.position = position;
  1723     class AnnotationDeproxy implements ProxyVisitor {
  1724         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1725             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1727         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1728             // also must fill in types!!!!
  1729             ListBuffer<Attribute.Compound> buf =
  1730                 new ListBuffer<Attribute.Compound>();
  1731             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1732                 buf.append(deproxyCompound(l.head));
  1734             return buf.toList();
  1737         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1738             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1739                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1740             for (List<Pair<Name,Attribute>> l = a.values;
  1741                  l.nonEmpty();
  1742                  l = l.tail) {
  1743                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1744                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1745                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1747             return new Attribute.Compound(a.type, buf.toList());
  1750         MethodSymbol findAccessMethod(Type container, Name name) {
  1751             CompletionFailure failure = null;
  1752             try {
  1753                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1754                      e.scope != null;
  1755                      e = e.next()) {
  1756                     Symbol sym = e.sym;
  1757                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1758                         return (MethodSymbol) sym;
  1760             } catch (CompletionFailure ex) {
  1761                 failure = ex;
  1763             // The method wasn't found: emit a warning and recover
  1764             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1765             try {
  1766                 if (failure == null) {
  1767                     log.warning("annotation.method.not.found",
  1768                                 container,
  1769                                 name);
  1770                 } else {
  1771                     log.warning("annotation.method.not.found.reason",
  1772                                 container,
  1773                                 name,
  1774                                 failure.getDetailValue());//diagnostic, if present
  1776             } finally {
  1777                 log.useSource(prevSource);
  1779             // Construct a new method type and symbol.  Use bottom
  1780             // type (typeof null) as return type because this type is
  1781             // a subtype of all reference types and can be converted
  1782             // to primitive types by unboxing.
  1783             MethodType mt = new MethodType(List.<Type>nil(),
  1784                                            syms.botType,
  1785                                            List.<Type>nil(),
  1786                                            syms.methodClass);
  1787             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1790         Attribute result;
  1791         Type type;
  1792         Attribute deproxy(Type t, Attribute a) {
  1793             Type oldType = type;
  1794             try {
  1795                 type = t;
  1796                 a.accept(this);
  1797                 return result;
  1798             } finally {
  1799                 type = oldType;
  1803         // implement Attribute.Visitor below
  1805         public void visitConstant(Attribute.Constant value) {
  1806             // assert value.type == type;
  1807             result = value;
  1810         public void visitClass(Attribute.Class clazz) {
  1811             result = clazz;
  1814         public void visitEnum(Attribute.Enum e) {
  1815             throw new AssertionError(); // shouldn't happen
  1818         public void visitCompound(Attribute.Compound compound) {
  1819             throw new AssertionError(); // shouldn't happen
  1822         public void visitArray(Attribute.Array array) {
  1823             throw new AssertionError(); // shouldn't happen
  1826         public void visitError(Attribute.Error e) {
  1827             throw new AssertionError(); // shouldn't happen
  1830         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1831             // type.tsym.flatName() should == proxy.enumFlatName
  1832             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1833             VarSymbol enumerator = null;
  1834             CompletionFailure failure = null;
  1835             try {
  1836                 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1837                      e.scope != null;
  1838                      e = e.next()) {
  1839                     if (e.sym.kind == VAR) {
  1840                         enumerator = (VarSymbol)e.sym;
  1841                         break;
  1845             catch (CompletionFailure ex) {
  1846                 failure = ex;
  1848             if (enumerator == null) {
  1849                 if (failure != null) {
  1850                     log.warning("unknown.enum.constant.reason",
  1851                               currentClassFile, enumTypeSym, proxy.enumerator,
  1852                               failure.getDiagnostic());
  1853                 } else {
  1854                     log.warning("unknown.enum.constant",
  1855                               currentClassFile, enumTypeSym, proxy.enumerator);
  1857                 result = new Attribute.Enum(enumTypeSym.type,
  1858                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
  1859             } else {
  1860                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1864         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1865             int length = proxy.values.length();
  1866             Attribute[] ats = new Attribute[length];
  1867             Type elemtype = types.elemtype(type);
  1868             int i = 0;
  1869             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1870                 ats[i++] = deproxy(elemtype, p.head);
  1872             result = new Attribute.Array(type, ats);
  1875         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1876             result = deproxyCompound(proxy);
  1880     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1881         final MethodSymbol sym;
  1882         final Attribute value;
  1883         final JavaFileObject classFile = currentClassFile;
  1884         @Override
  1885         public String toString() {
  1886             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1888         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1889             this.sym = sym;
  1890             this.value = value;
  1892         // implement Annotate.Annotator.enterAnnotation()
  1893         public void enterAnnotation() {
  1894             JavaFileObject previousClassFile = currentClassFile;
  1895             try {
  1896                 // Reset the interim value set earlier in
  1897                 // attachAnnotationDefault().
  1898                 sym.defaultValue = null;
  1899                 currentClassFile = classFile;
  1900                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1901             } finally {
  1902                 currentClassFile = previousClassFile;
  1907     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1908         final Symbol sym;
  1909         final List<CompoundAnnotationProxy> l;
  1910         final JavaFileObject classFile;
  1911         @Override
  1912         public String toString() {
  1913             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1915         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1916             this.sym = sym;
  1917             this.l = l;
  1918             this.classFile = currentClassFile;
  1920         // implement Annotate.Annotator.enterAnnotation()
  1921         public void enterAnnotation() {
  1922             JavaFileObject previousClassFile = currentClassFile;
  1923             try {
  1924                 currentClassFile = classFile;
  1925                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1926                 if (sym.annotationsPendingCompletion()) {
  1927                     sym.setDeclarationAttributes(newList);
  1928                 } else {
  1929                     sym.appendAttributes(newList);
  1931             } finally {
  1932                 currentClassFile = previousClassFile;
  1937     class TypeAnnotationCompleter extends AnnotationCompleter {
  1939         List<TypeAnnotationProxy> proxies;
  1941         TypeAnnotationCompleter(Symbol sym,
  1942                 List<TypeAnnotationProxy> proxies) {
  1943             super(sym, List.<CompoundAnnotationProxy>nil());
  1944             this.proxies = proxies;
  1947         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
  1948             ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  1949             for (TypeAnnotationProxy proxy: proxies) {
  1950                 Attribute.Compound compound = deproxyCompound(proxy.compound);
  1951                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
  1952                 buf.add(typeCompound);
  1954             return buf.toList();
  1957         @Override
  1958         public void enterAnnotation() {
  1959             JavaFileObject previousClassFile = currentClassFile;
  1960             try {
  1961                 currentClassFile = classFile;
  1962                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
  1963                 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
  1964             } finally {
  1965                 currentClassFile = previousClassFile;
  1971 /************************************************************************
  1972  * Reading Symbols
  1973  ***********************************************************************/
  1975     /** Read a field.
  1976      */
  1977     VarSymbol readField() {
  1978         long flags = adjustFieldFlags(nextChar());
  1979         Name name = readName(nextChar());
  1980         Type type = readType(nextChar());
  1981         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1982         readMemberAttrs(v);
  1983         return v;
  1986     /** Read a method.
  1987      */
  1988     MethodSymbol readMethod() {
  1989         long flags = adjustMethodFlags(nextChar());
  1990         Name name = readName(nextChar());
  1991         Type type = readType(nextChar());
  1992         if (currentOwner.isInterface() &&
  1993                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
  1994             if (majorVersion > Target.JDK1_8.majorVersion ||
  1995                     (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
  1996                 if ((flags & STATIC) == 0) {
  1997                     currentOwner.flags_field |= DEFAULT;
  1998                     flags |= DEFAULT | ABSTRACT;
  2000             } else {
  2001                 //protect against ill-formed classfiles
  2002                 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface",
  2003                                    Integer.toString(majorVersion),
  2004                                    Integer.toString(minorVersion));
  2007         if (name == names.init && currentOwner.hasOuterInstance()) {
  2008             // Sometimes anonymous classes don't have an outer
  2009             // instance, however, there is no reliable way to tell so
  2010             // we never strip this$n
  2011             if (!currentOwner.name.isEmpty())
  2012                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  2013                                       type.getReturnType(),
  2014                                       type.getThrownTypes(),
  2015                                       syms.methodClass);
  2017         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  2018         if (types.isSignaturePolymorphic(m)) {
  2019             m.flags_field |= SIGNATURE_POLYMORPHIC;
  2021         if (saveParameterNames)
  2022             initParameterNames(m);
  2023         Symbol prevOwner = currentOwner;
  2024         currentOwner = m;
  2025         try {
  2026             readMemberAttrs(m);
  2027         } finally {
  2028             currentOwner = prevOwner;
  2030         if (saveParameterNames)
  2031             setParameterNames(m, type);
  2032         return m;
  2035     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  2036         boolean isVarargs = (flags & VARARGS) != 0;
  2037         if (isVarargs) {
  2038             Type varargsElem = args.last();
  2039             ListBuffer<Type> adjustedArgs = new ListBuffer<>();
  2040             for (Type t : args) {
  2041                 adjustedArgs.append(t != varargsElem ?
  2042                     t :
  2043                     ((ArrayType)t).makeVarargs());
  2045             args = adjustedArgs.toList();
  2047         return args.tail;
  2050     /**
  2051      * Init the parameter names array.
  2052      * Parameter names are currently inferred from the names in the
  2053      * LocalVariableTable attributes of a Code attribute.
  2054      * (Note: this means parameter names are currently not available for
  2055      * methods without a Code attribute.)
  2056      * This method initializes an array in which to store the name indexes
  2057      * of parameter names found in LocalVariableTable attributes. It is
  2058      * slightly supersized to allow for additional slots with a start_pc of 0.
  2059      */
  2060     void initParameterNames(MethodSymbol sym) {
  2061         // make allowance for synthetic parameters.
  2062         final int excessSlots = 4;
  2063         int expectedParameterSlots =
  2064                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  2065         if (parameterNameIndices == null
  2066                 || parameterNameIndices.length < expectedParameterSlots) {
  2067             parameterNameIndices = new int[expectedParameterSlots];
  2068         } else
  2069             Arrays.fill(parameterNameIndices, 0);
  2070         haveParameterNameIndices = false;
  2071         sawMethodParameters = false;
  2074     /**
  2075      * Set the parameter names for a symbol from the name index in the
  2076      * parameterNameIndicies array. The type of the symbol may have changed
  2077      * while reading the method attributes (see the Signature attribute).
  2078      * This may be because of generic information or because anonymous
  2079      * synthetic parameters were added.   The original type (as read from
  2080      * the method descriptor) is used to help guess the existence of
  2081      * anonymous synthetic parameters.
  2082      * On completion, sym.savedParameter names will either be null (if
  2083      * no parameter names were found in the class file) or will be set to a
  2084      * list of names, one per entry in sym.type.getParameterTypes, with
  2085      * any missing names represented by the empty name.
  2086      */
  2087     void setParameterNames(MethodSymbol sym, Type jvmType) {
  2088         // if no names were found in the class file, there's nothing more to do
  2089         if (!haveParameterNameIndices)
  2090             return;
  2091         // If we get parameter names from MethodParameters, then we
  2092         // don't need to skip.
  2093         int firstParam = 0;
  2094         if (!sawMethodParameters) {
  2095             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  2096             // the code in readMethod may have skipped the first
  2097             // parameter when setting up the MethodType. If so, we
  2098             // make a corresponding allowance here for the position of
  2099             // the first parameter.  Note that this assumes the
  2100             // skipped parameter has a width of 1 -- i.e. it is not
  2101         // a double width type (long or double.)
  2102         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  2103             // Sometimes anonymous classes don't have an outer
  2104             // instance, however, there is no reliable way to tell so
  2105             // we never strip this$n
  2106             if (!currentOwner.name.isEmpty())
  2107                 firstParam += 1;
  2110         if (sym.type != jvmType) {
  2111                 // reading the method attributes has caused the
  2112                 // symbol's type to be changed. (i.e. the Signature
  2113                 // attribute.)  This may happen if there are hidden
  2114                 // (synthetic) parameters in the descriptor, but not
  2115                 // in the Signature.  The position of these hidden
  2116                 // parameters is unspecified; for now, assume they are
  2117                 // at the beginning, and so skip over them. The
  2118                 // primary case for this is two hidden parameters
  2119                 // passed into Enum constructors.
  2120             int skip = Code.width(jvmType.getParameterTypes())
  2121                     - Code.width(sym.type.getParameterTypes());
  2122             firstParam += skip;
  2125         List<Name> paramNames = List.nil();
  2126         int index = firstParam;
  2127         for (Type t: sym.type.getParameterTypes()) {
  2128             int nameIdx = (index < parameterNameIndices.length
  2129                     ? parameterNameIndices[index] : 0);
  2130             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  2131             paramNames = paramNames.prepend(name);
  2132             index += Code.width(t);
  2134         sym.savedParameterNames = paramNames.reverse();
  2137     /**
  2138      * skip n bytes
  2139      */
  2140     void skipBytes(int n) {
  2141         bp = bp + n;
  2144     /** Skip a field or method
  2145      */
  2146     void skipMember() {
  2147         bp = bp + 6;
  2148         char ac = nextChar();
  2149         for (int i = 0; i < ac; i++) {
  2150             bp = bp + 2;
  2151             int attrLen = nextInt();
  2152             bp = bp + attrLen;
  2156     /** Enter type variables of this classtype and all enclosing ones in
  2157      *  `typevars'.
  2158      */
  2159     protected void enterTypevars(Type t) {
  2160         if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
  2161             enterTypevars(t.getEnclosingType());
  2162         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  2163             typevars.enter(xs.head.tsym);
  2166     protected void enterTypevars(Symbol sym) {
  2167         if (sym.owner.kind == MTH) {
  2168             enterTypevars(sym.owner);
  2169             enterTypevars(sym.owner.owner);
  2171         enterTypevars(sym.type);
  2174     /** Read contents of a given class symbol `c'. Both external and internal
  2175      *  versions of an inner class are read.
  2176      */
  2177     void readClass(ClassSymbol c) {
  2178         ClassType ct = (ClassType)c.type;
  2180         // allocate scope for members
  2181         c.members_field = new Scope(c);
  2183         // prepare type variable table
  2184         typevars = typevars.dup(currentOwner);
  2185         if (ct.getEnclosingType().hasTag(CLASS))
  2186             enterTypevars(ct.getEnclosingType());
  2188         // read flags, or skip if this is an inner class
  2189         long flags = adjustClassFlags(nextChar());
  2190         if (c.owner.kind == PCK) c.flags_field = flags;
  2192         // read own class name and check that it matches
  2193         ClassSymbol self = readClassSymbol(nextChar());
  2194         if (c != self)
  2195             throw badClassFile("class.file.wrong.class",
  2196                                self.flatname);
  2198         // class attributes must be read before class
  2199         // skip ahead to read class attributes
  2200         int startbp = bp;
  2201         nextChar();
  2202         char interfaceCount = nextChar();
  2203         bp += interfaceCount * 2;
  2204         char fieldCount = nextChar();
  2205         for (int i = 0; i < fieldCount; i++) skipMember();
  2206         char methodCount = nextChar();
  2207         for (int i = 0; i < methodCount; i++) skipMember();
  2208         readClassAttrs(c);
  2210         if (readAllOfClassFile) {
  2211             for (int i = 1; i < poolObj.length; i++) readPool(i);
  2212             c.pool = new Pool(poolObj.length, poolObj, types);
  2215         // reset and read rest of classinfo
  2216         bp = startbp;
  2217         int n = nextChar();
  2218         if (ct.supertype_field == null)
  2219             ct.supertype_field = (n == 0)
  2220                 ? Type.noType
  2221                 : readClassSymbol(n).erasure(types);
  2222         n = nextChar();
  2223         List<Type> is = List.nil();
  2224         for (int i = 0; i < n; i++) {
  2225             Type _inter = readClassSymbol(nextChar()).erasure(types);
  2226             is = is.prepend(_inter);
  2228         if (ct.interfaces_field == null)
  2229             ct.interfaces_field = is.reverse();
  2231         Assert.check(fieldCount == nextChar());
  2232         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  2233         Assert.check(methodCount == nextChar());
  2234         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  2236         typevars = typevars.leave();
  2239     /** Read inner class info. For each inner/outer pair allocate a
  2240      *  member class.
  2241      */
  2242     void readInnerClasses(ClassSymbol c) {
  2243         int n = nextChar();
  2244         for (int i = 0; i < n; i++) {
  2245             nextChar(); // skip inner class symbol
  2246             ClassSymbol outer = readClassSymbol(nextChar());
  2247             Name name = readName(nextChar());
  2248             if (name == null) name = names.empty;
  2249             long flags = adjustClassFlags(nextChar());
  2250             if (outer != null) { // we have a member class
  2251                 if (name == names.empty)
  2252                     name = names.one;
  2253                 ClassSymbol member = enterClass(name, outer);
  2254                 if ((flags & STATIC) == 0) {
  2255                     ((ClassType)member.type).setEnclosingType(outer.type);
  2256                     if (member.erasure_field != null)
  2257                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  2259                 if (c == outer) {
  2260                     member.flags_field = flags;
  2261                     enterMember(c, member);
  2267     /** Read a class file.
  2268      */
  2269     private void readClassFile(ClassSymbol c) throws IOException {
  2270         int magic = nextInt();
  2271         if (magic != JAVA_MAGIC)
  2272             throw badClassFile("illegal.start.of.class.file");
  2274         minorVersion = nextChar();
  2275         majorVersion = nextChar();
  2276         int maxMajor = Target.MAX().majorVersion;
  2277         int maxMinor = Target.MAX().minorVersion;
  2278         if (majorVersion > maxMajor ||
  2279             majorVersion * 1000 + minorVersion <
  2280             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  2282             if (majorVersion == (maxMajor + 1))
  2283                 log.warning("big.major.version",
  2284                             currentClassFile,
  2285                             majorVersion,
  2286                             maxMajor);
  2287             else
  2288                 throw badClassFile("wrong.version",
  2289                                    Integer.toString(majorVersion),
  2290                                    Integer.toString(minorVersion),
  2291                                    Integer.toString(maxMajor),
  2292                                    Integer.toString(maxMinor));
  2294         else if (checkClassFile &&
  2295                  majorVersion == maxMajor &&
  2296                  minorVersion > maxMinor)
  2298             printCCF("found.later.version",
  2299                      Integer.toString(minorVersion));
  2301         indexPool();
  2302         if (signatureBuffer.length < bp) {
  2303             int ns = Integer.highestOneBit(bp) << 1;
  2304             signatureBuffer = new byte[ns];
  2306         readClass(c);
  2309 /************************************************************************
  2310  * Adjusting flags
  2311  ***********************************************************************/
  2313     long adjustFieldFlags(long flags) {
  2314         return flags;
  2316     long adjustMethodFlags(long flags) {
  2317         if ((flags & ACC_BRIDGE) != 0) {
  2318             flags &= ~ACC_BRIDGE;
  2319             flags |= BRIDGE;
  2320             if (!allowGenerics)
  2321                 flags &= ~SYNTHETIC;
  2323         if ((flags & ACC_VARARGS) != 0) {
  2324             flags &= ~ACC_VARARGS;
  2325             flags |= VARARGS;
  2327         return flags;
  2329     long adjustClassFlags(long flags) {
  2330         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2333 /************************************************************************
  2334  * Loading Classes
  2335  ***********************************************************************/
  2337     /** Define a new class given its name and owner.
  2338      */
  2339     public ClassSymbol defineClass(Name name, Symbol owner) {
  2340         ClassSymbol c = new ClassSymbol(0, name, owner);
  2341         if (owner.kind == PCK)
  2342             Assert.checkNull(classes.get(c.flatname), c);
  2343         c.completer = thisCompleter;
  2344         return c;
  2347     /** Create a new toplevel or member class symbol with given name
  2348      *  and owner and enter in `classes' unless already there.
  2349      */
  2350     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2351         Name flatname = TypeSymbol.formFlatName(name, owner);
  2352         ClassSymbol c = classes.get(flatname);
  2353         if (c == null) {
  2354             c = defineClass(name, owner);
  2355             classes.put(flatname, c);
  2356         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2357             // reassign fields of classes that might have been loaded with
  2358             // their flat names.
  2359             c.owner.members().remove(c);
  2360             c.name = name;
  2361             c.owner = owner;
  2362             c.fullname = ClassSymbol.formFullName(name, owner);
  2364         return c;
  2367     /**
  2368      * Creates a new toplevel class symbol with given flat name and
  2369      * given class (or source) file.
  2371      * @param flatName a fully qualified binary class name
  2372      * @param classFile the class file or compilation unit defining
  2373      * the class (may be {@code null})
  2374      * @return a newly created class symbol
  2375      * @throws AssertionError if the class symbol already exists
  2376      */
  2377     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2378         ClassSymbol cs = classes.get(flatName);
  2379         if (cs != null) {
  2380             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2381                                     cs.fullname,
  2382                                     cs.completer,
  2383                                     cs.classfile,
  2384                                     cs.sourcefile);
  2385             throw new AssertionError(msg);
  2387         Name packageName = Convert.packagePart(flatName);
  2388         PackageSymbol owner = packageName.isEmpty()
  2389                                 ? syms.unnamedPackage
  2390                                 : enterPackage(packageName);
  2391         cs = defineClass(Convert.shortName(flatName), owner);
  2392         cs.classfile = classFile;
  2393         classes.put(flatName, cs);
  2394         return cs;
  2397     /** Create a new member or toplevel class symbol with given flat name
  2398      *  and enter in `classes' unless already there.
  2399      */
  2400     public ClassSymbol enterClass(Name flatname) {
  2401         ClassSymbol c = classes.get(flatname);
  2402         if (c == null)
  2403             return enterClass(flatname, (JavaFileObject)null);
  2404         else
  2405             return c;
  2408     private boolean suppressFlush = false;
  2410     /** Completion for classes to be loaded. Before a class is loaded
  2411      *  we make sure its enclosing class (if any) is loaded.
  2412      */
  2413     private void complete(Symbol sym) throws CompletionFailure {
  2414         if (sym.kind == TYP) {
  2415             ClassSymbol c = (ClassSymbol)sym;
  2416             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2417             boolean saveSuppressFlush = suppressFlush;
  2418             suppressFlush = true;
  2419             try {
  2420                 completeOwners(c.owner);
  2421                 completeEnclosing(c);
  2422             } finally {
  2423                 suppressFlush = saveSuppressFlush;
  2425             fillIn(c);
  2426         } else if (sym.kind == PCK) {
  2427             PackageSymbol p = (PackageSymbol)sym;
  2428             try {
  2429                 fillIn(p);
  2430             } catch (IOException ex) {
  2431                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2434         if (!filling && !suppressFlush)
  2435             annotate.flush(); // finish attaching annotations
  2438     /** complete up through the enclosing package. */
  2439     private void completeOwners(Symbol o) {
  2440         if (o.kind != PCK) completeOwners(o.owner);
  2441         o.complete();
  2444     /**
  2445      * Tries to complete lexically enclosing classes if c looks like a
  2446      * nested class.  This is similar to completeOwners but handles
  2447      * the situation when a nested class is accessed directly as it is
  2448      * possible with the Tree API or javax.lang.model.*.
  2449      */
  2450     private void completeEnclosing(ClassSymbol c) {
  2451         if (c.owner.kind == PCK) {
  2452             Symbol owner = c.owner;
  2453             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2454                 Symbol encl = owner.members().lookup(name).sym;
  2455                 if (encl == null)
  2456                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2457                 if (encl != null)
  2458                     encl.complete();
  2463     /** We can only read a single class file at a time; this
  2464      *  flag keeps track of when we are currently reading a class
  2465      *  file.
  2466      */
  2467     private boolean filling = false;
  2469     /** Fill in definition of class `c' from corresponding class or
  2470      *  source file.
  2471      */
  2472     private void fillIn(ClassSymbol c) {
  2473         if (completionFailureName == c.fullname) {
  2474             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2476         currentOwner = c;
  2477         warnedAttrs.clear();
  2478         JavaFileObject classfile = c.classfile;
  2479         if (classfile != null) {
  2480             JavaFileObject previousClassFile = currentClassFile;
  2481             try {
  2482                 if (filling) {
  2483                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2485                 currentClassFile = classfile;
  2486                 if (verbose) {
  2487                     log.printVerbose("loading", currentClassFile.toString());
  2489                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2490                     filling = true;
  2491                     try {
  2492                         bp = 0;
  2493                         buf = readInputStream(buf, classfile.openInputStream());
  2494                         readClassFile(c);
  2495                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2496                             List<Type> missing = missingTypeVariables;
  2497                             List<Type> found = foundTypeVariables;
  2498                             missingTypeVariables = List.nil();
  2499                             foundTypeVariables = List.nil();
  2500                             filling = false;
  2501                             ClassType ct = (ClassType)currentOwner.type;
  2502                             ct.supertype_field =
  2503                                 types.subst(ct.supertype_field, missing, found);
  2504                             ct.interfaces_field =
  2505                                 types.subst(ct.interfaces_field, missing, found);
  2506                         } else if (missingTypeVariables.isEmpty() !=
  2507                                    foundTypeVariables.isEmpty()) {
  2508                             Name name = missingTypeVariables.head.tsym.name;
  2509                             throw badClassFile("undecl.type.var", name);
  2511                     } finally {
  2512                         missingTypeVariables = List.nil();
  2513                         foundTypeVariables = List.nil();
  2514                         filling = false;
  2516                 } else {
  2517                     if (sourceCompleter != null) {
  2518                         sourceCompleter.complete(c);
  2519                     } else {
  2520                         throw new IllegalStateException("Source completer required to read "
  2521                                                         + classfile.toUri());
  2524                 return;
  2525             } catch (IOException ex) {
  2526                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2527             } finally {
  2528                 currentClassFile = previousClassFile;
  2530         } else {
  2531             JCDiagnostic diag =
  2532                 diagFactory.fragment("class.file.not.found", c.flatname);
  2533             throw
  2534                 newCompletionFailure(c, diag);
  2537     // where
  2538         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2539             try {
  2540                 buf = ensureCapacity(buf, s.available());
  2541                 int r = s.read(buf);
  2542                 int bp = 0;
  2543                 while (r != -1) {
  2544                     bp += r;
  2545                     buf = ensureCapacity(buf, bp);
  2546                     r = s.read(buf, bp, buf.length - bp);
  2548                 return buf;
  2549             } finally {
  2550                 try {
  2551                     s.close();
  2552                 } catch (IOException e) {
  2553                     /* Ignore any errors, as this stream may have already
  2554                      * thrown a related exception which is the one that
  2555                      * should be reported.
  2556                      */
  2560         /*
  2561          * ensureCapacity will increase the buffer as needed, taking note that
  2562          * the new buffer will always be greater than the needed and never
  2563          * exactly equal to the needed size or bp. If equal then the read (above)
  2564          * will infinitely loop as buf.length - bp == 0.
  2565          */
  2566         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2567             if (buf.length <= needed) {
  2568                 byte[] old = buf;
  2569                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2570                 System.arraycopy(old, 0, buf, 0, old.length);
  2572             return buf;
  2574         /** Static factory for CompletionFailure objects.
  2575          *  In practice, only one can be used at a time, so we share one
  2576          *  to reduce the expense of allocating new exception objects.
  2577          */
  2578         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2579                                                        JCDiagnostic diag) {
  2580             if (!cacheCompletionFailure) {
  2581                 // log.warning("proc.messager",
  2582                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2583                 // c.debug.printStackTrace();
  2584                 return new CompletionFailure(c, diag);
  2585             } else {
  2586                 CompletionFailure result = cachedCompletionFailure;
  2587                 result.sym = c;
  2588                 result.diag = diag;
  2589                 return result;
  2592         private CompletionFailure cachedCompletionFailure =
  2593             new CompletionFailure(null, (JCDiagnostic) null);
  2595             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2598     /** Load a toplevel class with given fully qualified name
  2599      *  The class is entered into `classes' only if load was successful.
  2600      */
  2601     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2602         boolean absent = classes.get(flatname) == null;
  2603         ClassSymbol c = enterClass(flatname);
  2604         if (c.members_field == null && c.completer != null) {
  2605             try {
  2606                 c.complete();
  2607             } catch (CompletionFailure ex) {
  2608                 if (absent) classes.remove(flatname);
  2609                 throw ex;
  2612         return c;
  2615 /************************************************************************
  2616  * Loading Packages
  2617  ***********************************************************************/
  2619     /** Check to see if a package exists, given its fully qualified name.
  2620      */
  2621     public boolean packageExists(Name fullname) {
  2622         return enterPackage(fullname).exists();
  2625     /** Make a package, given its fully qualified name.
  2626      */
  2627     public PackageSymbol enterPackage(Name fullname) {
  2628         PackageSymbol p = packages.get(fullname);
  2629         if (p == null) {
  2630             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2631             p = new PackageSymbol(
  2632                 Convert.shortName(fullname),
  2633                 enterPackage(Convert.packagePart(fullname)));
  2634             p.completer = thisCompleter;
  2635             packages.put(fullname, p);
  2637         return p;
  2640     /** Make a package, given its unqualified name and enclosing package.
  2641      */
  2642     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2643         return enterPackage(TypeSymbol.formFullName(name, owner));
  2646     /** Include class corresponding to given class file in package,
  2647      *  unless (1) we already have one the same kind (.class or .java), or
  2648      *         (2) we have one of the other kind, and the given class file
  2649      *             is older.
  2650      */
  2651     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2652         if ((p.flags_field & EXISTS) == 0)
  2653             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2654                 q.flags_field |= EXISTS;
  2655         JavaFileObject.Kind kind = file.getKind();
  2656         int seen;
  2657         if (kind == JavaFileObject.Kind.CLASS)
  2658             seen = CLASS_SEEN;
  2659         else
  2660             seen = SOURCE_SEEN;
  2661         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2662         int lastDot = binaryName.lastIndexOf(".");
  2663         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2664         boolean isPkgInfo = classname == names.package_info;
  2665         ClassSymbol c = isPkgInfo
  2666             ? p.package_info
  2667             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2668         if (c == null) {
  2669             c = enterClass(classname, p);
  2670             if (c.classfile == null) // only update the file if's it's newly created
  2671                 c.classfile = file;
  2672             if (isPkgInfo) {
  2673                 p.package_info = c;
  2674             } else {
  2675                 if (c.owner == p)  // it might be an inner class
  2676                     p.members_field.enter(c);
  2678         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2679             // if c.classfile == null, we are currently compiling this class
  2680             // and no further action is necessary.
  2681             // if (c.flags_field & seen) != 0, we have already encountered
  2682             // a file of the same kind; again no further action is necessary.
  2683             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2684                 c.classfile = preferredFileObject(file, c.classfile);
  2686         c.flags_field |= seen;
  2689     /** Implement policy to choose to derive information from a source
  2690      *  file or a class file when both are present.  May be overridden
  2691      *  by subclasses.
  2692      */
  2693     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2694                                            JavaFileObject b) {
  2696         if (preferSource)
  2697             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2698         else {
  2699             long adate = a.getLastModified();
  2700             long bdate = b.getLastModified();
  2701             // 6449326: policy for bad lastModifiedTime in ClassReader
  2702             //assert adate >= 0 && bdate >= 0;
  2703             return (adate > bdate) ? a : b;
  2707     /**
  2708      * specifies types of files to be read when filling in a package symbol
  2709      */
  2710     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2711         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2714     /**
  2715      * this is used to support javadoc
  2716      */
  2717     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2720     protected Location currentLoc; // FIXME
  2722     private boolean verbosePath = true;
  2724     /** Load directory of package into members scope.
  2725      */
  2726     private void fillIn(PackageSymbol p) throws IOException {
  2727         if (p.members_field == null) p.members_field = new Scope(p);
  2728         String packageName = p.fullname.toString();
  2730         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2732         fillIn(p, PLATFORM_CLASS_PATH,
  2733                fileManager.list(PLATFORM_CLASS_PATH,
  2734                                 packageName,
  2735                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2736                                 false));
  2738         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2739         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2740         boolean wantClassFiles = !classKinds.isEmpty();
  2742         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2743         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2744         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2746         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2748         if (verbose && verbosePath) {
  2749             if (fileManager instanceof StandardJavaFileManager) {
  2750                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2751                 if (haveSourcePath && wantSourceFiles) {
  2752                     List<File> path = List.nil();
  2753                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2754                         path = path.prepend(file);
  2756                     log.printVerbose("sourcepath", path.reverse().toString());
  2757                 } else if (wantSourceFiles) {
  2758                     List<File> path = List.nil();
  2759                     for (File file : fm.getLocation(CLASS_PATH)) {
  2760                         path = path.prepend(file);
  2762                     log.printVerbose("sourcepath", path.reverse().toString());
  2764                 if (wantClassFiles) {
  2765                     List<File> path = List.nil();
  2766                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2767                         path = path.prepend(file);
  2769                     for (File file : fm.getLocation(CLASS_PATH)) {
  2770                         path = path.prepend(file);
  2772                     log.printVerbose("classpath",  path.reverse().toString());
  2777         if (wantSourceFiles && !haveSourcePath) {
  2778             fillIn(p, CLASS_PATH,
  2779                    fileManager.list(CLASS_PATH,
  2780                                     packageName,
  2781                                     kinds,
  2782                                     false));
  2783         } else {
  2784             if (wantClassFiles)
  2785                 fillIn(p, CLASS_PATH,
  2786                        fileManager.list(CLASS_PATH,
  2787                                         packageName,
  2788                                         classKinds,
  2789                                         false));
  2790             if (wantSourceFiles)
  2791                 fillIn(p, SOURCE_PATH,
  2792                        fileManager.list(SOURCE_PATH,
  2793                                         packageName,
  2794                                         sourceKinds,
  2795                                         false));
  2797         verbosePath = false;
  2799     // where
  2800         private void fillIn(PackageSymbol p,
  2801                             Location location,
  2802                             Iterable<JavaFileObject> files)
  2804             currentLoc = location;
  2805             for (JavaFileObject fo : files) {
  2806                 switch (fo.getKind()) {
  2807                 case CLASS:
  2808                 case SOURCE: {
  2809                     // TODO pass binaryName to includeClassFile
  2810                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2811                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2812                     if (SourceVersion.isIdentifier(simpleName) ||
  2813                         simpleName.equals("package-info"))
  2814                         includeClassFile(p, fo);
  2815                     break;
  2817                 default:
  2818                     extraFileActions(p, fo);
  2823     /** Output for "-checkclassfile" option.
  2824      *  @param key The key to look up the correct internationalized string.
  2825      *  @param arg An argument for substitution into the output string.
  2826      */
  2827     private void printCCF(String key, Object arg) {
  2828         log.printLines(key, arg);
  2832     public interface SourceCompleter {
  2833         void complete(ClassSymbol sym)
  2834             throws CompletionFailure;
  2837     /**
  2838      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2839      * The attribute is only the last component of the original filename, so is unlikely
  2840      * to be valid as is, so operations other than those to access the name throw
  2841      * UnsupportedOperationException
  2842      */
  2843     private static class SourceFileObject extends BaseFileObject {
  2845         /** The file's name.
  2846          */
  2847         private Name name;
  2848         private Name flatname;
  2850         public SourceFileObject(Name name, Name flatname) {
  2851             super(null); // no file manager; never referenced for this file object
  2852             this.name = name;
  2853             this.flatname = flatname;
  2856         @Override
  2857         public URI toUri() {
  2858             try {
  2859                 return new URI(null, name.toString(), null);
  2860             } catch (URISyntaxException e) {
  2861                 throw new CannotCreateUriError(name.toString(), e);
  2865         @Override
  2866         public String getName() {
  2867             return name.toString();
  2870         @Override
  2871         public String getShortName() {
  2872             return getName();
  2875         @Override
  2876         public JavaFileObject.Kind getKind() {
  2877             return getKind(getName());
  2880         @Override
  2881         public InputStream openInputStream() {
  2882             throw new UnsupportedOperationException();
  2885         @Override
  2886         public OutputStream openOutputStream() {
  2887             throw new UnsupportedOperationException();
  2890         @Override
  2891         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2892             throw new UnsupportedOperationException();
  2895         @Override
  2896         public Reader openReader(boolean ignoreEncodingErrors) {
  2897             throw new UnsupportedOperationException();
  2900         @Override
  2901         public Writer openWriter() {
  2902             throw new UnsupportedOperationException();
  2905         @Override
  2906         public long getLastModified() {
  2907             throw new UnsupportedOperationException();
  2910         @Override
  2911         public boolean delete() {
  2912             throw new UnsupportedOperationException();
  2915         @Override
  2916         protected String inferBinaryName(Iterable<? extends File> path) {
  2917             return flatname.toString();
  2920         @Override
  2921         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2922             return true; // fail-safe mode
  2925         /**
  2926          * Check if two file objects are equal.
  2927          * SourceFileObjects are just placeholder objects for the value of a
  2928          * SourceFile attribute, and do not directly represent specific files.
  2929          * Two SourceFileObjects are equal if their names are equal.
  2930          */
  2931         @Override
  2932         public boolean equals(Object other) {
  2933             if (this == other)
  2934                 return true;
  2936             if (!(other instanceof SourceFileObject))
  2937                 return false;
  2939             SourceFileObject o = (SourceFileObject) other;
  2940             return name.equals(o.name);
  2943         @Override
  2944         public int hashCode() {
  2945             return name.hashCode();

mercurial