Wed, 18 Jun 2008 07:23:25 -0700
6714365: refactor JavacFileManager to move nested classes to top level
Reviewed-by: mcimadamore
1 /*
2 * Copyright 1999-2006 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.jvm;
28 import java.io.*;
29 import java.net.URI;
30 import java.nio.CharBuffer;
31 import java.util.EnumSet;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.Set;
35 import javax.lang.model.SourceVersion;
36 import javax.tools.JavaFileObject;
37 import javax.tools.JavaFileManager;
38 import javax.tools.StandardJavaFileManager;
40 import com.sun.tools.javac.comp.Annotate;
41 import com.sun.tools.javac.code.*;
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.code.Symbol.*;
44 import com.sun.tools.javac.code.Symtab;
45 import com.sun.tools.javac.file.BaseFileObject;
46 import com.sun.tools.javac.util.*;
47 import com.sun.tools.javac.util.List;
49 import static com.sun.tools.javac.code.Flags.*;
50 import static com.sun.tools.javac.code.Kinds.*;
51 import static com.sun.tools.javac.code.TypeTags.*;
52 import com.sun.tools.javac.jvm.ClassFile.NameAndType;
53 import javax.tools.JavaFileManager.Location;
54 import static javax.tools.StandardLocation.*;
56 /** This class provides operations to read a classfile into an internal
57 * representation. The internal representation is anchored in a
58 * ClassSymbol which contains in its scope symbol representations
59 * for all other definitions in the classfile. Top-level Classes themselves
60 * appear as members of the scopes of PackageSymbols.
61 *
62 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
63 * you write code that depends on this, you do so at your own risk.
64 * This code and its internal interfaces are subject to change or
65 * deletion without notice.</b>
66 */
67 public class ClassReader extends ClassFile implements Completer {
68 /** The context key for the class reader. */
69 protected static final Context.Key<ClassReader> classReaderKey =
70 new Context.Key<ClassReader>();
72 Annotate annotate;
74 /** Switch: verbose output.
75 */
76 boolean verbose;
78 /** Switch: check class file for correct minor version, unrecognized
79 * attributes.
80 */
81 boolean checkClassFile;
83 /** Switch: read constant pool and code sections. This switch is initially
84 * set to false but can be turned on from outside.
85 */
86 public boolean readAllOfClassFile = false;
88 /** Switch: read GJ signature information.
89 */
90 boolean allowGenerics;
92 /** Switch: read varargs attribute.
93 */
94 boolean allowVarargs;
96 /** Switch: allow annotations.
97 */
98 boolean allowAnnotations;
100 /** Switch: preserve parameter names from the variable table.
101 */
102 public boolean saveParameterNames;
104 /**
105 * Switch: cache completion failures unless -XDdev is used
106 */
107 private boolean cacheCompletionFailure;
109 /**
110 * Switch: prefer source files instead of newer when both source
111 * and class are available
112 **/
113 public boolean preferSource;
115 /** The log to use for verbose output
116 */
117 final Log log;
119 /** The symbol table. */
120 Symtab syms;
122 Types types;
124 /** The name table. */
125 final Name.Table names;
127 /** Force a completion failure on this name
128 */
129 final Name completionFailureName;
131 /** Access to files
132 */
133 private final JavaFileManager fileManager;
135 /** Factory for diagnostics
136 */
137 JCDiagnostic.Factory diagFactory;
139 /** Can be reassigned from outside:
140 * the completer to be used for ".java" files. If this remains unassigned
141 * ".java" files will not be loaded.
142 */
143 public SourceCompleter sourceCompleter = null;
145 /** A hashtable containing the encountered top-level and member classes,
146 * indexed by flat names. The table does not contain local classes.
147 */
148 private Map<Name,ClassSymbol> classes;
150 /** A hashtable containing the encountered packages.
151 */
152 private Map<Name, PackageSymbol> packages;
154 /** The current scope where type variables are entered.
155 */
156 protected Scope typevars;
158 /** The path name of the class file currently being read.
159 */
160 protected JavaFileObject currentClassFile = null;
162 /** The class or method currently being read.
163 */
164 protected Symbol currentOwner = null;
166 /** The buffer containing the currently read class file.
167 */
168 byte[] buf = new byte[0x0fff0];
170 /** The current input pointer.
171 */
172 int bp;
174 /** The objects of the constant pool.
175 */
176 Object[] poolObj;
178 /** For every constant pool entry, an index into buf where the
179 * defining section of the entry is found.
180 */
181 int[] poolIdx;
183 /** Get the ClassReader instance for this invocation. */
184 public static ClassReader instance(Context context) {
185 ClassReader instance = context.get(classReaderKey);
186 if (instance == null)
187 instance = new ClassReader(context, true);
188 return instance;
189 }
191 /** Initialize classes and packages, treating this as the definitive classreader. */
192 public void init(Symtab syms) {
193 init(syms, true);
194 }
196 /** Initialize classes and packages, optionally treating this as
197 * the definitive classreader.
198 */
199 private void init(Symtab syms, boolean definitive) {
200 if (classes != null) return;
202 if (definitive) {
203 assert packages == null || packages == syms.packages;
204 packages = syms.packages;
205 assert classes == null || classes == syms.classes;
206 classes = syms.classes;
207 } else {
208 packages = new HashMap<Name, PackageSymbol>();
209 classes = new HashMap<Name, ClassSymbol>();
210 }
212 packages.put(names.empty, syms.rootPackage);
213 syms.rootPackage.completer = this;
214 syms.unnamedPackage.completer = this;
215 }
217 /** Construct a new class reader, optionally treated as the
218 * definitive classreader for this invocation.
219 */
220 protected ClassReader(Context context, boolean definitive) {
221 if (definitive) context.put(classReaderKey, this);
223 names = Name.Table.instance(context);
224 syms = Symtab.instance(context);
225 types = Types.instance(context);
226 fileManager = context.get(JavaFileManager.class);
227 if (fileManager == null)
228 throw new AssertionError("FileManager initialization error");
229 diagFactory = JCDiagnostic.Factory.instance(context);
231 init(syms, definitive);
232 log = Log.instance(context);
234 Options options = Options.instance(context);
235 annotate = Annotate.instance(context);
236 verbose = options.get("-verbose") != null;
237 checkClassFile = options.get("-checkclassfile") != null;
238 Source source = Source.instance(context);
239 allowGenerics = source.allowGenerics();
240 allowVarargs = source.allowVarargs();
241 allowAnnotations = source.allowAnnotations();
242 saveParameterNames = options.get("save-parameter-names") != null;
243 cacheCompletionFailure = options.get("dev") == null;
244 preferSource = "source".equals(options.get("-Xprefer"));
246 completionFailureName =
247 (options.get("failcomplete") != null)
248 ? names.fromString(options.get("failcomplete"))
249 : null;
251 typevars = new Scope(syms.noSymbol);
252 }
254 /** Add member to class unless it is synthetic.
255 */
256 private void enterMember(ClassSymbol c, Symbol sym) {
257 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
258 c.members_field.enter(sym);
259 }
261 /************************************************************************
262 * Error Diagnoses
263 ***********************************************************************/
266 public class BadClassFile extends CompletionFailure {
267 private static final long serialVersionUID = 0;
269 public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
270 super(sym, createBadClassFileDiagnostic(file, diag));
271 }
272 }
273 // where
274 private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
275 String key = (file.getKind() == JavaFileObject.Kind.SOURCE
276 ? "bad.source.file.header" : "bad.class.file.header");
277 return diagFactory.fragment(key, file, diag);
278 }
280 public BadClassFile badClassFile(String key, Object... args) {
281 return new BadClassFile (
282 currentOwner.enclClass(),
283 currentClassFile,
284 diagFactory.fragment(key, args));
285 }
287 /************************************************************************
288 * Buffer Access
289 ***********************************************************************/
291 /** Read a character.
292 */
293 char nextChar() {
294 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
295 }
297 /** Read an integer.
298 */
299 int nextInt() {
300 return
301 ((buf[bp++] & 0xFF) << 24) +
302 ((buf[bp++] & 0xFF) << 16) +
303 ((buf[bp++] & 0xFF) << 8) +
304 (buf[bp++] & 0xFF);
305 }
307 /** Extract a character at position bp from buf.
308 */
309 char getChar(int bp) {
310 return
311 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
312 }
314 /** Extract an integer at position bp from buf.
315 */
316 int getInt(int bp) {
317 return
318 ((buf[bp] & 0xFF) << 24) +
319 ((buf[bp+1] & 0xFF) << 16) +
320 ((buf[bp+2] & 0xFF) << 8) +
321 (buf[bp+3] & 0xFF);
322 }
325 /** Extract a long integer at position bp from buf.
326 */
327 long getLong(int bp) {
328 DataInputStream bufin =
329 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
330 try {
331 return bufin.readLong();
332 } catch (IOException e) {
333 throw new AssertionError(e);
334 }
335 }
337 /** Extract a float at position bp from buf.
338 */
339 float getFloat(int bp) {
340 DataInputStream bufin =
341 new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
342 try {
343 return bufin.readFloat();
344 } catch (IOException e) {
345 throw new AssertionError(e);
346 }
347 }
349 /** Extract a double at position bp from buf.
350 */
351 double getDouble(int bp) {
352 DataInputStream bufin =
353 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
354 try {
355 return bufin.readDouble();
356 } catch (IOException e) {
357 throw new AssertionError(e);
358 }
359 }
361 /************************************************************************
362 * Constant Pool Access
363 ***********************************************************************/
365 /** Index all constant pool entries, writing their start addresses into
366 * poolIdx.
367 */
368 void indexPool() {
369 poolIdx = new int[nextChar()];
370 poolObj = new Object[poolIdx.length];
371 int i = 1;
372 while (i < poolIdx.length) {
373 poolIdx[i++] = bp;
374 byte tag = buf[bp++];
375 switch (tag) {
376 case CONSTANT_Utf8: case CONSTANT_Unicode: {
377 int len = nextChar();
378 bp = bp + len;
379 break;
380 }
381 case CONSTANT_Class:
382 case CONSTANT_String:
383 bp = bp + 2;
384 break;
385 case CONSTANT_Fieldref:
386 case CONSTANT_Methodref:
387 case CONSTANT_InterfaceMethodref:
388 case CONSTANT_NameandType:
389 case CONSTANT_Integer:
390 case CONSTANT_Float:
391 bp = bp + 4;
392 break;
393 case CONSTANT_Long:
394 case CONSTANT_Double:
395 bp = bp + 8;
396 i++;
397 break;
398 default:
399 throw badClassFile("bad.const.pool.tag.at",
400 Byte.toString(tag),
401 Integer.toString(bp -1));
402 }
403 }
404 }
406 /** Read constant pool entry at start address i, use pool as a cache.
407 */
408 Object readPool(int i) {
409 Object result = poolObj[i];
410 if (result != null) return result;
412 int index = poolIdx[i];
413 if (index == 0) return null;
415 byte tag = buf[index];
416 switch (tag) {
417 case CONSTANT_Utf8:
418 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
419 break;
420 case CONSTANT_Unicode:
421 throw badClassFile("unicode.str.not.supported");
422 case CONSTANT_Class:
423 poolObj[i] = readClassOrType(getChar(index + 1));
424 break;
425 case CONSTANT_String:
426 // FIXME: (footprint) do not use toString here
427 poolObj[i] = readName(getChar(index + 1)).toString();
428 break;
429 case CONSTANT_Fieldref: {
430 ClassSymbol owner = readClassSymbol(getChar(index + 1));
431 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
432 poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
433 break;
434 }
435 case CONSTANT_Methodref:
436 case CONSTANT_InterfaceMethodref: {
437 ClassSymbol owner = readClassSymbol(getChar(index + 1));
438 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
439 poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
440 break;
441 }
442 case CONSTANT_NameandType:
443 poolObj[i] = new NameAndType(
444 readName(getChar(index + 1)),
445 readType(getChar(index + 3)));
446 break;
447 case CONSTANT_Integer:
448 poolObj[i] = getInt(index + 1);
449 break;
450 case CONSTANT_Float:
451 poolObj[i] = new Float(getFloat(index + 1));
452 break;
453 case CONSTANT_Long:
454 poolObj[i] = new Long(getLong(index + 1));
455 break;
456 case CONSTANT_Double:
457 poolObj[i] = new Double(getDouble(index + 1));
458 break;
459 default:
460 throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
461 }
462 return poolObj[i];
463 }
465 /** Read signature and convert to type.
466 */
467 Type readType(int i) {
468 int index = poolIdx[i];
469 return sigToType(buf, index + 3, getChar(index + 1));
470 }
472 /** If name is an array type or class signature, return the
473 * corresponding type; otherwise return a ClassSymbol with given name.
474 */
475 Object readClassOrType(int i) {
476 int index = poolIdx[i];
477 int len = getChar(index + 1);
478 int start = index + 3;
479 assert buf[start] == '[' || buf[start + len - 1] != ';';
480 // by the above assertion, the following test can be
481 // simplified to (buf[start] == '[')
482 return (buf[start] == '[' || buf[start + len - 1] == ';')
483 ? (Object)sigToType(buf, start, len)
484 : (Object)enterClass(names.fromUtf(internalize(buf, start,
485 len)));
486 }
488 /** Read signature and convert to type parameters.
489 */
490 List<Type> readTypeParams(int i) {
491 int index = poolIdx[i];
492 return sigToTypeParams(buf, index + 3, getChar(index + 1));
493 }
495 /** Read class entry.
496 */
497 ClassSymbol readClassSymbol(int i) {
498 return (ClassSymbol) (readPool(i));
499 }
501 /** Read name.
502 */
503 Name readName(int i) {
504 return (Name) (readPool(i));
505 }
507 /************************************************************************
508 * Reading Types
509 ***********************************************************************/
511 /** The unread portion of the currently read type is
512 * signature[sigp..siglimit-1].
513 */
514 byte[] signature;
515 int sigp;
516 int siglimit;
517 boolean sigEnterPhase = false;
519 /** Convert signature to type, where signature is a name.
520 */
521 Type sigToType(Name sig) {
522 return sig == null
523 ? null
524 : sigToType(sig.table.names, sig.index, sig.len);
525 }
527 /** Convert signature to type, where signature is a byte array segment.
528 */
529 Type sigToType(byte[] sig, int offset, int len) {
530 signature = sig;
531 sigp = offset;
532 siglimit = offset + len;
533 return sigToType();
534 }
536 /** Convert signature to type, where signature is implicit.
537 */
538 Type sigToType() {
539 switch ((char) signature[sigp]) {
540 case 'T':
541 sigp++;
542 int start = sigp;
543 while (signature[sigp] != ';') sigp++;
544 sigp++;
545 return sigEnterPhase
546 ? Type.noType
547 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
548 case '+': {
549 sigp++;
550 Type t = sigToType();
551 return new WildcardType(t, BoundKind.EXTENDS,
552 syms.boundClass);
553 }
554 case '*':
555 sigp++;
556 return new WildcardType(syms.objectType, BoundKind.UNBOUND,
557 syms.boundClass);
558 case '-': {
559 sigp++;
560 Type t = sigToType();
561 return new WildcardType(t, BoundKind.SUPER,
562 syms.boundClass);
563 }
564 case 'B':
565 sigp++;
566 return syms.byteType;
567 case 'C':
568 sigp++;
569 return syms.charType;
570 case 'D':
571 sigp++;
572 return syms.doubleType;
573 case 'F':
574 sigp++;
575 return syms.floatType;
576 case 'I':
577 sigp++;
578 return syms.intType;
579 case 'J':
580 sigp++;
581 return syms.longType;
582 case 'L':
583 {
584 // int oldsigp = sigp;
585 Type t = classSigToType();
586 if (sigp < siglimit && signature[sigp] == '.')
587 throw badClassFile("deprecated inner class signature syntax " +
588 "(please recompile from source)");
589 /*
590 System.err.println(" decoded " +
591 new String(signature, oldsigp, sigp-oldsigp) +
592 " => " + t + " outer " + t.outer());
593 */
594 return t;
595 }
596 case 'S':
597 sigp++;
598 return syms.shortType;
599 case 'V':
600 sigp++;
601 return syms.voidType;
602 case 'Z':
603 sigp++;
604 return syms.booleanType;
605 case '[':
606 sigp++;
607 return new ArrayType(sigToType(), syms.arrayClass);
608 case '(':
609 sigp++;
610 List<Type> argtypes = sigToTypes(')');
611 Type restype = sigToType();
612 List<Type> thrown = List.nil();
613 while (signature[sigp] == '^') {
614 sigp++;
615 thrown = thrown.prepend(sigToType());
616 }
617 return new MethodType(argtypes,
618 restype,
619 thrown.reverse(),
620 syms.methodClass);
621 case '<':
622 typevars = typevars.dup(currentOwner);
623 Type poly = new ForAll(sigToTypeParams(), sigToType());
624 typevars = typevars.leave();
625 return poly;
626 default:
627 throw badClassFile("bad.signature",
628 Convert.utf2string(signature, sigp, 10));
629 }
630 }
632 byte[] signatureBuffer = new byte[0];
633 int sbp = 0;
634 /** Convert class signature to type, where signature is implicit.
635 */
636 Type classSigToType() {
637 if (signature[sigp] != 'L')
638 throw badClassFile("bad.class.signature",
639 Convert.utf2string(signature, sigp, 10));
640 sigp++;
641 Type outer = Type.noType;
642 int startSbp = sbp;
644 while (true) {
645 final byte c = signature[sigp++];
646 switch (c) {
648 case ';': { // end
649 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
650 startSbp,
651 sbp - startSbp));
652 if (outer == Type.noType)
653 outer = t.erasure(types);
654 else
655 outer = new ClassType(outer, List.<Type>nil(), t);
656 sbp = startSbp;
657 return outer;
658 }
660 case '<': // generic arguments
661 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
662 startSbp,
663 sbp - startSbp));
664 outer = new ClassType(outer, sigToTypes('>'), t) {
665 boolean completed = false;
666 public Type getEnclosingType() {
667 if (!completed) {
668 completed = true;
669 tsym.complete();
670 Type enclosingType = tsym.type.getEnclosingType();
671 if (enclosingType != Type.noType) {
672 List<Type> typeArgs =
673 super.getEnclosingType().allparams();
674 List<Type> typeParams =
675 enclosingType.allparams();
676 if (typeParams.length() != typeArgs.length()) {
677 // no "rare" types
678 super.setEnclosingType(types.erasure(enclosingType));
679 } else {
680 super.setEnclosingType(types.subst(enclosingType,
681 typeParams,
682 typeArgs));
683 }
684 } else {
685 super.setEnclosingType(Type.noType);
686 }
687 }
688 return super.getEnclosingType();
689 }
690 public void setEnclosingType(Type outer) {
691 throw new UnsupportedOperationException();
692 }
693 };
694 switch (signature[sigp++]) {
695 case ';':
696 if (sigp < signature.length && signature[sigp] == '.') {
697 // support old-style GJC signatures
698 // The signature produced was
699 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
700 // rather than say
701 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
702 // so we skip past ".Lfoo/Outer$"
703 sigp += (sbp - startSbp) + // "foo/Outer"
704 3; // ".L" and "$"
705 signatureBuffer[sbp++] = (byte)'$';
706 break;
707 } else {
708 sbp = startSbp;
709 return outer;
710 }
711 case '.':
712 signatureBuffer[sbp++] = (byte)'$';
713 break;
714 default:
715 throw new AssertionError(signature[sigp-1]);
716 }
717 continue;
719 case '.':
720 signatureBuffer[sbp++] = (byte)'$';
721 continue;
722 case '/':
723 signatureBuffer[sbp++] = (byte)'.';
724 continue;
725 default:
726 signatureBuffer[sbp++] = c;
727 continue;
728 }
729 }
730 }
732 /** Convert (implicit) signature to list of types
733 * until `terminator' is encountered.
734 */
735 List<Type> sigToTypes(char terminator) {
736 List<Type> head = List.of(null);
737 List<Type> tail = head;
738 while (signature[sigp] != terminator)
739 tail = tail.setTail(List.of(sigToType()));
740 sigp++;
741 return head.tail;
742 }
744 /** Convert signature to type parameters, where signature is a name.
745 */
746 List<Type> sigToTypeParams(Name name) {
747 return sigToTypeParams(name.table.names, name.index, name.len);
748 }
750 /** Convert signature to type parameters, where signature is a byte
751 * array segment.
752 */
753 List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
754 signature = sig;
755 sigp = offset;
756 siglimit = offset + len;
757 return sigToTypeParams();
758 }
760 /** Convert signature to type parameters, where signature is implicit.
761 */
762 List<Type> sigToTypeParams() {
763 List<Type> tvars = List.nil();
764 if (signature[sigp] == '<') {
765 sigp++;
766 int start = sigp;
767 sigEnterPhase = true;
768 while (signature[sigp] != '>')
769 tvars = tvars.prepend(sigToTypeParam());
770 sigEnterPhase = false;
771 sigp = start;
772 while (signature[sigp] != '>')
773 sigToTypeParam();
774 sigp++;
775 }
776 return tvars.reverse();
777 }
779 /** Convert (implicit) signature to type parameter.
780 */
781 Type sigToTypeParam() {
782 int start = sigp;
783 while (signature[sigp] != ':') sigp++;
784 Name name = names.fromUtf(signature, start, sigp - start);
785 TypeVar tvar;
786 if (sigEnterPhase) {
787 tvar = new TypeVar(name, currentOwner, syms.botType);
788 typevars.enter(tvar.tsym);
789 } else {
790 tvar = (TypeVar)findTypeVar(name);
791 }
792 List<Type> bounds = List.nil();
793 Type st = null;
794 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
795 sigp++;
796 st = syms.objectType;
797 }
798 while (signature[sigp] == ':') {
799 sigp++;
800 bounds = bounds.prepend(sigToType());
801 }
802 if (!sigEnterPhase) {
803 types.setBounds(tvar, bounds.reverse(), st);
804 }
805 return tvar;
806 }
808 /** Find type variable with given name in `typevars' scope.
809 */
810 Type findTypeVar(Name name) {
811 Scope.Entry e = typevars.lookup(name);
812 if (e.scope != null) {
813 return e.sym.type;
814 } else {
815 if (readingClassAttr) {
816 // While reading the class attribute, the supertypes
817 // might refer to a type variable from an enclosing element
818 // (method or class).
819 // If the type variable is defined in the enclosing class,
820 // we can actually find it in
821 // currentOwner.owner.type.getTypeArguments()
822 // However, until we have read the enclosing method attribute
823 // we don't know for sure if this owner is correct. It could
824 // be a method and there is no way to tell before reading the
825 // enclosing method attribute.
826 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
827 missingTypeVariables = missingTypeVariables.prepend(t);
828 // System.err.println("Missing type var " + name);
829 return t;
830 }
831 throw badClassFile("undecl.type.var", name);
832 }
833 }
835 /************************************************************************
836 * Reading Attributes
837 ***********************************************************************/
839 /** Report unrecognized attribute.
840 */
841 void unrecognized(Name attrName) {
842 if (checkClassFile)
843 printCCF("ccf.unrecognized.attribute", attrName);
844 }
846 /** Read member attribute.
847 */
848 void readMemberAttr(Symbol sym, Name attrName, int attrLen) {
849 //- System.err.println(" z " + sym + ", " + attrName + ", " + attrLen);
850 if (attrName == names.ConstantValue) {
851 Object v = readPool(nextChar());
852 // Ignore ConstantValue attribute if field not final.
853 if ((sym.flags() & FINAL) != 0)
854 ((VarSymbol)sym).setData(v);
855 } else if (attrName == names.Code) {
856 if (readAllOfClassFile || saveParameterNames)
857 ((MethodSymbol)sym).code = readCode(sym);
858 else
859 bp = bp + attrLen;
860 } else if (attrName == names.Exceptions) {
861 int nexceptions = nextChar();
862 List<Type> thrown = List.nil();
863 for (int j = 0; j < nexceptions; j++)
864 thrown = thrown.prepend(readClassSymbol(nextChar()).type);
865 if (sym.type.getThrownTypes().isEmpty())
866 sym.type.asMethodType().thrown = thrown.reverse();
867 } else if (attrName == names.Synthetic) {
868 // bridge methods are visible when generics not enabled
869 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
870 sym.flags_field |= SYNTHETIC;
871 } else if (attrName == names.Bridge) {
872 sym.flags_field |= BRIDGE;
873 if (!allowGenerics)
874 sym.flags_field &= ~SYNTHETIC;
875 } else if (attrName == names.Deprecated) {
876 sym.flags_field |= DEPRECATED;
877 } else if (attrName == names.Varargs) {
878 if (allowVarargs) sym.flags_field |= VARARGS;
879 } else if (attrName == names.Annotation) {
880 if (allowAnnotations) sym.flags_field |= ANNOTATION;
881 } else if (attrName == names.Enum) {
882 sym.flags_field |= ENUM;
883 } else if (allowGenerics && attrName == names.Signature) {
884 List<Type> thrown = sym.type.getThrownTypes();
885 sym.type = readType(nextChar());
886 //- System.err.println(" # " + sym.type);
887 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
888 sym.type.asMethodType().thrown = thrown;
889 } else if (attrName == names.RuntimeVisibleAnnotations) {
890 attachAnnotations(sym);
891 } else if (attrName == names.RuntimeInvisibleAnnotations) {
892 attachAnnotations(sym);
893 } else if (attrName == names.RuntimeVisibleParameterAnnotations) {
894 attachParameterAnnotations(sym);
895 } else if (attrName == names.RuntimeInvisibleParameterAnnotations) {
896 attachParameterAnnotations(sym);
897 } else if (attrName == names.LocalVariableTable) {
898 int newbp = bp + attrLen;
899 if (saveParameterNames) {
900 // pick up parameter names from the variable table
901 List<Name> parameterNames = List.nil();
902 int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
903 int endParam = firstParam + Code.width(sym.type.getParameterTypes());
904 int numEntries = nextChar();
905 for (int i=0; i<numEntries; i++) {
906 int start_pc = nextChar();
907 int length = nextChar();
908 int nameIndex = nextChar();
909 int sigIndex = nextChar();
910 int register = nextChar();
911 if (start_pc == 0 &&
912 firstParam <= register &&
913 register < endParam) {
914 int index = firstParam;
915 for (Type t : sym.type.getParameterTypes()) {
916 if (index == register) {
917 parameterNames = parameterNames.prepend(readName(nameIndex));
918 break;
919 }
920 index += Code.width(t);
921 }
922 }
923 }
924 parameterNames = parameterNames.reverse();
925 ((MethodSymbol)sym).savedParameterNames = parameterNames;
926 }
927 bp = newbp;
928 } else if (attrName == names.AnnotationDefault) {
929 attachAnnotationDefault(sym);
930 } else if (attrName == names.EnclosingMethod) {
931 int newbp = bp + attrLen;
932 readEnclosingMethodAttr(sym);
933 bp = newbp;
934 } else {
935 unrecognized(attrName);
936 bp = bp + attrLen;
937 }
938 }
940 void readEnclosingMethodAttr(Symbol sym) {
941 // sym is a nested class with an "Enclosing Method" attribute
942 // remove sym from it's current owners scope and place it in
943 // the scope specified by the attribute
944 sym.owner.members().remove(sym);
945 ClassSymbol self = (ClassSymbol)sym;
946 ClassSymbol c = readClassSymbol(nextChar());
947 NameAndType nt = (NameAndType)readPool(nextChar());
949 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
950 if (nt != null && m == null)
951 throw badClassFile("bad.enclosing.method", self);
953 self.name = simpleBinaryName(self.flatname, c.flatname) ;
954 self.owner = m != null ? m : c;
955 if (self.name.len == 0)
956 self.fullname = null;
957 else
958 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
960 if (m != null) {
961 ((ClassType)sym.type).setEnclosingType(m.type);
962 } else if ((self.flags_field & STATIC) == 0) {
963 ((ClassType)sym.type).setEnclosingType(c.type);
964 } else {
965 ((ClassType)sym.type).setEnclosingType(Type.noType);
966 }
967 enterTypevars(self);
968 if (!missingTypeVariables.isEmpty()) {
969 ListBuffer<Type> typeVars = new ListBuffer<Type>();
970 for (Type typevar : missingTypeVariables) {
971 typeVars.append(findTypeVar(typevar.tsym.name));
972 }
973 foundTypeVariables = typeVars.toList();
974 } else {
975 foundTypeVariables = List.nil();
976 }
977 }
979 // See java.lang.Class
980 private Name simpleBinaryName(Name self, Name enclosing) {
981 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
982 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
983 throw badClassFile("bad.enclosing.method", self);
984 int index = 1;
985 while (index < simpleBinaryName.length() &&
986 isAsciiDigit(simpleBinaryName.charAt(index)))
987 index++;
988 return names.fromString(simpleBinaryName.substring(index));
989 }
991 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
992 if (nt == null)
993 return null;
995 MethodType type = nt.type.asMethodType();
997 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
998 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
999 return (MethodSymbol)e.sym;
1001 if (nt.name != names.init)
1002 // not a constructor
1003 return null;
1004 if ((flags & INTERFACE) != 0)
1005 // no enclosing instance
1006 return null;
1007 if (nt.type.getParameterTypes().isEmpty())
1008 // no parameters
1009 return null;
1011 // A constructor of an inner class.
1012 // Remove the first argument (the enclosing instance)
1013 nt.type = new MethodType(nt.type.getParameterTypes().tail,
1014 nt.type.getReturnType(),
1015 nt.type.getThrownTypes(),
1016 syms.methodClass);
1017 // Try searching again
1018 return findMethod(nt, scope, flags);
1019 }
1021 /** Similar to Types.isSameType but avoids completion */
1022 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1023 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1024 .prepend(types.erasure(mt1.getReturnType()));
1025 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1026 while (!types1.isEmpty() && !types2.isEmpty()) {
1027 if (types1.head.tsym != types2.head.tsym)
1028 return false;
1029 types1 = types1.tail;
1030 types2 = types2.tail;
1031 }
1032 return types1.isEmpty() && types2.isEmpty();
1033 }
1035 /**
1036 * Character.isDigit answers <tt>true</tt> to some non-ascii
1037 * digits. This one does not. <b>copied from java.lang.Class</b>
1038 */
1039 private static boolean isAsciiDigit(char c) {
1040 return '0' <= c && c <= '9';
1041 }
1043 /** Read member attributes.
1044 */
1045 void readMemberAttrs(Symbol sym) {
1046 char ac = nextChar();
1047 for (int i = 0; i < ac; i++) {
1048 Name attrName = readName(nextChar());
1049 int attrLen = nextInt();
1050 readMemberAttr(sym, attrName, attrLen);
1051 }
1052 }
1054 /** Read class attribute.
1055 */
1056 void readClassAttr(ClassSymbol c, Name attrName, int attrLen) {
1057 if (attrName == names.SourceFile) {
1058 Name n = readName(nextChar());
1059 c.sourcefile = new SourceFileObject(n, c.flatname);
1060 } else if (attrName == names.InnerClasses) {
1061 readInnerClasses(c);
1062 } else if (allowGenerics && attrName == names.Signature) {
1063 readingClassAttr = true;
1064 try {
1065 ClassType ct1 = (ClassType)c.type;
1066 assert c == currentOwner;
1067 ct1.typarams_field = readTypeParams(nextChar());
1068 ct1.supertype_field = sigToType();
1069 ListBuffer<Type> is = new ListBuffer<Type>();
1070 while (sigp != siglimit) is.append(sigToType());
1071 ct1.interfaces_field = is.toList();
1072 } finally {
1073 readingClassAttr = false;
1074 }
1075 } else {
1076 readMemberAttr(c, attrName, attrLen);
1077 }
1078 }
1079 private boolean readingClassAttr = false;
1080 private List<Type> missingTypeVariables = List.nil();
1081 private List<Type> foundTypeVariables = List.nil();
1083 /** Read class attributes.
1084 */
1085 void readClassAttrs(ClassSymbol c) {
1086 char ac = nextChar();
1087 for (int i = 0; i < ac; i++) {
1088 Name attrName = readName(nextChar());
1089 int attrLen = nextInt();
1090 readClassAttr(c, attrName, attrLen);
1091 }
1092 }
1094 /** Read code block.
1095 */
1096 Code readCode(Symbol owner) {
1097 nextChar(); // max_stack
1098 nextChar(); // max_locals
1099 final int code_length = nextInt();
1100 bp += code_length;
1101 final char exception_table_length = nextChar();
1102 bp += exception_table_length * 8;
1103 readMemberAttrs(owner);
1104 return null;
1105 }
1107 /************************************************************************
1108 * Reading Java-language annotations
1109 ***********************************************************************/
1111 /** Attach annotations.
1112 */
1113 void attachAnnotations(final Symbol sym) {
1114 int numAttributes = nextChar();
1115 if (numAttributes != 0) {
1116 ListBuffer<CompoundAnnotationProxy> proxies =
1117 new ListBuffer<CompoundAnnotationProxy>();
1118 for (int i = 0; i<numAttributes; i++) {
1119 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1120 if (proxy.type.tsym == syms.proprietaryType.tsym)
1121 sym.flags_field |= PROPRIETARY;
1122 else
1123 proxies.append(proxy);
1124 }
1125 annotate.later(new AnnotationCompleter(sym, proxies.toList()));
1126 }
1127 }
1129 /** Attach parameter annotations.
1130 */
1131 void attachParameterAnnotations(final Symbol method) {
1132 final MethodSymbol meth = (MethodSymbol)method;
1133 int numParameters = buf[bp++] & 0xFF;
1134 List<VarSymbol> parameters = meth.params();
1135 int pnum = 0;
1136 while (parameters.tail != null) {
1137 attachAnnotations(parameters.head);
1138 parameters = parameters.tail;
1139 pnum++;
1140 }
1141 if (pnum != numParameters) {
1142 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1143 }
1144 }
1146 /** Attach the default value for an annotation element.
1147 */
1148 void attachAnnotationDefault(final Symbol sym) {
1149 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1150 final Attribute value = readAttributeValue();
1151 annotate.later(new AnnotationDefaultCompleter(meth, value));
1152 }
1154 Type readTypeOrClassSymbol(int i) {
1155 // support preliminary jsr175-format class files
1156 if (buf[poolIdx[i]] == CONSTANT_Class)
1157 return readClassSymbol(i).type;
1158 return readType(i);
1159 }
1160 Type readEnumType(int i) {
1161 // support preliminary jsr175-format class files
1162 int index = poolIdx[i];
1163 int length = getChar(index + 1);
1164 if (buf[index + length + 2] != ';')
1165 return enterClass(readName(i)).type;
1166 return readType(i);
1167 }
1169 CompoundAnnotationProxy readCompoundAnnotation() {
1170 Type t = readTypeOrClassSymbol(nextChar());
1171 int numFields = nextChar();
1172 ListBuffer<Pair<Name,Attribute>> pairs =
1173 new ListBuffer<Pair<Name,Attribute>>();
1174 for (int i=0; i<numFields; i++) {
1175 Name name = readName(nextChar());
1176 Attribute value = readAttributeValue();
1177 pairs.append(new Pair<Name,Attribute>(name, value));
1178 }
1179 return new CompoundAnnotationProxy(t, pairs.toList());
1180 }
1182 Attribute readAttributeValue() {
1183 char c = (char) buf[bp++];
1184 switch (c) {
1185 case 'B':
1186 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1187 case 'C':
1188 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1189 case 'D':
1190 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1191 case 'F':
1192 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1193 case 'I':
1194 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1195 case 'J':
1196 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1197 case 'S':
1198 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1199 case 'Z':
1200 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1201 case 's':
1202 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1203 case 'e':
1204 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1205 case 'c':
1206 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1207 case '[': {
1208 int n = nextChar();
1209 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1210 for (int i=0; i<n; i++)
1211 l.append(readAttributeValue());
1212 return new ArrayAttributeProxy(l.toList());
1213 }
1214 case '@':
1215 return readCompoundAnnotation();
1216 default:
1217 throw new AssertionError("unknown annotation tag '" + c + "'");
1218 }
1219 }
1221 interface ProxyVisitor extends Attribute.Visitor {
1222 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1223 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1224 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1225 }
1227 static class EnumAttributeProxy extends Attribute {
1228 Type enumType;
1229 Name enumerator;
1230 public EnumAttributeProxy(Type enumType, Name enumerator) {
1231 super(null);
1232 this.enumType = enumType;
1233 this.enumerator = enumerator;
1234 }
1235 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1236 public String toString() {
1237 return "/*proxy enum*/" + enumType + "." + enumerator;
1238 }
1239 }
1241 static class ArrayAttributeProxy extends Attribute {
1242 List<Attribute> values;
1243 ArrayAttributeProxy(List<Attribute> values) {
1244 super(null);
1245 this.values = values;
1246 }
1247 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1248 public String toString() {
1249 return "{" + values + "}";
1250 }
1251 }
1253 /** A temporary proxy representing a compound attribute.
1254 */
1255 static class CompoundAnnotationProxy extends Attribute {
1256 final List<Pair<Name,Attribute>> values;
1257 public CompoundAnnotationProxy(Type type,
1258 List<Pair<Name,Attribute>> values) {
1259 super(type);
1260 this.values = values;
1261 }
1262 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1263 public String toString() {
1264 StringBuffer buf = new StringBuffer();
1265 buf.append("@");
1266 buf.append(type.tsym.getQualifiedName());
1267 buf.append("/*proxy*/{");
1268 boolean first = true;
1269 for (List<Pair<Name,Attribute>> v = values;
1270 v.nonEmpty(); v = v.tail) {
1271 Pair<Name,Attribute> value = v.head;
1272 if (!first) buf.append(",");
1273 first = false;
1274 buf.append(value.fst);
1275 buf.append("=");
1276 buf.append(value.snd);
1277 }
1278 buf.append("}");
1279 return buf.toString();
1280 }
1281 }
1283 class AnnotationDeproxy implements ProxyVisitor {
1284 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1285 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1287 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1288 // also must fill in types!!!!
1289 ListBuffer<Attribute.Compound> buf =
1290 new ListBuffer<Attribute.Compound>();
1291 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1292 buf.append(deproxyCompound(l.head));
1293 }
1294 return buf.toList();
1295 }
1297 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1298 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1299 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1300 for (List<Pair<Name,Attribute>> l = a.values;
1301 l.nonEmpty();
1302 l = l.tail) {
1303 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1304 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1305 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1306 }
1307 return new Attribute.Compound(a.type, buf.toList());
1308 }
1310 MethodSymbol findAccessMethod(Type container, Name name) {
1311 CompletionFailure failure = null;
1312 try {
1313 for (Scope.Entry e = container.tsym.members().lookup(name);
1314 e.scope != null;
1315 e = e.next()) {
1316 Symbol sym = e.sym;
1317 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1318 return (MethodSymbol) sym;
1319 }
1320 } catch (CompletionFailure ex) {
1321 failure = ex;
1322 }
1323 // The method wasn't found: emit a warning and recover
1324 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1325 try {
1326 if (failure == null) {
1327 log.warning("annotation.method.not.found",
1328 container,
1329 name);
1330 } else {
1331 log.warning("annotation.method.not.found.reason",
1332 container,
1333 name,
1334 failure.getMessage());
1335 }
1336 } finally {
1337 log.useSource(prevSource);
1338 }
1339 // Construct a new method type and symbol. Use bottom
1340 // type (typeof null) as return type because this type is
1341 // a subtype of all reference types and can be converted
1342 // to primitive types by unboxing.
1343 MethodType mt = new MethodType(List.<Type>nil(),
1344 syms.botType,
1345 List.<Type>nil(),
1346 syms.methodClass);
1347 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1348 }
1350 Attribute result;
1351 Type type;
1352 Attribute deproxy(Type t, Attribute a) {
1353 Type oldType = type;
1354 try {
1355 type = t;
1356 a.accept(this);
1357 return result;
1358 } finally {
1359 type = oldType;
1360 }
1361 }
1363 // implement Attribute.Visitor below
1365 public void visitConstant(Attribute.Constant value) {
1366 // assert value.type == type;
1367 result = value;
1368 }
1370 public void visitClass(Attribute.Class clazz) {
1371 result = clazz;
1372 }
1374 public void visitEnum(Attribute.Enum e) {
1375 throw new AssertionError(); // shouldn't happen
1376 }
1378 public void visitCompound(Attribute.Compound compound) {
1379 throw new AssertionError(); // shouldn't happen
1380 }
1382 public void visitArray(Attribute.Array array) {
1383 throw new AssertionError(); // shouldn't happen
1384 }
1386 public void visitError(Attribute.Error e) {
1387 throw new AssertionError(); // shouldn't happen
1388 }
1390 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1391 // type.tsym.flatName() should == proxy.enumFlatName
1392 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1393 VarSymbol enumerator = null;
1394 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1395 e.scope != null;
1396 e = e.next()) {
1397 if (e.sym.kind == VAR) {
1398 enumerator = (VarSymbol)e.sym;
1399 break;
1400 }
1401 }
1402 if (enumerator == null) {
1403 log.error("unknown.enum.constant",
1404 currentClassFile, enumTypeSym, proxy.enumerator);
1405 result = new Attribute.Error(enumTypeSym.type);
1406 } else {
1407 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1408 }
1409 }
1411 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1412 int length = proxy.values.length();
1413 Attribute[] ats = new Attribute[length];
1414 Type elemtype = types.elemtype(type);
1415 int i = 0;
1416 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1417 ats[i++] = deproxy(elemtype, p.head);
1418 }
1419 result = new Attribute.Array(type, ats);
1420 }
1422 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1423 result = deproxyCompound(proxy);
1424 }
1425 }
1427 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1428 final MethodSymbol sym;
1429 final Attribute value;
1430 final JavaFileObject classFile = currentClassFile;
1431 public String toString() {
1432 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1433 }
1434 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1435 this.sym = sym;
1436 this.value = value;
1437 }
1438 // implement Annotate.Annotator.enterAnnotation()
1439 public void enterAnnotation() {
1440 JavaFileObject previousClassFile = currentClassFile;
1441 try {
1442 currentClassFile = classFile;
1443 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1444 } finally {
1445 currentClassFile = previousClassFile;
1446 }
1447 }
1448 }
1450 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1451 final Symbol sym;
1452 final List<CompoundAnnotationProxy> l;
1453 final JavaFileObject classFile;
1454 public String toString() {
1455 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1456 }
1457 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1458 this.sym = sym;
1459 this.l = l;
1460 this.classFile = currentClassFile;
1461 }
1462 // implement Annotate.Annotator.enterAnnotation()
1463 public void enterAnnotation() {
1464 JavaFileObject previousClassFile = currentClassFile;
1465 try {
1466 currentClassFile = classFile;
1467 List<Attribute.Compound> newList = deproxyCompoundList(l);
1468 sym.attributes_field = ((sym.attributes_field == null)
1469 ? newList
1470 : newList.prependList(sym.attributes_field));
1471 } finally {
1472 currentClassFile = previousClassFile;
1473 }
1474 }
1475 }
1478 /************************************************************************
1479 * Reading Symbols
1480 ***********************************************************************/
1482 /** Read a field.
1483 */
1484 VarSymbol readField() {
1485 long flags = adjustFieldFlags(nextChar());
1486 Name name = readName(nextChar());
1487 Type type = readType(nextChar());
1488 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1489 readMemberAttrs(v);
1490 return v;
1491 }
1493 /** Read a method.
1494 */
1495 MethodSymbol readMethod() {
1496 long flags = adjustMethodFlags(nextChar());
1497 Name name = readName(nextChar());
1498 Type type = readType(nextChar());
1499 if (name == names.init && currentOwner.hasOuterInstance()) {
1500 // Sometimes anonymous classes don't have an outer
1501 // instance, however, there is no reliable way to tell so
1502 // we never strip this$n
1503 if (currentOwner.name.len != 0)
1504 type = new MethodType(type.getParameterTypes().tail,
1505 type.getReturnType(),
1506 type.getThrownTypes(),
1507 syms.methodClass);
1508 }
1509 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1510 Symbol prevOwner = currentOwner;
1511 currentOwner = m;
1512 try {
1513 readMemberAttrs(m);
1514 } finally {
1515 currentOwner = prevOwner;
1516 }
1517 return m;
1518 }
1520 /** Skip a field or method
1521 */
1522 void skipMember() {
1523 bp = bp + 6;
1524 char ac = nextChar();
1525 for (int i = 0; i < ac; i++) {
1526 bp = bp + 2;
1527 int attrLen = nextInt();
1528 bp = bp + attrLen;
1529 }
1530 }
1532 /** Enter type variables of this classtype and all enclosing ones in
1533 * `typevars'.
1534 */
1535 protected void enterTypevars(Type t) {
1536 if (t.getEnclosingType() != null && t.getEnclosingType().tag == CLASS)
1537 enterTypevars(t.getEnclosingType());
1538 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1539 typevars.enter(xs.head.tsym);
1540 }
1542 protected void enterTypevars(Symbol sym) {
1543 if (sym.owner.kind == MTH) {
1544 enterTypevars(sym.owner);
1545 enterTypevars(sym.owner.owner);
1546 }
1547 enterTypevars(sym.type);
1548 }
1550 /** Read contents of a given class symbol `c'. Both external and internal
1551 * versions of an inner class are read.
1552 */
1553 void readClass(ClassSymbol c) {
1554 ClassType ct = (ClassType)c.type;
1556 // allocate scope for members
1557 c.members_field = new Scope(c);
1559 // prepare type variable table
1560 typevars = typevars.dup(currentOwner);
1561 if (ct.getEnclosingType().tag == CLASS) enterTypevars(ct.getEnclosingType());
1563 // read flags, or skip if this is an inner class
1564 long flags = adjustClassFlags(nextChar());
1565 if (c.owner.kind == PCK) c.flags_field = flags;
1567 // read own class name and check that it matches
1568 ClassSymbol self = readClassSymbol(nextChar());
1569 if (c != self)
1570 throw badClassFile("class.file.wrong.class",
1571 self.flatname);
1573 // class attributes must be read before class
1574 // skip ahead to read class attributes
1575 int startbp = bp;
1576 nextChar();
1577 char interfaceCount = nextChar();
1578 bp += interfaceCount * 2;
1579 char fieldCount = nextChar();
1580 for (int i = 0; i < fieldCount; i++) skipMember();
1581 char methodCount = nextChar();
1582 for (int i = 0; i < methodCount; i++) skipMember();
1583 readClassAttrs(c);
1585 if (readAllOfClassFile) {
1586 for (int i = 1; i < poolObj.length; i++) readPool(i);
1587 c.pool = new Pool(poolObj.length, poolObj);
1588 }
1590 // reset and read rest of classinfo
1591 bp = startbp;
1592 int n = nextChar();
1593 if (ct.supertype_field == null)
1594 ct.supertype_field = (n == 0)
1595 ? Type.noType
1596 : readClassSymbol(n).erasure(types);
1597 n = nextChar();
1598 List<Type> is = List.nil();
1599 for (int i = 0; i < n; i++) {
1600 Type _inter = readClassSymbol(nextChar()).erasure(types);
1601 is = is.prepend(_inter);
1602 }
1603 if (ct.interfaces_field == null)
1604 ct.interfaces_field = is.reverse();
1606 if (fieldCount != nextChar()) assert false;
1607 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
1608 if (methodCount != nextChar()) assert false;
1609 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
1611 typevars = typevars.leave();
1612 }
1614 /** Read inner class info. For each inner/outer pair allocate a
1615 * member class.
1616 */
1617 void readInnerClasses(ClassSymbol c) {
1618 int n = nextChar();
1619 for (int i = 0; i < n; i++) {
1620 nextChar(); // skip inner class symbol
1621 ClassSymbol outer = readClassSymbol(nextChar());
1622 Name name = readName(nextChar());
1623 if (name == null) name = names.empty;
1624 long flags = adjustClassFlags(nextChar());
1625 if (outer != null) { // we have a member class
1626 if (name == names.empty)
1627 name = names.one;
1628 ClassSymbol member = enterClass(name, outer);
1629 if ((flags & STATIC) == 0) {
1630 ((ClassType)member.type).setEnclosingType(outer.type);
1631 if (member.erasure_field != null)
1632 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
1633 }
1634 if (c == outer) {
1635 member.flags_field = flags;
1636 enterMember(c, member);
1637 }
1638 }
1639 }
1640 }
1642 /** Read a class file.
1643 */
1644 private void readClassFile(ClassSymbol c) throws IOException {
1645 int magic = nextInt();
1646 if (magic != JAVA_MAGIC)
1647 throw badClassFile("illegal.start.of.class.file");
1649 int minorVersion = nextChar();
1650 int majorVersion = nextChar();
1651 int maxMajor = Target.MAX().majorVersion;
1652 int maxMinor = Target.MAX().minorVersion;
1653 if (majorVersion > maxMajor ||
1654 majorVersion * 1000 + minorVersion <
1655 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
1656 {
1657 if (majorVersion == (maxMajor + 1))
1658 log.warning("big.major.version",
1659 currentClassFile,
1660 majorVersion,
1661 maxMajor);
1662 else
1663 throw badClassFile("wrong.version",
1664 Integer.toString(majorVersion),
1665 Integer.toString(minorVersion),
1666 Integer.toString(maxMajor),
1667 Integer.toString(maxMinor));
1668 }
1669 else if (checkClassFile &&
1670 majorVersion == maxMajor &&
1671 minorVersion > maxMinor)
1672 {
1673 printCCF("found.later.version",
1674 Integer.toString(minorVersion));
1675 }
1676 indexPool();
1677 if (signatureBuffer.length < bp) {
1678 int ns = Integer.highestOneBit(bp) << 1;
1679 signatureBuffer = new byte[ns];
1680 }
1681 readClass(c);
1682 }
1684 /************************************************************************
1685 * Adjusting flags
1686 ***********************************************************************/
1688 long adjustFieldFlags(long flags) {
1689 return flags;
1690 }
1691 long adjustMethodFlags(long flags) {
1692 if ((flags & ACC_BRIDGE) != 0) {
1693 flags &= ~ACC_BRIDGE;
1694 flags |= BRIDGE;
1695 if (!allowGenerics)
1696 flags &= ~SYNTHETIC;
1697 }
1698 if ((flags & ACC_VARARGS) != 0) {
1699 flags &= ~ACC_VARARGS;
1700 flags |= VARARGS;
1701 }
1702 return flags;
1703 }
1704 long adjustClassFlags(long flags) {
1705 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
1706 }
1708 /************************************************************************
1709 * Loading Classes
1710 ***********************************************************************/
1712 /** Define a new class given its name and owner.
1713 */
1714 public ClassSymbol defineClass(Name name, Symbol owner) {
1715 ClassSymbol c = new ClassSymbol(0, name, owner);
1716 if (owner.kind == PCK)
1717 assert classes.get(c.flatname) == null : c;
1718 c.completer = this;
1719 return c;
1720 }
1722 /** Create a new toplevel or member class symbol with given name
1723 * and owner and enter in `classes' unless already there.
1724 */
1725 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
1726 Name flatname = TypeSymbol.formFlatName(name, owner);
1727 ClassSymbol c = classes.get(flatname);
1728 if (c == null) {
1729 c = defineClass(name, owner);
1730 classes.put(flatname, c);
1731 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
1732 // reassign fields of classes that might have been loaded with
1733 // their flat names.
1734 c.owner.members().remove(c);
1735 c.name = name;
1736 c.owner = owner;
1737 c.fullname = ClassSymbol.formFullName(name, owner);
1738 }
1739 return c;
1740 }
1742 /**
1743 * Creates a new toplevel class symbol with given flat name and
1744 * given class (or source) file.
1745 *
1746 * @param flatName a fully qualified binary class name
1747 * @param classFile the class file or compilation unit defining
1748 * the class (may be {@code null})
1749 * @return a newly created class symbol
1750 * @throws AssertionError if the class symbol already exists
1751 */
1752 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
1753 ClassSymbol cs = classes.get(flatName);
1754 if (cs != null) {
1755 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
1756 cs.fullname,
1757 cs.completer,
1758 cs.classfile,
1759 cs.sourcefile);
1760 throw new AssertionError(msg);
1761 }
1762 Name packageName = Convert.packagePart(flatName);
1763 PackageSymbol owner = packageName.isEmpty()
1764 ? syms.unnamedPackage
1765 : enterPackage(packageName);
1766 cs = defineClass(Convert.shortName(flatName), owner);
1767 cs.classfile = classFile;
1768 classes.put(flatName, cs);
1769 return cs;
1770 }
1772 /** Create a new member or toplevel class symbol with given flat name
1773 * and enter in `classes' unless already there.
1774 */
1775 public ClassSymbol enterClass(Name flatname) {
1776 ClassSymbol c = classes.get(flatname);
1777 if (c == null)
1778 return enterClass(flatname, (JavaFileObject)null);
1779 else
1780 return c;
1781 }
1783 private boolean suppressFlush = false;
1785 /** Completion for classes to be loaded. Before a class is loaded
1786 * we make sure its enclosing class (if any) is loaded.
1787 */
1788 public void complete(Symbol sym) throws CompletionFailure {
1789 if (sym.kind == TYP) {
1790 ClassSymbol c = (ClassSymbol)sym;
1791 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
1792 boolean suppressFlush = this.suppressFlush;
1793 this.suppressFlush = true;
1794 try {
1795 completeOwners(c.owner);
1796 completeEnclosing(c);
1797 } finally {
1798 this.suppressFlush = suppressFlush;
1799 }
1800 fillIn(c);
1801 } else if (sym.kind == PCK) {
1802 PackageSymbol p = (PackageSymbol)sym;
1803 try {
1804 fillIn(p);
1805 } catch (IOException ex) {
1806 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
1807 }
1808 }
1809 if (!filling && !suppressFlush)
1810 annotate.flush(); // finish attaching annotations
1811 }
1813 /** complete up through the enclosing package. */
1814 private void completeOwners(Symbol o) {
1815 if (o.kind != PCK) completeOwners(o.owner);
1816 o.complete();
1817 }
1819 /**
1820 * Tries to complete lexically enclosing classes if c looks like a
1821 * nested class. This is similar to completeOwners but handles
1822 * the situation when a nested class is accessed directly as it is
1823 * possible with the Tree API or javax.lang.model.*.
1824 */
1825 private void completeEnclosing(ClassSymbol c) {
1826 if (c.owner.kind == PCK) {
1827 Symbol owner = c.owner;
1828 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
1829 Symbol encl = owner.members().lookup(name).sym;
1830 if (encl == null)
1831 encl = classes.get(TypeSymbol.formFlatName(name, owner));
1832 if (encl != null)
1833 encl.complete();
1834 }
1835 }
1836 }
1838 /** We can only read a single class file at a time; this
1839 * flag keeps track of when we are currently reading a class
1840 * file.
1841 */
1842 private boolean filling = false;
1844 /** Fill in definition of class `c' from corresponding class or
1845 * source file.
1846 */
1847 private void fillIn(ClassSymbol c) {
1848 if (completionFailureName == c.fullname) {
1849 throw new CompletionFailure(c, "user-selected completion failure by class name");
1850 }
1851 currentOwner = c;
1852 JavaFileObject classfile = c.classfile;
1853 if (classfile != null) {
1854 JavaFileObject previousClassFile = currentClassFile;
1855 try {
1856 assert !filling :
1857 "Filling " + classfile.toUri() +
1858 " during " + previousClassFile;
1859 currentClassFile = classfile;
1860 if (verbose) {
1861 printVerbose("loading", currentClassFile.toString());
1862 }
1863 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
1864 filling = true;
1865 try {
1866 bp = 0;
1867 buf = readInputStream(buf, classfile.openInputStream());
1868 readClassFile(c);
1869 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
1870 List<Type> missing = missingTypeVariables;
1871 List<Type> found = foundTypeVariables;
1872 missingTypeVariables = List.nil();
1873 foundTypeVariables = List.nil();
1874 filling = false;
1875 ClassType ct = (ClassType)currentOwner.type;
1876 ct.supertype_field =
1877 types.subst(ct.supertype_field, missing, found);
1878 ct.interfaces_field =
1879 types.subst(ct.interfaces_field, missing, found);
1880 } else if (missingTypeVariables.isEmpty() !=
1881 foundTypeVariables.isEmpty()) {
1882 Name name = missingTypeVariables.head.tsym.name;
1883 throw badClassFile("undecl.type.var", name);
1884 }
1885 } finally {
1886 missingTypeVariables = List.nil();
1887 foundTypeVariables = List.nil();
1888 filling = false;
1889 }
1890 } else {
1891 if (sourceCompleter != null) {
1892 sourceCompleter.complete(c);
1893 } else {
1894 throw new IllegalStateException("Source completer required to read "
1895 + classfile.toUri());
1896 }
1897 }
1898 return;
1899 } catch (IOException ex) {
1900 throw badClassFile("unable.to.access.file", ex.getMessage());
1901 } finally {
1902 currentClassFile = previousClassFile;
1903 }
1904 } else {
1905 JCDiagnostic diag =
1906 diagFactory.fragment("class.file.not.found", c.flatname);
1907 throw
1908 newCompletionFailure(c, diag);
1909 }
1910 }
1911 // where
1912 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
1913 try {
1914 buf = ensureCapacity(buf, s.available());
1915 int r = s.read(buf);
1916 int bp = 0;
1917 while (r != -1) {
1918 bp += r;
1919 buf = ensureCapacity(buf, bp);
1920 r = s.read(buf, bp, buf.length - bp);
1921 }
1922 return buf;
1923 } finally {
1924 try {
1925 s.close();
1926 } catch (IOException e) {
1927 /* Ignore any errors, as this stream may have already
1928 * thrown a related exception which is the one that
1929 * should be reported.
1930 */
1931 }
1932 }
1933 }
1934 private static byte[] ensureCapacity(byte[] buf, int needed) {
1935 if (buf.length < needed) {
1936 byte[] old = buf;
1937 buf = new byte[Integer.highestOneBit(needed) << 1];
1938 System.arraycopy(old, 0, buf, 0, old.length);
1939 }
1940 return buf;
1941 }
1942 /** Static factory for CompletionFailure objects.
1943 * In practice, only one can be used at a time, so we share one
1944 * to reduce the expense of allocating new exception objects.
1945 */
1946 private CompletionFailure newCompletionFailure(TypeSymbol c,
1947 JCDiagnostic diag) {
1948 if (!cacheCompletionFailure) {
1949 // log.warning("proc.messager",
1950 // Log.getLocalizedString("class.file.not.found", c.flatname));
1951 // c.debug.printStackTrace();
1952 return new CompletionFailure(c, diag);
1953 } else {
1954 CompletionFailure result = cachedCompletionFailure;
1955 result.sym = c;
1956 result.diag = diag;
1957 return result;
1958 }
1959 }
1960 private CompletionFailure cachedCompletionFailure =
1961 new CompletionFailure(null, (JCDiagnostic) null);
1962 {
1963 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
1964 }
1966 /** Load a toplevel class with given fully qualified name
1967 * The class is entered into `classes' only if load was successful.
1968 */
1969 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
1970 boolean absent = classes.get(flatname) == null;
1971 ClassSymbol c = enterClass(flatname);
1972 if (c.members_field == null && c.completer != null) {
1973 try {
1974 c.complete();
1975 } catch (CompletionFailure ex) {
1976 if (absent) classes.remove(flatname);
1977 throw ex;
1978 }
1979 }
1980 return c;
1981 }
1983 /************************************************************************
1984 * Loading Packages
1985 ***********************************************************************/
1987 /** Check to see if a package exists, given its fully qualified name.
1988 */
1989 public boolean packageExists(Name fullname) {
1990 return enterPackage(fullname).exists();
1991 }
1993 /** Make a package, given its fully qualified name.
1994 */
1995 public PackageSymbol enterPackage(Name fullname) {
1996 PackageSymbol p = packages.get(fullname);
1997 if (p == null) {
1998 assert !fullname.isEmpty() : "rootPackage missing!";
1999 p = new PackageSymbol(
2000 Convert.shortName(fullname),
2001 enterPackage(Convert.packagePart(fullname)));
2002 p.completer = this;
2003 packages.put(fullname, p);
2004 }
2005 return p;
2006 }
2008 /** Make a package, given its unqualified name and enclosing package.
2009 */
2010 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2011 return enterPackage(TypeSymbol.formFullName(name, owner));
2012 }
2014 /** Include class corresponding to given class file in package,
2015 * unless (1) we already have one the same kind (.class or .java), or
2016 * (2) we have one of the other kind, and the given class file
2017 * is older.
2018 */
2019 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2020 if ((p.flags_field & EXISTS) == 0)
2021 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2022 q.flags_field |= EXISTS;
2023 JavaFileObject.Kind kind = file.getKind();
2024 int seen;
2025 if (kind == JavaFileObject.Kind.CLASS)
2026 seen = CLASS_SEEN;
2027 else
2028 seen = SOURCE_SEEN;
2029 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2030 int lastDot = binaryName.lastIndexOf(".");
2031 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2032 boolean isPkgInfo = classname == names.package_info;
2033 ClassSymbol c = isPkgInfo
2034 ? p.package_info
2035 : (ClassSymbol) p.members_field.lookup(classname).sym;
2036 if (c == null) {
2037 c = enterClass(classname, p);
2038 if (c.classfile == null) // only update the file if's it's newly created
2039 c.classfile = file;
2040 if (isPkgInfo) {
2041 p.package_info = c;
2042 } else {
2043 if (c.owner == p) // it might be an inner class
2044 p.members_field.enter(c);
2045 }
2046 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2047 // if c.classfile == null, we are currently compiling this class
2048 // and no further action is necessary.
2049 // if (c.flags_field & seen) != 0, we have already encountered
2050 // a file of the same kind; again no further action is necessary.
2051 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2052 c.classfile = preferredFileObject(file, c.classfile);
2053 }
2054 c.flags_field |= seen;
2055 }
2057 /** Implement policy to choose to derive information from a source
2058 * file or a class file when both are present. May be overridden
2059 * by subclasses.
2060 */
2061 protected JavaFileObject preferredFileObject(JavaFileObject a,
2062 JavaFileObject b) {
2064 if (preferSource)
2065 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2066 else {
2067 long adate = a.getLastModified();
2068 long bdate = b.getLastModified();
2069 // 6449326: policy for bad lastModifiedTime in ClassReader
2070 //assert adate >= 0 && bdate >= 0;
2071 return (adate > bdate) ? a : b;
2072 }
2073 }
2075 /**
2076 * specifies types of files to be read when filling in a package symbol
2077 */
2078 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2079 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2080 }
2082 /**
2083 * this is used to support javadoc
2084 */
2085 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2086 }
2088 protected Location currentLoc; // FIXME
2090 private boolean verbosePath = true;
2092 /** Load directory of package into members scope.
2093 */
2094 private void fillIn(PackageSymbol p) throws IOException {
2095 if (p.members_field == null) p.members_field = new Scope(p);
2096 String packageName = p.fullname.toString();
2098 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2100 fillIn(p, PLATFORM_CLASS_PATH,
2101 fileManager.list(PLATFORM_CLASS_PATH,
2102 packageName,
2103 EnumSet.of(JavaFileObject.Kind.CLASS),
2104 false));
2106 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2107 classKinds.remove(JavaFileObject.Kind.SOURCE);
2108 boolean wantClassFiles = !classKinds.isEmpty();
2110 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2111 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2112 boolean wantSourceFiles = !sourceKinds.isEmpty();
2114 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2116 if (verbose && verbosePath) {
2117 if (fileManager instanceof StandardJavaFileManager) {
2118 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2119 if (haveSourcePath && wantSourceFiles) {
2120 List<File> path = List.nil();
2121 for (File file : fm.getLocation(SOURCE_PATH)) {
2122 path = path.prepend(file);
2123 }
2124 printVerbose("sourcepath", path.reverse().toString());
2125 } else if (wantSourceFiles) {
2126 List<File> path = List.nil();
2127 for (File file : fm.getLocation(CLASS_PATH)) {
2128 path = path.prepend(file);
2129 }
2130 printVerbose("sourcepath", path.reverse().toString());
2131 }
2132 if (wantClassFiles) {
2133 List<File> path = List.nil();
2134 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2135 path = path.prepend(file);
2136 }
2137 for (File file : fm.getLocation(CLASS_PATH)) {
2138 path = path.prepend(file);
2139 }
2140 printVerbose("classpath", path.reverse().toString());
2141 }
2142 }
2143 }
2145 if (wantSourceFiles && !haveSourcePath) {
2146 fillIn(p, CLASS_PATH,
2147 fileManager.list(CLASS_PATH,
2148 packageName,
2149 kinds,
2150 false));
2151 } else {
2152 if (wantClassFiles)
2153 fillIn(p, CLASS_PATH,
2154 fileManager.list(CLASS_PATH,
2155 packageName,
2156 classKinds,
2157 false));
2158 if (wantSourceFiles)
2159 fillIn(p, SOURCE_PATH,
2160 fileManager.list(SOURCE_PATH,
2161 packageName,
2162 sourceKinds,
2163 false));
2164 }
2165 verbosePath = false;
2166 }
2167 // where
2168 private void fillIn(PackageSymbol p,
2169 Location location,
2170 Iterable<JavaFileObject> files)
2171 {
2172 currentLoc = location;
2173 for (JavaFileObject fo : files) {
2174 switch (fo.getKind()) {
2175 case CLASS:
2176 case SOURCE: {
2177 // TODO pass binaryName to includeClassFile
2178 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2179 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2180 if (SourceVersion.isIdentifier(simpleName) ||
2181 simpleName.equals("package-info"))
2182 includeClassFile(p, fo);
2183 break;
2184 }
2185 default:
2186 extraFileActions(p, fo);
2187 }
2188 }
2189 }
2191 /** Output for "-verbose" option.
2192 * @param key The key to look up the correct internationalized string.
2193 * @param arg An argument for substitution into the output string.
2194 */
2195 private void printVerbose(String key, CharSequence arg) {
2196 Log.printLines(log.noticeWriter, Log.getLocalizedString("verbose." + key, arg));
2197 }
2199 /** Output for "-checkclassfile" option.
2200 * @param key The key to look up the correct internationalized string.
2201 * @param arg An argument for substitution into the output string.
2202 */
2203 private void printCCF(String key, Object arg) {
2204 Log.printLines(log.noticeWriter, Log.getLocalizedString(key, arg));
2205 }
2208 public interface SourceCompleter {
2209 void complete(ClassSymbol sym)
2210 throws CompletionFailure;
2211 }
2213 /**
2214 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2215 * The attribute is only the last component of the original filename, so is unlikely
2216 * to be valid as is, so operations other than those to access the name throw
2217 * UnsupportedOperationException
2218 */
2219 private static class SourceFileObject extends BaseFileObject {
2221 /** The file's name.
2222 */
2223 private Name name;
2224 private Name flatname;
2226 public SourceFileObject(Name name, Name flatname) {
2227 super(null); // no file manager; never referenced for this file object
2228 this.name = name;
2229 this.flatname = flatname;
2230 }
2232 public InputStream openInputStream() {
2233 throw new UnsupportedOperationException();
2234 }
2236 public OutputStream openOutputStream() {
2237 throw new UnsupportedOperationException();
2238 }
2240 public Reader openReader() {
2241 throw new UnsupportedOperationException();
2242 }
2244 public Writer openWriter() {
2245 throw new UnsupportedOperationException();
2246 }
2248 /** @deprecated see bug 6410637 */
2249 @Deprecated
2250 public String getName() {
2251 return name.toString();
2252 }
2254 public long getLastModified() {
2255 throw new UnsupportedOperationException();
2256 }
2258 public boolean delete() {
2259 throw new UnsupportedOperationException();
2260 }
2262 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2263 throw new UnsupportedOperationException();
2264 }
2266 @Override
2267 public boolean equals(Object other) {
2268 if (!(other instanceof SourceFileObject))
2269 return false;
2270 SourceFileObject o = (SourceFileObject) other;
2271 return name.equals(o.name);
2272 }
2274 @Override
2275 public int hashCode() {
2276 return name.hashCode();
2277 }
2279 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2280 return true; // fail-safe mode
2281 }
2283 public URI toUri() {
2284 return URI.create(name.toString());
2285 }
2287 public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
2288 throw new UnsupportedOperationException();
2289 }
2291 @Override
2292 protected String inferBinaryName(Iterable<? extends File> path) {
2293 return flatname.toString();
2294 }
2295 }
2296 }