Types.java revision 3158:aae35f1ac70b
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 = Completer.NULL_COMPLETER;
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 15.12.3) 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.isCompound() || s.isCompound()) {
1499                    return !t.isCompound() ?
1500                            visitCompoundType((ClassType)s, t, true) :
1501                            visitCompoundType(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 visitCompoundType(ClassType ct, Type s, boolean reverse) {
1580                Warner warn = noWarnings;
1581                for (Type c : directSupertypes(ct)) {
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 visitWildcardType(WildcardType t, Boolean recurse) {
2186                Type erased = erasure(wildUpperBound(t), recurse);
2187                return combineMetadata(erased, t);
2188            }
2189
2190            @Override
2191            public Type visitClassType(ClassType t, Boolean recurse) {
2192                Type erased = t.tsym.erasure(Types.this);
2193                if (recurse) {
2194                    erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym,
2195                            t.getMetadata().without(Kind.ANNOTATIONS));
2196                    return erased;
2197                } else {
2198                    return combineMetadata(erased, t);
2199                }
2200            }
2201
2202            @Override
2203            public Type visitTypeVar(TypeVar t, Boolean recurse) {
2204                Type erased = erasure(t.bound, recurse);
2205                return combineMetadata(erased, t);
2206            }
2207        };
2208
2209    public List<Type> erasure(List<Type> ts) {
2210        return erasure.visit(ts, false);
2211    }
2212
2213    public Type erasureRecursive(Type t) {
2214        return erasure(t, true);
2215    }
2216
2217    public List<Type> erasureRecursive(List<Type> ts) {
2218        return erasure.visit(ts, true);
2219    }
2220    // </editor-fold>
2221
2222    // <editor-fold defaultstate="collapsed" desc="makeIntersectionType">
2223    /**
2224     * Make an intersection type from non-empty list of types.  The list should be ordered according to
2225     * {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion.
2226     * Hence, this version of makeIntersectionType may not be called during a classfile read.
2227     *
2228     * @param bounds    the types from which the intersection type is formed
2229     */
2230    public IntersectionClassType makeIntersectionType(List<Type> bounds) {
2231        return makeIntersectionType(bounds, bounds.head.tsym.isInterface());
2232    }
2233
2234    /**
2235     * Make an intersection type from non-empty list of types.  The list should be ordered according to
2236     * {@link TypeSymbol#precedes(TypeSymbol, Types)}. This does not cause symbol completion as
2237     * an extra parameter indicates as to whether all bounds are interfaces - in which case the
2238     * supertype is implicitly assumed to be 'Object'.
2239     *
2240     * @param bounds        the types from which the intersection type is formed
2241     * @param allInterfaces are all bounds interface types?
2242     */
2243    public IntersectionClassType makeIntersectionType(List<Type> bounds, boolean allInterfaces) {
2244        Assert.check(bounds.nonEmpty());
2245        Type firstExplicitBound = bounds.head;
2246        if (allInterfaces) {
2247            bounds = bounds.prepend(syms.objectType);
2248        }
2249        ClassSymbol bc =
2250            new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
2251                            Type.moreInfo
2252                                ? names.fromString(bounds.toString())
2253                                : names.empty,
2254                            null,
2255                            syms.noSymbol);
2256        IntersectionClassType intersectionType = new IntersectionClassType(bounds, bc, allInterfaces);
2257        bc.type = intersectionType;
2258        bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
2259                syms.objectType : // error condition, recover
2260                erasure(firstExplicitBound);
2261        bc.members_field = WriteableScope.create(bc);
2262        return intersectionType;
2263    }
2264    // </editor-fold>
2265
2266    // <editor-fold defaultstate="collapsed" desc="supertype">
2267    public Type supertype(Type t) {
2268        return supertype.visit(t);
2269    }
2270    // where
2271        private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2272
2273            public Type visitType(Type t, Void ignored) {
2274                // A note on wildcards: there is no good way to
2275                // determine a supertype for a super bounded wildcard.
2276                return Type.noType;
2277            }
2278
2279            @Override
2280            public Type visitClassType(ClassType t, Void ignored) {
2281                if (t.supertype_field == null) {
2282                    Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2283                    // An interface has no superclass; its supertype is Object.
2284                    if (t.isInterface())
2285                        supertype = ((ClassType)t.tsym.type).supertype_field;
2286                    if (t.supertype_field == null) {
2287                        List<Type> actuals = classBound(t).allparams();
2288                        List<Type> formals = t.tsym.type.allparams();
2289                        if (t.hasErasedSupertypes()) {
2290                            t.supertype_field = erasureRecursive(supertype);
2291                        } else if (formals.nonEmpty()) {
2292                            t.supertype_field = subst(supertype, formals, actuals);
2293                        }
2294                        else {
2295                            t.supertype_field = supertype;
2296                        }
2297                    }
2298                }
2299                return t.supertype_field;
2300            }
2301
2302            /**
2303             * The supertype is always a class type. If the type
2304             * variable's bounds start with a class type, this is also
2305             * the supertype.  Otherwise, the supertype is
2306             * java.lang.Object.
2307             */
2308            @Override
2309            public Type visitTypeVar(TypeVar t, Void ignored) {
2310                if (t.bound.hasTag(TYPEVAR) ||
2311                    (!t.bound.isCompound() && !t.bound.isInterface())) {
2312                    return t.bound;
2313                } else {
2314                    return supertype(t.bound);
2315                }
2316            }
2317
2318            @Override
2319            public Type visitArrayType(ArrayType t, Void ignored) {
2320                if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2321                    return arraySuperType();
2322                else
2323                    return new ArrayType(supertype(t.elemtype), t.tsym);
2324            }
2325
2326            @Override
2327            public Type visitErrorType(ErrorType t, Void ignored) {
2328                return Type.noType;
2329            }
2330        };
2331    // </editor-fold>
2332
2333    // <editor-fold defaultstate="collapsed" desc="interfaces">
2334    /**
2335     * Return the interfaces implemented by this class.
2336     */
2337    public List<Type> interfaces(Type t) {
2338        return interfaces.visit(t);
2339    }
2340    // where
2341        private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2342
2343            public List<Type> visitType(Type t, Void ignored) {
2344                return List.nil();
2345            }
2346
2347            @Override
2348            public List<Type> visitClassType(ClassType t, Void ignored) {
2349                if (t.interfaces_field == null) {
2350                    List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2351                    if (t.interfaces_field == null) {
2352                        // If t.interfaces_field is null, then t must
2353                        // be a parameterized type (not to be confused
2354                        // with a generic type declaration).
2355                        // Terminology:
2356                        //    Parameterized type: List<String>
2357                        //    Generic type declaration: class List<E> { ... }
2358                        // So t corresponds to List<String> and
2359                        // t.tsym.type corresponds to List<E>.
2360                        // The reason t must be parameterized type is
2361                        // that completion will happen as a side
2362                        // effect of calling
2363                        // ClassSymbol.getInterfaces.  Since
2364                        // t.interfaces_field is null after
2365                        // completion, we can assume that t is not the
2366                        // type of a class/interface declaration.
2367                        Assert.check(t != t.tsym.type, t);
2368                        List<Type> actuals = t.allparams();
2369                        List<Type> formals = t.tsym.type.allparams();
2370                        if (t.hasErasedSupertypes()) {
2371                            t.interfaces_field = erasureRecursive(interfaces);
2372                        } else if (formals.nonEmpty()) {
2373                            t.interfaces_field = subst(interfaces, formals, actuals);
2374                        }
2375                        else {
2376                            t.interfaces_field = interfaces;
2377                        }
2378                    }
2379                }
2380                return t.interfaces_field;
2381            }
2382
2383            @Override
2384            public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2385                if (t.bound.isCompound())
2386                    return interfaces(t.bound);
2387
2388                if (t.bound.isInterface())
2389                    return List.of(t.bound);
2390
2391                return List.nil();
2392            }
2393        };
2394
2395    public List<Type> directSupertypes(Type t) {
2396        return directSupertypes.visit(t);
2397    }
2398    // where
2399        private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
2400
2401            public List<Type> visitType(final Type type, final Void ignored) {
2402                if (!type.isIntersection()) {
2403                    final Type sup = supertype(type);
2404                    return (sup == Type.noType || sup == type || sup == null)
2405                        ? interfaces(type)
2406                        : interfaces(type).prepend(sup);
2407                } else {
2408                    return ((IntersectionClassType)type).getExplicitComponents();
2409                }
2410            }
2411        };
2412
2413    public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
2414        for (Type i2 : interfaces(origin.type)) {
2415            if (isym == i2.tsym) return true;
2416        }
2417        return false;
2418    }
2419    // </editor-fold>
2420
2421    // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2422    Map<Type,Boolean> isDerivedRawCache = new HashMap<>();
2423
2424    public boolean isDerivedRaw(Type t) {
2425        Boolean result = isDerivedRawCache.get(t);
2426        if (result == null) {
2427            result = isDerivedRawInternal(t);
2428            isDerivedRawCache.put(t, result);
2429        }
2430        return result;
2431    }
2432
2433    public boolean isDerivedRawInternal(Type t) {
2434        if (t.isErroneous())
2435            return false;
2436        return
2437            t.isRaw() ||
2438            supertype(t) != Type.noType && isDerivedRaw(supertype(t)) ||
2439            isDerivedRaw(interfaces(t));
2440    }
2441
2442    public boolean isDerivedRaw(List<Type> ts) {
2443        List<Type> l = ts;
2444        while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2445        return l.nonEmpty();
2446    }
2447    // </editor-fold>
2448
2449    // <editor-fold defaultstate="collapsed" desc="setBounds">
2450    /**
2451     * Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly,
2452     * as follows: if all all bounds are interface types, the computed supertype is Object,otherwise
2453     * the supertype is simply left null (in this case, the supertype is assumed to be the head of
2454     * the bound list passed as second argument). Note that this check might cause a symbol completion.
2455     * Hence, this version of setBounds may not be called during a classfile read.
2456     *
2457     * @param t         a type variable
2458     * @param bounds    the bounds, must be nonempty
2459     */
2460    public void setBounds(TypeVar t, List<Type> bounds) {
2461        setBounds(t, bounds, bounds.head.tsym.isInterface());
2462    }
2463
2464    /**
2465     * Set the bounds field of the given type variable to reflect a (possibly multiple) list of bounds.
2466     * This does not cause symbol completion as an extra parameter indicates as to whether all bounds
2467     * are interfaces - in which case the supertype is implicitly assumed to be 'Object'.
2468     *
2469     * @param t             a type variable
2470     * @param bounds        the bounds, must be nonempty
2471     * @param allInterfaces are all bounds interface types?
2472     */
2473    public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
2474        t.bound = bounds.tail.isEmpty() ?
2475                bounds.head :
2476                makeIntersectionType(bounds, allInterfaces);
2477        t.rank_field = -1;
2478    }
2479    // </editor-fold>
2480
2481    // <editor-fold defaultstate="collapsed" desc="getBounds">
2482    /**
2483     * Return list of bounds of the given type variable.
2484     */
2485    public List<Type> getBounds(TypeVar t) {
2486        if (t.bound.hasTag(NONE))
2487            return List.nil();
2488        else if (t.bound.isErroneous() || !t.bound.isCompound())
2489            return List.of(t.bound);
2490        else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2491            return interfaces(t).prepend(supertype(t));
2492        else
2493            // No superclass was given in bounds.
2494            // In this case, supertype is Object, erasure is first interface.
2495            return interfaces(t);
2496    }
2497    // </editor-fold>
2498
2499    // <editor-fold defaultstate="collapsed" desc="classBound">
2500    /**
2501     * If the given type is a (possibly selected) type variable,
2502     * return the bounding class of this type, otherwise return the
2503     * type itself.
2504     */
2505    public Type classBound(Type t) {
2506        return classBound.visit(t);
2507    }
2508    // where
2509        private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2510
2511            public Type visitType(Type t, Void ignored) {
2512                return t;
2513            }
2514
2515            @Override
2516            public Type visitClassType(ClassType t, Void ignored) {
2517                Type outer1 = classBound(t.getEnclosingType());
2518                if (outer1 != t.getEnclosingType())
2519                    return new ClassType(outer1, t.getTypeArguments(), t.tsym,
2520                                         t.getMetadata());
2521                else
2522                    return t;
2523            }
2524
2525            @Override
2526            public Type visitTypeVar(TypeVar t, Void ignored) {
2527                return classBound(supertype(t));
2528            }
2529
2530            @Override
2531            public Type visitErrorType(ErrorType t, Void ignored) {
2532                return t;
2533            }
2534        };
2535    // </editor-fold>
2536
2537    // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
2538    /**
2539     * Returns true iff the first signature is a <em>sub
2540     * signature</em> of the other.  This is <b>not</b> an equivalence
2541     * relation.
2542     *
2543     * @jls section 8.4.2.
2544     * @see #overrideEquivalent(Type t, Type s)
2545     * @param t first signature (possibly raw).
2546     * @param s second signature (could be subjected to erasure).
2547     * @return true if t is a sub signature of s.
2548     */
2549    public boolean isSubSignature(Type t, Type s) {
2550        return isSubSignature(t, s, true);
2551    }
2552
2553    public boolean isSubSignature(Type t, Type s, boolean strict) {
2554        return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
2555    }
2556
2557    /**
2558     * Returns true iff these signatures are related by <em>override
2559     * equivalence</em>.  This is the natural extension of
2560     * isSubSignature to an equivalence relation.
2561     *
2562     * @jls section 8.4.2.
2563     * @see #isSubSignature(Type t, Type s)
2564     * @param t a signature (possible raw, could be subjected to
2565     * erasure).
2566     * @param s a signature (possible raw, could be subjected to
2567     * erasure).
2568     * @return true if either argument is a sub signature of the other.
2569     */
2570    public boolean overrideEquivalent(Type t, Type s) {
2571        return hasSameArgs(t, s) ||
2572            hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2573    }
2574
2575    public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2576        for (Symbol sym : syms.objectType.tsym.members().getSymbolsByName(msym.name)) {
2577            if (msym.overrides(sym, origin, Types.this, true)) {
2578                return true;
2579            }
2580        }
2581        return false;
2582    }
2583
2584    // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2585    class ImplementationCache {
2586
2587        private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<>();
2588
2589        class Entry {
2590            final MethodSymbol cachedImpl;
2591            final Filter<Symbol> implFilter;
2592            final boolean checkResult;
2593            final int prevMark;
2594
2595            public Entry(MethodSymbol cachedImpl,
2596                    Filter<Symbol> scopeFilter,
2597                    boolean checkResult,
2598                    int prevMark) {
2599                this.cachedImpl = cachedImpl;
2600                this.implFilter = scopeFilter;
2601                this.checkResult = checkResult;
2602                this.prevMark = prevMark;
2603            }
2604
2605            boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
2606                return this.implFilter == scopeFilter &&
2607                        this.checkResult == checkResult &&
2608                        this.prevMark == mark;
2609            }
2610        }
2611
2612        MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2613            SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2614            Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2615            if (cache == null) {
2616                cache = new HashMap<>();
2617                _map.put(ms, new SoftReference<>(cache));
2618            }
2619            Entry e = cache.get(origin);
2620            CompoundScope members = membersClosure(origin.type, true);
2621            if (e == null ||
2622                    !e.matches(implFilter, checkResult, members.getMark())) {
2623                MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2624                cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2625                return impl;
2626            }
2627            else {
2628                return e.cachedImpl;
2629            }
2630        }
2631
2632        private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2633            for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
2634                t = skipTypeVars(t, false);
2635                TypeSymbol c = t.tsym;
2636                Symbol bestSoFar = null;
2637                for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) {
2638                    if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) {
2639                        bestSoFar = sym;
2640                        if ((sym.flags() & ABSTRACT) == 0) {
2641                            //if concrete impl is found, exit immediately
2642                            break;
2643                        }
2644                    }
2645                }
2646                if (bestSoFar != null) {
2647                    //return either the (only) concrete implementation or the first abstract one
2648                    return (MethodSymbol)bestSoFar;
2649                }
2650            }
2651            return null;
2652        }
2653    }
2654
2655    private ImplementationCache implCache = new ImplementationCache();
2656
2657    public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
2658        return implCache.get(ms, origin, checkResult, implFilter);
2659    }
2660    // </editor-fold>
2661
2662    // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
2663    class MembersClosureCache extends SimpleVisitor<Scope.CompoundScope, Void> {
2664
2665        private Map<TypeSymbol, CompoundScope> _map = new HashMap<>();
2666
2667        Set<TypeSymbol> seenTypes = new HashSet<>();
2668
2669        class MembersScope extends CompoundScope {
2670
2671            CompoundScope scope;
2672
2673            public MembersScope(CompoundScope scope) {
2674                super(scope.owner);
2675                this.scope = scope;
2676            }
2677
2678            Filter<Symbol> combine(Filter<Symbol> sf) {
2679                return s -> !s.owner.isInterface() && (sf == null || sf.accepts(s));
2680            }
2681
2682            @Override
2683            public Iterable<Symbol> getSymbols(Filter<Symbol> sf, LookupKind lookupKind) {
2684                return scope.getSymbols(combine(sf), lookupKind);
2685            }
2686
2687            @Override
2688            public Iterable<Symbol> getSymbolsByName(Name name, Filter<Symbol> sf, LookupKind lookupKind) {
2689                return scope.getSymbolsByName(name, combine(sf), lookupKind);
2690            }
2691
2692            @Override
2693            public int getMark() {
2694                return scope.getMark();
2695            }
2696        }
2697
2698        CompoundScope nilScope;
2699
2700        /** members closure visitor methods **/
2701
2702        public CompoundScope visitType(Type t, Void _unused) {
2703            if (nilScope == null) {
2704                nilScope = new CompoundScope(syms.noSymbol);
2705            }
2706            return nilScope;
2707        }
2708
2709        @Override
2710        public CompoundScope visitClassType(ClassType t, Void _unused) {
2711            if (!seenTypes.add(t.tsym)) {
2712                //this is possible when an interface is implemented in multiple
2713                //superclasses, or when a class hierarchy is circular - in such
2714                //cases we don't need to recurse (empty scope is returned)
2715                return new CompoundScope(t.tsym);
2716            }
2717            try {
2718                seenTypes.add(t.tsym);
2719                ClassSymbol csym = (ClassSymbol)t.tsym;
2720                CompoundScope membersClosure = _map.get(csym);
2721                if (membersClosure == null) {
2722                    membersClosure = new CompoundScope(csym);
2723                    for (Type i : interfaces(t)) {
2724                        membersClosure.prependSubScope(visit(i, null));
2725                    }
2726                    membersClosure.prependSubScope(visit(supertype(t), null));
2727                    membersClosure.prependSubScope(csym.members());
2728                    _map.put(csym, membersClosure);
2729                }
2730                return membersClosure;
2731            }
2732            finally {
2733                seenTypes.remove(t.tsym);
2734            }
2735        }
2736
2737        @Override
2738        public CompoundScope visitTypeVar(TypeVar t, Void _unused) {
2739            return visit(t.getUpperBound(), null);
2740        }
2741    }
2742
2743    private MembersClosureCache membersCache = new MembersClosureCache();
2744
2745    public CompoundScope membersClosure(Type site, boolean skipInterface) {
2746        CompoundScope cs = membersCache.visit(site, null);
2747        Assert.checkNonNull(cs, () -> "type " + site);
2748        return skipInterface ? membersCache.new MembersScope(cs) : cs;
2749    }
2750    // </editor-fold>
2751
2752
2753    /** Return first abstract member of class `sym'.
2754     */
2755    public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) {
2756        try {
2757            return firstUnimplementedAbstractImpl(sym, sym);
2758        } catch (CompletionFailure ex) {
2759            chk.completionError(enter.getEnv(sym).tree.pos(), ex);
2760            return null;
2761        }
2762    }
2763        //where:
2764        private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) {
2765            MethodSymbol undef = null;
2766            // Do not bother to search in classes that are not abstract,
2767            // since they cannot have abstract members.
2768            if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2769                Scope s = c.members();
2770                for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
2771                    if (sym.kind == MTH &&
2772                        (sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
2773                        MethodSymbol absmeth = (MethodSymbol)sym;
2774                        MethodSymbol implmeth = absmeth.implementation(impl, this, true);
2775                        if (implmeth == null || implmeth == absmeth) {
2776                            //look for default implementations
2777                            if (allowDefaultMethods) {
2778                                MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head;
2779                                if (prov != null && prov.overrides(absmeth, impl, this, true)) {
2780                                    implmeth = prov;
2781                                }
2782                            }
2783                        }
2784                        if (implmeth == null || implmeth == absmeth) {
2785                            undef = absmeth;
2786                            break;
2787                        }
2788                    }
2789                }
2790                if (undef == null) {
2791                    Type st = supertype(c.type);
2792                    if (st.hasTag(CLASS))
2793                        undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym);
2794                }
2795                for (List<Type> l = interfaces(c.type);
2796                     undef == null && l.nonEmpty();
2797                     l = l.tail) {
2798                    undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym);
2799                }
2800            }
2801            return undef;
2802        }
2803
2804
2805    //where
2806    public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
2807        Filter<Symbol> filter = new MethodFilter(ms, site);
2808        List<MethodSymbol> candidates = List.nil();
2809            for (Symbol s : membersClosure(site, false).getSymbols(filter)) {
2810                if (!site.tsym.isInterface() && !s.owner.isInterface()) {
2811                    return List.of((MethodSymbol)s);
2812                } else if (!candidates.contains(s)) {
2813                    candidates = candidates.prepend((MethodSymbol)s);
2814                }
2815            }
2816            return prune(candidates);
2817        }
2818
2819    public List<MethodSymbol> prune(List<MethodSymbol> methods) {
2820        ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
2821        for (MethodSymbol m1 : methods) {
2822            boolean isMin_m1 = true;
2823            for (MethodSymbol m2 : methods) {
2824                if (m1 == m2) continue;
2825                if (m2.owner != m1.owner &&
2826                        asSuper(m2.owner.type, m1.owner) != null) {
2827                    isMin_m1 = false;
2828                    break;
2829                }
2830            }
2831            if (isMin_m1)
2832                methodsMin.append(m1);
2833        }
2834        return methodsMin.toList();
2835    }
2836    // where
2837            private class MethodFilter implements Filter<Symbol> {
2838
2839                Symbol msym;
2840                Type site;
2841
2842                MethodFilter(Symbol msym, Type site) {
2843                    this.msym = msym;
2844                    this.site = site;
2845                }
2846
2847                public boolean accepts(Symbol s) {
2848                    return s.kind == MTH &&
2849                            s.name == msym.name &&
2850                            (s.flags() & SYNTHETIC) == 0 &&
2851                            s.isInheritedIn(site.tsym, Types.this) &&
2852                            overrideEquivalent(memberType(site, s), memberType(site, msym));
2853                }
2854            }
2855    // </editor-fold>
2856
2857    /**
2858     * Does t have the same arguments as s?  It is assumed that both
2859     * types are (possibly polymorphic) method types.  Monomorphic
2860     * method types "have the same arguments", if their argument lists
2861     * are equal.  Polymorphic method types "have the same arguments",
2862     * if they have the same arguments after renaming all type
2863     * variables of one to corresponding type variables in the other,
2864     * where correspondence is by position in the type parameter list.
2865     */
2866    public boolean hasSameArgs(Type t, Type s) {
2867        return hasSameArgs(t, s, true);
2868    }
2869
2870    public boolean hasSameArgs(Type t, Type s, boolean strict) {
2871        return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
2872    }
2873
2874    private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
2875        return hasSameArgs.visit(t, s);
2876    }
2877    // where
2878        private class HasSameArgs extends TypeRelation {
2879
2880            boolean strict;
2881
2882            public HasSameArgs(boolean strict) {
2883                this.strict = strict;
2884            }
2885
2886            public Boolean visitType(Type t, Type s) {
2887                throw new AssertionError();
2888            }
2889
2890            @Override
2891            public Boolean visitMethodType(MethodType t, Type s) {
2892                return s.hasTag(METHOD)
2893                    && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
2894            }
2895
2896            @Override
2897            public Boolean visitForAll(ForAll t, Type s) {
2898                if (!s.hasTag(FORALL))
2899                    return strict ? false : visitMethodType(t.asMethodType(), s);
2900
2901                ForAll forAll = (ForAll)s;
2902                return hasSameBounds(t, forAll)
2903                    && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
2904            }
2905
2906            @Override
2907            public Boolean visitErrorType(ErrorType t, Type s) {
2908                return false;
2909            }
2910        }
2911
2912    TypeRelation hasSameArgs_strict = new HasSameArgs(true);
2913        TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
2914
2915    // </editor-fold>
2916
2917    // <editor-fold defaultstate="collapsed" desc="subst">
2918    public List<Type> subst(List<Type> ts,
2919                            List<Type> from,
2920                            List<Type> to) {
2921        return ts.map(new Subst(from, to));
2922    }
2923
2924    /**
2925     * Substitute all occurrences of a type in `from' with the
2926     * corresponding type in `to' in 't'. Match lists `from' and `to'
2927     * from the right: If lists have different length, discard leading
2928     * elements of the longer list.
2929     */
2930    public Type subst(Type t, List<Type> from, List<Type> to) {
2931        return t.map(new Subst(from, to));
2932    }
2933
2934    private class Subst extends TypeMapping<Void> {
2935        List<Type> from;
2936        List<Type> to;
2937
2938        public Subst(List<Type> from, List<Type> to) {
2939            int fromLength = from.length();
2940            int toLength = to.length();
2941            while (fromLength > toLength) {
2942                fromLength--;
2943                from = from.tail;
2944            }
2945            while (fromLength < toLength) {
2946                toLength--;
2947                to = to.tail;
2948            }
2949            this.from = from;
2950            this.to = to;
2951        }
2952
2953        @Override
2954        public Type visitTypeVar(TypeVar t, Void ignored) {
2955            for (List<Type> from = this.from, to = this.to;
2956                 from.nonEmpty();
2957                 from = from.tail, to = to.tail) {
2958                if (t.equalsIgnoreMetadata(from.head)) {
2959                    return to.head.withTypeVar(t);
2960                }
2961            }
2962            return t;
2963        }
2964
2965        @Override
2966        public Type visitClassType(ClassType t, Void ignored) {
2967            if (!t.isCompound()) {
2968                return super.visitClassType(t, ignored);
2969            } else {
2970                Type st = visit(supertype(t));
2971                List<Type> is = visit(interfaces(t), ignored);
2972                if (st == supertype(t) && is == interfaces(t))
2973                    return t;
2974                else
2975                    return makeIntersectionType(is.prepend(st));
2976            }
2977        }
2978
2979        @Override
2980        public Type visitWildcardType(WildcardType t, Void ignored) {
2981            WildcardType t2 = (WildcardType)super.visitWildcardType(t, ignored);
2982            if (t2 != t && t.isExtendsBound() && t2.type.isExtendsBound()) {
2983                t2.type = wildUpperBound(t2.type);
2984            }
2985            return t2;
2986        }
2987
2988        @Override
2989        public Type visitForAll(ForAll t, Void ignored) {
2990            if (Type.containsAny(to, t.tvars)) {
2991                //perform alpha-renaming of free-variables in 't'
2992                //if 'to' types contain variables that are free in 't'
2993                List<Type> freevars = newInstances(t.tvars);
2994                t = new ForAll(freevars,
2995                               Types.this.subst(t.qtype, t.tvars, freevars));
2996            }
2997            List<Type> tvars1 = substBounds(t.tvars, from, to);
2998            Type qtype1 = visit(t.qtype);
2999            if (tvars1 == t.tvars && qtype1 == t.qtype) {
3000                return t;
3001            } else if (tvars1 == t.tvars) {
3002                return new ForAll(tvars1, qtype1) {
3003                    @Override
3004                    public boolean needsStripping() {
3005                        return true;
3006                    }
3007                };
3008            } else {
3009                return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)) {
3010                    @Override
3011                    public boolean needsStripping() {
3012                        return true;
3013                    }
3014                };
3015            }
3016        }
3017    }
3018
3019    public List<Type> substBounds(List<Type> tvars,
3020                                  List<Type> from,
3021                                  List<Type> to) {
3022        if (tvars.isEmpty())
3023            return tvars;
3024        ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
3025        boolean changed = false;
3026        // calculate new bounds
3027        for (Type t : tvars) {
3028            TypeVar tv = (TypeVar) t;
3029            Type bound = subst(tv.bound, from, to);
3030            if (bound != tv.bound)
3031                changed = true;
3032            newBoundsBuf.append(bound);
3033        }
3034        if (!changed)
3035            return tvars;
3036        ListBuffer<Type> newTvars = new ListBuffer<>();
3037        // create new type variables without bounds
3038        for (Type t : tvars) {
3039            newTvars.append(new TypeVar(t.tsym, null, syms.botType,
3040                                        t.getMetadata()));
3041        }
3042        // the new bounds should use the new type variables in place
3043        // of the old
3044        List<Type> newBounds = newBoundsBuf.toList();
3045        from = tvars;
3046        to = newTvars.toList();
3047        for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
3048            newBounds.head = subst(newBounds.head, from, to);
3049        }
3050        newBounds = newBoundsBuf.toList();
3051        // set the bounds of new type variables to the new bounds
3052        for (Type t : newTvars.toList()) {
3053            TypeVar tv = (TypeVar) t;
3054            tv.bound = newBounds.head;
3055            newBounds = newBounds.tail;
3056        }
3057        return newTvars.toList();
3058    }
3059
3060    public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
3061        Type bound1 = subst(t.bound, from, to);
3062        if (bound1 == t.bound)
3063            return t;
3064        else {
3065            // create new type variable without bounds
3066            TypeVar tv = new TypeVar(t.tsym, null, syms.botType,
3067                                     t.getMetadata());
3068            // the new bound should use the new type variable in place
3069            // of the old
3070            tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
3071            return tv;
3072        }
3073    }
3074    // </editor-fold>
3075
3076    // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
3077    /**
3078     * Does t have the same bounds for quantified variables as s?
3079     */
3080    public boolean hasSameBounds(ForAll t, ForAll s) {
3081        List<Type> l1 = t.tvars;
3082        List<Type> l2 = s.tvars;
3083        while (l1.nonEmpty() && l2.nonEmpty() &&
3084               isSameType(l1.head.getUpperBound(),
3085                          subst(l2.head.getUpperBound(),
3086                                s.tvars,
3087                                t.tvars))) {
3088            l1 = l1.tail;
3089            l2 = l2.tail;
3090        }
3091        return l1.isEmpty() && l2.isEmpty();
3092    }
3093    // </editor-fold>
3094
3095    // <editor-fold defaultstate="collapsed" desc="newInstances">
3096    /** Create new vector of type variables from list of variables
3097     *  changing all recursive bounds from old to new list.
3098     */
3099    public List<Type> newInstances(List<Type> tvars) {
3100        List<Type> tvars1 = tvars.map(newInstanceFun);
3101        for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
3102            TypeVar tv = (TypeVar) l.head;
3103            tv.bound = subst(tv.bound, tvars, tvars1);
3104        }
3105        return tvars1;
3106    }
3107        private static final TypeMapping<Void> newInstanceFun = new TypeMapping<Void>() {
3108            @Override
3109            public TypeVar visitTypeVar(TypeVar t, Void _unused) {
3110                return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound(), t.getMetadata());
3111            }
3112        };
3113    // </editor-fold>
3114
3115    public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
3116        return original.accept(methodWithParameters, newParams);
3117    }
3118    // where
3119        private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
3120            public Type visitType(Type t, List<Type> newParams) {
3121                throw new IllegalArgumentException("Not a method type: " + t);
3122            }
3123            public Type visitMethodType(MethodType t, List<Type> newParams) {
3124                return new MethodType(newParams, t.restype, t.thrown, t.tsym);
3125            }
3126            public Type visitForAll(ForAll t, List<Type> newParams) {
3127                return new ForAll(t.tvars, t.qtype.accept(this, newParams));
3128            }
3129        };
3130
3131    public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
3132        return original.accept(methodWithThrown, newThrown);
3133    }
3134    // where
3135        private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
3136            public Type visitType(Type t, List<Type> newThrown) {
3137                throw new IllegalArgumentException("Not a method type: " + t);
3138            }
3139            public Type visitMethodType(MethodType t, List<Type> newThrown) {
3140                return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
3141            }
3142            public Type visitForAll(ForAll t, List<Type> newThrown) {
3143                return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
3144            }
3145        };
3146
3147    public Type createMethodTypeWithReturn(Type original, Type newReturn) {
3148        return original.accept(methodWithReturn, newReturn);
3149    }
3150    // where
3151        private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3152            public Type visitType(Type t, Type newReturn) {
3153                throw new IllegalArgumentException("Not a method type: " + t);
3154            }
3155            public Type visitMethodType(MethodType t, Type newReturn) {
3156                return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym) {
3157                    @Override
3158                    public Type baseType() {
3159                        return t;
3160                    }
3161                };
3162            }
3163            public Type visitForAll(ForAll t, Type newReturn) {
3164                return new ForAll(t.tvars, t.qtype.accept(this, newReturn)) {
3165                    @Override
3166                    public Type baseType() {
3167                        return t;
3168                    }
3169                };
3170            }
3171        };
3172
3173    // <editor-fold defaultstate="collapsed" desc="createErrorType">
3174    public Type createErrorType(Type originalType) {
3175        return new ErrorType(originalType, syms.errSymbol);
3176    }
3177
3178    public Type createErrorType(ClassSymbol c, Type originalType) {
3179        return new ErrorType(c, originalType);
3180    }
3181
3182    public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3183        return new ErrorType(name, container, originalType);
3184    }
3185    // </editor-fold>
3186
3187    // <editor-fold defaultstate="collapsed" desc="rank">
3188    /**
3189     * The rank of a class is the length of the longest path between
3190     * the class and java.lang.Object in the class inheritance
3191     * graph. Undefined for all but reference types.
3192     */
3193    public int rank(Type t) {
3194        switch(t.getTag()) {
3195        case CLASS: {
3196            ClassType cls = (ClassType)t;
3197            if (cls.rank_field < 0) {
3198                Name fullname = cls.tsym.getQualifiedName();
3199                if (fullname == names.java_lang_Object)
3200                    cls.rank_field = 0;
3201                else {
3202                    int r = rank(supertype(cls));
3203                    for (List<Type> l = interfaces(cls);
3204                         l.nonEmpty();
3205                         l = l.tail) {
3206                        if (rank(l.head) > r)
3207                            r = rank(l.head);
3208                    }
3209                    cls.rank_field = r + 1;
3210                }
3211            }
3212            return cls.rank_field;
3213        }
3214        case TYPEVAR: {
3215            TypeVar tvar = (TypeVar)t;
3216            if (tvar.rank_field < 0) {
3217                int r = rank(supertype(tvar));
3218                for (List<Type> l = interfaces(tvar);
3219                     l.nonEmpty();
3220                     l = l.tail) {
3221                    if (rank(l.head) > r) r = rank(l.head);
3222                }
3223                tvar.rank_field = r + 1;
3224            }
3225            return tvar.rank_field;
3226        }
3227        case ERROR:
3228        case NONE:
3229            return 0;
3230        default:
3231            throw new AssertionError();
3232        }
3233    }
3234    // </editor-fold>
3235
3236    /**
3237     * Helper method for generating a string representation of a given type
3238     * accordingly to a given locale
3239     */
3240    public String toString(Type t, Locale locale) {
3241        return Printer.createStandardPrinter(messages).visit(t, locale);
3242    }
3243
3244    /**
3245     * Helper method for generating a string representation of a given type
3246     * accordingly to a given locale
3247     */
3248    public String toString(Symbol t, Locale locale) {
3249        return Printer.createStandardPrinter(messages).visit(t, locale);
3250    }
3251
3252    // <editor-fold defaultstate="collapsed" desc="toString">
3253    /**
3254     * This toString is slightly more descriptive than the one on Type.
3255     *
3256     * @deprecated Types.toString(Type t, Locale l) provides better support
3257     * for localization
3258     */
3259    @Deprecated
3260    public String toString(Type t) {
3261        if (t.hasTag(FORALL)) {
3262            ForAll forAll = (ForAll)t;
3263            return typaramsString(forAll.tvars) + forAll.qtype;
3264        }
3265        return "" + t;
3266    }
3267    // where
3268        private String typaramsString(List<Type> tvars) {
3269            StringBuilder s = new StringBuilder();
3270            s.append('<');
3271            boolean first = true;
3272            for (Type t : tvars) {
3273                if (!first) s.append(", ");
3274                first = false;
3275                appendTyparamString(((TypeVar)t), s);
3276            }
3277            s.append('>');
3278            return s.toString();
3279        }
3280        private void appendTyparamString(TypeVar t, StringBuilder buf) {
3281            buf.append(t);
3282            if (t.bound == null ||
3283                t.bound.tsym.getQualifiedName() == names.java_lang_Object)
3284                return;
3285            buf.append(" extends "); // Java syntax; no need for i18n
3286            Type bound = t.bound;
3287            if (!bound.isCompound()) {
3288                buf.append(bound);
3289            } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3290                buf.append(supertype(t));
3291                for (Type intf : interfaces(t)) {
3292                    buf.append('&');
3293                    buf.append(intf);
3294                }
3295            } else {
3296                // No superclass was given in bounds.
3297                // In this case, supertype is Object, erasure is first interface.
3298                boolean first = true;
3299                for (Type intf : interfaces(t)) {
3300                    if (!first) buf.append('&');
3301                    first = false;
3302                    buf.append(intf);
3303                }
3304            }
3305        }
3306    // </editor-fold>
3307
3308    // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3309    /**
3310     * A cache for closures.
3311     *
3312     * <p>A closure is a list of all the supertypes and interfaces of
3313     * a class or interface type, ordered by ClassSymbol.precedes
3314     * (that is, subclasses come first, arbitrary but fixed
3315     * otherwise).
3316     */
3317    private Map<Type,List<Type>> closureCache = new HashMap<>();
3318
3319    /**
3320     * Returns the closure of a class or interface type.
3321     */
3322    public List<Type> closure(Type t) {
3323        List<Type> cl = closureCache.get(t);
3324        if (cl == null) {
3325            Type st = supertype(t);
3326            if (!t.isCompound()) {
3327                if (st.hasTag(CLASS)) {
3328                    cl = insert(closure(st), t);
3329                } else if (st.hasTag(TYPEVAR)) {
3330                    cl = closure(st).prepend(t);
3331                } else {
3332                    cl = List.of(t);
3333                }
3334            } else {
3335                cl = closure(supertype(t));
3336            }
3337            for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3338                cl = union(cl, closure(l.head));
3339            closureCache.put(t, cl);
3340        }
3341        return cl;
3342    }
3343
3344    /**
3345     * Collect types into a new closure (using a @code{ClosureHolder})
3346     */
3347    public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3348        return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip),
3349                ClosureHolder::add,
3350                ClosureHolder::merge,
3351                ClosureHolder::closure);
3352    }
3353    //where
3354        class ClosureHolder {
3355            List<Type> closure;
3356            final boolean minClosure;
3357            final BiPredicate<Type, Type> shouldSkip;
3358
3359            ClosureHolder(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3360                this.closure = List.nil();
3361                this.minClosure = minClosure;
3362                this.shouldSkip = shouldSkip;
3363            }
3364
3365            void add(Type type) {
3366                closure = insert(closure, type, shouldSkip);
3367            }
3368
3369            ClosureHolder merge(ClosureHolder other) {
3370                closure = union(closure, other.closure, shouldSkip);
3371                return this;
3372            }
3373
3374            List<Type> closure() {
3375                return minClosure ? closureMin(closure) : closure;
3376            }
3377        }
3378
3379    BiPredicate<Type, Type> basicClosureSkip = (t1, t2) -> t1.tsym == t2.tsym;
3380
3381    /**
3382     * Insert a type in a closure
3383     */
3384    public List<Type> insert(List<Type> cl, Type t, BiPredicate<Type, Type> shouldSkip) {
3385        if (cl.isEmpty()) {
3386            return cl.prepend(t);
3387        } else if (shouldSkip.test(t, cl.head)) {
3388            return cl;
3389        } else if (t.tsym.precedes(cl.head.tsym, this)) {
3390            return cl.prepend(t);
3391        } else {
3392            // t comes after head, or the two are unrelated
3393            return insert(cl.tail, t, shouldSkip).prepend(cl.head);
3394        }
3395    }
3396
3397    public List<Type> insert(List<Type> cl, Type t) {
3398        return insert(cl, t, basicClosureSkip);
3399    }
3400
3401    /**
3402     * Form the union of two closures
3403     */
3404    public List<Type> union(List<Type> cl1, List<Type> cl2, BiPredicate<Type, Type> shouldSkip) {
3405        if (cl1.isEmpty()) {
3406            return cl2;
3407        } else if (cl2.isEmpty()) {
3408            return cl1;
3409        } else if (shouldSkip.test(cl1.head, cl2.head)) {
3410            return union(cl1.tail, cl2.tail, shouldSkip).prepend(cl1.head);
3411        } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
3412            return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
3413        } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3414            return union(cl1, cl2.tail, shouldSkip).prepend(cl2.head);
3415        } else {
3416            // unrelated types
3417            return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
3418        }
3419    }
3420
3421    public List<Type> union(List<Type> cl1, List<Type> cl2) {
3422        return union(cl1, cl2, basicClosureSkip);
3423    }
3424
3425    /**
3426     * Intersect two closures
3427     */
3428    public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3429        if (cl1 == cl2)
3430            return cl1;
3431        if (cl1.isEmpty() || cl2.isEmpty())
3432            return List.nil();
3433        if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3434            return intersect(cl1.tail, cl2);
3435        if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3436            return intersect(cl1, cl2.tail);
3437        if (isSameType(cl1.head, cl2.head))
3438            return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3439        if (cl1.head.tsym == cl2.head.tsym &&
3440            cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
3441            if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3442                Type merge = merge(cl1.head,cl2.head);
3443                return intersect(cl1.tail, cl2.tail).prepend(merge);
3444            }
3445            if (cl1.head.isRaw() || cl2.head.isRaw())
3446                return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3447        }
3448        return intersect(cl1.tail, cl2.tail);
3449    }
3450    // where
3451        class TypePair {
3452            final Type t1;
3453            final Type t2;
3454            boolean strict;
3455
3456            TypePair(Type t1, Type t2) {
3457                this(t1, t2, false);
3458            }
3459
3460            TypePair(Type t1, Type t2, boolean strict) {
3461                this.t1 = t1;
3462                this.t2 = t2;
3463                this.strict = strict;
3464            }
3465            @Override
3466            public int hashCode() {
3467                return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3468            }
3469            @Override
3470            public boolean equals(Object obj) {
3471                if (!(obj instanceof TypePair))
3472                    return false;
3473                TypePair typePair = (TypePair)obj;
3474                return isSameType(t1, typePair.t1, strict)
3475                    && isSameType(t2, typePair.t2, strict);
3476            }
3477        }
3478        Set<TypePair> mergeCache = new HashSet<>();
3479        private Type merge(Type c1, Type c2) {
3480            ClassType class1 = (ClassType) c1;
3481            List<Type> act1 = class1.getTypeArguments();
3482            ClassType class2 = (ClassType) c2;
3483            List<Type> act2 = class2.getTypeArguments();
3484            ListBuffer<Type> merged = new ListBuffer<>();
3485            List<Type> typarams = class1.tsym.type.getTypeArguments();
3486
3487            while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3488                if (containsType(act1.head, act2.head)) {
3489                    merged.append(act1.head);
3490                } else if (containsType(act2.head, act1.head)) {
3491                    merged.append(act2.head);
3492                } else {
3493                    TypePair pair = new TypePair(c1, c2);
3494                    Type m;
3495                    if (mergeCache.add(pair)) {
3496                        m = new WildcardType(lub(wildUpperBound(act1.head),
3497                                                 wildUpperBound(act2.head)),
3498                                             BoundKind.EXTENDS,
3499                                             syms.boundClass);
3500                        mergeCache.remove(pair);
3501                    } else {
3502                        m = new WildcardType(syms.objectType,
3503                                             BoundKind.UNBOUND,
3504                                             syms.boundClass);
3505                    }
3506                    merged.append(m.withTypeVar(typarams.head));
3507                }
3508                act1 = act1.tail;
3509                act2 = act2.tail;
3510                typarams = typarams.tail;
3511            }
3512            Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3513            // There is no spec detailing how type annotations are to
3514            // be inherited.  So set it to noAnnotations for now
3515            return new ClassType(class1.getEnclosingType(), merged.toList(),
3516                                 class1.tsym);
3517        }
3518
3519    /**
3520     * Return the minimum type of a closure, a compound type if no
3521     * unique minimum exists.
3522     */
3523    private Type compoundMin(List<Type> cl) {
3524        if (cl.isEmpty()) return syms.objectType;
3525        List<Type> compound = closureMin(cl);
3526        if (compound.isEmpty())
3527            return null;
3528        else if (compound.tail.isEmpty())
3529            return compound.head;
3530        else
3531            return makeIntersectionType(compound);
3532    }
3533
3534    /**
3535     * Return the minimum types of a closure, suitable for computing
3536     * compoundMin or glb.
3537     */
3538    private List<Type> closureMin(List<Type> cl) {
3539        ListBuffer<Type> classes = new ListBuffer<>();
3540        ListBuffer<Type> interfaces = new ListBuffer<>();
3541        Set<Type> toSkip = new HashSet<>();
3542        while (!cl.isEmpty()) {
3543            Type current = cl.head;
3544            boolean keep = !toSkip.contains(current);
3545            if (keep && current.hasTag(TYPEVAR)) {
3546                // skip lower-bounded variables with a subtype in cl.tail
3547                for (Type t : cl.tail) {
3548                    if (isSubtypeNoCapture(t, current)) {
3549                        keep = false;
3550                        break;
3551                    }
3552                }
3553            }
3554            if (keep) {
3555                if (current.isInterface())
3556                    interfaces.append(current);
3557                else
3558                    classes.append(current);
3559                for (Type t : cl.tail) {
3560                    // skip supertypes of 'current' in cl.tail
3561                    if (isSubtypeNoCapture(current, t))
3562                        toSkip.add(t);
3563                }
3564            }
3565            cl = cl.tail;
3566        }
3567        return classes.appendList(interfaces).toList();
3568    }
3569
3570    /**
3571     * Return the least upper bound of list of types.  if the lub does
3572     * not exist return null.
3573     */
3574    public Type lub(List<Type> ts) {
3575        return lub(ts.toArray(new Type[ts.length()]));
3576    }
3577
3578    /**
3579     * Return the least upper bound (lub) of set of types.  If the lub
3580     * does not exist return the type of null (bottom).
3581     */
3582    public Type lub(Type... ts) {
3583        final int UNKNOWN_BOUND = 0;
3584        final int ARRAY_BOUND = 1;
3585        final int CLASS_BOUND = 2;
3586
3587        int[] kinds = new int[ts.length];
3588
3589        int boundkind = UNKNOWN_BOUND;
3590        for (int i = 0 ; i < ts.length ; i++) {
3591            Type t = ts[i];
3592            switch (t.getTag()) {
3593            case CLASS:
3594                boundkind |= kinds[i] = CLASS_BOUND;
3595                break;
3596            case ARRAY:
3597                boundkind |= kinds[i] = ARRAY_BOUND;
3598                break;
3599            case  TYPEVAR:
3600                do {
3601                    t = t.getUpperBound();
3602                } while (t.hasTag(TYPEVAR));
3603                if (t.hasTag(ARRAY)) {
3604                    boundkind |= kinds[i] = ARRAY_BOUND;
3605                } else {
3606                    boundkind |= kinds[i] = CLASS_BOUND;
3607                }
3608                break;
3609            default:
3610                kinds[i] = UNKNOWN_BOUND;
3611                if (t.isPrimitive())
3612                    return syms.errType;
3613            }
3614        }
3615        switch (boundkind) {
3616        case 0:
3617            return syms.botType;
3618
3619        case ARRAY_BOUND:
3620            // calculate lub(A[], B[])
3621            Type[] elements = new Type[ts.length];
3622            for (int i = 0 ; i < ts.length ; i++) {
3623                Type elem = elements[i] = elemTypeFun.apply(ts[i]);
3624                if (elem.isPrimitive()) {
3625                    // if a primitive type is found, then return
3626                    // arraySuperType unless all the types are the
3627                    // same
3628                    Type first = ts[0];
3629                    for (int j = 1 ; j < ts.length ; j++) {
3630                        if (!isSameType(first, ts[j])) {
3631                             // lub(int[], B[]) is Cloneable & Serializable
3632                            return arraySuperType();
3633                        }
3634                    }
3635                    // all the array types are the same, return one
3636                    // lub(int[], int[]) is int[]
3637                    return first;
3638                }
3639            }
3640            // lub(A[], B[]) is lub(A, B)[]
3641            return new ArrayType(lub(elements), syms.arrayClass);
3642
3643        case CLASS_BOUND:
3644            // calculate lub(A, B)
3645            int startIdx = 0;
3646            for (int i = 0; i < ts.length ; i++) {
3647                Type t = ts[i];
3648                if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) {
3649                    break;
3650                } else {
3651                    startIdx++;
3652                }
3653            }
3654            Assert.check(startIdx < ts.length);
3655            //step 1 - compute erased candidate set (EC)
3656            List<Type> cl = erasedSupertypes(ts[startIdx]);
3657            for (int i = startIdx + 1 ; i < ts.length ; i++) {
3658                Type t = ts[i];
3659                if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
3660                    cl = intersect(cl, erasedSupertypes(t));
3661            }
3662            //step 2 - compute minimal erased candidate set (MEC)
3663            List<Type> mec = closureMin(cl);
3664            //step 3 - for each element G in MEC, compute lci(Inv(G))
3665            List<Type> candidates = List.nil();
3666            for (Type erasedSupertype : mec) {
3667                List<Type> lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym));
3668                for (int i = startIdx + 1 ; i < ts.length ; i++) {
3669                    Type superType = asSuper(ts[i], erasedSupertype.tsym);
3670                    lci = intersect(lci, superType != null ? List.of(superType) : List.<Type>nil());
3671                }
3672                candidates = candidates.appendList(lci);
3673            }
3674            //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
3675            //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
3676            return compoundMin(candidates);
3677
3678        default:
3679            // calculate lub(A, B[])
3680            List<Type> classes = List.of(arraySuperType());
3681            for (int i = 0 ; i < ts.length ; i++) {
3682                if (kinds[i] != ARRAY_BOUND) // Filter out any arrays
3683                    classes = classes.prepend(ts[i]);
3684            }
3685            // lub(A, B[]) is lub(A, arraySuperType)
3686            return lub(classes);
3687        }
3688    }
3689    // where
3690        List<Type> erasedSupertypes(Type t) {
3691            ListBuffer<Type> buf = new ListBuffer<>();
3692            for (Type sup : closure(t)) {
3693                if (sup.hasTag(TYPEVAR)) {
3694                    buf.append(sup);
3695                } else {
3696                    buf.append(erasure(sup));
3697                }
3698            }
3699            return buf.toList();
3700        }
3701
3702        private Type arraySuperType = null;
3703        private Type arraySuperType() {
3704            // initialized lazily to avoid problems during compiler startup
3705            if (arraySuperType == null) {
3706                synchronized (this) {
3707                    if (arraySuperType == null) {
3708                        // JLS 10.8: all arrays implement Cloneable and Serializable.
3709                        arraySuperType = makeIntersectionType(List.of(syms.serializableType,
3710                                syms.cloneableType), true);
3711                    }
3712                }
3713            }
3714            return arraySuperType;
3715        }
3716    // </editor-fold>
3717
3718    // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
3719    public Type glb(List<Type> ts) {
3720        Type t1 = ts.head;
3721        for (Type t2 : ts.tail) {
3722            if (t1.isErroneous())
3723                return t1;
3724            t1 = glb(t1, t2);
3725        }
3726        return t1;
3727    }
3728    //where
3729    public Type glb(Type t, Type s) {
3730        if (s == null)
3731            return t;
3732        else if (t.isPrimitive() || s.isPrimitive())
3733            return syms.errType;
3734        else if (isSubtypeNoCapture(t, s))
3735            return t;
3736        else if (isSubtypeNoCapture(s, t))
3737            return s;
3738
3739        List<Type> closure = union(closure(t), closure(s));
3740        return glbFlattened(closure, t);
3741    }
3742    //where
3743    /**
3744     * Perform glb for a list of non-primitive, non-error, non-compound types;
3745     * redundant elements are removed.  Bounds should be ordered according to
3746     * {@link Symbol#precedes(TypeSymbol,Types)}.
3747     *
3748     * @param flatBounds List of type to glb
3749     * @param errT Original type to use if the result is an error type
3750     */
3751    private Type glbFlattened(List<Type> flatBounds, Type errT) {
3752        List<Type> bounds = closureMin(flatBounds);
3753
3754        if (bounds.isEmpty()) {             // length == 0
3755            return syms.objectType;
3756        } else if (bounds.tail.isEmpty()) { // length == 1
3757            return bounds.head;
3758        } else {                            // length > 1
3759            int classCount = 0;
3760            List<Type> lowers = List.nil();
3761            for (Type bound : bounds) {
3762                if (!bound.isInterface()) {
3763                    classCount++;
3764                    Type lower = cvarLowerBound(bound);
3765                    if (bound != lower && !lower.hasTag(BOT))
3766                        lowers = insert(lowers, lower);
3767                }
3768            }
3769            if (classCount > 1) {
3770                if (lowers.isEmpty())
3771                    return createErrorType(errT);
3772                else
3773                    return glbFlattened(union(bounds, lowers), errT);
3774            }
3775        }
3776        return makeIntersectionType(bounds);
3777    }
3778    // </editor-fold>
3779
3780    // <editor-fold defaultstate="collapsed" desc="hashCode">
3781    /**
3782     * Compute a hash code on a type.
3783     */
3784    public int hashCode(Type t) {
3785        return hashCode(t, false);
3786    }
3787
3788    public int hashCode(Type t, boolean strict) {
3789        return strict ?
3790                hashCodeStrictVisitor.visit(t) :
3791                hashCodeVisitor.visit(t);
3792    }
3793    // where
3794        private static final HashCodeVisitor hashCodeVisitor = new HashCodeVisitor();
3795        private static final HashCodeVisitor hashCodeStrictVisitor = new HashCodeVisitor() {
3796            @Override
3797            public Integer visitTypeVar(TypeVar t, Void ignored) {
3798                return System.identityHashCode(t);
3799            }
3800        };
3801
3802        private static class HashCodeVisitor extends UnaryVisitor<Integer> {
3803            public Integer visitType(Type t, Void ignored) {
3804                return t.getTag().ordinal();
3805            }
3806
3807            @Override
3808            public Integer visitClassType(ClassType t, Void ignored) {
3809                int result = visit(t.getEnclosingType());
3810                result *= 127;
3811                result += t.tsym.flatName().hashCode();
3812                for (Type s : t.getTypeArguments()) {
3813                    result *= 127;
3814                    result += visit(s);
3815                }
3816                return result;
3817            }
3818
3819            @Override
3820            public Integer visitMethodType(MethodType t, Void ignored) {
3821                int h = METHOD.ordinal();
3822                for (List<Type> thisargs = t.argtypes;
3823                     thisargs.tail != null;
3824                     thisargs = thisargs.tail)
3825                    h = (h << 5) + visit(thisargs.head);
3826                return (h << 5) + visit(t.restype);
3827            }
3828
3829            @Override
3830            public Integer visitWildcardType(WildcardType t, Void ignored) {
3831                int result = t.kind.hashCode();
3832                if (t.type != null) {
3833                    result *= 127;
3834                    result += visit(t.type);
3835                }
3836                return result;
3837            }
3838
3839            @Override
3840            public Integer visitArrayType(ArrayType t, Void ignored) {
3841                return visit(t.elemtype) + 12;
3842            }
3843
3844            @Override
3845            public Integer visitTypeVar(TypeVar t, Void ignored) {
3846                return System.identityHashCode(t);
3847            }
3848
3849            @Override
3850            public Integer visitUndetVar(UndetVar t, Void ignored) {
3851                return System.identityHashCode(t);
3852            }
3853
3854            @Override
3855            public Integer visitErrorType(ErrorType t, Void ignored) {
3856                return 0;
3857            }
3858        }
3859    // </editor-fold>
3860
3861    // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
3862    /**
3863     * Does t have a result that is a subtype of the result type of s,
3864     * suitable for covariant returns?  It is assumed that both types
3865     * are (possibly polymorphic) method types.  Monomorphic method
3866     * types are handled in the obvious way.  Polymorphic method types
3867     * require renaming all type variables of one to corresponding
3868     * type variables in the other, where correspondence is by
3869     * position in the type parameter list. */
3870    public boolean resultSubtype(Type t, Type s, Warner warner) {
3871        List<Type> tvars = t.getTypeArguments();
3872        List<Type> svars = s.getTypeArguments();
3873        Type tres = t.getReturnType();
3874        Type sres = subst(s.getReturnType(), svars, tvars);
3875        return covariantReturnType(tres, sres, warner);
3876    }
3877
3878    /**
3879     * Return-Type-Substitutable.
3880     * @jls section 8.4.5
3881     */
3882    public boolean returnTypeSubstitutable(Type r1, Type r2) {
3883        if (hasSameArgs(r1, r2))
3884            return resultSubtype(r1, r2, noWarnings);
3885        else
3886            return covariantReturnType(r1.getReturnType(),
3887                                       erasure(r2.getReturnType()),
3888                                       noWarnings);
3889    }
3890
3891    public boolean returnTypeSubstitutable(Type r1,
3892                                           Type r2, Type r2res,
3893                                           Warner warner) {
3894        if (isSameType(r1.getReturnType(), r2res))
3895            return true;
3896        if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
3897            return false;
3898
3899        if (hasSameArgs(r1, r2))
3900            return covariantReturnType(r1.getReturnType(), r2res, warner);
3901        if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
3902            return true;
3903        if (!isSubtype(r1.getReturnType(), erasure(r2res)))
3904            return false;
3905        warner.warn(LintCategory.UNCHECKED);
3906        return true;
3907    }
3908
3909    /**
3910     * Is t an appropriate return type in an overrider for a
3911     * method that returns s?
3912     */
3913    public boolean covariantReturnType(Type t, Type s, Warner warner) {
3914        return
3915            isSameType(t, s) ||
3916            !t.isPrimitive() &&
3917            !s.isPrimitive() &&
3918            isAssignable(t, s, warner);
3919    }
3920    // </editor-fold>
3921
3922    // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
3923    /**
3924     * Return the class that boxes the given primitive.
3925     */
3926    public ClassSymbol boxedClass(Type t) {
3927        return syms.enterClass(syms.boxedName[t.getTag().ordinal()]);
3928    }
3929
3930    /**
3931     * Return the boxed type if 't' is primitive, otherwise return 't' itself.
3932     */
3933    public Type boxedTypeOrType(Type t) {
3934        return t.isPrimitive() ?
3935            boxedClass(t).type :
3936            t;
3937    }
3938
3939    /**
3940     * Return the primitive type corresponding to a boxed type.
3941     */
3942    public Type unboxedType(Type t) {
3943        for (int i=0; i<syms.boxedName.length; i++) {
3944            Name box = syms.boxedName[i];
3945            if (box != null &&
3946                asSuper(t, syms.enterClass(box)) != null)
3947                return syms.typeOfTag[i];
3948        }
3949        return Type.noType;
3950    }
3951
3952    /**
3953     * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
3954     */
3955    public Type unboxedTypeOrType(Type t) {
3956        Type unboxedType = unboxedType(t);
3957        return unboxedType.hasTag(NONE) ? t : unboxedType;
3958    }
3959    // </editor-fold>
3960
3961    // <editor-fold defaultstate="collapsed" desc="Capture conversion">
3962    /*
3963     * JLS 5.1.10 Capture Conversion:
3964     *
3965     * Let G name a generic type declaration with n formal type
3966     * parameters A1 ... An with corresponding bounds U1 ... Un. There
3967     * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
3968     * where, for 1 <= i <= n:
3969     *
3970     * + If Ti is a wildcard type argument (4.5.1) of the form ? then
3971     *   Si is a fresh type variable whose upper bound is
3972     *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
3973     *   type.
3974     *
3975     * + If Ti is a wildcard type argument of the form ? extends Bi,
3976     *   then Si is a fresh type variable whose upper bound is
3977     *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
3978     *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
3979     *   a compile-time error if for any two classes (not interfaces)
3980     *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
3981     *
3982     * + If Ti is a wildcard type argument of the form ? super Bi,
3983     *   then Si is a fresh type variable whose upper bound is
3984     *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
3985     *
3986     * + Otherwise, Si = Ti.
3987     *
3988     * Capture conversion on any type other than a parameterized type
3989     * (4.5) acts as an identity conversion (5.1.1). Capture
3990     * conversions never require a special action at run time and
3991     * therefore never throw an exception at run time.
3992     *
3993     * Capture conversion is not applied recursively.
3994     */
3995    /**
3996     * Capture conversion as specified by the JLS.
3997     */
3998
3999    public List<Type> capture(List<Type> ts) {
4000        List<Type> buf = List.nil();
4001        for (Type t : ts) {
4002            buf = buf.prepend(capture(t));
4003        }
4004        return buf.reverse();
4005    }
4006
4007    public Type capture(Type t) {
4008        if (!t.hasTag(CLASS)) {
4009            return t;
4010        }
4011        if (t.getEnclosingType() != Type.noType) {
4012            Type capturedEncl = capture(t.getEnclosingType());
4013            if (capturedEncl != t.getEnclosingType()) {
4014                Type type1 = memberType(capturedEncl, t.tsym);
4015                t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
4016            }
4017        }
4018        ClassType cls = (ClassType)t;
4019        if (cls.isRaw() || !cls.isParameterized())
4020            return cls;
4021
4022        ClassType G = (ClassType)cls.asElement().asType();
4023        List<Type> A = G.getTypeArguments();
4024        List<Type> T = cls.getTypeArguments();
4025        List<Type> S = freshTypeVariables(T);
4026
4027        List<Type> currentA = A;
4028        List<Type> currentT = T;
4029        List<Type> currentS = S;
4030        boolean captured = false;
4031        while (!currentA.isEmpty() &&
4032               !currentT.isEmpty() &&
4033               !currentS.isEmpty()) {
4034            if (currentS.head != currentT.head) {
4035                captured = true;
4036                WildcardType Ti = (WildcardType)currentT.head;
4037                Type Ui = currentA.head.getUpperBound();
4038                CapturedType Si = (CapturedType)currentS.head;
4039                if (Ui == null)
4040                    Ui = syms.objectType;
4041                switch (Ti.kind) {
4042                case UNBOUND:
4043                    Si.bound = subst(Ui, A, S);
4044                    Si.lower = syms.botType;
4045                    break;
4046                case EXTENDS:
4047                    Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
4048                    Si.lower = syms.botType;
4049                    break;
4050                case SUPER:
4051                    Si.bound = subst(Ui, A, S);
4052                    Si.lower = Ti.getSuperBound();
4053                    break;
4054                }
4055                Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
4056                Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
4057                if (!Si.bound.hasTag(ERROR) &&
4058                    !Si.lower.hasTag(ERROR) &&
4059                    isSameType(tmpBound, tmpLower, false)) {
4060                    currentS.head = Si.bound;
4061                }
4062            }
4063            currentA = currentA.tail;
4064            currentT = currentT.tail;
4065            currentS = currentS.tail;
4066        }
4067        if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
4068            return erasure(t); // some "rare" type involved
4069
4070        if (captured)
4071            return new ClassType(cls.getEnclosingType(), S, cls.tsym,
4072                                 cls.getMetadata());
4073        else
4074            return t;
4075    }
4076    // where
4077        public List<Type> freshTypeVariables(List<Type> types) {
4078            ListBuffer<Type> result = new ListBuffer<>();
4079            for (Type t : types) {
4080                if (t.hasTag(WILDCARD)) {
4081                    Type bound = ((WildcardType)t).getExtendsBound();
4082                    if (bound == null)
4083                        bound = syms.objectType;
4084                    result.append(new CapturedType(capturedName,
4085                                                   syms.noSymbol,
4086                                                   bound,
4087                                                   syms.botType,
4088                                                   (WildcardType)t));
4089                } else {
4090                    result.append(t);
4091                }
4092            }
4093            return result.toList();
4094        }
4095    // </editor-fold>
4096
4097    // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
4098    private boolean sideCast(Type from, Type to, Warner warn) {
4099        // We are casting from type $from$ to type $to$, which are
4100        // non-final unrelated types.  This method
4101        // tries to reject a cast by transferring type parameters
4102        // from $to$ to $from$ by common superinterfaces.
4103        boolean reverse = false;
4104        Type target = to;
4105        if ((to.tsym.flags() & INTERFACE) == 0) {
4106            Assert.check((from.tsym.flags() & INTERFACE) != 0);
4107            reverse = true;
4108            to = from;
4109            from = target;
4110        }
4111        List<Type> commonSupers = superClosure(to, erasure(from));
4112        boolean giveWarning = commonSupers.isEmpty();
4113        // The arguments to the supers could be unified here to
4114        // get a more accurate analysis
4115        while (commonSupers.nonEmpty()) {
4116            Type t1 = asSuper(from, commonSupers.head.tsym);
4117            Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
4118            if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4119                return false;
4120            giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
4121            commonSupers = commonSupers.tail;
4122        }
4123        if (giveWarning && !isReifiable(reverse ? from : to))
4124            warn.warn(LintCategory.UNCHECKED);
4125        return true;
4126    }
4127
4128    private boolean sideCastFinal(Type from, Type to, Warner warn) {
4129        // We are casting from type $from$ to type $to$, which are
4130        // unrelated types one of which is final and the other of
4131        // which is an interface.  This method
4132        // tries to reject a cast by transferring type parameters
4133        // from the final class to the interface.
4134        boolean reverse = false;
4135        Type target = to;
4136        if ((to.tsym.flags() & INTERFACE) == 0) {
4137            Assert.check((from.tsym.flags() & INTERFACE) != 0);
4138            reverse = true;
4139            to = from;
4140            from = target;
4141        }
4142        Assert.check((from.tsym.flags() & FINAL) != 0);
4143        Type t1 = asSuper(from, to.tsym);
4144        if (t1 == null) return false;
4145        Type t2 = to;
4146        if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4147            return false;
4148        if (!isReifiable(target) &&
4149            (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
4150            warn.warn(LintCategory.UNCHECKED);
4151        return true;
4152    }
4153
4154    private boolean giveWarning(Type from, Type to) {
4155        List<Type> bounds = to.isCompound() ?
4156                directSupertypes(to) : List.of(to);
4157        for (Type b : bounds) {
4158            Type subFrom = asSub(from, b.tsym);
4159            if (b.isParameterized() &&
4160                    (!(isUnbounded(b) ||
4161                    isSubtype(from, b) ||
4162                    ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
4163                return true;
4164            }
4165        }
4166        return false;
4167    }
4168
4169    private List<Type> superClosure(Type t, Type s) {
4170        List<Type> cl = List.nil();
4171        for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
4172            if (isSubtype(s, erasure(l.head))) {
4173                cl = insert(cl, l.head);
4174            } else {
4175                cl = union(cl, superClosure(l.head, s));
4176            }
4177        }
4178        return cl;
4179    }
4180
4181    private boolean containsTypeEquivalent(Type t, Type s) {
4182        return isSameType(t, s) || // shortcut
4183            containsType(t, s) && containsType(s, t);
4184    }
4185
4186    // <editor-fold defaultstate="collapsed" desc="adapt">
4187    /**
4188     * Adapt a type by computing a substitution which maps a source
4189     * type to a target type.
4190     *
4191     * @param source    the source type
4192     * @param target    the target type
4193     * @param from      the type variables of the computed substitution
4194     * @param to        the types of the computed substitution.
4195     */
4196    public void adapt(Type source,
4197                       Type target,
4198                       ListBuffer<Type> from,
4199                       ListBuffer<Type> to) throws AdaptFailure {
4200        new Adapter(from, to).adapt(source, target);
4201    }
4202
4203    class Adapter extends SimpleVisitor<Void, Type> {
4204
4205        ListBuffer<Type> from;
4206        ListBuffer<Type> to;
4207        Map<Symbol,Type> mapping;
4208
4209        Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
4210            this.from = from;
4211            this.to = to;
4212            mapping = new HashMap<>();
4213        }
4214
4215        public void adapt(Type source, Type target) throws AdaptFailure {
4216            visit(source, target);
4217            List<Type> fromList = from.toList();
4218            List<Type> toList = to.toList();
4219            while (!fromList.isEmpty()) {
4220                Type val = mapping.get(fromList.head.tsym);
4221                if (toList.head != val)
4222                    toList.head = val;
4223                fromList = fromList.tail;
4224                toList = toList.tail;
4225            }
4226        }
4227
4228        @Override
4229        public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
4230            if (target.hasTag(CLASS))
4231                adaptRecursive(source.allparams(), target.allparams());
4232            return null;
4233        }
4234
4235        @Override
4236        public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
4237            if (target.hasTag(ARRAY))
4238                adaptRecursive(elemtype(source), elemtype(target));
4239            return null;
4240        }
4241
4242        @Override
4243        public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
4244            if (source.isExtendsBound())
4245                adaptRecursive(wildUpperBound(source), wildUpperBound(target));
4246            else if (source.isSuperBound())
4247                adaptRecursive(wildLowerBound(source), wildLowerBound(target));
4248            return null;
4249        }
4250
4251        @Override
4252        public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
4253            // Check to see if there is
4254            // already a mapping for $source$, in which case
4255            // the old mapping will be merged with the new
4256            Type val = mapping.get(source.tsym);
4257            if (val != null) {
4258                if (val.isSuperBound() && target.isSuperBound()) {
4259                    val = isSubtype(wildLowerBound(val), wildLowerBound(target))
4260                        ? target : val;
4261                } else if (val.isExtendsBound() && target.isExtendsBound()) {
4262                    val = isSubtype(wildUpperBound(val), wildUpperBound(target))
4263                        ? val : target;
4264                } else if (!isSameType(val, target)) {
4265                    throw new AdaptFailure();
4266                }
4267            } else {
4268                val = target;
4269                from.append(source);
4270                to.append(target);
4271            }
4272            mapping.put(source.tsym, val);
4273            return null;
4274        }
4275
4276        @Override
4277        public Void visitType(Type source, Type target) {
4278            return null;
4279        }
4280
4281        private Set<TypePair> cache = new HashSet<>();
4282
4283        private void adaptRecursive(Type source, Type target) {
4284            TypePair pair = new TypePair(source, target);
4285            if (cache.add(pair)) {
4286                try {
4287                    visit(source, target);
4288                } finally {
4289                    cache.remove(pair);
4290                }
4291            }
4292        }
4293
4294        private void adaptRecursive(List<Type> source, List<Type> target) {
4295            if (source.length() == target.length()) {
4296                while (source.nonEmpty()) {
4297                    adaptRecursive(source.head, target.head);
4298                    source = source.tail;
4299                    target = target.tail;
4300                }
4301            }
4302        }
4303    }
4304
4305    public static class AdaptFailure extends RuntimeException {
4306        static final long serialVersionUID = -7490231548272701566L;
4307    }
4308
4309    private void adaptSelf(Type t,
4310                           ListBuffer<Type> from,
4311                           ListBuffer<Type> to) {
4312        try {
4313            //if (t.tsym.type != t)
4314                adapt(t.tsym.type, t, from, to);
4315        } catch (AdaptFailure ex) {
4316            // Adapt should never fail calculating a mapping from
4317            // t.tsym.type to t as there can be no merge problem.
4318            throw new AssertionError(ex);
4319        }
4320    }
4321    // </editor-fold>
4322
4323    /**
4324     * Rewrite all type variables (universal quantifiers) in the given
4325     * type to wildcards (existential quantifiers).  This is used to
4326     * determine if a cast is allowed.  For example, if high is true
4327     * and {@code T <: Number}, then {@code List<T>} is rewritten to
4328     * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
4329     * List<? extends Number>} a {@code List<T>} can be cast to {@code
4330     * List<Integer>} with a warning.
4331     * @param t a type
4332     * @param high if true return an upper bound; otherwise a lower
4333     * bound
4334     * @param rewriteTypeVars only rewrite captured wildcards if false;
4335     * otherwise rewrite all type variables
4336     * @return the type rewritten with wildcards (existential
4337     * quantifiers) only
4338     */
4339    private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4340        return new Rewriter(high, rewriteTypeVars).visit(t);
4341    }
4342
4343    class Rewriter extends UnaryVisitor<Type> {
4344
4345        boolean high;
4346        boolean rewriteTypeVars;
4347
4348        Rewriter(boolean high, boolean rewriteTypeVars) {
4349            this.high = high;
4350            this.rewriteTypeVars = rewriteTypeVars;
4351        }
4352
4353        @Override
4354        public Type visitClassType(ClassType t, Void s) {
4355            ListBuffer<Type> rewritten = new ListBuffer<>();
4356            boolean changed = false;
4357            for (Type arg : t.allparams()) {
4358                Type bound = visit(arg);
4359                if (arg != bound) {
4360                    changed = true;
4361                }
4362                rewritten.append(bound);
4363            }
4364            if (changed)
4365                return subst(t.tsym.type,
4366                        t.tsym.type.allparams(),
4367                        rewritten.toList());
4368            else
4369                return t;
4370        }
4371
4372        public Type visitType(Type t, Void s) {
4373            return t;
4374        }
4375
4376        @Override
4377        public Type visitCapturedType(CapturedType t, Void s) {
4378            Type w_bound = t.wildcard.type;
4379            Type bound = w_bound.contains(t) ?
4380                        erasure(w_bound) :
4381                        visit(w_bound);
4382            return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4383        }
4384
4385        @Override
4386        public Type visitTypeVar(TypeVar t, Void s) {
4387            if (rewriteTypeVars) {
4388                Type bound = t.bound.contains(t) ?
4389                        erasure(t.bound) :
4390                        visit(t.bound);
4391                return rewriteAsWildcardType(bound, t, EXTENDS);
4392            } else {
4393                return t;
4394            }
4395        }
4396
4397        @Override
4398        public Type visitWildcardType(WildcardType t, Void s) {
4399            Type bound2 = visit(t.type);
4400            return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4401        }
4402
4403        private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4404            switch (bk) {
4405               case EXTENDS: return high ?
4406                       makeExtendsWildcard(B(bound), formal) :
4407                       makeExtendsWildcard(syms.objectType, formal);
4408               case SUPER: return high ?
4409                       makeSuperWildcard(syms.botType, formal) :
4410                       makeSuperWildcard(B(bound), formal);
4411               case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4412               default:
4413                   Assert.error("Invalid bound kind " + bk);
4414                   return null;
4415            }
4416        }
4417
4418        Type B(Type t) {
4419            while (t.hasTag(WILDCARD)) {
4420                WildcardType w = (WildcardType)t;
4421                t = high ?
4422                    w.getExtendsBound() :
4423                    w.getSuperBound();
4424                if (t == null) {
4425                    t = high ? syms.objectType : syms.botType;
4426                }
4427            }
4428            return t;
4429        }
4430    }
4431
4432
4433    /**
4434     * Create a wildcard with the given upper (extends) bound; create
4435     * an unbounded wildcard if bound is Object.
4436     *
4437     * @param bound the upper bound
4438     * @param formal the formal type parameter that will be
4439     * substituted by the wildcard
4440     */
4441    private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4442        if (bound == syms.objectType) {
4443            return new WildcardType(syms.objectType,
4444                                    BoundKind.UNBOUND,
4445                                    syms.boundClass,
4446                                    formal);
4447        } else {
4448            return new WildcardType(bound,
4449                                    BoundKind.EXTENDS,
4450                                    syms.boundClass,
4451                                    formal);
4452        }
4453    }
4454
4455    /**
4456     * Create a wildcard with the given lower (super) bound; create an
4457     * unbounded wildcard if bound is bottom (type of {@code null}).
4458     *
4459     * @param bound the lower bound
4460     * @param formal the formal type parameter that will be
4461     * substituted by the wildcard
4462     */
4463    private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4464        if (bound.hasTag(BOT)) {
4465            return new WildcardType(syms.objectType,
4466                                    BoundKind.UNBOUND,
4467                                    syms.boundClass,
4468                                    formal);
4469        } else {
4470            return new WildcardType(bound,
4471                                    BoundKind.SUPER,
4472                                    syms.boundClass,
4473                                    formal);
4474        }
4475    }
4476
4477    /**
4478     * A wrapper for a type that allows use in sets.
4479     */
4480    public static class UniqueType {
4481        public final Type type;
4482        final Types types;
4483
4484        public UniqueType(Type type, Types types) {
4485            this.type = type;
4486            this.types = types;
4487        }
4488
4489        public int hashCode() {
4490            return types.hashCode(type);
4491        }
4492
4493        public boolean equals(Object obj) {
4494            return (obj instanceof UniqueType) &&
4495                types.isSameType(type, ((UniqueType)obj).type);
4496        }
4497
4498        public String toString() {
4499            return type.toString();
4500        }
4501
4502    }
4503    // </editor-fold>
4504
4505    // <editor-fold defaultstate="collapsed" desc="Visitors">
4506    /**
4507     * A default visitor for types.  All visitor methods except
4508     * visitType are implemented by delegating to visitType.  Concrete
4509     * subclasses must provide an implementation of visitType and can
4510     * override other methods as needed.
4511     *
4512     * @param <R> the return type of the operation implemented by this
4513     * visitor; use Void if no return type is needed.
4514     * @param <S> the type of the second argument (the first being the
4515     * type itself) of the operation implemented by this visitor; use
4516     * Void if a second argument is not needed.
4517     */
4518    public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4519        final public R visit(Type t, S s)               { return t.accept(this, s); }
4520        public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
4521        public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4522        public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
4523        public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
4524        public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
4525        public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
4526        public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4527        public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
4528        public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
4529        public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
4530    }
4531
4532    /**
4533     * A default visitor for symbols.  All visitor methods except
4534     * visitSymbol are implemented by delegating to visitSymbol.  Concrete
4535     * subclasses must provide an implementation of visitSymbol and can
4536     * override other methods as needed.
4537     *
4538     * @param <R> the return type of the operation implemented by this
4539     * visitor; use Void if no return type is needed.
4540     * @param <S> the type of the second argument (the first being the
4541     * symbol itself) of the operation implemented by this visitor; use
4542     * Void if a second argument is not needed.
4543     */
4544    public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4545        final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
4546        public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
4547        public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
4548        public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
4549        public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
4550        public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
4551        public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
4552    }
4553
4554    /**
4555     * A <em>simple</em> visitor for types.  This visitor is simple as
4556     * captured wildcards, for-all types (generic methods), and
4557     * undetermined type variables (part of inference) are hidden.
4558     * Captured wildcards are hidden by treating them as type
4559     * variables and the rest are hidden by visiting their qtypes.
4560     *
4561     * @param <R> the return type of the operation implemented by this
4562     * visitor; use Void if no return type is needed.
4563     * @param <S> the type of the second argument (the first being the
4564     * type itself) of the operation implemented by this visitor; use
4565     * Void if a second argument is not needed.
4566     */
4567    public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4568        @Override
4569        public R visitCapturedType(CapturedType t, S s) {
4570            return visitTypeVar(t, s);
4571        }
4572        @Override
4573        public R visitForAll(ForAll t, S s) {
4574            return visit(t.qtype, s);
4575        }
4576        @Override
4577        public R visitUndetVar(UndetVar t, S s) {
4578            return visit(t.qtype, s);
4579        }
4580    }
4581
4582    /**
4583     * A plain relation on types.  That is a 2-ary function on the
4584     * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
4585     * <!-- In plain text: Type x Type -> Boolean -->
4586     */
4587    public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
4588
4589    /**
4590     * A convenience visitor for implementing operations that only
4591     * require one argument (the type itself), that is, unary
4592     * operations.
4593     *
4594     * @param <R> the return type of the operation implemented by this
4595     * visitor; use Void if no return type is needed.
4596     */
4597    public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
4598        final public R visit(Type t) { return t.accept(this, null); }
4599    }
4600
4601    /**
4602     * A visitor for implementing a mapping from types to types.  The
4603     * default behavior of this class is to implement the identity
4604     * mapping (mapping a type to itself).  This can be overridden in
4605     * subclasses.
4606     *
4607     * @param <S> the type of the second argument (the first being the
4608     * type itself) of this mapping; use Void if a second argument is
4609     * not needed.
4610     */
4611    public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
4612        final public Type visit(Type t) { return t.accept(this, null); }
4613        public Type visitType(Type t, S s) { return t; }
4614    }
4615    // </editor-fold>
4616
4617
4618    // <editor-fold defaultstate="collapsed" desc="Annotation support">
4619
4620    public RetentionPolicy getRetention(Attribute.Compound a) {
4621        return getRetention(a.type.tsym);
4622    }
4623
4624    public RetentionPolicy getRetention(TypeSymbol sym) {
4625        RetentionPolicy vis = RetentionPolicy.CLASS; // the default
4626        Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
4627        if (c != null) {
4628            Attribute value = c.member(names.value);
4629            if (value != null && value instanceof Attribute.Enum) {
4630                Name levelName = ((Attribute.Enum)value).value.name;
4631                if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
4632                else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
4633                else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
4634                else ;// /* fail soft */ throw new AssertionError(levelName);
4635            }
4636        }
4637        return vis;
4638    }
4639    // </editor-fold>
4640
4641    // <editor-fold defaultstate="collapsed" desc="Signature Generation">
4642
4643    public static abstract class SignatureGenerator {
4644
4645        private final Types types;
4646
4647        protected abstract void append(char ch);
4648        protected abstract void append(byte[] ba);
4649        protected abstract void append(Name name);
4650        protected void classReference(ClassSymbol c) { /* by default: no-op */ }
4651
4652        protected SignatureGenerator(Types types) {
4653            this.types = types;
4654        }
4655
4656        /**
4657         * Assemble signature of given type in string buffer.
4658         */
4659        public void assembleSig(Type type) {
4660            switch (type.getTag()) {
4661                case BYTE:
4662                    append('B');
4663                    break;
4664                case SHORT:
4665                    append('S');
4666                    break;
4667                case CHAR:
4668                    append('C');
4669                    break;
4670                case INT:
4671                    append('I');
4672                    break;
4673                case LONG:
4674                    append('J');
4675                    break;
4676                case FLOAT:
4677                    append('F');
4678                    break;
4679                case DOUBLE:
4680                    append('D');
4681                    break;
4682                case BOOLEAN:
4683                    append('Z');
4684                    break;
4685                case VOID:
4686                    append('V');
4687                    break;
4688                case CLASS:
4689                    append('L');
4690                    assembleClassSig(type);
4691                    append(';');
4692                    break;
4693                case ARRAY:
4694                    ArrayType at = (ArrayType) type;
4695                    append('[');
4696                    assembleSig(at.elemtype);
4697                    break;
4698                case METHOD:
4699                    MethodType mt = (MethodType) type;
4700                    append('(');
4701                    assembleSig(mt.argtypes);
4702                    append(')');
4703                    assembleSig(mt.restype);
4704                    if (hasTypeVar(mt.thrown)) {
4705                        for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
4706                            append('^');
4707                            assembleSig(l.head);
4708                        }
4709                    }
4710                    break;
4711                case WILDCARD: {
4712                    Type.WildcardType ta = (Type.WildcardType) type;
4713                    switch (ta.kind) {
4714                        case SUPER:
4715                            append('-');
4716                            assembleSig(ta.type);
4717                            break;
4718                        case EXTENDS:
4719                            append('+');
4720                            assembleSig(ta.type);
4721                            break;
4722                        case UNBOUND:
4723                            append('*');
4724                            break;
4725                        default:
4726                            throw new AssertionError(ta.kind);
4727                    }
4728                    break;
4729                }
4730                case TYPEVAR:
4731                    append('T');
4732                    append(type.tsym.name);
4733                    append(';');
4734                    break;
4735                case FORALL:
4736                    Type.ForAll ft = (Type.ForAll) type;
4737                    assembleParamsSig(ft.tvars);
4738                    assembleSig(ft.qtype);
4739                    break;
4740                default:
4741                    throw new AssertionError("typeSig " + type.getTag());
4742            }
4743        }
4744
4745        public boolean hasTypeVar(List<Type> l) {
4746            while (l.nonEmpty()) {
4747                if (l.head.hasTag(TypeTag.TYPEVAR)) {
4748                    return true;
4749                }
4750                l = l.tail;
4751            }
4752            return false;
4753        }
4754
4755        public void assembleClassSig(Type type) {
4756            ClassType ct = (ClassType) type;
4757            ClassSymbol c = (ClassSymbol) ct.tsym;
4758            classReference(c);
4759            Type outer = ct.getEnclosingType();
4760            if (outer.allparams().nonEmpty()) {
4761                boolean rawOuter =
4762                        c.owner.kind == MTH || // either a local class
4763                        c.name == types.names.empty; // or anonymous
4764                assembleClassSig(rawOuter
4765                        ? types.erasure(outer)
4766                        : outer);
4767                append(rawOuter ? '$' : '.');
4768                Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
4769                append(rawOuter
4770                        ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
4771                        : c.name);
4772            } else {
4773                append(externalize(c.flatname));
4774            }
4775            if (ct.getTypeArguments().nonEmpty()) {
4776                append('<');
4777                assembleSig(ct.getTypeArguments());
4778                append('>');
4779            }
4780        }
4781
4782        public void assembleParamsSig(List<Type> typarams) {
4783            append('<');
4784            for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
4785                Type.TypeVar tvar = (Type.TypeVar) ts.head;
4786                append(tvar.tsym.name);
4787                List<Type> bounds = types.getBounds(tvar);
4788                if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
4789                    append(':');
4790                }
4791                for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
4792                    append(':');
4793                    assembleSig(l.head);
4794                }
4795            }
4796            append('>');
4797        }
4798
4799        private void assembleSig(List<Type> types) {
4800            for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
4801                assembleSig(ts.head);
4802            }
4803        }
4804    }
4805    // </editor-fold>
4806
4807    public void newRound() {
4808        descCache._map.clear();
4809        isDerivedRawCache.clear();
4810        implCache._map.clear();
4811        membersCache._map.clear();
4812        closureCache.clear();
4813    }
4814}
4815