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