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