Thu, 19 Sep 2013 20:57:37 +0100
8024437: Inferring the exception thrown: sometimes fails to compile
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.jvm;
28 import java.io.*;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.CharBuffer;
32 import java.util.Arrays;
33 import java.util.EnumSet;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Map;
37 import java.util.Set;
38 import javax.lang.model.SourceVersion;
39 import javax.tools.JavaFileObject;
40 import javax.tools.JavaFileManager;
41 import javax.tools.JavaFileManager.Location;
42 import javax.tools.StandardJavaFileManager;
44 import static javax.tools.StandardLocation.*;
46 import com.sun.tools.javac.comp.Annotate;
47 import com.sun.tools.javac.code.*;
48 import com.sun.tools.javac.code.Lint.LintCategory;
49 import com.sun.tools.javac.code.Type.*;
50 import com.sun.tools.javac.code.Symbol.*;
51 import com.sun.tools.javac.code.Symtab;
52 import com.sun.tools.javac.file.BaseFileObject;
53 import com.sun.tools.javac.util.*;
54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
56 import static com.sun.tools.javac.code.Flags.*;
57 import static com.sun.tools.javac.code.Kinds.*;
58 import static com.sun.tools.javac.code.TypeTag.CLASS;
59 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
60 import static com.sun.tools.javac.jvm.ClassFile.*;
61 import static com.sun.tools.javac.jvm.ClassFile.Version.*;
63 import static com.sun.tools.javac.main.Option.*;
65 /** This class provides operations to read a classfile into an internal
66 * representation. The internal representation is anchored in a
67 * ClassSymbol which contains in its scope symbol representations
68 * for all other definitions in the classfile. Top-level Classes themselves
69 * appear as members of the scopes of PackageSymbols.
70 *
71 * <p><b>This is NOT part of any supported API.
72 * If you write code that depends on this, you do so at your own risk.
73 * This code and its internal interfaces are subject to change or
74 * deletion without notice.</b>
75 */
76 public class ClassReader {
77 /** The context key for the class reader. */
78 protected static final Context.Key<ClassReader> classReaderKey =
79 new Context.Key<ClassReader>();
81 public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
83 Annotate annotate;
85 /** Switch: verbose output.
86 */
87 boolean verbose;
89 /** Switch: check class file for correct minor version, unrecognized
90 * attributes.
91 */
92 boolean checkClassFile;
94 /** Switch: read constant pool and code sections. This switch is initially
95 * set to false but can be turned on from outside.
96 */
97 public boolean readAllOfClassFile = false;
99 /** Switch: read GJ signature information.
100 */
101 boolean allowGenerics;
103 /** Switch: read varargs attribute.
104 */
105 boolean allowVarargs;
107 /** Switch: allow annotations.
108 */
109 boolean allowAnnotations;
111 /** Switch: allow simplified varargs.
112 */
113 boolean allowSimplifiedVarargs;
115 /** Lint option: warn about classfile issues
116 */
117 boolean lintClassfile;
119 /** Switch: allow default methods
120 */
121 boolean allowDefaultMethods;
123 /** Switch: preserve parameter names from the variable table.
124 */
125 public boolean saveParameterNames;
127 /**
128 * Switch: cache completion failures unless -XDdev is used
129 */
130 private boolean cacheCompletionFailure;
132 /**
133 * Switch: prefer source files instead of newer when both source
134 * and class are available
135 **/
136 public boolean preferSource;
138 /**
139 * The currently selected profile.
140 */
141 public final Profile profile;
143 /** The log to use for verbose output
144 */
145 final Log log;
147 /** The symbol table. */
148 Symtab syms;
150 Types types;
152 /** The name table. */
153 final Names names;
155 /** Force a completion failure on this name
156 */
157 final Name completionFailureName;
159 /** Access to files
160 */
161 private final JavaFileManager fileManager;
163 /** Factory for diagnostics
164 */
165 JCDiagnostic.Factory diagFactory;
167 /** Can be reassigned from outside:
168 * the completer to be used for ".java" files. If this remains unassigned
169 * ".java" files will not be loaded.
170 */
171 public SourceCompleter sourceCompleter = null;
173 /** A hashtable containing the encountered top-level and member classes,
174 * indexed by flat names. The table does not contain local classes.
175 */
176 private Map<Name,ClassSymbol> classes;
178 /** A hashtable containing the encountered packages.
179 */
180 private Map<Name, PackageSymbol> packages;
182 /** The current scope where type variables are entered.
183 */
184 protected Scope typevars;
186 /** The path name of the class file currently being read.
187 */
188 protected JavaFileObject currentClassFile = null;
190 /** The class or method currently being read.
191 */
192 protected Symbol currentOwner = null;
194 /** The buffer containing the currently read class file.
195 */
196 byte[] buf = new byte[INITIAL_BUFFER_SIZE];
198 /** The current input pointer.
199 */
200 protected int bp;
202 /** The objects of the constant pool.
203 */
204 Object[] poolObj;
206 /** For every constant pool entry, an index into buf where the
207 * defining section of the entry is found.
208 */
209 int[] poolIdx;
211 /** The major version number of the class file being read. */
212 int majorVersion;
213 /** The minor version number of the class file being read. */
214 int minorVersion;
216 /** A table to hold the constant pool indices for method parameter
217 * names, as given in LocalVariableTable attributes.
218 */
219 int[] parameterNameIndices;
221 /**
222 * Whether or not any parameter names have been found.
223 */
224 boolean haveParameterNameIndices;
226 /** Set this to false every time we start reading a method
227 * and are saving parameter names. Set it to true when we see
228 * MethodParameters, if it's set when we see a LocalVariableTable,
229 * then we ignore the parameter names from the LVT.
230 */
231 boolean sawMethodParameters;
233 /**
234 * The set of attribute names for which warnings have been generated for the current class
235 */
236 Set<Name> warnedAttrs = new HashSet<Name>();
238 /**
239 * Completer that delegates to the complete-method of this class.
240 */
241 private final Completer thisCompleter = new Completer() {
242 @Override
243 public void complete(Symbol sym) throws CompletionFailure {
244 ClassReader.this.complete(sym);
245 }
246 };
249 /** Get the ClassReader instance for this invocation. */
250 public static ClassReader instance(Context context) {
251 ClassReader instance = context.get(classReaderKey);
252 if (instance == null)
253 instance = new ClassReader(context, true);
254 return instance;
255 }
257 /** Initialize classes and packages, treating this as the definitive classreader. */
258 public void init(Symtab syms) {
259 init(syms, true);
260 }
262 /** Initialize classes and packages, optionally treating this as
263 * the definitive classreader.
264 */
265 private void init(Symtab syms, boolean definitive) {
266 if (classes != null) return;
268 if (definitive) {
269 Assert.check(packages == null || packages == syms.packages);
270 packages = syms.packages;
271 Assert.check(classes == null || classes == syms.classes);
272 classes = syms.classes;
273 } else {
274 packages = new HashMap<Name, PackageSymbol>();
275 classes = new HashMap<Name, ClassSymbol>();
276 }
278 packages.put(names.empty, syms.rootPackage);
279 syms.rootPackage.completer = thisCompleter;
280 syms.unnamedPackage.completer = thisCompleter;
281 }
283 /** Construct a new class reader, optionally treated as the
284 * definitive classreader for this invocation.
285 */
286 protected ClassReader(Context context, boolean definitive) {
287 if (definitive) context.put(classReaderKey, this);
289 names = Names.instance(context);
290 syms = Symtab.instance(context);
291 types = Types.instance(context);
292 fileManager = context.get(JavaFileManager.class);
293 if (fileManager == null)
294 throw new AssertionError("FileManager initialization error");
295 diagFactory = JCDiagnostic.Factory.instance(context);
297 init(syms, definitive);
298 log = Log.instance(context);
300 Options options = Options.instance(context);
301 annotate = Annotate.instance(context);
302 verbose = options.isSet(VERBOSE);
303 checkClassFile = options.isSet("-checkclassfile");
305 Source source = Source.instance(context);
306 allowGenerics = source.allowGenerics();
307 allowVarargs = source.allowVarargs();
308 allowAnnotations = source.allowAnnotations();
309 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
310 allowDefaultMethods = source.allowDefaultMethods();
312 saveParameterNames = options.isSet("save-parameter-names");
313 cacheCompletionFailure = options.isUnset("dev");
314 preferSource = "source".equals(options.get("-Xprefer"));
316 profile = Profile.instance(context);
318 completionFailureName =
319 options.isSet("failcomplete")
320 ? names.fromString(options.get("failcomplete"))
321 : null;
323 typevars = new Scope(syms.noSymbol);
325 lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
327 initAttributeReaders();
328 }
330 /** Add member to class unless it is synthetic.
331 */
332 private void enterMember(ClassSymbol c, Symbol sym) {
333 // Synthetic members are not entered -- reason lost to history (optimization?).
334 // Lambda methods must be entered because they may have inner classes (which reference them)
335 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
336 c.members_field.enter(sym);
337 }
339 /************************************************************************
340 * Error Diagnoses
341 ***********************************************************************/
344 public class BadClassFile extends CompletionFailure {
345 private static final long serialVersionUID = 0;
347 public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
348 super(sym, createBadClassFileDiagnostic(file, diag));
349 }
350 }
351 // where
352 private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
353 String key = (file.getKind() == JavaFileObject.Kind.SOURCE
354 ? "bad.source.file.header" : "bad.class.file.header");
355 return diagFactory.fragment(key, file, diag);
356 }
358 public BadClassFile badClassFile(String key, Object... args) {
359 return new BadClassFile (
360 currentOwner.enclClass(),
361 currentClassFile,
362 diagFactory.fragment(key, args));
363 }
365 /************************************************************************
366 * Buffer Access
367 ***********************************************************************/
369 /** Read a character.
370 */
371 char nextChar() {
372 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
373 }
375 /** Read a byte.
376 */
377 int nextByte() {
378 return buf[bp++] & 0xFF;
379 }
381 /** Read an integer.
382 */
383 int nextInt() {
384 return
385 ((buf[bp++] & 0xFF) << 24) +
386 ((buf[bp++] & 0xFF) << 16) +
387 ((buf[bp++] & 0xFF) << 8) +
388 (buf[bp++] & 0xFF);
389 }
391 /** Extract a character at position bp from buf.
392 */
393 char getChar(int bp) {
394 return
395 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
396 }
398 /** Extract an integer at position bp from buf.
399 */
400 int getInt(int bp) {
401 return
402 ((buf[bp] & 0xFF) << 24) +
403 ((buf[bp+1] & 0xFF) << 16) +
404 ((buf[bp+2] & 0xFF) << 8) +
405 (buf[bp+3] & 0xFF);
406 }
409 /** Extract a long integer at position bp from buf.
410 */
411 long getLong(int bp) {
412 DataInputStream bufin =
413 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
414 try {
415 return bufin.readLong();
416 } catch (IOException e) {
417 throw new AssertionError(e);
418 }
419 }
421 /** Extract a float at position bp from buf.
422 */
423 float getFloat(int bp) {
424 DataInputStream bufin =
425 new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
426 try {
427 return bufin.readFloat();
428 } catch (IOException e) {
429 throw new AssertionError(e);
430 }
431 }
433 /** Extract a double at position bp from buf.
434 */
435 double getDouble(int bp) {
436 DataInputStream bufin =
437 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
438 try {
439 return bufin.readDouble();
440 } catch (IOException e) {
441 throw new AssertionError(e);
442 }
443 }
445 /************************************************************************
446 * Constant Pool Access
447 ***********************************************************************/
449 /** Index all constant pool entries, writing their start addresses into
450 * poolIdx.
451 */
452 void indexPool() {
453 poolIdx = new int[nextChar()];
454 poolObj = new Object[poolIdx.length];
455 int i = 1;
456 while (i < poolIdx.length) {
457 poolIdx[i++] = bp;
458 byte tag = buf[bp++];
459 switch (tag) {
460 case CONSTANT_Utf8: case CONSTANT_Unicode: {
461 int len = nextChar();
462 bp = bp + len;
463 break;
464 }
465 case CONSTANT_Class:
466 case CONSTANT_String:
467 case CONSTANT_MethodType:
468 bp = bp + 2;
469 break;
470 case CONSTANT_MethodHandle:
471 bp = bp + 3;
472 break;
473 case CONSTANT_Fieldref:
474 case CONSTANT_Methodref:
475 case CONSTANT_InterfaceMethodref:
476 case CONSTANT_NameandType:
477 case CONSTANT_Integer:
478 case CONSTANT_Float:
479 case CONSTANT_InvokeDynamic:
480 bp = bp + 4;
481 break;
482 case CONSTANT_Long:
483 case CONSTANT_Double:
484 bp = bp + 8;
485 i++;
486 break;
487 default:
488 throw badClassFile("bad.const.pool.tag.at",
489 Byte.toString(tag),
490 Integer.toString(bp -1));
491 }
492 }
493 }
495 /** Read constant pool entry at start address i, use pool as a cache.
496 */
497 Object readPool(int i) {
498 Object result = poolObj[i];
499 if (result != null) return result;
501 int index = poolIdx[i];
502 if (index == 0) return null;
504 byte tag = buf[index];
505 switch (tag) {
506 case CONSTANT_Utf8:
507 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
508 break;
509 case CONSTANT_Unicode:
510 throw badClassFile("unicode.str.not.supported");
511 case CONSTANT_Class:
512 poolObj[i] = readClassOrType(getChar(index + 1));
513 break;
514 case CONSTANT_String:
515 // FIXME: (footprint) do not use toString here
516 poolObj[i] = readName(getChar(index + 1)).toString();
517 break;
518 case CONSTANT_Fieldref: {
519 ClassSymbol owner = readClassSymbol(getChar(index + 1));
520 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
521 poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
522 break;
523 }
524 case CONSTANT_Methodref:
525 case CONSTANT_InterfaceMethodref: {
526 ClassSymbol owner = readClassSymbol(getChar(index + 1));
527 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
528 poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
529 break;
530 }
531 case CONSTANT_NameandType:
532 poolObj[i] = new NameAndType(
533 readName(getChar(index + 1)),
534 readType(getChar(index + 3)), types);
535 break;
536 case CONSTANT_Integer:
537 poolObj[i] = getInt(index + 1);
538 break;
539 case CONSTANT_Float:
540 poolObj[i] = new Float(getFloat(index + 1));
541 break;
542 case CONSTANT_Long:
543 poolObj[i] = new Long(getLong(index + 1));
544 break;
545 case CONSTANT_Double:
546 poolObj[i] = new Double(getDouble(index + 1));
547 break;
548 case CONSTANT_MethodHandle:
549 skipBytes(4);
550 break;
551 case CONSTANT_MethodType:
552 skipBytes(3);
553 break;
554 case CONSTANT_InvokeDynamic:
555 skipBytes(5);
556 break;
557 default:
558 throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
559 }
560 return poolObj[i];
561 }
563 /** Read signature and convert to type.
564 */
565 Type readType(int i) {
566 int index = poolIdx[i];
567 return sigToType(buf, index + 3, getChar(index + 1));
568 }
570 /** If name is an array type or class signature, return the
571 * corresponding type; otherwise return a ClassSymbol with given name.
572 */
573 Object readClassOrType(int i) {
574 int index = poolIdx[i];
575 int len = getChar(index + 1);
576 int start = index + 3;
577 Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
578 // by the above assertion, the following test can be
579 // simplified to (buf[start] == '[')
580 return (buf[start] == '[' || buf[start + len - 1] == ';')
581 ? (Object)sigToType(buf, start, len)
582 : (Object)enterClass(names.fromUtf(internalize(buf, start,
583 len)));
584 }
586 /** Read signature and convert to type parameters.
587 */
588 List<Type> readTypeParams(int i) {
589 int index = poolIdx[i];
590 return sigToTypeParams(buf, index + 3, getChar(index + 1));
591 }
593 /** Read class entry.
594 */
595 ClassSymbol readClassSymbol(int i) {
596 return (ClassSymbol) (readPool(i));
597 }
599 /** Read name.
600 */
601 Name readName(int i) {
602 return (Name) (readPool(i));
603 }
605 /************************************************************************
606 * Reading Types
607 ***********************************************************************/
609 /** The unread portion of the currently read type is
610 * signature[sigp..siglimit-1].
611 */
612 byte[] signature;
613 int sigp;
614 int siglimit;
615 boolean sigEnterPhase = false;
617 /** Convert signature to type, where signature is a byte array segment.
618 */
619 Type sigToType(byte[] sig, int offset, int len) {
620 signature = sig;
621 sigp = offset;
622 siglimit = offset + len;
623 return sigToType();
624 }
626 /** Convert signature to type, where signature is implicit.
627 */
628 Type sigToType() {
629 switch ((char) signature[sigp]) {
630 case 'T':
631 sigp++;
632 int start = sigp;
633 while (signature[sigp] != ';') sigp++;
634 sigp++;
635 return sigEnterPhase
636 ? Type.noType
637 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
638 case '+': {
639 sigp++;
640 Type t = sigToType();
641 return new WildcardType(t, BoundKind.EXTENDS,
642 syms.boundClass);
643 }
644 case '*':
645 sigp++;
646 return new WildcardType(syms.objectType, BoundKind.UNBOUND,
647 syms.boundClass);
648 case '-': {
649 sigp++;
650 Type t = sigToType();
651 return new WildcardType(t, BoundKind.SUPER,
652 syms.boundClass);
653 }
654 case 'B':
655 sigp++;
656 return syms.byteType;
657 case 'C':
658 sigp++;
659 return syms.charType;
660 case 'D':
661 sigp++;
662 return syms.doubleType;
663 case 'F':
664 sigp++;
665 return syms.floatType;
666 case 'I':
667 sigp++;
668 return syms.intType;
669 case 'J':
670 sigp++;
671 return syms.longType;
672 case 'L':
673 {
674 // int oldsigp = sigp;
675 Type t = classSigToType();
676 if (sigp < siglimit && signature[sigp] == '.')
677 throw badClassFile("deprecated inner class signature syntax " +
678 "(please recompile from source)");
679 /*
680 System.err.println(" decoded " +
681 new String(signature, oldsigp, sigp-oldsigp) +
682 " => " + t + " outer " + t.outer());
683 */
684 return t;
685 }
686 case 'S':
687 sigp++;
688 return syms.shortType;
689 case 'V':
690 sigp++;
691 return syms.voidType;
692 case 'Z':
693 sigp++;
694 return syms.booleanType;
695 case '[':
696 sigp++;
697 return new ArrayType(sigToType(), syms.arrayClass);
698 case '(':
699 sigp++;
700 List<Type> argtypes = sigToTypes(')');
701 Type restype = sigToType();
702 List<Type> thrown = List.nil();
703 while (signature[sigp] == '^') {
704 sigp++;
705 thrown = thrown.prepend(sigToType());
706 }
707 // if there is a typevar in the throws clause we should state it.
708 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
709 if (l.head.hasTag(TYPEVAR)) {
710 l.head.tsym.flags_field |= THROWS;
711 }
712 }
713 return new MethodType(argtypes,
714 restype,
715 thrown.reverse(),
716 syms.methodClass);
717 case '<':
718 typevars = typevars.dup(currentOwner);
719 Type poly = new ForAll(sigToTypeParams(), sigToType());
720 typevars = typevars.leave();
721 return poly;
722 default:
723 throw badClassFile("bad.signature",
724 Convert.utf2string(signature, sigp, 10));
725 }
726 }
728 byte[] signatureBuffer = new byte[0];
729 int sbp = 0;
730 /** Convert class signature to type, where signature is implicit.
731 */
732 Type classSigToType() {
733 if (signature[sigp] != 'L')
734 throw badClassFile("bad.class.signature",
735 Convert.utf2string(signature, sigp, 10));
736 sigp++;
737 Type outer = Type.noType;
738 int startSbp = sbp;
740 while (true) {
741 final byte c = signature[sigp++];
742 switch (c) {
744 case ';': { // end
745 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
746 startSbp,
747 sbp - startSbp));
749 try {
750 return (outer == Type.noType) ?
751 t.erasure(types) :
752 new ClassType(outer, List.<Type>nil(), t);
753 } finally {
754 sbp = startSbp;
755 }
756 }
758 case '<': // generic arguments
759 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
760 startSbp,
761 sbp - startSbp));
762 outer = new ClassType(outer, sigToTypes('>'), t) {
763 boolean completed = false;
764 @Override
765 public Type getEnclosingType() {
766 if (!completed) {
767 completed = true;
768 tsym.complete();
769 Type enclosingType = tsym.type.getEnclosingType();
770 if (enclosingType != Type.noType) {
771 List<Type> typeArgs =
772 super.getEnclosingType().allparams();
773 List<Type> typeParams =
774 enclosingType.allparams();
775 if (typeParams.length() != typeArgs.length()) {
776 // no "rare" types
777 super.setEnclosingType(types.erasure(enclosingType));
778 } else {
779 super.setEnclosingType(types.subst(enclosingType,
780 typeParams,
781 typeArgs));
782 }
783 } else {
784 super.setEnclosingType(Type.noType);
785 }
786 }
787 return super.getEnclosingType();
788 }
789 @Override
790 public void setEnclosingType(Type outer) {
791 throw new UnsupportedOperationException();
792 }
793 };
794 switch (signature[sigp++]) {
795 case ';':
796 if (sigp < signature.length && signature[sigp] == '.') {
797 // support old-style GJC signatures
798 // The signature produced was
799 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
800 // rather than say
801 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
802 // so we skip past ".Lfoo/Outer$"
803 sigp += (sbp - startSbp) + // "foo/Outer"
804 3; // ".L" and "$"
805 signatureBuffer[sbp++] = (byte)'$';
806 break;
807 } else {
808 sbp = startSbp;
809 return outer;
810 }
811 case '.':
812 signatureBuffer[sbp++] = (byte)'$';
813 break;
814 default:
815 throw new AssertionError(signature[sigp-1]);
816 }
817 continue;
819 case '.':
820 //we have seen an enclosing non-generic class
821 if (outer != Type.noType) {
822 t = enterClass(names.fromUtf(signatureBuffer,
823 startSbp,
824 sbp - startSbp));
825 outer = new ClassType(outer, List.<Type>nil(), t);
826 }
827 signatureBuffer[sbp++] = (byte)'$';
828 continue;
829 case '/':
830 signatureBuffer[sbp++] = (byte)'.';
831 continue;
832 default:
833 signatureBuffer[sbp++] = c;
834 continue;
835 }
836 }
837 }
839 /** Convert (implicit) signature to list of types
840 * until `terminator' is encountered.
841 */
842 List<Type> sigToTypes(char terminator) {
843 List<Type> head = List.of(null);
844 List<Type> tail = head;
845 while (signature[sigp] != terminator)
846 tail = tail.setTail(List.of(sigToType()));
847 sigp++;
848 return head.tail;
849 }
851 /** Convert signature to type parameters, where signature is a byte
852 * array segment.
853 */
854 List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
855 signature = sig;
856 sigp = offset;
857 siglimit = offset + len;
858 return sigToTypeParams();
859 }
861 /** Convert signature to type parameters, where signature is implicit.
862 */
863 List<Type> sigToTypeParams() {
864 List<Type> tvars = List.nil();
865 if (signature[sigp] == '<') {
866 sigp++;
867 int start = sigp;
868 sigEnterPhase = true;
869 while (signature[sigp] != '>')
870 tvars = tvars.prepend(sigToTypeParam());
871 sigEnterPhase = false;
872 sigp = start;
873 while (signature[sigp] != '>')
874 sigToTypeParam();
875 sigp++;
876 }
877 return tvars.reverse();
878 }
880 /** Convert (implicit) signature to type parameter.
881 */
882 Type sigToTypeParam() {
883 int start = sigp;
884 while (signature[sigp] != ':') sigp++;
885 Name name = names.fromUtf(signature, start, sigp - start);
886 TypeVar tvar;
887 if (sigEnterPhase) {
888 tvar = new TypeVar(name, currentOwner, syms.botType);
889 typevars.enter(tvar.tsym);
890 } else {
891 tvar = (TypeVar)findTypeVar(name);
892 }
893 List<Type> bounds = List.nil();
894 boolean allInterfaces = false;
895 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
896 sigp++;
897 allInterfaces = true;
898 }
899 while (signature[sigp] == ':') {
900 sigp++;
901 bounds = bounds.prepend(sigToType());
902 }
903 if (!sigEnterPhase) {
904 types.setBounds(tvar, bounds.reverse(), allInterfaces);
905 }
906 return tvar;
907 }
909 /** Find type variable with given name in `typevars' scope.
910 */
911 Type findTypeVar(Name name) {
912 Scope.Entry e = typevars.lookup(name);
913 if (e.scope != null) {
914 return e.sym.type;
915 } else {
916 if (readingClassAttr) {
917 // While reading the class attribute, the supertypes
918 // might refer to a type variable from an enclosing element
919 // (method or class).
920 // If the type variable is defined in the enclosing class,
921 // we can actually find it in
922 // currentOwner.owner.type.getTypeArguments()
923 // However, until we have read the enclosing method attribute
924 // we don't know for sure if this owner is correct. It could
925 // be a method and there is no way to tell before reading the
926 // enclosing method attribute.
927 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
928 missingTypeVariables = missingTypeVariables.prepend(t);
929 // System.err.println("Missing type var " + name);
930 return t;
931 }
932 throw badClassFile("undecl.type.var", name);
933 }
934 }
936 /************************************************************************
937 * Reading Attributes
938 ***********************************************************************/
940 protected enum AttributeKind { CLASS, MEMBER };
941 protected abstract class AttributeReader {
942 protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
943 this.name = name;
944 this.version = version;
945 this.kinds = kinds;
946 }
948 protected boolean accepts(AttributeKind kind) {
949 if (kinds.contains(kind)) {
950 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
951 return true;
953 if (lintClassfile && !warnedAttrs.contains(name)) {
954 JavaFileObject prev = log.useSource(currentClassFile);
955 try {
956 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
957 name, version.major, version.minor, majorVersion, minorVersion);
958 } finally {
959 log.useSource(prev);
960 }
961 warnedAttrs.add(name);
962 }
963 }
964 return false;
965 }
967 protected abstract void read(Symbol sym, int attrLen);
969 protected final Name name;
970 protected final ClassFile.Version version;
971 protected final Set<AttributeKind> kinds;
972 }
974 protected Set<AttributeKind> CLASS_ATTRIBUTE =
975 EnumSet.of(AttributeKind.CLASS);
976 protected Set<AttributeKind> MEMBER_ATTRIBUTE =
977 EnumSet.of(AttributeKind.MEMBER);
978 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
979 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
981 protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
983 private void initAttributeReaders() {
984 AttributeReader[] readers = {
985 // v45.3 attributes
987 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
988 protected void read(Symbol sym, int attrLen) {
989 if (readAllOfClassFile || saveParameterNames)
990 ((MethodSymbol)sym).code = readCode(sym);
991 else
992 bp = bp + attrLen;
993 }
994 },
996 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
997 protected void read(Symbol sym, int attrLen) {
998 Object v = readPool(nextChar());
999 // Ignore ConstantValue attribute if field not final.
1000 if ((sym.flags() & FINAL) != 0)
1001 ((VarSymbol) sym).setData(v);
1002 }
1003 },
1005 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1006 protected void read(Symbol sym, int attrLen) {
1007 sym.flags_field |= DEPRECATED;
1008 }
1009 },
1011 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1012 protected void read(Symbol sym, int attrLen) {
1013 int nexceptions = nextChar();
1014 List<Type> thrown = List.nil();
1015 for (int j = 0; j < nexceptions; j++)
1016 thrown = thrown.prepend(readClassSymbol(nextChar()).type);
1017 if (sym.type.getThrownTypes().isEmpty())
1018 sym.type.asMethodType().thrown = thrown.reverse();
1019 }
1020 },
1022 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
1023 protected void read(Symbol sym, int attrLen) {
1024 ClassSymbol c = (ClassSymbol) sym;
1025 readInnerClasses(c);
1026 }
1027 },
1029 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1030 protected void read(Symbol sym, int attrLen) {
1031 int newbp = bp + attrLen;
1032 if (saveParameterNames && !sawMethodParameters) {
1033 // Pick up parameter names from the variable table.
1034 // Parameter names are not explicitly identified as such,
1035 // but all parameter name entries in the LocalVariableTable
1036 // have a start_pc of 0. Therefore, we record the name
1037 // indicies of all slots with a start_pc of zero in the
1038 // parameterNameIndicies array.
1039 // Note that this implicitly honors the JVMS spec that
1040 // there may be more than one LocalVariableTable, and that
1041 // there is no specified ordering for the entries.
1042 int numEntries = nextChar();
1043 for (int i = 0; i < numEntries; i++) {
1044 int start_pc = nextChar();
1045 int length = nextChar();
1046 int nameIndex = nextChar();
1047 int sigIndex = nextChar();
1048 int register = nextChar();
1049 if (start_pc == 0) {
1050 // ensure array large enough
1051 if (register >= parameterNameIndices.length) {
1052 int newSize = Math.max(register, parameterNameIndices.length + 8);
1053 parameterNameIndices =
1054 Arrays.copyOf(parameterNameIndices, newSize);
1055 }
1056 parameterNameIndices[register] = nameIndex;
1057 haveParameterNameIndices = true;
1058 }
1059 }
1060 }
1061 bp = newbp;
1062 }
1063 },
1065 new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
1066 protected void read(Symbol sym, int attrlen) {
1067 int newbp = bp + attrlen;
1068 if (saveParameterNames) {
1069 sawMethodParameters = true;
1070 int numEntries = nextByte();
1071 parameterNameIndices = new int[numEntries];
1072 haveParameterNameIndices = true;
1073 for (int i = 0; i < numEntries; i++) {
1074 int nameIndex = nextChar();
1075 int flags = nextChar();
1076 parameterNameIndices[i] = nameIndex;
1077 }
1078 }
1079 bp = newbp;
1080 }
1081 },
1084 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
1085 protected void read(Symbol sym, int attrLen) {
1086 ClassSymbol c = (ClassSymbol) sym;
1087 Name n = readName(nextChar());
1088 c.sourcefile = new SourceFileObject(n, c.flatname);
1089 // If the class is a toplevel class, originating from a Java source file,
1090 // but the class name does not match the file name, then it is
1091 // an auxiliary class.
1092 String sn = n.toString();
1093 if (c.owner.kind == Kinds.PCK &&
1094 sn.endsWith(".java") &&
1095 !sn.equals(c.name.toString()+".java")) {
1096 c.flags_field |= AUXILIARY;
1097 }
1098 }
1099 },
1101 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1102 protected void read(Symbol sym, int attrLen) {
1103 // bridge methods are visible when generics not enabled
1104 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
1105 sym.flags_field |= SYNTHETIC;
1106 }
1107 },
1109 // standard v49 attributes
1111 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1112 protected void read(Symbol sym, int attrLen) {
1113 int newbp = bp + attrLen;
1114 readEnclosingMethodAttr(sym);
1115 bp = newbp;
1116 }
1117 },
1119 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1120 @Override
1121 protected boolean accepts(AttributeKind kind) {
1122 return super.accepts(kind) && allowGenerics;
1123 }
1125 protected void read(Symbol sym, int attrLen) {
1126 if (sym.kind == TYP) {
1127 ClassSymbol c = (ClassSymbol) sym;
1128 readingClassAttr = true;
1129 try {
1130 ClassType ct1 = (ClassType)c.type;
1131 Assert.check(c == currentOwner);
1132 ct1.typarams_field = readTypeParams(nextChar());
1133 ct1.supertype_field = sigToType();
1134 ListBuffer<Type> is = new ListBuffer<Type>();
1135 while (sigp != siglimit) is.append(sigToType());
1136 ct1.interfaces_field = is.toList();
1137 } finally {
1138 readingClassAttr = false;
1139 }
1140 } else {
1141 List<Type> thrown = sym.type.getThrownTypes();
1142 sym.type = readType(nextChar());
1143 //- System.err.println(" # " + sym.type);
1144 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1145 sym.type.asMethodType().thrown = thrown;
1147 }
1148 }
1149 },
1151 // v49 annotation attributes
1153 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1154 protected void read(Symbol sym, int attrLen) {
1155 attachAnnotationDefault(sym);
1156 }
1157 },
1159 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1160 protected void read(Symbol sym, int attrLen) {
1161 attachAnnotations(sym);
1162 }
1163 },
1165 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1166 protected void read(Symbol sym, int attrLen) {
1167 attachParameterAnnotations(sym);
1168 }
1169 },
1171 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1172 protected void read(Symbol sym, int attrLen) {
1173 attachAnnotations(sym);
1174 }
1175 },
1177 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1178 protected void read(Symbol sym, int attrLen) {
1179 attachParameterAnnotations(sym);
1180 }
1181 },
1183 // additional "legacy" v49 attributes, superceded by flags
1185 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1186 protected void read(Symbol sym, int attrLen) {
1187 if (allowAnnotations)
1188 sym.flags_field |= ANNOTATION;
1189 }
1190 },
1192 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1193 protected void read(Symbol sym, int attrLen) {
1194 sym.flags_field |= BRIDGE;
1195 if (!allowGenerics)
1196 sym.flags_field &= ~SYNTHETIC;
1197 }
1198 },
1200 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1201 protected void read(Symbol sym, int attrLen) {
1202 sym.flags_field |= ENUM;
1203 }
1204 },
1206 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1207 protected void read(Symbol sym, int attrLen) {
1208 if (allowVarargs)
1209 sym.flags_field |= VARARGS;
1210 }
1211 },
1213 new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1214 protected void read(Symbol sym, int attrLen) {
1215 attachTypeAnnotations(sym);
1216 }
1217 },
1219 new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1220 protected void read(Symbol sym, int attrLen) {
1221 attachTypeAnnotations(sym);
1222 }
1223 },
1226 // The following attributes for a Code attribute are not currently handled
1227 // StackMapTable
1228 // SourceDebugExtension
1229 // LineNumberTable
1230 // LocalVariableTypeTable
1231 };
1233 for (AttributeReader r: readers)
1234 attributeReaders.put(r.name, r);
1235 }
1237 /** Report unrecognized attribute.
1238 */
1239 void unrecognized(Name attrName) {
1240 if (checkClassFile)
1241 printCCF("ccf.unrecognized.attribute", attrName);
1242 }
1246 protected void readEnclosingMethodAttr(Symbol sym) {
1247 // sym is a nested class with an "Enclosing Method" attribute
1248 // remove sym from it's current owners scope and place it in
1249 // the scope specified by the attribute
1250 sym.owner.members().remove(sym);
1251 ClassSymbol self = (ClassSymbol)sym;
1252 ClassSymbol c = readClassSymbol(nextChar());
1253 NameAndType nt = (NameAndType)readPool(nextChar());
1255 if (c.members_field == null)
1256 throw badClassFile("bad.enclosing.class", self, c);
1258 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1259 if (nt != null && m == null)
1260 throw badClassFile("bad.enclosing.method", self);
1262 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1263 self.owner = m != null ? m : c;
1264 if (self.name.isEmpty())
1265 self.fullname = names.empty;
1266 else
1267 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1269 if (m != null) {
1270 ((ClassType)sym.type).setEnclosingType(m.type);
1271 } else if ((self.flags_field & STATIC) == 0) {
1272 ((ClassType)sym.type).setEnclosingType(c.type);
1273 } else {
1274 ((ClassType)sym.type).setEnclosingType(Type.noType);
1275 }
1276 enterTypevars(self);
1277 if (!missingTypeVariables.isEmpty()) {
1278 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1279 for (Type typevar : missingTypeVariables) {
1280 typeVars.append(findTypeVar(typevar.tsym.name));
1281 }
1282 foundTypeVariables = typeVars.toList();
1283 } else {
1284 foundTypeVariables = List.nil();
1285 }
1286 }
1288 // See java.lang.Class
1289 private Name simpleBinaryName(Name self, Name enclosing) {
1290 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1291 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1292 throw badClassFile("bad.enclosing.method", self);
1293 int index = 1;
1294 while (index < simpleBinaryName.length() &&
1295 isAsciiDigit(simpleBinaryName.charAt(index)))
1296 index++;
1297 return names.fromString(simpleBinaryName.substring(index));
1298 }
1300 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1301 if (nt == null)
1302 return null;
1304 MethodType type = nt.uniqueType.type.asMethodType();
1306 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1307 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1308 return (MethodSymbol)e.sym;
1310 if (nt.name != names.init)
1311 // not a constructor
1312 return null;
1313 if ((flags & INTERFACE) != 0)
1314 // no enclosing instance
1315 return null;
1316 if (nt.uniqueType.type.getParameterTypes().isEmpty())
1317 // no parameters
1318 return null;
1320 // A constructor of an inner class.
1321 // Remove the first argument (the enclosing instance)
1322 nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
1323 nt.uniqueType.type.getReturnType(),
1324 nt.uniqueType.type.getThrownTypes(),
1325 syms.methodClass));
1326 // Try searching again
1327 return findMethod(nt, scope, flags);
1328 }
1330 /** Similar to Types.isSameType but avoids completion */
1331 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1332 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1333 .prepend(types.erasure(mt1.getReturnType()));
1334 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1335 while (!types1.isEmpty() && !types2.isEmpty()) {
1336 if (types1.head.tsym != types2.head.tsym)
1337 return false;
1338 types1 = types1.tail;
1339 types2 = types2.tail;
1340 }
1341 return types1.isEmpty() && types2.isEmpty();
1342 }
1344 /**
1345 * Character.isDigit answers <tt>true</tt> to some non-ascii
1346 * digits. This one does not. <b>copied from java.lang.Class</b>
1347 */
1348 private static boolean isAsciiDigit(char c) {
1349 return '0' <= c && c <= '9';
1350 }
1352 /** Read member attributes.
1353 */
1354 void readMemberAttrs(Symbol sym) {
1355 readAttrs(sym, AttributeKind.MEMBER);
1356 }
1358 void readAttrs(Symbol sym, AttributeKind kind) {
1359 char ac = nextChar();
1360 for (int i = 0; i < ac; i++) {
1361 Name attrName = readName(nextChar());
1362 int attrLen = nextInt();
1363 AttributeReader r = attributeReaders.get(attrName);
1364 if (r != null && r.accepts(kind))
1365 r.read(sym, attrLen);
1366 else {
1367 unrecognized(attrName);
1368 bp = bp + attrLen;
1369 }
1370 }
1371 }
1373 private boolean readingClassAttr = false;
1374 private List<Type> missingTypeVariables = List.nil();
1375 private List<Type> foundTypeVariables = List.nil();
1377 /** Read class attributes.
1378 */
1379 void readClassAttrs(ClassSymbol c) {
1380 readAttrs(c, AttributeKind.CLASS);
1381 }
1383 /** Read code block.
1384 */
1385 Code readCode(Symbol owner) {
1386 nextChar(); // max_stack
1387 nextChar(); // max_locals
1388 final int code_length = nextInt();
1389 bp += code_length;
1390 final char exception_table_length = nextChar();
1391 bp += exception_table_length * 8;
1392 readMemberAttrs(owner);
1393 return null;
1394 }
1396 /************************************************************************
1397 * Reading Java-language annotations
1398 ***********************************************************************/
1400 /** Attach annotations.
1401 */
1402 void attachAnnotations(final Symbol sym) {
1403 int numAttributes = nextChar();
1404 if (numAttributes != 0) {
1405 ListBuffer<CompoundAnnotationProxy> proxies =
1406 new ListBuffer<CompoundAnnotationProxy>();
1407 for (int i = 0; i<numAttributes; i++) {
1408 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1409 if (proxy.type.tsym == syms.proprietaryType.tsym)
1410 sym.flags_field |= PROPRIETARY;
1411 else if (proxy.type.tsym == syms.profileType.tsym) {
1412 if (profile != Profile.DEFAULT) {
1413 for (Pair<Name,Attribute> v: proxy.values) {
1414 if (v.fst == names.value && v.snd instanceof Attribute.Constant) {
1415 Attribute.Constant c = (Attribute.Constant) v.snd;
1416 if (c.type == syms.intType && ((Integer) c.value) > profile.value) {
1417 sym.flags_field |= NOT_IN_PROFILE;
1418 }
1419 }
1420 }
1421 }
1422 } else
1423 proxies.append(proxy);
1424 }
1425 annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1426 }
1427 }
1429 /** Attach parameter annotations.
1430 */
1431 void attachParameterAnnotations(final Symbol method) {
1432 final MethodSymbol meth = (MethodSymbol)method;
1433 int numParameters = buf[bp++] & 0xFF;
1434 List<VarSymbol> parameters = meth.params();
1435 int pnum = 0;
1436 while (parameters.tail != null) {
1437 attachAnnotations(parameters.head);
1438 parameters = parameters.tail;
1439 pnum++;
1440 }
1441 if (pnum != numParameters) {
1442 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1443 }
1444 }
1446 void attachTypeAnnotations(final Symbol sym) {
1447 int numAttributes = nextChar();
1448 if (numAttributes != 0) {
1449 ListBuffer<TypeAnnotationProxy> proxies =
1450 ListBuffer.lb();
1451 for (int i = 0; i < numAttributes; i++)
1452 proxies.append(readTypeAnnotation());
1453 annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
1454 }
1455 }
1457 /** Attach the default value for an annotation element.
1458 */
1459 void attachAnnotationDefault(final Symbol sym) {
1460 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1461 final Attribute value = readAttributeValue();
1463 // The default value is set later during annotation. It might
1464 // be the case that the Symbol sym is annotated _after_ the
1465 // repeating instances that depend on this default value,
1466 // because of this we set an interim value that tells us this
1467 // element (most likely) has a default.
1468 //
1469 // Set interim value for now, reset just before we do this
1470 // properly at annotate time.
1471 meth.defaultValue = value;
1472 annotate.normal(new AnnotationDefaultCompleter(meth, value));
1473 }
1475 Type readTypeOrClassSymbol(int i) {
1476 // support preliminary jsr175-format class files
1477 if (buf[poolIdx[i]] == CONSTANT_Class)
1478 return readClassSymbol(i).type;
1479 return readType(i);
1480 }
1481 Type readEnumType(int i) {
1482 // support preliminary jsr175-format class files
1483 int index = poolIdx[i];
1484 int length = getChar(index + 1);
1485 if (buf[index + length + 2] != ';')
1486 return enterClass(readName(i)).type;
1487 return readType(i);
1488 }
1490 CompoundAnnotationProxy readCompoundAnnotation() {
1491 Type t = readTypeOrClassSymbol(nextChar());
1492 int numFields = nextChar();
1493 ListBuffer<Pair<Name,Attribute>> pairs =
1494 new ListBuffer<Pair<Name,Attribute>>();
1495 for (int i=0; i<numFields; i++) {
1496 Name name = readName(nextChar());
1497 Attribute value = readAttributeValue();
1498 pairs.append(new Pair<Name,Attribute>(name, value));
1499 }
1500 return new CompoundAnnotationProxy(t, pairs.toList());
1501 }
1503 TypeAnnotationProxy readTypeAnnotation() {
1504 TypeAnnotationPosition position = readPosition();
1505 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1507 return new TypeAnnotationProxy(proxy, position);
1508 }
1510 TypeAnnotationPosition readPosition() {
1511 int tag = nextByte(); // TargetType tag is a byte
1513 if (!TargetType.isValidTargetTypeValue(tag))
1514 throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
1516 TypeAnnotationPosition position = new TypeAnnotationPosition();
1517 TargetType type = TargetType.fromTargetTypeValue(tag);
1519 position.type = type;
1521 switch (type) {
1522 // instanceof
1523 case INSTANCEOF:
1524 // new expression
1525 case NEW:
1526 // constructor/method reference receiver
1527 case CONSTRUCTOR_REFERENCE:
1528 case METHOD_REFERENCE:
1529 position.offset = nextChar();
1530 break;
1531 // local variable
1532 case LOCAL_VARIABLE:
1533 // resource variable
1534 case RESOURCE_VARIABLE:
1535 int table_length = nextChar();
1536 position.lvarOffset = new int[table_length];
1537 position.lvarLength = new int[table_length];
1538 position.lvarIndex = new int[table_length];
1540 for (int i = 0; i < table_length; ++i) {
1541 position.lvarOffset[i] = nextChar();
1542 position.lvarLength[i] = nextChar();
1543 position.lvarIndex[i] = nextChar();
1544 }
1545 break;
1546 // exception parameter
1547 case EXCEPTION_PARAMETER:
1548 position.exception_index = nextChar();
1549 break;
1550 // method receiver
1551 case METHOD_RECEIVER:
1552 // Do nothing
1553 break;
1554 // type parameter
1555 case CLASS_TYPE_PARAMETER:
1556 case METHOD_TYPE_PARAMETER:
1557 position.parameter_index = nextByte();
1558 break;
1559 // type parameter bound
1560 case CLASS_TYPE_PARAMETER_BOUND:
1561 case METHOD_TYPE_PARAMETER_BOUND:
1562 position.parameter_index = nextByte();
1563 position.bound_index = nextByte();
1564 break;
1565 // class extends or implements clause
1566 case CLASS_EXTENDS:
1567 position.type_index = nextChar();
1568 break;
1569 // throws
1570 case THROWS:
1571 position.type_index = nextChar();
1572 break;
1573 // method parameter
1574 case METHOD_FORMAL_PARAMETER:
1575 position.parameter_index = nextByte();
1576 break;
1577 // type cast
1578 case CAST:
1579 // method/constructor/reference type argument
1580 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
1581 case METHOD_INVOCATION_TYPE_ARGUMENT:
1582 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
1583 case METHOD_REFERENCE_TYPE_ARGUMENT:
1584 position.offset = nextChar();
1585 position.type_index = nextByte();
1586 break;
1587 // We don't need to worry about these
1588 case METHOD_RETURN:
1589 case FIELD:
1590 break;
1591 case UNKNOWN:
1592 throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
1593 default:
1594 throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
1595 }
1597 { // See whether there is location info and read it
1598 int len = nextByte();
1599 ListBuffer<Integer> loc = ListBuffer.lb();
1600 for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
1601 loc = loc.append(nextByte());
1602 position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
1603 }
1605 return position;
1606 }
1608 Attribute readAttributeValue() {
1609 char c = (char) buf[bp++];
1610 switch (c) {
1611 case 'B':
1612 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1613 case 'C':
1614 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1615 case 'D':
1616 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1617 case 'F':
1618 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1619 case 'I':
1620 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1621 case 'J':
1622 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1623 case 'S':
1624 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1625 case 'Z':
1626 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1627 case 's':
1628 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1629 case 'e':
1630 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1631 case 'c':
1632 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1633 case '[': {
1634 int n = nextChar();
1635 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1636 for (int i=0; i<n; i++)
1637 l.append(readAttributeValue());
1638 return new ArrayAttributeProxy(l.toList());
1639 }
1640 case '@':
1641 return readCompoundAnnotation();
1642 default:
1643 throw new AssertionError("unknown annotation tag '" + c + "'");
1644 }
1645 }
1647 interface ProxyVisitor extends Attribute.Visitor {
1648 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1649 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1650 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1651 }
1653 static class EnumAttributeProxy extends Attribute {
1654 Type enumType;
1655 Name enumerator;
1656 public EnumAttributeProxy(Type enumType, Name enumerator) {
1657 super(null);
1658 this.enumType = enumType;
1659 this.enumerator = enumerator;
1660 }
1661 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1662 @Override
1663 public String toString() {
1664 return "/*proxy enum*/" + enumType + "." + enumerator;
1665 }
1666 }
1668 static class ArrayAttributeProxy extends Attribute {
1669 List<Attribute> values;
1670 ArrayAttributeProxy(List<Attribute> values) {
1671 super(null);
1672 this.values = values;
1673 }
1674 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1675 @Override
1676 public String toString() {
1677 return "{" + values + "}";
1678 }
1679 }
1681 /** A temporary proxy representing a compound attribute.
1682 */
1683 static class CompoundAnnotationProxy extends Attribute {
1684 final List<Pair<Name,Attribute>> values;
1685 public CompoundAnnotationProxy(Type type,
1686 List<Pair<Name,Attribute>> values) {
1687 super(type);
1688 this.values = values;
1689 }
1690 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1691 @Override
1692 public String toString() {
1693 StringBuilder buf = new StringBuilder();
1694 buf.append("@");
1695 buf.append(type.tsym.getQualifiedName());
1696 buf.append("/*proxy*/{");
1697 boolean first = true;
1698 for (List<Pair<Name,Attribute>> v = values;
1699 v.nonEmpty(); v = v.tail) {
1700 Pair<Name,Attribute> value = v.head;
1701 if (!first) buf.append(",");
1702 first = false;
1703 buf.append(value.fst);
1704 buf.append("=");
1705 buf.append(value.snd);
1706 }
1707 buf.append("}");
1708 return buf.toString();
1709 }
1710 }
1712 /** A temporary proxy representing a type annotation.
1713 */
1714 static class TypeAnnotationProxy {
1715 final CompoundAnnotationProxy compound;
1716 final TypeAnnotationPosition position;
1717 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1718 TypeAnnotationPosition position) {
1719 this.compound = compound;
1720 this.position = position;
1721 }
1722 }
1724 class AnnotationDeproxy implements ProxyVisitor {
1725 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1726 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1728 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1729 // also must fill in types!!!!
1730 ListBuffer<Attribute.Compound> buf =
1731 new ListBuffer<Attribute.Compound>();
1732 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1733 buf.append(deproxyCompound(l.head));
1734 }
1735 return buf.toList();
1736 }
1738 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1739 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1740 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1741 for (List<Pair<Name,Attribute>> l = a.values;
1742 l.nonEmpty();
1743 l = l.tail) {
1744 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1745 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1746 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1747 }
1748 return new Attribute.Compound(a.type, buf.toList());
1749 }
1751 MethodSymbol findAccessMethod(Type container, Name name) {
1752 CompletionFailure failure = null;
1753 try {
1754 for (Scope.Entry e = container.tsym.members().lookup(name);
1755 e.scope != null;
1756 e = e.next()) {
1757 Symbol sym = e.sym;
1758 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1759 return (MethodSymbol) sym;
1760 }
1761 } catch (CompletionFailure ex) {
1762 failure = ex;
1763 }
1764 // The method wasn't found: emit a warning and recover
1765 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1766 try {
1767 if (failure == null) {
1768 log.warning("annotation.method.not.found",
1769 container,
1770 name);
1771 } else {
1772 log.warning("annotation.method.not.found.reason",
1773 container,
1774 name,
1775 failure.getDetailValue());//diagnostic, if present
1776 }
1777 } finally {
1778 log.useSource(prevSource);
1779 }
1780 // Construct a new method type and symbol. Use bottom
1781 // type (typeof null) as return type because this type is
1782 // a subtype of all reference types and can be converted
1783 // to primitive types by unboxing.
1784 MethodType mt = new MethodType(List.<Type>nil(),
1785 syms.botType,
1786 List.<Type>nil(),
1787 syms.methodClass);
1788 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1789 }
1791 Attribute result;
1792 Type type;
1793 Attribute deproxy(Type t, Attribute a) {
1794 Type oldType = type;
1795 try {
1796 type = t;
1797 a.accept(this);
1798 return result;
1799 } finally {
1800 type = oldType;
1801 }
1802 }
1804 // implement Attribute.Visitor below
1806 public void visitConstant(Attribute.Constant value) {
1807 // assert value.type == type;
1808 result = value;
1809 }
1811 public void visitClass(Attribute.Class clazz) {
1812 result = clazz;
1813 }
1815 public void visitEnum(Attribute.Enum e) {
1816 throw new AssertionError(); // shouldn't happen
1817 }
1819 public void visitCompound(Attribute.Compound compound) {
1820 throw new AssertionError(); // shouldn't happen
1821 }
1823 public void visitArray(Attribute.Array array) {
1824 throw new AssertionError(); // shouldn't happen
1825 }
1827 public void visitError(Attribute.Error e) {
1828 throw new AssertionError(); // shouldn't happen
1829 }
1831 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1832 // type.tsym.flatName() should == proxy.enumFlatName
1833 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1834 VarSymbol enumerator = null;
1835 CompletionFailure failure = null;
1836 try {
1837 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1838 e.scope != null;
1839 e = e.next()) {
1840 if (e.sym.kind == VAR) {
1841 enumerator = (VarSymbol)e.sym;
1842 break;
1843 }
1844 }
1845 }
1846 catch (CompletionFailure ex) {
1847 failure = ex;
1848 }
1849 if (enumerator == null) {
1850 if (failure != null) {
1851 log.warning("unknown.enum.constant.reason",
1852 currentClassFile, enumTypeSym, proxy.enumerator,
1853 failure.getDiagnostic());
1854 } else {
1855 log.warning("unknown.enum.constant",
1856 currentClassFile, enumTypeSym, proxy.enumerator);
1857 }
1858 result = new Attribute.Enum(enumTypeSym.type,
1859 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1860 } else {
1861 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1862 }
1863 }
1865 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1866 int length = proxy.values.length();
1867 Attribute[] ats = new Attribute[length];
1868 Type elemtype = types.elemtype(type);
1869 int i = 0;
1870 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1871 ats[i++] = deproxy(elemtype, p.head);
1872 }
1873 result = new Attribute.Array(type, ats);
1874 }
1876 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1877 result = deproxyCompound(proxy);
1878 }
1879 }
1881 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1882 final MethodSymbol sym;
1883 final Attribute value;
1884 final JavaFileObject classFile = currentClassFile;
1885 @Override
1886 public String toString() {
1887 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1888 }
1889 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1890 this.sym = sym;
1891 this.value = value;
1892 }
1893 // implement Annotate.Annotator.enterAnnotation()
1894 public void enterAnnotation() {
1895 JavaFileObject previousClassFile = currentClassFile;
1896 try {
1897 // Reset the interim value set earlier in
1898 // attachAnnotationDefault().
1899 sym.defaultValue = null;
1900 currentClassFile = classFile;
1901 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1902 } finally {
1903 currentClassFile = previousClassFile;
1904 }
1905 }
1906 }
1908 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1909 final Symbol sym;
1910 final List<CompoundAnnotationProxy> l;
1911 final JavaFileObject classFile;
1912 @Override
1913 public String toString() {
1914 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1915 }
1916 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1917 this.sym = sym;
1918 this.l = l;
1919 this.classFile = currentClassFile;
1920 }
1921 // implement Annotate.Annotator.enterAnnotation()
1922 public void enterAnnotation() {
1923 JavaFileObject previousClassFile = currentClassFile;
1924 try {
1925 currentClassFile = classFile;
1926 List<Attribute.Compound> newList = deproxyCompoundList(l);
1927 if (sym.annotationsPendingCompletion()) {
1928 sym.setDeclarationAttributes(newList);
1929 } else {
1930 sym.appendAttributes(newList);
1931 }
1932 } finally {
1933 currentClassFile = previousClassFile;
1934 }
1935 }
1936 }
1938 class TypeAnnotationCompleter extends AnnotationCompleter {
1940 List<TypeAnnotationProxy> proxies;
1942 TypeAnnotationCompleter(Symbol sym,
1943 List<TypeAnnotationProxy> proxies) {
1944 super(sym, List.<CompoundAnnotationProxy>nil());
1945 this.proxies = proxies;
1946 }
1948 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
1949 ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
1950 for (TypeAnnotationProxy proxy: proxies) {
1951 Attribute.Compound compound = deproxyCompound(proxy.compound);
1952 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
1953 buf.add(typeCompound);
1954 }
1955 return buf.toList();
1956 }
1958 @Override
1959 public void enterAnnotation() {
1960 JavaFileObject previousClassFile = currentClassFile;
1961 try {
1962 currentClassFile = classFile;
1963 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
1964 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
1965 } finally {
1966 currentClassFile = previousClassFile;
1967 }
1968 }
1969 }
1972 /************************************************************************
1973 * Reading Symbols
1974 ***********************************************************************/
1976 /** Read a field.
1977 */
1978 VarSymbol readField() {
1979 long flags = adjustFieldFlags(nextChar());
1980 Name name = readName(nextChar());
1981 Type type = readType(nextChar());
1982 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1983 readMemberAttrs(v);
1984 return v;
1985 }
1987 /** Read a method.
1988 */
1989 MethodSymbol readMethod() {
1990 long flags = adjustMethodFlags(nextChar());
1991 Name name = readName(nextChar());
1992 Type type = readType(nextChar());
1993 if (currentOwner.isInterface() &&
1994 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
1995 if (majorVersion > Target.JDK1_8.majorVersion ||
1996 (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
1997 currentOwner.flags_field |= DEFAULT;
1998 flags |= DEFAULT | ABSTRACT;
1999 } else {
2000 //protect against ill-formed classfiles
2001 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
2002 }
2003 }
2004 if (name == names.init && currentOwner.hasOuterInstance()) {
2005 // Sometimes anonymous classes don't have an outer
2006 // instance, however, there is no reliable way to tell so
2007 // we never strip this$n
2008 if (!currentOwner.name.isEmpty())
2009 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
2010 type.getReturnType(),
2011 type.getThrownTypes(),
2012 syms.methodClass);
2013 }
2014 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
2015 if (types.isSignaturePolymorphic(m)) {
2016 m.flags_field |= SIGNATURE_POLYMORPHIC;
2017 }
2018 if (saveParameterNames)
2019 initParameterNames(m);
2020 Symbol prevOwner = currentOwner;
2021 currentOwner = m;
2022 try {
2023 readMemberAttrs(m);
2024 } finally {
2025 currentOwner = prevOwner;
2026 }
2027 if (saveParameterNames)
2028 setParameterNames(m, type);
2029 return m;
2030 }
2032 private List<Type> adjustMethodParams(long flags, List<Type> args) {
2033 boolean isVarargs = (flags & VARARGS) != 0;
2034 if (isVarargs) {
2035 Type varargsElem = args.last();
2036 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
2037 for (Type t : args) {
2038 adjustedArgs.append(t != varargsElem ?
2039 t :
2040 ((ArrayType)t).makeVarargs());
2041 }
2042 args = adjustedArgs.toList();
2043 }
2044 return args.tail;
2045 }
2047 /**
2048 * Init the parameter names array.
2049 * Parameter names are currently inferred from the names in the
2050 * LocalVariableTable attributes of a Code attribute.
2051 * (Note: this means parameter names are currently not available for
2052 * methods without a Code attribute.)
2053 * This method initializes an array in which to store the name indexes
2054 * of parameter names found in LocalVariableTable attributes. It is
2055 * slightly supersized to allow for additional slots with a start_pc of 0.
2056 */
2057 void initParameterNames(MethodSymbol sym) {
2058 // make allowance for synthetic parameters.
2059 final int excessSlots = 4;
2060 int expectedParameterSlots =
2061 Code.width(sym.type.getParameterTypes()) + excessSlots;
2062 if (parameterNameIndices == null
2063 || parameterNameIndices.length < expectedParameterSlots) {
2064 parameterNameIndices = new int[expectedParameterSlots];
2065 } else
2066 Arrays.fill(parameterNameIndices, 0);
2067 haveParameterNameIndices = false;
2068 sawMethodParameters = false;
2069 }
2071 /**
2072 * Set the parameter names for a symbol from the name index in the
2073 * parameterNameIndicies array. The type of the symbol may have changed
2074 * while reading the method attributes (see the Signature attribute).
2075 * This may be because of generic information or because anonymous
2076 * synthetic parameters were added. The original type (as read from
2077 * the method descriptor) is used to help guess the existence of
2078 * anonymous synthetic parameters.
2079 * On completion, sym.savedParameter names will either be null (if
2080 * no parameter names were found in the class file) or will be set to a
2081 * list of names, one per entry in sym.type.getParameterTypes, with
2082 * any missing names represented by the empty name.
2083 */
2084 void setParameterNames(MethodSymbol sym, Type jvmType) {
2085 // if no names were found in the class file, there's nothing more to do
2086 if (!haveParameterNameIndices)
2087 return;
2088 // If we get parameter names from MethodParameters, then we
2089 // don't need to skip.
2090 int firstParam = 0;
2091 if (!sawMethodParameters) {
2092 firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
2093 // the code in readMethod may have skipped the first
2094 // parameter when setting up the MethodType. If so, we
2095 // make a corresponding allowance here for the position of
2096 // the first parameter. Note that this assumes the
2097 // skipped parameter has a width of 1 -- i.e. it is not
2098 // a double width type (long or double.)
2099 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
2100 // Sometimes anonymous classes don't have an outer
2101 // instance, however, there is no reliable way to tell so
2102 // we never strip this$n
2103 if (!currentOwner.name.isEmpty())
2104 firstParam += 1;
2105 }
2107 if (sym.type != jvmType) {
2108 // reading the method attributes has caused the
2109 // symbol's type to be changed. (i.e. the Signature
2110 // attribute.) This may happen if there are hidden
2111 // (synthetic) parameters in the descriptor, but not
2112 // in the Signature. The position of these hidden
2113 // parameters is unspecified; for now, assume they are
2114 // at the beginning, and so skip over them. The
2115 // primary case for this is two hidden parameters
2116 // passed into Enum constructors.
2117 int skip = Code.width(jvmType.getParameterTypes())
2118 - Code.width(sym.type.getParameterTypes());
2119 firstParam += skip;
2120 }
2121 }
2122 List<Name> paramNames = List.nil();
2123 int index = firstParam;
2124 for (Type t: sym.type.getParameterTypes()) {
2125 int nameIdx = (index < parameterNameIndices.length
2126 ? parameterNameIndices[index] : 0);
2127 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
2128 paramNames = paramNames.prepend(name);
2129 index += Code.width(t);
2130 }
2131 sym.savedParameterNames = paramNames.reverse();
2132 }
2134 /**
2135 * skip n bytes
2136 */
2137 void skipBytes(int n) {
2138 bp = bp + n;
2139 }
2141 /** Skip a field or method
2142 */
2143 void skipMember() {
2144 bp = bp + 6;
2145 char ac = nextChar();
2146 for (int i = 0; i < ac; i++) {
2147 bp = bp + 2;
2148 int attrLen = nextInt();
2149 bp = bp + attrLen;
2150 }
2151 }
2153 /** Enter type variables of this classtype and all enclosing ones in
2154 * `typevars'.
2155 */
2156 protected void enterTypevars(Type t) {
2157 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
2158 enterTypevars(t.getEnclosingType());
2159 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
2160 typevars.enter(xs.head.tsym);
2161 }
2163 protected void enterTypevars(Symbol sym) {
2164 if (sym.owner.kind == MTH) {
2165 enterTypevars(sym.owner);
2166 enterTypevars(sym.owner.owner);
2167 }
2168 enterTypevars(sym.type);
2169 }
2171 /** Read contents of a given class symbol `c'. Both external and internal
2172 * versions of an inner class are read.
2173 */
2174 void readClass(ClassSymbol c) {
2175 ClassType ct = (ClassType)c.type;
2177 // allocate scope for members
2178 c.members_field = new Scope(c);
2180 // prepare type variable table
2181 typevars = typevars.dup(currentOwner);
2182 if (ct.getEnclosingType().hasTag(CLASS))
2183 enterTypevars(ct.getEnclosingType());
2185 // read flags, or skip if this is an inner class
2186 long flags = adjustClassFlags(nextChar());
2187 if (c.owner.kind == PCK) c.flags_field = flags;
2189 // read own class name and check that it matches
2190 ClassSymbol self = readClassSymbol(nextChar());
2191 if (c != self)
2192 throw badClassFile("class.file.wrong.class",
2193 self.flatname);
2195 // class attributes must be read before class
2196 // skip ahead to read class attributes
2197 int startbp = bp;
2198 nextChar();
2199 char interfaceCount = nextChar();
2200 bp += interfaceCount * 2;
2201 char fieldCount = nextChar();
2202 for (int i = 0; i < fieldCount; i++) skipMember();
2203 char methodCount = nextChar();
2204 for (int i = 0; i < methodCount; i++) skipMember();
2205 readClassAttrs(c);
2207 if (readAllOfClassFile) {
2208 for (int i = 1; i < poolObj.length; i++) readPool(i);
2209 c.pool = new Pool(poolObj.length, poolObj, types);
2210 }
2212 // reset and read rest of classinfo
2213 bp = startbp;
2214 int n = nextChar();
2215 if (ct.supertype_field == null)
2216 ct.supertype_field = (n == 0)
2217 ? Type.noType
2218 : readClassSymbol(n).erasure(types);
2219 n = nextChar();
2220 List<Type> is = List.nil();
2221 for (int i = 0; i < n; i++) {
2222 Type _inter = readClassSymbol(nextChar()).erasure(types);
2223 is = is.prepend(_inter);
2224 }
2225 if (ct.interfaces_field == null)
2226 ct.interfaces_field = is.reverse();
2228 Assert.check(fieldCount == nextChar());
2229 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2230 Assert.check(methodCount == nextChar());
2231 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2233 typevars = typevars.leave();
2234 }
2236 /** Read inner class info. For each inner/outer pair allocate a
2237 * member class.
2238 */
2239 void readInnerClasses(ClassSymbol c) {
2240 int n = nextChar();
2241 for (int i = 0; i < n; i++) {
2242 nextChar(); // skip inner class symbol
2243 ClassSymbol outer = readClassSymbol(nextChar());
2244 Name name = readName(nextChar());
2245 if (name == null) name = names.empty;
2246 long flags = adjustClassFlags(nextChar());
2247 if (outer != null) { // we have a member class
2248 if (name == names.empty)
2249 name = names.one;
2250 ClassSymbol member = enterClass(name, outer);
2251 if ((flags & STATIC) == 0) {
2252 ((ClassType)member.type).setEnclosingType(outer.type);
2253 if (member.erasure_field != null)
2254 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2255 }
2256 if (c == outer) {
2257 member.flags_field = flags;
2258 enterMember(c, member);
2259 }
2260 }
2261 }
2262 }
2264 /** Read a class file.
2265 */
2266 private void readClassFile(ClassSymbol c) throws IOException {
2267 int magic = nextInt();
2268 if (magic != JAVA_MAGIC)
2269 throw badClassFile("illegal.start.of.class.file");
2271 minorVersion = nextChar();
2272 majorVersion = nextChar();
2273 int maxMajor = Target.MAX().majorVersion;
2274 int maxMinor = Target.MAX().minorVersion;
2275 if (majorVersion > maxMajor ||
2276 majorVersion * 1000 + minorVersion <
2277 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2278 {
2279 if (majorVersion == (maxMajor + 1))
2280 log.warning("big.major.version",
2281 currentClassFile,
2282 majorVersion,
2283 maxMajor);
2284 else
2285 throw badClassFile("wrong.version",
2286 Integer.toString(majorVersion),
2287 Integer.toString(minorVersion),
2288 Integer.toString(maxMajor),
2289 Integer.toString(maxMinor));
2290 }
2291 else if (checkClassFile &&
2292 majorVersion == maxMajor &&
2293 minorVersion > maxMinor)
2294 {
2295 printCCF("found.later.version",
2296 Integer.toString(minorVersion));
2297 }
2298 indexPool();
2299 if (signatureBuffer.length < bp) {
2300 int ns = Integer.highestOneBit(bp) << 1;
2301 signatureBuffer = new byte[ns];
2302 }
2303 readClass(c);
2304 }
2306 /************************************************************************
2307 * Adjusting flags
2308 ***********************************************************************/
2310 long adjustFieldFlags(long flags) {
2311 return flags;
2312 }
2313 long adjustMethodFlags(long flags) {
2314 if ((flags & ACC_BRIDGE) != 0) {
2315 flags &= ~ACC_BRIDGE;
2316 flags |= BRIDGE;
2317 if (!allowGenerics)
2318 flags &= ~SYNTHETIC;
2319 }
2320 if ((flags & ACC_VARARGS) != 0) {
2321 flags &= ~ACC_VARARGS;
2322 flags |= VARARGS;
2323 }
2324 return flags;
2325 }
2326 long adjustClassFlags(long flags) {
2327 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2328 }
2330 /************************************************************************
2331 * Loading Classes
2332 ***********************************************************************/
2334 /** Define a new class given its name and owner.
2335 */
2336 public ClassSymbol defineClass(Name name, Symbol owner) {
2337 ClassSymbol c = new ClassSymbol(0, name, owner);
2338 if (owner.kind == PCK)
2339 Assert.checkNull(classes.get(c.flatname), c);
2340 c.completer = thisCompleter;
2341 return c;
2342 }
2344 /** Create a new toplevel or member class symbol with given name
2345 * and owner and enter in `classes' unless already there.
2346 */
2347 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2348 Name flatname = TypeSymbol.formFlatName(name, owner);
2349 ClassSymbol c = classes.get(flatname);
2350 if (c == null) {
2351 c = defineClass(name, owner);
2352 classes.put(flatname, c);
2353 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2354 // reassign fields of classes that might have been loaded with
2355 // their flat names.
2356 c.owner.members().remove(c);
2357 c.name = name;
2358 c.owner = owner;
2359 c.fullname = ClassSymbol.formFullName(name, owner);
2360 }
2361 return c;
2362 }
2364 /**
2365 * Creates a new toplevel class symbol with given flat name and
2366 * given class (or source) file.
2367 *
2368 * @param flatName a fully qualified binary class name
2369 * @param classFile the class file or compilation unit defining
2370 * the class (may be {@code null})
2371 * @return a newly created class symbol
2372 * @throws AssertionError if the class symbol already exists
2373 */
2374 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2375 ClassSymbol cs = classes.get(flatName);
2376 if (cs != null) {
2377 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2378 cs.fullname,
2379 cs.completer,
2380 cs.classfile,
2381 cs.sourcefile);
2382 throw new AssertionError(msg);
2383 }
2384 Name packageName = Convert.packagePart(flatName);
2385 PackageSymbol owner = packageName.isEmpty()
2386 ? syms.unnamedPackage
2387 : enterPackage(packageName);
2388 cs = defineClass(Convert.shortName(flatName), owner);
2389 cs.classfile = classFile;
2390 classes.put(flatName, cs);
2391 return cs;
2392 }
2394 /** Create a new member or toplevel class symbol with given flat name
2395 * and enter in `classes' unless already there.
2396 */
2397 public ClassSymbol enterClass(Name flatname) {
2398 ClassSymbol c = classes.get(flatname);
2399 if (c == null)
2400 return enterClass(flatname, (JavaFileObject)null);
2401 else
2402 return c;
2403 }
2405 private boolean suppressFlush = false;
2407 /** Completion for classes to be loaded. Before a class is loaded
2408 * we make sure its enclosing class (if any) is loaded.
2409 */
2410 private void complete(Symbol sym) throws CompletionFailure {
2411 if (sym.kind == TYP) {
2412 ClassSymbol c = (ClassSymbol)sym;
2413 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2414 boolean saveSuppressFlush = suppressFlush;
2415 suppressFlush = true;
2416 try {
2417 completeOwners(c.owner);
2418 completeEnclosing(c);
2419 } finally {
2420 suppressFlush = saveSuppressFlush;
2421 }
2422 fillIn(c);
2423 } else if (sym.kind == PCK) {
2424 PackageSymbol p = (PackageSymbol)sym;
2425 try {
2426 fillIn(p);
2427 } catch (IOException ex) {
2428 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2429 }
2430 }
2431 if (!filling && !suppressFlush)
2432 annotate.flush(); // finish attaching annotations
2433 }
2435 /** complete up through the enclosing package. */
2436 private void completeOwners(Symbol o) {
2437 if (o.kind != PCK) completeOwners(o.owner);
2438 o.complete();
2439 }
2441 /**
2442 * Tries to complete lexically enclosing classes if c looks like a
2443 * nested class. This is similar to completeOwners but handles
2444 * the situation when a nested class is accessed directly as it is
2445 * possible with the Tree API or javax.lang.model.*.
2446 */
2447 private void completeEnclosing(ClassSymbol c) {
2448 if (c.owner.kind == PCK) {
2449 Symbol owner = c.owner;
2450 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2451 Symbol encl = owner.members().lookup(name).sym;
2452 if (encl == null)
2453 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2454 if (encl != null)
2455 encl.complete();
2456 }
2457 }
2458 }
2460 /** We can only read a single class file at a time; this
2461 * flag keeps track of when we are currently reading a class
2462 * file.
2463 */
2464 private boolean filling = false;
2466 /** Fill in definition of class `c' from corresponding class or
2467 * source file.
2468 */
2469 private void fillIn(ClassSymbol c) {
2470 if (completionFailureName == c.fullname) {
2471 throw new CompletionFailure(c, "user-selected completion failure by class name");
2472 }
2473 currentOwner = c;
2474 warnedAttrs.clear();
2475 JavaFileObject classfile = c.classfile;
2476 if (classfile != null) {
2477 JavaFileObject previousClassFile = currentClassFile;
2478 try {
2479 if (filling) {
2480 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2481 }
2482 currentClassFile = classfile;
2483 if (verbose) {
2484 log.printVerbose("loading", currentClassFile.toString());
2485 }
2486 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2487 filling = true;
2488 try {
2489 bp = 0;
2490 buf = readInputStream(buf, classfile.openInputStream());
2491 readClassFile(c);
2492 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2493 List<Type> missing = missingTypeVariables;
2494 List<Type> found = foundTypeVariables;
2495 missingTypeVariables = List.nil();
2496 foundTypeVariables = List.nil();
2497 filling = false;
2498 ClassType ct = (ClassType)currentOwner.type;
2499 ct.supertype_field =
2500 types.subst(ct.supertype_field, missing, found);
2501 ct.interfaces_field =
2502 types.subst(ct.interfaces_field, missing, found);
2503 } else if (missingTypeVariables.isEmpty() !=
2504 foundTypeVariables.isEmpty()) {
2505 Name name = missingTypeVariables.head.tsym.name;
2506 throw badClassFile("undecl.type.var", name);
2507 }
2508 } finally {
2509 missingTypeVariables = List.nil();
2510 foundTypeVariables = List.nil();
2511 filling = false;
2512 }
2513 } else {
2514 if (sourceCompleter != null) {
2515 sourceCompleter.complete(c);
2516 } else {
2517 throw new IllegalStateException("Source completer required to read "
2518 + classfile.toUri());
2519 }
2520 }
2521 return;
2522 } catch (IOException ex) {
2523 throw badClassFile("unable.to.access.file", ex.getMessage());
2524 } finally {
2525 currentClassFile = previousClassFile;
2526 }
2527 } else {
2528 JCDiagnostic diag =
2529 diagFactory.fragment("class.file.not.found", c.flatname);
2530 throw
2531 newCompletionFailure(c, diag);
2532 }
2533 }
2534 // where
2535 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2536 try {
2537 buf = ensureCapacity(buf, s.available());
2538 int r = s.read(buf);
2539 int bp = 0;
2540 while (r != -1) {
2541 bp += r;
2542 buf = ensureCapacity(buf, bp);
2543 r = s.read(buf, bp, buf.length - bp);
2544 }
2545 return buf;
2546 } finally {
2547 try {
2548 s.close();
2549 } catch (IOException e) {
2550 /* Ignore any errors, as this stream may have already
2551 * thrown a related exception which is the one that
2552 * should be reported.
2553 */
2554 }
2555 }
2556 }
2557 /*
2558 * ensureCapacity will increase the buffer as needed, taking note that
2559 * the new buffer will always be greater than the needed and never
2560 * exactly equal to the needed size or bp. If equal then the read (above)
2561 * will infinitely loop as buf.length - bp == 0.
2562 */
2563 private static byte[] ensureCapacity(byte[] buf, int needed) {
2564 if (buf.length <= needed) {
2565 byte[] old = buf;
2566 buf = new byte[Integer.highestOneBit(needed) << 1];
2567 System.arraycopy(old, 0, buf, 0, old.length);
2568 }
2569 return buf;
2570 }
2571 /** Static factory for CompletionFailure objects.
2572 * In practice, only one can be used at a time, so we share one
2573 * to reduce the expense of allocating new exception objects.
2574 */
2575 private CompletionFailure newCompletionFailure(TypeSymbol c,
2576 JCDiagnostic diag) {
2577 if (!cacheCompletionFailure) {
2578 // log.warning("proc.messager",
2579 // Log.getLocalizedString("class.file.not.found", c.flatname));
2580 // c.debug.printStackTrace();
2581 return new CompletionFailure(c, diag);
2582 } else {
2583 CompletionFailure result = cachedCompletionFailure;
2584 result.sym = c;
2585 result.diag = diag;
2586 return result;
2587 }
2588 }
2589 private CompletionFailure cachedCompletionFailure =
2590 new CompletionFailure(null, (JCDiagnostic) null);
2591 {
2592 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2593 }
2595 /** Load a toplevel class with given fully qualified name
2596 * The class is entered into `classes' only if load was successful.
2597 */
2598 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2599 boolean absent = classes.get(flatname) == null;
2600 ClassSymbol c = enterClass(flatname);
2601 if (c.members_field == null && c.completer != null) {
2602 try {
2603 c.complete();
2604 } catch (CompletionFailure ex) {
2605 if (absent) classes.remove(flatname);
2606 throw ex;
2607 }
2608 }
2609 return c;
2610 }
2612 /************************************************************************
2613 * Loading Packages
2614 ***********************************************************************/
2616 /** Check to see if a package exists, given its fully qualified name.
2617 */
2618 public boolean packageExists(Name fullname) {
2619 return enterPackage(fullname).exists();
2620 }
2622 /** Make a package, given its fully qualified name.
2623 */
2624 public PackageSymbol enterPackage(Name fullname) {
2625 PackageSymbol p = packages.get(fullname);
2626 if (p == null) {
2627 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2628 p = new PackageSymbol(
2629 Convert.shortName(fullname),
2630 enterPackage(Convert.packagePart(fullname)));
2631 p.completer = thisCompleter;
2632 packages.put(fullname, p);
2633 }
2634 return p;
2635 }
2637 /** Make a package, given its unqualified name and enclosing package.
2638 */
2639 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2640 return enterPackage(TypeSymbol.formFullName(name, owner));
2641 }
2643 /** Include class corresponding to given class file in package,
2644 * unless (1) we already have one the same kind (.class or .java), or
2645 * (2) we have one of the other kind, and the given class file
2646 * is older.
2647 */
2648 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2649 if ((p.flags_field & EXISTS) == 0)
2650 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2651 q.flags_field |= EXISTS;
2652 JavaFileObject.Kind kind = file.getKind();
2653 int seen;
2654 if (kind == JavaFileObject.Kind.CLASS)
2655 seen = CLASS_SEEN;
2656 else
2657 seen = SOURCE_SEEN;
2658 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2659 int lastDot = binaryName.lastIndexOf(".");
2660 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2661 boolean isPkgInfo = classname == names.package_info;
2662 ClassSymbol c = isPkgInfo
2663 ? p.package_info
2664 : (ClassSymbol) p.members_field.lookup(classname).sym;
2665 if (c == null) {
2666 c = enterClass(classname, p);
2667 if (c.classfile == null) // only update the file if's it's newly created
2668 c.classfile = file;
2669 if (isPkgInfo) {
2670 p.package_info = c;
2671 } else {
2672 if (c.owner == p) // it might be an inner class
2673 p.members_field.enter(c);
2674 }
2675 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2676 // if c.classfile == null, we are currently compiling this class
2677 // and no further action is necessary.
2678 // if (c.flags_field & seen) != 0, we have already encountered
2679 // a file of the same kind; again no further action is necessary.
2680 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2681 c.classfile = preferredFileObject(file, c.classfile);
2682 }
2683 c.flags_field |= seen;
2684 }
2686 /** Implement policy to choose to derive information from a source
2687 * file or a class file when both are present. May be overridden
2688 * by subclasses.
2689 */
2690 protected JavaFileObject preferredFileObject(JavaFileObject a,
2691 JavaFileObject b) {
2693 if (preferSource)
2694 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2695 else {
2696 long adate = a.getLastModified();
2697 long bdate = b.getLastModified();
2698 // 6449326: policy for bad lastModifiedTime in ClassReader
2699 //assert adate >= 0 && bdate >= 0;
2700 return (adate > bdate) ? a : b;
2701 }
2702 }
2704 /**
2705 * specifies types of files to be read when filling in a package symbol
2706 */
2707 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2708 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2709 }
2711 /**
2712 * this is used to support javadoc
2713 */
2714 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2715 }
2717 protected Location currentLoc; // FIXME
2719 private boolean verbosePath = true;
2721 /** Load directory of package into members scope.
2722 */
2723 private void fillIn(PackageSymbol p) throws IOException {
2724 if (p.members_field == null) p.members_field = new Scope(p);
2725 String packageName = p.fullname.toString();
2727 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2729 fillIn(p, PLATFORM_CLASS_PATH,
2730 fileManager.list(PLATFORM_CLASS_PATH,
2731 packageName,
2732 EnumSet.of(JavaFileObject.Kind.CLASS),
2733 false));
2735 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2736 classKinds.remove(JavaFileObject.Kind.SOURCE);
2737 boolean wantClassFiles = !classKinds.isEmpty();
2739 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2740 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2741 boolean wantSourceFiles = !sourceKinds.isEmpty();
2743 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2745 if (verbose && verbosePath) {
2746 if (fileManager instanceof StandardJavaFileManager) {
2747 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2748 if (haveSourcePath && wantSourceFiles) {
2749 List<File> path = List.nil();
2750 for (File file : fm.getLocation(SOURCE_PATH)) {
2751 path = path.prepend(file);
2752 }
2753 log.printVerbose("sourcepath", path.reverse().toString());
2754 } else if (wantSourceFiles) {
2755 List<File> path = List.nil();
2756 for (File file : fm.getLocation(CLASS_PATH)) {
2757 path = path.prepend(file);
2758 }
2759 log.printVerbose("sourcepath", path.reverse().toString());
2760 }
2761 if (wantClassFiles) {
2762 List<File> path = List.nil();
2763 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2764 path = path.prepend(file);
2765 }
2766 for (File file : fm.getLocation(CLASS_PATH)) {
2767 path = path.prepend(file);
2768 }
2769 log.printVerbose("classpath", path.reverse().toString());
2770 }
2771 }
2772 }
2774 if (wantSourceFiles && !haveSourcePath) {
2775 fillIn(p, CLASS_PATH,
2776 fileManager.list(CLASS_PATH,
2777 packageName,
2778 kinds,
2779 false));
2780 } else {
2781 if (wantClassFiles)
2782 fillIn(p, CLASS_PATH,
2783 fileManager.list(CLASS_PATH,
2784 packageName,
2785 classKinds,
2786 false));
2787 if (wantSourceFiles)
2788 fillIn(p, SOURCE_PATH,
2789 fileManager.list(SOURCE_PATH,
2790 packageName,
2791 sourceKinds,
2792 false));
2793 }
2794 verbosePath = false;
2795 }
2796 // where
2797 private void fillIn(PackageSymbol p,
2798 Location location,
2799 Iterable<JavaFileObject> files)
2800 {
2801 currentLoc = location;
2802 for (JavaFileObject fo : files) {
2803 switch (fo.getKind()) {
2804 case CLASS:
2805 case SOURCE: {
2806 // TODO pass binaryName to includeClassFile
2807 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2808 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2809 if (SourceVersion.isIdentifier(simpleName) ||
2810 simpleName.equals("package-info"))
2811 includeClassFile(p, fo);
2812 break;
2813 }
2814 default:
2815 extraFileActions(p, fo);
2816 }
2817 }
2818 }
2820 /** Output for "-checkclassfile" option.
2821 * @param key The key to look up the correct internationalized string.
2822 * @param arg An argument for substitution into the output string.
2823 */
2824 private void printCCF(String key, Object arg) {
2825 log.printLines(key, arg);
2826 }
2829 public interface SourceCompleter {
2830 void complete(ClassSymbol sym)
2831 throws CompletionFailure;
2832 }
2834 /**
2835 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2836 * The attribute is only the last component of the original filename, so is unlikely
2837 * to be valid as is, so operations other than those to access the name throw
2838 * UnsupportedOperationException
2839 */
2840 private static class SourceFileObject extends BaseFileObject {
2842 /** The file's name.
2843 */
2844 private Name name;
2845 private Name flatname;
2847 public SourceFileObject(Name name, Name flatname) {
2848 super(null); // no file manager; never referenced for this file object
2849 this.name = name;
2850 this.flatname = flatname;
2851 }
2853 @Override
2854 public URI toUri() {
2855 try {
2856 return new URI(null, name.toString(), null);
2857 } catch (URISyntaxException e) {
2858 throw new CannotCreateUriError(name.toString(), e);
2859 }
2860 }
2862 @Override
2863 public String getName() {
2864 return name.toString();
2865 }
2867 @Override
2868 public String getShortName() {
2869 return getName();
2870 }
2872 @Override
2873 public JavaFileObject.Kind getKind() {
2874 return getKind(getName());
2875 }
2877 @Override
2878 public InputStream openInputStream() {
2879 throw new UnsupportedOperationException();
2880 }
2882 @Override
2883 public OutputStream openOutputStream() {
2884 throw new UnsupportedOperationException();
2885 }
2887 @Override
2888 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2889 throw new UnsupportedOperationException();
2890 }
2892 @Override
2893 public Reader openReader(boolean ignoreEncodingErrors) {
2894 throw new UnsupportedOperationException();
2895 }
2897 @Override
2898 public Writer openWriter() {
2899 throw new UnsupportedOperationException();
2900 }
2902 @Override
2903 public long getLastModified() {
2904 throw new UnsupportedOperationException();
2905 }
2907 @Override
2908 public boolean delete() {
2909 throw new UnsupportedOperationException();
2910 }
2912 @Override
2913 protected String inferBinaryName(Iterable<? extends File> path) {
2914 return flatname.toString();
2915 }
2917 @Override
2918 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2919 return true; // fail-safe mode
2920 }
2922 /**
2923 * Check if two file objects are equal.
2924 * SourceFileObjects are just placeholder objects for the value of a
2925 * SourceFile attribute, and do not directly represent specific files.
2926 * Two SourceFileObjects are equal if their names are equal.
2927 */
2928 @Override
2929 public boolean equals(Object other) {
2930 if (this == other)
2931 return true;
2933 if (!(other instanceof SourceFileObject))
2934 return false;
2936 SourceFileObject o = (SourceFileObject) other;
2937 return name.equals(o.name);
2938 }
2940 @Override
2941 public int hashCode() {
2942 return name.hashCode();
2943 }
2944 }
2945 }