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

Mon, 02 Sep 2013 22:44:06 +0100

author
vromero
date
Mon, 02 Sep 2013 22:44:06 +0100
changeset 2001
2bf4c132bf90
parent 1820
6b48ebae2569
child 2007
a76c663a9cac
permissions
-rw-r--r--

8022162: Incorrect signature determination for certain inner class generics
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.jvm;
    28 import java.io.*;
    29 import java.net.URI;
    30 import java.net.URISyntaxException;
    31 import java.nio.CharBuffer;
    32 import java.util.Arrays;
    33 import java.util.EnumSet;
    34 import java.util.HashMap;
    35 import java.util.HashSet;
    36 import java.util.Map;
    37 import java.util.Set;
    38 import javax.lang.model.SourceVersion;
    39 import javax.tools.JavaFileObject;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileManager.Location;
    42 import javax.tools.StandardJavaFileManager;
    44 import static javax.tools.StandardLocation.*;
    46 import com.sun.tools.javac.comp.Annotate;
    47 import com.sun.tools.javac.code.*;
    48 import com.sun.tools.javac.code.Lint.LintCategory;
    49 import com.sun.tools.javac.code.Type.*;
    50 import com.sun.tools.javac.code.Symbol.*;
    51 import com.sun.tools.javac.code.Symtab;
    52 import com.sun.tools.javac.file.BaseFileObject;
    53 import com.sun.tools.javac.util.*;
    54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.TypeTag.CLASS;
    59 import static com.sun.tools.javac.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));
   731                 try {
   732                     return (outer == Type.noType) ?
   733                             t.erasure(types) :
   734                             new ClassType(outer, List.<Type>nil(), t);
   735                 } finally {
   736                     sbp = startSbp;
   737                 }
   738             }
   740             case '<':           // generic arguments
   741                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   742                                                          startSbp,
   743                                                          sbp - startSbp));
   744                 outer = new ClassType(outer, sigToTypes('>'), t) {
   745                         boolean completed = false;
   746                         @Override
   747                         public Type getEnclosingType() {
   748                             if (!completed) {
   749                                 completed = true;
   750                                 tsym.complete();
   751                                 Type enclosingType = tsym.type.getEnclosingType();
   752                                 if (enclosingType != Type.noType) {
   753                                     List<Type> typeArgs =
   754                                         super.getEnclosingType().allparams();
   755                                     List<Type> typeParams =
   756                                         enclosingType.allparams();
   757                                     if (typeParams.length() != typeArgs.length()) {
   758                                         // no "rare" types
   759                                         super.setEnclosingType(types.erasure(enclosingType));
   760                                     } else {
   761                                         super.setEnclosingType(types.subst(enclosingType,
   762                                                                            typeParams,
   763                                                                            typeArgs));
   764                                     }
   765                                 } else {
   766                                     super.setEnclosingType(Type.noType);
   767                                 }
   768                             }
   769                             return super.getEnclosingType();
   770                         }
   771                         @Override
   772                         public void setEnclosingType(Type outer) {
   773                             throw new UnsupportedOperationException();
   774                         }
   775                     };
   776                 switch (signature[sigp++]) {
   777                 case ';':
   778                     if (sigp < signature.length && signature[sigp] == '.') {
   779                         // support old-style GJC signatures
   780                         // The signature produced was
   781                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   782                         // rather than say
   783                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   784                         // so we skip past ".Lfoo/Outer$"
   785                         sigp += (sbp - startSbp) + // "foo/Outer"
   786                             3;  // ".L" and "$"
   787                         signatureBuffer[sbp++] = (byte)'$';
   788                         break;
   789                     } else {
   790                         sbp = startSbp;
   791                         return outer;
   792                     }
   793                 case '.':
   794                     signatureBuffer[sbp++] = (byte)'$';
   795                     break;
   796                 default:
   797                     throw new AssertionError(signature[sigp-1]);
   798                 }
   799                 continue;
   801             case '.':
   802                 //we have seen an enclosing non-generic class
   803                 if (outer != Type.noType) {
   804                     t = enterClass(names.fromUtf(signatureBuffer,
   805                                                  startSbp,
   806                                                  sbp - startSbp));
   807                     outer = new ClassType(outer, List.<Type>nil(), t);
   808                 }
   809                 signatureBuffer[sbp++] = (byte)'$';
   810                 continue;
   811             case '/':
   812                 signatureBuffer[sbp++] = (byte)'.';
   813                 continue;
   814             default:
   815                 signatureBuffer[sbp++] = c;
   816                 continue;
   817             }
   818         }
   819     }
   821     /** Convert (implicit) signature to list of types
   822      *  until `terminator' is encountered.
   823      */
   824     List<Type> sigToTypes(char terminator) {
   825         List<Type> head = List.of(null);
   826         List<Type> tail = head;
   827         while (signature[sigp] != terminator)
   828             tail = tail.setTail(List.of(sigToType()));
   829         sigp++;
   830         return head.tail;
   831     }
   833     /** Convert signature to type parameters, where signature is a byte
   834      *  array segment.
   835      */
   836     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   837         signature = sig;
   838         sigp = offset;
   839         siglimit = offset + len;
   840         return sigToTypeParams();
   841     }
   843     /** Convert signature to type parameters, where signature is implicit.
   844      */
   845     List<Type> sigToTypeParams() {
   846         List<Type> tvars = List.nil();
   847         if (signature[sigp] == '<') {
   848             sigp++;
   849             int start = sigp;
   850             sigEnterPhase = true;
   851             while (signature[sigp] != '>')
   852                 tvars = tvars.prepend(sigToTypeParam());
   853             sigEnterPhase = false;
   854             sigp = start;
   855             while (signature[sigp] != '>')
   856                 sigToTypeParam();
   857             sigp++;
   858         }
   859         return tvars.reverse();
   860     }
   862     /** Convert (implicit) signature to type parameter.
   863      */
   864     Type sigToTypeParam() {
   865         int start = sigp;
   866         while (signature[sigp] != ':') sigp++;
   867         Name name = names.fromUtf(signature, start, sigp - start);
   868         TypeVar tvar;
   869         if (sigEnterPhase) {
   870             tvar = new TypeVar(name, currentOwner, syms.botType);
   871             typevars.enter(tvar.tsym);
   872         } else {
   873             tvar = (TypeVar)findTypeVar(name);
   874         }
   875         List<Type> bounds = List.nil();
   876         boolean allInterfaces = false;
   877         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   878             sigp++;
   879             allInterfaces = true;
   880         }
   881         while (signature[sigp] == ':') {
   882             sigp++;
   883             bounds = bounds.prepend(sigToType());
   884         }
   885         if (!sigEnterPhase) {
   886             types.setBounds(tvar, bounds.reverse(), allInterfaces);
   887         }
   888         return tvar;
   889     }
   891     /** Find type variable with given name in `typevars' scope.
   892      */
   893     Type findTypeVar(Name name) {
   894         Scope.Entry e = typevars.lookup(name);
   895         if (e.scope != null) {
   896             return e.sym.type;
   897         } else {
   898             if (readingClassAttr) {
   899                 // While reading the class attribute, the supertypes
   900                 // might refer to a type variable from an enclosing element
   901                 // (method or class).
   902                 // If the type variable is defined in the enclosing class,
   903                 // we can actually find it in
   904                 // currentOwner.owner.type.getTypeArguments()
   905                 // However, until we have read the enclosing method attribute
   906                 // we don't know for sure if this owner is correct.  It could
   907                 // be a method and there is no way to tell before reading the
   908                 // enclosing method attribute.
   909                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   910                 missingTypeVariables = missingTypeVariables.prepend(t);
   911                 // System.err.println("Missing type var " + name);
   912                 return t;
   913             }
   914             throw badClassFile("undecl.type.var", name);
   915         }
   916     }
   918 /************************************************************************
   919  * Reading Attributes
   920  ***********************************************************************/
   922     protected enum AttributeKind { CLASS, MEMBER };
   923     protected abstract class AttributeReader {
   924         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   925             this.name = name;
   926             this.version = version;
   927             this.kinds = kinds;
   928         }
   930         protected boolean accepts(AttributeKind kind) {
   931             if (kinds.contains(kind)) {
   932                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   933                     return true;
   935                 if (lintClassfile && !warnedAttrs.contains(name)) {
   936                     JavaFileObject prev = log.useSource(currentClassFile);
   937                     try {
   938                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   939                                 name, version.major, version.minor, majorVersion, minorVersion);
   940                     } finally {
   941                         log.useSource(prev);
   942                     }
   943                     warnedAttrs.add(name);
   944                 }
   945             }
   946             return false;
   947         }
   949         protected abstract void read(Symbol sym, int attrLen);
   951         protected final Name name;
   952         protected final ClassFile.Version version;
   953         protected final Set<AttributeKind> kinds;
   954     }
   956     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   957             EnumSet.of(AttributeKind.CLASS);
   958     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   959             EnumSet.of(AttributeKind.MEMBER);
   960     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   961             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   963     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   965     private void initAttributeReaders() {
   966         AttributeReader[] readers = {
   967             // v45.3 attributes
   969             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   970                 protected void read(Symbol sym, int attrLen) {
   971                     if (readAllOfClassFile || saveParameterNames)
   972                         ((MethodSymbol)sym).code = readCode(sym);
   973                     else
   974                         bp = bp + attrLen;
   975                 }
   976             },
   978             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   979                 protected void read(Symbol sym, int attrLen) {
   980                     Object v = readPool(nextChar());
   981                     // Ignore ConstantValue attribute if field not final.
   982                     if ((sym.flags() & FINAL) != 0)
   983                         ((VarSymbol) sym).setData(v);
   984                 }
   985             },
   987             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   988                 protected void read(Symbol sym, int attrLen) {
   989                     sym.flags_field |= DEPRECATED;
   990                 }
   991             },
   993             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   994                 protected void read(Symbol sym, int attrLen) {
   995                     int nexceptions = nextChar();
   996                     List<Type> thrown = List.nil();
   997                     for (int j = 0; j < nexceptions; j++)
   998                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
   999                     if (sym.type.getThrownTypes().isEmpty())
  1000                         sym.type.asMethodType().thrown = thrown.reverse();
  1002             },
  1004             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
  1005                 protected void read(Symbol sym, int attrLen) {
  1006                     ClassSymbol c = (ClassSymbol) sym;
  1007                     readInnerClasses(c);
  1009             },
  1011             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1012                 protected void read(Symbol sym, int attrLen) {
  1013                     int newbp = bp + attrLen;
  1014                     if (saveParameterNames && !sawMethodParameters) {
  1015                         // Pick up parameter names from the variable table.
  1016                         // Parameter names are not explicitly identified as such,
  1017                         // but all parameter name entries in the LocalVariableTable
  1018                         // have a start_pc of 0.  Therefore, we record the name
  1019                         // indicies of all slots with a start_pc of zero in the
  1020                         // parameterNameIndicies array.
  1021                         // Note that this implicitly honors the JVMS spec that
  1022                         // there may be more than one LocalVariableTable, and that
  1023                         // there is no specified ordering for the entries.
  1024                         int numEntries = nextChar();
  1025                         for (int i = 0; i < numEntries; i++) {
  1026                             int start_pc = nextChar();
  1027                             int length = nextChar();
  1028                             int nameIndex = nextChar();
  1029                             int sigIndex = nextChar();
  1030                             int register = nextChar();
  1031                             if (start_pc == 0) {
  1032                                 // ensure array large enough
  1033                                 if (register >= parameterNameIndices.length) {
  1034                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1035                                     parameterNameIndices =
  1036                                             Arrays.copyOf(parameterNameIndices, newSize);
  1038                                 parameterNameIndices[register] = nameIndex;
  1039                                 haveParameterNameIndices = true;
  1043                     bp = newbp;
  1045             },
  1047             new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
  1048                 protected void read(Symbol sym, int attrlen) {
  1049                     int newbp = bp + attrlen;
  1050                     if (saveParameterNames) {
  1051                         sawMethodParameters = true;
  1052                         int numEntries = nextByte();
  1053                         parameterNameIndices = new int[numEntries];
  1054                         haveParameterNameIndices = true;
  1055                         for (int i = 0; i < numEntries; i++) {
  1056                             int nameIndex = nextChar();
  1057                             int flags = nextChar();
  1058                             parameterNameIndices[i] = nameIndex;
  1061                     bp = newbp;
  1063             },
  1066             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1067                 protected void read(Symbol sym, int attrLen) {
  1068                     ClassSymbol c = (ClassSymbol) sym;
  1069                     Name n = readName(nextChar());
  1070                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1071                     // If the class is a toplevel class, originating from a Java source file,
  1072                     // but the class name does not match the file name, then it is
  1073                     // an auxiliary class.
  1074                     String sn = n.toString();
  1075                     if (c.owner.kind == Kinds.PCK &&
  1076                         sn.endsWith(".java") &&
  1077                         !sn.equals(c.name.toString()+".java")) {
  1078                         c.flags_field |= AUXILIARY;
  1081             },
  1083             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1084                 protected void read(Symbol sym, int attrLen) {
  1085                     // bridge methods are visible when generics not enabled
  1086                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1087                         sym.flags_field |= SYNTHETIC;
  1089             },
  1091             // standard v49 attributes
  1093             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1094                 protected void read(Symbol sym, int attrLen) {
  1095                     int newbp = bp + attrLen;
  1096                     readEnclosingMethodAttr(sym);
  1097                     bp = newbp;
  1099             },
  1101             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1102                 @Override
  1103                 protected boolean accepts(AttributeKind kind) {
  1104                     return super.accepts(kind) && allowGenerics;
  1107                 protected void read(Symbol sym, int attrLen) {
  1108                     if (sym.kind == TYP) {
  1109                         ClassSymbol c = (ClassSymbol) sym;
  1110                         readingClassAttr = true;
  1111                         try {
  1112                             ClassType ct1 = (ClassType)c.type;
  1113                             Assert.check(c == currentOwner);
  1114                             ct1.typarams_field = readTypeParams(nextChar());
  1115                             ct1.supertype_field = sigToType();
  1116                             ListBuffer<Type> is = new ListBuffer<Type>();
  1117                             while (sigp != siglimit) is.append(sigToType());
  1118                             ct1.interfaces_field = is.toList();
  1119                         } finally {
  1120                             readingClassAttr = false;
  1122                     } else {
  1123                         List<Type> thrown = sym.type.getThrownTypes();
  1124                         sym.type = readType(nextChar());
  1125                         //- System.err.println(" # " + sym.type);
  1126                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1127                             sym.type.asMethodType().thrown = thrown;
  1131             },
  1133             // v49 annotation attributes
  1135             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1136                 protected void read(Symbol sym, int attrLen) {
  1137                     attachAnnotationDefault(sym);
  1139             },
  1141             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1142                 protected void read(Symbol sym, int attrLen) {
  1143                     attachAnnotations(sym);
  1145             },
  1147             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1148                 protected void read(Symbol sym, int attrLen) {
  1149                     attachParameterAnnotations(sym);
  1151             },
  1153             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1154                 protected void read(Symbol sym, int attrLen) {
  1155                     attachAnnotations(sym);
  1157             },
  1159             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1160                 protected void read(Symbol sym, int attrLen) {
  1161                     attachParameterAnnotations(sym);
  1163             },
  1165             // additional "legacy" v49 attributes, superceded by flags
  1167             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1168                 protected void read(Symbol sym, int attrLen) {
  1169                     if (allowAnnotations)
  1170                         sym.flags_field |= ANNOTATION;
  1172             },
  1174             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1175                 protected void read(Symbol sym, int attrLen) {
  1176                     sym.flags_field |= BRIDGE;
  1177                     if (!allowGenerics)
  1178                         sym.flags_field &= ~SYNTHETIC;
  1180             },
  1182             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1183                 protected void read(Symbol sym, int attrLen) {
  1184                     sym.flags_field |= ENUM;
  1186             },
  1188             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1189                 protected void read(Symbol sym, int attrLen) {
  1190                     if (allowVarargs)
  1191                         sym.flags_field |= VARARGS;
  1193             },
  1195             new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1196                 protected void read(Symbol sym, int attrLen) {
  1197                     attachTypeAnnotations(sym);
  1199             },
  1201             new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1202                 protected void read(Symbol sym, int attrLen) {
  1203                     attachTypeAnnotations(sym);
  1205             },
  1208             // The following attributes for a Code attribute are not currently handled
  1209             // StackMapTable
  1210             // SourceDebugExtension
  1211             // LineNumberTable
  1212             // LocalVariableTypeTable
  1213         };
  1215         for (AttributeReader r: readers)
  1216             attributeReaders.put(r.name, r);
  1219     /** Report unrecognized attribute.
  1220      */
  1221     void unrecognized(Name attrName) {
  1222         if (checkClassFile)
  1223             printCCF("ccf.unrecognized.attribute", attrName);
  1228     protected void readEnclosingMethodAttr(Symbol sym) {
  1229         // sym is a nested class with an "Enclosing Method" attribute
  1230         // remove sym from it's current owners scope and place it in
  1231         // the scope specified by the attribute
  1232         sym.owner.members().remove(sym);
  1233         ClassSymbol self = (ClassSymbol)sym;
  1234         ClassSymbol c = readClassSymbol(nextChar());
  1235         NameAndType nt = (NameAndType)readPool(nextChar());
  1237         if (c.members_field == null)
  1238             throw badClassFile("bad.enclosing.class", self, c);
  1240         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1241         if (nt != null && m == null)
  1242             throw badClassFile("bad.enclosing.method", self);
  1244         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1245         self.owner = m != null ? m : c;
  1246         if (self.name.isEmpty())
  1247             self.fullname = names.empty;
  1248         else
  1249             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1251         if (m != null) {
  1252             ((ClassType)sym.type).setEnclosingType(m.type);
  1253         } else if ((self.flags_field & STATIC) == 0) {
  1254             ((ClassType)sym.type).setEnclosingType(c.type);
  1255         } else {
  1256             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1258         enterTypevars(self);
  1259         if (!missingTypeVariables.isEmpty()) {
  1260             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1261             for (Type typevar : missingTypeVariables) {
  1262                 typeVars.append(findTypeVar(typevar.tsym.name));
  1264             foundTypeVariables = typeVars.toList();
  1265         } else {
  1266             foundTypeVariables = List.nil();
  1270     // See java.lang.Class
  1271     private Name simpleBinaryName(Name self, Name enclosing) {
  1272         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1273         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1274             throw badClassFile("bad.enclosing.method", self);
  1275         int index = 1;
  1276         while (index < simpleBinaryName.length() &&
  1277                isAsciiDigit(simpleBinaryName.charAt(index)))
  1278             index++;
  1279         return names.fromString(simpleBinaryName.substring(index));
  1282     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1283         if (nt == null)
  1284             return null;
  1286         MethodType type = nt.uniqueType.type.asMethodType();
  1288         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1289             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1290                 return (MethodSymbol)e.sym;
  1292         if (nt.name != names.init)
  1293             // not a constructor
  1294             return null;
  1295         if ((flags & INTERFACE) != 0)
  1296             // no enclosing instance
  1297             return null;
  1298         if (nt.uniqueType.type.getParameterTypes().isEmpty())
  1299             // no parameters
  1300             return null;
  1302         // A constructor of an inner class.
  1303         // Remove the first argument (the enclosing instance)
  1304         nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
  1305                                  nt.uniqueType.type.getReturnType(),
  1306                                  nt.uniqueType.type.getThrownTypes(),
  1307                                  syms.methodClass));
  1308         // Try searching again
  1309         return findMethod(nt, scope, flags);
  1312     /** Similar to Types.isSameType but avoids completion */
  1313     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1314         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1315             .prepend(types.erasure(mt1.getReturnType()));
  1316         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1317         while (!types1.isEmpty() && !types2.isEmpty()) {
  1318             if (types1.head.tsym != types2.head.tsym)
  1319                 return false;
  1320             types1 = types1.tail;
  1321             types2 = types2.tail;
  1323         return types1.isEmpty() && types2.isEmpty();
  1326     /**
  1327      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1328      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1329      */
  1330     private static boolean isAsciiDigit(char c) {
  1331         return '0' <= c && c <= '9';
  1334     /** Read member attributes.
  1335      */
  1336     void readMemberAttrs(Symbol sym) {
  1337         readAttrs(sym, AttributeKind.MEMBER);
  1340     void readAttrs(Symbol sym, AttributeKind kind) {
  1341         char ac = nextChar();
  1342         for (int i = 0; i < ac; i++) {
  1343             Name attrName = readName(nextChar());
  1344             int attrLen = nextInt();
  1345             AttributeReader r = attributeReaders.get(attrName);
  1346             if (r != null && r.accepts(kind))
  1347                 r.read(sym, attrLen);
  1348             else  {
  1349                 unrecognized(attrName);
  1350                 bp = bp + attrLen;
  1355     private boolean readingClassAttr = false;
  1356     private List<Type> missingTypeVariables = List.nil();
  1357     private List<Type> foundTypeVariables = List.nil();
  1359     /** Read class attributes.
  1360      */
  1361     void readClassAttrs(ClassSymbol c) {
  1362         readAttrs(c, AttributeKind.CLASS);
  1365     /** Read code block.
  1366      */
  1367     Code readCode(Symbol owner) {
  1368         nextChar(); // max_stack
  1369         nextChar(); // max_locals
  1370         final int  code_length = nextInt();
  1371         bp += code_length;
  1372         final char exception_table_length = nextChar();
  1373         bp += exception_table_length * 8;
  1374         readMemberAttrs(owner);
  1375         return null;
  1378 /************************************************************************
  1379  * Reading Java-language annotations
  1380  ***********************************************************************/
  1382     /** Attach annotations.
  1383      */
  1384     void attachAnnotations(final Symbol sym) {
  1385         int numAttributes = nextChar();
  1386         if (numAttributes != 0) {
  1387             ListBuffer<CompoundAnnotationProxy> proxies =
  1388                 new ListBuffer<CompoundAnnotationProxy>();
  1389             for (int i = 0; i<numAttributes; i++) {
  1390                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1391                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1392                     sym.flags_field |= PROPRIETARY;
  1393                 else if (proxy.type.tsym == syms.profileType.tsym) {
  1394                     if (profile != Profile.DEFAULT) {
  1395                         for (Pair<Name,Attribute> v: proxy.values) {
  1396                             if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
  1397                                 Attribute.Constant c = (Attribute.Constant) v.snd;
  1398                                 if (c.type == syms.intType && ((Integer) c.value) > profile.value) {
  1399                                     sym.flags_field |= NOT_IN_PROFILE;
  1404                 } else
  1405                     proxies.append(proxy);
  1407             annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
  1411     /** Attach parameter annotations.
  1412      */
  1413     void attachParameterAnnotations(final Symbol method) {
  1414         final MethodSymbol meth = (MethodSymbol)method;
  1415         int numParameters = buf[bp++] & 0xFF;
  1416         List<VarSymbol> parameters = meth.params();
  1417         int pnum = 0;
  1418         while (parameters.tail != null) {
  1419             attachAnnotations(parameters.head);
  1420             parameters = parameters.tail;
  1421             pnum++;
  1423         if (pnum != numParameters) {
  1424             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1428     void attachTypeAnnotations(final Symbol sym) {
  1429         int numAttributes = nextChar();
  1430         if (numAttributes != 0) {
  1431             ListBuffer<TypeAnnotationProxy> proxies =
  1432                 ListBuffer.lb();
  1433             for (int i = 0; i < numAttributes; i++)
  1434                 proxies.append(readTypeAnnotation());
  1435             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
  1439     /** Attach the default value for an annotation element.
  1440      */
  1441     void attachAnnotationDefault(final Symbol sym) {
  1442         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1443         final Attribute value = readAttributeValue();
  1445         // The default value is set later during annotation. It might
  1446         // be the case that the Symbol sym is annotated _after_ the
  1447         // repeating instances that depend on this default value,
  1448         // because of this we set an interim value that tells us this
  1449         // element (most likely) has a default.
  1450         //
  1451         // Set interim value for now, reset just before we do this
  1452         // properly at annotate time.
  1453         meth.defaultValue = value;
  1454         annotate.normal(new AnnotationDefaultCompleter(meth, value));
  1457     Type readTypeOrClassSymbol(int i) {
  1458         // support preliminary jsr175-format class files
  1459         if (buf[poolIdx[i]] == CONSTANT_Class)
  1460             return readClassSymbol(i).type;
  1461         return readType(i);
  1463     Type readEnumType(int i) {
  1464         // support preliminary jsr175-format class files
  1465         int index = poolIdx[i];
  1466         int length = getChar(index + 1);
  1467         if (buf[index + length + 2] != ';')
  1468             return enterClass(readName(i)).type;
  1469         return readType(i);
  1472     CompoundAnnotationProxy readCompoundAnnotation() {
  1473         Type t = readTypeOrClassSymbol(nextChar());
  1474         int numFields = nextChar();
  1475         ListBuffer<Pair<Name,Attribute>> pairs =
  1476             new ListBuffer<Pair<Name,Attribute>>();
  1477         for (int i=0; i<numFields; i++) {
  1478             Name name = readName(nextChar());
  1479             Attribute value = readAttributeValue();
  1480             pairs.append(new Pair<Name,Attribute>(name, value));
  1482         return new CompoundAnnotationProxy(t, pairs.toList());
  1485     TypeAnnotationProxy readTypeAnnotation() {
  1486         TypeAnnotationPosition position = readPosition();
  1487         CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1489         return new TypeAnnotationProxy(proxy, position);
  1492     TypeAnnotationPosition readPosition() {
  1493         int tag = nextByte(); // TargetType tag is a byte
  1495         if (!TargetType.isValidTargetTypeValue(tag))
  1496             throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
  1498         TypeAnnotationPosition position = new TypeAnnotationPosition();
  1499         TargetType type = TargetType.fromTargetTypeValue(tag);
  1501         position.type = type;
  1503         switch (type) {
  1504         // instanceof
  1505         case INSTANCEOF:
  1506         // new expression
  1507         case NEW:
  1508         // constructor/method reference receiver
  1509         case CONSTRUCTOR_REFERENCE:
  1510         case METHOD_REFERENCE:
  1511             position.offset = nextChar();
  1512             break;
  1513         // local variable
  1514         case LOCAL_VARIABLE:
  1515         // resource variable
  1516         case RESOURCE_VARIABLE:
  1517             int table_length = nextChar();
  1518             position.lvarOffset = new int[table_length];
  1519             position.lvarLength = new int[table_length];
  1520             position.lvarIndex = new int[table_length];
  1522             for (int i = 0; i < table_length; ++i) {
  1523                 position.lvarOffset[i] = nextChar();
  1524                 position.lvarLength[i] = nextChar();
  1525                 position.lvarIndex[i] = nextChar();
  1527             break;
  1528         // exception parameter
  1529         case EXCEPTION_PARAMETER:
  1530             position.exception_index = nextChar();
  1531             break;
  1532         // method receiver
  1533         case METHOD_RECEIVER:
  1534             // Do nothing
  1535             break;
  1536         // type parameter
  1537         case CLASS_TYPE_PARAMETER:
  1538         case METHOD_TYPE_PARAMETER:
  1539             position.parameter_index = nextByte();
  1540             break;
  1541         // type parameter bound
  1542         case CLASS_TYPE_PARAMETER_BOUND:
  1543         case METHOD_TYPE_PARAMETER_BOUND:
  1544             position.parameter_index = nextByte();
  1545             position.bound_index = nextByte();
  1546             break;
  1547         // class extends or implements clause
  1548         case CLASS_EXTENDS:
  1549             position.type_index = nextChar();
  1550             break;
  1551         // throws
  1552         case THROWS:
  1553             position.type_index = nextChar();
  1554             break;
  1555         // method parameter
  1556         case METHOD_FORMAL_PARAMETER:
  1557             position.parameter_index = nextByte();
  1558             break;
  1559         // type cast
  1560         case CAST:
  1561         // method/constructor/reference type argument
  1562         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
  1563         case METHOD_INVOCATION_TYPE_ARGUMENT:
  1564         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
  1565         case METHOD_REFERENCE_TYPE_ARGUMENT:
  1566             position.offset = nextChar();
  1567             position.type_index = nextByte();
  1568             break;
  1569         // We don't need to worry about these
  1570         case METHOD_RETURN:
  1571         case FIELD:
  1572             break;
  1573         case UNKNOWN:
  1574             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
  1575         default:
  1576             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
  1579         { // See whether there is location info and read it
  1580             int len = nextByte();
  1581             ListBuffer<Integer> loc = ListBuffer.lb();
  1582             for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
  1583                 loc = loc.append(nextByte());
  1584             position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
  1587         return position;
  1590     Attribute readAttributeValue() {
  1591         char c = (char) buf[bp++];
  1592         switch (c) {
  1593         case 'B':
  1594             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1595         case 'C':
  1596             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1597         case 'D':
  1598             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1599         case 'F':
  1600             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1601         case 'I':
  1602             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1603         case 'J':
  1604             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1605         case 'S':
  1606             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1607         case 'Z':
  1608             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1609         case 's':
  1610             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1611         case 'e':
  1612             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1613         case 'c':
  1614             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1615         case '[': {
  1616             int n = nextChar();
  1617             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1618             for (int i=0; i<n; i++)
  1619                 l.append(readAttributeValue());
  1620             return new ArrayAttributeProxy(l.toList());
  1622         case '@':
  1623             return readCompoundAnnotation();
  1624         default:
  1625             throw new AssertionError("unknown annotation tag '" + c + "'");
  1629     interface ProxyVisitor extends Attribute.Visitor {
  1630         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1631         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1632         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1635     static class EnumAttributeProxy extends Attribute {
  1636         Type enumType;
  1637         Name enumerator;
  1638         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1639             super(null);
  1640             this.enumType = enumType;
  1641             this.enumerator = enumerator;
  1643         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1644         @Override
  1645         public String toString() {
  1646             return "/*proxy enum*/" + enumType + "." + enumerator;
  1650     static class ArrayAttributeProxy extends Attribute {
  1651         List<Attribute> values;
  1652         ArrayAttributeProxy(List<Attribute> values) {
  1653             super(null);
  1654             this.values = values;
  1656         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1657         @Override
  1658         public String toString() {
  1659             return "{" + values + "}";
  1663     /** A temporary proxy representing a compound attribute.
  1664      */
  1665     static class CompoundAnnotationProxy extends Attribute {
  1666         final List<Pair<Name,Attribute>> values;
  1667         public CompoundAnnotationProxy(Type type,
  1668                                       List<Pair<Name,Attribute>> values) {
  1669             super(type);
  1670             this.values = values;
  1672         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1673         @Override
  1674         public String toString() {
  1675             StringBuilder buf = new StringBuilder();
  1676             buf.append("@");
  1677             buf.append(type.tsym.getQualifiedName());
  1678             buf.append("/*proxy*/{");
  1679             boolean first = true;
  1680             for (List<Pair<Name,Attribute>> v = values;
  1681                  v.nonEmpty(); v = v.tail) {
  1682                 Pair<Name,Attribute> value = v.head;
  1683                 if (!first) buf.append(",");
  1684                 first = false;
  1685                 buf.append(value.fst);
  1686                 buf.append("=");
  1687                 buf.append(value.snd);
  1689             buf.append("}");
  1690             return buf.toString();
  1694     /** A temporary proxy representing a type annotation.
  1695      */
  1696     static class TypeAnnotationProxy {
  1697         final CompoundAnnotationProxy compound;
  1698         final TypeAnnotationPosition position;
  1699         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1700                 TypeAnnotationPosition position) {
  1701             this.compound = compound;
  1702             this.position = position;
  1706     class AnnotationDeproxy implements ProxyVisitor {
  1707         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1708             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1710         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1711             // also must fill in types!!!!
  1712             ListBuffer<Attribute.Compound> buf =
  1713                 new ListBuffer<Attribute.Compound>();
  1714             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1715                 buf.append(deproxyCompound(l.head));
  1717             return buf.toList();
  1720         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1721             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1722                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1723             for (List<Pair<Name,Attribute>> l = a.values;
  1724                  l.nonEmpty();
  1725                  l = l.tail) {
  1726                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1727                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1728                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1730             return new Attribute.Compound(a.type, buf.toList());
  1733         MethodSymbol findAccessMethod(Type container, Name name) {
  1734             CompletionFailure failure = null;
  1735             try {
  1736                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1737                      e.scope != null;
  1738                      e = e.next()) {
  1739                     Symbol sym = e.sym;
  1740                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1741                         return (MethodSymbol) sym;
  1743             } catch (CompletionFailure ex) {
  1744                 failure = ex;
  1746             // The method wasn't found: emit a warning and recover
  1747             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1748             try {
  1749                 if (failure == null) {
  1750                     log.warning("annotation.method.not.found",
  1751                                 container,
  1752                                 name);
  1753                 } else {
  1754                     log.warning("annotation.method.not.found.reason",
  1755                                 container,
  1756                                 name,
  1757                                 failure.getDetailValue());//diagnostic, if present
  1759             } finally {
  1760                 log.useSource(prevSource);
  1762             // Construct a new method type and symbol.  Use bottom
  1763             // type (typeof null) as return type because this type is
  1764             // a subtype of all reference types and can be converted
  1765             // to primitive types by unboxing.
  1766             MethodType mt = new MethodType(List.<Type>nil(),
  1767                                            syms.botType,
  1768                                            List.<Type>nil(),
  1769                                            syms.methodClass);
  1770             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1773         Attribute result;
  1774         Type type;
  1775         Attribute deproxy(Type t, Attribute a) {
  1776             Type oldType = type;
  1777             try {
  1778                 type = t;
  1779                 a.accept(this);
  1780                 return result;
  1781             } finally {
  1782                 type = oldType;
  1786         // implement Attribute.Visitor below
  1788         public void visitConstant(Attribute.Constant value) {
  1789             // assert value.type == type;
  1790             result = value;
  1793         public void visitClass(Attribute.Class clazz) {
  1794             result = clazz;
  1797         public void visitEnum(Attribute.Enum e) {
  1798             throw new AssertionError(); // shouldn't happen
  1801         public void visitCompound(Attribute.Compound compound) {
  1802             throw new AssertionError(); // shouldn't happen
  1805         public void visitArray(Attribute.Array array) {
  1806             throw new AssertionError(); // shouldn't happen
  1809         public void visitError(Attribute.Error e) {
  1810             throw new AssertionError(); // shouldn't happen
  1813         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1814             // type.tsym.flatName() should == proxy.enumFlatName
  1815             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1816             VarSymbol enumerator = null;
  1817             CompletionFailure failure = null;
  1818             try {
  1819                 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1820                      e.scope != null;
  1821                      e = e.next()) {
  1822                     if (e.sym.kind == VAR) {
  1823                         enumerator = (VarSymbol)e.sym;
  1824                         break;
  1828             catch (CompletionFailure ex) {
  1829                 failure = ex;
  1831             if (enumerator == null) {
  1832                 if (failure != null) {
  1833                     log.warning("unknown.enum.constant.reason",
  1834                               currentClassFile, enumTypeSym, proxy.enumerator,
  1835                               failure.getDiagnostic());
  1836                 } else {
  1837                     log.warning("unknown.enum.constant",
  1838                               currentClassFile, enumTypeSym, proxy.enumerator);
  1840                 result = new Attribute.Enum(enumTypeSym.type,
  1841                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
  1842             } else {
  1843                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1847         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1848             int length = proxy.values.length();
  1849             Attribute[] ats = new Attribute[length];
  1850             Type elemtype = types.elemtype(type);
  1851             int i = 0;
  1852             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1853                 ats[i++] = deproxy(elemtype, p.head);
  1855             result = new Attribute.Array(type, ats);
  1858         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1859             result = deproxyCompound(proxy);
  1863     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1864         final MethodSymbol sym;
  1865         final Attribute value;
  1866         final JavaFileObject classFile = currentClassFile;
  1867         @Override
  1868         public String toString() {
  1869             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1871         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1872             this.sym = sym;
  1873             this.value = value;
  1875         // implement Annotate.Annotator.enterAnnotation()
  1876         public void enterAnnotation() {
  1877             JavaFileObject previousClassFile = currentClassFile;
  1878             try {
  1879                 // Reset the interim value set earlier in
  1880                 // attachAnnotationDefault().
  1881                 sym.defaultValue = null;
  1882                 currentClassFile = classFile;
  1883                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1884             } finally {
  1885                 currentClassFile = previousClassFile;
  1890     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1891         final Symbol sym;
  1892         final List<CompoundAnnotationProxy> l;
  1893         final JavaFileObject classFile;
  1894         @Override
  1895         public String toString() {
  1896             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1898         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1899             this.sym = sym;
  1900             this.l = l;
  1901             this.classFile = currentClassFile;
  1903         // implement Annotate.Annotator.enterAnnotation()
  1904         public void enterAnnotation() {
  1905             JavaFileObject previousClassFile = currentClassFile;
  1906             try {
  1907                 currentClassFile = classFile;
  1908                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1909                 if (sym.annotationsPendingCompletion()) {
  1910                     sym.setDeclarationAttributes(newList);
  1911                 } else {
  1912                     sym.appendAttributes(newList);
  1914             } finally {
  1915                 currentClassFile = previousClassFile;
  1920     class TypeAnnotationCompleter extends AnnotationCompleter {
  1922         List<TypeAnnotationProxy> proxies;
  1924         TypeAnnotationCompleter(Symbol sym,
  1925                 List<TypeAnnotationProxy> proxies) {
  1926             super(sym, List.<CompoundAnnotationProxy>nil());
  1927             this.proxies = proxies;
  1930         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
  1931             ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
  1932             for (TypeAnnotationProxy proxy: proxies) {
  1933                 Attribute.Compound compound = deproxyCompound(proxy.compound);
  1934                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
  1935                 buf.add(typeCompound);
  1937             return buf.toList();
  1940         @Override
  1941         public void enterAnnotation() {
  1942             JavaFileObject previousClassFile = currentClassFile;
  1943             try {
  1944                 currentClassFile = classFile;
  1945                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
  1946                 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
  1947             } finally {
  1948                 currentClassFile = previousClassFile;
  1954 /************************************************************************
  1955  * Reading Symbols
  1956  ***********************************************************************/
  1958     /** Read a field.
  1959      */
  1960     VarSymbol readField() {
  1961         long flags = adjustFieldFlags(nextChar());
  1962         Name name = readName(nextChar());
  1963         Type type = readType(nextChar());
  1964         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1965         readMemberAttrs(v);
  1966         return v;
  1969     /** Read a method.
  1970      */
  1971     MethodSymbol readMethod() {
  1972         long flags = adjustMethodFlags(nextChar());
  1973         Name name = readName(nextChar());
  1974         Type type = readType(nextChar());
  1975         if (currentOwner.isInterface() &&
  1976                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
  1977             if (majorVersion > Target.JDK1_8.majorVersion ||
  1978                     (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
  1979                 currentOwner.flags_field |= DEFAULT;
  1980                 flags |= DEFAULT | ABSTRACT;
  1981             } else {
  1982                 //protect against ill-formed classfiles
  1983                 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
  1986         if (name == names.init && currentOwner.hasOuterInstance()) {
  1987             // Sometimes anonymous classes don't have an outer
  1988             // instance, however, there is no reliable way to tell so
  1989             // we never strip this$n
  1990             if (!currentOwner.name.isEmpty())
  1991                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  1992                                       type.getReturnType(),
  1993                                       type.getThrownTypes(),
  1994                                       syms.methodClass);
  1996         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  1997         if (types.isSignaturePolymorphic(m)) {
  1998             m.flags_field |= SIGNATURE_POLYMORPHIC;
  2000         if (saveParameterNames)
  2001             initParameterNames(m);
  2002         Symbol prevOwner = currentOwner;
  2003         currentOwner = m;
  2004         try {
  2005             readMemberAttrs(m);
  2006         } finally {
  2007             currentOwner = prevOwner;
  2009         if (saveParameterNames)
  2010             setParameterNames(m, type);
  2011         return m;
  2014     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  2015         boolean isVarargs = (flags & VARARGS) != 0;
  2016         if (isVarargs) {
  2017             Type varargsElem = args.last();
  2018             ListBuffer<Type> adjustedArgs = ListBuffer.lb();
  2019             for (Type t : args) {
  2020                 adjustedArgs.append(t != varargsElem ?
  2021                     t :
  2022                     ((ArrayType)t).makeVarargs());
  2024             args = adjustedArgs.toList();
  2026         return args.tail;
  2029     /**
  2030      * Init the parameter names array.
  2031      * Parameter names are currently inferred from the names in the
  2032      * LocalVariableTable attributes of a Code attribute.
  2033      * (Note: this means parameter names are currently not available for
  2034      * methods without a Code attribute.)
  2035      * This method initializes an array in which to store the name indexes
  2036      * of parameter names found in LocalVariableTable attributes. It is
  2037      * slightly supersized to allow for additional slots with a start_pc of 0.
  2038      */
  2039     void initParameterNames(MethodSymbol sym) {
  2040         // make allowance for synthetic parameters.
  2041         final int excessSlots = 4;
  2042         int expectedParameterSlots =
  2043                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  2044         if (parameterNameIndices == null
  2045                 || parameterNameIndices.length < expectedParameterSlots) {
  2046             parameterNameIndices = new int[expectedParameterSlots];
  2047         } else
  2048             Arrays.fill(parameterNameIndices, 0);
  2049         haveParameterNameIndices = false;
  2050         sawMethodParameters = false;
  2053     /**
  2054      * Set the parameter names for a symbol from the name index in the
  2055      * parameterNameIndicies array. The type of the symbol may have changed
  2056      * while reading the method attributes (see the Signature attribute).
  2057      * This may be because of generic information or because anonymous
  2058      * synthetic parameters were added.   The original type (as read from
  2059      * the method descriptor) is used to help guess the existence of
  2060      * anonymous synthetic parameters.
  2061      * On completion, sym.savedParameter names will either be null (if
  2062      * no parameter names were found in the class file) or will be set to a
  2063      * list of names, one per entry in sym.type.getParameterTypes, with
  2064      * any missing names represented by the empty name.
  2065      */
  2066     void setParameterNames(MethodSymbol sym, Type jvmType) {
  2067         // if no names were found in the class file, there's nothing more to do
  2068         if (!haveParameterNameIndices)
  2069             return;
  2070         // If we get parameter names from MethodParameters, then we
  2071         // don't need to skip.
  2072         int firstParam = 0;
  2073         if (!sawMethodParameters) {
  2074             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  2075             // the code in readMethod may have skipped the first
  2076             // parameter when setting up the MethodType. If so, we
  2077             // make a corresponding allowance here for the position of
  2078             // the first parameter.  Note that this assumes the
  2079             // skipped parameter has a width of 1 -- i.e. it is not
  2080         // a double width type (long or double.)
  2081         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  2082             // Sometimes anonymous classes don't have an outer
  2083             // instance, however, there is no reliable way to tell so
  2084             // we never strip this$n
  2085             if (!currentOwner.name.isEmpty())
  2086                 firstParam += 1;
  2089         if (sym.type != jvmType) {
  2090                 // reading the method attributes has caused the
  2091                 // symbol's type to be changed. (i.e. the Signature
  2092                 // attribute.)  This may happen if there are hidden
  2093                 // (synthetic) parameters in the descriptor, but not
  2094                 // in the Signature.  The position of these hidden
  2095                 // parameters is unspecified; for now, assume they are
  2096                 // at the beginning, and so skip over them. The
  2097                 // primary case for this is two hidden parameters
  2098                 // passed into Enum constructors.
  2099             int skip = Code.width(jvmType.getParameterTypes())
  2100                     - Code.width(sym.type.getParameterTypes());
  2101             firstParam += skip;
  2104         List<Name> paramNames = List.nil();
  2105         int index = firstParam;
  2106         for (Type t: sym.type.getParameterTypes()) {
  2107             int nameIdx = (index < parameterNameIndices.length
  2108                     ? parameterNameIndices[index] : 0);
  2109             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  2110             paramNames = paramNames.prepend(name);
  2111             index += Code.width(t);
  2113         sym.savedParameterNames = paramNames.reverse();
  2116     /**
  2117      * skip n bytes
  2118      */
  2119     void skipBytes(int n) {
  2120         bp = bp + n;
  2123     /** Skip a field or method
  2124      */
  2125     void skipMember() {
  2126         bp = bp + 6;
  2127         char ac = nextChar();
  2128         for (int i = 0; i < ac; i++) {
  2129             bp = bp + 2;
  2130             int attrLen = nextInt();
  2131             bp = bp + attrLen;
  2135     /** Enter type variables of this classtype and all enclosing ones in
  2136      *  `typevars'.
  2137      */
  2138     protected void enterTypevars(Type t) {
  2139         if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
  2140             enterTypevars(t.getEnclosingType());
  2141         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  2142             typevars.enter(xs.head.tsym);
  2145     protected void enterTypevars(Symbol sym) {
  2146         if (sym.owner.kind == MTH) {
  2147             enterTypevars(sym.owner);
  2148             enterTypevars(sym.owner.owner);
  2150         enterTypevars(sym.type);
  2153     /** Read contents of a given class symbol `c'. Both external and internal
  2154      *  versions of an inner class are read.
  2155      */
  2156     void readClass(ClassSymbol c) {
  2157         ClassType ct = (ClassType)c.type;
  2159         // allocate scope for members
  2160         c.members_field = new Scope(c);
  2162         // prepare type variable table
  2163         typevars = typevars.dup(currentOwner);
  2164         if (ct.getEnclosingType().hasTag(CLASS))
  2165             enterTypevars(ct.getEnclosingType());
  2167         // read flags, or skip if this is an inner class
  2168         long flags = adjustClassFlags(nextChar());
  2169         if (c.owner.kind == PCK) c.flags_field = flags;
  2171         // read own class name and check that it matches
  2172         ClassSymbol self = readClassSymbol(nextChar());
  2173         if (c != self)
  2174             throw badClassFile("class.file.wrong.class",
  2175                                self.flatname);
  2177         // class attributes must be read before class
  2178         // skip ahead to read class attributes
  2179         int startbp = bp;
  2180         nextChar();
  2181         char interfaceCount = nextChar();
  2182         bp += interfaceCount * 2;
  2183         char fieldCount = nextChar();
  2184         for (int i = 0; i < fieldCount; i++) skipMember();
  2185         char methodCount = nextChar();
  2186         for (int i = 0; i < methodCount; i++) skipMember();
  2187         readClassAttrs(c);
  2189         if (readAllOfClassFile) {
  2190             for (int i = 1; i < poolObj.length; i++) readPool(i);
  2191             c.pool = new Pool(poolObj.length, poolObj, types);
  2194         // reset and read rest of classinfo
  2195         bp = startbp;
  2196         int n = nextChar();
  2197         if (ct.supertype_field == null)
  2198             ct.supertype_field = (n == 0)
  2199                 ? Type.noType
  2200                 : readClassSymbol(n).erasure(types);
  2201         n = nextChar();
  2202         List<Type> is = List.nil();
  2203         for (int i = 0; i < n; i++) {
  2204             Type _inter = readClassSymbol(nextChar()).erasure(types);
  2205             is = is.prepend(_inter);
  2207         if (ct.interfaces_field == null)
  2208             ct.interfaces_field = is.reverse();
  2210         Assert.check(fieldCount == nextChar());
  2211         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  2212         Assert.check(methodCount == nextChar());
  2213         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  2215         typevars = typevars.leave();
  2218     /** Read inner class info. For each inner/outer pair allocate a
  2219      *  member class.
  2220      */
  2221     void readInnerClasses(ClassSymbol c) {
  2222         int n = nextChar();
  2223         for (int i = 0; i < n; i++) {
  2224             nextChar(); // skip inner class symbol
  2225             ClassSymbol outer = readClassSymbol(nextChar());
  2226             Name name = readName(nextChar());
  2227             if (name == null) name = names.empty;
  2228             long flags = adjustClassFlags(nextChar());
  2229             if (outer != null) { // we have a member class
  2230                 if (name == names.empty)
  2231                     name = names.one;
  2232                 ClassSymbol member = enterClass(name, outer);
  2233                 if ((flags & STATIC) == 0) {
  2234                     ((ClassType)member.type).setEnclosingType(outer.type);
  2235                     if (member.erasure_field != null)
  2236                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  2238                 if (c == outer) {
  2239                     member.flags_field = flags;
  2240                     enterMember(c, member);
  2246     /** Read a class file.
  2247      */
  2248     private void readClassFile(ClassSymbol c) throws IOException {
  2249         int magic = nextInt();
  2250         if (magic != JAVA_MAGIC)
  2251             throw badClassFile("illegal.start.of.class.file");
  2253         minorVersion = nextChar();
  2254         majorVersion = nextChar();
  2255         int maxMajor = Target.MAX().majorVersion;
  2256         int maxMinor = Target.MAX().minorVersion;
  2257         if (majorVersion > maxMajor ||
  2258             majorVersion * 1000 + minorVersion <
  2259             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  2261             if (majorVersion == (maxMajor + 1))
  2262                 log.warning("big.major.version",
  2263                             currentClassFile,
  2264                             majorVersion,
  2265                             maxMajor);
  2266             else
  2267                 throw badClassFile("wrong.version",
  2268                                    Integer.toString(majorVersion),
  2269                                    Integer.toString(minorVersion),
  2270                                    Integer.toString(maxMajor),
  2271                                    Integer.toString(maxMinor));
  2273         else if (checkClassFile &&
  2274                  majorVersion == maxMajor &&
  2275                  minorVersion > maxMinor)
  2277             printCCF("found.later.version",
  2278                      Integer.toString(minorVersion));
  2280         indexPool();
  2281         if (signatureBuffer.length < bp) {
  2282             int ns = Integer.highestOneBit(bp) << 1;
  2283             signatureBuffer = new byte[ns];
  2285         readClass(c);
  2288 /************************************************************************
  2289  * Adjusting flags
  2290  ***********************************************************************/
  2292     long adjustFieldFlags(long flags) {
  2293         return flags;
  2295     long adjustMethodFlags(long flags) {
  2296         if ((flags & ACC_BRIDGE) != 0) {
  2297             flags &= ~ACC_BRIDGE;
  2298             flags |= BRIDGE;
  2299             if (!allowGenerics)
  2300                 flags &= ~SYNTHETIC;
  2302         if ((flags & ACC_VARARGS) != 0) {
  2303             flags &= ~ACC_VARARGS;
  2304             flags |= VARARGS;
  2306         return flags;
  2308     long adjustClassFlags(long flags) {
  2309         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2312 /************************************************************************
  2313  * Loading Classes
  2314  ***********************************************************************/
  2316     /** Define a new class given its name and owner.
  2317      */
  2318     public ClassSymbol defineClass(Name name, Symbol owner) {
  2319         ClassSymbol c = new ClassSymbol(0, name, owner);
  2320         if (owner.kind == PCK)
  2321             Assert.checkNull(classes.get(c.flatname), c);
  2322         c.completer = this;
  2323         return c;
  2326     /** Create a new toplevel or member class symbol with given name
  2327      *  and owner and enter in `classes' unless already there.
  2328      */
  2329     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2330         Name flatname = TypeSymbol.formFlatName(name, owner);
  2331         ClassSymbol c = classes.get(flatname);
  2332         if (c == null) {
  2333             c = defineClass(name, owner);
  2334             classes.put(flatname, c);
  2335         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2336             // reassign fields of classes that might have been loaded with
  2337             // their flat names.
  2338             c.owner.members().remove(c);
  2339             c.name = name;
  2340             c.owner = owner;
  2341             c.fullname = ClassSymbol.formFullName(name, owner);
  2343         return c;
  2346     /**
  2347      * Creates a new toplevel class symbol with given flat name and
  2348      * given class (or source) file.
  2350      * @param flatName a fully qualified binary class name
  2351      * @param classFile the class file or compilation unit defining
  2352      * the class (may be {@code null})
  2353      * @return a newly created class symbol
  2354      * @throws AssertionError if the class symbol already exists
  2355      */
  2356     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2357         ClassSymbol cs = classes.get(flatName);
  2358         if (cs != null) {
  2359             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2360                                     cs.fullname,
  2361                                     cs.completer,
  2362                                     cs.classfile,
  2363                                     cs.sourcefile);
  2364             throw new AssertionError(msg);
  2366         Name packageName = Convert.packagePart(flatName);
  2367         PackageSymbol owner = packageName.isEmpty()
  2368                                 ? syms.unnamedPackage
  2369                                 : enterPackage(packageName);
  2370         cs = defineClass(Convert.shortName(flatName), owner);
  2371         cs.classfile = classFile;
  2372         classes.put(flatName, cs);
  2373         return cs;
  2376     /** Create a new member or toplevel class symbol with given flat name
  2377      *  and enter in `classes' unless already there.
  2378      */
  2379     public ClassSymbol enterClass(Name flatname) {
  2380         ClassSymbol c = classes.get(flatname);
  2381         if (c == null)
  2382             return enterClass(flatname, (JavaFileObject)null);
  2383         else
  2384             return c;
  2387     private boolean suppressFlush = false;
  2389     /** Completion for classes to be loaded. Before a class is loaded
  2390      *  we make sure its enclosing class (if any) is loaded.
  2391      */
  2392     public void complete(Symbol sym) throws CompletionFailure {
  2393         if (sym.kind == TYP) {
  2394             ClassSymbol c = (ClassSymbol)sym;
  2395             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2396             boolean saveSuppressFlush = suppressFlush;
  2397             suppressFlush = true;
  2398             try {
  2399                 completeOwners(c.owner);
  2400                 completeEnclosing(c);
  2401             } finally {
  2402                 suppressFlush = saveSuppressFlush;
  2404             fillIn(c);
  2405         } else if (sym.kind == PCK) {
  2406             PackageSymbol p = (PackageSymbol)sym;
  2407             try {
  2408                 fillIn(p);
  2409             } catch (IOException ex) {
  2410                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2413         if (!filling && !suppressFlush)
  2414             annotate.flush(); // finish attaching annotations
  2417     /** complete up through the enclosing package. */
  2418     private void completeOwners(Symbol o) {
  2419         if (o.kind != PCK) completeOwners(o.owner);
  2420         o.complete();
  2423     /**
  2424      * Tries to complete lexically enclosing classes if c looks like a
  2425      * nested class.  This is similar to completeOwners but handles
  2426      * the situation when a nested class is accessed directly as it is
  2427      * possible with the Tree API or javax.lang.model.*.
  2428      */
  2429     private void completeEnclosing(ClassSymbol c) {
  2430         if (c.owner.kind == PCK) {
  2431             Symbol owner = c.owner;
  2432             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2433                 Symbol encl = owner.members().lookup(name).sym;
  2434                 if (encl == null)
  2435                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2436                 if (encl != null)
  2437                     encl.complete();
  2442     /** We can only read a single class file at a time; this
  2443      *  flag keeps track of when we are currently reading a class
  2444      *  file.
  2445      */
  2446     private boolean filling = false;
  2448     /** Fill in definition of class `c' from corresponding class or
  2449      *  source file.
  2450      */
  2451     private void fillIn(ClassSymbol c) {
  2452         if (completionFailureName == c.fullname) {
  2453             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2455         currentOwner = c;
  2456         warnedAttrs.clear();
  2457         JavaFileObject classfile = c.classfile;
  2458         if (classfile != null) {
  2459             JavaFileObject previousClassFile = currentClassFile;
  2460             try {
  2461                 if (filling) {
  2462                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2464                 currentClassFile = classfile;
  2465                 if (verbose) {
  2466                     log.printVerbose("loading", currentClassFile.toString());
  2468                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2469                     filling = true;
  2470                     try {
  2471                         bp = 0;
  2472                         buf = readInputStream(buf, classfile.openInputStream());
  2473                         readClassFile(c);
  2474                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2475                             List<Type> missing = missingTypeVariables;
  2476                             List<Type> found = foundTypeVariables;
  2477                             missingTypeVariables = List.nil();
  2478                             foundTypeVariables = List.nil();
  2479                             filling = false;
  2480                             ClassType ct = (ClassType)currentOwner.type;
  2481                             ct.supertype_field =
  2482                                 types.subst(ct.supertype_field, missing, found);
  2483                             ct.interfaces_field =
  2484                                 types.subst(ct.interfaces_field, missing, found);
  2485                         } else if (missingTypeVariables.isEmpty() !=
  2486                                    foundTypeVariables.isEmpty()) {
  2487                             Name name = missingTypeVariables.head.tsym.name;
  2488                             throw badClassFile("undecl.type.var", name);
  2490                     } finally {
  2491                         missingTypeVariables = List.nil();
  2492                         foundTypeVariables = List.nil();
  2493                         filling = false;
  2495                 } else {
  2496                     if (sourceCompleter != null) {
  2497                         sourceCompleter.complete(c);
  2498                     } else {
  2499                         throw new IllegalStateException("Source completer required to read "
  2500                                                         + classfile.toUri());
  2503                 return;
  2504             } catch (IOException ex) {
  2505                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2506             } finally {
  2507                 currentClassFile = previousClassFile;
  2509         } else {
  2510             JCDiagnostic diag =
  2511                 diagFactory.fragment("class.file.not.found", c.flatname);
  2512             throw
  2513                 newCompletionFailure(c, diag);
  2516     // where
  2517         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2518             try {
  2519                 buf = ensureCapacity(buf, s.available());
  2520                 int r = s.read(buf);
  2521                 int bp = 0;
  2522                 while (r != -1) {
  2523                     bp += r;
  2524                     buf = ensureCapacity(buf, bp);
  2525                     r = s.read(buf, bp, buf.length - bp);
  2527                 return buf;
  2528             } finally {
  2529                 try {
  2530                     s.close();
  2531                 } catch (IOException e) {
  2532                     /* Ignore any errors, as this stream may have already
  2533                      * thrown a related exception which is the one that
  2534                      * should be reported.
  2535                      */
  2539         /*
  2540          * ensureCapacity will increase the buffer as needed, taking note that
  2541          * the new buffer will always be greater than the needed and never
  2542          * exactly equal to the needed size or bp. If equal then the read (above)
  2543          * will infinitely loop as buf.length - bp == 0.
  2544          */
  2545         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2546             if (buf.length <= needed) {
  2547                 byte[] old = buf;
  2548                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2549                 System.arraycopy(old, 0, buf, 0, old.length);
  2551             return buf;
  2553         /** Static factory for CompletionFailure objects.
  2554          *  In practice, only one can be used at a time, so we share one
  2555          *  to reduce the expense of allocating new exception objects.
  2556          */
  2557         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2558                                                        JCDiagnostic diag) {
  2559             if (!cacheCompletionFailure) {
  2560                 // log.warning("proc.messager",
  2561                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2562                 // c.debug.printStackTrace();
  2563                 return new CompletionFailure(c, diag);
  2564             } else {
  2565                 CompletionFailure result = cachedCompletionFailure;
  2566                 result.sym = c;
  2567                 result.diag = diag;
  2568                 return result;
  2571         private CompletionFailure cachedCompletionFailure =
  2572             new CompletionFailure(null, (JCDiagnostic) null);
  2574             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2577     /** Load a toplevel class with given fully qualified name
  2578      *  The class is entered into `classes' only if load was successful.
  2579      */
  2580     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2581         boolean absent = classes.get(flatname) == null;
  2582         ClassSymbol c = enterClass(flatname);
  2583         if (c.members_field == null && c.completer != null) {
  2584             try {
  2585                 c.complete();
  2586             } catch (CompletionFailure ex) {
  2587                 if (absent) classes.remove(flatname);
  2588                 throw ex;
  2591         return c;
  2594 /************************************************************************
  2595  * Loading Packages
  2596  ***********************************************************************/
  2598     /** Check to see if a package exists, given its fully qualified name.
  2599      */
  2600     public boolean packageExists(Name fullname) {
  2601         return enterPackage(fullname).exists();
  2604     /** Make a package, given its fully qualified name.
  2605      */
  2606     public PackageSymbol enterPackage(Name fullname) {
  2607         PackageSymbol p = packages.get(fullname);
  2608         if (p == null) {
  2609             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2610             p = new PackageSymbol(
  2611                 Convert.shortName(fullname),
  2612                 enterPackage(Convert.packagePart(fullname)));
  2613             p.completer = this;
  2614             packages.put(fullname, p);
  2616         return p;
  2619     /** Make a package, given its unqualified name and enclosing package.
  2620      */
  2621     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2622         return enterPackage(TypeSymbol.formFullName(name, owner));
  2625     /** Include class corresponding to given class file in package,
  2626      *  unless (1) we already have one the same kind (.class or .java), or
  2627      *         (2) we have one of the other kind, and the given class file
  2628      *             is older.
  2629      */
  2630     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2631         if ((p.flags_field & EXISTS) == 0)
  2632             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2633                 q.flags_field |= EXISTS;
  2634         JavaFileObject.Kind kind = file.getKind();
  2635         int seen;
  2636         if (kind == JavaFileObject.Kind.CLASS)
  2637             seen = CLASS_SEEN;
  2638         else
  2639             seen = SOURCE_SEEN;
  2640         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2641         int lastDot = binaryName.lastIndexOf(".");
  2642         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2643         boolean isPkgInfo = classname == names.package_info;
  2644         ClassSymbol c = isPkgInfo
  2645             ? p.package_info
  2646             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2647         if (c == null) {
  2648             c = enterClass(classname, p);
  2649             if (c.classfile == null) // only update the file if's it's newly created
  2650                 c.classfile = file;
  2651             if (isPkgInfo) {
  2652                 p.package_info = c;
  2653             } else {
  2654                 if (c.owner == p)  // it might be an inner class
  2655                     p.members_field.enter(c);
  2657         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2658             // if c.classfile == null, we are currently compiling this class
  2659             // and no further action is necessary.
  2660             // if (c.flags_field & seen) != 0, we have already encountered
  2661             // a file of the same kind; again no further action is necessary.
  2662             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2663                 c.classfile = preferredFileObject(file, c.classfile);
  2665         c.flags_field |= seen;
  2668     /** Implement policy to choose to derive information from a source
  2669      *  file or a class file when both are present.  May be overridden
  2670      *  by subclasses.
  2671      */
  2672     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2673                                            JavaFileObject b) {
  2675         if (preferSource)
  2676             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2677         else {
  2678             long adate = a.getLastModified();
  2679             long bdate = b.getLastModified();
  2680             // 6449326: policy for bad lastModifiedTime in ClassReader
  2681             //assert adate >= 0 && bdate >= 0;
  2682             return (adate > bdate) ? a : b;
  2686     /**
  2687      * specifies types of files to be read when filling in a package symbol
  2688      */
  2689     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2690         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2693     /**
  2694      * this is used to support javadoc
  2695      */
  2696     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2699     protected Location currentLoc; // FIXME
  2701     private boolean verbosePath = true;
  2703     /** Load directory of package into members scope.
  2704      */
  2705     private void fillIn(PackageSymbol p) throws IOException {
  2706         if (p.members_field == null) p.members_field = new Scope(p);
  2707         String packageName = p.fullname.toString();
  2709         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2711         fillIn(p, PLATFORM_CLASS_PATH,
  2712                fileManager.list(PLATFORM_CLASS_PATH,
  2713                                 packageName,
  2714                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2715                                 false));
  2717         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2718         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2719         boolean wantClassFiles = !classKinds.isEmpty();
  2721         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2722         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2723         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2725         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2727         if (verbose && verbosePath) {
  2728             if (fileManager instanceof StandardJavaFileManager) {
  2729                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2730                 if (haveSourcePath && wantSourceFiles) {
  2731                     List<File> path = List.nil();
  2732                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2733                         path = path.prepend(file);
  2735                     log.printVerbose("sourcepath", path.reverse().toString());
  2736                 } else if (wantSourceFiles) {
  2737                     List<File> path = List.nil();
  2738                     for (File file : fm.getLocation(CLASS_PATH)) {
  2739                         path = path.prepend(file);
  2741                     log.printVerbose("sourcepath", path.reverse().toString());
  2743                 if (wantClassFiles) {
  2744                     List<File> path = List.nil();
  2745                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2746                         path = path.prepend(file);
  2748                     for (File file : fm.getLocation(CLASS_PATH)) {
  2749                         path = path.prepend(file);
  2751                     log.printVerbose("classpath",  path.reverse().toString());
  2756         if (wantSourceFiles && !haveSourcePath) {
  2757             fillIn(p, CLASS_PATH,
  2758                    fileManager.list(CLASS_PATH,
  2759                                     packageName,
  2760                                     kinds,
  2761                                     false));
  2762         } else {
  2763             if (wantClassFiles)
  2764                 fillIn(p, CLASS_PATH,
  2765                        fileManager.list(CLASS_PATH,
  2766                                         packageName,
  2767                                         classKinds,
  2768                                         false));
  2769             if (wantSourceFiles)
  2770                 fillIn(p, SOURCE_PATH,
  2771                        fileManager.list(SOURCE_PATH,
  2772                                         packageName,
  2773                                         sourceKinds,
  2774                                         false));
  2776         verbosePath = false;
  2778     // where
  2779         private void fillIn(PackageSymbol p,
  2780                             Location location,
  2781                             Iterable<JavaFileObject> files)
  2783             currentLoc = location;
  2784             for (JavaFileObject fo : files) {
  2785                 switch (fo.getKind()) {
  2786                 case CLASS:
  2787                 case SOURCE: {
  2788                     // TODO pass binaryName to includeClassFile
  2789                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2790                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2791                     if (SourceVersion.isIdentifier(simpleName) ||
  2792                         simpleName.equals("package-info"))
  2793                         includeClassFile(p, fo);
  2794                     break;
  2796                 default:
  2797                     extraFileActions(p, fo);
  2802     /** Output for "-checkclassfile" option.
  2803      *  @param key The key to look up the correct internationalized string.
  2804      *  @param arg An argument for substitution into the output string.
  2805      */
  2806     private void printCCF(String key, Object arg) {
  2807         log.printLines(key, arg);
  2811     public interface SourceCompleter {
  2812         void complete(ClassSymbol sym)
  2813             throws CompletionFailure;
  2816     /**
  2817      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2818      * The attribute is only the last component of the original filename, so is unlikely
  2819      * to be valid as is, so operations other than those to access the name throw
  2820      * UnsupportedOperationException
  2821      */
  2822     private static class SourceFileObject extends BaseFileObject {
  2824         /** The file's name.
  2825          */
  2826         private Name name;
  2827         private Name flatname;
  2829         public SourceFileObject(Name name, Name flatname) {
  2830             super(null); // no file manager; never referenced for this file object
  2831             this.name = name;
  2832             this.flatname = flatname;
  2835         @Override
  2836         public URI toUri() {
  2837             try {
  2838                 return new URI(null, name.toString(), null);
  2839             } catch (URISyntaxException e) {
  2840                 throw new CannotCreateUriError(name.toString(), e);
  2844         @Override
  2845         public String getName() {
  2846             return name.toString();
  2849         @Override
  2850         public String getShortName() {
  2851             return getName();
  2854         @Override
  2855         public JavaFileObject.Kind getKind() {
  2856             return getKind(getName());
  2859         @Override
  2860         public InputStream openInputStream() {
  2861             throw new UnsupportedOperationException();
  2864         @Override
  2865         public OutputStream openOutputStream() {
  2866             throw new UnsupportedOperationException();
  2869         @Override
  2870         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2871             throw new UnsupportedOperationException();
  2874         @Override
  2875         public Reader openReader(boolean ignoreEncodingErrors) {
  2876             throw new UnsupportedOperationException();
  2879         @Override
  2880         public Writer openWriter() {
  2881             throw new UnsupportedOperationException();
  2884         @Override
  2885         public long getLastModified() {
  2886             throw new UnsupportedOperationException();
  2889         @Override
  2890         public boolean delete() {
  2891             throw new UnsupportedOperationException();
  2894         @Override
  2895         protected String inferBinaryName(Iterable<? extends File> path) {
  2896             return flatname.toString();
  2899         @Override
  2900         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2901             return true; // fail-safe mode
  2904         /**
  2905          * Check if two file objects are equal.
  2906          * SourceFileObjects are just placeholder objects for the value of a
  2907          * SourceFile attribute, and do not directly represent specific files.
  2908          * Two SourceFileObjects are equal if their names are equal.
  2909          */
  2910         @Override
  2911         public boolean equals(Object other) {
  2912             if (this == other)
  2913                 return true;
  2915             if (!(other instanceof SourceFileObject))
  2916                 return false;
  2918             SourceFileObject o = (SourceFileObject) other;
  2919             return name.equals(o.name);
  2922         @Override
  2923         public int hashCode() {
  2924             return name.hashCode();

mercurial