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