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

Thu, 21 Feb 2013 17:49:56 -0800

author
lana
date
Thu, 21 Feb 2013 17:49:56 -0800
changeset 1603
6118072811e5
parent 1592
9345394ac8fe
parent 1571
af8417e590f4
child 1755
ddb4a2bfcd82
permissions
-rw-r--r--

Merge

     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.jvm.ClassFile.*;
    60 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
    62 import static com.sun.tools.javac.main.Option.*;
    64 /** This class provides operations to read a classfile into an internal
    65  *  representation. The internal representation is anchored in a
    66  *  ClassSymbol which contains in its scope symbol representations
    67  *  for all other definitions in the classfile. Top-level Classes themselves
    68  *  appear as members of the scopes of PackageSymbols.
    69  *
    70  *  <p><b>This is NOT part of any supported API.
    71  *  If you write code that depends on this, you do so at your own risk.
    72  *  This code and its internal interfaces are subject to change or
    73  *  deletion without notice.</b>
    74  */
    75 public class ClassReader implements Completer {
    76     /** The context key for the class reader. */
    77     protected static final Context.Key<ClassReader> classReaderKey =
    78         new Context.Key<ClassReader>();
    80     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
    82     Annotate annotate;
    84     /** Switch: verbose output.
    85      */
    86     boolean verbose;
    88     /** Switch: check class file for correct minor version, unrecognized
    89      *  attributes.
    90      */
    91     boolean checkClassFile;
    93     /** Switch: read constant pool and code sections. This switch is initially
    94      *  set to false but can be turned on from outside.
    95      */
    96     public boolean readAllOfClassFile = false;
    98     /** Switch: read GJ signature information.
    99      */
   100     boolean allowGenerics;
   102     /** Switch: read varargs attribute.
   103      */
   104     boolean allowVarargs;
   106     /** Switch: allow annotations.
   107      */
   108     boolean allowAnnotations;
   110     /** Switch: allow simplified varargs.
   111      */
   112     boolean allowSimplifiedVarargs;
   114    /** Lint option: warn about classfile issues
   115      */
   116     boolean lintClassfile;
   118     /** Switch: allow default methods
   119      */
   120     boolean allowDefaultMethods;
   122     /** Switch: preserve parameter names from the variable table.
   123      */
   124     public boolean saveParameterNames;
   126     /**
   127      * Switch: cache completion failures unless -XDdev is used
   128      */
   129     private boolean cacheCompletionFailure;
   131     /**
   132      * Switch: prefer source files instead of newer when both source
   133      * and class are available
   134      **/
   135     public boolean preferSource;
   137     /**
   138      * The currently selected profile.
   139      */
   140     public final Profile profile;
   142     /** The log to use for verbose output
   143      */
   144     final Log log;
   146     /** The symbol table. */
   147     Symtab syms;
   149     Types types;
   151     /** The name table. */
   152     final Names names;
   154     /** Force a completion failure on this name
   155      */
   156     final Name completionFailureName;
   158     /** Access to files
   159      */
   160     private final JavaFileManager fileManager;
   162     /** Factory for diagnostics
   163      */
   164     JCDiagnostic.Factory diagFactory;
   166     /** Can be reassigned from outside:
   167      *  the completer to be used for ".java" files. If this remains unassigned
   168      *  ".java" files will not be loaded.
   169      */
   170     public SourceCompleter sourceCompleter = null;
   172     /** A hashtable containing the encountered top-level and member classes,
   173      *  indexed by flat names. The table does not contain local classes.
   174      */
   175     private Map<Name,ClassSymbol> classes;
   177     /** A hashtable containing the encountered packages.
   178      */
   179     private Map<Name, PackageSymbol> packages;
   181     /** The current scope where type variables are entered.
   182      */
   183     protected Scope typevars;
   185     /** The path name of the class file currently being read.
   186      */
   187     protected JavaFileObject currentClassFile = null;
   189     /** The class or method currently being read.
   190      */
   191     protected Symbol currentOwner = null;
   193     /** The buffer containing the currently read class file.
   194      */
   195     byte[] buf = new byte[INITIAL_BUFFER_SIZE];
   197     /** The current input pointer.
   198      */
   199     protected int bp;
   201     /** The objects of the constant pool.
   202      */
   203     Object[] poolObj;
   205     /** For every constant pool entry, an index into buf where the
   206      *  defining section of the entry is found.
   207      */
   208     int[] poolIdx;
   210     /** The major version number of the class file being read. */
   211     int majorVersion;
   212     /** The minor version number of the class file being read. */
   213     int minorVersion;
   215     /** A table to hold the constant pool indices for method parameter
   216      * names, as given in LocalVariableTable attributes.
   217      */
   218     int[] parameterNameIndices;
   220     /**
   221      * Whether or not any parameter names have been found.
   222      */
   223     boolean haveParameterNameIndices;
   225     /** Set this to false every time we start reading a method
   226      * and are saving parameter names.  Set it to true when we see
   227      * MethodParameters, if it's set when we see a LocalVariableTable,
   228      * then we ignore the parameter names from the LVT.
   229      */
   230     boolean sawMethodParameters;
   232     /**
   233      * The set of attribute names for which warnings have been generated for the current class
   234      */
   235     Set<Name> warnedAttrs = new HashSet<Name>();
   237     /** Get the ClassReader instance for this invocation. */
   238     public static ClassReader instance(Context context) {
   239         ClassReader instance = context.get(classReaderKey);
   240         if (instance == null)
   241             instance = new ClassReader(context, true);
   242         return instance;
   243     }
   245     /** Initialize classes and packages, treating this as the definitive classreader. */
   246     public void init(Symtab syms) {
   247         init(syms, true);
   248     }
   250     /** Initialize classes and packages, optionally treating this as
   251      *  the definitive classreader.
   252      */
   253     private void init(Symtab syms, boolean definitive) {
   254         if (classes != null) return;
   256         if (definitive) {
   257             Assert.check(packages == null || packages == syms.packages);
   258             packages = syms.packages;
   259             Assert.check(classes == null || classes == syms.classes);
   260             classes = syms.classes;
   261         } else {
   262             packages = new HashMap<Name, PackageSymbol>();
   263             classes = new HashMap<Name, ClassSymbol>();
   264         }
   266         packages.put(names.empty, syms.rootPackage);
   267         syms.rootPackage.completer = this;
   268         syms.unnamedPackage.completer = this;
   269     }
   271     /** Construct a new class reader, optionally treated as the
   272      *  definitive classreader for this invocation.
   273      */
   274     protected ClassReader(Context context, boolean definitive) {
   275         if (definitive) context.put(classReaderKey, this);
   277         names = Names.instance(context);
   278         syms = Symtab.instance(context);
   279         types = Types.instance(context);
   280         fileManager = context.get(JavaFileManager.class);
   281         if (fileManager == null)
   282             throw new AssertionError("FileManager initialization error");
   283         diagFactory = JCDiagnostic.Factory.instance(context);
   285         init(syms, definitive);
   286         log = Log.instance(context);
   288         Options options = Options.instance(context);
   289         annotate = Annotate.instance(context);
   290         verbose        = options.isSet(VERBOSE);
   291         checkClassFile = options.isSet("-checkclassfile");
   293         Source source = Source.instance(context);
   294         allowGenerics    = source.allowGenerics();
   295         allowVarargs     = source.allowVarargs();
   296         allowAnnotations = source.allowAnnotations();
   297         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   298         allowDefaultMethods = source.allowDefaultMethods();
   300         saveParameterNames = options.isSet("save-parameter-names");
   301         cacheCompletionFailure = options.isUnset("dev");
   302         preferSource = "source".equals(options.get("-Xprefer"));
   304         profile = Profile.instance(context);
   306         completionFailureName =
   307             options.isSet("failcomplete")
   308             ? names.fromString(options.get("failcomplete"))
   309             : null;
   311         typevars = new Scope(syms.noSymbol);
   313         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
   315         initAttributeReaders();
   316     }
   318     /** Add member to class unless it is synthetic.
   319      */
   320     private void enterMember(ClassSymbol c, Symbol sym) {
   321         // Synthetic members are not entered -- reason lost to history (optimization?).
   322         // Lambda methods must be entered because they may have inner classes (which reference them)
   323         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
   324             c.members_field.enter(sym);
   325     }
   327 /************************************************************************
   328  * Error Diagnoses
   329  ***********************************************************************/
   332     public class BadClassFile extends CompletionFailure {
   333         private static final long serialVersionUID = 0;
   335         public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
   336             super(sym, createBadClassFileDiagnostic(file, diag));
   337         }
   338     }
   339     // where
   340     private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
   341         String key = (file.getKind() == JavaFileObject.Kind.SOURCE
   342                     ? "bad.source.file.header" : "bad.class.file.header");
   343         return diagFactory.fragment(key, file, diag);
   344     }
   346     public BadClassFile badClassFile(String key, Object... args) {
   347         return new BadClassFile (
   348             currentOwner.enclClass(),
   349             currentClassFile,
   350             diagFactory.fragment(key, args));
   351     }
   353 /************************************************************************
   354  * Buffer Access
   355  ***********************************************************************/
   357     /** Read a character.
   358      */
   359     char nextChar() {
   360         return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
   361     }
   363     /** Read a byte.
   364      */
   365     int nextByte() {
   366         return buf[bp++] & 0xFF;
   367     }
   369     /** Read an integer.
   370      */
   371     int nextInt() {
   372         return
   373             ((buf[bp++] & 0xFF) << 24) +
   374             ((buf[bp++] & 0xFF) << 16) +
   375             ((buf[bp++] & 0xFF) << 8) +
   376             (buf[bp++] & 0xFF);
   377     }
   379     /** Extract a character at position bp from buf.
   380      */
   381     char getChar(int bp) {
   382         return
   383             (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
   384     }
   386     /** Extract an integer at position bp from buf.
   387      */
   388     int getInt(int bp) {
   389         return
   390             ((buf[bp] & 0xFF) << 24) +
   391             ((buf[bp+1] & 0xFF) << 16) +
   392             ((buf[bp+2] & 0xFF) << 8) +
   393             (buf[bp+3] & 0xFF);
   394     }
   397     /** Extract a long integer at position bp from buf.
   398      */
   399     long getLong(int bp) {
   400         DataInputStream bufin =
   401             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   402         try {
   403             return bufin.readLong();
   404         } catch (IOException e) {
   405             throw new AssertionError(e);
   406         }
   407     }
   409     /** Extract a float at position bp from buf.
   410      */
   411     float getFloat(int bp) {
   412         DataInputStream bufin =
   413             new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
   414         try {
   415             return bufin.readFloat();
   416         } catch (IOException e) {
   417             throw new AssertionError(e);
   418         }
   419     }
   421     /** Extract a double at position bp from buf.
   422      */
   423     double getDouble(int bp) {
   424         DataInputStream bufin =
   425             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   426         try {
   427             return bufin.readDouble();
   428         } catch (IOException e) {
   429             throw new AssertionError(e);
   430         }
   431     }
   433 /************************************************************************
   434  * Constant Pool Access
   435  ***********************************************************************/
   437     /** Index all constant pool entries, writing their start addresses into
   438      *  poolIdx.
   439      */
   440     void indexPool() {
   441         poolIdx = new int[nextChar()];
   442         poolObj = new Object[poolIdx.length];
   443         int i = 1;
   444         while (i < poolIdx.length) {
   445             poolIdx[i++] = bp;
   446             byte tag = buf[bp++];
   447             switch (tag) {
   448             case CONSTANT_Utf8: case CONSTANT_Unicode: {
   449                 int len = nextChar();
   450                 bp = bp + len;
   451                 break;
   452             }
   453             case CONSTANT_Class:
   454             case CONSTANT_String:
   455             case CONSTANT_MethodType:
   456                 bp = bp + 2;
   457                 break;
   458             case CONSTANT_MethodHandle:
   459                 bp = bp + 3;
   460                 break;
   461             case CONSTANT_Fieldref:
   462             case CONSTANT_Methodref:
   463             case CONSTANT_InterfaceMethodref:
   464             case CONSTANT_NameandType:
   465             case CONSTANT_Integer:
   466             case CONSTANT_Float:
   467             case CONSTANT_InvokeDynamic:
   468                 bp = bp + 4;
   469                 break;
   470             case CONSTANT_Long:
   471             case CONSTANT_Double:
   472                 bp = bp + 8;
   473                 i++;
   474                 break;
   475             default:
   476                 throw badClassFile("bad.const.pool.tag.at",
   477                                    Byte.toString(tag),
   478                                    Integer.toString(bp -1));
   479             }
   480         }
   481     }
   483     /** Read constant pool entry at start address i, use pool as a cache.
   484      */
   485     Object readPool(int i) {
   486         Object result = poolObj[i];
   487         if (result != null) return result;
   489         int index = poolIdx[i];
   490         if (index == 0) return null;
   492         byte tag = buf[index];
   493         switch (tag) {
   494         case CONSTANT_Utf8:
   495             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   496             break;
   497         case CONSTANT_Unicode:
   498             throw badClassFile("unicode.str.not.supported");
   499         case CONSTANT_Class:
   500             poolObj[i] = readClassOrType(getChar(index + 1));
   501             break;
   502         case CONSTANT_String:
   503             // FIXME: (footprint) do not use toString here
   504             poolObj[i] = readName(getChar(index + 1)).toString();
   505             break;
   506         case CONSTANT_Fieldref: {
   507             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   508             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   509             poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
   510             break;
   511         }
   512         case CONSTANT_Methodref:
   513         case CONSTANT_InterfaceMethodref: {
   514             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   515             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   516             poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
   517             break;
   518         }
   519         case CONSTANT_NameandType:
   520             poolObj[i] = new NameAndType(
   521                 readName(getChar(index + 1)),
   522                 readType(getChar(index + 3)), types);
   523             break;
   524         case CONSTANT_Integer:
   525             poolObj[i] = getInt(index + 1);
   526             break;
   527         case CONSTANT_Float:
   528             poolObj[i] = new Float(getFloat(index + 1));
   529             break;
   530         case CONSTANT_Long:
   531             poolObj[i] = new Long(getLong(index + 1));
   532             break;
   533         case CONSTANT_Double:
   534             poolObj[i] = new Double(getDouble(index + 1));
   535             break;
   536         case CONSTANT_MethodHandle:
   537             skipBytes(4);
   538             break;
   539         case CONSTANT_MethodType:
   540             skipBytes(3);
   541             break;
   542         case CONSTANT_InvokeDynamic:
   543             skipBytes(5);
   544             break;
   545         default:
   546             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   547         }
   548         return poolObj[i];
   549     }
   551     /** Read signature and convert to type.
   552      */
   553     Type readType(int i) {
   554         int index = poolIdx[i];
   555         return sigToType(buf, index + 3, getChar(index + 1));
   556     }
   558     /** If name is an array type or class signature, return the
   559      *  corresponding type; otherwise return a ClassSymbol with given name.
   560      */
   561     Object readClassOrType(int i) {
   562         int index =  poolIdx[i];
   563         int len = getChar(index + 1);
   564         int start = index + 3;
   565         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   566         // by the above assertion, the following test can be
   567         // simplified to (buf[start] == '[')
   568         return (buf[start] == '[' || buf[start + len - 1] == ';')
   569             ? (Object)sigToType(buf, start, len)
   570             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   571                                                            len)));
   572     }
   574     /** Read signature and convert to type parameters.
   575      */
   576     List<Type> readTypeParams(int i) {
   577         int index = poolIdx[i];
   578         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   579     }
   581     /** Read class entry.
   582      */
   583     ClassSymbol readClassSymbol(int i) {
   584         return (ClassSymbol) (readPool(i));
   585     }
   587     /** Read name.
   588      */
   589     Name readName(int i) {
   590         return (Name) (readPool(i));
   591     }
   593 /************************************************************************
   594  * Reading Types
   595  ***********************************************************************/
   597     /** The unread portion of the currently read type is
   598      *  signature[sigp..siglimit-1].
   599      */
   600     byte[] signature;
   601     int sigp;
   602     int siglimit;
   603     boolean sigEnterPhase = false;
   605     /** Convert signature to type, where signature is a byte array segment.
   606      */
   607     Type sigToType(byte[] sig, int offset, int len) {
   608         signature = sig;
   609         sigp = offset;
   610         siglimit = offset + len;
   611         return sigToType();
   612     }
   614     /** Convert signature to type, where signature is implicit.
   615      */
   616     Type sigToType() {
   617         switch ((char) signature[sigp]) {
   618         case 'T':
   619             sigp++;
   620             int start = sigp;
   621             while (signature[sigp] != ';') sigp++;
   622             sigp++;
   623             return sigEnterPhase
   624                 ? Type.noType
   625                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   626         case '+': {
   627             sigp++;
   628             Type t = sigToType();
   629             return new WildcardType(t, BoundKind.EXTENDS,
   630                                     syms.boundClass);
   631         }
   632         case '*':
   633             sigp++;
   634             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   635                                     syms.boundClass);
   636         case '-': {
   637             sigp++;
   638             Type t = sigToType();
   639             return new WildcardType(t, BoundKind.SUPER,
   640                                     syms.boundClass);
   641         }
   642         case 'B':
   643             sigp++;
   644             return syms.byteType;
   645         case 'C':
   646             sigp++;
   647             return syms.charType;
   648         case 'D':
   649             sigp++;
   650             return syms.doubleType;
   651         case 'F':
   652             sigp++;
   653             return syms.floatType;
   654         case 'I':
   655             sigp++;
   656             return syms.intType;
   657         case 'J':
   658             sigp++;
   659             return syms.longType;
   660         case 'L':
   661             {
   662                 // int oldsigp = sigp;
   663                 Type t = classSigToType();
   664                 if (sigp < siglimit && signature[sigp] == '.')
   665                     throw badClassFile("deprecated inner class signature syntax " +
   666                                        "(please recompile from source)");
   667                 /*
   668                 System.err.println(" decoded " +
   669                                    new String(signature, oldsigp, sigp-oldsigp) +
   670                                    " => " + t + " outer " + t.outer());
   671                 */
   672                 return t;
   673             }
   674         case 'S':
   675             sigp++;
   676             return syms.shortType;
   677         case 'V':
   678             sigp++;
   679             return syms.voidType;
   680         case 'Z':
   681             sigp++;
   682             return syms.booleanType;
   683         case '[':
   684             sigp++;
   685             return new ArrayType(sigToType(), syms.arrayClass);
   686         case '(':
   687             sigp++;
   688             List<Type> argtypes = sigToTypes(')');
   689             Type restype = sigToType();
   690             List<Type> thrown = List.nil();
   691             while (signature[sigp] == '^') {
   692                 sigp++;
   693                 thrown = thrown.prepend(sigToType());
   694             }
   695             return new MethodType(argtypes,
   696                                   restype,
   697                                   thrown.reverse(),
   698                                   syms.methodClass);
   699         case '<':
   700             typevars = typevars.dup(currentOwner);
   701             Type poly = new ForAll(sigToTypeParams(), sigToType());
   702             typevars = typevars.leave();
   703             return poly;
   704         default:
   705             throw badClassFile("bad.signature",
   706                                Convert.utf2string(signature, sigp, 10));
   707         }
   708     }
   710     byte[] signatureBuffer = new byte[0];
   711     int sbp = 0;
   712     /** Convert class signature to type, where signature is implicit.
   713      */
   714     Type classSigToType() {
   715         if (signature[sigp] != 'L')
   716             throw badClassFile("bad.class.signature",
   717                                Convert.utf2string(signature, sigp, 10));
   718         sigp++;
   719         Type outer = Type.noType;
   720         int startSbp = sbp;
   722         while (true) {
   723             final byte c = signature[sigp++];
   724             switch (c) {
   726             case ';': {         // end
   727                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   728                                                          startSbp,
   729                                                          sbp - startSbp));
   730                 if (outer == Type.noType)
   731                     outer = t.erasure(types);
   732                 else
   733                     outer = new ClassType(outer, List.<Type>nil(), t);
   734                 sbp = startSbp;
   735                 return outer;
   736             }
   738             case '<':           // generic arguments
   739                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   740                                                          startSbp,
   741                                                          sbp - startSbp));
   742                 outer = new ClassType(outer, sigToTypes('>'), t) {
   743                         boolean completed = false;
   744                         @Override
   745                         public Type getEnclosingType() {
   746                             if (!completed) {
   747                                 completed = true;
   748                                 tsym.complete();
   749                                 Type enclosingType = tsym.type.getEnclosingType();
   750                                 if (enclosingType != Type.noType) {
   751                                     List<Type> typeArgs =
   752                                         super.getEnclosingType().allparams();
   753                                     List<Type> typeParams =
   754                                         enclosingType.allparams();
   755                                     if (typeParams.length() != typeArgs.length()) {
   756                                         // no "rare" types
   757                                         super.setEnclosingType(types.erasure(enclosingType));
   758                                     } else {
   759                                         super.setEnclosingType(types.subst(enclosingType,
   760                                                                            typeParams,
   761                                                                            typeArgs));
   762                                     }
   763                                 } else {
   764                                     super.setEnclosingType(Type.noType);
   765                                 }
   766                             }
   767                             return super.getEnclosingType();
   768                         }
   769                         @Override
   770                         public void setEnclosingType(Type outer) {
   771                             throw new UnsupportedOperationException();
   772                         }
   773                     };
   774                 switch (signature[sigp++]) {
   775                 case ';':
   776                     if (sigp < signature.length && signature[sigp] == '.') {
   777                         // support old-style GJC signatures
   778                         // The signature produced was
   779                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   780                         // rather than say
   781                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   782                         // so we skip past ".Lfoo/Outer$"
   783                         sigp += (sbp - startSbp) + // "foo/Outer"
   784                             3;  // ".L" and "$"
   785                         signatureBuffer[sbp++] = (byte)'$';
   786                         break;
   787                     } else {
   788                         sbp = startSbp;
   789                         return outer;
   790                     }
   791                 case '.':
   792                     signatureBuffer[sbp++] = (byte)'$';
   793                     break;
   794                 default:
   795                     throw new AssertionError(signature[sigp-1]);
   796                 }
   797                 continue;
   799             case '.':
   800                 signatureBuffer[sbp++] = (byte)'$';
   801                 continue;
   802             case '/':
   803                 signatureBuffer[sbp++] = (byte)'.';
   804                 continue;
   805             default:
   806                 signatureBuffer[sbp++] = c;
   807                 continue;
   808             }
   809         }
   810     }
   812     /** Convert (implicit) signature to list of types
   813      *  until `terminator' is encountered.
   814      */
   815     List<Type> sigToTypes(char terminator) {
   816         List<Type> head = List.of(null);
   817         List<Type> tail = head;
   818         while (signature[sigp] != terminator)
   819             tail = tail.setTail(List.of(sigToType()));
   820         sigp++;
   821         return head.tail;
   822     }
   824     /** Convert signature to type parameters, where signature is a byte
   825      *  array segment.
   826      */
   827     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   828         signature = sig;
   829         sigp = offset;
   830         siglimit = offset + len;
   831         return sigToTypeParams();
   832     }
   834     /** Convert signature to type parameters, where signature is implicit.
   835      */
   836     List<Type> sigToTypeParams() {
   837         List<Type> tvars = List.nil();
   838         if (signature[sigp] == '<') {
   839             sigp++;
   840             int start = sigp;
   841             sigEnterPhase = true;
   842             while (signature[sigp] != '>')
   843                 tvars = tvars.prepend(sigToTypeParam());
   844             sigEnterPhase = false;
   845             sigp = start;
   846             while (signature[sigp] != '>')
   847                 sigToTypeParam();
   848             sigp++;
   849         }
   850         return tvars.reverse();
   851     }
   853     /** Convert (implicit) signature to type parameter.
   854      */
   855     Type sigToTypeParam() {
   856         int start = sigp;
   857         while (signature[sigp] != ':') sigp++;
   858         Name name = names.fromUtf(signature, start, sigp - start);
   859         TypeVar tvar;
   860         if (sigEnterPhase) {
   861             tvar = new TypeVar(name, currentOwner, syms.botType);
   862             typevars.enter(tvar.tsym);
   863         } else {
   864             tvar = (TypeVar)findTypeVar(name);
   865         }
   866         List<Type> bounds = List.nil();
   867         boolean allInterfaces = false;
   868         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   869             sigp++;
   870             allInterfaces = true;
   871         }
   872         while (signature[sigp] == ':') {
   873             sigp++;
   874             bounds = bounds.prepend(sigToType());
   875         }
   876         if (!sigEnterPhase) {
   877             types.setBounds(tvar, bounds.reverse(), allInterfaces);
   878         }
   879         return tvar;
   880     }
   882     /** Find type variable with given name in `typevars' scope.
   883      */
   884     Type findTypeVar(Name name) {
   885         Scope.Entry e = typevars.lookup(name);
   886         if (e.scope != null) {
   887             return e.sym.type;
   888         } else {
   889             if (readingClassAttr) {
   890                 // While reading the class attribute, the supertypes
   891                 // might refer to a type variable from an enclosing element
   892                 // (method or class).
   893                 // If the type variable is defined in the enclosing class,
   894                 // we can actually find it in
   895                 // currentOwner.owner.type.getTypeArguments()
   896                 // However, until we have read the enclosing method attribute
   897                 // we don't know for sure if this owner is correct.  It could
   898                 // be a method and there is no way to tell before reading the
   899                 // enclosing method attribute.
   900                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   901                 missingTypeVariables = missingTypeVariables.prepend(t);
   902                 // System.err.println("Missing type var " + name);
   903                 return t;
   904             }
   905             throw badClassFile("undecl.type.var", name);
   906         }
   907     }
   909 /************************************************************************
   910  * Reading Attributes
   911  ***********************************************************************/
   913     protected enum AttributeKind { CLASS, MEMBER };
   914     protected abstract class AttributeReader {
   915         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   916             this.name = name;
   917             this.version = version;
   918             this.kinds = kinds;
   919         }
   921         protected boolean accepts(AttributeKind kind) {
   922             if (kinds.contains(kind)) {
   923                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   924                     return true;
   926                 if (lintClassfile && !warnedAttrs.contains(name)) {
   927                     JavaFileObject prev = log.useSource(currentClassFile);
   928                     try {
   929                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   930                                 name, version.major, version.minor, majorVersion, minorVersion);
   931                     } finally {
   932                         log.useSource(prev);
   933                     }
   934                     warnedAttrs.add(name);
   935                 }
   936             }
   937             return false;
   938         }
   940         protected abstract void read(Symbol sym, int attrLen);
   942         protected final Name name;
   943         protected final ClassFile.Version version;
   944         protected final Set<AttributeKind> kinds;
   945     }
   947     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   948             EnumSet.of(AttributeKind.CLASS);
   949     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   950             EnumSet.of(AttributeKind.MEMBER);
   951     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   952             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   954     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   956     private void initAttributeReaders() {
   957         AttributeReader[] readers = {
   958             // v45.3 attributes
   960             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   961                 protected void read(Symbol sym, int attrLen) {
   962                     if (readAllOfClassFile || saveParameterNames)
   963                         ((MethodSymbol)sym).code = readCode(sym);
   964                     else
   965                         bp = bp + attrLen;
   966                 }
   967             },
   969             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   970                 protected void read(Symbol sym, int attrLen) {
   971                     Object v = readPool(nextChar());
   972                     // Ignore ConstantValue attribute if field not final.
   973                     if ((sym.flags() & FINAL) != 0)
   974                         ((VarSymbol) sym).setData(v);
   975                 }
   976             },
   978             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   979                 protected void read(Symbol sym, int attrLen) {
   980                     sym.flags_field |= DEPRECATED;
   981                 }
   982             },
   984             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   985                 protected void read(Symbol sym, int attrLen) {
   986                     int nexceptions = nextChar();
   987                     List<Type> thrown = List.nil();
   988                     for (int j = 0; j < nexceptions; j++)
   989                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
   990                     if (sym.type.getThrownTypes().isEmpty())
   991                         sym.type.asMethodType().thrown = thrown.reverse();
   992                 }
   993             },
   995             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
   996                 protected void read(Symbol sym, int attrLen) {
   997                     ClassSymbol c = (ClassSymbol) sym;
   998                     readInnerClasses(c);
   999                 }
  1000             },
  1002             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1003                 protected void read(Symbol sym, int attrLen) {
  1004                     int newbp = bp + attrLen;
  1005                     if (saveParameterNames && !sawMethodParameters) {
  1006                         // Pick up parameter names from the variable table.
  1007                         // Parameter names are not explicitly identified as such,
  1008                         // but all parameter name entries in the LocalVariableTable
  1009                         // have a start_pc of 0.  Therefore, we record the name
  1010                         // indicies of all slots with a start_pc of zero in the
  1011                         // parameterNameIndicies array.
  1012                         // Note that this implicitly honors the JVMS spec that
  1013                         // there may be more than one LocalVariableTable, and that
  1014                         // there is no specified ordering for the entries.
  1015                         int numEntries = nextChar();
  1016                         for (int i = 0; i < numEntries; i++) {
  1017                             int start_pc = nextChar();
  1018                             int length = nextChar();
  1019                             int nameIndex = nextChar();
  1020                             int sigIndex = nextChar();
  1021                             int register = nextChar();
  1022                             if (start_pc == 0) {
  1023                                 // ensure array large enough
  1024                                 if (register >= parameterNameIndices.length) {
  1025                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1026                                     parameterNameIndices =
  1027                                             Arrays.copyOf(parameterNameIndices, newSize);
  1029                                 parameterNameIndices[register] = nameIndex;
  1030                                 haveParameterNameIndices = true;
  1034                     bp = newbp;
  1036             },
  1038             new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
  1039                 protected void read(Symbol sym, int attrlen) {
  1040                     int newbp = bp + attrlen;
  1041                     if (saveParameterNames) {
  1042                         sawMethodParameters = true;
  1043                         int numEntries = nextByte();
  1044                         parameterNameIndices = new int[numEntries];
  1045                         haveParameterNameIndices = true;
  1046                         for (int i = 0; i < numEntries; i++) {
  1047                             int nameIndex = nextChar();
  1048                             int flags = nextChar();
  1049                             parameterNameIndices[i] = nameIndex;
  1052                     bp = newbp;
  1054             },
  1057             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1058                 protected void read(Symbol sym, int attrLen) {
  1059                     ClassSymbol c = (ClassSymbol) sym;
  1060                     Name n = readName(nextChar());
  1061                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1062                     // If the class is a toplevel class, originating from a Java source file,
  1063                     // but the class name does not match the file name, then it is
  1064                     // an auxiliary class.
  1065                     String sn = n.toString();
  1066                     if (c.owner.kind == Kinds.PCK &&
  1067                         sn.endsWith(".java") &&
  1068                         !sn.equals(c.name.toString()+".java")) {
  1069                         c.flags_field |= AUXILIARY;
  1072             },
  1074             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1075                 protected void read(Symbol sym, int attrLen) {
  1076                     // bridge methods are visible when generics not enabled
  1077                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1078                         sym.flags_field |= SYNTHETIC;
  1080             },
  1082             // standard v49 attributes
  1084             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1085                 protected void read(Symbol sym, int attrLen) {
  1086                     int newbp = bp + attrLen;
  1087                     readEnclosingMethodAttr(sym);
  1088                     bp = newbp;
  1090             },
  1092             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1093                 @Override
  1094                 protected boolean accepts(AttributeKind kind) {
  1095                     return super.accepts(kind) && allowGenerics;
  1098                 protected void read(Symbol sym, int attrLen) {
  1099                     if (sym.kind == TYP) {
  1100                         ClassSymbol c = (ClassSymbol) sym;
  1101                         readingClassAttr = true;
  1102                         try {
  1103                             ClassType ct1 = (ClassType)c.type;
  1104                             Assert.check(c == currentOwner);
  1105                             ct1.typarams_field = readTypeParams(nextChar());
  1106                             ct1.supertype_field = sigToType();
  1107                             ListBuffer<Type> is = new ListBuffer<Type>();
  1108                             while (sigp != siglimit) is.append(sigToType());
  1109                             ct1.interfaces_field = is.toList();
  1110                         } finally {
  1111                             readingClassAttr = false;
  1113                     } else {
  1114                         List<Type> thrown = sym.type.getThrownTypes();
  1115                         sym.type = readType(nextChar());
  1116                         //- System.err.println(" # " + sym.type);
  1117                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1118                             sym.type.asMethodType().thrown = thrown;
  1122             },
  1124             // v49 annotation attributes
  1126             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1127                 protected void read(Symbol sym, int attrLen) {
  1128                     attachAnnotationDefault(sym);
  1130             },
  1132             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1133                 protected void read(Symbol sym, int attrLen) {
  1134                     attachAnnotations(sym);
  1136             },
  1138             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1139                 protected void read(Symbol sym, int attrLen) {
  1140                     attachParameterAnnotations(sym);
  1142             },
  1144             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1145                 protected void read(Symbol sym, int attrLen) {
  1146                     attachAnnotations(sym);
  1148             },
  1150             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1151                 protected void read(Symbol sym, int attrLen) {
  1152                     attachParameterAnnotations(sym);
  1154             },
  1156             // additional "legacy" v49 attributes, superceded by flags
  1158             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1159                 protected void read(Symbol sym, int attrLen) {
  1160                     if (allowAnnotations)
  1161                         sym.flags_field |= ANNOTATION;
  1163             },
  1165             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1166                 protected void read(Symbol sym, int attrLen) {
  1167                     sym.flags_field |= BRIDGE;
  1168                     if (!allowGenerics)
  1169                         sym.flags_field &= ~SYNTHETIC;
  1171             },
  1173             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1174                 protected void read(Symbol sym, int attrLen) {
  1175                     sym.flags_field |= ENUM;
  1177             },
  1179             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1180                 protected void read(Symbol sym, int attrLen) {
  1181                     if (allowVarargs)
  1182                         sym.flags_field |= VARARGS;
  1184             },
  1186             new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1187                 protected void read(Symbol sym, int attrLen) {
  1188                     attachTypeAnnotations(sym);
  1190             },
  1192             new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1193                 protected void read(Symbol sym, int attrLen) {
  1194                     attachTypeAnnotations(sym);
  1196             },
  1199             // The following attributes for a Code attribute are not currently handled
  1200             // StackMapTable
  1201             // SourceDebugExtension
  1202             // LineNumberTable
  1203             // LocalVariableTypeTable
  1204         };
  1206         for (AttributeReader r: readers)
  1207             attributeReaders.put(r.name, r);
  1210     /** Report unrecognized attribute.
  1211      */
  1212     void unrecognized(Name attrName) {
  1213         if (checkClassFile)
  1214             printCCF("ccf.unrecognized.attribute", attrName);
  1219     protected void readEnclosingMethodAttr(Symbol sym) {
  1220         // sym is a nested class with an "Enclosing Method" attribute
  1221         // remove sym from it's current owners scope and place it in
  1222         // the scope specified by the attribute
  1223         sym.owner.members().remove(sym);
  1224         ClassSymbol self = (ClassSymbol)sym;
  1225         ClassSymbol c = readClassSymbol(nextChar());
  1226         NameAndType nt = (NameAndType)readPool(nextChar());
  1228         if (c.members_field == null)
  1229             throw badClassFile("bad.enclosing.class", self, c);
  1231         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1232         if (nt != null && m == null)
  1233             throw badClassFile("bad.enclosing.method", self);
  1235         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1236         self.owner = m != null ? m : c;
  1237         if (self.name.isEmpty())
  1238             self.fullname = names.empty;
  1239         else
  1240             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1242         if (m != null) {
  1243             ((ClassType)sym.type).setEnclosingType(m.type);
  1244         } else if ((self.flags_field & STATIC) == 0) {
  1245             ((ClassType)sym.type).setEnclosingType(c.type);
  1246         } else {
  1247             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1249         enterTypevars(self);
  1250         if (!missingTypeVariables.isEmpty()) {
  1251             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1252             for (Type typevar : missingTypeVariables) {
  1253                 typeVars.append(findTypeVar(typevar.tsym.name));
  1255             foundTypeVariables = typeVars.toList();
  1256         } else {
  1257             foundTypeVariables = List.nil();
  1261     // See java.lang.Class
  1262     private Name simpleBinaryName(Name self, Name enclosing) {
  1263         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1264         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1265             throw badClassFile("bad.enclosing.method", self);
  1266         int index = 1;
  1267         while (index < simpleBinaryName.length() &&
  1268                isAsciiDigit(simpleBinaryName.charAt(index)))
  1269             index++;
  1270         return names.fromString(simpleBinaryName.substring(index));
  1273     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1274         if (nt == null)
  1275             return null;
  1277         MethodType type = nt.uniqueType.type.asMethodType();
  1279         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1280             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1281                 return (MethodSymbol)e.sym;
  1283         if (nt.name != names.init)
  1284             // not a constructor
  1285             return null;
  1286         if ((flags & INTERFACE) != 0)
  1287             // no enclosing instance
  1288             return null;
  1289         if (nt.uniqueType.type.getParameterTypes().isEmpty())
  1290             // no parameters
  1291             return null;
  1293         // A constructor of an inner class.
  1294         // Remove the first argument (the enclosing instance)
  1295         nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
  1296                                  nt.uniqueType.type.getReturnType(),
  1297                                  nt.uniqueType.type.getThrownTypes(),
  1298                                  syms.methodClass));
  1299         // Try searching again
  1300         return findMethod(nt, scope, flags);
  1303     /** Similar to Types.isSameType but avoids completion */
  1304     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1305         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1306             .prepend(types.erasure(mt1.getReturnType()));
  1307         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1308         while (!types1.isEmpty() && !types2.isEmpty()) {
  1309             if (types1.head.tsym != types2.head.tsym)
  1310                 return false;
  1311             types1 = types1.tail;
  1312             types2 = types2.tail;
  1314         return types1.isEmpty() && types2.isEmpty();
  1317     /**
  1318      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1319      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1320      */
  1321     private static boolean isAsciiDigit(char c) {
  1322         return '0' <= c && c <= '9';
  1325     /** Read member attributes.
  1326      */
  1327     void readMemberAttrs(Symbol sym) {
  1328         readAttrs(sym, AttributeKind.MEMBER);
  1331     void readAttrs(Symbol sym, AttributeKind kind) {
  1332         char ac = nextChar();
  1333         for (int i = 0; i < ac; i++) {
  1334             Name attrName = readName(nextChar());
  1335             int attrLen = nextInt();
  1336             AttributeReader r = attributeReaders.get(attrName);
  1337             if (r != null && r.accepts(kind))
  1338                 r.read(sym, attrLen);
  1339             else  {
  1340                 unrecognized(attrName);
  1341                 bp = bp + attrLen;
  1346     private boolean readingClassAttr = false;
  1347     private List<Type> missingTypeVariables = List.nil();
  1348     private List<Type> foundTypeVariables = List.nil();
  1350     /** Read class attributes.
  1351      */
  1352     void readClassAttrs(ClassSymbol c) {
  1353         readAttrs(c, AttributeKind.CLASS);
  1356     /** Read code block.
  1357      */
  1358     Code readCode(Symbol owner) {
  1359         nextChar(); // max_stack
  1360         nextChar(); // max_locals
  1361         final int  code_length = nextInt();
  1362         bp += code_length;
  1363         final char exception_table_length = nextChar();
  1364         bp += exception_table_length * 8;
  1365         readMemberAttrs(owner);
  1366         return null;
  1369 /************************************************************************
  1370  * Reading Java-language annotations
  1371  ***********************************************************************/
  1373     /** Attach annotations.
  1374      */
  1375     void attachAnnotations(final Symbol sym) {
  1376         int numAttributes = nextChar();
  1377         if (numAttributes != 0) {
  1378             ListBuffer<CompoundAnnotationProxy> proxies =
  1379                 new ListBuffer<CompoundAnnotationProxy>();
  1380             for (int i = 0; i<numAttributes; i++) {
  1381                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1382                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1383                     sym.flags_field |= PROPRIETARY;
  1384                 else if (proxy.type.tsym == syms.profileType.tsym) {
  1385                     if (profile != Profile.DEFAULT) {
  1386                         for (Pair<Name,Attribute> v: proxy.values) {
  1387                             if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
  1388                                 Attribute.Constant c = (Attribute.Constant) v.snd;
  1389                                 if (c.type == syms.intType && ((Integer) c.value) > profile.value) {
  1390                                     sym.flags_field |= NOT_IN_PROFILE;
  1395                 } else
  1396                     proxies.append(proxy);
  1398             annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
  1402     /** Attach parameter annotations.
  1403      */
  1404     void attachParameterAnnotations(final Symbol method) {
  1405         final MethodSymbol meth = (MethodSymbol)method;
  1406         int numParameters = buf[bp++] & 0xFF;
  1407         List<VarSymbol> parameters = meth.params();
  1408         int pnum = 0;
  1409         while (parameters.tail != null) {
  1410             attachAnnotations(parameters.head);
  1411             parameters = parameters.tail;
  1412             pnum++;
  1414         if (pnum != numParameters) {
  1415             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1419     void attachTypeAnnotations(final Symbol sym) {
  1420         int numAttributes = nextChar();
  1421         if (numAttributes != 0) {
  1422             ListBuffer<TypeAnnotationProxy> proxies =
  1423                 ListBuffer.lb();
  1424             for (int i = 0; i < numAttributes; i++)
  1425                 proxies.append(readTypeAnnotation());
  1426             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
  1430     /** Attach the default value for an annotation element.
  1431      */
  1432     void attachAnnotationDefault(final Symbol sym) {
  1433         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1434         final Attribute value = readAttributeValue();
  1436         // The default value is set later during annotation. It might
  1437         // be the case that the Symbol sym is annotated _after_ the
  1438         // repeating instances that depend on this default value,
  1439         // because of this we set an interim value that tells us this
  1440         // element (most likely) has a default.
  1441         //
  1442         // Set interim value for now, reset just before we do this
  1443         // properly at annotate time.
  1444         meth.defaultValue = value;
  1445         annotate.normal(new AnnotationDefaultCompleter(meth, value));
  1448     Type readTypeOrClassSymbol(int i) {
  1449         // support preliminary jsr175-format class files
  1450         if (buf[poolIdx[i]] == CONSTANT_Class)
  1451             return readClassSymbol(i).type;
  1452         return readType(i);
  1454     Type readEnumType(int i) {
  1455         // support preliminary jsr175-format class files
  1456         int index = poolIdx[i];
  1457         int length = getChar(index + 1);
  1458         if (buf[index + length + 2] != ';')
  1459             return enterClass(readName(i)).type;
  1460         return readType(i);
  1463     CompoundAnnotationProxy readCompoundAnnotation() {
  1464         Type t = readTypeOrClassSymbol(nextChar());
  1465         int numFields = nextChar();
  1466         ListBuffer<Pair<Name,Attribute>> pairs =
  1467             new ListBuffer<Pair<Name,Attribute>>();
  1468         for (int i=0; i<numFields; i++) {
  1469             Name name = readName(nextChar());
  1470             Attribute value = readAttributeValue();
  1471             pairs.append(new Pair<Name,Attribute>(name, value));
  1473         return new CompoundAnnotationProxy(t, pairs.toList());
  1476     TypeAnnotationProxy readTypeAnnotation() {
  1477         TypeAnnotationPosition position = readPosition();
  1478         CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1480         return new TypeAnnotationProxy(proxy, position);
  1483     TypeAnnotationPosition readPosition() {
  1484         int tag = nextByte(); // TargetType tag is a byte
  1486         if (!TargetType.isValidTargetTypeValue(tag))
  1487             throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
  1489         TypeAnnotationPosition position = new TypeAnnotationPosition();
  1490         TargetType type = TargetType.fromTargetTypeValue(tag);
  1492         position.type = type;
  1494         switch (type) {
  1495         // instanceof
  1496         case INSTANCEOF:
  1497         // new expression
  1498         case NEW:
  1499         // constructor/method reference receiver
  1500         case CONSTRUCTOR_REFERENCE:
  1501         case METHOD_REFERENCE:
  1502             position.offset = nextChar();
  1503             break;
  1504         // local variable
  1505         case LOCAL_VARIABLE:
  1506         // resource variable
  1507         case RESOURCE_VARIABLE:
  1508             int table_length = nextChar();
  1509             position.lvarOffset = new int[table_length];
  1510             position.lvarLength = new int[table_length];
  1511             position.lvarIndex = new int[table_length];
  1513             for (int i = 0; i < table_length; ++i) {
  1514                 position.lvarOffset[i] = nextChar();
  1515                 position.lvarLength[i] = nextChar();
  1516                 position.lvarIndex[i] = nextChar();
  1518             break;
  1519         // exception parameter
  1520         case EXCEPTION_PARAMETER:
  1521             position.exception_index = nextByte();
  1522             break;
  1523         // method receiver
  1524         case METHOD_RECEIVER:
  1525             // Do nothing
  1526             break;
  1527         // type parameter
  1528         case CLASS_TYPE_PARAMETER:
  1529         case METHOD_TYPE_PARAMETER:
  1530             position.parameter_index = nextByte();
  1531             break;
  1532         // type parameter bound
  1533         case CLASS_TYPE_PARAMETER_BOUND:
  1534         case METHOD_TYPE_PARAMETER_BOUND:
  1535             position.parameter_index = nextByte();
  1536             position.bound_index = nextByte();
  1537             break;
  1538         // class extends or implements clause
  1539         case CLASS_EXTENDS:
  1540             position.type_index = nextChar();
  1541             break;
  1542         // throws
  1543         case THROWS:
  1544             position.type_index = nextChar();
  1545             break;
  1546         // method parameter
  1547         case METHOD_FORMAL_PARAMETER:
  1548             position.parameter_index = nextByte();
  1549             break;
  1550         // type cast
  1551         case CAST:
  1552         // method/constructor/reference type argument
  1553         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
  1554         case METHOD_INVOCATION_TYPE_ARGUMENT:
  1555         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
  1556         case METHOD_REFERENCE_TYPE_ARGUMENT:
  1557             position.offset = nextChar();
  1558             position.type_index = nextByte();
  1559             break;
  1560         // We don't need to worry about these
  1561         case METHOD_RETURN:
  1562         case FIELD:
  1563             break;
  1564         case UNKNOWN:
  1565             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
  1566         default:
  1567             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
  1570         { // See whether there is location info and read it
  1571             int len = nextByte();
  1572             ListBuffer<Integer> loc = ListBuffer.lb();
  1573             for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
  1574                 loc = loc.append(nextByte());
  1575             position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
  1578         return position;
  1581     Attribute readAttributeValue() {
  1582         char c = (char) buf[bp++];
  1583         switch (c) {
  1584         case 'B':
  1585             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1586         case 'C':
  1587             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1588         case 'D':
  1589             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1590         case 'F':
  1591             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1592         case 'I':
  1593             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1594         case 'J':
  1595             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1596         case 'S':
  1597             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1598         case 'Z':
  1599             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1600         case 's':
  1601             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1602         case 'e':
  1603             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1604         case 'c':
  1605             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1606         case '[': {
  1607             int n = nextChar();
  1608             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1609             for (int i=0; i<n; i++)
  1610                 l.append(readAttributeValue());
  1611             return new ArrayAttributeProxy(l.toList());
  1613         case '@':
  1614             return readCompoundAnnotation();
  1615         default:
  1616             throw new AssertionError("unknown annotation tag '" + c + "'");
  1620     interface ProxyVisitor extends Attribute.Visitor {
  1621         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1622         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1623         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1626     static class EnumAttributeProxy extends Attribute {
  1627         Type enumType;
  1628         Name enumerator;
  1629         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1630             super(null);
  1631             this.enumType = enumType;
  1632             this.enumerator = enumerator;
  1634         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1635         @Override
  1636         public String toString() {
  1637             return "/*proxy enum*/" + enumType + "." + enumerator;
  1641     static class ArrayAttributeProxy extends Attribute {
  1642         List<Attribute> values;
  1643         ArrayAttributeProxy(List<Attribute> values) {
  1644             super(null);
  1645             this.values = values;
  1647         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1648         @Override
  1649         public String toString() {
  1650             return "{" + values + "}";
  1654     /** A temporary proxy representing a compound attribute.
  1655      */
  1656     static class CompoundAnnotationProxy extends Attribute {
  1657         final List<Pair<Name,Attribute>> values;
  1658         public CompoundAnnotationProxy(Type type,
  1659                                       List<Pair<Name,Attribute>> values) {
  1660             super(type);
  1661             this.values = values;
  1663         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1664         @Override
  1665         public String toString() {
  1666             StringBuilder buf = new StringBuilder();
  1667             buf.append("@");
  1668             buf.append(type.tsym.getQualifiedName());
  1669             buf.append("/*proxy*/{");
  1670             boolean first = true;
  1671             for (List<Pair<Name,Attribute>> v = values;
  1672                  v.nonEmpty(); v = v.tail) {
  1673                 Pair<Name,Attribute> value = v.head;
  1674                 if (!first) buf.append(",");
  1675                 first = false;
  1676                 buf.append(value.fst);
  1677                 buf.append("=");
  1678                 buf.append(value.snd);
  1680             buf.append("}");
  1681             return buf.toString();
  1685     /** A temporary proxy representing a type annotation.
  1686      */
  1687     static class TypeAnnotationProxy {
  1688         final CompoundAnnotationProxy compound;
  1689         final TypeAnnotationPosition position;
  1690         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1691                 TypeAnnotationPosition position) {
  1692             this.compound = compound;
  1693             this.position = position;
  1697     class AnnotationDeproxy implements ProxyVisitor {
  1698         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1699             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1701         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1702             // also must fill in types!!!!
  1703             ListBuffer<Attribute.Compound> buf =
  1704                 new ListBuffer<Attribute.Compound>();
  1705             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1706                 buf.append(deproxyCompound(l.head));
  1708             return buf.toList();
  1711         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1712             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1713                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1714             for (List<Pair<Name,Attribute>> l = a.values;
  1715                  l.nonEmpty();
  1716                  l = l.tail) {
  1717                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1718                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1719                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1721             return new Attribute.Compound(a.type, buf.toList());
  1724         MethodSymbol findAccessMethod(Type container, Name name) {
  1725             CompletionFailure failure = null;
  1726             try {
  1727                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1728                      e.scope != null;
  1729                      e = e.next()) {
  1730                     Symbol sym = e.sym;
  1731                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1732                         return (MethodSymbol) sym;
  1734             } catch (CompletionFailure ex) {
  1735                 failure = ex;
  1737             // The method wasn't found: emit a warning and recover
  1738             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1739             try {
  1740                 if (failure == null) {
  1741                     log.warning("annotation.method.not.found",
  1742                                 container,
  1743                                 name);
  1744                 } else {
  1745                     log.warning("annotation.method.not.found.reason",
  1746                                 container,
  1747                                 name,
  1748                                 failure.getDetailValue());//diagnostic, if present
  1750             } finally {
  1751                 log.useSource(prevSource);
  1753             // Construct a new method type and symbol.  Use bottom
  1754             // type (typeof null) as return type because this type is
  1755             // a subtype of all reference types and can be converted
  1756             // to primitive types by unboxing.
  1757             MethodType mt = new MethodType(List.<Type>nil(),
  1758                                            syms.botType,
  1759                                            List.<Type>nil(),
  1760                                            syms.methodClass);
  1761             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1764         Attribute result;
  1765         Type type;
  1766         Attribute deproxy(Type t, Attribute a) {
  1767             Type oldType = type;
  1768             try {
  1769                 type = t;
  1770                 a.accept(this);
  1771                 return result;
  1772             } finally {
  1773                 type = oldType;
  1777         // implement Attribute.Visitor below
  1779         public void visitConstant(Attribute.Constant value) {
  1780             // assert value.type == type;
  1781             result = value;
  1784         public void visitClass(Attribute.Class clazz) {
  1785             result = clazz;
  1788         public void visitEnum(Attribute.Enum e) {
  1789             throw new AssertionError(); // shouldn't happen
  1792         public void visitCompound(Attribute.Compound compound) {
  1793             throw new AssertionError(); // shouldn't happen
  1796         public void visitArray(Attribute.Array array) {
  1797             throw new AssertionError(); // shouldn't happen
  1800         public void visitError(Attribute.Error e) {
  1801             throw new AssertionError(); // shouldn't happen
  1804         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1805             // type.tsym.flatName() should == proxy.enumFlatName
  1806             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1807             VarSymbol enumerator = null;
  1808             CompletionFailure failure = null;
  1809             try {
  1810                 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1811                      e.scope != null;
  1812                      e = e.next()) {
  1813                     if (e.sym.kind == VAR) {
  1814                         enumerator = (VarSymbol)e.sym;
  1815                         break;
  1819             catch (CompletionFailure ex) {
  1820                 failure = ex;
  1822             if (enumerator == null) {
  1823                 if (failure != null) {
  1824                     log.warning("unknown.enum.constant.reason",
  1825                               currentClassFile, enumTypeSym, proxy.enumerator,
  1826                               failure.getDiagnostic());
  1827                 } else {
  1828                     log.warning("unknown.enum.constant",
  1829                               currentClassFile, enumTypeSym, proxy.enumerator);
  1831                 result = new Attribute.Enum(enumTypeSym.type,
  1832                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
  1833             } else {
  1834                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1838         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1839             int length = proxy.values.length();
  1840             Attribute[] ats = new Attribute[length];
  1841             Type elemtype = types.elemtype(type);
  1842             int i = 0;
  1843             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1844                 ats[i++] = deproxy(elemtype, p.head);
  1846             result = new Attribute.Array(type, ats);
  1849         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1850             result = deproxyCompound(proxy);
  1854     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1855         final MethodSymbol sym;
  1856         final Attribute value;
  1857         final JavaFileObject classFile = currentClassFile;
  1858         @Override
  1859         public String toString() {
  1860             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1862         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1863             this.sym = sym;
  1864             this.value = value;
  1866         // implement Annotate.Annotator.enterAnnotation()
  1867         public void enterAnnotation() {
  1868             JavaFileObject previousClassFile = currentClassFile;
  1869             try {
  1870                 // Reset the interim value set earlier in
  1871                 // attachAnnotationDefault().
  1872                 sym.defaultValue = null;
  1873                 currentClassFile = classFile;
  1874                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1875             } finally {
  1876                 currentClassFile = previousClassFile;
  1881     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1882         final Symbol sym;
  1883         final List<CompoundAnnotationProxy> l;
  1884         final JavaFileObject classFile;
  1885         @Override
  1886         public String toString() {
  1887             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1889         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1890             this.sym = sym;
  1891             this.l = l;
  1892             this.classFile = currentClassFile;
  1894         // implement Annotate.Annotator.enterAnnotation()
  1895         public void enterAnnotation() {
  1896             JavaFileObject previousClassFile = currentClassFile;
  1897             try {
  1898                 currentClassFile = classFile;
  1899                 Annotations annotations = sym.annotations;
  1900                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1901                 if (annotations.pendingCompletion()) {
  1902                     annotations.setDeclarationAttributes(newList);
  1903                 } else {
  1904                     annotations.append(newList);
  1906             } finally {
  1907                 currentClassFile = previousClassFile;
  1912     class TypeAnnotationCompleter extends AnnotationCompleter {
  1914         List<TypeAnnotationProxy> proxies;
  1916         TypeAnnotationCompleter(Symbol sym,
  1917                 List<TypeAnnotationProxy> proxies) {
  1918             super(sym, List.<CompoundAnnotationProxy>nil());
  1919             this.proxies = proxies;
  1922         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
  1923             ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
  1924             for (TypeAnnotationProxy proxy: proxies) {
  1925                 Attribute.Compound compound = deproxyCompound(proxy.compound);
  1926                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
  1927                 buf.add(typeCompound);
  1929             return buf.toList();
  1932         @Override
  1933         public void enterAnnotation() {
  1934             JavaFileObject previousClassFile = currentClassFile;
  1935             try {
  1936                 currentClassFile = classFile;
  1937                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
  1938                 sym.annotations.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
  1939             } finally {
  1940                 currentClassFile = previousClassFile;
  1946 /************************************************************************
  1947  * Reading Symbols
  1948  ***********************************************************************/
  1950     /** Read a field.
  1951      */
  1952     VarSymbol readField() {
  1953         long flags = adjustFieldFlags(nextChar());
  1954         Name name = readName(nextChar());
  1955         Type type = readType(nextChar());
  1956         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1957         readMemberAttrs(v);
  1958         return v;
  1961     /** Read a method.
  1962      */
  1963     MethodSymbol readMethod() {
  1964         long flags = adjustMethodFlags(nextChar());
  1965         Name name = readName(nextChar());
  1966         Type type = readType(nextChar());
  1967         if (currentOwner.isInterface() &&
  1968                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
  1969             if (majorVersion > Target.JDK1_8.majorVersion ||
  1970                     (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
  1971                 currentOwner.flags_field |= DEFAULT;
  1972                 flags |= DEFAULT | ABSTRACT;
  1973             } else {
  1974                 //protect against ill-formed classfiles
  1975                 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
  1978         if (name == names.init && currentOwner.hasOuterInstance()) {
  1979             // Sometimes anonymous classes don't have an outer
  1980             // instance, however, there is no reliable way to tell so
  1981             // we never strip this$n
  1982             if (!currentOwner.name.isEmpty())
  1983                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  1984                                       type.getReturnType(),
  1985                                       type.getThrownTypes(),
  1986                                       syms.methodClass);
  1988         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  1989         if (saveParameterNames)
  1990             initParameterNames(m);
  1991         Symbol prevOwner = currentOwner;
  1992         currentOwner = m;
  1993         try {
  1994             readMemberAttrs(m);
  1995         } finally {
  1996             currentOwner = prevOwner;
  1998         if (saveParameterNames)
  1999             setParameterNames(m, type);
  2000         return m;
  2003     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  2004         boolean isVarargs = (flags & VARARGS) != 0;
  2005         if (isVarargs) {
  2006             Type varargsElem = args.last();
  2007             ListBuffer<Type> adjustedArgs = ListBuffer.lb();
  2008             for (Type t : args) {
  2009                 adjustedArgs.append(t != varargsElem ?
  2010                     t :
  2011                     ((ArrayType)t).makeVarargs());
  2013             args = adjustedArgs.toList();
  2015         return args.tail;
  2018     /**
  2019      * Init the parameter names array.
  2020      * Parameter names are currently inferred from the names in the
  2021      * LocalVariableTable attributes of a Code attribute.
  2022      * (Note: this means parameter names are currently not available for
  2023      * methods without a Code attribute.)
  2024      * This method initializes an array in which to store the name indexes
  2025      * of parameter names found in LocalVariableTable attributes. It is
  2026      * slightly supersized to allow for additional slots with a start_pc of 0.
  2027      */
  2028     void initParameterNames(MethodSymbol sym) {
  2029         // make allowance for synthetic parameters.
  2030         final int excessSlots = 4;
  2031         int expectedParameterSlots =
  2032                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  2033         if (parameterNameIndices == null
  2034                 || parameterNameIndices.length < expectedParameterSlots) {
  2035             parameterNameIndices = new int[expectedParameterSlots];
  2036         } else
  2037             Arrays.fill(parameterNameIndices, 0);
  2038         haveParameterNameIndices = false;
  2039         sawMethodParameters = false;
  2042     /**
  2043      * Set the parameter names for a symbol from the name index in the
  2044      * parameterNameIndicies array. The type of the symbol may have changed
  2045      * while reading the method attributes (see the Signature attribute).
  2046      * This may be because of generic information or because anonymous
  2047      * synthetic parameters were added.   The original type (as read from
  2048      * the method descriptor) is used to help guess the existence of
  2049      * anonymous synthetic parameters.
  2050      * On completion, sym.savedParameter names will either be null (if
  2051      * no parameter names were found in the class file) or will be set to a
  2052      * list of names, one per entry in sym.type.getParameterTypes, with
  2053      * any missing names represented by the empty name.
  2054      */
  2055     void setParameterNames(MethodSymbol sym, Type jvmType) {
  2056         // if no names were found in the class file, there's nothing more to do
  2057         if (!haveParameterNameIndices)
  2058             return;
  2059         // If we get parameter names from MethodParameters, then we
  2060         // don't need to skip.
  2061         int firstParam = 0;
  2062         if (!sawMethodParameters) {
  2063             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  2064             // the code in readMethod may have skipped the first
  2065             // parameter when setting up the MethodType. If so, we
  2066             // make a corresponding allowance here for the position of
  2067             // the first parameter.  Note that this assumes the
  2068             // skipped parameter has a width of 1 -- i.e. it is not
  2069         // a double width type (long or double.)
  2070         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  2071             // Sometimes anonymous classes don't have an outer
  2072             // instance, however, there is no reliable way to tell so
  2073             // we never strip this$n
  2074             if (!currentOwner.name.isEmpty())
  2075                 firstParam += 1;
  2078         if (sym.type != jvmType) {
  2079                 // reading the method attributes has caused the
  2080                 // symbol's type to be changed. (i.e. the Signature
  2081                 // attribute.)  This may happen if there are hidden
  2082                 // (synthetic) parameters in the descriptor, but not
  2083                 // in the Signature.  The position of these hidden
  2084                 // parameters is unspecified; for now, assume they are
  2085                 // at the beginning, and so skip over them. The
  2086                 // primary case for this is two hidden parameters
  2087                 // passed into Enum constructors.
  2088             int skip = Code.width(jvmType.getParameterTypes())
  2089                     - Code.width(sym.type.getParameterTypes());
  2090             firstParam += skip;
  2093         List<Name> paramNames = List.nil();
  2094         int index = firstParam;
  2095         for (Type t: sym.type.getParameterTypes()) {
  2096             int nameIdx = (index < parameterNameIndices.length
  2097                     ? parameterNameIndices[index] : 0);
  2098             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  2099             paramNames = paramNames.prepend(name);
  2100             index += Code.width(t);
  2102         sym.savedParameterNames = paramNames.reverse();
  2105     /**
  2106      * skip n bytes
  2107      */
  2108     void skipBytes(int n) {
  2109         bp = bp + n;
  2112     /** Skip a field or method
  2113      */
  2114     void skipMember() {
  2115         bp = bp + 6;
  2116         char ac = nextChar();
  2117         for (int i = 0; i < ac; i++) {
  2118             bp = bp + 2;
  2119             int attrLen = nextInt();
  2120             bp = bp + attrLen;
  2124     /** Enter type variables of this classtype and all enclosing ones in
  2125      *  `typevars'.
  2126      */
  2127     protected void enterTypevars(Type t) {
  2128         if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
  2129             enterTypevars(t.getEnclosingType());
  2130         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  2131             typevars.enter(xs.head.tsym);
  2134     protected void enterTypevars(Symbol sym) {
  2135         if (sym.owner.kind == MTH) {
  2136             enterTypevars(sym.owner);
  2137             enterTypevars(sym.owner.owner);
  2139         enterTypevars(sym.type);
  2142     /** Read contents of a given class symbol `c'. Both external and internal
  2143      *  versions of an inner class are read.
  2144      */
  2145     void readClass(ClassSymbol c) {
  2146         ClassType ct = (ClassType)c.type;
  2148         // allocate scope for members
  2149         c.members_field = new Scope(c);
  2151         // prepare type variable table
  2152         typevars = typevars.dup(currentOwner);
  2153         if (ct.getEnclosingType().hasTag(CLASS))
  2154             enterTypevars(ct.getEnclosingType());
  2156         // read flags, or skip if this is an inner class
  2157         long flags = adjustClassFlags(nextChar());
  2158         if (c.owner.kind == PCK) c.flags_field = flags;
  2160         // read own class name and check that it matches
  2161         ClassSymbol self = readClassSymbol(nextChar());
  2162         if (c != self)
  2163             throw badClassFile("class.file.wrong.class",
  2164                                self.flatname);
  2166         // class attributes must be read before class
  2167         // skip ahead to read class attributes
  2168         int startbp = bp;
  2169         nextChar();
  2170         char interfaceCount = nextChar();
  2171         bp += interfaceCount * 2;
  2172         char fieldCount = nextChar();
  2173         for (int i = 0; i < fieldCount; i++) skipMember();
  2174         char methodCount = nextChar();
  2175         for (int i = 0; i < methodCount; i++) skipMember();
  2176         readClassAttrs(c);
  2178         if (readAllOfClassFile) {
  2179             for (int i = 1; i < poolObj.length; i++) readPool(i);
  2180             c.pool = new Pool(poolObj.length, poolObj, types);
  2183         // reset and read rest of classinfo
  2184         bp = startbp;
  2185         int n = nextChar();
  2186         if (ct.supertype_field == null)
  2187             ct.supertype_field = (n == 0)
  2188                 ? Type.noType
  2189                 : readClassSymbol(n).erasure(types);
  2190         n = nextChar();
  2191         List<Type> is = List.nil();
  2192         for (int i = 0; i < n; i++) {
  2193             Type _inter = readClassSymbol(nextChar()).erasure(types);
  2194             is = is.prepend(_inter);
  2196         if (ct.interfaces_field == null)
  2197             ct.interfaces_field = is.reverse();
  2199         Assert.check(fieldCount == nextChar());
  2200         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  2201         Assert.check(methodCount == nextChar());
  2202         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  2204         typevars = typevars.leave();
  2207     /** Read inner class info. For each inner/outer pair allocate a
  2208      *  member class.
  2209      */
  2210     void readInnerClasses(ClassSymbol c) {
  2211         int n = nextChar();
  2212         for (int i = 0; i < n; i++) {
  2213             nextChar(); // skip inner class symbol
  2214             ClassSymbol outer = readClassSymbol(nextChar());
  2215             Name name = readName(nextChar());
  2216             if (name == null) name = names.empty;
  2217             long flags = adjustClassFlags(nextChar());
  2218             if (outer != null) { // we have a member class
  2219                 if (name == names.empty)
  2220                     name = names.one;
  2221                 ClassSymbol member = enterClass(name, outer);
  2222                 if ((flags & STATIC) == 0) {
  2223                     ((ClassType)member.type).setEnclosingType(outer.type);
  2224                     if (member.erasure_field != null)
  2225                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  2227                 if (c == outer) {
  2228                     member.flags_field = flags;
  2229                     enterMember(c, member);
  2235     /** Read a class file.
  2236      */
  2237     private void readClassFile(ClassSymbol c) throws IOException {
  2238         int magic = nextInt();
  2239         if (magic != JAVA_MAGIC)
  2240             throw badClassFile("illegal.start.of.class.file");
  2242         minorVersion = nextChar();
  2243         majorVersion = nextChar();
  2244         int maxMajor = Target.MAX().majorVersion;
  2245         int maxMinor = Target.MAX().minorVersion;
  2246         if (majorVersion > maxMajor ||
  2247             majorVersion * 1000 + minorVersion <
  2248             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  2250             if (majorVersion == (maxMajor + 1))
  2251                 log.warning("big.major.version",
  2252                             currentClassFile,
  2253                             majorVersion,
  2254                             maxMajor);
  2255             else
  2256                 throw badClassFile("wrong.version",
  2257                                    Integer.toString(majorVersion),
  2258                                    Integer.toString(minorVersion),
  2259                                    Integer.toString(maxMajor),
  2260                                    Integer.toString(maxMinor));
  2262         else if (checkClassFile &&
  2263                  majorVersion == maxMajor &&
  2264                  minorVersion > maxMinor)
  2266             printCCF("found.later.version",
  2267                      Integer.toString(minorVersion));
  2269         indexPool();
  2270         if (signatureBuffer.length < bp) {
  2271             int ns = Integer.highestOneBit(bp) << 1;
  2272             signatureBuffer = new byte[ns];
  2274         readClass(c);
  2277 /************************************************************************
  2278  * Adjusting flags
  2279  ***********************************************************************/
  2281     long adjustFieldFlags(long flags) {
  2282         return flags;
  2284     long adjustMethodFlags(long flags) {
  2285         if ((flags & ACC_BRIDGE) != 0) {
  2286             flags &= ~ACC_BRIDGE;
  2287             flags |= BRIDGE;
  2288             if (!allowGenerics)
  2289                 flags &= ~SYNTHETIC;
  2291         if ((flags & ACC_VARARGS) != 0) {
  2292             flags &= ~ACC_VARARGS;
  2293             flags |= VARARGS;
  2295         return flags;
  2297     long adjustClassFlags(long flags) {
  2298         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2301 /************************************************************************
  2302  * Loading Classes
  2303  ***********************************************************************/
  2305     /** Define a new class given its name and owner.
  2306      */
  2307     public ClassSymbol defineClass(Name name, Symbol owner) {
  2308         ClassSymbol c = new ClassSymbol(0, name, owner);
  2309         if (owner.kind == PCK)
  2310             Assert.checkNull(classes.get(c.flatname), c);
  2311         c.completer = this;
  2312         return c;
  2315     /** Create a new toplevel or member class symbol with given name
  2316      *  and owner and enter in `classes' unless already there.
  2317      */
  2318     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2319         Name flatname = TypeSymbol.formFlatName(name, owner);
  2320         ClassSymbol c = classes.get(flatname);
  2321         if (c == null) {
  2322             c = defineClass(name, owner);
  2323             classes.put(flatname, c);
  2324         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2325             // reassign fields of classes that might have been loaded with
  2326             // their flat names.
  2327             c.owner.members().remove(c);
  2328             c.name = name;
  2329             c.owner = owner;
  2330             c.fullname = ClassSymbol.formFullName(name, owner);
  2332         return c;
  2335     /**
  2336      * Creates a new toplevel class symbol with given flat name and
  2337      * given class (or source) file.
  2339      * @param flatName a fully qualified binary class name
  2340      * @param classFile the class file or compilation unit defining
  2341      * the class (may be {@code null})
  2342      * @return a newly created class symbol
  2343      * @throws AssertionError if the class symbol already exists
  2344      */
  2345     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2346         ClassSymbol cs = classes.get(flatName);
  2347         if (cs != null) {
  2348             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2349                                     cs.fullname,
  2350                                     cs.completer,
  2351                                     cs.classfile,
  2352                                     cs.sourcefile);
  2353             throw new AssertionError(msg);
  2355         Name packageName = Convert.packagePart(flatName);
  2356         PackageSymbol owner = packageName.isEmpty()
  2357                                 ? syms.unnamedPackage
  2358                                 : enterPackage(packageName);
  2359         cs = defineClass(Convert.shortName(flatName), owner);
  2360         cs.classfile = classFile;
  2361         classes.put(flatName, cs);
  2362         return cs;
  2365     /** Create a new member or toplevel class symbol with given flat name
  2366      *  and enter in `classes' unless already there.
  2367      */
  2368     public ClassSymbol enterClass(Name flatname) {
  2369         ClassSymbol c = classes.get(flatname);
  2370         if (c == null)
  2371             return enterClass(flatname, (JavaFileObject)null);
  2372         else
  2373             return c;
  2376     private boolean suppressFlush = false;
  2378     /** Completion for classes to be loaded. Before a class is loaded
  2379      *  we make sure its enclosing class (if any) is loaded.
  2380      */
  2381     public void complete(Symbol sym) throws CompletionFailure {
  2382         if (sym.kind == TYP) {
  2383             ClassSymbol c = (ClassSymbol)sym;
  2384             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2385             boolean saveSuppressFlush = suppressFlush;
  2386             suppressFlush = true;
  2387             try {
  2388                 completeOwners(c.owner);
  2389                 completeEnclosing(c);
  2390             } finally {
  2391                 suppressFlush = saveSuppressFlush;
  2393             fillIn(c);
  2394         } else if (sym.kind == PCK) {
  2395             PackageSymbol p = (PackageSymbol)sym;
  2396             try {
  2397                 fillIn(p);
  2398             } catch (IOException ex) {
  2399                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2402         if (!filling && !suppressFlush)
  2403             annotate.flush(); // finish attaching annotations
  2406     /** complete up through the enclosing package. */
  2407     private void completeOwners(Symbol o) {
  2408         if (o.kind != PCK) completeOwners(o.owner);
  2409         o.complete();
  2412     /**
  2413      * Tries to complete lexically enclosing classes if c looks like a
  2414      * nested class.  This is similar to completeOwners but handles
  2415      * the situation when a nested class is accessed directly as it is
  2416      * possible with the Tree API or javax.lang.model.*.
  2417      */
  2418     private void completeEnclosing(ClassSymbol c) {
  2419         if (c.owner.kind == PCK) {
  2420             Symbol owner = c.owner;
  2421             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2422                 Symbol encl = owner.members().lookup(name).sym;
  2423                 if (encl == null)
  2424                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2425                 if (encl != null)
  2426                     encl.complete();
  2431     /** We can only read a single class file at a time; this
  2432      *  flag keeps track of when we are currently reading a class
  2433      *  file.
  2434      */
  2435     private boolean filling = false;
  2437     /** Fill in definition of class `c' from corresponding class or
  2438      *  source file.
  2439      */
  2440     private void fillIn(ClassSymbol c) {
  2441         if (completionFailureName == c.fullname) {
  2442             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2444         currentOwner = c;
  2445         warnedAttrs.clear();
  2446         JavaFileObject classfile = c.classfile;
  2447         if (classfile != null) {
  2448             JavaFileObject previousClassFile = currentClassFile;
  2449             try {
  2450                 if (filling) {
  2451                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2453                 currentClassFile = classfile;
  2454                 if (verbose) {
  2455                     log.printVerbose("loading", currentClassFile.toString());
  2457                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2458                     filling = true;
  2459                     try {
  2460                         bp = 0;
  2461                         buf = readInputStream(buf, classfile.openInputStream());
  2462                         readClassFile(c);
  2463                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2464                             List<Type> missing = missingTypeVariables;
  2465                             List<Type> found = foundTypeVariables;
  2466                             missingTypeVariables = List.nil();
  2467                             foundTypeVariables = List.nil();
  2468                             filling = false;
  2469                             ClassType ct = (ClassType)currentOwner.type;
  2470                             ct.supertype_field =
  2471                                 types.subst(ct.supertype_field, missing, found);
  2472                             ct.interfaces_field =
  2473                                 types.subst(ct.interfaces_field, missing, found);
  2474                         } else if (missingTypeVariables.isEmpty() !=
  2475                                    foundTypeVariables.isEmpty()) {
  2476                             Name name = missingTypeVariables.head.tsym.name;
  2477                             throw badClassFile("undecl.type.var", name);
  2479                     } finally {
  2480                         missingTypeVariables = List.nil();
  2481                         foundTypeVariables = List.nil();
  2482                         filling = false;
  2484                 } else {
  2485                     if (sourceCompleter != null) {
  2486                         sourceCompleter.complete(c);
  2487                     } else {
  2488                         throw new IllegalStateException("Source completer required to read "
  2489                                                         + classfile.toUri());
  2492                 return;
  2493             } catch (IOException ex) {
  2494                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2495             } finally {
  2496                 currentClassFile = previousClassFile;
  2498         } else {
  2499             JCDiagnostic diag =
  2500                 diagFactory.fragment("class.file.not.found", c.flatname);
  2501             throw
  2502                 newCompletionFailure(c, diag);
  2505     // where
  2506         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2507             try {
  2508                 buf = ensureCapacity(buf, s.available());
  2509                 int r = s.read(buf);
  2510                 int bp = 0;
  2511                 while (r != -1) {
  2512                     bp += r;
  2513                     buf = ensureCapacity(buf, bp);
  2514                     r = s.read(buf, bp, buf.length - bp);
  2516                 return buf;
  2517             } finally {
  2518                 try {
  2519                     s.close();
  2520                 } catch (IOException e) {
  2521                     /* Ignore any errors, as this stream may have already
  2522                      * thrown a related exception which is the one that
  2523                      * should be reported.
  2524                      */
  2528         /*
  2529          * ensureCapacity will increase the buffer as needed, taking note that
  2530          * the new buffer will always be greater than the needed and never
  2531          * exactly equal to the needed size or bp. If equal then the read (above)
  2532          * will infinitely loop as buf.length - bp == 0.
  2533          */
  2534         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2535             if (buf.length <= needed) {
  2536                 byte[] old = buf;
  2537                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2538                 System.arraycopy(old, 0, buf, 0, old.length);
  2540             return buf;
  2542         /** Static factory for CompletionFailure objects.
  2543          *  In practice, only one can be used at a time, so we share one
  2544          *  to reduce the expense of allocating new exception objects.
  2545          */
  2546         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2547                                                        JCDiagnostic diag) {
  2548             if (!cacheCompletionFailure) {
  2549                 // log.warning("proc.messager",
  2550                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2551                 // c.debug.printStackTrace();
  2552                 return new CompletionFailure(c, diag);
  2553             } else {
  2554                 CompletionFailure result = cachedCompletionFailure;
  2555                 result.sym = c;
  2556                 result.diag = diag;
  2557                 return result;
  2560         private CompletionFailure cachedCompletionFailure =
  2561             new CompletionFailure(null, (JCDiagnostic) null);
  2563             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2566     /** Load a toplevel class with given fully qualified name
  2567      *  The class is entered into `classes' only if load was successful.
  2568      */
  2569     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2570         boolean absent = classes.get(flatname) == null;
  2571         ClassSymbol c = enterClass(flatname);
  2572         if (c.members_field == null && c.completer != null) {
  2573             try {
  2574                 c.complete();
  2575             } catch (CompletionFailure ex) {
  2576                 if (absent) classes.remove(flatname);
  2577                 throw ex;
  2580         return c;
  2583 /************************************************************************
  2584  * Loading Packages
  2585  ***********************************************************************/
  2587     /** Check to see if a package exists, given its fully qualified name.
  2588      */
  2589     public boolean packageExists(Name fullname) {
  2590         return enterPackage(fullname).exists();
  2593     /** Make a package, given its fully qualified name.
  2594      */
  2595     public PackageSymbol enterPackage(Name fullname) {
  2596         PackageSymbol p = packages.get(fullname);
  2597         if (p == null) {
  2598             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2599             p = new PackageSymbol(
  2600                 Convert.shortName(fullname),
  2601                 enterPackage(Convert.packagePart(fullname)));
  2602             p.completer = this;
  2603             packages.put(fullname, p);
  2605         return p;
  2608     /** Make a package, given its unqualified name and enclosing package.
  2609      */
  2610     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2611         return enterPackage(TypeSymbol.formFullName(name, owner));
  2614     /** Include class corresponding to given class file in package,
  2615      *  unless (1) we already have one the same kind (.class or .java), or
  2616      *         (2) we have one of the other kind, and the given class file
  2617      *             is older.
  2618      */
  2619     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2620         if ((p.flags_field & EXISTS) == 0)
  2621             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2622                 q.flags_field |= EXISTS;
  2623         JavaFileObject.Kind kind = file.getKind();
  2624         int seen;
  2625         if (kind == JavaFileObject.Kind.CLASS)
  2626             seen = CLASS_SEEN;
  2627         else
  2628             seen = SOURCE_SEEN;
  2629         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2630         int lastDot = binaryName.lastIndexOf(".");
  2631         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2632         boolean isPkgInfo = classname == names.package_info;
  2633         ClassSymbol c = isPkgInfo
  2634             ? p.package_info
  2635             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2636         if (c == null) {
  2637             c = enterClass(classname, p);
  2638             if (c.classfile == null) // only update the file if's it's newly created
  2639                 c.classfile = file;
  2640             if (isPkgInfo) {
  2641                 p.package_info = c;
  2642             } else {
  2643                 if (c.owner == p)  // it might be an inner class
  2644                     p.members_field.enter(c);
  2646         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2647             // if c.classfile == null, we are currently compiling this class
  2648             // and no further action is necessary.
  2649             // if (c.flags_field & seen) != 0, we have already encountered
  2650             // a file of the same kind; again no further action is necessary.
  2651             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2652                 c.classfile = preferredFileObject(file, c.classfile);
  2654         c.flags_field |= seen;
  2657     /** Implement policy to choose to derive information from a source
  2658      *  file or a class file when both are present.  May be overridden
  2659      *  by subclasses.
  2660      */
  2661     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2662                                            JavaFileObject b) {
  2664         if (preferSource)
  2665             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2666         else {
  2667             long adate = a.getLastModified();
  2668             long bdate = b.getLastModified();
  2669             // 6449326: policy for bad lastModifiedTime in ClassReader
  2670             //assert adate >= 0 && bdate >= 0;
  2671             return (adate > bdate) ? a : b;
  2675     /**
  2676      * specifies types of files to be read when filling in a package symbol
  2677      */
  2678     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2679         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2682     /**
  2683      * this is used to support javadoc
  2684      */
  2685     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2688     protected Location currentLoc; // FIXME
  2690     private boolean verbosePath = true;
  2692     /** Load directory of package into members scope.
  2693      */
  2694     private void fillIn(PackageSymbol p) throws IOException {
  2695         if (p.members_field == null) p.members_field = new Scope(p);
  2696         String packageName = p.fullname.toString();
  2698         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2700         fillIn(p, PLATFORM_CLASS_PATH,
  2701                fileManager.list(PLATFORM_CLASS_PATH,
  2702                                 packageName,
  2703                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2704                                 false));
  2706         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2707         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2708         boolean wantClassFiles = !classKinds.isEmpty();
  2710         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2711         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2712         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2714         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2716         if (verbose && verbosePath) {
  2717             if (fileManager instanceof StandardJavaFileManager) {
  2718                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2719                 if (haveSourcePath && wantSourceFiles) {
  2720                     List<File> path = List.nil();
  2721                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2722                         path = path.prepend(file);
  2724                     log.printVerbose("sourcepath", path.reverse().toString());
  2725                 } else if (wantSourceFiles) {
  2726                     List<File> path = List.nil();
  2727                     for (File file : fm.getLocation(CLASS_PATH)) {
  2728                         path = path.prepend(file);
  2730                     log.printVerbose("sourcepath", path.reverse().toString());
  2732                 if (wantClassFiles) {
  2733                     List<File> path = List.nil();
  2734                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2735                         path = path.prepend(file);
  2737                     for (File file : fm.getLocation(CLASS_PATH)) {
  2738                         path = path.prepend(file);
  2740                     log.printVerbose("classpath",  path.reverse().toString());
  2745         if (wantSourceFiles && !haveSourcePath) {
  2746             fillIn(p, CLASS_PATH,
  2747                    fileManager.list(CLASS_PATH,
  2748                                     packageName,
  2749                                     kinds,
  2750                                     false));
  2751         } else {
  2752             if (wantClassFiles)
  2753                 fillIn(p, CLASS_PATH,
  2754                        fileManager.list(CLASS_PATH,
  2755                                         packageName,
  2756                                         classKinds,
  2757                                         false));
  2758             if (wantSourceFiles)
  2759                 fillIn(p, SOURCE_PATH,
  2760                        fileManager.list(SOURCE_PATH,
  2761                                         packageName,
  2762                                         sourceKinds,
  2763                                         false));
  2765         verbosePath = false;
  2767     // where
  2768         private void fillIn(PackageSymbol p,
  2769                             Location location,
  2770                             Iterable<JavaFileObject> files)
  2772             currentLoc = location;
  2773             for (JavaFileObject fo : files) {
  2774                 switch (fo.getKind()) {
  2775                 case CLASS:
  2776                 case SOURCE: {
  2777                     // TODO pass binaryName to includeClassFile
  2778                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2779                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2780                     if (SourceVersion.isIdentifier(simpleName) ||
  2781                         simpleName.equals("package-info"))
  2782                         includeClassFile(p, fo);
  2783                     break;
  2785                 default:
  2786                     extraFileActions(p, fo);
  2791     /** Output for "-checkclassfile" option.
  2792      *  @param key The key to look up the correct internationalized string.
  2793      *  @param arg An argument for substitution into the output string.
  2794      */
  2795     private void printCCF(String key, Object arg) {
  2796         log.printLines(key, arg);
  2800     public interface SourceCompleter {
  2801         void complete(ClassSymbol sym)
  2802             throws CompletionFailure;
  2805     /**
  2806      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2807      * The attribute is only the last component of the original filename, so is unlikely
  2808      * to be valid as is, so operations other than those to access the name throw
  2809      * UnsupportedOperationException
  2810      */
  2811     private static class SourceFileObject extends BaseFileObject {
  2813         /** The file's name.
  2814          */
  2815         private Name name;
  2816         private Name flatname;
  2818         public SourceFileObject(Name name, Name flatname) {
  2819             super(null); // no file manager; never referenced for this file object
  2820             this.name = name;
  2821             this.flatname = flatname;
  2824         @Override
  2825         public URI toUri() {
  2826             try {
  2827                 return new URI(null, name.toString(), null);
  2828             } catch (URISyntaxException e) {
  2829                 throw new CannotCreateUriError(name.toString(), e);
  2833         @Override
  2834         public String getName() {
  2835             return name.toString();
  2838         @Override
  2839         public String getShortName() {
  2840             return getName();
  2843         @Override
  2844         public JavaFileObject.Kind getKind() {
  2845             return getKind(getName());
  2848         @Override
  2849         public InputStream openInputStream() {
  2850             throw new UnsupportedOperationException();
  2853         @Override
  2854         public OutputStream openOutputStream() {
  2855             throw new UnsupportedOperationException();
  2858         @Override
  2859         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2860             throw new UnsupportedOperationException();
  2863         @Override
  2864         public Reader openReader(boolean ignoreEncodingErrors) {
  2865             throw new UnsupportedOperationException();
  2868         @Override
  2869         public Writer openWriter() {
  2870             throw new UnsupportedOperationException();
  2873         @Override
  2874         public long getLastModified() {
  2875             throw new UnsupportedOperationException();
  2878         @Override
  2879         public boolean delete() {
  2880             throw new UnsupportedOperationException();
  2883         @Override
  2884         protected String inferBinaryName(Iterable<? extends File> path) {
  2885             return flatname.toString();
  2888         @Override
  2889         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2890             return true; // fail-safe mode
  2893         /**
  2894          * Check if two file objects are equal.
  2895          * SourceFileObjects are just placeholder objects for the value of a
  2896          * SourceFile attribute, and do not directly represent specific files.
  2897          * Two SourceFileObjects are equal if their names are equal.
  2898          */
  2899         @Override
  2900         public boolean equals(Object other) {
  2901             if (this == other)
  2902                 return true;
  2904             if (!(other instanceof SourceFileObject))
  2905                 return false;
  2907             SourceFileObject o = (SourceFileObject) other;
  2908             return name.equals(o.name);
  2911         @Override
  2912         public int hashCode() {
  2913             return name.hashCode();

mercurial