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