Mon, 21 Jan 2013 20:15:16 +0000
8005851: Remove support for synchronized interface methods
Summary: Synchronized default methods are no longer supported
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2012, 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 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC)
313 c.members_field.enter(sym);
314 }
316 /************************************************************************
317 * Error Diagnoses
318 ***********************************************************************/
321 public class BadClassFile extends CompletionFailure {
322 private static final long serialVersionUID = 0;
324 public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) {
325 super(sym, createBadClassFileDiagnostic(file, diag));
326 }
327 }
328 // where
329 private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) {
330 String key = (file.getKind() == JavaFileObject.Kind.SOURCE
331 ? "bad.source.file.header" : "bad.class.file.header");
332 return diagFactory.fragment(key, file, diag);
333 }
335 public BadClassFile badClassFile(String key, Object... args) {
336 return new BadClassFile (
337 currentOwner.enclClass(),
338 currentClassFile,
339 diagFactory.fragment(key, args));
340 }
342 /************************************************************************
343 * Buffer Access
344 ***********************************************************************/
346 /** Read a character.
347 */
348 char nextChar() {
349 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
350 }
352 /** Read a byte.
353 */
354 byte nextByte() {
355 return buf[bp++];
356 }
358 /** Read an integer.
359 */
360 int nextInt() {
361 return
362 ((buf[bp++] & 0xFF) << 24) +
363 ((buf[bp++] & 0xFF) << 16) +
364 ((buf[bp++] & 0xFF) << 8) +
365 (buf[bp++] & 0xFF);
366 }
368 /** Extract a character at position bp from buf.
369 */
370 char getChar(int bp) {
371 return
372 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
373 }
375 /** Extract an integer at position bp from buf.
376 */
377 int getInt(int bp) {
378 return
379 ((buf[bp] & 0xFF) << 24) +
380 ((buf[bp+1] & 0xFF) << 16) +
381 ((buf[bp+2] & 0xFF) << 8) +
382 (buf[bp+3] & 0xFF);
383 }
386 /** Extract a long integer at position bp from buf.
387 */
388 long getLong(int bp) {
389 DataInputStream bufin =
390 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
391 try {
392 return bufin.readLong();
393 } catch (IOException e) {
394 throw new AssertionError(e);
395 }
396 }
398 /** Extract a float at position bp from buf.
399 */
400 float getFloat(int bp) {
401 DataInputStream bufin =
402 new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
403 try {
404 return bufin.readFloat();
405 } catch (IOException e) {
406 throw new AssertionError(e);
407 }
408 }
410 /** Extract a double at position bp from buf.
411 */
412 double getDouble(int bp) {
413 DataInputStream bufin =
414 new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
415 try {
416 return bufin.readDouble();
417 } catch (IOException e) {
418 throw new AssertionError(e);
419 }
420 }
422 /************************************************************************
423 * Constant Pool Access
424 ***********************************************************************/
426 /** Index all constant pool entries, writing their start addresses into
427 * poolIdx.
428 */
429 void indexPool() {
430 poolIdx = new int[nextChar()];
431 poolObj = new Object[poolIdx.length];
432 int i = 1;
433 while (i < poolIdx.length) {
434 poolIdx[i++] = bp;
435 byte tag = buf[bp++];
436 switch (tag) {
437 case CONSTANT_Utf8: case CONSTANT_Unicode: {
438 int len = nextChar();
439 bp = bp + len;
440 break;
441 }
442 case CONSTANT_Class:
443 case CONSTANT_String:
444 case CONSTANT_MethodType:
445 bp = bp + 2;
446 break;
447 case CONSTANT_MethodHandle:
448 bp = bp + 3;
449 break;
450 case CONSTANT_Fieldref:
451 case CONSTANT_Methodref:
452 case CONSTANT_InterfaceMethodref:
453 case CONSTANT_NameandType:
454 case CONSTANT_Integer:
455 case CONSTANT_Float:
456 case CONSTANT_InvokeDynamic:
457 bp = bp + 4;
458 break;
459 case CONSTANT_Long:
460 case CONSTANT_Double:
461 bp = bp + 8;
462 i++;
463 break;
464 default:
465 throw badClassFile("bad.const.pool.tag.at",
466 Byte.toString(tag),
467 Integer.toString(bp -1));
468 }
469 }
470 }
472 /** Read constant pool entry at start address i, use pool as a cache.
473 */
474 Object readPool(int i) {
475 Object result = poolObj[i];
476 if (result != null) return result;
478 int index = poolIdx[i];
479 if (index == 0) return null;
481 byte tag = buf[index];
482 switch (tag) {
483 case CONSTANT_Utf8:
484 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
485 break;
486 case CONSTANT_Unicode:
487 throw badClassFile("unicode.str.not.supported");
488 case CONSTANT_Class:
489 poolObj[i] = readClassOrType(getChar(index + 1));
490 break;
491 case CONSTANT_String:
492 // FIXME: (footprint) do not use toString here
493 poolObj[i] = readName(getChar(index + 1)).toString();
494 break;
495 case CONSTANT_Fieldref: {
496 ClassSymbol owner = readClassSymbol(getChar(index + 1));
497 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
498 poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
499 break;
500 }
501 case CONSTANT_Methodref:
502 case CONSTANT_InterfaceMethodref: {
503 ClassSymbol owner = readClassSymbol(getChar(index + 1));
504 NameAndType nt = (NameAndType)readPool(getChar(index + 3));
505 poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
506 break;
507 }
508 case CONSTANT_NameandType:
509 poolObj[i] = new NameAndType(
510 readName(getChar(index + 1)),
511 readType(getChar(index + 3)), types);
512 break;
513 case CONSTANT_Integer:
514 poolObj[i] = getInt(index + 1);
515 break;
516 case CONSTANT_Float:
517 poolObj[i] = new Float(getFloat(index + 1));
518 break;
519 case CONSTANT_Long:
520 poolObj[i] = new Long(getLong(index + 1));
521 break;
522 case CONSTANT_Double:
523 poolObj[i] = new Double(getDouble(index + 1));
524 break;
525 case CONSTANT_MethodHandle:
526 skipBytes(4);
527 break;
528 case CONSTANT_MethodType:
529 skipBytes(3);
530 break;
531 case CONSTANT_InvokeDynamic:
532 skipBytes(5);
533 break;
534 default:
535 throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
536 }
537 return poolObj[i];
538 }
540 /** Read signature and convert to type.
541 */
542 Type readType(int i) {
543 int index = poolIdx[i];
544 return sigToType(buf, index + 3, getChar(index + 1));
545 }
547 /** If name is an array type or class signature, return the
548 * corresponding type; otherwise return a ClassSymbol with given name.
549 */
550 Object readClassOrType(int i) {
551 int index = poolIdx[i];
552 int len = getChar(index + 1);
553 int start = index + 3;
554 Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
555 // by the above assertion, the following test can be
556 // simplified to (buf[start] == '[')
557 return (buf[start] == '[' || buf[start + len - 1] == ';')
558 ? (Object)sigToType(buf, start, len)
559 : (Object)enterClass(names.fromUtf(internalize(buf, start,
560 len)));
561 }
563 /** Read signature and convert to type parameters.
564 */
565 List<Type> readTypeParams(int i) {
566 int index = poolIdx[i];
567 return sigToTypeParams(buf, index + 3, getChar(index + 1));
568 }
570 /** Read class entry.
571 */
572 ClassSymbol readClassSymbol(int i) {
573 return (ClassSymbol) (readPool(i));
574 }
576 /** Read name.
577 */
578 Name readName(int i) {
579 return (Name) (readPool(i));
580 }
582 /************************************************************************
583 * Reading Types
584 ***********************************************************************/
586 /** The unread portion of the currently read type is
587 * signature[sigp..siglimit-1].
588 */
589 byte[] signature;
590 int sigp;
591 int siglimit;
592 boolean sigEnterPhase = false;
594 /** Convert signature to type, where signature is a byte array segment.
595 */
596 Type sigToType(byte[] sig, int offset, int len) {
597 signature = sig;
598 sigp = offset;
599 siglimit = offset + len;
600 return sigToType();
601 }
603 /** Convert signature to type, where signature is implicit.
604 */
605 Type sigToType() {
606 switch ((char) signature[sigp]) {
607 case 'T':
608 sigp++;
609 int start = sigp;
610 while (signature[sigp] != ';') sigp++;
611 sigp++;
612 return sigEnterPhase
613 ? Type.noType
614 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
615 case '+': {
616 sigp++;
617 Type t = sigToType();
618 return new WildcardType(t, BoundKind.EXTENDS,
619 syms.boundClass);
620 }
621 case '*':
622 sigp++;
623 return new WildcardType(syms.objectType, BoundKind.UNBOUND,
624 syms.boundClass);
625 case '-': {
626 sigp++;
627 Type t = sigToType();
628 return new WildcardType(t, BoundKind.SUPER,
629 syms.boundClass);
630 }
631 case 'B':
632 sigp++;
633 return syms.byteType;
634 case 'C':
635 sigp++;
636 return syms.charType;
637 case 'D':
638 sigp++;
639 return syms.doubleType;
640 case 'F':
641 sigp++;
642 return syms.floatType;
643 case 'I':
644 sigp++;
645 return syms.intType;
646 case 'J':
647 sigp++;
648 return syms.longType;
649 case 'L':
650 {
651 // int oldsigp = sigp;
652 Type t = classSigToType();
653 if (sigp < siglimit && signature[sigp] == '.')
654 throw badClassFile("deprecated inner class signature syntax " +
655 "(please recompile from source)");
656 /*
657 System.err.println(" decoded " +
658 new String(signature, oldsigp, sigp-oldsigp) +
659 " => " + t + " outer " + t.outer());
660 */
661 return t;
662 }
663 case 'S':
664 sigp++;
665 return syms.shortType;
666 case 'V':
667 sigp++;
668 return syms.voidType;
669 case 'Z':
670 sigp++;
671 return syms.booleanType;
672 case '[':
673 sigp++;
674 return new ArrayType(sigToType(), syms.arrayClass);
675 case '(':
676 sigp++;
677 List<Type> argtypes = sigToTypes(')');
678 Type restype = sigToType();
679 List<Type> thrown = List.nil();
680 while (signature[sigp] == '^') {
681 sigp++;
682 thrown = thrown.prepend(sigToType());
683 }
684 return new MethodType(argtypes,
685 restype,
686 thrown.reverse(),
687 syms.methodClass);
688 case '<':
689 typevars = typevars.dup(currentOwner);
690 Type poly = new ForAll(sigToTypeParams(), sigToType());
691 typevars = typevars.leave();
692 return poly;
693 default:
694 throw badClassFile("bad.signature",
695 Convert.utf2string(signature, sigp, 10));
696 }
697 }
699 byte[] signatureBuffer = new byte[0];
700 int sbp = 0;
701 /** Convert class signature to type, where signature is implicit.
702 */
703 Type classSigToType() {
704 if (signature[sigp] != 'L')
705 throw badClassFile("bad.class.signature",
706 Convert.utf2string(signature, sigp, 10));
707 sigp++;
708 Type outer = Type.noType;
709 int startSbp = sbp;
711 while (true) {
712 final byte c = signature[sigp++];
713 switch (c) {
715 case ';': { // end
716 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
717 startSbp,
718 sbp - startSbp));
719 if (outer == Type.noType)
720 outer = t.erasure(types);
721 else
722 outer = new ClassType(outer, List.<Type>nil(), t);
723 sbp = startSbp;
724 return outer;
725 }
727 case '<': // generic arguments
728 ClassSymbol t = enterClass(names.fromUtf(signatureBuffer,
729 startSbp,
730 sbp - startSbp));
731 outer = new ClassType(outer, sigToTypes('>'), t) {
732 boolean completed = false;
733 @Override
734 public Type getEnclosingType() {
735 if (!completed) {
736 completed = true;
737 tsym.complete();
738 Type enclosingType = tsym.type.getEnclosingType();
739 if (enclosingType != Type.noType) {
740 List<Type> typeArgs =
741 super.getEnclosingType().allparams();
742 List<Type> typeParams =
743 enclosingType.allparams();
744 if (typeParams.length() != typeArgs.length()) {
745 // no "rare" types
746 super.setEnclosingType(types.erasure(enclosingType));
747 } else {
748 super.setEnclosingType(types.subst(enclosingType,
749 typeParams,
750 typeArgs));
751 }
752 } else {
753 super.setEnclosingType(Type.noType);
754 }
755 }
756 return super.getEnclosingType();
757 }
758 @Override
759 public void setEnclosingType(Type outer) {
760 throw new UnsupportedOperationException();
761 }
762 };
763 switch (signature[sigp++]) {
764 case ';':
765 if (sigp < signature.length && signature[sigp] == '.') {
766 // support old-style GJC signatures
767 // The signature produced was
768 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
769 // rather than say
770 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
771 // so we skip past ".Lfoo/Outer$"
772 sigp += (sbp - startSbp) + // "foo/Outer"
773 3; // ".L" and "$"
774 signatureBuffer[sbp++] = (byte)'$';
775 break;
776 } else {
777 sbp = startSbp;
778 return outer;
779 }
780 case '.':
781 signatureBuffer[sbp++] = (byte)'$';
782 break;
783 default:
784 throw new AssertionError(signature[sigp-1]);
785 }
786 continue;
788 case '.':
789 signatureBuffer[sbp++] = (byte)'$';
790 continue;
791 case '/':
792 signatureBuffer[sbp++] = (byte)'.';
793 continue;
794 default:
795 signatureBuffer[sbp++] = c;
796 continue;
797 }
798 }
799 }
801 /** Convert (implicit) signature to list of types
802 * until `terminator' is encountered.
803 */
804 List<Type> sigToTypes(char terminator) {
805 List<Type> head = List.of(null);
806 List<Type> tail = head;
807 while (signature[sigp] != terminator)
808 tail = tail.setTail(List.of(sigToType()));
809 sigp++;
810 return head.tail;
811 }
813 /** Convert signature to type parameters, where signature is a byte
814 * array segment.
815 */
816 List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
817 signature = sig;
818 sigp = offset;
819 siglimit = offset + len;
820 return sigToTypeParams();
821 }
823 /** Convert signature to type parameters, where signature is implicit.
824 */
825 List<Type> sigToTypeParams() {
826 List<Type> tvars = List.nil();
827 if (signature[sigp] == '<') {
828 sigp++;
829 int start = sigp;
830 sigEnterPhase = true;
831 while (signature[sigp] != '>')
832 tvars = tvars.prepend(sigToTypeParam());
833 sigEnterPhase = false;
834 sigp = start;
835 while (signature[sigp] != '>')
836 sigToTypeParam();
837 sigp++;
838 }
839 return tvars.reverse();
840 }
842 /** Convert (implicit) signature to type parameter.
843 */
844 Type sigToTypeParam() {
845 int start = sigp;
846 while (signature[sigp] != ':') sigp++;
847 Name name = names.fromUtf(signature, start, sigp - start);
848 TypeVar tvar;
849 if (sigEnterPhase) {
850 tvar = new TypeVar(name, currentOwner, syms.botType);
851 typevars.enter(tvar.tsym);
852 } else {
853 tvar = (TypeVar)findTypeVar(name);
854 }
855 List<Type> bounds = List.nil();
856 boolean allInterfaces = false;
857 if (signature[sigp] == ':' && signature[sigp+1] == ':') {
858 sigp++;
859 allInterfaces = true;
860 }
861 while (signature[sigp] == ':') {
862 sigp++;
863 bounds = bounds.prepend(sigToType());
864 }
865 if (!sigEnterPhase) {
866 types.setBounds(tvar, bounds.reverse(), allInterfaces);
867 }
868 return tvar;
869 }
871 /** Find type variable with given name in `typevars' scope.
872 */
873 Type findTypeVar(Name name) {
874 Scope.Entry e = typevars.lookup(name);
875 if (e.scope != null) {
876 return e.sym.type;
877 } else {
878 if (readingClassAttr) {
879 // While reading the class attribute, the supertypes
880 // might refer to a type variable from an enclosing element
881 // (method or class).
882 // If the type variable is defined in the enclosing class,
883 // we can actually find it in
884 // currentOwner.owner.type.getTypeArguments()
885 // However, until we have read the enclosing method attribute
886 // we don't know for sure if this owner is correct. It could
887 // be a method and there is no way to tell before reading the
888 // enclosing method attribute.
889 TypeVar t = new TypeVar(name, currentOwner, syms.botType);
890 missingTypeVariables = missingTypeVariables.prepend(t);
891 // System.err.println("Missing type var " + name);
892 return t;
893 }
894 throw badClassFile("undecl.type.var", name);
895 }
896 }
898 /************************************************************************
899 * Reading Attributes
900 ***********************************************************************/
902 protected enum AttributeKind { CLASS, MEMBER };
903 protected abstract class AttributeReader {
904 protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
905 this.name = name;
906 this.version = version;
907 this.kinds = kinds;
908 }
910 protected boolean accepts(AttributeKind kind) {
911 if (kinds.contains(kind)) {
912 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
913 return true;
915 if (lintClassfile && !warnedAttrs.contains(name)) {
916 JavaFileObject prev = log.useSource(currentClassFile);
917 try {
918 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
919 name, version.major, version.minor, majorVersion, minorVersion);
920 } finally {
921 log.useSource(prev);
922 }
923 warnedAttrs.add(name);
924 }
925 }
926 return false;
927 }
929 protected abstract void read(Symbol sym, int attrLen);
931 protected final Name name;
932 protected final ClassFile.Version version;
933 protected final Set<AttributeKind> kinds;
934 }
936 protected Set<AttributeKind> CLASS_ATTRIBUTE =
937 EnumSet.of(AttributeKind.CLASS);
938 protected Set<AttributeKind> MEMBER_ATTRIBUTE =
939 EnumSet.of(AttributeKind.MEMBER);
940 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
941 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
943 protected Map<Name, AttributeReader> attributeReaders = new HashMap<Name, AttributeReader>();
945 private void initAttributeReaders() {
946 AttributeReader[] readers = {
947 // v45.3 attributes
949 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
950 protected void read(Symbol sym, int attrLen) {
951 if (readAllOfClassFile || saveParameterNames)
952 ((MethodSymbol)sym).code = readCode(sym);
953 else
954 bp = bp + attrLen;
955 }
956 },
958 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
959 protected void read(Symbol sym, int attrLen) {
960 Object v = readPool(nextChar());
961 // Ignore ConstantValue attribute if field not final.
962 if ((sym.flags() & FINAL) != 0)
963 ((VarSymbol) sym).setData(v);
964 }
965 },
967 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
968 protected void read(Symbol sym, int attrLen) {
969 sym.flags_field |= DEPRECATED;
970 }
971 },
973 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
974 protected void read(Symbol sym, int attrLen) {
975 int nexceptions = nextChar();
976 List<Type> thrown = List.nil();
977 for (int j = 0; j < nexceptions; j++)
978 thrown = thrown.prepend(readClassSymbol(nextChar()).type);
979 if (sym.type.getThrownTypes().isEmpty())
980 sym.type.asMethodType().thrown = thrown.reverse();
981 }
982 },
984 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
985 protected void read(Symbol sym, int attrLen) {
986 ClassSymbol c = (ClassSymbol) sym;
987 readInnerClasses(c);
988 }
989 },
991 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
992 protected void read(Symbol sym, int attrLen) {
993 int newbp = bp + attrLen;
994 if (saveParameterNames && !sawMethodParameters) {
995 // Pick up parameter names from the variable table.
996 // Parameter names are not explicitly identified as such,
997 // but all parameter name entries in the LocalVariableTable
998 // have a start_pc of 0. Therefore, we record the name
999 // indicies of all slots with a start_pc of zero in the
1000 // parameterNameIndicies array.
1001 // Note that this implicitly honors the JVMS spec that
1002 // there may be more than one LocalVariableTable, and that
1003 // there is no specified ordering for the entries.
1004 int numEntries = nextChar();
1005 for (int i = 0; i < numEntries; i++) {
1006 int start_pc = nextChar();
1007 int length = nextChar();
1008 int nameIndex = nextChar();
1009 int sigIndex = nextChar();
1010 int register = nextChar();
1011 if (start_pc == 0) {
1012 // ensure array large enough
1013 if (register >= parameterNameIndices.length) {
1014 int newSize = Math.max(register, parameterNameIndices.length + 8);
1015 parameterNameIndices =
1016 Arrays.copyOf(parameterNameIndices, newSize);
1017 }
1018 parameterNameIndices[register] = nameIndex;
1019 haveParameterNameIndices = true;
1020 }
1021 }
1022 }
1023 bp = newbp;
1024 }
1025 },
1027 new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
1028 protected void read(Symbol sym, int attrlen) {
1029 int newbp = bp + attrlen;
1030 if (saveParameterNames) {
1031 sawMethodParameters = true;
1032 int numEntries = nextByte();
1033 parameterNameIndices = new int[numEntries];
1034 haveParameterNameIndices = true;
1035 for (int i = 0; i < numEntries; i++) {
1036 int nameIndex = nextChar();
1037 int flags = nextInt();
1038 parameterNameIndices[i] = nameIndex;
1039 }
1040 }
1041 bp = newbp;
1042 }
1043 },
1046 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
1047 protected void read(Symbol sym, int attrLen) {
1048 ClassSymbol c = (ClassSymbol) sym;
1049 Name n = readName(nextChar());
1050 c.sourcefile = new SourceFileObject(n, c.flatname);
1051 // If the class is a toplevel class, originating from a Java source file,
1052 // but the class name does not match the file name, then it is
1053 // an auxiliary class.
1054 String sn = n.toString();
1055 if (c.owner.kind == Kinds.PCK &&
1056 sn.endsWith(".java") &&
1057 !sn.equals(c.name.toString()+".java")) {
1058 c.flags_field |= AUXILIARY;
1059 }
1060 }
1061 },
1063 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1064 protected void read(Symbol sym, int attrLen) {
1065 // bridge methods are visible when generics not enabled
1066 if (allowGenerics || (sym.flags_field & BRIDGE) == 0)
1067 sym.flags_field |= SYNTHETIC;
1068 }
1069 },
1071 // standard v49 attributes
1073 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1074 protected void read(Symbol sym, int attrLen) {
1075 int newbp = bp + attrLen;
1076 readEnclosingMethodAttr(sym);
1077 bp = newbp;
1078 }
1079 },
1081 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1082 @Override
1083 protected boolean accepts(AttributeKind kind) {
1084 return super.accepts(kind) && allowGenerics;
1085 }
1087 protected void read(Symbol sym, int attrLen) {
1088 if (sym.kind == TYP) {
1089 ClassSymbol c = (ClassSymbol) sym;
1090 readingClassAttr = true;
1091 try {
1092 ClassType ct1 = (ClassType)c.type;
1093 Assert.check(c == currentOwner);
1094 ct1.typarams_field = readTypeParams(nextChar());
1095 ct1.supertype_field = sigToType();
1096 ListBuffer<Type> is = new ListBuffer<Type>();
1097 while (sigp != siglimit) is.append(sigToType());
1098 ct1.interfaces_field = is.toList();
1099 } finally {
1100 readingClassAttr = false;
1101 }
1102 } else {
1103 List<Type> thrown = sym.type.getThrownTypes();
1104 sym.type = readType(nextChar());
1105 //- System.err.println(" # " + sym.type);
1106 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1107 sym.type.asMethodType().thrown = thrown;
1109 }
1110 }
1111 },
1113 // v49 annotation attributes
1115 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1116 protected void read(Symbol sym, int attrLen) {
1117 attachAnnotationDefault(sym);
1118 }
1119 },
1121 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1122 protected void read(Symbol sym, int attrLen) {
1123 attachAnnotations(sym);
1124 }
1125 },
1127 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1128 protected void read(Symbol sym, int attrLen) {
1129 attachParameterAnnotations(sym);
1130 }
1131 },
1133 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1134 protected void read(Symbol sym, int attrLen) {
1135 attachAnnotations(sym);
1136 }
1137 },
1139 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1140 protected void read(Symbol sym, int attrLen) {
1141 attachParameterAnnotations(sym);
1142 }
1143 },
1145 // additional "legacy" v49 attributes, superceded by flags
1147 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1148 protected void read(Symbol sym, int attrLen) {
1149 if (allowAnnotations)
1150 sym.flags_field |= ANNOTATION;
1151 }
1152 },
1154 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1155 protected void read(Symbol sym, int attrLen) {
1156 sym.flags_field |= BRIDGE;
1157 if (!allowGenerics)
1158 sym.flags_field &= ~SYNTHETIC;
1159 }
1160 },
1162 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1163 protected void read(Symbol sym, int attrLen) {
1164 sym.flags_field |= ENUM;
1165 }
1166 },
1168 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1169 protected void read(Symbol sym, int attrLen) {
1170 if (allowVarargs)
1171 sym.flags_field |= VARARGS;
1172 }
1173 },
1175 // The following attributes for a Code attribute are not currently handled
1176 // StackMapTable
1177 // SourceDebugExtension
1178 // LineNumberTable
1179 // LocalVariableTypeTable
1180 };
1182 for (AttributeReader r: readers)
1183 attributeReaders.put(r.name, r);
1184 }
1186 /** Report unrecognized attribute.
1187 */
1188 void unrecognized(Name attrName) {
1189 if (checkClassFile)
1190 printCCF("ccf.unrecognized.attribute", attrName);
1191 }
1195 protected void readEnclosingMethodAttr(Symbol sym) {
1196 // sym is a nested class with an "Enclosing Method" attribute
1197 // remove sym from it's current owners scope and place it in
1198 // the scope specified by the attribute
1199 sym.owner.members().remove(sym);
1200 ClassSymbol self = (ClassSymbol)sym;
1201 ClassSymbol c = readClassSymbol(nextChar());
1202 NameAndType nt = (NameAndType)readPool(nextChar());
1204 if (c.members_field == null)
1205 throw badClassFile("bad.enclosing.class", self, c);
1207 MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1208 if (nt != null && m == null)
1209 throw badClassFile("bad.enclosing.method", self);
1211 self.name = simpleBinaryName(self.flatname, c.flatname) ;
1212 self.owner = m != null ? m : c;
1213 if (self.name.isEmpty())
1214 self.fullname = names.empty;
1215 else
1216 self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1218 if (m != null) {
1219 ((ClassType)sym.type).setEnclosingType(m.type);
1220 } else if ((self.flags_field & STATIC) == 0) {
1221 ((ClassType)sym.type).setEnclosingType(c.type);
1222 } else {
1223 ((ClassType)sym.type).setEnclosingType(Type.noType);
1224 }
1225 enterTypevars(self);
1226 if (!missingTypeVariables.isEmpty()) {
1227 ListBuffer<Type> typeVars = new ListBuffer<Type>();
1228 for (Type typevar : missingTypeVariables) {
1229 typeVars.append(findTypeVar(typevar.tsym.name));
1230 }
1231 foundTypeVariables = typeVars.toList();
1232 } else {
1233 foundTypeVariables = List.nil();
1234 }
1235 }
1237 // See java.lang.Class
1238 private Name simpleBinaryName(Name self, Name enclosing) {
1239 String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1240 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1241 throw badClassFile("bad.enclosing.method", self);
1242 int index = 1;
1243 while (index < simpleBinaryName.length() &&
1244 isAsciiDigit(simpleBinaryName.charAt(index)))
1245 index++;
1246 return names.fromString(simpleBinaryName.substring(index));
1247 }
1249 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1250 if (nt == null)
1251 return null;
1253 MethodType type = nt.uniqueType.type.asMethodType();
1255 for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
1256 if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
1257 return (MethodSymbol)e.sym;
1259 if (nt.name != names.init)
1260 // not a constructor
1261 return null;
1262 if ((flags & INTERFACE) != 0)
1263 // no enclosing instance
1264 return null;
1265 if (nt.uniqueType.type.getParameterTypes().isEmpty())
1266 // no parameters
1267 return null;
1269 // A constructor of an inner class.
1270 // Remove the first argument (the enclosing instance)
1271 nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
1272 nt.uniqueType.type.getReturnType(),
1273 nt.uniqueType.type.getThrownTypes(),
1274 syms.methodClass));
1275 // Try searching again
1276 return findMethod(nt, scope, flags);
1277 }
1279 /** Similar to Types.isSameType but avoids completion */
1280 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1281 List<Type> types1 = types.erasure(mt1.getParameterTypes())
1282 .prepend(types.erasure(mt1.getReturnType()));
1283 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1284 while (!types1.isEmpty() && !types2.isEmpty()) {
1285 if (types1.head.tsym != types2.head.tsym)
1286 return false;
1287 types1 = types1.tail;
1288 types2 = types2.tail;
1289 }
1290 return types1.isEmpty() && types2.isEmpty();
1291 }
1293 /**
1294 * Character.isDigit answers <tt>true</tt> to some non-ascii
1295 * digits. This one does not. <b>copied from java.lang.Class</b>
1296 */
1297 private static boolean isAsciiDigit(char c) {
1298 return '0' <= c && c <= '9';
1299 }
1301 /** Read member attributes.
1302 */
1303 void readMemberAttrs(Symbol sym) {
1304 readAttrs(sym, AttributeKind.MEMBER);
1305 }
1307 void readAttrs(Symbol sym, AttributeKind kind) {
1308 char ac = nextChar();
1309 for (int i = 0; i < ac; i++) {
1310 Name attrName = readName(nextChar());
1311 int attrLen = nextInt();
1312 AttributeReader r = attributeReaders.get(attrName);
1313 if (r != null && r.accepts(kind))
1314 r.read(sym, attrLen);
1315 else {
1316 unrecognized(attrName);
1317 bp = bp + attrLen;
1318 }
1319 }
1320 }
1322 private boolean readingClassAttr = false;
1323 private List<Type> missingTypeVariables = List.nil();
1324 private List<Type> foundTypeVariables = List.nil();
1326 /** Read class attributes.
1327 */
1328 void readClassAttrs(ClassSymbol c) {
1329 readAttrs(c, AttributeKind.CLASS);
1330 }
1332 /** Read code block.
1333 */
1334 Code readCode(Symbol owner) {
1335 nextChar(); // max_stack
1336 nextChar(); // max_locals
1337 final int code_length = nextInt();
1338 bp += code_length;
1339 final char exception_table_length = nextChar();
1340 bp += exception_table_length * 8;
1341 readMemberAttrs(owner);
1342 return null;
1343 }
1345 /************************************************************************
1346 * Reading Java-language annotations
1347 ***********************************************************************/
1349 /** Attach annotations.
1350 */
1351 void attachAnnotations(final Symbol sym) {
1352 int numAttributes = nextChar();
1353 if (numAttributes != 0) {
1354 ListBuffer<CompoundAnnotationProxy> proxies =
1355 new ListBuffer<CompoundAnnotationProxy>();
1356 for (int i = 0; i<numAttributes; i++) {
1357 CompoundAnnotationProxy proxy = readCompoundAnnotation();
1358 if (proxy.type.tsym == syms.proprietaryType.tsym)
1359 sym.flags_field |= PROPRIETARY;
1360 else
1361 proxies.append(proxy);
1362 }
1363 annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1364 }
1365 }
1367 /** Attach parameter annotations.
1368 */
1369 void attachParameterAnnotations(final Symbol method) {
1370 final MethodSymbol meth = (MethodSymbol)method;
1371 int numParameters = buf[bp++] & 0xFF;
1372 List<VarSymbol> parameters = meth.params();
1373 int pnum = 0;
1374 while (parameters.tail != null) {
1375 attachAnnotations(parameters.head);
1376 parameters = parameters.tail;
1377 pnum++;
1378 }
1379 if (pnum != numParameters) {
1380 throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1381 }
1382 }
1384 /** Attach the default value for an annotation element.
1385 */
1386 void attachAnnotationDefault(final Symbol sym) {
1387 final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1388 final Attribute value = readAttributeValue();
1390 // The default value is set later during annotation. It might
1391 // be the case that the Symbol sym is annotated _after_ the
1392 // repeating instances that depend on this default value,
1393 // because of this we set an interim value that tells us this
1394 // element (most likely) has a default.
1395 //
1396 // Set interim value for now, reset just before we do this
1397 // properly at annotate time.
1398 meth.defaultValue = value;
1399 annotate.normal(new AnnotationDefaultCompleter(meth, value));
1400 }
1402 Type readTypeOrClassSymbol(int i) {
1403 // support preliminary jsr175-format class files
1404 if (buf[poolIdx[i]] == CONSTANT_Class)
1405 return readClassSymbol(i).type;
1406 return readType(i);
1407 }
1408 Type readEnumType(int i) {
1409 // support preliminary jsr175-format class files
1410 int index = poolIdx[i];
1411 int length = getChar(index + 1);
1412 if (buf[index + length + 2] != ';')
1413 return enterClass(readName(i)).type;
1414 return readType(i);
1415 }
1417 CompoundAnnotationProxy readCompoundAnnotation() {
1418 Type t = readTypeOrClassSymbol(nextChar());
1419 int numFields = nextChar();
1420 ListBuffer<Pair<Name,Attribute>> pairs =
1421 new ListBuffer<Pair<Name,Attribute>>();
1422 for (int i=0; i<numFields; i++) {
1423 Name name = readName(nextChar());
1424 Attribute value = readAttributeValue();
1425 pairs.append(new Pair<Name,Attribute>(name, value));
1426 }
1427 return new CompoundAnnotationProxy(t, pairs.toList());
1428 }
1430 Attribute readAttributeValue() {
1431 char c = (char) buf[bp++];
1432 switch (c) {
1433 case 'B':
1434 return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1435 case 'C':
1436 return new Attribute.Constant(syms.charType, readPool(nextChar()));
1437 case 'D':
1438 return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1439 case 'F':
1440 return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1441 case 'I':
1442 return new Attribute.Constant(syms.intType, readPool(nextChar()));
1443 case 'J':
1444 return new Attribute.Constant(syms.longType, readPool(nextChar()));
1445 case 'S':
1446 return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1447 case 'Z':
1448 return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1449 case 's':
1450 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1451 case 'e':
1452 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1453 case 'c':
1454 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1455 case '[': {
1456 int n = nextChar();
1457 ListBuffer<Attribute> l = new ListBuffer<Attribute>();
1458 for (int i=0; i<n; i++)
1459 l.append(readAttributeValue());
1460 return new ArrayAttributeProxy(l.toList());
1461 }
1462 case '@':
1463 return readCompoundAnnotation();
1464 default:
1465 throw new AssertionError("unknown annotation tag '" + c + "'");
1466 }
1467 }
1469 interface ProxyVisitor extends Attribute.Visitor {
1470 void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1471 void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1472 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1473 }
1475 static class EnumAttributeProxy extends Attribute {
1476 Type enumType;
1477 Name enumerator;
1478 public EnumAttributeProxy(Type enumType, Name enumerator) {
1479 super(null);
1480 this.enumType = enumType;
1481 this.enumerator = enumerator;
1482 }
1483 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1484 @Override
1485 public String toString() {
1486 return "/*proxy enum*/" + enumType + "." + enumerator;
1487 }
1488 }
1490 static class ArrayAttributeProxy extends Attribute {
1491 List<Attribute> values;
1492 ArrayAttributeProxy(List<Attribute> values) {
1493 super(null);
1494 this.values = values;
1495 }
1496 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1497 @Override
1498 public String toString() {
1499 return "{" + values + "}";
1500 }
1501 }
1503 /** A temporary proxy representing a compound attribute.
1504 */
1505 static class CompoundAnnotationProxy extends Attribute {
1506 final List<Pair<Name,Attribute>> values;
1507 public CompoundAnnotationProxy(Type type,
1508 List<Pair<Name,Attribute>> values) {
1509 super(type);
1510 this.values = values;
1511 }
1512 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1513 @Override
1514 public String toString() {
1515 StringBuilder buf = new StringBuilder();
1516 buf.append("@");
1517 buf.append(type.tsym.getQualifiedName());
1518 buf.append("/*proxy*/{");
1519 boolean first = true;
1520 for (List<Pair<Name,Attribute>> v = values;
1521 v.nonEmpty(); v = v.tail) {
1522 Pair<Name,Attribute> value = v.head;
1523 if (!first) buf.append(",");
1524 first = false;
1525 buf.append(value.fst);
1526 buf.append("=");
1527 buf.append(value.snd);
1528 }
1529 buf.append("}");
1530 return buf.toString();
1531 }
1532 }
1534 /** A temporary proxy representing a type annotation.
1535 */
1536 static class TypeAnnotationProxy {
1537 final CompoundAnnotationProxy compound;
1538 final TypeAnnotationPosition position;
1539 public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1540 TypeAnnotationPosition position) {
1541 this.compound = compound;
1542 this.position = position;
1543 }
1544 }
1546 class AnnotationDeproxy implements ProxyVisitor {
1547 private ClassSymbol requestingOwner = currentOwner.kind == MTH
1548 ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1550 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1551 // also must fill in types!!!!
1552 ListBuffer<Attribute.Compound> buf =
1553 new ListBuffer<Attribute.Compound>();
1554 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1555 buf.append(deproxyCompound(l.head));
1556 }
1557 return buf.toList();
1558 }
1560 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1561 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf =
1562 new ListBuffer<Pair<Symbol.MethodSymbol,Attribute>>();
1563 for (List<Pair<Name,Attribute>> l = a.values;
1564 l.nonEmpty();
1565 l = l.tail) {
1566 MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1567 buf.append(new Pair<Symbol.MethodSymbol,Attribute>
1568 (meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1569 }
1570 return new Attribute.Compound(a.type, buf.toList());
1571 }
1573 MethodSymbol findAccessMethod(Type container, Name name) {
1574 CompletionFailure failure = null;
1575 try {
1576 for (Scope.Entry e = container.tsym.members().lookup(name);
1577 e.scope != null;
1578 e = e.next()) {
1579 Symbol sym = e.sym;
1580 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1581 return (MethodSymbol) sym;
1582 }
1583 } catch (CompletionFailure ex) {
1584 failure = ex;
1585 }
1586 // The method wasn't found: emit a warning and recover
1587 JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1588 try {
1589 if (failure == null) {
1590 log.warning("annotation.method.not.found",
1591 container,
1592 name);
1593 } else {
1594 log.warning("annotation.method.not.found.reason",
1595 container,
1596 name,
1597 failure.getDetailValue());//diagnostic, if present
1598 }
1599 } finally {
1600 log.useSource(prevSource);
1601 }
1602 // Construct a new method type and symbol. Use bottom
1603 // type (typeof null) as return type because this type is
1604 // a subtype of all reference types and can be converted
1605 // to primitive types by unboxing.
1606 MethodType mt = new MethodType(List.<Type>nil(),
1607 syms.botType,
1608 List.<Type>nil(),
1609 syms.methodClass);
1610 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1611 }
1613 Attribute result;
1614 Type type;
1615 Attribute deproxy(Type t, Attribute a) {
1616 Type oldType = type;
1617 try {
1618 type = t;
1619 a.accept(this);
1620 return result;
1621 } finally {
1622 type = oldType;
1623 }
1624 }
1626 // implement Attribute.Visitor below
1628 public void visitConstant(Attribute.Constant value) {
1629 // assert value.type == type;
1630 result = value;
1631 }
1633 public void visitClass(Attribute.Class clazz) {
1634 result = clazz;
1635 }
1637 public void visitEnum(Attribute.Enum e) {
1638 throw new AssertionError(); // shouldn't happen
1639 }
1641 public void visitCompound(Attribute.Compound compound) {
1642 throw new AssertionError(); // shouldn't happen
1643 }
1645 public void visitArray(Attribute.Array array) {
1646 throw new AssertionError(); // shouldn't happen
1647 }
1649 public void visitError(Attribute.Error e) {
1650 throw new AssertionError(); // shouldn't happen
1651 }
1653 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1654 // type.tsym.flatName() should == proxy.enumFlatName
1655 TypeSymbol enumTypeSym = proxy.enumType.tsym;
1656 VarSymbol enumerator = null;
1657 CompletionFailure failure = null;
1658 try {
1659 for (Scope.Entry e = enumTypeSym.members().lookup(proxy.enumerator);
1660 e.scope != null;
1661 e = e.next()) {
1662 if (e.sym.kind == VAR) {
1663 enumerator = (VarSymbol)e.sym;
1664 break;
1665 }
1666 }
1667 }
1668 catch (CompletionFailure ex) {
1669 failure = ex;
1670 }
1671 if (enumerator == null) {
1672 if (failure != null) {
1673 log.warning("unknown.enum.constant.reason",
1674 currentClassFile, enumTypeSym, proxy.enumerator,
1675 failure.getDiagnostic());
1676 } else {
1677 log.warning("unknown.enum.constant",
1678 currentClassFile, enumTypeSym, proxy.enumerator);
1679 }
1680 result = new Attribute.Enum(enumTypeSym.type,
1681 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1682 } else {
1683 result = new Attribute.Enum(enumTypeSym.type, enumerator);
1684 }
1685 }
1687 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1688 int length = proxy.values.length();
1689 Attribute[] ats = new Attribute[length];
1690 Type elemtype = types.elemtype(type);
1691 int i = 0;
1692 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1693 ats[i++] = deproxy(elemtype, p.head);
1694 }
1695 result = new Attribute.Array(type, ats);
1696 }
1698 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1699 result = deproxyCompound(proxy);
1700 }
1701 }
1703 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1704 final MethodSymbol sym;
1705 final Attribute value;
1706 final JavaFileObject classFile = currentClassFile;
1707 @Override
1708 public String toString() {
1709 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1710 }
1711 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1712 this.sym = sym;
1713 this.value = value;
1714 }
1715 // implement Annotate.Annotator.enterAnnotation()
1716 public void enterAnnotation() {
1717 JavaFileObject previousClassFile = currentClassFile;
1718 try {
1719 // Reset the interim value set earlier in
1720 // attachAnnotationDefault().
1721 sym.defaultValue = null;
1722 currentClassFile = classFile;
1723 sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1724 } finally {
1725 currentClassFile = previousClassFile;
1726 }
1727 }
1728 }
1730 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Annotator {
1731 final Symbol sym;
1732 final List<CompoundAnnotationProxy> l;
1733 final JavaFileObject classFile;
1734 @Override
1735 public String toString() {
1736 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1737 }
1738 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1739 this.sym = sym;
1740 this.l = l;
1741 this.classFile = currentClassFile;
1742 }
1743 // implement Annotate.Annotator.enterAnnotation()
1744 public void enterAnnotation() {
1745 JavaFileObject previousClassFile = currentClassFile;
1746 try {
1747 currentClassFile = classFile;
1748 Annotations annotations = sym.annotations;
1749 List<Attribute.Compound> newList = deproxyCompoundList(l);
1750 if (annotations.pendingCompletion()) {
1751 annotations.setAttributes(newList);
1752 } else {
1753 annotations.append(newList);
1754 }
1755 } finally {
1756 currentClassFile = previousClassFile;
1757 }
1758 }
1759 }
1762 /************************************************************************
1763 * Reading Symbols
1764 ***********************************************************************/
1766 /** Read a field.
1767 */
1768 VarSymbol readField() {
1769 long flags = adjustFieldFlags(nextChar());
1770 Name name = readName(nextChar());
1771 Type type = readType(nextChar());
1772 VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1773 readMemberAttrs(v);
1774 return v;
1775 }
1777 /** Read a method.
1778 */
1779 MethodSymbol readMethod() {
1780 long flags = adjustMethodFlags(nextChar());
1781 Name name = readName(nextChar());
1782 Type type = readType(nextChar());
1783 if (currentOwner.isInterface() &&
1784 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
1785 if (majorVersion > Target.JDK1_8.majorVersion ||
1786 (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) {
1787 currentOwner.flags_field |= DEFAULT;
1788 flags |= DEFAULT | ABSTRACT;
1789 } else {
1790 //protect against ill-formed classfiles
1791 throw new CompletionFailure(currentOwner, "default method found in pre JDK 8 classfile");
1792 }
1793 }
1794 if (name == names.init && currentOwner.hasOuterInstance()) {
1795 // Sometimes anonymous classes don't have an outer
1796 // instance, however, there is no reliable way to tell so
1797 // we never strip this$n
1798 if (!currentOwner.name.isEmpty())
1799 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1800 type.getReturnType(),
1801 type.getThrownTypes(),
1802 syms.methodClass);
1803 }
1804 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1805 if (saveParameterNames)
1806 initParameterNames(m);
1807 Symbol prevOwner = currentOwner;
1808 currentOwner = m;
1809 try {
1810 readMemberAttrs(m);
1811 } finally {
1812 currentOwner = prevOwner;
1813 }
1814 if (saveParameterNames)
1815 setParameterNames(m, type);
1816 return m;
1817 }
1819 private List<Type> adjustMethodParams(long flags, List<Type> args) {
1820 boolean isVarargs = (flags & VARARGS) != 0;
1821 if (isVarargs) {
1822 Type varargsElem = args.last();
1823 ListBuffer<Type> adjustedArgs = ListBuffer.lb();
1824 for (Type t : args) {
1825 adjustedArgs.append(t != varargsElem ?
1826 t :
1827 ((ArrayType)t).makeVarargs());
1828 }
1829 args = adjustedArgs.toList();
1830 }
1831 return args.tail;
1832 }
1834 /**
1835 * Init the parameter names array.
1836 * Parameter names are currently inferred from the names in the
1837 * LocalVariableTable attributes of a Code attribute.
1838 * (Note: this means parameter names are currently not available for
1839 * methods without a Code attribute.)
1840 * This method initializes an array in which to store the name indexes
1841 * of parameter names found in LocalVariableTable attributes. It is
1842 * slightly supersized to allow for additional slots with a start_pc of 0.
1843 */
1844 void initParameterNames(MethodSymbol sym) {
1845 // make allowance for synthetic parameters.
1846 final int excessSlots = 4;
1847 int expectedParameterSlots =
1848 Code.width(sym.type.getParameterTypes()) + excessSlots;
1849 if (parameterNameIndices == null
1850 || parameterNameIndices.length < expectedParameterSlots) {
1851 parameterNameIndices = new int[expectedParameterSlots];
1852 } else
1853 Arrays.fill(parameterNameIndices, 0);
1854 haveParameterNameIndices = false;
1855 sawMethodParameters = false;
1856 }
1858 /**
1859 * Set the parameter names for a symbol from the name index in the
1860 * parameterNameIndicies array. The type of the symbol may have changed
1861 * while reading the method attributes (see the Signature attribute).
1862 * This may be because of generic information or because anonymous
1863 * synthetic parameters were added. The original type (as read from
1864 * the method descriptor) is used to help guess the existence of
1865 * anonymous synthetic parameters.
1866 * On completion, sym.savedParameter names will either be null (if
1867 * no parameter names were found in the class file) or will be set to a
1868 * list of names, one per entry in sym.type.getParameterTypes, with
1869 * any missing names represented by the empty name.
1870 */
1871 void setParameterNames(MethodSymbol sym, Type jvmType) {
1872 // if no names were found in the class file, there's nothing more to do
1873 if (!haveParameterNameIndices)
1874 return;
1875 // If we get parameter names from MethodParameters, then we
1876 // don't need to skip.
1877 int firstParam = 0;
1878 if (!sawMethodParameters) {
1879 firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
1880 // the code in readMethod may have skipped the first
1881 // parameter when setting up the MethodType. If so, we
1882 // make a corresponding allowance here for the position of
1883 // the first parameter. Note that this assumes the
1884 // skipped parameter has a width of 1 -- i.e. it is not
1885 // a double width type (long or double.)
1886 if (sym.name == names.init && currentOwner.hasOuterInstance()) {
1887 // Sometimes anonymous classes don't have an outer
1888 // instance, however, there is no reliable way to tell so
1889 // we never strip this$n
1890 if (!currentOwner.name.isEmpty())
1891 firstParam += 1;
1892 }
1894 if (sym.type != jvmType) {
1895 // reading the method attributes has caused the
1896 // symbol's type to be changed. (i.e. the Signature
1897 // attribute.) This may happen if there are hidden
1898 // (synthetic) parameters in the descriptor, but not
1899 // in the Signature. The position of these hidden
1900 // parameters is unspecified; for now, assume they are
1901 // at the beginning, and so skip over them. The
1902 // primary case for this is two hidden parameters
1903 // passed into Enum constructors.
1904 int skip = Code.width(jvmType.getParameterTypes())
1905 - Code.width(sym.type.getParameterTypes());
1906 firstParam += skip;
1907 }
1908 }
1909 List<Name> paramNames = List.nil();
1910 int index = firstParam;
1911 for (Type t: sym.type.getParameterTypes()) {
1912 int nameIdx = (index < parameterNameIndices.length
1913 ? parameterNameIndices[index] : 0);
1914 Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
1915 paramNames = paramNames.prepend(name);
1916 index += Code.width(t);
1917 }
1918 sym.savedParameterNames = paramNames.reverse();
1919 }
1921 /**
1922 * skip n bytes
1923 */
1924 void skipBytes(int n) {
1925 bp = bp + n;
1926 }
1928 /** Skip a field or method
1929 */
1930 void skipMember() {
1931 bp = bp + 6;
1932 char ac = nextChar();
1933 for (int i = 0; i < ac; i++) {
1934 bp = bp + 2;
1935 int attrLen = nextInt();
1936 bp = bp + attrLen;
1937 }
1938 }
1940 /** Enter type variables of this classtype and all enclosing ones in
1941 * `typevars'.
1942 */
1943 protected void enterTypevars(Type t) {
1944 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
1945 enterTypevars(t.getEnclosingType());
1946 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
1947 typevars.enter(xs.head.tsym);
1948 }
1950 protected void enterTypevars(Symbol sym) {
1951 if (sym.owner.kind == MTH) {
1952 enterTypevars(sym.owner);
1953 enterTypevars(sym.owner.owner);
1954 }
1955 enterTypevars(sym.type);
1956 }
1958 /** Read contents of a given class symbol `c'. Both external and internal
1959 * versions of an inner class are read.
1960 */
1961 void readClass(ClassSymbol c) {
1962 ClassType ct = (ClassType)c.type;
1964 // allocate scope for members
1965 c.members_field = new Scope(c);
1967 // prepare type variable table
1968 typevars = typevars.dup(currentOwner);
1969 if (ct.getEnclosingType().hasTag(CLASS))
1970 enterTypevars(ct.getEnclosingType());
1972 // read flags, or skip if this is an inner class
1973 long flags = adjustClassFlags(nextChar());
1974 if (c.owner.kind == PCK) c.flags_field = flags;
1976 // read own class name and check that it matches
1977 ClassSymbol self = readClassSymbol(nextChar());
1978 if (c != self)
1979 throw badClassFile("class.file.wrong.class",
1980 self.flatname);
1982 // class attributes must be read before class
1983 // skip ahead to read class attributes
1984 int startbp = bp;
1985 nextChar();
1986 char interfaceCount = nextChar();
1987 bp += interfaceCount * 2;
1988 char fieldCount = nextChar();
1989 for (int i = 0; i < fieldCount; i++) skipMember();
1990 char methodCount = nextChar();
1991 for (int i = 0; i < methodCount; i++) skipMember();
1992 readClassAttrs(c);
1994 if (readAllOfClassFile) {
1995 for (int i = 1; i < poolObj.length; i++) readPool(i);
1996 c.pool = new Pool(poolObj.length, poolObj, types);
1997 }
1999 // reset and read rest of classinfo
2000 bp = startbp;
2001 int n = nextChar();
2002 if (ct.supertype_field == null)
2003 ct.supertype_field = (n == 0)
2004 ? Type.noType
2005 : readClassSymbol(n).erasure(types);
2006 n = nextChar();
2007 List<Type> is = List.nil();
2008 for (int i = 0; i < n; i++) {
2009 Type _inter = readClassSymbol(nextChar()).erasure(types);
2010 is = is.prepend(_inter);
2011 }
2012 if (ct.interfaces_field == null)
2013 ct.interfaces_field = is.reverse();
2015 Assert.check(fieldCount == nextChar());
2016 for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2017 Assert.check(methodCount == nextChar());
2018 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2020 typevars = typevars.leave();
2021 }
2023 /** Read inner class info. For each inner/outer pair allocate a
2024 * member class.
2025 */
2026 void readInnerClasses(ClassSymbol c) {
2027 int n = nextChar();
2028 for (int i = 0; i < n; i++) {
2029 nextChar(); // skip inner class symbol
2030 ClassSymbol outer = readClassSymbol(nextChar());
2031 Name name = readName(nextChar());
2032 if (name == null) name = names.empty;
2033 long flags = adjustClassFlags(nextChar());
2034 if (outer != null) { // we have a member class
2035 if (name == names.empty)
2036 name = names.one;
2037 ClassSymbol member = enterClass(name, outer);
2038 if ((flags & STATIC) == 0) {
2039 ((ClassType)member.type).setEnclosingType(outer.type);
2040 if (member.erasure_field != null)
2041 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2042 }
2043 if (c == outer) {
2044 member.flags_field = flags;
2045 enterMember(c, member);
2046 }
2047 }
2048 }
2049 }
2051 /** Read a class file.
2052 */
2053 private void readClassFile(ClassSymbol c) throws IOException {
2054 int magic = nextInt();
2055 if (magic != JAVA_MAGIC)
2056 throw badClassFile("illegal.start.of.class.file");
2058 minorVersion = nextChar();
2059 majorVersion = nextChar();
2060 int maxMajor = Target.MAX().majorVersion;
2061 int maxMinor = Target.MAX().minorVersion;
2062 if (majorVersion > maxMajor ||
2063 majorVersion * 1000 + minorVersion <
2064 Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion)
2065 {
2066 if (majorVersion == (maxMajor + 1))
2067 log.warning("big.major.version",
2068 currentClassFile,
2069 majorVersion,
2070 maxMajor);
2071 else
2072 throw badClassFile("wrong.version",
2073 Integer.toString(majorVersion),
2074 Integer.toString(minorVersion),
2075 Integer.toString(maxMajor),
2076 Integer.toString(maxMinor));
2077 }
2078 else if (checkClassFile &&
2079 majorVersion == maxMajor &&
2080 minorVersion > maxMinor)
2081 {
2082 printCCF("found.later.version",
2083 Integer.toString(minorVersion));
2084 }
2085 indexPool();
2086 if (signatureBuffer.length < bp) {
2087 int ns = Integer.highestOneBit(bp) << 1;
2088 signatureBuffer = new byte[ns];
2089 }
2090 readClass(c);
2091 }
2093 /************************************************************************
2094 * Adjusting flags
2095 ***********************************************************************/
2097 long adjustFieldFlags(long flags) {
2098 return flags;
2099 }
2100 long adjustMethodFlags(long flags) {
2101 if ((flags & ACC_BRIDGE) != 0) {
2102 flags &= ~ACC_BRIDGE;
2103 flags |= BRIDGE;
2104 if (!allowGenerics)
2105 flags &= ~SYNTHETIC;
2106 }
2107 if ((flags & ACC_VARARGS) != 0) {
2108 flags &= ~ACC_VARARGS;
2109 flags |= VARARGS;
2110 }
2111 return flags;
2112 }
2113 long adjustClassFlags(long flags) {
2114 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2115 }
2117 /************************************************************************
2118 * Loading Classes
2119 ***********************************************************************/
2121 /** Define a new class given its name and owner.
2122 */
2123 public ClassSymbol defineClass(Name name, Symbol owner) {
2124 ClassSymbol c = new ClassSymbol(0, name, owner);
2125 if (owner.kind == PCK)
2126 Assert.checkNull(classes.get(c.flatname), c);
2127 c.completer = this;
2128 return c;
2129 }
2131 /** Create a new toplevel or member class symbol with given name
2132 * and owner and enter in `classes' unless already there.
2133 */
2134 public ClassSymbol enterClass(Name name, TypeSymbol owner) {
2135 Name flatname = TypeSymbol.formFlatName(name, owner);
2136 ClassSymbol c = classes.get(flatname);
2137 if (c == null) {
2138 c = defineClass(name, owner);
2139 classes.put(flatname, c);
2140 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
2141 // reassign fields of classes that might have been loaded with
2142 // their flat names.
2143 c.owner.members().remove(c);
2144 c.name = name;
2145 c.owner = owner;
2146 c.fullname = ClassSymbol.formFullName(name, owner);
2147 }
2148 return c;
2149 }
2151 /**
2152 * Creates a new toplevel class symbol with given flat name and
2153 * given class (or source) file.
2154 *
2155 * @param flatName a fully qualified binary class name
2156 * @param classFile the class file or compilation unit defining
2157 * the class (may be {@code null})
2158 * @return a newly created class symbol
2159 * @throws AssertionError if the class symbol already exists
2160 */
2161 public ClassSymbol enterClass(Name flatName, JavaFileObject classFile) {
2162 ClassSymbol cs = classes.get(flatName);
2163 if (cs != null) {
2164 String msg = Log.format("%s: completer = %s; class file = %s; source file = %s",
2165 cs.fullname,
2166 cs.completer,
2167 cs.classfile,
2168 cs.sourcefile);
2169 throw new AssertionError(msg);
2170 }
2171 Name packageName = Convert.packagePart(flatName);
2172 PackageSymbol owner = packageName.isEmpty()
2173 ? syms.unnamedPackage
2174 : enterPackage(packageName);
2175 cs = defineClass(Convert.shortName(flatName), owner);
2176 cs.classfile = classFile;
2177 classes.put(flatName, cs);
2178 return cs;
2179 }
2181 /** Create a new member or toplevel class symbol with given flat name
2182 * and enter in `classes' unless already there.
2183 */
2184 public ClassSymbol enterClass(Name flatname) {
2185 ClassSymbol c = classes.get(flatname);
2186 if (c == null)
2187 return enterClass(flatname, (JavaFileObject)null);
2188 else
2189 return c;
2190 }
2192 private boolean suppressFlush = false;
2194 /** Completion for classes to be loaded. Before a class is loaded
2195 * we make sure its enclosing class (if any) is loaded.
2196 */
2197 public void complete(Symbol sym) throws CompletionFailure {
2198 if (sym.kind == TYP) {
2199 ClassSymbol c = (ClassSymbol)sym;
2200 c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
2201 boolean saveSuppressFlush = suppressFlush;
2202 suppressFlush = true;
2203 try {
2204 completeOwners(c.owner);
2205 completeEnclosing(c);
2206 } finally {
2207 suppressFlush = saveSuppressFlush;
2208 }
2209 fillIn(c);
2210 } else if (sym.kind == PCK) {
2211 PackageSymbol p = (PackageSymbol)sym;
2212 try {
2213 fillIn(p);
2214 } catch (IOException ex) {
2215 throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
2216 }
2217 }
2218 if (!filling && !suppressFlush)
2219 annotate.flush(); // finish attaching annotations
2220 }
2222 /** complete up through the enclosing package. */
2223 private void completeOwners(Symbol o) {
2224 if (o.kind != PCK) completeOwners(o.owner);
2225 o.complete();
2226 }
2228 /**
2229 * Tries to complete lexically enclosing classes if c looks like a
2230 * nested class. This is similar to completeOwners but handles
2231 * the situation when a nested class is accessed directly as it is
2232 * possible with the Tree API or javax.lang.model.*.
2233 */
2234 private void completeEnclosing(ClassSymbol c) {
2235 if (c.owner.kind == PCK) {
2236 Symbol owner = c.owner;
2237 for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) {
2238 Symbol encl = owner.members().lookup(name).sym;
2239 if (encl == null)
2240 encl = classes.get(TypeSymbol.formFlatName(name, owner));
2241 if (encl != null)
2242 encl.complete();
2243 }
2244 }
2245 }
2247 /** We can only read a single class file at a time; this
2248 * flag keeps track of when we are currently reading a class
2249 * file.
2250 */
2251 private boolean filling = false;
2253 /** Fill in definition of class `c' from corresponding class or
2254 * source file.
2255 */
2256 private void fillIn(ClassSymbol c) {
2257 if (completionFailureName == c.fullname) {
2258 throw new CompletionFailure(c, "user-selected completion failure by class name");
2259 }
2260 currentOwner = c;
2261 warnedAttrs.clear();
2262 JavaFileObject classfile = c.classfile;
2263 if (classfile != null) {
2264 JavaFileObject previousClassFile = currentClassFile;
2265 try {
2266 if (filling) {
2267 Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile);
2268 }
2269 currentClassFile = classfile;
2270 if (verbose) {
2271 log.printVerbose("loading", currentClassFile.toString());
2272 }
2273 if (classfile.getKind() == JavaFileObject.Kind.CLASS) {
2274 filling = true;
2275 try {
2276 bp = 0;
2277 buf = readInputStream(buf, classfile.openInputStream());
2278 readClassFile(c);
2279 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2280 List<Type> missing = missingTypeVariables;
2281 List<Type> found = foundTypeVariables;
2282 missingTypeVariables = List.nil();
2283 foundTypeVariables = List.nil();
2284 filling = false;
2285 ClassType ct = (ClassType)currentOwner.type;
2286 ct.supertype_field =
2287 types.subst(ct.supertype_field, missing, found);
2288 ct.interfaces_field =
2289 types.subst(ct.interfaces_field, missing, found);
2290 } else if (missingTypeVariables.isEmpty() !=
2291 foundTypeVariables.isEmpty()) {
2292 Name name = missingTypeVariables.head.tsym.name;
2293 throw badClassFile("undecl.type.var", name);
2294 }
2295 } finally {
2296 missingTypeVariables = List.nil();
2297 foundTypeVariables = List.nil();
2298 filling = false;
2299 }
2300 } else {
2301 if (sourceCompleter != null) {
2302 sourceCompleter.complete(c);
2303 } else {
2304 throw new IllegalStateException("Source completer required to read "
2305 + classfile.toUri());
2306 }
2307 }
2308 return;
2309 } catch (IOException ex) {
2310 throw badClassFile("unable.to.access.file", ex.getMessage());
2311 } finally {
2312 currentClassFile = previousClassFile;
2313 }
2314 } else {
2315 JCDiagnostic diag =
2316 diagFactory.fragment("class.file.not.found", c.flatname);
2317 throw
2318 newCompletionFailure(c, diag);
2319 }
2320 }
2321 // where
2322 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2323 try {
2324 buf = ensureCapacity(buf, s.available());
2325 int r = s.read(buf);
2326 int bp = 0;
2327 while (r != -1) {
2328 bp += r;
2329 buf = ensureCapacity(buf, bp);
2330 r = s.read(buf, bp, buf.length - bp);
2331 }
2332 return buf;
2333 } finally {
2334 try {
2335 s.close();
2336 } catch (IOException e) {
2337 /* Ignore any errors, as this stream may have already
2338 * thrown a related exception which is the one that
2339 * should be reported.
2340 */
2341 }
2342 }
2343 }
2344 /*
2345 * ensureCapacity will increase the buffer as needed, taking note that
2346 * the new buffer will always be greater than the needed and never
2347 * exactly equal to the needed size or bp. If equal then the read (above)
2348 * will infinitely loop as buf.length - bp == 0.
2349 */
2350 private static byte[] ensureCapacity(byte[] buf, int needed) {
2351 if (buf.length <= needed) {
2352 byte[] old = buf;
2353 buf = new byte[Integer.highestOneBit(needed) << 1];
2354 System.arraycopy(old, 0, buf, 0, old.length);
2355 }
2356 return buf;
2357 }
2358 /** Static factory for CompletionFailure objects.
2359 * In practice, only one can be used at a time, so we share one
2360 * to reduce the expense of allocating new exception objects.
2361 */
2362 private CompletionFailure newCompletionFailure(TypeSymbol c,
2363 JCDiagnostic diag) {
2364 if (!cacheCompletionFailure) {
2365 // log.warning("proc.messager",
2366 // Log.getLocalizedString("class.file.not.found", c.flatname));
2367 // c.debug.printStackTrace();
2368 return new CompletionFailure(c, diag);
2369 } else {
2370 CompletionFailure result = cachedCompletionFailure;
2371 result.sym = c;
2372 result.diag = diag;
2373 return result;
2374 }
2375 }
2376 private CompletionFailure cachedCompletionFailure =
2377 new CompletionFailure(null, (JCDiagnostic) null);
2378 {
2379 cachedCompletionFailure.setStackTrace(new StackTraceElement[0]);
2380 }
2382 /** Load a toplevel class with given fully qualified name
2383 * The class is entered into `classes' only if load was successful.
2384 */
2385 public ClassSymbol loadClass(Name flatname) throws CompletionFailure {
2386 boolean absent = classes.get(flatname) == null;
2387 ClassSymbol c = enterClass(flatname);
2388 if (c.members_field == null && c.completer != null) {
2389 try {
2390 c.complete();
2391 } catch (CompletionFailure ex) {
2392 if (absent) classes.remove(flatname);
2393 throw ex;
2394 }
2395 }
2396 return c;
2397 }
2399 /************************************************************************
2400 * Loading Packages
2401 ***********************************************************************/
2403 /** Check to see if a package exists, given its fully qualified name.
2404 */
2405 public boolean packageExists(Name fullname) {
2406 return enterPackage(fullname).exists();
2407 }
2409 /** Make a package, given its fully qualified name.
2410 */
2411 public PackageSymbol enterPackage(Name fullname) {
2412 PackageSymbol p = packages.get(fullname);
2413 if (p == null) {
2414 Assert.check(!fullname.isEmpty(), "rootPackage missing!");
2415 p = new PackageSymbol(
2416 Convert.shortName(fullname),
2417 enterPackage(Convert.packagePart(fullname)));
2418 p.completer = this;
2419 packages.put(fullname, p);
2420 }
2421 return p;
2422 }
2424 /** Make a package, given its unqualified name and enclosing package.
2425 */
2426 public PackageSymbol enterPackage(Name name, PackageSymbol owner) {
2427 return enterPackage(TypeSymbol.formFullName(name, owner));
2428 }
2430 /** Include class corresponding to given class file in package,
2431 * unless (1) we already have one the same kind (.class or .java), or
2432 * (2) we have one of the other kind, and the given class file
2433 * is older.
2434 */
2435 protected void includeClassFile(PackageSymbol p, JavaFileObject file) {
2436 if ((p.flags_field & EXISTS) == 0)
2437 for (Symbol q = p; q != null && q.kind == PCK; q = q.owner)
2438 q.flags_field |= EXISTS;
2439 JavaFileObject.Kind kind = file.getKind();
2440 int seen;
2441 if (kind == JavaFileObject.Kind.CLASS)
2442 seen = CLASS_SEEN;
2443 else
2444 seen = SOURCE_SEEN;
2445 String binaryName = fileManager.inferBinaryName(currentLoc, file);
2446 int lastDot = binaryName.lastIndexOf(".");
2447 Name classname = names.fromString(binaryName.substring(lastDot + 1));
2448 boolean isPkgInfo = classname == names.package_info;
2449 ClassSymbol c = isPkgInfo
2450 ? p.package_info
2451 : (ClassSymbol) p.members_field.lookup(classname).sym;
2452 if (c == null) {
2453 c = enterClass(classname, p);
2454 if (c.classfile == null) // only update the file if's it's newly created
2455 c.classfile = file;
2456 if (isPkgInfo) {
2457 p.package_info = c;
2458 } else {
2459 if (c.owner == p) // it might be an inner class
2460 p.members_field.enter(c);
2461 }
2462 } else if (c.classfile != null && (c.flags_field & seen) == 0) {
2463 // if c.classfile == null, we are currently compiling this class
2464 // and no further action is necessary.
2465 // if (c.flags_field & seen) != 0, we have already encountered
2466 // a file of the same kind; again no further action is necessary.
2467 if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0)
2468 c.classfile = preferredFileObject(file, c.classfile);
2469 }
2470 c.flags_field |= seen;
2471 }
2473 /** Implement policy to choose to derive information from a source
2474 * file or a class file when both are present. May be overridden
2475 * by subclasses.
2476 */
2477 protected JavaFileObject preferredFileObject(JavaFileObject a,
2478 JavaFileObject b) {
2480 if (preferSource)
2481 return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
2482 else {
2483 long adate = a.getLastModified();
2484 long bdate = b.getLastModified();
2485 // 6449326: policy for bad lastModifiedTime in ClassReader
2486 //assert adate >= 0 && bdate >= 0;
2487 return (adate > bdate) ? a : b;
2488 }
2489 }
2491 /**
2492 * specifies types of files to be read when filling in a package symbol
2493 */
2494 protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
2495 return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
2496 }
2498 /**
2499 * this is used to support javadoc
2500 */
2501 protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) {
2502 }
2504 protected Location currentLoc; // FIXME
2506 private boolean verbosePath = true;
2508 /** Load directory of package into members scope.
2509 */
2510 private void fillIn(PackageSymbol p) throws IOException {
2511 if (p.members_field == null) p.members_field = new Scope(p);
2512 String packageName = p.fullname.toString();
2514 Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
2516 fillIn(p, PLATFORM_CLASS_PATH,
2517 fileManager.list(PLATFORM_CLASS_PATH,
2518 packageName,
2519 EnumSet.of(JavaFileObject.Kind.CLASS),
2520 false));
2522 Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
2523 classKinds.remove(JavaFileObject.Kind.SOURCE);
2524 boolean wantClassFiles = !classKinds.isEmpty();
2526 Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
2527 sourceKinds.remove(JavaFileObject.Kind.CLASS);
2528 boolean wantSourceFiles = !sourceKinds.isEmpty();
2530 boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
2532 if (verbose && verbosePath) {
2533 if (fileManager instanceof StandardJavaFileManager) {
2534 StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
2535 if (haveSourcePath && wantSourceFiles) {
2536 List<File> path = List.nil();
2537 for (File file : fm.getLocation(SOURCE_PATH)) {
2538 path = path.prepend(file);
2539 }
2540 log.printVerbose("sourcepath", path.reverse().toString());
2541 } else if (wantSourceFiles) {
2542 List<File> path = List.nil();
2543 for (File file : fm.getLocation(CLASS_PATH)) {
2544 path = path.prepend(file);
2545 }
2546 log.printVerbose("sourcepath", path.reverse().toString());
2547 }
2548 if (wantClassFiles) {
2549 List<File> path = List.nil();
2550 for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
2551 path = path.prepend(file);
2552 }
2553 for (File file : fm.getLocation(CLASS_PATH)) {
2554 path = path.prepend(file);
2555 }
2556 log.printVerbose("classpath", path.reverse().toString());
2557 }
2558 }
2559 }
2561 if (wantSourceFiles && !haveSourcePath) {
2562 fillIn(p, CLASS_PATH,
2563 fileManager.list(CLASS_PATH,
2564 packageName,
2565 kinds,
2566 false));
2567 } else {
2568 if (wantClassFiles)
2569 fillIn(p, CLASS_PATH,
2570 fileManager.list(CLASS_PATH,
2571 packageName,
2572 classKinds,
2573 false));
2574 if (wantSourceFiles)
2575 fillIn(p, SOURCE_PATH,
2576 fileManager.list(SOURCE_PATH,
2577 packageName,
2578 sourceKinds,
2579 false));
2580 }
2581 verbosePath = false;
2582 }
2583 // where
2584 private void fillIn(PackageSymbol p,
2585 Location location,
2586 Iterable<JavaFileObject> files)
2587 {
2588 currentLoc = location;
2589 for (JavaFileObject fo : files) {
2590 switch (fo.getKind()) {
2591 case CLASS:
2592 case SOURCE: {
2593 // TODO pass binaryName to includeClassFile
2594 String binaryName = fileManager.inferBinaryName(currentLoc, fo);
2595 String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
2596 if (SourceVersion.isIdentifier(simpleName) ||
2597 simpleName.equals("package-info"))
2598 includeClassFile(p, fo);
2599 break;
2600 }
2601 default:
2602 extraFileActions(p, fo);
2603 }
2604 }
2605 }
2607 /** Output for "-checkclassfile" option.
2608 * @param key The key to look up the correct internationalized string.
2609 * @param arg An argument for substitution into the output string.
2610 */
2611 private void printCCF(String key, Object arg) {
2612 log.printLines(key, arg);
2613 }
2616 public interface SourceCompleter {
2617 void complete(ClassSymbol sym)
2618 throws CompletionFailure;
2619 }
2621 /**
2622 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2623 * The attribute is only the last component of the original filename, so is unlikely
2624 * to be valid as is, so operations other than those to access the name throw
2625 * UnsupportedOperationException
2626 */
2627 private static class SourceFileObject extends BaseFileObject {
2629 /** The file's name.
2630 */
2631 private Name name;
2632 private Name flatname;
2634 public SourceFileObject(Name name, Name flatname) {
2635 super(null); // no file manager; never referenced for this file object
2636 this.name = name;
2637 this.flatname = flatname;
2638 }
2640 @Override
2641 public URI toUri() {
2642 try {
2643 return new URI(null, name.toString(), null);
2644 } catch (URISyntaxException e) {
2645 throw new CannotCreateUriError(name.toString(), e);
2646 }
2647 }
2649 @Override
2650 public String getName() {
2651 return name.toString();
2652 }
2654 @Override
2655 public String getShortName() {
2656 return getName();
2657 }
2659 @Override
2660 public JavaFileObject.Kind getKind() {
2661 return getKind(getName());
2662 }
2664 @Override
2665 public InputStream openInputStream() {
2666 throw new UnsupportedOperationException();
2667 }
2669 @Override
2670 public OutputStream openOutputStream() {
2671 throw new UnsupportedOperationException();
2672 }
2674 @Override
2675 public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2676 throw new UnsupportedOperationException();
2677 }
2679 @Override
2680 public Reader openReader(boolean ignoreEncodingErrors) {
2681 throw new UnsupportedOperationException();
2682 }
2684 @Override
2685 public Writer openWriter() {
2686 throw new UnsupportedOperationException();
2687 }
2689 @Override
2690 public long getLastModified() {
2691 throw new UnsupportedOperationException();
2692 }
2694 @Override
2695 public boolean delete() {
2696 throw new UnsupportedOperationException();
2697 }
2699 @Override
2700 protected String inferBinaryName(Iterable<? extends File> path) {
2701 return flatname.toString();
2702 }
2704 @Override
2705 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2706 return true; // fail-safe mode
2707 }
2709 /**
2710 * Check if two file objects are equal.
2711 * SourceFileObjects are just placeholder objects for the value of a
2712 * SourceFile attribute, and do not directly represent specific files.
2713 * Two SourceFileObjects are equal if their names are equal.
2714 */
2715 @Override
2716 public boolean equals(Object other) {
2717 if (this == other)
2718 return true;
2720 if (!(other instanceof SourceFileObject))
2721 return false;
2723 SourceFileObject o = (SourceFileObject) other;
2724 return name.equals(o.name);
2725 }
2727 @Override
2728 public int hashCode() {
2729 return name.hashCode();
2730 }
2731 }
2732 }