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

Sat, 17 Nov 2012 19:01:03 +0000

author
mcimadamore
date
Sat, 17 Nov 2012 19:01:03 +0000
changeset 1415
01c9d4161882
parent 1393
d7d932236fee
child 1436
f6f1fd261f57
permissions
-rw-r--r--

8003280: Add lambda tests
Summary: Turn on lambda expression, method reference and default method support
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.jvm;
    28 import java.io.*;
    29 import java.net.URI;
    30 import java.net.URISyntaxException;
    31 import java.nio.CharBuffer;
    32 import java.util.Arrays;
    33 import java.util.EnumSet;
    34 import java.util.HashMap;
    35 import java.util.HashSet;
    36 import java.util.Map;
    37 import java.util.Set;
    38 import javax.lang.model.SourceVersion;
    39 import javax.tools.JavaFileObject;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileManager.Location;
    42 import javax.tools.StandardJavaFileManager;
    44 import static javax.tools.StandardLocation.*;
    46 import com.sun.tools.javac.comp.Annotate;
    47 import com.sun.tools.javac.code.*;
    48 import com.sun.tools.javac.code.Lint.LintCategory;
    49 import com.sun.tools.javac.code.Type.*;
    50 import com.sun.tools.javac.code.Symbol.*;
    51 import com.sun.tools.javac.code.Symtab;
    52 import com.sun.tools.javac.file.BaseFileObject;
    53 import com.sun.tools.javac.util.*;
    54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.TypeTag.CLASS;
    59 import static com.sun.tools.javac.jvm.ClassFile.*;
    60 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
    62 import static com.sun.tools.javac.main.Option.*;
    64 /** This class provides operations to read a classfile into an internal
    65  *  representation. The internal representation is anchored in a
    66  *  ClassSymbol which contains in its scope symbol representations
    67  *  for all other definitions in the classfile. Top-level Classes themselves
    68  *  appear as members of the scopes of PackageSymbols.
    69  *
    70  *  <p><b>This is NOT part of any supported API.
    71  *  If you write code that depends on this, you do so at your own risk.
    72  *  This code and its internal interfaces are subject to change or
    73  *  deletion without notice.</b>
    74  */
    75 public class ClassReader implements Completer {
    76     /** The context key for the class reader. */
    77     protected static final Context.Key<ClassReader> classReaderKey =
    78         new Context.Key<ClassReader>();
    80     public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
    82     Annotate annotate;
    84     /** Switch: verbose output.
    85      */
    86     boolean verbose;
    88     /** Switch: check class file for correct minor version, unrecognized
    89      *  attributes.
    90      */
    91     boolean checkClassFile;
    93     /** Switch: read constant pool and code sections. This switch is initially
    94      *  set to false but can be turned on from outside.
    95      */
    96     public boolean readAllOfClassFile = false;
    98     /** Switch: read GJ signature information.
    99      */
   100     boolean allowGenerics;
   102     /** Switch: read varargs attribute.
   103      */
   104     boolean allowVarargs;
   106     /** Switch: allow annotations.
   107      */
   108     boolean allowAnnotations;
   110     /** Switch: allow simplified varargs.
   111      */
   112     boolean allowSimplifiedVarargs;
   114    /** Lint option: warn about classfile issues
   115      */
   116     boolean lintClassfile;
   118     /** Switch: allow default methods
   119      */
   120     boolean allowDefaultMethods;
   122     /** Switch: preserve parameter names from the variable table.
   123      */
   124     public boolean saveParameterNames;
   126     /**
   127      * Switch: cache completion failures unless -XDdev is used
   128      */
   129     private boolean cacheCompletionFailure;
   131     /**
   132      * Switch: prefer source files instead of newer when both source
   133      * and class are available
   134      **/
   135     public boolean preferSource;
   137     /** The log to use for verbose output
   138      */
   139     final Log log;
   141     /** The symbol table. */
   142     Symtab syms;
   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     protected 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         types = Types.instance(context);
   268         fileManager = context.get(JavaFileManager.class);
   269         if (fileManager == null)
   270             throw new AssertionError("FileManager initialization error");
   271         diagFactory = JCDiagnostic.Factory.instance(context);
   273         init(syms, definitive);
   274         log = Log.instance(context);
   276         Options options = Options.instance(context);
   277         annotate = Annotate.instance(context);
   278         verbose        = options.isSet(VERBOSE);
   279         checkClassFile = options.isSet("-checkclassfile");
   280         Source source = Source.instance(context);
   281         allowGenerics    = source.allowGenerics();
   282         allowVarargs     = source.allowVarargs();
   283         allowAnnotations = source.allowAnnotations();
   284         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   285         allowDefaultMethods = source.allowDefaultMethods();
   286         saveParameterNames = options.isSet("save-parameter-names");
   287         cacheCompletionFailure = options.isUnset("dev");
   288         preferSource = "source".equals(options.get("-Xprefer"));
   290         completionFailureName =
   291             options.isSet("failcomplete")
   292             ? names.fromString(options.get("failcomplete"))
   293             : null;
   295         typevars = new Scope(syms.noSymbol);
   297         lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
   299         initAttributeReaders();
   300     }
   302     /** Add member to class unless it is synthetic.
   303      */
   304     private void enterMember(ClassSymbol c, Symbol sym) {
   305         if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
   306             c.members_field.enter(sym);
   307     }
   309 /************************************************************************
   310  * Error Diagnoses
   311  ***********************************************************************/
   314     public class BadClassFile extends CompletionFailure {
   315         private static final long serialVersionUID = 0;
   317         public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
   318             super(sym, createBadClassFileDiagnostic(file, diag));
   319         }
   320     }
   321     // where
   322     private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
   323         String key = (file.getKind() == JavaFileObject.Kind.SOURCE
   324                     ? "bad.source.file.header" : "bad.class.file.header");
   325         return diagFactory.fragment(key, file, diag);
   326     }
   328     public BadClassFile badClassFile(String key, Object... args) {
   329         return new BadClassFile (
   330             currentOwner.enclClass(),
   331             currentClassFile,
   332             diagFactory.fragment(key, args));
   333     }
   335 /************************************************************************
   336  * Buffer Access
   337  ***********************************************************************/
   339     /** Read a character.
   340      */
   341     char nextChar() {
   342         return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
   343     }
   345     /** Read a byte.
   346      */
   347     byte nextByte() {
   348         return buf[bp++];
   349     }
   351     /** Read an integer.
   352      */
   353     int nextInt() {
   354         return
   355             ((buf[bp++] & 0xFF) << 24) +
   356             ((buf[bp++] & 0xFF) << 16) +
   357             ((buf[bp++] & 0xFF) << 8) +
   358             (buf[bp++] & 0xFF);
   359     }
   361     /** Extract a character at position bp from buf.
   362      */
   363     char getChar(int bp) {
   364         return
   365             (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
   366     }
   368     /** Extract an integer at position bp from buf.
   369      */
   370     int getInt(int bp) {
   371         return
   372             ((buf[bp] & 0xFF) << 24) +
   373             ((buf[bp+1] & 0xFF) << 16) +
   374             ((buf[bp+2] & 0xFF) << 8) +
   375             (buf[bp+3] & 0xFF);
   376     }
   379     /** Extract a long integer at position bp from buf.
   380      */
   381     long getLong(int bp) {
   382         DataInputStream bufin =
   383             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   384         try {
   385             return bufin.readLong();
   386         } catch (IOException e) {
   387             throw new AssertionError(e);
   388         }
   389     }
   391     /** Extract a float at position bp from buf.
   392      */
   393     float getFloat(int bp) {
   394         DataInputStream bufin =
   395             new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
   396         try {
   397             return bufin.readFloat();
   398         } catch (IOException e) {
   399             throw new AssertionError(e);
   400         }
   401     }
   403     /** Extract a double at position bp from buf.
   404      */
   405     double getDouble(int bp) {
   406         DataInputStream bufin =
   407             new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
   408         try {
   409             return bufin.readDouble();
   410         } catch (IOException e) {
   411             throw new AssertionError(e);
   412         }
   413     }
   415 /************************************************************************
   416  * Constant Pool Access
   417  ***********************************************************************/
   419     /** Index all constant pool entries, writing their start addresses into
   420      *  poolIdx.
   421      */
   422     void indexPool() {
   423         poolIdx = new int[nextChar()];
   424         poolObj = new Object[poolIdx.length];
   425         int i = 1;
   426         while (i < poolIdx.length) {
   427             poolIdx[i++] = bp;
   428             byte tag = buf[bp++];
   429             switch (tag) {
   430             case CONSTANT_Utf8: case CONSTANT_Unicode: {
   431                 int len = nextChar();
   432                 bp = bp + len;
   433                 break;
   434             }
   435             case CONSTANT_Class:
   436             case CONSTANT_String:
   437             case CONSTANT_MethodType:
   438                 bp = bp + 2;
   439                 break;
   440             case CONSTANT_MethodHandle:
   441                 bp = bp + 3;
   442                 break;
   443             case CONSTANT_Fieldref:
   444             case CONSTANT_Methodref:
   445             case CONSTANT_InterfaceMethodref:
   446             case CONSTANT_NameandType:
   447             case CONSTANT_Integer:
   448             case CONSTANT_Float:
   449             case CONSTANT_InvokeDynamic:
   450                 bp = bp + 4;
   451                 break;
   452             case CONSTANT_Long:
   453             case CONSTANT_Double:
   454                 bp = bp + 8;
   455                 i++;
   456                 break;
   457             default:
   458                 throw badClassFile("bad.const.pool.tag.at",
   459                                    Byte.toString(tag),
   460                                    Integer.toString(bp -1));
   461             }
   462         }
   463     }
   465     /** Read constant pool entry at start address i, use pool as a cache.
   466      */
   467     Object readPool(int i) {
   468         Object result = poolObj[i];
   469         if (result != null) return result;
   471         int index = poolIdx[i];
   472         if (index == 0) return null;
   474         byte tag = buf[index];
   475         switch (tag) {
   476         case CONSTANT_Utf8:
   477             poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
   478             break;
   479         case CONSTANT_Unicode:
   480             throw badClassFile("unicode.str.not.supported");
   481         case CONSTANT_Class:
   482             poolObj[i] = readClassOrType(getChar(index + 1));
   483             break;
   484         case CONSTANT_String:
   485             // FIXME: (footprint) do not use toString here
   486             poolObj[i] = readName(getChar(index + 1)).toString();
   487             break;
   488         case CONSTANT_Fieldref: {
   489             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   490             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   491             poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
   492             break;
   493         }
   494         case CONSTANT_Methodref:
   495         case CONSTANT_InterfaceMethodref: {
   496             ClassSymbol owner = readClassSymbol(getChar(index + 1));
   497             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
   498             poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
   499             break;
   500         }
   501         case CONSTANT_NameandType:
   502             poolObj[i] = new NameAndType(
   503                 readName(getChar(index + 1)),
   504                 readType(getChar(index + 3)));
   505             break;
   506         case CONSTANT_Integer:
   507             poolObj[i] = getInt(index + 1);
   508             break;
   509         case CONSTANT_Float:
   510             poolObj[i] = new Float(getFloat(index + 1));
   511             break;
   512         case CONSTANT_Long:
   513             poolObj[i] = new Long(getLong(index + 1));
   514             break;
   515         case CONSTANT_Double:
   516             poolObj[i] = new Double(getDouble(index + 1));
   517             break;
   518         case CONSTANT_MethodHandle:
   519             skipBytes(4);
   520             break;
   521         case CONSTANT_MethodType:
   522             skipBytes(3);
   523             break;
   524         case CONSTANT_InvokeDynamic:
   525             skipBytes(5);
   526             break;
   527         default:
   528             throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
   529         }
   530         return poolObj[i];
   531     }
   533     /** Read signature and convert to type.
   534      */
   535     Type readType(int i) {
   536         int index = poolIdx[i];
   537         return sigToType(buf, index + 3, getChar(index + 1));
   538     }
   540     /** If name is an array type or class signature, return the
   541      *  corresponding type; otherwise return a ClassSymbol with given name.
   542      */
   543     Object readClassOrType(int i) {
   544         int index =  poolIdx[i];
   545         int len = getChar(index + 1);
   546         int start = index + 3;
   547         Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
   548         // by the above assertion, the following test can be
   549         // simplified to (buf[start] == '[')
   550         return (buf[start] == '[' || buf[start + len - 1] == ';')
   551             ? (Object)sigToType(buf, start, len)
   552             : (Object)enterClass(names.fromUtf(internalize(buf, start,
   553                                                            len)));
   554     }
   556     /** Read signature and convert to type parameters.
   557      */
   558     List<Type> readTypeParams(int i) {
   559         int index = poolIdx[i];
   560         return sigToTypeParams(buf, index + 3, getChar(index + 1));
   561     }
   563     /** Read class entry.
   564      */
   565     ClassSymbol readClassSymbol(int i) {
   566         return (ClassSymbol) (readPool(i));
   567     }
   569     /** Read name.
   570      */
   571     Name readName(int i) {
   572         return (Name) (readPool(i));
   573     }
   575 /************************************************************************
   576  * Reading Types
   577  ***********************************************************************/
   579     /** The unread portion of the currently read type is
   580      *  signature[sigp..siglimit-1].
   581      */
   582     byte[] signature;
   583     int sigp;
   584     int siglimit;
   585     boolean sigEnterPhase = false;
   587     /** Convert signature to type, where signature is a byte array segment.
   588      */
   589     Type sigToType(byte[] sig, int offset, int len) {
   590         signature = sig;
   591         sigp = offset;
   592         siglimit = offset + len;
   593         return sigToType();
   594     }
   596     /** Convert signature to type, where signature is implicit.
   597      */
   598     Type sigToType() {
   599         switch ((char) signature[sigp]) {
   600         case 'T':
   601             sigp++;
   602             int start = sigp;
   603             while (signature[sigp] != ';') sigp++;
   604             sigp++;
   605             return sigEnterPhase
   606                 ? Type.noType
   607                 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
   608         case '+': {
   609             sigp++;
   610             Type t = sigToType();
   611             return new WildcardType(t, BoundKind.EXTENDS,
   612                                     syms.boundClass);
   613         }
   614         case '*':
   615             sigp++;
   616             return new WildcardType(syms.objectType, BoundKind.UNBOUND,
   617                                     syms.boundClass);
   618         case '-': {
   619             sigp++;
   620             Type t = sigToType();
   621             return new WildcardType(t, BoundKind.SUPER,
   622                                     syms.boundClass);
   623         }
   624         case 'B':
   625             sigp++;
   626             return syms.byteType;
   627         case 'C':
   628             sigp++;
   629             return syms.charType;
   630         case 'D':
   631             sigp++;
   632             return syms.doubleType;
   633         case 'F':
   634             sigp++;
   635             return syms.floatType;
   636         case 'I':
   637             sigp++;
   638             return syms.intType;
   639         case 'J':
   640             sigp++;
   641             return syms.longType;
   642         case 'L':
   643             {
   644                 // int oldsigp = sigp;
   645                 Type t = classSigToType();
   646                 if (sigp < siglimit && signature[sigp] == '.')
   647                     throw badClassFile("deprecated inner class signature syntax " +
   648                                        "(please recompile from source)");
   649                 /*
   650                 System.err.println(" decoded " +
   651                                    new String(signature, oldsigp, sigp-oldsigp) +
   652                                    " => " + t + " outer " + t.outer());
   653                 */
   654                 return t;
   655             }
   656         case 'S':
   657             sigp++;
   658             return syms.shortType;
   659         case 'V':
   660             sigp++;
   661             return syms.voidType;
   662         case 'Z':
   663             sigp++;
   664             return syms.booleanType;
   665         case '[':
   666             sigp++;
   667             return new ArrayType(sigToType(), syms.arrayClass);
   668         case '(':
   669             sigp++;
   670             List<Type> argtypes = sigToTypes(')');
   671             Type restype = sigToType();
   672             List<Type> thrown = List.nil();
   673             while (signature[sigp] == '^') {
   674                 sigp++;
   675                 thrown = thrown.prepend(sigToType());
   676             }
   677             return new MethodType(argtypes,
   678                                   restype,
   679                                   thrown.reverse(),
   680                                   syms.methodClass);
   681         case '<':
   682             typevars = typevars.dup(currentOwner);
   683             Type poly = new ForAll(sigToTypeParams(), sigToType());
   684             typevars = typevars.leave();
   685             return poly;
   686         default:
   687             throw badClassFile("bad.signature",
   688                                Convert.utf2string(signature, sigp, 10));
   689         }
   690     }
   692     byte[] signatureBuffer = new byte[0];
   693     int sbp = 0;
   694     /** Convert class signature to type, where signature is implicit.
   695      */
   696     Type classSigToType() {
   697         if (signature[sigp] != 'L')
   698             throw badClassFile("bad.class.signature",
   699                                Convert.utf2string(signature, sigp, 10));
   700         sigp++;
   701         Type outer = Type.noType;
   702         int startSbp = sbp;
   704         while (true) {
   705             final byte c = signature[sigp++];
   706             switch (c) {
   708             case ';': {         // end
   709                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   710                                                          startSbp,
   711                                                          sbp - startSbp));
   712                 if (outer == Type.noType)
   713                     outer = t.erasure(types);
   714                 else
   715                     outer = new ClassType(outer, List.<Type>nil(), t);
   716                 sbp = startSbp;
   717                 return outer;
   718             }
   720             case '<':           // generic arguments
   721                 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
   722                                                          startSbp,
   723                                                          sbp - startSbp));
   724                 outer = new ClassType(outer, sigToTypes('>'), t) {
   725                         boolean completed = false;
   726                         @Override
   727                         public Type getEnclosingType() {
   728                             if (!completed) {
   729                                 completed = true;
   730                                 tsym.complete();
   731                                 Type enclosingType = tsym.type.getEnclosingType();
   732                                 if (enclosingType != Type.noType) {
   733                                     List<Type> typeArgs =
   734                                         super.getEnclosingType().allparams();
   735                                     List<Type> typeParams =
   736                                         enclosingType.allparams();
   737                                     if (typeParams.length() != typeArgs.length()) {
   738                                         // no "rare" types
   739                                         super.setEnclosingType(types.erasure(enclosingType));
   740                                     } else {
   741                                         super.setEnclosingType(types.subst(enclosingType,
   742                                                                            typeParams,
   743                                                                            typeArgs));
   744                                     }
   745                                 } else {
   746                                     super.setEnclosingType(Type.noType);
   747                                 }
   748                             }
   749                             return super.getEnclosingType();
   750                         }
   751                         @Override
   752                         public void setEnclosingType(Type outer) {
   753                             throw new UnsupportedOperationException();
   754                         }
   755                     };
   756                 switch (signature[sigp++]) {
   757                 case ';':
   758                     if (sigp < signature.length && signature[sigp] == '.') {
   759                         // support old-style GJC signatures
   760                         // The signature produced was
   761                         // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
   762                         // rather than say
   763                         // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
   764                         // so we skip past ".Lfoo/Outer$"
   765                         sigp += (sbp - startSbp) + // "foo/Outer"
   766                             3;  // ".L" and "$"
   767                         signatureBuffer[sbp++] = (byte)'$';
   768                         break;
   769                     } else {
   770                         sbp = startSbp;
   771                         return outer;
   772                     }
   773                 case '.':
   774                     signatureBuffer[sbp++] = (byte)'$';
   775                     break;
   776                 default:
   777                     throw new AssertionError(signature[sigp-1]);
   778                 }
   779                 continue;
   781             case '.':
   782                 signatureBuffer[sbp++] = (byte)'$';
   783                 continue;
   784             case '/':
   785                 signatureBuffer[sbp++] = (byte)'.';
   786                 continue;
   787             default:
   788                 signatureBuffer[sbp++] = c;
   789                 continue;
   790             }
   791         }
   792     }
   794     /** Convert (implicit) signature to list of types
   795      *  until `terminator' is encountered.
   796      */
   797     List<Type> sigToTypes(char terminator) {
   798         List<Type> head = List.of(null);
   799         List<Type> tail = head;
   800         while (signature[sigp] != terminator)
   801             tail = tail.setTail(List.of(sigToType()));
   802         sigp++;
   803         return head.tail;
   804     }
   806     /** Convert signature to type parameters, where signature is a byte
   807      *  array segment.
   808      */
   809     List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
   810         signature = sig;
   811         sigp = offset;
   812         siglimit = offset + len;
   813         return sigToTypeParams();
   814     }
   816     /** Convert signature to type parameters, where signature is implicit.
   817      */
   818     List<Type> sigToTypeParams() {
   819         List<Type> tvars = List.nil();
   820         if (signature[sigp] == '<') {
   821             sigp++;
   822             int start = sigp;
   823             sigEnterPhase = true;
   824             while (signature[sigp] != '>')
   825                 tvars = tvars.prepend(sigToTypeParam());
   826             sigEnterPhase = false;
   827             sigp = start;
   828             while (signature[sigp] != '>')
   829                 sigToTypeParam();
   830             sigp++;
   831         }
   832         return tvars.reverse();
   833     }
   835     /** Convert (implicit) signature to type parameter.
   836      */
   837     Type sigToTypeParam() {
   838         int start = sigp;
   839         while (signature[sigp] != ':') sigp++;
   840         Name name = names.fromUtf(signature, start, sigp - start);
   841         TypeVar tvar;
   842         if (sigEnterPhase) {
   843             tvar = new TypeVar(name, currentOwner, syms.botType);
   844             typevars.enter(tvar.tsym);
   845         } else {
   846             tvar = (TypeVar)findTypeVar(name);
   847         }
   848         List<Type> bounds = List.nil();
   849         Type st = null;
   850         if (signature[sigp] == ':' && signature[sigp+1] == ':') {
   851             sigp++;
   852             st = syms.objectType;
   853         }
   854         while (signature[sigp] == ':') {
   855             sigp++;
   856             bounds = bounds.prepend(sigToType());
   857         }
   858         if (!sigEnterPhase) {
   859             types.setBounds(tvar, bounds.reverse(), st);
   860         }
   861         return tvar;
   862     }
   864     /** Find type variable with given name in `typevars' scope.
   865      */
   866     Type findTypeVar(Name name) {
   867         Scope.Entry e = typevars.lookup(name);
   868         if (e.scope != null) {
   869             return e.sym.type;
   870         } else {
   871             if (readingClassAttr) {
   872                 // While reading the class attribute, the supertypes
   873                 // might refer to a type variable from an enclosing element
   874                 // (method or class).
   875                 // If the type variable is defined in the enclosing class,
   876                 // we can actually find it in
   877                 // currentOwner.owner.type.getTypeArguments()
   878                 // However, until we have read the enclosing method attribute
   879                 // we don't know for sure if this owner is correct.  It could
   880                 // be a method and there is no way to tell before reading the
   881                 // enclosing method attribute.
   882                 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
   883                 missingTypeVariables = missingTypeVariables.prepend(t);
   884                 // System.err.println("Missing type var " + name);
   885                 return t;
   886             }
   887             throw badClassFile("undecl.type.var", name);
   888         }
   889     }
   891 /************************************************************************
   892  * Reading Attributes
   893  ***********************************************************************/
   895     protected enum AttributeKind { CLASS, MEMBER };
   896     protected abstract class AttributeReader {
   897         protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
   898             this.name = name;
   899             this.version = version;
   900             this.kinds = kinds;
   901         }
   903         protected boolean accepts(AttributeKind kind) {
   904             if (kinds.contains(kind)) {
   905                 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
   906                     return true;
   908                 if (lintClassfile && !warnedAttrs.contains(name)) {
   909                     JavaFileObject prev = log.useSource(currentClassFile);
   910                     try {
   911                         log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
   912                                 name, version.major, version.minor, majorVersion, minorVersion);
   913                     } finally {
   914                         log.useSource(prev);
   915                     }
   916                     warnedAttrs.add(name);
   917                 }
   918             }
   919             return false;
   920         }
   922         protected abstract void read(Symbol sym, int attrLen);
   924         protected final Name name;
   925         protected final ClassFile.Version version;
   926         protected final Set<AttributeKind> kinds;
   927     }
   929     protected Set<AttributeKind> CLASS_ATTRIBUTE =
   930             EnumSet.of(AttributeKind.CLASS);
   931     protected Set<AttributeKind> MEMBER_ATTRIBUTE =
   932             EnumSet.of(AttributeKind.MEMBER);
   933     protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
   934             EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
   936     protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
   938     private void initAttributeReaders() {
   939         AttributeReader[] readers = {
   940             // v45.3 attributes
   942             new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
   943                 protected void read(Symbol sym, int attrLen) {
   944                     if (readAllOfClassFile || saveParameterNames)
   945                         ((MethodSymbol)sym).code = readCode(sym);
   946                     else
   947                         bp = bp + attrLen;
   948                 }
   949             },
   951             new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
   952                 protected void read(Symbol sym, int attrLen) {
   953                     Object v = readPool(nextChar());
   954                     // Ignore ConstantValue attribute if field not final.
   955                     if ((sym.flags() & FINAL) != 0)
   956                         ((VarSymbol) sym).setData(v);
   957                 }
   958             },
   960             new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   961                 protected void read(Symbol sym, int attrLen) {
   962                     sym.flags_field |= DEPRECATED;
   963                 }
   964             },
   966             new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   967                 protected void read(Symbol sym, int attrLen) {
   968                     int nexceptions = nextChar();
   969                     List<Type> thrown = List.nil();
   970                     for (int j = 0; j < nexceptions; j++)
   971                         thrown = thrown.prepend(readClassSymbol(nextChar()).type);
   972                     if (sym.type.getThrownTypes().isEmpty())
   973                         sym.type.asMethodType().thrown = thrown.reverse();
   974                 }
   975             },
   977             new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
   978                 protected void read(Symbol sym, int attrLen) {
   979                     ClassSymbol c = (ClassSymbol) sym;
   980                     readInnerClasses(c);
   981                 }
   982             },
   984             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
   985                 protected void read(Symbol sym, int attrLen) {
   986                     int newbp = bp + attrLen;
   987                     if (saveParameterNames) {
   988                         // Pick up parameter names from the variable table.
   989                         // Parameter names are not explicitly identified as such,
   990                         // but all parameter name entries in the LocalVariableTable
   991                         // have a start_pc of 0.  Therefore, we record the name
   992                         // indicies of all slots with a start_pc of zero in the
   993                         // parameterNameIndicies array.
   994                         // Note that this implicitly honors the JVMS spec that
   995                         // there may be more than one LocalVariableTable, and that
   996                         // there is no specified ordering for the entries.
   997                         int numEntries = nextChar();
   998                         for (int i = 0; i < numEntries; i++) {
   999                             int start_pc = nextChar();
  1000                             int length = nextChar();
  1001                             int nameIndex = nextChar();
  1002                             int sigIndex = nextChar();
  1003                             int register = nextChar();
  1004                             if (start_pc == 0) {
  1005                                 // ensure array large enough
  1006                                 if (register >= parameterNameIndices.length) {
  1007                                     int newSize = Math.max(register, parameterNameIndices.length + 8);
  1008                                     parameterNameIndices =
  1009                                             Arrays.copyOf(parameterNameIndices, newSize);
  1011                                 parameterNameIndices[register] = nameIndex;
  1012                                 haveParameterNameIndices = true;
  1016                     bp = newbp;
  1018             },
  1020             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
  1021                 protected void read(Symbol sym, int attrLen) {
  1022                     ClassSymbol c = (ClassSymbol) sym;
  1023                     Name n = readName(nextChar());
  1024                     c.sourcefile = new SourceFileObject(n, c.flatname);
  1025                     // If the class is a toplevel class, originating from a Java source file,
  1026                     // but the class name does not match the file name, then it is
  1027                     // an auxiliary class.
  1028                     String sn = n.toString();
  1029                     if (c.owner.kind == Kinds.PCK &&
  1030                         sn.endsWith(".java") &&
  1031                         !sn.equals(c.name.toString()+".java")) {
  1032                         c.flags_field |= AUXILIARY;
  1035             },
  1037             new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
  1038                 protected void read(Symbol sym, int attrLen) {
  1039                     // bridge methods are visible when generics not enabled
  1040                     if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
  1041                         sym.flags_field |= SYNTHETIC;
  1043             },
  1045             // standard v49 attributes
  1047             new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
  1048                 protected void read(Symbol sym, int attrLen) {
  1049                     int newbp = bp + attrLen;
  1050                     readEnclosingMethodAttr(sym);
  1051                     bp = newbp;
  1053             },
  1055             new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1056                 @Override
  1057                 protected boolean accepts(AttributeKind kind) {
  1058                     return super.accepts(kind) && allowGenerics;
  1061                 protected void read(Symbol sym, int attrLen) {
  1062                     if (sym.kind == TYP) {
  1063                         ClassSymbol c = (ClassSymbol) sym;
  1064                         readingClassAttr = true;
  1065                         try {
  1066                             ClassType ct1 = (ClassType)c.type;
  1067                             Assert.check(c == currentOwner);
  1068                             ct1.typarams_field = readTypeParams(nextChar());
  1069                             ct1.supertype_field = sigToType();
  1070                             ListBuffer<Type> is = new ListBuffer<Type>();
  1071                             while (sigp != siglimit) is.append(sigToType());
  1072                             ct1.interfaces_field = is.toList();
  1073                         } finally {
  1074                             readingClassAttr = false;
  1076                     } else {
  1077                         List<Type> thrown = sym.type.getThrownTypes();
  1078                         sym.type = readType(nextChar());
  1079                         //- System.err.println(" # " + sym.type);
  1080                         if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
  1081                             sym.type.asMethodType().thrown = thrown;
  1085             },
  1087             // v49 annotation attributes
  1089             new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1090                 protected void read(Symbol sym, int attrLen) {
  1091                     attachAnnotationDefault(sym);
  1093             },
  1095             new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1096                 protected void read(Symbol sym, int attrLen) {
  1097                     attachAnnotations(sym);
  1099             },
  1101             new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1102                 protected void read(Symbol sym, int attrLen) {
  1103                     attachParameterAnnotations(sym);
  1105             },
  1107             new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1108                 protected void read(Symbol sym, int attrLen) {
  1109                     attachAnnotations(sym);
  1111             },
  1113             new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1114                 protected void read(Symbol sym, int attrLen) {
  1115                     attachParameterAnnotations(sym);
  1117             },
  1119             // additional "legacy" v49 attributes, superceded by flags
  1121             new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1122                 protected void read(Symbol sym, int attrLen) {
  1123                     if (allowAnnotations)
  1124                         sym.flags_field |= ANNOTATION;
  1126             },
  1128             new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
  1129                 protected void read(Symbol sym, int attrLen) {
  1130                     sym.flags_field |= BRIDGE;
  1131                     if (!allowGenerics)
  1132                         sym.flags_field &= ~SYNTHETIC;
  1134             },
  1136             new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1137                 protected void read(Symbol sym, int attrLen) {
  1138                     sym.flags_field |= ENUM;
  1140             },
  1142             new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
  1143                 protected void read(Symbol sym, int attrLen) {
  1144                     if (allowVarargs)
  1145                         sym.flags_field |= VARARGS;
  1147             },
  1149             // The following attributes for a Code attribute are not currently handled
  1150             // StackMapTable
  1151             // SourceDebugExtension
  1152             // LineNumberTable
  1153             // LocalVariableTypeTable
  1154         };
  1156         for (AttributeReader r: readers)
  1157             attributeReaders.put(r.name, r);
  1160     /** Report unrecognized attribute.
  1161      */
  1162     void unrecognized(Name attrName) {
  1163         if (checkClassFile)
  1164             printCCF("ccf.unrecognized.attribute", attrName);
  1169     protected void readEnclosingMethodAttr(Symbol sym) {
  1170         // sym is a nested class with an "Enclosing Method" attribute
  1171         // remove sym from it's current owners scope and place it in
  1172         // the scope specified by the attribute
  1173         sym.owner.members().remove(sym);
  1174         ClassSymbol self = (ClassSymbol)sym;
  1175         ClassSymbol c = readClassSymbol(nextChar());
  1176         NameAndType nt = (NameAndType)readPool(nextChar());
  1178         if (c.members_field == null)
  1179             throw badClassFile("bad.enclosing.class", self, c);
  1181         MethodSymbol m = findMethod(nt, c.members_field, self.flags());
  1182         if (nt != null && m == null)
  1183             throw badClassFile("bad.enclosing.method", self);
  1185         self.name = simpleBinaryName(self.flatname, c.flatname) ;
  1186         self.owner = m != null ? m : c;
  1187         if (self.name.isEmpty())
  1188             self.fullname = names.empty;
  1189         else
  1190             self.fullname = ClassSymbol.formFullName(self.name, self.owner);
  1192         if (m != null) {
  1193             ((ClassType)sym.type).setEnclosingType(m.type);
  1194         } else if ((self.flags_field & STATIC) == 0) {
  1195             ((ClassType)sym.type).setEnclosingType(c.type);
  1196         } else {
  1197             ((ClassType)sym.type).setEnclosingType(Type.noType);
  1199         enterTypevars(self);
  1200         if (!missingTypeVariables.isEmpty()) {
  1201             ListBuffer<Type> typeVars =  new ListBuffer<Type>();
  1202             for (Type typevar : missingTypeVariables) {
  1203                 typeVars.append(findTypeVar(typevar.tsym.name));
  1205             foundTypeVariables = typeVars.toList();
  1206         } else {
  1207             foundTypeVariables = List.nil();
  1211     // See java.lang.Class
  1212     private Name simpleBinaryName(Name self, Name enclosing) {
  1213         String simpleBinaryName = self.toString().substring(enclosing.toString().length());
  1214         if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
  1215             throw badClassFile("bad.enclosing.method", self);
  1216         int index = 1;
  1217         while (index < simpleBinaryName.length() &&
  1218                isAsciiDigit(simpleBinaryName.charAt(index)))
  1219             index++;
  1220         return names.fromString(simpleBinaryName.substring(index));
  1223     private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
  1224         if (nt == null)
  1225             return null;
  1227         MethodType type = nt.type.asMethodType();
  1229         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
  1230             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
  1231                 return (MethodSymbol)e.sym;
  1233         if (nt.name != names.init)
  1234             // not a constructor
  1235             return null;
  1236         if ((flags & INTERFACE) != 0)
  1237             // no enclosing instance
  1238             return null;
  1239         if (nt.type.getParameterTypes().isEmpty())
  1240             // no parameters
  1241             return null;
  1243         // A constructor of an inner class.
  1244         // Remove the first argument (the enclosing instance)
  1245         nt.type = new MethodType(nt.type.getParameterTypes().tail,
  1246                                  nt.type.getReturnType(),
  1247                                  nt.type.getThrownTypes(),
  1248                                  syms.methodClass);
  1249         // Try searching again
  1250         return findMethod(nt, scope, flags);
  1253     /** Similar to Types.isSameType but avoids completion */
  1254     private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
  1255         List<Type> types1 = types.erasure(mt1.getParameterTypes())
  1256             .prepend(types.erasure(mt1.getReturnType()));
  1257         List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
  1258         while (!types1.isEmpty() && !types2.isEmpty()) {
  1259             if (types1.head.tsym != types2.head.tsym)
  1260                 return false;
  1261             types1 = types1.tail;
  1262             types2 = types2.tail;
  1264         return types1.isEmpty() && types2.isEmpty();
  1267     /**
  1268      * Character.isDigit answers <tt>true</tt> to some non-ascii
  1269      * digits.  This one does not.  <b>copied from java.lang.Class</b>
  1270      */
  1271     private static boolean isAsciiDigit(char c) {
  1272         return '0' <= c && c <= '9';
  1275     /** Read member attributes.
  1276      */
  1277     void readMemberAttrs(Symbol sym) {
  1278         readAttrs(sym, AttributeKind.MEMBER);
  1281     void readAttrs(Symbol sym, AttributeKind kind) {
  1282         char ac = nextChar();
  1283         for (int i = 0; i < ac; i++) {
  1284             Name attrName = readName(nextChar());
  1285             int attrLen = nextInt();
  1286             AttributeReader r = attributeReaders.get(attrName);
  1287             if (r != null && r.accepts(kind))
  1288                 r.read(sym, attrLen);
  1289             else  {
  1290                 unrecognized(attrName);
  1291                 bp = bp + attrLen;
  1296     private boolean readingClassAttr = false;
  1297     private List<Type> missingTypeVariables = List.nil();
  1298     private List<Type> foundTypeVariables = List.nil();
  1300     /** Read class attributes.
  1301      */
  1302     void readClassAttrs(ClassSymbol c) {
  1303         readAttrs(c, AttributeKind.CLASS);
  1306     /** Read code block.
  1307      */
  1308     Code readCode(Symbol owner) {
  1309         nextChar(); // max_stack
  1310         nextChar(); // max_locals
  1311         final int  code_length = nextInt();
  1312         bp += code_length;
  1313         final char exception_table_length = nextChar();
  1314         bp += exception_table_length * 8;
  1315         readMemberAttrs(owner);
  1316         return null;
  1319 /************************************************************************
  1320  * Reading Java-language annotations
  1321  ***********************************************************************/
  1323     /** Attach annotations.
  1324      */
  1325     void attachAnnotations(final Symbol sym) {
  1326         int numAttributes = nextChar();
  1327         if (numAttributes != 0) {
  1328             ListBuffer<CompoundAnnotationProxy> proxies =
  1329                 new ListBuffer<CompoundAnnotationProxy>();
  1330             for (int i = 0; i<numAttributes; i++) {
  1331                 CompoundAnnotationProxy proxy = readCompoundAnnotation();
  1332                 if (proxy.type.tsym == syms.proprietaryType.tsym)
  1333                     sym.flags_field |= PROPRIETARY;
  1334                 else
  1335                     proxies.append(proxy);
  1337             annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
  1341     /** Attach parameter annotations.
  1342      */
  1343     void attachParameterAnnotations(final Symbol method) {
  1344         final MethodSymbol meth = (MethodSymbol)method;
  1345         int numParameters = buf[bp++] & 0xFF;
  1346         List<VarSymbol> parameters = meth.params();
  1347         int pnum = 0;
  1348         while (parameters.tail != null) {
  1349             attachAnnotations(parameters.head);
  1350             parameters = parameters.tail;
  1351             pnum++;
  1353         if (pnum != numParameters) {
  1354             throw badClassFile("bad.runtime.invisible.param.annotations", meth);
  1358     /** Attach the default value for an annotation element.
  1359      */
  1360     void attachAnnotationDefault(final Symbol sym) {
  1361         final MethodSymbol meth = (MethodSymbol)sym; // only on methods
  1362         final Attribute value = readAttributeValue();
  1363         annotate.normal(new AnnotationDefaultCompleter(meth, value));
  1366     Type readTypeOrClassSymbol(int i) {
  1367         // support preliminary jsr175-format class files
  1368         if (buf[poolIdx[i]] == CONSTANT_Class)
  1369             return readClassSymbol(i).type;
  1370         return readType(i);
  1372     Type readEnumType(int i) {
  1373         // support preliminary jsr175-format class files
  1374         int index = poolIdx[i];
  1375         int length = getChar(index + 1);
  1376         if (buf[index + length + 2] != ';')
  1377             return enterClass(readName(i)).type;
  1378         return readType(i);
  1381     CompoundAnnotationProxy readCompoundAnnotation() {
  1382         Type t = readTypeOrClassSymbol(nextChar());
  1383         int numFields = nextChar();
  1384         ListBuffer<Pair<Name,Attribute>> pairs =
  1385             new ListBuffer<Pair<Name,Attribute>>();
  1386         for (int i=0; i<numFields; i++) {
  1387             Name name = readName(nextChar());
  1388             Attribute value = readAttributeValue();
  1389             pairs.append(new Pair<Name,Attribute>(name, value));
  1391         return new CompoundAnnotationProxy(t, pairs.toList());
  1394     Attribute readAttributeValue() {
  1395         char c = (char) buf[bp++];
  1396         switch (c) {
  1397         case 'B':
  1398             return new Attribute.Constant(syms.byteType, readPool(nextChar()));
  1399         case 'C':
  1400             return new Attribute.Constant(syms.charType, readPool(nextChar()));
  1401         case 'D':
  1402             return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
  1403         case 'F':
  1404             return new Attribute.Constant(syms.floatType, readPool(nextChar()));
  1405         case 'I':
  1406             return new Attribute.Constant(syms.intType, readPool(nextChar()));
  1407         case 'J':
  1408             return new Attribute.Constant(syms.longType, readPool(nextChar()));
  1409         case 'S':
  1410             return new Attribute.Constant(syms.shortType, readPool(nextChar()));
  1411         case 'Z':
  1412             return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
  1413         case 's':
  1414             return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
  1415         case 'e':
  1416             return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
  1417         case 'c':
  1418             return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
  1419         case '[': {
  1420             int n = nextChar();
  1421             ListBuffer<Attribute> l = new ListBuffer<Attribute>();
  1422             for (int i=0; i<n; i++)
  1423                 l.append(readAttributeValue());
  1424             return new ArrayAttributeProxy(l.toList());
  1426         case '@':
  1427             return readCompoundAnnotation();
  1428         default:
  1429             throw new AssertionError("unknown annotation tag '" + c + "'");
  1433     interface ProxyVisitor extends Attribute.Visitor {
  1434         void visitEnumAttributeProxy(EnumAttributeProxy proxy);
  1435         void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
  1436         void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
  1439     static class EnumAttributeProxy extends Attribute {
  1440         Type enumType;
  1441         Name enumerator;
  1442         public EnumAttributeProxy(Type enumType, Name enumerator) {
  1443             super(null);
  1444             this.enumType = enumType;
  1445             this.enumerator = enumerator;
  1447         public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
  1448         @Override
  1449         public String toString() {
  1450             return "/*proxy enum*/" + enumType + "." + enumerator;
  1454     static class ArrayAttributeProxy extends Attribute {
  1455         List<Attribute> values;
  1456         ArrayAttributeProxy(List<Attribute> values) {
  1457             super(null);
  1458             this.values = values;
  1460         public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
  1461         @Override
  1462         public String toString() {
  1463             return "{" + values + "}";
  1467     /** A temporary proxy representing a compound attribute.
  1468      */
  1469     static class CompoundAnnotationProxy extends Attribute {
  1470         final List<Pair<Name,Attribute>> values;
  1471         public CompoundAnnotationProxy(Type type,
  1472                                       List<Pair<Name,Attribute>> values) {
  1473             super(type);
  1474             this.values = values;
  1476         public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
  1477         @Override
  1478         public String toString() {
  1479             StringBuilder buf = new StringBuilder();
  1480             buf.append("@");
  1481             buf.append(type.tsym.getQualifiedName());
  1482             buf.append("/*proxy*/{");
  1483             boolean first = true;
  1484             for (List<Pair<Name,Attribute>> v = values;
  1485                  v.nonEmpty(); v = v.tail) {
  1486                 Pair<Name,Attribute> value = v.head;
  1487                 if (!first) buf.append(",");
  1488                 first = false;
  1489                 buf.append(value.fst);
  1490                 buf.append("=");
  1491                 buf.append(value.snd);
  1493             buf.append("}");
  1494             return buf.toString();
  1498     /** A temporary proxy representing a type annotation.
  1499      */
  1500     static class TypeAnnotationProxy {
  1501         final CompoundAnnotationProxy compound;
  1502         final TypeAnnotationPosition position;
  1503         public TypeAnnotationProxy(CompoundAnnotationProxy compound,
  1504                 TypeAnnotationPosition position) {
  1505             this.compound = compound;
  1506             this.position = position;
  1510     class AnnotationDeproxy implements ProxyVisitor {
  1511         private ClassSymbol requestingOwner = currentOwner.kind == MTH
  1512             ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
  1514         List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
  1515             // also must fill in types!!!!
  1516             ListBuffer<Attribute.Compound> buf =
  1517                 new ListBuffer<Attribute.Compound>();
  1518             for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
  1519                 buf.append(deproxyCompound(l.head));
  1521             return buf.toList();
  1524         Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
  1525             ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
  1526                 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
  1527             for (List<Pair<Name,Attribute>> l = a.values;
  1528                  l.nonEmpty();
  1529                  l = l.tail) {
  1530                 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
  1531                 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
  1532                            (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
  1534             return new Attribute.Compound(a.type, buf.toList());
  1537         MethodSymbol findAccessMethod(Type container, Name name) {
  1538             CompletionFailure failure = null;
  1539             try {
  1540                 for (Scope.Entry e = container.tsym.members().lookup(name);
  1541                      e.scope != null;
  1542                      e = e.next()) {
  1543                     Symbol sym = e.sym;
  1544                     if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
  1545                         return (MethodSymbol) sym;
  1547             } catch (CompletionFailure ex) {
  1548                 failure = ex;
  1550             // The method wasn't found: emit a warning and recover
  1551             JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
  1552             try {
  1553                 if (failure == null) {
  1554                     log.warning("annotation.method.not.found",
  1555                                 container,
  1556                                 name);
  1557                 } else {
  1558                     log.warning("annotation.method.not.found.reason",
  1559                                 container,
  1560                                 name,
  1561                                 failure.getDetailValue());//diagnostic, if present
  1563             } finally {
  1564                 log.useSource(prevSource);
  1566             // Construct a new method type and symbol.  Use bottom
  1567             // type (typeof null) as return type because this type is
  1568             // a subtype of all reference types and can be converted
  1569             // to primitive types by unboxing.
  1570             MethodType mt = new MethodType(List.<Type>nil(),
  1571                                            syms.botType,
  1572                                            List.<Type>nil(),
  1573                                            syms.methodClass);
  1574             return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
  1577         Attribute result;
  1578         Type type;
  1579         Attribute deproxy(Type t, Attribute a) {
  1580             Type oldType = type;
  1581             try {
  1582                 type = t;
  1583                 a.accept(this);
  1584                 return result;
  1585             } finally {
  1586                 type = oldType;
  1590         // implement Attribute.Visitor below
  1592         public void visitConstant(Attribute.Constant value) {
  1593             // assert value.type == type;
  1594             result = value;
  1597         public void visitClass(Attribute.Class clazz) {
  1598             result = clazz;
  1601         public void visitEnum(Attribute.Enum e) {
  1602             throw new AssertionError(); // shouldn't happen
  1605         public void visitCompound(Attribute.Compound compound) {
  1606             throw new AssertionError(); // shouldn't happen
  1609         public void visitArray(Attribute.Array array) {
  1610             throw new AssertionError(); // shouldn't happen
  1613         public void visitError(Attribute.Error e) {
  1614             throw new AssertionError(); // shouldn't happen
  1617         public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
  1618             // type.tsym.flatName() should == proxy.enumFlatName
  1619             TypeSymbol enumTypeSym = proxy.enumType.tsym;
  1620             VarSymbol enumerator = null;
  1621             CompletionFailure failure = null;
  1622             try {
  1623                 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
  1624                      e.scope != null;
  1625                      e = e.next()) {
  1626                     if (e.sym.kind == VAR) {
  1627                         enumerator = (VarSymbol)e.sym;
  1628                         break;
  1632             catch (CompletionFailure ex) {
  1633                 failure = ex;
  1635             if (enumerator == null) {
  1636                 if (failure != null) {
  1637                     log.warning("unknown.enum.constant.reason",
  1638                               currentClassFile, enumTypeSym, proxy.enumerator,
  1639                               failure.getDiagnostic());
  1640                 } else {
  1641                     log.warning("unknown.enum.constant",
  1642                               currentClassFile, enumTypeSym, proxy.enumerator);
  1644                 result = new Attribute.Enum(enumTypeSym.type,
  1645                         new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
  1646             } else {
  1647                 result = new Attribute.Enum(enumTypeSym.type, enumerator);
  1651         public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
  1652             int length = proxy.values.length();
  1653             Attribute[] ats = new Attribute[length];
  1654             Type elemtype = types.elemtype(type);
  1655             int i = 0;
  1656             for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
  1657                 ats[i++] = deproxy(elemtype, p.head);
  1659             result = new Attribute.Array(type, ats);
  1662         public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
  1663             result = deproxyCompound(proxy);
  1667     class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1668         final MethodSymbol sym;
  1669         final Attribute value;
  1670         final JavaFileObject classFile = currentClassFile;
  1671         @Override
  1672         public String toString() {
  1673             return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
  1675         AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
  1676             this.sym = sym;
  1677             this.value = value;
  1679         // implement Annotate.Annotator.enterAnnotation()
  1680         public void enterAnnotation() {
  1681             JavaFileObject previousClassFile = currentClassFile;
  1682             try {
  1683                 currentClassFile = classFile;
  1684                 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
  1685             } finally {
  1686                 currentClassFile = previousClassFile;
  1691     class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
  1692         final Symbol sym;
  1693         final List<CompoundAnnotationProxy> l;
  1694         final JavaFileObject classFile;
  1695         @Override
  1696         public String toString() {
  1697             return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
  1699         AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
  1700             this.sym = sym;
  1701             this.l = l;
  1702             this.classFile = currentClassFile;
  1704         // implement Annotate.Annotator.enterAnnotation()
  1705         public void enterAnnotation() {
  1706             JavaFileObject previousClassFile = currentClassFile;
  1707             try {
  1708                 currentClassFile = classFile;
  1709                 Annotations annotations = sym.annotations;
  1710                 List<Attribute.Compound> newList = deproxyCompoundList(l);
  1711                 if (annotations.pendingCompletion()) {
  1712                     annotations.setAttributes(newList);
  1713                 } else {
  1714                     annotations.append(newList);
  1716             } finally {
  1717                 currentClassFile = previousClassFile;
  1723 /************************************************************************
  1724  * Reading Symbols
  1725  ***********************************************************************/
  1727     /** Read a field.
  1728      */
  1729     VarSymbol readField() {
  1730         long flags = adjustFieldFlags(nextChar());
  1731         Name name = readName(nextChar());
  1732         Type type = readType(nextChar());
  1733         VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
  1734         readMemberAttrs(v);
  1735         return v;
  1738     /** Read a method.
  1739      */
  1740     MethodSymbol readMethod() {
  1741         long flags = adjustMethodFlags(nextChar());
  1742         Name name = readName(nextChar());
  1743         Type type = readType(nextChar());
  1744         if (currentOwner.isInterface() &&
  1745                 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
  1746             if (majorVersion > Target.JDK1_8.majorVersion ||
  1747                     (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
  1748                 currentOwner.flags_field |= DEFAULT;
  1749                 flags |= DEFAULT | ABSTRACT;
  1750             } else {
  1751                 //protect against ill-formed classfiles
  1752                 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
  1755         if (name == names.init && currentOwner.hasOuterInstance()) {
  1756             // Sometimes anonymous classes don't have an outer
  1757             // instance, however, there is no reliable way to tell so
  1758             // we never strip this$n
  1759             if (!currentOwner.name.isEmpty())
  1760                 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
  1761                                       type.getReturnType(),
  1762                                       type.getThrownTypes(),
  1763                                       syms.methodClass);
  1765         MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
  1766         if (saveParameterNames)
  1767             initParameterNames(m);
  1768         Symbol prevOwner = currentOwner;
  1769         currentOwner = m;
  1770         try {
  1771             readMemberAttrs(m);
  1772         } finally {
  1773             currentOwner = prevOwner;
  1775         if (saveParameterNames)
  1776             setParameterNames(m, type);
  1777         return m;
  1780     private List<Type> adjustMethodParams(long flags, List<Type> args) {
  1781         boolean isVarargs = (flags & VARARGS) != 0;
  1782         if (isVarargs) {
  1783             Type varargsElem = args.last();
  1784             ListBuffer<Type> adjustedArgs = ListBuffer.lb();
  1785             for (Type t : args) {
  1786                 adjustedArgs.append(t != varargsElem ?
  1787                     t :
  1788                     ((ArrayType)t).makeVarargs());
  1790             args = adjustedArgs.toList();
  1792         return args.tail;
  1795     /**
  1796      * Init the parameter names array.
  1797      * Parameter names are currently inferred from the names in the
  1798      * LocalVariableTable attributes of a Code attribute.
  1799      * (Note: this means parameter names are currently not available for
  1800      * methods without a Code attribute.)
  1801      * This method initializes an array in which to store the name indexes
  1802      * of parameter names found in LocalVariableTable attributes. It is
  1803      * slightly supersized to allow for additional slots with a start_pc of 0.
  1804      */
  1805     void initParameterNames(MethodSymbol sym) {
  1806         // make allowance for synthetic parameters.
  1807         final int excessSlots = 4;
  1808         int expectedParameterSlots =
  1809                 Code.width(sym.type.getParameterTypes()) + excessSlots;
  1810         if (parameterNameIndices == null
  1811                 || parameterNameIndices.length < expectedParameterSlots) {
  1812             parameterNameIndices = new int[expectedParameterSlots];
  1813         } else
  1814             Arrays.fill(parameterNameIndices, 0);
  1815         haveParameterNameIndices = false;
  1818     /**
  1819      * Set the parameter names for a symbol from the name index in the
  1820      * parameterNameIndicies array. The type of the symbol may have changed
  1821      * while reading the method attributes (see the Signature attribute).
  1822      * This may be because of generic information or because anonymous
  1823      * synthetic parameters were added.   The original type (as read from
  1824      * the method descriptor) is used to help guess the existence of
  1825      * anonymous synthetic parameters.
  1826      * On completion, sym.savedParameter names will either be null (if
  1827      * no parameter names were found in the class file) or will be set to a
  1828      * list of names, one per entry in sym.type.getParameterTypes, with
  1829      * any missing names represented by the empty name.
  1830      */
  1831     void setParameterNames(MethodSymbol sym, Type jvmType) {
  1832         // if no names were found in the class file, there's nothing more to do
  1833         if (!haveParameterNameIndices)
  1834             return;
  1836         int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
  1837         // the code in readMethod may have skipped the first parameter when
  1838         // setting up the MethodType. If so, we make a corresponding allowance
  1839         // here for the position of the first parameter.  Note that this
  1840         // assumes the skipped parameter has a width of 1 -- i.e. it is not
  1841         // a double width type (long or double.)
  1842         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
  1843             // Sometimes anonymous classes don't have an outer
  1844             // instance, however, there is no reliable way to tell so
  1845             // we never strip this$n
  1846             if (!currentOwner.name.isEmpty())
  1847                 firstParam += 1;
  1850         if (sym.type != jvmType) {
  1851             // reading the method attributes has caused the symbol's type to
  1852             // be changed. (i.e. the Signature attribute.)  This may happen if
  1853             // there are hidden (synthetic) parameters in the descriptor, but
  1854             // not in the Signature.  The position of these hidden parameters
  1855             // is unspecified; for now, assume they are at the beginning, and
  1856             // so skip over them. The primary case for this is two hidden
  1857             // parameters passed into Enum constructors.
  1858             int skip = Code.width(jvmType.getParameterTypes())
  1859                     - Code.width(sym.type.getParameterTypes());
  1860             firstParam += skip;
  1862         List<Name> paramNames = List.nil();
  1863         int index = firstParam;
  1864         for (Type t: sym.type.getParameterTypes()) {
  1865             int nameIdx = (index < parameterNameIndices.length
  1866                     ? parameterNameIndices[index] : 0);
  1867             Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
  1868             paramNames = paramNames.prepend(name);
  1869             index += Code.width(t);
  1871         sym.savedParameterNames = paramNames.reverse();
  1874     /**
  1875      * skip n bytes
  1876      */
  1877     void skipBytes(int n) {
  1878         bp = bp + n;
  1881     /** Skip a field or method
  1882      */
  1883     void skipMember() {
  1884         bp = bp + 6;
  1885         char ac = nextChar();
  1886         for (int i = 0; i < ac; i++) {
  1887             bp = bp + 2;
  1888             int attrLen = nextInt();
  1889             bp = bp + attrLen;
  1893     /** Enter type variables of this classtype and all enclosing ones in
  1894      *  `typevars'.
  1895      */
  1896     protected void enterTypevars(Type t) {
  1897         if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
  1898             enterTypevars(t.getEnclosingType());
  1899         for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
  1900             typevars.enter(xs.head.tsym);
  1903     protected void enterTypevars(Symbol sym) {
  1904         if (sym.owner.kind == MTH) {
  1905             enterTypevars(sym.owner);
  1906             enterTypevars(sym.owner.owner);
  1908         enterTypevars(sym.type);
  1911     /** Read contents of a given class symbol `c'. Both external and internal
  1912      *  versions of an inner class are read.
  1913      */
  1914     void readClass(ClassSymbol c) {
  1915         ClassType ct = (ClassType)c.type;
  1917         // allocate scope for members
  1918         c.members_field = new Scope(c);
  1920         // prepare type variable table
  1921         typevars = typevars.dup(currentOwner);
  1922         if (ct.getEnclosingType().hasTag(CLASS))
  1923             enterTypevars(ct.getEnclosingType());
  1925         // read flags, or skip if this is an inner class
  1926         long flags = adjustClassFlags(nextChar());
  1927         if (c.owner.kind == PCK) c.flags_field = flags;
  1929         // read own class name and check that it matches
  1930         ClassSymbol self = readClassSymbol(nextChar());
  1931         if (c != self)
  1932             throw badClassFile("class.file.wrong.class",
  1933                                self.flatname);
  1935         // class attributes must be read before class
  1936         // skip ahead to read class attributes
  1937         int startbp = bp;
  1938         nextChar();
  1939         char interfaceCount = nextChar();
  1940         bp += interfaceCount * 2;
  1941         char fieldCount = nextChar();
  1942         for (int i = 0; i < fieldCount; i++) skipMember();
  1943         char methodCount = nextChar();
  1944         for (int i = 0; i < methodCount; i++) skipMember();
  1945         readClassAttrs(c);
  1947         if (readAllOfClassFile) {
  1948             for (int i = 1; i < poolObj.length; i++) readPool(i);
  1949             c.pool = new Pool(poolObj.length, poolObj);
  1952         // reset and read rest of classinfo
  1953         bp = startbp;
  1954         int n = nextChar();
  1955         if (ct.supertype_field == null)
  1956             ct.supertype_field = (n == 0)
  1957                 ? Type.noType
  1958                 : readClassSymbol(n).erasure(types);
  1959         n = nextChar();
  1960         List<Type> is = List.nil();
  1961         for (int i = 0; i < n; i++) {
  1962             Type _inter = readClassSymbol(nextChar()).erasure(types);
  1963             is = is.prepend(_inter);
  1965         if (ct.interfaces_field == null)
  1966             ct.interfaces_field = is.reverse();
  1968         Assert.check(fieldCount == nextChar());
  1969         for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
  1970         Assert.check(methodCount == nextChar());
  1971         for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
  1973         typevars = typevars.leave();
  1976     /** Read inner class info. For each inner/outer pair allocate a
  1977      *  member class.
  1978      */
  1979     void readInnerClasses(ClassSymbol c) {
  1980         int n = nextChar();
  1981         for (int i = 0; i < n; i++) {
  1982             nextChar(); // skip inner class symbol
  1983             ClassSymbol outer = readClassSymbol(nextChar());
  1984             Name name = readName(nextChar());
  1985             if (name == null) name = names.empty;
  1986             long flags = adjustClassFlags(nextChar());
  1987             if (outer != null) { // we have a member class
  1988                 if (name == names.empty)
  1989                     name = names.one;
  1990                 ClassSymbol member = enterClass(name, outer);
  1991                 if ((flags & STATIC) == 0) {
  1992                     ((ClassType)member.type).setEnclosingType(outer.type);
  1993                     if (member.erasure_field != null)
  1994                         ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
  1996                 if (c == outer) {
  1997                     member.flags_field = flags;
  1998                     enterMember(c, member);
  2004     /** Read a class file.
  2005      */
  2006     private void readClassFile(ClassSymbol c) throws IOException {
  2007         int magic = nextInt();
  2008         if (magic != JAVA_MAGIC)
  2009             throw badClassFile("illegal.start.of.class.file");
  2011         minorVersion = nextChar();
  2012         majorVersion = nextChar();
  2013         int maxMajor = Target.MAX().majorVersion;
  2014         int maxMinor = Target.MAX().minorVersion;
  2015         if (majorVersion > maxMajor ||
  2016             majorVersion * 1000 + minorVersion <
  2017             Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
  2019             if (majorVersion == (maxMajor + 1))
  2020                 log.warning("big.major.version",
  2021                             currentClassFile,
  2022                             majorVersion,
  2023                             maxMajor);
  2024             else
  2025                 throw badClassFile("wrong.version",
  2026                                    Integer.toString(majorVersion),
  2027                                    Integer.toString(minorVersion),
  2028                                    Integer.toString(maxMajor),
  2029                                    Integer.toString(maxMinor));
  2031         else if (checkClassFile &&
  2032                  majorVersion == maxMajor &&
  2033                  minorVersion > maxMinor)
  2035             printCCF("found.later.version",
  2036                      Integer.toString(minorVersion));
  2038         indexPool();
  2039         if (signatureBuffer.length < bp) {
  2040             int ns = Integer.highestOneBit(bp) << 1;
  2041             signatureBuffer = new byte[ns];
  2043         readClass(c);
  2046 /************************************************************************
  2047  * Adjusting flags
  2048  ***********************************************************************/
  2050     long adjustFieldFlags(long flags) {
  2051         return flags;
  2053     long adjustMethodFlags(long flags) {
  2054         if ((flags & ACC_BRIDGE) != 0) {
  2055             flags &= ~ACC_BRIDGE;
  2056             flags |= BRIDGE;
  2057             if (!allowGenerics)
  2058                 flags &= ~SYNTHETIC;
  2060         if ((flags & ACC_VARARGS) != 0) {
  2061             flags &= ~ACC_VARARGS;
  2062             flags |= VARARGS;
  2064         return flags;
  2066     long adjustClassFlags(long flags) {
  2067         return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
  2070 /************************************************************************
  2071  * Loading Classes
  2072  ***********************************************************************/
  2074     /** Define a new class given its name and owner.
  2075      */
  2076     public ClassSymbol defineClass(Name name, Symbol owner) {
  2077         ClassSymbol c = new ClassSymbol(0, name, owner);
  2078         if (owner.kind == PCK)
  2079             Assert.checkNull(classes.get(c.flatname), c);
  2080         c.completer = this;
  2081         return c;
  2084     /** Create a new toplevel or member class symbol with given name
  2085      *  and owner and enter in `classes' unless already there.
  2086      */
  2087     public ClassSymbol enterClass(Name name, TypeSymbol owner) {
  2088         Name flatname = TypeSymbol.formFlatName(name, owner);
  2089         ClassSymbol c = classes.get(flatname);
  2090         if (c == null) {
  2091             c = defineClass(name, owner);
  2092             classes.put(flatname, c);
  2093         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
  2094             // reassign fields of classes that might have been loaded with
  2095             // their flat names.
  2096             c.owner.members().remove(c);
  2097             c.name = name;
  2098             c.owner = owner;
  2099             c.fullname = ClassSymbol.formFullName(name, owner);
  2101         return c;
  2104     /**
  2105      * Creates a new toplevel class symbol with given flat name and
  2106      * given class (or source) file.
  2108      * @param flatName a fully qualified binary class name
  2109      * @param classFile the class file or compilation unit defining
  2110      * the class (may be {@code null})
  2111      * @return a newly created class symbol
  2112      * @throws AssertionError if the class symbol already exists
  2113      */
  2114     public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
  2115         ClassSymbol cs = classes.get(flatName);
  2116         if (cs != null) {
  2117             String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
  2118                                     cs.fullname,
  2119                                     cs.completer,
  2120                                     cs.classfile,
  2121                                     cs.sourcefile);
  2122             throw new AssertionError(msg);
  2124         Name packageName = Convert.packagePart(flatName);
  2125         PackageSymbol owner = packageName.isEmpty()
  2126                                 ? syms.unnamedPackage
  2127                                 : enterPackage(packageName);
  2128         cs = defineClass(Convert.shortName(flatName), owner);
  2129         cs.classfile = classFile;
  2130         classes.put(flatName, cs);
  2131         return cs;
  2134     /** Create a new member or toplevel class symbol with given flat name
  2135      *  and enter in `classes' unless already there.
  2136      */
  2137     public ClassSymbol enterClass(Name flatname) {
  2138         ClassSymbol c = classes.get(flatname);
  2139         if (c == null)
  2140             return enterClass(flatname, (JavaFileObject)null);
  2141         else
  2142             return c;
  2145     private boolean suppressFlush = false;
  2147     /** Completion for classes to be loaded. Before a class is loaded
  2148      *  we make sure its enclosing class (if any) is loaded.
  2149      */
  2150     public void complete(Symbol sym) throws CompletionFailure {
  2151         if (sym.kind == TYP) {
  2152             ClassSymbol c = (ClassSymbol)sym;
  2153             c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
  2154             boolean saveSuppressFlush = suppressFlush;
  2155             suppressFlush = true;
  2156             try {
  2157                 completeOwners(c.owner);
  2158                 completeEnclosing(c);
  2159             } finally {
  2160                 suppressFlush = saveSuppressFlush;
  2162             fillIn(c);
  2163         } else if (sym.kind == PCK) {
  2164             PackageSymbol p = (PackageSymbol)sym;
  2165             try {
  2166                 fillIn(p);
  2167             } catch (IOException ex) {
  2168                 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
  2171         if (!filling && !suppressFlush)
  2172             annotate.flush(); // finish attaching annotations
  2175     /** complete up through the enclosing package. */
  2176     private void completeOwners(Symbol o) {
  2177         if (o.kind != PCK) completeOwners(o.owner);
  2178         o.complete();
  2181     /**
  2182      * Tries to complete lexically enclosing classes if c looks like a
  2183      * nested class.  This is similar to completeOwners but handles
  2184      * the situation when a nested class is accessed directly as it is
  2185      * possible with the Tree API or javax.lang.model.*.
  2186      */
  2187     private void completeEnclosing(ClassSymbol c) {
  2188         if (c.owner.kind == PCK) {
  2189             Symbol owner = c.owner;
  2190             for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
  2191                 Symbol encl = owner.members().lookup(name).sym;
  2192                 if (encl == null)
  2193                     encl = classes.get(TypeSymbol.formFlatName(name, owner));
  2194                 if (encl != null)
  2195                     encl.complete();
  2200     /** We can only read a single class file at a time; this
  2201      *  flag keeps track of when we are currently reading a class
  2202      *  file.
  2203      */
  2204     private boolean filling = false;
  2206     /** Fill in definition of class `c' from corresponding class or
  2207      *  source file.
  2208      */
  2209     private void fillIn(ClassSymbol c) {
  2210         if (completionFailureName == c.fullname) {
  2211             throw new CompletionFailure(c, "user-selected completion failure by class name");
  2213         currentOwner = c;
  2214         warnedAttrs.clear();
  2215         JavaFileObject classfile = c.classfile;
  2216         if (classfile != null) {
  2217             JavaFileObject previousClassFile = currentClassFile;
  2218             try {
  2219                 if (filling) {
  2220                     Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
  2222                 currentClassFile = classfile;
  2223                 if (verbose) {
  2224                     log.printVerbose("loading", currentClassFile.toString());
  2226                 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
  2227                     filling = true;
  2228                     try {
  2229                         bp = 0;
  2230                         buf = readInputStream(buf, classfile.openInputStream());
  2231                         readClassFile(c);
  2232                         if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
  2233                             List<Type> missing = missingTypeVariables;
  2234                             List<Type> found = foundTypeVariables;
  2235                             missingTypeVariables = List.nil();
  2236                             foundTypeVariables = List.nil();
  2237                             filling = false;
  2238                             ClassType ct = (ClassType)currentOwner.type;
  2239                             ct.supertype_field =
  2240                                 types.subst(ct.supertype_field, missing, found);
  2241                             ct.interfaces_field =
  2242                                 types.subst(ct.interfaces_field, missing, found);
  2243                         } else if (missingTypeVariables.isEmpty() !=
  2244                                    foundTypeVariables.isEmpty()) {
  2245                             Name name = missingTypeVariables.head.tsym.name;
  2246                             throw badClassFile("undecl.type.var", name);
  2248                     } finally {
  2249                         missingTypeVariables = List.nil();
  2250                         foundTypeVariables = List.nil();
  2251                         filling = false;
  2253                 } else {
  2254                     if (sourceCompleter != null) {
  2255                         sourceCompleter.complete(c);
  2256                     } else {
  2257                         throw new IllegalStateException("Source completer required to read "
  2258                                                         + classfile.toUri());
  2261                 return;
  2262             } catch (IOException ex) {
  2263                 throw badClassFile("unable.to.access.file", ex.getMessage());
  2264             } finally {
  2265                 currentClassFile = previousClassFile;
  2267         } else {
  2268             JCDiagnostic diag =
  2269                 diagFactory.fragment("class.file.not.found", c.flatname);
  2270             throw
  2271                 newCompletionFailure(c, diag);
  2274     // where
  2275         private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
  2276             try {
  2277                 buf = ensureCapacity(buf, s.available());
  2278                 int r = s.read(buf);
  2279                 int bp = 0;
  2280                 while (r != -1) {
  2281                     bp += r;
  2282                     buf = ensureCapacity(buf, bp);
  2283                     r = s.read(buf, bp, buf.length - bp);
  2285                 return buf;
  2286             } finally {
  2287                 try {
  2288                     s.close();
  2289                 } catch (IOException e) {
  2290                     /* Ignore any errors, as this stream may have already
  2291                      * thrown a related exception which is the one that
  2292                      * should be reported.
  2293                      */
  2297         /*
  2298          * ensureCapacity will increase the buffer as needed, taking note that
  2299          * the new buffer will always be greater than the needed and never
  2300          * exactly equal to the needed size or bp. If equal then the read (above)
  2301          * will infinitely loop as buf.length - bp == 0.
  2302          */
  2303         private static byte[] ensureCapacity(byte[] buf, int needed) {
  2304             if (buf.length <= needed) {
  2305                 byte[] old = buf;
  2306                 buf = new byte[Integer.highestOneBit(needed) << 1];
  2307                 System.arraycopy(old, 0, buf, 0, old.length);
  2309             return buf;
  2311         /** Static factory for CompletionFailure objects.
  2312          *  In practice, only one can be used at a time, so we share one
  2313          *  to reduce the expense of allocating new exception objects.
  2314          */
  2315         private CompletionFailure newCompletionFailure(TypeSymbol c,
  2316                                                        JCDiagnostic diag) {
  2317             if (!cacheCompletionFailure) {
  2318                 // log.warning("proc.messager",
  2319                 //             Log.getLocalizedString("class.file.not.found", c.flatname));
  2320                 // c.debug.printStackTrace();
  2321                 return new CompletionFailure(c, diag);
  2322             } else {
  2323                 CompletionFailure result = cachedCompletionFailure;
  2324                 result.sym = c;
  2325                 result.diag = diag;
  2326                 return result;
  2329         private CompletionFailure cachedCompletionFailure =
  2330             new CompletionFailure(null, (JCDiagnostic) null);
  2332             cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
  2335     /** Load a toplevel class with given fully qualified name
  2336      *  The class is entered into `classes' only if load was successful.
  2337      */
  2338     public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
  2339         boolean absent = classes.get(flatname) == null;
  2340         ClassSymbol c = enterClass(flatname);
  2341         if (c.members_field == null && c.completer != null) {
  2342             try {
  2343                 c.complete();
  2344             } catch (CompletionFailure ex) {
  2345                 if (absent) classes.remove(flatname);
  2346                 throw ex;
  2349         return c;
  2352 /************************************************************************
  2353  * Loading Packages
  2354  ***********************************************************************/
  2356     /** Check to see if a package exists, given its fully qualified name.
  2357      */
  2358     public boolean packageExists(Name fullname) {
  2359         return enterPackage(fullname).exists();
  2362     /** Make a package, given its fully qualified name.
  2363      */
  2364     public PackageSymbol enterPackage(Name fullname) {
  2365         PackageSymbol p = packages.get(fullname);
  2366         if (p == null) {
  2367             Assert.check(!fullname.isEmpty(), "rootPackage missing!");
  2368             p = new PackageSymbol(
  2369                 Convert.shortName(fullname),
  2370                 enterPackage(Convert.packagePart(fullname)));
  2371             p.completer = this;
  2372             packages.put(fullname, p);
  2374         return p;
  2377     /** Make a package, given its unqualified name and enclosing package.
  2378      */
  2379     public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
  2380         return enterPackage(TypeSymbol.formFullName(name, owner));
  2383     /** Include class corresponding to given class file in package,
  2384      *  unless (1) we already have one the same kind (.class or .java), or
  2385      *         (2) we have one of the other kind, and the given class file
  2386      *             is older.
  2387      */
  2388     protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
  2389         if ((p.flags_field & EXISTS) == 0)
  2390             for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
  2391                 q.flags_field |= EXISTS;
  2392         JavaFileObject.Kind kind = file.getKind();
  2393         int seen;
  2394         if (kind == JavaFileObject.Kind.CLASS)
  2395             seen = CLASS_SEEN;
  2396         else
  2397             seen = SOURCE_SEEN;
  2398         String binaryName = fileManager.inferBinaryName(currentLoc, file);
  2399         int lastDot = binaryName.lastIndexOf(".");
  2400         Name classname = names.fromString(binaryName.substring(lastDot + 1));
  2401         boolean isPkgInfo = classname == names.package_info;
  2402         ClassSymbol c = isPkgInfo
  2403             ? p.package_info
  2404             : (ClassSymbol) p.members_field.lookup(classname).sym;
  2405         if (c == null) {
  2406             c = enterClass(classname, p);
  2407             if (c.classfile == null) // only update the file if's it's newly created
  2408                 c.classfile = file;
  2409             if (isPkgInfo) {
  2410                 p.package_info = c;
  2411             } else {
  2412                 if (c.owner == p)  // it might be an inner class
  2413                     p.members_field.enter(c);
  2415         } else if (c.classfile != null && (c.flags_field & seen) == 0) {
  2416             // if c.classfile == null, we are currently compiling this class
  2417             // and no further action is necessary.
  2418             // if (c.flags_field & seen) != 0, we have already encountered
  2419             // a file of the same kind; again no further action is necessary.
  2420             if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
  2421                 c.classfile = preferredFileObject(file, c.classfile);
  2423         c.flags_field |= seen;
  2426     /** Implement policy to choose to derive information from a source
  2427      *  file or a class file when both are present.  May be overridden
  2428      *  by subclasses.
  2429      */
  2430     protected JavaFileObject preferredFileObject(JavaFileObject a,
  2431                                            JavaFileObject b) {
  2433         if (preferSource)
  2434             return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
  2435         else {
  2436             long adate = a.getLastModified();
  2437             long bdate = b.getLastModified();
  2438             // 6449326: policy for bad lastModifiedTime in ClassReader
  2439             //assert adate >= 0 && bdate >= 0;
  2440             return (adate > bdate) ? a : b;
  2444     /**
  2445      * specifies types of files to be read when filling in a package symbol
  2446      */
  2447     protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
  2448         return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
  2451     /**
  2452      * this is used to support javadoc
  2453      */
  2454     protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
  2457     protected Location currentLoc; // FIXME
  2459     private boolean verbosePath = true;
  2461     /** Load directory of package into members scope.
  2462      */
  2463     private void fillIn(PackageSymbol p) throws IOException {
  2464         if (p.members_field == null) p.members_field = new Scope(p);
  2465         String packageName = p.fullname.toString();
  2467         Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
  2469         fillIn(p, PLATFORM_CLASS_PATH,
  2470                fileManager.list(PLATFORM_CLASS_PATH,
  2471                                 packageName,
  2472                                 EnumSet.of(JavaFileObject.Kind.CLASS),
  2473                                 false));
  2475         Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
  2476         classKinds.remove(JavaFileObject.Kind.SOURCE);
  2477         boolean wantClassFiles = !classKinds.isEmpty();
  2479         Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
  2480         sourceKinds.remove(JavaFileObject.Kind.CLASS);
  2481         boolean wantSourceFiles = !sourceKinds.isEmpty();
  2483         boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
  2485         if (verbose && verbosePath) {
  2486             if (fileManager instanceof StandardJavaFileManager) {
  2487                 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
  2488                 if (haveSourcePath && wantSourceFiles) {
  2489                     List<File> path = List.nil();
  2490                     for (File file : fm.getLocation(SOURCE_PATH)) {
  2491                         path = path.prepend(file);
  2493                     log.printVerbose("sourcepath", path.reverse().toString());
  2494                 } else if (wantSourceFiles) {
  2495                     List<File> path = List.nil();
  2496                     for (File file : fm.getLocation(CLASS_PATH)) {
  2497                         path = path.prepend(file);
  2499                     log.printVerbose("sourcepath", path.reverse().toString());
  2501                 if (wantClassFiles) {
  2502                     List<File> path = List.nil();
  2503                     for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
  2504                         path = path.prepend(file);
  2506                     for (File file : fm.getLocation(CLASS_PATH)) {
  2507                         path = path.prepend(file);
  2509                     log.printVerbose("classpath",  path.reverse().toString());
  2514         if (wantSourceFiles && !haveSourcePath) {
  2515             fillIn(p, CLASS_PATH,
  2516                    fileManager.list(CLASS_PATH,
  2517                                     packageName,
  2518                                     kinds,
  2519                                     false));
  2520         } else {
  2521             if (wantClassFiles)
  2522                 fillIn(p, CLASS_PATH,
  2523                        fileManager.list(CLASS_PATH,
  2524                                         packageName,
  2525                                         classKinds,
  2526                                         false));
  2527             if (wantSourceFiles)
  2528                 fillIn(p, SOURCE_PATH,
  2529                        fileManager.list(SOURCE_PATH,
  2530                                         packageName,
  2531                                         sourceKinds,
  2532                                         false));
  2534         verbosePath = false;
  2536     // where
  2537         private void fillIn(PackageSymbol p,
  2538                             Location location,
  2539                             Iterable<JavaFileObject> files)
  2541             currentLoc = location;
  2542             for (JavaFileObject fo : files) {
  2543                 switch (fo.getKind()) {
  2544                 case CLASS:
  2545                 case SOURCE: {
  2546                     // TODO pass binaryName to includeClassFile
  2547                     String binaryName = fileManager.inferBinaryName(currentLoc, fo);
  2548                     String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
  2549                     if (SourceVersion.isIdentifier(simpleName) ||
  2550                         simpleName.equals("package-info"))
  2551                         includeClassFile(p, fo);
  2552                     break;
  2554                 default:
  2555                     extraFileActions(p, fo);
  2560     /** Output for "-checkclassfile" option.
  2561      *  @param key The key to look up the correct internationalized string.
  2562      *  @param arg An argument for substitution into the output string.
  2563      */
  2564     private void printCCF(String key, Object arg) {
  2565         log.printLines(key, arg);
  2569     public interface SourceCompleter {
  2570         void complete(ClassSymbol sym)
  2571             throws CompletionFailure;
  2574     /**
  2575      * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
  2576      * The attribute is only the last component of the original filename, so is unlikely
  2577      * to be valid as is, so operations other than those to access the name throw
  2578      * UnsupportedOperationException
  2579      */
  2580     private static class SourceFileObject extends BaseFileObject {
  2582         /** The file's name.
  2583          */
  2584         private Name name;
  2585         private Name flatname;
  2587         public SourceFileObject(Name name, Name flatname) {
  2588             super(null); // no file manager; never referenced for this file object
  2589             this.name = name;
  2590             this.flatname = flatname;
  2593         @Override
  2594         public URI toUri() {
  2595             try {
  2596                 return new URI(null, name.toString(), null);
  2597             } catch (URISyntaxException e) {
  2598                 throw new CannotCreateUriError(name.toString(), e);
  2602         @Override
  2603         public String getName() {
  2604             return name.toString();
  2607         @Override
  2608         public String getShortName() {
  2609             return getName();
  2612         @Override
  2613         public JavaFileObject.Kind getKind() {
  2614             return getKind(getName());
  2617         @Override
  2618         public InputStream openInputStream() {
  2619             throw new UnsupportedOperationException();
  2622         @Override
  2623         public OutputStream openOutputStream() {
  2624             throw new UnsupportedOperationException();
  2627         @Override
  2628         public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
  2629             throw new UnsupportedOperationException();
  2632         @Override
  2633         public Reader openReader(boolean ignoreEncodingErrors) {
  2634             throw new UnsupportedOperationException();
  2637         @Override
  2638         public Writer openWriter() {
  2639             throw new UnsupportedOperationException();
  2642         @Override
  2643         public long getLastModified() {
  2644             throw new UnsupportedOperationException();
  2647         @Override
  2648         public boolean delete() {
  2649             throw new UnsupportedOperationException();
  2652         @Override
  2653         protected String inferBinaryName(Iterable<? extends File> path) {
  2654             return flatname.toString();
  2657         @Override
  2658         public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
  2659             return true; // fail-safe mode
  2662         /**
  2663          * Check if two file objects are equal.
  2664          * SourceFileObjects are just placeholder objects for the value of a
  2665          * SourceFile attribute, and do not directly represent specific files.
  2666          * Two SourceFileObjects are equal if their names are equal.
  2667          */
  2668         @Override
  2669         public boolean equals(Object other) {
  2670             if (this == other)
  2671                 return true;
  2673             if (!(other instanceof SourceFileObject))
  2674                 return false;
  2676             SourceFileObject o = (SourceFileObject) other;
  2677             return name.equals(o.name);
  2680         @Override
  2681         public int hashCode() {
  2682             return name.hashCode();

mercurial