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

Mon, 10 Jan 2011 15:08:31 -0800

author
jjg
date
Mon, 10 Jan 2011 15:08:31 -0800
changeset 816
7c537f4298fb
parent 815
d17f37522154
child 826
5cf6c432ef2f
permissions
-rw-r--r--

6396503: javac should not require assertions enabled
Reviewed-by: mcimadamore

     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                 bp = bp + 2;
   438                 break;
   439             case CONSTANT_Fieldref:
   440             case CONSTANT_Methodref:
   441             case CONSTANT_InterfaceMethodref:
   442             case CONSTANT_NameandType:
   443             case CONSTANT_Integer:
   444             case CONSTANT_Float:
   445                 bp = bp + 4;
   446                 break;
   447             case CONSTANT_Long:
   448             case CONSTANT_Double:
   449                 bp = bp + 8;
   450                 i++;
   451                 break;
   452             default:
   453                 throw badClassFile("bad.const.pool.tag.at",
   454                                    Byte.toString(tag),
   455                                    Integer.toString(bp -1));
   456             }
   457         }
   458     }
   460     /** Read constant pool entry at start address i, use pool as a cache.
   461      */
   462     Object readPool(int i) {
   463         Object result = poolObj[i];
   464         if (result != null) return result;
   466         int index = poolIdx[i];
   467         if (index == 0) return null;
   469         byte tag = buf[index];
   470         switch (tag) {
   471         case CONSTANT_Utf8:
   472             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   473             break;
   474         case CONSTANT_Unicode:
   475             throw badClassFile("unicode.str.not.supported");
   476         case CONSTANT_Class:
   477             poolObj[i] = readClassOrType(getChar(index + 1));
   478             break;
   479         case CONSTANT_String:
   480             // FIXME: (footprint) do not use toString here
   481             poolObj[i] = readName(getChar(index + 1)).toString();
   482             break;
   483         case CONSTANT_Fieldref: {
   484             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   485             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   486             poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
   487             break;
   488         }
   489         case CONSTANT_Methodref:
   490         case CONSTANT_InterfaceMethodref: {
   491             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   492             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   493             poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
   494             break;
   495         }
   496         case CONSTANT_NameandType:
   497             poolObj[i] = new NameAndType(
   498                 readName(getChar(index + 1)),
   499                 readType(getChar(index + 3)));
   500             break;
   501         case CONSTANT_Integer:
   502             poolObj[i] = getInt(index + 1);
   503             break;
   504         case CONSTANT_Float:
   505             poolObj[i] = new Float(getFloat(index + 1));
   506             break;
   507         case CONSTANT_Long:
   508             poolObj[i] = new Long(getLong(index + 1));
   509             break;
   510         case CONSTANT_Double:
   511             poolObj[i] = new Double(getDouble(index + 1));
   512             break;
   513         default:
   514             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   515         }
   516         return poolObj[i];
   517     }
   519     /** Read signature and convert to type.
   520      */
   521     Type readType(int i) {
   522         int index = poolIdx[i];
   523         return sigToType(buf, index + 3, getChar(index + 1));
   524     }
   526     /** If name is an array type or class signature, return the
   527      *  corresponding type; otherwise return a ClassSymbol with given name.
   528      */
   529     Object readClassOrType(int i) {
   530         int index =  poolIdx[i];
   531         int len = getChar(index + 1);
   532         int start = index + 3;
   533         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   534         // by the above assertion, the following test can be
   535         // simplified to (buf[start] == '[')
   536         return (buf[start] == '[' || buf[start + len - 1] == ';')
   537             ? (Object)sigToType(buf, start, len)
   538             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   539                                                            len)));
   540     }
   542     /** Read signature and convert to type parameters.
   543      */
   544     List<Type> readTypeParams(int i) {
   545         int index = poolIdx[i];
   546         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   547     }
   549     /** Read class entry.
   550      */
   551     ClassSymbol readClassSymbol(int i) {
   552         return (ClassSymbol) (readPool(i));
   553     }
   555     /** Read name.
   556      */
   557     Name readName(int i) {
   558         return (Name) (readPool(i));
   559     }
   561 /************************************************************************
   562  * Reading Types
   563  ***********************************************************************/
   565     /** The unread portion of the currently read type is
   566      *  signature[sigp..siglimit-1].
   567      */
   568     byte[] signature;
   569     int sigp;
   570     int siglimit;
   571     boolean sigEnterPhase = false;
   573     /** Convert signature to type, where signature is a byte array segment.
   574      */
   575     Type sigToType(byte[] sig, int offset, int len) {
   576         signature = sig;
   577         sigp = offset;
   578         siglimit = offset + len;
   579         return sigToType();
   580     }
   582     /** Convert signature to type, where signature is implicit.
   583      */
   584     Type sigToType() {
   585         switch ((char) signature[sigp]) {
   586         case 'T':
   587             sigp++;
   588             int start = sigp;
   589             while (signature[sigp] != ';') sigp++;
   590             sigp++;
   591             return sigEnterPhase
   592                 ? Type.noType
   593                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   594         case '+': {
   595             sigp++;
   596             Type t = sigToType();
   597             return new WildcardType(t, BoundKind.EXTENDS,
   598                                     syms.boundClass);
   599         }
   600         case '*':
   601             sigp++;
   602             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   603                                     syms.boundClass);
   604         case '-': {
   605             sigp++;
   606             Type t = sigToType();
   607             return new WildcardType(t, BoundKind.SUPER,
   608                                     syms.boundClass);
   609         }
   610         case 'B':
   611             sigp++;
   612             return syms.byteType;
   613         case 'C':
   614             sigp++;
   615             return syms.charType;
   616         case 'D':
   617             sigp++;
   618             return syms.doubleType;
   619         case 'F':
   620             sigp++;
   621             return syms.floatType;
   622         case 'I':
   623             sigp++;
   624             return syms.intType;
   625         case 'J':
   626             sigp++;
   627             return syms.longType;
   628         case 'L':
   629             {
   630                 // int oldsigp = sigp;
   631                 Type t = classSigToType();
   632                 if (sigp < siglimit && signature[sigp] == '.')
   633                     throw badClassFile("deprecated inner class signature syntax " +
   634                                        "(please recompile from source)");
   635                 /*
   636                 System.err.println(" decoded " +
   637                                    new String(signature, oldsigp, sigp-oldsigp) +
   638                                    " => " + t + " outer " + t.outer());
   639                 */
   640                 return t;
   641             }
   642         case 'S':
   643             sigp++;
   644             return syms.shortType;
   645         case 'V':
   646             sigp++;
   647             return syms.voidType;
   648         case 'Z':
   649             sigp++;
   650             return syms.booleanType;
   651         case '[':
   652             sigp++;
   653             return new ArrayType(sigToType(), syms.arrayClass);
   654         case '(':
   655             sigp++;
   656             List<Type> argtypes = sigToTypes(')');
   657             Type restype = sigToType();
   658             List<Type> thrown = List.nil();
   659             while (signature[sigp] == '^') {
   660                 sigp++;
   661                 thrown = thrown.prepend(sigToType());
   662             }
   663             return new MethodType(argtypes,
   664                                   restype,
   665                                   thrown.reverse(),
   666                                   syms.methodClass);
   667         case '<':
   668             typevars = typevars.dup(currentOwner);
   669             Type poly = new ForAll(sigToTypeParams(), sigToType());
   670             typevars = typevars.leave();
   671             return poly;
   672         default:
   673             throw badClassFile("bad.signature",
   674                                Convert.utf2string(signature, sigp, 10));
   675         }
   676     }
   678     byte[] signatureBuffer = new byte[0];
   679     int sbp = 0;
   680     /** Convert class signature to type, where signature is implicit.
   681      */
   682     Type classSigToType() {
   683         if (signature[sigp] != 'L')
   684             throw badClassFile("bad.class.signature",
   685                                Convert.utf2string(signature, sigp, 10));
   686         sigp++;
   687         Type outer = Type.noType;
   688         int startSbp = sbp;
   690         while (true) {
   691             final byte c = signature[sigp++];
   692             switch (c) {
   694             case ';': {         // end
   695                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   696                                                          startSbp,
   697                                                          sbp - startSbp));
   698                 if (outer == Type.noType)
   699                     outer = t.erasure(types);
   700                 else
   701                     outer = new ClassType(outer, List.<Type>nil(), t);
   702                 sbp = startSbp;
   703                 return outer;
   704             }
   706             case '<':           // generic arguments
   707                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   708                                                          startSbp,
   709                                                          sbp - startSbp));
   710                 outer = new ClassType(outer, sigToTypes('>'), t) {
   711                         boolean completed = false;
   712                         @Override
   713                         public Type getEnclosingType() {
   714                             if (!completed) {
   715                                 completed = true;
   716                                 tsym.complete();
   717                                 Type enclosingType = tsym.type.getEnclosingType();
   718                                 if (enclosingType != Type.noType) {
   719                                     List<Type> typeArgs =
   720                                         super.getEnclosingType().allparams();
   721                                     List<Type> typeParams =
   722                                         enclosingType.allparams();
   723                                     if (typeParams.length() != typeArgs.length()) {
   724                                         // no "rare" types
   725                                         super.setEnclosingType(types.erasure(enclosingType));
   726                                     } else {
   727                                         super.setEnclosingType(types.subst(enclosingType,
   728                                                                            typeParams,
   729                                                                            typeArgs));
   730                                     }
   731                                 } else {
   732                                     super.setEnclosingType(Type.noType);
   733                                 }
   734                             }
   735                             return super.getEnclosingType();
   736                         }
   737                         @Override
   738                         public void setEnclosingType(Type outer) {
   739                             throw new UnsupportedOperationException();
   740                         }
   741                     };
   742                 switch (signature[sigp++]) {
   743                 case ';':
   744                     if (sigp < signature.length && signature[sigp] == '.') {
   745                         // support old-style GJC signatures
   746                         // The signature produced was
   747                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   748                         // rather than say
   749                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   750                         // so we skip past ".Lfoo/Outer$"
   751                         sigp += (sbp - startSbp) + // "foo/Outer"
   752                             3;  // ".L" and "$"
   753                         signatureBuffer[sbp++] = (byte)'$';
   754                         break;
   755                     } else {
   756                         sbp = startSbp;
   757                         return outer;
   758                     }
   759                 case '.':
   760                     signatureBuffer[sbp++] = (byte)'$';
   761                     break;
   762                 default:
   763                     throw new AssertionError(signature[sigp-1]);
   764                 }
   765                 continue;
   767             case '.':
   768                 signatureBuffer[sbp++] = (byte)'$';
   769                 continue;
   770             case '/':
   771                 signatureBuffer[sbp++] = (byte)'.';
   772                 continue;
   773             default:
   774                 signatureBuffer[sbp++] = c;
   775                 continue;
   776             }
   777         }
   778     }
   780     /** Convert (implicit) signature to list of types
   781      *  until `terminator' is encountered.
   782      */
   783     List<Type> sigToTypes(char terminator) {
   784         List<Type> head = List.of(null);
   785         List<Type> tail = head;
   786         while (signature[sigp] != terminator)
   787             tail = tail.setTail(List.of(sigToType()));
   788         sigp++;
   789         return head.tail;
   790     }
   792     /** Convert signature to type parameters, where signature is a byte
   793      *  array segment.
   794      */
   795     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   796         signature = sig;
   797         sigp = offset;
   798         siglimit = offset + len;
   799         return sigToTypeParams();
   800     }
   802     /** Convert signature to type parameters, where signature is implicit.
   803      */
   804     List<Type> sigToTypeParams() {
   805         List<Type> tvars = List.nil();
   806         if (signature[sigp] == '<') {
   807             sigp++;
   808             int start = sigp;
   809             sigEnterPhase = true;
   810             while (signature[sigp] != '>')
   811                 tvars = tvars.prepend(sigToTypeParam());
   812             sigEnterPhase = false;
   813             sigp = start;
   814             while (signature[sigp] != '>')
   815                 sigToTypeParam();
   816             sigp++;
   817         }
   818         return tvars.reverse();
   819     }
   821     /** Convert (implicit) signature to type parameter.
   822      */
   823     Type sigToTypeParam() {
   824         int start = sigp;
   825         while (signature[sigp] != ':') sigp++;
   826         Name name = names.fromUtf(signature, start, sigp - start);
   827         TypeVar tvar;
   828         if (sigEnterPhase) {
   829             tvar = new TypeVar(name, currentOwner, syms.botType);
   830             typevars.enter(tvar.tsym);
   831         } else {
   832             tvar = (TypeVar)findTypeVar(name);
   833         }
   834         List<Type> bounds = List.nil();
   835         Type st = null;
   836         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   837             sigp++;
   838             st = syms.objectType;
   839         }
   840         while (signature[sigp] == ':') {
   841             sigp++;
   842             bounds = bounds.prepend(sigToType());
   843         }
   844         if (!sigEnterPhase) {
   845             types.setBounds(tvar, bounds.reverse(), st);
   846         }
   847         return tvar;
   848     }
   850     /** Find type variable with given name in `typevars' scope.
   851      */
   852     Type findTypeVar(Name name) {
   853         Scope.Entry e = typevars.lookup(name);
   854         if (e.scope != null) {
   855             return e.sym.type;
   856         } else {
   857             if (readingClassAttr) {
   858                 // While reading the class attribute, the supertypes
   859                 // might refer to a type variable from an enclosing element
   860                 // (method or class).
   861                 // If the type variable is defined in the enclosing class,
   862                 // we can actually find it in
   863                 // currentOwner.owner.type.getTypeArguments()
   864                 // However, until we have read the enclosing method attribute
   865                 // we don't know for sure if this owner is correct.  It could
   866                 // be a method and there is no way to tell before reading the
   867                 // enclosing method attribute.
   868                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   869                 missingTypeVariables = missingTypeVariables.prepend(t);
   870                 // System.err.println("Missing type var " + name);
   871                 return t;
   872             }
   873             throw badClassFile("undecl.type.var", name);
   874         }
   875     }
   877 /************************************************************************
   878  * Reading Attributes
   879  ***********************************************************************/
   881     protected enum AttributeKind { CLASS, MEMBER };
   882     protected abstract class AttributeReader {
   883         AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   884             this.name = name;
   885             this.version = version;
   886             this.kinds = kinds;
   887         }
   889         boolean accepts(AttributeKind kind) {
   890             if (kinds.contains(kind)) {
   891                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   892                     return true;
   894                 if (lintClassfile && !warnedAttrs.contains(name)) {
   895                     JavaFileObject prev = log.useSource(currentClassFile);
   896                     try {
   897                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   898                                 name, version.major, version.minor, majorVersion, minorVersion);
   899                     } finally {
   900                         log.useSource(prev);
   901                     }
   902                     warnedAttrs.add(name);
   903                 }
   904             }
   905             return false;
   906         }
   908         abstract void read(Symbol sym, int attrLen);
   910         final Name name;
   911         final ClassFile.Version version;
   912         final Set<AttributeKind> kinds;
   913     }
   915     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   916             EnumSet.of(AttributeKind.CLASS);
   917     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   918             EnumSet.of(AttributeKind.MEMBER);
   919     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   920             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   922     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   924     private void initAttributeReaders() {
   925         AttributeReader[] readers = {
   926             // v45.3 attributes
   928             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   929                 void read(Symbol sym, int attrLen) {
   930                     if (readAllOfClassFile || saveParameterNames)
   931                         ((MethodSymbol)sym).code = readCode(sym);
   932                     else
   933                         bp = bp + attrLen;
   934                 }
   935             },
   937             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   938                 void read(Symbol sym, int attrLen) {
   939                     Object v = readPool(nextChar());
   940                     // Ignore ConstantValue attribute if field not final.
   941                     if ((sym.flags() & FINAL) != 0)
   942                         ((VarSymbol) sym).setData(v);
   943                 }
   944             },
   946             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   947                 void read(Symbol sym, int attrLen) {
   948                     sym.flags_field |= DEPRECATED;
   949                 }
   950             },
   952             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   953                 void read(Symbol sym, int attrLen) {
   954                     int nexceptions = nextChar();
   955                     List<Type> thrown = List.nil();
   956                     for (int j = 0; j < nexceptions; j++)
   957                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
   958                     if (sym.type.getThrownTypes().isEmpty())
   959                         sym.type.asMethodType().thrown = thrown.reverse();
   960                 }
   961             },
   963             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
   964                 void read(Symbol sym, int attrLen) {
   965                     ClassSymbol c = (ClassSymbol) sym;
   966                     readInnerClasses(c);
   967                 }
   968             },
   970             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   971                 void read(Symbol sym, int attrLen) {
   972                     int newbp = bp + attrLen;
   973                     if (saveParameterNames) {
   974                         // Pick up parameter names from the variable table.
   975                         // Parameter names are not explicitly identified as such,
   976                         // but all parameter name entries in the LocalVariableTable
   977                         // have a start_pc of 0.  Therefore, we record the name
   978                         // indicies of all slots with a start_pc of zero in the
   979                         // parameterNameIndicies array.
   980                         // Note that this implicitly honors the JVMS spec that
   981                         // there may be more than one LocalVariableTable, and that
   982                         // there is no specified ordering for the entries.
   983                         int numEntries = nextChar();
   984                         for (int i = 0; i < numEntries; i++) {
   985                             int start_pc = nextChar();
   986                             int length = nextChar();
   987                             int nameIndex = nextChar();
   988                             int sigIndex = nextChar();
   989                             int register = nextChar();
   990                             if (start_pc == 0) {
   991                                 // ensure array large enough
   992                                 if (register >= parameterNameIndices.length) {
   993                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
   994                                     parameterNameIndices =
   995                                             Arrays.copyOf(parameterNameIndices, newSize);
   996                                 }
   997                                 parameterNameIndices[register] = nameIndex;
   998                                 haveParameterNameIndices = true;
   999                             }
  1002                     bp = newbp;
  1004             },
  1006             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1007                 void read(Symbol sym, int attrLen) {
  1008                     ClassSymbol c = (ClassSymbol) sym;
  1009                     Name n = readName(nextChar());
  1010                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1012             },
  1014             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1015                 void read(Symbol sym, int attrLen) {
  1016                     // bridge methods are visible when generics not enabled
  1017                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1018                         sym.flags_field |= SYNTHETIC;
  1020             },
  1022             // standard v49 attributes
  1024             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1025                 void read(Symbol sym, int attrLen) {
  1026                     int newbp = bp + attrLen;
  1027                     readEnclosingMethodAttr(sym);
  1028                     bp = newbp;
  1030             },
  1032             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1033                 @Override
  1034                 boolean accepts(AttributeKind kind) {
  1035                     return super.accepts(kind) && allowGenerics;
  1038                 void read(Symbol sym, int attrLen) {
  1039                     if (sym.kind == TYP) {
  1040                         ClassSymbol c = (ClassSymbol) sym;
  1041                         readingClassAttr = true;
  1042                         try {
  1043                             ClassType ct1 = (ClassType)c.type;
  1044                             Assert.check(c == currentOwner);
  1045                             ct1.typarams_field = readTypeParams(nextChar());
  1046                             ct1.supertype_field = sigToType();
  1047                             ListBuffer<Type> is = new ListBuffer<Type>();
  1048                             while (sigp != siglimit) is.append(sigToType());
  1049                             ct1.interfaces_field = is.toList();
  1050                         } finally {
  1051                             readingClassAttr = false;
  1053                     } else {
  1054                         List<Type> thrown = sym.type.getThrownTypes();
  1055                         sym.type = readType(nextChar());
  1056                         //- System.err.println(" # " + sym.type);
  1057                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1058                             sym.type.asMethodType().thrown = thrown;
  1062             },
  1064             // v49 annotation attributes
  1066             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1067                 void read(Symbol sym, int attrLen) {
  1068                     attachAnnotationDefault(sym);
  1070             },
  1072             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1073                 void read(Symbol sym, int attrLen) {
  1074                     attachAnnotations(sym);
  1076             },
  1078             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1079                 void read(Symbol sym, int attrLen) {
  1080                     attachParameterAnnotations(sym);
  1082             },
  1084             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1085                 void read(Symbol sym, int attrLen) {
  1086                     attachAnnotations(sym);
  1088             },
  1090             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1091                 void read(Symbol sym, int attrLen) {
  1092                     attachParameterAnnotations(sym);
  1094             },
  1096             // additional "legacy" v49 attributes, superceded by flags
  1098             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1099                 void read(Symbol sym, int attrLen) {
  1100                     if (allowAnnotations)
  1101                         sym.flags_field |= ANNOTATION;
  1103             },
  1105             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1106                 void read(Symbol sym, int attrLen) {
  1107                     sym.flags_field |= BRIDGE;
  1108                     if (!allowGenerics)
  1109                         sym.flags_field &= ~SYNTHETIC;
  1111             },
  1113             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1114                 void read(Symbol sym, int attrLen) {
  1115                     sym.flags_field |= ENUM;
  1117             },
  1119             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1120                 void read(Symbol sym, int attrLen) {
  1121                     if (allowVarargs)
  1122                         sym.flags_field |= VARARGS;
  1124             },
  1126             // The following attributes for a Code attribute are not currently handled
  1127             // StackMapTable
  1128             // SourceDebugExtension
  1129             // LineNumberTable
  1130             // LocalVariableTypeTable
  1131         };
  1133         for (AttributeReader r: readers)
  1134             attributeReaders.put(r.name, r);
  1137     /** Report unrecognized attribute.
  1138      */
  1139     void unrecognized(Name attrName) {
  1140         if (checkClassFile)
  1141             printCCF("ccf.unrecognized.attribute", attrName);
  1146     void readEnclosingMethodAttr(Symbol sym) {
  1147         // sym is a nested class with an "Enclosing Method" attribute
  1148         // remove sym from it's current owners scope and place it in
  1149         // the scope specified by the attribute
  1150         sym.owner.members().remove(sym);
  1151         ClassSymbol self = (ClassSymbol)sym;
  1152         ClassSymbol c = readClassSymbol(nextChar());
  1153         NameAndType nt = (NameAndType)readPool(nextChar());
  1155         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1156         if (nt != null && m == null)
  1157             throw badClassFile("bad.enclosing.method", self);
  1159         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1160         self.owner = m != null ? m : c;
  1161         if (self.name.isEmpty())
  1162             self.fullname = names.empty;
  1163         else
  1164             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1166         if (m != null) {
  1167             ((ClassType)sym.type).setEnclosingType(m.type);
  1168         } else if ((self.flags_field & STATIC) == 0) {
  1169             ((ClassType)sym.type).setEnclosingType(c.type);
  1170         } else {
  1171             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1173         enterTypevars(self);
  1174         if (!missingTypeVariables.isEmpty()) {
  1175             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1176             for (Type typevar : missingTypeVariables) {
  1177                 typeVars.append(findTypeVar(typevar.tsym.name));
  1179             foundTypeVariables = typeVars.toList();
  1180         } else {
  1181             foundTypeVariables = List.nil();
  1185     // See java.lang.Class
  1186     private Name simpleBinaryName(Name self, Name enclosing) {
  1187         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1188         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1189             throw badClassFile("bad.enclosing.method", self);
  1190         int index = 1;
  1191         while (index < simpleBinaryName.length() &&
  1192                isAsciiDigit(simpleBinaryName.charAt(index)))
  1193             index++;
  1194         return names.fromString(simpleBinaryName.substring(index));
  1197     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1198         if (nt == null)
  1199             return null;
  1201         MethodType type = nt.type.asMethodType();
  1203         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1204             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1205                 return (MethodSymbol)e.sym;
  1207         if (nt.name != names.init)
  1208             // not a constructor
  1209             return null;
  1210         if ((flags & INTERFACE) != 0)
  1211             // no enclosing instance
  1212             return null;
  1213         if (nt.type.getParameterTypes().isEmpty())
  1214             // no parameters
  1215             return null;
  1217         // A constructor of an inner class.
  1218         // Remove the first argument (the enclosing instance)
  1219         nt.type = new MethodType(nt.type.getParameterTypes().tail,
  1220                                  nt.type.getReturnType(),
  1221                                  nt.type.getThrownTypes(),
  1222                                  syms.methodClass);
  1223         // Try searching again
  1224         return findMethod(nt, scope, flags);
  1227     /** Similar to Types.isSameType but avoids completion */
  1228     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1229         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1230             .prepend(types.erasure(mt1.getReturnType()));
  1231         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1232         while (!types1.isEmpty() && !types2.isEmpty()) {
  1233             if (types1.head.tsym != types2.head.tsym)
  1234                 return false;
  1235             types1 = types1.tail;
  1236             types2 = types2.tail;
  1238         return types1.isEmpty() && types2.isEmpty();
  1241     /**
  1242      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1243      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1244      */
  1245     private static boolean isAsciiDigit(char c) {
  1246         return '0' <= c && c <= '9';
  1249     /** Read member attributes.
  1250      */
  1251     void readMemberAttrs(Symbol sym) {
  1252         readAttrs(sym, AttributeKind.MEMBER);
  1255     void readAttrs(Symbol sym, AttributeKind kind) {
  1256         char ac = nextChar();
  1257         for (int i = 0; i < ac; i++) {
  1258             Name attrName = readName(nextChar());
  1259             int attrLen = nextInt();
  1260             AttributeReader r = attributeReaders.get(attrName);
  1261             if (r != null && r.accepts(kind))
  1262                 r.read(sym, attrLen);
  1263             else  {
  1264                 unrecognized(attrName);
  1265                 bp = bp + attrLen;
  1270     private boolean readingClassAttr = false;
  1271     private List<Type> missingTypeVariables = List.nil();
  1272     private List<Type> foundTypeVariables = List.nil();
  1274     /** Read class attributes.
  1275      */
  1276     void readClassAttrs(ClassSymbol c) {
  1277         readAttrs(c, AttributeKind.CLASS);
  1280     /** Read code block.
  1281      */
  1282     Code readCode(Symbol owner) {
  1283         nextChar(); // max_stack
  1284         nextChar(); // max_locals
  1285         final int  code_length = nextInt();
  1286         bp += code_length;
  1287         final char exception_table_length = nextChar();
  1288         bp += exception_table_length * 8;
  1289         readMemberAttrs(owner);
  1290         return null;
  1293 /************************************************************************
  1294  * Reading Java-language annotations
  1295  ***********************************************************************/
  1297     /** Attach annotations.
  1298      */
  1299     void attachAnnotations(final Symbol sym) {
  1300         int numAttributes = nextChar();
  1301         if (numAttributes != 0) {
  1302             ListBuffer<CompoundAnnotationProxy> proxies =
  1303                 new ListBuffer<CompoundAnnotationProxy>();
  1304             for (int i = 0; i<numAttributes; i++) {
  1305                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1306                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1307                     sym.flags_field |= PROPRIETARY;
  1308                 else
  1309                     proxies.append(proxy);
  1310                 if (majorVersion >= V51.major && proxy.type.tsym == syms.polymorphicSignatureType.tsym) {
  1311                     sym.flags_field |= POLYMORPHIC_SIGNATURE;
  1314             annotate.later(new AnnotationCompleter(sym, proxies.toList()));
  1318     /** Attach parameter annotations.
  1319      */
  1320     void attachParameterAnnotations(final Symbol method) {
  1321         final MethodSymbol meth = (MethodSymbol)method;
  1322         int numParameters = buf[bp++] & 0xFF;
  1323         List<VarSymbol> parameters = meth.params();
  1324         int pnum = 0;
  1325         while (parameters.tail != null) {
  1326             attachAnnotations(parameters.head);
  1327             parameters = parameters.tail;
  1328             pnum++;
  1330         if (pnum != numParameters) {
  1331             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1335     /** Attach the default value for an annotation element.
  1336      */
  1337     void attachAnnotationDefault(final Symbol sym) {
  1338         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1339         final Attribute value = readAttributeValue();
  1340         annotate.later(new AnnotationDefaultCompleter(meth, value));
  1343     Type readTypeOrClassSymbol(int i) {
  1344         // support preliminary jsr175-format class files
  1345         if (buf[poolIdx[i]] == CONSTANT_Class)
  1346             return readClassSymbol(i).type;
  1347         return readType(i);
  1349     Type readEnumType(int i) {
  1350         // support preliminary jsr175-format class files
  1351         int index = poolIdx[i];
  1352         int length = getChar(index + 1);
  1353         if (buf[index + length + 2] != ';')
  1354             return enterClass(readName(i)).type;
  1355         return readType(i);
  1358     CompoundAnnotationProxy readCompoundAnnotation() {
  1359         Type t = readTypeOrClassSymbol(nextChar());
  1360         int numFields = nextChar();
  1361         ListBuffer<Pair<Name,Attribute>> pairs =
  1362             new ListBuffer<Pair<Name,Attribute>>();
  1363         for (int i=0; i<numFields; i++) {
  1364             Name name = readName(nextChar());
  1365             Attribute value = readAttributeValue();
  1366             pairs.append(new Pair<Name,Attribute>(name, value));
  1368         return new CompoundAnnotationProxy(t, pairs.toList());
  1371     Attribute readAttributeValue() {
  1372         char c = (char) buf[bp++];
  1373         switch (c) {
  1374         case 'B':
  1375             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1376         case 'C':
  1377             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1378         case 'D':
  1379             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1380         case 'F':
  1381             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1382         case 'I':
  1383             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1384         case 'J':
  1385             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1386         case 'S':
  1387             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1388         case 'Z':
  1389             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1390         case 's':
  1391             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1392         case 'e':
  1393             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1394         case 'c':
  1395             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1396         case '[': {
  1397             int n = nextChar();
  1398             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1399             for (int i=0; i<n; i++)
  1400                 l.append(readAttributeValue());
  1401             return new ArrayAttributeProxy(l.toList());
  1403         case '@':
  1404             return readCompoundAnnotation();
  1405         default:
  1406             throw new AssertionError("unknown annotation tag '" + c + "'");
  1410     interface ProxyVisitor extends Attribute.Visitor {
  1411         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1412         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1413         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1416     static class EnumAttributeProxy extends Attribute {
  1417         Type enumType;
  1418         Name enumerator;
  1419         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1420             super(null);
  1421             this.enumType = enumType;
  1422             this.enumerator = enumerator;
  1424         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1425         @Override
  1426         public String toString() {
  1427             return "/*proxy enum*/" + enumType + "." + enumerator;
  1431     static class ArrayAttributeProxy extends Attribute {
  1432         List<Attribute> values;
  1433         ArrayAttributeProxy(List<Attribute> values) {
  1434             super(null);
  1435             this.values = values;
  1437         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1438         @Override
  1439         public String toString() {
  1440             return "{" + values + "}";
  1444     /** A temporary proxy representing a compound attribute.
  1445      */
  1446     static class CompoundAnnotationProxy extends Attribute {
  1447         final List<Pair<Name,Attribute>> values;
  1448         public CompoundAnnotationProxy(Type type,
  1449                                       List<Pair<Name,Attribute>> values) {
  1450             super(type);
  1451             this.values = values;
  1453         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1454         @Override
  1455         public String toString() {
  1456             StringBuilder buf = new StringBuilder();
  1457             buf.append("@");
  1458             buf.append(type.tsym.getQualifiedName());
  1459             buf.append("/*proxy*/{");
  1460             boolean first = true;
  1461             for (List<Pair<Name,Attribute>> v = values;
  1462                  v.nonEmpty(); v = v.tail) {
  1463                 Pair<Name,Attribute> value = v.head;
  1464                 if (!first) buf.append(",");
  1465                 first = false;
  1466                 buf.append(value.fst);
  1467                 buf.append("=");
  1468                 buf.append(value.snd);
  1470             buf.append("}");
  1471             return buf.toString();
  1475     /** A temporary proxy representing a type annotation.
  1476      */
  1477     static class TypeAnnotationProxy {
  1478         final CompoundAnnotationProxy compound;
  1479         final TypeAnnotationPosition position;
  1480         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1481                 TypeAnnotationPosition position) {
  1482             this.compound = compound;
  1483             this.position = position;
  1487     class AnnotationDeproxy implements ProxyVisitor {
  1488         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1489             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1491         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1492             // also must fill in types!!!!
  1493             ListBuffer<Attribute.Compound> buf =
  1494                 new ListBuffer<Attribute.Compound>();
  1495             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1496                 buf.append(deproxyCompound(l.head));
  1498             return buf.toList();
  1501         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1502             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1503                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1504             for (List<Pair<Name,Attribute>> l = a.values;
  1505                  l.nonEmpty();
  1506                  l = l.tail) {
  1507                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1508                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1509                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1511             return new Attribute.Compound(a.type, buf.toList());
  1514         MethodSymbol findAccessMethod(Type container, Name name) {
  1515             CompletionFailure failure = null;
  1516             try {
  1517                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1518                      e.scope != null;
  1519                      e = e.next()) {
  1520                     Symbol sym = e.sym;
  1521                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1522                         return (MethodSymbol) sym;
  1524             } catch (CompletionFailure ex) {
  1525                 failure = ex;
  1527             // The method wasn't found: emit a warning and recover
  1528             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1529             try {
  1530                 if (failure == null) {
  1531                     log.warning("annotation.method.not.found",
  1532                                 container,
  1533                                 name);
  1534                 } else {
  1535                     log.warning("annotation.method.not.found.reason",
  1536                                 container,
  1537                                 name,
  1538                                 failure.getDetailValue());//diagnostic, if present
  1540             } finally {
  1541                 log.useSource(prevSource);
  1543             // Construct a new method type and symbol.  Use bottom
  1544             // type (typeof null) as return type because this type is
  1545             // a subtype of all reference types and can be converted
  1546             // to primitive types by unboxing.
  1547             MethodType mt = new MethodType(List.<Type>nil(),
  1548                                            syms.botType,
  1549                                            List.<Type>nil(),
  1550                                            syms.methodClass);
  1551             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1554         Attribute result;
  1555         Type type;
  1556         Attribute deproxy(Type t, Attribute a) {
  1557             Type oldType = type;
  1558             try {
  1559                 type = t;
  1560                 a.accept(this);
  1561                 return result;
  1562             } finally {
  1563                 type = oldType;
  1567         // implement Attribute.Visitor below
  1569         public void visitConstant(Attribute.Constant value) {
  1570             // assert value.type == type;
  1571             result = value;
  1574         public void visitClass(Attribute.Class clazz) {
  1575             result = clazz;
  1578         public void visitEnum(Attribute.Enum e) {
  1579             throw new AssertionError(); // shouldn't happen
  1582         public void visitCompound(Attribute.Compound compound) {
  1583             throw new AssertionError(); // shouldn't happen
  1586         public void visitArray(Attribute.Array array) {
  1587             throw new AssertionError(); // shouldn't happen
  1590         public void visitError(Attribute.Error e) {
  1591             throw new AssertionError(); // shouldn't happen
  1594         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1595             // type.tsym.flatName() should == proxy.enumFlatName
  1596             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1597             VarSymbol enumerator = null;
  1598             for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1599                  e.scope != null;
  1600                  e = e.next()) {
  1601                 if (e.sym.kind == VAR) {
  1602                     enumerator = (VarSymbol)e.sym;
  1603                     break;
  1606             if (enumerator == null) {
  1607                 log.error("unknown.enum.constant",
  1608                           currentClassFile, enumTypeSym, proxy.enumerator);
  1609                 result = new Attribute.Error(enumTypeSym.type);
  1610             } else {
  1611                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1615         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1616             int length = proxy.values.length();
  1617             Attribute[] ats = new Attribute[length];
  1618             Type elemtype = types.elemtype(type);
  1619             int i = 0;
  1620             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1621                 ats[i++] = deproxy(elemtype, p.head);
  1623             result = new Attribute.Array(type, ats);
  1626         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1627             result = deproxyCompound(proxy);
  1631     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1632         final MethodSymbol sym;
  1633         final Attribute value;
  1634         final JavaFileObject classFile = currentClassFile;
  1635         @Override
  1636         public String toString() {
  1637             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1639         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1640             this.sym = sym;
  1641             this.value = value;
  1643         // implement Annotate.Annotator.enterAnnotation()
  1644         public void enterAnnotation() {
  1645             JavaFileObject previousClassFile = currentClassFile;
  1646             try {
  1647                 currentClassFile = classFile;
  1648                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1649             } finally {
  1650                 currentClassFile = previousClassFile;
  1655     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1656         final Symbol sym;
  1657         final List<CompoundAnnotationProxy> l;
  1658         final JavaFileObject classFile;
  1659         @Override
  1660         public String toString() {
  1661             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1663         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1664             this.sym = sym;
  1665             this.l = l;
  1666             this.classFile = currentClassFile;
  1668         // implement Annotate.Annotator.enterAnnotation()
  1669         public void enterAnnotation() {
  1670             JavaFileObject previousClassFile = currentClassFile;
  1671             try {
  1672                 currentClassFile = classFile;
  1673                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1674                 sym.attributes_field = ((sym.attributes_field == null)
  1675                                         ? newList
  1676                                         : newList.prependList(sym.attributes_field));
  1677             } finally {
  1678                 currentClassFile = previousClassFile;
  1684 /************************************************************************
  1685  * Reading Symbols
  1686  ***********************************************************************/
  1688     /** Read a field.
  1689      */
  1690     VarSymbol readField() {
  1691         long flags = adjustFieldFlags(nextChar());
  1692         Name name = readName(nextChar());
  1693         Type type = readType(nextChar());
  1694         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1695         readMemberAttrs(v);
  1696         return v;
  1699     /** Read a method.
  1700      */
  1701     MethodSymbol readMethod() {
  1702         long flags = adjustMethodFlags(nextChar());
  1703         Name name = readName(nextChar());
  1704         Type type = readType(nextChar());
  1705         if (name == names.init && currentOwner.hasOuterInstance()) {
  1706             // Sometimes anonymous classes don't have an outer
  1707             // instance, however, there is no reliable way to tell so
  1708             // we never strip this$n
  1709             if (!currentOwner.name.isEmpty())
  1710                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  1711                                       type.getReturnType(),
  1712                                       type.getThrownTypes(),
  1713                                       syms.methodClass);
  1715         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  1716         if (saveParameterNames)
  1717             initParameterNames(m);
  1718         Symbol prevOwner = currentOwner;
  1719         currentOwner = m;
  1720         try {
  1721             readMemberAttrs(m);
  1722         } finally {
  1723             currentOwner = prevOwner;
  1725         if (saveParameterNames)
  1726             setParameterNames(m, type);
  1727         return m;
  1730     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  1731         boolean isVarargs = (flags & VARARGS) != 0;
  1732         if (isVarargs) {
  1733             Type varargsElem = args.last();
  1734             ListBuffer<Type> adjustedArgs = ListBuffer.lb();
  1735             for (Type t : args) {
  1736                 adjustedArgs.append(t != varargsElem ?
  1737                     t :
  1738                     ((ArrayType)t).makeVarargs());
  1740             args = adjustedArgs.toList();
  1742         return args.tail;
  1745     /**
  1746      * Init the parameter names array.
  1747      * Parameter names are currently inferred from the names in the
  1748      * LocalVariableTable attributes of a Code attribute.
  1749      * (Note: this means parameter names are currently not available for
  1750      * methods without a Code attribute.)
  1751      * This method initializes an array in which to store the name indexes
  1752      * of parameter names found in LocalVariableTable attributes. It is
  1753      * slightly supersized to allow for additional slots with a start_pc of 0.
  1754      */
  1755     void initParameterNames(MethodSymbol sym) {
  1756         // make allowance for synthetic parameters.
  1757         final int excessSlots = 4;
  1758         int expectedParameterSlots =
  1759                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  1760         if (parameterNameIndices == null
  1761                 || parameterNameIndices.length < expectedParameterSlots) {
  1762             parameterNameIndices = new int[expectedParameterSlots];
  1763         } else
  1764             Arrays.fill(parameterNameIndices, 0);
  1765         haveParameterNameIndices = false;
  1768     /**
  1769      * Set the parameter names for a symbol from the name index in the
  1770      * parameterNameIndicies array. The type of the symbol may have changed
  1771      * while reading the method attributes (see the Signature attribute).
  1772      * This may be because of generic information or because anonymous
  1773      * synthetic parameters were added.   The original type (as read from
  1774      * the method descriptor) is used to help guess the existence of
  1775      * anonymous synthetic parameters.
  1776      * On completion, sym.savedParameter names will either be null (if
  1777      * no parameter names were found in the class file) or will be set to a
  1778      * list of names, one per entry in sym.type.getParameterTypes, with
  1779      * any missing names represented by the empty name.
  1780      */
  1781     void setParameterNames(MethodSymbol sym, Type jvmType) {
  1782         // if no names were found in the class file, there's nothing more to do
  1783         if (!haveParameterNameIndices)
  1784             return;
  1786         int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  1787         // the code in readMethod may have skipped the first parameter when
  1788         // setting up the MethodType. If so, we make a corresponding allowance
  1789         // here for the position of the first parameter.  Note that this
  1790         // assumes the skipped parameter has a width of 1 -- i.e. it is not
  1791         // a double width type (long or double.)
  1792         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  1793             // Sometimes anonymous classes don't have an outer
  1794             // instance, however, there is no reliable way to tell so
  1795             // we never strip this$n
  1796             if (!currentOwner.name.isEmpty())
  1797                 firstParam += 1;
  1800         if (sym.type != jvmType) {
  1801             // reading the method attributes has caused the symbol's type to
  1802             // be changed. (i.e. the Signature attribute.)  This may happen if
  1803             // there are hidden (synthetic) parameters in the descriptor, but
  1804             // not in the Signature.  The position of these hidden parameters
  1805             // is unspecified; for now, assume they are at the beginning, and
  1806             // so skip over them. The primary case for this is two hidden
  1807             // parameters passed into Enum constructors.
  1808             int skip = Code.width(jvmType.getParameterTypes())
  1809                     - Code.width(sym.type.getParameterTypes());
  1810             firstParam += skip;
  1812         List<Name> paramNames = List.nil();
  1813         int index = firstParam;
  1814         for (Type t: sym.type.getParameterTypes()) {
  1815             int nameIdx = (index < parameterNameIndices.length
  1816                     ? parameterNameIndices[index] : 0);
  1817             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  1818             paramNames = paramNames.prepend(name);
  1819             index += Code.width(t);
  1821         sym.savedParameterNames = paramNames.reverse();
  1824     /** Skip a field or method
  1825      */
  1826     void skipMember() {
  1827         bp = bp + 6;
  1828         char ac = nextChar();
  1829         for (int i = 0; i < ac; i++) {
  1830             bp = bp + 2;
  1831             int attrLen = nextInt();
  1832             bp = bp + attrLen;
  1836     /** Enter type variables of this classtype and all enclosing ones in
  1837      *  `typevars'.
  1838      */
  1839     protected void enterTypevars(Type t) {
  1840         if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
  1841             enterTypevars(t.getEnclosingType());
  1842         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  1843             typevars.enter(xs.head.tsym);
  1846     protected void enterTypevars(Symbol sym) {
  1847         if (sym.owner.kind == MTH) {
  1848             enterTypevars(sym.owner);
  1849             enterTypevars(sym.owner.owner);
  1851         enterTypevars(sym.type);
  1854     /** Read contents of a given class symbol `c'. Both external and internal
  1855      *  versions of an inner class are read.
  1856      */
  1857     void readClass(ClassSymbol c) {
  1858         ClassType ct = (ClassType)c.type;
  1860         // allocate scope for members
  1861         c.members_field = new Scope.ClassScope(c, scopeCounter);
  1863         // prepare type variable table
  1864         typevars = typevars.dup(currentOwner);
  1865         if (ct.getEnclosingType().tag == CLASS)
  1866             enterTypevars(ct.getEnclosingType());
  1868         // read flags, or skip if this is an inner class
  1869         long flags = adjustClassFlags(nextChar());
  1870         if (c.owner.kind == PCK) c.flags_field = flags;
  1872         // read own class name and check that it matches
  1873         ClassSymbol self = readClassSymbol(nextChar());
  1874         if (c != self)
  1875             throw badClassFile("class.file.wrong.class",
  1876                                self.flatname);
  1878         // class attributes must be read before class
  1879         // skip ahead to read class attributes
  1880         int startbp = bp;
  1881         nextChar();
  1882         char interfaceCount = nextChar();
  1883         bp += interfaceCount * 2;
  1884         char fieldCount = nextChar();
  1885         for (int i = 0; i < fieldCount; i++) skipMember();
  1886         char methodCount = nextChar();
  1887         for (int i = 0; i < methodCount; i++) skipMember();
  1888         readClassAttrs(c);
  1890         if (readAllOfClassFile) {
  1891             for (int i = 1; i < poolObj.length; i++) readPool(i);
  1892             c.pool = new Pool(poolObj.length, poolObj);
  1895         // reset and read rest of classinfo
  1896         bp = startbp;
  1897         int n = nextChar();
  1898         if (ct.supertype_field == null)
  1899             ct.supertype_field = (n == 0)
  1900                 ? Type.noType
  1901                 : readClassSymbol(n).erasure(types);
  1902         n = nextChar();
  1903         List<Type> is = List.nil();
  1904         for (int i = 0; i < n; i++) {
  1905             Type _inter = readClassSymbol(nextChar()).erasure(types);
  1906             is = is.prepend(_inter);
  1908         if (ct.interfaces_field == null)
  1909             ct.interfaces_field = is.reverse();
  1911         Assert.check(fieldCount == nextChar());
  1912         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  1913         Assert.check(methodCount == nextChar());
  1914         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  1916         typevars = typevars.leave();
  1919     /** Read inner class info. For each inner/outer pair allocate a
  1920      *  member class.
  1921      */
  1922     void readInnerClasses(ClassSymbol c) {
  1923         int n = nextChar();
  1924         for (int i = 0; i < n; i++) {
  1925             nextChar(); // skip inner class symbol
  1926             ClassSymbol outer = readClassSymbol(nextChar());
  1927             Name name = readName(nextChar());
  1928             if (name == null) name = names.empty;
  1929             long flags = adjustClassFlags(nextChar());
  1930             if (outer != null) { // we have a member class
  1931                 if (name == names.empty)
  1932                     name = names.one;
  1933                 ClassSymbol member = enterClass(name, outer);
  1934                 if ((flags & STATIC) == 0) {
  1935                     ((ClassType)member.type).setEnclosingType(outer.type);
  1936                     if (member.erasure_field != null)
  1937                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  1939                 if (c == outer) {
  1940                     member.flags_field = flags;
  1941                     enterMember(c, member);
  1947     /** Read a class file.
  1948      */
  1949     private void readClassFile(ClassSymbol c) throws IOException {
  1950         int magic = nextInt();
  1951         if (magic != JAVA_MAGIC)
  1952             throw badClassFile("illegal.start.of.class.file");
  1954         minorVersion = nextChar();
  1955         majorVersion = nextChar();
  1956         int maxMajor = Target.MAX().majorVersion;
  1957         int maxMinor = Target.MAX().minorVersion;
  1958         if (majorVersion > maxMajor ||
  1959             majorVersion * 1000 + minorVersion <
  1960             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  1962             if (majorVersion == (maxMajor + 1))
  1963                 log.warning("big.major.version",
  1964                             currentClassFile,
  1965                             majorVersion,
  1966                             maxMajor);
  1967             else
  1968                 throw badClassFile("wrong.version",
  1969                                    Integer.toString(majorVersion),
  1970                                    Integer.toString(minorVersion),
  1971                                    Integer.toString(maxMajor),
  1972                                    Integer.toString(maxMinor));
  1974         else if (checkClassFile &&
  1975                  majorVersion == maxMajor &&
  1976                  minorVersion > maxMinor)
  1978             printCCF("found.later.version",
  1979                      Integer.toString(minorVersion));
  1981         indexPool();
  1982         if (signatureBuffer.length < bp) {
  1983             int ns = Integer.highestOneBit(bp) << 1;
  1984             signatureBuffer = new byte[ns];
  1986         readClass(c);
  1989 /************************************************************************
  1990  * Adjusting flags
  1991  ***********************************************************************/
  1993     long adjustFieldFlags(long flags) {
  1994         return flags;
  1996     long adjustMethodFlags(long flags) {
  1997         if ((flags & ACC_BRIDGE) != 0) {
  1998             flags &= ~ACC_BRIDGE;
  1999             flags |= BRIDGE;
  2000             if (!allowGenerics)
  2001                 flags &= ~SYNTHETIC;
  2003         if ((flags & ACC_VARARGS) != 0) {
  2004             flags &= ~ACC_VARARGS;
  2005             flags |= VARARGS;
  2007         return flags;
  2009     long adjustClassFlags(long flags) {
  2010         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2013 /************************************************************************
  2014  * Loading Classes
  2015  ***********************************************************************/
  2017     /** Define a new class given its name and owner.
  2018      */
  2019     public ClassSymbol defineClass(Name name, Symbol owner) {
  2020         ClassSymbol c = new ClassSymbol(0, name, owner);
  2021         if (owner.kind == PCK)
  2022             Assert.checkNull(classes.get(c.flatname), c);
  2023         c.completer = this;
  2024         return c;
  2027     /** Create a new toplevel or member class symbol with given name
  2028      *  and owner and enter in `classes' unless already there.
  2029      */
  2030     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2031         Name flatname = TypeSymbol.formFlatName(name, owner);
  2032         ClassSymbol c = classes.get(flatname);
  2033         if (c == null) {
  2034             c = defineClass(name, owner);
  2035             classes.put(flatname, c);
  2036         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2037             // reassign fields of classes that might have been loaded with
  2038             // their flat names.
  2039             c.owner.members().remove(c);
  2040             c.name = name;
  2041             c.owner = owner;
  2042             c.fullname = ClassSymbol.formFullName(name, owner);
  2044         return c;
  2047     /**
  2048      * Creates a new toplevel class symbol with given flat name and
  2049      * given class (or source) file.
  2051      * @param flatName a fully qualified binary class name
  2052      * @param classFile the class file or compilation unit defining
  2053      * the class (may be {@code null})
  2054      * @return a newly created class symbol
  2055      * @throws AssertionError if the class symbol already exists
  2056      */
  2057     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2058         ClassSymbol cs = classes.get(flatName);
  2059         if (cs != null) {
  2060             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2061                                     cs.fullname,
  2062                                     cs.completer,
  2063                                     cs.classfile,
  2064                                     cs.sourcefile);
  2065             throw new AssertionError(msg);
  2067         Name packageName = Convert.packagePart(flatName);
  2068         PackageSymbol owner = packageName.isEmpty()
  2069                                 ? syms.unnamedPackage
  2070                                 : enterPackage(packageName);
  2071         cs = defineClass(Convert.shortName(flatName), owner);
  2072         cs.classfile = classFile;
  2073         classes.put(flatName, cs);
  2074         return cs;
  2077     /** Create a new member or toplevel class symbol with given flat name
  2078      *  and enter in `classes' unless already there.
  2079      */
  2080     public ClassSymbol enterClass(Name flatname) {
  2081         ClassSymbol c = classes.get(flatname);
  2082         if (c == null)
  2083             return enterClass(flatname, (JavaFileObject)null);
  2084         else
  2085             return c;
  2088     private boolean suppressFlush = false;
  2090     /** Completion for classes to be loaded. Before a class is loaded
  2091      *  we make sure its enclosing class (if any) is loaded.
  2092      */
  2093     public void complete(Symbol sym) throws CompletionFailure {
  2094         if (sym.kind == TYP) {
  2095             ClassSymbol c = (ClassSymbol)sym;
  2096             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2097             boolean saveSuppressFlush = suppressFlush;
  2098             suppressFlush = true;
  2099             try {
  2100                 completeOwners(c.owner);
  2101                 completeEnclosing(c);
  2102             } finally {
  2103                 suppressFlush = saveSuppressFlush;
  2105             fillIn(c);
  2106         } else if (sym.kind == PCK) {
  2107             PackageSymbol p = (PackageSymbol)sym;
  2108             try {
  2109                 fillIn(p);
  2110             } catch (IOException ex) {
  2111                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2114         if (!filling && !suppressFlush)
  2115             annotate.flush(); // finish attaching annotations
  2118     /** complete up through the enclosing package. */
  2119     private void completeOwners(Symbol o) {
  2120         if (o.kind != PCK) completeOwners(o.owner);
  2121         o.complete();
  2124     /**
  2125      * Tries to complete lexically enclosing classes if c looks like a
  2126      * nested class.  This is similar to completeOwners but handles
  2127      * the situation when a nested class is accessed directly as it is
  2128      * possible with the Tree API or javax.lang.model.*.
  2129      */
  2130     private void completeEnclosing(ClassSymbol c) {
  2131         if (c.owner.kind == PCK) {
  2132             Symbol owner = c.owner;
  2133             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2134                 Symbol encl = owner.members().lookup(name).sym;
  2135                 if (encl == null)
  2136                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2137                 if (encl != null)
  2138                     encl.complete();
  2143     /** We can only read a single class file at a time; this
  2144      *  flag keeps track of when we are currently reading a class
  2145      *  file.
  2146      */
  2147     private boolean filling = false;
  2149     /** Fill in definition of class `c' from corresponding class or
  2150      *  source file.
  2151      */
  2152     private void fillIn(ClassSymbol c) {
  2153         if (completionFailureName == c.fullname) {
  2154             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2156         currentOwner = c;
  2157         warnedAttrs.clear();
  2158         JavaFileObject classfile = c.classfile;
  2159         if (classfile != null) {
  2160             JavaFileObject previousClassFile = currentClassFile;
  2161             try {
  2162                 if (filling) {
  2163                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2165                 currentClassFile = classfile;
  2166                 if (verbose) {
  2167                     printVerbose("loading", currentClassFile.toString());
  2169                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2170                     filling = true;
  2171                     try {
  2172                         bp = 0;
  2173                         buf = readInputStream(buf, classfile.openInputStream());
  2174                         readClassFile(c);
  2175                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2176                             List<Type> missing = missingTypeVariables;
  2177                             List<Type> found = foundTypeVariables;
  2178                             missingTypeVariables = List.nil();
  2179                             foundTypeVariables = List.nil();
  2180                             filling = false;
  2181                             ClassType ct = (ClassType)currentOwner.type;
  2182                             ct.supertype_field =
  2183                                 types.subst(ct.supertype_field, missing, found);
  2184                             ct.interfaces_field =
  2185                                 types.subst(ct.interfaces_field, missing, found);
  2186                         } else if (missingTypeVariables.isEmpty() !=
  2187                                    foundTypeVariables.isEmpty()) {
  2188                             Name name = missingTypeVariables.head.tsym.name;
  2189                             throw badClassFile("undecl.type.var", name);
  2191                     } finally {
  2192                         missingTypeVariables = List.nil();
  2193                         foundTypeVariables = List.nil();
  2194                         filling = false;
  2196                 } else {
  2197                     if (sourceCompleter != null) {
  2198                         sourceCompleter.complete(c);
  2199                     } else {
  2200                         throw new IllegalStateException("Source completer required to read "
  2201                                                         + classfile.toUri());
  2204                 return;
  2205             } catch (IOException ex) {
  2206                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2207             } finally {
  2208                 currentClassFile = previousClassFile;
  2210         } else {
  2211             JCDiagnostic diag =
  2212                 diagFactory.fragment("class.file.not.found", c.flatname);
  2213             throw
  2214                 newCompletionFailure(c, diag);
  2217     // where
  2218         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2219             try {
  2220                 buf = ensureCapacity(buf, s.available());
  2221                 int r = s.read(buf);
  2222                 int bp = 0;
  2223                 while (r != -1) {
  2224                     bp += r;
  2225                     buf = ensureCapacity(buf, bp);
  2226                     r = s.read(buf, bp, buf.length - bp);
  2228                 return buf;
  2229             } finally {
  2230                 try {
  2231                     s.close();
  2232                 } catch (IOException e) {
  2233                     /* Ignore any errors, as this stream may have already
  2234                      * thrown a related exception which is the one that
  2235                      * should be reported.
  2236                      */
  2240         /*
  2241          * ensureCapacity will increase the buffer as needed, taking note that
  2242          * the new buffer will always be greater than the needed and never
  2243          * exactly equal to the needed size or bp. If equal then the read (above)
  2244          * will infinitely loop as buf.length - bp == 0.
  2245          */
  2246         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2247             if (buf.length <= needed) {
  2248                 byte[] old = buf;
  2249                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2250                 System.arraycopy(old, 0, buf, 0, old.length);
  2252             return buf;
  2254         /** Static factory for CompletionFailure objects.
  2255          *  In practice, only one can be used at a time, so we share one
  2256          *  to reduce the expense of allocating new exception objects.
  2257          */
  2258         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2259                                                        JCDiagnostic diag) {
  2260             if (!cacheCompletionFailure) {
  2261                 // log.warning("proc.messager",
  2262                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2263                 // c.debug.printStackTrace();
  2264                 return new CompletionFailure(c, diag);
  2265             } else {
  2266                 CompletionFailure result = cachedCompletionFailure;
  2267                 result.sym = c;
  2268                 result.diag = diag;
  2269                 return result;
  2272         private CompletionFailure cachedCompletionFailure =
  2273             new CompletionFailure(null, (JCDiagnostic) null);
  2275             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2278     /** Load a toplevel class with given fully qualified name
  2279      *  The class is entered into `classes' only if load was successful.
  2280      */
  2281     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2282         boolean absent = classes.get(flatname) == null;
  2283         ClassSymbol c = enterClass(flatname);
  2284         if (c.members_field == null && c.completer != null) {
  2285             try {
  2286                 c.complete();
  2287             } catch (CompletionFailure ex) {
  2288                 if (absent) classes.remove(flatname);
  2289                 throw ex;
  2292         return c;
  2295 /************************************************************************
  2296  * Loading Packages
  2297  ***********************************************************************/
  2299     /** Check to see if a package exists, given its fully qualified name.
  2300      */
  2301     public boolean packageExists(Name fullname) {
  2302         return enterPackage(fullname).exists();
  2305     /** Make a package, given its fully qualified name.
  2306      */
  2307     public PackageSymbol enterPackage(Name fullname) {
  2308         PackageSymbol p = packages.get(fullname);
  2309         if (p == null) {
  2310             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2311             p = new PackageSymbol(
  2312                 Convert.shortName(fullname),
  2313                 enterPackage(Convert.packagePart(fullname)));
  2314             p.completer = this;
  2315             packages.put(fullname, p);
  2317         return p;
  2320     /** Make a package, given its unqualified name and enclosing package.
  2321      */
  2322     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2323         return enterPackage(TypeSymbol.formFullName(name, owner));
  2326     /** Include class corresponding to given class file in package,
  2327      *  unless (1) we already have one the same kind (.class or .java), or
  2328      *         (2) we have one of the other kind, and the given class file
  2329      *             is older.
  2330      */
  2331     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2332         if ((p.flags_field & EXISTS) == 0)
  2333             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2334                 q.flags_field |= EXISTS;
  2335         JavaFileObject.Kind kind = file.getKind();
  2336         int seen;
  2337         if (kind == JavaFileObject.Kind.CLASS)
  2338             seen = CLASS_SEEN;
  2339         else
  2340             seen = SOURCE_SEEN;
  2341         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2342         int lastDot = binaryName.lastIndexOf(".");
  2343         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2344         boolean isPkgInfo = classname == names.package_info;
  2345         ClassSymbol c = isPkgInfo
  2346             ? p.package_info
  2347             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2348         if (c == null) {
  2349             c = enterClass(classname, p);
  2350             if (c.classfile == null) // only update the file if's it's newly created
  2351                 c.classfile = file;
  2352             if (isPkgInfo) {
  2353                 p.package_info = c;
  2354             } else {
  2355                 if (c.owner == p)  // it might be an inner class
  2356                     p.members_field.enter(c);
  2358         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2359             // if c.classfile == null, we are currently compiling this class
  2360             // and no further action is necessary.
  2361             // if (c.flags_field & seen) != 0, we have already encountered
  2362             // a file of the same kind; again no further action is necessary.
  2363             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2364                 c.classfile = preferredFileObject(file, c.classfile);
  2366         c.flags_field |= seen;
  2369     /** Implement policy to choose to derive information from a source
  2370      *  file or a class file when both are present.  May be overridden
  2371      *  by subclasses.
  2372      */
  2373     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2374                                            JavaFileObject b) {
  2376         if (preferSource)
  2377             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2378         else {
  2379             long adate = a.getLastModified();
  2380             long bdate = b.getLastModified();
  2381             // 6449326: policy for bad lastModifiedTime in ClassReader
  2382             //assert adate >= 0 && bdate >= 0;
  2383             return (adate > bdate) ? a : b;
  2387     /**
  2388      * specifies types of files to be read when filling in a package symbol
  2389      */
  2390     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2391         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2394     /**
  2395      * this is used to support javadoc
  2396      */
  2397     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2400     protected Location currentLoc; // FIXME
  2402     private boolean verbosePath = true;
  2404     /** Load directory of package into members scope.
  2405      */
  2406     private void fillIn(PackageSymbol p) throws IOException {
  2407         if (p.members_field == null) p.members_field = new Scope(p);
  2408         String packageName = p.fullname.toString();
  2410         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2412         fillIn(p, PLATFORM_CLASS_PATH,
  2413                fileManager.list(PLATFORM_CLASS_PATH,
  2414                                 packageName,
  2415                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2416                                 false));
  2418         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2419         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2420         boolean wantClassFiles = !classKinds.isEmpty();
  2422         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2423         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2424         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2426         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2428         if (verbose && verbosePath) {
  2429             if (fileManager instanceof StandardJavaFileManager) {
  2430                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2431                 if (haveSourcePath && wantSourceFiles) {
  2432                     List<File> path = List.nil();
  2433                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2434                         path = path.prepend(file);
  2436                     printVerbose("sourcepath", path.reverse().toString());
  2437                 } else if (wantSourceFiles) {
  2438                     List<File> path = List.nil();
  2439                     for (File file : fm.getLocation(CLASS_PATH)) {
  2440                         path = path.prepend(file);
  2442                     printVerbose("sourcepath", path.reverse().toString());
  2444                 if (wantClassFiles) {
  2445                     List<File> path = List.nil();
  2446                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2447                         path = path.prepend(file);
  2449                     for (File file : fm.getLocation(CLASS_PATH)) {
  2450                         path = path.prepend(file);
  2452                     printVerbose("classpath",  path.reverse().toString());
  2457         if (wantSourceFiles && !haveSourcePath) {
  2458             fillIn(p, CLASS_PATH,
  2459                    fileManager.list(CLASS_PATH,
  2460                                     packageName,
  2461                                     kinds,
  2462                                     false));
  2463         } else {
  2464             if (wantClassFiles)
  2465                 fillIn(p, CLASS_PATH,
  2466                        fileManager.list(CLASS_PATH,
  2467                                         packageName,
  2468                                         classKinds,
  2469                                         false));
  2470             if (wantSourceFiles)
  2471                 fillIn(p, SOURCE_PATH,
  2472                        fileManager.list(SOURCE_PATH,
  2473                                         packageName,
  2474                                         sourceKinds,
  2475                                         false));
  2477         verbosePath = false;
  2479     // where
  2480         private void fillIn(PackageSymbol p,
  2481                             Location location,
  2482                             Iterable<JavaFileObject> files)
  2484             currentLoc = location;
  2485             for (JavaFileObject fo : files) {
  2486                 switch (fo.getKind()) {
  2487                 case CLASS:
  2488                 case SOURCE: {
  2489                     // TODO pass binaryName to includeClassFile
  2490                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2491                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2492                     if (SourceVersion.isIdentifier(simpleName) ||
  2493                         simpleName.equals("package-info"))
  2494                         includeClassFile(p, fo);
  2495                     break;
  2497                 default:
  2498                     extraFileActions(p, fo);
  2503     /** Output for "-verbose" option.
  2504      *  @param key The key to look up the correct internationalized string.
  2505      *  @param arg An argument for substitution into the output string.
  2506      */
  2507     private void printVerbose(String key, CharSequence arg) {
  2508         log.printNoteLines("verbose." + key, arg);
  2511     /** Output for "-checkclassfile" option.
  2512      *  @param key The key to look up the correct internationalized string.
  2513      *  @param arg An argument for substitution into the output string.
  2514      */
  2515     private void printCCF(String key, Object arg) {
  2516         log.printNoteLines(key, arg);
  2520     public interface SourceCompleter {
  2521         void complete(ClassSymbol sym)
  2522             throws CompletionFailure;
  2525     /**
  2526      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2527      * The attribute is only the last component of the original filename, so is unlikely
  2528      * to be valid as is, so operations other than those to access the name throw
  2529      * UnsupportedOperationException
  2530      */
  2531     private static class SourceFileObject extends BaseFileObject {
  2533         /** The file's name.
  2534          */
  2535         private Name name;
  2536         private Name flatname;
  2538         public SourceFileObject(Name name, Name flatname) {
  2539             super(null); // no file manager; never referenced for this file object
  2540             this.name = name;
  2541             this.flatname = flatname;
  2544         @Override
  2545         public URI toUri() {
  2546             try {
  2547                 return new URI(null, name.toString(), null);
  2548             } catch (URISyntaxException e) {
  2549                 throw new CannotCreateUriError(name.toString(), e);
  2553         @Override
  2554         public String getName() {
  2555             return name.toString();
  2558         @Override
  2559         public String getShortName() {
  2560             return getName();
  2563         @Override
  2564         public JavaFileObject.Kind getKind() {
  2565             return getKind(getName());
  2568         @Override
  2569         public InputStream openInputStream() {
  2570             throw new UnsupportedOperationException();
  2573         @Override
  2574         public OutputStream openOutputStream() {
  2575             throw new UnsupportedOperationException();
  2578         @Override
  2579         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2580             throw new UnsupportedOperationException();
  2583         @Override
  2584         public Reader openReader(boolean ignoreEncodingErrors) {
  2585             throw new UnsupportedOperationException();
  2588         @Override
  2589         public Writer openWriter() {
  2590             throw new UnsupportedOperationException();
  2593         @Override
  2594         public long getLastModified() {
  2595             throw new UnsupportedOperationException();
  2598         @Override
  2599         public boolean delete() {
  2600             throw new UnsupportedOperationException();
  2603         @Override
  2604         protected String inferBinaryName(Iterable<? extends File> path) {
  2605             return flatname.toString();
  2608         @Override
  2609         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2610             return true; // fail-safe mode
  2613         /**
  2614          * Check if two file objects are equal.
  2615          * SourceFileObjects are just placeholder objects for the value of a
  2616          * SourceFile attribute, and do not directly represent specific files.
  2617          * Two SourceFileObjects are equal if their names are equal.
  2618          */
  2619         @Override
  2620         public boolean equals(Object other) {
  2621             if (this == other)
  2622                 return true;
  2624             if (!(other instanceof SourceFileObject))
  2625                 return false;
  2627             SourceFileObject o = (SourceFileObject) other;
  2628             return name.equals(o.name);
  2631         @Override
  2632         public int hashCode() {
  2633             return name.hashCode();

mercurial