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