Mon, 23 Sep 2013 10:42:38 +0200
6386236: Please rename com.sun.tools.javac.util.ListBuffer.lb()
Summary: Static factory method ListBuffer.lb removed. Replaced by constructor calls.
Reviewed-by: jfranck, 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 = new ListBuffer<>();
1450 for (int i = 0; i < numAttributes; i++)
1451 proxies.append(readTypeAnnotation());
1452 annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
1453 }
1454 }
1456 /** Attach the default value for an annotation element.
1457 */
1458 void attachAnnotationDefault(final Symbol sym) {
1459 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1460 final Attribute value = readAttributeValue();
1462 // The default value is set later during annotation. It might
1463 // be the case that the Symbol sym is annotated _after_ the
1464 // repeating instances that depend on this default value,
1465 // because of this we set an interim value that tells us this
1466 // element (most likely) has a default.
1467 //
1468 // Set interim value for now, reset just before we do this
1469 // properly at annotate time.
1470 meth.defaultValue = value;
1471 annotate.normal(new AnnotationDefaultCompleter(meth, value));
1472 }
1474 Type readTypeOrClassSymbol(int i) {
1475 // support preliminary jsr175-format class files
1476 if (buf[poolIdx[i]] == CONSTANT_Class)
1477 return readClassSymbol(i).type;
1478 return readType(i);
1479 }
1480 Type readEnumType(int i) {
1481 // support preliminary jsr175-format class files
1482 int index = poolIdx[i];
1483 int length = getChar(index + 1);
1484 if (buf[index + length + 2] != ';')
1485 return enterClass(readName(i)).type;
1486 return readType(i);
1487 }
1489 CompoundAnnotationProxy readCompoundAnnotation() {
1490 Type t = readTypeOrClassSymbol(nextChar());
1491 int numFields = nextChar();
1492 ListBuffer<Pair<Name,Attribute>> pairs =
1493 new ListBuffer<Pair<Name,Attribute>>();
1494 for (int i=0; i<numFields; i++) {
1495 Name name = readName(nextChar());
1496 Attribute value = readAttributeValue();
1497 pairs.append(new Pair<Name,Attribute>(name, value));
1498 }
1499 return new CompoundAnnotationProxy(t, pairs.toList());
1500 }
1502 TypeAnnotationProxy readTypeAnnotation() {
1503 TypeAnnotationPosition position = readPosition();
1504 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1506 return new TypeAnnotationProxy(proxy, position);
1507 }
1509 TypeAnnotationPosition readPosition() {
1510 int tag = nextByte(); // TargetType tag is a byte
1512 if (!TargetType.isValidTargetTypeValue(tag))
1513 throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
1515 TypeAnnotationPosition position = new TypeAnnotationPosition();
1516 TargetType type = TargetType.fromTargetTypeValue(tag);
1518 position.type = type;
1520 switch (type) {
1521 // instanceof
1522 case INSTANCEOF:
1523 // new expression
1524 case NEW:
1525 // constructor/method reference receiver
1526 case CONSTRUCTOR_REFERENCE:
1527 case METHOD_REFERENCE:
1528 position.offset = nextChar();
1529 break;
1530 // local variable
1531 case LOCAL_VARIABLE:
1532 // resource variable
1533 case RESOURCE_VARIABLE:
1534 int table_length = nextChar();
1535 position.lvarOffset = new int[table_length];
1536 position.lvarLength = new int[table_length];
1537 position.lvarIndex = new int[table_length];
1539 for (int i = 0; i < table_length; ++i) {
1540 position.lvarOffset[i] = nextChar();
1541 position.lvarLength[i] = nextChar();
1542 position.lvarIndex[i] = nextChar();
1543 }
1544 break;
1545 // exception parameter
1546 case EXCEPTION_PARAMETER:
1547 position.exception_index = nextChar();
1548 break;
1549 // method receiver
1550 case METHOD_RECEIVER:
1551 // Do nothing
1552 break;
1553 // type parameter
1554 case CLASS_TYPE_PARAMETER:
1555 case METHOD_TYPE_PARAMETER:
1556 position.parameter_index = nextByte();
1557 break;
1558 // type parameter bound
1559 case CLASS_TYPE_PARAMETER_BOUND:
1560 case METHOD_TYPE_PARAMETER_BOUND:
1561 position.parameter_index = nextByte();
1562 position.bound_index = nextByte();
1563 break;
1564 // class extends or implements clause
1565 case CLASS_EXTENDS:
1566 position.type_index = nextChar();
1567 break;
1568 // throws
1569 case THROWS:
1570 position.type_index = nextChar();
1571 break;
1572 // method parameter
1573 case METHOD_FORMAL_PARAMETER:
1574 position.parameter_index = nextByte();
1575 break;
1576 // type cast
1577 case CAST:
1578 // method/constructor/reference type argument
1579 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
1580 case METHOD_INVOCATION_TYPE_ARGUMENT:
1581 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
1582 case METHOD_REFERENCE_TYPE_ARGUMENT:
1583 position.offset = nextChar();
1584 position.type_index = nextByte();
1585 break;
1586 // We don't need to worry about these
1587 case METHOD_RETURN:
1588 case FIELD:
1589 break;
1590 case UNKNOWN:
1591 throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
1592 default:
1593 throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + position);
1594 }
1596 { // See whether there is location info and read it
1597 int len = nextByte();
1598 ListBuffer<Integer> loc = new ListBuffer<>();
1599 for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
1600 loc = loc.append(nextByte());
1601 position.location = TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
1602 }
1604 return position;
1605 }
1607 Attribute readAttributeValue() {
1608 char c = (char) buf[bp++];
1609 switch (c) {
1610 case 'B':
1611 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1612 case 'C':
1613 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1614 case 'D':
1615 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1616 case 'F':
1617 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1618 case 'I':
1619 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1620 case 'J':
1621 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1622 case 'S':
1623 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1624 case 'Z':
1625 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1626 case 's':
1627 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1628 case 'e':
1629 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1630 case 'c':
1631 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1632 case '[': {
1633 int n = nextChar();
1634 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1635 for (int i=0; i<n; i++)
1636 l.append(readAttributeValue());
1637 return new ArrayAttributeProxy(l.toList());
1638 }
1639 case '@':
1640 return readCompoundAnnotation();
1641 default:
1642 throw new AssertionError("unknown annotation tag '" + c + "'");
1643 }
1644 }
1646 interface ProxyVisitor extends Attribute.Visitor {
1647 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1648 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1649 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1650 }
1652 static class EnumAttributeProxy extends Attribute {
1653 Type enumType;
1654 Name enumerator;
1655 public EnumAttributeProxy(Type enumType, Name enumerator) {
1656 super(null);
1657 this.enumType = enumType;
1658 this.enumerator = enumerator;
1659 }
1660 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1661 @Override
1662 public String toString() {
1663 return "/*proxy enum*/" + enumType + "." + enumerator;
1664 }
1665 }
1667 static class ArrayAttributeProxy extends Attribute {
1668 List<Attribute> values;
1669 ArrayAttributeProxy(List<Attribute> values) {
1670 super(null);
1671 this.values = values;
1672 }
1673 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1674 @Override
1675 public String toString() {
1676 return "{" + values + "}";
1677 }
1678 }
1680 /** A temporary proxy representing a compound attribute.
1681 */
1682 static class CompoundAnnotationProxy extends Attribute {
1683 final List<Pair<Name,Attribute>> values;
1684 public CompoundAnnotationProxy(Type type,
1685 List<Pair<Name,Attribute>> values) {
1686 super(type);
1687 this.values = values;
1688 }
1689 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1690 @Override
1691 public String toString() {
1692 StringBuilder buf = new StringBuilder();
1693 buf.append("@");
1694 buf.append(type.tsym.getQualifiedName());
1695 buf.append("/*proxy*/{");
1696 boolean first = true;
1697 for (List<Pair<Name,Attribute>> v = values;
1698 v.nonEmpty(); v = v.tail) {
1699 Pair<Name,Attribute> value = v.head;
1700 if (!first) buf.append(",");
1701 first = false;
1702 buf.append(value.fst);
1703 buf.append("=");
1704 buf.append(value.snd);
1705 }
1706 buf.append("}");
1707 return buf.toString();
1708 }
1709 }
1711 /** A temporary proxy representing a type annotation.
1712 */
1713 static class TypeAnnotationProxy {
1714 final CompoundAnnotationProxy compound;
1715 final TypeAnnotationPosition position;
1716 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1717 TypeAnnotationPosition position) {
1718 this.compound = compound;
1719 this.position = position;
1720 }
1721 }
1723 class AnnotationDeproxy implements ProxyVisitor {
1724 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1725 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1727 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1728 // also must fill in types!!!!
1729 ListBuffer<Attribute.Compound> buf =
1730 new ListBuffer<Attribute.Compound>();
1731 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1732 buf.append(deproxyCompound(l.head));
1733 }
1734 return buf.toList();
1735 }
1737 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1738 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1739 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1740 for (List<Pair<Name,Attribute>> l = a.values;
1741 l.nonEmpty();
1742 l = l.tail) {
1743 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1744 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1745 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1746 }
1747 return new Attribute.Compound(a.type, buf.toList());
1748 }
1750 MethodSymbol findAccessMethod(Type container, Name name) {
1751 CompletionFailure failure = null;
1752 try {
1753 for (Scope.Entry e = container.tsym.members().lookup(name);
1754 e.scope != null;
1755 e = e.next()) {
1756 Symbol sym = e.sym;
1757 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1758 return (MethodSymbol) sym;
1759 }
1760 } catch (CompletionFailure ex) {
1761 failure = ex;
1762 }
1763 // The method wasn't found: emit a warning and recover
1764 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1765 try {
1766 if (failure == null) {
1767 log.warning("annotation.method.not.found",
1768 container,
1769 name);
1770 } else {
1771 log.warning("annotation.method.not.found.reason",
1772 container,
1773 name,
1774 failure.getDetailValue());//diagnostic, if present
1775 }
1776 } finally {
1777 log.useSource(prevSource);
1778 }
1779 // Construct a new method type and symbol. Use bottom
1780 // type (typeof null) as return type because this type is
1781 // a subtype of all reference types and can be converted
1782 // to primitive types by unboxing.
1783 MethodType mt = new MethodType(List.<Type>nil(),
1784 syms.botType,
1785 List.<Type>nil(),
1786 syms.methodClass);
1787 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1788 }
1790 Attribute result;
1791 Type type;
1792 Attribute deproxy(Type t, Attribute a) {
1793 Type oldType = type;
1794 try {
1795 type = t;
1796 a.accept(this);
1797 return result;
1798 } finally {
1799 type = oldType;
1800 }
1801 }
1803 // implement Attribute.Visitor below
1805 public void visitConstant(Attribute.Constant value) {
1806 // assert value.type == type;
1807 result = value;
1808 }
1810 public void visitClass(Attribute.Class clazz) {
1811 result = clazz;
1812 }
1814 public void visitEnum(Attribute.Enum e) {
1815 throw new AssertionError(); // shouldn't happen
1816 }
1818 public void visitCompound(Attribute.Compound compound) {
1819 throw new AssertionError(); // shouldn't happen
1820 }
1822 public void visitArray(Attribute.Array array) {
1823 throw new AssertionError(); // shouldn't happen
1824 }
1826 public void visitError(Attribute.Error e) {
1827 throw new AssertionError(); // shouldn't happen
1828 }
1830 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1831 // type.tsym.flatName() should == proxy.enumFlatName
1832 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1833 VarSymbol enumerator = null;
1834 CompletionFailure failure = null;
1835 try {
1836 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1837 e.scope != null;
1838 e = e.next()) {
1839 if (e.sym.kind == VAR) {
1840 enumerator = (VarSymbol)e.sym;
1841 break;
1842 }
1843 }
1844 }
1845 catch (CompletionFailure ex) {
1846 failure = ex;
1847 }
1848 if (enumerator == null) {
1849 if (failure != null) {
1850 log.warning("unknown.enum.constant.reason",
1851 currentClassFile, enumTypeSym, proxy.enumerator,
1852 failure.getDiagnostic());
1853 } else {
1854 log.warning("unknown.enum.constant",
1855 currentClassFile, enumTypeSym, proxy.enumerator);
1856 }
1857 result = new Attribute.Enum(enumTypeSym.type,
1858 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1859 } else {
1860 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1861 }
1862 }
1864 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1865 int length = proxy.values.length();
1866 Attribute[] ats = new Attribute[length];
1867 Type elemtype = types.elemtype(type);
1868 int i = 0;
1869 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1870 ats[i++] = deproxy(elemtype, p.head);
1871 }
1872 result = new Attribute.Array(type, ats);
1873 }
1875 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1876 result = deproxyCompound(proxy);
1877 }
1878 }
1880 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1881 final MethodSymbol sym;
1882 final Attribute value;
1883 final JavaFileObject classFile = currentClassFile;
1884 @Override
1885 public String toString() {
1886 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1887 }
1888 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1889 this.sym = sym;
1890 this.value = value;
1891 }
1892 // implement Annotate.Annotator.enterAnnotation()
1893 public void enterAnnotation() {
1894 JavaFileObject previousClassFile = currentClassFile;
1895 try {
1896 // Reset the interim value set earlier in
1897 // attachAnnotationDefault().
1898 sym.defaultValue = null;
1899 currentClassFile = classFile;
1900 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1901 } finally {
1902 currentClassFile = previousClassFile;
1903 }
1904 }
1905 }
1907 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1908 final Symbol sym;
1909 final List<CompoundAnnotationProxy> l;
1910 final JavaFileObject classFile;
1911 @Override
1912 public String toString() {
1913 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1914 }
1915 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1916 this.sym = sym;
1917 this.l = l;
1918 this.classFile = currentClassFile;
1919 }
1920 // implement Annotate.Annotator.enterAnnotation()
1921 public void enterAnnotation() {
1922 JavaFileObject previousClassFile = currentClassFile;
1923 try {
1924 currentClassFile = classFile;
1925 List<Attribute.Compound> newList = deproxyCompoundList(l);
1926 if (sym.annotationsPendingCompletion()) {
1927 sym.setDeclarationAttributes(newList);
1928 } else {
1929 sym.appendAttributes(newList);
1930 }
1931 } finally {
1932 currentClassFile = previousClassFile;
1933 }
1934 }
1935 }
1937 class TypeAnnotationCompleter extends AnnotationCompleter {
1939 List<TypeAnnotationProxy> proxies;
1941 TypeAnnotationCompleter(Symbol sym,
1942 List<TypeAnnotationProxy> proxies) {
1943 super(sym, List.<CompoundAnnotationProxy>nil());
1944 this.proxies = proxies;
1945 }
1947 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
1948 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
1949 for (TypeAnnotationProxy proxy: proxies) {
1950 Attribute.Compound compound = deproxyCompound(proxy.compound);
1951 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
1952 buf.add(typeCompound);
1953 }
1954 return buf.toList();
1955 }
1957 @Override
1958 public void enterAnnotation() {
1959 JavaFileObject previousClassFile = currentClassFile;
1960 try {
1961 currentClassFile = classFile;
1962 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
1963 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
1964 } finally {
1965 currentClassFile = previousClassFile;
1966 }
1967 }
1968 }
1971 /************************************************************************
1972 * Reading Symbols
1973 ***********************************************************************/
1975 /** Read a field.
1976 */
1977 VarSymbol readField() {
1978 long flags = adjustFieldFlags(nextChar());
1979 Name name = readName(nextChar());
1980 Type type = readType(nextChar());
1981 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1982 readMemberAttrs(v);
1983 return v;
1984 }
1986 /** Read a method.
1987 */
1988 MethodSymbol readMethod() {
1989 long flags = adjustMethodFlags(nextChar());
1990 Name name = readName(nextChar());
1991 Type type = readType(nextChar());
1992 if (currentOwner.isInterface() &&
1993 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
1994 if (majorVersion > Target.JDK1_8.majorVersion ||
1995 (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
1996 currentOwner.flags_field |= DEFAULT;
1997 flags |= DEFAULT | ABSTRACT;
1998 } else {
1999 //protect against ill-formed classfiles
2000 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
2001 }
2002 }
2003 if (name == names.init && currentOwner.hasOuterInstance()) {
2004 // Sometimes anonymous classes don't have an outer
2005 // instance, however, there is no reliable way to tell so
2006 // we never strip this$n
2007 if (!currentOwner.name.isEmpty())
2008 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
2009 type.getReturnType(),
2010 type.getThrownTypes(),
2011 syms.methodClass);
2012 }
2013 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
2014 if (types.isSignaturePolymorphic(m)) {
2015 m.flags_field |= SIGNATURE_POLYMORPHIC;
2016 }
2017 if (saveParameterNames)
2018 initParameterNames(m);
2019 Symbol prevOwner = currentOwner;
2020 currentOwner = m;
2021 try {
2022 readMemberAttrs(m);
2023 } finally {
2024 currentOwner = prevOwner;
2025 }
2026 if (saveParameterNames)
2027 setParameterNames(m, type);
2028 return m;
2029 }
2031 private List<Type> adjustMethodParams(long flags, List<Type> args) {
2032 boolean isVarargs = (flags & VARARGS) != 0;
2033 if (isVarargs) {
2034 Type varargsElem = args.last();
2035 ListBuffer<Type> adjustedArgs = new ListBuffer<>();
2036 for (Type t : args) {
2037 adjustedArgs.append(t != varargsElem ?
2038 t :
2039 ((ArrayType)t).makeVarargs());
2040 }
2041 args = adjustedArgs.toList();
2042 }
2043 return args.tail;
2044 }
2046 /**
2047 * Init the parameter names array.
2048 * Parameter names are currently inferred from the names in the
2049 * LocalVariableTable attributes of a Code attribute.
2050 * (Note: this means parameter names are currently not available for
2051 * methods without a Code attribute.)
2052 * This method initializes an array in which to store the name indexes
2053 * of parameter names found in LocalVariableTable attributes. It is
2054 * slightly supersized to allow for additional slots with a start_pc of 0.
2055 */
2056 void initParameterNames(MethodSymbol sym) {
2057 // make allowance for synthetic parameters.
2058 final int excessSlots = 4;
2059 int expectedParameterSlots =
2060 Code.width(sym.type.getParameterTypes()) + excessSlots;
2061 if (parameterNameIndices == null
2062 || parameterNameIndices.length < expectedParameterSlots) {
2063 parameterNameIndices = new int[expectedParameterSlots];
2064 } else
2065 Arrays.fill(parameterNameIndices, 0);
2066 haveParameterNameIndices = false;
2067 sawMethodParameters = false;
2068 }
2070 /**
2071 * Set the parameter names for a symbol from the name index in the
2072 * parameterNameIndicies array. The type of the symbol may have changed
2073 * while reading the method attributes (see the Signature attribute).
2074 * This may be because of generic information or because anonymous
2075 * synthetic parameters were added. The original type (as read from
2076 * the method descriptor) is used to help guess the existence of
2077 * anonymous synthetic parameters.
2078 * On completion, sym.savedParameter names will either be null (if
2079 * no parameter names were found in the class file) or will be set to a
2080 * list of names, one per entry in sym.type.getParameterTypes, with
2081 * any missing names represented by the empty name.
2082 */
2083 void setParameterNames(MethodSymbol sym, Type jvmType) {
2084 // if no names were found in the class file, there's nothing more to do
2085 if (!haveParameterNameIndices)
2086 return;
2087 // If we get parameter names from MethodParameters, then we
2088 // don't need to skip.
2089 int firstParam = 0;
2090 if (!sawMethodParameters) {
2091 firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
2092 // the code in readMethod may have skipped the first
2093 // parameter when setting up the MethodType. If so, we
2094 // make a corresponding allowance here for the position of
2095 // the first parameter. Note that this assumes the
2096 // skipped parameter has a width of 1 -- i.e. it is not
2097 // a double width type (long or double.)
2098 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
2099 // Sometimes anonymous classes don't have an outer
2100 // instance, however, there is no reliable way to tell so
2101 // we never strip this$n
2102 if (!currentOwner.name.isEmpty())
2103 firstParam += 1;
2104 }
2106 if (sym.type != jvmType) {
2107 // reading the method attributes has caused the
2108 // symbol's type to be changed. (i.e. the Signature
2109 // attribute.) This may happen if there are hidden
2110 // (synthetic) parameters in the descriptor, but not
2111 // in the Signature. The position of these hidden
2112 // parameters is unspecified; for now, assume they are
2113 // at the beginning, and so skip over them. The
2114 // primary case for this is two hidden parameters
2115 // passed into Enum constructors.
2116 int skip = Code.width(jvmType.getParameterTypes())
2117 - Code.width(sym.type.getParameterTypes());
2118 firstParam += skip;
2119 }
2120 }
2121 List<Name> paramNames = List.nil();
2122 int index = firstParam;
2123 for (Type t: sym.type.getParameterTypes()) {
2124 int nameIdx = (index < parameterNameIndices.length
2125 ? parameterNameIndices[index] : 0);
2126 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
2127 paramNames = paramNames.prepend(name);
2128 index += Code.width(t);
2129 }
2130 sym.savedParameterNames = paramNames.reverse();
2131 }
2133 /**
2134 * skip n bytes
2135 */
2136 void skipBytes(int n) {
2137 bp = bp + n;
2138 }
2140 /** Skip a field or method
2141 */
2142 void skipMember() {
2143 bp = bp + 6;
2144 char ac = nextChar();
2145 for (int i = 0; i < ac; i++) {
2146 bp = bp + 2;
2147 int attrLen = nextInt();
2148 bp = bp + attrLen;
2149 }
2150 }
2152 /** Enter type variables of this classtype and all enclosing ones in
2153 * `typevars'.
2154 */
2155 protected void enterTypevars(Type t) {
2156 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
2157 enterTypevars(t.getEnclosingType());
2158 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
2159 typevars.enter(xs.head.tsym);
2160 }
2162 protected void enterTypevars(Symbol sym) {
2163 if (sym.owner.kind == MTH) {
2164 enterTypevars(sym.owner);
2165 enterTypevars(sym.owner.owner);
2166 }
2167 enterTypevars(sym.type);
2168 }
2170 /** Read contents of a given class symbol `c'. Both external and internal
2171 * versions of an inner class are read.
2172 */
2173 void readClass(ClassSymbol c) {
2174 ClassType ct = (ClassType)c.type;
2176 // allocate scope for members
2177 c.members_field = new Scope(c);
2179 // prepare type variable table
2180 typevars = typevars.dup(currentOwner);
2181 if (ct.getEnclosingType().hasTag(CLASS))
2182 enterTypevars(ct.getEnclosingType());
2184 // read flags, or skip if this is an inner class
2185 long flags = adjustClassFlags(nextChar());
2186 if (c.owner.kind == PCK) c.flags_field = flags;
2188 // read own class name and check that it matches
2189 ClassSymbol self = readClassSymbol(nextChar());
2190 if (c != self)
2191 throw badClassFile("class.file.wrong.class",
2192 self.flatname);
2194 // class attributes must be read before class
2195 // skip ahead to read class attributes
2196 int startbp = bp;
2197 nextChar();
2198 char interfaceCount = nextChar();
2199 bp += interfaceCount * 2;
2200 char fieldCount = nextChar();
2201 for (int i = 0; i < fieldCount; i++) skipMember();
2202 char methodCount = nextChar();
2203 for (int i = 0; i < methodCount; i++) skipMember();
2204 readClassAttrs(c);
2206 if (readAllOfClassFile) {
2207 for (int i = 1; i < poolObj.length; i++) readPool(i);
2208 c.pool = new Pool(poolObj.length, poolObj, types);
2209 }
2211 // reset and read rest of classinfo
2212 bp = startbp;
2213 int n = nextChar();
2214 if (ct.supertype_field == null)
2215 ct.supertype_field = (n == 0)
2216 ? Type.noType
2217 : readClassSymbol(n).erasure(types);
2218 n = nextChar();
2219 List<Type> is = List.nil();
2220 for (int i = 0; i < n; i++) {
2221 Type _inter = readClassSymbol(nextChar()).erasure(types);
2222 is = is.prepend(_inter);
2223 }
2224 if (ct.interfaces_field == null)
2225 ct.interfaces_field = is.reverse();
2227 Assert.check(fieldCount == nextChar());
2228 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2229 Assert.check(methodCount == nextChar());
2230 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2232 typevars = typevars.leave();
2233 }
2235 /** Read inner class info. For each inner/outer pair allocate a
2236 * member class.
2237 */
2238 void readInnerClasses(ClassSymbol c) {
2239 int n = nextChar();
2240 for (int i = 0; i < n; i++) {
2241 nextChar(); // skip inner class symbol
2242 ClassSymbol outer = readClassSymbol(nextChar());
2243 Name name = readName(nextChar());
2244 if (name == null) name = names.empty;
2245 long flags = adjustClassFlags(nextChar());
2246 if (outer != null) { // we have a member class
2247 if (name == names.empty)
2248 name = names.one;
2249 ClassSymbol member = enterClass(name, outer);
2250 if ((flags & STATIC) == 0) {
2251 ((ClassType)member.type).setEnclosingType(outer.type);
2252 if (member.erasure_field != null)
2253 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2254 }
2255 if (c == outer) {
2256 member.flags_field = flags;
2257 enterMember(c, member);
2258 }
2259 }
2260 }
2261 }
2263 /** Read a class file.
2264 */
2265 private void readClassFile(ClassSymbol c) throws IOException {
2266 int magic = nextInt();
2267 if (magic != JAVA_MAGIC)
2268 throw badClassFile("illegal.start.of.class.file");
2270 minorVersion = nextChar();
2271 majorVersion = nextChar();
2272 int maxMajor = Target.MAX().majorVersion;
2273 int maxMinor = Target.MAX().minorVersion;
2274 if (majorVersion > maxMajor ||
2275 majorVersion * 1000 + minorVersion <
2276 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2277 {
2278 if (majorVersion == (maxMajor + 1))
2279 log.warning("big.major.version",
2280 currentClassFile,
2281 majorVersion,
2282 maxMajor);
2283 else
2284 throw badClassFile("wrong.version",
2285 Integer.toString(majorVersion),
2286 Integer.toString(minorVersion),
2287 Integer.toString(maxMajor),
2288 Integer.toString(maxMinor));
2289 }
2290 else if (checkClassFile &&
2291 majorVersion == maxMajor &&
2292 minorVersion > maxMinor)
2293 {
2294 printCCF("found.later.version",
2295 Integer.toString(minorVersion));
2296 }
2297 indexPool();
2298 if (signatureBuffer.length < bp) {
2299 int ns = Integer.highestOneBit(bp) << 1;
2300 signatureBuffer = new byte[ns];
2301 }
2302 readClass(c);
2303 }
2305 /************************************************************************
2306 * Adjusting flags
2307 ***********************************************************************/
2309 long adjustFieldFlags(long flags) {
2310 return flags;
2311 }
2312 long adjustMethodFlags(long flags) {
2313 if ((flags & ACC_BRIDGE) != 0) {
2314 flags &= ~ACC_BRIDGE;
2315 flags |= BRIDGE;
2316 if (!allowGenerics)
2317 flags &= ~SYNTHETIC;
2318 }
2319 if ((flags & ACC_VARARGS) != 0) {
2320 flags &= ~ACC_VARARGS;
2321 flags |= VARARGS;
2322 }
2323 return flags;
2324 }
2325 long adjustClassFlags(long flags) {
2326 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2327 }
2329 /************************************************************************
2330 * Loading Classes
2331 ***********************************************************************/
2333 /** Define a new class given its name and owner.
2334 */
2335 public ClassSymbol defineClass(Name name, Symbol owner) {
2336 ClassSymbol c = new ClassSymbol(0, name, owner);
2337 if (owner.kind == PCK)
2338 Assert.checkNull(classes.get(c.flatname), c);
2339 c.completer = thisCompleter;
2340 return c;
2341 }
2343 /** Create a new toplevel or member class symbol with given name
2344 * and owner and enter in `classes' unless already there.
2345 */
2346 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2347 Name flatname = TypeSymbol.formFlatName(name, owner);
2348 ClassSymbol c = classes.get(flatname);
2349 if (c == null) {
2350 c = defineClass(name, owner);
2351 classes.put(flatname, c);
2352 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2353 // reassign fields of classes that might have been loaded with
2354 // their flat names.
2355 c.owner.members().remove(c);
2356 c.name = name;
2357 c.owner = owner;
2358 c.fullname = ClassSymbol.formFullName(name, owner);
2359 }
2360 return c;
2361 }
2363 /**
2364 * Creates a new toplevel class symbol with given flat name and
2365 * given class (or source) file.
2366 *
2367 * @param flatName a fully qualified binary class name
2368 * @param classFile the class file or compilation unit defining
2369 * the class (may be {@code null})
2370 * @return a newly created class symbol
2371 * @throws AssertionError if the class symbol already exists
2372 */
2373 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2374 ClassSymbol cs = classes.get(flatName);
2375 if (cs != null) {
2376 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2377 cs.fullname,
2378 cs.completer,
2379 cs.classfile,
2380 cs.sourcefile);
2381 throw new AssertionError(msg);
2382 }
2383 Name packageName = Convert.packagePart(flatName);
2384 PackageSymbol owner = packageName.isEmpty()
2385 ? syms.unnamedPackage
2386 : enterPackage(packageName);
2387 cs = defineClass(Convert.shortName(flatName), owner);
2388 cs.classfile = classFile;
2389 classes.put(flatName, cs);
2390 return cs;
2391 }
2393 /** Create a new member or toplevel class symbol with given flat name
2394 * and enter in `classes' unless already there.
2395 */
2396 public ClassSymbol enterClass(Name flatname) {
2397 ClassSymbol c = classes.get(flatname);
2398 if (c == null)
2399 return enterClass(flatname, (JavaFileObject)null);
2400 else
2401 return c;
2402 }
2404 private boolean suppressFlush = false;
2406 /** Completion for classes to be loaded. Before a class is loaded
2407 * we make sure its enclosing class (if any) is loaded.
2408 */
2409 private void complete(Symbol sym) throws CompletionFailure {
2410 if (sym.kind == TYP) {
2411 ClassSymbol c = (ClassSymbol)sym;
2412 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2413 boolean saveSuppressFlush = suppressFlush;
2414 suppressFlush = true;
2415 try {
2416 completeOwners(c.owner);
2417 completeEnclosing(c);
2418 } finally {
2419 suppressFlush = saveSuppressFlush;
2420 }
2421 fillIn(c);
2422 } else if (sym.kind == PCK) {
2423 PackageSymbol p = (PackageSymbol)sym;
2424 try {
2425 fillIn(p);
2426 } catch (IOException ex) {
2427 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2428 }
2429 }
2430 if (!filling && !suppressFlush)
2431 annotate.flush(); // finish attaching annotations
2432 }
2434 /** complete up through the enclosing package. */
2435 private void completeOwners(Symbol o) {
2436 if (o.kind != PCK) completeOwners(o.owner);
2437 o.complete();
2438 }
2440 /**
2441 * Tries to complete lexically enclosing classes if c looks like a
2442 * nested class. This is similar to completeOwners but handles
2443 * the situation when a nested class is accessed directly as it is
2444 * possible with the Tree API or javax.lang.model.*.
2445 */
2446 private void completeEnclosing(ClassSymbol c) {
2447 if (c.owner.kind == PCK) {
2448 Symbol owner = c.owner;
2449 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2450 Symbol encl = owner.members().lookup(name).sym;
2451 if (encl == null)
2452 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2453 if (encl != null)
2454 encl.complete();
2455 }
2456 }
2457 }
2459 /** We can only read a single class file at a time; this
2460 * flag keeps track of when we are currently reading a class
2461 * file.
2462 */
2463 private boolean filling = false;
2465 /** Fill in definition of class `c' from corresponding class or
2466 * source file.
2467 */
2468 private void fillIn(ClassSymbol c) {
2469 if (completionFailureName == c.fullname) {
2470 throw new CompletionFailure(c, "user-selected completion failure by class name");
2471 }
2472 currentOwner = c;
2473 warnedAttrs.clear();
2474 JavaFileObject classfile = c.classfile;
2475 if (classfile != null) {
2476 JavaFileObject previousClassFile = currentClassFile;
2477 try {
2478 if (filling) {
2479 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2480 }
2481 currentClassFile = classfile;
2482 if (verbose) {
2483 log.printVerbose("loading", currentClassFile.toString());
2484 }
2485 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2486 filling = true;
2487 try {
2488 bp = 0;
2489 buf = readInputStream(buf, classfile.openInputStream());
2490 readClassFile(c);
2491 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2492 List<Type> missing = missingTypeVariables;
2493 List<Type> found = foundTypeVariables;
2494 missingTypeVariables = List.nil();
2495 foundTypeVariables = List.nil();
2496 filling = false;
2497 ClassType ct = (ClassType)currentOwner.type;
2498 ct.supertype_field =
2499 types.subst(ct.supertype_field, missing, found);
2500 ct.interfaces_field =
2501 types.subst(ct.interfaces_field, missing, found);
2502 } else if (missingTypeVariables.isEmpty() !=
2503 foundTypeVariables.isEmpty()) {
2504 Name name = missingTypeVariables.head.tsym.name;
2505 throw badClassFile("undecl.type.var", name);
2506 }
2507 } finally {
2508 missingTypeVariables = List.nil();
2509 foundTypeVariables = List.nil();
2510 filling = false;
2511 }
2512 } else {
2513 if (sourceCompleter != null) {
2514 sourceCompleter.complete(c);
2515 } else {
2516 throw new IllegalStateException("Source completer required to read "
2517 + classfile.toUri());
2518 }
2519 }
2520 return;
2521 } catch (IOException ex) {
2522 throw badClassFile("unable.to.access.file", ex.getMessage());
2523 } finally {
2524 currentClassFile = previousClassFile;
2525 }
2526 } else {
2527 JCDiagnostic diag =
2528 diagFactory.fragment("class.file.not.found", c.flatname);
2529 throw
2530 newCompletionFailure(c, diag);
2531 }
2532 }
2533 // where
2534 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2535 try {
2536 buf = ensureCapacity(buf, s.available());
2537 int r = s.read(buf);
2538 int bp = 0;
2539 while (r != -1) {
2540 bp += r;
2541 buf = ensureCapacity(buf, bp);
2542 r = s.read(buf, bp, buf.length - bp);
2543 }
2544 return buf;
2545 } finally {
2546 try {
2547 s.close();
2548 } catch (IOException e) {
2549 /* Ignore any errors, as this stream may have already
2550 * thrown a related exception which is the one that
2551 * should be reported.
2552 */
2553 }
2554 }
2555 }
2556 /*
2557 * ensureCapacity will increase the buffer as needed, taking note that
2558 * the new buffer will always be greater than the needed and never
2559 * exactly equal to the needed size or bp. If equal then the read (above)
2560 * will infinitely loop as buf.length - bp == 0.
2561 */
2562 private static byte[] ensureCapacity(byte[] buf, int needed) {
2563 if (buf.length <= needed) {
2564 byte[] old = buf;
2565 buf = new byte[Integer.highestOneBit(needed) << 1];
2566 System.arraycopy(old, 0, buf, 0, old.length);
2567 }
2568 return buf;
2569 }
2570 /** Static factory for CompletionFailure objects.
2571 * In practice, only one can be used at a time, so we share one
2572 * to reduce the expense of allocating new exception objects.
2573 */
2574 private CompletionFailure newCompletionFailure(TypeSymbol c,
2575 JCDiagnostic diag) {
2576 if (!cacheCompletionFailure) {
2577 // log.warning("proc.messager",
2578 // Log.getLocalizedString("class.file.not.found", c.flatname));
2579 // c.debug.printStackTrace();
2580 return new CompletionFailure(c, diag);
2581 } else {
2582 CompletionFailure result = cachedCompletionFailure;
2583 result.sym = c;
2584 result.diag = diag;
2585 return result;
2586 }
2587 }
2588 private CompletionFailure cachedCompletionFailure =
2589 new CompletionFailure(null, (JCDiagnostic) null);
2590 {
2591 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2592 }
2594 /** Load a toplevel class with given fully qualified name
2595 * The class is entered into `classes' only if load was successful.
2596 */
2597 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2598 boolean absent = classes.get(flatname) == null;
2599 ClassSymbol c = enterClass(flatname);
2600 if (c.members_field == null && c.completer != null) {
2601 try {
2602 c.complete();
2603 } catch (CompletionFailure ex) {
2604 if (absent) classes.remove(flatname);
2605 throw ex;
2606 }
2607 }
2608 return c;
2609 }
2611 /************************************************************************
2612 * Loading Packages
2613 ***********************************************************************/
2615 /** Check to see if a package exists, given its fully qualified name.
2616 */
2617 public boolean packageExists(Name fullname) {
2618 return enterPackage(fullname).exists();
2619 }
2621 /** Make a package, given its fully qualified name.
2622 */
2623 public PackageSymbol enterPackage(Name fullname) {
2624 PackageSymbol p = packages.get(fullname);
2625 if (p == null) {
2626 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2627 p = new PackageSymbol(
2628 Convert.shortName(fullname),
2629 enterPackage(Convert.packagePart(fullname)));
2630 p.completer = thisCompleter;
2631 packages.put(fullname, p);
2632 }
2633 return p;
2634 }
2636 /** Make a package, given its unqualified name and enclosing package.
2637 */
2638 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2639 return enterPackage(TypeSymbol.formFullName(name, owner));
2640 }
2642 /** Include class corresponding to given class file in package,
2643 * unless (1) we already have one the same kind (.class or .java), or
2644 * (2) we have one of the other kind, and the given class file
2645 * is older.
2646 */
2647 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2648 if ((p.flags_field & EXISTS) == 0)
2649 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2650 q.flags_field |= EXISTS;
2651 JavaFileObject.Kind kind = file.getKind();
2652 int seen;
2653 if (kind == JavaFileObject.Kind.CLASS)
2654 seen = CLASS_SEEN;
2655 else
2656 seen = SOURCE_SEEN;
2657 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2658 int lastDot = binaryName.lastIndexOf(".");
2659 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2660 boolean isPkgInfo = classname == names.package_info;
2661 ClassSymbol c = isPkgInfo
2662 ? p.package_info
2663 : (ClassSymbol) p.members_field.lookup(classname).sym;
2664 if (c == null) {
2665 c = enterClass(classname, p);
2666 if (c.classfile == null) // only update the file if's it's newly created
2667 c.classfile = file;
2668 if (isPkgInfo) {
2669 p.package_info = c;
2670 } else {
2671 if (c.owner == p) // it might be an inner class
2672 p.members_field.enter(c);
2673 }
2674 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2675 // if c.classfile == null, we are currently compiling this class
2676 // and no further action is necessary.
2677 // if (c.flags_field & seen) != 0, we have already encountered
2678 // a file of the same kind; again no further action is necessary.
2679 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2680 c.classfile = preferredFileObject(file, c.classfile);
2681 }
2682 c.flags_field |= seen;
2683 }
2685 /** Implement policy to choose to derive information from a source
2686 * file or a class file when both are present. May be overridden
2687 * by subclasses.
2688 */
2689 protected JavaFileObject preferredFileObject(JavaFileObject a,
2690 JavaFileObject b) {
2692 if (preferSource)
2693 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2694 else {
2695 long adate = a.getLastModified();
2696 long bdate = b.getLastModified();
2697 // 6449326: policy for bad lastModifiedTime in ClassReader
2698 //assert adate >= 0 && bdate >= 0;
2699 return (adate > bdate) ? a : b;
2700 }
2701 }
2703 /**
2704 * specifies types of files to be read when filling in a package symbol
2705 */
2706 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2707 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2708 }
2710 /**
2711 * this is used to support javadoc
2712 */
2713 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2714 }
2716 protected Location currentLoc; // FIXME
2718 private boolean verbosePath = true;
2720 /** Load directory of package into members scope.
2721 */
2722 private void fillIn(PackageSymbol p) throws IOException {
2723 if (p.members_field == null) p.members_field = new Scope(p);
2724 String packageName = p.fullname.toString();
2726 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2728 fillIn(p, PLATFORM_CLASS_PATH,
2729 fileManager.list(PLATFORM_CLASS_PATH,
2730 packageName,
2731 EnumSet.of(JavaFileObject.Kind.CLASS),
2732 false));
2734 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2735 classKinds.remove(JavaFileObject.Kind.SOURCE);
2736 boolean wantClassFiles = !classKinds.isEmpty();
2738 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2739 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2740 boolean wantSourceFiles = !sourceKinds.isEmpty();
2742 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2744 if (verbose && verbosePath) {
2745 if (fileManager instanceof StandardJavaFileManager) {
2746 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2747 if (haveSourcePath && wantSourceFiles) {
2748 List<File> path = List.nil();
2749 for (File file : fm.getLocation(SOURCE_PATH)) {
2750 path = path.prepend(file);
2751 }
2752 log.printVerbose("sourcepath", path.reverse().toString());
2753 } else if (wantSourceFiles) {
2754 List<File> path = List.nil();
2755 for (File file : fm.getLocation(CLASS_PATH)) {
2756 path = path.prepend(file);
2757 }
2758 log.printVerbose("sourcepath", path.reverse().toString());
2759 }
2760 if (wantClassFiles) {
2761 List<File> path = List.nil();
2762 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2763 path = path.prepend(file);
2764 }
2765 for (File file : fm.getLocation(CLASS_PATH)) {
2766 path = path.prepend(file);
2767 }
2768 log.printVerbose("classpath", path.reverse().toString());
2769 }
2770 }
2771 }
2773 if (wantSourceFiles && !haveSourcePath) {
2774 fillIn(p, CLASS_PATH,
2775 fileManager.list(CLASS_PATH,
2776 packageName,
2777 kinds,
2778 false));
2779 } else {
2780 if (wantClassFiles)
2781 fillIn(p, CLASS_PATH,
2782 fileManager.list(CLASS_PATH,
2783 packageName,
2784 classKinds,
2785 false));
2786 if (wantSourceFiles)
2787 fillIn(p, SOURCE_PATH,
2788 fileManager.list(SOURCE_PATH,
2789 packageName,
2790 sourceKinds,
2791 false));
2792 }
2793 verbosePath = false;
2794 }
2795 // where
2796 private void fillIn(PackageSymbol p,
2797 Location location,
2798 Iterable<JavaFileObject> files)
2799 {
2800 currentLoc = location;
2801 for (JavaFileObject fo : files) {
2802 switch (fo.getKind()) {
2803 case CLASS:
2804 case SOURCE: {
2805 // TODO pass binaryName to includeClassFile
2806 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2807 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2808 if (SourceVersion.isIdentifier(simpleName) ||
2809 simpleName.equals("package-info"))
2810 includeClassFile(p, fo);
2811 break;
2812 }
2813 default:
2814 extraFileActions(p, fo);
2815 }
2816 }
2817 }
2819 /** Output for "-checkclassfile" option.
2820 * @param key The key to look up the correct internationalized string.
2821 * @param arg An argument for substitution into the output string.
2822 */
2823 private void printCCF(String key, Object arg) {
2824 log.printLines(key, arg);
2825 }
2828 public interface SourceCompleter {
2829 void complete(ClassSymbol sym)
2830 throws CompletionFailure;
2831 }
2833 /**
2834 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2835 * The attribute is only the last component of the original filename, so is unlikely
2836 * to be valid as is, so operations other than those to access the name throw
2837 * UnsupportedOperationException
2838 */
2839 private static class SourceFileObject extends BaseFileObject {
2841 /** The file's name.
2842 */
2843 private Name name;
2844 private Name flatname;
2846 public SourceFileObject(Name name, Name flatname) {
2847 super(null); // no file manager; never referenced for this file object
2848 this.name = name;
2849 this.flatname = flatname;
2850 }
2852 @Override
2853 public URI toUri() {
2854 try {
2855 return new URI(null, name.toString(), null);
2856 } catch (URISyntaxException e) {
2857 throw new CannotCreateUriError(name.toString(), e);
2858 }
2859 }
2861 @Override
2862 public String getName() {
2863 return name.toString();
2864 }
2866 @Override
2867 public String getShortName() {
2868 return getName();
2869 }
2871 @Override
2872 public JavaFileObject.Kind getKind() {
2873 return getKind(getName());
2874 }
2876 @Override
2877 public InputStream openInputStream() {
2878 throw new UnsupportedOperationException();
2879 }
2881 @Override
2882 public OutputStream openOutputStream() {
2883 throw new UnsupportedOperationException();
2884 }
2886 @Override
2887 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2888 throw new UnsupportedOperationException();
2889 }
2891 @Override
2892 public Reader openReader(boolean ignoreEncodingErrors) {
2893 throw new UnsupportedOperationException();
2894 }
2896 @Override
2897 public Writer openWriter() {
2898 throw new UnsupportedOperationException();
2899 }
2901 @Override
2902 public long getLastModified() {
2903 throw new UnsupportedOperationException();
2904 }
2906 @Override
2907 public boolean delete() {
2908 throw new UnsupportedOperationException();
2909 }
2911 @Override
2912 protected String inferBinaryName(Iterable<? extends File> path) {
2913 return flatname.toString();
2914 }
2916 @Override
2917 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2918 return true; // fail-safe mode
2919 }
2921 /**
2922 * Check if two file objects are equal.
2923 * SourceFileObjects are just placeholder objects for the value of a
2924 * SourceFile attribute, and do not directly represent specific files.
2925 * Two SourceFileObjects are equal if their names are equal.
2926 */
2927 @Override
2928 public boolean equals(Object other) {
2929 if (this == other)
2930 return true;
2932 if (!(other instanceof SourceFileObject))
2933 return false;
2935 SourceFileObject o = (SourceFileObject) other;
2936 return name.equals(o.name);
2937 }
2939 @Override
2940 public int hashCode() {
2941 return name.hashCode();
2942 }
2943 }
2944 }