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