Tue, 28 Dec 2010 15:54:52 -0800
6962318: Update copyright year
Reviewed-by: xdono
1 /*
2 * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.jvm;
28 import java.io.*;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.CharBuffer;
32 import java.util.Arrays;
33 import java.util.EnumSet;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Map;
37 import java.util.Set;
38 import javax.lang.model.SourceVersion;
39 import javax.tools.JavaFileObject;
40 import javax.tools.JavaFileManager;
41 import javax.tools.JavaFileManager.Location;
42 import javax.tools.StandardJavaFileManager;
44 import static javax.tools.StandardLocation.*;
46 import com.sun.tools.javac.comp.Annotate;
47 import com.sun.tools.javac.code.*;
48 import com.sun.tools.javac.code.Lint.LintCategory;
49 import com.sun.tools.javac.code.Type.*;
50 import com.sun.tools.javac.code.Symbol.*;
51 import com.sun.tools.javac.code.Symtab;
52 import com.sun.tools.javac.file.BaseFileObject;
53 import com.sun.tools.javac.util.*;
54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
56 import static com.sun.tools.javac.code.Flags.*;
57 import static com.sun.tools.javac.code.Kinds.*;
58 import static com.sun.tools.javac.code.TypeTags.*;
59 import static com.sun.tools.javac.jvm.ClassFile.*;
60 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
62 import static com.sun.tools.javac.main.OptionName.*;
64 /** This class provides operations to read a classfile into an internal
65 * representation. The internal representation is anchored in a
66 * ClassSymbol which contains in its scope symbol representations
67 * for all other definitions in the classfile. Top-level Classes themselves
68 * appear as members of the scopes of PackageSymbols.
69 *
70 * <p><b>This is NOT part of any supported API.
71 * If you write code that depends on this, you do so at your own risk.
72 * This code and its internal interfaces are subject to change or
73 * deletion without notice.</b>
74 */
75 public class ClassReader implements Completer {
76 /** The context key for the class reader. */
77 protected static final Context.Key<ClassReader> classReaderKey =
78 new Context.Key<ClassReader>();
80 Annotate annotate;
82 /** Switch: verbose output.
83 */
84 boolean verbose;
86 /** Switch: check class file for correct minor version, unrecognized
87 * attributes.
88 */
89 boolean checkClassFile;
91 /** Switch: read constant pool and code sections. This switch is initially
92 * set to false but can be turned on from outside.
93 */
94 public boolean readAllOfClassFile = false;
96 /** Switch: read GJ signature information.
97 */
98 boolean allowGenerics;
100 /** Switch: read varargs attribute.
101 */
102 boolean allowVarargs;
104 /** Switch: allow annotations.
105 */
106 boolean allowAnnotations;
108 /** Switch: allow simplified varargs.
109 */
110 boolean allowSimplifiedVarargs;
112 /** Lint option: warn about classfile issues
113 */
114 boolean lintClassfile;
117 /** Switch: preserve parameter names from the variable table.
118 */
119 public boolean saveParameterNames;
121 /**
122 * Switch: cache completion failures unless -XDdev is used
123 */
124 private boolean cacheCompletionFailure;
126 /**
127 * Switch: prefer source files instead of newer when both source
128 * and class are available
129 **/
130 public boolean preferSource;
132 /** The log to use for verbose output
133 */
134 final Log log;
136 /** The symbol table. */
137 Symtab syms;
139 /** The scope counter */
140 Scope.ScopeCounter scopeCounter;
142 Types types;
144 /** The name table. */
145 final Names names;
147 /** Force a completion failure on this name
148 */
149 final Name completionFailureName;
151 /** Access to files
152 */
153 private final JavaFileManager fileManager;
155 /** Factory for diagnostics
156 */
157 JCDiagnostic.Factory diagFactory;
159 /** Can be reassigned from outside:
160 * the completer to be used for ".java" files. If this remains unassigned
161 * ".java" files will not be loaded.
162 */
163 public SourceCompleter sourceCompleter = null;
165 /** A hashtable containing the encountered top-level and member classes,
166 * indexed by flat names. The table does not contain local classes.
167 */
168 private Map<Name,ClassSymbol> classes;
170 /** A hashtable containing the encountered packages.
171 */
172 private Map<Name, PackageSymbol> packages;
174 /** The current scope where type variables are entered.
175 */
176 protected Scope typevars;
178 /** The path name of the class file currently being read.
179 */
180 protected JavaFileObject currentClassFile = null;
182 /** The class or method currently being read.
183 */
184 protected Symbol currentOwner = null;
186 /** The buffer containing the currently read class file.
187 */
188 byte[] buf = new byte[0x0fff0];
190 /** The current input pointer.
191 */
192 int bp;
194 /** The objects of the constant pool.
195 */
196 Object[] poolObj;
198 /** For every constant pool entry, an index into buf where the
199 * defining section of the entry is found.
200 */
201 int[] poolIdx;
203 /** The major version number of the class file being read. */
204 int majorVersion;
205 /** The minor version number of the class file being read. */
206 int minorVersion;
208 /** Switch: debug output for JSR 308-related operations.
209 */
210 boolean debugJSR308;
212 /** A table to hold the constant pool indices for method parameter
213 * names, as given in LocalVariableTable attributes.
214 */
215 int[] parameterNameIndices;
217 /**
218 * Whether or not any parameter names have been found.
219 */
220 boolean haveParameterNameIndices;
222 /**
223 * The set of attribute names for which warnings have been generated for the current class
224 */
225 Set<Name> warnedAttrs = new HashSet<Name>();
227 /** Get the ClassReader instance for this invocation. */
228 public static ClassReader instance(Context context) {
229 ClassReader instance = context.get(classReaderKey);
230 if (instance == null)
231 instance = new ClassReader(context, true);
232 return instance;
233 }
235 /** Initialize classes and packages, treating this as the definitive classreader. */
236 public void init(Symtab syms) {
237 init(syms, true);
238 }
240 /** Initialize classes and packages, optionally treating this as
241 * the definitive classreader.
242 */
243 private void init(Symtab syms, boolean definitive) {
244 if (classes != null) return;
246 if (definitive) {
247 assert packages == null || packages == syms.packages;
248 packages = syms.packages;
249 assert classes == null || classes == syms.classes;
250 classes = syms.classes;
251 } else {
252 packages = new HashMap<Name, PackageSymbol>();
253 classes = new HashMap<Name, ClassSymbol>();
254 }
256 packages.put(names.empty, syms.rootPackage);
257 syms.rootPackage.completer = this;
258 syms.unnamedPackage.completer = this;
259 }
261 /** Construct a new class reader, optionally treated as the
262 * definitive classreader for this invocation.
263 */
264 protected ClassReader(Context context, boolean definitive) {
265 if (definitive) context.put(classReaderKey, this);
267 names = Names.instance(context);
268 syms = Symtab.instance(context);
269 scopeCounter = Scope.ScopeCounter.instance(context);
270 types = Types.instance(context);
271 fileManager = context.get(JavaFileManager.class);
272 if (fileManager == null)
273 throw new AssertionError("FileManager initialization error");
274 diagFactory = JCDiagnostic.Factory.instance(context);
276 init(syms, definitive);
277 log = Log.instance(context);
279 Options options = Options.instance(context);
280 annotate = Annotate.instance(context);
281 verbose = options.isSet(VERBOSE);
282 checkClassFile = options.isSet("-checkclassfile");
283 Source source = Source.instance(context);
284 allowGenerics = source.allowGenerics();
285 allowVarargs = source.allowVarargs();
286 allowAnnotations = source.allowAnnotations();
287 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
288 saveParameterNames = options.isSet("save-parameter-names");
289 cacheCompletionFailure = options.isUnset("dev");
290 preferSource = "source".equals(options.get("-Xprefer"));
292 completionFailureName =
293 options.isSet("failcomplete")
294 ? names.fromString(options.get("failcomplete"))
295 : null;
297 typevars = new Scope(syms.noSymbol);
298 debugJSR308 = options.isSet("TA:reader");
300 lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
302 initAttributeReaders();
303 }
305 /** Add member to class unless it is synthetic.
306 */
307 private void enterMember(ClassSymbol c, Symbol sym) {
308 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
309 c.members_field.enter(sym);
310 }
312 /************************************************************************
313 * Error Diagnoses
314 ***********************************************************************/
317 public class BadClassFile extends CompletionFailure {
318 private static final long serialVersionUID = 0;
320 public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
321 super(sym, createBadClassFileDiagnostic(file, diag));
322 }
323 }
324 // where
325 private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
326 String key = (file.getKind() == JavaFileObject.Kind.SOURCE
327 ? "bad.source.file.header" : "bad.class.file.header");
328 return diagFactory.fragment(key, file, diag);
329 }
331 public BadClassFile badClassFile(String key, Object... args) {
332 return new BadClassFile (
333 currentOwner.enclClass(),
334 currentClassFile,
335 diagFactory.fragment(key, args));
336 }
338 /************************************************************************
339 * Buffer Access
340 ***********************************************************************/
342 /** Read a character.
343 */
344 char nextChar() {
345 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
346 }
348 /** Read a byte.
349 */
350 byte nextByte() {
351 return buf[bp++];
352 }
354 /** Read an integer.
355 */
356 int nextInt() {
357 return
358 ((buf[bp++] & 0xFF) << 24) +
359 ((buf[bp++] & 0xFF) << 16) +
360 ((buf[bp++] & 0xFF) << 8) +
361 (buf[bp++] & 0xFF);
362 }
364 /** Extract a character at position bp from buf.
365 */
366 char getChar(int bp) {
367 return
368 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
369 }
371 /** Extract an integer at position bp from buf.
372 */
373 int getInt(int bp) {
374 return
375 ((buf[bp] & 0xFF) << 24) +
376 ((buf[bp+1] & 0xFF) << 16) +
377 ((buf[bp+2] & 0xFF) << 8) +
378 (buf[bp+3] & 0xFF);
379 }
382 /** Extract a long integer at position bp from buf.
383 */
384 long getLong(int bp) {
385 DataInputStream bufin =
386 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
387 try {
388 return bufin.readLong();
389 } catch (IOException e) {
390 throw new AssertionError(e);
391 }
392 }
394 /** Extract a float at position bp from buf.
395 */
396 float getFloat(int bp) {
397 DataInputStream bufin =
398 new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
399 try {
400 return bufin.readFloat();
401 } catch (IOException e) {
402 throw new AssertionError(e);
403 }
404 }
406 /** Extract a double at position bp from buf.
407 */
408 double getDouble(int bp) {
409 DataInputStream bufin =
410 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
411 try {
412 return bufin.readDouble();
413 } catch (IOException e) {
414 throw new AssertionError(e);
415 }
416 }
418 /************************************************************************
419 * Constant Pool Access
420 ***********************************************************************/
422 /** Index all constant pool entries, writing their start addresses into
423 * poolIdx.
424 */
425 void indexPool() {
426 poolIdx = new int[nextChar()];
427 poolObj = new Object[poolIdx.length];
428 int i = 1;
429 while (i < poolIdx.length) {
430 poolIdx[i++] = bp;
431 byte tag = buf[bp++];
432 switch (tag) {
433 case CONSTANT_Utf8: case CONSTANT_Unicode: {
434 int len = nextChar();
435 bp = bp + len;
436 break;
437 }
438 case CONSTANT_Class:
439 case CONSTANT_String:
440 bp = bp + 2;
441 break;
442 case CONSTANT_Fieldref:
443 case CONSTANT_Methodref:
444 case CONSTANT_InterfaceMethodref:
445 case CONSTANT_NameandType:
446 case CONSTANT_Integer:
447 case CONSTANT_Float:
448 bp = bp + 4;
449 break;
450 case CONSTANT_Long:
451 case CONSTANT_Double:
452 bp = bp + 8;
453 i++;
454 break;
455 default:
456 throw badClassFile("bad.const.pool.tag.at",
457 Byte.toString(tag),
458 Integer.toString(bp -1));
459 }
460 }
461 }
463 /** Read constant pool entry at start address i, use pool as a cache.
464 */
465 Object readPool(int i) {
466 Object result = poolObj[i];
467 if (result != null) return result;
469 int index = poolIdx[i];
470 if (index == 0) return null;
472 byte tag = buf[index];
473 switch (tag) {
474 case CONSTANT_Utf8:
475 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
476 break;
477 case CONSTANT_Unicode:
478 throw badClassFile("unicode.str.not.supported");
479 case CONSTANT_Class:
480 poolObj[i] = readClassOrType(getChar(index + 1));
481 break;
482 case CONSTANT_String:
483 // FIXME: (footprint) do not use toString here
484 poolObj[i] = readName(getChar(index + 1)).toString();
485 break;
486 case CONSTANT_Fieldref: {
487 ClassSymbol owner = readClassSymbol(getChar(index + 1));
488 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
489 poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
490 break;
491 }
492 case CONSTANT_Methodref:
493 case CONSTANT_InterfaceMethodref: {
494 ClassSymbol owner = readClassSymbol(getChar(index + 1));
495 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
496 poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
497 break;
498 }
499 case CONSTANT_NameandType:
500 poolObj[i] = new NameAndType(
501 readName(getChar(index + 1)),
502 readType(getChar(index + 3)));
503 break;
504 case CONSTANT_Integer:
505 poolObj[i] = getInt(index + 1);
506 break;
507 case CONSTANT_Float:
508 poolObj[i] = new Float(getFloat(index + 1));
509 break;
510 case CONSTANT_Long:
511 poolObj[i] = new Long(getLong(index + 1));
512 break;
513 case CONSTANT_Double:
514 poolObj[i] = new Double(getDouble(index + 1));
515 break;
516 default:
517 throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
518 }
519 return poolObj[i];
520 }
522 /** Read signature and convert to type.
523 */
524 Type readType(int i) {
525 int index = poolIdx[i];
526 return sigToType(buf, index + 3, getChar(index + 1));
527 }
529 /** If name is an array type or class signature, return the
530 * corresponding type; otherwise return a ClassSymbol with given name.
531 */
532 Object readClassOrType(int i) {
533 int index = poolIdx[i];
534 int len = getChar(index + 1);
535 int start = index + 3;
536 assert buf[start] == '[' || buf[start + len - 1] != ';';
537 // by the above assertion, the following test can be
538 // simplified to (buf[start] == '[')
539 return (buf[start] == '[' || buf[start + len - 1] == ';')
540 ? (Object)sigToType(buf, start, len)
541 : (Object)enterClass(names.fromUtf(internalize(buf, start,
542 len)));
543 }
545 /** Read signature and convert to type parameters.
546 */
547 List<Type> readTypeParams(int i) {
548 int index = poolIdx[i];
549 return sigToTypeParams(buf, index + 3, getChar(index + 1));
550 }
552 /** Read class entry.
553 */
554 ClassSymbol readClassSymbol(int i) {
555 return (ClassSymbol) (readPool(i));
556 }
558 /** Read name.
559 */
560 Name readName(int i) {
561 return (Name) (readPool(i));
562 }
564 /************************************************************************
565 * Reading Types
566 ***********************************************************************/
568 /** The unread portion of the currently read type is
569 * signature[sigp..siglimit-1].
570 */
571 byte[] signature;
572 int sigp;
573 int siglimit;
574 boolean sigEnterPhase = false;
576 /** Convert signature to type, where signature is a byte array segment.
577 */
578 Type sigToType(byte[] sig, int offset, int len) {
579 signature = sig;
580 sigp = offset;
581 siglimit = offset + len;
582 return sigToType();
583 }
585 /** Convert signature to type, where signature is implicit.
586 */
587 Type sigToType() {
588 switch ((char) signature[sigp]) {
589 case 'T':
590 sigp++;
591 int start = sigp;
592 while (signature[sigp] != ';') sigp++;
593 sigp++;
594 return sigEnterPhase
595 ? Type.noType
596 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
597 case '+': {
598 sigp++;
599 Type t = sigToType();
600 return new WildcardType(t, BoundKind.EXTENDS,
601 syms.boundClass);
602 }
603 case '*':
604 sigp++;
605 return new WildcardType(syms.objectType, BoundKind.UNBOUND,
606 syms.boundClass);
607 case '-': {
608 sigp++;
609 Type t = sigToType();
610 return new WildcardType(t, BoundKind.SUPER,
611 syms.boundClass);
612 }
613 case 'B':
614 sigp++;
615 return syms.byteType;
616 case 'C':
617 sigp++;
618 return syms.charType;
619 case 'D':
620 sigp++;
621 return syms.doubleType;
622 case 'F':
623 sigp++;
624 return syms.floatType;
625 case 'I':
626 sigp++;
627 return syms.intType;
628 case 'J':
629 sigp++;
630 return syms.longType;
631 case 'L':
632 {
633 // int oldsigp = sigp;
634 Type t = classSigToType();
635 if (sigp < siglimit && signature[sigp] == '.')
636 throw badClassFile("deprecated inner class signature syntax " +
637 "(please recompile from source)");
638 /*
639 System.err.println(" decoded " +
640 new String(signature, oldsigp, sigp-oldsigp) +
641 " => " + t + " outer " + t.outer());
642 */
643 return t;
644 }
645 case 'S':
646 sigp++;
647 return syms.shortType;
648 case 'V':
649 sigp++;
650 return syms.voidType;
651 case 'Z':
652 sigp++;
653 return syms.booleanType;
654 case '[':
655 sigp++;
656 return new ArrayType(sigToType(), syms.arrayClass);
657 case '(':
658 sigp++;
659 List<Type> argtypes = sigToTypes(')');
660 Type restype = sigToType();
661 List<Type> thrown = List.nil();
662 while (signature[sigp] == '^') {
663 sigp++;
664 thrown = thrown.prepend(sigToType());
665 }
666 return new MethodType(argtypes,
667 restype,
668 thrown.reverse(),
669 syms.methodClass);
670 case '<':
671 typevars = typevars.dup(currentOwner);
672 Type poly = new ForAll(sigToTypeParams(), sigToType());
673 typevars = typevars.leave();
674 return poly;
675 default:
676 throw badClassFile("bad.signature",
677 Convert.utf2string(signature, sigp, 10));
678 }
679 }
681 byte[] signatureBuffer = new byte[0];
682 int sbp = 0;
683 /** Convert class signature to type, where signature is implicit.
684 */
685 Type classSigToType() {
686 if (signature[sigp] != 'L')
687 throw badClassFile("bad.class.signature",
688 Convert.utf2string(signature, sigp, 10));
689 sigp++;
690 Type outer = Type.noType;
691 int startSbp = sbp;
693 while (true) {
694 final byte c = signature[sigp++];
695 switch (c) {
697 case ';': { // end
698 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
699 startSbp,
700 sbp - startSbp));
701 if (outer == Type.noType)
702 outer = t.erasure(types);
703 else
704 outer = new ClassType(outer, List.<Type>nil(), t);
705 sbp = startSbp;
706 return outer;
707 }
709 case '<': // generic arguments
710 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
711 startSbp,
712 sbp - startSbp));
713 outer = new ClassType(outer, sigToTypes('>'), t) {
714 boolean completed = false;
715 @Override
716 public Type getEnclosingType() {
717 if (!completed) {
718 completed = true;
719 tsym.complete();
720 Type enclosingType = tsym.type.getEnclosingType();
721 if (enclosingType != Type.noType) {
722 List<Type> typeArgs =
723 super.getEnclosingType().allparams();
724 List<Type> typeParams =
725 enclosingType.allparams();
726 if (typeParams.length() != typeArgs.length()) {
727 // no "rare" types
728 super.setEnclosingType(types.erasure(enclosingType));
729 } else {
730 super.setEnclosingType(types.subst(enclosingType,
731 typeParams,
732 typeArgs));
733 }
734 } else {
735 super.setEnclosingType(Type.noType);
736 }
737 }
738 return super.getEnclosingType();
739 }
740 @Override
741 public void setEnclosingType(Type outer) {
742 throw new UnsupportedOperationException();
743 }
744 };
745 switch (signature[sigp++]) {
746 case ';':
747 if (sigp < signature.length && signature[sigp] == '.') {
748 // support old-style GJC signatures
749 // The signature produced was
750 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
751 // rather than say
752 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
753 // so we skip past ".Lfoo/Outer$"
754 sigp += (sbp - startSbp) + // "foo/Outer"
755 3; // ".L" and "$"
756 signatureBuffer[sbp++] = (byte)'$';
757 break;
758 } else {
759 sbp = startSbp;
760 return outer;
761 }
762 case '.':
763 signatureBuffer[sbp++] = (byte)'$';
764 break;
765 default:
766 throw new AssertionError(signature[sigp-1]);
767 }
768 continue;
770 case '.':
771 signatureBuffer[sbp++] = (byte)'$';
772 continue;
773 case '/':
774 signatureBuffer[sbp++] = (byte)'.';
775 continue;
776 default:
777 signatureBuffer[sbp++] = c;
778 continue;
779 }
780 }
781 }
783 /** Convert (implicit) signature to list of types
784 * until `terminator' is encountered.
785 */
786 List<Type> sigToTypes(char terminator) {
787 List<Type> head = List.of(null);
788 List<Type> tail = head;
789 while (signature[sigp] != terminator)
790 tail = tail.setTail(List.of(sigToType()));
791 sigp++;
792 return head.tail;
793 }
795 /** Convert signature to type parameters, where signature is a byte
796 * array segment.
797 */
798 List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
799 signature = sig;
800 sigp = offset;
801 siglimit = offset + len;
802 return sigToTypeParams();
803 }
805 /** Convert signature to type parameters, where signature is implicit.
806 */
807 List<Type> sigToTypeParams() {
808 List<Type> tvars = List.nil();
809 if (signature[sigp] == '<') {
810 sigp++;
811 int start = sigp;
812 sigEnterPhase = true;
813 while (signature[sigp] != '>')
814 tvars = tvars.prepend(sigToTypeParam());
815 sigEnterPhase = false;
816 sigp = start;
817 while (signature[sigp] != '>')
818 sigToTypeParam();
819 sigp++;
820 }
821 return tvars.reverse();
822 }
824 /** Convert (implicit) signature to type parameter.
825 */
826 Type sigToTypeParam() {
827 int start = sigp;
828 while (signature[sigp] != ':') sigp++;
829 Name name = names.fromUtf(signature, start, sigp - start);
830 TypeVar tvar;
831 if (sigEnterPhase) {
832 tvar = new TypeVar(name, currentOwner, syms.botType);
833 typevars.enter(tvar.tsym);
834 } else {
835 tvar = (TypeVar)findTypeVar(name);
836 }
837 List<Type> bounds = List.nil();
838 Type st = null;
839 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
840 sigp++;
841 st = syms.objectType;
842 }
843 while (signature[sigp] == ':') {
844 sigp++;
845 bounds = bounds.prepend(sigToType());
846 }
847 if (!sigEnterPhase) {
848 types.setBounds(tvar, bounds.reverse(), st);
849 }
850 return tvar;
851 }
853 /** Find type variable with given name in `typevars' scope.
854 */
855 Type findTypeVar(Name name) {
856 Scope.Entry e = typevars.lookup(name);
857 if (e.scope != null) {
858 return e.sym.type;
859 } else {
860 if (readingClassAttr) {
861 // While reading the class attribute, the supertypes
862 // might refer to a type variable from an enclosing element
863 // (method or class).
864 // If the type variable is defined in the enclosing class,
865 // we can actually find it in
866 // currentOwner.owner.type.getTypeArguments()
867 // However, until we have read the enclosing method attribute
868 // we don't know for sure if this owner is correct. It could
869 // be a method and there is no way to tell before reading the
870 // enclosing method attribute.
871 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
872 missingTypeVariables = missingTypeVariables.prepend(t);
873 // System.err.println("Missing type var " + name);
874 return t;
875 }
876 throw badClassFile("undecl.type.var", name);
877 }
878 }
880 /************************************************************************
881 * Reading Attributes
882 ***********************************************************************/
884 protected enum AttributeKind { CLASS, MEMBER };
885 protected abstract class AttributeReader {
886 AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
887 this.name = name;
888 this.version = version;
889 this.kinds = kinds;
890 }
892 boolean accepts(AttributeKind kind) {
893 if (kinds.contains(kind)) {
894 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
895 return true;
897 if (lintClassfile && !warnedAttrs.contains(name)) {
898 JavaFileObject prev = log.useSource(currentClassFile);
899 try {
900 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
901 name, version.major, version.minor, majorVersion, minorVersion);
902 } finally {
903 log.useSource(prev);
904 }
905 warnedAttrs.add(name);
906 }
907 }
908 return false;
909 }
911 abstract void read(Symbol sym, int attrLen);
913 final Name name;
914 final ClassFile.Version version;
915 final Set<AttributeKind> kinds;
916 }
918 protected Set<AttributeKind> CLASS_ATTRIBUTE =
919 EnumSet.of(AttributeKind.CLASS);
920 protected Set<AttributeKind> MEMBER_ATTRIBUTE =
921 EnumSet.of(AttributeKind.MEMBER);
922 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
923 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
925 protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
927 private void initAttributeReaders() {
928 AttributeReader[] readers = {
929 // v45.3 attributes
931 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
932 void read(Symbol sym, int attrLen) {
933 if (readAllOfClassFile || saveParameterNames)
934 ((MethodSymbol)sym).code = readCode(sym);
935 else
936 bp = bp + attrLen;
937 }
938 },
940 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
941 void read(Symbol sym, int attrLen) {
942 Object v = readPool(nextChar());
943 // Ignore ConstantValue attribute if field not final.
944 if ((sym.flags() & FINAL) != 0)
945 ((VarSymbol) sym).setData(v);
946 }
947 },
949 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
950 void read(Symbol sym, int attrLen) {
951 sym.flags_field |= DEPRECATED;
952 }
953 },
955 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
956 void read(Symbol sym, int attrLen) {
957 int nexceptions = nextChar();
958 List<Type> thrown = List.nil();
959 for (int j = 0; j < nexceptions; j++)
960 thrown = thrown.prepend(readClassSymbol(nextChar()).type);
961 if (sym.type.getThrownTypes().isEmpty())
962 sym.type.asMethodType().thrown = thrown.reverse();
963 }
964 },
966 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
967 void read(Symbol sym, int attrLen) {
968 ClassSymbol c = (ClassSymbol) sym;
969 readInnerClasses(c);
970 }
971 },
973 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
974 void read(Symbol sym, int attrLen) {
975 int newbp = bp + attrLen;
976 if (saveParameterNames) {
977 // Pick up parameter names from the variable table.
978 // Parameter names are not explicitly identified as such,
979 // but all parameter name entries in the LocalVariableTable
980 // have a start_pc of 0. Therefore, we record the name
981 // indicies of all slots with a start_pc of zero in the
982 // parameterNameIndicies array.
983 // Note that this implicitly honors the JVMS spec that
984 // there may be more than one LocalVariableTable, and that
985 // there is no specified ordering for the entries.
986 int numEntries = nextChar();
987 for (int i = 0; i < numEntries; i++) {
988 int start_pc = nextChar();
989 int length = nextChar();
990 int nameIndex = nextChar();
991 int sigIndex = nextChar();
992 int register = nextChar();
993 if (start_pc == 0) {
994 // ensure array large enough
995 if (register >= parameterNameIndices.length) {
996 int newSize = Math.max(register, parameterNameIndices.length + 8);
997 parameterNameIndices =
998 Arrays.copyOf(parameterNameIndices, newSize);
999 }
1000 parameterNameIndices[register] = nameIndex;
1001 haveParameterNameIndices = true;
1002 }
1003 }
1004 }
1005 bp = newbp;
1006 }
1007 },
1009 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
1010 void read(Symbol sym, int attrLen) {
1011 ClassSymbol c = (ClassSymbol) sym;
1012 Name n = readName(nextChar());
1013 c.sourcefile = new SourceFileObject(n, c.flatname);
1014 }
1015 },
1017 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1018 void read(Symbol sym, int attrLen) {
1019 // bridge methods are visible when generics not enabled
1020 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
1021 sym.flags_field |= SYNTHETIC;
1022 }
1023 },
1025 // standard v49 attributes
1027 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1028 void read(Symbol sym, int attrLen) {
1029 int newbp = bp + attrLen;
1030 readEnclosingMethodAttr(sym);
1031 bp = newbp;
1032 }
1033 },
1035 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1036 @Override
1037 boolean accepts(AttributeKind kind) {
1038 return super.accepts(kind) && allowGenerics;
1039 }
1041 void read(Symbol sym, int attrLen) {
1042 if (sym.kind == TYP) {
1043 ClassSymbol c = (ClassSymbol) sym;
1044 readingClassAttr = true;
1045 try {
1046 ClassType ct1 = (ClassType)c.type;
1047 assert c == currentOwner;
1048 ct1.typarams_field = readTypeParams(nextChar());
1049 ct1.supertype_field = sigToType();
1050 ListBuffer<Type> is = new ListBuffer<Type>();
1051 while (sigp != siglimit) is.append(sigToType());
1052 ct1.interfaces_field = is.toList();
1053 } finally {
1054 readingClassAttr = false;
1055 }
1056 } else {
1057 List<Type> thrown = sym.type.getThrownTypes();
1058 sym.type = readType(nextChar());
1059 //- System.err.println(" # " + sym.type);
1060 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1061 sym.type.asMethodType().thrown = thrown;
1063 }
1064 }
1065 },
1067 // v49 annotation attributes
1069 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1070 void read(Symbol sym, int attrLen) {
1071 attachAnnotationDefault(sym);
1072 }
1073 },
1075 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1076 void read(Symbol sym, int attrLen) {
1077 attachAnnotations(sym);
1078 }
1079 },
1081 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1082 void read(Symbol sym, int attrLen) {
1083 attachParameterAnnotations(sym);
1084 }
1085 },
1087 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1088 void read(Symbol sym, int attrLen) {
1089 attachAnnotations(sym);
1090 }
1091 },
1093 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1094 void read(Symbol sym, int attrLen) {
1095 attachParameterAnnotations(sym);
1096 }
1097 },
1099 // additional "legacy" v49 attributes, superceded by flags
1101 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1102 void read(Symbol sym, int attrLen) {
1103 if (allowAnnotations)
1104 sym.flags_field |= ANNOTATION;
1105 }
1106 },
1108 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1109 void read(Symbol sym, int attrLen) {
1110 sym.flags_field |= BRIDGE;
1111 if (!allowGenerics)
1112 sym.flags_field &= ~SYNTHETIC;
1113 }
1114 },
1116 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1117 void read(Symbol sym, int attrLen) {
1118 sym.flags_field |= ENUM;
1119 }
1120 },
1122 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1123 void read(Symbol sym, int attrLen) {
1124 if (allowVarargs)
1125 sym.flags_field |= VARARGS;
1126 }
1127 },
1129 // v51 attributes
1130 new AttributeReader(names.RuntimeVisibleTypeAnnotations, V51, CLASS_OR_MEMBER_ATTRIBUTE) {
1131 void read(Symbol sym, int attrLen) {
1132 attachTypeAnnotations(sym);
1133 }
1134 },
1136 new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V51, CLASS_OR_MEMBER_ATTRIBUTE) {
1137 void read(Symbol sym, int attrLen) {
1138 attachTypeAnnotations(sym);
1139 }
1140 },
1143 // The following attributes for a Code attribute are not currently handled
1144 // StackMapTable
1145 // SourceDebugExtension
1146 // LineNumberTable
1147 // LocalVariableTypeTable
1148 };
1150 for (AttributeReader r: readers)
1151 attributeReaders.put(r.name, r);
1152 }
1154 /** Report unrecognized attribute.
1155 */
1156 void unrecognized(Name attrName) {
1157 if (checkClassFile)
1158 printCCF("ccf.unrecognized.attribute", attrName);
1159 }
1163 void readEnclosingMethodAttr(Symbol sym) {
1164 // sym is a nested class with an "Enclosing Method" attribute
1165 // remove sym from it's current owners scope and place it in
1166 // the scope specified by the attribute
1167 sym.owner.members().remove(sym);
1168 ClassSymbol self = (ClassSymbol)sym;
1169 ClassSymbol c = readClassSymbol(nextChar());
1170 NameAndType nt = (NameAndType)readPool(nextChar());
1172 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1173 if (nt != null && m == null)
1174 throw badClassFile("bad.enclosing.method", self);
1176 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1177 self.owner = m != null ? m : c;
1178 if (self.name.isEmpty())
1179 self.fullname = names.empty;
1180 else
1181 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1183 if (m != null) {
1184 ((ClassType)sym.type).setEnclosingType(m.type);
1185 } else if ((self.flags_field & STATIC) == 0) {
1186 ((ClassType)sym.type).setEnclosingType(c.type);
1187 } else {
1188 ((ClassType)sym.type).setEnclosingType(Type.noType);
1189 }
1190 enterTypevars(self);
1191 if (!missingTypeVariables.isEmpty()) {
1192 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1193 for (Type typevar : missingTypeVariables) {
1194 typeVars.append(findTypeVar(typevar.tsym.name));
1195 }
1196 foundTypeVariables = typeVars.toList();
1197 } else {
1198 foundTypeVariables = List.nil();
1199 }
1200 }
1202 // See java.lang.Class
1203 private Name simpleBinaryName(Name self, Name enclosing) {
1204 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1205 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1206 throw badClassFile("bad.enclosing.method", self);
1207 int index = 1;
1208 while (index < simpleBinaryName.length() &&
1209 isAsciiDigit(simpleBinaryName.charAt(index)))
1210 index++;
1211 return names.fromString(simpleBinaryName.substring(index));
1212 }
1214 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1215 if (nt == null)
1216 return null;
1218 MethodType type = nt.type.asMethodType();
1220 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1221 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1222 return (MethodSymbol)e.sym;
1224 if (nt.name != names.init)
1225 // not a constructor
1226 return null;
1227 if ((flags & INTERFACE) != 0)
1228 // no enclosing instance
1229 return null;
1230 if (nt.type.getParameterTypes().isEmpty())
1231 // no parameters
1232 return null;
1234 // A constructor of an inner class.
1235 // Remove the first argument (the enclosing instance)
1236 nt.type = new MethodType(nt.type.getParameterTypes().tail,
1237 nt.type.getReturnType(),
1238 nt.type.getThrownTypes(),
1239 syms.methodClass);
1240 // Try searching again
1241 return findMethod(nt, scope, flags);
1242 }
1244 /** Similar to Types.isSameType but avoids completion */
1245 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1246 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1247 .prepend(types.erasure(mt1.getReturnType()));
1248 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1249 while (!types1.isEmpty() && !types2.isEmpty()) {
1250 if (types1.head.tsym != types2.head.tsym)
1251 return false;
1252 types1 = types1.tail;
1253 types2 = types2.tail;
1254 }
1255 return types1.isEmpty() && types2.isEmpty();
1256 }
1258 /**
1259 * Character.isDigit answers <tt>true</tt> to some non-ascii
1260 * digits. This one does not. <b>copied from java.lang.Class</b>
1261 */
1262 private static boolean isAsciiDigit(char c) {
1263 return '0' <= c && c <= '9';
1264 }
1266 /** Read member attributes.
1267 */
1268 void readMemberAttrs(Symbol sym) {
1269 readAttrs(sym, AttributeKind.MEMBER);
1270 }
1272 void readAttrs(Symbol sym, AttributeKind kind) {
1273 char ac = nextChar();
1274 for (int i = 0; i < ac; i++) {
1275 Name attrName = readName(nextChar());
1276 int attrLen = nextInt();
1277 AttributeReader r = attributeReaders.get(attrName);
1278 if (r != null && r.accepts(kind))
1279 r.read(sym, attrLen);
1280 else {
1281 unrecognized(attrName);
1282 bp = bp + attrLen;
1283 }
1284 }
1285 }
1287 private boolean readingClassAttr = false;
1288 private List<Type> missingTypeVariables = List.nil();
1289 private List<Type> foundTypeVariables = List.nil();
1291 /** Read class attributes.
1292 */
1293 void readClassAttrs(ClassSymbol c) {
1294 readAttrs(c, AttributeKind.CLASS);
1295 }
1297 /** Read code block.
1298 */
1299 Code readCode(Symbol owner) {
1300 nextChar(); // max_stack
1301 nextChar(); // max_locals
1302 final int code_length = nextInt();
1303 bp += code_length;
1304 final char exception_table_length = nextChar();
1305 bp += exception_table_length * 8;
1306 readMemberAttrs(owner);
1307 return null;
1308 }
1310 /************************************************************************
1311 * Reading Java-language annotations
1312 ***********************************************************************/
1314 /** Attach annotations.
1315 */
1316 void attachAnnotations(final Symbol sym) {
1317 int numAttributes = nextChar();
1318 if (numAttributes != 0) {
1319 ListBuffer<CompoundAnnotationProxy> proxies =
1320 new ListBuffer<CompoundAnnotationProxy>();
1321 for (int i = 0; i<numAttributes; i++) {
1322 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1323 if (proxy.type.tsym == syms.proprietaryType.tsym)
1324 sym.flags_field |= PROPRIETARY;
1325 else
1326 proxies.append(proxy);
1327 if (majorVersion >= V51.major && proxy.type.tsym == syms.polymorphicSignatureType.tsym) {
1328 sym.flags_field |= POLYMORPHIC_SIGNATURE;
1329 }
1330 }
1331 annotate.later(new AnnotationCompleter(sym, proxies.toList()));
1332 }
1333 }
1335 /** Attach parameter annotations.
1336 */
1337 void attachParameterAnnotations(final Symbol method) {
1338 final MethodSymbol meth = (MethodSymbol)method;
1339 int numParameters = buf[bp++] & 0xFF;
1340 List<VarSymbol> parameters = meth.params();
1341 int pnum = 0;
1342 while (parameters.tail != null) {
1343 attachAnnotations(parameters.head);
1344 parameters = parameters.tail;
1345 pnum++;
1346 }
1347 if (pnum != numParameters) {
1348 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1349 }
1350 }
1352 void attachTypeAnnotations(final Symbol sym) {
1353 int numAttributes = nextChar();
1354 if (numAttributes != 0) {
1355 ListBuffer<TypeAnnotationProxy> proxies =
1356 ListBuffer.lb();
1357 for (int i = 0; i < numAttributes; i++)
1358 proxies.append(readTypeAnnotation());
1359 annotate.later(new TypeAnnotationCompleter(sym, proxies.toList()));
1360 }
1361 }
1363 /** Attach the default value for an annotation element.
1364 */
1365 void attachAnnotationDefault(final Symbol sym) {
1366 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1367 final Attribute value = readAttributeValue();
1368 annotate.later(new AnnotationDefaultCompleter(meth, value));
1369 }
1371 Type readTypeOrClassSymbol(int i) {
1372 // support preliminary jsr175-format class files
1373 if (buf[poolIdx[i]] == CONSTANT_Class)
1374 return readClassSymbol(i).type;
1375 return readType(i);
1376 }
1377 Type readEnumType(int i) {
1378 // support preliminary jsr175-format class files
1379 int index = poolIdx[i];
1380 int length = getChar(index + 1);
1381 if (buf[index + length + 2] != ';')
1382 return enterClass(readName(i)).type;
1383 return readType(i);
1384 }
1386 CompoundAnnotationProxy readCompoundAnnotation() {
1387 Type t = readTypeOrClassSymbol(nextChar());
1388 int numFields = nextChar();
1389 ListBuffer<Pair<Name,Attribute>> pairs =
1390 new ListBuffer<Pair<Name,Attribute>>();
1391 for (int i=0; i<numFields; i++) {
1392 Name name = readName(nextChar());
1393 Attribute value = readAttributeValue();
1394 pairs.append(new Pair<Name,Attribute>(name, value));
1395 }
1396 return new CompoundAnnotationProxy(t, pairs.toList());
1397 }
1399 TypeAnnotationProxy readTypeAnnotation() {
1400 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1401 TypeAnnotationPosition position = readPosition();
1403 if (debugJSR308)
1404 System.out.println("TA: reading: " + proxy + " @ " + position
1405 + " in " + log.currentSourceFile());
1407 return new TypeAnnotationProxy(proxy, position);
1408 }
1410 TypeAnnotationPosition readPosition() {
1411 byte tag = nextByte();
1413 if (!TargetType.isValidTargetTypeValue(tag))
1414 throw this.badClassFile("bad.type.annotation.value", tag);
1416 TypeAnnotationPosition position = new TypeAnnotationPosition();
1417 TargetType type = TargetType.fromTargetTypeValue(tag);
1419 position.type = type;
1421 switch (type) {
1422 // type case
1423 case TYPECAST:
1424 case TYPECAST_GENERIC_OR_ARRAY:
1425 // object creation
1426 case INSTANCEOF:
1427 case INSTANCEOF_GENERIC_OR_ARRAY:
1428 // new expression
1429 case NEW:
1430 case NEW_GENERIC_OR_ARRAY:
1431 position.offset = nextChar();
1432 break;
1433 // local variable
1434 case LOCAL_VARIABLE:
1435 case LOCAL_VARIABLE_GENERIC_OR_ARRAY:
1436 int table_length = nextChar();
1437 position.lvarOffset = new int[table_length];
1438 position.lvarLength = new int[table_length];
1439 position.lvarIndex = new int[table_length];
1441 for (int i = 0; i < table_length; ++i) {
1442 position.lvarOffset[i] = nextChar();
1443 position.lvarLength[i] = nextChar();
1444 position.lvarIndex[i] = nextChar();
1445 }
1446 break;
1447 // method receiver
1448 case METHOD_RECEIVER:
1449 // Do nothing
1450 break;
1451 // type parameters
1452 case CLASS_TYPE_PARAMETER:
1453 case METHOD_TYPE_PARAMETER:
1454 position.parameter_index = nextByte();
1455 break;
1456 // type parameter bounds
1457 case CLASS_TYPE_PARAMETER_BOUND:
1458 case CLASS_TYPE_PARAMETER_BOUND_GENERIC_OR_ARRAY:
1459 case METHOD_TYPE_PARAMETER_BOUND:
1460 case METHOD_TYPE_PARAMETER_BOUND_GENERIC_OR_ARRAY:
1461 position.parameter_index = nextByte();
1462 position.bound_index = nextByte();
1463 break;
1464 // wildcard
1465 case WILDCARD_BOUND:
1466 case WILDCARD_BOUND_GENERIC_OR_ARRAY:
1467 position.wildcard_position = readPosition();
1468 break;
1469 // Class extends and implements clauses
1470 case CLASS_EXTENDS:
1471 case CLASS_EXTENDS_GENERIC_OR_ARRAY:
1472 position.type_index = nextChar();
1473 break;
1474 // throws
1475 case THROWS:
1476 position.type_index = nextChar();
1477 break;
1478 case CLASS_LITERAL:
1479 case CLASS_LITERAL_GENERIC_OR_ARRAY:
1480 position.offset = nextChar();
1481 break;
1482 // method parameter: not specified
1483 case METHOD_PARAMETER_GENERIC_OR_ARRAY:
1484 position.parameter_index = nextByte();
1485 break;
1486 // method type argument: wasn't specified
1487 case NEW_TYPE_ARGUMENT:
1488 case NEW_TYPE_ARGUMENT_GENERIC_OR_ARRAY:
1489 case METHOD_TYPE_ARGUMENT:
1490 case METHOD_TYPE_ARGUMENT_GENERIC_OR_ARRAY:
1491 position.offset = nextChar();
1492 position.type_index = nextByte();
1493 break;
1494 // We don't need to worry abut these
1495 case METHOD_RETURN_GENERIC_OR_ARRAY:
1496 case FIELD_GENERIC_OR_ARRAY:
1497 break;
1498 case UNKNOWN:
1499 break;
1500 default:
1501 throw new AssertionError("unknown type: " + position);
1502 }
1504 if (type.hasLocation()) {
1505 int len = nextChar();
1506 ListBuffer<Integer> loc = ListBuffer.lb();
1507 for (int i = 0; i < len; i++)
1508 loc = loc.append((int)nextByte());
1509 position.location = loc.toList();
1510 }
1512 return position;
1513 }
1514 Attribute readAttributeValue() {
1515 char c = (char) buf[bp++];
1516 switch (c) {
1517 case 'B':
1518 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1519 case 'C':
1520 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1521 case 'D':
1522 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1523 case 'F':
1524 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1525 case 'I':
1526 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1527 case 'J':
1528 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1529 case 'S':
1530 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1531 case 'Z':
1532 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1533 case 's':
1534 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1535 case 'e':
1536 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1537 case 'c':
1538 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1539 case '[': {
1540 int n = nextChar();
1541 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1542 for (int i=0; i<n; i++)
1543 l.append(readAttributeValue());
1544 return new ArrayAttributeProxy(l.toList());
1545 }
1546 case '@':
1547 return readCompoundAnnotation();
1548 default:
1549 throw new AssertionError("unknown annotation tag '" + c + "'");
1550 }
1551 }
1553 interface ProxyVisitor extends Attribute.Visitor {
1554 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1555 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1556 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1557 }
1559 static class EnumAttributeProxy extends Attribute {
1560 Type enumType;
1561 Name enumerator;
1562 public EnumAttributeProxy(Type enumType, Name enumerator) {
1563 super(null);
1564 this.enumType = enumType;
1565 this.enumerator = enumerator;
1566 }
1567 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1568 @Override
1569 public String toString() {
1570 return "/*proxy enum*/" + enumType + "." + enumerator;
1571 }
1572 }
1574 static class ArrayAttributeProxy extends Attribute {
1575 List<Attribute> values;
1576 ArrayAttributeProxy(List<Attribute> values) {
1577 super(null);
1578 this.values = values;
1579 }
1580 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1581 @Override
1582 public String toString() {
1583 return "{" + values + "}";
1584 }
1585 }
1587 /** A temporary proxy representing a compound attribute.
1588 */
1589 static class CompoundAnnotationProxy extends Attribute {
1590 final List<Pair<Name,Attribute>> values;
1591 public CompoundAnnotationProxy(Type type,
1592 List<Pair<Name,Attribute>> values) {
1593 super(type);
1594 this.values = values;
1595 }
1596 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1597 @Override
1598 public String toString() {
1599 StringBuilder buf = new StringBuilder();
1600 buf.append("@");
1601 buf.append(type.tsym.getQualifiedName());
1602 buf.append("/*proxy*/{");
1603 boolean first = true;
1604 for (List<Pair<Name,Attribute>> v = values;
1605 v.nonEmpty(); v = v.tail) {
1606 Pair<Name,Attribute> value = v.head;
1607 if (!first) buf.append(",");
1608 first = false;
1609 buf.append(value.fst);
1610 buf.append("=");
1611 buf.append(value.snd);
1612 }
1613 buf.append("}");
1614 return buf.toString();
1615 }
1616 }
1618 /** A temporary proxy representing a type annotation.
1619 */
1620 static class TypeAnnotationProxy {
1621 final CompoundAnnotationProxy compound;
1622 final TypeAnnotationPosition position;
1623 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1624 TypeAnnotationPosition position) {
1625 this.compound = compound;
1626 this.position = position;
1627 }
1628 }
1630 class AnnotationDeproxy implements ProxyVisitor {
1631 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1632 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1634 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1635 // also must fill in types!!!!
1636 ListBuffer<Attribute.Compound> buf =
1637 new ListBuffer<Attribute.Compound>();
1638 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1639 buf.append(deproxyCompound(l.head));
1640 }
1641 return buf.toList();
1642 }
1644 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1645 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1646 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1647 for (List<Pair<Name,Attribute>> l = a.values;
1648 l.nonEmpty();
1649 l = l.tail) {
1650 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1651 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1652 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1653 }
1654 return new Attribute.Compound(a.type, buf.toList());
1655 }
1657 MethodSymbol findAccessMethod(Type container, Name name) {
1658 CompletionFailure failure = null;
1659 try {
1660 for (Scope.Entry e = container.tsym.members().lookup(name);
1661 e.scope != null;
1662 e = e.next()) {
1663 Symbol sym = e.sym;
1664 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1665 return (MethodSymbol) sym;
1666 }
1667 } catch (CompletionFailure ex) {
1668 failure = ex;
1669 }
1670 // The method wasn't found: emit a warning and recover
1671 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1672 try {
1673 if (failure == null) {
1674 log.warning("annotation.method.not.found",
1675 container,
1676 name);
1677 } else {
1678 log.warning("annotation.method.not.found.reason",
1679 container,
1680 name,
1681 failure.getDetailValue());//diagnostic, if present
1682 }
1683 } finally {
1684 log.useSource(prevSource);
1685 }
1686 // Construct a new method type and symbol. Use bottom
1687 // type (typeof null) as return type because this type is
1688 // a subtype of all reference types and can be converted
1689 // to primitive types by unboxing.
1690 MethodType mt = new MethodType(List.<Type>nil(),
1691 syms.botType,
1692 List.<Type>nil(),
1693 syms.methodClass);
1694 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1695 }
1697 Attribute result;
1698 Type type;
1699 Attribute deproxy(Type t, Attribute a) {
1700 Type oldType = type;
1701 try {
1702 type = t;
1703 a.accept(this);
1704 return result;
1705 } finally {
1706 type = oldType;
1707 }
1708 }
1710 // implement Attribute.Visitor below
1712 public void visitConstant(Attribute.Constant value) {
1713 // assert value.type == type;
1714 result = value;
1715 }
1717 public void visitClass(Attribute.Class clazz) {
1718 result = clazz;
1719 }
1721 public void visitEnum(Attribute.Enum e) {
1722 throw new AssertionError(); // shouldn't happen
1723 }
1725 public void visitCompound(Attribute.Compound compound) {
1726 throw new AssertionError(); // shouldn't happen
1727 }
1729 public void visitArray(Attribute.Array array) {
1730 throw new AssertionError(); // shouldn't happen
1731 }
1733 public void visitError(Attribute.Error e) {
1734 throw new AssertionError(); // shouldn't happen
1735 }
1737 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1738 // type.tsym.flatName() should == proxy.enumFlatName
1739 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1740 VarSymbol enumerator = null;
1741 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1742 e.scope != null;
1743 e = e.next()) {
1744 if (e.sym.kind == VAR) {
1745 enumerator = (VarSymbol)e.sym;
1746 break;
1747 }
1748 }
1749 if (enumerator == null) {
1750 log.error("unknown.enum.constant",
1751 currentClassFile, enumTypeSym, proxy.enumerator);
1752 result = new Attribute.Error(enumTypeSym.type);
1753 } else {
1754 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1755 }
1756 }
1758 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1759 int length = proxy.values.length();
1760 Attribute[] ats = new Attribute[length];
1761 Type elemtype = types.elemtype(type);
1762 int i = 0;
1763 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1764 ats[i++] = deproxy(elemtype, p.head);
1765 }
1766 result = new Attribute.Array(type, ats);
1767 }
1769 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1770 result = deproxyCompound(proxy);
1771 }
1772 }
1774 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1775 final MethodSymbol sym;
1776 final Attribute value;
1777 final JavaFileObject classFile = currentClassFile;
1778 @Override
1779 public String toString() {
1780 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1781 }
1782 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1783 this.sym = sym;
1784 this.value = value;
1785 }
1786 // implement Annotate.Annotator.enterAnnotation()
1787 public void enterAnnotation() {
1788 JavaFileObject previousClassFile = currentClassFile;
1789 try {
1790 currentClassFile = classFile;
1791 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1792 } finally {
1793 currentClassFile = previousClassFile;
1794 }
1795 }
1796 }
1798 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1799 final Symbol sym;
1800 final List<CompoundAnnotationProxy> l;
1801 final JavaFileObject classFile;
1802 @Override
1803 public String toString() {
1804 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1805 }
1806 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1807 this.sym = sym;
1808 this.l = l;
1809 this.classFile = currentClassFile;
1810 }
1811 // implement Annotate.Annotator.enterAnnotation()
1812 public void enterAnnotation() {
1813 JavaFileObject previousClassFile = currentClassFile;
1814 try {
1815 currentClassFile = classFile;
1816 List<Attribute.Compound> newList = deproxyCompoundList(l);
1817 sym.attributes_field = ((sym.attributes_field == null)
1818 ? newList
1819 : newList.prependList(sym.attributes_field));
1820 } finally {
1821 currentClassFile = previousClassFile;
1822 }
1823 }
1824 }
1826 class TypeAnnotationCompleter extends AnnotationCompleter {
1828 List<TypeAnnotationProxy> proxies;
1830 TypeAnnotationCompleter(Symbol sym,
1831 List<TypeAnnotationProxy> proxies) {
1832 super(sym, List.<CompoundAnnotationProxy>nil());
1833 this.proxies = proxies;
1834 }
1836 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
1837 ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
1838 for (TypeAnnotationProxy proxy: proxies) {
1839 Attribute.Compound compound = deproxyCompound(proxy.compound);
1840 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
1841 buf.add(typeCompound);
1842 }
1843 return buf.toList();
1844 }
1846 @Override
1847 public void enterAnnotation() {
1848 JavaFileObject previousClassFile = currentClassFile;
1849 try {
1850 currentClassFile = classFile;
1851 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
1852 if (debugJSR308)
1853 System.out.println("TA: reading: adding " + newList
1854 + " to symbol " + sym + " in " + log.currentSourceFile());
1855 sym.typeAnnotations = ((sym.typeAnnotations == null)
1856 ? newList
1857 : newList.prependList(sym.typeAnnotations));
1859 } finally {
1860 currentClassFile = previousClassFile;
1861 }
1862 }
1863 }
1866 /************************************************************************
1867 * Reading Symbols
1868 ***********************************************************************/
1870 /** Read a field.
1871 */
1872 VarSymbol readField() {
1873 long flags = adjustFieldFlags(nextChar());
1874 Name name = readName(nextChar());
1875 Type type = readType(nextChar());
1876 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1877 readMemberAttrs(v);
1878 return v;
1879 }
1881 /** Read a method.
1882 */
1883 MethodSymbol readMethod() {
1884 long flags = adjustMethodFlags(nextChar());
1885 Name name = readName(nextChar());
1886 Type type = readType(nextChar());
1887 if (name == names.init && currentOwner.hasOuterInstance()) {
1888 // Sometimes anonymous classes don't have an outer
1889 // instance, however, there is no reliable way to tell so
1890 // we never strip this$n
1891 if (!currentOwner.name.isEmpty())
1892 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1893 type.getReturnType(),
1894 type.getThrownTypes(),
1895 syms.methodClass);
1896 }
1897 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1898 if (saveParameterNames)
1899 initParameterNames(m);
1900 Symbol prevOwner = currentOwner;
1901 currentOwner = m;
1902 try {
1903 readMemberAttrs(m);
1904 } finally {
1905 currentOwner = prevOwner;
1906 }
1907 if (saveParameterNames)
1908 setParameterNames(m, type);
1909 return m;
1910 }
1912 private List<Type> adjustMethodParams(long flags, List<Type> args) {
1913 boolean isVarargs = (flags & VARARGS) != 0;
1914 if (isVarargs) {
1915 Type varargsElem = args.last();
1916 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
1917 for (Type t : args) {
1918 adjustedArgs.append(t != varargsElem ?
1919 t :
1920 ((ArrayType)t).makeVarargs());
1921 }
1922 args = adjustedArgs.toList();
1923 }
1924 return args.tail;
1925 }
1927 /**
1928 * Init the parameter names array.
1929 * Parameter names are currently inferred from the names in the
1930 * LocalVariableTable attributes of a Code attribute.
1931 * (Note: this means parameter names are currently not available for
1932 * methods without a Code attribute.)
1933 * This method initializes an array in which to store the name indexes
1934 * of parameter names found in LocalVariableTable attributes. It is
1935 * slightly supersized to allow for additional slots with a start_pc of 0.
1936 */
1937 void initParameterNames(MethodSymbol sym) {
1938 // make allowance for synthetic parameters.
1939 final int excessSlots = 4;
1940 int expectedParameterSlots =
1941 Code.width(sym.type.getParameterTypes()) + excessSlots;
1942 if (parameterNameIndices == null
1943 || parameterNameIndices.length < expectedParameterSlots) {
1944 parameterNameIndices = new int[expectedParameterSlots];
1945 } else
1946 Arrays.fill(parameterNameIndices, 0);
1947 haveParameterNameIndices = false;
1948 }
1950 /**
1951 * Set the parameter names for a symbol from the name index in the
1952 * parameterNameIndicies array. The type of the symbol may have changed
1953 * while reading the method attributes (see the Signature attribute).
1954 * This may be because of generic information or because anonymous
1955 * synthetic parameters were added. The original type (as read from
1956 * the method descriptor) is used to help guess the existence of
1957 * anonymous synthetic parameters.
1958 * On completion, sym.savedParameter names will either be null (if
1959 * no parameter names were found in the class file) or will be set to a
1960 * list of names, one per entry in sym.type.getParameterTypes, with
1961 * any missing names represented by the empty name.
1962 */
1963 void setParameterNames(MethodSymbol sym, Type jvmType) {
1964 // if no names were found in the class file, there's nothing more to do
1965 if (!haveParameterNameIndices)
1966 return;
1968 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1969 // the code in readMethod may have skipped the first parameter when
1970 // setting up the MethodType. If so, we make a corresponding allowance
1971 // here for the position of the first parameter. Note that this
1972 // assumes the skipped parameter has a width of 1 -- i.e. it is not
1973 // a double width type (long or double.)
1974 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1975 // Sometimes anonymous classes don't have an outer
1976 // instance, however, there is no reliable way to tell so
1977 // we never strip this$n
1978 if (!currentOwner.name.isEmpty())
1979 firstParam += 1;
1980 }
1982 if (sym.type != jvmType) {
1983 // reading the method attributes has caused the symbol's type to
1984 // be changed. (i.e. the Signature attribute.) This may happen if
1985 // there are hidden (synthetic) parameters in the descriptor, but
1986 // not in the Signature. The position of these hidden parameters
1987 // is unspecified; for now, assume they are at the beginning, and
1988 // so skip over them. The primary case for this is two hidden
1989 // parameters passed into Enum constructors.
1990 int skip = Code.width(jvmType.getParameterTypes())
1991 - Code.width(sym.type.getParameterTypes());
1992 firstParam += skip;
1993 }
1994 List<Name> paramNames = List.nil();
1995 int index = firstParam;
1996 for (Type t: sym.type.getParameterTypes()) {
1997 int nameIdx = (index < parameterNameIndices.length
1998 ? parameterNameIndices[index] : 0);
1999 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
2000 paramNames = paramNames.prepend(name);
2001 index += Code.width(t);
2002 }
2003 sym.savedParameterNames = paramNames.reverse();
2004 }
2006 /** Skip a field or method
2007 */
2008 void skipMember() {
2009 bp = bp + 6;
2010 char ac = nextChar();
2011 for (int i = 0; i < ac; i++) {
2012 bp = bp + 2;
2013 int attrLen = nextInt();
2014 bp = bp + attrLen;
2015 }
2016 }
2018 /** Enter type variables of this classtype and all enclosing ones in
2019 * `typevars'.
2020 */
2021 protected void enterTypevars(Type t) {
2022 if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
2023 enterTypevars(t.getEnclosingType());
2024 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
2025 typevars.enter(xs.head.tsym);
2026 }
2028 protected void enterTypevars(Symbol sym) {
2029 if (sym.owner.kind == MTH) {
2030 enterTypevars(sym.owner);
2031 enterTypevars(sym.owner.owner);
2032 }
2033 enterTypevars(sym.type);
2034 }
2036 /** Read contents of a given class symbol `c'. Both external and internal
2037 * versions of an inner class are read.
2038 */
2039 void readClass(ClassSymbol c) {
2040 ClassType ct = (ClassType)c.type;
2042 // allocate scope for members
2043 c.members_field = new Scope.ClassScope(c, scopeCounter);
2045 // prepare type variable table
2046 typevars = typevars.dup(currentOwner);
2047 if (ct.getEnclosingType().tag == CLASS)
2048 enterTypevars(ct.getEnclosingType());
2050 // read flags, or skip if this is an inner class
2051 long flags = adjustClassFlags(nextChar());
2052 if (c.owner.kind == PCK) c.flags_field = flags;
2054 // read own class name and check that it matches
2055 ClassSymbol self = readClassSymbol(nextChar());
2056 if (c != self)
2057 throw badClassFile("class.file.wrong.class",
2058 self.flatname);
2060 // class attributes must be read before class
2061 // skip ahead to read class attributes
2062 int startbp = bp;
2063 nextChar();
2064 char interfaceCount = nextChar();
2065 bp += interfaceCount * 2;
2066 char fieldCount = nextChar();
2067 for (int i = 0; i < fieldCount; i++) skipMember();
2068 char methodCount = nextChar();
2069 for (int i = 0; i < methodCount; i++) skipMember();
2070 readClassAttrs(c);
2072 if (readAllOfClassFile) {
2073 for (int i = 1; i < poolObj.length; i++) readPool(i);
2074 c.pool = new Pool(poolObj.length, poolObj);
2075 }
2077 // reset and read rest of classinfo
2078 bp = startbp;
2079 int n = nextChar();
2080 if (ct.supertype_field == null)
2081 ct.supertype_field = (n == 0)
2082 ? Type.noType
2083 : readClassSymbol(n).erasure(types);
2084 n = nextChar();
2085 List<Type> is = List.nil();
2086 for (int i = 0; i < n; i++) {
2087 Type _inter = readClassSymbol(nextChar()).erasure(types);
2088 is = is.prepend(_inter);
2089 }
2090 if (ct.interfaces_field == null)
2091 ct.interfaces_field = is.reverse();
2093 if (fieldCount != nextChar()) assert false;
2094 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2095 if (methodCount != nextChar()) assert false;
2096 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2098 typevars = typevars.leave();
2099 }
2101 /** Read inner class info. For each inner/outer pair allocate a
2102 * member class.
2103 */
2104 void readInnerClasses(ClassSymbol c) {
2105 int n = nextChar();
2106 for (int i = 0; i < n; i++) {
2107 nextChar(); // skip inner class symbol
2108 ClassSymbol outer = readClassSymbol(nextChar());
2109 Name name = readName(nextChar());
2110 if (name == null) name = names.empty;
2111 long flags = adjustClassFlags(nextChar());
2112 if (outer != null) { // we have a member class
2113 if (name == names.empty)
2114 name = names.one;
2115 ClassSymbol member = enterClass(name, outer);
2116 if ((flags & STATIC) == 0) {
2117 ((ClassType)member.type).setEnclosingType(outer.type);
2118 if (member.erasure_field != null)
2119 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2120 }
2121 if (c == outer) {
2122 member.flags_field = flags;
2123 enterMember(c, member);
2124 }
2125 }
2126 }
2127 }
2129 /** Read a class file.
2130 */
2131 private void readClassFile(ClassSymbol c) throws IOException {
2132 int magic = nextInt();
2133 if (magic != JAVA_MAGIC)
2134 throw badClassFile("illegal.start.of.class.file");
2136 minorVersion = nextChar();
2137 majorVersion = nextChar();
2138 int maxMajor = Target.MAX().majorVersion;
2139 int maxMinor = Target.MAX().minorVersion;
2140 if (majorVersion > maxMajor ||
2141 majorVersion * 1000 + minorVersion <
2142 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2143 {
2144 if (majorVersion == (maxMajor + 1))
2145 log.warning("big.major.version",
2146 currentClassFile,
2147 majorVersion,
2148 maxMajor);
2149 else
2150 throw badClassFile("wrong.version",
2151 Integer.toString(majorVersion),
2152 Integer.toString(minorVersion),
2153 Integer.toString(maxMajor),
2154 Integer.toString(maxMinor));
2155 }
2156 else if (checkClassFile &&
2157 majorVersion == maxMajor &&
2158 minorVersion > maxMinor)
2159 {
2160 printCCF("found.later.version",
2161 Integer.toString(minorVersion));
2162 }
2163 indexPool();
2164 if (signatureBuffer.length < bp) {
2165 int ns = Integer.highestOneBit(bp) << 1;
2166 signatureBuffer = new byte[ns];
2167 }
2168 readClass(c);
2169 }
2171 /************************************************************************
2172 * Adjusting flags
2173 ***********************************************************************/
2175 long adjustFieldFlags(long flags) {
2176 return flags;
2177 }
2178 long adjustMethodFlags(long flags) {
2179 if ((flags & ACC_BRIDGE) != 0) {
2180 flags &= ~ACC_BRIDGE;
2181 flags |= BRIDGE;
2182 if (!allowGenerics)
2183 flags &= ~SYNTHETIC;
2184 }
2185 if ((flags & ACC_VARARGS) != 0) {
2186 flags &= ~ACC_VARARGS;
2187 flags |= VARARGS;
2188 }
2189 return flags;
2190 }
2191 long adjustClassFlags(long flags) {
2192 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2193 }
2195 /************************************************************************
2196 * Loading Classes
2197 ***********************************************************************/
2199 /** Define a new class given its name and owner.
2200 */
2201 public ClassSymbol defineClass(Name name, Symbol owner) {
2202 ClassSymbol c = new ClassSymbol(0, name, owner);
2203 if (owner.kind == PCK)
2204 assert classes.get(c.flatname) == null : c;
2205 c.completer = this;
2206 return c;
2207 }
2209 /** Create a new toplevel or member class symbol with given name
2210 * and owner and enter in `classes' unless already there.
2211 */
2212 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2213 Name flatname = TypeSymbol.formFlatName(name, owner);
2214 ClassSymbol c = classes.get(flatname);
2215 if (c == null) {
2216 c = defineClass(name, owner);
2217 classes.put(flatname, c);
2218 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2219 // reassign fields of classes that might have been loaded with
2220 // their flat names.
2221 c.owner.members().remove(c);
2222 c.name = name;
2223 c.owner = owner;
2224 c.fullname = ClassSymbol.formFullName(name, owner);
2225 }
2226 return c;
2227 }
2229 /**
2230 * Creates a new toplevel class symbol with given flat name and
2231 * given class (or source) file.
2232 *
2233 * @param flatName a fully qualified binary class name
2234 * @param classFile the class file or compilation unit defining
2235 * the class (may be {@code null})
2236 * @return a newly created class symbol
2237 * @throws AssertionError if the class symbol already exists
2238 */
2239 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2240 ClassSymbol cs = classes.get(flatName);
2241 if (cs != null) {
2242 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2243 cs.fullname,
2244 cs.completer,
2245 cs.classfile,
2246 cs.sourcefile);
2247 throw new AssertionError(msg);
2248 }
2249 Name packageName = Convert.packagePart(flatName);
2250 PackageSymbol owner = packageName.isEmpty()
2251 ? syms.unnamedPackage
2252 : enterPackage(packageName);
2253 cs = defineClass(Convert.shortName(flatName), owner);
2254 cs.classfile = classFile;
2255 classes.put(flatName, cs);
2256 return cs;
2257 }
2259 /** Create a new member or toplevel class symbol with given flat name
2260 * and enter in `classes' unless already there.
2261 */
2262 public ClassSymbol enterClass(Name flatname) {
2263 ClassSymbol c = classes.get(flatname);
2264 if (c == null)
2265 return enterClass(flatname, (JavaFileObject)null);
2266 else
2267 return c;
2268 }
2270 private boolean suppressFlush = false;
2272 /** Completion for classes to be loaded. Before a class is loaded
2273 * we make sure its enclosing class (if any) is loaded.
2274 */
2275 public void complete(Symbol sym) throws CompletionFailure {
2276 if (sym.kind == TYP) {
2277 ClassSymbol c = (ClassSymbol)sym;
2278 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2279 boolean saveSuppressFlush = suppressFlush;
2280 suppressFlush = true;
2281 try {
2282 completeOwners(c.owner);
2283 completeEnclosing(c);
2284 } finally {
2285 suppressFlush = saveSuppressFlush;
2286 }
2287 fillIn(c);
2288 } else if (sym.kind == PCK) {
2289 PackageSymbol p = (PackageSymbol)sym;
2290 try {
2291 fillIn(p);
2292 } catch (IOException ex) {
2293 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2294 }
2295 }
2296 if (!filling && !suppressFlush)
2297 annotate.flush(); // finish attaching annotations
2298 }
2300 /** complete up through the enclosing package. */
2301 private void completeOwners(Symbol o) {
2302 if (o.kind != PCK) completeOwners(o.owner);
2303 o.complete();
2304 }
2306 /**
2307 * Tries to complete lexically enclosing classes if c looks like a
2308 * nested class. This is similar to completeOwners but handles
2309 * the situation when a nested class is accessed directly as it is
2310 * possible with the Tree API or javax.lang.model.*.
2311 */
2312 private void completeEnclosing(ClassSymbol c) {
2313 if (c.owner.kind == PCK) {
2314 Symbol owner = c.owner;
2315 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2316 Symbol encl = owner.members().lookup(name).sym;
2317 if (encl == null)
2318 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2319 if (encl != null)
2320 encl.complete();
2321 }
2322 }
2323 }
2325 /** We can only read a single class file at a time; this
2326 * flag keeps track of when we are currently reading a class
2327 * file.
2328 */
2329 private boolean filling = false;
2331 /** Fill in definition of class `c' from corresponding class or
2332 * source file.
2333 */
2334 private void fillIn(ClassSymbol c) {
2335 if (completionFailureName == c.fullname) {
2336 throw new CompletionFailure(c, "user-selected completion failure by class name");
2337 }
2338 currentOwner = c;
2339 warnedAttrs.clear();
2340 JavaFileObject classfile = c.classfile;
2341 if (classfile != null) {
2342 JavaFileObject previousClassFile = currentClassFile;
2343 try {
2344 assert !filling :
2345 "Filling " + classfile.toUri() +
2346 " during " + previousClassFile;
2347 currentClassFile = classfile;
2348 if (verbose) {
2349 printVerbose("loading", currentClassFile.toString());
2350 }
2351 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2352 filling = true;
2353 try {
2354 bp = 0;
2355 buf = readInputStream(buf, classfile.openInputStream());
2356 readClassFile(c);
2357 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2358 List<Type> missing = missingTypeVariables;
2359 List<Type> found = foundTypeVariables;
2360 missingTypeVariables = List.nil();
2361 foundTypeVariables = List.nil();
2362 filling = false;
2363 ClassType ct = (ClassType)currentOwner.type;
2364 ct.supertype_field =
2365 types.subst(ct.supertype_field, missing, found);
2366 ct.interfaces_field =
2367 types.subst(ct.interfaces_field, missing, found);
2368 } else if (missingTypeVariables.isEmpty() !=
2369 foundTypeVariables.isEmpty()) {
2370 Name name = missingTypeVariables.head.tsym.name;
2371 throw badClassFile("undecl.type.var", name);
2372 }
2373 } finally {
2374 missingTypeVariables = List.nil();
2375 foundTypeVariables = List.nil();
2376 filling = false;
2377 }
2378 } else {
2379 if (sourceCompleter != null) {
2380 sourceCompleter.complete(c);
2381 } else {
2382 throw new IllegalStateException("Source completer required to read "
2383 + classfile.toUri());
2384 }
2385 }
2386 return;
2387 } catch (IOException ex) {
2388 throw badClassFile("unable.to.access.file", ex.getMessage());
2389 } finally {
2390 currentClassFile = previousClassFile;
2391 }
2392 } else {
2393 JCDiagnostic diag =
2394 diagFactory.fragment("class.file.not.found", c.flatname);
2395 throw
2396 newCompletionFailure(c, diag);
2397 }
2398 }
2399 // where
2400 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2401 try {
2402 buf = ensureCapacity(buf, s.available());
2403 int r = s.read(buf);
2404 int bp = 0;
2405 while (r != -1) {
2406 bp += r;
2407 buf = ensureCapacity(buf, bp);
2408 r = s.read(buf, bp, buf.length - bp);
2409 }
2410 return buf;
2411 } finally {
2412 try {
2413 s.close();
2414 } catch (IOException e) {
2415 /* Ignore any errors, as this stream may have already
2416 * thrown a related exception which is the one that
2417 * should be reported.
2418 */
2419 }
2420 }
2421 }
2422 private static byte[] ensureCapacity(byte[] buf, int needed) {
2423 if (buf.length < needed) {
2424 byte[] old = buf;
2425 buf = new byte[Integer.highestOneBit(needed) << 1];
2426 System.arraycopy(old, 0, buf, 0, old.length);
2427 }
2428 return buf;
2429 }
2430 /** Static factory for CompletionFailure objects.
2431 * In practice, only one can be used at a time, so we share one
2432 * to reduce the expense of allocating new exception objects.
2433 */
2434 private CompletionFailure newCompletionFailure(TypeSymbol c,
2435 JCDiagnostic diag) {
2436 if (!cacheCompletionFailure) {
2437 // log.warning("proc.messager",
2438 // Log.getLocalizedString("class.file.not.found", c.flatname));
2439 // c.debug.printStackTrace();
2440 return new CompletionFailure(c, diag);
2441 } else {
2442 CompletionFailure result = cachedCompletionFailure;
2443 result.sym = c;
2444 result.diag = diag;
2445 return result;
2446 }
2447 }
2448 private CompletionFailure cachedCompletionFailure =
2449 new CompletionFailure(null, (JCDiagnostic) null);
2450 {
2451 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2452 }
2454 /** Load a toplevel class with given fully qualified name
2455 * The class is entered into `classes' only if load was successful.
2456 */
2457 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2458 boolean absent = classes.get(flatname) == null;
2459 ClassSymbol c = enterClass(flatname);
2460 if (c.members_field == null && c.completer != null) {
2461 try {
2462 c.complete();
2463 } catch (CompletionFailure ex) {
2464 if (absent) classes.remove(flatname);
2465 throw ex;
2466 }
2467 }
2468 return c;
2469 }
2471 /************************************************************************
2472 * Loading Packages
2473 ***********************************************************************/
2475 /** Check to see if a package exists, given its fully qualified name.
2476 */
2477 public boolean packageExists(Name fullname) {
2478 return enterPackage(fullname).exists();
2479 }
2481 /** Make a package, given its fully qualified name.
2482 */
2483 public PackageSymbol enterPackage(Name fullname) {
2484 PackageSymbol p = packages.get(fullname);
2485 if (p == null) {
2486 assert !fullname.isEmpty() : "rootPackage missing!";
2487 p = new PackageSymbol(
2488 Convert.shortName(fullname),
2489 enterPackage(Convert.packagePart(fullname)));
2490 p.completer = this;
2491 packages.put(fullname, p);
2492 }
2493 return p;
2494 }
2496 /** Make a package, given its unqualified name and enclosing package.
2497 */
2498 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2499 return enterPackage(TypeSymbol.formFullName(name, owner));
2500 }
2502 /** Include class corresponding to given class file in package,
2503 * unless (1) we already have one the same kind (.class or .java), or
2504 * (2) we have one of the other kind, and the given class file
2505 * is older.
2506 */
2507 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2508 if ((p.flags_field & EXISTS) == 0)
2509 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2510 q.flags_field |= EXISTS;
2511 JavaFileObject.Kind kind = file.getKind();
2512 int seen;
2513 if (kind == JavaFileObject.Kind.CLASS)
2514 seen = CLASS_SEEN;
2515 else
2516 seen = SOURCE_SEEN;
2517 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2518 int lastDot = binaryName.lastIndexOf(".");
2519 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2520 boolean isPkgInfo = classname == names.package_info;
2521 ClassSymbol c = isPkgInfo
2522 ? p.package_info
2523 : (ClassSymbol) p.members_field.lookup(classname).sym;
2524 if (c == null) {
2525 c = enterClass(classname, p);
2526 if (c.classfile == null) // only update the file if's it's newly created
2527 c.classfile = file;
2528 if (isPkgInfo) {
2529 p.package_info = c;
2530 } else {
2531 if (c.owner == p) // it might be an inner class
2532 p.members_field.enter(c);
2533 }
2534 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2535 // if c.classfile == null, we are currently compiling this class
2536 // and no further action is necessary.
2537 // if (c.flags_field & seen) != 0, we have already encountered
2538 // a file of the same kind; again no further action is necessary.
2539 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2540 c.classfile = preferredFileObject(file, c.classfile);
2541 }
2542 c.flags_field |= seen;
2543 }
2545 /** Implement policy to choose to derive information from a source
2546 * file or a class file when both are present. May be overridden
2547 * by subclasses.
2548 */
2549 protected JavaFileObject preferredFileObject(JavaFileObject a,
2550 JavaFileObject b) {
2552 if (preferSource)
2553 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2554 else {
2555 long adate = a.getLastModified();
2556 long bdate = b.getLastModified();
2557 // 6449326: policy for bad lastModifiedTime in ClassReader
2558 //assert adate >= 0 && bdate >= 0;
2559 return (adate > bdate) ? a : b;
2560 }
2561 }
2563 /**
2564 * specifies types of files to be read when filling in a package symbol
2565 */
2566 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2567 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2568 }
2570 /**
2571 * this is used to support javadoc
2572 */
2573 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2574 }
2576 protected Location currentLoc; // FIXME
2578 private boolean verbosePath = true;
2580 /** Load directory of package into members scope.
2581 */
2582 private void fillIn(PackageSymbol p) throws IOException {
2583 if (p.members_field == null) p.members_field = new Scope(p);
2584 String packageName = p.fullname.toString();
2586 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2588 fillIn(p, PLATFORM_CLASS_PATH,
2589 fileManager.list(PLATFORM_CLASS_PATH,
2590 packageName,
2591 EnumSet.of(JavaFileObject.Kind.CLASS),
2592 false));
2594 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2595 classKinds.remove(JavaFileObject.Kind.SOURCE);
2596 boolean wantClassFiles = !classKinds.isEmpty();
2598 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2599 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2600 boolean wantSourceFiles = !sourceKinds.isEmpty();
2602 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2604 if (verbose && verbosePath) {
2605 if (fileManager instanceof StandardJavaFileManager) {
2606 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2607 if (haveSourcePath && wantSourceFiles) {
2608 List<File> path = List.nil();
2609 for (File file : fm.getLocation(SOURCE_PATH)) {
2610 path = path.prepend(file);
2611 }
2612 printVerbose("sourcepath", path.reverse().toString());
2613 } else if (wantSourceFiles) {
2614 List<File> path = List.nil();
2615 for (File file : fm.getLocation(CLASS_PATH)) {
2616 path = path.prepend(file);
2617 }
2618 printVerbose("sourcepath", path.reverse().toString());
2619 }
2620 if (wantClassFiles) {
2621 List<File> path = List.nil();
2622 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2623 path = path.prepend(file);
2624 }
2625 for (File file : fm.getLocation(CLASS_PATH)) {
2626 path = path.prepend(file);
2627 }
2628 printVerbose("classpath", path.reverse().toString());
2629 }
2630 }
2631 }
2633 if (wantSourceFiles && !haveSourcePath) {
2634 fillIn(p, CLASS_PATH,
2635 fileManager.list(CLASS_PATH,
2636 packageName,
2637 kinds,
2638 false));
2639 } else {
2640 if (wantClassFiles)
2641 fillIn(p, CLASS_PATH,
2642 fileManager.list(CLASS_PATH,
2643 packageName,
2644 classKinds,
2645 false));
2646 if (wantSourceFiles)
2647 fillIn(p, SOURCE_PATH,
2648 fileManager.list(SOURCE_PATH,
2649 packageName,
2650 sourceKinds,
2651 false));
2652 }
2653 verbosePath = false;
2654 }
2655 // where
2656 private void fillIn(PackageSymbol p,
2657 Location location,
2658 Iterable<JavaFileObject> files)
2659 {
2660 currentLoc = location;
2661 for (JavaFileObject fo : files) {
2662 switch (fo.getKind()) {
2663 case CLASS:
2664 case SOURCE: {
2665 // TODO pass binaryName to includeClassFile
2666 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2667 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2668 if (SourceVersion.isIdentifier(simpleName) ||
2669 simpleName.equals("package-info"))
2670 includeClassFile(p, fo);
2671 break;
2672 }
2673 default:
2674 extraFileActions(p, fo);
2675 }
2676 }
2677 }
2679 /** Output for "-verbose" option.
2680 * @param key The key to look up the correct internationalized string.
2681 * @param arg An argument for substitution into the output string.
2682 */
2683 private void printVerbose(String key, CharSequence arg) {
2684 log.printNoteLines("verbose." + key, arg);
2685 }
2687 /** Output for "-checkclassfile" option.
2688 * @param key The key to look up the correct internationalized string.
2689 * @param arg An argument for substitution into the output string.
2690 */
2691 private void printCCF(String key, Object arg) {
2692 log.printNoteLines(key, arg);
2693 }
2696 public interface SourceCompleter {
2697 void complete(ClassSymbol sym)
2698 throws CompletionFailure;
2699 }
2701 /**
2702 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2703 * The attribute is only the last component of the original filename, so is unlikely
2704 * to be valid as is, so operations other than those to access the name throw
2705 * UnsupportedOperationException
2706 */
2707 private static class SourceFileObject extends BaseFileObject {
2709 /** The file's name.
2710 */
2711 private Name name;
2712 private Name flatname;
2714 public SourceFileObject(Name name, Name flatname) {
2715 super(null); // no file manager; never referenced for this file object
2716 this.name = name;
2717 this.flatname = flatname;
2718 }
2720 @Override
2721 public URI toUri() {
2722 try {
2723 return new URI(null, name.toString(), null);
2724 } catch (URISyntaxException e) {
2725 throw new CannotCreateUriError(name.toString(), e);
2726 }
2727 }
2729 @Override
2730 public String getName() {
2731 return name.toString();
2732 }
2734 @Override
2735 public String getShortName() {
2736 return getName();
2737 }
2739 @Override
2740 public JavaFileObject.Kind getKind() {
2741 return getKind(getName());
2742 }
2744 @Override
2745 public InputStream openInputStream() {
2746 throw new UnsupportedOperationException();
2747 }
2749 @Override
2750 public OutputStream openOutputStream() {
2751 throw new UnsupportedOperationException();
2752 }
2754 @Override
2755 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2756 throw new UnsupportedOperationException();
2757 }
2759 @Override
2760 public Reader openReader(boolean ignoreEncodingErrors) {
2761 throw new UnsupportedOperationException();
2762 }
2764 @Override
2765 public Writer openWriter() {
2766 throw new UnsupportedOperationException();
2767 }
2769 @Override
2770 public long getLastModified() {
2771 throw new UnsupportedOperationException();
2772 }
2774 @Override
2775 public boolean delete() {
2776 throw new UnsupportedOperationException();
2777 }
2779 @Override
2780 protected String inferBinaryName(Iterable<? extends File> path) {
2781 return flatname.toString();
2782 }
2784 @Override
2785 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2786 return true; // fail-safe mode
2787 }
2789 /**
2790 * Check if two file objects are equal.
2791 * SourceFileObjects are just placeholder objects for the value of a
2792 * SourceFile attribute, and do not directly represent specific files.
2793 * Two SourceFileObjects are equal if their names are equal.
2794 */
2795 @Override
2796 public boolean equals(Object other) {
2797 if (this == other)
2798 return true;
2800 if (!(other instanceof SourceFileObject))
2801 return false;
2803 SourceFileObject o = (SourceFileObject) other;
2804 return name.equals(o.name);
2805 }
2807 @Override
2808 public int hashCode() {
2809 return name.hashCode();
2810 }
2811 }
2812 }