Type.java revision 2571:10fc81ac75b4
1/*
2 * Copyright (c) 1999, 2014, 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 */
25
26package com.sun.tools.javac.code;
27
28import java.lang.annotation.Annotation;
29import java.util.Collections;
30import java.util.EnumMap;
31import java.util.EnumSet;
32import java.util.Map;
33import java.util.Set;
34
35import javax.lang.model.type.*;
36
37import com.sun.tools.javac.code.Symbol.*;
38import com.sun.tools.javac.util.*;
39import static com.sun.tools.javac.code.BoundKind.*;
40import static com.sun.tools.javac.code.Flags.*;
41import static com.sun.tools.javac.code.Kinds.*;
42import static com.sun.tools.javac.code.TypeTag.*;
43
44/** This class represents Java types. The class itself defines the behavior of
45 *  the following types:
46 *  <pre>
47 *  base types (tags: BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN),
48 *  type `void' (tag: VOID),
49 *  the bottom type (tag: BOT),
50 *  the missing type (tag: NONE).
51 *  </pre>
52 *  <p>The behavior of the following types is defined in subclasses, which are
53 *  all static inner classes of this class:
54 *  <pre>
55 *  class types (tag: CLASS, class: ClassType),
56 *  array types (tag: ARRAY, class: ArrayType),
57 *  method types (tag: METHOD, class: MethodType),
58 *  package types (tag: PACKAGE, class: PackageType),
59 *  type variables (tag: TYPEVAR, class: TypeVar),
60 *  type arguments (tag: WILDCARD, class: WildcardType),
61 *  generic method types (tag: FORALL, class: ForAll),
62 *  the error type (tag: ERROR, class: ErrorType).
63 *  </pre>
64 *
65 *  <p><b>This is NOT part of any supported API.
66 *  If you write code that depends on this, you do so at your own risk.
67 *  This code and its internal interfaces are subject to change or
68 *  deletion without notice.</b>
69 *
70 *  @see TypeTag
71 */
72public abstract class Type extends AnnoConstruct implements TypeMirror {
73
74    /** Constant type: no type at all. */
75    public static final JCNoType noType = new JCNoType() {
76        @Override
77        public String toString() {
78            return "none";
79        }
80    };
81
82    /** Constant type: special type to be used during recovery of deferred expressions. */
83    public static final JCNoType recoveryType = new JCNoType(){
84        @Override
85        public String toString() {
86            return "recovery";
87        }
88    };
89
90    /** Constant type: special type to be used for marking stuck trees. */
91    public static final JCNoType stuckType = new JCNoType() {
92        @Override
93        public String toString() {
94            return "stuck";
95        }
96    };
97
98    public static final List<Attribute.TypeCompound> noAnnotations =
99        List.nil();
100
101    /** If this switch is turned on, the names of type variables
102     *  and anonymous classes are printed with hashcodes appended.
103     */
104    public static boolean moreInfo = false;
105
106    /** The defining class / interface / package / type variable.
107     */
108    public TypeSymbol tsym;
109
110    /** The type annotations on this type.
111     */
112    protected final List<Attribute.TypeCompound> annos;
113
114    /**
115     * Checks if the current type tag is equal to the given tag.
116     * @return true if tag is equal to the current type tag.
117     */
118    public boolean hasTag(TypeTag tag) {
119        return tag == getTag();
120    }
121
122    /**
123     * Returns the current type tag.
124     * @return the value of the current type tag.
125     */
126    public abstract TypeTag getTag();
127
128    public boolean isNumeric() {
129        return false;
130    }
131
132    public boolean isPrimitive() {
133        return false;
134    }
135
136    public boolean isPrimitiveOrVoid() {
137        return false;
138    }
139
140    public boolean isReference() {
141        return false;
142    }
143
144    public boolean isNullOrReference() {
145        return false;
146    }
147
148    public boolean isPartial() {
149        return false;
150    }
151
152    /**
153     * The constant value of this type, null if this type does not
154     * have a constant value attribute. Only primitive types and
155     * strings (ClassType) can have a constant value attribute.
156     * @return the constant value attribute of this type
157     */
158    public Object constValue() {
159        return null;
160    }
161
162    /** Is this a constant type whose value is false?
163     */
164    public boolean isFalse() {
165        return false;
166    }
167
168    /** Is this a constant type whose value is true?
169     */
170    public boolean isTrue() {
171        return false;
172    }
173
174    /**
175     * Get the representation of this type used for modelling purposes.
176     * By default, this is itself. For ErrorType, a different value
177     * may be provided.
178     */
179    public Type getModelType() {
180        return this;
181    }
182
183    public static List<Type> getModelTypes(List<Type> ts) {
184        ListBuffer<Type> lb = new ListBuffer<>();
185        for (Type t: ts)
186            lb.append(t.getModelType());
187        return lb.toList();
188    }
189
190    /**For ErrorType, returns the original type, otherwise returns the type itself.
191     */
192    public Type getOriginalType() {
193        return this;
194    }
195
196    public <R,S> R accept(Type.Visitor<R,S> v, S s) { return v.visitType(this, s); }
197
198    /** Define a type given its tag, type symbol, and type annotations
199     */
200    public Type(TypeSymbol tsym, List<Attribute.TypeCompound> annos) {
201        if(annos == null) {
202            Assert.error("Attempting to create type " + tsym + " with null type annotations");
203        }
204
205        this.tsym = tsym;
206        this.annos = annos;
207    }
208
209    /** An abstract class for mappings from types to types
210     */
211    public static abstract class Mapping {
212        private String name;
213        public Mapping(String name) {
214            this.name = name;
215        }
216        public abstract Type apply(Type t);
217        public String toString() {
218            return name;
219        }
220    }
221
222    /** map a type function over all immediate descendants of this type
223     */
224    public Type map(Mapping f) {
225        return this;
226    }
227
228    /** map a type function over a list of types
229     */
230    public static List<Type> map(List<Type> ts, Mapping f) {
231        if (ts.nonEmpty()) {
232            List<Type> tail1 = map(ts.tail, f);
233            Type t = f.apply(ts.head);
234            if (tail1 != ts.tail || t != ts.head)
235                return tail1.prepend(t);
236        }
237        return ts;
238    }
239
240    /** Define a constant type, of the same kind as this type
241     *  and with given constant value
242     */
243    public Type constType(Object constValue) {
244        throw new AssertionError();
245    }
246
247    /**
248     * If this is a constant type, return its underlying type.
249     * Otherwise, return the type itself.
250     */
251    public Type baseType() {
252        return this;
253    }
254
255    public abstract Type annotatedType(List<Attribute.TypeCompound> annos);
256
257    public boolean isAnnotated() {
258        return !annos.isEmpty();
259    }
260
261    @Override
262    public List<Attribute.TypeCompound> getAnnotationMirrors() {
263        return annos;
264    }
265
266
267    @Override
268    public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
269        return null;
270    }
271
272
273    @Override
274    public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
275        @SuppressWarnings("unchecked")
276        A[] tmp = (A[]) java.lang.reflect.Array.newInstance(annotationType, 0);
277        return tmp;
278    }
279
280    /** Return the base types of a list of types.
281     */
282    public static List<Type> baseTypes(List<Type> ts) {
283        if (ts.nonEmpty()) {
284            Type t = ts.head.baseType();
285            List<Type> baseTypes = baseTypes(ts.tail);
286            if (t != ts.head || baseTypes != ts.tail)
287                return baseTypes.prepend(t);
288        }
289        return ts;
290    }
291
292    protected void appendAnnotationsString(StringBuilder sb,
293                                         boolean prefix) {
294        if (isAnnotated()) {
295            if (prefix) {
296                sb.append(" ");
297            }
298            sb.append(annos);
299            sb.append(" ");
300        }
301    }
302
303    protected void appendAnnotationsString(StringBuilder sb) {
304        appendAnnotationsString(sb, false);
305    }
306
307    /** The Java source which this type represents.
308     */
309    public String toString() {
310        StringBuilder sb = new StringBuilder();
311        appendAnnotationsString(sb);
312        if (tsym == null || tsym.name == null) {
313            sb.append("<none>");
314        } else {
315            sb.append(tsym.name);
316        }
317        if (moreInfo && hasTag(TYPEVAR)) {
318            sb.append(hashCode());
319        }
320        return sb.toString();
321    }
322
323    /**
324     * The Java source which this type list represents.  A List is
325     * represented as a comma-spearated listing of the elements in
326     * that list.
327     */
328    public static String toString(List<Type> ts) {
329        if (ts.isEmpty()) {
330            return "";
331        } else {
332            StringBuilder buf = new StringBuilder();
333            buf.append(ts.head.toString());
334            for (List<Type> l = ts.tail; l.nonEmpty(); l = l.tail)
335                buf.append(",").append(l.head.toString());
336            return buf.toString();
337        }
338    }
339
340    /**
341     * The constant value of this type, converted to String
342     */
343    public String stringValue() {
344        Object cv = Assert.checkNonNull(constValue());
345        return cv.toString();
346    }
347
348    /**
349     * This method is analogous to isSameType, but weaker, since we
350     * never complete classes. Where isSameType would complete a
351     * class, equals assumes that the two types are different.
352     */
353    @Override
354    public boolean equals(Object t) {
355        return super.equals(t);
356    }
357
358    @Override
359    public int hashCode() {
360        return super.hashCode();
361    }
362
363    public String argtypes(boolean varargs) {
364        List<Type> args = getParameterTypes();
365        if (!varargs) return args.toString();
366        StringBuilder buf = new StringBuilder();
367        while (args.tail.nonEmpty()) {
368            buf.append(args.head);
369            args = args.tail;
370            buf.append(',');
371        }
372        if (args.head.hasTag(ARRAY)) {
373            buf.append(((ArrayType)args.head).elemtype);
374            if (args.head.getAnnotationMirrors().nonEmpty()) {
375                buf.append(args.head.getAnnotationMirrors());
376            }
377            buf.append("...");
378        } else {
379            buf.append(args.head);
380        }
381        return buf.toString();
382    }
383
384    /** Access methods.
385     */
386    public List<Type>        getTypeArguments()  { return List.nil(); }
387    public Type              getEnclosingType()  { return null; }
388    public List<Type>        getParameterTypes() { return List.nil(); }
389    public Type              getReturnType()     { return null; }
390    public Type              getReceiverType()   { return null; }
391    public List<Type>        getThrownTypes()    { return List.nil(); }
392    public Type              getUpperBound()     { return null; }
393    public Type              getLowerBound()     { return null; }
394
395    /** Navigation methods, these will work for classes, type variables,
396     *  foralls, but will return null for arrays and methods.
397     */
398
399   /** Return all parameters of this type and all its outer types in order
400    *  outer (first) to inner (last).
401    */
402    public List<Type> allparams() { return List.nil(); }
403
404    /** Does this type contain "error" elements?
405     */
406    public boolean isErroneous() {
407        return false;
408    }
409
410    public static boolean isErroneous(List<Type> ts) {
411        for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
412            if (l.head.isErroneous()) return true;
413        return false;
414    }
415
416    /** Is this type parameterized?
417     *  A class type is parameterized if it has some parameters.
418     *  An array type is parameterized if its element type is parameterized.
419     *  All other types are not parameterized.
420     */
421    public boolean isParameterized() {
422        return false;
423    }
424
425    /** Is this type a raw type?
426     *  A class type is a raw type if it misses some of its parameters.
427     *  An array type is a raw type if its element type is raw.
428     *  All other types are not raw.
429     *  Type validation will ensure that the only raw types
430     *  in a program are types that miss all their type variables.
431     */
432    public boolean isRaw() {
433        return false;
434    }
435
436    public boolean isCompound() {
437        return tsym.completer == null
438            // Compound types can't have a completer.  Calling
439            // flags() will complete the symbol causing the
440            // compiler to load classes unnecessarily.  This led
441            // to regression 6180021.
442            && (tsym.flags() & COMPOUND) != 0;
443    }
444
445    public boolean isInterface() {
446        return (tsym.flags() & INTERFACE) != 0;
447    }
448
449    public boolean isFinal() {
450        return (tsym.flags() & FINAL) != 0;
451    }
452
453    /**
454     * Does this type contain occurrences of type t?
455     */
456    public boolean contains(Type t) {
457        return t == this;
458    }
459
460    public static boolean contains(List<Type> ts, Type t) {
461        for (List<Type> l = ts;
462             l.tail != null /*inlined: l.nonEmpty()*/;
463             l = l.tail)
464            if (l.head.contains(t)) return true;
465        return false;
466    }
467
468    /** Does this type contain an occurrence of some type in 'ts'?
469     */
470    public boolean containsAny(List<Type> ts) {
471        for (Type t : ts)
472            if (this.contains(t)) return true;
473        return false;
474    }
475
476    public static boolean containsAny(List<Type> ts1, List<Type> ts2) {
477        for (Type t : ts1)
478            if (t.containsAny(ts2)) return true;
479        return false;
480    }
481
482    public static List<Type> filter(List<Type> ts, Filter<Type> tf) {
483        ListBuffer<Type> buf = new ListBuffer<>();
484        for (Type t : ts) {
485            if (tf.accepts(t)) {
486                buf.append(t);
487            }
488        }
489        return buf.toList();
490    }
491
492    public boolean isSuperBound() { return false; }
493    public boolean isExtendsBound() { return false; }
494    public boolean isUnbound() { return false; }
495    public Type withTypeVar(Type t) { return this; }
496
497    /** The underlying method type of this type.
498     */
499    public MethodType asMethodType() { throw new AssertionError(); }
500
501    /** Complete loading all classes in this type.
502     */
503    public void complete() {}
504
505    public TypeSymbol asElement() {
506        return tsym;
507    }
508
509    @Override
510    public TypeKind getKind() {
511        return TypeKind.OTHER;
512    }
513
514    @Override
515    public <R, P> R accept(TypeVisitor<R, P> v, P p) {
516        throw new AssertionError();
517    }
518
519    public static class JCPrimitiveType extends Type
520            implements javax.lang.model.type.PrimitiveType {
521
522        TypeTag tag;
523
524        public JCPrimitiveType(TypeTag tag, TypeSymbol tsym) {
525            this(tag, tsym, noAnnotations);
526        }
527
528        public JCPrimitiveType(TypeTag tag, TypeSymbol tsym,
529                               List<Attribute.TypeCompound> annos) {
530            super(tsym, annos);
531            this.tag = tag;
532            Assert.check(tag.isPrimitive);
533        }
534
535        @Override
536        public Type annotatedType(List<Attribute.TypeCompound> annos) {
537            return new JCPrimitiveType(tag, tsym, annos);
538        }
539
540        @Override
541        public boolean isNumeric() {
542            return tag != BOOLEAN;
543        }
544
545        @Override
546        public boolean isPrimitive() {
547            return true;
548        }
549
550        @Override
551        public TypeTag getTag() {
552            return tag;
553        }
554
555        @Override
556        public boolean isPrimitiveOrVoid() {
557            return true;
558        }
559
560        /** Define a constant type, of the same kind as this type
561         *  and with given constant value
562         */
563        @Override
564        public Type constType(Object constValue) {
565            final Object value = constValue;
566            return new JCPrimitiveType(tag, tsym, annos) {
567                    @Override
568                    public Object constValue() {
569                        return value;
570                    }
571                    @Override
572                    public Type baseType() {
573                        return tsym.type;
574                    }
575                };
576        }
577
578        /**
579         * The constant value of this type, converted to String
580         */
581        @Override
582        public String stringValue() {
583            Object cv = Assert.checkNonNull(constValue());
584            if (tag == BOOLEAN) {
585                return ((Integer) cv).intValue() == 0 ? "false" : "true";
586            }
587            else if (tag == CHAR) {
588                return String.valueOf((char) ((Integer) cv).intValue());
589            }
590            else {
591                return cv.toString();
592            }
593        }
594
595        /** Is this a constant type whose value is false?
596         */
597        @Override
598        public boolean isFalse() {
599            return
600                tag == BOOLEAN &&
601                constValue() != null &&
602                ((Integer)constValue()).intValue() == 0;
603        }
604
605        /** Is this a constant type whose value is true?
606         */
607        @Override
608        public boolean isTrue() {
609            return
610                tag == BOOLEAN &&
611                constValue() != null &&
612                ((Integer)constValue()).intValue() != 0;
613        }
614
615        @Override
616        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
617            return v.visitPrimitive(this, p);
618        }
619
620        @Override
621        public TypeKind getKind() {
622            switch (tag) {
623                case BYTE:      return TypeKind.BYTE;
624                case CHAR:      return TypeKind.CHAR;
625                case SHORT:     return TypeKind.SHORT;
626                case INT:       return TypeKind.INT;
627                case LONG:      return TypeKind.LONG;
628                case FLOAT:     return TypeKind.FLOAT;
629                case DOUBLE:    return TypeKind.DOUBLE;
630                case BOOLEAN:   return TypeKind.BOOLEAN;
631            }
632            throw new AssertionError();
633        }
634
635    }
636
637    public static class WildcardType extends Type
638            implements javax.lang.model.type.WildcardType {
639
640        public Type type;
641        public BoundKind kind;
642        public TypeVar bound;
643
644        @Override
645        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
646            return v.visitWildcardType(this, s);
647        }
648
649        public WildcardType(Type type, BoundKind kind, TypeSymbol tsym) {
650            this(type, kind, tsym, null, noAnnotations);
651        }
652
653        public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
654                            List<Attribute.TypeCompound> annos) {
655            this(type, kind, tsym, null, annos);
656        }
657
658        public WildcardType(WildcardType t, TypeVar bound,
659                            List<Attribute.TypeCompound> annos) {
660            this(t.type, t.kind, t.tsym, bound, annos);
661        }
662
663        public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
664                            TypeVar bound) {
665            this(type, kind, tsym, noAnnotations);
666        }
667
668        public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
669                            TypeVar bound, List<Attribute.TypeCompound> annos) {
670            super(tsym, annos);
671            this.type = Assert.checkNonNull(type);
672            this.kind = kind;
673            this.bound = bound;
674        }
675
676        @Override
677        public WildcardType annotatedType(List<Attribute.TypeCompound> annos) {
678            return new WildcardType(type, kind, tsym, bound, annos);
679        }
680
681        @Override
682        public TypeTag getTag() {
683            return WILDCARD;
684        }
685
686        @Override
687        public boolean contains(Type t) {
688            return kind != UNBOUND && type.contains(t);
689        }
690
691        public boolean isSuperBound() {
692            return kind == SUPER ||
693                kind == UNBOUND;
694        }
695        public boolean isExtendsBound() {
696            return kind == EXTENDS ||
697                kind == UNBOUND;
698        }
699        public boolean isUnbound() {
700            return kind == UNBOUND;
701        }
702
703        @Override
704        public boolean isReference() {
705            return true;
706        }
707
708        @Override
709        public boolean isNullOrReference() {
710            return true;
711        }
712
713        @Override
714        public Type withTypeVar(Type t) {
715            //-System.err.println(this+".withTypeVar("+t+");");//DEBUG
716            if (bound == t)
717                return this;
718            bound = (TypeVar)t;
719            return this;
720        }
721
722        boolean isPrintingBound = false;
723        public String toString() {
724            StringBuilder s = new StringBuilder();
725            appendAnnotationsString(s);
726            s.append(kind.toString());
727            if (kind != UNBOUND)
728                s.append(type);
729            if (moreInfo && bound != null && !isPrintingBound)
730                try {
731                    isPrintingBound = true;
732                    s.append("{:").append(bound.bound).append(":}");
733                } finally {
734                    isPrintingBound = false;
735                }
736            return s.toString();
737        }
738
739        public Type map(Mapping f) {
740            //- System.err.println("   (" + this + ").map(" + f + ")");//DEBUG
741            Type t = type;
742            if (t != null)
743                t = f.apply(t);
744            if (t == type)
745                return this;
746            else
747                return new WildcardType(t, kind, tsym, bound, annos);
748        }
749
750        public Type getExtendsBound() {
751            if (kind == EXTENDS)
752                return type;
753            else
754                return null;
755        }
756
757        public Type getSuperBound() {
758            if (kind == SUPER)
759                return type;
760            else
761                return null;
762        }
763
764        public TypeKind getKind() {
765            return TypeKind.WILDCARD;
766        }
767
768        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
769            return v.visitWildcard(this, p);
770        }
771    }
772
773    public static class ClassType extends Type implements DeclaredType {
774
775        /** The enclosing type of this type. If this is the type of an inner
776         *  class, outer_field refers to the type of its enclosing
777         *  instance class, in all other cases it refers to noType.
778         */
779        private Type outer_field;
780
781        /** The type parameters of this type (to be set once class is loaded).
782         */
783        public List<Type> typarams_field;
784
785        /** A cache variable for the type parameters of this type,
786         *  appended to all parameters of its enclosing class.
787         *  @see #allparams
788         */
789        public List<Type> allparams_field;
790
791        /** The supertype of this class (to be set once class is loaded).
792         */
793        public Type supertype_field;
794
795        /** The interfaces of this class (to be set once class is loaded).
796         */
797        public List<Type> interfaces_field;
798
799        /** All the interfaces of this class, including missing ones.
800         */
801        public List<Type> all_interfaces_field;
802
803        public ClassType(Type outer, List<Type> typarams, TypeSymbol tsym) {
804            this(outer, typarams, tsym, noAnnotations);
805        }
806
807        public ClassType(Type outer, List<Type> typarams, TypeSymbol tsym,
808                         List<Attribute.TypeCompound> annos) {
809            super(tsym, annos);
810            this.outer_field = outer;
811            this.typarams_field = typarams;
812            this.allparams_field = null;
813            this.supertype_field = null;
814            this.interfaces_field = null;
815            /*
816            // this can happen during error recovery
817            assert
818                outer.isParameterized() ?
819                typarams.length() == tsym.type.typarams().length() :
820                outer.isRaw() ?
821                typarams.length() == 0 :
822                true;
823            */
824        }
825
826        @Override
827        public ClassType annotatedType(List<Attribute.TypeCompound> annos) {
828            final ClassType out = new ClassType(outer_field, typarams_field, tsym, annos);
829            out.allparams_field = allparams_field;
830            out.supertype_field = supertype_field;
831            out.interfaces_field = interfaces_field;
832            return out;
833        }
834
835        @Override
836        public TypeTag getTag() {
837            return CLASS;
838        }
839
840        @Override
841        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
842            return v.visitClassType(this, s);
843        }
844
845        public Type constType(Object constValue) {
846            final Object value = constValue;
847            return new ClassType(getEnclosingType(), typarams_field, tsym, annos) {
848                    @Override
849                    public Object constValue() {
850                        return value;
851                    }
852                    @Override
853                    public Type baseType() {
854                        return tsym.type;
855                    }
856                };
857        }
858
859        /** The Java source which this type represents.
860         */
861        public String toString() {
862            StringBuilder buf = new StringBuilder();
863            appendAnnotationsString(buf);
864            if (getEnclosingType().hasTag(CLASS) && tsym.owner.kind == TYP) {
865                buf.append(getEnclosingType().toString());
866                buf.append(".");
867                buf.append(className(tsym, false));
868            } else {
869                buf.append(className(tsym, true));
870            }
871            if (getTypeArguments().nonEmpty()) {
872                buf.append('<');
873                buf.append(getTypeArguments().toString());
874                buf.append(">");
875            }
876            return buf.toString();
877        }
878//where
879            private String className(Symbol sym, boolean longform) {
880                if (sym.name.isEmpty() && (sym.flags() & COMPOUND) != 0) {
881                    StringBuilder s = new StringBuilder(supertype_field.toString());
882                    for (List<Type> is=interfaces_field; is.nonEmpty(); is = is.tail) {
883                        s.append("&");
884                        s.append(is.head.toString());
885                    }
886                    return s.toString();
887                } else if (sym.name.isEmpty()) {
888                    String s;
889                    ClassType norm = (ClassType) tsym.type;
890                    if (norm == null) {
891                        s = Log.getLocalizedString("anonymous.class", (Object)null);
892                    } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
893                        s = Log.getLocalizedString("anonymous.class",
894                                                   norm.interfaces_field.head);
895                    } else {
896                        s = Log.getLocalizedString("anonymous.class",
897                                                   norm.supertype_field);
898                    }
899                    if (moreInfo)
900                        s += String.valueOf(sym.hashCode());
901                    return s;
902                } else if (longform) {
903                    return sym.getQualifiedName().toString();
904                } else {
905                    return sym.name.toString();
906                }
907            }
908
909        public List<Type> getTypeArguments() {
910            if (typarams_field == null) {
911                complete();
912                if (typarams_field == null)
913                    typarams_field = List.nil();
914            }
915            return typarams_field;
916        }
917
918        public boolean hasErasedSupertypes() {
919            return isRaw();
920        }
921
922        public Type getEnclosingType() {
923            return outer_field;
924        }
925
926        public void setEnclosingType(Type outer) {
927            outer_field = outer;
928        }
929
930        public List<Type> allparams() {
931            if (allparams_field == null) {
932                allparams_field = getTypeArguments().prependList(getEnclosingType().allparams());
933            }
934            return allparams_field;
935        }
936
937        public boolean isErroneous() {
938            return
939                getEnclosingType().isErroneous() ||
940                isErroneous(getTypeArguments()) ||
941                this != tsym.type && tsym.type.isErroneous();
942        }
943
944        public boolean isParameterized() {
945            return allparams().tail != null;
946            // optimization, was: allparams().nonEmpty();
947        }
948
949        @Override
950        public boolean isReference() {
951            return true;
952        }
953
954        @Override
955        public boolean isNullOrReference() {
956            return true;
957        }
958
959        /** A cache for the rank. */
960        int rank_field = -1;
961
962        /** A class type is raw if it misses some
963         *  of its type parameter sections.
964         *  After validation, this is equivalent to:
965         *  {@code allparams.isEmpty() && tsym.type.allparams.nonEmpty(); }
966         */
967        public boolean isRaw() {
968            return
969                this != tsym.type && // necessary, but not sufficient condition
970                tsym.type.allparams().nonEmpty() &&
971                allparams().isEmpty();
972        }
973
974        public Type map(Mapping f) {
975            Type outer = getEnclosingType();
976            Type outer1 = f.apply(outer);
977            List<Type> typarams = getTypeArguments();
978            List<Type> typarams1 = map(typarams, f);
979            if (outer1 == outer && typarams1 == typarams) return this;
980            else return new ClassType(outer1, typarams1, tsym, annos);
981        }
982
983        public boolean contains(Type elem) {
984            return
985                elem == this
986                || (isParameterized()
987                    && (getEnclosingType().contains(elem) || contains(getTypeArguments(), elem)))
988                || (isCompound()
989                    && (supertype_field.contains(elem) || contains(interfaces_field, elem)));
990        }
991
992        public void complete() {
993            if (tsym.completer != null) tsym.complete();
994        }
995
996        public TypeKind getKind() {
997            return TypeKind.DECLARED;
998        }
999
1000        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1001            return v.visitDeclared(this, p);
1002        }
1003    }
1004
1005    public static class ErasedClassType extends ClassType {
1006        public ErasedClassType(Type outer, TypeSymbol tsym) {
1007            this(outer, tsym, noAnnotations);
1008        }
1009
1010        public ErasedClassType(Type outer, TypeSymbol tsym,
1011                               List<Attribute.TypeCompound> annos) {
1012            super(outer, List.<Type>nil(), tsym, annos);
1013        }
1014
1015        @Override
1016        public boolean hasErasedSupertypes() {
1017            return true;
1018        }
1019    }
1020
1021    // a clone of a ClassType that knows about the alternatives of a union type.
1022    public static class UnionClassType extends ClassType implements UnionType {
1023        final List<? extends Type> alternatives_field;
1024
1025        public UnionClassType(ClassType ct, List<? extends Type> alternatives) {
1026            // Presently no way to refer to this type directly, so we
1027            // cannot put annotations directly on it.
1028            super(ct.outer_field, ct.typarams_field, ct.tsym, noAnnotations);
1029            allparams_field = ct.allparams_field;
1030            supertype_field = ct.supertype_field;
1031            interfaces_field = ct.interfaces_field;
1032            all_interfaces_field = ct.interfaces_field;
1033            alternatives_field = alternatives;
1034        }
1035
1036        public Type getLub() {
1037            return tsym.type;
1038        }
1039
1040        public java.util.List<? extends TypeMirror> getAlternatives() {
1041            return Collections.unmodifiableList(alternatives_field);
1042        }
1043
1044        @Override
1045        public TypeKind getKind() {
1046            return TypeKind.UNION;
1047        }
1048
1049        @Override
1050        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1051            return v.visitUnion(this, p);
1052        }
1053
1054        public Iterable<? extends Type> getAlternativeTypes() {
1055            return alternatives_field;
1056        }
1057    }
1058
1059    // a clone of a ClassType that knows about the bounds of an intersection type.
1060    public static class IntersectionClassType extends ClassType implements IntersectionType {
1061
1062        public boolean allInterfaces;
1063
1064        public IntersectionClassType(List<Type> bounds, ClassSymbol csym, boolean allInterfaces) {
1065            // Presently no way to refer to this type directly, so we
1066            // cannot put annotations directly on it.
1067            super(Type.noType, List.<Type>nil(), csym, noAnnotations);
1068            this.allInterfaces = allInterfaces;
1069            Assert.check((csym.flags() & COMPOUND) != 0);
1070            supertype_field = bounds.head;
1071            interfaces_field = bounds.tail;
1072            Assert.check(supertype_field.tsym.completer != null ||
1073                    !supertype_field.isInterface(), supertype_field);
1074        }
1075
1076        public java.util.List<? extends TypeMirror> getBounds() {
1077            return Collections.unmodifiableList(getExplicitComponents());
1078        }
1079
1080        public List<Type> getComponents() {
1081            return interfaces_field.prepend(supertype_field);
1082        }
1083
1084        public List<Type> getExplicitComponents() {
1085            return allInterfaces ?
1086                    interfaces_field :
1087                    getComponents();
1088        }
1089
1090        @Override
1091        public TypeKind getKind() {
1092            return TypeKind.INTERSECTION;
1093        }
1094
1095        @Override
1096        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1097            return v.visitIntersection(this, p);
1098        }
1099    }
1100
1101    public static class ArrayType extends Type
1102            implements javax.lang.model.type.ArrayType {
1103
1104        public Type elemtype;
1105
1106        public ArrayType(Type elemtype, TypeSymbol arrayClass) {
1107            this(elemtype, arrayClass, noAnnotations);
1108        }
1109
1110        public ArrayType(Type elemtype, TypeSymbol arrayClass,
1111                         List<Attribute.TypeCompound> annos) {
1112            super(arrayClass, annos);
1113            this.elemtype = elemtype;
1114        }
1115
1116        @Override
1117        public ArrayType annotatedType(List<Attribute.TypeCompound> annos) {
1118            return new ArrayType(elemtype, tsym, annos);
1119        }
1120
1121        @Override
1122        public TypeTag getTag() {
1123            return ARRAY;
1124        }
1125
1126        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1127            return v.visitArrayType(this, s);
1128        }
1129
1130        public String toString() {
1131            StringBuilder sb = new StringBuilder();
1132            sb.append(elemtype);
1133            appendAnnotationsString(sb, true);
1134            sb.append("[]");
1135            return sb.toString();
1136        }
1137
1138        public boolean equals(Object obj) {
1139            return
1140                this == obj ||
1141                (obj instanceof ArrayType &&
1142                 this.elemtype.equals(((ArrayType)obj).elemtype));
1143        }
1144
1145        public int hashCode() {
1146            return (ARRAY.ordinal() << 5) + elemtype.hashCode();
1147        }
1148
1149        public boolean isVarargs() {
1150            return false;
1151        }
1152
1153        public List<Type> allparams() { return elemtype.allparams(); }
1154
1155        public boolean isErroneous() {
1156            return elemtype.isErroneous();
1157        }
1158
1159        public boolean isParameterized() {
1160            return elemtype.isParameterized();
1161        }
1162
1163        @Override
1164        public boolean isReference() {
1165            return true;
1166        }
1167
1168        @Override
1169        public boolean isNullOrReference() {
1170            return true;
1171        }
1172
1173        public boolean isRaw() {
1174            return elemtype.isRaw();
1175        }
1176
1177        public ArrayType makeVarargs() {
1178            return new ArrayType(elemtype, tsym, annos) {
1179                @Override
1180                public boolean isVarargs() {
1181                    return true;
1182                }
1183            };
1184        }
1185
1186        public Type map(Mapping f) {
1187            Type elemtype1 = f.apply(elemtype);
1188            if (elemtype1 == elemtype) return this;
1189            else return new ArrayType(elemtype1, tsym, annos);
1190        }
1191
1192        public boolean contains(Type elem) {
1193            return elem == this || elemtype.contains(elem);
1194        }
1195
1196        public void complete() {
1197            elemtype.complete();
1198        }
1199
1200        public Type getComponentType() {
1201            return elemtype;
1202        }
1203
1204        public TypeKind getKind() {
1205            return TypeKind.ARRAY;
1206        }
1207
1208        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1209            return v.visitArray(this, p);
1210        }
1211    }
1212
1213    public static class MethodType extends Type implements ExecutableType {
1214
1215        public List<Type> argtypes;
1216        public Type restype;
1217        public List<Type> thrown;
1218
1219        /** The type annotations on the method receiver.
1220         */
1221        public Type recvtype;
1222
1223        public MethodType(List<Type> argtypes,
1224                          Type restype,
1225                          List<Type> thrown,
1226                          TypeSymbol methodClass) {
1227            // Presently no way to refer to a method type directly, so
1228            // we cannot put type annotations on it.
1229            super(methodClass, noAnnotations);
1230            this.argtypes = argtypes;
1231            this.restype = restype;
1232            this.thrown = thrown;
1233        }
1234
1235        @Override
1236        public MethodType annotatedType(List<Attribute.TypeCompound> annos) {
1237            throw new AssertionError("Cannot annotate a method type");
1238        }
1239
1240        @Override
1241        public TypeTag getTag() {
1242            return METHOD;
1243        }
1244
1245        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1246            return v.visitMethodType(this, s);
1247        }
1248
1249        /** The Java source which this type represents.
1250         *
1251         *  XXX 06/09/99 iris This isn't correct Java syntax, but it probably
1252         *  should be.
1253         */
1254        public String toString() {
1255            StringBuilder sb = new StringBuilder();
1256            appendAnnotationsString(sb);
1257            sb.append('(');
1258            sb.append(argtypes);
1259            sb.append(')');
1260            sb.append(restype);
1261            return sb.toString();
1262        }
1263
1264        public List<Type>        getParameterTypes() { return argtypes; }
1265        public Type              getReturnType()     { return restype; }
1266        public Type              getReceiverType()   { return recvtype; }
1267        public List<Type>        getThrownTypes()    { return thrown; }
1268
1269        public boolean isErroneous() {
1270            return
1271                isErroneous(argtypes) ||
1272                restype != null && restype.isErroneous();
1273        }
1274
1275        public Type map(Mapping f) {
1276            List<Type> argtypes1 = map(argtypes, f);
1277            Type restype1 = f.apply(restype);
1278            List<Type> thrown1 = map(thrown, f);
1279            if (argtypes1 == argtypes &&
1280                restype1 == restype &&
1281                thrown1 == thrown) return this;
1282            else return new MethodType(argtypes1, restype1, thrown1, tsym);
1283        }
1284
1285        public boolean contains(Type elem) {
1286            return elem == this || contains(argtypes, elem) || restype.contains(elem) || contains(thrown, elem);
1287        }
1288
1289        public MethodType asMethodType() { return this; }
1290
1291        public void complete() {
1292            for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail)
1293                l.head.complete();
1294            restype.complete();
1295            recvtype.complete();
1296            for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1297                l.head.complete();
1298        }
1299
1300        public List<TypeVar> getTypeVariables() {
1301            return List.nil();
1302        }
1303
1304        public TypeSymbol asElement() {
1305            return null;
1306        }
1307
1308        public TypeKind getKind() {
1309            return TypeKind.EXECUTABLE;
1310        }
1311
1312        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1313            return v.visitExecutable(this, p);
1314        }
1315    }
1316
1317    public static class PackageType extends Type implements NoType {
1318
1319        PackageType(TypeSymbol tsym) {
1320            // Package types cannot be annotated
1321            super(tsym, noAnnotations);
1322        }
1323
1324        @Override
1325        public PackageType annotatedType(List<Attribute.TypeCompound> annos) {
1326            throw new AssertionError("Cannot annotate a package type");
1327        }
1328
1329        @Override
1330        public TypeTag getTag() {
1331            return PACKAGE;
1332        }
1333
1334        @Override
1335        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1336            return v.visitPackageType(this, s);
1337        }
1338
1339        public String toString() {
1340            return tsym.getQualifiedName().toString();
1341        }
1342
1343        public TypeKind getKind() {
1344            return TypeKind.PACKAGE;
1345        }
1346
1347        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1348            return v.visitNoType(this, p);
1349        }
1350    }
1351
1352    public static class TypeVar extends Type implements TypeVariable {
1353
1354        /** The upper bound of this type variable; set from outside.
1355         *  Must be nonempty once it is set.
1356         *  For a bound, `bound' is the bound type itself.
1357         *  Multiple bounds are expressed as a single class type which has the
1358         *  individual bounds as superclass, respectively interfaces.
1359         *  The class type then has as `tsym' a compiler generated class `c',
1360         *  which has a flag COMPOUND and whose owner is the type variable
1361         *  itself. Furthermore, the erasure_field of the class
1362         *  points to the first class or interface bound.
1363         */
1364        public Type bound = null;
1365
1366        /** The lower bound of this type variable.
1367         *  TypeVars don't normally have a lower bound, so it is normally set
1368         *  to syms.botType.
1369         *  Subtypes, such as CapturedType, may provide a different value.
1370         */
1371        public Type lower;
1372
1373        public TypeVar(Name name, Symbol owner, Type lower) {
1374            this(name, owner, lower, noAnnotations);
1375        }
1376
1377        public TypeVar(Name name, Symbol owner, Type lower,
1378                       List<Attribute.TypeCompound> annos) {
1379            super(null, annos);
1380            tsym = new TypeVariableSymbol(0, name, this, owner);
1381            this.lower = lower;
1382        }
1383
1384        public TypeVar(TypeSymbol tsym, Type bound, Type lower,
1385                       List<Attribute.TypeCompound> annos) {
1386            super(tsym, annos);
1387            this.bound = bound;
1388            this.lower = lower;
1389        }
1390
1391        @Override
1392        public TypeVar annotatedType(List<Attribute.TypeCompound> annos) {
1393            return new TypeVar(tsym, bound, lower, annos);
1394        }
1395
1396        @Override
1397        public TypeTag getTag() {
1398            return TYPEVAR;
1399        }
1400
1401        @Override
1402        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1403            return v.visitTypeVar(this, s);
1404        }
1405
1406        @Override
1407        public Type getUpperBound() {
1408            if ((bound == null || bound.hasTag(NONE)) && this != tsym.type) {
1409                bound = tsym.type.getUpperBound();
1410            }
1411            return bound;
1412        }
1413
1414        int rank_field = -1;
1415
1416        @Override
1417        public Type getLowerBound() {
1418            return lower;
1419        }
1420
1421        public TypeKind getKind() {
1422            return TypeKind.TYPEVAR;
1423        }
1424
1425        public boolean isCaptured() {
1426            return false;
1427        }
1428
1429        @Override
1430        public boolean isReference() {
1431            return true;
1432        }
1433
1434        @Override
1435        public boolean isNullOrReference() {
1436            return true;
1437        }
1438
1439        @Override
1440        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1441            return v.visitTypeVariable(this, p);
1442        }
1443    }
1444
1445    /** A captured type variable comes from wildcards which can have
1446     *  both upper and lower bound.  CapturedType extends TypeVar with
1447     *  a lower bound.
1448     */
1449    public static class CapturedType extends TypeVar {
1450
1451        public WildcardType wildcard;
1452
1453        public CapturedType(Name name,
1454                            Symbol owner,
1455                            Type upper,
1456                            Type lower,
1457                            WildcardType wildcard,
1458                            List<Attribute.TypeCompound> annos) {
1459            super(name, owner, lower, annos);
1460            this.lower = Assert.checkNonNull(lower);
1461            this.bound = upper;
1462            this.wildcard = wildcard;
1463        }
1464
1465        public CapturedType(TypeSymbol tsym,
1466                            Type bound,
1467                            Type upper,
1468                            Type lower,
1469                            WildcardType wildcard,
1470                            List<Attribute.TypeCompound> annos) {
1471            super(tsym, bound, lower, annos);
1472            this.wildcard = wildcard;
1473        }
1474
1475        @Override
1476        public CapturedType annotatedType(List<Attribute.TypeCompound> annos) {
1477            return new CapturedType(tsym, bound, bound, lower, wildcard, annos);
1478        }
1479
1480        @Override
1481        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1482            return v.visitCapturedType(this, s);
1483        }
1484
1485        @Override
1486        public boolean isCaptured() {
1487            return true;
1488        }
1489
1490        @Override
1491        public String toString() {
1492            StringBuilder sb = new StringBuilder();
1493            appendAnnotationsString(sb);
1494            sb.append("capture#");
1495            sb.append((hashCode() & 0xFFFFFFFFL) % Printer.PRIME);
1496            sb.append(" of ");
1497            sb.append(wildcard);
1498            return sb.toString();
1499        }
1500    }
1501
1502    public static abstract class DelegatedType extends Type {
1503        public Type qtype;
1504        public TypeTag tag;
1505        public DelegatedType(TypeTag tag, Type qtype,
1506                             List<Attribute.TypeCompound> annos) {
1507            super(qtype.tsym, annos);
1508            this.tag = tag;
1509            this.qtype = qtype;
1510        }
1511        public TypeTag getTag() { return tag; }
1512        public String toString() { return qtype.toString(); }
1513        public List<Type> getTypeArguments() { return qtype.getTypeArguments(); }
1514        public Type getEnclosingType() { return qtype.getEnclosingType(); }
1515        public List<Type> getParameterTypes() { return qtype.getParameterTypes(); }
1516        public Type getReturnType() { return qtype.getReturnType(); }
1517        public Type getReceiverType() { return qtype.getReceiverType(); }
1518        public List<Type> getThrownTypes() { return qtype.getThrownTypes(); }
1519        public List<Type> allparams() { return qtype.allparams(); }
1520        public Type getUpperBound() { return qtype.getUpperBound(); }
1521        public boolean isErroneous() { return qtype.isErroneous(); }
1522    }
1523
1524    /**
1525     * The type of a generic method type. It consists of a method type and
1526     * a list of method type-parameters that are used within the method
1527     * type.
1528     */
1529    public static class ForAll extends DelegatedType implements ExecutableType {
1530        public List<Type> tvars;
1531
1532        public ForAll(List<Type> tvars, Type qtype) {
1533            super(FORALL, (MethodType)qtype, noAnnotations);
1534            this.tvars = tvars;
1535        }
1536
1537        @Override
1538        public ForAll annotatedType(List<Attribute.TypeCompound> annos) {
1539            throw new AssertionError("Cannot annotate forall type");
1540        }
1541
1542        @Override
1543        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1544            return v.visitForAll(this, s);
1545        }
1546
1547        public String toString() {
1548            StringBuilder sb = new StringBuilder();
1549            appendAnnotationsString(sb);
1550            sb.append('<');
1551            sb.append(tvars);
1552            sb.append('>');
1553            sb.append(qtype);
1554            return sb.toString();
1555        }
1556
1557        public List<Type> getTypeArguments()   { return tvars; }
1558
1559        public boolean isErroneous()  {
1560            return qtype.isErroneous();
1561        }
1562
1563        public Type map(Mapping f) {
1564            return f.apply(qtype);
1565        }
1566
1567        public boolean contains(Type elem) {
1568            return qtype.contains(elem);
1569        }
1570
1571        public MethodType asMethodType() {
1572            return (MethodType)qtype;
1573        }
1574
1575        public void complete() {
1576            for (List<Type> l = tvars; l.nonEmpty(); l = l.tail) {
1577                ((TypeVar)l.head).bound.complete();
1578            }
1579            qtype.complete();
1580        }
1581
1582        public List<TypeVar> getTypeVariables() {
1583            return List.convert(TypeVar.class, getTypeArguments());
1584        }
1585
1586        public TypeKind getKind() {
1587            return TypeKind.EXECUTABLE;
1588        }
1589
1590        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1591            return v.visitExecutable(this, p);
1592        }
1593    }
1594
1595    /** A class for inference variables, for use during method/diamond type
1596     *  inference. An inference variable has upper/lower bounds and a set
1597     *  of equality constraints. Such bounds are set during subtyping, type-containment,
1598     *  type-equality checks, when the types being tested contain inference variables.
1599     *  A change listener can be attached to an inference variable, to receive notifications
1600     *  whenever the bounds of an inference variable change.
1601     */
1602    public static class UndetVar extends DelegatedType {
1603
1604        /** Inference variable change listener. The listener method is called
1605         *  whenever a change to the inference variable's bounds occurs
1606         */
1607        public interface UndetVarListener {
1608            /** called when some inference variable bounds (of given kinds ibs) change */
1609            void varChanged(UndetVar uv, Set<InferenceBound> ibs);
1610        }
1611
1612        /**
1613         * Inference variable bound kinds
1614         */
1615        public enum InferenceBound {
1616            /** upper bounds */
1617            UPPER {
1618                public InferenceBound complement() { return LOWER; }
1619            },
1620            /** lower bounds */
1621            LOWER {
1622                public InferenceBound complement() { return UPPER; }
1623            },
1624            /** equality constraints */
1625            EQ {
1626                public InferenceBound complement() { return EQ; }
1627            };
1628
1629            public abstract InferenceBound complement();
1630        }
1631
1632        /** inference variable bounds */
1633        protected Map<InferenceBound, List<Type>> bounds;
1634
1635        /** inference variable's inferred type (set from Infer.java) */
1636        public Type inst = null;
1637
1638        /** number of declared (upper) bounds */
1639        public int declaredCount;
1640
1641        /** inference variable's change listener */
1642        public UndetVarListener listener = null;
1643
1644        @Override
1645        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1646            return v.visitUndetVar(this, s);
1647        }
1648
1649        public UndetVar(TypeVar origin, Types types) {
1650            // This is a synthesized internal type, so we cannot annotate it.
1651            super(UNDETVAR, origin, noAnnotations);
1652            bounds = new EnumMap<>(InferenceBound.class);
1653            List<Type> declaredBounds = types.getBounds(origin);
1654            declaredCount = declaredBounds.length();
1655            bounds.put(InferenceBound.UPPER, declaredBounds);
1656            bounds.put(InferenceBound.LOWER, List.<Type>nil());
1657            bounds.put(InferenceBound.EQ, List.<Type>nil());
1658        }
1659
1660        public String toString() {
1661            StringBuilder sb = new StringBuilder();
1662            appendAnnotationsString(sb);
1663            if (inst == null) {
1664                sb.append(qtype);
1665                sb.append('?');
1666            } else {
1667                sb.append(inst);
1668            }
1669            return sb.toString();
1670        }
1671
1672        public String debugString() {
1673            String result = "inference var = " + qtype + "\n";
1674            if (inst != null) {
1675                result += "inst = " + inst + '\n';
1676            }
1677            for (InferenceBound bound: InferenceBound.values()) {
1678                List<Type> aboundList = bounds.get(bound);
1679                if (aboundList.size() > 0) {
1680                    result += bound + " = " + aboundList + '\n';
1681                }
1682            }
1683            return result;
1684        }
1685
1686        @Override
1687        public UndetVar annotatedType(List<Attribute.TypeCompound> annos) {
1688            throw new AssertionError("Cannot annotate an UndetVar type");
1689        }
1690
1691        @Override
1692        public boolean isPartial() {
1693            return true;
1694        }
1695
1696        @Override
1697        public Type baseType() {
1698            return (inst == null) ? this : inst.baseType();
1699        }
1700
1701        /** get all bounds of a given kind */
1702        public List<Type> getBounds(InferenceBound... ibs) {
1703            ListBuffer<Type> buf = new ListBuffer<>();
1704            for (InferenceBound ib : ibs) {
1705                buf.appendList(bounds.get(ib));
1706            }
1707            return buf.toList();
1708        }
1709
1710        /** get the list of declared (upper) bounds */
1711        public List<Type> getDeclaredBounds() {
1712            ListBuffer<Type> buf = new ListBuffer<>();
1713            int count = 0;
1714            for (Type b : getBounds(InferenceBound.UPPER)) {
1715                if (count++ == declaredCount) break;
1716                buf.append(b);
1717            }
1718            return buf.toList();
1719        }
1720
1721        /** internal method used to override an undetvar bounds */
1722        public void setBounds(InferenceBound ib, List<Type> newBounds) {
1723            bounds.put(ib, newBounds);
1724        }
1725
1726        /** add a bound of a given kind - this might trigger listener notification */
1727        public final void addBound(InferenceBound ib, Type bound, Types types) {
1728            addBound(ib, bound, types, false);
1729        }
1730
1731        protected void addBound(InferenceBound ib, Type bound, Types types, boolean update) {
1732            Type bound2 = toTypeVarMap.apply(bound).baseType();
1733            List<Type> prevBounds = bounds.get(ib);
1734            for (Type b : prevBounds) {
1735                //check for redundancy - use strict version of isSameType on tvars
1736                //(as the standard version will lead to false positives w.r.t. clones ivars)
1737                if (types.isSameType(b, bound2, true) || bound == qtype) return;
1738            }
1739            bounds.put(ib, prevBounds.prepend(bound2));
1740            notifyChange(EnumSet.of(ib));
1741        }
1742        //where
1743            Type.Mapping toTypeVarMap = new Mapping("toTypeVarMap") {
1744                @Override
1745                public Type apply(Type t) {
1746                    if (t.hasTag(UNDETVAR)) {
1747                        UndetVar uv = (UndetVar)t;
1748                        return uv.inst != null ? uv.inst : uv.qtype;
1749                    } else {
1750                        return t.map(this);
1751                    }
1752                }
1753            };
1754
1755        /** replace types in all bounds - this might trigger listener notification */
1756        public void substBounds(List<Type> from, List<Type> to, Types types) {
1757            List<Type> instVars = from.diff(to);
1758            //if set of instantiated ivars is empty, there's nothing to do!
1759            if (instVars.isEmpty()) return;
1760            final EnumSet<InferenceBound> boundsChanged = EnumSet.noneOf(InferenceBound.class);
1761            UndetVarListener prevListener = listener;
1762            try {
1763                //setup new listener for keeping track of changed bounds
1764                listener = new UndetVarListener() {
1765                    public void varChanged(UndetVar uv, Set<InferenceBound> ibs) {
1766                        boundsChanged.addAll(ibs);
1767                    }
1768                };
1769                for (Map.Entry<InferenceBound, List<Type>> _entry : bounds.entrySet()) {
1770                    InferenceBound ib = _entry.getKey();
1771                    List<Type> prevBounds = _entry.getValue();
1772                    ListBuffer<Type> newBounds = new ListBuffer<>();
1773                    ListBuffer<Type> deps = new ListBuffer<>();
1774                    //step 1 - re-add bounds that are not dependent on ivars
1775                    for (Type t : prevBounds) {
1776                        if (!t.containsAny(instVars)) {
1777                            newBounds.append(t);
1778                        } else {
1779                            deps.append(t);
1780                        }
1781                    }
1782                    //step 2 - replace bounds
1783                    bounds.put(ib, newBounds.toList());
1784                    //step 3 - for each dependency, add new replaced bound
1785                    for (Type dep : deps) {
1786                        addBound(ib, types.subst(dep, from, to), types, true);
1787                    }
1788                }
1789            } finally {
1790                listener = prevListener;
1791                if (!boundsChanged.isEmpty()) {
1792                    notifyChange(boundsChanged);
1793                }
1794            }
1795        }
1796
1797        private void notifyChange(EnumSet<InferenceBound> ibs) {
1798            if (listener != null) {
1799                listener.varChanged(this, ibs);
1800            }
1801        }
1802
1803        public boolean isCaptured() {
1804            return false;
1805        }
1806    }
1807
1808    /**
1809     * This class is used to represent synthetic captured inference variables
1810     * that can be generated during nested generic method calls. The only difference
1811     * between these inference variables and ordinary ones is that captured inference
1812     * variables cannot get new bounds through incorporation.
1813     */
1814    public static class CapturedUndetVar extends UndetVar {
1815
1816        public CapturedUndetVar(CapturedType origin, Types types) {
1817            super(origin, types);
1818            if (!origin.lower.hasTag(BOT)) {
1819                bounds.put(InferenceBound.LOWER, List.of(origin.lower));
1820            }
1821        }
1822
1823        @Override
1824        public void addBound(InferenceBound ib, Type bound, Types types, boolean update) {
1825            if (update) {
1826                //only change bounds if request comes from substBounds
1827                super.addBound(ib, bound, types, update);
1828            }
1829            else if (bound.hasTag(UNDETVAR) && !((UndetVar) bound).isCaptured()) {
1830                ((UndetVar) bound).addBound(ib.complement(), this, types, false);
1831            }
1832        }
1833
1834        @Override
1835        public boolean isCaptured() {
1836            return true;
1837        }
1838    }
1839
1840    /** Represents NONE.
1841     */
1842    public static class JCNoType extends Type implements NoType {
1843        public JCNoType() {
1844            // Need to use List.nil(), because JCNoType constructor
1845            // gets called in static initializers in Type, where
1846            // noAnnotations is also defined.
1847            super(null, List.<Attribute.TypeCompound>nil());
1848        }
1849
1850        @Override
1851        public JCNoType annotatedType(List<Attribute.TypeCompound> annos) {
1852            throw new AssertionError("Cannot annotate JCNoType");
1853        }
1854
1855        @Override
1856        public TypeTag getTag() {
1857            return NONE;
1858        }
1859
1860        @Override
1861        public TypeKind getKind() {
1862            return TypeKind.NONE;
1863        }
1864
1865        @Override
1866        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1867            return v.visitNoType(this, p);
1868        }
1869
1870        @Override
1871        public boolean isCompound() { return false; }
1872    }
1873
1874    /** Represents VOID.
1875     */
1876    public static class JCVoidType extends Type implements NoType {
1877
1878        public JCVoidType() {
1879            // Void cannot be annotated
1880            super(null, noAnnotations);
1881        }
1882
1883        @Override
1884        public JCVoidType annotatedType(List<Attribute.TypeCompound> annos) {
1885            throw new AssertionError("Cannot annotate void type");
1886        }
1887
1888        @Override
1889        public TypeTag getTag() {
1890            return VOID;
1891        }
1892
1893        @Override
1894        public TypeKind getKind() {
1895            return TypeKind.VOID;
1896        }
1897
1898        @Override
1899        public boolean isCompound() { return false; }
1900
1901        @Override
1902        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1903            return v.visitNoType(this, p);
1904        }
1905
1906        @Override
1907        public boolean isPrimitiveOrVoid() {
1908            return true;
1909        }
1910    }
1911
1912    static class BottomType extends Type implements NullType {
1913        public BottomType() {
1914            // Bottom is a synthesized internal type, so it cannot be annotated
1915            super(null, noAnnotations);
1916        }
1917
1918        @Override
1919        public BottomType annotatedType(List<Attribute.TypeCompound> annos) {
1920            throw new AssertionError("Cannot annotate bottom type");
1921        }
1922
1923        @Override
1924        public TypeTag getTag() {
1925            return BOT;
1926        }
1927
1928        @Override
1929        public TypeKind getKind() {
1930            return TypeKind.NULL;
1931        }
1932
1933        @Override
1934        public boolean isCompound() { return false; }
1935
1936        @Override
1937        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1938            return v.visitNull(this, p);
1939        }
1940
1941        @Override
1942        public Type constType(Object value) {
1943            return this;
1944        }
1945
1946        @Override
1947        public String stringValue() {
1948            return "null";
1949        }
1950
1951        @Override
1952        public boolean isNullOrReference() {
1953            return true;
1954        }
1955
1956    }
1957
1958    public static class ErrorType extends ClassType
1959            implements javax.lang.model.type.ErrorType {
1960
1961        private Type originalType = null;
1962
1963        public ErrorType(Type originalType, TypeSymbol tsym) {
1964            this(originalType, tsym, noAnnotations);
1965        }
1966
1967        public ErrorType(Type originalType, TypeSymbol tsym,
1968                         List<Attribute.TypeCompound> typeAnnotations) {
1969            super(noType, List.<Type>nil(), null, typeAnnotations);
1970            this.tsym = tsym;
1971            this.originalType = (originalType == null ? noType : originalType);
1972        }
1973
1974        public ErrorType(ClassSymbol c, Type originalType) {
1975            this(originalType, c);
1976            c.type = this;
1977            c.kind = ERR;
1978            c.members_field = new Scope.ErrorScope(c);
1979        }
1980
1981        @Override
1982        public ErrorType annotatedType(List<Attribute.TypeCompound> annos) {
1983            return new ErrorType(originalType, tsym, annos);
1984        }
1985
1986        @Override
1987        public TypeTag getTag() {
1988            return ERROR;
1989        }
1990
1991        @Override
1992        public boolean isPartial() {
1993            return true;
1994        }
1995
1996        @Override
1997        public boolean isReference() {
1998            return true;
1999        }
2000
2001        @Override
2002        public boolean isNullOrReference() {
2003            return true;
2004        }
2005
2006        public ErrorType(Name name, TypeSymbol container, Type originalType) {
2007            this(new ClassSymbol(PUBLIC|STATIC|ACYCLIC, name, null, container), originalType);
2008        }
2009
2010        @Override
2011        public <R,S> R accept(Type.Visitor<R,S> v, S s) {
2012            return v.visitErrorType(this, s);
2013        }
2014
2015        public Type constType(Object constValue) { return this; }
2016        public Type getEnclosingType()           { return this; }
2017        public Type getReturnType()              { return this; }
2018        public Type asSub(Symbol sym)            { return this; }
2019        public Type map(Mapping f)               { return this; }
2020
2021        public boolean isGenType(Type t)         { return true; }
2022        public boolean isErroneous()             { return true; }
2023        public boolean isCompound()              { return false; }
2024        public boolean isInterface()             { return false; }
2025
2026        public List<Type> allparams()            { return List.nil(); }
2027        public List<Type> getTypeArguments()     { return List.nil(); }
2028
2029        public TypeKind getKind() {
2030            return TypeKind.ERROR;
2031        }
2032
2033        public Type getOriginalType() {
2034            return originalType;
2035        }
2036
2037        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2038            return v.visitError(this, p);
2039        }
2040    }
2041
2042    public static class UnknownType extends Type {
2043
2044        public UnknownType() {
2045            // Unknown is a synthesized internal type, so it cannot be
2046            // annotated.
2047            super(null, noAnnotations);
2048        }
2049
2050        @Override
2051        public UnknownType annotatedType(List<Attribute.TypeCompound> annos) {
2052            throw new AssertionError("Cannot annotate unknown type");
2053        }
2054
2055        @Override
2056        public TypeTag getTag() {
2057            return UNKNOWN;
2058        }
2059
2060        @Override
2061        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2062            return v.visitUnknown(this, p);
2063        }
2064
2065        @Override
2066        public boolean isPartial() {
2067            return true;
2068        }
2069    }
2070
2071    /**
2072     * A visitor for types.  A visitor is used to implement operations
2073     * (or relations) on types.  Most common operations on types are
2074     * binary relations and this interface is designed for binary
2075     * relations, that is, operations of the form
2076     * Type&nbsp;&times;&nbsp;S&nbsp;&rarr;&nbsp;R.
2077     * <!-- In plain text: Type x S -> R -->
2078     *
2079     * @param <R> the return type of the operation implemented by this
2080     * visitor; use Void if no return type is needed.
2081     * @param <S> the type of the second argument (the first being the
2082     * type itself) of the operation implemented by this visitor; use
2083     * Void if a second argument is not needed.
2084     */
2085    public interface Visitor<R,S> {
2086        R visitClassType(ClassType t, S s);
2087        R visitWildcardType(WildcardType t, S s);
2088        R visitArrayType(ArrayType t, S s);
2089        R visitMethodType(MethodType t, S s);
2090        R visitPackageType(PackageType t, S s);
2091        R visitTypeVar(TypeVar t, S s);
2092        R visitCapturedType(CapturedType t, S s);
2093        R visitForAll(ForAll t, S s);
2094        R visitUndetVar(UndetVar t, S s);
2095        R visitErrorType(ErrorType t, S s);
2096        R visitType(Type t, S s);
2097    }
2098}
2099