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

Thu, 06 Feb 2014 21:03:03 +0000

author
vromero
date
Thu, 06 Feb 2014 21:03:03 +0000
changeset 2260
fb870c70e774
parent 2136
7f6481e5fe3a
child 2375
3a2ebbad5911
permissions
-rw-r--r--

8029240: Default methods not always visible under -source 7
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.jvm;
    28 import java.io.*;
    29 import java.net.URI;
    30 import java.net.URISyntaxException;
    31 import java.nio.CharBuffer;
    32 import java.util.Arrays;
    33 import java.util.EnumSet;
    34 import java.util.HashMap;
    35 import java.util.HashSet;
    36 import java.util.Map;
    37 import java.util.Set;
    38 import javax.lang.model.SourceVersion;
    39 import javax.tools.JavaFileObject;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileManager.Location;
    42 import javax.tools.StandardJavaFileManager;
    44 import static javax.tools.StandardLocation.*;
    46 import com.sun.tools.javac.comp.Annotate;
    47 import com.sun.tools.javac.code.*;
    48 import com.sun.tools.javac.code.Lint.LintCategory;
    49 import com.sun.tools.javac.code.Type.*;
    50 import com.sun.tools.javac.code.Symbol.*;
    51 import com.sun.tools.javac.code.Symtab;
    52 import com.sun.tools.javac.file.BaseFileObject;
    53 import com.sun.tools.javac.util.*;
    54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.TypeTag.CLASS;
    59 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    60 import static com.sun.tools.javac.jvm.ClassFile.*;
    61 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
    63 import static com.sun.tools.javac.main.Option.*;
    65 /** This class provides operations to read a classfile into an internal
    66  *  representation. The internal representation is anchored in a
    67  *  ClassSymbol which contains in its scope symbol representations
    68  *  for all other definitions in the classfile. Top-level Classes themselves
    69  *  appear as members of the scopes of PackageSymbols.
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class ClassReader {
    77     /** The context key for the class reader. */
    78     protected static final Context.Key<ClassReader> classReaderKey =
    79         new Context.Key<ClassReader>();
    81     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
    83     Annotate annotate;
    85     /** Switch: verbose output.
    86      */
    87     boolean verbose;
    89     /** Switch: check class file for correct minor version, unrecognized
    90      *  attributes.
    91      */
    92     boolean checkClassFile;
    94     /** Switch: read constant pool and code sections. This switch is initially
    95      *  set to false but can be turned on from outside.
    96      */
    97     public boolean readAllOfClassFile = false;
    99     /** Switch: read GJ signature information.
   100      */
   101     boolean allowGenerics;
   103     /** Switch: read varargs attribute.
   104      */
   105     boolean allowVarargs;
   107     /** Switch: allow annotations.
   108      */
   109     boolean allowAnnotations;
   111     /** Switch: allow simplified varargs.
   112      */
   113     boolean allowSimplifiedVarargs;
   115    /** Lint option: warn about classfile issues
   116      */
   117     boolean lintClassfile;
   119     /** Switch: preserve parameter names from the variable table.
   120      */
   121     public boolean saveParameterNames;
   123     /**
   124      * Switch: cache completion failures unless -XDdev is used
   125      */
   126     private boolean cacheCompletionFailure;
   128     /**
   129      * Switch: prefer source files instead of newer when both source
   130      * and class are available
   131      **/
   132     public boolean preferSource;
   134     /**
   135      * The currently selected profile.
   136      */
   137     public final Profile profile;
   139     /** The log to use for verbose output
   140      */
   141     final Log log;
   143     /** The symbol table. */
   144     Symtab syms;
   146     Types types;
   148     /** The name table. */
   149     final Names names;
   151     /** Force a completion failure on this name
   152      */
   153     final Name completionFailureName;
   155     /** Access to files
   156      */
   157     private final JavaFileManager fileManager;
   159     /** Factory for diagnostics
   160      */
   161     JCDiagnostic.Factory diagFactory;
   163     /** Can be reassigned from outside:
   164      *  the completer to be used for ".java" files. If this remains unassigned
   165      *  ".java" files will not be loaded.
   166      */
   167     public SourceCompleter sourceCompleter = null;
   169     /** A hashtable containing the encountered top-level and member classes,
   170      *  indexed by flat names. The table does not contain local classes.
   171      */
   172     private Map<Name,ClassSymbol> classes;
   174     /** A hashtable containing the encountered packages.
   175      */
   176     private Map<Name, PackageSymbol> packages;
   178     /** The current scope where type variables are entered.
   179      */
   180     protected Scope typevars;
   182     /** The path name of the class file currently being read.
   183      */
   184     protected JavaFileObject currentClassFile = null;
   186     /** The class or method currently being read.
   187      */
   188     protected Symbol currentOwner = null;
   190     /** The buffer containing the currently read class file.
   191      */
   192     byte[] buf = new byte[INITIAL_BUFFER_SIZE];
   194     /** The current input pointer.
   195      */
   196     protected int bp;
   198     /** The objects of the constant pool.
   199      */
   200     Object[] poolObj;
   202     /** For every constant pool entry, an index into buf where the
   203      *  defining section of the entry is found.
   204      */
   205     int[] poolIdx;
   207     /** The major version number of the class file being read. */
   208     int majorVersion;
   209     /** The minor version number of the class file being read. */
   210     int minorVersion;
   212     /** A table to hold the constant pool indices for method parameter
   213      * names, as given in LocalVariableTable attributes.
   214      */
   215     int[] parameterNameIndices;
   217     /**
   218      * Whether or not any parameter names have been found.
   219      */
   220     boolean haveParameterNameIndices;
   222     /** Set this to false every time we start reading a method
   223      * and are saving parameter names.  Set it to true when we see
   224      * MethodParameters, if it's set when we see a LocalVariableTable,
   225      * then we ignore the parameter names from the LVT.
   226      */
   227     boolean sawMethodParameters;
   229     /**
   230      * The set of attribute names for which warnings have been generated for the current class
   231      */
   232     Set<Name> warnedAttrs = new HashSet<Name>();
   234     /**
   235      * Completer that delegates to the complete-method of this class.
   236      */
   237     private final Completer thisCompleter = new Completer() {
   238         @Override
   239         public void complete(Symbol sym) throws CompletionFailure {
   240             ClassReader.this.complete(sym);
   241         }
   242     };
   245     /** Get the ClassReader instance for this invocation. */
   246     public static ClassReader instance(Context context) {
   247         ClassReader instance = context.get(classReaderKey);
   248         if (instance == null)
   249             instance = new ClassReader(context, true);
   250         return instance;
   251     }
   253     /** Initialize classes and packages, treating this as the definitive classreader. */
   254     public void init(Symtab syms) {
   255         init(syms, true);
   256     }
   258     /** Initialize classes and packages, optionally treating this as
   259      *  the definitive classreader.
   260      */
   261     private void init(Symtab syms, boolean definitive) {
   262         if (classes != null) return;
   264         if (definitive) {
   265             Assert.check(packages == null || packages == syms.packages);
   266             packages = syms.packages;
   267             Assert.check(classes == null || classes == syms.classes);
   268             classes = syms.classes;
   269         } else {
   270             packages = new HashMap<Name, PackageSymbol>();
   271             classes = new HashMap<Name, ClassSymbol>();
   272         }
   274         packages.put(names.empty, syms.rootPackage);
   275         syms.rootPackage.completer = thisCompleter;
   276         syms.unnamedPackage.completer = thisCompleter;
   277     }
   279     /** Construct a new class reader, optionally treated as the
   280      *  definitive classreader for this invocation.
   281      */
   282     protected ClassReader(Context context, boolean definitive) {
   283         if (definitive) context.put(classReaderKey, this);
   285         names = Names.instance(context);
   286         syms = Symtab.instance(context);
   287         types = Types.instance(context);
   288         fileManager = context.get(JavaFileManager.class);
   289         if (fileManager == null)
   290             throw new AssertionError("FileManager initialization error");
   291         diagFactory = JCDiagnostic.Factory.instance(context);
   293         init(syms, definitive);
   294         log = Log.instance(context);
   296         Options options = Options.instance(context);
   297         annotate = Annotate.instance(context);
   298         verbose        = options.isSet(VERBOSE);
   299         checkClassFile = options.isSet("-checkclassfile");
   301         Source source = Source.instance(context);
   302         allowGenerics    = source.allowGenerics();
   303         allowVarargs     = source.allowVarargs();
   304         allowAnnotations = source.allowAnnotations();
   305         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   307         saveParameterNames = options.isSet("save-parameter-names");
   308         cacheCompletionFailure = options.isUnset("dev");
   309         preferSource = "source".equals(options.get("-Xprefer"));
   311         profile = Profile.instance(context);
   313         completionFailureName =
   314             options.isSet("failcomplete")
   315             ? names.fromString(options.get("failcomplete"))
   316             : null;
   318         typevars = new Scope(syms.noSymbol);
   320         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
   322         initAttributeReaders();
   323     }
   325     /** Add member to class unless it is synthetic.
   326      */
   327     private void enterMember(ClassSymbol c, Symbol sym) {
   328         // Synthetic members are not entered -- reason lost to history (optimization?).
   329         // Lambda methods must be entered because they may have inner classes (which reference them)
   330         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
   331             c.members_field.enter(sym);
   332     }
   334 /************************************************************************
   335  * Error Diagnoses
   336  ***********************************************************************/
   339     public class BadClassFile extends CompletionFailure {
   340         private static final long serialVersionUID = 0;
   342         public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
   343             super(sym, createBadClassFileDiagnostic(file, diag));
   344         }
   345     }
   346     // where
   347     private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
   348         String key = (file.getKind() == JavaFileObject.Kind.SOURCE
   349                     ? "bad.source.file.header" : "bad.class.file.header");
   350         return diagFactory.fragment(key, file, diag);
   351     }
   353     public BadClassFile badClassFile(String key, Object... args) {
   354         return new BadClassFile (
   355             currentOwner.enclClass(),
   356             currentClassFile,
   357             diagFactory.fragment(key, args));
   358     }
   360 /************************************************************************
   361  * Buffer Access
   362  ***********************************************************************/
   364     /** Read a character.
   365      */
   366     char nextChar() {
   367         return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
   368     }
   370     /** Read a byte.
   371      */
   372     int nextByte() {
   373         return buf[bp++] & 0xFF;
   374     }
   376     /** Read an integer.
   377      */
   378     int nextInt() {
   379         return
   380             ((buf[bp++] & 0xFF) << 24) +
   381             ((buf[bp++] & 0xFF) << 16) +
   382             ((buf[bp++] & 0xFF) << 8) +
   383             (buf[bp++] & 0xFF);
   384     }
   386     /** Extract a character at position bp from buf.
   387      */
   388     char getChar(int bp) {
   389         return
   390             (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
   391     }
   393     /** Extract an integer at position bp from buf.
   394      */
   395     int getInt(int bp) {
   396         return
   397             ((buf[bp] & 0xFF) << 24) +
   398             ((buf[bp+1] & 0xFF) << 16) +
   399             ((buf[bp+2] & 0xFF) << 8) +
   400             (buf[bp+3] & 0xFF);
   401     }
   404     /** Extract a long integer at position bp from buf.
   405      */
   406     long getLong(int bp) {
   407         DataInputStream bufin =
   408             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   409         try {
   410             return bufin.readLong();
   411         } catch (IOException e) {
   412             throw new AssertionError(e);
   413         }
   414     }
   416     /** Extract a float at position bp from buf.
   417      */
   418     float getFloat(int bp) {
   419         DataInputStream bufin =
   420             new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
   421         try {
   422             return bufin.readFloat();
   423         } catch (IOException e) {
   424             throw new AssertionError(e);
   425         }
   426     }
   428     /** Extract a double at position bp from buf.
   429      */
   430     double getDouble(int bp) {
   431         DataInputStream bufin =
   432             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   433         try {
   434             return bufin.readDouble();
   435         } catch (IOException e) {
   436             throw new AssertionError(e);
   437         }
   438     }
   440 /************************************************************************
   441  * Constant Pool Access
   442  ***********************************************************************/
   444     /** Index all constant pool entries, writing their start addresses into
   445      *  poolIdx.
   446      */
   447     void indexPool() {
   448         poolIdx = new int[nextChar()];
   449         poolObj = new Object[poolIdx.length];
   450         int i = 1;
   451         while (i < poolIdx.length) {
   452             poolIdx[i++] = bp;
   453             byte tag = buf[bp++];
   454             switch (tag) {
   455             case CONSTANT_Utf8: case CONSTANT_Unicode: {
   456                 int len = nextChar();
   457                 bp = bp + len;
   458                 break;
   459             }
   460             case CONSTANT_Class:
   461             case CONSTANT_String:
   462             case CONSTANT_MethodType:
   463                 bp = bp + 2;
   464                 break;
   465             case CONSTANT_MethodHandle:
   466                 bp = bp + 3;
   467                 break;
   468             case CONSTANT_Fieldref:
   469             case CONSTANT_Methodref:
   470             case CONSTANT_InterfaceMethodref:
   471             case CONSTANT_NameandType:
   472             case CONSTANT_Integer:
   473             case CONSTANT_Float:
   474             case CONSTANT_InvokeDynamic:
   475                 bp = bp + 4;
   476                 break;
   477             case CONSTANT_Long:
   478             case CONSTANT_Double:
   479                 bp = bp + 8;
   480                 i++;
   481                 break;
   482             default:
   483                 throw badClassFile("bad.const.pool.tag.at",
   484                                    Byte.toString(tag),
   485                                    Integer.toString(bp -1));
   486             }
   487         }
   488     }
   490     /** Read constant pool entry at start address i, use pool as a cache.
   491      */
   492     Object readPool(int i) {
   493         Object result = poolObj[i];
   494         if (result != null) return result;
   496         int index = poolIdx[i];
   497         if (index == 0) return null;
   499         byte tag = buf[index];
   500         switch (tag) {
   501         case CONSTANT_Utf8:
   502             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   503             break;
   504         case CONSTANT_Unicode:
   505             throw badClassFile("unicode.str.not.supported");
   506         case CONSTANT_Class:
   507             poolObj[i] = readClassOrType(getChar(index + 1));
   508             break;
   509         case CONSTANT_String:
   510             // FIXME: (footprint) do not use toString here
   511             poolObj[i] = readName(getChar(index + 1)).toString();
   512             break;
   513         case CONSTANT_Fieldref: {
   514             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   515             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   516             poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
   517             break;
   518         }
   519         case CONSTANT_Methodref:
   520         case CONSTANT_InterfaceMethodref: {
   521             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   522             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   523             poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
   524             break;
   525         }
   526         case CONSTANT_NameandType:
   527             poolObj[i] = new NameAndType(
   528                 readName(getChar(index + 1)),
   529                 readType(getChar(index + 3)), types);
   530             break;
   531         case CONSTANT_Integer:
   532             poolObj[i] = getInt(index + 1);
   533             break;
   534         case CONSTANT_Float:
   535             poolObj[i] = new Float(getFloat(index + 1));
   536             break;
   537         case CONSTANT_Long:
   538             poolObj[i] = new Long(getLong(index + 1));
   539             break;
   540         case CONSTANT_Double:
   541             poolObj[i] = new Double(getDouble(index + 1));
   542             break;
   543         case CONSTANT_MethodHandle:
   544             skipBytes(4);
   545             break;
   546         case CONSTANT_MethodType:
   547             skipBytes(3);
   548             break;
   549         case CONSTANT_InvokeDynamic:
   550             skipBytes(5);
   551             break;
   552         default:
   553             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   554         }
   555         return poolObj[i];
   556     }
   558     /** Read signature and convert to type.
   559      */
   560     Type readType(int i) {
   561         int index = poolIdx[i];
   562         return sigToType(buf, index + 3, getChar(index + 1));
   563     }
   565     /** If name is an array type or class signature, return the
   566      *  corresponding type; otherwise return a ClassSymbol with given name.
   567      */
   568     Object readClassOrType(int i) {
   569         int index =  poolIdx[i];
   570         int len = getChar(index + 1);
   571         int start = index + 3;
   572         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   573         // by the above assertion, the following test can be
   574         // simplified to (buf[start] == '[')
   575         return (buf[start] == '[' || buf[start + len - 1] == ';')
   576             ? (Object)sigToType(buf, start, len)
   577             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   578                                                            len)));
   579     }
   581     /** Read signature and convert to type parameters.
   582      */
   583     List<Type> readTypeParams(int i) {
   584         int index = poolIdx[i];
   585         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   586     }
   588     /** Read class entry.
   589      */
   590     ClassSymbol readClassSymbol(int i) {
   591         return (ClassSymbol) (readPool(i));
   592     }
   594     /** Read name.
   595      */
   596     Name readName(int i) {
   597         return (Name) (readPool(i));
   598     }
   600 /************************************************************************
   601  * Reading Types
   602  ***********************************************************************/
   604     /** The unread portion of the currently read type is
   605      *  signature[sigp..siglimit-1].
   606      */
   607     byte[] signature;
   608     int sigp;
   609     int siglimit;
   610     boolean sigEnterPhase = false;
   612     /** Convert signature to type, where signature is a byte array segment.
   613      */
   614     Type sigToType(byte[] sig, int offset, int len) {
   615         signature = sig;
   616         sigp = offset;
   617         siglimit = offset + len;
   618         return sigToType();
   619     }
   621     /** Convert signature to type, where signature is implicit.
   622      */
   623     Type sigToType() {
   624         switch ((char) signature[sigp]) {
   625         case 'T':
   626             sigp++;
   627             int start = sigp;
   628             while (signature[sigp] != ';') sigp++;
   629             sigp++;
   630             return sigEnterPhase
   631                 ? Type.noType
   632                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   633         case '+': {
   634             sigp++;
   635             Type t = sigToType();
   636             return new WildcardType(t, BoundKind.EXTENDS,
   637                                     syms.boundClass);
   638         }
   639         case '*':
   640             sigp++;
   641             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   642                                     syms.boundClass);
   643         case '-': {
   644             sigp++;
   645             Type t = sigToType();
   646             return new WildcardType(t, BoundKind.SUPER,
   647                                     syms.boundClass);
   648         }
   649         case 'B':
   650             sigp++;
   651             return syms.byteType;
   652         case 'C':
   653             sigp++;
   654             return syms.charType;
   655         case 'D':
   656             sigp++;
   657             return syms.doubleType;
   658         case 'F':
   659             sigp++;
   660             return syms.floatType;
   661         case 'I':
   662             sigp++;
   663             return syms.intType;
   664         case 'J':
   665             sigp++;
   666             return syms.longType;
   667         case 'L':
   668             {
   669                 // int oldsigp = sigp;
   670                 Type t = classSigToType();
   671                 if (sigp < siglimit && signature[sigp] == '.')
   672                     throw badClassFile("deprecated inner class signature syntax " +
   673                                        "(please recompile from source)");
   674                 /*
   675                 System.err.println(" decoded " +
   676                                    new String(signature, oldsigp, sigp-oldsigp) +
   677                                    " => " + t + " outer " + t.outer());
   678                 */
   679                 return t;
   680             }
   681         case 'S':
   682             sigp++;
   683             return syms.shortType;
   684         case 'V':
   685             sigp++;
   686             return syms.voidType;
   687         case 'Z':
   688             sigp++;
   689             return syms.booleanType;
   690         case '[':
   691             sigp++;
   692             return new ArrayType(sigToType(), syms.arrayClass);
   693         case '(':
   694             sigp++;
   695             List<Type> argtypes = sigToTypes(')');
   696             Type restype = sigToType();
   697             List<Type> thrown = List.nil();
   698             while (signature[sigp] == '^') {
   699                 sigp++;
   700                 thrown = thrown.prepend(sigToType());
   701             }
   702             // if there is a typevar in the throws clause we should state it.
   703             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
   704                 if (l.head.hasTag(TYPEVAR)) {
   705                     l.head.tsym.flags_field |= THROWS;
   706                 }
   707             }
   708             return new MethodType(argtypes,
   709                                   restype,
   710                                   thrown.reverse(),
   711                                   syms.methodClass);
   712         case '<':
   713             typevars = typevars.dup(currentOwner);
   714             Type poly = new ForAll(sigToTypeParams(), sigToType());
   715             typevars = typevars.leave();
   716             return poly;
   717         default:
   718             throw badClassFile("bad.signature",
   719                                Convert.utf2string(signature, sigp, 10));
   720         }
   721     }
   723     byte[] signatureBuffer = new byte[0];
   724     int sbp = 0;
   725     /** Convert class signature to type, where signature is implicit.
   726      */
   727     Type classSigToType() {
   728         if (signature[sigp] != 'L')
   729             throw badClassFile("bad.class.signature",
   730                                Convert.utf2string(signature, sigp, 10));
   731         sigp++;
   732         Type outer = Type.noType;
   733         int startSbp = sbp;
   735         while (true) {
   736             final byte c = signature[sigp++];
   737             switch (c) {
   739             case ';': {         // end
   740                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   741                                                          startSbp,
   742                                                          sbp - startSbp));
   744                 try {
   745                     return (outer == Type.noType) ?
   746                             t.erasure(types) :
   747                             new ClassType(outer, List.<Type>nil(), t);
   748                 } finally {
   749                     sbp = startSbp;
   750                 }
   751             }
   753             case '<':           // generic arguments
   754                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   755                                                          startSbp,
   756                                                          sbp - startSbp));
   757                 outer = new ClassType(outer, sigToTypes('>'), t) {
   758                         boolean completed = false;
   759                         @Override
   760                         public Type getEnclosingType() {
   761                             if (!completed) {
   762                                 completed = true;
   763                                 tsym.complete();
   764                                 Type enclosingType = tsym.type.getEnclosingType();
   765                                 if (enclosingType != Type.noType) {
   766                                     List<Type> typeArgs =
   767                                         super.getEnclosingType().allparams();
   768                                     List<Type> typeParams =
   769                                         enclosingType.allparams();
   770                                     if (typeParams.length() != typeArgs.length()) {
   771                                         // no "rare" types
   772                                         super.setEnclosingType(types.erasure(enclosingType));
   773                                     } else {
   774                                         super.setEnclosingType(types.subst(enclosingType,
   775                                                                            typeParams,
   776                                                                            typeArgs));
   777                                     }
   778                                 } else {
   779                                     super.setEnclosingType(Type.noType);
   780                                 }
   781                             }
   782                             return super.getEnclosingType();
   783                         }
   784                         @Override
   785                         public void setEnclosingType(Type outer) {
   786                             throw new UnsupportedOperationException();
   787                         }
   788                     };
   789                 switch (signature[sigp++]) {
   790                 case ';':
   791                     if (sigp < signature.length && signature[sigp] == '.') {
   792                         // support old-style GJC signatures
   793                         // The signature produced was
   794                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   795                         // rather than say
   796                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   797                         // so we skip past ".Lfoo/Outer$"
   798                         sigp += (sbp - startSbp) + // "foo/Outer"
   799                             3;  // ".L" and "$"
   800                         signatureBuffer[sbp++] = (byte)'$';
   801                         break;
   802                     } else {
   803                         sbp = startSbp;
   804                         return outer;
   805                     }
   806                 case '.':
   807                     signatureBuffer[sbp++] = (byte)'$';
   808                     break;
   809                 default:
   810                     throw new AssertionError(signature[sigp-1]);
   811                 }
   812                 continue;
   814             case '.':
   815                 //we have seen an enclosing non-generic class
   816                 if (outer != Type.noType) {
   817                     t = enterClass(names.fromUtf(signatureBuffer,
   818                                                  startSbp,
   819                                                  sbp - startSbp));
   820                     outer = new ClassType(outer, List.<Type>nil(), t);
   821                 }
   822                 signatureBuffer[sbp++] = (byte)'$';
   823                 continue;
   824             case '/':
   825                 signatureBuffer[sbp++] = (byte)'.';
   826                 continue;
   827             default:
   828                 signatureBuffer[sbp++] = c;
   829                 continue;
   830             }
   831         }
   832     }
   834     /** Convert (implicit) signature to list of types
   835      *  until `terminator' is encountered.
   836      */
   837     List<Type> sigToTypes(char terminator) {
   838         List<Type> head = List.of(null);
   839         List<Type> tail = head;
   840         while (signature[sigp] != terminator)
   841             tail = tail.setTail(List.of(sigToType()));
   842         sigp++;
   843         return head.tail;
   844     }
   846     /** Convert signature to type parameters, where signature is a byte
   847      *  array segment.
   848      */
   849     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   850         signature = sig;
   851         sigp = offset;
   852         siglimit = offset + len;
   853         return sigToTypeParams();
   854     }
   856     /** Convert signature to type parameters, where signature is implicit.
   857      */
   858     List<Type> sigToTypeParams() {
   859         List<Type> tvars = List.nil();
   860         if (signature[sigp] == '<') {
   861             sigp++;
   862             int start = sigp;
   863             sigEnterPhase = true;
   864             while (signature[sigp] != '>')
   865                 tvars = tvars.prepend(sigToTypeParam());
   866             sigEnterPhase = false;
   867             sigp = start;
   868             while (signature[sigp] != '>')
   869                 sigToTypeParam();
   870             sigp++;
   871         }
   872         return tvars.reverse();
   873     }
   875     /** Convert (implicit) signature to type parameter.
   876      */
   877     Type sigToTypeParam() {
   878         int start = sigp;
   879         while (signature[sigp] != ':') sigp++;
   880         Name name = names.fromUtf(signature, start, sigp - start);
   881         TypeVar tvar;
   882         if (sigEnterPhase) {
   883             tvar = new TypeVar(name, currentOwner, syms.botType);
   884             typevars.enter(tvar.tsym);
   885         } else {
   886             tvar = (TypeVar)findTypeVar(name);
   887         }
   888         List<Type> bounds = List.nil();
   889         boolean allInterfaces = false;
   890         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   891             sigp++;
   892             allInterfaces = true;
   893         }
   894         while (signature[sigp] == ':') {
   895             sigp++;
   896             bounds = bounds.prepend(sigToType());
   897         }
   898         if (!sigEnterPhase) {
   899             types.setBounds(tvar, bounds.reverse(), allInterfaces);
   900         }
   901         return tvar;
   902     }
   904     /** Find type variable with given name in `typevars' scope.
   905      */
   906     Type findTypeVar(Name name) {
   907         Scope.Entry e = typevars.lookup(name);
   908         if (e.scope != null) {
   909             return e.sym.type;
   910         } else {
   911             if (readingClassAttr) {
   912                 // While reading the class attribute, the supertypes
   913                 // might refer to a type variable from an enclosing element
   914                 // (method or class).
   915                 // If the type variable is defined in the enclosing class,
   916                 // we can actually find it in
   917                 // currentOwner.owner.type.getTypeArguments()
   918                 // However, until we have read the enclosing method attribute
   919                 // we don't know for sure if this owner is correct.  It could
   920                 // be a method and there is no way to tell before reading the
   921                 // enclosing method attribute.
   922                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   923                 missingTypeVariables = missingTypeVariables.prepend(t);
   924                 // System.err.println("Missing type var " + name);
   925                 return t;
   926             }
   927             throw badClassFile("undecl.type.var", name);
   928         }
   929     }
   931 /************************************************************************
   932  * Reading Attributes
   933  ***********************************************************************/
   935     protected enum AttributeKind { CLASS, MEMBER };
   936     protected abstract class AttributeReader {
   937         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   938             this.name = name;
   939             this.version = version;
   940             this.kinds = kinds;
   941         }
   943         protected boolean accepts(AttributeKind kind) {
   944             if (kinds.contains(kind)) {
   945                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   946                     return true;
   948                 if (lintClassfile && !warnedAttrs.contains(name)) {
   949                     JavaFileObject prev = log.useSource(currentClassFile);
   950                     try {
   951                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   952                                 name, version.major, version.minor, majorVersion, minorVersion);
   953                     } finally {
   954                         log.useSource(prev);
   955                     }
   956                     warnedAttrs.add(name);
   957                 }
   958             }
   959             return false;
   960         }
   962         protected abstract void read(Symbol sym, int attrLen);
   964         protected final Name name;
   965         protected final ClassFile.Version version;
   966         protected final Set<AttributeKind> kinds;
   967     }
   969     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   970             EnumSet.of(AttributeKind.CLASS);
   971     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   972             EnumSet.of(AttributeKind.MEMBER);
   973     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   974             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   976     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   978     private void initAttributeReaders() {
   979         AttributeReader[] readers = {
   980             // v45.3 attributes
   982             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   983                 protected void read(Symbol sym, int attrLen) {
   984                     if (readAllOfClassFile || saveParameterNames)
   985                         ((MethodSymbol)sym).code = readCode(sym);
   986                     else
   987                         bp = bp + attrLen;
   988                 }
   989             },
   991             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   992                 protected void read(Symbol sym, int attrLen) {
   993                     Object v = readPool(nextChar());
   994                     // Ignore ConstantValue attribute if field not final.
   995                     if ((sym.flags() & FINAL) != 0)
   996                         ((VarSymbol) sym).setData(v);
   997                 }
   998             },
  1000             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1001                 protected void read(Symbol sym, int attrLen) {
  1002                     sym.flags_field |= DEPRECATED;
  1004             },
  1006             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1007                 protected void read(Symbol sym, int attrLen) {
  1008                     int nexceptions = nextChar();
  1009                     List<Type> thrown = List.nil();
  1010                     for (int j = 0; j < nexceptions; j++)
  1011                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
  1012                     if (sym.type.getThrownTypes().isEmpty())
  1013                         sym.type.asMethodType().thrown = thrown.reverse();
  1015             },
  1017             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
  1018                 protected void read(Symbol sym, int attrLen) {
  1019                     ClassSymbol c = (ClassSymbol) sym;
  1020                     readInnerClasses(c);
  1022             },
  1024             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1025                 protected void read(Symbol sym, int attrLen) {
  1026                     int newbp = bp + attrLen;
  1027                     if (saveParameterNames && !sawMethodParameters) {
  1028                         // Pick up parameter names from the variable table.
  1029                         // Parameter names are not explicitly identified as such,
  1030                         // but all parameter name entries in the LocalVariableTable
  1031                         // have a start_pc of 0.  Therefore, we record the name
  1032                         // indicies of all slots with a start_pc of zero in the
  1033                         // parameterNameIndicies array.
  1034                         // Note that this implicitly honors the JVMS spec that
  1035                         // there may be more than one LocalVariableTable, and that
  1036                         // there is no specified ordering for the entries.
  1037                         int numEntries = nextChar();
  1038                         for (int i = 0; i < numEntries; i++) {
  1039                             int start_pc = nextChar();
  1040                             int length = nextChar();
  1041                             int nameIndex = nextChar();
  1042                             int sigIndex = nextChar();
  1043                             int register = nextChar();
  1044                             if (start_pc == 0) {
  1045                                 // ensure array large enough
  1046                                 if (register >= parameterNameIndices.length) {
  1047                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1048                                     parameterNameIndices =
  1049                                             Arrays.copyOf(parameterNameIndices, newSize);
  1051                                 parameterNameIndices[register] = nameIndex;
  1052                                 haveParameterNameIndices = true;
  1056                     bp = newbp;
  1058             },
  1060             new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
  1061                 protected void read(Symbol sym, int attrlen) {
  1062                     int newbp = bp + attrlen;
  1063                     if (saveParameterNames) {
  1064                         sawMethodParameters = true;
  1065                         int numEntries = nextByte();
  1066                         parameterNameIndices = new int[numEntries];
  1067                         haveParameterNameIndices = true;
  1068                         for (int i = 0; i < numEntries; i++) {
  1069                             int nameIndex = nextChar();
  1070                             int flags = nextChar();
  1071                             parameterNameIndices[i] = nameIndex;
  1074                     bp = newbp;
  1076             },
  1079             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1080                 protected void read(Symbol sym, int attrLen) {
  1081                     ClassSymbol c = (ClassSymbol) sym;
  1082                     Name n = readName(nextChar());
  1083                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1084                     // If the class is a toplevel class, originating from a Java source file,
  1085                     // but the class name does not match the file name, then it is
  1086                     // an auxiliary class.
  1087                     String sn = n.toString();
  1088                     if (c.owner.kind == Kinds.PCK &&
  1089                         sn.endsWith(".java") &&
  1090                         !sn.equals(c.name.toString()+".java")) {
  1091                         c.flags_field |= AUXILIARY;
  1094             },
  1096             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1097                 protected void read(Symbol sym, int attrLen) {
  1098                     // bridge methods are visible when generics not enabled
  1099                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1100                         sym.flags_field |= SYNTHETIC;
  1102             },
  1104             // standard v49 attributes
  1106             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1107                 protected void read(Symbol sym, int attrLen) {
  1108                     int newbp = bp + attrLen;
  1109                     readEnclosingMethodAttr(sym);
  1110                     bp = newbp;
  1112             },
  1114             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1115                 @Override
  1116                 protected boolean accepts(AttributeKind kind) {
  1117                     return super.accepts(kind) && allowGenerics;
  1120                 protected void read(Symbol sym, int attrLen) {
  1121                     if (sym.kind == TYP) {
  1122                         ClassSymbol c = (ClassSymbol) sym;
  1123                         readingClassAttr = true;
  1124                         try {
  1125                             ClassType ct1 = (ClassType)c.type;
  1126                             Assert.check(c == currentOwner);
  1127                             ct1.typarams_field = readTypeParams(nextChar());
  1128                             ct1.supertype_field = sigToType();
  1129                             ListBuffer<Type> is = new ListBuffer<Type>();
  1130                             while (sigp != siglimit) is.append(sigToType());
  1131                             ct1.interfaces_field = is.toList();
  1132                         } finally {
  1133                             readingClassAttr = false;
  1135                     } else {
  1136                         List<Type> thrown = sym.type.getThrownTypes();
  1137                         sym.type = readType(nextChar());
  1138                         //- System.err.println(" # " + sym.type);
  1139                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1140                             sym.type.asMethodType().thrown = thrown;
  1144             },
  1146             // v49 annotation attributes
  1148             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1149                 protected void read(Symbol sym, int attrLen) {
  1150                     attachAnnotationDefault(sym);
  1152             },
  1154             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1155                 protected void read(Symbol sym, int attrLen) {
  1156                     attachAnnotations(sym);
  1158             },
  1160             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1161                 protected void read(Symbol sym, int attrLen) {
  1162                     attachParameterAnnotations(sym);
  1164             },
  1166             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1167                 protected void read(Symbol sym, int attrLen) {
  1168                     attachAnnotations(sym);
  1170             },
  1172             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1173                 protected void read(Symbol sym, int attrLen) {
  1174                     attachParameterAnnotations(sym);
  1176             },
  1178             // additional "legacy" v49 attributes, superceded by flags
  1180             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1181                 protected void read(Symbol sym, int attrLen) {
  1182                     if (allowAnnotations)
  1183                         sym.flags_field |= ANNOTATION;
  1185             },
  1187             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1188                 protected void read(Symbol sym, int attrLen) {
  1189                     sym.flags_field |= BRIDGE;
  1190                     if (!allowGenerics)
  1191                         sym.flags_field &= ~SYNTHETIC;
  1193             },
  1195             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1196                 protected void read(Symbol sym, int attrLen) {
  1197                     sym.flags_field |= ENUM;
  1199             },
  1201             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1202                 protected void read(Symbol sym, int attrLen) {
  1203                     if (allowVarargs)
  1204                         sym.flags_field |= VARARGS;
  1206             },
  1208             new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1209                 protected void read(Symbol sym, int attrLen) {
  1210                     attachTypeAnnotations(sym);
  1212             },
  1214             new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
  1215                 protected void read(Symbol sym, int attrLen) {
  1216                     attachTypeAnnotations(sym);
  1218             },
  1221             // The following attributes for a Code attribute are not currently handled
  1222             // StackMapTable
  1223             // SourceDebugExtension
  1224             // LineNumberTable
  1225             // LocalVariableTypeTable
  1226         };
  1228         for (AttributeReader r: readers)
  1229             attributeReaders.put(r.name, r);
  1232     /** Report unrecognized attribute.
  1233      */
  1234     void unrecognized(Name attrName) {
  1235         if (checkClassFile)
  1236             printCCF("ccf.unrecognized.attribute", attrName);
  1241     protected void readEnclosingMethodAttr(Symbol sym) {
  1242         // sym is a nested class with an "Enclosing Method" attribute
  1243         // remove sym from it's current owners scope and place it in
  1244         // the scope specified by the attribute
  1245         sym.owner.members().remove(sym);
  1246         ClassSymbol self = (ClassSymbol)sym;
  1247         ClassSymbol c = readClassSymbol(nextChar());
  1248         NameAndType nt = (NameAndType)readPool(nextChar());
  1250         if (c.members_field == null)
  1251             throw badClassFile("bad.enclosing.class", self, c);
  1253         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1254         if (nt != null && m == null)
  1255             throw badClassFile("bad.enclosing.method", self);
  1257         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1258         self.owner = m != null ? m : c;
  1259         if (self.name.isEmpty())
  1260             self.fullname = names.empty;
  1261         else
  1262             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1264         if (m != null) {
  1265             ((ClassType)sym.type).setEnclosingType(m.type);
  1266         } else if ((self.flags_field & STATIC) == 0) {
  1267             ((ClassType)sym.type).setEnclosingType(c.type);
  1268         } else {
  1269             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1271         enterTypevars(self);
  1272         if (!missingTypeVariables.isEmpty()) {
  1273             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1274             for (Type typevar : missingTypeVariables) {
  1275                 typeVars.append(findTypeVar(typevar.tsym.name));
  1277             foundTypeVariables = typeVars.toList();
  1278         } else {
  1279             foundTypeVariables = List.nil();
  1283     // See java.lang.Class
  1284     private Name simpleBinaryName(Name self, Name enclosing) {
  1285         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1286         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1287             throw badClassFile("bad.enclosing.method", self);
  1288         int index = 1;
  1289         while (index < simpleBinaryName.length() &&
  1290                isAsciiDigit(simpleBinaryName.charAt(index)))
  1291             index++;
  1292         return names.fromString(simpleBinaryName.substring(index));
  1295     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1296         if (nt == null)
  1297             return null;
  1299         MethodType type = nt.uniqueType.type.asMethodType();
  1301         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1302             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1303                 return (MethodSymbol)e.sym;
  1305         if (nt.name != names.init)
  1306             // not a constructor
  1307             return null;
  1308         if ((flags & INTERFACE) != 0)
  1309             // no enclosing instance
  1310             return null;
  1311         if (nt.uniqueType.type.getParameterTypes().isEmpty())
  1312             // no parameters
  1313             return null;
  1315         // A constructor of an inner class.
  1316         // Remove the first argument (the enclosing instance)
  1317         nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
  1318                                  nt.uniqueType.type.getReturnType(),
  1319                                  nt.uniqueType.type.getThrownTypes(),
  1320                                  syms.methodClass));
  1321         // Try searching again
  1322         return findMethod(nt, scope, flags);
  1325     /** Similar to Types.isSameType but avoids completion */
  1326     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1327         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1328             .prepend(types.erasure(mt1.getReturnType()));
  1329         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1330         while (!types1.isEmpty() && !types2.isEmpty()) {
  1331             if (types1.head.tsym != types2.head.tsym)
  1332                 return false;
  1333             types1 = types1.tail;
  1334             types2 = types2.tail;
  1336         return types1.isEmpty() && types2.isEmpty();
  1339     /**
  1340      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1341      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1342      */
  1343     private static boolean isAsciiDigit(char c) {
  1344         return '0' <= c && c <= '9';
  1347     /** Read member attributes.
  1348      */
  1349     void readMemberAttrs(Symbol sym) {
  1350         readAttrs(sym, AttributeKind.MEMBER);
  1353     void readAttrs(Symbol sym, AttributeKind kind) {
  1354         char ac = nextChar();
  1355         for (int i = 0; i < ac; i++) {
  1356             Name attrName = readName(nextChar());
  1357             int attrLen = nextInt();
  1358             AttributeReader r = attributeReaders.get(attrName);
  1359             if (r != null && r.accepts(kind))
  1360                 r.read(sym, attrLen);
  1361             else  {
  1362                 unrecognized(attrName);
  1363                 bp = bp + attrLen;
  1368     private boolean readingClassAttr = false;
  1369     private List<Type> missingTypeVariables = List.nil();
  1370     private List<Type> foundTypeVariables = List.nil();
  1372     /** Read class attributes.
  1373      */
  1374     void readClassAttrs(ClassSymbol c) {
  1375         readAttrs(c, AttributeKind.CLASS);
  1378     /** Read code block.
  1379      */
  1380     Code readCode(Symbol owner) {
  1381         nextChar(); // max_stack
  1382         nextChar(); // max_locals
  1383         final int  code_length = nextInt();
  1384         bp += code_length;
  1385         final char exception_table_length = nextChar();
  1386         bp += exception_table_length * 8;
  1387         readMemberAttrs(owner);
  1388         return null;
  1391 /************************************************************************
  1392  * Reading Java-language annotations
  1393  ***********************************************************************/
  1395     /** Attach annotations.
  1396      */
  1397     void attachAnnotations(final Symbol sym) {
  1398         int numAttributes = nextChar();
  1399         if (numAttributes != 0) {
  1400             ListBuffer<CompoundAnnotationProxy> proxies =
  1401                 new ListBuffer<CompoundAnnotationProxy>();
  1402             for (int i = 0; i<numAttributes; i++) {
  1403                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1404                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1405                     sym.flags_field |= PROPRIETARY;
  1406                 else if (proxy.type.tsym == syms.profileType.tsym) {
  1407                     if (profile != Profile.DEFAULT) {
  1408                         for (Pair<Name,Attribute> v: proxy.values) {
  1409                             if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
  1410                                 Attribute.Constant c = (Attribute.Constant) v.snd;
  1411                                 if (c.type == syms.intType && ((Integer) c.value) > profile.value) {
  1412                                     sym.flags_field |= NOT_IN_PROFILE;
  1417                 } else
  1418                     proxies.append(proxy);
  1420             annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
  1424     /** Attach parameter annotations.
  1425      */
  1426     void attachParameterAnnotations(final Symbol method) {
  1427         final MethodSymbol meth = (MethodSymbol)method;
  1428         int numParameters = buf[bp++] & 0xFF;
  1429         List<VarSymbol> parameters = meth.params();
  1430         int pnum = 0;
  1431         while (parameters.tail != null) {
  1432             attachAnnotations(parameters.head);
  1433             parameters = parameters.tail;
  1434             pnum++;
  1436         if (pnum != numParameters) {
  1437             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1441     void attachTypeAnnotations(final Symbol sym) {
  1442         int numAttributes = nextChar();
  1443         if (numAttributes != 0) {
  1444             ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>();
  1445             for (int i = 0; i < numAttributes; i++)
  1446                 proxies.append(readTypeAnnotation());
  1447             annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
  1451     /** Attach the default value for an annotation element.
  1452      */
  1453     void attachAnnotationDefault(final Symbol sym) {
  1454         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1455         final Attribute value = readAttributeValue();
  1457         // The default value is set later during annotation. It might
  1458         // be the case that the Symbol sym is annotated _after_ the
  1459         // repeating instances that depend on this default value,
  1460         // because of this we set an interim value that tells us this
  1461         // element (most likely) has a default.
  1462         //
  1463         // Set interim value for now, reset just before we do this
  1464         // properly at annotate time.
  1465         meth.defaultValue = value;
  1466         annotate.normal(new AnnotationDefaultCompleter(meth, value));
  1469     Type readTypeOrClassSymbol(int i) {
  1470         // support preliminary jsr175-format class files
  1471         if (buf[poolIdx[i]] == CONSTANT_Class)
  1472             return readClassSymbol(i).type;
  1473         return readType(i);
  1475     Type readEnumType(int i) {
  1476         // support preliminary jsr175-format class files
  1477         int index = poolIdx[i];
  1478         int length = getChar(index + 1);
  1479         if (buf[index + length + 2] != ';')
  1480             return enterClass(readName(i)).type;
  1481         return readType(i);
  1484     CompoundAnnotationProxy readCompoundAnnotation() {
  1485         Type t = readTypeOrClassSymbol(nextChar());
  1486         int numFields = nextChar();
  1487         ListBuffer<Pair<Name,Attribute>> pairs =
  1488             new ListBuffer<Pair<Name,Attribute>>();
  1489         for (int i=0; i<numFields; i++) {
  1490             Name name = readName(nextChar());
  1491             Attribute value = readAttributeValue();
  1492             pairs.append(new Pair<Name,Attribute>(name, value));
  1494         return new CompoundAnnotationProxy(t, pairs.toList());
  1497     TypeAnnotationProxy readTypeAnnotation() {
  1498         TypeAnnotationPosition position = readPosition();
  1499         CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1501         return new TypeAnnotationProxy(proxy, position);
  1504     TypeAnnotationPosition readPosition() {
  1505         int tag = nextByte(); // TargetType tag is a byte
  1507         if (!TargetType.isValidTargetTypeValue(tag))
  1508             throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
  1510         TypeAnnotationPosition position = new TypeAnnotationPosition();
  1511         TargetType type = TargetType.fromTargetTypeValue(tag);
  1513         position.type = type;
  1515         switch (type) {
  1516         // instanceof
  1517         case INSTANCEOF:
  1518         // new expression
  1519         case NEW:
  1520         // constructor/method reference receiver
  1521         case CONSTRUCTOR_REFERENCE:
  1522         case METHOD_REFERENCE:
  1523             position.offset = nextChar();
  1524             break;
  1525         // local variable
  1526         case LOCAL_VARIABLE:
  1527         // resource variable
  1528         case RESOURCE_VARIABLE:
  1529             int table_length = nextChar();
  1530             position.lvarOffset = new int[table_length];
  1531             position.lvarLength = new int[table_length];
  1532             position.lvarIndex = new int[table_length];
  1534             for (int i = 0; i < table_length; ++i) {
  1535                 position.lvarOffset[i] = nextChar();
  1536                 position.lvarLength[i] = nextChar();
  1537                 position.lvarIndex[i] = nextChar();
  1539             break;
  1540         // exception parameter
  1541         case EXCEPTION_PARAMETER:
  1542             position.exception_index = nextChar();
  1543             break;
  1544         // method receiver
  1545         case METHOD_RECEIVER:
  1546             // Do nothing
  1547             break;
  1548         // type parameter
  1549         case CLASS_TYPE_PARAMETER:
  1550         case METHOD_TYPE_PARAMETER:
  1551             position.parameter_index = nextByte();
  1552             break;
  1553         // type parameter bound
  1554         case CLASS_TYPE_PARAMETER_BOUND:
  1555         case METHOD_TYPE_PARAMETER_BOUND:
  1556             position.parameter_index = nextByte();
  1557             position.bound_index = nextByte();
  1558             break;
  1559         // class extends or implements clause
  1560         case CLASS_EXTENDS:
  1561             position.type_index = nextChar();
  1562             break;
  1563         // throws
  1564         case THROWS:
  1565             position.type_index = nextChar();
  1566             break;
  1567         // method parameter
  1568         case METHOD_FORMAL_PARAMETER:
  1569             position.parameter_index = nextByte();
  1570             break;
  1571         // type cast
  1572         case CAST:
  1573         // method/constructor/reference type argument
  1574         case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
  1575         case METHOD_INVOCATION_TYPE_ARGUMENT:
  1576         case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
  1577         case METHOD_REFERENCE_TYPE_ARGUMENT:
  1578             position.offset = nextChar();
  1579             position.type_index = nextByte();
  1580             break;
  1581         // We don't need to worry about these
  1582         case METHOD_RETURN:
  1583         case FIELD:
  1584             break;
  1585         case UNKNOWN:
  1586             throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
  1587         default:
  1588             throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
  1591         { // See whether there is location info and read it
  1592             int len = nextByte();
  1593             ListBuffer<Integer> loc = new ListBuffer<>();
  1594             for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
  1595                 loc = loc.append(nextByte());
  1596             position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
  1599         return position;
  1602     Attribute readAttributeValue() {
  1603         char c = (char) buf[bp++];
  1604         switch (c) {
  1605         case 'B':
  1606             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1607         case 'C':
  1608             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1609         case 'D':
  1610             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1611         case 'F':
  1612             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1613         case 'I':
  1614             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1615         case 'J':
  1616             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1617         case 'S':
  1618             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1619         case 'Z':
  1620             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1621         case 's':
  1622             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1623         case 'e':
  1624             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1625         case 'c':
  1626             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1627         case '[': {
  1628             int n = nextChar();
  1629             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1630             for (int i=0; i<n; i++)
  1631                 l.append(readAttributeValue());
  1632             return new ArrayAttributeProxy(l.toList());
  1634         case '@':
  1635             return readCompoundAnnotation();
  1636         default:
  1637             throw new AssertionError("unknown annotation tag '" + c + "'");
  1641     interface ProxyVisitor extends Attribute.Visitor {
  1642         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1643         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1644         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1647     static class EnumAttributeProxy extends Attribute {
  1648         Type enumType;
  1649         Name enumerator;
  1650         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1651             super(null);
  1652             this.enumType = enumType;
  1653             this.enumerator = enumerator;
  1655         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1656         @Override
  1657         public String toString() {
  1658             return "/*proxy enum*/" + enumType + "." + enumerator;
  1662     static class ArrayAttributeProxy extends Attribute {
  1663         List<Attribute> values;
  1664         ArrayAttributeProxy(List<Attribute> values) {
  1665             super(null);
  1666             this.values = values;
  1668         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1669         @Override
  1670         public String toString() {
  1671             return "{" + values + "}";
  1675     /** A temporary proxy representing a compound attribute.
  1676      */
  1677     static class CompoundAnnotationProxy extends Attribute {
  1678         final List<Pair<Name,Attribute>> values;
  1679         public CompoundAnnotationProxy(Type type,
  1680                                       List<Pair<Name,Attribute>> values) {
  1681             super(type);
  1682             this.values = values;
  1684         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1685         @Override
  1686         public String toString() {
  1687             StringBuilder buf = new StringBuilder();
  1688             buf.append("@");
  1689             buf.append(type.tsym.getQualifiedName());
  1690             buf.append("/*proxy*/{");
  1691             boolean first = true;
  1692             for (List<Pair<Name,Attribute>> v = values;
  1693                  v.nonEmpty(); v = v.tail) {
  1694                 Pair<Name,Attribute> value = v.head;
  1695                 if (!first) buf.append(",");
  1696                 first = false;
  1697                 buf.append(value.fst);
  1698                 buf.append("=");
  1699                 buf.append(value.snd);
  1701             buf.append("}");
  1702             return buf.toString();
  1706     /** A temporary proxy representing a type annotation.
  1707      */
  1708     static class TypeAnnotationProxy {
  1709         final CompoundAnnotationProxy compound;
  1710         final TypeAnnotationPosition position;
  1711         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1712                 TypeAnnotationPosition position) {
  1713             this.compound = compound;
  1714             this.position = position;
  1718     class AnnotationDeproxy implements ProxyVisitor {
  1719         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1720             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1722         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1723             // also must fill in types!!!!
  1724             ListBuffer<Attribute.Compound> buf =
  1725                 new ListBuffer<Attribute.Compound>();
  1726             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1727                 buf.append(deproxyCompound(l.head));
  1729             return buf.toList();
  1732         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1733             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1734                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1735             for (List<Pair<Name,Attribute>> l = a.values;
  1736                  l.nonEmpty();
  1737                  l = l.tail) {
  1738                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1739                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1740                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1742             return new Attribute.Compound(a.type, buf.toList());
  1745         MethodSymbol findAccessMethod(Type container, Name name) {
  1746             CompletionFailure failure = null;
  1747             try {
  1748                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1749                      e.scope != null;
  1750                      e = e.next()) {
  1751                     Symbol sym = e.sym;
  1752                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1753                         return (MethodSymbol) sym;
  1755             } catch (CompletionFailure ex) {
  1756                 failure = ex;
  1758             // The method wasn't found: emit a warning and recover
  1759             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1760             try {
  1761                 if (failure == null) {
  1762                     log.warning("annotation.method.not.found",
  1763                                 container,
  1764                                 name);
  1765                 } else {
  1766                     log.warning("annotation.method.not.found.reason",
  1767                                 container,
  1768                                 name,
  1769                                 failure.getDetailValue());//diagnostic, if present
  1771             } finally {
  1772                 log.useSource(prevSource);
  1774             // Construct a new method type and symbol.  Use bottom
  1775             // type (typeof null) as return type because this type is
  1776             // a subtype of all reference types and can be converted
  1777             // to primitive types by unboxing.
  1778             MethodType mt = new MethodType(List.<Type>nil(),
  1779                                            syms.botType,
  1780                                            List.<Type>nil(),
  1781                                            syms.methodClass);
  1782             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1785         Attribute result;
  1786         Type type;
  1787         Attribute deproxy(Type t, Attribute a) {
  1788             Type oldType = type;
  1789             try {
  1790                 type = t;
  1791                 a.accept(this);
  1792                 return result;
  1793             } finally {
  1794                 type = oldType;
  1798         // implement Attribute.Visitor below
  1800         public void visitConstant(Attribute.Constant value) {
  1801             // assert value.type == type;
  1802             result = value;
  1805         public void visitClass(Attribute.Class clazz) {
  1806             result = clazz;
  1809         public void visitEnum(Attribute.Enum e) {
  1810             throw new AssertionError(); // shouldn't happen
  1813         public void visitCompound(Attribute.Compound compound) {
  1814             throw new AssertionError(); // shouldn't happen
  1817         public void visitArray(Attribute.Array array) {
  1818             throw new AssertionError(); // shouldn't happen
  1821         public void visitError(Attribute.Error e) {
  1822             throw new AssertionError(); // shouldn't happen
  1825         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1826             // type.tsym.flatName() should == proxy.enumFlatName
  1827             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1828             VarSymbol enumerator = null;
  1829             CompletionFailure failure = null;
  1830             try {
  1831                 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1832                      e.scope != null;
  1833                      e = e.next()) {
  1834                     if (e.sym.kind == VAR) {
  1835                         enumerator = (VarSymbol)e.sym;
  1836                         break;
  1840             catch (CompletionFailure ex) {
  1841                 failure = ex;
  1843             if (enumerator == null) {
  1844                 if (failure != null) {
  1845                     log.warning("unknown.enum.constant.reason",
  1846                               currentClassFile, enumTypeSym, proxy.enumerator,
  1847                               failure.getDiagnostic());
  1848                 } else {
  1849                     log.warning("unknown.enum.constant",
  1850                               currentClassFile, enumTypeSym, proxy.enumerator);
  1852                 result = new Attribute.Enum(enumTypeSym.type,
  1853                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
  1854             } else {
  1855                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1859         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1860             int length = proxy.values.length();
  1861             Attribute[] ats = new Attribute[length];
  1862             Type elemtype = types.elemtype(type);
  1863             int i = 0;
  1864             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1865                 ats[i++] = deproxy(elemtype, p.head);
  1867             result = new Attribute.Array(type, ats);
  1870         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1871             result = deproxyCompound(proxy);
  1875     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Worker {
  1876         final MethodSymbol sym;
  1877         final Attribute value;
  1878         final JavaFileObject classFile = currentClassFile;
  1879         @Override
  1880         public String toString() {
  1881             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1883         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1884             this.sym = sym;
  1885             this.value = value;
  1887         // implement Annotate.Worker.run()
  1888         public void run() {
  1889             JavaFileObject previousClassFile = currentClassFile;
  1890             try {
  1891                 // Reset the interim value set earlier in
  1892                 // attachAnnotationDefault().
  1893                 sym.defaultValue = null;
  1894                 currentClassFile = classFile;
  1895                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1896             } finally {
  1897                 currentClassFile = previousClassFile;
  1902     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Worker {
  1903         final Symbol sym;
  1904         final List<CompoundAnnotationProxy> l;
  1905         final JavaFileObject classFile;
  1906         @Override
  1907         public String toString() {
  1908             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1910         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1911             this.sym = sym;
  1912             this.l = l;
  1913             this.classFile = currentClassFile;
  1915         // implement Annotate.Worker.run()
  1916         public void run() {
  1917             JavaFileObject previousClassFile = currentClassFile;
  1918             try {
  1919                 currentClassFile = classFile;
  1920                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1921                 if (sym.annotationsPendingCompletion()) {
  1922                     sym.setDeclarationAttributes(newList);
  1923                 } else {
  1924                     sym.appendAttributes(newList);
  1926             } finally {
  1927                 currentClassFile = previousClassFile;
  1932     class TypeAnnotationCompleter extends AnnotationCompleter {
  1934         List<TypeAnnotationProxy> proxies;
  1936         TypeAnnotationCompleter(Symbol sym,
  1937                 List<TypeAnnotationProxy> proxies) {
  1938             super(sym, List.<CompoundAnnotationProxy>nil());
  1939             this.proxies = proxies;
  1942         List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
  1943             ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  1944             for (TypeAnnotationProxy proxy: proxies) {
  1945                 Attribute.Compound compound = deproxyCompound(proxy.compound);
  1946                 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
  1947                 buf.add(typeCompound);
  1949             return buf.toList();
  1952         @Override
  1953         public void run() {
  1954             JavaFileObject previousClassFile = currentClassFile;
  1955             try {
  1956                 currentClassFile = classFile;
  1957                 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
  1958                 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
  1959             } finally {
  1960                 currentClassFile = previousClassFile;
  1966 /************************************************************************
  1967  * Reading Symbols
  1968  ***********************************************************************/
  1970     /** Read a field.
  1971      */
  1972     VarSymbol readField() {
  1973         long flags = adjustFieldFlags(nextChar());
  1974         Name name = readName(nextChar());
  1975         Type type = readType(nextChar());
  1976         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1977         readMemberAttrs(v);
  1978         return v;
  1981     /** Read a method.
  1982      */
  1983     MethodSymbol readMethod() {
  1984         long flags = adjustMethodFlags(nextChar());
  1985         Name name = readName(nextChar());
  1986         Type type = readType(nextChar());
  1987         if (currentOwner.isInterface() &&
  1988                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
  1989             if (majorVersion > Target.JDK1_8.majorVersion ||
  1990                     (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
  1991                 if ((flags & STATIC) == 0) {
  1992                     currentOwner.flags_field |= DEFAULT;
  1993                     flags |= DEFAULT | ABSTRACT;
  1995             } else {
  1996                 //protect against ill-formed classfiles
  1997                 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface",
  1998                                    Integer.toString(majorVersion),
  1999                                    Integer.toString(minorVersion));
  2002         if (name == names.init && currentOwner.hasOuterInstance()) {
  2003             // Sometimes anonymous classes don't have an outer
  2004             // instance, however, there is no reliable way to tell so
  2005             // we never strip this$n
  2006             if (!currentOwner.name.isEmpty())
  2007                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  2008                                       type.getReturnType(),
  2009                                       type.getThrownTypes(),
  2010                                       syms.methodClass);
  2012         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  2013         if (types.isSignaturePolymorphic(m)) {
  2014             m.flags_field |= SIGNATURE_POLYMORPHIC;
  2016         if (saveParameterNames)
  2017             initParameterNames(m);
  2018         Symbol prevOwner = currentOwner;
  2019         currentOwner = m;
  2020         try {
  2021             readMemberAttrs(m);
  2022         } finally {
  2023             currentOwner = prevOwner;
  2025         if (saveParameterNames)
  2026             setParameterNames(m, type);
  2027         return m;
  2030     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  2031         boolean isVarargs = (flags & VARARGS) != 0;
  2032         if (isVarargs) {
  2033             Type varargsElem = args.last();
  2034             ListBuffer<Type> adjustedArgs = new ListBuffer<>();
  2035             for (Type t : args) {
  2036                 adjustedArgs.append(t != varargsElem ?
  2037                     t :
  2038                     ((ArrayType)t).makeVarargs());
  2040             args = adjustedArgs.toList();
  2042         return args.tail;
  2045     /**
  2046      * Init the parameter names array.
  2047      * Parameter names are currently inferred from the names in the
  2048      * LocalVariableTable attributes of a Code attribute.
  2049      * (Note: this means parameter names are currently not available for
  2050      * methods without a Code attribute.)
  2051      * This method initializes an array in which to store the name indexes
  2052      * of parameter names found in LocalVariableTable attributes. It is
  2053      * slightly supersized to allow for additional slots with a start_pc of 0.
  2054      */
  2055     void initParameterNames(MethodSymbol sym) {
  2056         // make allowance for synthetic parameters.
  2057         final int excessSlots = 4;
  2058         int expectedParameterSlots =
  2059                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  2060         if (parameterNameIndices == null
  2061                 || parameterNameIndices.length < expectedParameterSlots) {
  2062             parameterNameIndices = new int[expectedParameterSlots];
  2063         } else
  2064             Arrays.fill(parameterNameIndices, 0);
  2065         haveParameterNameIndices = false;
  2066         sawMethodParameters = false;
  2069     /**
  2070      * Set the parameter names for a symbol from the name index in the
  2071      * parameterNameIndicies array. The type of the symbol may have changed
  2072      * while reading the method attributes (see the Signature attribute).
  2073      * This may be because of generic information or because anonymous
  2074      * synthetic parameters were added.   The original type (as read from
  2075      * the method descriptor) is used to help guess the existence of
  2076      * anonymous synthetic parameters.
  2077      * On completion, sym.savedParameter names will either be null (if
  2078      * no parameter names were found in the class file) or will be set to a
  2079      * list of names, one per entry in sym.type.getParameterTypes, with
  2080      * any missing names represented by the empty name.
  2081      */
  2082     void setParameterNames(MethodSymbol sym, Type jvmType) {
  2083         // if no names were found in the class file, there's nothing more to do
  2084         if (!haveParameterNameIndices)
  2085             return;
  2086         // If we get parameter names from MethodParameters, then we
  2087         // don't need to skip.
  2088         int firstParam = 0;
  2089         if (!sawMethodParameters) {
  2090             firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  2091             // the code in readMethod may have skipped the first
  2092             // parameter when setting up the MethodType. If so, we
  2093             // make a corresponding allowance here for the position of
  2094             // the first parameter.  Note that this assumes the
  2095             // skipped parameter has a width of 1 -- i.e. it is not
  2096         // a double width type (long or double.)
  2097         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  2098             // Sometimes anonymous classes don't have an outer
  2099             // instance, however, there is no reliable way to tell so
  2100             // we never strip this$n
  2101             if (!currentOwner.name.isEmpty())
  2102                 firstParam += 1;
  2105         if (sym.type != jvmType) {
  2106                 // reading the method attributes has caused the
  2107                 // symbol's type to be changed. (i.e. the Signature
  2108                 // attribute.)  This may happen if there are hidden
  2109                 // (synthetic) parameters in the descriptor, but not
  2110                 // in the Signature.  The position of these hidden
  2111                 // parameters is unspecified; for now, assume they are
  2112                 // at the beginning, and so skip over them. The
  2113                 // primary case for this is two hidden parameters
  2114                 // passed into Enum constructors.
  2115             int skip = Code.width(jvmType.getParameterTypes())
  2116                     - Code.width(sym.type.getParameterTypes());
  2117             firstParam += skip;
  2120         List<Name> paramNames = List.nil();
  2121         int index = firstParam;
  2122         for (Type t: sym.type.getParameterTypes()) {
  2123             int nameIdx = (index < parameterNameIndices.length
  2124                     ? parameterNameIndices[index] : 0);
  2125             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  2126             paramNames = paramNames.prepend(name);
  2127             index += Code.width(t);
  2129         sym.savedParameterNames = paramNames.reverse();
  2132     /**
  2133      * skip n bytes
  2134      */
  2135     void skipBytes(int n) {
  2136         bp = bp + n;
  2139     /** Skip a field or method
  2140      */
  2141     void skipMember() {
  2142         bp = bp + 6;
  2143         char ac = nextChar();
  2144         for (int i = 0; i < ac; i++) {
  2145             bp = bp + 2;
  2146             int attrLen = nextInt();
  2147             bp = bp + attrLen;
  2151     /** Enter type variables of this classtype and all enclosing ones in
  2152      *  `typevars'.
  2153      */
  2154     protected void enterTypevars(Type t) {
  2155         if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
  2156             enterTypevars(t.getEnclosingType());
  2157         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  2158             typevars.enter(xs.head.tsym);
  2161     protected void enterTypevars(Symbol sym) {
  2162         if (sym.owner.kind == MTH) {
  2163             enterTypevars(sym.owner);
  2164             enterTypevars(sym.owner.owner);
  2166         enterTypevars(sym.type);
  2169     /** Read contents of a given class symbol `c'. Both external and internal
  2170      *  versions of an inner class are read.
  2171      */
  2172     void readClass(ClassSymbol c) {
  2173         ClassType ct = (ClassType)c.type;
  2175         // allocate scope for members
  2176         c.members_field = new Scope(c);
  2178         // prepare type variable table
  2179         typevars = typevars.dup(currentOwner);
  2180         if (ct.getEnclosingType().hasTag(CLASS))
  2181             enterTypevars(ct.getEnclosingType());
  2183         // read flags, or skip if this is an inner class
  2184         long flags = adjustClassFlags(nextChar());
  2185         if (c.owner.kind == PCK) c.flags_field = flags;
  2187         // read own class name and check that it matches
  2188         ClassSymbol self = readClassSymbol(nextChar());
  2189         if (c != self)
  2190             throw badClassFile("class.file.wrong.class",
  2191                                self.flatname);
  2193         // class attributes must be read before class
  2194         // skip ahead to read class attributes
  2195         int startbp = bp;
  2196         nextChar();
  2197         char interfaceCount = nextChar();
  2198         bp += interfaceCount * 2;
  2199         char fieldCount = nextChar();
  2200         for (int i = 0; i < fieldCount; i++) skipMember();
  2201         char methodCount = nextChar();
  2202         for (int i = 0; i < methodCount; i++) skipMember();
  2203         readClassAttrs(c);
  2205         if (readAllOfClassFile) {
  2206             for (int i = 1; i < poolObj.length; i++) readPool(i);
  2207             c.pool = new Pool(poolObj.length, poolObj, types);
  2210         // reset and read rest of classinfo
  2211         bp = startbp;
  2212         int n = nextChar();
  2213         if (ct.supertype_field == null)
  2214             ct.supertype_field = (n == 0)
  2215                 ? Type.noType
  2216                 : readClassSymbol(n).erasure(types);
  2217         n = nextChar();
  2218         List<Type> is = List.nil();
  2219         for (int i = 0; i < n; i++) {
  2220             Type _inter = readClassSymbol(nextChar()).erasure(types);
  2221             is = is.prepend(_inter);
  2223         if (ct.interfaces_field == null)
  2224             ct.interfaces_field = is.reverse();
  2226         Assert.check(fieldCount == nextChar());
  2227         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  2228         Assert.check(methodCount == nextChar());
  2229         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  2231         typevars = typevars.leave();
  2234     /** Read inner class info. For each inner/outer pair allocate a
  2235      *  member class.
  2236      */
  2237     void readInnerClasses(ClassSymbol c) {
  2238         int n = nextChar();
  2239         for (int i = 0; i < n; i++) {
  2240             nextChar(); // skip inner class symbol
  2241             ClassSymbol outer = readClassSymbol(nextChar());
  2242             Name name = readName(nextChar());
  2243             if (name == null) name = names.empty;
  2244             long flags = adjustClassFlags(nextChar());
  2245             if (outer != null) { // we have a member class
  2246                 if (name == names.empty)
  2247                     name = names.one;
  2248                 ClassSymbol member = enterClass(name, outer);
  2249                 if ((flags & STATIC) == 0) {
  2250                     ((ClassType)member.type).setEnclosingType(outer.type);
  2251                     if (member.erasure_field != null)
  2252                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  2254                 if (c == outer) {
  2255                     member.flags_field = flags;
  2256                     enterMember(c, member);
  2262     /** Read a class file.
  2263      */
  2264     private void readClassFile(ClassSymbol c) throws IOException {
  2265         int magic = nextInt();
  2266         if (magic != JAVA_MAGIC)
  2267             throw badClassFile("illegal.start.of.class.file");
  2269         minorVersion = nextChar();
  2270         majorVersion = nextChar();
  2271         int maxMajor = Target.MAX().majorVersion;
  2272         int maxMinor = Target.MAX().minorVersion;
  2273         if (majorVersion > maxMajor ||
  2274             majorVersion * 1000 + minorVersion <
  2275             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  2277             if (majorVersion == (maxMajor + 1))
  2278                 log.warning("big.major.version",
  2279                             currentClassFile,
  2280                             majorVersion,
  2281                             maxMajor);
  2282             else
  2283                 throw badClassFile("wrong.version",
  2284                                    Integer.toString(majorVersion),
  2285                                    Integer.toString(minorVersion),
  2286                                    Integer.toString(maxMajor),
  2287                                    Integer.toString(maxMinor));
  2289         else if (checkClassFile &&
  2290                  majorVersion == maxMajor &&
  2291                  minorVersion > maxMinor)
  2293             printCCF("found.later.version",
  2294                      Integer.toString(minorVersion));
  2296         indexPool();
  2297         if (signatureBuffer.length < bp) {
  2298             int ns = Integer.highestOneBit(bp) << 1;
  2299             signatureBuffer = new byte[ns];
  2301         readClass(c);
  2304 /************************************************************************
  2305  * Adjusting flags
  2306  ***********************************************************************/
  2308     long adjustFieldFlags(long flags) {
  2309         return flags;
  2311     long adjustMethodFlags(long flags) {
  2312         if ((flags & ACC_BRIDGE) != 0) {
  2313             flags &= ~ACC_BRIDGE;
  2314             flags |= BRIDGE;
  2315             if (!allowGenerics)
  2316                 flags &= ~SYNTHETIC;
  2318         if ((flags & ACC_VARARGS) != 0) {
  2319             flags &= ~ACC_VARARGS;
  2320             flags |= VARARGS;
  2322         return flags;
  2324     long adjustClassFlags(long flags) {
  2325         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2328 /************************************************************************
  2329  * Loading Classes
  2330  ***********************************************************************/
  2332     /** Define a new class given its name and owner.
  2333      */
  2334     public ClassSymbol defineClass(Name name, Symbol owner) {
  2335         ClassSymbol c = new ClassSymbol(0, name, owner);
  2336         if (owner.kind == PCK)
  2337             Assert.checkNull(classes.get(c.flatname), c);
  2338         c.completer = thisCompleter;
  2339         return c;
  2342     /** Create a new toplevel or member class symbol with given name
  2343      *  and owner and enter in `classes' unless already there.
  2344      */
  2345     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2346         Name flatname = TypeSymbol.formFlatName(name, owner);
  2347         ClassSymbol c = classes.get(flatname);
  2348         if (c == null) {
  2349             c = defineClass(name, owner);
  2350             classes.put(flatname, c);
  2351         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2352             // reassign fields of classes that might have been loaded with
  2353             // their flat names.
  2354             c.owner.members().remove(c);
  2355             c.name = name;
  2356             c.owner = owner;
  2357             c.fullname = ClassSymbol.formFullName(name, owner);
  2359         return c;
  2362     /**
  2363      * Creates a new toplevel class symbol with given flat name and
  2364      * given class (or source) file.
  2366      * @param flatName a fully qualified binary class name
  2367      * @param classFile the class file or compilation unit defining
  2368      * the class (may be {@code null})
  2369      * @return a newly created class symbol
  2370      * @throws AssertionError if the class symbol already exists
  2371      */
  2372     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2373         ClassSymbol cs = classes.get(flatName);
  2374         if (cs != null) {
  2375             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2376                                     cs.fullname,
  2377                                     cs.completer,
  2378                                     cs.classfile,
  2379                                     cs.sourcefile);
  2380             throw new AssertionError(msg);
  2382         Name packageName = Convert.packagePart(flatName);
  2383         PackageSymbol owner = packageName.isEmpty()
  2384                                 ? syms.unnamedPackage
  2385                                 : enterPackage(packageName);
  2386         cs = defineClass(Convert.shortName(flatName), owner);
  2387         cs.classfile = classFile;
  2388         classes.put(flatName, cs);
  2389         return cs;
  2392     /** Create a new member or toplevel class symbol with given flat name
  2393      *  and enter in `classes' unless already there.
  2394      */
  2395     public ClassSymbol enterClass(Name flatname) {
  2396         ClassSymbol c = classes.get(flatname);
  2397         if (c == null)
  2398             return enterClass(flatname, (JavaFileObject)null);
  2399         else
  2400             return c;
  2403     /** Completion for classes to be loaded. Before a class is loaded
  2404      *  we make sure its enclosing class (if any) is loaded.
  2405      */
  2406     private void complete(Symbol sym) throws CompletionFailure {
  2407         if (sym.kind == TYP) {
  2408             ClassSymbol c = (ClassSymbol)sym;
  2409             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2410             annotate.enterStart();
  2411             try {
  2412                 completeOwners(c.owner);
  2413                 completeEnclosing(c);
  2414             } finally {
  2415                 // The flush needs to happen only after annotations
  2416                 // are filled in.
  2417                 annotate.enterDoneWithoutFlush();
  2419             fillIn(c);
  2420         } else if (sym.kind == PCK) {
  2421             PackageSymbol p = (PackageSymbol)sym;
  2422             try {
  2423                 fillIn(p);
  2424             } catch (IOException ex) {
  2425                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2428         if (!filling)
  2429             annotate.flush(); // finish attaching annotations
  2432     /** complete up through the enclosing package. */
  2433     private void completeOwners(Symbol o) {
  2434         if (o.kind != PCK) completeOwners(o.owner);
  2435         o.complete();
  2438     /**
  2439      * Tries to complete lexically enclosing classes if c looks like a
  2440      * nested class.  This is similar to completeOwners but handles
  2441      * the situation when a nested class is accessed directly as it is
  2442      * possible with the Tree API or javax.lang.model.*.
  2443      */
  2444     private void completeEnclosing(ClassSymbol c) {
  2445         if (c.owner.kind == PCK) {
  2446             Symbol owner = c.owner;
  2447             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2448                 Symbol encl = owner.members().lookup(name).sym;
  2449                 if (encl == null)
  2450                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2451                 if (encl != null)
  2452                     encl.complete();
  2457     /** We can only read a single class file at a time; this
  2458      *  flag keeps track of when we are currently reading a class
  2459      *  file.
  2460      */
  2461     private boolean filling = false;
  2463     /** Fill in definition of class `c' from corresponding class or
  2464      *  source file.
  2465      */
  2466     private void fillIn(ClassSymbol c) {
  2467         if (completionFailureName == c.fullname) {
  2468             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2470         currentOwner = c;
  2471         warnedAttrs.clear();
  2472         JavaFileObject classfile = c.classfile;
  2473         if (classfile != null) {
  2474             JavaFileObject previousClassFile = currentClassFile;
  2475             try {
  2476                 if (filling) {
  2477                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2479                 currentClassFile = classfile;
  2480                 if (verbose) {
  2481                     log.printVerbose("loading", currentClassFile.toString());
  2483                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2484                     filling = true;
  2485                     try {
  2486                         bp = 0;
  2487                         buf = readInputStream(buf, classfile.openInputStream());
  2488                         readClassFile(c);
  2489                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2490                             List<Type> missing = missingTypeVariables;
  2491                             List<Type> found = foundTypeVariables;
  2492                             missingTypeVariables = List.nil();
  2493                             foundTypeVariables = List.nil();
  2494                             filling = false;
  2495                             ClassType ct = (ClassType)currentOwner.type;
  2496                             ct.supertype_field =
  2497                                 types.subst(ct.supertype_field, missing, found);
  2498                             ct.interfaces_field =
  2499                                 types.subst(ct.interfaces_field, missing, found);
  2500                         } else if (missingTypeVariables.isEmpty() !=
  2501                                    foundTypeVariables.isEmpty()) {
  2502                             Name name = missingTypeVariables.head.tsym.name;
  2503                             throw badClassFile("undecl.type.var", name);
  2505                     } finally {
  2506                         missingTypeVariables = List.nil();
  2507                         foundTypeVariables = List.nil();
  2508                         filling = false;
  2510                 } else {
  2511                     if (sourceCompleter != null) {
  2512                         sourceCompleter.complete(c);
  2513                     } else {
  2514                         throw new IllegalStateException("Source completer required to read "
  2515                                                         + classfile.toUri());
  2518                 return;
  2519             } catch (IOException ex) {
  2520                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2521             } finally {
  2522                 currentClassFile = previousClassFile;
  2524         } else {
  2525             JCDiagnostic diag =
  2526                 diagFactory.fragment("class.file.not.found", c.flatname);
  2527             throw
  2528                 newCompletionFailure(c, diag);
  2531     // where
  2532         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2533             try {
  2534                 buf = ensureCapacity(buf, s.available());
  2535                 int r = s.read(buf);
  2536                 int bp = 0;
  2537                 while (r != -1) {
  2538                     bp += r;
  2539                     buf = ensureCapacity(buf, bp);
  2540                     r = s.read(buf, bp, buf.length - bp);
  2542                 return buf;
  2543             } finally {
  2544                 try {
  2545                     s.close();
  2546                 } catch (IOException e) {
  2547                     /* Ignore any errors, as this stream may have already
  2548                      * thrown a related exception which is the one that
  2549                      * should be reported.
  2550                      */
  2554         /*
  2555          * ensureCapacity will increase the buffer as needed, taking note that
  2556          * the new buffer will always be greater than the needed and never
  2557          * exactly equal to the needed size or bp. If equal then the read (above)
  2558          * will infinitely loop as buf.length - bp == 0.
  2559          */
  2560         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2561             if (buf.length <= needed) {
  2562                 byte[] old = buf;
  2563                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2564                 System.arraycopy(old, 0, buf, 0, old.length);
  2566             return buf;
  2568         /** Static factory for CompletionFailure objects.
  2569          *  In practice, only one can be used at a time, so we share one
  2570          *  to reduce the expense of allocating new exception objects.
  2571          */
  2572         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2573                                                        JCDiagnostic diag) {
  2574             if (!cacheCompletionFailure) {
  2575                 // log.warning("proc.messager",
  2576                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2577                 // c.debug.printStackTrace();
  2578                 return new CompletionFailure(c, diag);
  2579             } else {
  2580                 CompletionFailure result = cachedCompletionFailure;
  2581                 result.sym = c;
  2582                 result.diag = diag;
  2583                 return result;
  2586         private CompletionFailure cachedCompletionFailure =
  2587             new CompletionFailure(null, (JCDiagnostic) null);
  2589             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2592     /** Load a toplevel class with given fully qualified name
  2593      *  The class is entered into `classes' only if load was successful.
  2594      */
  2595     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2596         boolean absent = classes.get(flatname) == null;
  2597         ClassSymbol c = enterClass(flatname);
  2598         if (c.members_field == null && c.completer != null) {
  2599             try {
  2600                 c.complete();
  2601             } catch (CompletionFailure ex) {
  2602                 if (absent) classes.remove(flatname);
  2603                 throw ex;
  2606         return c;
  2609 /************************************************************************
  2610  * Loading Packages
  2611  ***********************************************************************/
  2613     /** Check to see if a package exists, given its fully qualified name.
  2614      */
  2615     public boolean packageExists(Name fullname) {
  2616         return enterPackage(fullname).exists();
  2619     /** Make a package, given its fully qualified name.
  2620      */
  2621     public PackageSymbol enterPackage(Name fullname) {
  2622         PackageSymbol p = packages.get(fullname);
  2623         if (p == null) {
  2624             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2625             p = new PackageSymbol(
  2626                 Convert.shortName(fullname),
  2627                 enterPackage(Convert.packagePart(fullname)));
  2628             p.completer = thisCompleter;
  2629             packages.put(fullname, p);
  2631         return p;
  2634     /** Make a package, given its unqualified name and enclosing package.
  2635      */
  2636     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2637         return enterPackage(TypeSymbol.formFullName(name, owner));
  2640     /** Include class corresponding to given class file in package,
  2641      *  unless (1) we already have one the same kind (.class or .java), or
  2642      *         (2) we have one of the other kind, and the given class file
  2643      *             is older.
  2644      */
  2645     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2646         if ((p.flags_field & EXISTS) == 0)
  2647             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2648                 q.flags_field |= EXISTS;
  2649         JavaFileObject.Kind kind = file.getKind();
  2650         int seen;
  2651         if (kind == JavaFileObject.Kind.CLASS)
  2652             seen = CLASS_SEEN;
  2653         else
  2654             seen = SOURCE_SEEN;
  2655         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2656         int lastDot = binaryName.lastIndexOf(".");
  2657         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2658         boolean isPkgInfo = classname == names.package_info;
  2659         ClassSymbol c = isPkgInfo
  2660             ? p.package_info
  2661             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2662         if (c == null) {
  2663             c = enterClass(classname, p);
  2664             if (c.classfile == null) // only update the file if's it's newly created
  2665                 c.classfile = file;
  2666             if (isPkgInfo) {
  2667                 p.package_info = c;
  2668             } else {
  2669                 if (c.owner == p)  // it might be an inner class
  2670                     p.members_field.enter(c);
  2672         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2673             // if c.classfile == null, we are currently compiling this class
  2674             // and no further action is necessary.
  2675             // if (c.flags_field & seen) != 0, we have already encountered
  2676             // a file of the same kind; again no further action is necessary.
  2677             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2678                 c.classfile = preferredFileObject(file, c.classfile);
  2680         c.flags_field |= seen;
  2683     /** Implement policy to choose to derive information from a source
  2684      *  file or a class file when both are present.  May be overridden
  2685      *  by subclasses.
  2686      */
  2687     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2688                                            JavaFileObject b) {
  2690         if (preferSource)
  2691             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2692         else {
  2693             long adate = a.getLastModified();
  2694             long bdate = b.getLastModified();
  2695             // 6449326: policy for bad lastModifiedTime in ClassReader
  2696             //assert adate >= 0 && bdate >= 0;
  2697             return (adate > bdate) ? a : b;
  2701     /**
  2702      * specifies types of files to be read when filling in a package symbol
  2703      */
  2704     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2705         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2708     /**
  2709      * this is used to support javadoc
  2710      */
  2711     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2714     protected Location currentLoc; // FIXME
  2716     private boolean verbosePath = true;
  2718     /** Load directory of package into members scope.
  2719      */
  2720     private void fillIn(PackageSymbol p) throws IOException {
  2721         if (p.members_field == null) p.members_field = new Scope(p);
  2722         String packageName = p.fullname.toString();
  2724         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2726         fillIn(p, PLATFORM_CLASS_PATH,
  2727                fileManager.list(PLATFORM_CLASS_PATH,
  2728                                 packageName,
  2729                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2730                                 false));
  2732         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2733         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2734         boolean wantClassFiles = !classKinds.isEmpty();
  2736         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2737         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2738         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2740         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2742         if (verbose && verbosePath) {
  2743             if (fileManager instanceof StandardJavaFileManager) {
  2744                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2745                 if (haveSourcePath && wantSourceFiles) {
  2746                     List<File> path = List.nil();
  2747                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2748                         path = path.prepend(file);
  2750                     log.printVerbose("sourcepath", path.reverse().toString());
  2751                 } else if (wantSourceFiles) {
  2752                     List<File> path = List.nil();
  2753                     for (File file : fm.getLocation(CLASS_PATH)) {
  2754                         path = path.prepend(file);
  2756                     log.printVerbose("sourcepath", path.reverse().toString());
  2758                 if (wantClassFiles) {
  2759                     List<File> path = List.nil();
  2760                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2761                         path = path.prepend(file);
  2763                     for (File file : fm.getLocation(CLASS_PATH)) {
  2764                         path = path.prepend(file);
  2766                     log.printVerbose("classpath",  path.reverse().toString());
  2771         if (wantSourceFiles && !haveSourcePath) {
  2772             fillIn(p, CLASS_PATH,
  2773                    fileManager.list(CLASS_PATH,
  2774                                     packageName,
  2775                                     kinds,
  2776                                     false));
  2777         } else {
  2778             if (wantClassFiles)
  2779                 fillIn(p, CLASS_PATH,
  2780                        fileManager.list(CLASS_PATH,
  2781                                         packageName,
  2782                                         classKinds,
  2783                                         false));
  2784             if (wantSourceFiles)
  2785                 fillIn(p, SOURCE_PATH,
  2786                        fileManager.list(SOURCE_PATH,
  2787                                         packageName,
  2788                                         sourceKinds,
  2789                                         false));
  2791         verbosePath = false;
  2793     // where
  2794         private void fillIn(PackageSymbol p,
  2795                             Location location,
  2796                             Iterable<JavaFileObject> files)
  2798             currentLoc = location;
  2799             for (JavaFileObject fo : files) {
  2800                 switch (fo.getKind()) {
  2801                 case CLASS:
  2802                 case SOURCE: {
  2803                     // TODO pass binaryName to includeClassFile
  2804                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2805                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2806                     if (SourceVersion.isIdentifier(simpleName) ||
  2807                         simpleName.equals("package-info"))
  2808                         includeClassFile(p, fo);
  2809                     break;
  2811                 default:
  2812                     extraFileActions(p, fo);
  2817     /** Output for "-checkclassfile" option.
  2818      *  @param key The key to look up the correct internationalized string.
  2819      *  @param arg An argument for substitution into the output string.
  2820      */
  2821     private void printCCF(String key, Object arg) {
  2822         log.printLines(key, arg);
  2826     public interface SourceCompleter {
  2827         void complete(ClassSymbol sym)
  2828             throws CompletionFailure;
  2831     /**
  2832      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2833      * The attribute is only the last component of the original filename, so is unlikely
  2834      * to be valid as is, so operations other than those to access the name throw
  2835      * UnsupportedOperationException
  2836      */
  2837     private static class SourceFileObject extends BaseFileObject {
  2839         /** The file's name.
  2840          */
  2841         private Name name;
  2842         private Name flatname;
  2844         public SourceFileObject(Name name, Name flatname) {
  2845             super(null); // no file manager; never referenced for this file object
  2846             this.name = name;
  2847             this.flatname = flatname;
  2850         @Override
  2851         public URI toUri() {
  2852             try {
  2853                 return new URI(null, name.toString(), null);
  2854             } catch (URISyntaxException e) {
  2855                 throw new CannotCreateUriError(name.toString(), e);
  2859         @Override
  2860         public String getName() {
  2861             return name.toString();
  2864         @Override
  2865         public String getShortName() {
  2866             return getName();
  2869         @Override
  2870         public JavaFileObject.Kind getKind() {
  2871             return getKind(getName());
  2874         @Override
  2875         public InputStream openInputStream() {
  2876             throw new UnsupportedOperationException();
  2879         @Override
  2880         public OutputStream openOutputStream() {
  2881             throw new UnsupportedOperationException();
  2884         @Override
  2885         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2886             throw new UnsupportedOperationException();
  2889         @Override
  2890         public Reader openReader(boolean ignoreEncodingErrors) {
  2891             throw new UnsupportedOperationException();
  2894         @Override
  2895         public Writer openWriter() {
  2896             throw new UnsupportedOperationException();
  2899         @Override
  2900         public long getLastModified() {
  2901             throw new UnsupportedOperationException();
  2904         @Override
  2905         public boolean delete() {
  2906             throw new UnsupportedOperationException();
  2909         @Override
  2910         protected String inferBinaryName(Iterable<? extends File> path) {
  2911             return flatname.toString();
  2914         @Override
  2915         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2916             return true; // fail-safe mode
  2919         /**
  2920          * Check if two file objects are equal.
  2921          * SourceFileObjects are just placeholder objects for the value of a
  2922          * SourceFile attribute, and do not directly represent specific files.
  2923          * Two SourceFileObjects are equal if their names are equal.
  2924          */
  2925         @Override
  2926         public boolean equals(Object other) {
  2927             if (this == other)
  2928                 return true;
  2930             if (!(other instanceof SourceFileObject))
  2931                 return false;
  2933             SourceFileObject o = (SourceFileObject) other;
  2934             return name.equals(o.name);
  2937         @Override
  2938         public int hashCode() {
  2939             return name.hashCode();

mercurial