Mon, 03 Dec 2012 11:16:32 +0100
8001114: Container annotation is not checked for semantic correctness
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 boolean allInterfaces = false;
850 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
851 sigp++;
852 allInterfaces = true;
853 }
854 while (signature[sigp] == ':') {
855 sigp++;
856 bounds = bounds.prepend(sigToType());
857 }
858 if (!sigEnterPhase) {
859 types.setBounds(tvar, bounds.reverse(), allInterfaces);
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);
1010 }
1011 parameterNameIndices[register] = nameIndex;
1012 haveParameterNameIndices = true;
1013 }
1014 }
1015 }
1016 bp = newbp;
1017 }
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;
1033 }
1034 }
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;
1042 }
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;
1052 }
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;
1059 }
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;
1075 }
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;
1083 }
1084 }
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);
1092 }
1093 },
1095 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1096 protected void read(Symbol sym, int attrLen) {
1097 attachAnnotations(sym);
1098 }
1099 },
1101 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1102 protected void read(Symbol sym, int attrLen) {
1103 attachParameterAnnotations(sym);
1104 }
1105 },
1107 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1108 protected void read(Symbol sym, int attrLen) {
1109 attachAnnotations(sym);
1110 }
1111 },
1113 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1114 protected void read(Symbol sym, int attrLen) {
1115 attachParameterAnnotations(sym);
1116 }
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;
1125 }
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;
1133 }
1134 },
1136 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1137 protected void read(Symbol sym, int attrLen) {
1138 sym.flags_field |= ENUM;
1139 }
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;
1146 }
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);
1158 }
1160 /** Report unrecognized attribute.
1161 */
1162 void unrecognized(Name attrName) {
1163 if (checkClassFile)
1164 printCCF("ccf.unrecognized.attribute", attrName);
1165 }
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);
1198 }
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));
1204 }
1205 foundTypeVariables = typeVars.toList();
1206 } else {
1207 foundTypeVariables = List.nil();
1208 }
1209 }
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));
1221 }
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);
1251 }
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;
1263 }
1264 return types1.isEmpty() && types2.isEmpty();
1265 }
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';
1273 }
1275 /** Read member attributes.
1276 */
1277 void readMemberAttrs(Symbol sym) {
1278 readAttrs(sym, AttributeKind.MEMBER);
1279 }
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;
1292 }
1293 }
1294 }
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);
1304 }
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;
1317 }
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);
1336 }
1337 annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1338 }
1339 }
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++;
1352 }
1353 if (pnum != numParameters) {
1354 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1355 }
1356 }
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();
1364 // The default value is set later during annotation. It might
1365 // be the case that the Symbol sym is annotated _after_ the
1366 // repeating instances that depend on this default value,
1367 // because of this we set an interim value that tells us this
1368 // element (most likely) has a default.
1369 //
1370 // Set interim value for now, reset just before we do this
1371 // properly at annotate time.
1372 meth.defaultValue = value;
1373 annotate.normal(new AnnotationDefaultCompleter(meth, value));
1374 }
1376 Type readTypeOrClassSymbol(int i) {
1377 // support preliminary jsr175-format class files
1378 if (buf[poolIdx[i]] == CONSTANT_Class)
1379 return readClassSymbol(i).type;
1380 return readType(i);
1381 }
1382 Type readEnumType(int i) {
1383 // support preliminary jsr175-format class files
1384 int index = poolIdx[i];
1385 int length = getChar(index + 1);
1386 if (buf[index + length + 2] != ';')
1387 return enterClass(readName(i)).type;
1388 return readType(i);
1389 }
1391 CompoundAnnotationProxy readCompoundAnnotation() {
1392 Type t = readTypeOrClassSymbol(nextChar());
1393 int numFields = nextChar();
1394 ListBuffer<Pair<Name,Attribute>> pairs =
1395 new ListBuffer<Pair<Name,Attribute>>();
1396 for (int i=0; i<numFields; i++) {
1397 Name name = readName(nextChar());
1398 Attribute value = readAttributeValue();
1399 pairs.append(new Pair<Name,Attribute>(name, value));
1400 }
1401 return new CompoundAnnotationProxy(t, pairs.toList());
1402 }
1404 Attribute readAttributeValue() {
1405 char c = (char) buf[bp++];
1406 switch (c) {
1407 case 'B':
1408 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1409 case 'C':
1410 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1411 case 'D':
1412 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1413 case 'F':
1414 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1415 case 'I':
1416 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1417 case 'J':
1418 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1419 case 'S':
1420 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1421 case 'Z':
1422 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1423 case 's':
1424 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1425 case 'e':
1426 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1427 case 'c':
1428 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1429 case '[': {
1430 int n = nextChar();
1431 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1432 for (int i=0; i<n; i++)
1433 l.append(readAttributeValue());
1434 return new ArrayAttributeProxy(l.toList());
1435 }
1436 case '@':
1437 return readCompoundAnnotation();
1438 default:
1439 throw new AssertionError("unknown annotation tag '" + c + "'");
1440 }
1441 }
1443 interface ProxyVisitor extends Attribute.Visitor {
1444 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1445 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1446 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1447 }
1449 static class EnumAttributeProxy extends Attribute {
1450 Type enumType;
1451 Name enumerator;
1452 public EnumAttributeProxy(Type enumType, Name enumerator) {
1453 super(null);
1454 this.enumType = enumType;
1455 this.enumerator = enumerator;
1456 }
1457 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1458 @Override
1459 public String toString() {
1460 return "/*proxy enum*/" + enumType + "." + enumerator;
1461 }
1462 }
1464 static class ArrayAttributeProxy extends Attribute {
1465 List<Attribute> values;
1466 ArrayAttributeProxy(List<Attribute> values) {
1467 super(null);
1468 this.values = values;
1469 }
1470 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1471 @Override
1472 public String toString() {
1473 return "{" + values + "}";
1474 }
1475 }
1477 /** A temporary proxy representing a compound attribute.
1478 */
1479 static class CompoundAnnotationProxy extends Attribute {
1480 final List<Pair<Name,Attribute>> values;
1481 public CompoundAnnotationProxy(Type type,
1482 List<Pair<Name,Attribute>> values) {
1483 super(type);
1484 this.values = values;
1485 }
1486 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1487 @Override
1488 public String toString() {
1489 StringBuilder buf = new StringBuilder();
1490 buf.append("@");
1491 buf.append(type.tsym.getQualifiedName());
1492 buf.append("/*proxy*/{");
1493 boolean first = true;
1494 for (List<Pair<Name,Attribute>> v = values;
1495 v.nonEmpty(); v = v.tail) {
1496 Pair<Name,Attribute> value = v.head;
1497 if (!first) buf.append(",");
1498 first = false;
1499 buf.append(value.fst);
1500 buf.append("=");
1501 buf.append(value.snd);
1502 }
1503 buf.append("}");
1504 return buf.toString();
1505 }
1506 }
1508 /** A temporary proxy representing a type annotation.
1509 */
1510 static class TypeAnnotationProxy {
1511 final CompoundAnnotationProxy compound;
1512 final TypeAnnotationPosition position;
1513 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1514 TypeAnnotationPosition position) {
1515 this.compound = compound;
1516 this.position = position;
1517 }
1518 }
1520 class AnnotationDeproxy implements ProxyVisitor {
1521 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1522 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1524 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1525 // also must fill in types!!!!
1526 ListBuffer<Attribute.Compound> buf =
1527 new ListBuffer<Attribute.Compound>();
1528 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1529 buf.append(deproxyCompound(l.head));
1530 }
1531 return buf.toList();
1532 }
1534 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1535 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1536 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1537 for (List<Pair<Name,Attribute>> l = a.values;
1538 l.nonEmpty();
1539 l = l.tail) {
1540 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1541 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1542 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1543 }
1544 return new Attribute.Compound(a.type, buf.toList());
1545 }
1547 MethodSymbol findAccessMethod(Type container, Name name) {
1548 CompletionFailure failure = null;
1549 try {
1550 for (Scope.Entry e = container.tsym.members().lookup(name);
1551 e.scope != null;
1552 e = e.next()) {
1553 Symbol sym = e.sym;
1554 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1555 return (MethodSymbol) sym;
1556 }
1557 } catch (CompletionFailure ex) {
1558 failure = ex;
1559 }
1560 // The method wasn't found: emit a warning and recover
1561 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1562 try {
1563 if (failure == null) {
1564 log.warning("annotation.method.not.found",
1565 container,
1566 name);
1567 } else {
1568 log.warning("annotation.method.not.found.reason",
1569 container,
1570 name,
1571 failure.getDetailValue());//diagnostic, if present
1572 }
1573 } finally {
1574 log.useSource(prevSource);
1575 }
1576 // Construct a new method type and symbol. Use bottom
1577 // type (typeof null) as return type because this type is
1578 // a subtype of all reference types and can be converted
1579 // to primitive types by unboxing.
1580 MethodType mt = new MethodType(List.<Type>nil(),
1581 syms.botType,
1582 List.<Type>nil(),
1583 syms.methodClass);
1584 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1585 }
1587 Attribute result;
1588 Type type;
1589 Attribute deproxy(Type t, Attribute a) {
1590 Type oldType = type;
1591 try {
1592 type = t;
1593 a.accept(this);
1594 return result;
1595 } finally {
1596 type = oldType;
1597 }
1598 }
1600 // implement Attribute.Visitor below
1602 public void visitConstant(Attribute.Constant value) {
1603 // assert value.type == type;
1604 result = value;
1605 }
1607 public void visitClass(Attribute.Class clazz) {
1608 result = clazz;
1609 }
1611 public void visitEnum(Attribute.Enum e) {
1612 throw new AssertionError(); // shouldn't happen
1613 }
1615 public void visitCompound(Attribute.Compound compound) {
1616 throw new AssertionError(); // shouldn't happen
1617 }
1619 public void visitArray(Attribute.Array array) {
1620 throw new AssertionError(); // shouldn't happen
1621 }
1623 public void visitError(Attribute.Error e) {
1624 throw new AssertionError(); // shouldn't happen
1625 }
1627 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1628 // type.tsym.flatName() should == proxy.enumFlatName
1629 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1630 VarSymbol enumerator = null;
1631 CompletionFailure failure = null;
1632 try {
1633 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1634 e.scope != null;
1635 e = e.next()) {
1636 if (e.sym.kind == VAR) {
1637 enumerator = (VarSymbol)e.sym;
1638 break;
1639 }
1640 }
1641 }
1642 catch (CompletionFailure ex) {
1643 failure = ex;
1644 }
1645 if (enumerator == null) {
1646 if (failure != null) {
1647 log.warning("unknown.enum.constant.reason",
1648 currentClassFile, enumTypeSym, proxy.enumerator,
1649 failure.getDiagnostic());
1650 } else {
1651 log.warning("unknown.enum.constant",
1652 currentClassFile, enumTypeSym, proxy.enumerator);
1653 }
1654 result = new Attribute.Enum(enumTypeSym.type,
1655 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1656 } else {
1657 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1658 }
1659 }
1661 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1662 int length = proxy.values.length();
1663 Attribute[] ats = new Attribute[length];
1664 Type elemtype = types.elemtype(type);
1665 int i = 0;
1666 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1667 ats[i++] = deproxy(elemtype, p.head);
1668 }
1669 result = new Attribute.Array(type, ats);
1670 }
1672 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1673 result = deproxyCompound(proxy);
1674 }
1675 }
1677 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1678 final MethodSymbol sym;
1679 final Attribute value;
1680 final JavaFileObject classFile = currentClassFile;
1681 @Override
1682 public String toString() {
1683 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1684 }
1685 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1686 this.sym = sym;
1687 this.value = value;
1688 }
1689 // implement Annotate.Annotator.enterAnnotation()
1690 public void enterAnnotation() {
1691 JavaFileObject previousClassFile = currentClassFile;
1692 try {
1693 // Reset the interim value set earlier in
1694 // attachAnnotationDefault().
1695 sym.defaultValue = null;
1696 currentClassFile = classFile;
1697 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1698 } finally {
1699 currentClassFile = previousClassFile;
1700 }
1701 }
1702 }
1704 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1705 final Symbol sym;
1706 final List<CompoundAnnotationProxy> l;
1707 final JavaFileObject classFile;
1708 @Override
1709 public String toString() {
1710 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1711 }
1712 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1713 this.sym = sym;
1714 this.l = l;
1715 this.classFile = currentClassFile;
1716 }
1717 // implement Annotate.Annotator.enterAnnotation()
1718 public void enterAnnotation() {
1719 JavaFileObject previousClassFile = currentClassFile;
1720 try {
1721 currentClassFile = classFile;
1722 Annotations annotations = sym.annotations;
1723 List<Attribute.Compound> newList = deproxyCompoundList(l);
1724 if (annotations.pendingCompletion()) {
1725 annotations.setAttributes(newList);
1726 } else {
1727 annotations.append(newList);
1728 }
1729 } finally {
1730 currentClassFile = previousClassFile;
1731 }
1732 }
1733 }
1736 /************************************************************************
1737 * Reading Symbols
1738 ***********************************************************************/
1740 /** Read a field.
1741 */
1742 VarSymbol readField() {
1743 long flags = adjustFieldFlags(nextChar());
1744 Name name = readName(nextChar());
1745 Type type = readType(nextChar());
1746 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1747 readMemberAttrs(v);
1748 return v;
1749 }
1751 /** Read a method.
1752 */
1753 MethodSymbol readMethod() {
1754 long flags = adjustMethodFlags(nextChar());
1755 Name name = readName(nextChar());
1756 Type type = readType(nextChar());
1757 if (currentOwner.isInterface() &&
1758 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
1759 if (majorVersion > Target.JDK1_8.majorVersion ||
1760 (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
1761 currentOwner.flags_field |= DEFAULT;
1762 flags |= DEFAULT | ABSTRACT;
1763 } else {
1764 //protect against ill-formed classfiles
1765 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
1766 }
1767 }
1768 if (name == names.init && currentOwner.hasOuterInstance()) {
1769 // Sometimes anonymous classes don't have an outer
1770 // instance, however, there is no reliable way to tell so
1771 // we never strip this$n
1772 if (!currentOwner.name.isEmpty())
1773 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1774 type.getReturnType(),
1775 type.getThrownTypes(),
1776 syms.methodClass);
1777 }
1778 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1779 if (saveParameterNames)
1780 initParameterNames(m);
1781 Symbol prevOwner = currentOwner;
1782 currentOwner = m;
1783 try {
1784 readMemberAttrs(m);
1785 } finally {
1786 currentOwner = prevOwner;
1787 }
1788 if (saveParameterNames)
1789 setParameterNames(m, type);
1790 return m;
1791 }
1793 private List<Type> adjustMethodParams(long flags, List<Type> args) {
1794 boolean isVarargs = (flags & VARARGS) != 0;
1795 if (isVarargs) {
1796 Type varargsElem = args.last();
1797 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
1798 for (Type t : args) {
1799 adjustedArgs.append(t != varargsElem ?
1800 t :
1801 ((ArrayType)t).makeVarargs());
1802 }
1803 args = adjustedArgs.toList();
1804 }
1805 return args.tail;
1806 }
1808 /**
1809 * Init the parameter names array.
1810 * Parameter names are currently inferred from the names in the
1811 * LocalVariableTable attributes of a Code attribute.
1812 * (Note: this means parameter names are currently not available for
1813 * methods without a Code attribute.)
1814 * This method initializes an array in which to store the name indexes
1815 * of parameter names found in LocalVariableTable attributes. It is
1816 * slightly supersized to allow for additional slots with a start_pc of 0.
1817 */
1818 void initParameterNames(MethodSymbol sym) {
1819 // make allowance for synthetic parameters.
1820 final int excessSlots = 4;
1821 int expectedParameterSlots =
1822 Code.width(sym.type.getParameterTypes()) + excessSlots;
1823 if (parameterNameIndices == null
1824 || parameterNameIndices.length < expectedParameterSlots) {
1825 parameterNameIndices = new int[expectedParameterSlots];
1826 } else
1827 Arrays.fill(parameterNameIndices, 0);
1828 haveParameterNameIndices = false;
1829 }
1831 /**
1832 * Set the parameter names for a symbol from the name index in the
1833 * parameterNameIndicies array. The type of the symbol may have changed
1834 * while reading the method attributes (see the Signature attribute).
1835 * This may be because of generic information or because anonymous
1836 * synthetic parameters were added. The original type (as read from
1837 * the method descriptor) is used to help guess the existence of
1838 * anonymous synthetic parameters.
1839 * On completion, sym.savedParameter names will either be null (if
1840 * no parameter names were found in the class file) or will be set to a
1841 * list of names, one per entry in sym.type.getParameterTypes, with
1842 * any missing names represented by the empty name.
1843 */
1844 void setParameterNames(MethodSymbol sym, Type jvmType) {
1845 // if no names were found in the class file, there's nothing more to do
1846 if (!haveParameterNameIndices)
1847 return;
1849 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1850 // the code in readMethod may have skipped the first parameter when
1851 // setting up the MethodType. If so, we make a corresponding allowance
1852 // here for the position of the first parameter. Note that this
1853 // assumes the skipped parameter has a width of 1 -- i.e. it is not
1854 // a double width type (long or double.)
1855 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1856 // Sometimes anonymous classes don't have an outer
1857 // instance, however, there is no reliable way to tell so
1858 // we never strip this$n
1859 if (!currentOwner.name.isEmpty())
1860 firstParam += 1;
1861 }
1863 if (sym.type != jvmType) {
1864 // reading the method attributes has caused the symbol's type to
1865 // be changed. (i.e. the Signature attribute.) This may happen if
1866 // there are hidden (synthetic) parameters in the descriptor, but
1867 // not in the Signature. The position of these hidden parameters
1868 // is unspecified; for now, assume they are at the beginning, and
1869 // so skip over them. The primary case for this is two hidden
1870 // parameters passed into Enum constructors.
1871 int skip = Code.width(jvmType.getParameterTypes())
1872 - Code.width(sym.type.getParameterTypes());
1873 firstParam += skip;
1874 }
1875 List<Name> paramNames = List.nil();
1876 int index = firstParam;
1877 for (Type t: sym.type.getParameterTypes()) {
1878 int nameIdx = (index < parameterNameIndices.length
1879 ? parameterNameIndices[index] : 0);
1880 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
1881 paramNames = paramNames.prepend(name);
1882 index += Code.width(t);
1883 }
1884 sym.savedParameterNames = paramNames.reverse();
1885 }
1887 /**
1888 * skip n bytes
1889 */
1890 void skipBytes(int n) {
1891 bp = bp + n;
1892 }
1894 /** Skip a field or method
1895 */
1896 void skipMember() {
1897 bp = bp + 6;
1898 char ac = nextChar();
1899 for (int i = 0; i < ac; i++) {
1900 bp = bp + 2;
1901 int attrLen = nextInt();
1902 bp = bp + attrLen;
1903 }
1904 }
1906 /** Enter type variables of this classtype and all enclosing ones in
1907 * `typevars'.
1908 */
1909 protected void enterTypevars(Type t) {
1910 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
1911 enterTypevars(t.getEnclosingType());
1912 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1913 typevars.enter(xs.head.tsym);
1914 }
1916 protected void enterTypevars(Symbol sym) {
1917 if (sym.owner.kind == MTH) {
1918 enterTypevars(sym.owner);
1919 enterTypevars(sym.owner.owner);
1920 }
1921 enterTypevars(sym.type);
1922 }
1924 /** Read contents of a given class symbol `c'. Both external and internal
1925 * versions of an inner class are read.
1926 */
1927 void readClass(ClassSymbol c) {
1928 ClassType ct = (ClassType)c.type;
1930 // allocate scope for members
1931 c.members_field = new Scope(c);
1933 // prepare type variable table
1934 typevars = typevars.dup(currentOwner);
1935 if (ct.getEnclosingType().hasTag(CLASS))
1936 enterTypevars(ct.getEnclosingType());
1938 // read flags, or skip if this is an inner class
1939 long flags = adjustClassFlags(nextChar());
1940 if (c.owner.kind == PCK) c.flags_field = flags;
1942 // read own class name and check that it matches
1943 ClassSymbol self = readClassSymbol(nextChar());
1944 if (c != self)
1945 throw badClassFile("class.file.wrong.class",
1946 self.flatname);
1948 // class attributes must be read before class
1949 // skip ahead to read class attributes
1950 int startbp = bp;
1951 nextChar();
1952 char interfaceCount = nextChar();
1953 bp += interfaceCount * 2;
1954 char fieldCount = nextChar();
1955 for (int i = 0; i < fieldCount; i++) skipMember();
1956 char methodCount = nextChar();
1957 for (int i = 0; i < methodCount; i++) skipMember();
1958 readClassAttrs(c);
1960 if (readAllOfClassFile) {
1961 for (int i = 1; i < poolObj.length; i++) readPool(i);
1962 c.pool = new Pool(poolObj.length, poolObj);
1963 }
1965 // reset and read rest of classinfo
1966 bp = startbp;
1967 int n = nextChar();
1968 if (ct.supertype_field == null)
1969 ct.supertype_field = (n == 0)
1970 ? Type.noType
1971 : readClassSymbol(n).erasure(types);
1972 n = nextChar();
1973 List<Type> is = List.nil();
1974 for (int i = 0; i < n; i++) {
1975 Type _inter = readClassSymbol(nextChar()).erasure(types);
1976 is = is.prepend(_inter);
1977 }
1978 if (ct.interfaces_field == null)
1979 ct.interfaces_field = is.reverse();
1981 Assert.check(fieldCount == nextChar());
1982 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
1983 Assert.check(methodCount == nextChar());
1984 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
1986 typevars = typevars.leave();
1987 }
1989 /** Read inner class info. For each inner/outer pair allocate a
1990 * member class.
1991 */
1992 void readInnerClasses(ClassSymbol c) {
1993 int n = nextChar();
1994 for (int i = 0; i < n; i++) {
1995 nextChar(); // skip inner class symbol
1996 ClassSymbol outer = readClassSymbol(nextChar());
1997 Name name = readName(nextChar());
1998 if (name == null) name = names.empty;
1999 long flags = adjustClassFlags(nextChar());
2000 if (outer != null) { // we have a member class
2001 if (name == names.empty)
2002 name = names.one;
2003 ClassSymbol member = enterClass(name, outer);
2004 if ((flags & STATIC) == 0) {
2005 ((ClassType)member.type).setEnclosingType(outer.type);
2006 if (member.erasure_field != null)
2007 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2008 }
2009 if (c == outer) {
2010 member.flags_field = flags;
2011 enterMember(c, member);
2012 }
2013 }
2014 }
2015 }
2017 /** Read a class file.
2018 */
2019 private void readClassFile(ClassSymbol c) throws IOException {
2020 int magic = nextInt();
2021 if (magic != JAVA_MAGIC)
2022 throw badClassFile("illegal.start.of.class.file");
2024 minorVersion = nextChar();
2025 majorVersion = nextChar();
2026 int maxMajor = Target.MAX().majorVersion;
2027 int maxMinor = Target.MAX().minorVersion;
2028 if (majorVersion > maxMajor ||
2029 majorVersion * 1000 + minorVersion <
2030 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2031 {
2032 if (majorVersion == (maxMajor + 1))
2033 log.warning("big.major.version",
2034 currentClassFile,
2035 majorVersion,
2036 maxMajor);
2037 else
2038 throw badClassFile("wrong.version",
2039 Integer.toString(majorVersion),
2040 Integer.toString(minorVersion),
2041 Integer.toString(maxMajor),
2042 Integer.toString(maxMinor));
2043 }
2044 else if (checkClassFile &&
2045 majorVersion == maxMajor &&
2046 minorVersion > maxMinor)
2047 {
2048 printCCF("found.later.version",
2049 Integer.toString(minorVersion));
2050 }
2051 indexPool();
2052 if (signatureBuffer.length < bp) {
2053 int ns = Integer.highestOneBit(bp) << 1;
2054 signatureBuffer = new byte[ns];
2055 }
2056 readClass(c);
2057 }
2059 /************************************************************************
2060 * Adjusting flags
2061 ***********************************************************************/
2063 long adjustFieldFlags(long flags) {
2064 return flags;
2065 }
2066 long adjustMethodFlags(long flags) {
2067 if ((flags & ACC_BRIDGE) != 0) {
2068 flags &= ~ACC_BRIDGE;
2069 flags |= BRIDGE;
2070 if (!allowGenerics)
2071 flags &= ~SYNTHETIC;
2072 }
2073 if ((flags & ACC_VARARGS) != 0) {
2074 flags &= ~ACC_VARARGS;
2075 flags |= VARARGS;
2076 }
2077 return flags;
2078 }
2079 long adjustClassFlags(long flags) {
2080 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2081 }
2083 /************************************************************************
2084 * Loading Classes
2085 ***********************************************************************/
2087 /** Define a new class given its name and owner.
2088 */
2089 public ClassSymbol defineClass(Name name, Symbol owner) {
2090 ClassSymbol c = new ClassSymbol(0, name, owner);
2091 if (owner.kind == PCK)
2092 Assert.checkNull(classes.get(c.flatname), c);
2093 c.completer = this;
2094 return c;
2095 }
2097 /** Create a new toplevel or member class symbol with given name
2098 * and owner and enter in `classes' unless already there.
2099 */
2100 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2101 Name flatname = TypeSymbol.formFlatName(name, owner);
2102 ClassSymbol c = classes.get(flatname);
2103 if (c == null) {
2104 c = defineClass(name, owner);
2105 classes.put(flatname, c);
2106 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2107 // reassign fields of classes that might have been loaded with
2108 // their flat names.
2109 c.owner.members().remove(c);
2110 c.name = name;
2111 c.owner = owner;
2112 c.fullname = ClassSymbol.formFullName(name, owner);
2113 }
2114 return c;
2115 }
2117 /**
2118 * Creates a new toplevel class symbol with given flat name and
2119 * given class (or source) file.
2120 *
2121 * @param flatName a fully qualified binary class name
2122 * @param classFile the class file or compilation unit defining
2123 * the class (may be {@code null})
2124 * @return a newly created class symbol
2125 * @throws AssertionError if the class symbol already exists
2126 */
2127 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2128 ClassSymbol cs = classes.get(flatName);
2129 if (cs != null) {
2130 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2131 cs.fullname,
2132 cs.completer,
2133 cs.classfile,
2134 cs.sourcefile);
2135 throw new AssertionError(msg);
2136 }
2137 Name packageName = Convert.packagePart(flatName);
2138 PackageSymbol owner = packageName.isEmpty()
2139 ? syms.unnamedPackage
2140 : enterPackage(packageName);
2141 cs = defineClass(Convert.shortName(flatName), owner);
2142 cs.classfile = classFile;
2143 classes.put(flatName, cs);
2144 return cs;
2145 }
2147 /** Create a new member or toplevel class symbol with given flat name
2148 * and enter in `classes' unless already there.
2149 */
2150 public ClassSymbol enterClass(Name flatname) {
2151 ClassSymbol c = classes.get(flatname);
2152 if (c == null)
2153 return enterClass(flatname, (JavaFileObject)null);
2154 else
2155 return c;
2156 }
2158 private boolean suppressFlush = false;
2160 /** Completion for classes to be loaded. Before a class is loaded
2161 * we make sure its enclosing class (if any) is loaded.
2162 */
2163 public void complete(Symbol sym) throws CompletionFailure {
2164 if (sym.kind == TYP) {
2165 ClassSymbol c = (ClassSymbol)sym;
2166 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2167 boolean saveSuppressFlush = suppressFlush;
2168 suppressFlush = true;
2169 try {
2170 completeOwners(c.owner);
2171 completeEnclosing(c);
2172 } finally {
2173 suppressFlush = saveSuppressFlush;
2174 }
2175 fillIn(c);
2176 } else if (sym.kind == PCK) {
2177 PackageSymbol p = (PackageSymbol)sym;
2178 try {
2179 fillIn(p);
2180 } catch (IOException ex) {
2181 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2182 }
2183 }
2184 if (!filling && !suppressFlush)
2185 annotate.flush(); // finish attaching annotations
2186 }
2188 /** complete up through the enclosing package. */
2189 private void completeOwners(Symbol o) {
2190 if (o.kind != PCK) completeOwners(o.owner);
2191 o.complete();
2192 }
2194 /**
2195 * Tries to complete lexically enclosing classes if c looks like a
2196 * nested class. This is similar to completeOwners but handles
2197 * the situation when a nested class is accessed directly as it is
2198 * possible with the Tree API or javax.lang.model.*.
2199 */
2200 private void completeEnclosing(ClassSymbol c) {
2201 if (c.owner.kind == PCK) {
2202 Symbol owner = c.owner;
2203 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2204 Symbol encl = owner.members().lookup(name).sym;
2205 if (encl == null)
2206 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2207 if (encl != null)
2208 encl.complete();
2209 }
2210 }
2211 }
2213 /** We can only read a single class file at a time; this
2214 * flag keeps track of when we are currently reading a class
2215 * file.
2216 */
2217 private boolean filling = false;
2219 /** Fill in definition of class `c' from corresponding class or
2220 * source file.
2221 */
2222 private void fillIn(ClassSymbol c) {
2223 if (completionFailureName == c.fullname) {
2224 throw new CompletionFailure(c, "user-selected completion failure by class name");
2225 }
2226 currentOwner = c;
2227 warnedAttrs.clear();
2228 JavaFileObject classfile = c.classfile;
2229 if (classfile != null) {
2230 JavaFileObject previousClassFile = currentClassFile;
2231 try {
2232 if (filling) {
2233 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2234 }
2235 currentClassFile = classfile;
2236 if (verbose) {
2237 log.printVerbose("loading", currentClassFile.toString());
2238 }
2239 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2240 filling = true;
2241 try {
2242 bp = 0;
2243 buf = readInputStream(buf, classfile.openInputStream());
2244 readClassFile(c);
2245 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2246 List<Type> missing = missingTypeVariables;
2247 List<Type> found = foundTypeVariables;
2248 missingTypeVariables = List.nil();
2249 foundTypeVariables = List.nil();
2250 filling = false;
2251 ClassType ct = (ClassType)currentOwner.type;
2252 ct.supertype_field =
2253 types.subst(ct.supertype_field, missing, found);
2254 ct.interfaces_field =
2255 types.subst(ct.interfaces_field, missing, found);
2256 } else if (missingTypeVariables.isEmpty() !=
2257 foundTypeVariables.isEmpty()) {
2258 Name name = missingTypeVariables.head.tsym.name;
2259 throw badClassFile("undecl.type.var", name);
2260 }
2261 } finally {
2262 missingTypeVariables = List.nil();
2263 foundTypeVariables = List.nil();
2264 filling = false;
2265 }
2266 } else {
2267 if (sourceCompleter != null) {
2268 sourceCompleter.complete(c);
2269 } else {
2270 throw new IllegalStateException("Source completer required to read "
2271 + classfile.toUri());
2272 }
2273 }
2274 return;
2275 } catch (IOException ex) {
2276 throw badClassFile("unable.to.access.file", ex.getMessage());
2277 } finally {
2278 currentClassFile = previousClassFile;
2279 }
2280 } else {
2281 JCDiagnostic diag =
2282 diagFactory.fragment("class.file.not.found", c.flatname);
2283 throw
2284 newCompletionFailure(c, diag);
2285 }
2286 }
2287 // where
2288 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2289 try {
2290 buf = ensureCapacity(buf, s.available());
2291 int r = s.read(buf);
2292 int bp = 0;
2293 while (r != -1) {
2294 bp += r;
2295 buf = ensureCapacity(buf, bp);
2296 r = s.read(buf, bp, buf.length - bp);
2297 }
2298 return buf;
2299 } finally {
2300 try {
2301 s.close();
2302 } catch (IOException e) {
2303 /* Ignore any errors, as this stream may have already
2304 * thrown a related exception which is the one that
2305 * should be reported.
2306 */
2307 }
2308 }
2309 }
2310 /*
2311 * ensureCapacity will increase the buffer as needed, taking note that
2312 * the new buffer will always be greater than the needed and never
2313 * exactly equal to the needed size or bp. If equal then the read (above)
2314 * will infinitely loop as buf.length - bp == 0.
2315 */
2316 private static byte[] ensureCapacity(byte[] buf, int needed) {
2317 if (buf.length <= needed) {
2318 byte[] old = buf;
2319 buf = new byte[Integer.highestOneBit(needed) << 1];
2320 System.arraycopy(old, 0, buf, 0, old.length);
2321 }
2322 return buf;
2323 }
2324 /** Static factory for CompletionFailure objects.
2325 * In practice, only one can be used at a time, so we share one
2326 * to reduce the expense of allocating new exception objects.
2327 */
2328 private CompletionFailure newCompletionFailure(TypeSymbol c,
2329 JCDiagnostic diag) {
2330 if (!cacheCompletionFailure) {
2331 // log.warning("proc.messager",
2332 // Log.getLocalizedString("class.file.not.found", c.flatname));
2333 // c.debug.printStackTrace();
2334 return new CompletionFailure(c, diag);
2335 } else {
2336 CompletionFailure result = cachedCompletionFailure;
2337 result.sym = c;
2338 result.diag = diag;
2339 return result;
2340 }
2341 }
2342 private CompletionFailure cachedCompletionFailure =
2343 new CompletionFailure(null, (JCDiagnostic) null);
2344 {
2345 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2346 }
2348 /** Load a toplevel class with given fully qualified name
2349 * The class is entered into `classes' only if load was successful.
2350 */
2351 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2352 boolean absent = classes.get(flatname) == null;
2353 ClassSymbol c = enterClass(flatname);
2354 if (c.members_field == null && c.completer != null) {
2355 try {
2356 c.complete();
2357 } catch (CompletionFailure ex) {
2358 if (absent) classes.remove(flatname);
2359 throw ex;
2360 }
2361 }
2362 return c;
2363 }
2365 /************************************************************************
2366 * Loading Packages
2367 ***********************************************************************/
2369 /** Check to see if a package exists, given its fully qualified name.
2370 */
2371 public boolean packageExists(Name fullname) {
2372 return enterPackage(fullname).exists();
2373 }
2375 /** Make a package, given its fully qualified name.
2376 */
2377 public PackageSymbol enterPackage(Name fullname) {
2378 PackageSymbol p = packages.get(fullname);
2379 if (p == null) {
2380 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2381 p = new PackageSymbol(
2382 Convert.shortName(fullname),
2383 enterPackage(Convert.packagePart(fullname)));
2384 p.completer = this;
2385 packages.put(fullname, p);
2386 }
2387 return p;
2388 }
2390 /** Make a package, given its unqualified name and enclosing package.
2391 */
2392 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2393 return enterPackage(TypeSymbol.formFullName(name, owner));
2394 }
2396 /** Include class corresponding to given class file in package,
2397 * unless (1) we already have one the same kind (.class or .java), or
2398 * (2) we have one of the other kind, and the given class file
2399 * is older.
2400 */
2401 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2402 if ((p.flags_field & EXISTS) == 0)
2403 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2404 q.flags_field |= EXISTS;
2405 JavaFileObject.Kind kind = file.getKind();
2406 int seen;
2407 if (kind == JavaFileObject.Kind.CLASS)
2408 seen = CLASS_SEEN;
2409 else
2410 seen = SOURCE_SEEN;
2411 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2412 int lastDot = binaryName.lastIndexOf(".");
2413 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2414 boolean isPkgInfo = classname == names.package_info;
2415 ClassSymbol c = isPkgInfo
2416 ? p.package_info
2417 : (ClassSymbol) p.members_field.lookup(classname).sym;
2418 if (c == null) {
2419 c = enterClass(classname, p);
2420 if (c.classfile == null) // only update the file if's it's newly created
2421 c.classfile = file;
2422 if (isPkgInfo) {
2423 p.package_info = c;
2424 } else {
2425 if (c.owner == p) // it might be an inner class
2426 p.members_field.enter(c);
2427 }
2428 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2429 // if c.classfile == null, we are currently compiling this class
2430 // and no further action is necessary.
2431 // if (c.flags_field & seen) != 0, we have already encountered
2432 // a file of the same kind; again no further action is necessary.
2433 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2434 c.classfile = preferredFileObject(file, c.classfile);
2435 }
2436 c.flags_field |= seen;
2437 }
2439 /** Implement policy to choose to derive information from a source
2440 * file or a class file when both are present. May be overridden
2441 * by subclasses.
2442 */
2443 protected JavaFileObject preferredFileObject(JavaFileObject a,
2444 JavaFileObject b) {
2446 if (preferSource)
2447 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2448 else {
2449 long adate = a.getLastModified();
2450 long bdate = b.getLastModified();
2451 // 6449326: policy for bad lastModifiedTime in ClassReader
2452 //assert adate >= 0 && bdate >= 0;
2453 return (adate > bdate) ? a : b;
2454 }
2455 }
2457 /**
2458 * specifies types of files to be read when filling in a package symbol
2459 */
2460 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2461 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2462 }
2464 /**
2465 * this is used to support javadoc
2466 */
2467 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2468 }
2470 protected Location currentLoc; // FIXME
2472 private boolean verbosePath = true;
2474 /** Load directory of package into members scope.
2475 */
2476 private void fillIn(PackageSymbol p) throws IOException {
2477 if (p.members_field == null) p.members_field = new Scope(p);
2478 String packageName = p.fullname.toString();
2480 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2482 fillIn(p, PLATFORM_CLASS_PATH,
2483 fileManager.list(PLATFORM_CLASS_PATH,
2484 packageName,
2485 EnumSet.of(JavaFileObject.Kind.CLASS),
2486 false));
2488 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2489 classKinds.remove(JavaFileObject.Kind.SOURCE);
2490 boolean wantClassFiles = !classKinds.isEmpty();
2492 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2493 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2494 boolean wantSourceFiles = !sourceKinds.isEmpty();
2496 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2498 if (verbose && verbosePath) {
2499 if (fileManager instanceof StandardJavaFileManager) {
2500 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2501 if (haveSourcePath && wantSourceFiles) {
2502 List<File> path = List.nil();
2503 for (File file : fm.getLocation(SOURCE_PATH)) {
2504 path = path.prepend(file);
2505 }
2506 log.printVerbose("sourcepath", path.reverse().toString());
2507 } else if (wantSourceFiles) {
2508 List<File> path = List.nil();
2509 for (File file : fm.getLocation(CLASS_PATH)) {
2510 path = path.prepend(file);
2511 }
2512 log.printVerbose("sourcepath", path.reverse().toString());
2513 }
2514 if (wantClassFiles) {
2515 List<File> path = List.nil();
2516 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2517 path = path.prepend(file);
2518 }
2519 for (File file : fm.getLocation(CLASS_PATH)) {
2520 path = path.prepend(file);
2521 }
2522 log.printVerbose("classpath", path.reverse().toString());
2523 }
2524 }
2525 }
2527 if (wantSourceFiles && !haveSourcePath) {
2528 fillIn(p, CLASS_PATH,
2529 fileManager.list(CLASS_PATH,
2530 packageName,
2531 kinds,
2532 false));
2533 } else {
2534 if (wantClassFiles)
2535 fillIn(p, CLASS_PATH,
2536 fileManager.list(CLASS_PATH,
2537 packageName,
2538 classKinds,
2539 false));
2540 if (wantSourceFiles)
2541 fillIn(p, SOURCE_PATH,
2542 fileManager.list(SOURCE_PATH,
2543 packageName,
2544 sourceKinds,
2545 false));
2546 }
2547 verbosePath = false;
2548 }
2549 // where
2550 private void fillIn(PackageSymbol p,
2551 Location location,
2552 Iterable<JavaFileObject> files)
2553 {
2554 currentLoc = location;
2555 for (JavaFileObject fo : files) {
2556 switch (fo.getKind()) {
2557 case CLASS:
2558 case SOURCE: {
2559 // TODO pass binaryName to includeClassFile
2560 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2561 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2562 if (SourceVersion.isIdentifier(simpleName) ||
2563 simpleName.equals("package-info"))
2564 includeClassFile(p, fo);
2565 break;
2566 }
2567 default:
2568 extraFileActions(p, fo);
2569 }
2570 }
2571 }
2573 /** Output for "-checkclassfile" option.
2574 * @param key The key to look up the correct internationalized string.
2575 * @param arg An argument for substitution into the output string.
2576 */
2577 private void printCCF(String key, Object arg) {
2578 log.printLines(key, arg);
2579 }
2582 public interface SourceCompleter {
2583 void complete(ClassSymbol sym)
2584 throws CompletionFailure;
2585 }
2587 /**
2588 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2589 * The attribute is only the last component of the original filename, so is unlikely
2590 * to be valid as is, so operations other than those to access the name throw
2591 * UnsupportedOperationException
2592 */
2593 private static class SourceFileObject extends BaseFileObject {
2595 /** The file's name.
2596 */
2597 private Name name;
2598 private Name flatname;
2600 public SourceFileObject(Name name, Name flatname) {
2601 super(null); // no file manager; never referenced for this file object
2602 this.name = name;
2603 this.flatname = flatname;
2604 }
2606 @Override
2607 public URI toUri() {
2608 try {
2609 return new URI(null, name.toString(), null);
2610 } catch (URISyntaxException e) {
2611 throw new CannotCreateUriError(name.toString(), e);
2612 }
2613 }
2615 @Override
2616 public String getName() {
2617 return name.toString();
2618 }
2620 @Override
2621 public String getShortName() {
2622 return getName();
2623 }
2625 @Override
2626 public JavaFileObject.Kind getKind() {
2627 return getKind(getName());
2628 }
2630 @Override
2631 public InputStream openInputStream() {
2632 throw new UnsupportedOperationException();
2633 }
2635 @Override
2636 public OutputStream openOutputStream() {
2637 throw new UnsupportedOperationException();
2638 }
2640 @Override
2641 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2642 throw new UnsupportedOperationException();
2643 }
2645 @Override
2646 public Reader openReader(boolean ignoreEncodingErrors) {
2647 throw new UnsupportedOperationException();
2648 }
2650 @Override
2651 public Writer openWriter() {
2652 throw new UnsupportedOperationException();
2653 }
2655 @Override
2656 public long getLastModified() {
2657 throw new UnsupportedOperationException();
2658 }
2660 @Override
2661 public boolean delete() {
2662 throw new UnsupportedOperationException();
2663 }
2665 @Override
2666 protected String inferBinaryName(Iterable<? extends File> path) {
2667 return flatname.toString();
2668 }
2670 @Override
2671 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2672 return true; // fail-safe mode
2673 }
2675 /**
2676 * Check if two file objects are equal.
2677 * SourceFileObjects are just placeholder objects for the value of a
2678 * SourceFile attribute, and do not directly represent specific files.
2679 * Two SourceFileObjects are equal if their names are equal.
2680 */
2681 @Override
2682 public boolean equals(Object other) {
2683 if (this == other)
2684 return true;
2686 if (!(other instanceof SourceFileObject))
2687 return false;
2689 SourceFileObject o = (SourceFileObject) other;
2690 return name.equals(o.name);
2691 }
2693 @Override
2694 public int hashCode() {
2695 return name.hashCode();
2696 }
2697 }
2698 }