Types.java revision 2838:218d589184d3
1/*
2 * Copyright (c) 2003, 2015, 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.ref.SoftReference;
29import java.util.HashSet;
30import java.util.HashMap;
31import java.util.Locale;
32import java.util.Map;
33import java.util.Set;
34import java.util.WeakHashMap;
35
36import javax.tools.JavaFileObject;
37
38import com.sun.tools.javac.code.Attribute.RetentionPolicy;
39import com.sun.tools.javac.code.Lint.LintCategory;
40import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
41import com.sun.tools.javac.comp.AttrContext;
42import com.sun.tools.javac.comp.Check;
43import com.sun.tools.javac.comp.Enter;
44import com.sun.tools.javac.comp.Env;
45import com.sun.tools.javac.util.*;
46
47import static com.sun.tools.javac.code.BoundKind.*;
48import static com.sun.tools.javac.code.Flags.*;
49import static com.sun.tools.javac.code.Kinds.Kind.*;
50import static com.sun.tools.javac.code.Scope.*;
51import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
52import static com.sun.tools.javac.code.Symbol.*;
53import static com.sun.tools.javac.code.Type.*;
54import static com.sun.tools.javac.code.TypeTag.*;
55import static com.sun.tools.javac.jvm.ClassFile.externalize;
56
57/**
58 * Utility class containing various operations on types.
59 *
60 * <p>Unless other names are more illustrative, the following naming
61 * conventions should be observed in this file:
62 *
63 * <dl>
64 * <dt>t</dt>
65 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
66 * <dt>s</dt>
67 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
68 * <dt>ts</dt>
69 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
70 * <dt>ss</dt>
71 * <dd>A second list of types should be named ss.</dd>
72 * </dl>
73 *
74 * <p><b>This is NOT part of any supported API.
75 * If you write code that depends on this, you do so at your own risk.
76 * This code and its internal interfaces are subject to change or
77 * deletion without notice.</b>
78 */
79public class Types {
80    protected static final Context.Key<Types> typesKey = new Context.Key<>();
81
82    final Symtab syms;
83    final JavacMessages messages;
84    final Names names;
85    final boolean allowObjectToPrimitiveCast;
86    final boolean allowDefaultMethods;
87    final Check chk;
88    final Enter enter;
89    JCDiagnostic.Factory diags;
90    List<Warner> warnStack = List.nil();
91    final Name capturedName;
92    private final FunctionDescriptorLookupError functionDescriptorLookupError;
93
94    public final Warner noWarnings;
95
96    // <editor-fold defaultstate="collapsed" desc="Instantiating">
97    public static Types instance(Context context) {
98        Types instance = context.get(typesKey);
99        if (instance == null)
100            instance = new Types(context);
101        return instance;
102    }
103
104    protected Types(Context context) {
105        context.put(typesKey, this);
106        syms = Symtab.instance(context);
107        names = Names.instance(context);
108        Source source = Source.instance(context);
109        allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
110        allowDefaultMethods = source.allowDefaultMethods();
111        chk = Check.instance(context);
112        enter = Enter.instance(context);
113        capturedName = names.fromString("<captured wildcard>");
114        messages = JavacMessages.instance(context);
115        diags = JCDiagnostic.Factory.instance(context);
116        functionDescriptorLookupError = new FunctionDescriptorLookupError();
117        noWarnings = new Warner(null);
118    }
119    // </editor-fold>
120
121    // <editor-fold defaultstate="collapsed" desc="bounds">
122    /**
123     * Get a wildcard's upper bound, returning non-wildcards unchanged.
124     * @param t a type argument, either a wildcard or a type
125     */
126    public Type wildUpperBound(Type t) {
127        if (t.hasTag(WILDCARD)) {
128            WildcardType w = (WildcardType) t;
129            if (w.isSuperBound())
130                return w.bound == null ? syms.objectType : w.bound.bound;
131            else
132                return wildUpperBound(w.type);
133        }
134        else return t;
135    }
136
137    /**
138     * Get a capture variable's upper bound, returning other types unchanged.
139     * @param t a type
140     */
141    public Type cvarUpperBound(Type t) {
142        if (t.hasTag(TYPEVAR)) {
143            TypeVar v = (TypeVar) t;
144            return v.isCaptured() ? cvarUpperBound(v.bound) : v;
145        }
146        else return t;
147    }
148
149    /**
150     * Get a wildcard's lower bound, returning non-wildcards unchanged.
151     * @param t a type argument, either a wildcard or a type
152     */
153    public Type wildLowerBound(Type t) {
154        if (t.hasTag(WILDCARD)) {
155            WildcardType w = (WildcardType) t;
156            return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
157        }
158        else return t;
159    }
160
161    /**
162     * Get a capture variable's lower bound, returning other types unchanged.
163     * @param t a type
164     */
165    public Type cvarLowerBound(Type t) {
166        if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
167            return cvarLowerBound(t.getLowerBound());
168        }
169        else return t;
170    }
171
172    /**
173     * Recursively skip type-variables until a class/array type is found; capture conversion is then
174     * (optionally) applied to the resulting type. This is useful for i.e. computing a site that is
175     * suitable for a method lookup.
176     */
177    public Type skipTypeVars(Type site, boolean capture) {
178        while (site.hasTag(TYPEVAR)) {
179            site = site.getUpperBound();
180        }
181        return capture ? capture(site) : site;
182    }
183    // </editor-fold>
184
185    // <editor-fold defaultstate="collapsed" desc="isUnbounded">
186    /**
187     * Checks that all the arguments to a class are unbounded
188     * wildcards or something else that doesn't make any restrictions
189     * on the arguments. If a class isUnbounded, a raw super- or
190     * subclass can be cast to it without a warning.
191     * @param t a type
192     * @return true iff the given type is unbounded or raw
193     */
194    public boolean isUnbounded(Type t) {
195        return isUnbounded.visit(t);
196    }
197    // where
198        private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
199
200            public Boolean visitType(Type t, Void ignored) {
201                return true;
202            }
203
204            @Override
205            public Boolean visitClassType(ClassType t, Void ignored) {
206                List<Type> parms = t.tsym.type.allparams();
207                List<Type> args = t.allparams();
208                while (parms.nonEmpty()) {
209                    WildcardType unb = new WildcardType(syms.objectType,
210                                                        BoundKind.UNBOUND,
211                                                        syms.boundClass,
212                                                        (TypeVar)parms.head);
213                    if (!containsType(args.head, unb))
214                        return false;
215                    parms = parms.tail;
216                    args = args.tail;
217                }
218                return true;
219            }
220        };
221    // </editor-fold>
222
223    // <editor-fold defaultstate="collapsed" desc="asSub">
224    /**
225     * Return the least specific subtype of t that starts with symbol
226     * sym.  If none exists, return null.  The least specific subtype
227     * is determined as follows:
228     *
229     * <p>If there is exactly one parameterized instance of sym that is a
230     * subtype of t, that parameterized instance is returned.<br>
231     * Otherwise, if the plain type or raw type `sym' is a subtype of
232     * type t, the type `sym' itself is returned.  Otherwise, null is
233     * returned.
234     */
235    public Type asSub(Type t, Symbol sym) {
236        return asSub.visit(t, sym);
237    }
238    // where
239        private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
240
241            public Type visitType(Type t, Symbol sym) {
242                return null;
243            }
244
245            @Override
246            public Type visitClassType(ClassType t, Symbol sym) {
247                if (t.tsym == sym)
248                    return t;
249                Type base = asSuper(sym.type, t.tsym);
250                if (base == null)
251                    return null;
252                ListBuffer<Type> from = new ListBuffer<>();
253                ListBuffer<Type> to = new ListBuffer<>();
254                try {
255                    adapt(base, t, from, to);
256                } catch (AdaptFailure ex) {
257                    return null;
258                }
259                Type res = subst(sym.type, from.toList(), to.toList());
260                if (!isSubtype(res, t))
261                    return null;
262                ListBuffer<Type> openVars = new ListBuffer<>();
263                for (List<Type> l = sym.type.allparams();
264                     l.nonEmpty(); l = l.tail)
265                    if (res.contains(l.head) && !t.contains(l.head))
266                        openVars.append(l.head);
267                if (openVars.nonEmpty()) {
268                    if (t.isRaw()) {
269                        // The subtype of a raw type is raw
270                        res = erasure(res);
271                    } else {
272                        // Unbound type arguments default to ?
273                        List<Type> opens = openVars.toList();
274                        ListBuffer<Type> qs = new ListBuffer<>();
275                        for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
276                            qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND,
277                                                       syms.boundClass, (TypeVar) iter.head));
278                        }
279                        res = subst(res, opens, qs.toList());
280                    }
281                }
282                return res;
283            }
284
285            @Override
286            public Type visitErrorType(ErrorType t, Symbol sym) {
287                return t;
288            }
289        };
290    // </editor-fold>
291
292    // <editor-fold defaultstate="collapsed" desc="isConvertible">
293    /**
294     * Is t a subtype of or convertible via boxing/unboxing
295     * conversion to s?
296     */
297    public boolean isConvertible(Type t, Type s, Warner warn) {
298        if (t.hasTag(ERROR)) {
299            return true;
300        }
301        boolean tPrimitive = t.isPrimitive();
302        boolean sPrimitive = s.isPrimitive();
303        if (tPrimitive == sPrimitive) {
304            return isSubtypeUnchecked(t, s, warn);
305        }
306        return tPrimitive
307            ? isSubtype(boxedClass(t).type, s)
308            : isSubtype(unboxedType(t), s);
309    }
310
311    /**
312     * Is t a subtype of or convertible via boxing/unboxing
313     * conversions to s?
314     */
315    public boolean isConvertible(Type t, Type s) {
316        return isConvertible(t, s, noWarnings);
317    }
318    // </editor-fold>
319
320    // <editor-fold defaultstate="collapsed" desc="findSam">
321
322    /**
323     * Exception used to report a function descriptor lookup failure. The exception
324     * wraps a diagnostic that can be used to generate more details error
325     * messages.
326     */
327    public static class FunctionDescriptorLookupError extends RuntimeException {
328        private static final long serialVersionUID = 0;
329
330        JCDiagnostic diagnostic;
331
332        FunctionDescriptorLookupError() {
333            this.diagnostic = null;
334        }
335
336        FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
337            this.diagnostic = diag;
338            return this;
339        }
340
341        public JCDiagnostic getDiagnostic() {
342            return diagnostic;
343        }
344    }
345
346    /**
347     * A cache that keeps track of function descriptors associated with given
348     * functional interfaces.
349     */
350    class DescriptorCache {
351
352        private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>();
353
354        class FunctionDescriptor {
355            Symbol descSym;
356
357            FunctionDescriptor(Symbol descSym) {
358                this.descSym = descSym;
359            }
360
361            public Symbol getSymbol() {
362                return descSym;
363            }
364
365            public Type getType(Type site) {
366                site = removeWildcards(site);
367                if (!chk.checkValidGenericType(site)) {
368                    //if the inferred functional interface type is not well-formed,
369                    //or if it's not a subtype of the original target, issue an error
370                    throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
371                }
372                return memberType(site, descSym);
373            }
374        }
375
376        class Entry {
377            final FunctionDescriptor cachedDescRes;
378            final int prevMark;
379
380            public Entry(FunctionDescriptor cachedDescRes,
381                    int prevMark) {
382                this.cachedDescRes = cachedDescRes;
383                this.prevMark = prevMark;
384            }
385
386            boolean matches(int mark) {
387                return  this.prevMark == mark;
388            }
389        }
390
391        FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
392            Entry e = _map.get(origin);
393            CompoundScope members = membersClosure(origin.type, false);
394            if (e == null ||
395                    !e.matches(members.getMark())) {
396                FunctionDescriptor descRes = findDescriptorInternal(origin, members);
397                _map.put(origin, new Entry(descRes, members.getMark()));
398                return descRes;
399            }
400            else {
401                return e.cachedDescRes;
402            }
403        }
404
405        /**
406         * Compute the function descriptor associated with a given functional interface
407         */
408        public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
409                CompoundScope membersCache) throws FunctionDescriptorLookupError {
410            if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
411                //t must be an interface
412                throw failure("not.a.functional.intf", origin);
413            }
414
415            final ListBuffer<Symbol> abstracts = new ListBuffer<>();
416            for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) {
417                Type mtype = memberType(origin.type, sym);
418                if (abstracts.isEmpty() ||
419                        (sym.name == abstracts.first().name &&
420                        overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
421                    abstracts.append(sym);
422                } else {
423                    //the target method(s) should be the only abstract members of t
424                    throw failure("not.a.functional.intf.1",  origin,
425                            diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
426                }
427            }
428            if (abstracts.isEmpty()) {
429                //t must define a suitable non-generic method
430                throw failure("not.a.functional.intf.1", origin,
431                            diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
432            } else if (abstracts.size() == 1) {
433                return new FunctionDescriptor(abstracts.first());
434            } else { // size > 1
435                FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
436                if (descRes == null) {
437                    //we can get here if the functional interface is ill-formed
438                    ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
439                    for (Symbol desc : abstracts) {
440                        String key = desc.type.getThrownTypes().nonEmpty() ?
441                                "descriptor.throws" : "descriptor";
442                        descriptors.append(diags.fragment(key, desc.name,
443                                desc.type.getParameterTypes(),
444                                desc.type.getReturnType(),
445                                desc.type.getThrownTypes()));
446                    }
447                    JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
448                            new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
449                            Kinds.kindName(origin), origin), descriptors.toList());
450                    throw failure(incompatibleDescriptors);
451                }
452                return descRes;
453            }
454        }
455
456        /**
457         * Compute a synthetic type for the target descriptor given a list
458         * of override-equivalent methods in the functional interface type.
459         * The resulting method type is a method type that is override-equivalent
460         * and return-type substitutable with each method in the original list.
461         */
462        private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
463            //pick argument types - simply take the signature that is a
464            //subsignature of all other signatures in the list (as per JLS 8.4.2)
465            List<Symbol> mostSpecific = List.nil();
466            outer: for (Symbol msym1 : methodSyms) {
467                Type mt1 = memberType(origin.type, msym1);
468                for (Symbol msym2 : methodSyms) {
469                    Type mt2 = memberType(origin.type, msym2);
470                    if (!isSubSignature(mt1, mt2)) {
471                        continue outer;
472                    }
473                }
474                mostSpecific = mostSpecific.prepend(msym1);
475            }
476            if (mostSpecific.isEmpty()) {
477                return null;
478            }
479
480
481            //pick return types - this is done in two phases: (i) first, the most
482            //specific return type is chosen using strict subtyping; if this fails,
483            //a second attempt is made using return type substitutability (see JLS 8.4.5)
484            boolean phase2 = false;
485            Symbol bestSoFar = null;
486            while (bestSoFar == null) {
487                outer: for (Symbol msym1 : mostSpecific) {
488                    Type mt1 = memberType(origin.type, msym1);
489                    for (Symbol msym2 : methodSyms) {
490                        Type mt2 = memberType(origin.type, msym2);
491                        if (phase2 ?
492                                !returnTypeSubstitutable(mt1, mt2) :
493                                !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
494                            continue outer;
495                        }
496                    }
497                    bestSoFar = msym1;
498                }
499                if (phase2) {
500                    break;
501                } else {
502                    phase2 = true;
503                }
504            }
505            if (bestSoFar == null) return null;
506
507            //merge thrown types - form the intersection of all the thrown types in
508            //all the signatures in the list
509            boolean toErase = !bestSoFar.type.hasTag(FORALL);
510            List<Type> thrown = null;
511            Type mt1 = memberType(origin.type, bestSoFar);
512            for (Symbol msym2 : methodSyms) {
513                Type mt2 = memberType(origin.type, msym2);
514                List<Type> thrown_mt2 = mt2.getThrownTypes();
515                if (toErase) {
516                    thrown_mt2 = erasure(thrown_mt2);
517                } else {
518                    /* If bestSoFar is generic then all the methods are generic.
519                     * The opposite is not true: a non generic method can override
520                     * a generic method (raw override) so it's safe to cast mt1 and
521                     * mt2 to ForAll.
522                     */
523                    ForAll fa1 = (ForAll)mt1;
524                    ForAll fa2 = (ForAll)mt2;
525                    thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
526                }
527                thrown = (thrown == null) ?
528                    thrown_mt2 :
529                    chk.intersect(thrown_mt2, thrown);
530            }
531
532            final List<Type> thrown1 = thrown;
533            return new FunctionDescriptor(bestSoFar) {
534                @Override
535                public Type getType(Type origin) {
536                    Type mt = memberType(origin, getSymbol());
537                    return createMethodTypeWithThrown(mt, thrown1);
538                }
539            };
540        }
541
542        boolean isSubtypeInternal(Type s, Type t) {
543            return (s.isPrimitive() && t.isPrimitive()) ?
544                    isSameType(t, s) :
545                    isSubtype(s, t);
546        }
547
548        FunctionDescriptorLookupError failure(String msg, Object... args) {
549            return failure(diags.fragment(msg, args));
550        }
551
552        FunctionDescriptorLookupError failure(JCDiagnostic diag) {
553            return functionDescriptorLookupError.setMessage(diag);
554        }
555    }
556
557    private DescriptorCache descCache = new DescriptorCache();
558
559    /**
560     * Find the method descriptor associated to this class symbol - if the
561     * symbol 'origin' is not a functional interface, an exception is thrown.
562     */
563    public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
564        return descCache.get(origin).getSymbol();
565    }
566
567    /**
568     * Find the type of the method descriptor associated to this class symbol -
569     * if the symbol 'origin' is not a functional interface, an exception is thrown.
570     */
571    public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
572        return descCache.get(origin.tsym).getType(origin);
573    }
574
575    /**
576     * Is given type a functional interface?
577     */
578    public boolean isFunctionalInterface(TypeSymbol tsym) {
579        try {
580            findDescriptorSymbol(tsym);
581            return true;
582        } catch (FunctionDescriptorLookupError ex) {
583            return false;
584        }
585    }
586
587    public boolean isFunctionalInterface(Type site) {
588        try {
589            findDescriptorType(site);
590            return true;
591        } catch (FunctionDescriptorLookupError ex) {
592            return false;
593        }
594    }
595
596    public Type removeWildcards(Type site) {
597        Type capturedSite = capture(site);
598        if (capturedSite != site) {
599            Type formalInterface = site.tsym.type;
600            ListBuffer<Type> typeargs = new ListBuffer<>();
601            List<Type> actualTypeargs = site.getTypeArguments();
602            List<Type> capturedTypeargs = capturedSite.getTypeArguments();
603            //simply replace the wildcards with its bound
604            for (Type t : formalInterface.getTypeArguments()) {
605                if (actualTypeargs.head.hasTag(WILDCARD)) {
606                    WildcardType wt = (WildcardType)actualTypeargs.head;
607                    Type bound;
608                    switch (wt.kind) {
609                        case EXTENDS:
610                        case UNBOUND:
611                            CapturedType capVar = (CapturedType)capturedTypeargs.head;
612                            //use declared bound if it doesn't depend on formal type-args
613                            bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
614                                    wt.type : capVar.bound;
615                            break;
616                        default:
617                            bound = wt.type;
618                    }
619                    typeargs.append(bound);
620                } else {
621                    typeargs.append(actualTypeargs.head);
622                }
623                actualTypeargs = actualTypeargs.tail;
624                capturedTypeargs = capturedTypeargs.tail;
625            }
626            return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
627        } else {
628            return site;
629        }
630    }
631
632    /**
633     * Create a symbol for a class that implements a given functional interface
634     * and overrides its functional descriptor. This routine is used for two
635     * main purposes: (i) checking well-formedness of a functional interface;
636     * (ii) perform functional interface bridge calculation.
637     */
638    public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
639        if (targets.isEmpty()) {
640            return null;
641        }
642        Symbol descSym = findDescriptorSymbol(targets.head.tsym);
643        Type descType = findDescriptorType(targets.head);
644        ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
645        csym.completer = null;
646        csym.members_field = WriteableScope.create(csym);
647        MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
648        csym.members_field.enter(instDescSym);
649        Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
650        ctype.supertype_field = syms.objectType;
651        ctype.interfaces_field = targets;
652        csym.type = ctype;
653        csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
654        return csym;
655    }
656
657    /**
658     * Find the minimal set of methods that are overridden by the functional
659     * descriptor in 'origin'. All returned methods are assumed to have different
660     * erased signatures.
661     */
662    public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
663        Assert.check(isFunctionalInterface(origin));
664        Symbol descSym = findDescriptorSymbol(origin);
665        CompoundScope members = membersClosure(origin.type, false);
666        ListBuffer<Symbol> overridden = new ListBuffer<>();
667        outer: for (Symbol m2 : members.getSymbolsByName(descSym.name, bridgeFilter)) {
668            if (m2 == descSym) continue;
669            else if (descSym.overrides(m2, origin, Types.this, false)) {
670                for (Symbol m3 : overridden) {
671                    if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
672                            (m3.overrides(m2, origin, Types.this, false) &&
673                            (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
674                            (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
675                        continue outer;
676                    }
677                }
678                overridden.add(m2);
679            }
680        }
681        return overridden.toList();
682    }
683    //where
684        private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
685            public boolean accepts(Symbol t) {
686                return t.kind == MTH &&
687                        t.name != names.init &&
688                        t.name != names.clinit &&
689                        (t.flags() & SYNTHETIC) == 0;
690            }
691        };
692        private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
693            //a symbol will be completed from a classfile if (a) symbol has
694            //an associated file object with CLASS kind and (b) the symbol has
695            //not been entered
696            if (origin.classfile != null &&
697                    origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
698                    enter.getEnv(origin) == null) {
699                return false;
700            }
701            if (origin == s) {
702                return true;
703            }
704            for (Type t : interfaces(origin.type)) {
705                if (pendingBridges((ClassSymbol)t.tsym, s)) {
706                    return true;
707                }
708            }
709            return false;
710        }
711    // </editor-fold>
712
713   /**
714    * Scope filter used to skip methods that should be ignored (such as methods
715    * overridden by j.l.Object) during function interface conversion interface check
716    */
717    class DescriptorFilter implements Filter<Symbol> {
718
719       TypeSymbol origin;
720
721       DescriptorFilter(TypeSymbol origin) {
722           this.origin = origin;
723       }
724
725       @Override
726       public boolean accepts(Symbol sym) {
727           return sym.kind == MTH &&
728                   (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
729                   !overridesObjectMethod(origin, sym) &&
730                   (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
731       }
732    }
733
734    // <editor-fold defaultstate="collapsed" desc="isSubtype">
735    /**
736     * Is t an unchecked subtype of s?
737     */
738    public boolean isSubtypeUnchecked(Type t, Type s) {
739        return isSubtypeUnchecked(t, s, noWarnings);
740    }
741    /**
742     * Is t an unchecked subtype of s?
743     */
744    public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
745        boolean result = isSubtypeUncheckedInternal(t, s, warn);
746        if (result) {
747            checkUnsafeVarargsConversion(t, s, warn);
748        }
749        return result;
750    }
751    //where
752        private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
753            if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
754                if (((ArrayType)t).elemtype.isPrimitive()) {
755                    return isSameType(elemtype(t), elemtype(s));
756                } else {
757                    return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
758                }
759            } else if (isSubtype(t, s)) {
760                return true;
761            } else if (t.hasTag(TYPEVAR)) {
762                return isSubtypeUnchecked(t.getUpperBound(), s, warn);
763            } else if (!s.isRaw()) {
764                Type t2 = asSuper(t, s.tsym);
765                if (t2 != null && t2.isRaw()) {
766                    if (isReifiable(s)) {
767                        warn.silentWarn(LintCategory.UNCHECKED);
768                    } else {
769                        warn.warn(LintCategory.UNCHECKED);
770                    }
771                    return true;
772                }
773            }
774            return false;
775        }
776
777        private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
778            if (!t.hasTag(ARRAY) || isReifiable(t)) {
779                return;
780            }
781            ArrayType from = (ArrayType)t;
782            boolean shouldWarn = false;
783            switch (s.getTag()) {
784                case ARRAY:
785                    ArrayType to = (ArrayType)s;
786                    shouldWarn = from.isVarargs() &&
787                            !to.isVarargs() &&
788                            !isReifiable(from);
789                    break;
790                case CLASS:
791                    shouldWarn = from.isVarargs();
792                    break;
793            }
794            if (shouldWarn) {
795                warn.warn(LintCategory.VARARGS);
796            }
797        }
798
799    /**
800     * Is t a subtype of s?<br>
801     * (not defined for Method and ForAll types)
802     */
803    final public boolean isSubtype(Type t, Type s) {
804        return isSubtype(t, s, true);
805    }
806    final public boolean isSubtypeNoCapture(Type t, Type s) {
807        return isSubtype(t, s, false);
808    }
809    public boolean isSubtype(Type t, Type s, boolean capture) {
810        if (t == s)
811            return true;
812        if (s.isPartial())
813            return isSuperType(s, t);
814
815        if (s.isCompound()) {
816            for (Type s2 : interfaces(s).prepend(supertype(s))) {
817                if (!isSubtype(t, s2, capture))
818                    return false;
819            }
820            return true;
821        }
822
823        // Generally, if 's' is a lower-bounded type variable, recur on lower bound; but
824        // for inference variables and intersections, we need to keep 's'
825        // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars)
826        if (!t.hasTag(UNDETVAR) && !t.isCompound()) {
827            // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
828            Type lower = cvarLowerBound(wildLowerBound(s));
829            if (s != lower && !lower.hasTag(BOT))
830                return isSubtype(capture ? capture(t) : t, lower, false);
831        }
832
833        return isSubtype.visit(capture ? capture(t) : t, s);
834    }
835    // where
836        private TypeRelation isSubtype = new TypeRelation()
837        {
838            @Override
839            public Boolean visitType(Type t, Type s) {
840                switch (t.getTag()) {
841                 case BYTE:
842                     return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
843                 case CHAR:
844                     return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
845                 case SHORT: case INT: case LONG:
846                 case FLOAT: case DOUBLE:
847                     return t.getTag().isSubRangeOf(s.getTag());
848                 case BOOLEAN: case VOID:
849                     return t.hasTag(s.getTag());
850                 case TYPEVAR:
851                     return isSubtypeNoCapture(t.getUpperBound(), s);
852                 case BOT:
853                     return
854                         s.hasTag(BOT) || s.hasTag(CLASS) ||
855                         s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
856                 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
857                 case NONE:
858                     return false;
859                 default:
860                     throw new AssertionError("isSubtype " + t.getTag());
861                 }
862            }
863
864            private Set<TypePair> cache = new HashSet<>();
865
866            private boolean containsTypeRecursive(Type t, Type s) {
867                TypePair pair = new TypePair(t, s);
868                if (cache.add(pair)) {
869                    try {
870                        return containsType(t.getTypeArguments(),
871                                            s.getTypeArguments());
872                    } finally {
873                        cache.remove(pair);
874                    }
875                } else {
876                    return containsType(t.getTypeArguments(),
877                                        rewriteSupers(s).getTypeArguments());
878                }
879            }
880
881            private Type rewriteSupers(Type t) {
882                if (!t.isParameterized())
883                    return t;
884                ListBuffer<Type> from = new ListBuffer<>();
885                ListBuffer<Type> to = new ListBuffer<>();
886                adaptSelf(t, from, to);
887                if (from.isEmpty())
888                    return t;
889                ListBuffer<Type> rewrite = new ListBuffer<>();
890                boolean changed = false;
891                for (Type orig : to.toList()) {
892                    Type s = rewriteSupers(orig);
893                    if (s.isSuperBound() && !s.isExtendsBound()) {
894                        s = new WildcardType(syms.objectType,
895                                             BoundKind.UNBOUND,
896                                             syms.boundClass,
897                                             s.getMetadata());
898                        changed = true;
899                    } else if (s != orig) {
900                        s = new WildcardType(wildUpperBound(s),
901                                             BoundKind.EXTENDS,
902                                             syms.boundClass,
903                                             s.getMetadata());
904                        changed = true;
905                    }
906                    rewrite.append(s);
907                }
908                if (changed)
909                    return subst(t.tsym.type, from.toList(), rewrite.toList());
910                else
911                    return t;
912            }
913
914            @Override
915            public Boolean visitClassType(ClassType t, Type s) {
916                Type sup = asSuper(t, s.tsym);
917                if (sup == null) return false;
918                // If t is an intersection, sup might not be a class type
919                if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s);
920                return sup.tsym == s.tsym
921                     // Check type variable containment
922                    && (!s.isParameterized() || containsTypeRecursive(s, sup))
923                    && isSubtypeNoCapture(sup.getEnclosingType(),
924                                          s.getEnclosingType());
925            }
926
927            @Override
928            public Boolean visitArrayType(ArrayType t, Type s) {
929                if (s.hasTag(ARRAY)) {
930                    if (t.elemtype.isPrimitive())
931                        return isSameType(t.elemtype, elemtype(s));
932                    else
933                        return isSubtypeNoCapture(t.elemtype, elemtype(s));
934                }
935
936                if (s.hasTag(CLASS)) {
937                    Name sname = s.tsym.getQualifiedName();
938                    return sname == names.java_lang_Object
939                        || sname == names.java_lang_Cloneable
940                        || sname == names.java_io_Serializable;
941                }
942
943                return false;
944            }
945
946            @Override
947            public Boolean visitUndetVar(UndetVar t, Type s) {
948                //todo: test against origin needed? or replace with substitution?
949                if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
950                    return true;
951                } else if (s.hasTag(BOT)) {
952                    //if 's' is 'null' there's no instantiated type U for which
953                    //U <: s (but 'null' itself, which is not a valid type)
954                    return false;
955                }
956
957                t.addBound(InferenceBound.UPPER, s, Types.this);
958                return true;
959            }
960
961            @Override
962            public Boolean visitErrorType(ErrorType t, Type s) {
963                return true;
964            }
965        };
966
967    /**
968     * Is t a subtype of every type in given list `ts'?<br>
969     * (not defined for Method and ForAll types)<br>
970     * Allows unchecked conversions.
971     */
972    public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
973        for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
974            if (!isSubtypeUnchecked(t, l.head, warn))
975                return false;
976        return true;
977    }
978
979    /**
980     * Are corresponding elements of ts subtypes of ss?  If lists are
981     * of different length, return false.
982     */
983    public boolean isSubtypes(List<Type> ts, List<Type> ss) {
984        while (ts.tail != null && ss.tail != null
985               /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
986               isSubtype(ts.head, ss.head)) {
987            ts = ts.tail;
988            ss = ss.tail;
989        }
990        return ts.tail == null && ss.tail == null;
991        /*inlined: ts.isEmpty() && ss.isEmpty();*/
992    }
993
994    /**
995     * Are corresponding elements of ts subtypes of ss, allowing
996     * unchecked conversions?  If lists are of different length,
997     * return false.
998     **/
999    public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
1000        while (ts.tail != null && ss.tail != null
1001               /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1002               isSubtypeUnchecked(ts.head, ss.head, warn)) {
1003            ts = ts.tail;
1004            ss = ss.tail;
1005        }
1006        return ts.tail == null && ss.tail == null;
1007        /*inlined: ts.isEmpty() && ss.isEmpty();*/
1008    }
1009    // </editor-fold>
1010
1011    // <editor-fold defaultstate="collapsed" desc="isSuperType">
1012    /**
1013     * Is t a supertype of s?
1014     */
1015    public boolean isSuperType(Type t, Type s) {
1016        switch (t.getTag()) {
1017        case ERROR:
1018            return true;
1019        case UNDETVAR: {
1020            UndetVar undet = (UndetVar)t;
1021            if (t == s ||
1022                undet.qtype == s ||
1023                s.hasTag(ERROR) ||
1024                s.hasTag(BOT)) {
1025                return true;
1026            }
1027            undet.addBound(InferenceBound.LOWER, s, this);
1028            return true;
1029        }
1030        default:
1031            return isSubtype(s, t);
1032        }
1033    }
1034    // </editor-fold>
1035
1036    // <editor-fold defaultstate="collapsed" desc="isSameType">
1037    /**
1038     * Are corresponding elements of the lists the same type?  If
1039     * lists are of different length, return false.
1040     */
1041    public boolean isSameTypes(List<Type> ts, List<Type> ss) {
1042        return isSameTypes(ts, ss, false);
1043    }
1044    public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
1045        while (ts.tail != null && ss.tail != null
1046               /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1047               isSameType(ts.head, ss.head, strict)) {
1048            ts = ts.tail;
1049            ss = ss.tail;
1050        }
1051        return ts.tail == null && ss.tail == null;
1052        /*inlined: ts.isEmpty() && ss.isEmpty();*/
1053    }
1054
1055    /**
1056    * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
1057    * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
1058    * a single variable arity parameter (iii) whose declared type is Object[],
1059    * (iv) has a return type of Object and (v) is native.
1060    */
1061   public boolean isSignaturePolymorphic(MethodSymbol msym) {
1062       List<Type> argtypes = msym.type.getParameterTypes();
1063       return (msym.flags_field & NATIVE) != 0 &&
1064               msym.owner == syms.methodHandleType.tsym &&
1065               argtypes.tail.tail == null &&
1066               argtypes.head.hasTag(TypeTag.ARRAY) &&
1067               msym.type.getReturnType().tsym == syms.objectType.tsym &&
1068               ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
1069   }
1070
1071    /**
1072     * Is t the same type as s?
1073     */
1074    public boolean isSameType(Type t, Type s) {
1075        return isSameType(t, s, false);
1076    }
1077    public boolean isSameType(Type t, Type s, boolean strict) {
1078        return strict ?
1079                isSameTypeStrict.visit(t, s) :
1080                isSameTypeLoose.visit(t, s);
1081    }
1082    public boolean isSameAnnotatedType(Type t, Type s) {
1083        return isSameAnnotatedType.visit(t, s);
1084    }
1085    // where
1086        abstract class SameTypeVisitor extends TypeRelation {
1087
1088            public Boolean visitType(Type t, Type s) {
1089                if (t == s)
1090                    return true;
1091
1092                if (s.isPartial())
1093                    return visit(s, t);
1094
1095                switch (t.getTag()) {
1096                case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1097                case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
1098                    return t.hasTag(s.getTag());
1099                case TYPEVAR: {
1100                    if (s.hasTag(TYPEVAR)) {
1101                        //type-substitution does not preserve type-var types
1102                        //check that type var symbols and bounds are indeed the same
1103                        return sameTypeVars((TypeVar)t, (TypeVar)s);
1104                    }
1105                    else {
1106                        //special case for s == ? super X, where upper(s) = u
1107                        //check that u == t, where u has been set by Type.withTypeVar
1108                        return s.isSuperBound() &&
1109                                !s.isExtendsBound() &&
1110                                visit(t, wildUpperBound(s));
1111                    }
1112                }
1113                default:
1114                    throw new AssertionError("isSameType " + t.getTag());
1115                }
1116            }
1117
1118            abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
1119
1120            @Override
1121            public Boolean visitWildcardType(WildcardType t, Type s) {
1122                if (s.isPartial())
1123                    return visit(s, t);
1124                else
1125                    return false;
1126            }
1127
1128            @Override
1129            public Boolean visitClassType(ClassType t, Type s) {
1130                if (t == s)
1131                    return true;
1132
1133                if (s.isPartial())
1134                    return visit(s, t);
1135
1136                if (s.isSuperBound() && !s.isExtendsBound())
1137                    return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s));
1138
1139                if (t.isCompound() && s.isCompound()) {
1140                    if (!visit(supertype(t), supertype(s)))
1141                        return false;
1142
1143                    HashSet<UniqueType> set = new HashSet<>();
1144                    for (Type x : interfaces(t))
1145                        set.add(new UniqueType(x, Types.this));
1146                    for (Type x : interfaces(s)) {
1147                        if (!set.remove(new UniqueType(x, Types.this)))
1148                            return false;
1149                    }
1150                    return (set.isEmpty());
1151                }
1152                return t.tsym == s.tsym
1153                    && visit(t.getEnclosingType(), s.getEnclosingType())
1154                    && containsTypes(t.getTypeArguments(), s.getTypeArguments());
1155            }
1156
1157            abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
1158
1159            @Override
1160            public Boolean visitArrayType(ArrayType t, Type s) {
1161                if (t == s)
1162                    return true;
1163
1164                if (s.isPartial())
1165                    return visit(s, t);
1166
1167                return s.hasTag(ARRAY)
1168                    && containsTypeEquivalent(t.elemtype, elemtype(s));
1169            }
1170
1171            @Override
1172            public Boolean visitMethodType(MethodType t, Type s) {
1173                // isSameType for methods does not take thrown
1174                // exceptions into account!
1175                return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
1176            }
1177
1178            @Override
1179            public Boolean visitPackageType(PackageType t, Type s) {
1180                return t == s;
1181            }
1182
1183            @Override
1184            public Boolean visitForAll(ForAll t, Type s) {
1185                if (!s.hasTag(FORALL)) {
1186                    return false;
1187                }
1188
1189                ForAll forAll = (ForAll)s;
1190                return hasSameBounds(t, forAll)
1191                    && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1192            }
1193
1194            @Override
1195            public Boolean visitUndetVar(UndetVar t, Type s) {
1196                if (s.hasTag(WILDCARD)) {
1197                    // FIXME, this might be leftovers from before capture conversion
1198                    return false;
1199                }
1200
1201                if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
1202                    return true;
1203                }
1204
1205                t.addBound(InferenceBound.EQ, s, Types.this);
1206
1207                return true;
1208            }
1209
1210            @Override
1211            public Boolean visitErrorType(ErrorType t, Type s) {
1212                return true;
1213            }
1214        }
1215
1216        /**
1217         * Standard type-equality relation - type variables are considered
1218         * equals if they share the same type symbol.
1219         */
1220        TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
1221
1222        private class LooseSameTypeVisitor extends SameTypeVisitor {
1223
1224            /** cache of the type-variable pairs being (recursively) tested. */
1225            private Set<TypePair> cache = new HashSet<>();
1226
1227            @Override
1228            boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
1229                return tv1.tsym == tv2.tsym && checkSameBounds(tv1, tv2);
1230            }
1231            @Override
1232            protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
1233                return containsTypeEquivalent(ts1, ts2);
1234            }
1235
1236            /**
1237             * Since type-variable bounds can be recursive, we need to protect against
1238             * infinite loops - where the same bounds are checked over and over recursively.
1239             */
1240            private boolean checkSameBounds(TypeVar tv1, TypeVar tv2) {
1241                TypePair p = new TypePair(tv1, tv2, true);
1242                if (cache.add(p)) {
1243                    try {
1244                        return visit(tv1.getUpperBound(), tv2.getUpperBound());
1245                    } finally {
1246                        cache.remove(p);
1247                    }
1248                } else {
1249                    return false;
1250                }
1251            }
1252        };
1253
1254        /**
1255         * Strict type-equality relation - type variables are considered
1256         * equals if they share the same object identity.
1257         */
1258        TypeRelation isSameTypeStrict = new SameTypeVisitor() {
1259            @Override
1260            boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
1261                return tv1 == tv2;
1262            }
1263            @Override
1264            protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
1265                return isSameTypes(ts1, ts2, true);
1266            }
1267
1268            @Override
1269            public Boolean visitWildcardType(WildcardType t, Type s) {
1270                if (!s.hasTag(WILDCARD)) {
1271                    return false;
1272                } else {
1273                    WildcardType t2 = (WildcardType)s;
1274                    return t.kind == t2.kind &&
1275                            isSameType(t.type, t2.type, true);
1276                }
1277            }
1278        };
1279
1280    // </editor-fold>
1281
1282    TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
1283            private Boolean compareAnnotations(Type t1, Type t2) {
1284                List<Attribute.TypeCompound> annos1 = t1.getAnnotationMirrors();
1285                List<Attribute.TypeCompound> annos2 = t2.getAnnotationMirrors();
1286                return annos1.containsAll(annos2) && annos2.containsAll(annos1);
1287            }
1288
1289            @Override
1290            public Boolean visitType(Type t, Type s) {
1291                return compareAnnotations(t, s) && super.visitType(t, s);
1292            }
1293
1294            @Override
1295            public Boolean visitWildcardType(WildcardType t, Type s) {
1296                return compareAnnotations(t, s) && super.visitWildcardType(t, s);
1297            }
1298
1299            @Override
1300            public Boolean visitClassType(ClassType t, Type s) {
1301                return compareAnnotations(t, s) && super.visitClassType(t, s);
1302            }
1303
1304            @Override
1305            public Boolean visitArrayType(ArrayType t, Type s) {
1306                return compareAnnotations(t, s) && super.visitArrayType(t, s);
1307            }
1308
1309            @Override
1310            public Boolean visitForAll(ForAll t, Type s) {
1311                return compareAnnotations(t, s) && super.visitForAll(t, s);
1312            }
1313        };
1314
1315    // <editor-fold defaultstate="collapsed" desc="Contains Type">
1316    public boolean containedBy(Type t, Type s) {
1317        switch (t.getTag()) {
1318        case UNDETVAR:
1319            if (s.hasTag(WILDCARD)) {
1320                UndetVar undetvar = (UndetVar)t;
1321                WildcardType wt = (WildcardType)s;
1322                switch(wt.kind) {
1323                    case UNBOUND:
1324                        break;
1325                    case EXTENDS: {
1326                        Type bound = wildUpperBound(s);
1327                        undetvar.addBound(InferenceBound.UPPER, bound, this);
1328                        break;
1329                    }
1330                    case SUPER: {
1331                        Type bound = wildLowerBound(s);
1332                        undetvar.addBound(InferenceBound.LOWER, bound, this);
1333                        break;
1334                    }
1335                }
1336                return true;
1337            } else {
1338                return isSameType(t, s);
1339            }
1340        case ERROR:
1341            return true;
1342        default:
1343            return containsType(s, t);
1344        }
1345    }
1346
1347    boolean containsType(List<Type> ts, List<Type> ss) {
1348        while (ts.nonEmpty() && ss.nonEmpty()
1349               && containsType(ts.head, ss.head)) {
1350            ts = ts.tail;
1351            ss = ss.tail;
1352        }
1353        return ts.isEmpty() && ss.isEmpty();
1354    }
1355
1356    /**
1357     * Check if t contains s.
1358     *
1359     * <p>T contains S if:
1360     *
1361     * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1362     *
1363     * <p>This relation is only used by ClassType.isSubtype(), that
1364     * is,
1365     *
1366     * <p>{@code C<S> <: C<T> if T contains S.}
1367     *
1368     * <p>Because of F-bounds, this relation can lead to infinite
1369     * recursion.  Thus we must somehow break that recursion.  Notice
1370     * that containsType() is only called from ClassType.isSubtype().
1371     * Since the arguments have already been checked against their
1372     * bounds, we know:
1373     *
1374     * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1375     *
1376     * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1377     *
1378     * @param t a type
1379     * @param s a type
1380     */
1381    public boolean containsType(Type t, Type s) {
1382        return containsType.visit(t, s);
1383    }
1384    // where
1385        private TypeRelation containsType = new TypeRelation() {
1386
1387            public Boolean visitType(Type t, Type s) {
1388                if (s.isPartial())
1389                    return containedBy(s, t);
1390                else
1391                    return isSameType(t, s);
1392            }
1393
1394//            void debugContainsType(WildcardType t, Type s) {
1395//                System.err.println();
1396//                System.err.format(" does %s contain %s?%n", t, s);
1397//                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1398//                                  wildUpperBound(s), s, t, wildUpperBound(t),
1399//                                  t.isSuperBound()
1400//                                  || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t)));
1401//                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1402//                                  wildLowerBound(t), t, s, wildLowerBound(s),
1403//                                  t.isExtendsBound()
1404//                                  || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s)));
1405//                System.err.println();
1406//            }
1407
1408            @Override
1409            public Boolean visitWildcardType(WildcardType t, Type s) {
1410                if (s.isPartial())
1411                    return containedBy(s, t);
1412                else {
1413//                    debugContainsType(t, s);
1414                    return isSameWildcard(t, s)
1415                        || isCaptureOf(s, t)
1416                        || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))) &&
1417                            (t.isSuperBound() || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t))));
1418                }
1419            }
1420
1421            @Override
1422            public Boolean visitUndetVar(UndetVar t, Type s) {
1423                if (!s.hasTag(WILDCARD)) {
1424                    return isSameType(t, s);
1425                } else {
1426                    return false;
1427                }
1428            }
1429
1430            @Override
1431            public Boolean visitErrorType(ErrorType t, Type s) {
1432                return true;
1433            }
1434        };
1435
1436    public boolean isCaptureOf(Type s, WildcardType t) {
1437        if (!s.hasTag(TYPEVAR) || !((TypeVar)s).isCaptured())
1438            return false;
1439        return isSameWildcard(t, ((CapturedType)s).wildcard);
1440    }
1441
1442    public boolean isSameWildcard(WildcardType t, Type s) {
1443        if (!s.hasTag(WILDCARD))
1444            return false;
1445        WildcardType w = (WildcardType)s;
1446        return w.kind == t.kind && w.type == t.type;
1447    }
1448
1449    public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1450        while (ts.nonEmpty() && ss.nonEmpty()
1451               && containsTypeEquivalent(ts.head, ss.head)) {
1452            ts = ts.tail;
1453            ss = ss.tail;
1454        }
1455        return ts.isEmpty() && ss.isEmpty();
1456    }
1457    // </editor-fold>
1458
1459    // <editor-fold defaultstate="collapsed" desc="isCastable">
1460    public boolean isCastable(Type t, Type s) {
1461        return isCastable(t, s, noWarnings);
1462    }
1463
1464    /**
1465     * Is t is castable to s?<br>
1466     * s is assumed to be an erased type.<br>
1467     * (not defined for Method and ForAll types).
1468     */
1469    public boolean isCastable(Type t, Type s, Warner warn) {
1470        if (t == s)
1471            return true;
1472
1473        if (t.isPrimitive() != s.isPrimitive())
1474            return (isConvertible(t, s, warn)
1475                    || (allowObjectToPrimitiveCast &&
1476                        s.isPrimitive() &&
1477                        isSubtype(boxedClass(s).type, t)));
1478        if (warn != warnStack.head) {
1479            try {
1480                warnStack = warnStack.prepend(warn);
1481                checkUnsafeVarargsConversion(t, s, warn);
1482                return isCastable.visit(t,s);
1483            } finally {
1484                warnStack = warnStack.tail;
1485            }
1486        } else {
1487            return isCastable.visit(t,s);
1488        }
1489    }
1490    // where
1491        private TypeRelation isCastable = new TypeRelation() {
1492
1493            public Boolean visitType(Type t, Type s) {
1494                if (s.hasTag(ERROR))
1495                    return true;
1496
1497                switch (t.getTag()) {
1498                case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1499                case DOUBLE:
1500                    return s.isNumeric();
1501                case BOOLEAN:
1502                    return s.hasTag(BOOLEAN);
1503                case VOID:
1504                    return false;
1505                case BOT:
1506                    return isSubtype(t, s);
1507                default:
1508                    throw new AssertionError();
1509                }
1510            }
1511
1512            @Override
1513            public Boolean visitWildcardType(WildcardType t, Type s) {
1514                return isCastable(wildUpperBound(t), s, warnStack.head);
1515            }
1516
1517            @Override
1518            public Boolean visitClassType(ClassType t, Type s) {
1519                if (s.hasTag(ERROR) || s.hasTag(BOT))
1520                    return true;
1521
1522                if (s.hasTag(TYPEVAR)) {
1523                    if (isCastable(t, s.getUpperBound(), noWarnings)) {
1524                        warnStack.head.warn(LintCategory.UNCHECKED);
1525                        return true;
1526                    } else {
1527                        return false;
1528                    }
1529                }
1530
1531                if (t.isIntersection() || s.isIntersection()) {
1532                    return !t.isIntersection() ?
1533                            visitIntersectionType((IntersectionClassType)s, t, true) :
1534                            visitIntersectionType((IntersectionClassType)t, s, false);
1535                }
1536
1537                if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
1538                    boolean upcast;
1539                    if ((upcast = isSubtype(erasure(t), erasure(s)))
1540                        || isSubtype(erasure(s), erasure(t))) {
1541                        if (!upcast && s.hasTag(ARRAY)) {
1542                            if (!isReifiable(s))
1543                                warnStack.head.warn(LintCategory.UNCHECKED);
1544                            return true;
1545                        } else if (s.isRaw()) {
1546                            return true;
1547                        } else if (t.isRaw()) {
1548                            if (!isUnbounded(s))
1549                                warnStack.head.warn(LintCategory.UNCHECKED);
1550                            return true;
1551                        }
1552                        // Assume |a| <: |b|
1553                        final Type a = upcast ? t : s;
1554                        final Type b = upcast ? s : t;
1555                        final boolean HIGH = true;
1556                        final boolean LOW = false;
1557                        final boolean DONT_REWRITE_TYPEVARS = false;
1558                        Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1559                        Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
1560                        Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1561                        Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
1562                        Type lowSub = asSub(bLow, aLow.tsym);
1563                        Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1564                        if (highSub == null) {
1565                            final boolean REWRITE_TYPEVARS = true;
1566                            aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1567                            aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
1568                            bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1569                            bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
1570                            lowSub = asSub(bLow, aLow.tsym);
1571                            highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1572                        }
1573                        if (highSub != null) {
1574                            if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1575                                Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1576                            }
1577                            if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1578                                && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1579                                && !disjointTypes(aLow.allparams(), highSub.allparams())
1580                                && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1581                                if (upcast ? giveWarning(a, b) :
1582                                    giveWarning(b, a))
1583                                    warnStack.head.warn(LintCategory.UNCHECKED);
1584                                return true;
1585                            }
1586                        }
1587                        if (isReifiable(s))
1588                            return isSubtypeUnchecked(a, b);
1589                        else
1590                            return isSubtypeUnchecked(a, b, warnStack.head);
1591                    }
1592
1593                    // Sidecast
1594                    if (s.hasTag(CLASS)) {
1595                        if ((s.tsym.flags() & INTERFACE) != 0) {
1596                            return ((t.tsym.flags() & FINAL) == 0)
1597                                ? sideCast(t, s, warnStack.head)
1598                                : sideCastFinal(t, s, warnStack.head);
1599                        } else if ((t.tsym.flags() & INTERFACE) != 0) {
1600                            return ((s.tsym.flags() & FINAL) == 0)
1601                                ? sideCast(t, s, warnStack.head)
1602                                : sideCastFinal(t, s, warnStack.head);
1603                        } else {
1604                            // unrelated class types
1605                            return false;
1606                        }
1607                    }
1608                }
1609                return false;
1610            }
1611
1612            boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
1613                Warner warn = noWarnings;
1614                for (Type c : ict.getComponents()) {
1615                    warn.clear();
1616                    if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
1617                        return false;
1618                }
1619                if (warn.hasLint(LintCategory.UNCHECKED))
1620                    warnStack.head.warn(LintCategory.UNCHECKED);
1621                return true;
1622            }
1623
1624            @Override
1625            public Boolean visitArrayType(ArrayType t, Type s) {
1626                switch (s.getTag()) {
1627                case ERROR:
1628                case BOT:
1629                    return true;
1630                case TYPEVAR:
1631                    if (isCastable(s, t, noWarnings)) {
1632                        warnStack.head.warn(LintCategory.UNCHECKED);
1633                        return true;
1634                    } else {
1635                        return false;
1636                    }
1637                case CLASS:
1638                    return isSubtype(t, s);
1639                case ARRAY:
1640                    if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
1641                        return elemtype(t).hasTag(elemtype(s).getTag());
1642                    } else {
1643                        return visit(elemtype(t), elemtype(s));
1644                    }
1645                default:
1646                    return false;
1647                }
1648            }
1649
1650            @Override
1651            public Boolean visitTypeVar(TypeVar t, Type s) {
1652                switch (s.getTag()) {
1653                case ERROR:
1654                case BOT:
1655                    return true;
1656                case TYPEVAR:
1657                    if (isSubtype(t, s)) {
1658                        return true;
1659                    } else if (isCastable(t.bound, s, noWarnings)) {
1660                        warnStack.head.warn(LintCategory.UNCHECKED);
1661                        return true;
1662                    } else {
1663                        return false;
1664                    }
1665                default:
1666                    return isCastable(t.bound, s, warnStack.head);
1667                }
1668            }
1669
1670            @Override
1671            public Boolean visitErrorType(ErrorType t, Type s) {
1672                return true;
1673            }
1674        };
1675    // </editor-fold>
1676
1677    // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1678    public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1679        while (ts.tail != null && ss.tail != null) {
1680            if (disjointType(ts.head, ss.head)) return true;
1681            ts = ts.tail;
1682            ss = ss.tail;
1683        }
1684        return false;
1685    }
1686
1687    /**
1688     * Two types or wildcards are considered disjoint if it can be
1689     * proven that no type can be contained in both. It is
1690     * conservative in that it is allowed to say that two types are
1691     * not disjoint, even though they actually are.
1692     *
1693     * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1694     * {@code X} and {@code Y} are not disjoint.
1695     */
1696    public boolean disjointType(Type t, Type s) {
1697        return disjointType.visit(t, s);
1698    }
1699    // where
1700        private TypeRelation disjointType = new TypeRelation() {
1701
1702            private Set<TypePair> cache = new HashSet<>();
1703
1704            @Override
1705            public Boolean visitType(Type t, Type s) {
1706                if (s.hasTag(WILDCARD))
1707                    return visit(s, t);
1708                else
1709                    return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1710            }
1711
1712            private boolean isCastableRecursive(Type t, Type s) {
1713                TypePair pair = new TypePair(t, s);
1714                if (cache.add(pair)) {
1715                    try {
1716                        return Types.this.isCastable(t, s);
1717                    } finally {
1718                        cache.remove(pair);
1719                    }
1720                } else {
1721                    return true;
1722                }
1723            }
1724
1725            private boolean notSoftSubtypeRecursive(Type t, Type s) {
1726                TypePair pair = new TypePair(t, s);
1727                if (cache.add(pair)) {
1728                    try {
1729                        return Types.this.notSoftSubtype(t, s);
1730                    } finally {
1731                        cache.remove(pair);
1732                    }
1733                } else {
1734                    return false;
1735                }
1736            }
1737
1738            @Override
1739            public Boolean visitWildcardType(WildcardType t, Type s) {
1740                if (t.isUnbound())
1741                    return false;
1742
1743                if (!s.hasTag(WILDCARD)) {
1744                    if (t.isExtendsBound())
1745                        return notSoftSubtypeRecursive(s, t.type);
1746                    else
1747                        return notSoftSubtypeRecursive(t.type, s);
1748                }
1749
1750                if (s.isUnbound())
1751                    return false;
1752
1753                if (t.isExtendsBound()) {
1754                    if (s.isExtendsBound())
1755                        return !isCastableRecursive(t.type, wildUpperBound(s));
1756                    else if (s.isSuperBound())
1757                        return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
1758                } else if (t.isSuperBound()) {
1759                    if (s.isExtendsBound())
1760                        return notSoftSubtypeRecursive(t.type, wildUpperBound(s));
1761                }
1762                return false;
1763            }
1764        };
1765    // </editor-fold>
1766
1767    // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
1768    public List<Type> cvarLowerBounds(List<Type> ts) {
1769        return map(ts, cvarLowerBoundMapping);
1770    }
1771    private final Mapping cvarLowerBoundMapping = new Mapping("cvarLowerBound") {
1772            public Type apply(Type t) {
1773                return cvarLowerBound(t);
1774            }
1775        };
1776    // </editor-fold>
1777
1778    // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1779    /**
1780     * This relation answers the question: is impossible that
1781     * something of type `t' can be a subtype of `s'? This is
1782     * different from the question "is `t' not a subtype of `s'?"
1783     * when type variables are involved: Integer is not a subtype of T
1784     * where {@code <T extends Number>} but it is not true that Integer cannot
1785     * possibly be a subtype of T.
1786     */
1787    public boolean notSoftSubtype(Type t, Type s) {
1788        if (t == s) return false;
1789        if (t.hasTag(TYPEVAR)) {
1790            TypeVar tv = (TypeVar) t;
1791            return !isCastable(tv.bound,
1792                               relaxBound(s),
1793                               noWarnings);
1794        }
1795        if (!s.hasTag(WILDCARD))
1796            s = cvarUpperBound(s);
1797
1798        return !isSubtype(t, relaxBound(s));
1799    }
1800
1801    private Type relaxBound(Type t) {
1802        return (t.hasTag(TYPEVAR)) ?
1803                rewriteQuantifiers(skipTypeVars(t, false), true, true) :
1804                t;
1805    }
1806    // </editor-fold>
1807
1808    // <editor-fold defaultstate="collapsed" desc="isReifiable">
1809    public boolean isReifiable(Type t) {
1810        return isReifiable.visit(t);
1811    }
1812    // where
1813        private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1814
1815            public Boolean visitType(Type t, Void ignored) {
1816                return true;
1817            }
1818
1819            @Override
1820            public Boolean visitClassType(ClassType t, Void ignored) {
1821                if (t.isCompound())
1822                    return false;
1823                else {
1824                    if (!t.isParameterized())
1825                        return true;
1826
1827                    for (Type param : t.allparams()) {
1828                        if (!param.isUnbound())
1829                            return false;
1830                    }
1831                    return true;
1832                }
1833            }
1834
1835            @Override
1836            public Boolean visitArrayType(ArrayType t, Void ignored) {
1837                return visit(t.elemtype);
1838            }
1839
1840            @Override
1841            public Boolean visitTypeVar(TypeVar t, Void ignored) {
1842                return false;
1843            }
1844        };
1845    // </editor-fold>
1846
1847    // <editor-fold defaultstate="collapsed" desc="Array Utils">
1848    public boolean isArray(Type t) {
1849        while (t.hasTag(WILDCARD))
1850            t = wildUpperBound(t);
1851        return t.hasTag(ARRAY);
1852    }
1853
1854    /**
1855     * The element type of an array.
1856     */
1857    public Type elemtype(Type t) {
1858        switch (t.getTag()) {
1859        case WILDCARD:
1860            return elemtype(wildUpperBound(t));
1861        case ARRAY:
1862            return ((ArrayType)t).elemtype;
1863        case FORALL:
1864            return elemtype(((ForAll)t).qtype);
1865        case ERROR:
1866            return t;
1867        default:
1868            return null;
1869        }
1870    }
1871
1872    public Type elemtypeOrType(Type t) {
1873        Type elemtype = elemtype(t);
1874        return elemtype != null ?
1875            elemtype :
1876            t;
1877    }
1878
1879    /**
1880     * Mapping to take element type of an arraytype
1881     */
1882    private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1883        public Type apply(Type t) {
1884            return elemtype(skipTypeVars(t, false));
1885        }
1886    };
1887
1888    /**
1889     * The number of dimensions of an array type.
1890     */
1891    public int dimensions(Type t) {
1892        int result = 0;
1893        while (t.hasTag(ARRAY)) {
1894            result++;
1895            t = elemtype(t);
1896        }
1897        return result;
1898    }
1899
1900    /**
1901     * Returns an ArrayType with the component type t
1902     *
1903     * @param t The component type of the ArrayType
1904     * @return the ArrayType for the given component
1905     */
1906    public ArrayType makeArrayType(Type t) {
1907        if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
1908            Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
1909        }
1910        return new ArrayType(t, syms.arrayClass);
1911    }
1912    // </editor-fold>
1913
1914    // <editor-fold defaultstate="collapsed" desc="asSuper">
1915    /**
1916     * Return the (most specific) base type of t that starts with the
1917     * given symbol.  If none exists, return null.
1918     *
1919     * Caveat Emptor: Since javac represents the class of all arrays with a singleton
1920     * symbol Symtab.arrayClass, which by being a singleton cannot hold any discriminant,
1921     * this method could yield surprising answers when invoked on arrays. For example when
1922     * invoked with t being byte [] and sym being t.sym itself, asSuper would answer null.
1923     *
1924     * @param t a type
1925     * @param sym a symbol
1926     */
1927    public Type asSuper(Type t, Symbol sym) {
1928        /* Some examples:
1929         *
1930         * (Enum<E>, Comparable) => Comparable<E>
1931         * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
1932         * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
1933         * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
1934         *     Iterable<capture#160 of ? extends c.s.s.d.DocTree>
1935         */
1936        if (sym.type == syms.objectType) { //optimization
1937            return syms.objectType;
1938        }
1939        return asSuper.visit(t, sym);
1940    }
1941    // where
1942        private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1943
1944            public Type visitType(Type t, Symbol sym) {
1945                return null;
1946            }
1947
1948            @Override
1949            public Type visitClassType(ClassType t, Symbol sym) {
1950                if (t.tsym == sym)
1951                    return t;
1952
1953                Type st = supertype(t);
1954                if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) {
1955                    Type x = asSuper(st, sym);
1956                    if (x != null)
1957                        return x;
1958                }
1959                if ((sym.flags() & INTERFACE) != 0) {
1960                    for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1961                        if (!l.head.hasTag(ERROR)) {
1962                            Type x = asSuper(l.head, sym);
1963                            if (x != null)
1964                                return x;
1965                        }
1966                    }
1967                }
1968                return null;
1969            }
1970
1971            @Override
1972            public Type visitArrayType(ArrayType t, Symbol sym) {
1973                return isSubtype(t, sym.type) ? sym.type : null;
1974            }
1975
1976            @Override
1977            public Type visitTypeVar(TypeVar t, Symbol sym) {
1978                if (t.tsym == sym)
1979                    return t;
1980                else
1981                    return asSuper(t.bound, sym);
1982            }
1983
1984            @Override
1985            public Type visitErrorType(ErrorType t, Symbol sym) {
1986                return t;
1987            }
1988        };
1989
1990    /**
1991     * Return the base type of t or any of its outer types that starts
1992     * with the given symbol.  If none exists, return null.
1993     *
1994     * @param t a type
1995     * @param sym a symbol
1996     */
1997    public Type asOuterSuper(Type t, Symbol sym) {
1998        switch (t.getTag()) {
1999        case CLASS:
2000            do {
2001                Type s = asSuper(t, sym);
2002                if (s != null) return s;
2003                t = t.getEnclosingType();
2004            } while (t.hasTag(CLASS));
2005            return null;
2006        case ARRAY:
2007            return isSubtype(t, sym.type) ? sym.type : null;
2008        case TYPEVAR:
2009            return asSuper(t, sym);
2010        case ERROR:
2011            return t;
2012        default:
2013            return null;
2014        }
2015    }
2016
2017    /**
2018     * Return the base type of t or any of its enclosing types that
2019     * starts with the given symbol.  If none exists, return null.
2020     *
2021     * @param t a type
2022     * @param sym a symbol
2023     */
2024    public Type asEnclosingSuper(Type t, Symbol sym) {
2025        switch (t.getTag()) {
2026        case CLASS:
2027            do {
2028                Type s = asSuper(t, sym);
2029                if (s != null) return s;
2030                Type outer = t.getEnclosingType();
2031                t = (outer.hasTag(CLASS)) ? outer :
2032                    (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
2033                    Type.noType;
2034            } while (t.hasTag(CLASS));
2035            return null;
2036        case ARRAY:
2037            return isSubtype(t, sym.type) ? sym.type : null;
2038        case TYPEVAR:
2039            return asSuper(t, sym);
2040        case ERROR:
2041            return t;
2042        default:
2043            return null;
2044        }
2045    }
2046    // </editor-fold>
2047
2048    // <editor-fold defaultstate="collapsed" desc="memberType">
2049    /**
2050     * The type of given symbol, seen as a member of t.
2051     *
2052     * @param t a type
2053     * @param sym a symbol
2054     */
2055    public Type memberType(Type t, Symbol sym) {
2056        return (sym.flags() & STATIC) != 0
2057            ? sym.type
2058            : memberType.visit(t, sym);
2059        }
2060    // where
2061        private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
2062
2063            public Type visitType(Type t, Symbol sym) {
2064                return sym.type;
2065            }
2066
2067            @Override
2068            public Type visitWildcardType(WildcardType t, Symbol sym) {
2069                return memberType(wildUpperBound(t), sym);
2070            }
2071
2072            @Override
2073            public Type visitClassType(ClassType t, Symbol sym) {
2074                Symbol owner = sym.owner;
2075                long flags = sym.flags();
2076                if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
2077                    Type base = asOuterSuper(t, owner);
2078                    //if t is an intersection type T = CT & I1 & I2 ... & In
2079                    //its supertypes CT, I1, ... In might contain wildcards
2080                    //so we need to go through capture conversion
2081                    base = t.isCompound() ? capture(base) : base;
2082                    if (base != null) {
2083                        List<Type> ownerParams = owner.type.allparams();
2084                        List<Type> baseParams = base.allparams();
2085                        if (ownerParams.nonEmpty()) {
2086                            if (baseParams.isEmpty()) {
2087                                // then base is a raw type
2088                                return erasure(sym.type);
2089                            } else {
2090                                return subst(sym.type, ownerParams, baseParams);
2091                            }
2092                        }
2093                    }
2094                }
2095                return sym.type;
2096            }
2097
2098            @Override
2099            public Type visitTypeVar(TypeVar t, Symbol sym) {
2100                return memberType(t.bound, sym);
2101            }
2102
2103            @Override
2104            public Type visitErrorType(ErrorType t, Symbol sym) {
2105                return t;
2106            }
2107        };
2108    // </editor-fold>
2109
2110    // <editor-fold defaultstate="collapsed" desc="isAssignable">
2111    public boolean isAssignable(Type t, Type s) {
2112        return isAssignable(t, s, noWarnings);
2113    }
2114
2115    /**
2116     * Is t assignable to s?<br>
2117     * Equivalent to subtype except for constant values and raw
2118     * types.<br>
2119     * (not defined for Method and ForAll types)
2120     */
2121    public boolean isAssignable(Type t, Type s, Warner warn) {
2122        if (t.hasTag(ERROR))
2123            return true;
2124        if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
2125            int value = ((Number)t.constValue()).intValue();
2126            switch (s.getTag()) {
2127            case BYTE:
2128                if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
2129                    return true;
2130                break;
2131            case CHAR:
2132                if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
2133                    return true;
2134                break;
2135            case SHORT:
2136                if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
2137                    return true;
2138                break;
2139            case INT:
2140                return true;
2141            case CLASS:
2142                switch (unboxedType(s).getTag()) {
2143                case BYTE:
2144                case CHAR:
2145                case SHORT:
2146                    return isAssignable(t, unboxedType(s), warn);
2147                }
2148                break;
2149            }
2150        }
2151        return isConvertible(t, s, warn);
2152    }
2153    // </editor-fold>
2154
2155    // <editor-fold defaultstate="collapsed" desc="erasure">
2156    /**
2157     * The erasure of t {@code |t|} -- the type that results when all
2158     * type parameters in t are deleted.
2159     */
2160    public Type erasure(Type t) {
2161        return eraseNotNeeded(t)? t : erasure(t, false);
2162    }
2163    //where
2164    private boolean eraseNotNeeded(Type t) {
2165        // We don't want to erase primitive types and String type as that
2166        // operation is idempotent. Also, erasing these could result in loss
2167        // of information such as constant values attached to such types.
2168        return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
2169    }
2170
2171    private Type erasure(Type t, boolean recurse) {
2172        if (t.isPrimitive()) {
2173            return t; /* fast special case */
2174        } else {
2175            Type out = erasure.visit(t, recurse);
2176            return out;
2177        }
2178        }
2179    // where
2180        private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
2181            private Type combineMetadata(final Type ty,
2182                                         final TypeMetadata md) {
2183                if (!md.isEmpty()) {
2184                    switch (ty.getKind()) {
2185                    default: return ty.clone(ty.metadata.combine(md));
2186                    case OTHER:
2187                    case UNION:
2188                    case INTERSECTION:
2189                    case PACKAGE:
2190                    case EXECUTABLE:
2191                    case NONE:
2192                    case VOID:
2193                    case ERROR:
2194                        return ty;
2195                    }
2196                } else {
2197                    return ty;
2198                }
2199            }
2200
2201            public Type visitType(Type t, Boolean recurse) {
2202                if (t.isPrimitive())
2203                    return t; /*fast special case*/
2204                else {
2205                    Type erased = t.map(recurse ? erasureRecFun : erasureFun);
2206                    return combineMetadata(erased, t.getMetadata());
2207                }
2208            }
2209
2210            @Override
2211            public Type visitClassType(ClassType t, Boolean recurse) {
2212                Type erased = t.tsym.erasure(Types.this);
2213                if (recurse) {
2214                    erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym, t.getMetadata());
2215                    return erased;
2216                } else {
2217                    return combineMetadata(erased, t.getMetadata());
2218                }
2219            }
2220
2221            @Override
2222            public Type visitTypeVar(TypeVar t, Boolean recurse) {
2223                Type erased = erasure(t.bound, recurse);
2224                return combineMetadata(erased, t.getMetadata());
2225            }
2226
2227            @Override
2228            public Type visitErrorType(ErrorType t, Boolean recurse) {
2229                return t;
2230            }
2231        };
2232
2233    private Mapping erasureFun = new Mapping ("erasure") {
2234            public Type apply(Type t) { return erasure(t); }
2235        };
2236
2237    private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
2238        public Type apply(Type t) { return erasureRecursive(t); }
2239    };
2240
2241    public List<Type> erasure(List<Type> ts) {
2242        return Type.map(ts, erasureFun);
2243    }
2244
2245    public Type erasureRecursive(Type t) {
2246        return erasure(t, true);
2247    }
2248
2249    public List<Type> erasureRecursive(List<Type> ts) {
2250        return Type.map(ts, erasureRecFun);
2251    }
2252    // </editor-fold>
2253
2254    // <editor-fold defaultstate="collapsed" desc="makeIntersectionType">
2255    /**
2256     * Make an intersection type from non-empty list of types.  The list should be ordered according to
2257     * {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion.
2258     * Hence, this version of makeIntersectionType may not be called during a classfile read.
2259     *
2260     * @param bounds    the types from which the intersection type is formed
2261     */
2262    public IntersectionClassType makeIntersectionType(List<Type> bounds) {
2263        return makeIntersectionType(bounds, bounds.head.tsym.isInterface());
2264    }
2265
2266    /**
2267     * Make an intersection type from non-empty list of types.  The list should be ordered according to
2268     * {@link TypeSymbol#precedes(TypeSymbol, Types)}. This does not cause symbol completion as
2269     * an extra parameter indicates as to whether all bounds are interfaces - in which case the
2270     * supertype is implicitly assumed to be 'Object'.
2271     *
2272     * @param bounds        the types from which the intersection type is formed
2273     * @param allInterfaces are all bounds interface types?
2274     */
2275    public IntersectionClassType makeIntersectionType(List<Type> bounds, boolean allInterfaces) {
2276        Assert.check(bounds.nonEmpty());
2277        Type firstExplicitBound = bounds.head;
2278        if (allInterfaces) {
2279            bounds = bounds.prepend(syms.objectType);
2280        }
2281        ClassSymbol bc =
2282            new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
2283                            Type.moreInfo
2284                                ? names.fromString(bounds.toString())
2285                                : names.empty,
2286                            null,
2287                            syms.noSymbol);
2288        IntersectionClassType intersectionType = new IntersectionClassType(bounds, bc, allInterfaces);
2289        bc.type = intersectionType;
2290        bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
2291                syms.objectType : // error condition, recover
2292                erasure(firstExplicitBound);
2293        bc.members_field = WriteableScope.create(bc);
2294        return intersectionType;
2295    }
2296    // </editor-fold>
2297
2298    // <editor-fold defaultstate="collapsed" desc="supertype">
2299    public Type supertype(Type t) {
2300        return supertype.visit(t);
2301    }
2302    // where
2303        private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2304
2305            public Type visitType(Type t, Void ignored) {
2306                // A note on wildcards: there is no good way to
2307                // determine a supertype for a super bounded wildcard.
2308                return Type.noType;
2309            }
2310
2311            @Override
2312            public Type visitClassType(ClassType t, Void ignored) {
2313                if (t.supertype_field == null) {
2314                    Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2315                    // An interface has no superclass; its supertype is Object.
2316                    if (t.isInterface())
2317                        supertype = ((ClassType)t.tsym.type).supertype_field;
2318                    if (t.supertype_field == null) {
2319                        List<Type> actuals = classBound(t).allparams();
2320                        List<Type> formals = t.tsym.type.allparams();
2321                        if (t.hasErasedSupertypes()) {
2322                            t.supertype_field = erasureRecursive(supertype);
2323                        } else if (formals.nonEmpty()) {
2324                            t.supertype_field = subst(supertype, formals, actuals);
2325                        }
2326                        else {
2327                            t.supertype_field = supertype;
2328                        }
2329                    }
2330                }
2331                return t.supertype_field;
2332            }
2333
2334            /**
2335             * The supertype is always a class type. If the type
2336             * variable's bounds start with a class type, this is also
2337             * the supertype.  Otherwise, the supertype is
2338             * java.lang.Object.
2339             */
2340            @Override
2341            public Type visitTypeVar(TypeVar t, Void ignored) {
2342                if (t.bound.hasTag(TYPEVAR) ||
2343                    (!t.bound.isCompound() && !t.bound.isInterface())) {
2344                    return t.bound;
2345                } else {
2346                    return supertype(t.bound);
2347                }
2348            }
2349
2350            @Override
2351            public Type visitArrayType(ArrayType t, Void ignored) {
2352                if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2353                    return arraySuperType();
2354                else
2355                    return new ArrayType(supertype(t.elemtype), t.tsym);
2356            }
2357
2358            @Override
2359            public Type visitErrorType(ErrorType t, Void ignored) {
2360                return Type.noType;
2361            }
2362        };
2363    // </editor-fold>
2364
2365    // <editor-fold defaultstate="collapsed" desc="interfaces">
2366    /**
2367     * Return the interfaces implemented by this class.
2368     */
2369    public List<Type> interfaces(Type t) {
2370        return interfaces.visit(t);
2371    }
2372    // where
2373        private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2374
2375            public List<Type> visitType(Type t, Void ignored) {
2376                return List.nil();
2377            }
2378
2379            @Override
2380            public List<Type> visitClassType(ClassType t, Void ignored) {
2381                if (t.interfaces_field == null) {
2382                    List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2383                    if (t.interfaces_field == null) {
2384                        // If t.interfaces_field is null, then t must
2385                        // be a parameterized type (not to be confused
2386                        // with a generic type declaration).
2387                        // Terminology:
2388                        //    Parameterized type: List<String>
2389                        //    Generic type declaration: class List<E> { ... }
2390                        // So t corresponds to List<String> and
2391                        // t.tsym.type corresponds to List<E>.
2392                        // The reason t must be parameterized type is
2393                        // that completion will happen as a side
2394                        // effect of calling
2395                        // ClassSymbol.getInterfaces.  Since
2396                        // t.interfaces_field is null after
2397                        // completion, we can assume that t is not the
2398                        // type of a class/interface declaration.
2399                        Assert.check(t != t.tsym.type, t);
2400                        List<Type> actuals = t.allparams();
2401                        List<Type> formals = t.tsym.type.allparams();
2402                        if (t.hasErasedSupertypes()) {
2403                            t.interfaces_field = erasureRecursive(interfaces);
2404                        } else if (formals.nonEmpty()) {
2405                            t.interfaces_field = subst(interfaces, formals, actuals);
2406                        }
2407                        else {
2408                            t.interfaces_field = interfaces;
2409                        }
2410                    }
2411                }
2412                return t.interfaces_field;
2413            }
2414
2415            @Override
2416            public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2417                if (t.bound.isCompound())
2418                    return interfaces(t.bound);
2419
2420                if (t.bound.isInterface())
2421                    return List.of(t.bound);
2422
2423                return List.nil();
2424            }
2425        };
2426
2427    public List<Type> directSupertypes(Type t) {
2428        return directSupertypes.visit(t);
2429    }
2430    // where
2431        private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
2432
2433            public List<Type> visitType(final Type type, final Void ignored) {
2434                if (!type.isIntersection()) {
2435                    final Type sup = supertype(type);
2436                    return (sup == Type.noType || sup == type || sup == null)
2437                        ? interfaces(type)
2438                        : interfaces(type).prepend(sup);
2439                } else {
2440                    return visitIntersectionType((IntersectionClassType) type);
2441                }
2442            }
2443
2444            private List<Type> visitIntersectionType(final IntersectionClassType it) {
2445                return it.getExplicitComponents();
2446            }
2447
2448        };
2449
2450    public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
2451        for (Type i2 : interfaces(origin.type)) {
2452            if (isym == i2.tsym) return true;
2453        }
2454        return false;
2455    }
2456    // </editor-fold>
2457
2458    // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2459    Map<Type,Boolean> isDerivedRawCache = new HashMap<>();
2460
2461    public boolean isDerivedRaw(Type t) {
2462        Boolean result = isDerivedRawCache.get(t);
2463        if (result == null) {
2464            result = isDerivedRawInternal(t);
2465            isDerivedRawCache.put(t, result);
2466        }
2467        return result;
2468    }
2469
2470    public boolean isDerivedRawInternal(Type t) {
2471        if (t.isErroneous())
2472            return false;
2473        return
2474            t.isRaw() ||
2475            supertype(t) != Type.noType && isDerivedRaw(supertype(t)) ||
2476            isDerivedRaw(interfaces(t));
2477    }
2478
2479    public boolean isDerivedRaw(List<Type> ts) {
2480        List<Type> l = ts;
2481        while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2482        return l.nonEmpty();
2483    }
2484    // </editor-fold>
2485
2486    // <editor-fold defaultstate="collapsed" desc="setBounds">
2487    /**
2488     * Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly,
2489     * as follows: if all all bounds are interface types, the computed supertype is Object,otherwise
2490     * the supertype is simply left null (in this case, the supertype is assumed to be the head of
2491     * the bound list passed as second argument). Note that this check might cause a symbol completion.
2492     * Hence, this version of setBounds may not be called during a classfile read.
2493     *
2494     * @param t         a type variable
2495     * @param bounds    the bounds, must be nonempty
2496     */
2497    public void setBounds(TypeVar t, List<Type> bounds) {
2498        setBounds(t, bounds, bounds.head.tsym.isInterface());
2499    }
2500
2501    /**
2502     * Set the bounds field of the given type variable to reflect a (possibly multiple) list of bounds.
2503     * This does not cause symbol completion as an extra parameter indicates as to whether all bounds
2504     * are interfaces - in which case the supertype is implicitly assumed to be 'Object'.
2505     *
2506     * @param t             a type variable
2507     * @param bounds        the bounds, must be nonempty
2508     * @param allInterfaces are all bounds interface types?
2509     */
2510    public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
2511        t.bound = bounds.tail.isEmpty() ?
2512                bounds.head :
2513                makeIntersectionType(bounds, allInterfaces);
2514        t.rank_field = -1;
2515    }
2516    // </editor-fold>
2517
2518    // <editor-fold defaultstate="collapsed" desc="getBounds">
2519    /**
2520     * Return list of bounds of the given type variable.
2521     */
2522    public List<Type> getBounds(TypeVar t) {
2523        if (t.bound.hasTag(NONE))
2524            return List.nil();
2525        else if (t.bound.isErroneous() || !t.bound.isCompound())
2526            return List.of(t.bound);
2527        else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2528            return interfaces(t).prepend(supertype(t));
2529        else
2530            // No superclass was given in bounds.
2531            // In this case, supertype is Object, erasure is first interface.
2532            return interfaces(t);
2533    }
2534    // </editor-fold>
2535
2536    // <editor-fold defaultstate="collapsed" desc="classBound">
2537    /**
2538     * If the given type is a (possibly selected) type variable,
2539     * return the bounding class of this type, otherwise return the
2540     * type itself.
2541     */
2542    public Type classBound(Type t) {
2543        return classBound.visit(t);
2544    }
2545    // where
2546        private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2547
2548            public Type visitType(Type t, Void ignored) {
2549                return t;
2550            }
2551
2552            @Override
2553            public Type visitClassType(ClassType t, Void ignored) {
2554                Type outer1 = classBound(t.getEnclosingType());
2555                if (outer1 != t.getEnclosingType())
2556                    return new ClassType(outer1, t.getTypeArguments(), t.tsym,
2557                                         t.getMetadata());
2558                else
2559                    return t;
2560            }
2561
2562            @Override
2563            public Type visitTypeVar(TypeVar t, Void ignored) {
2564                return classBound(supertype(t));
2565            }
2566
2567            @Override
2568            public Type visitErrorType(ErrorType t, Void ignored) {
2569                return t;
2570            }
2571        };
2572    // </editor-fold>
2573
2574    // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
2575    /**
2576     * Returns true iff the first signature is a <em>sub
2577     * signature</em> of the other.  This is <b>not</b> an equivalence
2578     * relation.
2579     *
2580     * @jls section 8.4.2.
2581     * @see #overrideEquivalent(Type t, Type s)
2582     * @param t first signature (possibly raw).
2583     * @param s second signature (could be subjected to erasure).
2584     * @return true if t is a sub signature of s.
2585     */
2586    public boolean isSubSignature(Type t, Type s) {
2587        return isSubSignature(t, s, true);
2588    }
2589
2590    public boolean isSubSignature(Type t, Type s, boolean strict) {
2591        return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2592    }
2593
2594    /**
2595     * Returns true iff these signatures are related by <em>override
2596     * equivalence</em>.  This is the natural extension of
2597     * isSubSignature to an equivalence relation.
2598     *
2599     * @jls section 8.4.2.
2600     * @see #isSubSignature(Type t, Type s)
2601     * @param t a signature (possible raw, could be subjected to
2602     * erasure).
2603     * @param s a signature (possible raw, could be subjected to
2604     * erasure).
2605     * @return true if either argument is a sub signature of the other.
2606     */
2607    public boolean overrideEquivalent(Type t, Type s) {
2608        return hasSameArgs(t, s) ||
2609            hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2610    }
2611
2612    public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2613        for (Symbol sym : syms.objectType.tsym.members().getSymbolsByName(msym.name)) {
2614            if (msym.overrides(sym, origin, Types.this, true)) {
2615                return true;
2616            }
2617        }
2618        return false;
2619    }
2620
2621    // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2622    class ImplementationCache {
2623
2624        private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<>();
2625
2626        class Entry {
2627            final MethodSymbol cachedImpl;
2628            final Filter<Symbol> implFilter;
2629            final boolean checkResult;
2630            final int prevMark;
2631
2632            public Entry(MethodSymbol cachedImpl,
2633                    Filter<Symbol> scopeFilter,
2634                    boolean checkResult,
2635                    int prevMark) {
2636                this.cachedImpl = cachedImpl;
2637                this.implFilter = scopeFilter;
2638                this.checkResult = checkResult;
2639                this.prevMark = prevMark;
2640            }
2641
2642            boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2643                return this.implFilter == scopeFilter &&
2644                        this.checkResult == checkResult &&
2645                        this.prevMark == mark;
2646            }
2647        }
2648
2649        MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2650            SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2651            Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2652            if (cache == null) {
2653                cache = new HashMap<>();
2654                _map.put(ms, new SoftReference<>(cache));
2655            }
2656            Entry e = cache.get(origin);
2657            CompoundScope members = membersClosure(origin.type, true);
2658            if (e == null ||
2659                    !e.matches(implFilter, checkResult, members.getMark())) {
2660                MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2661                cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2662                return impl;
2663            }
2664            else {
2665                return e.cachedImpl;
2666            }
2667        }
2668
2669        private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2670            for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
2671                t = skipTypeVars(t, false);
2672                TypeSymbol c = t.tsym;
2673                Symbol bestSoFar = null;
2674                for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) {
2675                    if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) {
2676                        bestSoFar = sym;
2677                        if ((sym.flags() & ABSTRACT) == 0) {
2678                            //if concrete impl is found, exit immediately
2679                            break;
2680                        }
2681                    }
2682                }
2683                if (bestSoFar != null) {
2684                    //return either the (only) concrete implementation or the first abstract one
2685                    return (MethodSymbol)bestSoFar;
2686                }
2687            }
2688            return null;
2689        }
2690    }
2691
2692    private ImplementationCache implCache = new ImplementationCache();
2693
2694    public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2695        return implCache.get(ms, origin, checkResult, implFilter);
2696    }
2697    // </editor-fold>
2698
2699    // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2700    class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
2701
2702        private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>();
2703
2704        class Entry {
2705            final boolean skipInterfaces;
2706            final CompoundScope compoundScope;
2707
2708            public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
2709                this.skipInterfaces = skipInterfaces;
2710                this.compoundScope = compoundScope;
2711            }
2712
2713            boolean matches(boolean skipInterfaces) {
2714                return this.skipInterfaces == skipInterfaces;
2715            }
2716        }
2717
2718        List<TypeSymbol> seenTypes = List.nil();
2719
2720        /** members closure visitor methods **/
2721
2722        public CompoundScope visitType(Type t, Boolean skipInterface) {
2723            return null;
2724        }
2725
2726        @Override
2727        public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
2728            if (seenTypes.contains(t.tsym)) {
2729                //this is possible when an interface is implemented in multiple
2730                //superclasses, or when a classs hierarchy is circular - in such
2731                //cases we don't need to recurse (empty scope is returned)
2732                return new CompoundScope(t.tsym);
2733            }
2734            try {
2735                seenTypes = seenTypes.prepend(t.tsym);
2736                ClassSymbol csym = (ClassSymbol)t.tsym;
2737                Entry e = _map.get(csym);
2738                if (e == null || !e.matches(skipInterface)) {
2739                    CompoundScope membersClosure = new CompoundScope(csym);
2740                    if (!skipInterface) {
2741                        for (Type i : interfaces(t)) {
2742                            membersClosure.prependSubScope(visit(i, skipInterface));
2743                        }
2744                    }
2745                    membersClosure.prependSubScope(visit(supertype(t), skipInterface));
2746                    membersClosure.prependSubScope(csym.members());
2747                    e = new Entry(skipInterface, membersClosure);
2748                    _map.put(csym, e);
2749                }
2750                return e.compoundScope;
2751            }
2752            finally {
2753                seenTypes = seenTypes.tail;
2754            }
2755        }
2756
2757        @Override
2758        public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
2759            return visit(t.getUpperBound(), skipInterface);
2760        }
2761    }
2762
2763    private MembersClosureCache membersCache = new MembersClosureCache();
2764
2765    public CompoundScope membersClosure(Type site, boolean skipInterface) {
2766        return membersCache.visit(site, skipInterface);
2767    }
2768    // </editor-fold>
2769
2770
2771    /** Return first abstract member of class `sym'.
2772     */
2773    public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) {
2774        try {
2775            return firstUnimplementedAbstractImpl(sym, sym);
2776        } catch (CompletionFailure ex) {
2777            chk.completionError(enter.getEnv(sym).tree.pos(), ex);
2778            return null;
2779        }
2780    }
2781        //where:
2782        private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) {
2783            MethodSymbol undef = null;
2784            // Do not bother to search in classes that are not abstract,
2785            // since they cannot have abstract members.
2786            if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2787                Scope s = c.members();
2788                for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
2789                    if (sym.kind == MTH &&
2790                        (sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
2791                        MethodSymbol absmeth = (MethodSymbol)sym;
2792                        MethodSymbol implmeth = absmeth.implementation(impl, this, true);
2793                        if (implmeth == null || implmeth == absmeth) {
2794                            //look for default implementations
2795                            if (allowDefaultMethods) {
2796                                MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head;
2797                                if (prov != null && prov.overrides(absmeth, impl, this, true)) {
2798                                    implmeth = prov;
2799                                }
2800                            }
2801                        }
2802                        if (implmeth == null || implmeth == absmeth) {
2803                            undef = absmeth;
2804                            break;
2805                        }
2806                    }
2807                }
2808                if (undef == null) {
2809                    Type st = supertype(c.type);
2810                    if (st.hasTag(CLASS))
2811                        undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym);
2812                }
2813                for (List<Type> l = interfaces(c.type);
2814                     undef == null && l.nonEmpty();
2815                     l = l.tail) {
2816                    undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym);
2817                }
2818            }
2819            return undef;
2820        }
2821
2822
2823    //where
2824    public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
2825        Filter<Symbol> filter = new MethodFilter(ms, site);
2826        List<MethodSymbol> candidates = List.nil();
2827            for (Symbol s : membersClosure(site, false).getSymbols(filter)) {
2828                if (!site.tsym.isInterface() && !s.owner.isInterface()) {
2829                    return List.of((MethodSymbol)s);
2830                } else if (!candidates.contains(s)) {
2831                    candidates = candidates.prepend((MethodSymbol)s);
2832                }
2833            }
2834            return prune(candidates);
2835        }
2836
2837    public List<MethodSymbol> prune(List<MethodSymbol> methods) {
2838        ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
2839        for (MethodSymbol m1 : methods) {
2840            boolean isMin_m1 = true;
2841            for (MethodSymbol m2 : methods) {
2842                if (m1 == m2) continue;
2843                if (m2.owner != m1.owner &&
2844                        asSuper(m2.owner.type, m1.owner) != null) {
2845                    isMin_m1 = false;
2846                    break;
2847                }
2848            }
2849            if (isMin_m1)
2850                methodsMin.append(m1);
2851        }
2852        return methodsMin.toList();
2853    }
2854    // where
2855            private class MethodFilter implements Filter<Symbol> {
2856
2857                Symbol msym;
2858                Type site;
2859
2860                MethodFilter(Symbol msym, Type site) {
2861                    this.msym = msym;
2862                    this.site = site;
2863                }
2864
2865                public boolean accepts(Symbol s) {
2866                    return s.kind == MTH &&
2867                            s.name == msym.name &&
2868                            (s.flags() & SYNTHETIC) == 0 &&
2869                            s.isInheritedIn(site.tsym, Types.this) &&
2870                            overrideEquivalent(memberType(site, s), memberType(site, msym));
2871                }
2872            }
2873    // </editor-fold>
2874
2875    /**
2876     * Does t have the same arguments as s?  It is assumed that both
2877     * types are (possibly polymorphic) method types.  Monomorphic
2878     * method types "have the same arguments", if their argument lists
2879     * are equal.  Polymorphic method types "have the same arguments",
2880     * if they have the same arguments after renaming all type
2881     * variables of one to corresponding type variables in the other,
2882     * where correspondence is by position in the type parameter list.
2883     */
2884    public boolean hasSameArgs(Type t, Type s) {
2885        return hasSameArgs(t, s, true);
2886    }
2887
2888    public boolean hasSameArgs(Type t, Type s, boolean strict) {
2889        return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2890    }
2891
2892    private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2893        return hasSameArgs.visit(t, s);
2894    }
2895    // where
2896        private class HasSameArgs extends TypeRelation {
2897
2898            boolean strict;
2899
2900            public HasSameArgs(boolean strict) {
2901                this.strict = strict;
2902            }
2903
2904            public Boolean visitType(Type t, Type s) {
2905                throw new AssertionError();
2906            }
2907
2908            @Override
2909            public Boolean visitMethodType(MethodType t, Type s) {
2910                return s.hasTag(METHOD)
2911                    && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2912            }
2913
2914            @Override
2915            public Boolean visitForAll(ForAll t, Type s) {
2916                if (!s.hasTag(FORALL))
2917                    return strict ? false : visitMethodType(t.asMethodType(), s);
2918
2919                ForAll forAll = (ForAll)s;
2920                return hasSameBounds(t, forAll)
2921                    && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2922            }
2923
2924            @Override
2925            public Boolean visitErrorType(ErrorType t, Type s) {
2926                return false;
2927            }
2928        }
2929
2930    TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2931        TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2932
2933    // </editor-fold>
2934
2935    // <editor-fold defaultstate="collapsed" desc="subst">
2936    public List<Type> subst(List<Type> ts,
2937                            List<Type> from,
2938                            List<Type> to) {
2939        return new Subst(from, to).subst(ts);
2940    }
2941
2942    /**
2943     * Substitute all occurrences of a type in `from' with the
2944     * corresponding type in `to' in 't'. Match lists `from' and `to'
2945     * from the right: If lists have different length, discard leading
2946     * elements of the longer list.
2947     */
2948    public Type subst(Type t, List<Type> from, List<Type> to) {
2949        return new Subst(from, to).subst(t);
2950    }
2951
2952    private class Subst extends UnaryVisitor<Type> {
2953        List<Type> from;
2954        List<Type> to;
2955
2956        public Subst(List<Type> from, List<Type> to) {
2957            int fromLength = from.length();
2958            int toLength = to.length();
2959            while (fromLength > toLength) {
2960                fromLength--;
2961                from = from.tail;
2962            }
2963            while (fromLength < toLength) {
2964                toLength--;
2965                to = to.tail;
2966            }
2967            this.from = from;
2968            this.to = to;
2969        }
2970
2971        Type subst(Type t) {
2972            if (from.tail == null)
2973                return t;
2974            else
2975                return visit(t);
2976            }
2977
2978        List<Type> subst(List<Type> ts) {
2979            if (from.tail == null)
2980                return ts;
2981            boolean wild = false;
2982            if (ts.nonEmpty() && from.nonEmpty()) {
2983                Type head1 = subst(ts.head);
2984                List<Type> tail1 = subst(ts.tail);
2985                if (head1 != ts.head || tail1 != ts.tail)
2986                    return tail1.prepend(head1);
2987            }
2988            return ts;
2989        }
2990
2991        public Type visitType(Type t, Void ignored) {
2992            return t;
2993        }
2994
2995        @Override
2996        public Type visitMethodType(MethodType t, Void ignored) {
2997            List<Type> argtypes = subst(t.argtypes);
2998            Type restype = subst(t.restype);
2999            List<Type> thrown = subst(t.thrown);
3000            if (argtypes == t.argtypes &&
3001                restype == t.restype &&
3002                thrown == t.thrown)
3003                return t;
3004            else
3005                return new MethodType(argtypes, restype, thrown, t.tsym);
3006        }
3007
3008        @Override
3009        public Type visitTypeVar(TypeVar t, Void ignored) {
3010            for (List<Type> from = this.from, to = this.to;
3011                 from.nonEmpty();
3012                 from = from.tail, to = to.tail) {
3013                if (t == from.head) {
3014                    return to.head.withTypeVar(t);
3015                }
3016            }
3017            return t;
3018        }
3019
3020        @Override
3021        public Type visitUndetVar(UndetVar t, Void ignored) {
3022            //do nothing - we should not replace inside undet variables
3023            return t;
3024        }
3025
3026        @Override
3027        public Type visitClassType(ClassType t, Void ignored) {
3028            if (!t.isCompound()) {
3029                List<Type> typarams = t.getTypeArguments();
3030                List<Type> typarams1 = subst(typarams);
3031                Type outer = t.getEnclosingType();
3032                Type outer1 = subst(outer);
3033                if (typarams1 == typarams && outer1 == outer)
3034                    return t;
3035                else
3036                    return new ClassType(outer1, typarams1, t.tsym,
3037                                         t.getMetadata());
3038            } else {
3039                Type st = subst(supertype(t));
3040                List<Type> is = subst(interfaces(t));
3041                if (st == supertype(t) && is == interfaces(t))
3042                    return t;
3043                else
3044                    return makeIntersectionType(is.prepend(st));
3045            }
3046        }
3047
3048        @Override
3049        public Type visitWildcardType(WildcardType t, Void ignored) {
3050            Type bound = t.type;
3051            if (t.kind != BoundKind.UNBOUND)
3052                bound = subst(bound);
3053            if (bound == t.type) {
3054                return t;
3055            } else {
3056                if (t.isExtendsBound() && bound.isExtendsBound())
3057                    bound = wildUpperBound(bound);
3058                return new WildcardType(bound, t.kind, syms.boundClass,
3059                                        t.bound, t.getMetadata());
3060            }
3061        }
3062
3063        @Override
3064        public Type visitArrayType(ArrayType t, Void ignored) {
3065            Type elemtype = subst(t.elemtype);
3066            if (elemtype == t.elemtype)
3067                return t;
3068            else
3069                return new ArrayType(elemtype, t.tsym, t.getMetadata());
3070        }
3071
3072        @Override
3073        public Type visitForAll(ForAll t, Void ignored) {
3074            if (Type.containsAny(to, t.tvars)) {
3075                //perform alpha-renaming of free-variables in 't'
3076                //if 'to' types contain variables that are free in 't'
3077                List<Type> freevars = newInstances(t.tvars);
3078                t = new ForAll(freevars,
3079                               Types.this.subst(t.qtype, t.tvars, freevars));
3080            }
3081            List<Type> tvars1 = substBounds(t.tvars, from, to);
3082            Type qtype1 = subst(t.qtype);
3083            if (tvars1 == t.tvars && qtype1 == t.qtype) {
3084                return t;
3085            } else if (tvars1 == t.tvars) {
3086                return new ForAll(tvars1, qtype1);
3087            } else {
3088                return new ForAll(tvars1,
3089                                  Types.this.subst(qtype1, t.tvars, tvars1));
3090            }
3091        }
3092
3093        @Override
3094        public Type visitErrorType(ErrorType t, Void ignored) {
3095            return t;
3096        }
3097    }
3098
3099    public List<Type> substBounds(List<Type> tvars,
3100                                  List<Type> from,
3101                                  List<Type> to) {
3102        if (tvars.isEmpty())
3103            return tvars;
3104        ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
3105        boolean changed = false;
3106        // calculate new bounds
3107        for (Type t : tvars) {
3108            TypeVar tv = (TypeVar) t;
3109            Type bound = subst(tv.bound, from, to);
3110            if (bound != tv.bound)
3111                changed = true;
3112            newBoundsBuf.append(bound);
3113        }
3114        if (!changed)
3115            return tvars;
3116        ListBuffer<Type> newTvars = new ListBuffer<>();
3117        // create new type variables without bounds
3118        for (Type t : tvars) {
3119            newTvars.append(new TypeVar(t.tsym, null, syms.botType,
3120                                        t.getMetadata()));
3121        }
3122        // the new bounds should use the new type variables in place
3123        // of the old
3124        List<Type> newBounds = newBoundsBuf.toList();
3125        from = tvars;
3126        to = newTvars.toList();
3127        for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
3128            newBounds.head = subst(newBounds.head, from, to);
3129        }
3130        newBounds = newBoundsBuf.toList();
3131        // set the bounds of new type variables to the new bounds
3132        for (Type t : newTvars.toList()) {
3133            TypeVar tv = (TypeVar) t;
3134            tv.bound = newBounds.head;
3135            newBounds = newBounds.tail;
3136        }
3137        return newTvars.toList();
3138    }
3139
3140    public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
3141        Type bound1 = subst(t.bound, from, to);
3142        if (bound1 == t.bound)
3143            return t;
3144        else {
3145            // create new type variable without bounds
3146            TypeVar tv = new TypeVar(t.tsym, null, syms.botType,
3147                                     t.getMetadata());
3148            // the new bound should use the new type variable in place
3149            // of the old
3150            tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
3151            return tv;
3152        }
3153    }
3154    // </editor-fold>
3155
3156    // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
3157    /**
3158     * Does t have the same bounds for quantified variables as s?
3159     */
3160    public boolean hasSameBounds(ForAll t, ForAll s) {
3161        List<Type> l1 = t.tvars;
3162        List<Type> l2 = s.tvars;
3163        while (l1.nonEmpty() && l2.nonEmpty() &&
3164               isSameType(l1.head.getUpperBound(),
3165                          subst(l2.head.getUpperBound(),
3166                                s.tvars,
3167                                t.tvars))) {
3168            l1 = l1.tail;
3169            l2 = l2.tail;
3170        }
3171        return l1.isEmpty() && l2.isEmpty();
3172    }
3173    // </editor-fold>
3174
3175    // <editor-fold defaultstate="collapsed" desc="newInstances">
3176    /** Create new vector of type variables from list of variables
3177     *  changing all recursive bounds from old to new list.
3178     */
3179    public List<Type> newInstances(List<Type> tvars) {
3180        List<Type> tvars1 = Type.map(tvars, newInstanceFun);
3181        for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
3182            TypeVar tv = (TypeVar) l.head;
3183            tv.bound = subst(tv.bound, tvars, tvars1);
3184        }
3185        return tvars1;
3186    }
3187    private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
3188            public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound(), t.getMetadata()); }
3189        };
3190    // </editor-fold>
3191
3192    public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
3193        return original.accept(methodWithParameters, newParams);
3194    }
3195    // where
3196        private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
3197            public Type visitType(Type t, List<Type> newParams) {
3198                throw new IllegalArgumentException("Not a method type: " + t);
3199            }
3200            public Type visitMethodType(MethodType t, List<Type> newParams) {
3201                return new MethodType(newParams, t.restype, t.thrown, t.tsym);
3202            }
3203            public Type visitForAll(ForAll t, List<Type> newParams) {
3204                return new ForAll(t.tvars, t.qtype.accept(this, newParams));
3205            }
3206        };
3207
3208    public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
3209        return original.accept(methodWithThrown, newThrown);
3210    }
3211    // where
3212        private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
3213            public Type visitType(Type t, List<Type> newThrown) {
3214                throw new IllegalArgumentException("Not a method type: " + t);
3215            }
3216            public Type visitMethodType(MethodType t, List<Type> newThrown) {
3217                return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
3218            }
3219            public Type visitForAll(ForAll t, List<Type> newThrown) {
3220                return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
3221            }
3222        };
3223
3224    public Type createMethodTypeWithReturn(Type original, Type newReturn) {
3225        return original.accept(methodWithReturn, newReturn);
3226    }
3227    // where
3228        private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3229            public Type visitType(Type t, Type newReturn) {
3230                throw new IllegalArgumentException("Not a method type: " + t);
3231            }
3232            public Type visitMethodType(MethodType t, Type newReturn) {
3233                return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
3234            }
3235            public Type visitForAll(ForAll t, Type newReturn) {
3236                return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
3237            }
3238        };
3239
3240    // <editor-fold defaultstate="collapsed" desc="createErrorType">
3241    public Type createErrorType(Type originalType) {
3242        return new ErrorType(originalType, syms.errSymbol);
3243    }
3244
3245    public Type createErrorType(ClassSymbol c, Type originalType) {
3246        return new ErrorType(c, originalType);
3247    }
3248
3249    public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3250        return new ErrorType(name, container, originalType);
3251    }
3252    // </editor-fold>
3253
3254    // <editor-fold defaultstate="collapsed" desc="rank">
3255    /**
3256     * The rank of a class is the length of the longest path between
3257     * the class and java.lang.Object in the class inheritance
3258     * graph. Undefined for all but reference types.
3259     */
3260    public int rank(Type t) {
3261        switch(t.getTag()) {
3262        case CLASS: {
3263            ClassType cls = (ClassType)t;
3264            if (cls.rank_field < 0) {
3265                Name fullname = cls.tsym.getQualifiedName();
3266                if (fullname == names.java_lang_Object)
3267                    cls.rank_field = 0;
3268                else {
3269                    int r = rank(supertype(cls));
3270                    for (List<Type> l = interfaces(cls);
3271                         l.nonEmpty();
3272                         l = l.tail) {
3273                        if (rank(l.head) > r)
3274                            r = rank(l.head);
3275                    }
3276                    cls.rank_field = r + 1;
3277                }
3278            }
3279            return cls.rank_field;
3280        }
3281        case TYPEVAR: {
3282            TypeVar tvar = (TypeVar)t;
3283            if (tvar.rank_field < 0) {
3284                int r = rank(supertype(tvar));
3285                for (List<Type> l = interfaces(tvar);
3286                     l.nonEmpty();
3287                     l = l.tail) {
3288                    if (rank(l.head) > r) r = rank(l.head);
3289                }
3290                tvar.rank_field = r + 1;
3291            }
3292            return tvar.rank_field;
3293        }
3294        case ERROR:
3295        case NONE:
3296            return 0;
3297        default:
3298            throw new AssertionError();
3299        }
3300    }
3301    // </editor-fold>
3302
3303    /**
3304     * Helper method for generating a string representation of a given type
3305     * accordingly to a given locale
3306     */
3307    public String toString(Type t, Locale locale) {
3308        return Printer.createStandardPrinter(messages).visit(t, locale);
3309    }
3310
3311    /**
3312     * Helper method for generating a string representation of a given type
3313     * accordingly to a given locale
3314     */
3315    public String toString(Symbol t, Locale locale) {
3316        return Printer.createStandardPrinter(messages).visit(t, locale);
3317    }
3318
3319    // <editor-fold defaultstate="collapsed" desc="toString">
3320    /**
3321     * This toString is slightly more descriptive than the one on Type.
3322     *
3323     * @deprecated Types.toString(Type t, Locale l) provides better support
3324     * for localization
3325     */
3326    @Deprecated
3327    public String toString(Type t) {
3328        if (t.hasTag(FORALL)) {
3329            ForAll forAll = (ForAll)t;
3330            return typaramsString(forAll.tvars) + forAll.qtype;
3331        }
3332        return "" + t;
3333    }
3334    // where
3335        private String typaramsString(List<Type> tvars) {
3336            StringBuilder s = new StringBuilder();
3337            s.append('<');
3338            boolean first = true;
3339            for (Type t : tvars) {
3340                if (!first) s.append(", ");
3341                first = false;
3342                appendTyparamString(((TypeVar)t), s);
3343            }
3344            s.append('>');
3345            return s.toString();
3346        }
3347        private void appendTyparamString(TypeVar t, StringBuilder buf) {
3348            buf.append(t);
3349            if (t.bound == null ||
3350                t.bound.tsym.getQualifiedName() == names.java_lang_Object)
3351                return;
3352            buf.append(" extends "); // Java syntax; no need for i18n
3353            Type bound = t.bound;
3354            if (!bound.isCompound()) {
3355                buf.append(bound);
3356            } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3357                buf.append(supertype(t));
3358                for (Type intf : interfaces(t)) {
3359                    buf.append('&');
3360                    buf.append(intf);
3361                }
3362            } else {
3363                // No superclass was given in bounds.
3364                // In this case, supertype is Object, erasure is first interface.
3365                boolean first = true;
3366                for (Type intf : interfaces(t)) {
3367                    if (!first) buf.append('&');
3368                    first = false;
3369                    buf.append(intf);
3370                }
3371            }
3372        }
3373    // </editor-fold>
3374
3375    // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3376    /**
3377     * A cache for closures.
3378     *
3379     * <p>A closure is a list of all the supertypes and interfaces of
3380     * a class or interface type, ordered by ClassSymbol.precedes
3381     * (that is, subclasses come first, arbitrary but fixed
3382     * otherwise).
3383     */
3384    private Map<Type,List<Type>> closureCache = new HashMap<>();
3385
3386    /**
3387     * Returns the closure of a class or interface type.
3388     */
3389    public List<Type> closure(Type t) {
3390        List<Type> cl = closureCache.get(t);
3391        if (cl == null) {
3392            Type st = supertype(t);
3393            if (!t.isCompound()) {
3394                if (st.hasTag(CLASS)) {
3395                    cl = insert(closure(st), t);
3396                } else if (st.hasTag(TYPEVAR)) {
3397                    cl = closure(st).prepend(t);
3398                } else {
3399                    cl = List.of(t);
3400                }
3401            } else {
3402                cl = closure(supertype(t));
3403            }
3404            for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3405                cl = union(cl, closure(l.head));
3406            closureCache.put(t, cl);
3407        }
3408        return cl;
3409    }
3410
3411    /**
3412     * Insert a type in a closure
3413     */
3414    public List<Type> insert(List<Type> cl, Type t) {
3415        if (cl.isEmpty()) {
3416            return cl.prepend(t);
3417        } else if (t.tsym == cl.head.tsym) {
3418            return cl;
3419        } else if (t.tsym.precedes(cl.head.tsym, this)) {
3420            return cl.prepend(t);
3421        } else {
3422            // t comes after head, or the two are unrelated
3423            return insert(cl.tail, t).prepend(cl.head);
3424        }
3425    }
3426
3427    /**
3428     * Form the union of two closures
3429     */
3430    public List<Type> union(List<Type> cl1, List<Type> cl2) {
3431        if (cl1.isEmpty()) {
3432            return cl2;
3433        } else if (cl2.isEmpty()) {
3434            return cl1;
3435        } else if (cl1.head.tsym == cl2.head.tsym) {
3436            return union(cl1.tail, cl2.tail).prepend(cl1.head);
3437        } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3438            return union(cl1.tail, cl2).prepend(cl1.head);
3439        } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3440            return union(cl1, cl2.tail).prepend(cl2.head);
3441        } else {
3442            // unrelated types
3443            return union(cl1.tail, cl2).prepend(cl1.head);
3444        }
3445    }
3446
3447    /**
3448     * Intersect two closures
3449     */
3450    public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3451        if (cl1 == cl2)
3452            return cl1;
3453        if (cl1.isEmpty() || cl2.isEmpty())
3454            return List.nil();
3455        if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3456            return intersect(cl1.tail, cl2);
3457        if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3458            return intersect(cl1, cl2.tail);
3459        if (isSameType(cl1.head, cl2.head))
3460            return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3461        if (cl1.head.tsym == cl2.head.tsym &&
3462            cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
3463            if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3464                Type merge = merge(cl1.head,cl2.head);
3465                return intersect(cl1.tail, cl2.tail).prepend(merge);
3466            }
3467            if (cl1.head.isRaw() || cl2.head.isRaw())
3468                return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3469        }
3470        return intersect(cl1.tail, cl2.tail);
3471    }
3472    // where
3473        class TypePair {
3474            final Type t1;
3475            final Type t2;
3476            boolean strict;
3477
3478            TypePair(Type t1, Type t2) {
3479                this(t1, t2, false);
3480            }
3481
3482            TypePair(Type t1, Type t2, boolean strict) {
3483                this.t1 = t1;
3484                this.t2 = t2;
3485                this.strict = strict;
3486            }
3487            @Override
3488            public int hashCode() {
3489                return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3490            }
3491            @Override
3492            public boolean equals(Object obj) {
3493                if (!(obj instanceof TypePair))
3494                    return false;
3495                TypePair typePair = (TypePair)obj;
3496                return isSameType(t1, typePair.t1, strict)
3497                    && isSameType(t2, typePair.t2, strict);
3498            }
3499        }
3500        Set<TypePair> mergeCache = new HashSet<>();
3501        private Type merge(Type c1, Type c2) {
3502            ClassType class1 = (ClassType) c1;
3503            List<Type> act1 = class1.getTypeArguments();
3504            ClassType class2 = (ClassType) c2;
3505            List<Type> act2 = class2.getTypeArguments();
3506            ListBuffer<Type> merged = new ListBuffer<>();
3507            List<Type> typarams = class1.tsym.type.getTypeArguments();
3508
3509            while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3510                if (containsType(act1.head, act2.head)) {
3511                    merged.append(act1.head);
3512                } else if (containsType(act2.head, act1.head)) {
3513                    merged.append(act2.head);
3514                } else {
3515                    TypePair pair = new TypePair(c1, c2);
3516                    Type m;
3517                    if (mergeCache.add(pair)) {
3518                        m = new WildcardType(lub(wildUpperBound(act1.head),
3519                                                 wildUpperBound(act2.head)),
3520                                             BoundKind.EXTENDS,
3521                                             syms.boundClass);
3522                        mergeCache.remove(pair);
3523                    } else {
3524                        m = new WildcardType(syms.objectType,
3525                                             BoundKind.UNBOUND,
3526                                             syms.boundClass);
3527                    }
3528                    merged.append(m.withTypeVar(typarams.head));
3529                }
3530                act1 = act1.tail;
3531                act2 = act2.tail;
3532                typarams = typarams.tail;
3533            }
3534            Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3535            // There is no spec detailing how type annotations are to
3536            // be inherited.  So set it to noAnnotations for now
3537            return new ClassType(class1.getEnclosingType(), merged.toList(),
3538                                 class1.tsym);
3539        }
3540
3541    /**
3542     * Return the minimum type of a closure, a compound type if no
3543     * unique minimum exists.
3544     */
3545    private Type compoundMin(List<Type> cl) {
3546        if (cl.isEmpty()) return syms.objectType;
3547        List<Type> compound = closureMin(cl);
3548        if (compound.isEmpty())
3549            return null;
3550        else if (compound.tail.isEmpty())
3551            return compound.head;
3552        else
3553            return makeIntersectionType(compound);
3554    }
3555
3556    /**
3557     * Return the minimum types of a closure, suitable for computing
3558     * compoundMin or glb.
3559     */
3560    private List<Type> closureMin(List<Type> cl) {
3561        ListBuffer<Type> classes = new ListBuffer<>();
3562        ListBuffer<Type> interfaces = new ListBuffer<>();
3563        Set<Type> toSkip = new HashSet<>();
3564        while (!cl.isEmpty()) {
3565            Type current = cl.head;
3566            boolean keep = !toSkip.contains(current);
3567            if (keep && current.hasTag(TYPEVAR)) {
3568                // skip lower-bounded variables with a subtype in cl.tail
3569                for (Type t : cl.tail) {
3570                    if (isSubtypeNoCapture(t, current)) {
3571                        keep = false;
3572                        break;
3573                    }
3574                }
3575            }
3576            if (keep) {
3577                if (current.isInterface())
3578                    interfaces.append(current);
3579                else
3580                    classes.append(current);
3581                for (Type t : cl.tail) {
3582                    // skip supertypes of 'current' in cl.tail
3583                    if (isSubtypeNoCapture(current, t))
3584                        toSkip.add(t);
3585                }
3586            }
3587            cl = cl.tail;
3588        }
3589        return classes.appendList(interfaces).toList();
3590    }
3591
3592    /**
3593     * Return the least upper bound of list of types.  if the lub does
3594     * not exist return null.
3595     */
3596    public Type lub(List<Type> ts) {
3597        return lub(ts.toArray(new Type[ts.length()]));
3598    }
3599
3600    /**
3601     * Return the least upper bound (lub) of set of types.  If the lub
3602     * does not exist return the type of null (bottom).
3603     */
3604    public Type lub(Type... ts) {
3605        final int UNKNOWN_BOUND = 0;
3606        final int ARRAY_BOUND = 1;
3607        final int CLASS_BOUND = 2;
3608
3609        int[] kinds = new int[ts.length];
3610
3611        int boundkind = UNKNOWN_BOUND;
3612        for (int i = 0 ; i < ts.length ; i++) {
3613            Type t = ts[i];
3614            switch (t.getTag()) {
3615            case CLASS:
3616                boundkind |= kinds[i] = CLASS_BOUND;
3617                break;
3618            case ARRAY:
3619                boundkind |= kinds[i] = ARRAY_BOUND;
3620                break;
3621            case  TYPEVAR:
3622                do {
3623                    t = t.getUpperBound();
3624                } while (t.hasTag(TYPEVAR));
3625                if (t.hasTag(ARRAY)) {
3626                    boundkind |= kinds[i] = ARRAY_BOUND;
3627                } else {
3628                    boundkind |= kinds[i] = CLASS_BOUND;
3629                }
3630                break;
3631            default:
3632                kinds[i] = UNKNOWN_BOUND;
3633                if (t.isPrimitive())
3634                    return syms.errType;
3635            }
3636        }
3637        switch (boundkind) {
3638        case 0:
3639            return syms.botType;
3640
3641        case ARRAY_BOUND:
3642            // calculate lub(A[], B[])
3643            Type[] elements = new Type[ts.length];
3644            for (int i = 0 ; i < ts.length ; i++) {
3645                Type elem = elements[i] = elemTypeFun.apply(ts[i]);
3646                if (elem.isPrimitive()) {
3647                    // if a primitive type is found, then return
3648                    // arraySuperType unless all the types are the
3649                    // same
3650                    Type first = ts[0];
3651                    for (int j = 1 ; j < ts.length ; j++) {
3652                        if (!isSameType(first, ts[j])) {
3653                             // lub(int[], B[]) is Cloneable & Serializable
3654                            return arraySuperType();
3655                        }
3656                    }
3657                    // all the array types are the same, return one
3658                    // lub(int[], int[]) is int[]
3659                    return first;
3660                }
3661            }
3662            // lub(A[], B[]) is lub(A, B)[]
3663            return new ArrayType(lub(elements), syms.arrayClass);
3664
3665        case CLASS_BOUND:
3666            // calculate lub(A, B)
3667            int startIdx = 0;
3668            for (int i = 0; i < ts.length ; i++) {
3669                Type t = ts[i];
3670                if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) {
3671                    break;
3672                } else {
3673                    startIdx++;
3674                }
3675            }
3676            Assert.check(startIdx < ts.length);
3677            //step 1 - compute erased candidate set (EC)
3678            List<Type> cl = erasedSupertypes(ts[startIdx]);
3679            for (int i = startIdx + 1 ; i < ts.length ; i++) {
3680                Type t = ts[i];
3681                if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
3682                    cl = intersect(cl, erasedSupertypes(t));
3683            }
3684            //step 2 - compute minimal erased candidate set (MEC)
3685            List<Type> mec = closureMin(cl);
3686            //step 3 - for each element G in MEC, compute lci(Inv(G))
3687            List<Type> candidates = List.nil();
3688            for (Type erasedSupertype : mec) {
3689                List<Type> lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym));
3690                for (int i = startIdx + 1 ; i < ts.length ; i++) {
3691                    Type superType = asSuper(ts[i], erasedSupertype.tsym);
3692                    lci = intersect(lci, superType != null ? List.of(superType) : List.<Type>nil());
3693                }
3694                candidates = candidates.appendList(lci);
3695            }
3696            //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3697            //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3698            return compoundMin(candidates);
3699
3700        default:
3701            // calculate lub(A, B[])
3702            List<Type> classes = List.of(arraySuperType());
3703            for (int i = 0 ; i < ts.length ; i++) {
3704                if (kinds[i] != ARRAY_BOUND) // Filter out any arrays
3705                    classes = classes.prepend(ts[i]);
3706            }
3707            // lub(A, B[]) is lub(A, arraySuperType)
3708            return lub(classes);
3709        }
3710    }
3711    // where
3712        List<Type> erasedSupertypes(Type t) {
3713            ListBuffer<Type> buf = new ListBuffer<>();
3714            for (Type sup : closure(t)) {
3715                if (sup.hasTag(TYPEVAR)) {
3716                    buf.append(sup);
3717                } else {
3718                    buf.append(erasure(sup));
3719                }
3720            }
3721            return buf.toList();
3722        }
3723
3724        private Type arraySuperType = null;
3725        private Type arraySuperType() {
3726            // initialized lazily to avoid problems during compiler startup
3727            if (arraySuperType == null) {
3728                synchronized (this) {
3729                    if (arraySuperType == null) {
3730                        // JLS 10.8: all arrays implement Cloneable and Serializable.
3731                        arraySuperType = makeIntersectionType(List.of(syms.serializableType,
3732                                syms.cloneableType), true);
3733                    }
3734                }
3735            }
3736            return arraySuperType;
3737        }
3738    // </editor-fold>
3739
3740    // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3741    public Type glb(List<Type> ts) {
3742        Type t1 = ts.head;
3743        for (Type t2 : ts.tail) {
3744            if (t1.isErroneous())
3745                return t1;
3746            t1 = glb(t1, t2);
3747        }
3748        return t1;
3749    }
3750    //where
3751    public Type glb(Type t, Type s) {
3752        if (s == null)
3753            return t;
3754        else if (t.isPrimitive() || s.isPrimitive())
3755            return syms.errType;
3756        else if (isSubtypeNoCapture(t, s))
3757            return t;
3758        else if (isSubtypeNoCapture(s, t))
3759            return s;
3760
3761        List<Type> closure = union(closure(t), closure(s));
3762        return glbFlattened(closure, t);
3763    }
3764    //where
3765    /**
3766     * Perform glb for a list of non-primitive, non-error, non-compound types;
3767     * redundant elements are removed.  Bounds should be ordered according to
3768     * {@link Symbol#precedes(TypeSymbol,Types)}.
3769     *
3770     * @param flatBounds List of type to glb
3771     * @param errT Original type to use if the result is an error type
3772     */
3773    private Type glbFlattened(List<Type> flatBounds, Type errT) {
3774        List<Type> bounds = closureMin(flatBounds);
3775
3776        if (bounds.isEmpty()) {             // length == 0
3777            return syms.objectType;
3778        } else if (bounds.tail.isEmpty()) { // length == 1
3779            return bounds.head;
3780        } else {                            // length > 1
3781            int classCount = 0;
3782            List<Type> lowers = List.nil();
3783            for (Type bound : bounds) {
3784                if (!bound.isInterface()) {
3785                    classCount++;
3786                    Type lower = cvarLowerBound(bound);
3787                    if (bound != lower && !lower.hasTag(BOT))
3788                        lowers = insert(lowers, lower);
3789                }
3790            }
3791            if (classCount > 1) {
3792                if (lowers.isEmpty())
3793                    return createErrorType(errT);
3794                else
3795                    return glbFlattened(union(bounds, lowers), errT);
3796            }
3797        }
3798        return makeIntersectionType(bounds);
3799    }
3800    // </editor-fold>
3801
3802    // <editor-fold defaultstate="collapsed" desc="hashCode">
3803    /**
3804     * Compute a hash code on a type.
3805     */
3806    public int hashCode(Type t) {
3807        return hashCode.visit(t);
3808    }
3809    // where
3810        private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
3811
3812            public Integer visitType(Type t, Void ignored) {
3813                return t.getTag().ordinal();
3814            }
3815
3816            @Override
3817            public Integer visitClassType(ClassType t, Void ignored) {
3818                int result = visit(t.getEnclosingType());
3819                result *= 127;
3820                result += t.tsym.flatName().hashCode();
3821                for (Type s : t.getTypeArguments()) {
3822                    result *= 127;
3823                    result += visit(s);
3824                }
3825                return result;
3826            }
3827
3828            @Override
3829            public Integer visitMethodType(MethodType t, Void ignored) {
3830                int h = METHOD.ordinal();
3831                for (List<Type> thisargs = t.argtypes;
3832                     thisargs.tail != null;
3833                     thisargs = thisargs.tail)
3834                    h = (h << 5) + visit(thisargs.head);
3835                return (h << 5) + visit(t.restype);
3836            }
3837
3838            @Override
3839            public Integer visitWildcardType(WildcardType t, Void ignored) {
3840                int result = t.kind.hashCode();
3841                if (t.type != null) {
3842                    result *= 127;
3843                    result += visit(t.type);
3844                }
3845                return result;
3846            }
3847
3848            @Override
3849            public Integer visitArrayType(ArrayType t, Void ignored) {
3850                return visit(t.elemtype) + 12;
3851            }
3852
3853            @Override
3854            public Integer visitTypeVar(TypeVar t, Void ignored) {
3855                return System.identityHashCode(t.tsym);
3856            }
3857
3858            @Override
3859            public Integer visitUndetVar(UndetVar t, Void ignored) {
3860                return System.identityHashCode(t);
3861            }
3862
3863            @Override
3864            public Integer visitErrorType(ErrorType t, Void ignored) {
3865                return 0;
3866            }
3867        };
3868    // </editor-fold>
3869
3870    // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3871    /**
3872     * Does t have a result that is a subtype of the result type of s,
3873     * suitable for covariant returns?  It is assumed that both types
3874     * are (possibly polymorphic) method types.  Monomorphic method
3875     * types are handled in the obvious way.  Polymorphic method types
3876     * require renaming all type variables of one to corresponding
3877     * type variables in the other, where correspondence is by
3878     * position in the type parameter list. */
3879    public boolean resultSubtype(Type t, Type s, Warner warner) {
3880        List<Type> tvars = t.getTypeArguments();
3881        List<Type> svars = s.getTypeArguments();
3882        Type tres = t.getReturnType();
3883        Type sres = subst(s.getReturnType(), svars, tvars);
3884        return covariantReturnType(tres, sres, warner);
3885    }
3886
3887    /**
3888     * Return-Type-Substitutable.
3889     * @jls section 8.4.5
3890     */
3891    public boolean returnTypeSubstitutable(Type r1, Type r2) {
3892        if (hasSameArgs(r1, r2))
3893            return resultSubtype(r1, r2, noWarnings);
3894        else
3895            return covariantReturnType(r1.getReturnType(),
3896                                       erasure(r2.getReturnType()),
3897                                       noWarnings);
3898    }
3899
3900    public boolean returnTypeSubstitutable(Type r1,
3901                                           Type r2, Type r2res,
3902                                           Warner warner) {
3903        if (isSameType(r1.getReturnType(), r2res))
3904            return true;
3905        if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3906            return false;
3907
3908        if (hasSameArgs(r1, r2))
3909            return covariantReturnType(r1.getReturnType(), r2res, warner);
3910        if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3911            return true;
3912        if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3913            return false;
3914        warner.warn(LintCategory.UNCHECKED);
3915        return true;
3916    }
3917
3918    /**
3919     * Is t an appropriate return type in an overrider for a
3920     * method that returns s?
3921     */
3922    public boolean covariantReturnType(Type t, Type s, Warner warner) {
3923        return
3924            isSameType(t, s) ||
3925            !t.isPrimitive() &&
3926            !s.isPrimitive() &&
3927            isAssignable(t, s, warner);
3928    }
3929    // </editor-fold>
3930
3931    // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3932    /**
3933     * Return the class that boxes the given primitive.
3934     */
3935    public ClassSymbol boxedClass(Type t) {
3936        return syms.enterClass(syms.boxedName[t.getTag().ordinal()]);
3937    }
3938
3939    /**
3940     * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3941     */
3942    public Type boxedTypeOrType(Type t) {
3943        return t.isPrimitive() ?
3944            boxedClass(t).type :
3945            t;
3946    }
3947
3948    /**
3949     * Return the primitive type corresponding to a boxed type.
3950     */
3951    public Type unboxedType(Type t) {
3952        for (int i=0; i<syms.boxedName.length; i++) {
3953            Name box = syms.boxedName[i];
3954            if (box != null &&
3955                asSuper(t, syms.enterClass(box)) != null)
3956                return syms.typeOfTag[i];
3957        }
3958        return Type.noType;
3959    }
3960
3961    /**
3962     * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3963     */
3964    public Type unboxedTypeOrType(Type t) {
3965        Type unboxedType = unboxedType(t);
3966        return unboxedType.hasTag(NONE) ? t : unboxedType;
3967    }
3968    // </editor-fold>
3969
3970    // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3971    /*
3972     * JLS 5.1.10 Capture Conversion:
3973     *
3974     * Let G name a generic type declaration with n formal type
3975     * parameters A1 ... An with corresponding bounds U1 ... Un. There
3976     * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3977     * where, for 1 <= i <= n:
3978     *
3979     * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3980     *   Si is a fresh type variable whose upper bound is
3981     *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3982     *   type.
3983     *
3984     * + If Ti is a wildcard type argument of the form ? extends Bi,
3985     *   then Si is a fresh type variable whose upper bound is
3986     *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3987     *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3988     *   a compile-time error if for any two classes (not interfaces)
3989     *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
3990     *
3991     * + If Ti is a wildcard type argument of the form ? super Bi,
3992     *   then Si is a fresh type variable whose upper bound is
3993     *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3994     *
3995     * + Otherwise, Si = Ti.
3996     *
3997     * Capture conversion on any type other than a parameterized type
3998     * (4.5) acts as an identity conversion (5.1.1). Capture
3999     * conversions never require a special action at run time and
4000     * therefore never throw an exception at run time.
4001     *
4002     * Capture conversion is not applied recursively.
4003     */
4004    /**
4005     * Capture conversion as specified by the JLS.
4006     */
4007
4008    public List<Type> capture(List<Type> ts) {
4009        List<Type> buf = List.nil();
4010        for (Type t : ts) {
4011            buf = buf.prepend(capture(t));
4012        }
4013        return buf.reverse();
4014    }
4015
4016    public Type capture(Type t) {
4017        if (!t.hasTag(CLASS)) {
4018            return t;
4019        }
4020        if (t.getEnclosingType() != Type.noType) {
4021            Type capturedEncl = capture(t.getEnclosingType());
4022            if (capturedEncl != t.getEnclosingType()) {
4023                Type type1 = memberType(capturedEncl, t.tsym);
4024                t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
4025            }
4026        }
4027        ClassType cls = (ClassType)t;
4028        if (cls.isRaw() || !cls.isParameterized())
4029            return cls;
4030
4031        ClassType G = (ClassType)cls.asElement().asType();
4032        List<Type> A = G.getTypeArguments();
4033        List<Type> T = cls.getTypeArguments();
4034        List<Type> S = freshTypeVariables(T);
4035
4036        List<Type> currentA = A;
4037        List<Type> currentT = T;
4038        List<Type> currentS = S;
4039        boolean captured = false;
4040        while (!currentA.isEmpty() &&
4041               !currentT.isEmpty() &&
4042               !currentS.isEmpty()) {
4043            if (currentS.head != currentT.head) {
4044                captured = true;
4045                WildcardType Ti = (WildcardType)currentT.head;
4046                Type Ui = currentA.head.getUpperBound();
4047                CapturedType Si = (CapturedType)currentS.head;
4048                if (Ui == null)
4049                    Ui = syms.objectType;
4050                switch (Ti.kind) {
4051                case UNBOUND:
4052                    Si.bound = subst(Ui, A, S);
4053                    Si.lower = syms.botType;
4054                    break;
4055                case EXTENDS:
4056                    Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
4057                    Si.lower = syms.botType;
4058                    break;
4059                case SUPER:
4060                    Si.bound = subst(Ui, A, S);
4061                    Si.lower = Ti.getSuperBound();
4062                    break;
4063                }
4064                Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
4065                Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
4066                if (!Si.bound.hasTag(ERROR) &&
4067                    !Si.lower.hasTag(ERROR) &&
4068                    isSameType(tmpBound, tmpLower, false)) {
4069                    currentS.head = Si.bound;
4070                }
4071            }
4072            currentA = currentA.tail;
4073            currentT = currentT.tail;
4074            currentS = currentS.tail;
4075        }
4076        if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
4077            return erasure(t); // some "rare" type involved
4078
4079        if (captured)
4080            return new ClassType(cls.getEnclosingType(), S, cls.tsym,
4081                                 cls.getMetadata());
4082        else
4083            return t;
4084    }
4085    // where
4086        public List<Type> freshTypeVariables(List<Type> types) {
4087            ListBuffer<Type> result = new ListBuffer<>();
4088            for (Type t : types) {
4089                if (t.hasTag(WILDCARD)) {
4090                    Type bound = ((WildcardType)t).getExtendsBound();
4091                    if (bound == null)
4092                        bound = syms.objectType;
4093                    result.append(new CapturedType(capturedName,
4094                                                   syms.noSymbol,
4095                                                   bound,
4096                                                   syms.botType,
4097                                                   (WildcardType)t));
4098                } else {
4099                    result.append(t);
4100                }
4101            }
4102            return result.toList();
4103        }
4104    // </editor-fold>
4105
4106    // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
4107    private boolean sideCast(Type from, Type to, Warner warn) {
4108        // We are casting from type $from$ to type $to$, which are
4109        // non-final unrelated types.  This method
4110        // tries to reject a cast by transferring type parameters
4111        // from $to$ to $from$ by common superinterfaces.
4112        boolean reverse = false;
4113        Type target = to;
4114        if ((to.tsym.flags() & INTERFACE) == 0) {
4115            Assert.check((from.tsym.flags() & INTERFACE) != 0);
4116            reverse = true;
4117            to = from;
4118            from = target;
4119        }
4120        List<Type> commonSupers = superClosure(to, erasure(from));
4121        boolean giveWarning = commonSupers.isEmpty();
4122        // The arguments to the supers could be unified here to
4123        // get a more accurate analysis
4124        while (commonSupers.nonEmpty()) {
4125            Type t1 = asSuper(from, commonSupers.head.tsym);
4126            Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
4127            if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4128                return false;
4129            giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
4130            commonSupers = commonSupers.tail;
4131        }
4132        if (giveWarning && !isReifiable(reverse ? from : to))
4133            warn.warn(LintCategory.UNCHECKED);
4134        return true;
4135    }
4136
4137    private boolean sideCastFinal(Type from, Type to, Warner warn) {
4138        // We are casting from type $from$ to type $to$, which are
4139        // unrelated types one of which is final and the other of
4140        // which is an interface.  This method
4141        // tries to reject a cast by transferring type parameters
4142        // from the final class to the interface.
4143        boolean reverse = false;
4144        Type target = to;
4145        if ((to.tsym.flags() & INTERFACE) == 0) {
4146            Assert.check((from.tsym.flags() & INTERFACE) != 0);
4147            reverse = true;
4148            to = from;
4149            from = target;
4150        }
4151        Assert.check((from.tsym.flags() & FINAL) != 0);
4152        Type t1 = asSuper(from, to.tsym);
4153        if (t1 == null) return false;
4154        Type t2 = to;
4155        if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4156            return false;
4157        if (!isReifiable(target) &&
4158            (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
4159            warn.warn(LintCategory.UNCHECKED);
4160        return true;
4161    }
4162
4163    private boolean giveWarning(Type from, Type to) {
4164        List<Type> bounds = to.isCompound() ?
4165                ((IntersectionClassType)to).getComponents() : List.of(to);
4166        for (Type b : bounds) {
4167            Type subFrom = asSub(from, b.tsym);
4168            if (b.isParameterized() &&
4169                    (!(isUnbounded(b) ||
4170                    isSubtype(from, b) ||
4171                    ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
4172                return true;
4173            }
4174        }
4175        return false;
4176    }
4177
4178    private List<Type> superClosure(Type t, Type s) {
4179        List<Type> cl = List.nil();
4180        for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
4181            if (isSubtype(s, erasure(l.head))) {
4182                cl = insert(cl, l.head);
4183            } else {
4184                cl = union(cl, superClosure(l.head, s));
4185            }
4186        }
4187        return cl;
4188    }
4189
4190    private boolean containsTypeEquivalent(Type t, Type s) {
4191        return
4192            isSameType(t, s) || // shortcut
4193            containsType(t, s) && containsType(s, t);
4194    }
4195
4196    // <editor-fold defaultstate="collapsed" desc="adapt">
4197    /**
4198     * Adapt a type by computing a substitution which maps a source
4199     * type to a target type.
4200     *
4201     * @param source    the source type
4202     * @param target    the target type
4203     * @param from      the type variables of the computed substitution
4204     * @param to        the types of the computed substitution.
4205     */
4206    public void adapt(Type source,
4207                       Type target,
4208                       ListBuffer<Type> from,
4209                       ListBuffer<Type> to) throws AdaptFailure {
4210        new Adapter(from, to).adapt(source, target);
4211    }
4212
4213    class Adapter extends SimpleVisitor<Void, Type> {
4214
4215        ListBuffer<Type> from;
4216        ListBuffer<Type> to;
4217        Map<Symbol,Type> mapping;
4218
4219        Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
4220            this.from = from;
4221            this.to = to;
4222            mapping = new HashMap<>();
4223        }
4224
4225        public void adapt(Type source, Type target) throws AdaptFailure {
4226            visit(source, target);
4227            List<Type> fromList = from.toList();
4228            List<Type> toList = to.toList();
4229            while (!fromList.isEmpty()) {
4230                Type val = mapping.get(fromList.head.tsym);
4231                if (toList.head != val)
4232                    toList.head = val;
4233                fromList = fromList.tail;
4234                toList = toList.tail;
4235            }
4236        }
4237
4238        @Override
4239        public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
4240            if (target.hasTag(CLASS))
4241                adaptRecursive(source.allparams(), target.allparams());
4242            return null;
4243        }
4244
4245        @Override
4246        public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
4247            if (target.hasTag(ARRAY))
4248                adaptRecursive(elemtype(source), elemtype(target));
4249            return null;
4250        }
4251
4252        @Override
4253        public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
4254            if (source.isExtendsBound())
4255                adaptRecursive(wildUpperBound(source), wildUpperBound(target));
4256            else if (source.isSuperBound())
4257                adaptRecursive(wildLowerBound(source), wildLowerBound(target));
4258            return null;
4259        }
4260
4261        @Override
4262        public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
4263            // Check to see if there is
4264            // already a mapping for $source$, in which case
4265            // the old mapping will be merged with the new
4266            Type val = mapping.get(source.tsym);
4267            if (val != null) {
4268                if (val.isSuperBound() && target.isSuperBound()) {
4269                    val = isSubtype(wildLowerBound(val), wildLowerBound(target))
4270                        ? target : val;
4271                } else if (val.isExtendsBound() && target.isExtendsBound()) {
4272                    val = isSubtype(wildUpperBound(val), wildUpperBound(target))
4273                        ? val : target;
4274                } else if (!isSameType(val, target)) {
4275                    throw new AdaptFailure();
4276                }
4277            } else {
4278                val = target;
4279                from.append(source);
4280                to.append(target);
4281            }
4282            mapping.put(source.tsym, val);
4283            return null;
4284        }
4285
4286        @Override
4287        public Void visitType(Type source, Type target) {
4288            return null;
4289        }
4290
4291        private Set<TypePair> cache = new HashSet<>();
4292
4293        private void adaptRecursive(Type source, Type target) {
4294            TypePair pair = new TypePair(source, target);
4295            if (cache.add(pair)) {
4296                try {
4297                    visit(source, target);
4298                } finally {
4299                    cache.remove(pair);
4300                }
4301            }
4302        }
4303
4304        private void adaptRecursive(List<Type> source, List<Type> target) {
4305            if (source.length() == target.length()) {
4306                while (source.nonEmpty()) {
4307                    adaptRecursive(source.head, target.head);
4308                    source = source.tail;
4309                    target = target.tail;
4310                }
4311            }
4312        }
4313    }
4314
4315    public static class AdaptFailure extends RuntimeException {
4316        static final long serialVersionUID = -7490231548272701566L;
4317    }
4318
4319    private void adaptSelf(Type t,
4320                           ListBuffer<Type> from,
4321                           ListBuffer<Type> to) {
4322        try {
4323            //if (t.tsym.type != t)
4324                adapt(t.tsym.type, t, from, to);
4325        } catch (AdaptFailure ex) {
4326            // Adapt should never fail calculating a mapping from
4327            // t.tsym.type to t as there can be no merge problem.
4328            throw new AssertionError(ex);
4329        }
4330    }
4331    // </editor-fold>
4332
4333    /**
4334     * Rewrite all type variables (universal quantifiers) in the given
4335     * type to wildcards (existential quantifiers).  This is used to
4336     * determine if a cast is allowed.  For example, if high is true
4337     * and {@code T <: Number}, then {@code List<T>} is rewritten to
4338     * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
4339     * List<? extends Number>} a {@code List<T>} can be cast to {@code
4340     * List<Integer>} with a warning.
4341     * @param t a type
4342     * @param high if true return an upper bound; otherwise a lower
4343     * bound
4344     * @param rewriteTypeVars only rewrite captured wildcards if false;
4345     * otherwise rewrite all type variables
4346     * @return the type rewritten with wildcards (existential
4347     * quantifiers) only
4348     */
4349    private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4350        return new Rewriter(high, rewriteTypeVars).visit(t);
4351    }
4352
4353    class Rewriter extends UnaryVisitor<Type> {
4354
4355        boolean high;
4356        boolean rewriteTypeVars;
4357
4358        Rewriter(boolean high, boolean rewriteTypeVars) {
4359            this.high = high;
4360            this.rewriteTypeVars = rewriteTypeVars;
4361        }
4362
4363        @Override
4364        public Type visitClassType(ClassType t, Void s) {
4365            ListBuffer<Type> rewritten = new ListBuffer<>();
4366            boolean changed = false;
4367            for (Type arg : t.allparams()) {
4368                Type bound = visit(arg);
4369                if (arg != bound) {
4370                    changed = true;
4371                }
4372                rewritten.append(bound);
4373            }
4374            if (changed)
4375                return subst(t.tsym.type,
4376                        t.tsym.type.allparams(),
4377                        rewritten.toList());
4378            else
4379                return t;
4380        }
4381
4382        public Type visitType(Type t, Void s) {
4383            return t;
4384        }
4385
4386        @Override
4387        public Type visitCapturedType(CapturedType t, Void s) {
4388            Type w_bound = t.wildcard.type;
4389            Type bound = w_bound.contains(t) ?
4390                        erasure(w_bound) :
4391                        visit(w_bound);
4392            return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4393        }
4394
4395        @Override
4396        public Type visitTypeVar(TypeVar t, Void s) {
4397            if (rewriteTypeVars) {
4398                Type bound = t.bound.contains(t) ?
4399                        erasure(t.bound) :
4400                        visit(t.bound);
4401                return rewriteAsWildcardType(bound, t, EXTENDS);
4402            } else {
4403                return t;
4404            }
4405        }
4406
4407        @Override
4408        public Type visitWildcardType(WildcardType t, Void s) {
4409            Type bound2 = visit(t.type);
4410            return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4411        }
4412
4413        private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4414            switch (bk) {
4415               case EXTENDS: return high ?
4416                       makeExtendsWildcard(B(bound), formal) :
4417                       makeExtendsWildcard(syms.objectType, formal);
4418               case SUPER: return high ?
4419                       makeSuperWildcard(syms.botType, formal) :
4420                       makeSuperWildcard(B(bound), formal);
4421               case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4422               default:
4423                   Assert.error("Invalid bound kind " + bk);
4424                   return null;
4425            }
4426        }
4427
4428        Type B(Type t) {
4429            while (t.hasTag(WILDCARD)) {
4430                WildcardType w = (WildcardType)t;
4431                t = high ?
4432                    w.getExtendsBound() :
4433                    w.getSuperBound();
4434                if (t == null) {
4435                    t = high ? syms.objectType : syms.botType;
4436                }
4437            }
4438            return t;
4439        }
4440    }
4441
4442
4443    /**
4444     * Create a wildcard with the given upper (extends) bound; create
4445     * an unbounded wildcard if bound is Object.
4446     *
4447     * @param bound the upper bound
4448     * @param formal the formal type parameter that will be
4449     * substituted by the wildcard
4450     */
4451    private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4452        if (bound == syms.objectType) {
4453            return new WildcardType(syms.objectType,
4454                                    BoundKind.UNBOUND,
4455                                    syms.boundClass,
4456                                    formal);
4457        } else {
4458            return new WildcardType(bound,
4459                                    BoundKind.EXTENDS,
4460                                    syms.boundClass,
4461                                    formal);
4462        }
4463    }
4464
4465    /**
4466     * Create a wildcard with the given lower (super) bound; create an
4467     * unbounded wildcard if bound is bottom (type of {@code null}).
4468     *
4469     * @param bound the lower bound
4470     * @param formal the formal type parameter that will be
4471     * substituted by the wildcard
4472     */
4473    private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4474        if (bound.hasTag(BOT)) {
4475            return new WildcardType(syms.objectType,
4476                                    BoundKind.UNBOUND,
4477                                    syms.boundClass,
4478                                    formal);
4479        } else {
4480            return new WildcardType(bound,
4481                                    BoundKind.SUPER,
4482                                    syms.boundClass,
4483                                    formal);
4484        }
4485    }
4486
4487    /**
4488     * A wrapper for a type that allows use in sets.
4489     */
4490    public static class UniqueType {
4491        public final Type type;
4492        final Types types;
4493
4494        public UniqueType(Type type, Types types) {
4495            this.type = type;
4496            this.types = types;
4497        }
4498
4499        public int hashCode() {
4500            return types.hashCode(type);
4501        }
4502
4503        public boolean equals(Object obj) {
4504            return (obj instanceof UniqueType) &&
4505                types.isSameType(type, ((UniqueType)obj).type);
4506        }
4507
4508        public String toString() {
4509            return type.toString();
4510        }
4511
4512    }
4513    // </editor-fold>
4514
4515    // <editor-fold defaultstate="collapsed" desc="Visitors">
4516    /**
4517     * A default visitor for types.  All visitor methods except
4518     * visitType are implemented by delegating to visitType.  Concrete
4519     * subclasses must provide an implementation of visitType and can
4520     * override other methods as needed.
4521     *
4522     * @param <R> the return type of the operation implemented by this
4523     * visitor; use Void if no return type is needed.
4524     * @param <S> the type of the second argument (the first being the
4525     * type itself) of the operation implemented by this visitor; use
4526     * Void if a second argument is not needed.
4527     */
4528    public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4529        final public R visit(Type t, S s)               { return t.accept(this, s); }
4530        public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
4531        public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4532        public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
4533        public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
4534        public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
4535        public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
4536        public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4537        public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
4538        public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
4539        public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
4540    }
4541
4542    /**
4543     * A default visitor for symbols.  All visitor methods except
4544     * visitSymbol are implemented by delegating to visitSymbol.  Concrete
4545     * subclasses must provide an implementation of visitSymbol and can
4546     * override other methods as needed.
4547     *
4548     * @param <R> the return type of the operation implemented by this
4549     * visitor; use Void if no return type is needed.
4550     * @param <S> the type of the second argument (the first being the
4551     * symbol itself) of the operation implemented by this visitor; use
4552     * Void if a second argument is not needed.
4553     */
4554    public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4555        final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
4556        public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
4557        public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
4558        public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
4559        public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
4560        public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
4561        public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
4562    }
4563
4564    /**
4565     * A <em>simple</em> visitor for types.  This visitor is simple as
4566     * captured wildcards, for-all types (generic methods), and
4567     * undetermined type variables (part of inference) are hidden.
4568     * Captured wildcards are hidden by treating them as type
4569     * variables and the rest are hidden by visiting their qtypes.
4570     *
4571     * @param <R> the return type of the operation implemented by this
4572     * visitor; use Void if no return type is needed.
4573     * @param <S> the type of the second argument (the first being the
4574     * type itself) of the operation implemented by this visitor; use
4575     * Void if a second argument is not needed.
4576     */
4577    public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4578        @Override
4579        public R visitCapturedType(CapturedType t, S s) {
4580            return visitTypeVar(t, s);
4581        }
4582        @Override
4583        public R visitForAll(ForAll t, S s) {
4584            return visit(t.qtype, s);
4585        }
4586        @Override
4587        public R visitUndetVar(UndetVar t, S s) {
4588            return visit(t.qtype, s);
4589        }
4590    }
4591
4592    /**
4593     * A plain relation on types.  That is a 2-ary function on the
4594     * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
4595     * <!-- In plain text: Type x Type -> Boolean -->
4596     */
4597    public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4598
4599    /**
4600     * A convenience visitor for implementing operations that only
4601     * require one argument (the type itself), that is, unary
4602     * operations.
4603     *
4604     * @param <R> the return type of the operation implemented by this
4605     * visitor; use Void if no return type is needed.
4606     */
4607    public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4608        final public R visit(Type t) { return t.accept(this, null); }
4609    }
4610
4611    /**
4612     * A visitor for implementing a mapping from types to types.  The
4613     * default behavior of this class is to implement the identity
4614     * mapping (mapping a type to itself).  This can be overridden in
4615     * subclasses.
4616     *
4617     * @param <S> the type of the second argument (the first being the
4618     * type itself) of this mapping; use Void if a second argument is
4619     * not needed.
4620     */
4621    public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4622        final public Type visit(Type t) { return t.accept(this, null); }
4623        public Type visitType(Type t, S s) { return t; }
4624    }
4625    // </editor-fold>
4626
4627
4628    // <editor-fold defaultstate="collapsed" desc="Annotation support">
4629
4630    public RetentionPolicy getRetention(Attribute.Compound a) {
4631        return getRetention(a.type.tsym);
4632    }
4633
4634    public RetentionPolicy getRetention(Symbol sym) {
4635        RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4636        Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4637        if (c != null) {
4638            Attribute value = c.member(names.value);
4639            if (value != null && value instanceof Attribute.Enum) {
4640                Name levelName = ((Attribute.Enum)value).value.name;
4641                if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4642                else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4643                else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4644                else ;// /* fail soft */ throw new AssertionError(levelName);
4645            }
4646        }
4647        return vis;
4648    }
4649    // </editor-fold>
4650
4651    // <editor-fold defaultstate="collapsed" desc="Signature Generation">
4652
4653    public static abstract class SignatureGenerator {
4654
4655        private final Types types;
4656
4657        protected abstract void append(char ch);
4658        protected abstract void append(byte[] ba);
4659        protected abstract void append(Name name);
4660        protected void classReference(ClassSymbol c) { /* by default: no-op */ }
4661
4662        protected SignatureGenerator(Types types) {
4663            this.types = types;
4664        }
4665
4666        /**
4667         * Assemble signature of given type in string buffer.
4668         */
4669        public void assembleSig(Type type) {
4670            switch (type.getTag()) {
4671                case BYTE:
4672                    append('B');
4673                    break;
4674                case SHORT:
4675                    append('S');
4676                    break;
4677                case CHAR:
4678                    append('C');
4679                    break;
4680                case INT:
4681                    append('I');
4682                    break;
4683                case LONG:
4684                    append('J');
4685                    break;
4686                case FLOAT:
4687                    append('F');
4688                    break;
4689                case DOUBLE:
4690                    append('D');
4691                    break;
4692                case BOOLEAN:
4693                    append('Z');
4694                    break;
4695                case VOID:
4696                    append('V');
4697                    break;
4698                case CLASS:
4699                    append('L');
4700                    assembleClassSig(type);
4701                    append(';');
4702                    break;
4703                case ARRAY:
4704                    ArrayType at = (ArrayType) type;
4705                    append('[');
4706                    assembleSig(at.elemtype);
4707                    break;
4708                case METHOD:
4709                    MethodType mt = (MethodType) type;
4710                    append('(');
4711                    assembleSig(mt.argtypes);
4712                    append(')');
4713                    assembleSig(mt.restype);
4714                    if (hasTypeVar(mt.thrown)) {
4715                        for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
4716                            append('^');
4717                            assembleSig(l.head);
4718                        }
4719                    }
4720                    break;
4721                case WILDCARD: {
4722                    Type.WildcardType ta = (Type.WildcardType) type;
4723                    switch (ta.kind) {
4724                        case SUPER:
4725                            append('-');
4726                            assembleSig(ta.type);
4727                            break;
4728                        case EXTENDS:
4729                            append('+');
4730                            assembleSig(ta.type);
4731                            break;
4732                        case UNBOUND:
4733                            append('*');
4734                            break;
4735                        default:
4736                            throw new AssertionError(ta.kind);
4737                    }
4738                    break;
4739                }
4740                case TYPEVAR:
4741                    append('T');
4742                    append(type.tsym.name);
4743                    append(';');
4744                    break;
4745                case FORALL:
4746                    Type.ForAll ft = (Type.ForAll) type;
4747                    assembleParamsSig(ft.tvars);
4748                    assembleSig(ft.qtype);
4749                    break;
4750                default:
4751                    throw new AssertionError("typeSig " + type.getTag());
4752            }
4753        }
4754
4755        public boolean hasTypeVar(List<Type> l) {
4756            while (l.nonEmpty()) {
4757                if (l.head.hasTag(TypeTag.TYPEVAR)) {
4758                    return true;
4759                }
4760                l = l.tail;
4761            }
4762            return false;
4763        }
4764
4765        public void assembleClassSig(Type type) {
4766            ClassType ct = (ClassType) type;
4767            ClassSymbol c = (ClassSymbol) ct.tsym;
4768            classReference(c);
4769            Type outer = ct.getEnclosingType();
4770            if (outer.allparams().nonEmpty()) {
4771                boolean rawOuter =
4772                        c.owner.kind == MTH || // either a local class
4773                        c.name == types.names.empty; // or anonymous
4774                assembleClassSig(rawOuter
4775                        ? types.erasure(outer)
4776                        : outer);
4777                append(rawOuter ? '$' : '.');
4778                Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
4779                append(rawOuter
4780                        ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
4781                        : c.name);
4782            } else {
4783                append(externalize(c.flatname));
4784            }
4785            if (ct.getTypeArguments().nonEmpty()) {
4786                append('<');
4787                assembleSig(ct.getTypeArguments());
4788                append('>');
4789            }
4790        }
4791
4792        public void assembleParamsSig(List<Type> typarams) {
4793            append('<');
4794            for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
4795                Type.TypeVar tvar = (Type.TypeVar) ts.head;
4796                append(tvar.tsym.name);
4797                List<Type> bounds = types.getBounds(tvar);
4798                if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
4799                    append(':');
4800                }
4801                for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
4802                    append(':');
4803                    assembleSig(l.head);
4804                }
4805            }
4806            append('>');
4807        }
4808
4809        private void assembleSig(List<Type> types) {
4810            for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
4811                assembleSig(ts.head);
4812            }
4813        }
4814    }
4815    // </editor-fold>
4816
4817    public void newRound() {
4818        descCache._map.clear();
4819        isDerivedRawCache.clear();
4820        implCache._map.clear();
4821        membersCache._map.clear();
4822        closureCache.clear();
4823    }
4824}
4825