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

Tue, 18 Jan 2011 08:37:05 -0800

author
ksrini
date
Tue, 18 Jan 2011 08:37:05 -0800
changeset 826
5cf6c432ef2f
parent 816
7c537f4298fb
child 857
3aa269645199
permissions
-rw-r--r--

6982999: tools must support -target 7 bytecodes
Reviewed-by: jjg, jrose

     1 /*
     2  * Copyright (c) 1999, 2011, 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.TypeTags.*;
    59 import static com.sun.tools.javac.jvm.ClassFile.*;
    60 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
    62 import static com.sun.tools.javac.main.OptionName.*;
    64 /** This class provides operations to read a classfile into an internal
    65  *  representation. The internal representation is anchored in a
    66  *  ClassSymbol which contains in its scope symbol representations
    67  *  for all other definitions in the classfile. Top-level Classes themselves
    68  *  appear as members of the scopes of PackageSymbols.
    69  *
    70  *  <p><b>This is NOT part of any supported API.
    71  *  If you write code that depends on this, you do so at your own risk.
    72  *  This code and its internal interfaces are subject to change or
    73  *  deletion without notice.</b>
    74  */
    75 public class ClassReader implements Completer {
    76     /** The context key for the class reader. */
    77     protected static final Context.Key<ClassReader> classReaderKey =
    78         new Context.Key<ClassReader>();
    80     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
    82     Annotate annotate;
    84     /** Switch: verbose output.
    85      */
    86     boolean verbose;
    88     /** Switch: check class file for correct minor version, unrecognized
    89      *  attributes.
    90      */
    91     boolean checkClassFile;
    93     /** Switch: read constant pool and code sections. This switch is initially
    94      *  set to false but can be turned on from outside.
    95      */
    96     public boolean readAllOfClassFile = false;
    98     /** Switch: read GJ signature information.
    99      */
   100     boolean allowGenerics;
   102     /** Switch: read varargs attribute.
   103      */
   104     boolean allowVarargs;
   106     /** Switch: allow annotations.
   107      */
   108     boolean allowAnnotations;
   110     /** Switch: allow simplified varargs.
   111      */
   112     boolean allowSimplifiedVarargs;
   114    /** Lint option: warn about classfile issues
   115      */
   116     boolean lintClassfile;
   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     /** The log to use for verbose output
   135      */
   136     final Log log;
   138     /** The symbol table. */
   139     Symtab syms;
   141     /** The scope counter */
   142     Scope.ScopeCounter scopeCounter;
   144     Types types;
   146     /** The name table. */
   147     final Names names;
   149     /** Force a completion failure on this name
   150      */
   151     final Name completionFailureName;
   153     /** Access to files
   154      */
   155     private final JavaFileManager fileManager;
   157     /** Factory for diagnostics
   158      */
   159     JCDiagnostic.Factory diagFactory;
   161     /** Can be reassigned from outside:
   162      *  the completer to be used for ".java" files. If this remains unassigned
   163      *  ".java" files will not be loaded.
   164      */
   165     public SourceCompleter sourceCompleter = null;
   167     /** A hashtable containing the encountered top-level and member classes,
   168      *  indexed by flat names. The table does not contain local classes.
   169      */
   170     private Map<Name,ClassSymbol> classes;
   172     /** A hashtable containing the encountered packages.
   173      */
   174     private Map<Name, PackageSymbol> packages;
   176     /** The current scope where type variables are entered.
   177      */
   178     protected Scope typevars;
   180     /** The path name of the class file currently being read.
   181      */
   182     protected JavaFileObject currentClassFile = null;
   184     /** The class or method currently being read.
   185      */
   186     protected Symbol currentOwner = null;
   188     /** The buffer containing the currently read class file.
   189      */
   190     byte[] buf = new byte[INITIAL_BUFFER_SIZE];
   192     /** The current input pointer.
   193      */
   194     int bp;
   196     /** The objects of the constant pool.
   197      */
   198     Object[] poolObj;
   200     /** For every constant pool entry, an index into buf where the
   201      *  defining section of the entry is found.
   202      */
   203     int[] poolIdx;
   205     /** The major version number of the class file being read. */
   206     int majorVersion;
   207     /** The minor version number of the class file being read. */
   208     int minorVersion;
   210     /** A table to hold the constant pool indices for method parameter
   211      * names, as given in LocalVariableTable attributes.
   212      */
   213     int[] parameterNameIndices;
   215     /**
   216      * Whether or not any parameter names have been found.
   217      */
   218     boolean haveParameterNameIndices;
   220     /**
   221      * The set of attribute names for which warnings have been generated for the current class
   222      */
   223     Set<Name> warnedAttrs = new HashSet<Name>();
   225     /** Get the ClassReader instance for this invocation. */
   226     public static ClassReader instance(Context context) {
   227         ClassReader instance = context.get(classReaderKey);
   228         if (instance == null)
   229             instance = new ClassReader(context, true);
   230         return instance;
   231     }
   233     /** Initialize classes and packages, treating this as the definitive classreader. */
   234     public void init(Symtab syms) {
   235         init(syms, true);
   236     }
   238     /** Initialize classes and packages, optionally treating this as
   239      *  the definitive classreader.
   240      */
   241     private void init(Symtab syms, boolean definitive) {
   242         if (classes != null) return;
   244         if (definitive) {
   245             Assert.check(packages == null || packages == syms.packages);
   246             packages = syms.packages;
   247             Assert.check(classes == null || classes == syms.classes);
   248             classes = syms.classes;
   249         } else {
   250             packages = new HashMap<Name, PackageSymbol>();
   251             classes = new HashMap<Name, ClassSymbol>();
   252         }
   254         packages.put(names.empty, syms.rootPackage);
   255         syms.rootPackage.completer = this;
   256         syms.unnamedPackage.completer = this;
   257     }
   259     /** Construct a new class reader, optionally treated as the
   260      *  definitive classreader for this invocation.
   261      */
   262     protected ClassReader(Context context, boolean definitive) {
   263         if (definitive) context.put(classReaderKey, this);
   265         names = Names.instance(context);
   266         syms = Symtab.instance(context);
   267         scopeCounter = Scope.ScopeCounter.instance(context);
   268         types = Types.instance(context);
   269         fileManager = context.get(JavaFileManager.class);
   270         if (fileManager == null)
   271             throw new AssertionError("FileManager initialization error");
   272         diagFactory = JCDiagnostic.Factory.instance(context);
   274         init(syms, definitive);
   275         log = Log.instance(context);
   277         Options options = Options.instance(context);
   278         annotate = Annotate.instance(context);
   279         verbose        = options.isSet(VERBOSE);
   280         checkClassFile = options.isSet("-checkclassfile");
   281         Source source = Source.instance(context);
   282         allowGenerics    = source.allowGenerics();
   283         allowVarargs     = source.allowVarargs();
   284         allowAnnotations = source.allowAnnotations();
   285         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   286         saveParameterNames = options.isSet("save-parameter-names");
   287         cacheCompletionFailure = options.isUnset("dev");
   288         preferSource = "source".equals(options.get("-Xprefer"));
   290         completionFailureName =
   291             options.isSet("failcomplete")
   292             ? names.fromString(options.get("failcomplete"))
   293             : null;
   295         typevars = new Scope(syms.noSymbol);
   297         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
   299         initAttributeReaders();
   300     }
   302     /** Add member to class unless it is synthetic.
   303      */
   304     private void enterMember(ClassSymbol c, Symbol sym) {
   305         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
   306             c.members_field.enter(sym);
   307     }
   309 /************************************************************************
   310  * Error Diagnoses
   311  ***********************************************************************/
   314     public class BadClassFile extends CompletionFailure {
   315         private static final long serialVersionUID = 0;
   317         public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
   318             super(sym, createBadClassFileDiagnostic(file, diag));
   319         }
   320     }
   321     // where
   322     private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
   323         String key = (file.getKind() == JavaFileObject.Kind.SOURCE
   324                     ? "bad.source.file.header" : "bad.class.file.header");
   325         return diagFactory.fragment(key, file, diag);
   326     }
   328     public BadClassFile badClassFile(String key, Object... args) {
   329         return new BadClassFile (
   330             currentOwner.enclClass(),
   331             currentClassFile,
   332             diagFactory.fragment(key, args));
   333     }
   335 /************************************************************************
   336  * Buffer Access
   337  ***********************************************************************/
   339     /** Read a character.
   340      */
   341     char nextChar() {
   342         return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
   343     }
   345     /** Read a byte.
   346      */
   347     byte nextByte() {
   348         return buf[bp++];
   349     }
   351     /** Read an integer.
   352      */
   353     int nextInt() {
   354         return
   355             ((buf[bp++] & 0xFF) << 24) +
   356             ((buf[bp++] & 0xFF) << 16) +
   357             ((buf[bp++] & 0xFF) << 8) +
   358             (buf[bp++] & 0xFF);
   359     }
   361     /** Extract a character at position bp from buf.
   362      */
   363     char getChar(int bp) {
   364         return
   365             (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
   366     }
   368     /** Extract an integer at position bp from buf.
   369      */
   370     int getInt(int bp) {
   371         return
   372             ((buf[bp] & 0xFF) << 24) +
   373             ((buf[bp+1] & 0xFF) << 16) +
   374             ((buf[bp+2] & 0xFF) << 8) +
   375             (buf[bp+3] & 0xFF);
   376     }
   379     /** Extract a long integer at position bp from buf.
   380      */
   381     long getLong(int bp) {
   382         DataInputStream bufin =
   383             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   384         try {
   385             return bufin.readLong();
   386         } catch (IOException e) {
   387             throw new AssertionError(e);
   388         }
   389     }
   391     /** Extract a float at position bp from buf.
   392      */
   393     float getFloat(int bp) {
   394         DataInputStream bufin =
   395             new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
   396         try {
   397             return bufin.readFloat();
   398         } catch (IOException e) {
   399             throw new AssertionError(e);
   400         }
   401     }
   403     /** Extract a double at position bp from buf.
   404      */
   405     double getDouble(int bp) {
   406         DataInputStream bufin =
   407             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   408         try {
   409             return bufin.readDouble();
   410         } catch (IOException e) {
   411             throw new AssertionError(e);
   412         }
   413     }
   415 /************************************************************************
   416  * Constant Pool Access
   417  ***********************************************************************/
   419     /** Index all constant pool entries, writing their start addresses into
   420      *  poolIdx.
   421      */
   422     void indexPool() {
   423         poolIdx = new int[nextChar()];
   424         poolObj = new Object[poolIdx.length];
   425         int i = 1;
   426         while (i < poolIdx.length) {
   427             poolIdx[i++] = bp;
   428             byte tag = buf[bp++];
   429             switch (tag) {
   430             case CONSTANT_Utf8: case CONSTANT_Unicode: {
   431                 int len = nextChar();
   432                 bp = bp + len;
   433                 break;
   434             }
   435             case CONSTANT_Class:
   436             case CONSTANT_String:
   437             case CONSTANT_MethodType:
   438                 bp = bp + 2;
   439                 break;
   440             case CONSTANT_MethodHandle:
   441                 bp = bp + 3;
   442                 break;
   443             case CONSTANT_Fieldref:
   444             case CONSTANT_Methodref:
   445             case CONSTANT_InterfaceMethodref:
   446             case CONSTANT_NameandType:
   447             case CONSTANT_Integer:
   448             case CONSTANT_Float:
   449             case CONSTANT_InvokeDynamic:
   450                 bp = bp + 4;
   451                 break;
   452             case CONSTANT_Long:
   453             case CONSTANT_Double:
   454                 bp = bp + 8;
   455                 i++;
   456                 break;
   457             default:
   458                 throw badClassFile("bad.const.pool.tag.at",
   459                                    Byte.toString(tag),
   460                                    Integer.toString(bp -1));
   461             }
   462         }
   463     }
   465     /** Read constant pool entry at start address i, use pool as a cache.
   466      */
   467     Object readPool(int i) {
   468         Object result = poolObj[i];
   469         if (result != null) return result;
   471         int index = poolIdx[i];
   472         if (index == 0) return null;
   474         byte tag = buf[index];
   475         switch (tag) {
   476         case CONSTANT_Utf8:
   477             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   478             break;
   479         case CONSTANT_Unicode:
   480             throw badClassFile("unicode.str.not.supported");
   481         case CONSTANT_Class:
   482             poolObj[i] = readClassOrType(getChar(index + 1));
   483             break;
   484         case CONSTANT_String:
   485             // FIXME: (footprint) do not use toString here
   486             poolObj[i] = readName(getChar(index + 1)).toString();
   487             break;
   488         case CONSTANT_Fieldref: {
   489             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   490             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   491             poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
   492             break;
   493         }
   494         case CONSTANT_Methodref:
   495         case CONSTANT_InterfaceMethodref: {
   496             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   497             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   498             poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
   499             break;
   500         }
   501         case CONSTANT_NameandType:
   502             poolObj[i] = new NameAndType(
   503                 readName(getChar(index + 1)),
   504                 readType(getChar(index + 3)));
   505             break;
   506         case CONSTANT_Integer:
   507             poolObj[i] = getInt(index + 1);
   508             break;
   509         case CONSTANT_Float:
   510             poolObj[i] = new Float(getFloat(index + 1));
   511             break;
   512         case CONSTANT_Long:
   513             poolObj[i] = new Long(getLong(index + 1));
   514             break;
   515         case CONSTANT_Double:
   516             poolObj[i] = new Double(getDouble(index + 1));
   517             break;
   518         case CONSTANT_MethodHandle:
   519             skipBytes(4);
   520             break;
   521         case CONSTANT_MethodType:
   522             skipBytes(3);
   523             break;
   524         case CONSTANT_InvokeDynamic:
   525             skipBytes(5);
   526             break;
   527         default:
   528             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   529         }
   530         return poolObj[i];
   531     }
   533     /** Read signature and convert to type.
   534      */
   535     Type readType(int i) {
   536         int index = poolIdx[i];
   537         return sigToType(buf, index + 3, getChar(index + 1));
   538     }
   540     /** If name is an array type or class signature, return the
   541      *  corresponding type; otherwise return a ClassSymbol with given name.
   542      */
   543     Object readClassOrType(int i) {
   544         int index =  poolIdx[i];
   545         int len = getChar(index + 1);
   546         int start = index + 3;
   547         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   548         // by the above assertion, the following test can be
   549         // simplified to (buf[start] == '[')
   550         return (buf[start] == '[' || buf[start + len - 1] == ';')
   551             ? (Object)sigToType(buf, start, len)
   552             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   553                                                            len)));
   554     }
   556     /** Read signature and convert to type parameters.
   557      */
   558     List<Type> readTypeParams(int i) {
   559         int index = poolIdx[i];
   560         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   561     }
   563     /** Read class entry.
   564      */
   565     ClassSymbol readClassSymbol(int i) {
   566         return (ClassSymbol) (readPool(i));
   567     }
   569     /** Read name.
   570      */
   571     Name readName(int i) {
   572         return (Name) (readPool(i));
   573     }
   575 /************************************************************************
   576  * Reading Types
   577  ***********************************************************************/
   579     /** The unread portion of the currently read type is
   580      *  signature[sigp..siglimit-1].
   581      */
   582     byte[] signature;
   583     int sigp;
   584     int siglimit;
   585     boolean sigEnterPhase = false;
   587     /** Convert signature to type, where signature is a byte array segment.
   588      */
   589     Type sigToType(byte[] sig, int offset, int len) {
   590         signature = sig;
   591         sigp = offset;
   592         siglimit = offset + len;
   593         return sigToType();
   594     }
   596     /** Convert signature to type, where signature is implicit.
   597      */
   598     Type sigToType() {
   599         switch ((char) signature[sigp]) {
   600         case 'T':
   601             sigp++;
   602             int start = sigp;
   603             while (signature[sigp] != ';') sigp++;
   604             sigp++;
   605             return sigEnterPhase
   606                 ? Type.noType
   607                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   608         case '+': {
   609             sigp++;
   610             Type t = sigToType();
   611             return new WildcardType(t, BoundKind.EXTENDS,
   612                                     syms.boundClass);
   613         }
   614         case '*':
   615             sigp++;
   616             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   617                                     syms.boundClass);
   618         case '-': {
   619             sigp++;
   620             Type t = sigToType();
   621             return new WildcardType(t, BoundKind.SUPER,
   622                                     syms.boundClass);
   623         }
   624         case 'B':
   625             sigp++;
   626             return syms.byteType;
   627         case 'C':
   628             sigp++;
   629             return syms.charType;
   630         case 'D':
   631             sigp++;
   632             return syms.doubleType;
   633         case 'F':
   634             sigp++;
   635             return syms.floatType;
   636         case 'I':
   637             sigp++;
   638             return syms.intType;
   639         case 'J':
   640             sigp++;
   641             return syms.longType;
   642         case 'L':
   643             {
   644                 // int oldsigp = sigp;
   645                 Type t = classSigToType();
   646                 if (sigp < siglimit && signature[sigp] == '.')
   647                     throw badClassFile("deprecated inner class signature syntax " +
   648                                        "(please recompile from source)");
   649                 /*
   650                 System.err.println(" decoded " +
   651                                    new String(signature, oldsigp, sigp-oldsigp) +
   652                                    " => " + t + " outer " + t.outer());
   653                 */
   654                 return t;
   655             }
   656         case 'S':
   657             sigp++;
   658             return syms.shortType;
   659         case 'V':
   660             sigp++;
   661             return syms.voidType;
   662         case 'Z':
   663             sigp++;
   664             return syms.booleanType;
   665         case '[':
   666             sigp++;
   667             return new ArrayType(sigToType(), syms.arrayClass);
   668         case '(':
   669             sigp++;
   670             List<Type> argtypes = sigToTypes(')');
   671             Type restype = sigToType();
   672             List<Type> thrown = List.nil();
   673             while (signature[sigp] == '^') {
   674                 sigp++;
   675                 thrown = thrown.prepend(sigToType());
   676             }
   677             return new MethodType(argtypes,
   678                                   restype,
   679                                   thrown.reverse(),
   680                                   syms.methodClass);
   681         case '<':
   682             typevars = typevars.dup(currentOwner);
   683             Type poly = new ForAll(sigToTypeParams(), sigToType());
   684             typevars = typevars.leave();
   685             return poly;
   686         default:
   687             throw badClassFile("bad.signature",
   688                                Convert.utf2string(signature, sigp, 10));
   689         }
   690     }
   692     byte[] signatureBuffer = new byte[0];
   693     int sbp = 0;
   694     /** Convert class signature to type, where signature is implicit.
   695      */
   696     Type classSigToType() {
   697         if (signature[sigp] != 'L')
   698             throw badClassFile("bad.class.signature",
   699                                Convert.utf2string(signature, sigp, 10));
   700         sigp++;
   701         Type outer = Type.noType;
   702         int startSbp = sbp;
   704         while (true) {
   705             final byte c = signature[sigp++];
   706             switch (c) {
   708             case ';': {         // end
   709                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   710                                                          startSbp,
   711                                                          sbp - startSbp));
   712                 if (outer == Type.noType)
   713                     outer = t.erasure(types);
   714                 else
   715                     outer = new ClassType(outer, List.<Type>nil(), t);
   716                 sbp = startSbp;
   717                 return outer;
   718             }
   720             case '<':           // generic arguments
   721                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   722                                                          startSbp,
   723                                                          sbp - startSbp));
   724                 outer = new ClassType(outer, sigToTypes('>'), t) {
   725                         boolean completed = false;
   726                         @Override
   727                         public Type getEnclosingType() {
   728                             if (!completed) {
   729                                 completed = true;
   730                                 tsym.complete();
   731                                 Type enclosingType = tsym.type.getEnclosingType();
   732                                 if (enclosingType != Type.noType) {
   733                                     List<Type> typeArgs =
   734                                         super.getEnclosingType().allparams();
   735                                     List<Type> typeParams =
   736                                         enclosingType.allparams();
   737                                     if (typeParams.length() != typeArgs.length()) {
   738                                         // no "rare" types
   739                                         super.setEnclosingType(types.erasure(enclosingType));
   740                                     } else {
   741                                         super.setEnclosingType(types.subst(enclosingType,
   742                                                                            typeParams,
   743                                                                            typeArgs));
   744                                     }
   745                                 } else {
   746                                     super.setEnclosingType(Type.noType);
   747                                 }
   748                             }
   749                             return super.getEnclosingType();
   750                         }
   751                         @Override
   752                         public void setEnclosingType(Type outer) {
   753                             throw new UnsupportedOperationException();
   754                         }
   755                     };
   756                 switch (signature[sigp++]) {
   757                 case ';':
   758                     if (sigp < signature.length && signature[sigp] == '.') {
   759                         // support old-style GJC signatures
   760                         // The signature produced was
   761                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   762                         // rather than say
   763                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   764                         // so we skip past ".Lfoo/Outer$"
   765                         sigp += (sbp - startSbp) + // "foo/Outer"
   766                             3;  // ".L" and "$"
   767                         signatureBuffer[sbp++] = (byte)'$';
   768                         break;
   769                     } else {
   770                         sbp = startSbp;
   771                         return outer;
   772                     }
   773                 case '.':
   774                     signatureBuffer[sbp++] = (byte)'$';
   775                     break;
   776                 default:
   777                     throw new AssertionError(signature[sigp-1]);
   778                 }
   779                 continue;
   781             case '.':
   782                 signatureBuffer[sbp++] = (byte)'$';
   783                 continue;
   784             case '/':
   785                 signatureBuffer[sbp++] = (byte)'.';
   786                 continue;
   787             default:
   788                 signatureBuffer[sbp++] = c;
   789                 continue;
   790             }
   791         }
   792     }
   794     /** Convert (implicit) signature to list of types
   795      *  until `terminator' is encountered.
   796      */
   797     List<Type> sigToTypes(char terminator) {
   798         List<Type> head = List.of(null);
   799         List<Type> tail = head;
   800         while (signature[sigp] != terminator)
   801             tail = tail.setTail(List.of(sigToType()));
   802         sigp++;
   803         return head.tail;
   804     }
   806     /** Convert signature to type parameters, where signature is a byte
   807      *  array segment.
   808      */
   809     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   810         signature = sig;
   811         sigp = offset;
   812         siglimit = offset + len;
   813         return sigToTypeParams();
   814     }
   816     /** Convert signature to type parameters, where signature is implicit.
   817      */
   818     List<Type> sigToTypeParams() {
   819         List<Type> tvars = List.nil();
   820         if (signature[sigp] == '<') {
   821             sigp++;
   822             int start = sigp;
   823             sigEnterPhase = true;
   824             while (signature[sigp] != '>')
   825                 tvars = tvars.prepend(sigToTypeParam());
   826             sigEnterPhase = false;
   827             sigp = start;
   828             while (signature[sigp] != '>')
   829                 sigToTypeParam();
   830             sigp++;
   831         }
   832         return tvars.reverse();
   833     }
   835     /** Convert (implicit) signature to type parameter.
   836      */
   837     Type sigToTypeParam() {
   838         int start = sigp;
   839         while (signature[sigp] != ':') sigp++;
   840         Name name = names.fromUtf(signature, start, sigp - start);
   841         TypeVar tvar;
   842         if (sigEnterPhase) {
   843             tvar = new TypeVar(name, currentOwner, syms.botType);
   844             typevars.enter(tvar.tsym);
   845         } else {
   846             tvar = (TypeVar)findTypeVar(name);
   847         }
   848         List<Type> bounds = List.nil();
   849         Type st = null;
   850         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   851             sigp++;
   852             st = syms.objectType;
   853         }
   854         while (signature[sigp] == ':') {
   855             sigp++;
   856             bounds = bounds.prepend(sigToType());
   857         }
   858         if (!sigEnterPhase) {
   859             types.setBounds(tvar, bounds.reverse(), st);
   860         }
   861         return tvar;
   862     }
   864     /** Find type variable with given name in `typevars' scope.
   865      */
   866     Type findTypeVar(Name name) {
   867         Scope.Entry e = typevars.lookup(name);
   868         if (e.scope != null) {
   869             return e.sym.type;
   870         } else {
   871             if (readingClassAttr) {
   872                 // While reading the class attribute, the supertypes
   873                 // might refer to a type variable from an enclosing element
   874                 // (method or class).
   875                 // If the type variable is defined in the enclosing class,
   876                 // we can actually find it in
   877                 // currentOwner.owner.type.getTypeArguments()
   878                 // However, until we have read the enclosing method attribute
   879                 // we don't know for sure if this owner is correct.  It could
   880                 // be a method and there is no way to tell before reading the
   881                 // enclosing method attribute.
   882                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   883                 missingTypeVariables = missingTypeVariables.prepend(t);
   884                 // System.err.println("Missing type var " + name);
   885                 return t;
   886             }
   887             throw badClassFile("undecl.type.var", name);
   888         }
   889     }
   891 /************************************************************************
   892  * Reading Attributes
   893  ***********************************************************************/
   895     protected enum AttributeKind { CLASS, MEMBER };
   896     protected abstract class AttributeReader {
   897         AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   898             this.name = name;
   899             this.version = version;
   900             this.kinds = kinds;
   901         }
   903         boolean accepts(AttributeKind kind) {
   904             if (kinds.contains(kind)) {
   905                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   906                     return true;
   908                 if (lintClassfile && !warnedAttrs.contains(name)) {
   909                     JavaFileObject prev = log.useSource(currentClassFile);
   910                     try {
   911                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   912                                 name, version.major, version.minor, majorVersion, minorVersion);
   913                     } finally {
   914                         log.useSource(prev);
   915                     }
   916                     warnedAttrs.add(name);
   917                 }
   918             }
   919             return false;
   920         }
   922         abstract void read(Symbol sym, int attrLen);
   924         final Name name;
   925         final ClassFile.Version version;
   926         final Set<AttributeKind> kinds;
   927     }
   929     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   930             EnumSet.of(AttributeKind.CLASS);
   931     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   932             EnumSet.of(AttributeKind.MEMBER);
   933     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   934             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   936     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   938     private void initAttributeReaders() {
   939         AttributeReader[] readers = {
   940             // v45.3 attributes
   942             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   943                 void read(Symbol sym, int attrLen) {
   944                     if (readAllOfClassFile || saveParameterNames)
   945                         ((MethodSymbol)sym).code = readCode(sym);
   946                     else
   947                         bp = bp + attrLen;
   948                 }
   949             },
   951             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   952                 void read(Symbol sym, int attrLen) {
   953                     Object v = readPool(nextChar());
   954                     // Ignore ConstantValue attribute if field not final.
   955                     if ((sym.flags() & FINAL) != 0)
   956                         ((VarSymbol) sym).setData(v);
   957                 }
   958             },
   960             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   961                 void read(Symbol sym, int attrLen) {
   962                     sym.flags_field |= DEPRECATED;
   963                 }
   964             },
   966             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   967                 void read(Symbol sym, int attrLen) {
   968                     int nexceptions = nextChar();
   969                     List<Type> thrown = List.nil();
   970                     for (int j = 0; j < nexceptions; j++)
   971                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
   972                     if (sym.type.getThrownTypes().isEmpty())
   973                         sym.type.asMethodType().thrown = thrown.reverse();
   974                 }
   975             },
   977             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
   978                 void read(Symbol sym, int attrLen) {
   979                     ClassSymbol c = (ClassSymbol) sym;
   980                     readInnerClasses(c);
   981                 }
   982             },
   984             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   985                 void read(Symbol sym, int attrLen) {
   986                     int newbp = bp + attrLen;
   987                     if (saveParameterNames) {
   988                         // Pick up parameter names from the variable table.
   989                         // Parameter names are not explicitly identified as such,
   990                         // but all parameter name entries in the LocalVariableTable
   991                         // have a start_pc of 0.  Therefore, we record the name
   992                         // indicies of all slots with a start_pc of zero in the
   993                         // parameterNameIndicies array.
   994                         // Note that this implicitly honors the JVMS spec that
   995                         // there may be more than one LocalVariableTable, and that
   996                         // there is no specified ordering for the entries.
   997                         int numEntries = nextChar();
   998                         for (int i = 0; i < numEntries; i++) {
   999                             int start_pc = nextChar();
  1000                             int length = nextChar();
  1001                             int nameIndex = nextChar();
  1002                             int sigIndex = nextChar();
  1003                             int register = nextChar();
  1004                             if (start_pc == 0) {
  1005                                 // ensure array large enough
  1006                                 if (register >= parameterNameIndices.length) {
  1007                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1008                                     parameterNameIndices =
  1009                                             Arrays.copyOf(parameterNameIndices, newSize);
  1011                                 parameterNameIndices[register] = nameIndex;
  1012                                 haveParameterNameIndices = true;
  1016                     bp = newbp;
  1018             },
  1020             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1021                 void read(Symbol sym, int attrLen) {
  1022                     ClassSymbol c = (ClassSymbol) sym;
  1023                     Name n = readName(nextChar());
  1024                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1026             },
  1028             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1029                 void read(Symbol sym, int attrLen) {
  1030                     // bridge methods are visible when generics not enabled
  1031                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1032                         sym.flags_field |= SYNTHETIC;
  1034             },
  1036             // standard v49 attributes
  1038             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1039                 void read(Symbol sym, int attrLen) {
  1040                     int newbp = bp + attrLen;
  1041                     readEnclosingMethodAttr(sym);
  1042                     bp = newbp;
  1044             },
  1046             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1047                 @Override
  1048                 boolean accepts(AttributeKind kind) {
  1049                     return super.accepts(kind) && allowGenerics;
  1052                 void read(Symbol sym, int attrLen) {
  1053                     if (sym.kind == TYP) {
  1054                         ClassSymbol c = (ClassSymbol) sym;
  1055                         readingClassAttr = true;
  1056                         try {
  1057                             ClassType ct1 = (ClassType)c.type;
  1058                             Assert.check(c == currentOwner);
  1059                             ct1.typarams_field = readTypeParams(nextChar());
  1060                             ct1.supertype_field = sigToType();
  1061                             ListBuffer<Type> is = new ListBuffer<Type>();
  1062                             while (sigp != siglimit) is.append(sigToType());
  1063                             ct1.interfaces_field = is.toList();
  1064                         } finally {
  1065                             readingClassAttr = false;
  1067                     } else {
  1068                         List<Type> thrown = sym.type.getThrownTypes();
  1069                         sym.type = readType(nextChar());
  1070                         //- System.err.println(" # " + sym.type);
  1071                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1072                             sym.type.asMethodType().thrown = thrown;
  1076             },
  1078             // v49 annotation attributes
  1080             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1081                 void read(Symbol sym, int attrLen) {
  1082                     attachAnnotationDefault(sym);
  1084             },
  1086             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1087                 void read(Symbol sym, int attrLen) {
  1088                     attachAnnotations(sym);
  1090             },
  1092             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1093                 void read(Symbol sym, int attrLen) {
  1094                     attachParameterAnnotations(sym);
  1096             },
  1098             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1099                 void read(Symbol sym, int attrLen) {
  1100                     attachAnnotations(sym);
  1102             },
  1104             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1105                 void read(Symbol sym, int attrLen) {
  1106                     attachParameterAnnotations(sym);
  1108             },
  1110             // additional "legacy" v49 attributes, superceded by flags
  1112             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1113                 void read(Symbol sym, int attrLen) {
  1114                     if (allowAnnotations)
  1115                         sym.flags_field |= ANNOTATION;
  1117             },
  1119             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1120                 void read(Symbol sym, int attrLen) {
  1121                     sym.flags_field |= BRIDGE;
  1122                     if (!allowGenerics)
  1123                         sym.flags_field &= ~SYNTHETIC;
  1125             },
  1127             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1128                 void read(Symbol sym, int attrLen) {
  1129                     sym.flags_field |= ENUM;
  1131             },
  1133             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1134                 void read(Symbol sym, int attrLen) {
  1135                     if (allowVarargs)
  1136                         sym.flags_field |= VARARGS;
  1138             },
  1140             // The following attributes for a Code attribute are not currently handled
  1141             // StackMapTable
  1142             // SourceDebugExtension
  1143             // LineNumberTable
  1144             // LocalVariableTypeTable
  1145         };
  1147         for (AttributeReader r: readers)
  1148             attributeReaders.put(r.name, r);
  1151     /** Report unrecognized attribute.
  1152      */
  1153     void unrecognized(Name attrName) {
  1154         if (checkClassFile)
  1155             printCCF("ccf.unrecognized.attribute", attrName);
  1160     void readEnclosingMethodAttr(Symbol sym) {
  1161         // sym is a nested class with an "Enclosing Method" attribute
  1162         // remove sym from it's current owners scope and place it in
  1163         // the scope specified by the attribute
  1164         sym.owner.members().remove(sym);
  1165         ClassSymbol self = (ClassSymbol)sym;
  1166         ClassSymbol c = readClassSymbol(nextChar());
  1167         NameAndType nt = (NameAndType)readPool(nextChar());
  1169         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1170         if (nt != null && m == null)
  1171             throw badClassFile("bad.enclosing.method", self);
  1173         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1174         self.owner = m != null ? m : c;
  1175         if (self.name.isEmpty())
  1176             self.fullname = names.empty;
  1177         else
  1178             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1180         if (m != null) {
  1181             ((ClassType)sym.type).setEnclosingType(m.type);
  1182         } else if ((self.flags_field & STATIC) == 0) {
  1183             ((ClassType)sym.type).setEnclosingType(c.type);
  1184         } else {
  1185             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1187         enterTypevars(self);
  1188         if (!missingTypeVariables.isEmpty()) {
  1189             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1190             for (Type typevar : missingTypeVariables) {
  1191                 typeVars.append(findTypeVar(typevar.tsym.name));
  1193             foundTypeVariables = typeVars.toList();
  1194         } else {
  1195             foundTypeVariables = List.nil();
  1199     // See java.lang.Class
  1200     private Name simpleBinaryName(Name self, Name enclosing) {
  1201         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1202         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1203             throw badClassFile("bad.enclosing.method", self);
  1204         int index = 1;
  1205         while (index < simpleBinaryName.length() &&
  1206                isAsciiDigit(simpleBinaryName.charAt(index)))
  1207             index++;
  1208         return names.fromString(simpleBinaryName.substring(index));
  1211     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1212         if (nt == null)
  1213             return null;
  1215         MethodType type = nt.type.asMethodType();
  1217         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1218             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1219                 return (MethodSymbol)e.sym;
  1221         if (nt.name != names.init)
  1222             // not a constructor
  1223             return null;
  1224         if ((flags & INTERFACE) != 0)
  1225             // no enclosing instance
  1226             return null;
  1227         if (nt.type.getParameterTypes().isEmpty())
  1228             // no parameters
  1229             return null;
  1231         // A constructor of an inner class.
  1232         // Remove the first argument (the enclosing instance)
  1233         nt.type = new MethodType(nt.type.getParameterTypes().tail,
  1234                                  nt.type.getReturnType(),
  1235                                  nt.type.getThrownTypes(),
  1236                                  syms.methodClass);
  1237         // Try searching again
  1238         return findMethod(nt, scope, flags);
  1241     /** Similar to Types.isSameType but avoids completion */
  1242     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1243         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1244             .prepend(types.erasure(mt1.getReturnType()));
  1245         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1246         while (!types1.isEmpty() && !types2.isEmpty()) {
  1247             if (types1.head.tsym != types2.head.tsym)
  1248                 return false;
  1249             types1 = types1.tail;
  1250             types2 = types2.tail;
  1252         return types1.isEmpty() && types2.isEmpty();
  1255     /**
  1256      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1257      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1258      */
  1259     private static boolean isAsciiDigit(char c) {
  1260         return '0' <= c && c <= '9';
  1263     /** Read member attributes.
  1264      */
  1265     void readMemberAttrs(Symbol sym) {
  1266         readAttrs(sym, AttributeKind.MEMBER);
  1269     void readAttrs(Symbol sym, AttributeKind kind) {
  1270         char ac = nextChar();
  1271         for (int i = 0; i < ac; i++) {
  1272             Name attrName = readName(nextChar());
  1273             int attrLen = nextInt();
  1274             AttributeReader r = attributeReaders.get(attrName);
  1275             if (r != null && r.accepts(kind))
  1276                 r.read(sym, attrLen);
  1277             else  {
  1278                 unrecognized(attrName);
  1279                 bp = bp + attrLen;
  1284     private boolean readingClassAttr = false;
  1285     private List<Type> missingTypeVariables = List.nil();
  1286     private List<Type> foundTypeVariables = List.nil();
  1288     /** Read class attributes.
  1289      */
  1290     void readClassAttrs(ClassSymbol c) {
  1291         readAttrs(c, AttributeKind.CLASS);
  1294     /** Read code block.
  1295      */
  1296     Code readCode(Symbol owner) {
  1297         nextChar(); // max_stack
  1298         nextChar(); // max_locals
  1299         final int  code_length = nextInt();
  1300         bp += code_length;
  1301         final char exception_table_length = nextChar();
  1302         bp += exception_table_length * 8;
  1303         readMemberAttrs(owner);
  1304         return null;
  1307 /************************************************************************
  1308  * Reading Java-language annotations
  1309  ***********************************************************************/
  1311     /** Attach annotations.
  1312      */
  1313     void attachAnnotations(final Symbol sym) {
  1314         int numAttributes = nextChar();
  1315         if (numAttributes != 0) {
  1316             ListBuffer<CompoundAnnotationProxy> proxies =
  1317                 new ListBuffer<CompoundAnnotationProxy>();
  1318             for (int i = 0; i<numAttributes; i++) {
  1319                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1320                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1321                     sym.flags_field |= PROPRIETARY;
  1322                 else
  1323                     proxies.append(proxy);
  1324                 if (majorVersion >= V51.major && proxy.type.tsym == syms.polymorphicSignatureType.tsym) {
  1325                     sym.flags_field |= POLYMORPHIC_SIGNATURE;
  1328             annotate.later(new AnnotationCompleter(sym, proxies.toList()));
  1332     /** Attach parameter annotations.
  1333      */
  1334     void attachParameterAnnotations(final Symbol method) {
  1335         final MethodSymbol meth = (MethodSymbol)method;
  1336         int numParameters = buf[bp++] & 0xFF;
  1337         List<VarSymbol> parameters = meth.params();
  1338         int pnum = 0;
  1339         while (parameters.tail != null) {
  1340             attachAnnotations(parameters.head);
  1341             parameters = parameters.tail;
  1342             pnum++;
  1344         if (pnum != numParameters) {
  1345             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1349     /** Attach the default value for an annotation element.
  1350      */
  1351     void attachAnnotationDefault(final Symbol sym) {
  1352         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1353         final Attribute value = readAttributeValue();
  1354         annotate.later(new AnnotationDefaultCompleter(meth, value));
  1357     Type readTypeOrClassSymbol(int i) {
  1358         // support preliminary jsr175-format class files
  1359         if (buf[poolIdx[i]] == CONSTANT_Class)
  1360             return readClassSymbol(i).type;
  1361         return readType(i);
  1363     Type readEnumType(int i) {
  1364         // support preliminary jsr175-format class files
  1365         int index = poolIdx[i];
  1366         int length = getChar(index + 1);
  1367         if (buf[index + length + 2] != ';')
  1368             return enterClass(readName(i)).type;
  1369         return readType(i);
  1372     CompoundAnnotationProxy readCompoundAnnotation() {
  1373         Type t = readTypeOrClassSymbol(nextChar());
  1374         int numFields = nextChar();
  1375         ListBuffer<Pair<Name,Attribute>> pairs =
  1376             new ListBuffer<Pair<Name,Attribute>>();
  1377         for (int i=0; i<numFields; i++) {
  1378             Name name = readName(nextChar());
  1379             Attribute value = readAttributeValue();
  1380             pairs.append(new Pair<Name,Attribute>(name, value));
  1382         return new CompoundAnnotationProxy(t, pairs.toList());
  1385     Attribute readAttributeValue() {
  1386         char c = (char) buf[bp++];
  1387         switch (c) {
  1388         case 'B':
  1389             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1390         case 'C':
  1391             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1392         case 'D':
  1393             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1394         case 'F':
  1395             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1396         case 'I':
  1397             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1398         case 'J':
  1399             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1400         case 'S':
  1401             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1402         case 'Z':
  1403             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1404         case 's':
  1405             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1406         case 'e':
  1407             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1408         case 'c':
  1409             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1410         case '[': {
  1411             int n = nextChar();
  1412             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1413             for (int i=0; i<n; i++)
  1414                 l.append(readAttributeValue());
  1415             return new ArrayAttributeProxy(l.toList());
  1417         case '@':
  1418             return readCompoundAnnotation();
  1419         default:
  1420             throw new AssertionError("unknown annotation tag '" + c + "'");
  1424     interface ProxyVisitor extends Attribute.Visitor {
  1425         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1426         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1427         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1430     static class EnumAttributeProxy extends Attribute {
  1431         Type enumType;
  1432         Name enumerator;
  1433         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1434             super(null);
  1435             this.enumType = enumType;
  1436             this.enumerator = enumerator;
  1438         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1439         @Override
  1440         public String toString() {
  1441             return "/*proxy enum*/" + enumType + "." + enumerator;
  1445     static class ArrayAttributeProxy extends Attribute {
  1446         List<Attribute> values;
  1447         ArrayAttributeProxy(List<Attribute> values) {
  1448             super(null);
  1449             this.values = values;
  1451         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1452         @Override
  1453         public String toString() {
  1454             return "{" + values + "}";
  1458     /** A temporary proxy representing a compound attribute.
  1459      */
  1460     static class CompoundAnnotationProxy extends Attribute {
  1461         final List<Pair<Name,Attribute>> values;
  1462         public CompoundAnnotationProxy(Type type,
  1463                                       List<Pair<Name,Attribute>> values) {
  1464             super(type);
  1465             this.values = values;
  1467         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1468         @Override
  1469         public String toString() {
  1470             StringBuilder buf = new StringBuilder();
  1471             buf.append("@");
  1472             buf.append(type.tsym.getQualifiedName());
  1473             buf.append("/*proxy*/{");
  1474             boolean first = true;
  1475             for (List<Pair<Name,Attribute>> v = values;
  1476                  v.nonEmpty(); v = v.tail) {
  1477                 Pair<Name,Attribute> value = v.head;
  1478                 if (!first) buf.append(",");
  1479                 first = false;
  1480                 buf.append(value.fst);
  1481                 buf.append("=");
  1482                 buf.append(value.snd);
  1484             buf.append("}");
  1485             return buf.toString();
  1489     /** A temporary proxy representing a type annotation.
  1490      */
  1491     static class TypeAnnotationProxy {
  1492         final CompoundAnnotationProxy compound;
  1493         final TypeAnnotationPosition position;
  1494         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1495                 TypeAnnotationPosition position) {
  1496             this.compound = compound;
  1497             this.position = position;
  1501     class AnnotationDeproxy implements ProxyVisitor {
  1502         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1503             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1505         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1506             // also must fill in types!!!!
  1507             ListBuffer<Attribute.Compound> buf =
  1508                 new ListBuffer<Attribute.Compound>();
  1509             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1510                 buf.append(deproxyCompound(l.head));
  1512             return buf.toList();
  1515         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1516             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1517                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1518             for (List<Pair<Name,Attribute>> l = a.values;
  1519                  l.nonEmpty();
  1520                  l = l.tail) {
  1521                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1522                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1523                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1525             return new Attribute.Compound(a.type, buf.toList());
  1528         MethodSymbol findAccessMethod(Type container, Name name) {
  1529             CompletionFailure failure = null;
  1530             try {
  1531                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1532                      e.scope != null;
  1533                      e = e.next()) {
  1534                     Symbol sym = e.sym;
  1535                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1536                         return (MethodSymbol) sym;
  1538             } catch (CompletionFailure ex) {
  1539                 failure = ex;
  1541             // The method wasn't found: emit a warning and recover
  1542             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1543             try {
  1544                 if (failure == null) {
  1545                     log.warning("annotation.method.not.found",
  1546                                 container,
  1547                                 name);
  1548                 } else {
  1549                     log.warning("annotation.method.not.found.reason",
  1550                                 container,
  1551                                 name,
  1552                                 failure.getDetailValue());//diagnostic, if present
  1554             } finally {
  1555                 log.useSource(prevSource);
  1557             // Construct a new method type and symbol.  Use bottom
  1558             // type (typeof null) as return type because this type is
  1559             // a subtype of all reference types and can be converted
  1560             // to primitive types by unboxing.
  1561             MethodType mt = new MethodType(List.<Type>nil(),
  1562                                            syms.botType,
  1563                                            List.<Type>nil(),
  1564                                            syms.methodClass);
  1565             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1568         Attribute result;
  1569         Type type;
  1570         Attribute deproxy(Type t, Attribute a) {
  1571             Type oldType = type;
  1572             try {
  1573                 type = t;
  1574                 a.accept(this);
  1575                 return result;
  1576             } finally {
  1577                 type = oldType;
  1581         // implement Attribute.Visitor below
  1583         public void visitConstant(Attribute.Constant value) {
  1584             // assert value.type == type;
  1585             result = value;
  1588         public void visitClass(Attribute.Class clazz) {
  1589             result = clazz;
  1592         public void visitEnum(Attribute.Enum e) {
  1593             throw new AssertionError(); // shouldn't happen
  1596         public void visitCompound(Attribute.Compound compound) {
  1597             throw new AssertionError(); // shouldn't happen
  1600         public void visitArray(Attribute.Array array) {
  1601             throw new AssertionError(); // shouldn't happen
  1604         public void visitError(Attribute.Error e) {
  1605             throw new AssertionError(); // shouldn't happen
  1608         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1609             // type.tsym.flatName() should == proxy.enumFlatName
  1610             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1611             VarSymbol enumerator = null;
  1612             for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1613                  e.scope != null;
  1614                  e = e.next()) {
  1615                 if (e.sym.kind == VAR) {
  1616                     enumerator = (VarSymbol)e.sym;
  1617                     break;
  1620             if (enumerator == null) {
  1621                 log.error("unknown.enum.constant",
  1622                           currentClassFile, enumTypeSym, proxy.enumerator);
  1623                 result = new Attribute.Error(enumTypeSym.type);
  1624             } else {
  1625                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1629         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1630             int length = proxy.values.length();
  1631             Attribute[] ats = new Attribute[length];
  1632             Type elemtype = types.elemtype(type);
  1633             int i = 0;
  1634             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1635                 ats[i++] = deproxy(elemtype, p.head);
  1637             result = new Attribute.Array(type, ats);
  1640         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1641             result = deproxyCompound(proxy);
  1645     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1646         final MethodSymbol sym;
  1647         final Attribute value;
  1648         final JavaFileObject classFile = currentClassFile;
  1649         @Override
  1650         public String toString() {
  1651             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1653         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1654             this.sym = sym;
  1655             this.value = value;
  1657         // implement Annotate.Annotator.enterAnnotation()
  1658         public void enterAnnotation() {
  1659             JavaFileObject previousClassFile = currentClassFile;
  1660             try {
  1661                 currentClassFile = classFile;
  1662                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1663             } finally {
  1664                 currentClassFile = previousClassFile;
  1669     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1670         final Symbol sym;
  1671         final List<CompoundAnnotationProxy> l;
  1672         final JavaFileObject classFile;
  1673         @Override
  1674         public String toString() {
  1675             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1677         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1678             this.sym = sym;
  1679             this.l = l;
  1680             this.classFile = currentClassFile;
  1682         // implement Annotate.Annotator.enterAnnotation()
  1683         public void enterAnnotation() {
  1684             JavaFileObject previousClassFile = currentClassFile;
  1685             try {
  1686                 currentClassFile = classFile;
  1687                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1688                 sym.attributes_field = ((sym.attributes_field == null)
  1689                                         ? newList
  1690                                         : newList.prependList(sym.attributes_field));
  1691             } finally {
  1692                 currentClassFile = previousClassFile;
  1698 /************************************************************************
  1699  * Reading Symbols
  1700  ***********************************************************************/
  1702     /** Read a field.
  1703      */
  1704     VarSymbol readField() {
  1705         long flags = adjustFieldFlags(nextChar());
  1706         Name name = readName(nextChar());
  1707         Type type = readType(nextChar());
  1708         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1709         readMemberAttrs(v);
  1710         return v;
  1713     /** Read a method.
  1714      */
  1715     MethodSymbol readMethod() {
  1716         long flags = adjustMethodFlags(nextChar());
  1717         Name name = readName(nextChar());
  1718         Type type = readType(nextChar());
  1719         if (name == names.init && currentOwner.hasOuterInstance()) {
  1720             // Sometimes anonymous classes don't have an outer
  1721             // instance, however, there is no reliable way to tell so
  1722             // we never strip this$n
  1723             if (!currentOwner.name.isEmpty())
  1724                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  1725                                       type.getReturnType(),
  1726                                       type.getThrownTypes(),
  1727                                       syms.methodClass);
  1729         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  1730         if (saveParameterNames)
  1731             initParameterNames(m);
  1732         Symbol prevOwner = currentOwner;
  1733         currentOwner = m;
  1734         try {
  1735             readMemberAttrs(m);
  1736         } finally {
  1737             currentOwner = prevOwner;
  1739         if (saveParameterNames)
  1740             setParameterNames(m, type);
  1741         return m;
  1744     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  1745         boolean isVarargs = (flags & VARARGS) != 0;
  1746         if (isVarargs) {
  1747             Type varargsElem = args.last();
  1748             ListBuffer<Type> adjustedArgs = ListBuffer.lb();
  1749             for (Type t : args) {
  1750                 adjustedArgs.append(t != varargsElem ?
  1751                     t :
  1752                     ((ArrayType)t).makeVarargs());
  1754             args = adjustedArgs.toList();
  1756         return args.tail;
  1759     /**
  1760      * Init the parameter names array.
  1761      * Parameter names are currently inferred from the names in the
  1762      * LocalVariableTable attributes of a Code attribute.
  1763      * (Note: this means parameter names are currently not available for
  1764      * methods without a Code attribute.)
  1765      * This method initializes an array in which to store the name indexes
  1766      * of parameter names found in LocalVariableTable attributes. It is
  1767      * slightly supersized to allow for additional slots with a start_pc of 0.
  1768      */
  1769     void initParameterNames(MethodSymbol sym) {
  1770         // make allowance for synthetic parameters.
  1771         final int excessSlots = 4;
  1772         int expectedParameterSlots =
  1773                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  1774         if (parameterNameIndices == null
  1775                 || parameterNameIndices.length < expectedParameterSlots) {
  1776             parameterNameIndices = new int[expectedParameterSlots];
  1777         } else
  1778             Arrays.fill(parameterNameIndices, 0);
  1779         haveParameterNameIndices = false;
  1782     /**
  1783      * Set the parameter names for a symbol from the name index in the
  1784      * parameterNameIndicies array. The type of the symbol may have changed
  1785      * while reading the method attributes (see the Signature attribute).
  1786      * This may be because of generic information or because anonymous
  1787      * synthetic parameters were added.   The original type (as read from
  1788      * the method descriptor) is used to help guess the existence of
  1789      * anonymous synthetic parameters.
  1790      * On completion, sym.savedParameter names will either be null (if
  1791      * no parameter names were found in the class file) or will be set to a
  1792      * list of names, one per entry in sym.type.getParameterTypes, with
  1793      * any missing names represented by the empty name.
  1794      */
  1795     void setParameterNames(MethodSymbol sym, Type jvmType) {
  1796         // if no names were found in the class file, there's nothing more to do
  1797         if (!haveParameterNameIndices)
  1798             return;
  1800         int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  1801         // the code in readMethod may have skipped the first parameter when
  1802         // setting up the MethodType. If so, we make a corresponding allowance
  1803         // here for the position of the first parameter.  Note that this
  1804         // assumes the skipped parameter has a width of 1 -- i.e. it is not
  1805         // a double width type (long or double.)
  1806         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  1807             // Sometimes anonymous classes don't have an outer
  1808             // instance, however, there is no reliable way to tell so
  1809             // we never strip this$n
  1810             if (!currentOwner.name.isEmpty())
  1811                 firstParam += 1;
  1814         if (sym.type != jvmType) {
  1815             // reading the method attributes has caused the symbol's type to
  1816             // be changed. (i.e. the Signature attribute.)  This may happen if
  1817             // there are hidden (synthetic) parameters in the descriptor, but
  1818             // not in the Signature.  The position of these hidden parameters
  1819             // is unspecified; for now, assume they are at the beginning, and
  1820             // so skip over them. The primary case for this is two hidden
  1821             // parameters passed into Enum constructors.
  1822             int skip = Code.width(jvmType.getParameterTypes())
  1823                     - Code.width(sym.type.getParameterTypes());
  1824             firstParam += skip;
  1826         List<Name> paramNames = List.nil();
  1827         int index = firstParam;
  1828         for (Type t: sym.type.getParameterTypes()) {
  1829             int nameIdx = (index < parameterNameIndices.length
  1830                     ? parameterNameIndices[index] : 0);
  1831             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  1832             paramNames = paramNames.prepend(name);
  1833             index += Code.width(t);
  1835         sym.savedParameterNames = paramNames.reverse();
  1838     /**
  1839      * skip n bytes
  1840      */
  1841     void skipBytes(int n) {
  1842         bp = bp + n;
  1845     /** Skip a field or method
  1846      */
  1847     void skipMember() {
  1848         bp = bp + 6;
  1849         char ac = nextChar();
  1850         for (int i = 0; i < ac; i++) {
  1851             bp = bp + 2;
  1852             int attrLen = nextInt();
  1853             bp = bp + attrLen;
  1857     /** Enter type variables of this classtype and all enclosing ones in
  1858      *  `typevars'.
  1859      */
  1860     protected void enterTypevars(Type t) {
  1861         if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
  1862             enterTypevars(t.getEnclosingType());
  1863         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  1864             typevars.enter(xs.head.tsym);
  1867     protected void enterTypevars(Symbol sym) {
  1868         if (sym.owner.kind == MTH) {
  1869             enterTypevars(sym.owner);
  1870             enterTypevars(sym.owner.owner);
  1872         enterTypevars(sym.type);
  1875     /** Read contents of a given class symbol `c'. Both external and internal
  1876      *  versions of an inner class are read.
  1877      */
  1878     void readClass(ClassSymbol c) {
  1879         ClassType ct = (ClassType)c.type;
  1881         // allocate scope for members
  1882         c.members_field = new Scope.ClassScope(c, scopeCounter);
  1884         // prepare type variable table
  1885         typevars = typevars.dup(currentOwner);
  1886         if (ct.getEnclosingType().tag == CLASS)
  1887             enterTypevars(ct.getEnclosingType());
  1889         // read flags, or skip if this is an inner class
  1890         long flags = adjustClassFlags(nextChar());
  1891         if (c.owner.kind == PCK) c.flags_field = flags;
  1893         // read own class name and check that it matches
  1894         ClassSymbol self = readClassSymbol(nextChar());
  1895         if (c != self)
  1896             throw badClassFile("class.file.wrong.class",
  1897                                self.flatname);
  1899         // class attributes must be read before class
  1900         // skip ahead to read class attributes
  1901         int startbp = bp;
  1902         nextChar();
  1903         char interfaceCount = nextChar();
  1904         bp += interfaceCount * 2;
  1905         char fieldCount = nextChar();
  1906         for (int i = 0; i < fieldCount; i++) skipMember();
  1907         char methodCount = nextChar();
  1908         for (int i = 0; i < methodCount; i++) skipMember();
  1909         readClassAttrs(c);
  1911         if (readAllOfClassFile) {
  1912             for (int i = 1; i < poolObj.length; i++) readPool(i);
  1913             c.pool = new Pool(poolObj.length, poolObj);
  1916         // reset and read rest of classinfo
  1917         bp = startbp;
  1918         int n = nextChar();
  1919         if (ct.supertype_field == null)
  1920             ct.supertype_field = (n == 0)
  1921                 ? Type.noType
  1922                 : readClassSymbol(n).erasure(types);
  1923         n = nextChar();
  1924         List<Type> is = List.nil();
  1925         for (int i = 0; i < n; i++) {
  1926             Type _inter = readClassSymbol(nextChar()).erasure(types);
  1927             is = is.prepend(_inter);
  1929         if (ct.interfaces_field == null)
  1930             ct.interfaces_field = is.reverse();
  1932         Assert.check(fieldCount == nextChar());
  1933         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  1934         Assert.check(methodCount == nextChar());
  1935         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  1937         typevars = typevars.leave();
  1940     /** Read inner class info. For each inner/outer pair allocate a
  1941      *  member class.
  1942      */
  1943     void readInnerClasses(ClassSymbol c) {
  1944         int n = nextChar();
  1945         for (int i = 0; i < n; i++) {
  1946             nextChar(); // skip inner class symbol
  1947             ClassSymbol outer = readClassSymbol(nextChar());
  1948             Name name = readName(nextChar());
  1949             if (name == null) name = names.empty;
  1950             long flags = adjustClassFlags(nextChar());
  1951             if (outer != null) { // we have a member class
  1952                 if (name == names.empty)
  1953                     name = names.one;
  1954                 ClassSymbol member = enterClass(name, outer);
  1955                 if ((flags & STATIC) == 0) {
  1956                     ((ClassType)member.type).setEnclosingType(outer.type);
  1957                     if (member.erasure_field != null)
  1958                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  1960                 if (c == outer) {
  1961                     member.flags_field = flags;
  1962                     enterMember(c, member);
  1968     /** Read a class file.
  1969      */
  1970     private void readClassFile(ClassSymbol c) throws IOException {
  1971         int magic = nextInt();
  1972         if (magic != JAVA_MAGIC)
  1973             throw badClassFile("illegal.start.of.class.file");
  1975         minorVersion = nextChar();
  1976         majorVersion = nextChar();
  1977         int maxMajor = Target.MAX().majorVersion;
  1978         int maxMinor = Target.MAX().minorVersion;
  1979         if (majorVersion > maxMajor ||
  1980             majorVersion * 1000 + minorVersion <
  1981             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  1983             if (majorVersion == (maxMajor + 1))
  1984                 log.warning("big.major.version",
  1985                             currentClassFile,
  1986                             majorVersion,
  1987                             maxMajor);
  1988             else
  1989                 throw badClassFile("wrong.version",
  1990                                    Integer.toString(majorVersion),
  1991                                    Integer.toString(minorVersion),
  1992                                    Integer.toString(maxMajor),
  1993                                    Integer.toString(maxMinor));
  1995         else if (checkClassFile &&
  1996                  majorVersion == maxMajor &&
  1997                  minorVersion > maxMinor)
  1999             printCCF("found.later.version",
  2000                      Integer.toString(minorVersion));
  2002         indexPool();
  2003         if (signatureBuffer.length < bp) {
  2004             int ns = Integer.highestOneBit(bp) << 1;
  2005             signatureBuffer = new byte[ns];
  2007         readClass(c);
  2010 /************************************************************************
  2011  * Adjusting flags
  2012  ***********************************************************************/
  2014     long adjustFieldFlags(long flags) {
  2015         return flags;
  2017     long adjustMethodFlags(long flags) {
  2018         if ((flags & ACC_BRIDGE) != 0) {
  2019             flags &= ~ACC_BRIDGE;
  2020             flags |= BRIDGE;
  2021             if (!allowGenerics)
  2022                 flags &= ~SYNTHETIC;
  2024         if ((flags & ACC_VARARGS) != 0) {
  2025             flags &= ~ACC_VARARGS;
  2026             flags |= VARARGS;
  2028         return flags;
  2030     long adjustClassFlags(long flags) {
  2031         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2034 /************************************************************************
  2035  * Loading Classes
  2036  ***********************************************************************/
  2038     /** Define a new class given its name and owner.
  2039      */
  2040     public ClassSymbol defineClass(Name name, Symbol owner) {
  2041         ClassSymbol c = new ClassSymbol(0, name, owner);
  2042         if (owner.kind == PCK)
  2043             Assert.checkNull(classes.get(c.flatname), c);
  2044         c.completer = this;
  2045         return c;
  2048     /** Create a new toplevel or member class symbol with given name
  2049      *  and owner and enter in `classes' unless already there.
  2050      */
  2051     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2052         Name flatname = TypeSymbol.formFlatName(name, owner);
  2053         ClassSymbol c = classes.get(flatname);
  2054         if (c == null) {
  2055             c = defineClass(name, owner);
  2056             classes.put(flatname, c);
  2057         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2058             // reassign fields of classes that might have been loaded with
  2059             // their flat names.
  2060             c.owner.members().remove(c);
  2061             c.name = name;
  2062             c.owner = owner;
  2063             c.fullname = ClassSymbol.formFullName(name, owner);
  2065         return c;
  2068     /**
  2069      * Creates a new toplevel class symbol with given flat name and
  2070      * given class (or source) file.
  2072      * @param flatName a fully qualified binary class name
  2073      * @param classFile the class file or compilation unit defining
  2074      * the class (may be {@code null})
  2075      * @return a newly created class symbol
  2076      * @throws AssertionError if the class symbol already exists
  2077      */
  2078     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2079         ClassSymbol cs = classes.get(flatName);
  2080         if (cs != null) {
  2081             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2082                                     cs.fullname,
  2083                                     cs.completer,
  2084                                     cs.classfile,
  2085                                     cs.sourcefile);
  2086             throw new AssertionError(msg);
  2088         Name packageName = Convert.packagePart(flatName);
  2089         PackageSymbol owner = packageName.isEmpty()
  2090                                 ? syms.unnamedPackage
  2091                                 : enterPackage(packageName);
  2092         cs = defineClass(Convert.shortName(flatName), owner);
  2093         cs.classfile = classFile;
  2094         classes.put(flatName, cs);
  2095         return cs;
  2098     /** Create a new member or toplevel class symbol with given flat name
  2099      *  and enter in `classes' unless already there.
  2100      */
  2101     public ClassSymbol enterClass(Name flatname) {
  2102         ClassSymbol c = classes.get(flatname);
  2103         if (c == null)
  2104             return enterClass(flatname, (JavaFileObject)null);
  2105         else
  2106             return c;
  2109     private boolean suppressFlush = false;
  2111     /** Completion for classes to be loaded. Before a class is loaded
  2112      *  we make sure its enclosing class (if any) is loaded.
  2113      */
  2114     public void complete(Symbol sym) throws CompletionFailure {
  2115         if (sym.kind == TYP) {
  2116             ClassSymbol c = (ClassSymbol)sym;
  2117             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2118             boolean saveSuppressFlush = suppressFlush;
  2119             suppressFlush = true;
  2120             try {
  2121                 completeOwners(c.owner);
  2122                 completeEnclosing(c);
  2123             } finally {
  2124                 suppressFlush = saveSuppressFlush;
  2126             fillIn(c);
  2127         } else if (sym.kind == PCK) {
  2128             PackageSymbol p = (PackageSymbol)sym;
  2129             try {
  2130                 fillIn(p);
  2131             } catch (IOException ex) {
  2132                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2135         if (!filling && !suppressFlush)
  2136             annotate.flush(); // finish attaching annotations
  2139     /** complete up through the enclosing package. */
  2140     private void completeOwners(Symbol o) {
  2141         if (o.kind != PCK) completeOwners(o.owner);
  2142         o.complete();
  2145     /**
  2146      * Tries to complete lexically enclosing classes if c looks like a
  2147      * nested class.  This is similar to completeOwners but handles
  2148      * the situation when a nested class is accessed directly as it is
  2149      * possible with the Tree API or javax.lang.model.*.
  2150      */
  2151     private void completeEnclosing(ClassSymbol c) {
  2152         if (c.owner.kind == PCK) {
  2153             Symbol owner = c.owner;
  2154             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2155                 Symbol encl = owner.members().lookup(name).sym;
  2156                 if (encl == null)
  2157                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2158                 if (encl != null)
  2159                     encl.complete();
  2164     /** We can only read a single class file at a time; this
  2165      *  flag keeps track of when we are currently reading a class
  2166      *  file.
  2167      */
  2168     private boolean filling = false;
  2170     /** Fill in definition of class `c' from corresponding class or
  2171      *  source file.
  2172      */
  2173     private void fillIn(ClassSymbol c) {
  2174         if (completionFailureName == c.fullname) {
  2175             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2177         currentOwner = c;
  2178         warnedAttrs.clear();
  2179         JavaFileObject classfile = c.classfile;
  2180         if (classfile != null) {
  2181             JavaFileObject previousClassFile = currentClassFile;
  2182             try {
  2183                 if (filling) {
  2184                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2186                 currentClassFile = classfile;
  2187                 if (verbose) {
  2188                     printVerbose("loading", currentClassFile.toString());
  2190                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2191                     filling = true;
  2192                     try {
  2193                         bp = 0;
  2194                         buf = readInputStream(buf, classfile.openInputStream());
  2195                         readClassFile(c);
  2196                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2197                             List<Type> missing = missingTypeVariables;
  2198                             List<Type> found = foundTypeVariables;
  2199                             missingTypeVariables = List.nil();
  2200                             foundTypeVariables = List.nil();
  2201                             filling = false;
  2202                             ClassType ct = (ClassType)currentOwner.type;
  2203                             ct.supertype_field =
  2204                                 types.subst(ct.supertype_field, missing, found);
  2205                             ct.interfaces_field =
  2206                                 types.subst(ct.interfaces_field, missing, found);
  2207                         } else if (missingTypeVariables.isEmpty() !=
  2208                                    foundTypeVariables.isEmpty()) {
  2209                             Name name = missingTypeVariables.head.tsym.name;
  2210                             throw badClassFile("undecl.type.var", name);
  2212                     } finally {
  2213                         missingTypeVariables = List.nil();
  2214                         foundTypeVariables = List.nil();
  2215                         filling = false;
  2217                 } else {
  2218                     if (sourceCompleter != null) {
  2219                         sourceCompleter.complete(c);
  2220                     } else {
  2221                         throw new IllegalStateException("Source completer required to read "
  2222                                                         + classfile.toUri());
  2225                 return;
  2226             } catch (IOException ex) {
  2227                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2228             } finally {
  2229                 currentClassFile = previousClassFile;
  2231         } else {
  2232             JCDiagnostic diag =
  2233                 diagFactory.fragment("class.file.not.found", c.flatname);
  2234             throw
  2235                 newCompletionFailure(c, diag);
  2238     // where
  2239         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2240             try {
  2241                 buf = ensureCapacity(buf, s.available());
  2242                 int r = s.read(buf);
  2243                 int bp = 0;
  2244                 while (r != -1) {
  2245                     bp += r;
  2246                     buf = ensureCapacity(buf, bp);
  2247                     r = s.read(buf, bp, buf.length - bp);
  2249                 return buf;
  2250             } finally {
  2251                 try {
  2252                     s.close();
  2253                 } catch (IOException e) {
  2254                     /* Ignore any errors, as this stream may have already
  2255                      * thrown a related exception which is the one that
  2256                      * should be reported.
  2257                      */
  2261         /*
  2262          * ensureCapacity will increase the buffer as needed, taking note that
  2263          * the new buffer will always be greater than the needed and never
  2264          * exactly equal to the needed size or bp. If equal then the read (above)
  2265          * will infinitely loop as buf.length - bp == 0.
  2266          */
  2267         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2268             if (buf.length <= needed) {
  2269                 byte[] old = buf;
  2270                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2271                 System.arraycopy(old, 0, buf, 0, old.length);
  2273             return buf;
  2275         /** Static factory for CompletionFailure objects.
  2276          *  In practice, only one can be used at a time, so we share one
  2277          *  to reduce the expense of allocating new exception objects.
  2278          */
  2279         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2280                                                        JCDiagnostic diag) {
  2281             if (!cacheCompletionFailure) {
  2282                 // log.warning("proc.messager",
  2283                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2284                 // c.debug.printStackTrace();
  2285                 return new CompletionFailure(c, diag);
  2286             } else {
  2287                 CompletionFailure result = cachedCompletionFailure;
  2288                 result.sym = c;
  2289                 result.diag = diag;
  2290                 return result;
  2293         private CompletionFailure cachedCompletionFailure =
  2294             new CompletionFailure(null, (JCDiagnostic) null);
  2296             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2299     /** Load a toplevel class with given fully qualified name
  2300      *  The class is entered into `classes' only if load was successful.
  2301      */
  2302     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2303         boolean absent = classes.get(flatname) == null;
  2304         ClassSymbol c = enterClass(flatname);
  2305         if (c.members_field == null && c.completer != null) {
  2306             try {
  2307                 c.complete();
  2308             } catch (CompletionFailure ex) {
  2309                 if (absent) classes.remove(flatname);
  2310                 throw ex;
  2313         return c;
  2316 /************************************************************************
  2317  * Loading Packages
  2318  ***********************************************************************/
  2320     /** Check to see if a package exists, given its fully qualified name.
  2321      */
  2322     public boolean packageExists(Name fullname) {
  2323         return enterPackage(fullname).exists();
  2326     /** Make a package, given its fully qualified name.
  2327      */
  2328     public PackageSymbol enterPackage(Name fullname) {
  2329         PackageSymbol p = packages.get(fullname);
  2330         if (p == null) {
  2331             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2332             p = new PackageSymbol(
  2333                 Convert.shortName(fullname),
  2334                 enterPackage(Convert.packagePart(fullname)));
  2335             p.completer = this;
  2336             packages.put(fullname, p);
  2338         return p;
  2341     /** Make a package, given its unqualified name and enclosing package.
  2342      */
  2343     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2344         return enterPackage(TypeSymbol.formFullName(name, owner));
  2347     /** Include class corresponding to given class file in package,
  2348      *  unless (1) we already have one the same kind (.class or .java), or
  2349      *         (2) we have one of the other kind, and the given class file
  2350      *             is older.
  2351      */
  2352     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2353         if ((p.flags_field & EXISTS) == 0)
  2354             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2355                 q.flags_field |= EXISTS;
  2356         JavaFileObject.Kind kind = file.getKind();
  2357         int seen;
  2358         if (kind == JavaFileObject.Kind.CLASS)
  2359             seen = CLASS_SEEN;
  2360         else
  2361             seen = SOURCE_SEEN;
  2362         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2363         int lastDot = binaryName.lastIndexOf(".");
  2364         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2365         boolean isPkgInfo = classname == names.package_info;
  2366         ClassSymbol c = isPkgInfo
  2367             ? p.package_info
  2368             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2369         if (c == null) {
  2370             c = enterClass(classname, p);
  2371             if (c.classfile == null) // only update the file if's it's newly created
  2372                 c.classfile = file;
  2373             if (isPkgInfo) {
  2374                 p.package_info = c;
  2375             } else {
  2376                 if (c.owner == p)  // it might be an inner class
  2377                     p.members_field.enter(c);
  2379         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2380             // if c.classfile == null, we are currently compiling this class
  2381             // and no further action is necessary.
  2382             // if (c.flags_field & seen) != 0, we have already encountered
  2383             // a file of the same kind; again no further action is necessary.
  2384             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2385                 c.classfile = preferredFileObject(file, c.classfile);
  2387         c.flags_field |= seen;
  2390     /** Implement policy to choose to derive information from a source
  2391      *  file or a class file when both are present.  May be overridden
  2392      *  by subclasses.
  2393      */
  2394     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2395                                            JavaFileObject b) {
  2397         if (preferSource)
  2398             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2399         else {
  2400             long adate = a.getLastModified();
  2401             long bdate = b.getLastModified();
  2402             // 6449326: policy for bad lastModifiedTime in ClassReader
  2403             //assert adate >= 0 && bdate >= 0;
  2404             return (adate > bdate) ? a : b;
  2408     /**
  2409      * specifies types of files to be read when filling in a package symbol
  2410      */
  2411     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2412         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2415     /**
  2416      * this is used to support javadoc
  2417      */
  2418     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2421     protected Location currentLoc; // FIXME
  2423     private boolean verbosePath = true;
  2425     /** Load directory of package into members scope.
  2426      */
  2427     private void fillIn(PackageSymbol p) throws IOException {
  2428         if (p.members_field == null) p.members_field = new Scope(p);
  2429         String packageName = p.fullname.toString();
  2431         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2433         fillIn(p, PLATFORM_CLASS_PATH,
  2434                fileManager.list(PLATFORM_CLASS_PATH,
  2435                                 packageName,
  2436                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2437                                 false));
  2439         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2440         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2441         boolean wantClassFiles = !classKinds.isEmpty();
  2443         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2444         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2445         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2447         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2449         if (verbose && verbosePath) {
  2450             if (fileManager instanceof StandardJavaFileManager) {
  2451                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2452                 if (haveSourcePath && wantSourceFiles) {
  2453                     List<File> path = List.nil();
  2454                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2455                         path = path.prepend(file);
  2457                     printVerbose("sourcepath", path.reverse().toString());
  2458                 } else if (wantSourceFiles) {
  2459                     List<File> path = List.nil();
  2460                     for (File file : fm.getLocation(CLASS_PATH)) {
  2461                         path = path.prepend(file);
  2463                     printVerbose("sourcepath", path.reverse().toString());
  2465                 if (wantClassFiles) {
  2466                     List<File> path = List.nil();
  2467                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2468                         path = path.prepend(file);
  2470                     for (File file : fm.getLocation(CLASS_PATH)) {
  2471                         path = path.prepend(file);
  2473                     printVerbose("classpath",  path.reverse().toString());
  2478         if (wantSourceFiles && !haveSourcePath) {
  2479             fillIn(p, CLASS_PATH,
  2480                    fileManager.list(CLASS_PATH,
  2481                                     packageName,
  2482                                     kinds,
  2483                                     false));
  2484         } else {
  2485             if (wantClassFiles)
  2486                 fillIn(p, CLASS_PATH,
  2487                        fileManager.list(CLASS_PATH,
  2488                                         packageName,
  2489                                         classKinds,
  2490                                         false));
  2491             if (wantSourceFiles)
  2492                 fillIn(p, SOURCE_PATH,
  2493                        fileManager.list(SOURCE_PATH,
  2494                                         packageName,
  2495                                         sourceKinds,
  2496                                         false));
  2498         verbosePath = false;
  2500     // where
  2501         private void fillIn(PackageSymbol p,
  2502                             Location location,
  2503                             Iterable<JavaFileObject> files)
  2505             currentLoc = location;
  2506             for (JavaFileObject fo : files) {
  2507                 switch (fo.getKind()) {
  2508                 case CLASS:
  2509                 case SOURCE: {
  2510                     // TODO pass binaryName to includeClassFile
  2511                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2512                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2513                     if (SourceVersion.isIdentifier(simpleName) ||
  2514                         simpleName.equals("package-info"))
  2515                         includeClassFile(p, fo);
  2516                     break;
  2518                 default:
  2519                     extraFileActions(p, fo);
  2524     /** Output for "-verbose" option.
  2525      *  @param key The key to look up the correct internationalized string.
  2526      *  @param arg An argument for substitution into the output string.
  2527      */
  2528     private void printVerbose(String key, CharSequence arg) {
  2529         log.printNoteLines("verbose." + key, arg);
  2532     /** Output for "-checkclassfile" option.
  2533      *  @param key The key to look up the correct internationalized string.
  2534      *  @param arg An argument for substitution into the output string.
  2535      */
  2536     private void printCCF(String key, Object arg) {
  2537         log.printNoteLines(key, arg);
  2541     public interface SourceCompleter {
  2542         void complete(ClassSymbol sym)
  2543             throws CompletionFailure;
  2546     /**
  2547      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2548      * The attribute is only the last component of the original filename, so is unlikely
  2549      * to be valid as is, so operations other than those to access the name throw
  2550      * UnsupportedOperationException
  2551      */
  2552     private static class SourceFileObject extends BaseFileObject {
  2554         /** The file's name.
  2555          */
  2556         private Name name;
  2557         private Name flatname;
  2559         public SourceFileObject(Name name, Name flatname) {
  2560             super(null); // no file manager; never referenced for this file object
  2561             this.name = name;
  2562             this.flatname = flatname;
  2565         @Override
  2566         public URI toUri() {
  2567             try {
  2568                 return new URI(null, name.toString(), null);
  2569             } catch (URISyntaxException e) {
  2570                 throw new CannotCreateUriError(name.toString(), e);
  2574         @Override
  2575         public String getName() {
  2576             return name.toString();
  2579         @Override
  2580         public String getShortName() {
  2581             return getName();
  2584         @Override
  2585         public JavaFileObject.Kind getKind() {
  2586             return getKind(getName());
  2589         @Override
  2590         public InputStream openInputStream() {
  2591             throw new UnsupportedOperationException();
  2594         @Override
  2595         public OutputStream openOutputStream() {
  2596             throw new UnsupportedOperationException();
  2599         @Override
  2600         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2601             throw new UnsupportedOperationException();
  2604         @Override
  2605         public Reader openReader(boolean ignoreEncodingErrors) {
  2606             throw new UnsupportedOperationException();
  2609         @Override
  2610         public Writer openWriter() {
  2611             throw new UnsupportedOperationException();
  2614         @Override
  2615         public long getLastModified() {
  2616             throw new UnsupportedOperationException();
  2619         @Override
  2620         public boolean delete() {
  2621             throw new UnsupportedOperationException();
  2624         @Override
  2625         protected String inferBinaryName(Iterable<? extends File> path) {
  2626             return flatname.toString();
  2629         @Override
  2630         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2631             return true; // fail-safe mode
  2634         /**
  2635          * Check if two file objects are equal.
  2636          * SourceFileObjects are just placeholder objects for the value of a
  2637          * SourceFile attribute, and do not directly represent specific files.
  2638          * Two SourceFileObjects are equal if their names are equal.
  2639          */
  2640         @Override
  2641         public boolean equals(Object other) {
  2642             if (this == other)
  2643                 return true;
  2645             if (!(other instanceof SourceFileObject))
  2646                 return false;
  2648             SourceFileObject o = (SourceFileObject) other;
  2649             return name.equals(o.name);
  2652         @Override
  2653         public int hashCode() {
  2654             return name.hashCode();

mercurial