Tue, 29 Jun 2010 22:43:59 -0700
Merge
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 },
1101 new AttributeReader(names.PolymorphicSignature, V45_3/*S.B.V51*/, CLASS_OR_MEMBER_ATTRIBUTE) {
1102 void read(Symbol sym, int attrLen) {
1103 sym.flags_field |= POLYMORPHIC_SIGNATURE;
1104 }
1105 },
1108 // The following attributes for a Code attribute are not currently handled
1109 // StackMapTable
1110 // SourceDebugExtension
1111 // LineNumberTable
1112 // LocalVariableTypeTable
1113 };
1115 for (AttributeReader r: readers)
1116 attributeReaders.put(r.name, r);
1117 }
1119 /** Report unrecognized attribute.
1120 */
1121 void unrecognized(Name attrName) {
1122 if (checkClassFile)
1123 printCCF("ccf.unrecognized.attribute", attrName);
1124 }
1128 void readEnclosingMethodAttr(Symbol sym) {
1129 // sym is a nested class with an "Enclosing Method" attribute
1130 // remove sym from it's current owners scope and place it in
1131 // the scope specified by the attribute
1132 sym.owner.members().remove(sym);
1133 ClassSymbol self = (ClassSymbol)sym;
1134 ClassSymbol c = readClassSymbol(nextChar());
1135 NameAndType nt = (NameAndType)readPool(nextChar());
1137 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1138 if (nt != null && m == null)
1139 throw badClassFile("bad.enclosing.method", self);
1141 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1142 self.owner = m != null ? m : c;
1143 if (self.name.isEmpty())
1144 self.fullname = names.empty;
1145 else
1146 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1148 if (m != null) {
1149 ((ClassType)sym.type).setEnclosingType(m.type);
1150 } else if ((self.flags_field & STATIC) == 0) {
1151 ((ClassType)sym.type).setEnclosingType(c.type);
1152 } else {
1153 ((ClassType)sym.type).setEnclosingType(Type.noType);
1154 }
1155 enterTypevars(self);
1156 if (!missingTypeVariables.isEmpty()) {
1157 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1158 for (Type typevar : missingTypeVariables) {
1159 typeVars.append(findTypeVar(typevar.tsym.name));
1160 }
1161 foundTypeVariables = typeVars.toList();
1162 } else {
1163 foundTypeVariables = List.nil();
1164 }
1165 }
1167 // See java.lang.Class
1168 private Name simpleBinaryName(Name self, Name enclosing) {
1169 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1170 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1171 throw badClassFile("bad.enclosing.method", self);
1172 int index = 1;
1173 while (index < simpleBinaryName.length() &&
1174 isAsciiDigit(simpleBinaryName.charAt(index)))
1175 index++;
1176 return names.fromString(simpleBinaryName.substring(index));
1177 }
1179 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1180 if (nt == null)
1181 return null;
1183 MethodType type = nt.type.asMethodType();
1185 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1186 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1187 return (MethodSymbol)e.sym;
1189 if (nt.name != names.init)
1190 // not a constructor
1191 return null;
1192 if ((flags & INTERFACE) != 0)
1193 // no enclosing instance
1194 return null;
1195 if (nt.type.getParameterTypes().isEmpty())
1196 // no parameters
1197 return null;
1199 // A constructor of an inner class.
1200 // Remove the first argument (the enclosing instance)
1201 nt.type = new MethodType(nt.type.getParameterTypes().tail,
1202 nt.type.getReturnType(),
1203 nt.type.getThrownTypes(),
1204 syms.methodClass);
1205 // Try searching again
1206 return findMethod(nt, scope, flags);
1207 }
1209 /** Similar to Types.isSameType but avoids completion */
1210 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1211 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1212 .prepend(types.erasure(mt1.getReturnType()));
1213 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1214 while (!types1.isEmpty() && !types2.isEmpty()) {
1215 if (types1.head.tsym != types2.head.tsym)
1216 return false;
1217 types1 = types1.tail;
1218 types2 = types2.tail;
1219 }
1220 return types1.isEmpty() && types2.isEmpty();
1221 }
1223 /**
1224 * Character.isDigit answers <tt>true</tt> to some non-ascii
1225 * digits. This one does not. <b>copied from java.lang.Class</b>
1226 */
1227 private static boolean isAsciiDigit(char c) {
1228 return '0' <= c && c <= '9';
1229 }
1231 /** Read member attributes.
1232 */
1233 void readMemberAttrs(Symbol sym) {
1234 readAttrs(sym, AttributeKind.MEMBER);
1235 }
1237 void readAttrs(Symbol sym, AttributeKind kind) {
1238 char ac = nextChar();
1239 for (int i = 0; i < ac; i++) {
1240 Name attrName = readName(nextChar());
1241 int attrLen = nextInt();
1242 AttributeReader r = attributeReaders.get(attrName);
1243 if (r != null && r.accepts(kind))
1244 r.read(sym, attrLen);
1245 else {
1246 unrecognized(attrName);
1247 bp = bp + attrLen;
1248 }
1249 }
1250 }
1252 private boolean readingClassAttr = false;
1253 private List<Type> missingTypeVariables = List.nil();
1254 private List<Type> foundTypeVariables = List.nil();
1256 /** Read class attributes.
1257 */
1258 void readClassAttrs(ClassSymbol c) {
1259 readAttrs(c, AttributeKind.CLASS);
1260 }
1262 /** Read code block.
1263 */
1264 Code readCode(Symbol owner) {
1265 nextChar(); // max_stack
1266 nextChar(); // max_locals
1267 final int code_length = nextInt();
1268 bp += code_length;
1269 final char exception_table_length = nextChar();
1270 bp += exception_table_length * 8;
1271 readMemberAttrs(owner);
1272 return null;
1273 }
1275 /************************************************************************
1276 * Reading Java-language annotations
1277 ***********************************************************************/
1279 /** Attach annotations.
1280 */
1281 void attachAnnotations(final Symbol sym) {
1282 int numAttributes = nextChar();
1283 if (numAttributes != 0) {
1284 ListBuffer<CompoundAnnotationProxy> proxies =
1285 new ListBuffer<CompoundAnnotationProxy>();
1286 for (int i = 0; i<numAttributes; i++) {
1287 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1288 if (proxy.type.tsym == syms.proprietaryType.tsym)
1289 sym.flags_field |= PROPRIETARY;
1290 else
1291 proxies.append(proxy);
1292 }
1293 annotate.later(new AnnotationCompleter(sym, proxies.toList()));
1294 }
1295 }
1297 /** Attach parameter annotations.
1298 */
1299 void attachParameterAnnotations(final Symbol method) {
1300 final MethodSymbol meth = (MethodSymbol)method;
1301 int numParameters = buf[bp++] & 0xFF;
1302 List<VarSymbol> parameters = meth.params();
1303 int pnum = 0;
1304 while (parameters.tail != null) {
1305 attachAnnotations(parameters.head);
1306 parameters = parameters.tail;
1307 pnum++;
1308 }
1309 if (pnum != numParameters) {
1310 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1311 }
1312 }
1314 void attachTypeAnnotations(final Symbol sym) {
1315 int numAttributes = nextChar();
1316 if (numAttributes != 0) {
1317 ListBuffer<TypeAnnotationProxy> proxies =
1318 ListBuffer.lb();
1319 for (int i = 0; i < numAttributes; i++)
1320 proxies.append(readTypeAnnotation());
1321 annotate.later(new TypeAnnotationCompleter(sym, proxies.toList()));
1322 }
1323 }
1325 /** Attach the default value for an annotation element.
1326 */
1327 void attachAnnotationDefault(final Symbol sym) {
1328 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1329 final Attribute value = readAttributeValue();
1330 annotate.later(new AnnotationDefaultCompleter(meth, value));
1331 }
1333 Type readTypeOrClassSymbol(int i) {
1334 // support preliminary jsr175-format class files
1335 if (buf[poolIdx[i]] == CONSTANT_Class)
1336 return readClassSymbol(i).type;
1337 return readType(i);
1338 }
1339 Type readEnumType(int i) {
1340 // support preliminary jsr175-format class files
1341 int index = poolIdx[i];
1342 int length = getChar(index + 1);
1343 if (buf[index + length + 2] != ';')
1344 return enterClass(readName(i)).type;
1345 return readType(i);
1346 }
1348 CompoundAnnotationProxy readCompoundAnnotation() {
1349 Type t = readTypeOrClassSymbol(nextChar());
1350 int numFields = nextChar();
1351 ListBuffer<Pair<Name,Attribute>> pairs =
1352 new ListBuffer<Pair<Name,Attribute>>();
1353 for (int i=0; i<numFields; i++) {
1354 Name name = readName(nextChar());
1355 Attribute value = readAttributeValue();
1356 pairs.append(new Pair<Name,Attribute>(name, value));
1357 }
1358 return new CompoundAnnotationProxy(t, pairs.toList());
1359 }
1361 TypeAnnotationProxy readTypeAnnotation() {
1362 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1363 TypeAnnotationPosition position = readPosition();
1365 if (debugJSR308)
1366 System.out.println("TA: reading: " + proxy + " @ " + position
1367 + " in " + log.currentSourceFile());
1369 return new TypeAnnotationProxy(proxy, position);
1370 }
1372 TypeAnnotationPosition readPosition() {
1373 byte tag = nextByte();
1375 if (!TargetType.isValidTargetTypeValue(tag))
1376 throw this.badClassFile("bad.type.annotation.value", tag);
1378 TypeAnnotationPosition position = new TypeAnnotationPosition();
1379 TargetType type = TargetType.fromTargetTypeValue(tag);
1381 position.type = type;
1383 switch (type) {
1384 // type case
1385 case TYPECAST:
1386 case TYPECAST_GENERIC_OR_ARRAY:
1387 // object creation
1388 case INSTANCEOF:
1389 case INSTANCEOF_GENERIC_OR_ARRAY:
1390 // new expression
1391 case NEW:
1392 case NEW_GENERIC_OR_ARRAY:
1393 position.offset = nextChar();
1394 break;
1395 // local variable
1396 case LOCAL_VARIABLE:
1397 case LOCAL_VARIABLE_GENERIC_OR_ARRAY:
1398 int table_length = nextChar();
1399 position.lvarOffset = new int[table_length];
1400 position.lvarLength = new int[table_length];
1401 position.lvarIndex = new int[table_length];
1403 for (int i = 0; i < table_length; ++i) {
1404 position.lvarOffset[i] = nextChar();
1405 position.lvarLength[i] = nextChar();
1406 position.lvarIndex[i] = nextChar();
1407 }
1408 break;
1409 // method receiver
1410 case METHOD_RECEIVER:
1411 // Do nothing
1412 break;
1413 // type parameters
1414 case CLASS_TYPE_PARAMETER:
1415 case METHOD_TYPE_PARAMETER:
1416 position.parameter_index = nextByte();
1417 break;
1418 // type parameter bounds
1419 case CLASS_TYPE_PARAMETER_BOUND:
1420 case CLASS_TYPE_PARAMETER_BOUND_GENERIC_OR_ARRAY:
1421 case METHOD_TYPE_PARAMETER_BOUND:
1422 case METHOD_TYPE_PARAMETER_BOUND_GENERIC_OR_ARRAY:
1423 position.parameter_index = nextByte();
1424 position.bound_index = nextByte();
1425 break;
1426 // wildcard
1427 case WILDCARD_BOUND:
1428 case WILDCARD_BOUND_GENERIC_OR_ARRAY:
1429 position.wildcard_position = readPosition();
1430 break;
1431 // Class extends and implements clauses
1432 case CLASS_EXTENDS:
1433 case CLASS_EXTENDS_GENERIC_OR_ARRAY:
1434 position.type_index = nextChar();
1435 break;
1436 // throws
1437 case THROWS:
1438 position.type_index = nextChar();
1439 break;
1440 case CLASS_LITERAL:
1441 case CLASS_LITERAL_GENERIC_OR_ARRAY:
1442 position.offset = nextChar();
1443 break;
1444 // method parameter: not specified
1445 case METHOD_PARAMETER_GENERIC_OR_ARRAY:
1446 position.parameter_index = nextByte();
1447 break;
1448 // method type argument: wasn't specified
1449 case NEW_TYPE_ARGUMENT:
1450 case NEW_TYPE_ARGUMENT_GENERIC_OR_ARRAY:
1451 case METHOD_TYPE_ARGUMENT:
1452 case METHOD_TYPE_ARGUMENT_GENERIC_OR_ARRAY:
1453 position.offset = nextChar();
1454 position.type_index = nextByte();
1455 break;
1456 // We don't need to worry abut these
1457 case METHOD_RETURN_GENERIC_OR_ARRAY:
1458 case FIELD_GENERIC_OR_ARRAY:
1459 break;
1460 case UNKNOWN:
1461 break;
1462 default:
1463 throw new AssertionError("unknown type: " + position);
1464 }
1466 if (type.hasLocation()) {
1467 int len = nextChar();
1468 ListBuffer<Integer> loc = ListBuffer.lb();
1469 for (int i = 0; i < len; i++)
1470 loc = loc.append((int)nextByte());
1471 position.location = loc.toList();
1472 }
1474 return position;
1475 }
1476 Attribute readAttributeValue() {
1477 char c = (char) buf[bp++];
1478 switch (c) {
1479 case 'B':
1480 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1481 case 'C':
1482 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1483 case 'D':
1484 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1485 case 'F':
1486 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1487 case 'I':
1488 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1489 case 'J':
1490 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1491 case 'S':
1492 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1493 case 'Z':
1494 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1495 case 's':
1496 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1497 case 'e':
1498 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1499 case 'c':
1500 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1501 case '[': {
1502 int n = nextChar();
1503 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1504 for (int i=0; i<n; i++)
1505 l.append(readAttributeValue());
1506 return new ArrayAttributeProxy(l.toList());
1507 }
1508 case '@':
1509 return readCompoundAnnotation();
1510 default:
1511 throw new AssertionError("unknown annotation tag '" + c + "'");
1512 }
1513 }
1515 interface ProxyVisitor extends Attribute.Visitor {
1516 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1517 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1518 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1519 }
1521 static class EnumAttributeProxy extends Attribute {
1522 Type enumType;
1523 Name enumerator;
1524 public EnumAttributeProxy(Type enumType, Name enumerator) {
1525 super(null);
1526 this.enumType = enumType;
1527 this.enumerator = enumerator;
1528 }
1529 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1530 @Override
1531 public String toString() {
1532 return "/*proxy enum*/" + enumType + "." + enumerator;
1533 }
1534 }
1536 static class ArrayAttributeProxy extends Attribute {
1537 List<Attribute> values;
1538 ArrayAttributeProxy(List<Attribute> values) {
1539 super(null);
1540 this.values = values;
1541 }
1542 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1543 @Override
1544 public String toString() {
1545 return "{" + values + "}";
1546 }
1547 }
1549 /** A temporary proxy representing a compound attribute.
1550 */
1551 static class CompoundAnnotationProxy extends Attribute {
1552 final List<Pair<Name,Attribute>> values;
1553 public CompoundAnnotationProxy(Type type,
1554 List<Pair<Name,Attribute>> values) {
1555 super(type);
1556 this.values = values;
1557 }
1558 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1559 @Override
1560 public String toString() {
1561 StringBuffer buf = new StringBuffer();
1562 buf.append("@");
1563 buf.append(type.tsym.getQualifiedName());
1564 buf.append("/*proxy*/{");
1565 boolean first = true;
1566 for (List<Pair<Name,Attribute>> v = values;
1567 v.nonEmpty(); v = v.tail) {
1568 Pair<Name,Attribute> value = v.head;
1569 if (!first) buf.append(",");
1570 first = false;
1571 buf.append(value.fst);
1572 buf.append("=");
1573 buf.append(value.snd);
1574 }
1575 buf.append("}");
1576 return buf.toString();
1577 }
1578 }
1580 /** A temporary proxy representing a type annotation.
1581 */
1582 static class TypeAnnotationProxy {
1583 final CompoundAnnotationProxy compound;
1584 final TypeAnnotationPosition position;
1585 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1586 TypeAnnotationPosition position) {
1587 this.compound = compound;
1588 this.position = position;
1589 }
1590 }
1592 class AnnotationDeproxy implements ProxyVisitor {
1593 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1594 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1596 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1597 // also must fill in types!!!!
1598 ListBuffer<Attribute.Compound> buf =
1599 new ListBuffer<Attribute.Compound>();
1600 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1601 buf.append(deproxyCompound(l.head));
1602 }
1603 return buf.toList();
1604 }
1606 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1607 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1608 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1609 for (List<Pair<Name,Attribute>> l = a.values;
1610 l.nonEmpty();
1611 l = l.tail) {
1612 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1613 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1614 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1615 }
1616 return new Attribute.Compound(a.type, buf.toList());
1617 }
1619 MethodSymbol findAccessMethod(Type container, Name name) {
1620 CompletionFailure failure = null;
1621 try {
1622 for (Scope.Entry e = container.tsym.members().lookup(name);
1623 e.scope != null;
1624 e = e.next()) {
1625 Symbol sym = e.sym;
1626 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1627 return (MethodSymbol) sym;
1628 }
1629 } catch (CompletionFailure ex) {
1630 failure = ex;
1631 }
1632 // The method wasn't found: emit a warning and recover
1633 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1634 try {
1635 if (failure == null) {
1636 log.warning("annotation.method.not.found",
1637 container,
1638 name);
1639 } else {
1640 log.warning("annotation.method.not.found.reason",
1641 container,
1642 name,
1643 failure.getDetailValue());//diagnostic, if present
1644 }
1645 } finally {
1646 log.useSource(prevSource);
1647 }
1648 // Construct a new method type and symbol. Use bottom
1649 // type (typeof null) as return type because this type is
1650 // a subtype of all reference types and can be converted
1651 // to primitive types by unboxing.
1652 MethodType mt = new MethodType(List.<Type>nil(),
1653 syms.botType,
1654 List.<Type>nil(),
1655 syms.methodClass);
1656 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1657 }
1659 Attribute result;
1660 Type type;
1661 Attribute deproxy(Type t, Attribute a) {
1662 Type oldType = type;
1663 try {
1664 type = t;
1665 a.accept(this);
1666 return result;
1667 } finally {
1668 type = oldType;
1669 }
1670 }
1672 // implement Attribute.Visitor below
1674 public void visitConstant(Attribute.Constant value) {
1675 // assert value.type == type;
1676 result = value;
1677 }
1679 public void visitClass(Attribute.Class clazz) {
1680 result = clazz;
1681 }
1683 public void visitEnum(Attribute.Enum e) {
1684 throw new AssertionError(); // shouldn't happen
1685 }
1687 public void visitCompound(Attribute.Compound compound) {
1688 throw new AssertionError(); // shouldn't happen
1689 }
1691 public void visitArray(Attribute.Array array) {
1692 throw new AssertionError(); // shouldn't happen
1693 }
1695 public void visitError(Attribute.Error e) {
1696 throw new AssertionError(); // shouldn't happen
1697 }
1699 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1700 // type.tsym.flatName() should == proxy.enumFlatName
1701 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1702 VarSymbol enumerator = null;
1703 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1704 e.scope != null;
1705 e = e.next()) {
1706 if (e.sym.kind == VAR) {
1707 enumerator = (VarSymbol)e.sym;
1708 break;
1709 }
1710 }
1711 if (enumerator == null) {
1712 log.error("unknown.enum.constant",
1713 currentClassFile, enumTypeSym, proxy.enumerator);
1714 result = new Attribute.Error(enumTypeSym.type);
1715 } else {
1716 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1717 }
1718 }
1720 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1721 int length = proxy.values.length();
1722 Attribute[] ats = new Attribute[length];
1723 Type elemtype = types.elemtype(type);
1724 int i = 0;
1725 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1726 ats[i++] = deproxy(elemtype, p.head);
1727 }
1728 result = new Attribute.Array(type, ats);
1729 }
1731 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1732 result = deproxyCompound(proxy);
1733 }
1734 }
1736 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1737 final MethodSymbol sym;
1738 final Attribute value;
1739 final JavaFileObject classFile = currentClassFile;
1740 @Override
1741 public String toString() {
1742 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1743 }
1744 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1745 this.sym = sym;
1746 this.value = value;
1747 }
1748 // implement Annotate.Annotator.enterAnnotation()
1749 public void enterAnnotation() {
1750 JavaFileObject previousClassFile = currentClassFile;
1751 try {
1752 currentClassFile = classFile;
1753 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1754 } finally {
1755 currentClassFile = previousClassFile;
1756 }
1757 }
1758 }
1760 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1761 final Symbol sym;
1762 final List<CompoundAnnotationProxy> l;
1763 final JavaFileObject classFile;
1764 @Override
1765 public String toString() {
1766 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1767 }
1768 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1769 this.sym = sym;
1770 this.l = l;
1771 this.classFile = currentClassFile;
1772 }
1773 // implement Annotate.Annotator.enterAnnotation()
1774 public void enterAnnotation() {
1775 JavaFileObject previousClassFile = currentClassFile;
1776 try {
1777 currentClassFile = classFile;
1778 List<Attribute.Compound> newList = deproxyCompoundList(l);
1779 sym.attributes_field = ((sym.attributes_field == null)
1780 ? newList
1781 : newList.prependList(sym.attributes_field));
1782 } finally {
1783 currentClassFile = previousClassFile;
1784 }
1785 }
1786 }
1788 class TypeAnnotationCompleter extends AnnotationCompleter {
1790 List<TypeAnnotationProxy> proxies;
1792 TypeAnnotationCompleter(Symbol sym,
1793 List<TypeAnnotationProxy> proxies) {
1794 super(sym, List.<CompoundAnnotationProxy>nil());
1795 this.proxies = proxies;
1796 }
1798 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
1799 ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
1800 for (TypeAnnotationProxy proxy: proxies) {
1801 Attribute.Compound compound = deproxyCompound(proxy.compound);
1802 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
1803 buf.add(typeCompound);
1804 }
1805 return buf.toList();
1806 }
1808 @Override
1809 public void enterAnnotation() {
1810 JavaFileObject previousClassFile = currentClassFile;
1811 try {
1812 currentClassFile = classFile;
1813 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
1814 if (debugJSR308)
1815 System.out.println("TA: reading: adding " + newList
1816 + " to symbol " + sym + " in " + log.currentSourceFile());
1817 sym.typeAnnotations = ((sym.typeAnnotations == null)
1818 ? newList
1819 : newList.prependList(sym.typeAnnotations));
1821 } finally {
1822 currentClassFile = previousClassFile;
1823 }
1824 }
1825 }
1828 /************************************************************************
1829 * Reading Symbols
1830 ***********************************************************************/
1832 /** Read a field.
1833 */
1834 VarSymbol readField() {
1835 long flags = adjustFieldFlags(nextChar());
1836 Name name = readName(nextChar());
1837 Type type = readType(nextChar());
1838 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1839 readMemberAttrs(v);
1840 return v;
1841 }
1843 /** Read a method.
1844 */
1845 MethodSymbol readMethod() {
1846 long flags = adjustMethodFlags(nextChar());
1847 Name name = readName(nextChar());
1848 Type type = readType(nextChar());
1849 if (name == names.init && currentOwner.hasOuterInstance()) {
1850 // Sometimes anonymous classes don't have an outer
1851 // instance, however, there is no reliable way to tell so
1852 // we never strip this$n
1853 if (!currentOwner.name.isEmpty())
1854 type = new MethodType(type.getParameterTypes().tail,
1855 type.getReturnType(),
1856 type.getThrownTypes(),
1857 syms.methodClass);
1858 }
1859 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1860 if (saveParameterNames)
1861 initParameterNames(m);
1862 Symbol prevOwner = currentOwner;
1863 currentOwner = m;
1864 try {
1865 readMemberAttrs(m);
1866 } finally {
1867 currentOwner = prevOwner;
1868 }
1869 if (saveParameterNames)
1870 setParameterNames(m, type);
1871 return m;
1872 }
1874 /**
1875 * Init the parameter names array.
1876 * Parameter names are currently inferred from the names in the
1877 * LocalVariableTable attributes of a Code attribute.
1878 * (Note: this means parameter names are currently not available for
1879 * methods without a Code attribute.)
1880 * This method initializes an array in which to store the name indexes
1881 * of parameter names found in LocalVariableTable attributes. It is
1882 * slightly supersized to allow for additional slots with a start_pc of 0.
1883 */
1884 void initParameterNames(MethodSymbol sym) {
1885 // make allowance for synthetic parameters.
1886 final int excessSlots = 4;
1887 int expectedParameterSlots =
1888 Code.width(sym.type.getParameterTypes()) + excessSlots;
1889 if (parameterNameIndices == null
1890 || parameterNameIndices.length < expectedParameterSlots) {
1891 parameterNameIndices = new int[expectedParameterSlots];
1892 } else
1893 Arrays.fill(parameterNameIndices, 0);
1894 haveParameterNameIndices = false;
1895 }
1897 /**
1898 * Set the parameter names for a symbol from the name index in the
1899 * parameterNameIndicies array. The type of the symbol may have changed
1900 * while reading the method attributes (see the Signature attribute).
1901 * This may be because of generic information or because anonymous
1902 * synthetic parameters were added. The original type (as read from
1903 * the method descriptor) is used to help guess the existence of
1904 * anonymous synthetic parameters.
1905 * On completion, sym.savedParameter names will either be null (if
1906 * no parameter names were found in the class file) or will be set to a
1907 * list of names, one per entry in sym.type.getParameterTypes, with
1908 * any missing names represented by the empty name.
1909 */
1910 void setParameterNames(MethodSymbol sym, Type jvmType) {
1911 // if no names were found in the class file, there's nothing more to do
1912 if (!haveParameterNameIndices)
1913 return;
1915 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1916 // the code in readMethod may have skipped the first parameter when
1917 // setting up the MethodType. If so, we make a corresponding allowance
1918 // here for the position of the first parameter. Note that this
1919 // assumes the skipped parameter has a width of 1 -- i.e. it is not
1920 // a double width type (long or double.)
1921 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1922 // Sometimes anonymous classes don't have an outer
1923 // instance, however, there is no reliable way to tell so
1924 // we never strip this$n
1925 if (!currentOwner.name.isEmpty())
1926 firstParam += 1;
1927 }
1929 if (sym.type != jvmType) {
1930 // reading the method attributes has caused the symbol's type to
1931 // be changed. (i.e. the Signature attribute.) This may happen if
1932 // there are hidden (synthetic) parameters in the descriptor, but
1933 // not in the Signature. The position of these hidden parameters
1934 // is unspecified; for now, assume they are at the beginning, and
1935 // so skip over them. The primary case for this is two hidden
1936 // parameters passed into Enum constructors.
1937 int skip = Code.width(jvmType.getParameterTypes())
1938 - Code.width(sym.type.getParameterTypes());
1939 firstParam += skip;
1940 }
1941 List<Name> paramNames = List.nil();
1942 int index = firstParam;
1943 for (Type t: sym.type.getParameterTypes()) {
1944 int nameIdx = (index < parameterNameIndices.length
1945 ? parameterNameIndices[index] : 0);
1946 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
1947 paramNames = paramNames.prepend(name);
1948 index += Code.width(t);
1949 }
1950 sym.savedParameterNames = paramNames.reverse();
1951 }
1953 /** Skip a field or method
1954 */
1955 void skipMember() {
1956 bp = bp + 6;
1957 char ac = nextChar();
1958 for (int i = 0; i < ac; i++) {
1959 bp = bp + 2;
1960 int attrLen = nextInt();
1961 bp = bp + attrLen;
1962 }
1963 }
1965 /** Enter type variables of this classtype and all enclosing ones in
1966 * `typevars'.
1967 */
1968 protected void enterTypevars(Type t) {
1969 if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
1970 enterTypevars(t.getEnclosingType());
1971 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1972 typevars.enter(xs.head.tsym);
1973 }
1975 protected void enterTypevars(Symbol sym) {
1976 if (sym.owner.kind == MTH) {
1977 enterTypevars(sym.owner);
1978 enterTypevars(sym.owner.owner);
1979 }
1980 enterTypevars(sym.type);
1981 }
1983 /** Read contents of a given class symbol `c'. Both external and internal
1984 * versions of an inner class are read.
1985 */
1986 void readClass(ClassSymbol c) {
1987 ClassType ct = (ClassType)c.type;
1989 // allocate scope for members
1990 c.members_field = new Scope(c);
1992 // prepare type variable table
1993 typevars = typevars.dup(currentOwner);
1994 if (ct.getEnclosingType().tag == CLASS)
1995 enterTypevars(ct.getEnclosingType());
1997 // read flags, or skip if this is an inner class
1998 long flags = adjustClassFlags(nextChar());
1999 if (c.owner.kind == PCK) c.flags_field = flags;
2001 // read own class name and check that it matches
2002 ClassSymbol self = readClassSymbol(nextChar());
2003 if (c != self)
2004 throw badClassFile("class.file.wrong.class",
2005 self.flatname);
2007 // class attributes must be read before class
2008 // skip ahead to read class attributes
2009 int startbp = bp;
2010 nextChar();
2011 char interfaceCount = nextChar();
2012 bp += interfaceCount * 2;
2013 char fieldCount = nextChar();
2014 for (int i = 0; i < fieldCount; i++) skipMember();
2015 char methodCount = nextChar();
2016 for (int i = 0; i < methodCount; i++) skipMember();
2017 readClassAttrs(c);
2019 if (readAllOfClassFile) {
2020 for (int i = 1; i < poolObj.length; i++) readPool(i);
2021 c.pool = new Pool(poolObj.length, poolObj);
2022 }
2024 // reset and read rest of classinfo
2025 bp = startbp;
2026 int n = nextChar();
2027 if (ct.supertype_field == null)
2028 ct.supertype_field = (n == 0)
2029 ? Type.noType
2030 : readClassSymbol(n).erasure(types);
2031 n = nextChar();
2032 List<Type> is = List.nil();
2033 for (int i = 0; i < n; i++) {
2034 Type _inter = readClassSymbol(nextChar()).erasure(types);
2035 is = is.prepend(_inter);
2036 }
2037 if (ct.interfaces_field == null)
2038 ct.interfaces_field = is.reverse();
2040 if (fieldCount != nextChar()) assert false;
2041 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2042 if (methodCount != nextChar()) assert false;
2043 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2045 typevars = typevars.leave();
2046 }
2048 /** Read inner class info. For each inner/outer pair allocate a
2049 * member class.
2050 */
2051 void readInnerClasses(ClassSymbol c) {
2052 int n = nextChar();
2053 for (int i = 0; i < n; i++) {
2054 nextChar(); // skip inner class symbol
2055 ClassSymbol outer = readClassSymbol(nextChar());
2056 Name name = readName(nextChar());
2057 if (name == null) name = names.empty;
2058 long flags = adjustClassFlags(nextChar());
2059 if (outer != null) { // we have a member class
2060 if (name == names.empty)
2061 name = names.one;
2062 ClassSymbol member = enterClass(name, outer);
2063 if ((flags & STATIC) == 0) {
2064 ((ClassType)member.type).setEnclosingType(outer.type);
2065 if (member.erasure_field != null)
2066 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2067 }
2068 if (c == outer) {
2069 member.flags_field = flags;
2070 enterMember(c, member);
2071 }
2072 }
2073 }
2074 }
2076 /** Read a class file.
2077 */
2078 private void readClassFile(ClassSymbol c) throws IOException {
2079 int magic = nextInt();
2080 if (magic != JAVA_MAGIC)
2081 throw badClassFile("illegal.start.of.class.file");
2083 minorVersion = nextChar();
2084 majorVersion = nextChar();
2085 int maxMajor = Target.MAX().majorVersion;
2086 int maxMinor = Target.MAX().minorVersion;
2087 if (majorVersion > maxMajor ||
2088 majorVersion * 1000 + minorVersion <
2089 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2090 {
2091 if (majorVersion == (maxMajor + 1))
2092 log.warning("big.major.version",
2093 currentClassFile,
2094 majorVersion,
2095 maxMajor);
2096 else
2097 throw badClassFile("wrong.version",
2098 Integer.toString(majorVersion),
2099 Integer.toString(minorVersion),
2100 Integer.toString(maxMajor),
2101 Integer.toString(maxMinor));
2102 }
2103 else if (checkClassFile &&
2104 majorVersion == maxMajor &&
2105 minorVersion > maxMinor)
2106 {
2107 printCCF("found.later.version",
2108 Integer.toString(minorVersion));
2109 }
2110 indexPool();
2111 if (signatureBuffer.length < bp) {
2112 int ns = Integer.highestOneBit(bp) << 1;
2113 signatureBuffer = new byte[ns];
2114 }
2115 readClass(c);
2116 }
2118 /************************************************************************
2119 * Adjusting flags
2120 ***********************************************************************/
2122 long adjustFieldFlags(long flags) {
2123 return flags;
2124 }
2125 long adjustMethodFlags(long flags) {
2126 if ((flags & ACC_BRIDGE) != 0) {
2127 flags &= ~ACC_BRIDGE;
2128 flags |= BRIDGE;
2129 if (!allowGenerics)
2130 flags &= ~SYNTHETIC;
2131 }
2132 if ((flags & ACC_VARARGS) != 0) {
2133 flags &= ~ACC_VARARGS;
2134 flags |= VARARGS;
2135 }
2136 return flags;
2137 }
2138 long adjustClassFlags(long flags) {
2139 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2140 }
2142 /************************************************************************
2143 * Loading Classes
2144 ***********************************************************************/
2146 /** Define a new class given its name and owner.
2147 */
2148 public ClassSymbol defineClass(Name name, Symbol owner) {
2149 ClassSymbol c = new ClassSymbol(0, name, owner);
2150 if (owner.kind == PCK)
2151 assert classes.get(c.flatname) == null : c;
2152 c.completer = this;
2153 return c;
2154 }
2156 /** Create a new toplevel or member class symbol with given name
2157 * and owner and enter in `classes' unless already there.
2158 */
2159 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2160 Name flatname = TypeSymbol.formFlatName(name, owner);
2161 ClassSymbol c = classes.get(flatname);
2162 if (c == null) {
2163 c = defineClass(name, owner);
2164 classes.put(flatname, c);
2165 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2166 // reassign fields of classes that might have been loaded with
2167 // their flat names.
2168 c.owner.members().remove(c);
2169 c.name = name;
2170 c.owner = owner;
2171 c.fullname = ClassSymbol.formFullName(name, owner);
2172 }
2173 return c;
2174 }
2176 /**
2177 * Creates a new toplevel class symbol with given flat name and
2178 * given class (or source) file.
2179 *
2180 * @param flatName a fully qualified binary class name
2181 * @param classFile the class file or compilation unit defining
2182 * the class (may be {@code null})
2183 * @return a newly created class symbol
2184 * @throws AssertionError if the class symbol already exists
2185 */
2186 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2187 ClassSymbol cs = classes.get(flatName);
2188 if (cs != null) {
2189 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2190 cs.fullname,
2191 cs.completer,
2192 cs.classfile,
2193 cs.sourcefile);
2194 throw new AssertionError(msg);
2195 }
2196 Name packageName = Convert.packagePart(flatName);
2197 PackageSymbol owner = packageName.isEmpty()
2198 ? syms.unnamedPackage
2199 : enterPackage(packageName);
2200 cs = defineClass(Convert.shortName(flatName), owner);
2201 cs.classfile = classFile;
2202 classes.put(flatName, cs);
2203 return cs;
2204 }
2206 /** Create a new member or toplevel class symbol with given flat name
2207 * and enter in `classes' unless already there.
2208 */
2209 public ClassSymbol enterClass(Name flatname) {
2210 ClassSymbol c = classes.get(flatname);
2211 if (c == null)
2212 return enterClass(flatname, (JavaFileObject)null);
2213 else
2214 return c;
2215 }
2217 private boolean suppressFlush = false;
2219 /** Completion for classes to be loaded. Before a class is loaded
2220 * we make sure its enclosing class (if any) is loaded.
2221 */
2222 public void complete(Symbol sym) throws CompletionFailure {
2223 if (sym.kind == TYP) {
2224 ClassSymbol c = (ClassSymbol)sym;
2225 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2226 boolean saveSuppressFlush = suppressFlush;
2227 suppressFlush = true;
2228 try {
2229 completeOwners(c.owner);
2230 completeEnclosing(c);
2231 } finally {
2232 suppressFlush = saveSuppressFlush;
2233 }
2234 fillIn(c);
2235 } else if (sym.kind == PCK) {
2236 PackageSymbol p = (PackageSymbol)sym;
2237 try {
2238 fillIn(p);
2239 } catch (IOException ex) {
2240 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2241 }
2242 }
2243 if (!filling && !suppressFlush)
2244 annotate.flush(); // finish attaching annotations
2245 }
2247 /** complete up through the enclosing package. */
2248 private void completeOwners(Symbol o) {
2249 if (o.kind != PCK) completeOwners(o.owner);
2250 o.complete();
2251 }
2253 /**
2254 * Tries to complete lexically enclosing classes if c looks like a
2255 * nested class. This is similar to completeOwners but handles
2256 * the situation when a nested class is accessed directly as it is
2257 * possible with the Tree API or javax.lang.model.*.
2258 */
2259 private void completeEnclosing(ClassSymbol c) {
2260 if (c.owner.kind == PCK) {
2261 Symbol owner = c.owner;
2262 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2263 Symbol encl = owner.members().lookup(name).sym;
2264 if (encl == null)
2265 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2266 if (encl != null)
2267 encl.complete();
2268 }
2269 }
2270 }
2272 /** We can only read a single class file at a time; this
2273 * flag keeps track of when we are currently reading a class
2274 * file.
2275 */
2276 private boolean filling = false;
2278 /** Fill in definition of class `c' from corresponding class or
2279 * source file.
2280 */
2281 private void fillIn(ClassSymbol c) {
2282 if (completionFailureName == c.fullname) {
2283 throw new CompletionFailure(c, "user-selected completion failure by class name");
2284 }
2285 currentOwner = c;
2286 JavaFileObject classfile = c.classfile;
2287 if (classfile != null) {
2288 JavaFileObject previousClassFile = currentClassFile;
2289 try {
2290 assert !filling :
2291 "Filling " + classfile.toUri() +
2292 " during " + previousClassFile;
2293 currentClassFile = classfile;
2294 if (verbose) {
2295 printVerbose("loading", currentClassFile.toString());
2296 }
2297 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2298 filling = true;
2299 try {
2300 bp = 0;
2301 buf = readInputStream(buf, classfile.openInputStream());
2302 readClassFile(c);
2303 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2304 List<Type> missing = missingTypeVariables;
2305 List<Type> found = foundTypeVariables;
2306 missingTypeVariables = List.nil();
2307 foundTypeVariables = List.nil();
2308 filling = false;
2309 ClassType ct = (ClassType)currentOwner.type;
2310 ct.supertype_field =
2311 types.subst(ct.supertype_field, missing, found);
2312 ct.interfaces_field =
2313 types.subst(ct.interfaces_field, missing, found);
2314 } else if (missingTypeVariables.isEmpty() !=
2315 foundTypeVariables.isEmpty()) {
2316 Name name = missingTypeVariables.head.tsym.name;
2317 throw badClassFile("undecl.type.var", name);
2318 }
2319 } finally {
2320 missingTypeVariables = List.nil();
2321 foundTypeVariables = List.nil();
2322 filling = false;
2323 }
2324 } else {
2325 if (sourceCompleter != null) {
2326 sourceCompleter.complete(c);
2327 } else {
2328 throw new IllegalStateException("Source completer required to read "
2329 + classfile.toUri());
2330 }
2331 }
2332 return;
2333 } catch (IOException ex) {
2334 throw badClassFile("unable.to.access.file", ex.getMessage());
2335 } finally {
2336 currentClassFile = previousClassFile;
2337 }
2338 } else {
2339 JCDiagnostic diag =
2340 diagFactory.fragment("class.file.not.found", c.flatname);
2341 throw
2342 newCompletionFailure(c, diag);
2343 }
2344 }
2345 // where
2346 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2347 try {
2348 buf = ensureCapacity(buf, s.available());
2349 int r = s.read(buf);
2350 int bp = 0;
2351 while (r != -1) {
2352 bp += r;
2353 buf = ensureCapacity(buf, bp);
2354 r = s.read(buf, bp, buf.length - bp);
2355 }
2356 return buf;
2357 } finally {
2358 try {
2359 s.close();
2360 } catch (IOException e) {
2361 /* Ignore any errors, as this stream may have already
2362 * thrown a related exception which is the one that
2363 * should be reported.
2364 */
2365 }
2366 }
2367 }
2368 private static byte[] ensureCapacity(byte[] buf, int needed) {
2369 if (buf.length < needed) {
2370 byte[] old = buf;
2371 buf = new byte[Integer.highestOneBit(needed) << 1];
2372 System.arraycopy(old, 0, buf, 0, old.length);
2373 }
2374 return buf;
2375 }
2376 /** Static factory for CompletionFailure objects.
2377 * In practice, only one can be used at a time, so we share one
2378 * to reduce the expense of allocating new exception objects.
2379 */
2380 private CompletionFailure newCompletionFailure(TypeSymbol c,
2381 JCDiagnostic diag) {
2382 if (!cacheCompletionFailure) {
2383 // log.warning("proc.messager",
2384 // Log.getLocalizedString("class.file.not.found", c.flatname));
2385 // c.debug.printStackTrace();
2386 return new CompletionFailure(c, diag);
2387 } else {
2388 CompletionFailure result = cachedCompletionFailure;
2389 result.sym = c;
2390 result.diag = diag;
2391 return result;
2392 }
2393 }
2394 private CompletionFailure cachedCompletionFailure =
2395 new CompletionFailure(null, (JCDiagnostic) null);
2396 {
2397 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2398 }
2400 /** Load a toplevel class with given fully qualified name
2401 * The class is entered into `classes' only if load was successful.
2402 */
2403 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2404 boolean absent = classes.get(flatname) == null;
2405 ClassSymbol c = enterClass(flatname);
2406 if (c.members_field == null && c.completer != null) {
2407 try {
2408 c.complete();
2409 } catch (CompletionFailure ex) {
2410 if (absent) classes.remove(flatname);
2411 throw ex;
2412 }
2413 }
2414 return c;
2415 }
2417 /************************************************************************
2418 * Loading Packages
2419 ***********************************************************************/
2421 /** Check to see if a package exists, given its fully qualified name.
2422 */
2423 public boolean packageExists(Name fullname) {
2424 return enterPackage(fullname).exists();
2425 }
2427 /** Make a package, given its fully qualified name.
2428 */
2429 public PackageSymbol enterPackage(Name fullname) {
2430 PackageSymbol p = packages.get(fullname);
2431 if (p == null) {
2432 assert !fullname.isEmpty() : "rootPackage missing!";
2433 p = new PackageSymbol(
2434 Convert.shortName(fullname),
2435 enterPackage(Convert.packagePart(fullname)));
2436 p.completer = this;
2437 packages.put(fullname, p);
2438 }
2439 return p;
2440 }
2442 /** Make a package, given its unqualified name and enclosing package.
2443 */
2444 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2445 return enterPackage(TypeSymbol.formFullName(name, owner));
2446 }
2448 /** Include class corresponding to given class file in package,
2449 * unless (1) we already have one the same kind (.class or .java), or
2450 * (2) we have one of the other kind, and the given class file
2451 * is older.
2452 */
2453 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2454 if ((p.flags_field & EXISTS) == 0)
2455 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2456 q.flags_field |= EXISTS;
2457 JavaFileObject.Kind kind = file.getKind();
2458 int seen;
2459 if (kind == JavaFileObject.Kind.CLASS)
2460 seen = CLASS_SEEN;
2461 else
2462 seen = SOURCE_SEEN;
2463 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2464 int lastDot = binaryName.lastIndexOf(".");
2465 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2466 boolean isPkgInfo = classname == names.package_info;
2467 ClassSymbol c = isPkgInfo
2468 ? p.package_info
2469 : (ClassSymbol) p.members_field.lookup(classname).sym;
2470 if (c == null) {
2471 c = enterClass(classname, p);
2472 if (c.classfile == null) // only update the file if's it's newly created
2473 c.classfile = file;
2474 if (isPkgInfo) {
2475 p.package_info = c;
2476 } else {
2477 if (c.owner == p) // it might be an inner class
2478 p.members_field.enter(c);
2479 }
2480 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2481 // if c.classfile == null, we are currently compiling this class
2482 // and no further action is necessary.
2483 // if (c.flags_field & seen) != 0, we have already encountered
2484 // a file of the same kind; again no further action is necessary.
2485 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2486 c.classfile = preferredFileObject(file, c.classfile);
2487 }
2488 c.flags_field |= seen;
2489 }
2491 /** Implement policy to choose to derive information from a source
2492 * file or a class file when both are present. May be overridden
2493 * by subclasses.
2494 */
2495 protected JavaFileObject preferredFileObject(JavaFileObject a,
2496 JavaFileObject b) {
2498 if (preferSource)
2499 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2500 else {
2501 long adate = a.getLastModified();
2502 long bdate = b.getLastModified();
2503 // 6449326: policy for bad lastModifiedTime in ClassReader
2504 //assert adate >= 0 && bdate >= 0;
2505 return (adate > bdate) ? a : b;
2506 }
2507 }
2509 /**
2510 * specifies types of files to be read when filling in a package symbol
2511 */
2512 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2513 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2514 }
2516 /**
2517 * this is used to support javadoc
2518 */
2519 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2520 }
2522 protected Location currentLoc; // FIXME
2524 private boolean verbosePath = true;
2526 /** Load directory of package into members scope.
2527 */
2528 private void fillIn(PackageSymbol p) throws IOException {
2529 if (p.members_field == null) p.members_field = new Scope(p);
2530 String packageName = p.fullname.toString();
2532 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2534 fillIn(p, PLATFORM_CLASS_PATH,
2535 fileManager.list(PLATFORM_CLASS_PATH,
2536 packageName,
2537 EnumSet.of(JavaFileObject.Kind.CLASS),
2538 false));
2540 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2541 classKinds.remove(JavaFileObject.Kind.SOURCE);
2542 boolean wantClassFiles = !classKinds.isEmpty();
2544 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2545 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2546 boolean wantSourceFiles = !sourceKinds.isEmpty();
2548 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2550 if (verbose && verbosePath) {
2551 if (fileManager instanceof StandardJavaFileManager) {
2552 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2553 if (haveSourcePath && wantSourceFiles) {
2554 List<File> path = List.nil();
2555 for (File file : fm.getLocation(SOURCE_PATH)) {
2556 path = path.prepend(file);
2557 }
2558 printVerbose("sourcepath", path.reverse().toString());
2559 } else if (wantSourceFiles) {
2560 List<File> path = List.nil();
2561 for (File file : fm.getLocation(CLASS_PATH)) {
2562 path = path.prepend(file);
2563 }
2564 printVerbose("sourcepath", path.reverse().toString());
2565 }
2566 if (wantClassFiles) {
2567 List<File> path = List.nil();
2568 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2569 path = path.prepend(file);
2570 }
2571 for (File file : fm.getLocation(CLASS_PATH)) {
2572 path = path.prepend(file);
2573 }
2574 printVerbose("classpath", path.reverse().toString());
2575 }
2576 }
2577 }
2579 if (wantSourceFiles && !haveSourcePath) {
2580 fillIn(p, CLASS_PATH,
2581 fileManager.list(CLASS_PATH,
2582 packageName,
2583 kinds,
2584 false));
2585 } else {
2586 if (wantClassFiles)
2587 fillIn(p, CLASS_PATH,
2588 fileManager.list(CLASS_PATH,
2589 packageName,
2590 classKinds,
2591 false));
2592 if (wantSourceFiles)
2593 fillIn(p, SOURCE_PATH,
2594 fileManager.list(SOURCE_PATH,
2595 packageName,
2596 sourceKinds,
2597 false));
2598 }
2599 verbosePath = false;
2600 }
2601 // where
2602 private void fillIn(PackageSymbol p,
2603 Location location,
2604 Iterable<JavaFileObject> files)
2605 {
2606 currentLoc = location;
2607 for (JavaFileObject fo : files) {
2608 switch (fo.getKind()) {
2609 case CLASS:
2610 case SOURCE: {
2611 // TODO pass binaryName to includeClassFile
2612 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2613 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2614 if (SourceVersion.isIdentifier(simpleName) ||
2615 fo.getKind() == JavaFileObject.Kind.CLASS ||
2616 simpleName.equals("package-info"))
2617 includeClassFile(p, fo);
2618 break;
2619 }
2620 default:
2621 extraFileActions(p, fo);
2622 }
2623 }
2624 }
2626 /** Output for "-verbose" option.
2627 * @param key The key to look up the correct internationalized string.
2628 * @param arg An argument for substitution into the output string.
2629 */
2630 private void printVerbose(String key, CharSequence arg) {
2631 Log.printLines(log.noticeWriter, Log.getLocalizedString("verbose." + key, arg));
2632 }
2634 /** Output for "-checkclassfile" option.
2635 * @param key The key to look up the correct internationalized string.
2636 * @param arg An argument for substitution into the output string.
2637 */
2638 private void printCCF(String key, Object arg) {
2639 Log.printLines(log.noticeWriter, Log.getLocalizedString(key, arg));
2640 }
2643 public interface SourceCompleter {
2644 void complete(ClassSymbol sym)
2645 throws CompletionFailure;
2646 }
2648 /**
2649 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2650 * The attribute is only the last component of the original filename, so is unlikely
2651 * to be valid as is, so operations other than those to access the name throw
2652 * UnsupportedOperationException
2653 */
2654 private static class SourceFileObject extends BaseFileObject {
2656 /** The file's name.
2657 */
2658 private Name name;
2659 private Name flatname;
2661 public SourceFileObject(Name name, Name flatname) {
2662 super(null); // no file manager; never referenced for this file object
2663 this.name = name;
2664 this.flatname = flatname;
2665 }
2667 @Override
2668 public URI toUri() {
2669 try {
2670 return new URI(null, name.toString(), null);
2671 } catch (URISyntaxException e) {
2672 throw new CannotCreateUriError(name.toString(), e);
2673 }
2674 }
2676 @Override
2677 public String getName() {
2678 return name.toString();
2679 }
2681 @Override
2682 public String getShortName() {
2683 return getName();
2684 }
2686 @Override
2687 public JavaFileObject.Kind getKind() {
2688 return getKind(getName());
2689 }
2691 @Override
2692 public InputStream openInputStream() {
2693 throw new UnsupportedOperationException();
2694 }
2696 @Override
2697 public OutputStream openOutputStream() {
2698 throw new UnsupportedOperationException();
2699 }
2701 @Override
2702 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2703 throw new UnsupportedOperationException();
2704 }
2706 @Override
2707 public Reader openReader(boolean ignoreEncodingErrors) {
2708 throw new UnsupportedOperationException();
2709 }
2711 @Override
2712 public Writer openWriter() {
2713 throw new UnsupportedOperationException();
2714 }
2716 @Override
2717 public long getLastModified() {
2718 throw new UnsupportedOperationException();
2719 }
2721 @Override
2722 public boolean delete() {
2723 throw new UnsupportedOperationException();
2724 }
2726 @Override
2727 protected String inferBinaryName(Iterable<? extends File> path) {
2728 return flatname.toString();
2729 }
2731 @Override
2732 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2733 return true; // fail-safe mode
2734 }
2736 /**
2737 * Check if two file objects are equal.
2738 * SourceFileObjects are just placeholder objects for the value of a
2739 * SourceFile attribute, and do not directly represent specific files.
2740 * Two SourceFileObjects are equal if their names are equal.
2741 */
2742 @Override
2743 public boolean equals(Object other) {
2744 if (this == other)
2745 return true;
2747 if (!(other instanceof SourceFileObject))
2748 return false;
2750 SourceFileObject o = (SourceFileObject) other;
2751 return name.equals(o.name);
2752 }
2754 @Override
2755 public int hashCode() {
2756 return name.hashCode();
2757 }
2758 }
2759 }