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