Thu, 01 Nov 2012 10:48:36 +0100
7153951: Add new lint option -Xlint:auxiliaryclass
Reviewed-by: jjg, mcimadamore, forax
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;
119 /** Switch: preserve parameter names from the variable table.
120 */
121 public boolean saveParameterNames;
123 /**
124 * Switch: cache completion failures unless -XDdev is used
125 */
126 private boolean cacheCompletionFailure;
128 /**
129 * Switch: prefer source files instead of newer when both source
130 * and class are available
131 **/
132 public boolean preferSource;
134 /** The log to use for verbose output
135 */
136 final Log log;
138 /** The symbol table. */
139 Symtab syms;
141 Types types;
143 /** The name table. */
144 final Names names;
146 /** Force a completion failure on this name
147 */
148 final Name completionFailureName;
150 /** Access to files
151 */
152 private final JavaFileManager fileManager;
154 /** Factory for diagnostics
155 */
156 JCDiagnostic.Factory diagFactory;
158 /** Can be reassigned from outside:
159 * the completer to be used for ".java" files. If this remains unassigned
160 * ".java" files will not be loaded.
161 */
162 public SourceCompleter sourceCompleter = null;
164 /** A hashtable containing the encountered top-level and member classes,
165 * indexed by flat names. The table does not contain local classes.
166 */
167 private Map<Name,ClassSymbol> classes;
169 /** A hashtable containing the encountered packages.
170 */
171 private Map<Name, PackageSymbol> packages;
173 /** The current scope where type variables are entered.
174 */
175 protected Scope typevars;
177 /** The path name of the class file currently being read.
178 */
179 protected JavaFileObject currentClassFile = null;
181 /** The class or method currently being read.
182 */
183 protected Symbol currentOwner = null;
185 /** The buffer containing the currently read class file.
186 */
187 byte[] buf = new byte[INITIAL_BUFFER_SIZE];
189 /** The current input pointer.
190 */
191 protected int bp;
193 /** The objects of the constant pool.
194 */
195 Object[] poolObj;
197 /** For every constant pool entry, an index into buf where the
198 * defining section of the entry is found.
199 */
200 int[] poolIdx;
202 /** The major version number of the class file being read. */
203 int majorVersion;
204 /** The minor version number of the class file being read. */
205 int minorVersion;
207 /** A table to hold the constant pool indices for method parameter
208 * names, as given in LocalVariableTable attributes.
209 */
210 int[] parameterNameIndices;
212 /**
213 * Whether or not any parameter names have been found.
214 */
215 boolean haveParameterNameIndices;
217 /**
218 * The set of attribute names for which warnings have been generated for the current class
219 */
220 Set<Name> warnedAttrs = new HashSet<Name>();
222 /** Get the ClassReader instance for this invocation. */
223 public static ClassReader instance(Context context) {
224 ClassReader instance = context.get(classReaderKey);
225 if (instance == null)
226 instance = new ClassReader(context, true);
227 return instance;
228 }
230 /** Initialize classes and packages, treating this as the definitive classreader. */
231 public void init(Symtab syms) {
232 init(syms, true);
233 }
235 /** Initialize classes and packages, optionally treating this as
236 * the definitive classreader.
237 */
238 private void init(Symtab syms, boolean definitive) {
239 if (classes != null) return;
241 if (definitive) {
242 Assert.check(packages == null || packages == syms.packages);
243 packages = syms.packages;
244 Assert.check(classes == null || classes == syms.classes);
245 classes = syms.classes;
246 } else {
247 packages = new HashMap<Name, PackageSymbol>();
248 classes = new HashMap<Name, ClassSymbol>();
249 }
251 packages.put(names.empty, syms.rootPackage);
252 syms.rootPackage.completer = this;
253 syms.unnamedPackage.completer = this;
254 }
256 /** Construct a new class reader, optionally treated as the
257 * definitive classreader for this invocation.
258 */
259 protected ClassReader(Context context, boolean definitive) {
260 if (definitive) context.put(classReaderKey, this);
262 names = Names.instance(context);
263 syms = Symtab.instance(context);
264 types = Types.instance(context);
265 fileManager = context.get(JavaFileManager.class);
266 if (fileManager == null)
267 throw new AssertionError("FileManager initialization error");
268 diagFactory = JCDiagnostic.Factory.instance(context);
270 init(syms, definitive);
271 log = Log.instance(context);
273 Options options = Options.instance(context);
274 annotate = Annotate.instance(context);
275 verbose = options.isSet(VERBOSE);
276 checkClassFile = options.isSet("-checkclassfile");
277 Source source = Source.instance(context);
278 allowGenerics = source.allowGenerics();
279 allowVarargs = source.allowVarargs();
280 allowAnnotations = source.allowAnnotations();
281 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
282 saveParameterNames = options.isSet("save-parameter-names");
283 cacheCompletionFailure = options.isUnset("dev");
284 preferSource = "source".equals(options.get("-Xprefer"));
286 completionFailureName =
287 options.isSet("failcomplete")
288 ? names.fromString(options.get("failcomplete"))
289 : null;
291 typevars = new Scope(syms.noSymbol);
293 lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
295 initAttributeReaders();
296 }
298 /** Add member to class unless it is synthetic.
299 */
300 private void enterMember(ClassSymbol c, Symbol sym) {
301 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
302 c.members_field.enter(sym);
303 }
305 /************************************************************************
306 * Error Diagnoses
307 ***********************************************************************/
310 public class BadClassFile extends CompletionFailure {
311 private static final long serialVersionUID = 0;
313 public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
314 super(sym, createBadClassFileDiagnostic(file, diag));
315 }
316 }
317 // where
318 private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
319 String key = (file.getKind() == JavaFileObject.Kind.SOURCE
320 ? "bad.source.file.header" : "bad.class.file.header");
321 return diagFactory.fragment(key, file, diag);
322 }
324 public BadClassFile badClassFile(String key, Object... args) {
325 return new BadClassFile (
326 currentOwner.enclClass(),
327 currentClassFile,
328 diagFactory.fragment(key, args));
329 }
331 /************************************************************************
332 * Buffer Access
333 ***********************************************************************/
335 /** Read a character.
336 */
337 char nextChar() {
338 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
339 }
341 /** Read a byte.
342 */
343 byte nextByte() {
344 return buf[bp++];
345 }
347 /** Read an integer.
348 */
349 int nextInt() {
350 return
351 ((buf[bp++] & 0xFF) << 24) +
352 ((buf[bp++] & 0xFF) << 16) +
353 ((buf[bp++] & 0xFF) << 8) +
354 (buf[bp++] & 0xFF);
355 }
357 /** Extract a character at position bp from buf.
358 */
359 char getChar(int bp) {
360 return
361 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
362 }
364 /** Extract an integer at position bp from buf.
365 */
366 int getInt(int bp) {
367 return
368 ((buf[bp] & 0xFF) << 24) +
369 ((buf[bp+1] & 0xFF) << 16) +
370 ((buf[bp+2] & 0xFF) << 8) +
371 (buf[bp+3] & 0xFF);
372 }
375 /** Extract a long integer at position bp from buf.
376 */
377 long getLong(int bp) {
378 DataInputStream bufin =
379 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
380 try {
381 return bufin.readLong();
382 } catch (IOException e) {
383 throw new AssertionError(e);
384 }
385 }
387 /** Extract a float at position bp from buf.
388 */
389 float getFloat(int bp) {
390 DataInputStream bufin =
391 new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
392 try {
393 return bufin.readFloat();
394 } catch (IOException e) {
395 throw new AssertionError(e);
396 }
397 }
399 /** Extract a double at position bp from buf.
400 */
401 double getDouble(int bp) {
402 DataInputStream bufin =
403 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
404 try {
405 return bufin.readDouble();
406 } catch (IOException e) {
407 throw new AssertionError(e);
408 }
409 }
411 /************************************************************************
412 * Constant Pool Access
413 ***********************************************************************/
415 /** Index all constant pool entries, writing their start addresses into
416 * poolIdx.
417 */
418 void indexPool() {
419 poolIdx = new int[nextChar()];
420 poolObj = new Object[poolIdx.length];
421 int i = 1;
422 while (i < poolIdx.length) {
423 poolIdx[i++] = bp;
424 byte tag = buf[bp++];
425 switch (tag) {
426 case CONSTANT_Utf8: case CONSTANT_Unicode: {
427 int len = nextChar();
428 bp = bp + len;
429 break;
430 }
431 case CONSTANT_Class:
432 case CONSTANT_String:
433 case CONSTANT_MethodType:
434 bp = bp + 2;
435 break;
436 case CONSTANT_MethodHandle:
437 bp = bp + 3;
438 break;
439 case CONSTANT_Fieldref:
440 case CONSTANT_Methodref:
441 case CONSTANT_InterfaceMethodref:
442 case CONSTANT_NameandType:
443 case CONSTANT_Integer:
444 case CONSTANT_Float:
445 case CONSTANT_InvokeDynamic:
446 bp = bp + 4;
447 break;
448 case CONSTANT_Long:
449 case CONSTANT_Double:
450 bp = bp + 8;
451 i++;
452 break;
453 default:
454 throw badClassFile("bad.const.pool.tag.at",
455 Byte.toString(tag),
456 Integer.toString(bp -1));
457 }
458 }
459 }
461 /** Read constant pool entry at start address i, use pool as a cache.
462 */
463 Object readPool(int i) {
464 Object result = poolObj[i];
465 if (result != null) return result;
467 int index = poolIdx[i];
468 if (index == 0) return null;
470 byte tag = buf[index];
471 switch (tag) {
472 case CONSTANT_Utf8:
473 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
474 break;
475 case CONSTANT_Unicode:
476 throw badClassFile("unicode.str.not.supported");
477 case CONSTANT_Class:
478 poolObj[i] = readClassOrType(getChar(index + 1));
479 break;
480 case CONSTANT_String:
481 // FIXME: (footprint) do not use toString here
482 poolObj[i] = readName(getChar(index + 1)).toString();
483 break;
484 case CONSTANT_Fieldref: {
485 ClassSymbol owner = readClassSymbol(getChar(index + 1));
486 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
487 poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
488 break;
489 }
490 case CONSTANT_Methodref:
491 case CONSTANT_InterfaceMethodref: {
492 ClassSymbol owner = readClassSymbol(getChar(index + 1));
493 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
494 poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
495 break;
496 }
497 case CONSTANT_NameandType:
498 poolObj[i] = new NameAndType(
499 readName(getChar(index + 1)),
500 readType(getChar(index + 3)));
501 break;
502 case CONSTANT_Integer:
503 poolObj[i] = getInt(index + 1);
504 break;
505 case CONSTANT_Float:
506 poolObj[i] = new Float(getFloat(index + 1));
507 break;
508 case CONSTANT_Long:
509 poolObj[i] = new Long(getLong(index + 1));
510 break;
511 case CONSTANT_Double:
512 poolObj[i] = new Double(getDouble(index + 1));
513 break;
514 case CONSTANT_MethodHandle:
515 skipBytes(4);
516 break;
517 case CONSTANT_MethodType:
518 skipBytes(3);
519 break;
520 case CONSTANT_InvokeDynamic:
521 skipBytes(5);
522 break;
523 default:
524 throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
525 }
526 return poolObj[i];
527 }
529 /** Read signature and convert to type.
530 */
531 Type readType(int i) {
532 int index = poolIdx[i];
533 return sigToType(buf, index + 3, getChar(index + 1));
534 }
536 /** If name is an array type or class signature, return the
537 * corresponding type; otherwise return a ClassSymbol with given name.
538 */
539 Object readClassOrType(int i) {
540 int index = poolIdx[i];
541 int len = getChar(index + 1);
542 int start = index + 3;
543 Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
544 // by the above assertion, the following test can be
545 // simplified to (buf[start] == '[')
546 return (buf[start] == '[' || buf[start + len - 1] == ';')
547 ? (Object)sigToType(buf, start, len)
548 : (Object)enterClass(names.fromUtf(internalize(buf, start,
549 len)));
550 }
552 /** Read signature and convert to type parameters.
553 */
554 List<Type> readTypeParams(int i) {
555 int index = poolIdx[i];
556 return sigToTypeParams(buf, index + 3, getChar(index + 1));
557 }
559 /** Read class entry.
560 */
561 ClassSymbol readClassSymbol(int i) {
562 return (ClassSymbol) (readPool(i));
563 }
565 /** Read name.
566 */
567 Name readName(int i) {
568 return (Name) (readPool(i));
569 }
571 /************************************************************************
572 * Reading Types
573 ***********************************************************************/
575 /** The unread portion of the currently read type is
576 * signature[sigp..siglimit-1].
577 */
578 byte[] signature;
579 int sigp;
580 int siglimit;
581 boolean sigEnterPhase = false;
583 /** Convert signature to type, where signature is a byte array segment.
584 */
585 Type sigToType(byte[] sig, int offset, int len) {
586 signature = sig;
587 sigp = offset;
588 siglimit = offset + len;
589 return sigToType();
590 }
592 /** Convert signature to type, where signature is implicit.
593 */
594 Type sigToType() {
595 switch ((char) signature[sigp]) {
596 case 'T':
597 sigp++;
598 int start = sigp;
599 while (signature[sigp] != ';') sigp++;
600 sigp++;
601 return sigEnterPhase
602 ? Type.noType
603 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
604 case '+': {
605 sigp++;
606 Type t = sigToType();
607 return new WildcardType(t, BoundKind.EXTENDS,
608 syms.boundClass);
609 }
610 case '*':
611 sigp++;
612 return new WildcardType(syms.objectType, BoundKind.UNBOUND,
613 syms.boundClass);
614 case '-': {
615 sigp++;
616 Type t = sigToType();
617 return new WildcardType(t, BoundKind.SUPER,
618 syms.boundClass);
619 }
620 case 'B':
621 sigp++;
622 return syms.byteType;
623 case 'C':
624 sigp++;
625 return syms.charType;
626 case 'D':
627 sigp++;
628 return syms.doubleType;
629 case 'F':
630 sigp++;
631 return syms.floatType;
632 case 'I':
633 sigp++;
634 return syms.intType;
635 case 'J':
636 sigp++;
637 return syms.longType;
638 case 'L':
639 {
640 // int oldsigp = sigp;
641 Type t = classSigToType();
642 if (sigp < siglimit && signature[sigp] == '.')
643 throw badClassFile("deprecated inner class signature syntax " +
644 "(please recompile from source)");
645 /*
646 System.err.println(" decoded " +
647 new String(signature, oldsigp, sigp-oldsigp) +
648 " => " + t + " outer " + t.outer());
649 */
650 return t;
651 }
652 case 'S':
653 sigp++;
654 return syms.shortType;
655 case 'V':
656 sigp++;
657 return syms.voidType;
658 case 'Z':
659 sigp++;
660 return syms.booleanType;
661 case '[':
662 sigp++;
663 return new ArrayType(sigToType(), syms.arrayClass);
664 case '(':
665 sigp++;
666 List<Type> argtypes = sigToTypes(')');
667 Type restype = sigToType();
668 List<Type> thrown = List.nil();
669 while (signature[sigp] == '^') {
670 sigp++;
671 thrown = thrown.prepend(sigToType());
672 }
673 return new MethodType(argtypes,
674 restype,
675 thrown.reverse(),
676 syms.methodClass);
677 case '<':
678 typevars = typevars.dup(currentOwner);
679 Type poly = new ForAll(sigToTypeParams(), sigToType());
680 typevars = typevars.leave();
681 return poly;
682 default:
683 throw badClassFile("bad.signature",
684 Convert.utf2string(signature, sigp, 10));
685 }
686 }
688 byte[] signatureBuffer = new byte[0];
689 int sbp = 0;
690 /** Convert class signature to type, where signature is implicit.
691 */
692 Type classSigToType() {
693 if (signature[sigp] != 'L')
694 throw badClassFile("bad.class.signature",
695 Convert.utf2string(signature, sigp, 10));
696 sigp++;
697 Type outer = Type.noType;
698 int startSbp = sbp;
700 while (true) {
701 final byte c = signature[sigp++];
702 switch (c) {
704 case ';': { // end
705 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
706 startSbp,
707 sbp - startSbp));
708 if (outer == Type.noType)
709 outer = t.erasure(types);
710 else
711 outer = new ClassType(outer, List.<Type>nil(), t);
712 sbp = startSbp;
713 return outer;
714 }
716 case '<': // generic arguments
717 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
718 startSbp,
719 sbp - startSbp));
720 outer = new ClassType(outer, sigToTypes('>'), t) {
721 boolean completed = false;
722 @Override
723 public Type getEnclosingType() {
724 if (!completed) {
725 completed = true;
726 tsym.complete();
727 Type enclosingType = tsym.type.getEnclosingType();
728 if (enclosingType != Type.noType) {
729 List<Type> typeArgs =
730 super.getEnclosingType().allparams();
731 List<Type> typeParams =
732 enclosingType.allparams();
733 if (typeParams.length() != typeArgs.length()) {
734 // no "rare" types
735 super.setEnclosingType(types.erasure(enclosingType));
736 } else {
737 super.setEnclosingType(types.subst(enclosingType,
738 typeParams,
739 typeArgs));
740 }
741 } else {
742 super.setEnclosingType(Type.noType);
743 }
744 }
745 return super.getEnclosingType();
746 }
747 @Override
748 public void setEnclosingType(Type outer) {
749 throw new UnsupportedOperationException();
750 }
751 };
752 switch (signature[sigp++]) {
753 case ';':
754 if (sigp < signature.length && signature[sigp] == '.') {
755 // support old-style GJC signatures
756 // The signature produced was
757 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
758 // rather than say
759 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
760 // so we skip past ".Lfoo/Outer$"
761 sigp += (sbp - startSbp) + // "foo/Outer"
762 3; // ".L" and "$"
763 signatureBuffer[sbp++] = (byte)'$';
764 break;
765 } else {
766 sbp = startSbp;
767 return outer;
768 }
769 case '.':
770 signatureBuffer[sbp++] = (byte)'$';
771 break;
772 default:
773 throw new AssertionError(signature[sigp-1]);
774 }
775 continue;
777 case '.':
778 signatureBuffer[sbp++] = (byte)'$';
779 continue;
780 case '/':
781 signatureBuffer[sbp++] = (byte)'.';
782 continue;
783 default:
784 signatureBuffer[sbp++] = c;
785 continue;
786 }
787 }
788 }
790 /** Convert (implicit) signature to list of types
791 * until `terminator' is encountered.
792 */
793 List<Type> sigToTypes(char terminator) {
794 List<Type> head = List.of(null);
795 List<Type> tail = head;
796 while (signature[sigp] != terminator)
797 tail = tail.setTail(List.of(sigToType()));
798 sigp++;
799 return head.tail;
800 }
802 /** Convert signature to type parameters, where signature is a byte
803 * array segment.
804 */
805 List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
806 signature = sig;
807 sigp = offset;
808 siglimit = offset + len;
809 return sigToTypeParams();
810 }
812 /** Convert signature to type parameters, where signature is implicit.
813 */
814 List<Type> sigToTypeParams() {
815 List<Type> tvars = List.nil();
816 if (signature[sigp] == '<') {
817 sigp++;
818 int start = sigp;
819 sigEnterPhase = true;
820 while (signature[sigp] != '>')
821 tvars = tvars.prepend(sigToTypeParam());
822 sigEnterPhase = false;
823 sigp = start;
824 while (signature[sigp] != '>')
825 sigToTypeParam();
826 sigp++;
827 }
828 return tvars.reverse();
829 }
831 /** Convert (implicit) signature to type parameter.
832 */
833 Type sigToTypeParam() {
834 int start = sigp;
835 while (signature[sigp] != ':') sigp++;
836 Name name = names.fromUtf(signature, start, sigp - start);
837 TypeVar tvar;
838 if (sigEnterPhase) {
839 tvar = new TypeVar(name, currentOwner, syms.botType);
840 typevars.enter(tvar.tsym);
841 } else {
842 tvar = (TypeVar)findTypeVar(name);
843 }
844 List<Type> bounds = List.nil();
845 Type st = null;
846 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
847 sigp++;
848 st = syms.objectType;
849 }
850 while (signature[sigp] == ':') {
851 sigp++;
852 bounds = bounds.prepend(sigToType());
853 }
854 if (!sigEnterPhase) {
855 types.setBounds(tvar, bounds.reverse(), st);
856 }
857 return tvar;
858 }
860 /** Find type variable with given name in `typevars' scope.
861 */
862 Type findTypeVar(Name name) {
863 Scope.Entry e = typevars.lookup(name);
864 if (e.scope != null) {
865 return e.sym.type;
866 } else {
867 if (readingClassAttr) {
868 // While reading the class attribute, the supertypes
869 // might refer to a type variable from an enclosing element
870 // (method or class).
871 // If the type variable is defined in the enclosing class,
872 // we can actually find it in
873 // currentOwner.owner.type.getTypeArguments()
874 // However, until we have read the enclosing method attribute
875 // we don't know for sure if this owner is correct. It could
876 // be a method and there is no way to tell before reading the
877 // enclosing method attribute.
878 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
879 missingTypeVariables = missingTypeVariables.prepend(t);
880 // System.err.println("Missing type var " + name);
881 return t;
882 }
883 throw badClassFile("undecl.type.var", name);
884 }
885 }
887 /************************************************************************
888 * Reading Attributes
889 ***********************************************************************/
891 protected enum AttributeKind { CLASS, MEMBER };
892 protected abstract class AttributeReader {
893 protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
894 this.name = name;
895 this.version = version;
896 this.kinds = kinds;
897 }
899 protected boolean accepts(AttributeKind kind) {
900 if (kinds.contains(kind)) {
901 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
902 return true;
904 if (lintClassfile && !warnedAttrs.contains(name)) {
905 JavaFileObject prev = log.useSource(currentClassFile);
906 try {
907 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
908 name, version.major, version.minor, majorVersion, minorVersion);
909 } finally {
910 log.useSource(prev);
911 }
912 warnedAttrs.add(name);
913 }
914 }
915 return false;
916 }
918 protected abstract void read(Symbol sym, int attrLen);
920 protected final Name name;
921 protected final ClassFile.Version version;
922 protected final Set<AttributeKind> kinds;
923 }
925 protected Set<AttributeKind> CLASS_ATTRIBUTE =
926 EnumSet.of(AttributeKind.CLASS);
927 protected Set<AttributeKind> MEMBER_ATTRIBUTE =
928 EnumSet.of(AttributeKind.MEMBER);
929 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
930 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
932 protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
934 private void initAttributeReaders() {
935 AttributeReader[] readers = {
936 // v45.3 attributes
938 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
939 protected void read(Symbol sym, int attrLen) {
940 if (readAllOfClassFile || saveParameterNames)
941 ((MethodSymbol)sym).code = readCode(sym);
942 else
943 bp = bp + attrLen;
944 }
945 },
947 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
948 protected void read(Symbol sym, int attrLen) {
949 Object v = readPool(nextChar());
950 // Ignore ConstantValue attribute if field not final.
951 if ((sym.flags() & FINAL) != 0)
952 ((VarSymbol) sym).setData(v);
953 }
954 },
956 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
957 protected void read(Symbol sym, int attrLen) {
958 sym.flags_field |= DEPRECATED;
959 }
960 },
962 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
963 protected void read(Symbol sym, int attrLen) {
964 int nexceptions = nextChar();
965 List<Type> thrown = List.nil();
966 for (int j = 0; j < nexceptions; j++)
967 thrown = thrown.prepend(readClassSymbol(nextChar()).type);
968 if (sym.type.getThrownTypes().isEmpty())
969 sym.type.asMethodType().thrown = thrown.reverse();
970 }
971 },
973 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
974 protected void read(Symbol sym, int attrLen) {
975 ClassSymbol c = (ClassSymbol) sym;
976 readInnerClasses(c);
977 }
978 },
980 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
981 protected void read(Symbol sym, int attrLen) {
982 int newbp = bp + attrLen;
983 if (saveParameterNames) {
984 // Pick up parameter names from the variable table.
985 // Parameter names are not explicitly identified as such,
986 // but all parameter name entries in the LocalVariableTable
987 // have a start_pc of 0. Therefore, we record the name
988 // indicies of all slots with a start_pc of zero in the
989 // parameterNameIndicies array.
990 // Note that this implicitly honors the JVMS spec that
991 // there may be more than one LocalVariableTable, and that
992 // there is no specified ordering for the entries.
993 int numEntries = nextChar();
994 for (int i = 0; i < numEntries; i++) {
995 int start_pc = nextChar();
996 int length = nextChar();
997 int nameIndex = nextChar();
998 int sigIndex = nextChar();
999 int register = nextChar();
1000 if (start_pc == 0) {
1001 // ensure array large enough
1002 if (register >= parameterNameIndices.length) {
1003 int newSize = Math.max(register, parameterNameIndices.length + 8);
1004 parameterNameIndices =
1005 Arrays.copyOf(parameterNameIndices, newSize);
1006 }
1007 parameterNameIndices[register] = nameIndex;
1008 haveParameterNameIndices = true;
1009 }
1010 }
1011 }
1012 bp = newbp;
1013 }
1014 },
1016 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
1017 protected void read(Symbol sym, int attrLen) {
1018 ClassSymbol c = (ClassSymbol) sym;
1019 Name n = readName(nextChar());
1020 c.sourcefile = new SourceFileObject(n, c.flatname);
1021 // If the class is a toplevel class, originating from a Java source file,
1022 // but the class name does not match the file name, then it is
1023 // an auxiliary class.
1024 String sn = n.toString();
1025 if (c.owner.kind == Kinds.PCK &&
1026 sn.endsWith(".java") &&
1027 !sn.equals(c.name.toString()+".java")) {
1028 c.flags_field |= AUXILIARY;
1029 }
1030 }
1031 },
1033 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1034 protected void read(Symbol sym, int attrLen) {
1035 // bridge methods are visible when generics not enabled
1036 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
1037 sym.flags_field |= SYNTHETIC;
1038 }
1039 },
1041 // standard v49 attributes
1043 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1044 protected void read(Symbol sym, int attrLen) {
1045 int newbp = bp + attrLen;
1046 readEnclosingMethodAttr(sym);
1047 bp = newbp;
1048 }
1049 },
1051 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1052 @Override
1053 protected boolean accepts(AttributeKind kind) {
1054 return super.accepts(kind) && allowGenerics;
1055 }
1057 protected void read(Symbol sym, int attrLen) {
1058 if (sym.kind == TYP) {
1059 ClassSymbol c = (ClassSymbol) sym;
1060 readingClassAttr = true;
1061 try {
1062 ClassType ct1 = (ClassType)c.type;
1063 Assert.check(c == currentOwner);
1064 ct1.typarams_field = readTypeParams(nextChar());
1065 ct1.supertype_field = sigToType();
1066 ListBuffer<Type> is = new ListBuffer<Type>();
1067 while (sigp != siglimit) is.append(sigToType());
1068 ct1.interfaces_field = is.toList();
1069 } finally {
1070 readingClassAttr = false;
1071 }
1072 } else {
1073 List<Type> thrown = sym.type.getThrownTypes();
1074 sym.type = readType(nextChar());
1075 //- System.err.println(" # " + sym.type);
1076 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1077 sym.type.asMethodType().thrown = thrown;
1079 }
1080 }
1081 },
1083 // v49 annotation attributes
1085 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1086 protected void read(Symbol sym, int attrLen) {
1087 attachAnnotationDefault(sym);
1088 }
1089 },
1091 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1092 protected void read(Symbol sym, int attrLen) {
1093 attachAnnotations(sym);
1094 }
1095 },
1097 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1098 protected void read(Symbol sym, int attrLen) {
1099 attachParameterAnnotations(sym);
1100 }
1101 },
1103 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1104 protected void read(Symbol sym, int attrLen) {
1105 attachAnnotations(sym);
1106 }
1107 },
1109 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1110 protected void read(Symbol sym, int attrLen) {
1111 attachParameterAnnotations(sym);
1112 }
1113 },
1115 // additional "legacy" v49 attributes, superceded by flags
1117 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1118 protected void read(Symbol sym, int attrLen) {
1119 if (allowAnnotations)
1120 sym.flags_field |= ANNOTATION;
1121 }
1122 },
1124 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1125 protected void read(Symbol sym, int attrLen) {
1126 sym.flags_field |= BRIDGE;
1127 if (!allowGenerics)
1128 sym.flags_field &= ~SYNTHETIC;
1129 }
1130 },
1132 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1133 protected void read(Symbol sym, int attrLen) {
1134 sym.flags_field |= ENUM;
1135 }
1136 },
1138 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1139 protected void read(Symbol sym, int attrLen) {
1140 if (allowVarargs)
1141 sym.flags_field |= VARARGS;
1142 }
1143 },
1145 // The following attributes for a Code attribute are not currently handled
1146 // StackMapTable
1147 // SourceDebugExtension
1148 // LineNumberTable
1149 // LocalVariableTypeTable
1150 };
1152 for (AttributeReader r: readers)
1153 attributeReaders.put(r.name, r);
1154 }
1156 /** Report unrecognized attribute.
1157 */
1158 void unrecognized(Name attrName) {
1159 if (checkClassFile)
1160 printCCF("ccf.unrecognized.attribute", attrName);
1161 }
1165 protected void readEnclosingMethodAttr(Symbol sym) {
1166 // sym is a nested class with an "Enclosing Method" attribute
1167 // remove sym from it's current owners scope and place it in
1168 // the scope specified by the attribute
1169 sym.owner.members().remove(sym);
1170 ClassSymbol self = (ClassSymbol)sym;
1171 ClassSymbol c = readClassSymbol(nextChar());
1172 NameAndType nt = (NameAndType)readPool(nextChar());
1174 if (c.members_field == null)
1175 throw badClassFile("bad.enclosing.class", self, c);
1177 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1178 if (nt != null && m == null)
1179 throw badClassFile("bad.enclosing.method", self);
1181 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1182 self.owner = m != null ? m : c;
1183 if (self.name.isEmpty())
1184 self.fullname = names.empty;
1185 else
1186 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1188 if (m != null) {
1189 ((ClassType)sym.type).setEnclosingType(m.type);
1190 } else if ((self.flags_field & STATIC) == 0) {
1191 ((ClassType)sym.type).setEnclosingType(c.type);
1192 } else {
1193 ((ClassType)sym.type).setEnclosingType(Type.noType);
1194 }
1195 enterTypevars(self);
1196 if (!missingTypeVariables.isEmpty()) {
1197 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1198 for (Type typevar : missingTypeVariables) {
1199 typeVars.append(findTypeVar(typevar.tsym.name));
1200 }
1201 foundTypeVariables = typeVars.toList();
1202 } else {
1203 foundTypeVariables = List.nil();
1204 }
1205 }
1207 // See java.lang.Class
1208 private Name simpleBinaryName(Name self, Name enclosing) {
1209 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1210 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1211 throw badClassFile("bad.enclosing.method", self);
1212 int index = 1;
1213 while (index < simpleBinaryName.length() &&
1214 isAsciiDigit(simpleBinaryName.charAt(index)))
1215 index++;
1216 return names.fromString(simpleBinaryName.substring(index));
1217 }
1219 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1220 if (nt == null)
1221 return null;
1223 MethodType type = nt.type.asMethodType();
1225 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1226 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1227 return (MethodSymbol)e.sym;
1229 if (nt.name != names.init)
1230 // not a constructor
1231 return null;
1232 if ((flags & INTERFACE) != 0)
1233 // no enclosing instance
1234 return null;
1235 if (nt.type.getParameterTypes().isEmpty())
1236 // no parameters
1237 return null;
1239 // A constructor of an inner class.
1240 // Remove the first argument (the enclosing instance)
1241 nt.type = new MethodType(nt.type.getParameterTypes().tail,
1242 nt.type.getReturnType(),
1243 nt.type.getThrownTypes(),
1244 syms.methodClass);
1245 // Try searching again
1246 return findMethod(nt, scope, flags);
1247 }
1249 /** Similar to Types.isSameType but avoids completion */
1250 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1251 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1252 .prepend(types.erasure(mt1.getReturnType()));
1253 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1254 while (!types1.isEmpty() && !types2.isEmpty()) {
1255 if (types1.head.tsym != types2.head.tsym)
1256 return false;
1257 types1 = types1.tail;
1258 types2 = types2.tail;
1259 }
1260 return types1.isEmpty() && types2.isEmpty();
1261 }
1263 /**
1264 * Character.isDigit answers <tt>true</tt> to some non-ascii
1265 * digits. This one does not. <b>copied from java.lang.Class</b>
1266 */
1267 private static boolean isAsciiDigit(char c) {
1268 return '0' <= c && c <= '9';
1269 }
1271 /** Read member attributes.
1272 */
1273 void readMemberAttrs(Symbol sym) {
1274 readAttrs(sym, AttributeKind.MEMBER);
1275 }
1277 void readAttrs(Symbol sym, AttributeKind kind) {
1278 char ac = nextChar();
1279 for (int i = 0; i < ac; i++) {
1280 Name attrName = readName(nextChar());
1281 int attrLen = nextInt();
1282 AttributeReader r = attributeReaders.get(attrName);
1283 if (r != null && r.accepts(kind))
1284 r.read(sym, attrLen);
1285 else {
1286 unrecognized(attrName);
1287 bp = bp + attrLen;
1288 }
1289 }
1290 }
1292 private boolean readingClassAttr = false;
1293 private List<Type> missingTypeVariables = List.nil();
1294 private List<Type> foundTypeVariables = List.nil();
1296 /** Read class attributes.
1297 */
1298 void readClassAttrs(ClassSymbol c) {
1299 readAttrs(c, AttributeKind.CLASS);
1300 }
1302 /** Read code block.
1303 */
1304 Code readCode(Symbol owner) {
1305 nextChar(); // max_stack
1306 nextChar(); // max_locals
1307 final int code_length = nextInt();
1308 bp += code_length;
1309 final char exception_table_length = nextChar();
1310 bp += exception_table_length * 8;
1311 readMemberAttrs(owner);
1312 return null;
1313 }
1315 /************************************************************************
1316 * Reading Java-language annotations
1317 ***********************************************************************/
1319 /** Attach annotations.
1320 */
1321 void attachAnnotations(final Symbol sym) {
1322 int numAttributes = nextChar();
1323 if (numAttributes != 0) {
1324 ListBuffer<CompoundAnnotationProxy> proxies =
1325 new ListBuffer<CompoundAnnotationProxy>();
1326 for (int i = 0; i<numAttributes; i++) {
1327 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1328 if (proxy.type.tsym == syms.proprietaryType.tsym)
1329 sym.flags_field |= PROPRIETARY;
1330 else
1331 proxies.append(proxy);
1332 }
1333 annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1334 }
1335 }
1337 /** Attach parameter annotations.
1338 */
1339 void attachParameterAnnotations(final Symbol method) {
1340 final MethodSymbol meth = (MethodSymbol)method;
1341 int numParameters = buf[bp++] & 0xFF;
1342 List<VarSymbol> parameters = meth.params();
1343 int pnum = 0;
1344 while (parameters.tail != null) {
1345 attachAnnotations(parameters.head);
1346 parameters = parameters.tail;
1347 pnum++;
1348 }
1349 if (pnum != numParameters) {
1350 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1351 }
1352 }
1354 /** Attach the default value for an annotation element.
1355 */
1356 void attachAnnotationDefault(final Symbol sym) {
1357 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1358 final Attribute value = readAttributeValue();
1359 annotate.normal(new AnnotationDefaultCompleter(meth, value));
1360 }
1362 Type readTypeOrClassSymbol(int i) {
1363 // support preliminary jsr175-format class files
1364 if (buf[poolIdx[i]] == CONSTANT_Class)
1365 return readClassSymbol(i).type;
1366 return readType(i);
1367 }
1368 Type readEnumType(int i) {
1369 // support preliminary jsr175-format class files
1370 int index = poolIdx[i];
1371 int length = getChar(index + 1);
1372 if (buf[index + length + 2] != ';')
1373 return enterClass(readName(i)).type;
1374 return readType(i);
1375 }
1377 CompoundAnnotationProxy readCompoundAnnotation() {
1378 Type t = readTypeOrClassSymbol(nextChar());
1379 int numFields = nextChar();
1380 ListBuffer<Pair<Name,Attribute>> pairs =
1381 new ListBuffer<Pair<Name,Attribute>>();
1382 for (int i=0; i<numFields; i++) {
1383 Name name = readName(nextChar());
1384 Attribute value = readAttributeValue();
1385 pairs.append(new Pair<Name,Attribute>(name, value));
1386 }
1387 return new CompoundAnnotationProxy(t, pairs.toList());
1388 }
1390 Attribute readAttributeValue() {
1391 char c = (char) buf[bp++];
1392 switch (c) {
1393 case 'B':
1394 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1395 case 'C':
1396 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1397 case 'D':
1398 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1399 case 'F':
1400 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1401 case 'I':
1402 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1403 case 'J':
1404 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1405 case 'S':
1406 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1407 case 'Z':
1408 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1409 case 's':
1410 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1411 case 'e':
1412 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1413 case 'c':
1414 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1415 case '[': {
1416 int n = nextChar();
1417 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1418 for (int i=0; i<n; i++)
1419 l.append(readAttributeValue());
1420 return new ArrayAttributeProxy(l.toList());
1421 }
1422 case '@':
1423 return readCompoundAnnotation();
1424 default:
1425 throw new AssertionError("unknown annotation tag '" + c + "'");
1426 }
1427 }
1429 interface ProxyVisitor extends Attribute.Visitor {
1430 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1431 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1432 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1433 }
1435 static class EnumAttributeProxy extends Attribute {
1436 Type enumType;
1437 Name enumerator;
1438 public EnumAttributeProxy(Type enumType, Name enumerator) {
1439 super(null);
1440 this.enumType = enumType;
1441 this.enumerator = enumerator;
1442 }
1443 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1444 @Override
1445 public String toString() {
1446 return "/*proxy enum*/" + enumType + "." + enumerator;
1447 }
1448 }
1450 static class ArrayAttributeProxy extends Attribute {
1451 List<Attribute> values;
1452 ArrayAttributeProxy(List<Attribute> values) {
1453 super(null);
1454 this.values = values;
1455 }
1456 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1457 @Override
1458 public String toString() {
1459 return "{" + values + "}";
1460 }
1461 }
1463 /** A temporary proxy representing a compound attribute.
1464 */
1465 static class CompoundAnnotationProxy extends Attribute {
1466 final List<Pair<Name,Attribute>> values;
1467 public CompoundAnnotationProxy(Type type,
1468 List<Pair<Name,Attribute>> values) {
1469 super(type);
1470 this.values = values;
1471 }
1472 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1473 @Override
1474 public String toString() {
1475 StringBuilder buf = new StringBuilder();
1476 buf.append("@");
1477 buf.append(type.tsym.getQualifiedName());
1478 buf.append("/*proxy*/{");
1479 boolean first = true;
1480 for (List<Pair<Name,Attribute>> v = values;
1481 v.nonEmpty(); v = v.tail) {
1482 Pair<Name,Attribute> value = v.head;
1483 if (!first) buf.append(",");
1484 first = false;
1485 buf.append(value.fst);
1486 buf.append("=");
1487 buf.append(value.snd);
1488 }
1489 buf.append("}");
1490 return buf.toString();
1491 }
1492 }
1494 /** A temporary proxy representing a type annotation.
1495 */
1496 static class TypeAnnotationProxy {
1497 final CompoundAnnotationProxy compound;
1498 final TypeAnnotationPosition position;
1499 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1500 TypeAnnotationPosition position) {
1501 this.compound = compound;
1502 this.position = position;
1503 }
1504 }
1506 class AnnotationDeproxy implements ProxyVisitor {
1507 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1508 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1510 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1511 // also must fill in types!!!!
1512 ListBuffer<Attribute.Compound> buf =
1513 new ListBuffer<Attribute.Compound>();
1514 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1515 buf.append(deproxyCompound(l.head));
1516 }
1517 return buf.toList();
1518 }
1520 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1521 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1522 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1523 for (List<Pair<Name,Attribute>> l = a.values;
1524 l.nonEmpty();
1525 l = l.tail) {
1526 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1527 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1528 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1529 }
1530 return new Attribute.Compound(a.type, buf.toList());
1531 }
1533 MethodSymbol findAccessMethod(Type container, Name name) {
1534 CompletionFailure failure = null;
1535 try {
1536 for (Scope.Entry e = container.tsym.members().lookup(name);
1537 e.scope != null;
1538 e = e.next()) {
1539 Symbol sym = e.sym;
1540 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1541 return (MethodSymbol) sym;
1542 }
1543 } catch (CompletionFailure ex) {
1544 failure = ex;
1545 }
1546 // The method wasn't found: emit a warning and recover
1547 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1548 try {
1549 if (failure == null) {
1550 log.warning("annotation.method.not.found",
1551 container,
1552 name);
1553 } else {
1554 log.warning("annotation.method.not.found.reason",
1555 container,
1556 name,
1557 failure.getDetailValue());//diagnostic, if present
1558 }
1559 } finally {
1560 log.useSource(prevSource);
1561 }
1562 // Construct a new method type and symbol. Use bottom
1563 // type (typeof null) as return type because this type is
1564 // a subtype of all reference types and can be converted
1565 // to primitive types by unboxing.
1566 MethodType mt = new MethodType(List.<Type>nil(),
1567 syms.botType,
1568 List.<Type>nil(),
1569 syms.methodClass);
1570 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1571 }
1573 Attribute result;
1574 Type type;
1575 Attribute deproxy(Type t, Attribute a) {
1576 Type oldType = type;
1577 try {
1578 type = t;
1579 a.accept(this);
1580 return result;
1581 } finally {
1582 type = oldType;
1583 }
1584 }
1586 // implement Attribute.Visitor below
1588 public void visitConstant(Attribute.Constant value) {
1589 // assert value.type == type;
1590 result = value;
1591 }
1593 public void visitClass(Attribute.Class clazz) {
1594 result = clazz;
1595 }
1597 public void visitEnum(Attribute.Enum e) {
1598 throw new AssertionError(); // shouldn't happen
1599 }
1601 public void visitCompound(Attribute.Compound compound) {
1602 throw new AssertionError(); // shouldn't happen
1603 }
1605 public void visitArray(Attribute.Array array) {
1606 throw new AssertionError(); // shouldn't happen
1607 }
1609 public void visitError(Attribute.Error e) {
1610 throw new AssertionError(); // shouldn't happen
1611 }
1613 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1614 // type.tsym.flatName() should == proxy.enumFlatName
1615 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1616 VarSymbol enumerator = null;
1617 CompletionFailure failure = null;
1618 try {
1619 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1620 e.scope != null;
1621 e = e.next()) {
1622 if (e.sym.kind == VAR) {
1623 enumerator = (VarSymbol)e.sym;
1624 break;
1625 }
1626 }
1627 }
1628 catch (CompletionFailure ex) {
1629 failure = ex;
1630 }
1631 if (enumerator == null) {
1632 if (failure != null) {
1633 log.warning("unknown.enum.constant.reason",
1634 currentClassFile, enumTypeSym, proxy.enumerator,
1635 failure.getDiagnostic());
1636 } else {
1637 log.warning("unknown.enum.constant",
1638 currentClassFile, enumTypeSym, proxy.enumerator);
1639 }
1640 result = new Attribute.Enum(enumTypeSym.type,
1641 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1642 } else {
1643 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1644 }
1645 }
1647 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1648 int length = proxy.values.length();
1649 Attribute[] ats = new Attribute[length];
1650 Type elemtype = types.elemtype(type);
1651 int i = 0;
1652 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1653 ats[i++] = deproxy(elemtype, p.head);
1654 }
1655 result = new Attribute.Array(type, ats);
1656 }
1658 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1659 result = deproxyCompound(proxy);
1660 }
1661 }
1663 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1664 final MethodSymbol sym;
1665 final Attribute value;
1666 final JavaFileObject classFile = currentClassFile;
1667 @Override
1668 public String toString() {
1669 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1670 }
1671 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1672 this.sym = sym;
1673 this.value = value;
1674 }
1675 // implement Annotate.Annotator.enterAnnotation()
1676 public void enterAnnotation() {
1677 JavaFileObject previousClassFile = currentClassFile;
1678 try {
1679 currentClassFile = classFile;
1680 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1681 } finally {
1682 currentClassFile = previousClassFile;
1683 }
1684 }
1685 }
1687 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1688 final Symbol sym;
1689 final List<CompoundAnnotationProxy> l;
1690 final JavaFileObject classFile;
1691 @Override
1692 public String toString() {
1693 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1694 }
1695 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1696 this.sym = sym;
1697 this.l = l;
1698 this.classFile = currentClassFile;
1699 }
1700 // implement Annotate.Annotator.enterAnnotation()
1701 public void enterAnnotation() {
1702 JavaFileObject previousClassFile = currentClassFile;
1703 try {
1704 currentClassFile = classFile;
1705 Annotations annotations = sym.annotations;
1706 List<Attribute.Compound> newList = deproxyCompoundList(l);
1707 if (annotations.pendingCompletion()) {
1708 annotations.setAttributes(newList);
1709 } else {
1710 annotations.append(newList);
1711 }
1712 } finally {
1713 currentClassFile = previousClassFile;
1714 }
1715 }
1716 }
1719 /************************************************************************
1720 * Reading Symbols
1721 ***********************************************************************/
1723 /** Read a field.
1724 */
1725 VarSymbol readField() {
1726 long flags = adjustFieldFlags(nextChar());
1727 Name name = readName(nextChar());
1728 Type type = readType(nextChar());
1729 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1730 readMemberAttrs(v);
1731 return v;
1732 }
1734 /** Read a method.
1735 */
1736 MethodSymbol readMethod() {
1737 long flags = adjustMethodFlags(nextChar());
1738 Name name = readName(nextChar());
1739 Type type = readType(nextChar());
1740 if (name == names.init && currentOwner.hasOuterInstance()) {
1741 // Sometimes anonymous classes don't have an outer
1742 // instance, however, there is no reliable way to tell so
1743 // we never strip this$n
1744 if (!currentOwner.name.isEmpty())
1745 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1746 type.getReturnType(),
1747 type.getThrownTypes(),
1748 syms.methodClass);
1749 }
1750 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1751 if (saveParameterNames)
1752 initParameterNames(m);
1753 Symbol prevOwner = currentOwner;
1754 currentOwner = m;
1755 try {
1756 readMemberAttrs(m);
1757 } finally {
1758 currentOwner = prevOwner;
1759 }
1760 if (saveParameterNames)
1761 setParameterNames(m, type);
1762 return m;
1763 }
1765 private List<Type> adjustMethodParams(long flags, List<Type> args) {
1766 boolean isVarargs = (flags & VARARGS) != 0;
1767 if (isVarargs) {
1768 Type varargsElem = args.last();
1769 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
1770 for (Type t : args) {
1771 adjustedArgs.append(t != varargsElem ?
1772 t :
1773 ((ArrayType)t).makeVarargs());
1774 }
1775 args = adjustedArgs.toList();
1776 }
1777 return args.tail;
1778 }
1780 /**
1781 * Init the parameter names array.
1782 * Parameter names are currently inferred from the names in the
1783 * LocalVariableTable attributes of a Code attribute.
1784 * (Note: this means parameter names are currently not available for
1785 * methods without a Code attribute.)
1786 * This method initializes an array in which to store the name indexes
1787 * of parameter names found in LocalVariableTable attributes. It is
1788 * slightly supersized to allow for additional slots with a start_pc of 0.
1789 */
1790 void initParameterNames(MethodSymbol sym) {
1791 // make allowance for synthetic parameters.
1792 final int excessSlots = 4;
1793 int expectedParameterSlots =
1794 Code.width(sym.type.getParameterTypes()) + excessSlots;
1795 if (parameterNameIndices == null
1796 || parameterNameIndices.length < expectedParameterSlots) {
1797 parameterNameIndices = new int[expectedParameterSlots];
1798 } else
1799 Arrays.fill(parameterNameIndices, 0);
1800 haveParameterNameIndices = false;
1801 }
1803 /**
1804 * Set the parameter names for a symbol from the name index in the
1805 * parameterNameIndicies array. The type of the symbol may have changed
1806 * while reading the method attributes (see the Signature attribute).
1807 * This may be because of generic information or because anonymous
1808 * synthetic parameters were added. The original type (as read from
1809 * the method descriptor) is used to help guess the existence of
1810 * anonymous synthetic parameters.
1811 * On completion, sym.savedParameter names will either be null (if
1812 * no parameter names were found in the class file) or will be set to a
1813 * list of names, one per entry in sym.type.getParameterTypes, with
1814 * any missing names represented by the empty name.
1815 */
1816 void setParameterNames(MethodSymbol sym, Type jvmType) {
1817 // if no names were found in the class file, there's nothing more to do
1818 if (!haveParameterNameIndices)
1819 return;
1821 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1822 // the code in readMethod may have skipped the first parameter when
1823 // setting up the MethodType. If so, we make a corresponding allowance
1824 // here for the position of the first parameter. Note that this
1825 // assumes the skipped parameter has a width of 1 -- i.e. it is not
1826 // a double width type (long or double.)
1827 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1828 // Sometimes anonymous classes don't have an outer
1829 // instance, however, there is no reliable way to tell so
1830 // we never strip this$n
1831 if (!currentOwner.name.isEmpty())
1832 firstParam += 1;
1833 }
1835 if (sym.type != jvmType) {
1836 // reading the method attributes has caused the symbol's type to
1837 // be changed. (i.e. the Signature attribute.) This may happen if
1838 // there are hidden (synthetic) parameters in the descriptor, but
1839 // not in the Signature. The position of these hidden parameters
1840 // is unspecified; for now, assume they are at the beginning, and
1841 // so skip over them. The primary case for this is two hidden
1842 // parameters passed into Enum constructors.
1843 int skip = Code.width(jvmType.getParameterTypes())
1844 - Code.width(sym.type.getParameterTypes());
1845 firstParam += skip;
1846 }
1847 List<Name> paramNames = List.nil();
1848 int index = firstParam;
1849 for (Type t: sym.type.getParameterTypes()) {
1850 int nameIdx = (index < parameterNameIndices.length
1851 ? parameterNameIndices[index] : 0);
1852 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
1853 paramNames = paramNames.prepend(name);
1854 index += Code.width(t);
1855 }
1856 sym.savedParameterNames = paramNames.reverse();
1857 }
1859 /**
1860 * skip n bytes
1861 */
1862 void skipBytes(int n) {
1863 bp = bp + n;
1864 }
1866 /** Skip a field or method
1867 */
1868 void skipMember() {
1869 bp = bp + 6;
1870 char ac = nextChar();
1871 for (int i = 0; i < ac; i++) {
1872 bp = bp + 2;
1873 int attrLen = nextInt();
1874 bp = bp + attrLen;
1875 }
1876 }
1878 /** Enter type variables of this classtype and all enclosing ones in
1879 * `typevars'.
1880 */
1881 protected void enterTypevars(Type t) {
1882 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
1883 enterTypevars(t.getEnclosingType());
1884 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1885 typevars.enter(xs.head.tsym);
1886 }
1888 protected void enterTypevars(Symbol sym) {
1889 if (sym.owner.kind == MTH) {
1890 enterTypevars(sym.owner);
1891 enterTypevars(sym.owner.owner);
1892 }
1893 enterTypevars(sym.type);
1894 }
1896 /** Read contents of a given class symbol `c'. Both external and internal
1897 * versions of an inner class are read.
1898 */
1899 void readClass(ClassSymbol c) {
1900 ClassType ct = (ClassType)c.type;
1902 // allocate scope for members
1903 c.members_field = new Scope(c);
1905 // prepare type variable table
1906 typevars = typevars.dup(currentOwner);
1907 if (ct.getEnclosingType().hasTag(CLASS))
1908 enterTypevars(ct.getEnclosingType());
1910 // read flags, or skip if this is an inner class
1911 long flags = adjustClassFlags(nextChar());
1912 if (c.owner.kind == PCK) c.flags_field = flags;
1914 // read own class name and check that it matches
1915 ClassSymbol self = readClassSymbol(nextChar());
1916 if (c != self)
1917 throw badClassFile("class.file.wrong.class",
1918 self.flatname);
1920 // class attributes must be read before class
1921 // skip ahead to read class attributes
1922 int startbp = bp;
1923 nextChar();
1924 char interfaceCount = nextChar();
1925 bp += interfaceCount * 2;
1926 char fieldCount = nextChar();
1927 for (int i = 0; i < fieldCount; i++) skipMember();
1928 char methodCount = nextChar();
1929 for (int i = 0; i < methodCount; i++) skipMember();
1930 readClassAttrs(c);
1932 if (readAllOfClassFile) {
1933 for (int i = 1; i < poolObj.length; i++) readPool(i);
1934 c.pool = new Pool(poolObj.length, poolObj);
1935 }
1937 // reset and read rest of classinfo
1938 bp = startbp;
1939 int n = nextChar();
1940 if (ct.supertype_field == null)
1941 ct.supertype_field = (n == 0)
1942 ? Type.noType
1943 : readClassSymbol(n).erasure(types);
1944 n = nextChar();
1945 List<Type> is = List.nil();
1946 for (int i = 0; i < n; i++) {
1947 Type _inter = readClassSymbol(nextChar()).erasure(types);
1948 is = is.prepend(_inter);
1949 }
1950 if (ct.interfaces_field == null)
1951 ct.interfaces_field = is.reverse();
1953 Assert.check(fieldCount == nextChar());
1954 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
1955 Assert.check(methodCount == nextChar());
1956 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
1958 typevars = typevars.leave();
1959 }
1961 /** Read inner class info. For each inner/outer pair allocate a
1962 * member class.
1963 */
1964 void readInnerClasses(ClassSymbol c) {
1965 int n = nextChar();
1966 for (int i = 0; i < n; i++) {
1967 nextChar(); // skip inner class symbol
1968 ClassSymbol outer = readClassSymbol(nextChar());
1969 Name name = readName(nextChar());
1970 if (name == null) name = names.empty;
1971 long flags = adjustClassFlags(nextChar());
1972 if (outer != null) { // we have a member class
1973 if (name == names.empty)
1974 name = names.one;
1975 ClassSymbol member = enterClass(name, outer);
1976 if ((flags & STATIC) == 0) {
1977 ((ClassType)member.type).setEnclosingType(outer.type);
1978 if (member.erasure_field != null)
1979 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
1980 }
1981 if (c == outer) {
1982 member.flags_field = flags;
1983 enterMember(c, member);
1984 }
1985 }
1986 }
1987 }
1989 /** Read a class file.
1990 */
1991 private void readClassFile(ClassSymbol c) throws IOException {
1992 int magic = nextInt();
1993 if (magic != JAVA_MAGIC)
1994 throw badClassFile("illegal.start.of.class.file");
1996 minorVersion = nextChar();
1997 majorVersion = nextChar();
1998 int maxMajor = Target.MAX().majorVersion;
1999 int maxMinor = Target.MAX().minorVersion;
2000 if (majorVersion > maxMajor ||
2001 majorVersion * 1000 + minorVersion <
2002 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2003 {
2004 if (majorVersion == (maxMajor + 1))
2005 log.warning("big.major.version",
2006 currentClassFile,
2007 majorVersion,
2008 maxMajor);
2009 else
2010 throw badClassFile("wrong.version",
2011 Integer.toString(majorVersion),
2012 Integer.toString(minorVersion),
2013 Integer.toString(maxMajor),
2014 Integer.toString(maxMinor));
2015 }
2016 else if (checkClassFile &&
2017 majorVersion == maxMajor &&
2018 minorVersion > maxMinor)
2019 {
2020 printCCF("found.later.version",
2021 Integer.toString(minorVersion));
2022 }
2023 indexPool();
2024 if (signatureBuffer.length < bp) {
2025 int ns = Integer.highestOneBit(bp) << 1;
2026 signatureBuffer = new byte[ns];
2027 }
2028 readClass(c);
2029 }
2031 /************************************************************************
2032 * Adjusting flags
2033 ***********************************************************************/
2035 long adjustFieldFlags(long flags) {
2036 return flags;
2037 }
2038 long adjustMethodFlags(long flags) {
2039 if ((flags & ACC_BRIDGE) != 0) {
2040 flags &= ~ACC_BRIDGE;
2041 flags |= BRIDGE;
2042 if (!allowGenerics)
2043 flags &= ~SYNTHETIC;
2044 }
2045 if ((flags & ACC_VARARGS) != 0) {
2046 flags &= ~ACC_VARARGS;
2047 flags |= VARARGS;
2048 }
2049 return flags;
2050 }
2051 long adjustClassFlags(long flags) {
2052 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2053 }
2055 /************************************************************************
2056 * Loading Classes
2057 ***********************************************************************/
2059 /** Define a new class given its name and owner.
2060 */
2061 public ClassSymbol defineClass(Name name, Symbol owner) {
2062 ClassSymbol c = new ClassSymbol(0, name, owner);
2063 if (owner.kind == PCK)
2064 Assert.checkNull(classes.get(c.flatname), c);
2065 c.completer = this;
2066 return c;
2067 }
2069 /** Create a new toplevel or member class symbol with given name
2070 * and owner and enter in `classes' unless already there.
2071 */
2072 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2073 Name flatname = TypeSymbol.formFlatName(name, owner);
2074 ClassSymbol c = classes.get(flatname);
2075 if (c == null) {
2076 c = defineClass(name, owner);
2077 classes.put(flatname, c);
2078 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2079 // reassign fields of classes that might have been loaded with
2080 // their flat names.
2081 c.owner.members().remove(c);
2082 c.name = name;
2083 c.owner = owner;
2084 c.fullname = ClassSymbol.formFullName(name, owner);
2085 }
2086 return c;
2087 }
2089 /**
2090 * Creates a new toplevel class symbol with given flat name and
2091 * given class (or source) file.
2092 *
2093 * @param flatName a fully qualified binary class name
2094 * @param classFile the class file or compilation unit defining
2095 * the class (may be {@code null})
2096 * @return a newly created class symbol
2097 * @throws AssertionError if the class symbol already exists
2098 */
2099 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2100 ClassSymbol cs = classes.get(flatName);
2101 if (cs != null) {
2102 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2103 cs.fullname,
2104 cs.completer,
2105 cs.classfile,
2106 cs.sourcefile);
2107 throw new AssertionError(msg);
2108 }
2109 Name packageName = Convert.packagePart(flatName);
2110 PackageSymbol owner = packageName.isEmpty()
2111 ? syms.unnamedPackage
2112 : enterPackage(packageName);
2113 cs = defineClass(Convert.shortName(flatName), owner);
2114 cs.classfile = classFile;
2115 classes.put(flatName, cs);
2116 return cs;
2117 }
2119 /** Create a new member or toplevel class symbol with given flat name
2120 * and enter in `classes' unless already there.
2121 */
2122 public ClassSymbol enterClass(Name flatname) {
2123 ClassSymbol c = classes.get(flatname);
2124 if (c == null)
2125 return enterClass(flatname, (JavaFileObject)null);
2126 else
2127 return c;
2128 }
2130 private boolean suppressFlush = false;
2132 /** Completion for classes to be loaded. Before a class is loaded
2133 * we make sure its enclosing class (if any) is loaded.
2134 */
2135 public void complete(Symbol sym) throws CompletionFailure {
2136 if (sym.kind == TYP) {
2137 ClassSymbol c = (ClassSymbol)sym;
2138 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2139 boolean saveSuppressFlush = suppressFlush;
2140 suppressFlush = true;
2141 try {
2142 completeOwners(c.owner);
2143 completeEnclosing(c);
2144 } finally {
2145 suppressFlush = saveSuppressFlush;
2146 }
2147 fillIn(c);
2148 } else if (sym.kind == PCK) {
2149 PackageSymbol p = (PackageSymbol)sym;
2150 try {
2151 fillIn(p);
2152 } catch (IOException ex) {
2153 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2154 }
2155 }
2156 if (!filling && !suppressFlush)
2157 annotate.flush(); // finish attaching annotations
2158 }
2160 /** complete up through the enclosing package. */
2161 private void completeOwners(Symbol o) {
2162 if (o.kind != PCK) completeOwners(o.owner);
2163 o.complete();
2164 }
2166 /**
2167 * Tries to complete lexically enclosing classes if c looks like a
2168 * nested class. This is similar to completeOwners but handles
2169 * the situation when a nested class is accessed directly as it is
2170 * possible with the Tree API or javax.lang.model.*.
2171 */
2172 private void completeEnclosing(ClassSymbol c) {
2173 if (c.owner.kind == PCK) {
2174 Symbol owner = c.owner;
2175 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2176 Symbol encl = owner.members().lookup(name).sym;
2177 if (encl == null)
2178 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2179 if (encl != null)
2180 encl.complete();
2181 }
2182 }
2183 }
2185 /** We can only read a single class file at a time; this
2186 * flag keeps track of when we are currently reading a class
2187 * file.
2188 */
2189 private boolean filling = false;
2191 /** Fill in definition of class `c' from corresponding class or
2192 * source file.
2193 */
2194 private void fillIn(ClassSymbol c) {
2195 if (completionFailureName == c.fullname) {
2196 throw new CompletionFailure(c, "user-selected completion failure by class name");
2197 }
2198 currentOwner = c;
2199 warnedAttrs.clear();
2200 JavaFileObject classfile = c.classfile;
2201 if (classfile != null) {
2202 JavaFileObject previousClassFile = currentClassFile;
2203 try {
2204 if (filling) {
2205 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2206 }
2207 currentClassFile = classfile;
2208 if (verbose) {
2209 log.printVerbose("loading", currentClassFile.toString());
2210 }
2211 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2212 filling = true;
2213 try {
2214 bp = 0;
2215 buf = readInputStream(buf, classfile.openInputStream());
2216 readClassFile(c);
2217 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2218 List<Type> missing = missingTypeVariables;
2219 List<Type> found = foundTypeVariables;
2220 missingTypeVariables = List.nil();
2221 foundTypeVariables = List.nil();
2222 filling = false;
2223 ClassType ct = (ClassType)currentOwner.type;
2224 ct.supertype_field =
2225 types.subst(ct.supertype_field, missing, found);
2226 ct.interfaces_field =
2227 types.subst(ct.interfaces_field, missing, found);
2228 } else if (missingTypeVariables.isEmpty() !=
2229 foundTypeVariables.isEmpty()) {
2230 Name name = missingTypeVariables.head.tsym.name;
2231 throw badClassFile("undecl.type.var", name);
2232 }
2233 } finally {
2234 missingTypeVariables = List.nil();
2235 foundTypeVariables = List.nil();
2236 filling = false;
2237 }
2238 } else {
2239 if (sourceCompleter != null) {
2240 sourceCompleter.complete(c);
2241 } else {
2242 throw new IllegalStateException("Source completer required to read "
2243 + classfile.toUri());
2244 }
2245 }
2246 return;
2247 } catch (IOException ex) {
2248 throw badClassFile("unable.to.access.file", ex.getMessage());
2249 } finally {
2250 currentClassFile = previousClassFile;
2251 }
2252 } else {
2253 JCDiagnostic diag =
2254 diagFactory.fragment("class.file.not.found", c.flatname);
2255 throw
2256 newCompletionFailure(c, diag);
2257 }
2258 }
2259 // where
2260 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2261 try {
2262 buf = ensureCapacity(buf, s.available());
2263 int r = s.read(buf);
2264 int bp = 0;
2265 while (r != -1) {
2266 bp += r;
2267 buf = ensureCapacity(buf, bp);
2268 r = s.read(buf, bp, buf.length - bp);
2269 }
2270 return buf;
2271 } finally {
2272 try {
2273 s.close();
2274 } catch (IOException e) {
2275 /* Ignore any errors, as this stream may have already
2276 * thrown a related exception which is the one that
2277 * should be reported.
2278 */
2279 }
2280 }
2281 }
2282 /*
2283 * ensureCapacity will increase the buffer as needed, taking note that
2284 * the new buffer will always be greater than the needed and never
2285 * exactly equal to the needed size or bp. If equal then the read (above)
2286 * will infinitely loop as buf.length - bp == 0.
2287 */
2288 private static byte[] ensureCapacity(byte[] buf, int needed) {
2289 if (buf.length <= needed) {
2290 byte[] old = buf;
2291 buf = new byte[Integer.highestOneBit(needed) << 1];
2292 System.arraycopy(old, 0, buf, 0, old.length);
2293 }
2294 return buf;
2295 }
2296 /** Static factory for CompletionFailure objects.
2297 * In practice, only one can be used at a time, so we share one
2298 * to reduce the expense of allocating new exception objects.
2299 */
2300 private CompletionFailure newCompletionFailure(TypeSymbol c,
2301 JCDiagnostic diag) {
2302 if (!cacheCompletionFailure) {
2303 // log.warning("proc.messager",
2304 // Log.getLocalizedString("class.file.not.found", c.flatname));
2305 // c.debug.printStackTrace();
2306 return new CompletionFailure(c, diag);
2307 } else {
2308 CompletionFailure result = cachedCompletionFailure;
2309 result.sym = c;
2310 result.diag = diag;
2311 return result;
2312 }
2313 }
2314 private CompletionFailure cachedCompletionFailure =
2315 new CompletionFailure(null, (JCDiagnostic) null);
2316 {
2317 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2318 }
2320 /** Load a toplevel class with given fully qualified name
2321 * The class is entered into `classes' only if load was successful.
2322 */
2323 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2324 boolean absent = classes.get(flatname) == null;
2325 ClassSymbol c = enterClass(flatname);
2326 if (c.members_field == null && c.completer != null) {
2327 try {
2328 c.complete();
2329 } catch (CompletionFailure ex) {
2330 if (absent) classes.remove(flatname);
2331 throw ex;
2332 }
2333 }
2334 return c;
2335 }
2337 /************************************************************************
2338 * Loading Packages
2339 ***********************************************************************/
2341 /** Check to see if a package exists, given its fully qualified name.
2342 */
2343 public boolean packageExists(Name fullname) {
2344 return enterPackage(fullname).exists();
2345 }
2347 /** Make a package, given its fully qualified name.
2348 */
2349 public PackageSymbol enterPackage(Name fullname) {
2350 PackageSymbol p = packages.get(fullname);
2351 if (p == null) {
2352 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2353 p = new PackageSymbol(
2354 Convert.shortName(fullname),
2355 enterPackage(Convert.packagePart(fullname)));
2356 p.completer = this;
2357 packages.put(fullname, p);
2358 }
2359 return p;
2360 }
2362 /** Make a package, given its unqualified name and enclosing package.
2363 */
2364 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2365 return enterPackage(TypeSymbol.formFullName(name, owner));
2366 }
2368 /** Include class corresponding to given class file in package,
2369 * unless (1) we already have one the same kind (.class or .java), or
2370 * (2) we have one of the other kind, and the given class file
2371 * is older.
2372 */
2373 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2374 if ((p.flags_field & EXISTS) == 0)
2375 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2376 q.flags_field |= EXISTS;
2377 JavaFileObject.Kind kind = file.getKind();
2378 int seen;
2379 if (kind == JavaFileObject.Kind.CLASS)
2380 seen = CLASS_SEEN;
2381 else
2382 seen = SOURCE_SEEN;
2383 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2384 int lastDot = binaryName.lastIndexOf(".");
2385 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2386 boolean isPkgInfo = classname == names.package_info;
2387 ClassSymbol c = isPkgInfo
2388 ? p.package_info
2389 : (ClassSymbol) p.members_field.lookup(classname).sym;
2390 if (c == null) {
2391 c = enterClass(classname, p);
2392 if (c.classfile == null) // only update the file if's it's newly created
2393 c.classfile = file;
2394 if (isPkgInfo) {
2395 p.package_info = c;
2396 } else {
2397 if (c.owner == p) // it might be an inner class
2398 p.members_field.enter(c);
2399 }
2400 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2401 // if c.classfile == null, we are currently compiling this class
2402 // and no further action is necessary.
2403 // if (c.flags_field & seen) != 0, we have already encountered
2404 // a file of the same kind; again no further action is necessary.
2405 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2406 c.classfile = preferredFileObject(file, c.classfile);
2407 }
2408 c.flags_field |= seen;
2409 }
2411 /** Implement policy to choose to derive information from a source
2412 * file or a class file when both are present. May be overridden
2413 * by subclasses.
2414 */
2415 protected JavaFileObject preferredFileObject(JavaFileObject a,
2416 JavaFileObject b) {
2418 if (preferSource)
2419 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2420 else {
2421 long adate = a.getLastModified();
2422 long bdate = b.getLastModified();
2423 // 6449326: policy for bad lastModifiedTime in ClassReader
2424 //assert adate >= 0 && bdate >= 0;
2425 return (adate > bdate) ? a : b;
2426 }
2427 }
2429 /**
2430 * specifies types of files to be read when filling in a package symbol
2431 */
2432 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2433 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2434 }
2436 /**
2437 * this is used to support javadoc
2438 */
2439 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2440 }
2442 protected Location currentLoc; // FIXME
2444 private boolean verbosePath = true;
2446 /** Load directory of package into members scope.
2447 */
2448 private void fillIn(PackageSymbol p) throws IOException {
2449 if (p.members_field == null) p.members_field = new Scope(p);
2450 String packageName = p.fullname.toString();
2452 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2454 fillIn(p, PLATFORM_CLASS_PATH,
2455 fileManager.list(PLATFORM_CLASS_PATH,
2456 packageName,
2457 EnumSet.of(JavaFileObject.Kind.CLASS),
2458 false));
2460 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2461 classKinds.remove(JavaFileObject.Kind.SOURCE);
2462 boolean wantClassFiles = !classKinds.isEmpty();
2464 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2465 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2466 boolean wantSourceFiles = !sourceKinds.isEmpty();
2468 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2470 if (verbose && verbosePath) {
2471 if (fileManager instanceof StandardJavaFileManager) {
2472 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2473 if (haveSourcePath && wantSourceFiles) {
2474 List<File> path = List.nil();
2475 for (File file : fm.getLocation(SOURCE_PATH)) {
2476 path = path.prepend(file);
2477 }
2478 log.printVerbose("sourcepath", path.reverse().toString());
2479 } else if (wantSourceFiles) {
2480 List<File> path = List.nil();
2481 for (File file : fm.getLocation(CLASS_PATH)) {
2482 path = path.prepend(file);
2483 }
2484 log.printVerbose("sourcepath", path.reverse().toString());
2485 }
2486 if (wantClassFiles) {
2487 List<File> path = List.nil();
2488 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2489 path = path.prepend(file);
2490 }
2491 for (File file : fm.getLocation(CLASS_PATH)) {
2492 path = path.prepend(file);
2493 }
2494 log.printVerbose("classpath", path.reverse().toString());
2495 }
2496 }
2497 }
2499 if (wantSourceFiles && !haveSourcePath) {
2500 fillIn(p, CLASS_PATH,
2501 fileManager.list(CLASS_PATH,
2502 packageName,
2503 kinds,
2504 false));
2505 } else {
2506 if (wantClassFiles)
2507 fillIn(p, CLASS_PATH,
2508 fileManager.list(CLASS_PATH,
2509 packageName,
2510 classKinds,
2511 false));
2512 if (wantSourceFiles)
2513 fillIn(p, SOURCE_PATH,
2514 fileManager.list(SOURCE_PATH,
2515 packageName,
2516 sourceKinds,
2517 false));
2518 }
2519 verbosePath = false;
2520 }
2521 // where
2522 private void fillIn(PackageSymbol p,
2523 Location location,
2524 Iterable<JavaFileObject> files)
2525 {
2526 currentLoc = location;
2527 for (JavaFileObject fo : files) {
2528 switch (fo.getKind()) {
2529 case CLASS:
2530 case SOURCE: {
2531 // TODO pass binaryName to includeClassFile
2532 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2533 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2534 if (SourceVersion.isIdentifier(simpleName) ||
2535 simpleName.equals("package-info"))
2536 includeClassFile(p, fo);
2537 break;
2538 }
2539 default:
2540 extraFileActions(p, fo);
2541 }
2542 }
2543 }
2545 /** Output for "-checkclassfile" option.
2546 * @param key The key to look up the correct internationalized string.
2547 * @param arg An argument for substitution into the output string.
2548 */
2549 private void printCCF(String key, Object arg) {
2550 log.printLines(key, arg);
2551 }
2554 public interface SourceCompleter {
2555 void complete(ClassSymbol sym)
2556 throws CompletionFailure;
2557 }
2559 /**
2560 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2561 * The attribute is only the last component of the original filename, so is unlikely
2562 * to be valid as is, so operations other than those to access the name throw
2563 * UnsupportedOperationException
2564 */
2565 private static class SourceFileObject extends BaseFileObject {
2567 /** The file's name.
2568 */
2569 private Name name;
2570 private Name flatname;
2572 public SourceFileObject(Name name, Name flatname) {
2573 super(null); // no file manager; never referenced for this file object
2574 this.name = name;
2575 this.flatname = flatname;
2576 }
2578 @Override
2579 public URI toUri() {
2580 try {
2581 return new URI(null, name.toString(), null);
2582 } catch (URISyntaxException e) {
2583 throw new CannotCreateUriError(name.toString(), e);
2584 }
2585 }
2587 @Override
2588 public String getName() {
2589 return name.toString();
2590 }
2592 @Override
2593 public String getShortName() {
2594 return getName();
2595 }
2597 @Override
2598 public JavaFileObject.Kind getKind() {
2599 return getKind(getName());
2600 }
2602 @Override
2603 public InputStream openInputStream() {
2604 throw new UnsupportedOperationException();
2605 }
2607 @Override
2608 public OutputStream openOutputStream() {
2609 throw new UnsupportedOperationException();
2610 }
2612 @Override
2613 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2614 throw new UnsupportedOperationException();
2615 }
2617 @Override
2618 public Reader openReader(boolean ignoreEncodingErrors) {
2619 throw new UnsupportedOperationException();
2620 }
2622 @Override
2623 public Writer openWriter() {
2624 throw new UnsupportedOperationException();
2625 }
2627 @Override
2628 public long getLastModified() {
2629 throw new UnsupportedOperationException();
2630 }
2632 @Override
2633 public boolean delete() {
2634 throw new UnsupportedOperationException();
2635 }
2637 @Override
2638 protected String inferBinaryName(Iterable<? extends File> path) {
2639 return flatname.toString();
2640 }
2642 @Override
2643 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2644 return true; // fail-safe mode
2645 }
2647 /**
2648 * Check if two file objects are equal.
2649 * SourceFileObjects are just placeholder objects for the value of a
2650 * SourceFile attribute, and do not directly represent specific files.
2651 * Two SourceFileObjects are equal if their names are equal.
2652 */
2653 @Override
2654 public boolean equals(Object other) {
2655 if (this == other)
2656 return true;
2658 if (!(other instanceof SourceFileObject))
2659 return false;
2661 SourceFileObject o = (SourceFileObject) other;
2662 return name.equals(o.name);
2663 }
2665 @Override
2666 public int hashCode() {
2667 return name.hashCode();
2668 }
2669 }
2670 }