Tue, 07 Sep 2010 17:32:27 +0100
6979327: method handle invocation should use casts instead of type parameters to specify return type
Summary: infer return type for polymorphic signature calls according to updated JSR 292 draft
Reviewed-by: jjg
Contributed-by: john.r.rose@oracle.com
1 /*
2 * Copyright (c) 1999, 2008, 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;
30 import javax.lang.model.element.*;
31 import javax.tools.JavaFileObject;
33 import com.sun.tools.javac.util.*;
34 import com.sun.tools.javac.util.Name;
35 import com.sun.tools.javac.code.Type.*;
36 import com.sun.tools.javac.comp.Attr;
37 import com.sun.tools.javac.comp.AttrContext;
38 import com.sun.tools.javac.comp.Env;
39 import com.sun.tools.javac.jvm.*;
40 import com.sun.tools.javac.model.*;
41 import com.sun.tools.javac.tree.JCTree;
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.TypeTags.*;
47 /** Root class for Java symbols. It contains subclasses
48 * for specific sorts of symbols, such as variables, methods and operators,
49 * types, packages. Each subclass is represented as a static inner class
50 * inside Symbol.
51 *
52 * <p><b>This is NOT part of any supported API.
53 * If you write code that depends on this, you do so at your own risk.
54 * This code and its internal interfaces are subject to change or
55 * deletion without notice.</b>
56 */
57 public abstract class Symbol implements Element {
58 // public Throwable debug = new Throwable();
60 /** The kind of this symbol.
61 * @see Kinds
62 */
63 public int kind;
65 /** The flags of this symbol.
66 */
67 public long flags_field;
69 /** An accessor method for the flags of this symbol.
70 * Flags of class symbols should be accessed through the accessor
71 * method to make sure that the class symbol is loaded.
72 */
73 public long flags() { return flags_field; }
75 /** The attributes of this symbol.
76 */
77 public List<Attribute.Compound> attributes_field;
79 /** An accessor method for the attributes of this symbol.
80 * Attributes of class symbols should be accessed through the accessor
81 * method to make sure that the class symbol is loaded.
82 */
83 public List<Attribute.Compound> getAnnotationMirrors() {
84 assert attributes_field != null;
85 return attributes_field;
86 }
88 /** Fetch a particular annotation from a symbol. */
89 public Attribute.Compound attribute(Symbol anno) {
90 for (Attribute.Compound a : getAnnotationMirrors())
91 if (a.type.tsym == anno) return a;
92 return null;
93 }
95 /** The name of this symbol in Utf8 representation.
96 */
97 public Name name;
99 /** The type of this symbol.
100 */
101 public Type type;
103 /** The type annotations targeted to a tree directly owned by this symbol
104 */
105 // type annotations are stored here for two purposes:
106 // - convenient location to store annotations for generation after erasure
107 // - a private interface for accessing type annotations parsed from
108 // classfiles
109 // the field is populated for the following declaration only
110 // class, field, variable and type parameters
111 //
112 public List<Attribute.TypeCompound> typeAnnotations;
114 /** The owner of this symbol.
115 */
116 public Symbol owner;
118 /** The completer of this symbol.
119 */
120 public Completer completer;
122 /** A cache for the type erasure of this symbol.
123 */
124 public Type erasure_field;
126 /** Construct a symbol with given kind, flags, name, type and owner.
127 */
128 public Symbol(int kind, long flags, Name name, Type type, Symbol owner) {
129 this.kind = kind;
130 this.flags_field = flags;
131 this.type = type;
132 this.owner = owner;
133 this.completer = null;
134 this.erasure_field = null;
135 this.attributes_field = List.nil();
136 this.typeAnnotations = List.nil();
137 this.name = name;
138 }
140 /** Clone this symbol with new owner.
141 * Legal only for fields and methods.
142 */
143 public Symbol clone(Symbol newOwner) {
144 throw new AssertionError();
145 }
147 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
148 return v.visitSymbol(this, p);
149 }
151 /** The Java source which this symbol represents.
152 * A description of this symbol; overrides Object.
153 */
154 public String toString() {
155 return name.toString();
156 }
158 /** A Java source description of the location of this symbol; used for
159 * error reporting.
160 *
161 * @return null if the symbol is a package or a toplevel class defined in
162 * the default package; otherwise, the owner symbol is returned
163 */
164 public Symbol location() {
165 if (owner.name == null || (owner.name.isEmpty() && owner.kind != PCK && owner.kind != TYP)) {
166 return null;
167 }
168 return owner;
169 }
171 public Symbol location(Type site, Types types) {
172 if (owner.name == null || owner.name.isEmpty()) {
173 return location();
174 }
175 if (owner.type.tag == CLASS) {
176 Type ownertype = types.asOuterSuper(site, owner);
177 if (ownertype != null) return ownertype.tsym;
178 }
179 return owner;
180 }
182 /** The symbol's erased type.
183 */
184 public Type erasure(Types types) {
185 if (erasure_field == null)
186 erasure_field = types.erasure(type);
187 return erasure_field;
188 }
190 /** The external type of a symbol. This is the symbol's erased type
191 * except for constructors of inner classes which get the enclosing
192 * instance class added as first argument.
193 */
194 public Type externalType(Types types) {
195 Type t = erasure(types);
196 if (name == name.table.names.init && owner.hasOuterInstance()) {
197 Type outerThisType = types.erasure(owner.type.getEnclosingType());
198 return new MethodType(t.getParameterTypes().prepend(outerThisType),
199 t.getReturnType(),
200 t.getThrownTypes(),
201 t.tsym);
202 } else {
203 return t;
204 }
205 }
207 public boolean isStatic() {
208 return
209 (flags() & STATIC) != 0 ||
210 (owner.flags() & INTERFACE) != 0 && kind != MTH;
211 }
213 public boolean isInterface() {
214 return (flags() & INTERFACE) != 0;
215 }
217 /** Recognize if this symbol was marked @PolymorphicSignature in the source. */
218 public boolean isPolymorphicSignatureGeneric() {
219 return (flags() & (POLYMORPHIC_SIGNATURE | HYPOTHETICAL)) == POLYMORPHIC_SIGNATURE;
220 }
222 /** Recognize if this symbol was split from a @PolymorphicSignature symbol in the source. */
223 public boolean isPolymorphicSignatureInstance() {
224 return (flags() & (POLYMORPHIC_SIGNATURE | HYPOTHETICAL)) == (POLYMORPHIC_SIGNATURE | HYPOTHETICAL);
225 }
227 /** Is this symbol declared (directly or indirectly) local
228 * to a method or variable initializer?
229 * Also includes fields of inner classes which are in
230 * turn local to a method or variable initializer.
231 */
232 public boolean isLocal() {
233 return
234 (owner.kind & (VAR | MTH)) != 0 ||
235 (owner.kind == TYP && owner.isLocal());
236 }
238 /** Has this symbol an empty name? This includes anonymous
239 * inner classses.
240 */
241 public boolean isAnonymous() {
242 return name.isEmpty();
243 }
245 /** Is this symbol a constructor?
246 */
247 public boolean isConstructor() {
248 return name == name.table.names.init;
249 }
251 /** The fully qualified name of this symbol.
252 * This is the same as the symbol's name except for class symbols,
253 * which are handled separately.
254 */
255 public Name getQualifiedName() {
256 return name;
257 }
259 /** The fully qualified name of this symbol after converting to flat
260 * representation. This is the same as the symbol's name except for
261 * class symbols, which are handled separately.
262 */
263 public Name flatName() {
264 return getQualifiedName();
265 }
267 /** If this is a class or package, its members, otherwise null.
268 */
269 public Scope members() {
270 return null;
271 }
273 /** A class is an inner class if it it has an enclosing instance class.
274 */
275 public boolean isInner() {
276 return type.getEnclosingType().tag == CLASS;
277 }
279 /** An inner class has an outer instance if it is not an interface
280 * it has an enclosing instance class which might be referenced from the class.
281 * Nested classes can see instance members of their enclosing class.
282 * Their constructors carry an additional this$n parameter, inserted
283 * implicitly by the compiler.
284 *
285 * @see #isInner
286 */
287 public boolean hasOuterInstance() {
288 return
289 type.getEnclosingType().tag == CLASS && (flags() & (INTERFACE | NOOUTERTHIS)) == 0;
290 }
292 /** The closest enclosing class of this symbol's declaration.
293 */
294 public ClassSymbol enclClass() {
295 Symbol c = this;
296 while (c != null &&
297 ((c.kind & TYP) == 0 || c.type.tag != CLASS)) {
298 c = c.owner;
299 }
300 return (ClassSymbol)c;
301 }
303 /** The outermost class which indirectly owns this symbol.
304 */
305 public ClassSymbol outermostClass() {
306 Symbol sym = this;
307 Symbol prev = null;
308 while (sym.kind != PCK) {
309 prev = sym;
310 sym = sym.owner;
311 }
312 return (ClassSymbol) prev;
313 }
315 /** The package which indirectly owns this symbol.
316 */
317 public PackageSymbol packge() {
318 Symbol sym = this;
319 while (sym.kind != PCK) {
320 sym = sym.owner;
321 }
322 return (PackageSymbol) sym;
323 }
325 /** Is this symbol a subclass of `base'? Only defined for ClassSymbols.
326 */
327 public boolean isSubClass(Symbol base, Types types) {
328 throw new AssertionError("isSubClass " + this);
329 }
331 /** Fully check membership: hierarchy, protection, and hiding.
332 * Does not exclude methods not inherited due to overriding.
333 */
334 public boolean isMemberOf(TypeSymbol clazz, Types types) {
335 return
336 owner == clazz ||
337 clazz.isSubClass(owner, types) &&
338 isInheritedIn(clazz, types) &&
339 !hiddenIn((ClassSymbol)clazz, types);
340 }
342 /** Is this symbol the same as or enclosed by the given class? */
343 public boolean isEnclosedBy(ClassSymbol clazz) {
344 for (Symbol sym = this; sym.kind != PCK; sym = sym.owner)
345 if (sym == clazz) return true;
346 return false;
347 }
349 /** Check for hiding. Note that this doesn't handle multiple
350 * (interface) inheritance. */
351 private boolean hiddenIn(ClassSymbol clazz, Types types) {
352 if (kind == MTH && (flags() & STATIC) == 0) return false;
353 while (true) {
354 if (owner == clazz) return false;
355 Scope.Entry e = clazz.members().lookup(name);
356 while (e.scope != null) {
357 if (e.sym == this) return false;
358 if (e.sym.kind == kind &&
359 (kind != MTH ||
360 (e.sym.flags() & STATIC) != 0 &&
361 types.isSubSignature(e.sym.type, type)))
362 return true;
363 e = e.next();
364 }
365 Type superType = types.supertype(clazz.type);
366 if (superType.tag != TypeTags.CLASS) return false;
367 clazz = (ClassSymbol)superType.tsym;
368 }
369 }
371 /** Is this symbol inherited into a given class?
372 * PRE: If symbol's owner is a interface,
373 * it is already assumed that the interface is a superinterface
374 * of given class.
375 * @param clazz The class for which we want to establish membership.
376 * This must be a subclass of the member's owner.
377 */
378 public boolean isInheritedIn(Symbol clazz, Types types) {
379 switch ((int)(flags_field & Flags.AccessFlags)) {
380 default: // error recovery
381 case PUBLIC:
382 return true;
383 case PRIVATE:
384 return this.owner == clazz;
385 case PROTECTED:
386 // we model interfaces as extending Object
387 return (clazz.flags() & INTERFACE) == 0;
388 case 0:
389 PackageSymbol thisPackage = this.packge();
390 for (Symbol sup = clazz;
391 sup != null && sup != this.owner;
392 sup = types.supertype(sup.type).tsym) {
393 while (sup.type.tag == TYPEVAR)
394 sup = sup.type.getUpperBound().tsym;
395 if (sup.type.isErroneous())
396 return true; // error recovery
397 if ((sup.flags() & COMPOUND) != 0)
398 continue;
399 if (sup.packge() != thisPackage)
400 return false;
401 }
402 return (clazz.flags() & INTERFACE) == 0;
403 }
404 }
406 /** The (variable or method) symbol seen as a member of given
407 * class type`site' (this might change the symbol's type).
408 * This is used exclusively for producing diagnostics.
409 */
410 public Symbol asMemberOf(Type site, Types types) {
411 throw new AssertionError();
412 }
414 /** Does this method symbol override `other' symbol, when both are seen as
415 * members of class `origin'? It is assumed that _other is a member
416 * of origin.
417 *
418 * It is assumed that both symbols have the same name. The static
419 * modifier is ignored for this test.
420 *
421 * See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
422 */
423 public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
424 return false;
425 }
427 /** Complete the elaboration of this symbol's definition.
428 */
429 public void complete() throws CompletionFailure {
430 if (completer != null) {
431 Completer c = completer;
432 completer = null;
433 c.complete(this);
434 }
435 }
437 /** True if the symbol represents an entity that exists.
438 */
439 public boolean exists() {
440 return true;
441 }
443 public Type asType() {
444 return type;
445 }
447 public Symbol getEnclosingElement() {
448 return owner;
449 }
451 public ElementKind getKind() {
452 return ElementKind.OTHER; // most unkind
453 }
455 public Set<Modifier> getModifiers() {
456 return Flags.asModifierSet(flags());
457 }
459 public Name getSimpleName() {
460 return name;
461 }
463 /**
464 * @deprecated this method should never be used by javac internally.
465 */
466 @Deprecated
467 public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
468 return JavacElements.getAnnotation(this, annoType);
469 }
471 // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
472 public java.util.List<Symbol> getEnclosedElements() {
473 return List.nil();
474 }
476 public List<TypeSymbol> getTypeParameters() {
477 ListBuffer<TypeSymbol> l = ListBuffer.lb();
478 for (Type t : type.getTypeArguments()) {
479 l.append(t.tsym);
480 }
481 return l.toList();
482 }
484 public static class DelegatedSymbol extends Symbol {
485 protected Symbol other;
486 public DelegatedSymbol(Symbol other) {
487 super(other.kind, other.flags_field, other.name, other.type, other.owner);
488 this.other = other;
489 }
490 public String toString() { return other.toString(); }
491 public Symbol location() { return other.location(); }
492 public Symbol location(Type site, Types types) { return other.location(site, types); }
493 public Type erasure(Types types) { return other.erasure(types); }
494 public Type externalType(Types types) { return other.externalType(types); }
495 public boolean isLocal() { return other.isLocal(); }
496 public boolean isConstructor() { return other.isConstructor(); }
497 public Name getQualifiedName() { return other.getQualifiedName(); }
498 public Name flatName() { return other.flatName(); }
499 public Scope members() { return other.members(); }
500 public boolean isInner() { return other.isInner(); }
501 public boolean hasOuterInstance() { return other.hasOuterInstance(); }
502 public ClassSymbol enclClass() { return other.enclClass(); }
503 public ClassSymbol outermostClass() { return other.outermostClass(); }
504 public PackageSymbol packge() { return other.packge(); }
505 public boolean isSubClass(Symbol base, Types types) { return other.isSubClass(base, types); }
506 public boolean isMemberOf(TypeSymbol clazz, Types types) { return other.isMemberOf(clazz, types); }
507 public boolean isEnclosedBy(ClassSymbol clazz) { return other.isEnclosedBy(clazz); }
508 public boolean isInheritedIn(Symbol clazz, Types types) { return other.isInheritedIn(clazz, types); }
509 public Symbol asMemberOf(Type site, Types types) { return other.asMemberOf(site, types); }
510 public void complete() throws CompletionFailure { other.complete(); }
512 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
513 return other.accept(v, p);
514 }
516 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
517 return v.visitSymbol(other, p);
518 }
519 }
521 /** A class for type symbols. Type variables are represented by instances
522 * of this class, classes and packages by instances of subclasses.
523 */
524 public static class TypeSymbol
525 extends Symbol implements TypeParameterElement {
526 // Implements TypeParameterElement because type parameters don't
527 // have their own TypeSymbol subclass.
528 // TODO: type parameters should have their own TypeSymbol subclass
530 public TypeSymbol(long flags, Name name, Type type, Symbol owner) {
531 super(TYP, flags, name, type, owner);
532 }
534 /** form a fully qualified name from a name and an owner
535 */
536 static public Name formFullName(Name name, Symbol owner) {
537 if (owner == null) return name;
538 if (((owner.kind != ERR)) &&
539 ((owner.kind & (VAR | MTH)) != 0
540 || (owner.kind == TYP && owner.type.tag == TYPEVAR)
541 )) return name;
542 Name prefix = owner.getQualifiedName();
543 if (prefix == null || prefix == prefix.table.names.empty)
544 return name;
545 else return prefix.append('.', name);
546 }
548 /** form a fully qualified name from a name and an owner, after
549 * converting to flat representation
550 */
551 static public Name formFlatName(Name name, Symbol owner) {
552 if (owner == null ||
553 (owner.kind & (VAR | MTH)) != 0
554 || (owner.kind == TYP && owner.type.tag == TYPEVAR)
555 ) return name;
556 char sep = owner.kind == TYP ? '$' : '.';
557 Name prefix = owner.flatName();
558 if (prefix == null || prefix == prefix.table.names.empty)
559 return name;
560 else return prefix.append(sep, name);
561 }
563 /**
564 * A total ordering between type symbols that refines the
565 * class inheritance graph.
566 *
567 * Typevariables always precede other kinds of symbols.
568 */
569 public final boolean precedes(TypeSymbol that, Types types) {
570 if (this == that)
571 return false;
572 if (this.type.tag == that.type.tag) {
573 if (this.type.tag == CLASS) {
574 return
575 types.rank(that.type) < types.rank(this.type) ||
576 types.rank(that.type) == types.rank(this.type) &&
577 that.getQualifiedName().compareTo(this.getQualifiedName()) < 0;
578 } else if (this.type.tag == TYPEVAR) {
579 return types.isSubtype(this.type, that.type);
580 }
581 }
582 return this.type.tag == TYPEVAR;
583 }
585 // For type params; overridden in subclasses.
586 public ElementKind getKind() {
587 return ElementKind.TYPE_PARAMETER;
588 }
590 public java.util.List<Symbol> getEnclosedElements() {
591 List<Symbol> list = List.nil();
592 if (kind == TYP && type.tag == TYPEVAR) {
593 return list;
594 }
595 for (Scope.Entry e = members().elems; e != null; e = e.sibling) {
596 if (e.sym != null && (e.sym.flags() & SYNTHETIC) == 0 && e.sym.owner == this)
597 list = list.prepend(e.sym);
598 }
599 return list;
600 }
602 // For type params.
603 // Perhaps not needed if getEnclosingElement can be spec'ed
604 // to do the same thing.
605 // TODO: getGenericElement() might not be needed
606 public Symbol getGenericElement() {
607 return owner;
608 }
610 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
611 assert type.tag == TYPEVAR; // else override will be invoked
612 return v.visitTypeParameter(this, p);
613 }
615 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
616 return v.visitTypeSymbol(this, p);
617 }
619 public List<Type> getBounds() {
620 TypeVar t = (TypeVar)type;
621 Type bound = t.getUpperBound();
622 if (!bound.isCompound())
623 return List.of(bound);
624 ClassType ct = (ClassType)bound;
625 if (!ct.tsym.erasure_field.isInterface()) {
626 return ct.interfaces_field.prepend(ct.supertype_field);
627 } else {
628 // No superclass was given in bounds.
629 // In this case, supertype is Object, erasure is first interface.
630 return ct.interfaces_field;
631 }
632 }
633 }
635 /** A class for package symbols
636 */
637 public static class PackageSymbol extends TypeSymbol
638 implements PackageElement {
640 public Scope members_field;
641 public Name fullname;
642 public ClassSymbol package_info; // see bug 6443073
644 public PackageSymbol(Name name, Type type, Symbol owner) {
645 super(0, name, type, owner);
646 this.kind = PCK;
647 this.members_field = null;
648 this.fullname = formFullName(name, owner);
649 }
651 public PackageSymbol(Name name, Symbol owner) {
652 this(name, null, owner);
653 this.type = new PackageType(this);
654 }
656 public String toString() {
657 return fullname.toString();
658 }
660 public Name getQualifiedName() {
661 return fullname;
662 }
664 public boolean isUnnamed() {
665 return name.isEmpty() && owner != null;
666 }
668 public Scope members() {
669 if (completer != null) complete();
670 return members_field;
671 }
673 public long flags() {
674 if (completer != null) complete();
675 return flags_field;
676 }
678 public List<Attribute.Compound> getAnnotationMirrors() {
679 if (completer != null) complete();
680 if (package_info != null && package_info.completer != null) {
681 package_info.complete();
682 if (attributes_field.isEmpty())
683 attributes_field = package_info.attributes_field;
684 }
685 assert attributes_field != null;
686 return attributes_field;
687 }
689 /** A package "exists" if a type or package that exists has
690 * been seen within it.
691 */
692 public boolean exists() {
693 return (flags_field & EXISTS) != 0;
694 }
696 public ElementKind getKind() {
697 return ElementKind.PACKAGE;
698 }
700 public Symbol getEnclosingElement() {
701 return null;
702 }
704 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
705 return v.visitPackage(this, p);
706 }
708 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
709 return v.visitPackageSymbol(this, p);
710 }
711 }
713 /** A class for class symbols
714 */
715 public static class ClassSymbol extends TypeSymbol implements TypeElement {
717 /** a scope for all class members; variables, methods and inner classes
718 * type parameters are not part of this scope
719 */
720 public Scope members_field;
722 /** the fully qualified name of the class, i.e. pck.outer.inner.
723 * null for anonymous classes
724 */
725 public Name fullname;
727 /** the fully qualified name of the class after converting to flat
728 * representation, i.e. pck.outer$inner,
729 * set externally for local and anonymous classes
730 */
731 public Name flatname;
733 /** the sourcefile where the class came from
734 */
735 public JavaFileObject sourcefile;
737 /** the classfile from where to load this class
738 * this will have extension .class or .java
739 */
740 public JavaFileObject classfile;
742 /** the constant pool of the class
743 */
744 public Pool pool;
746 public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
747 super(flags, name, type, owner);
748 this.members_field = null;
749 this.fullname = formFullName(name, owner);
750 this.flatname = formFlatName(name, owner);
751 this.sourcefile = null;
752 this.classfile = null;
753 this.pool = null;
754 }
756 public ClassSymbol(long flags, Name name, Symbol owner) {
757 this(
758 flags,
759 name,
760 new ClassType(Type.noType, null, null),
761 owner);
762 this.type.tsym = this;
763 }
765 /** The Java source which this symbol represents.
766 */
767 public String toString() {
768 return className();
769 }
771 public long flags() {
772 if (completer != null) complete();
773 return flags_field;
774 }
776 public Scope members() {
777 if (completer != null) complete();
778 return members_field;
779 }
781 public List<Attribute.Compound> getAnnotationMirrors() {
782 if (completer != null) complete();
783 assert attributes_field != null;
784 return attributes_field;
785 }
787 public Type erasure(Types types) {
788 if (erasure_field == null)
789 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
790 List.<Type>nil(), this);
791 return erasure_field;
792 }
794 public String className() {
795 if (name.isEmpty())
796 return
797 Log.getLocalizedString("anonymous.class", flatname);
798 else
799 return fullname.toString();
800 }
802 public Name getQualifiedName() {
803 return fullname;
804 }
806 public Name flatName() {
807 return flatname;
808 }
810 public boolean isSubClass(Symbol base, Types types) {
811 if (this == base) {
812 return true;
813 } else if ((base.flags() & INTERFACE) != 0) {
814 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
815 for (List<Type> is = types.interfaces(t);
816 is.nonEmpty();
817 is = is.tail)
818 if (is.head.tsym.isSubClass(base, types)) return true;
819 } else {
820 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
821 if (t.tsym == base) return true;
822 }
823 return false;
824 }
826 /** Complete the elaboration of this symbol's definition.
827 */
828 public void complete() throws CompletionFailure {
829 try {
830 super.complete();
831 } catch (CompletionFailure ex) {
832 // quiet error recovery
833 flags_field |= (PUBLIC|STATIC);
834 this.type = new ErrorType(this, Type.noType);
835 throw ex;
836 }
837 }
839 public List<Type> getInterfaces() {
840 complete();
841 if (type instanceof ClassType) {
842 ClassType t = (ClassType)type;
843 if (t.interfaces_field == null) // FIXME: shouldn't be null
844 t.interfaces_field = List.nil();
845 return t.interfaces_field;
846 } else {
847 return List.nil();
848 }
849 }
851 public Type getSuperclass() {
852 complete();
853 if (type instanceof ClassType) {
854 ClassType t = (ClassType)type;
855 if (t.supertype_field == null) // FIXME: shouldn't be null
856 t.supertype_field = Type.noType;
857 // An interface has no superclass; its supertype is Object.
858 return t.isInterface()
859 ? Type.noType
860 : t.supertype_field;
861 } else {
862 return Type.noType;
863 }
864 }
866 public ElementKind getKind() {
867 long flags = flags();
868 if ((flags & ANNOTATION) != 0)
869 return ElementKind.ANNOTATION_TYPE;
870 else if ((flags & INTERFACE) != 0)
871 return ElementKind.INTERFACE;
872 else if ((flags & ENUM) != 0)
873 return ElementKind.ENUM;
874 else
875 return ElementKind.CLASS;
876 }
878 public NestingKind getNestingKind() {
879 complete();
880 if (owner.kind == PCK)
881 return NestingKind.TOP_LEVEL;
882 else if (name.isEmpty())
883 return NestingKind.ANONYMOUS;
884 else if (owner.kind == MTH)
885 return NestingKind.LOCAL;
886 else
887 return NestingKind.MEMBER;
888 }
890 /**
891 * @deprecated this method should never be used by javac internally.
892 */
893 @Override @Deprecated
894 public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
895 return JavacElements.getAnnotation(this, annoType);
896 }
898 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
899 return v.visitType(this, p);
900 }
902 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
903 return v.visitClassSymbol(this, p);
904 }
905 }
908 /** A class for variable symbols
909 */
910 public static class VarSymbol extends Symbol implements VariableElement {
912 /** The variable's declaration position.
913 */
914 public int pos = Position.NOPOS;
916 /** The variable's address. Used for different purposes during
917 * flow analysis, translation and code generation.
918 * Flow analysis:
919 * If this is a blank final or local variable, its sequence number.
920 * Translation:
921 * If this is a private field, its access number.
922 * Code generation:
923 * If this is a local variable, its logical slot number.
924 */
925 public int adr = -1;
927 /** Construct a variable symbol, given its flags, name, type and owner.
928 */
929 public VarSymbol(long flags, Name name, Type type, Symbol owner) {
930 super(VAR, flags, name, type, owner);
931 }
933 /** Clone this symbol with new owner.
934 */
935 public VarSymbol clone(Symbol newOwner) {
936 VarSymbol v = new VarSymbol(flags_field, name, type, newOwner);
937 v.pos = pos;
938 v.adr = adr;
939 v.data = data;
940 // System.out.println("clone " + v + " in " + newOwner);//DEBUG
941 return v;
942 }
944 public String toString() {
945 return name.toString();
946 }
948 public Symbol asMemberOf(Type site, Types types) {
949 return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
950 }
952 public ElementKind getKind() {
953 long flags = flags();
954 if ((flags & PARAMETER) != 0) {
955 if (isExceptionParameter())
956 return ElementKind.EXCEPTION_PARAMETER;
957 else
958 return ElementKind.PARAMETER;
959 } else if ((flags & ENUM) != 0) {
960 return ElementKind.ENUM_CONSTANT;
961 } else if (owner.kind == TYP || owner.kind == ERR) {
962 return ElementKind.FIELD;
963 } else {
964 return ElementKind.LOCAL_VARIABLE;
965 }
966 }
968 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
969 return v.visitVariable(this, p);
970 }
972 public Object getConstantValue() { // Mirror API
973 return Constants.decode(getConstValue(), type);
974 }
976 public void setLazyConstValue(final Env<AttrContext> env,
977 final Log log,
978 final Attr attr,
979 final JCTree.JCExpression initializer)
980 {
981 setData(new Callable<Object>() {
982 public Object call() {
983 JavaFileObject source = log.useSource(env.toplevel.sourcefile);
984 try {
985 Type itype = attr.attribExpr(initializer, env, type);
986 if (itype.constValue() != null)
987 return attr.coerce(itype, type).constValue();
988 else
989 return null;
990 } finally {
991 log.useSource(source);
992 }
993 }
994 });
995 }
997 /**
998 * The variable's constant value, if this is a constant.
999 * Before the constant value is evaluated, it points to an
1000 * initalizer environment. If this is not a constant, it can
1001 * be used for other stuff.
1002 */
1003 private Object data;
1005 public boolean isExceptionParameter() {
1006 return data == ElementKind.EXCEPTION_PARAMETER;
1007 }
1009 public boolean isResourceVariable() {
1010 return data == ElementKind.RESOURCE_VARIABLE;
1011 }
1013 public Object getConstValue() {
1014 // TODO: Consider if getConstValue and getConstantValue can be collapsed
1015 if (data == ElementKind.EXCEPTION_PARAMETER ||
1016 data == ElementKind.RESOURCE_VARIABLE) {
1017 return null;
1018 } else if (data instanceof Callable<?>) {
1019 // In this case, this is a final variable, with an as
1020 // yet unevaluated initializer.
1021 Callable<?> eval = (Callable<?>)data;
1022 data = null; // to make sure we don't evaluate this twice.
1023 try {
1024 data = eval.call();
1025 } catch (Exception ex) {
1026 throw new AssertionError(ex);
1027 }
1028 }
1029 return data;
1030 }
1032 public void setData(Object data) {
1033 assert !(data instanceof Env<?>) : this;
1034 this.data = data;
1035 }
1037 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1038 return v.visitVarSymbol(this, p);
1039 }
1040 }
1042 /** A class for method symbols.
1043 */
1044 public static class MethodSymbol extends Symbol implements ExecutableElement {
1046 /** The code of the method. */
1047 public Code code = null;
1049 /** The parameters of the method. */
1050 public List<VarSymbol> params = null;
1052 /** The names of the parameters */
1053 public List<Name> savedParameterNames;
1055 /** For an attribute field accessor, its default value if any.
1056 * The value is null if none appeared in the method
1057 * declaration.
1058 */
1059 public Attribute defaultValue = null;
1061 /** Construct a method symbol, given its flags, name, type and owner.
1062 */
1063 public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
1064 super(MTH, flags, name, type, owner);
1065 assert owner.type.tag != TYPEVAR : owner + "." + name;
1066 }
1068 /** Clone this symbol with new owner.
1069 */
1070 public MethodSymbol clone(Symbol newOwner) {
1071 MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner);
1072 m.code = code;
1073 return m;
1074 }
1076 /** The Java source which this symbol represents.
1077 */
1078 public String toString() {
1079 if ((flags() & BLOCK) != 0) {
1080 return owner.name.toString();
1081 } else {
1082 String s = (name == name.table.names.init)
1083 ? owner.name.toString()
1084 : name.toString();
1085 if (type != null) {
1086 if (type.tag == FORALL)
1087 s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
1088 s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
1089 }
1090 return s;
1091 }
1092 }
1094 /** find a symbol that this (proxy method) symbol implements.
1095 * @param c The class whose members are searched for
1096 * implementations
1097 */
1098 public Symbol implemented(TypeSymbol c, Types types) {
1099 Symbol impl = null;
1100 for (List<Type> is = types.interfaces(c.type);
1101 impl == null && is.nonEmpty();
1102 is = is.tail) {
1103 TypeSymbol i = is.head.tsym;
1104 for (Scope.Entry e = i.members().lookup(name);
1105 impl == null && e.scope != null;
1106 e = e.next()) {
1107 if (this.overrides(e.sym, (TypeSymbol)owner, types, true) &&
1108 // FIXME: I suspect the following requires a
1109 // subst() for a parametric return type.
1110 types.isSameType(type.getReturnType(),
1111 types.memberType(owner.type, e.sym).getReturnType())) {
1112 impl = e.sym;
1113 }
1114 if (impl == null)
1115 impl = implemented(i, types);
1116 }
1117 }
1118 return impl;
1119 }
1121 /** Will the erasure of this method be considered by the VM to
1122 * override the erasure of the other when seen from class `origin'?
1123 */
1124 public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
1125 if (isConstructor() || _other.kind != MTH) return false;
1127 if (this == _other) return true;
1128 MethodSymbol other = (MethodSymbol)_other;
1130 // check for a direct implementation
1131 if (other.isOverridableIn((TypeSymbol)owner) &&
1132 types.asSuper(owner.type, other.owner) != null &&
1133 types.isSameType(erasure(types), other.erasure(types)))
1134 return true;
1136 // check for an inherited implementation
1137 return
1138 (flags() & ABSTRACT) == 0 &&
1139 other.isOverridableIn(origin) &&
1140 this.isMemberOf(origin, types) &&
1141 types.isSameType(erasure(types), other.erasure(types));
1142 }
1144 /** The implementation of this (abstract) symbol in class origin,
1145 * from the VM's point of view, null if method does not have an
1146 * implementation in class.
1147 * @param origin The class of which the implementation is a member.
1148 */
1149 public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
1150 for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
1151 for (Scope.Entry e = c.members().lookup(name);
1152 e.scope != null;
1153 e = e.next()) {
1154 if (e.sym.kind == MTH &&
1155 ((MethodSymbol)e.sym).binaryOverrides(this, origin, types))
1156 return (MethodSymbol)e.sym;
1157 }
1158 }
1159 return null;
1160 }
1162 /** Does this symbol override `other' symbol, when both are seen as
1163 * members of class `origin'? It is assumed that _other is a member
1164 * of origin.
1165 *
1166 * It is assumed that both symbols have the same name. The static
1167 * modifier is ignored for this test.
1168 *
1169 * See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1170 */
1171 public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
1172 if (isConstructor() || _other.kind != MTH) return false;
1174 if (this == _other) return true;
1175 MethodSymbol other = (MethodSymbol)_other;
1177 // check for a direct implementation
1178 if (other.isOverridableIn((TypeSymbol)owner) &&
1179 types.asSuper(owner.type, other.owner) != null) {
1180 Type mt = types.memberType(owner.type, this);
1181 Type ot = types.memberType(owner.type, other);
1182 if (types.isSubSignature(mt, ot)) {
1183 if (!checkResult)
1184 return true;
1185 if (types.returnTypeSubstitutable(mt, ot))
1186 return true;
1187 }
1188 }
1190 // check for an inherited implementation
1191 if ((flags() & ABSTRACT) != 0 ||
1192 (other.flags() & ABSTRACT) == 0 ||
1193 !other.isOverridableIn(origin) ||
1194 !this.isMemberOf(origin, types))
1195 return false;
1197 // assert types.asSuper(origin.type, other.owner) != null;
1198 Type mt = types.memberType(origin.type, this);
1199 Type ot = types.memberType(origin.type, other);
1200 return
1201 types.isSubSignature(mt, ot) &&
1202 (!checkResult || types.resultSubtype(mt, ot, Warner.noWarnings));
1203 }
1205 private boolean isOverridableIn(TypeSymbol origin) {
1206 // JLS3 8.4.6.1
1207 switch ((int)(flags_field & Flags.AccessFlags)) {
1208 case Flags.PRIVATE:
1209 return false;
1210 case Flags.PUBLIC:
1211 return true;
1212 case Flags.PROTECTED:
1213 return (origin.flags() & INTERFACE) == 0;
1214 case 0:
1215 // for package private: can only override in the same
1216 // package
1217 return
1218 this.packge() == origin.packge() &&
1219 (origin.flags() & INTERFACE) == 0;
1220 default:
1221 return false;
1222 }
1223 }
1225 /** The implementation of this (abstract) symbol in class origin;
1226 * null if none exists. Synthetic methods are not considered
1227 * as possible implementations.
1228 */
1229 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1230 return implementation(origin, types, checkResult, implementation_filter);
1231 }
1232 // where
1233 private static final Filter<Symbol> implementation_filter = new Filter<Symbol>() {
1234 public boolean accepts(Symbol s) {
1235 return s.kind == Kinds.MTH &&
1236 (s.flags() & SYNTHETIC) == 0;
1237 }
1238 };
1240 public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
1241 MethodSymbol res = types.implementation(this, origin, types, checkResult, implFilter);
1242 if (res != null)
1243 return res;
1244 // if origin is derived from a raw type, we might have missed
1245 // an implementation because we do not know enough about instantiations.
1246 // in this case continue with the supertype as origin.
1247 if (types.isDerivedRaw(origin.type))
1248 return implementation(types.supertype(origin.type).tsym, types, checkResult);
1249 else
1250 return null;
1251 }
1253 public List<VarSymbol> params() {
1254 owner.complete();
1255 if (params == null) {
1256 // If ClassReader.saveParameterNames has been set true, then
1257 // savedParameterNames will be set to a list of names that
1258 // matches the types in type.getParameterTypes(). If any names
1259 // were not found in the class file, those names in the list will
1260 // be set to the empty name.
1261 // If ClassReader.saveParameterNames has been set false, then
1262 // savedParameterNames will be null.
1263 List<Name> paramNames = savedParameterNames;
1264 savedParameterNames = null;
1265 // discard the provided names if the list of names is the wrong size.
1266 if (paramNames == null || paramNames.size() != type.getParameterTypes().size())
1267 paramNames = List.nil();
1268 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
1269 List<Name> remaining = paramNames;
1270 // assert: remaining and paramNames are both empty or both
1271 // have same cardinality as type.getParameterTypes()
1272 int i = 0;
1273 for (Type t : type.getParameterTypes()) {
1274 Name paramName;
1275 if (remaining.isEmpty()) {
1276 // no names for any parameters available
1277 paramName = createArgName(i, paramNames);
1278 } else {
1279 paramName = remaining.head;
1280 remaining = remaining.tail;
1281 if (paramName.isEmpty()) {
1282 // no name for this specific parameter
1283 paramName = createArgName(i, paramNames);
1284 }
1285 }
1286 buf.append(new VarSymbol(PARAMETER, paramName, t, this));
1287 i++;
1288 }
1289 params = buf.toList();
1290 }
1291 return params;
1292 }
1294 // Create a name for the argument at position 'index' that is not in
1295 // the exclude list. In normal use, either no names will have been
1296 // provided, in which case the exclude list is empty, or all the names
1297 // will have been provided, in which case this method will not be called.
1298 private Name createArgName(int index, List<Name> exclude) {
1299 String prefix = "arg";
1300 while (true) {
1301 Name argName = name.table.fromString(prefix + index);
1302 if (!exclude.contains(argName))
1303 return argName;
1304 prefix += "$";
1305 }
1306 }
1308 public Symbol asMemberOf(Type site, Types types) {
1309 return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
1310 }
1312 public ElementKind getKind() {
1313 if (name == name.table.names.init)
1314 return ElementKind.CONSTRUCTOR;
1315 else if (name == name.table.names.clinit)
1316 return ElementKind.STATIC_INIT;
1317 else
1318 return ElementKind.METHOD;
1319 }
1321 public Attribute getDefaultValue() {
1322 return defaultValue;
1323 }
1325 public List<VarSymbol> getParameters() {
1326 return params();
1327 }
1329 public boolean isVarArgs() {
1330 return (flags() & VARARGS) != 0;
1331 }
1333 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1334 return v.visitExecutable(this, p);
1335 }
1337 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1338 return v.visitMethodSymbol(this, p);
1339 }
1341 public Type getReturnType() {
1342 return asType().getReturnType();
1343 }
1345 public List<Type> getThrownTypes() {
1346 return asType().getThrownTypes();
1347 }
1348 }
1350 /** A class for predefined operators.
1351 */
1352 public static class OperatorSymbol extends MethodSymbol {
1354 public int opcode;
1356 public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
1357 super(PUBLIC | STATIC, name, type, owner);
1358 this.opcode = opcode;
1359 }
1361 public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1362 return v.visitOperatorSymbol(this, p);
1363 }
1364 }
1366 /** Symbol completer interface.
1367 */
1368 public static interface Completer {
1369 void complete(Symbol sym) throws CompletionFailure;
1370 }
1372 public static class CompletionFailure extends RuntimeException {
1373 private static final long serialVersionUID = 0;
1374 public Symbol sym;
1376 /** A diagnostic object describing the failure
1377 */
1378 public JCDiagnostic diag;
1380 /** A localized string describing the failure.
1381 * @deprecated Use {@code getDetail()} or {@code getMessage()}
1382 */
1383 @Deprecated
1384 public String errmsg;
1386 public CompletionFailure(Symbol sym, String errmsg) {
1387 this.sym = sym;
1388 this.errmsg = errmsg;
1389 // this.printStackTrace();//DEBUG
1390 }
1392 public CompletionFailure(Symbol sym, JCDiagnostic diag) {
1393 this.sym = sym;
1394 this.diag = diag;
1395 // this.printStackTrace();//DEBUG
1396 }
1398 public JCDiagnostic getDiagnostic() {
1399 return diag;
1400 }
1402 @Override
1403 public String getMessage() {
1404 if (diag != null)
1405 return diag.getMessage(null);
1406 else
1407 return errmsg;
1408 }
1410 public Object getDetailValue() {
1411 return (diag != null ? diag : errmsg);
1412 }
1414 @Override
1415 public CompletionFailure initCause(Throwable cause) {
1416 super.initCause(cause);
1417 return this;
1418 }
1420 }
1422 /**
1423 * A visitor for symbols. A visitor is used to implement operations
1424 * (or relations) on symbols. Most common operations on types are
1425 * binary relations and this interface is designed for binary
1426 * relations, that is, operations on the form
1427 * Symbol × P → R.
1428 * <!-- In plain text: Type x P -> R -->
1429 *
1430 * @param <R> the return type of the operation implemented by this
1431 * visitor; use Void if no return type is needed.
1432 * @param <P> the type of the second argument (the first being the
1433 * symbol itself) of the operation implemented by this visitor; use
1434 * Void if a second argument is not needed.
1435 */
1436 public interface Visitor<R,P> {
1437 R visitClassSymbol(ClassSymbol s, P arg);
1438 R visitMethodSymbol(MethodSymbol s, P arg);
1439 R visitPackageSymbol(PackageSymbol s, P arg);
1440 R visitOperatorSymbol(OperatorSymbol s, P arg);
1441 R visitVarSymbol(VarSymbol s, P arg);
1442 R visitTypeSymbol(TypeSymbol s, P arg);
1443 R visitSymbol(Symbol s, P arg);
1444 }
1445 }