Mon, 26 Mar 2012 15:28:49 +0100
7133185: Update 292 overload resolution logic to match JLS
Summary: Re-implement special overload resolution support for method handles according to the JLS SE 7 definition
Reviewed-by: jjg, dlsmith, jrose
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.TypeTags.*;
59 import static com.sun.tools.javac.jvm.ClassFile.*;
60 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
62 import static com.sun.tools.javac.main.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 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 AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
894 this.name = name;
895 this.version = version;
896 this.kinds = kinds;
897 }
899 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 abstract void read(Symbol sym, int attrLen);
920 final Name name;
921 final ClassFile.Version version;
922 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 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 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 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 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 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 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 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 }
1022 },
1024 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1025 void read(Symbol sym, int attrLen) {
1026 // bridge methods are visible when generics not enabled
1027 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
1028 sym.flags_field |= SYNTHETIC;
1029 }
1030 },
1032 // standard v49 attributes
1034 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1035 void read(Symbol sym, int attrLen) {
1036 int newbp = bp + attrLen;
1037 readEnclosingMethodAttr(sym);
1038 bp = newbp;
1039 }
1040 },
1042 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1043 @Override
1044 boolean accepts(AttributeKind kind) {
1045 return super.accepts(kind) && allowGenerics;
1046 }
1048 void read(Symbol sym, int attrLen) {
1049 if (sym.kind == TYP) {
1050 ClassSymbol c = (ClassSymbol) sym;
1051 readingClassAttr = true;
1052 try {
1053 ClassType ct1 = (ClassType)c.type;
1054 Assert.check(c == currentOwner);
1055 ct1.typarams_field = readTypeParams(nextChar());
1056 ct1.supertype_field = sigToType();
1057 ListBuffer<Type> is = new ListBuffer<Type>();
1058 while (sigp != siglimit) is.append(sigToType());
1059 ct1.interfaces_field = is.toList();
1060 } finally {
1061 readingClassAttr = false;
1062 }
1063 } else {
1064 List<Type> thrown = sym.type.getThrownTypes();
1065 sym.type = readType(nextChar());
1066 //- System.err.println(" # " + sym.type);
1067 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1068 sym.type.asMethodType().thrown = thrown;
1070 }
1071 }
1072 },
1074 // v49 annotation attributes
1076 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1077 void read(Symbol sym, int attrLen) {
1078 attachAnnotationDefault(sym);
1079 }
1080 },
1082 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1083 void read(Symbol sym, int attrLen) {
1084 attachAnnotations(sym);
1085 }
1086 },
1088 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1089 void read(Symbol sym, int attrLen) {
1090 attachParameterAnnotations(sym);
1091 }
1092 },
1094 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1095 void read(Symbol sym, int attrLen) {
1096 attachAnnotations(sym);
1097 }
1098 },
1100 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1101 void read(Symbol sym, int attrLen) {
1102 attachParameterAnnotations(sym);
1103 }
1104 },
1106 // additional "legacy" v49 attributes, superceded by flags
1108 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1109 void read(Symbol sym, int attrLen) {
1110 if (allowAnnotations)
1111 sym.flags_field |= ANNOTATION;
1112 }
1113 },
1115 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1116 void read(Symbol sym, int attrLen) {
1117 sym.flags_field |= BRIDGE;
1118 if (!allowGenerics)
1119 sym.flags_field &= ~SYNTHETIC;
1120 }
1121 },
1123 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1124 void read(Symbol sym, int attrLen) {
1125 sym.flags_field |= ENUM;
1126 }
1127 },
1129 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1130 void read(Symbol sym, int attrLen) {
1131 if (allowVarargs)
1132 sym.flags_field |= VARARGS;
1133 }
1134 },
1136 // The following attributes for a Code attribute are not currently handled
1137 // StackMapTable
1138 // SourceDebugExtension
1139 // LineNumberTable
1140 // LocalVariableTypeTable
1141 };
1143 for (AttributeReader r: readers)
1144 attributeReaders.put(r.name, r);
1145 }
1147 /** Report unrecognized attribute.
1148 */
1149 void unrecognized(Name attrName) {
1150 if (checkClassFile)
1151 printCCF("ccf.unrecognized.attribute", attrName);
1152 }
1156 void readEnclosingMethodAttr(Symbol sym) {
1157 // sym is a nested class with an "Enclosing Method" attribute
1158 // remove sym from it's current owners scope and place it in
1159 // the scope specified by the attribute
1160 sym.owner.members().remove(sym);
1161 ClassSymbol self = (ClassSymbol)sym;
1162 ClassSymbol c = readClassSymbol(nextChar());
1163 NameAndType nt = (NameAndType)readPool(nextChar());
1165 if (c.members_field == null)
1166 throw badClassFile("bad.enclosing.class", self, c);
1168 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1169 if (nt != null && m == null)
1170 throw badClassFile("bad.enclosing.method", self);
1172 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1173 self.owner = m != null ? m : c;
1174 if (self.name.isEmpty())
1175 self.fullname = names.empty;
1176 else
1177 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1179 if (m != null) {
1180 ((ClassType)sym.type).setEnclosingType(m.type);
1181 } else if ((self.flags_field & STATIC) == 0) {
1182 ((ClassType)sym.type).setEnclosingType(c.type);
1183 } else {
1184 ((ClassType)sym.type).setEnclosingType(Type.noType);
1185 }
1186 enterTypevars(self);
1187 if (!missingTypeVariables.isEmpty()) {
1188 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1189 for (Type typevar : missingTypeVariables) {
1190 typeVars.append(findTypeVar(typevar.tsym.name));
1191 }
1192 foundTypeVariables = typeVars.toList();
1193 } else {
1194 foundTypeVariables = List.nil();
1195 }
1196 }
1198 // See java.lang.Class
1199 private Name simpleBinaryName(Name self, Name enclosing) {
1200 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1201 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1202 throw badClassFile("bad.enclosing.method", self);
1203 int index = 1;
1204 while (index < simpleBinaryName.length() &&
1205 isAsciiDigit(simpleBinaryName.charAt(index)))
1206 index++;
1207 return names.fromString(simpleBinaryName.substring(index));
1208 }
1210 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1211 if (nt == null)
1212 return null;
1214 MethodType type = nt.type.asMethodType();
1216 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1217 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1218 return (MethodSymbol)e.sym;
1220 if (nt.name != names.init)
1221 // not a constructor
1222 return null;
1223 if ((flags & INTERFACE) != 0)
1224 // no enclosing instance
1225 return null;
1226 if (nt.type.getParameterTypes().isEmpty())
1227 // no parameters
1228 return null;
1230 // A constructor of an inner class.
1231 // Remove the first argument (the enclosing instance)
1232 nt.type = new MethodType(nt.type.getParameterTypes().tail,
1233 nt.type.getReturnType(),
1234 nt.type.getThrownTypes(),
1235 syms.methodClass);
1236 // Try searching again
1237 return findMethod(nt, scope, flags);
1238 }
1240 /** Similar to Types.isSameType but avoids completion */
1241 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1242 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1243 .prepend(types.erasure(mt1.getReturnType()));
1244 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1245 while (!types1.isEmpty() && !types2.isEmpty()) {
1246 if (types1.head.tsym != types2.head.tsym)
1247 return false;
1248 types1 = types1.tail;
1249 types2 = types2.tail;
1250 }
1251 return types1.isEmpty() && types2.isEmpty();
1252 }
1254 /**
1255 * Character.isDigit answers <tt>true</tt> to some non-ascii
1256 * digits. This one does not. <b>copied from java.lang.Class</b>
1257 */
1258 private static boolean isAsciiDigit(char c) {
1259 return '0' <= c && c <= '9';
1260 }
1262 /** Read member attributes.
1263 */
1264 void readMemberAttrs(Symbol sym) {
1265 readAttrs(sym, AttributeKind.MEMBER);
1266 }
1268 void readAttrs(Symbol sym, AttributeKind kind) {
1269 char ac = nextChar();
1270 for (int i = 0; i < ac; i++) {
1271 Name attrName = readName(nextChar());
1272 int attrLen = nextInt();
1273 AttributeReader r = attributeReaders.get(attrName);
1274 if (r != null && r.accepts(kind))
1275 r.read(sym, attrLen);
1276 else {
1277 unrecognized(attrName);
1278 bp = bp + attrLen;
1279 }
1280 }
1281 }
1283 private boolean readingClassAttr = false;
1284 private List<Type> missingTypeVariables = List.nil();
1285 private List<Type> foundTypeVariables = List.nil();
1287 /** Read class attributes.
1288 */
1289 void readClassAttrs(ClassSymbol c) {
1290 readAttrs(c, AttributeKind.CLASS);
1291 }
1293 /** Read code block.
1294 */
1295 Code readCode(Symbol owner) {
1296 nextChar(); // max_stack
1297 nextChar(); // max_locals
1298 final int code_length = nextInt();
1299 bp += code_length;
1300 final char exception_table_length = nextChar();
1301 bp += exception_table_length * 8;
1302 readMemberAttrs(owner);
1303 return null;
1304 }
1306 /************************************************************************
1307 * Reading Java-language annotations
1308 ***********************************************************************/
1310 /** Attach annotations.
1311 */
1312 void attachAnnotations(final Symbol sym) {
1313 int numAttributes = nextChar();
1314 if (numAttributes != 0) {
1315 ListBuffer<CompoundAnnotationProxy> proxies =
1316 new ListBuffer<CompoundAnnotationProxy>();
1317 for (int i = 0; i<numAttributes; i++) {
1318 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1319 if (proxy.type.tsym == syms.proprietaryType.tsym)
1320 sym.flags_field |= PROPRIETARY;
1321 else
1322 proxies.append(proxy);
1323 }
1324 annotate.later(new AnnotationCompleter(sym, proxies.toList()));
1325 }
1326 }
1328 /** Attach parameter annotations.
1329 */
1330 void attachParameterAnnotations(final Symbol method) {
1331 final MethodSymbol meth = (MethodSymbol)method;
1332 int numParameters = buf[bp++] & 0xFF;
1333 List<VarSymbol> parameters = meth.params();
1334 int pnum = 0;
1335 while (parameters.tail != null) {
1336 attachAnnotations(parameters.head);
1337 parameters = parameters.tail;
1338 pnum++;
1339 }
1340 if (pnum != numParameters) {
1341 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1342 }
1343 }
1345 /** Attach the default value for an annotation element.
1346 */
1347 void attachAnnotationDefault(final Symbol sym) {
1348 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1349 final Attribute value = readAttributeValue();
1350 annotate.later(new AnnotationDefaultCompleter(meth, value));
1351 }
1353 Type readTypeOrClassSymbol(int i) {
1354 // support preliminary jsr175-format class files
1355 if (buf[poolIdx[i]] == CONSTANT_Class)
1356 return readClassSymbol(i).type;
1357 return readType(i);
1358 }
1359 Type readEnumType(int i) {
1360 // support preliminary jsr175-format class files
1361 int index = poolIdx[i];
1362 int length = getChar(index + 1);
1363 if (buf[index + length + 2] != ';')
1364 return enterClass(readName(i)).type;
1365 return readType(i);
1366 }
1368 CompoundAnnotationProxy readCompoundAnnotation() {
1369 Type t = readTypeOrClassSymbol(nextChar());
1370 int numFields = nextChar();
1371 ListBuffer<Pair<Name,Attribute>> pairs =
1372 new ListBuffer<Pair<Name,Attribute>>();
1373 for (int i=0; i<numFields; i++) {
1374 Name name = readName(nextChar());
1375 Attribute value = readAttributeValue();
1376 pairs.append(new Pair<Name,Attribute>(name, value));
1377 }
1378 return new CompoundAnnotationProxy(t, pairs.toList());
1379 }
1381 Attribute readAttributeValue() {
1382 char c = (char) buf[bp++];
1383 switch (c) {
1384 case 'B':
1385 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1386 case 'C':
1387 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1388 case 'D':
1389 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1390 case 'F':
1391 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1392 case 'I':
1393 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1394 case 'J':
1395 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1396 case 'S':
1397 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1398 case 'Z':
1399 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1400 case 's':
1401 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1402 case 'e':
1403 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1404 case 'c':
1405 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1406 case '[': {
1407 int n = nextChar();
1408 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1409 for (int i=0; i<n; i++)
1410 l.append(readAttributeValue());
1411 return new ArrayAttributeProxy(l.toList());
1412 }
1413 case '@':
1414 return readCompoundAnnotation();
1415 default:
1416 throw new AssertionError("unknown annotation tag '" + c + "'");
1417 }
1418 }
1420 interface ProxyVisitor extends Attribute.Visitor {
1421 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1422 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1423 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1424 }
1426 static class EnumAttributeProxy extends Attribute {
1427 Type enumType;
1428 Name enumerator;
1429 public EnumAttributeProxy(Type enumType, Name enumerator) {
1430 super(null);
1431 this.enumType = enumType;
1432 this.enumerator = enumerator;
1433 }
1434 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1435 @Override
1436 public String toString() {
1437 return "/*proxy enum*/" + enumType + "." + enumerator;
1438 }
1439 }
1441 static class ArrayAttributeProxy extends Attribute {
1442 List<Attribute> values;
1443 ArrayAttributeProxy(List<Attribute> values) {
1444 super(null);
1445 this.values = values;
1446 }
1447 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1448 @Override
1449 public String toString() {
1450 return "{" + values + "}";
1451 }
1452 }
1454 /** A temporary proxy representing a compound attribute.
1455 */
1456 static class CompoundAnnotationProxy extends Attribute {
1457 final List<Pair<Name,Attribute>> values;
1458 public CompoundAnnotationProxy(Type type,
1459 List<Pair<Name,Attribute>> values) {
1460 super(type);
1461 this.values = values;
1462 }
1463 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1464 @Override
1465 public String toString() {
1466 StringBuilder buf = new StringBuilder();
1467 buf.append("@");
1468 buf.append(type.tsym.getQualifiedName());
1469 buf.append("/*proxy*/{");
1470 boolean first = true;
1471 for (List<Pair<Name,Attribute>> v = values;
1472 v.nonEmpty(); v = v.tail) {
1473 Pair<Name,Attribute> value = v.head;
1474 if (!first) buf.append(",");
1475 first = false;
1476 buf.append(value.fst);
1477 buf.append("=");
1478 buf.append(value.snd);
1479 }
1480 buf.append("}");
1481 return buf.toString();
1482 }
1483 }
1485 /** A temporary proxy representing a type annotation.
1486 */
1487 static class TypeAnnotationProxy {
1488 final CompoundAnnotationProxy compound;
1489 final TypeAnnotationPosition position;
1490 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1491 TypeAnnotationPosition position) {
1492 this.compound = compound;
1493 this.position = position;
1494 }
1495 }
1497 class AnnotationDeproxy implements ProxyVisitor {
1498 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1499 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1501 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1502 // also must fill in types!!!!
1503 ListBuffer<Attribute.Compound> buf =
1504 new ListBuffer<Attribute.Compound>();
1505 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1506 buf.append(deproxyCompound(l.head));
1507 }
1508 return buf.toList();
1509 }
1511 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1512 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1513 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1514 for (List<Pair<Name,Attribute>> l = a.values;
1515 l.nonEmpty();
1516 l = l.tail) {
1517 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1518 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1519 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1520 }
1521 return new Attribute.Compound(a.type, buf.toList());
1522 }
1524 MethodSymbol findAccessMethod(Type container, Name name) {
1525 CompletionFailure failure = null;
1526 try {
1527 for (Scope.Entry e = container.tsym.members().lookup(name);
1528 e.scope != null;
1529 e = e.next()) {
1530 Symbol sym = e.sym;
1531 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1532 return (MethodSymbol) sym;
1533 }
1534 } catch (CompletionFailure ex) {
1535 failure = ex;
1536 }
1537 // The method wasn't found: emit a warning and recover
1538 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1539 try {
1540 if (failure == null) {
1541 log.warning("annotation.method.not.found",
1542 container,
1543 name);
1544 } else {
1545 log.warning("annotation.method.not.found.reason",
1546 container,
1547 name,
1548 failure.getDetailValue());//diagnostic, if present
1549 }
1550 } finally {
1551 log.useSource(prevSource);
1552 }
1553 // Construct a new method type and symbol. Use bottom
1554 // type (typeof null) as return type because this type is
1555 // a subtype of all reference types and can be converted
1556 // to primitive types by unboxing.
1557 MethodType mt = new MethodType(List.<Type>nil(),
1558 syms.botType,
1559 List.<Type>nil(),
1560 syms.methodClass);
1561 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1562 }
1564 Attribute result;
1565 Type type;
1566 Attribute deproxy(Type t, Attribute a) {
1567 Type oldType = type;
1568 try {
1569 type = t;
1570 a.accept(this);
1571 return result;
1572 } finally {
1573 type = oldType;
1574 }
1575 }
1577 // implement Attribute.Visitor below
1579 public void visitConstant(Attribute.Constant value) {
1580 // assert value.type == type;
1581 result = value;
1582 }
1584 public void visitClass(Attribute.Class clazz) {
1585 result = clazz;
1586 }
1588 public void visitEnum(Attribute.Enum e) {
1589 throw new AssertionError(); // shouldn't happen
1590 }
1592 public void visitCompound(Attribute.Compound compound) {
1593 throw new AssertionError(); // shouldn't happen
1594 }
1596 public void visitArray(Attribute.Array array) {
1597 throw new AssertionError(); // shouldn't happen
1598 }
1600 public void visitError(Attribute.Error e) {
1601 throw new AssertionError(); // shouldn't happen
1602 }
1604 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1605 // type.tsym.flatName() should == proxy.enumFlatName
1606 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1607 VarSymbol enumerator = null;
1608 CompletionFailure failure = null;
1609 try {
1610 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1611 e.scope != null;
1612 e = e.next()) {
1613 if (e.sym.kind == VAR) {
1614 enumerator = (VarSymbol)e.sym;
1615 break;
1616 }
1617 }
1618 }
1619 catch (CompletionFailure ex) {
1620 failure = ex;
1621 }
1622 if (enumerator == null) {
1623 if (failure != null) {
1624 log.warning("unknown.enum.constant.reason",
1625 currentClassFile, enumTypeSym, proxy.enumerator,
1626 failure.getDiagnostic());
1627 } else {
1628 log.warning("unknown.enum.constant",
1629 currentClassFile, enumTypeSym, proxy.enumerator);
1630 }
1631 result = new Attribute.Enum(enumTypeSym.type,
1632 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1633 } else {
1634 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1635 }
1636 }
1638 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1639 int length = proxy.values.length();
1640 Attribute[] ats = new Attribute[length];
1641 Type elemtype = types.elemtype(type);
1642 int i = 0;
1643 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1644 ats[i++] = deproxy(elemtype, p.head);
1645 }
1646 result = new Attribute.Array(type, ats);
1647 }
1649 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1650 result = deproxyCompound(proxy);
1651 }
1652 }
1654 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1655 final MethodSymbol sym;
1656 final Attribute value;
1657 final JavaFileObject classFile = currentClassFile;
1658 @Override
1659 public String toString() {
1660 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1661 }
1662 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1663 this.sym = sym;
1664 this.value = value;
1665 }
1666 // implement Annotate.Annotator.enterAnnotation()
1667 public void enterAnnotation() {
1668 JavaFileObject previousClassFile = currentClassFile;
1669 try {
1670 currentClassFile = classFile;
1671 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1672 } finally {
1673 currentClassFile = previousClassFile;
1674 }
1675 }
1676 }
1678 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1679 final Symbol sym;
1680 final List<CompoundAnnotationProxy> l;
1681 final JavaFileObject classFile;
1682 @Override
1683 public String toString() {
1684 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1685 }
1686 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1687 this.sym = sym;
1688 this.l = l;
1689 this.classFile = currentClassFile;
1690 }
1691 // implement Annotate.Annotator.enterAnnotation()
1692 public void enterAnnotation() {
1693 JavaFileObject previousClassFile = currentClassFile;
1694 try {
1695 currentClassFile = classFile;
1696 List<Attribute.Compound> newList = deproxyCompoundList(l);
1697 sym.attributes_field = ((sym.attributes_field == null)
1698 ? newList
1699 : newList.prependList(sym.attributes_field));
1700 } finally {
1701 currentClassFile = previousClassFile;
1702 }
1703 }
1704 }
1707 /************************************************************************
1708 * Reading Symbols
1709 ***********************************************************************/
1711 /** Read a field.
1712 */
1713 VarSymbol readField() {
1714 long flags = adjustFieldFlags(nextChar());
1715 Name name = readName(nextChar());
1716 Type type = readType(nextChar());
1717 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1718 readMemberAttrs(v);
1719 return v;
1720 }
1722 /** Read a method.
1723 */
1724 MethodSymbol readMethod() {
1725 long flags = adjustMethodFlags(nextChar());
1726 Name name = readName(nextChar());
1727 Type type = readType(nextChar());
1728 if (name == names.init && currentOwner.hasOuterInstance()) {
1729 // Sometimes anonymous classes don't have an outer
1730 // instance, however, there is no reliable way to tell so
1731 // we never strip this$n
1732 if (!currentOwner.name.isEmpty())
1733 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1734 type.getReturnType(),
1735 type.getThrownTypes(),
1736 syms.methodClass);
1737 }
1738 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1739 if (saveParameterNames)
1740 initParameterNames(m);
1741 Symbol prevOwner = currentOwner;
1742 currentOwner = m;
1743 try {
1744 readMemberAttrs(m);
1745 } finally {
1746 currentOwner = prevOwner;
1747 }
1748 if (saveParameterNames)
1749 setParameterNames(m, type);
1750 return m;
1751 }
1753 private List<Type> adjustMethodParams(long flags, List<Type> args) {
1754 boolean isVarargs = (flags & VARARGS) != 0;
1755 if (isVarargs) {
1756 Type varargsElem = args.last();
1757 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
1758 for (Type t : args) {
1759 adjustedArgs.append(t != varargsElem ?
1760 t :
1761 ((ArrayType)t).makeVarargs());
1762 }
1763 args = adjustedArgs.toList();
1764 }
1765 return args.tail;
1766 }
1768 /**
1769 * Init the parameter names array.
1770 * Parameter names are currently inferred from the names in the
1771 * LocalVariableTable attributes of a Code attribute.
1772 * (Note: this means parameter names are currently not available for
1773 * methods without a Code attribute.)
1774 * This method initializes an array in which to store the name indexes
1775 * of parameter names found in LocalVariableTable attributes. It is
1776 * slightly supersized to allow for additional slots with a start_pc of 0.
1777 */
1778 void initParameterNames(MethodSymbol sym) {
1779 // make allowance for synthetic parameters.
1780 final int excessSlots = 4;
1781 int expectedParameterSlots =
1782 Code.width(sym.type.getParameterTypes()) + excessSlots;
1783 if (parameterNameIndices == null
1784 || parameterNameIndices.length < expectedParameterSlots) {
1785 parameterNameIndices = new int[expectedParameterSlots];
1786 } else
1787 Arrays.fill(parameterNameIndices, 0);
1788 haveParameterNameIndices = false;
1789 }
1791 /**
1792 * Set the parameter names for a symbol from the name index in the
1793 * parameterNameIndicies array. The type of the symbol may have changed
1794 * while reading the method attributes (see the Signature attribute).
1795 * This may be because of generic information or because anonymous
1796 * synthetic parameters were added. The original type (as read from
1797 * the method descriptor) is used to help guess the existence of
1798 * anonymous synthetic parameters.
1799 * On completion, sym.savedParameter names will either be null (if
1800 * no parameter names were found in the class file) or will be set to a
1801 * list of names, one per entry in sym.type.getParameterTypes, with
1802 * any missing names represented by the empty name.
1803 */
1804 void setParameterNames(MethodSymbol sym, Type jvmType) {
1805 // if no names were found in the class file, there's nothing more to do
1806 if (!haveParameterNameIndices)
1807 return;
1809 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1810 // the code in readMethod may have skipped the first parameter when
1811 // setting up the MethodType. If so, we make a corresponding allowance
1812 // here for the position of the first parameter. Note that this
1813 // assumes the skipped parameter has a width of 1 -- i.e. it is not
1814 // a double width type (long or double.)
1815 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1816 // Sometimes anonymous classes don't have an outer
1817 // instance, however, there is no reliable way to tell so
1818 // we never strip this$n
1819 if (!currentOwner.name.isEmpty())
1820 firstParam += 1;
1821 }
1823 if (sym.type != jvmType) {
1824 // reading the method attributes has caused the symbol's type to
1825 // be changed. (i.e. the Signature attribute.) This may happen if
1826 // there are hidden (synthetic) parameters in the descriptor, but
1827 // not in the Signature. The position of these hidden parameters
1828 // is unspecified; for now, assume they are at the beginning, and
1829 // so skip over them. The primary case for this is two hidden
1830 // parameters passed into Enum constructors.
1831 int skip = Code.width(jvmType.getParameterTypes())
1832 - Code.width(sym.type.getParameterTypes());
1833 firstParam += skip;
1834 }
1835 List<Name> paramNames = List.nil();
1836 int index = firstParam;
1837 for (Type t: sym.type.getParameterTypes()) {
1838 int nameIdx = (index < parameterNameIndices.length
1839 ? parameterNameIndices[index] : 0);
1840 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
1841 paramNames = paramNames.prepend(name);
1842 index += Code.width(t);
1843 }
1844 sym.savedParameterNames = paramNames.reverse();
1845 }
1847 /**
1848 * skip n bytes
1849 */
1850 void skipBytes(int n) {
1851 bp = bp + n;
1852 }
1854 /** Skip a field or method
1855 */
1856 void skipMember() {
1857 bp = bp + 6;
1858 char ac = nextChar();
1859 for (int i = 0; i < ac; i++) {
1860 bp = bp + 2;
1861 int attrLen = nextInt();
1862 bp = bp + attrLen;
1863 }
1864 }
1866 /** Enter type variables of this classtype and all enclosing ones in
1867 * `typevars'.
1868 */
1869 protected void enterTypevars(Type t) {
1870 if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
1871 enterTypevars(t.getEnclosingType());
1872 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1873 typevars.enter(xs.head.tsym);
1874 }
1876 protected void enterTypevars(Symbol sym) {
1877 if (sym.owner.kind == MTH) {
1878 enterTypevars(sym.owner);
1879 enterTypevars(sym.owner.owner);
1880 }
1881 enterTypevars(sym.type);
1882 }
1884 /** Read contents of a given class symbol `c'. Both external and internal
1885 * versions of an inner class are read.
1886 */
1887 void readClass(ClassSymbol c) {
1888 ClassType ct = (ClassType)c.type;
1890 // allocate scope for members
1891 c.members_field = new Scope(c);
1893 // prepare type variable table
1894 typevars = typevars.dup(currentOwner);
1895 if (ct.getEnclosingType().tag == CLASS)
1896 enterTypevars(ct.getEnclosingType());
1898 // read flags, or skip if this is an inner class
1899 long flags = adjustClassFlags(nextChar());
1900 if (c.owner.kind == PCK) c.flags_field = flags;
1902 // read own class name and check that it matches
1903 ClassSymbol self = readClassSymbol(nextChar());
1904 if (c != self)
1905 throw badClassFile("class.file.wrong.class",
1906 self.flatname);
1908 // class attributes must be read before class
1909 // skip ahead to read class attributes
1910 int startbp = bp;
1911 nextChar();
1912 char interfaceCount = nextChar();
1913 bp += interfaceCount * 2;
1914 char fieldCount = nextChar();
1915 for (int i = 0; i < fieldCount; i++) skipMember();
1916 char methodCount = nextChar();
1917 for (int i = 0; i < methodCount; i++) skipMember();
1918 readClassAttrs(c);
1920 if (readAllOfClassFile) {
1921 for (int i = 1; i < poolObj.length; i++) readPool(i);
1922 c.pool = new Pool(poolObj.length, poolObj);
1923 }
1925 // reset and read rest of classinfo
1926 bp = startbp;
1927 int n = nextChar();
1928 if (ct.supertype_field == null)
1929 ct.supertype_field = (n == 0)
1930 ? Type.noType
1931 : readClassSymbol(n).erasure(types);
1932 n = nextChar();
1933 List<Type> is = List.nil();
1934 for (int i = 0; i < n; i++) {
1935 Type _inter = readClassSymbol(nextChar()).erasure(types);
1936 is = is.prepend(_inter);
1937 }
1938 if (ct.interfaces_field == null)
1939 ct.interfaces_field = is.reverse();
1941 Assert.check(fieldCount == nextChar());
1942 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
1943 Assert.check(methodCount == nextChar());
1944 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
1946 typevars = typevars.leave();
1947 }
1949 /** Read inner class info. For each inner/outer pair allocate a
1950 * member class.
1951 */
1952 void readInnerClasses(ClassSymbol c) {
1953 int n = nextChar();
1954 for (int i = 0; i < n; i++) {
1955 nextChar(); // skip inner class symbol
1956 ClassSymbol outer = readClassSymbol(nextChar());
1957 Name name = readName(nextChar());
1958 if (name == null) name = names.empty;
1959 long flags = adjustClassFlags(nextChar());
1960 if (outer != null) { // we have a member class
1961 if (name == names.empty)
1962 name = names.one;
1963 ClassSymbol member = enterClass(name, outer);
1964 if ((flags & STATIC) == 0) {
1965 ((ClassType)member.type).setEnclosingType(outer.type);
1966 if (member.erasure_field != null)
1967 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
1968 }
1969 if (c == outer) {
1970 member.flags_field = flags;
1971 enterMember(c, member);
1972 }
1973 }
1974 }
1975 }
1977 /** Read a class file.
1978 */
1979 private void readClassFile(ClassSymbol c) throws IOException {
1980 int magic = nextInt();
1981 if (magic != JAVA_MAGIC)
1982 throw badClassFile("illegal.start.of.class.file");
1984 minorVersion = nextChar();
1985 majorVersion = nextChar();
1986 int maxMajor = Target.MAX().majorVersion;
1987 int maxMinor = Target.MAX().minorVersion;
1988 if (majorVersion > maxMajor ||
1989 majorVersion * 1000 + minorVersion <
1990 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
1991 {
1992 if (majorVersion == (maxMajor + 1))
1993 log.warning("big.major.version",
1994 currentClassFile,
1995 majorVersion,
1996 maxMajor);
1997 else
1998 throw badClassFile("wrong.version",
1999 Integer.toString(majorVersion),
2000 Integer.toString(minorVersion),
2001 Integer.toString(maxMajor),
2002 Integer.toString(maxMinor));
2003 }
2004 else if (checkClassFile &&
2005 majorVersion == maxMajor &&
2006 minorVersion > maxMinor)
2007 {
2008 printCCF("found.later.version",
2009 Integer.toString(minorVersion));
2010 }
2011 indexPool();
2012 if (signatureBuffer.length < bp) {
2013 int ns = Integer.highestOneBit(bp) << 1;
2014 signatureBuffer = new byte[ns];
2015 }
2016 readClass(c);
2017 }
2019 /************************************************************************
2020 * Adjusting flags
2021 ***********************************************************************/
2023 long adjustFieldFlags(long flags) {
2024 return flags;
2025 }
2026 long adjustMethodFlags(long flags) {
2027 if ((flags & ACC_BRIDGE) != 0) {
2028 flags &= ~ACC_BRIDGE;
2029 flags |= BRIDGE;
2030 if (!allowGenerics)
2031 flags &= ~SYNTHETIC;
2032 }
2033 if ((flags & ACC_VARARGS) != 0) {
2034 flags &= ~ACC_VARARGS;
2035 flags |= VARARGS;
2036 }
2037 return flags;
2038 }
2039 long adjustClassFlags(long flags) {
2040 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2041 }
2043 /************************************************************************
2044 * Loading Classes
2045 ***********************************************************************/
2047 /** Define a new class given its name and owner.
2048 */
2049 public ClassSymbol defineClass(Name name, Symbol owner) {
2050 ClassSymbol c = new ClassSymbol(0, name, owner);
2051 if (owner.kind == PCK)
2052 Assert.checkNull(classes.get(c.flatname), c);
2053 c.completer = this;
2054 return c;
2055 }
2057 /** Create a new toplevel or member class symbol with given name
2058 * and owner and enter in `classes' unless already there.
2059 */
2060 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2061 Name flatname = TypeSymbol.formFlatName(name, owner);
2062 ClassSymbol c = classes.get(flatname);
2063 if (c == null) {
2064 c = defineClass(name, owner);
2065 classes.put(flatname, c);
2066 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2067 // reassign fields of classes that might have been loaded with
2068 // their flat names.
2069 c.owner.members().remove(c);
2070 c.name = name;
2071 c.owner = owner;
2072 c.fullname = ClassSymbol.formFullName(name, owner);
2073 }
2074 return c;
2075 }
2077 /**
2078 * Creates a new toplevel class symbol with given flat name and
2079 * given class (or source) file.
2080 *
2081 * @param flatName a fully qualified binary class name
2082 * @param classFile the class file or compilation unit defining
2083 * the class (may be {@code null})
2084 * @return a newly created class symbol
2085 * @throws AssertionError if the class symbol already exists
2086 */
2087 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2088 ClassSymbol cs = classes.get(flatName);
2089 if (cs != null) {
2090 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2091 cs.fullname,
2092 cs.completer,
2093 cs.classfile,
2094 cs.sourcefile);
2095 throw new AssertionError(msg);
2096 }
2097 Name packageName = Convert.packagePart(flatName);
2098 PackageSymbol owner = packageName.isEmpty()
2099 ? syms.unnamedPackage
2100 : enterPackage(packageName);
2101 cs = defineClass(Convert.shortName(flatName), owner);
2102 cs.classfile = classFile;
2103 classes.put(flatName, cs);
2104 return cs;
2105 }
2107 /** Create a new member or toplevel class symbol with given flat name
2108 * and enter in `classes' unless already there.
2109 */
2110 public ClassSymbol enterClass(Name flatname) {
2111 ClassSymbol c = classes.get(flatname);
2112 if (c == null)
2113 return enterClass(flatname, (JavaFileObject)null);
2114 else
2115 return c;
2116 }
2118 private boolean suppressFlush = false;
2120 /** Completion for classes to be loaded. Before a class is loaded
2121 * we make sure its enclosing class (if any) is loaded.
2122 */
2123 public void complete(Symbol sym) throws CompletionFailure {
2124 if (sym.kind == TYP) {
2125 ClassSymbol c = (ClassSymbol)sym;
2126 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2127 boolean saveSuppressFlush = suppressFlush;
2128 suppressFlush = true;
2129 try {
2130 completeOwners(c.owner);
2131 completeEnclosing(c);
2132 } finally {
2133 suppressFlush = saveSuppressFlush;
2134 }
2135 fillIn(c);
2136 } else if (sym.kind == PCK) {
2137 PackageSymbol p = (PackageSymbol)sym;
2138 try {
2139 fillIn(p);
2140 } catch (IOException ex) {
2141 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2142 }
2143 }
2144 if (!filling && !suppressFlush)
2145 annotate.flush(); // finish attaching annotations
2146 }
2148 /** complete up through the enclosing package. */
2149 private void completeOwners(Symbol o) {
2150 if (o.kind != PCK) completeOwners(o.owner);
2151 o.complete();
2152 }
2154 /**
2155 * Tries to complete lexically enclosing classes if c looks like a
2156 * nested class. This is similar to completeOwners but handles
2157 * the situation when a nested class is accessed directly as it is
2158 * possible with the Tree API or javax.lang.model.*.
2159 */
2160 private void completeEnclosing(ClassSymbol c) {
2161 if (c.owner.kind == PCK) {
2162 Symbol owner = c.owner;
2163 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2164 Symbol encl = owner.members().lookup(name).sym;
2165 if (encl == null)
2166 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2167 if (encl != null)
2168 encl.complete();
2169 }
2170 }
2171 }
2173 /** We can only read a single class file at a time; this
2174 * flag keeps track of when we are currently reading a class
2175 * file.
2176 */
2177 private boolean filling = false;
2179 /** Fill in definition of class `c' from corresponding class or
2180 * source file.
2181 */
2182 private void fillIn(ClassSymbol c) {
2183 if (completionFailureName == c.fullname) {
2184 throw new CompletionFailure(c, "user-selected completion failure by class name");
2185 }
2186 currentOwner = c;
2187 warnedAttrs.clear();
2188 JavaFileObject classfile = c.classfile;
2189 if (classfile != null) {
2190 JavaFileObject previousClassFile = currentClassFile;
2191 try {
2192 if (filling) {
2193 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2194 }
2195 currentClassFile = classfile;
2196 if (verbose) {
2197 log.printVerbose("loading", currentClassFile.toString());
2198 }
2199 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2200 filling = true;
2201 try {
2202 bp = 0;
2203 buf = readInputStream(buf, classfile.openInputStream());
2204 readClassFile(c);
2205 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2206 List<Type> missing = missingTypeVariables;
2207 List<Type> found = foundTypeVariables;
2208 missingTypeVariables = List.nil();
2209 foundTypeVariables = List.nil();
2210 filling = false;
2211 ClassType ct = (ClassType)currentOwner.type;
2212 ct.supertype_field =
2213 types.subst(ct.supertype_field, missing, found);
2214 ct.interfaces_field =
2215 types.subst(ct.interfaces_field, missing, found);
2216 } else if (missingTypeVariables.isEmpty() !=
2217 foundTypeVariables.isEmpty()) {
2218 Name name = missingTypeVariables.head.tsym.name;
2219 throw badClassFile("undecl.type.var", name);
2220 }
2221 } finally {
2222 missingTypeVariables = List.nil();
2223 foundTypeVariables = List.nil();
2224 filling = false;
2225 }
2226 } else {
2227 if (sourceCompleter != null) {
2228 sourceCompleter.complete(c);
2229 } else {
2230 throw new IllegalStateException("Source completer required to read "
2231 + classfile.toUri());
2232 }
2233 }
2234 return;
2235 } catch (IOException ex) {
2236 throw badClassFile("unable.to.access.file", ex.getMessage());
2237 } finally {
2238 currentClassFile = previousClassFile;
2239 }
2240 } else {
2241 JCDiagnostic diag =
2242 diagFactory.fragment("class.file.not.found", c.flatname);
2243 throw
2244 newCompletionFailure(c, diag);
2245 }
2246 }
2247 // where
2248 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2249 try {
2250 buf = ensureCapacity(buf, s.available());
2251 int r = s.read(buf);
2252 int bp = 0;
2253 while (r != -1) {
2254 bp += r;
2255 buf = ensureCapacity(buf, bp);
2256 r = s.read(buf, bp, buf.length - bp);
2257 }
2258 return buf;
2259 } finally {
2260 try {
2261 s.close();
2262 } catch (IOException e) {
2263 /* Ignore any errors, as this stream may have already
2264 * thrown a related exception which is the one that
2265 * should be reported.
2266 */
2267 }
2268 }
2269 }
2270 /*
2271 * ensureCapacity will increase the buffer as needed, taking note that
2272 * the new buffer will always be greater than the needed and never
2273 * exactly equal to the needed size or bp. If equal then the read (above)
2274 * will infinitely loop as buf.length - bp == 0.
2275 */
2276 private static byte[] ensureCapacity(byte[] buf, int needed) {
2277 if (buf.length <= needed) {
2278 byte[] old = buf;
2279 buf = new byte[Integer.highestOneBit(needed) << 1];
2280 System.arraycopy(old, 0, buf, 0, old.length);
2281 }
2282 return buf;
2283 }
2284 /** Static factory for CompletionFailure objects.
2285 * In practice, only one can be used at a time, so we share one
2286 * to reduce the expense of allocating new exception objects.
2287 */
2288 private CompletionFailure newCompletionFailure(TypeSymbol c,
2289 JCDiagnostic diag) {
2290 if (!cacheCompletionFailure) {
2291 // log.warning("proc.messager",
2292 // Log.getLocalizedString("class.file.not.found", c.flatname));
2293 // c.debug.printStackTrace();
2294 return new CompletionFailure(c, diag);
2295 } else {
2296 CompletionFailure result = cachedCompletionFailure;
2297 result.sym = c;
2298 result.diag = diag;
2299 return result;
2300 }
2301 }
2302 private CompletionFailure cachedCompletionFailure =
2303 new CompletionFailure(null, (JCDiagnostic) null);
2304 {
2305 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2306 }
2308 /** Load a toplevel class with given fully qualified name
2309 * The class is entered into `classes' only if load was successful.
2310 */
2311 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2312 boolean absent = classes.get(flatname) == null;
2313 ClassSymbol c = enterClass(flatname);
2314 if (c.members_field == null && c.completer != null) {
2315 try {
2316 c.complete();
2317 } catch (CompletionFailure ex) {
2318 if (absent) classes.remove(flatname);
2319 throw ex;
2320 }
2321 }
2322 return c;
2323 }
2325 /************************************************************************
2326 * Loading Packages
2327 ***********************************************************************/
2329 /** Check to see if a package exists, given its fully qualified name.
2330 */
2331 public boolean packageExists(Name fullname) {
2332 return enterPackage(fullname).exists();
2333 }
2335 /** Make a package, given its fully qualified name.
2336 */
2337 public PackageSymbol enterPackage(Name fullname) {
2338 PackageSymbol p = packages.get(fullname);
2339 if (p == null) {
2340 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2341 p = new PackageSymbol(
2342 Convert.shortName(fullname),
2343 enterPackage(Convert.packagePart(fullname)));
2344 p.completer = this;
2345 packages.put(fullname, p);
2346 }
2347 return p;
2348 }
2350 /** Make a package, given its unqualified name and enclosing package.
2351 */
2352 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2353 return enterPackage(TypeSymbol.formFullName(name, owner));
2354 }
2356 /** Include class corresponding to given class file in package,
2357 * unless (1) we already have one the same kind (.class or .java), or
2358 * (2) we have one of the other kind, and the given class file
2359 * is older.
2360 */
2361 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2362 if ((p.flags_field & EXISTS) == 0)
2363 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2364 q.flags_field |= EXISTS;
2365 JavaFileObject.Kind kind = file.getKind();
2366 int seen;
2367 if (kind == JavaFileObject.Kind.CLASS)
2368 seen = CLASS_SEEN;
2369 else
2370 seen = SOURCE_SEEN;
2371 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2372 int lastDot = binaryName.lastIndexOf(".");
2373 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2374 boolean isPkgInfo = classname == names.package_info;
2375 ClassSymbol c = isPkgInfo
2376 ? p.package_info
2377 : (ClassSymbol) p.members_field.lookup(classname).sym;
2378 if (c == null) {
2379 c = enterClass(classname, p);
2380 if (c.classfile == null) // only update the file if's it's newly created
2381 c.classfile = file;
2382 if (isPkgInfo) {
2383 p.package_info = c;
2384 } else {
2385 if (c.owner == p) // it might be an inner class
2386 p.members_field.enter(c);
2387 }
2388 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2389 // if c.classfile == null, we are currently compiling this class
2390 // and no further action is necessary.
2391 // if (c.flags_field & seen) != 0, we have already encountered
2392 // a file of the same kind; again no further action is necessary.
2393 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2394 c.classfile = preferredFileObject(file, c.classfile);
2395 }
2396 c.flags_field |= seen;
2397 }
2399 /** Implement policy to choose to derive information from a source
2400 * file or a class file when both are present. May be overridden
2401 * by subclasses.
2402 */
2403 protected JavaFileObject preferredFileObject(JavaFileObject a,
2404 JavaFileObject b) {
2406 if (preferSource)
2407 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2408 else {
2409 long adate = a.getLastModified();
2410 long bdate = b.getLastModified();
2411 // 6449326: policy for bad lastModifiedTime in ClassReader
2412 //assert adate >= 0 && bdate >= 0;
2413 return (adate > bdate) ? a : b;
2414 }
2415 }
2417 /**
2418 * specifies types of files to be read when filling in a package symbol
2419 */
2420 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2421 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2422 }
2424 /**
2425 * this is used to support javadoc
2426 */
2427 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2428 }
2430 protected Location currentLoc; // FIXME
2432 private boolean verbosePath = true;
2434 /** Load directory of package into members scope.
2435 */
2436 private void fillIn(PackageSymbol p) throws IOException {
2437 if (p.members_field == null) p.members_field = new Scope(p);
2438 String packageName = p.fullname.toString();
2440 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2442 fillIn(p, PLATFORM_CLASS_PATH,
2443 fileManager.list(PLATFORM_CLASS_PATH,
2444 packageName,
2445 EnumSet.of(JavaFileObject.Kind.CLASS),
2446 false));
2448 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2449 classKinds.remove(JavaFileObject.Kind.SOURCE);
2450 boolean wantClassFiles = !classKinds.isEmpty();
2452 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2453 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2454 boolean wantSourceFiles = !sourceKinds.isEmpty();
2456 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2458 if (verbose && verbosePath) {
2459 if (fileManager instanceof StandardJavaFileManager) {
2460 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2461 if (haveSourcePath && wantSourceFiles) {
2462 List<File> path = List.nil();
2463 for (File file : fm.getLocation(SOURCE_PATH)) {
2464 path = path.prepend(file);
2465 }
2466 log.printVerbose("sourcepath", path.reverse().toString());
2467 } else if (wantSourceFiles) {
2468 List<File> path = List.nil();
2469 for (File file : fm.getLocation(CLASS_PATH)) {
2470 path = path.prepend(file);
2471 }
2472 log.printVerbose("sourcepath", path.reverse().toString());
2473 }
2474 if (wantClassFiles) {
2475 List<File> path = List.nil();
2476 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2477 path = path.prepend(file);
2478 }
2479 for (File file : fm.getLocation(CLASS_PATH)) {
2480 path = path.prepend(file);
2481 }
2482 log.printVerbose("classpath", path.reverse().toString());
2483 }
2484 }
2485 }
2487 if (wantSourceFiles && !haveSourcePath) {
2488 fillIn(p, CLASS_PATH,
2489 fileManager.list(CLASS_PATH,
2490 packageName,
2491 kinds,
2492 false));
2493 } else {
2494 if (wantClassFiles)
2495 fillIn(p, CLASS_PATH,
2496 fileManager.list(CLASS_PATH,
2497 packageName,
2498 classKinds,
2499 false));
2500 if (wantSourceFiles)
2501 fillIn(p, SOURCE_PATH,
2502 fileManager.list(SOURCE_PATH,
2503 packageName,
2504 sourceKinds,
2505 false));
2506 }
2507 verbosePath = false;
2508 }
2509 // where
2510 private void fillIn(PackageSymbol p,
2511 Location location,
2512 Iterable<JavaFileObject> files)
2513 {
2514 currentLoc = location;
2515 for (JavaFileObject fo : files) {
2516 switch (fo.getKind()) {
2517 case CLASS:
2518 case SOURCE: {
2519 // TODO pass binaryName to includeClassFile
2520 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2521 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2522 if (SourceVersion.isIdentifier(simpleName) ||
2523 simpleName.equals("package-info"))
2524 includeClassFile(p, fo);
2525 break;
2526 }
2527 default:
2528 extraFileActions(p, fo);
2529 }
2530 }
2531 }
2533 /** Output for "-checkclassfile" option.
2534 * @param key The key to look up the correct internationalized string.
2535 * @param arg An argument for substitution into the output string.
2536 */
2537 private void printCCF(String key, Object arg) {
2538 log.printLines(key, arg);
2539 }
2542 public interface SourceCompleter {
2543 void complete(ClassSymbol sym)
2544 throws CompletionFailure;
2545 }
2547 /**
2548 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2549 * The attribute is only the last component of the original filename, so is unlikely
2550 * to be valid as is, so operations other than those to access the name throw
2551 * UnsupportedOperationException
2552 */
2553 private static class SourceFileObject extends BaseFileObject {
2555 /** The file's name.
2556 */
2557 private Name name;
2558 private Name flatname;
2560 public SourceFileObject(Name name, Name flatname) {
2561 super(null); // no file manager; never referenced for this file object
2562 this.name = name;
2563 this.flatname = flatname;
2564 }
2566 @Override
2567 public URI toUri() {
2568 try {
2569 return new URI(null, name.toString(), null);
2570 } catch (URISyntaxException e) {
2571 throw new CannotCreateUriError(name.toString(), e);
2572 }
2573 }
2575 @Override
2576 public String getName() {
2577 return name.toString();
2578 }
2580 @Override
2581 public String getShortName() {
2582 return getName();
2583 }
2585 @Override
2586 public JavaFileObject.Kind getKind() {
2587 return getKind(getName());
2588 }
2590 @Override
2591 public InputStream openInputStream() {
2592 throw new UnsupportedOperationException();
2593 }
2595 @Override
2596 public OutputStream openOutputStream() {
2597 throw new UnsupportedOperationException();
2598 }
2600 @Override
2601 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2602 throw new UnsupportedOperationException();
2603 }
2605 @Override
2606 public Reader openReader(boolean ignoreEncodingErrors) {
2607 throw new UnsupportedOperationException();
2608 }
2610 @Override
2611 public Writer openWriter() {
2612 throw new UnsupportedOperationException();
2613 }
2615 @Override
2616 public long getLastModified() {
2617 throw new UnsupportedOperationException();
2618 }
2620 @Override
2621 public boolean delete() {
2622 throw new UnsupportedOperationException();
2623 }
2625 @Override
2626 protected String inferBinaryName(Iterable<? extends File> path) {
2627 return flatname.toString();
2628 }
2630 @Override
2631 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2632 return true; // fail-safe mode
2633 }
2635 /**
2636 * Check if two file objects are equal.
2637 * SourceFileObjects are just placeholder objects for the value of a
2638 * SourceFile attribute, and do not directly represent specific files.
2639 * Two SourceFileObjects are equal if their names are equal.
2640 */
2641 @Override
2642 public boolean equals(Object other) {
2643 if (this == other)
2644 return true;
2646 if (!(other instanceof SourceFileObject))
2647 return false;
2649 SourceFileObject o = (SourceFileObject) other;
2650 return name.equals(o.name);
2651 }
2653 @Override
2654 public int hashCode() {
2655 return name.hashCode();
2656 }
2657 }
2658 }