Sat, 29 Dec 2012 17:33:17 -0800
8004727: Add compiler support for parameter reflection
Reviewed-by: jjg
Contributed-by: eric.mccorkle@oracle.com
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.code;
28 import java.util.Set;
29 import java.util.concurrent.Callable;
31 import javax.lang.model.element.*;
32 import javax.tools.JavaFileObject;
34 import com.sun.tools.javac.code.Type.*;
35 import com.sun.tools.javac.comp.Attr;
36 import com.sun.tools.javac.comp.AttrContext;
37 import com.sun.tools.javac.comp.Env;
38 import com.sun.tools.javac.jvm.*;
39 import com.sun.tools.javac.model.*;
40 import com.sun.tools.javac.tree.JCTree;
41 import com.sun.tools.javac.util.*;
42 import com.sun.tools.javac.util.Name;
43 import static com.sun.tools.javac.code.Flags.*;
44 import static com.sun.tools.javac.code.Kinds.*;
45 import static com.sun.tools.javac.code.TypeTag.CLASS;
46 import static com.sun.tools.javac.code.TypeTag.FORALL;
47 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
49 /** Root class for Java symbols. It contains subclasses
50 * for specific sorts of symbols, such as variables, methods and operators,
51 * types, packages. Each subclass is represented as a static inner class
52 * inside Symbol.
53 *
54 * <p><b>This is NOT part of any supported API.
55 * If you write code that depends on this, you do so at your own risk.
56 * This code and its internal interfaces are subject to change or
57 * deletion without notice.</b>
58 */
59 public abstract class Symbol implements Element {
60 // public Throwable debug = new Throwable();
62 /** The kind of this symbol.
63 * @see Kinds
64 */
65 public int kind;
67 /** The flags of this symbol.
68 */
69 public long flags_field;
71 /** An accessor method for the flags of this symbol.
72 * Flags of class symbols should be accessed through the accessor
73 * method to make sure that the class symbol is loaded.
74 */
75 public long flags() { return flags_field; }
77 /** The attributes of this symbol are contained in this
78 * Annotations. The Annotations instance is NOT immutable.
79 */
80 public final Annotations annotations = new Annotations(this);
82 /** An accessor method for the attributes of this symbol.
83 * Attributes of class symbols should be accessed through the accessor
84 * method to make sure that the class symbol is loaded.
85 */
86 public List<Attribute.Compound> getRawAttributes() {
87 return annotations.getAttributes();
88 }
90 /** Fetch a particular annotation from a symbol. */
91 public Attribute.Compound attribute(Symbol anno) {
92 for (Attribute.Compound a : getRawAttributes()) {
93 if (a.type.tsym == anno) return a;
94 }
95 return null;
96 }
98 /** The name of this symbol in Utf8 representation.
99 */
100 public Name name;
102 /** The type of this symbol.
103 */
104 public Type type;
106 /** The owner of this symbol.
107 */
108 public Symbol owner;
110 /** The completer of this symbol.
111 */
112 public Completer completer;
114 /** A cache for the type erasure of this symbol.
115 */
116 public Type erasure_field;
118 /** Construct a symbol with given kind, flags, name, type and owner.
119 */
120 public Symbol(int kind, long flags, Name name, Type type, Symbol owner) {
121 this.kind = kind;
122 this.flags_field = flags;
123 this.type = type;
124 this.owner = owner;
125 this.completer = null;
126 this.erasure_field = null;
127 this.name = name;
128 }
130 /** Clone this symbol with new owner.
131 * Legal only for fields and methods.
132 */
133 public Symbol clone(Symbol newOwner) {
134 throw new AssertionError();
135 }
137 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
138 return v.visitSymbol(this, p);
139 }
141 /** The Java source which this symbol represents.
142 * A description of this symbol; overrides Object.
143 */
144 public String toString() {
145 return name.toString();
146 }
148 /** A Java source description of the location of this symbol; used for
149 * error reporting.
150 *
151 * @return null if the symbol is a package or a toplevel class defined in
152 * the default package; otherwise, the owner symbol is returned
153 */
154 public Symbol location() {
155 if (owner.name == null || (owner.name.isEmpty() &&
156 (owner.flags() & BLOCK) == 0 && owner.kind != PCK && owner.kind != TYP)) {
157 return null;
158 }
159 return owner;
160 }
162 public Symbol location(Type site, Types types) {
163 if (owner.name == null || owner.name.isEmpty()) {
164 return location();
165 }
166 if (owner.type.hasTag(CLASS)) {
167 Type ownertype = types.asOuterSuper(site, owner);
168 if (ownertype != null) return ownertype.tsym;
169 }
170 return owner;
171 }
173 public Symbol baseSymbol() {
174 return this;
175 }
177 /** The symbol's erased type.
178 */
179 public Type erasure(Types types) {
180 if (erasure_field == null)
181 erasure_field = types.erasure(type);
182 return erasure_field;
183 }
185 /** The external type of a symbol. This is the symbol's erased type
186 * except for constructors of inner classes which get the enclosing
187 * instance class added as first argument.
188 */
189 public Type externalType(Types types) {
190 Type t = erasure(types);
191 if (name == name.table.names.init && owner.hasOuterInstance()) {
192 Type outerThisType = types.erasure(owner.type.getEnclosingType());
193 return new MethodType(t.getParameterTypes().prepend(outerThisType),
194 t.getReturnType(),
195 t.getThrownTypes(),
196 t.tsym);
197 } else {
198 return t;
199 }
200 }
202 public boolean isStatic() {
203 return
204 (flags() & STATIC) != 0 ||
205 (owner.flags() & INTERFACE) != 0 && kind != MTH;
206 }
208 public boolean isInterface() {
209 return (flags() & INTERFACE) != 0;
210 }
212 /** Is this symbol declared (directly or indirectly) local
213 * to a method or variable initializer?
214 * Also includes fields of inner classes which are in
215 * turn local to a method or variable initializer.
216 */
217 public boolean isLocal() {
218 return
219 (owner.kind & (VAR | MTH)) != 0 ||
220 (owner.kind == TYP && owner.isLocal());
221 }
223 /** Has this symbol an empty name? This includes anonymous
224 * inner classses.
225 */
226 public boolean isAnonymous() {
227 return name.isEmpty();
228 }
230 /** Is this symbol a constructor?
231 */
232 public boolean isConstructor() {
233 return name == name.table.names.init;
234 }
236 /** The fully qualified name of this symbol.
237 * This is the same as the symbol's name except for class symbols,
238 * which are handled separately.
239 */
240 public Name getQualifiedName() {
241 return name;
242 }
244 /** The fully qualified name of this symbol after converting to flat
245 * representation. This is the same as the symbol's name except for
246 * class symbols, which are handled separately.
247 */
248 public Name flatName() {
249 return getQualifiedName();
250 }
252 /** If this is a class or package, its members, otherwise null.
253 */
254 public Scope members() {
255 return null;
256 }
258 /** A class is an inner class if it it has an enclosing instance class.
259 */
260 public boolean isInner() {
261 return type.getEnclosingType().hasTag(CLASS);
262 }
264 /** An inner class has an outer instance if it is not an interface
265 * it has an enclosing instance class which might be referenced from the class.
266 * Nested classes can see instance members of their enclosing class.
267 * Their constructors carry an additional this$n parameter, inserted
268 * implicitly by the compiler.
269 *
270 * @see #isInner
271 */
272 public boolean hasOuterInstance() {
273 return
274 type.getEnclosingType().hasTag(CLASS) && (flags() & (INTERFACE | NOOUTERTHIS)) == 0;
275 }
277 /** The closest enclosing class of this symbol's declaration.
278 */
279 public ClassSymbol enclClass() {
280 Symbol c = this;
281 while (c != null &&
282 ((c.kind & TYP) == 0 || !c.type.hasTag(CLASS))) {
283 c = c.owner;
284 }
285 return (ClassSymbol)c;
286 }
288 /** The outermost class which indirectly owns this symbol.
289 */
290 public ClassSymbol outermostClass() {
291 Symbol sym = this;
292 Symbol prev = null;
293 while (sym.kind != PCK) {
294 prev = sym;
295 sym = sym.owner;
296 }
297 return (ClassSymbol) prev;
298 }
300 /** The package which indirectly owns this symbol.
301 */
302 public PackageSymbol packge() {
303 Symbol sym = this;
304 while (sym.kind != PCK) {
305 sym = sym.owner;
306 }
307 return (PackageSymbol) sym;
308 }
310 /** Is this symbol a subclass of `base'? Only defined for ClassSymbols.
311 */
312 public boolean isSubClass(Symbol base, Types types) {
313 throw new AssertionError("isSubClass " + this);
314 }
316 /** Fully check membership: hierarchy, protection, and hiding.
317 * Does not exclude methods not inherited due to overriding.
318 */
319 public boolean isMemberOf(TypeSymbol clazz, Types types) {
320 return
321 owner == clazz ||
322 clazz.isSubClass(owner, types) &&
323 isInheritedIn(clazz, types) &&
324 !hiddenIn((ClassSymbol)clazz, types);
325 }
327 /** Is this symbol the same as or enclosed by the given class? */
328 public boolean isEnclosedBy(ClassSymbol clazz) {
329 for (Symbol sym = this; sym.kind != PCK; sym = sym.owner)
330 if (sym == clazz) return true;
331 return false;
332 }
334 /** Check for hiding. Note that this doesn't handle multiple
335 * (interface) inheritance. */
336 private boolean hiddenIn(ClassSymbol clazz, Types types) {
337 if (kind == MTH && (flags() & STATIC) == 0) return false;
338 while (true) {
339 if (owner == clazz) return false;
340 Scope.Entry e = clazz.members().lookup(name);
341 while (e.scope != null) {
342 if (e.sym == this) return false;
343 if (e.sym.kind == kind &&
344 (kind != MTH ||
345 (e.sym.flags() & STATIC) != 0 &&
346 types.isSubSignature(e.sym.type, type)))
347 return true;
348 e = e.next();
349 }
350 Type superType = types.supertype(clazz.type);
351 if (!superType.hasTag(CLASS)) return false;
352 clazz = (ClassSymbol)superType.tsym;
353 }
354 }
356 /** Is this symbol inherited into a given class?
357 * PRE: If symbol's owner is a interface,
358 * it is already assumed that the interface is a superinterface
359 * of given class.
360 * @param clazz The class for which we want to establish membership.
361 * This must be a subclass of the member's owner.
362 */
363 public boolean isInheritedIn(Symbol clazz, Types types) {
364 switch ((int)(flags_field & Flags.AccessFlags)) {
365 default: // error recovery
366 case PUBLIC:
367 return true;
368 case PRIVATE:
369 return this.owner == clazz;
370 case PROTECTED:
371 // we model interfaces as extending Object
372 return (clazz.flags() & INTERFACE) == 0;
373 case 0:
374 PackageSymbol thisPackage = this.packge();
375 for (Symbol sup = clazz;
376 sup != null && sup != this.owner;
377 sup = types.supertype(sup.type).tsym) {
378 while (sup.type.hasTag(TYPEVAR))
379 sup = sup.type.getUpperBound().tsym;
380 if (sup.type.isErroneous())
381 return true; // error recovery
382 if ((sup.flags() & COMPOUND) != 0)
383 continue;
384 if (sup.packge() != thisPackage)
385 return false;
386 }
387 return (clazz.flags() & INTERFACE) == 0;
388 }
389 }
391 /** The (variable or method) symbol seen as a member of given
392 * class type`site' (this might change the symbol's type).
393 * This is used exclusively for producing diagnostics.
394 */
395 public Symbol asMemberOf(Type site, Types types) {
396 throw new AssertionError();
397 }
399 /** Does this method symbol override `other' symbol, when both are seen as
400 * members of class `origin'? It is assumed that _other is a member
401 * of origin.
402 *
403 * It is assumed that both symbols have the same name. The static
404 * modifier is ignored for this test.
405 *
406 * See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
407 */
408 public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
409 return false;
410 }
412 /** Complete the elaboration of this symbol's definition.
413 */
414 public void complete() throws CompletionFailure {
415 if (completer != null) {
416 Completer c = completer;
417 completer = null;
418 c.complete(this);
419 }
420 }
422 /** True if the symbol represents an entity that exists.
423 */
424 public boolean exists() {
425 return true;
426 }
428 public Type asType() {
429 return type;
430 }
432 public Symbol getEnclosingElement() {
433 return owner;
434 }
436 public ElementKind getKind() {
437 return ElementKind.OTHER; // most unkind
438 }
440 public Set<Modifier> getModifiers() {
441 long flags = flags();
442 return Flags.asModifierSet((flags & DEFAULT) != 0 ? flags & ~ABSTRACT : flags);
443 }
445 public Name getSimpleName() {
446 return name;
447 }
449 /**
450 * This is the implementation for {@code
451 * javax.lang.model.element.Element.getAnnotationMirrors()}.
452 */
453 public final List<Attribute.Compound> getAnnotationMirrors() {
454 return getRawAttributes();
455 }
457 /**
458 * @deprecated this method should never be used by javac internally.
459 */
460 @Deprecated
461 public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
462 return JavacElements.getAnnotation(this, annoType);
463 }
465 // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
466 public java.util.List<Symbol> getEnclosedElements() {
467 return List.nil();
468 }
470 public List<TypeSymbol> getTypeParameters() {
471 ListBuffer<TypeSymbol> l = ListBuffer.lb();
472 for (Type t : type.getTypeArguments()) {
473 l.append(t.tsym);
474 }
475 return l.toList();
476 }
478 public static class DelegatedSymbol extends Symbol {
479 protected Symbol other;
480 public DelegatedSymbol(Symbol other) {
481 super(other.kind, other.flags_field, other.name, other.type, other.owner);
482 this.other = other;
483 }
484 public String toString() { return other.toString(); }
485 public Symbol location() { return other.location(); }
486 public Symbol location(Type site, Types types) { return other.location(site, types); }
487 public Symbol baseSymbol() { return other; }
488 public Type erasure(Types types) { return other.erasure(types); }
489 public Type externalType(Types types) { return other.externalType(types); }
490 public boolean isLocal() { return other.isLocal(); }
491 public boolean isConstructor() { return other.isConstructor(); }
492 public Name getQualifiedName() { return other.getQualifiedName(); }
493 public Name flatName() { return other.flatName(); }
494 public Scope members() { return other.members(); }
495 public boolean isInner() { return other.isInner(); }
496 public boolean hasOuterInstance() { return other.hasOuterInstance(); }
497 public ClassSymbol enclClass() { return other.enclClass(); }
498 public ClassSymbol outermostClass() { return other.outermostClass(); }
499 public PackageSymbol packge() { return other.packge(); }
500 public boolean isSubClass(Symbol base, Types types) { return other.isSubClass(base, types); }
501 public boolean isMemberOf(TypeSymbol clazz, Types types) { return other.isMemberOf(clazz, types); }
502 public boolean isEnclosedBy(ClassSymbol clazz) { return other.isEnclosedBy(clazz); }
503 public boolean isInheritedIn(Symbol clazz, Types types) { return other.isInheritedIn(clazz, types); }
504 public Symbol asMemberOf(Type site, Types types) { return other.asMemberOf(site, types); }
505 public void complete() throws CompletionFailure { other.complete(); }
507 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
508 return other.accept(v, p);
509 }
511 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
512 return v.visitSymbol(other, p);
513 }
514 }
516 /** A class for type symbols. Type variables are represented by instances
517 * of this class, classes and packages by instances of subclasses.
518 */
519 public static class TypeSymbol
520 extends Symbol implements TypeParameterElement {
521 // Implements TypeParameterElement because type parameters don't
522 // have their own TypeSymbol subclass.
523 // TODO: type parameters should have their own TypeSymbol subclass
525 public TypeSymbol(long flags, Name name, Type type, Symbol owner) {
526 super(TYP, flags, name, type, owner);
527 }
529 /** form a fully qualified name from a name and an owner
530 */
531 static public Name formFullName(Name name, Symbol owner) {
532 if (owner == null) return name;
533 if (((owner.kind != ERR)) &&
534 ((owner.kind & (VAR | MTH)) != 0
535 || (owner.kind == TYP && owner.type.hasTag(TYPEVAR))
536 )) return name;
537 Name prefix = owner.getQualifiedName();
538 if (prefix == null || prefix == prefix.table.names.empty)
539 return name;
540 else return prefix.append('.', name);
541 }
543 /** form a fully qualified name from a name and an owner, after
544 * converting to flat representation
545 */
546 static public Name formFlatName(Name name, Symbol owner) {
547 if (owner == null ||
548 (owner.kind & (VAR | MTH)) != 0
549 || (owner.kind == TYP && owner.type.hasTag(TYPEVAR))
550 ) return name;
551 char sep = owner.kind == TYP ? '$' : '.';
552 Name prefix = owner.flatName();
553 if (prefix == null || prefix == prefix.table.names.empty)
554 return name;
555 else return prefix.append(sep, name);
556 }
558 /**
559 * A total ordering between type symbols that refines the
560 * class inheritance graph.
561 *
562 * Typevariables always precede other kinds of symbols.
563 */
564 public final boolean precedes(TypeSymbol that, Types types) {
565 if (this == that)
566 return false;
567 if (this.type.tag == that.type.tag) {
568 if (this.type.hasTag(CLASS)) {
569 return
570 types.rank(that.type) < types.rank(this.type) ||
571 types.rank(that.type) == types.rank(this.type) &&
572 that.getQualifiedName().compareTo(this.getQualifiedName()) < 0;
573 } else if (this.type.hasTag(TYPEVAR)) {
574 return types.isSubtype(this.type, that.type);
575 }
576 }
577 return this.type.hasTag(TYPEVAR);
578 }
580 // For type params; overridden in subclasses.
581 public ElementKind getKind() {
582 return ElementKind.TYPE_PARAMETER;
583 }
585 public java.util.List<Symbol> getEnclosedElements() {
586 List<Symbol> list = List.nil();
587 if (kind == TYP && type.hasTag(TYPEVAR)) {
588 return list;
589 }
590 for (Scope.Entry e = members().elems; e != null; e = e.sibling) {
591 if (e.sym != null && (e.sym.flags() & SYNTHETIC) == 0 && e.sym.owner == this)
592 list = list.prepend(e.sym);
593 }
594 return list;
595 }
597 // For type params.
598 // Perhaps not needed if getEnclosingElement can be spec'ed
599 // to do the same thing.
600 // TODO: getGenericElement() might not be needed
601 public Symbol getGenericElement() {
602 return owner;
603 }
605 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
606 Assert.check(type.hasTag(TYPEVAR)); // else override will be invoked
607 return v.visitTypeParameter(this, p);
608 }
610 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
611 return v.visitTypeSymbol(this, p);
612 }
614 public List<Type> getBounds() {
615 TypeVar t = (TypeVar)type;
616 Type bound = t.getUpperBound();
617 if (!bound.isCompound())
618 return List.of(bound);
619 ClassType ct = (ClassType)bound;
620 if (!ct.tsym.erasure_field.isInterface()) {
621 return ct.interfaces_field.prepend(ct.supertype_field);
622 } else {
623 // No superclass was given in bounds.
624 // In this case, supertype is Object, erasure is first interface.
625 return ct.interfaces_field;
626 }
627 }
628 }
630 /** A class for package symbols
631 */
632 public static class PackageSymbol extends TypeSymbol
633 implements PackageElement {
635 public Scope members_field;
636 public Name fullname;
637 public ClassSymbol package_info; // see bug 6443073
639 public PackageSymbol(Name name, Type type, Symbol owner) {
640 super(0, name, type, owner);
641 this.kind = PCK;
642 this.members_field = null;
643 this.fullname = formFullName(name, owner);
644 }
646 public PackageSymbol(Name name, Symbol owner) {
647 this(name, null, owner);
648 this.type = new PackageType(this);
649 }
651 public String toString() {
652 return fullname.toString();
653 }
655 public Name getQualifiedName() {
656 return fullname;
657 }
659 public boolean isUnnamed() {
660 return name.isEmpty() && owner != null;
661 }
663 public Scope members() {
664 if (completer != null) complete();
665 return members_field;
666 }
668 public long flags() {
669 if (completer != null) complete();
670 return flags_field;
671 }
673 @Override
674 public List<Attribute.Compound> getRawAttributes() {
675 if (completer != null) complete();
676 if (package_info != null && package_info.completer != null) {
677 package_info.complete();
678 mergeAttributes();
679 }
680 return super.getRawAttributes();
681 }
683 private void mergeAttributes() {
684 if (annotations.isEmpty() &&
685 !package_info.annotations.isEmpty()) {
686 annotations.setAttributes(package_info.annotations);
687 }
688 }
690 /** A package "exists" if a type or package that exists has
691 * been seen within it.
692 */
693 public boolean exists() {
694 return (flags_field & EXISTS) != 0;
695 }
697 public ElementKind getKind() {
698 return ElementKind.PACKAGE;
699 }
701 public Symbol getEnclosingElement() {
702 return null;
703 }
705 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
706 return v.visitPackage(this, p);
707 }
709 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
710 return v.visitPackageSymbol(this, p);
711 }
712 }
714 /** A class for class symbols
715 */
716 public static class ClassSymbol extends TypeSymbol implements TypeElement {
718 /** a scope for all class members; variables, methods and inner classes
719 * type parameters are not part of this scope
720 */
721 public Scope members_field;
723 /** the fully qualified name of the class, i.e. pck.outer.inner.
724 * null for anonymous classes
725 */
726 public Name fullname;
728 /** the fully qualified name of the class after converting to flat
729 * representation, i.e. pck.outer$inner,
730 * set externally for local and anonymous classes
731 */
732 public Name flatname;
734 /** the sourcefile where the class came from
735 */
736 public JavaFileObject sourcefile;
738 /** the classfile from where to load this class
739 * this will have extension .class or .java
740 */
741 public JavaFileObject classfile;
743 /** the list of translated local classes (used for generating
744 * InnerClasses attribute)
745 */
746 public List<ClassSymbol> trans_local;
748 /** the constant pool of the class
749 */
750 public Pool pool;
752 public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
753 super(flags, name, type, owner);
754 this.members_field = null;
755 this.fullname = formFullName(name, owner);
756 this.flatname = formFlatName(name, owner);
757 this.sourcefile = null;
758 this.classfile = null;
759 this.pool = null;
760 }
762 public ClassSymbol(long flags, Name name, Symbol owner) {
763 this(
764 flags,
765 name,
766 new ClassType(Type.noType, null, null),
767 owner);
768 this.type.tsym = this;
769 }
771 /** The Java source which this symbol represents.
772 */
773 public String toString() {
774 return className();
775 }
777 public long flags() {
778 if (completer != null) complete();
779 return flags_field;
780 }
782 public Scope members() {
783 if (completer != null) complete();
784 return members_field;
785 }
787 @Override
788 public List<Attribute.Compound> getRawAttributes() {
789 if (completer != null) complete();
790 return super.getRawAttributes();
791 }
793 public Type erasure(Types types) {
794 if (erasure_field == null)
795 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
796 List.<Type>nil(), this);
797 return erasure_field;
798 }
800 public String className() {
801 if (name.isEmpty())
802 return
803 Log.getLocalizedString("anonymous.class", flatname);
804 else
805 return fullname.toString();
806 }
808 public Name getQualifiedName() {
809 return fullname;
810 }
812 public Name flatName() {
813 return flatname;
814 }
816 public boolean isSubClass(Symbol base, Types types) {
817 if (this == base) {
818 return true;
819 } else if ((base.flags() & INTERFACE) != 0) {
820 for (Type t = type; t.hasTag(CLASS); t = types.supertype(t))
821 for (List<Type> is = types.interfaces(t);
822 is.nonEmpty();
823 is = is.tail)
824 if (is.head.tsym.isSubClass(base, types)) return true;
825 } else {
826 for (Type t = type; t.hasTag(CLASS); t = types.supertype(t))
827 if (t.tsym == base) return true;
828 }
829 return false;
830 }
832 /** Complete the elaboration of this symbol's definition.
833 */
834 public void complete() throws CompletionFailure {
835 try {
836 super.complete();
837 } catch (CompletionFailure ex) {
838 // quiet error recovery
839 flags_field |= (PUBLIC|STATIC);
840 this.type = new ErrorType(this, Type.noType);
841 throw ex;
842 }
843 }
845 public List<Type> getInterfaces() {
846 complete();
847 if (type instanceof ClassType) {
848 ClassType t = (ClassType)type;
849 if (t.interfaces_field == null) // FIXME: shouldn't be null
850 t.interfaces_field = List.nil();
851 if (t.all_interfaces_field != null)
852 return Type.getModelTypes(t.all_interfaces_field);
853 return t.interfaces_field;
854 } else {
855 return List.nil();
856 }
857 }
859 public Type getSuperclass() {
860 complete();
861 if (type instanceof ClassType) {
862 ClassType t = (ClassType)type;
863 if (t.supertype_field == null) // FIXME: shouldn't be null
864 t.supertype_field = Type.noType;
865 // An interface has no superclass; its supertype is Object.
866 return t.isInterface()
867 ? Type.noType
868 : t.supertype_field.getModelType();
869 } else {
870 return Type.noType;
871 }
872 }
874 public ElementKind getKind() {
875 long flags = flags();
876 if ((flags & ANNOTATION) != 0)
877 return ElementKind.ANNOTATION_TYPE;
878 else if ((flags & INTERFACE) != 0)
879 return ElementKind.INTERFACE;
880 else if ((flags & ENUM) != 0)
881 return ElementKind.ENUM;
882 else
883 return ElementKind.CLASS;
884 }
886 public NestingKind getNestingKind() {
887 complete();
888 if (owner.kind == PCK)
889 return NestingKind.TOP_LEVEL;
890 else if (name.isEmpty())
891 return NestingKind.ANONYMOUS;
892 else if (owner.kind == MTH)
893 return NestingKind.LOCAL;
894 else
895 return NestingKind.MEMBER;
896 }
898 /**
899 * @deprecated this method should never be used by javac internally.
900 */
901 @Override @Deprecated
902 public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
903 return JavacElements.getAnnotation(this, annoType);
904 }
906 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
907 return v.visitType(this, p);
908 }
910 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
911 return v.visitClassSymbol(this, p);
912 }
913 }
916 /** A class for variable symbols
917 */
918 public static class VarSymbol extends Symbol implements VariableElement {
920 /** The variable's declaration position.
921 */
922 public int pos = Position.NOPOS;
924 /** The variable's address. Used for different purposes during
925 * flow analysis, translation and code generation.
926 * Flow analysis:
927 * If this is a blank final or local variable, its sequence number.
928 * Translation:
929 * If this is a private field, its access number.
930 * Code generation:
931 * If this is a local variable, its logical slot number.
932 */
933 public int adr = -1;
935 /** Construct a variable symbol, given its flags, name, type and owner.
936 */
937 public VarSymbol(long flags, Name name, Type type, Symbol owner) {
938 super(VAR, flags, name, type, owner);
939 }
941 /** Clone this symbol with new owner.
942 */
943 public VarSymbol clone(Symbol newOwner) {
944 VarSymbol v = new VarSymbol(flags_field, name, type, newOwner) {
945 @Override
946 public Symbol baseSymbol() {
947 return VarSymbol.this;
948 }
949 };
950 v.pos = pos;
951 v.adr = adr;
952 v.data = data;
953 // System.out.println("clone " + v + " in " + newOwner);//DEBUG
954 return v;
955 }
957 public String toString() {
958 return name.toString();
959 }
961 public Symbol asMemberOf(Type site, Types types) {
962 return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
963 }
965 public ElementKind getKind() {
966 long flags = flags();
967 if ((flags & PARAMETER) != 0) {
968 if (isExceptionParameter())
969 return ElementKind.EXCEPTION_PARAMETER;
970 else
971 return ElementKind.PARAMETER;
972 } else if ((flags & ENUM) != 0) {
973 return ElementKind.ENUM_CONSTANT;
974 } else if (owner.kind == TYP || owner.kind == ERR) {
975 return ElementKind.FIELD;
976 } else if (isResourceVariable()) {
977 return ElementKind.RESOURCE_VARIABLE;
978 } else {
979 return ElementKind.LOCAL_VARIABLE;
980 }
981 }
983 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
984 return v.visitVariable(this, p);
985 }
987 public Object getConstantValue() { // Mirror API
988 return Constants.decode(getConstValue(), type);
989 }
991 public void setLazyConstValue(final Env<AttrContext> env,
992 final Attr attr,
993 final JCTree.JCExpression initializer)
994 {
995 setData(new Callable<Object>() {
996 public Object call() {
997 return attr.attribLazyConstantValue(env, initializer, type);
998 }
999 });
1000 }
1002 /**
1003 * The variable's constant value, if this is a constant.
1004 * Before the constant value is evaluated, it points to an
1005 * initalizer environment. If this is not a constant, it can
1006 * be used for other stuff.
1007 */
1008 private Object data;
1010 public boolean isExceptionParameter() {
1011 return data == ElementKind.EXCEPTION_PARAMETER;
1012 }
1014 public boolean isResourceVariable() {
1015 return data == ElementKind.RESOURCE_VARIABLE;
1016 }
1018 public Object getConstValue() {
1019 // TODO: Consider if getConstValue and getConstantValue can be collapsed
1020 if (data == ElementKind.EXCEPTION_PARAMETER ||
1021 data == ElementKind.RESOURCE_VARIABLE) {
1022 return null;
1023 } else if (data instanceof Callable<?>) {
1024 // In this case, this is a final variable, with an as
1025 // yet unevaluated initializer.
1026 Callable<?> eval = (Callable<?>)data;
1027 data = null; // to make sure we don't evaluate this twice.
1028 try {
1029 data = eval.call();
1030 } catch (Exception ex) {
1031 throw new AssertionError(ex);
1032 }
1033 }
1034 return data;
1035 }
1037 public void setData(Object data) {
1038 Assert.check(!(data instanceof Env<?>), this);
1039 this.data = data;
1040 }
1042 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1043 return v.visitVarSymbol(this, p);
1044 }
1045 }
1047 /** A class for method symbols.
1048 */
1049 public static class MethodSymbol extends Symbol implements ExecutableElement {
1051 /** The code of the method. */
1052 public Code code = null;
1054 /** The parameters of the method. */
1055 public List<VarSymbol> params = null;
1057 /** The names of the parameters */
1058 public List<Name> savedParameterNames;
1060 /** For an attribute field accessor, its default value if any.
1061 * The value is null if none appeared in the method
1062 * declaration.
1063 */
1064 public Attribute defaultValue = null;
1066 /** Construct a method symbol, given its flags, name, type and owner.
1067 */
1068 public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
1069 super(MTH, flags, name, type, owner);
1070 if (owner.type.hasTag(TYPEVAR)) Assert.error(owner + "." + name);
1071 }
1073 /** Clone this symbol with new owner.
1074 */
1075 public MethodSymbol clone(Symbol newOwner) {
1076 MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner) {
1077 @Override
1078 public Symbol baseSymbol() {
1079 return MethodSymbol.this;
1080 }
1081 };
1082 m.code = code;
1083 return m;
1084 }
1086 /** The Java source which this symbol represents.
1087 */
1088 public String toString() {
1089 if ((flags() & BLOCK) != 0) {
1090 return owner.name.toString();
1091 } else {
1092 String s = (name == name.table.names.init)
1093 ? owner.name.toString()
1094 : name.toString();
1095 if (type != null) {
1096 if (type.hasTag(FORALL))
1097 s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
1098 s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
1099 }
1100 return s;
1101 }
1102 }
1104 public boolean isDynamic() {
1105 return false;
1106 }
1108 /** find a symbol that this (proxy method) symbol implements.
1109 * @param c The class whose members are searched for
1110 * implementations
1111 */
1112 public Symbol implemented(TypeSymbol c, Types types) {
1113 Symbol impl = null;
1114 for (List<Type> is = types.interfaces(c.type);
1115 impl == null && is.nonEmpty();
1116 is = is.tail) {
1117 TypeSymbol i = is.head.tsym;
1118 impl = implementedIn(i, types);
1119 if (impl == null)
1120 impl = implemented(i, types);
1121 }
1122 return impl;
1123 }
1125 public Symbol implementedIn(TypeSymbol c, Types types) {
1126 Symbol impl = null;
1127 for (Scope.Entry e = c.members().lookup(name);
1128 impl == null && e.scope != null;
1129 e = e.next()) {
1130 if (this.overrides(e.sym, (TypeSymbol)owner, types, true) &&
1131 // FIXME: I suspect the following requires a
1132 // subst() for a parametric return type.
1133 types.isSameType(type.getReturnType(),
1134 types.memberType(owner.type, e.sym).getReturnType())) {
1135 impl = e.sym;
1136 }
1137 }
1138 return impl;
1139 }
1141 /** Will the erasure of this method be considered by the VM to
1142 * override the erasure of the other when seen from class `origin'?
1143 */
1144 public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
1145 if (isConstructor() || _other.kind != MTH) return false;
1147 if (this == _other) return true;
1148 MethodSymbol other = (MethodSymbol)_other;
1150 // check for a direct implementation
1151 if (other.isOverridableIn((TypeSymbol)owner) &&
1152 types.asSuper(owner.type, other.owner) != null &&
1153 types.isSameType(erasure(types), other.erasure(types)))
1154 return true;
1156 // check for an inherited implementation
1157 return
1158 (flags() & ABSTRACT) == 0 &&
1159 other.isOverridableIn(origin) &&
1160 this.isMemberOf(origin, types) &&
1161 types.isSameType(erasure(types), other.erasure(types));
1162 }
1164 /** The implementation of this (abstract) symbol in class origin,
1165 * from the VM's point of view, null if method does not have an
1166 * implementation in class.
1167 * @param origin The class of which the implementation is a member.
1168 */
1169 public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
1170 for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
1171 for (Scope.Entry e = c.members().lookup(name);
1172 e.scope != null;
1173 e = e.next()) {
1174 if (e.sym.kind == MTH &&
1175 ((MethodSymbol)e.sym).binaryOverrides(this, origin, types))
1176 return (MethodSymbol)e.sym;
1177 }
1178 }
1179 return null;
1180 }
1182 /** Does this symbol override `other' symbol, when both are seen as
1183 * members of class `origin'? It is assumed that _other is a member
1184 * of origin.
1185 *
1186 * It is assumed that both symbols have the same name. The static
1187 * modifier is ignored for this test.
1188 *
1189 * See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1190 */
1191 public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
1192 if (isConstructor() || _other.kind != MTH) return false;
1194 if (this == _other) return true;
1195 MethodSymbol other = (MethodSymbol)_other;
1197 // check for a direct implementation
1198 if (other.isOverridableIn((TypeSymbol)owner) &&
1199 types.asSuper(owner.type, other.owner) != null) {
1200 Type mt = types.memberType(owner.type, this);
1201 Type ot = types.memberType(owner.type, other);
1202 if (types.isSubSignature(mt, ot)) {
1203 if (!checkResult)
1204 return true;
1205 if (types.returnTypeSubstitutable(mt, ot))
1206 return true;
1207 }
1208 }
1210 // check for an inherited implementation
1211 if ((flags() & ABSTRACT) != 0 ||
1212 ((other.flags() & ABSTRACT) == 0 && (other.flags() & DEFAULT) == 0) ||
1213 !other.isOverridableIn(origin) ||
1214 !this.isMemberOf(origin, types))
1215 return false;
1217 // assert types.asSuper(origin.type, other.owner) != null;
1218 Type mt = types.memberType(origin.type, this);
1219 Type ot = types.memberType(origin.type, other);
1220 return
1221 types.isSubSignature(mt, ot) &&
1222 (!checkResult || types.resultSubtype(mt, ot, types.noWarnings));
1223 }
1225 private boolean isOverridableIn(TypeSymbol origin) {
1226 // JLS 8.4.6.1
1227 switch ((int)(flags_field & Flags.AccessFlags)) {
1228 case Flags.PRIVATE:
1229 return false;
1230 case Flags.PUBLIC:
1231 return true;
1232 case Flags.PROTECTED:
1233 return (origin.flags() & INTERFACE) == 0;
1234 case 0:
1235 // for package private: can only override in the same
1236 // package
1237 return
1238 this.packge() == origin.packge() &&
1239 (origin.flags() & INTERFACE) == 0;
1240 default:
1241 return false;
1242 }
1243 }
1245 /** The implementation of this (abstract) symbol in class origin;
1246 * null if none exists. Synthetic methods are not considered
1247 * as possible implementations.
1248 */
1249 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1250 return implementation(origin, types, checkResult, implementation_filter);
1251 }
1252 // where
1253 private static final Filter<Symbol> implementation_filter = new Filter<Symbol>() {
1254 public boolean accepts(Symbol s) {
1255 return s.kind == Kinds.MTH &&
1256 (s.flags() & SYNTHETIC) == 0;
1257 }
1258 };
1260 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
1261 MethodSymbol res = types.implementation(this, origin, checkResult, implFilter);
1262 if (res != null)
1263 return res;
1264 // if origin is derived from a raw type, we might have missed
1265 // an implementation because we do not know enough about instantiations.
1266 // in this case continue with the supertype as origin.
1267 if (types.isDerivedRaw(origin.type) && !origin.isInterface())
1268 return implementation(types.supertype(origin.type).tsym, types, checkResult);
1269 else
1270 return null;
1271 }
1273 public List<VarSymbol> params() {
1274 owner.complete();
1275 if (params == null) {
1276 // If ClassReader.saveParameterNames has been set true, then
1277 // savedParameterNames will be set to a list of names that
1278 // matches the types in type.getParameterTypes(). If any names
1279 // were not found in the class file, those names in the list will
1280 // be set to the empty name.
1281 // If ClassReader.saveParameterNames has been set false, then
1282 // savedParameterNames will be null.
1283 List<Name> paramNames = savedParameterNames;
1284 savedParameterNames = null;
1285 // discard the provided names if the list of names is the wrong size.
1286 if (paramNames == null || paramNames.size() != type.getParameterTypes().size()) {
1287 paramNames = List.nil();
1288 }
1289 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
1290 List<Name> remaining = paramNames;
1291 // assert: remaining and paramNames are both empty or both
1292 // have same cardinality as type.getParameterTypes()
1293 int i = 0;
1294 for (Type t : type.getParameterTypes()) {
1295 Name paramName;
1296 if (remaining.isEmpty()) {
1297 // no names for any parameters available
1298 paramName = createArgName(i, paramNames);
1299 } else {
1300 paramName = remaining.head;
1301 remaining = remaining.tail;
1302 if (paramName.isEmpty()) {
1303 // no name for this specific parameter
1304 paramName = createArgName(i, paramNames);
1305 }
1306 }
1307 buf.append(new VarSymbol(PARAMETER, paramName, t, this));
1308 i++;
1309 }
1310 params = buf.toList();
1311 }
1312 return params;
1313 }
1315 // Create a name for the argument at position 'index' that is not in
1316 // the exclude list. In normal use, either no names will have been
1317 // provided, in which case the exclude list is empty, or all the names
1318 // will have been provided, in which case this method will not be called.
1319 private Name createArgName(int index, List<Name> exclude) {
1320 String prefix = "arg";
1321 while (true) {
1322 Name argName = name.table.fromString(prefix + index);
1323 if (!exclude.contains(argName))
1324 return argName;
1325 prefix += "$";
1326 }
1327 }
1329 public Symbol asMemberOf(Type site, Types types) {
1330 return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
1331 }
1333 public ElementKind getKind() {
1334 if (name == name.table.names.init)
1335 return ElementKind.CONSTRUCTOR;
1336 else if (name == name.table.names.clinit)
1337 return ElementKind.STATIC_INIT;
1338 else if ((flags() & BLOCK) != 0)
1339 return isStatic() ? ElementKind.STATIC_INIT : ElementKind.INSTANCE_INIT;
1340 else
1341 return ElementKind.METHOD;
1342 }
1344 public boolean isStaticOrInstanceInit() {
1345 return getKind() == ElementKind.STATIC_INIT ||
1346 getKind() == ElementKind.INSTANCE_INIT;
1347 }
1349 /**
1350 * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
1351 * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
1352 * a single variable arity parameter (iii) whose declared type is Object[],
1353 * (iv) has a return type of Object and (v) is native.
1354 */
1355 public boolean isSignaturePolymorphic(Types types) {
1356 List<Type> argtypes = type.getParameterTypes();
1357 Type firstElemType = argtypes.nonEmpty() ?
1358 types.elemtype(argtypes.head) :
1359 null;
1360 return owner == types.syms.methodHandleType.tsym &&
1361 argtypes.length() == 1 &&
1362 firstElemType != null &&
1363 types.isSameType(firstElemType, types.syms.objectType) &&
1364 types.isSameType(type.getReturnType(), types.syms.objectType) &&
1365 (flags() & NATIVE) != 0;
1366 }
1368 public Attribute getDefaultValue() {
1369 return defaultValue;
1370 }
1372 public List<VarSymbol> getParameters() {
1373 return params();
1374 }
1376 public boolean isVarArgs() {
1377 return (flags() & VARARGS) != 0;
1378 }
1380 public boolean isDefault() {
1381 return (flags() & DEFAULT) != 0;
1382 }
1384 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1385 return v.visitExecutable(this, p);
1386 }
1388 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1389 return v.visitMethodSymbol(this, p);
1390 }
1392 public Type getReturnType() {
1393 return asType().getReturnType();
1394 }
1396 public List<Type> getThrownTypes() {
1397 return asType().getThrownTypes();
1398 }
1399 }
1401 /** A class for invokedynamic method calls.
1402 */
1403 public static class DynamicMethodSymbol extends MethodSymbol {
1405 public Object[] staticArgs;
1406 public Symbol bsm;
1407 public int bsmKind;
1409 public DynamicMethodSymbol(Name name, Symbol owner, int bsmKind, MethodSymbol bsm, Type type, Object[] staticArgs) {
1410 super(0, name, type, owner);
1411 this.bsm = bsm;
1412 this.bsmKind = bsmKind;
1413 this.staticArgs = staticArgs;
1414 }
1416 @Override
1417 public boolean isDynamic() {
1418 return true;
1419 }
1420 }
1422 /** A class for predefined operators.
1423 */
1424 public static class OperatorSymbol extends MethodSymbol {
1426 public int opcode;
1428 public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
1429 super(PUBLIC | STATIC, name, type, owner);
1430 this.opcode = opcode;
1431 }
1433 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1434 return v.visitOperatorSymbol(this, p);
1435 }
1436 }
1438 /** Symbol completer interface.
1439 */
1440 public static interface Completer {
1441 void complete(Symbol sym) throws CompletionFailure;
1442 }
1444 public static class CompletionFailure extends RuntimeException {
1445 private static final long serialVersionUID = 0;
1446 public Symbol sym;
1448 /** A diagnostic object describing the failure
1449 */
1450 public JCDiagnostic diag;
1452 /** A localized string describing the failure.
1453 * @deprecated Use {@code getDetail()} or {@code getMessage()}
1454 */
1455 @Deprecated
1456 public String errmsg;
1458 public CompletionFailure(Symbol sym, String errmsg) {
1459 this.sym = sym;
1460 this.errmsg = errmsg;
1461 // this.printStackTrace();//DEBUG
1462 }
1464 public CompletionFailure(Symbol sym, JCDiagnostic diag) {
1465 this.sym = sym;
1466 this.diag = diag;
1467 // this.printStackTrace();//DEBUG
1468 }
1470 public JCDiagnostic getDiagnostic() {
1471 return diag;
1472 }
1474 @Override
1475 public String getMessage() {
1476 if (diag != null)
1477 return diag.getMessage(null);
1478 else
1479 return errmsg;
1480 }
1482 public Object getDetailValue() {
1483 return (diag != null ? diag : errmsg);
1484 }
1486 @Override
1487 public CompletionFailure initCause(Throwable cause) {
1488 super.initCause(cause);
1489 return this;
1490 }
1492 }
1494 /**
1495 * A visitor for symbols. A visitor is used to implement operations
1496 * (or relations) on symbols. Most common operations on types are
1497 * binary relations and this interface is designed for binary
1498 * relations, that is, operations on the form
1499 * Symbol × P → R.
1500 * <!-- In plain text: Type x P -> R -->
1501 *
1502 * @param <R> the return type of the operation implemented by this
1503 * visitor; use Void if no return type is needed.
1504 * @param <P> the type of the second argument (the first being the
1505 * symbol itself) of the operation implemented by this visitor; use
1506 * Void if a second argument is not needed.
1507 */
1508 public interface Visitor<R,P> {
1509 R visitClassSymbol(ClassSymbol s, P arg);
1510 R visitMethodSymbol(MethodSymbol s, P arg);
1511 R visitPackageSymbol(PackageSymbol s, P arg);
1512 R visitOperatorSymbol(OperatorSymbol s, P arg);
1513 R visitVarSymbol(VarSymbol s, P arg);
1514 R visitTypeSymbol(TypeSymbol s, P arg);
1515 R visitSymbol(Symbol s, P arg);
1516 }
1517 }