Check.java revision 3578:b56896d30c0f
1/*
2 * Copyright (c) 1999, 2016, 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.comp;
27
28import java.util.*;
29
30import javax.tools.JavaFileManager;
31
32import com.sun.tools.javac.code.*;
33import com.sun.tools.javac.code.Attribute.Compound;
34import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
35import com.sun.tools.javac.jvm.*;
36import com.sun.tools.javac.resources.CompilerProperties.Errors;
37import com.sun.tools.javac.resources.CompilerProperties.Fragments;
38import com.sun.tools.javac.tree.*;
39import com.sun.tools.javac.util.*;
40import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
41import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
42import com.sun.tools.javac.util.List;
43
44import com.sun.tools.javac.code.Lint;
45import com.sun.tools.javac.code.Lint.LintCategory;
46import com.sun.tools.javac.code.Scope.WriteableScope;
47import com.sun.tools.javac.code.Type.*;
48import com.sun.tools.javac.code.Symbol.*;
49import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
50import com.sun.tools.javac.comp.Infer.FreeTypeListener;
51import com.sun.tools.javac.tree.JCTree.*;
52
53import static com.sun.tools.javac.code.Flags.*;
54import static com.sun.tools.javac.code.Flags.ANNOTATION;
55import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
56import static com.sun.tools.javac.code.Kinds.*;
57import static com.sun.tools.javac.code.Kinds.Kind.*;
58import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
59import static com.sun.tools.javac.code.TypeTag.*;
60import static com.sun.tools.javac.code.TypeTag.WILDCARD;
61
62import static com.sun.tools.javac.tree.JCTree.Tag.*;
63
64/** Type checking helper class for the attribution phase.
65 *
66 *  <p><b>This is NOT part of any supported API.
67 *  If you write code that depends on this, you do so at your own risk.
68 *  This code and its internal interfaces are subject to change or
69 *  deletion without notice.</b>
70 */
71public class Check {
72    protected static final Context.Key<Check> checkKey = new Context.Key<>();
73
74    private final Names names;
75    private final Log log;
76    private final Resolve rs;
77    private final Symtab syms;
78    private final Enter enter;
79    private final DeferredAttr deferredAttr;
80    private final Infer infer;
81    private final Types types;
82    private final TypeAnnotations typeAnnotations;
83    private final JCDiagnostic.Factory diags;
84    private final JavaFileManager fileManager;
85    private final Source source;
86    private final Profile profile;
87    private final boolean warnOnAccessToSensitiveMembers;
88
89    // The set of lint options currently in effect. It is initialized
90    // from the context, and then is set/reset as needed by Attr as it
91    // visits all the various parts of the trees during attribution.
92    private Lint lint;
93
94    // The method being analyzed in Attr - it is set/reset as needed by
95    // Attr as it visits new method declarations.
96    private MethodSymbol method;
97
98    public static Check instance(Context context) {
99        Check instance = context.get(checkKey);
100        if (instance == null)
101            instance = new Check(context);
102        return instance;
103    }
104
105    protected Check(Context context) {
106        context.put(checkKey, this);
107
108        names = Names.instance(context);
109        dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
110            names.FIELD, names.METHOD, names.CONSTRUCTOR,
111            names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
112        log = Log.instance(context);
113        rs = Resolve.instance(context);
114        syms = Symtab.instance(context);
115        enter = Enter.instance(context);
116        deferredAttr = DeferredAttr.instance(context);
117        infer = Infer.instance(context);
118        types = Types.instance(context);
119        typeAnnotations = TypeAnnotations.instance(context);
120        diags = JCDiagnostic.Factory.instance(context);
121        Options options = Options.instance(context);
122        lint = Lint.instance(context);
123        fileManager = context.get(JavaFileManager.class);
124
125        source = Source.instance(context);
126        allowSimplifiedVarargs = source.allowSimplifiedVarargs();
127        allowDefaultMethods = source.allowDefaultMethods();
128        allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
129        allowPrivateSafeVarargs = source.allowPrivateSafeVarargs();
130        allowDiamondWithAnonymousClassCreation = source.allowDiamondWithAnonymousClassCreation();
131        warnOnAccessToSensitiveMembers = options.isSet("warnOnAccessToSensitiveMembers");
132
133        Target target = Target.instance(context);
134        syntheticNameChar = target.syntheticNameChar();
135
136        profile = Profile.instance(context);
137
138        boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
139        boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
140        boolean enforceMandatoryWarnings = true;
141
142        deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
143                enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
144        uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
145                enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
146        sunApiHandler = new MandatoryWarningHandler(log, false,
147                enforceMandatoryWarnings, "sunapi", null);
148
149        deferredLintHandler = DeferredLintHandler.instance(context);
150    }
151
152    /** Switch: simplified varargs enabled?
153     */
154    boolean allowSimplifiedVarargs;
155
156    /** Switch: default methods enabled?
157     */
158    boolean allowDefaultMethods;
159
160    /** Switch: should unrelated return types trigger a method clash?
161     */
162    boolean allowStrictMethodClashCheck;
163
164    /** Switch: can the @SafeVarargs annotation be applied to private methods?
165     */
166    boolean allowPrivateSafeVarargs;
167
168    /** Switch: can diamond inference be used in anonymous instance creation ?
169     */
170    boolean allowDiamondWithAnonymousClassCreation;
171
172    /** Character for synthetic names
173     */
174    char syntheticNameChar;
175
176    /** A table mapping flat names of all compiled classes for each module in this run
177     *  to their symbols; maintained from outside.
178     */
179    private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
180
181    /** A handler for messages about deprecated usage.
182     */
183    private MandatoryWarningHandler deprecationHandler;
184
185    /** A handler for messages about unchecked or unsafe usage.
186     */
187    private MandatoryWarningHandler uncheckedHandler;
188
189    /** A handler for messages about using proprietary API.
190     */
191    private MandatoryWarningHandler sunApiHandler;
192
193    /** A handler for deferred lint warnings.
194     */
195    private DeferredLintHandler deferredLintHandler;
196
197/* *************************************************************************
198 * Errors and Warnings
199 **************************************************************************/
200
201    Lint setLint(Lint newLint) {
202        Lint prev = lint;
203        lint = newLint;
204        return prev;
205    }
206
207    MethodSymbol setMethod(MethodSymbol newMethod) {
208        MethodSymbol prev = method;
209        method = newMethod;
210        return prev;
211    }
212
213    /** Warn about deprecated symbol.
214     *  @param pos        Position to be used for error reporting.
215     *  @param sym        The deprecated symbol.
216     */
217    void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
218        if (!lint.isSuppressed(LintCategory.DEPRECATION))
219            deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
220    }
221
222    /** Warn about unchecked operation.
223     *  @param pos        Position to be used for error reporting.
224     *  @param msg        A string describing the problem.
225     */
226    public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
227        if (!lint.isSuppressed(LintCategory.UNCHECKED))
228            uncheckedHandler.report(pos, msg, args);
229    }
230
231    /** Warn about unsafe vararg method decl.
232     *  @param pos        Position to be used for error reporting.
233     */
234    void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
235        if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
236            log.warning(LintCategory.VARARGS, pos, key, args);
237    }
238
239    public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
240        if (lint.isEnabled(LintCategory.STATIC))
241            log.warning(LintCategory.STATIC, pos, msg, args);
242    }
243
244    /** Warn about division by integer constant zero.
245     *  @param pos        Position to be used for error reporting.
246     */
247    void warnDivZero(DiagnosticPosition pos) {
248        if (lint.isEnabled(LintCategory.DIVZERO))
249            log.warning(LintCategory.DIVZERO, pos, "div.zero");
250    }
251
252    /**
253     * Report any deferred diagnostics.
254     */
255    public void reportDeferredDiagnostics() {
256        deprecationHandler.reportDeferredDiagnostic();
257        uncheckedHandler.reportDeferredDiagnostic();
258        sunApiHandler.reportDeferredDiagnostic();
259    }
260
261
262    /** Report a failure to complete a class.
263     *  @param pos        Position to be used for error reporting.
264     *  @param ex         The failure to report.
265     */
266    public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
267        log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue());
268        if (ex instanceof ClassFinder.BadClassFile) throw new Abort();
269        else return syms.errType;
270    }
271
272    /** Report an error that wrong type tag was found.
273     *  @param pos        Position to be used for error reporting.
274     *  @param required   An internationalized string describing the type tag
275     *                    required.
276     *  @param found      The type that was found.
277     */
278    Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
279        // this error used to be raised by the parser,
280        // but has been delayed to this point:
281        if (found instanceof Type && ((Type)found).hasTag(VOID)) {
282            log.error(pos, "illegal.start.of.type");
283            return syms.errType;
284        }
285        log.error(pos, "type.found.req", found, required);
286        return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
287    }
288
289    /** Report an error that symbol cannot be referenced before super
290     *  has been called.
291     *  @param pos        Position to be used for error reporting.
292     *  @param sym        The referenced symbol.
293     */
294    void earlyRefError(DiagnosticPosition pos, Symbol sym) {
295        log.error(pos, "cant.ref.before.ctor.called", sym);
296    }
297
298    /** Report duplicate declaration error.
299     */
300    void duplicateError(DiagnosticPosition pos, Symbol sym) {
301        if (!sym.type.isErroneous()) {
302            Symbol location = sym.location();
303            if (location.kind == MTH &&
304                    ((MethodSymbol)location).isStaticOrInstanceInit()) {
305                log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
306                        kindName(sym.location()), kindName(sym.location().enclClass()),
307                        sym.location().enclClass());
308            } else {
309                log.error(pos, "already.defined", kindName(sym), sym,
310                        kindName(sym.location()), sym.location());
311            }
312        }
313    }
314
315    /** Report array/varargs duplicate declaration
316     */
317    void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
318        if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
319            log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
320        }
321    }
322
323/* ************************************************************************
324 * duplicate declaration checking
325 *************************************************************************/
326
327    /** Check that variable does not hide variable with same name in
328     *  immediately enclosing local scope.
329     *  @param pos           Position for error reporting.
330     *  @param v             The symbol.
331     *  @param s             The scope.
332     */
333    void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
334        for (Symbol sym : s.getSymbolsByName(v.name)) {
335            if (sym.owner != v.owner) break;
336            if (sym.kind == VAR &&
337                sym.owner.kind.matches(KindSelector.VAL_MTH) &&
338                v.name != names.error) {
339                duplicateError(pos, sym);
340                return;
341            }
342        }
343    }
344
345    /** Check that a class or interface does not hide a class or
346     *  interface with same name in immediately enclosing local scope.
347     *  @param pos           Position for error reporting.
348     *  @param c             The symbol.
349     *  @param s             The scope.
350     */
351    void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
352        for (Symbol sym : s.getSymbolsByName(c.name)) {
353            if (sym.owner != c.owner) break;
354            if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
355                sym.owner.kind.matches(KindSelector.VAL_MTH) &&
356                c.name != names.error) {
357                duplicateError(pos, sym);
358                return;
359            }
360        }
361    }
362
363    /** Check that class does not have the same name as one of
364     *  its enclosing classes, or as a class defined in its enclosing scope.
365     *  return true if class is unique in its enclosing scope.
366     *  @param pos           Position for error reporting.
367     *  @param name          The class name.
368     *  @param s             The enclosing scope.
369     */
370    boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
371        for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
372            if (sym.kind == TYP && sym.name != names.error) {
373                duplicateError(pos, sym);
374                return false;
375            }
376        }
377        for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
378            if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
379                duplicateError(pos, sym);
380                return true;
381            }
382        }
383        return true;
384    }
385
386/* *************************************************************************
387 * Class name generation
388 **************************************************************************/
389
390
391    private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
392
393    /** Return name of local class.
394     *  This is of the form   {@code <enclClass> $ n <classname> }
395     *  where
396     *    enclClass is the flat name of the enclosing class,
397     *    classname is the simple name of the local class
398     */
399    Name localClassName(ClassSymbol c) {
400        Name enclFlatname = c.owner.enclClass().flatname;
401        String enclFlatnameStr = enclFlatname.toString();
402        Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
403        Integer index = localClassNameIndexes.get(key);
404        for (int i = (index == null) ? 1 : index; ; i++) {
405            Name flatname = names.fromString(enclFlatnameStr
406                    + syntheticNameChar + i + c.name);
407            if (getCompiled(c.packge().modle, flatname) == null) {
408                localClassNameIndexes.put(key, i + 1);
409                return flatname;
410            }
411        }
412    }
413
414    void clearLocalClassNameIndexes(ClassSymbol c) {
415        localClassNameIndexes.remove(new Pair<>(
416                c.owner.enclClass().flatname, c.name));
417    }
418
419    public void newRound() {
420        compiled.clear();
421        localClassNameIndexes.clear();
422    }
423
424    public void putCompiled(ClassSymbol csym) {
425        compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
426    }
427
428    public ClassSymbol getCompiled(ClassSymbol csym) {
429        return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
430    }
431
432    public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
433        return compiled.get(Pair.of(msym, flatname));
434    }
435
436    public void removeCompiled(ClassSymbol csym) {
437        compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
438    }
439
440/* *************************************************************************
441 * Type Checking
442 **************************************************************************/
443
444    /**
445     * A check context is an object that can be used to perform compatibility
446     * checks - depending on the check context, meaning of 'compatibility' might
447     * vary significantly.
448     */
449    public interface CheckContext {
450        /**
451         * Is type 'found' compatible with type 'req' in given context
452         */
453        boolean compatible(Type found, Type req, Warner warn);
454        /**
455         * Report a check error
456         */
457        void report(DiagnosticPosition pos, JCDiagnostic details);
458        /**
459         * Obtain a warner for this check context
460         */
461        public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
462
463        public InferenceContext inferenceContext();
464
465        public DeferredAttr.DeferredAttrContext deferredAttrContext();
466    }
467
468    /**
469     * This class represent a check context that is nested within another check
470     * context - useful to check sub-expressions. The default behavior simply
471     * redirects all method calls to the enclosing check context leveraging
472     * the forwarding pattern.
473     */
474    static class NestedCheckContext implements CheckContext {
475        CheckContext enclosingContext;
476
477        NestedCheckContext(CheckContext enclosingContext) {
478            this.enclosingContext = enclosingContext;
479        }
480
481        public boolean compatible(Type found, Type req, Warner warn) {
482            return enclosingContext.compatible(found, req, warn);
483        }
484
485        public void report(DiagnosticPosition pos, JCDiagnostic details) {
486            enclosingContext.report(pos, details);
487        }
488
489        public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
490            return enclosingContext.checkWarner(pos, found, req);
491        }
492
493        public InferenceContext inferenceContext() {
494            return enclosingContext.inferenceContext();
495        }
496
497        public DeferredAttrContext deferredAttrContext() {
498            return enclosingContext.deferredAttrContext();
499        }
500    }
501
502    /**
503     * Check context to be used when evaluating assignment/return statements
504     */
505    CheckContext basicHandler = new CheckContext() {
506        public void report(DiagnosticPosition pos, JCDiagnostic details) {
507            log.error(pos, "prob.found.req", details);
508        }
509        public boolean compatible(Type found, Type req, Warner warn) {
510            return types.isAssignable(found, req, warn);
511        }
512
513        public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
514            return convertWarner(pos, found, req);
515        }
516
517        public InferenceContext inferenceContext() {
518            return infer.emptyContext;
519        }
520
521        public DeferredAttrContext deferredAttrContext() {
522            return deferredAttr.emptyDeferredAttrContext;
523        }
524
525        @Override
526        public String toString() {
527            return "CheckContext: basicHandler";
528        }
529    };
530
531    /** Check that a given type is assignable to a given proto-type.
532     *  If it is, return the type, otherwise return errType.
533     *  @param pos        Position to be used for error reporting.
534     *  @param found      The type that was found.
535     *  @param req        The type that was required.
536     */
537    public Type checkType(DiagnosticPosition pos, Type found, Type req) {
538        return checkType(pos, found, req, basicHandler);
539    }
540
541    Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
542        final InferenceContext inferenceContext = checkContext.inferenceContext();
543        if (inferenceContext.free(req) || inferenceContext.free(found)) {
544            inferenceContext.addFreeTypeListener(List.of(req, found), new FreeTypeListener() {
545                @Override
546                public void typesInferred(InferenceContext inferenceContext) {
547                    checkType(pos, inferenceContext.asInstType(found), inferenceContext.asInstType(req), checkContext);
548                }
549            });
550        }
551        if (req.hasTag(ERROR))
552            return req;
553        if (req.hasTag(NONE))
554            return found;
555        if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
556            return found;
557        } else {
558            if (found.isNumeric() && req.isNumeric()) {
559                checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
560                return types.createErrorType(found);
561            }
562            checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
563            return types.createErrorType(found);
564        }
565    }
566
567    /** Check that a given type can be cast to a given target type.
568     *  Return the result of the cast.
569     *  @param pos        Position to be used for error reporting.
570     *  @param found      The type that is being cast.
571     *  @param req        The target type of the cast.
572     */
573    Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
574        return checkCastable(pos, found, req, basicHandler);
575    }
576    Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
577        if (types.isCastable(found, req, castWarner(pos, found, req))) {
578            return req;
579        } else {
580            checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
581            return types.createErrorType(found);
582        }
583    }
584
585    /** Check for redundant casts (i.e. where source type is a subtype of target type)
586     * The problem should only be reported for non-292 cast
587     */
588    public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
589        if (!tree.type.isErroneous()
590                && types.isSameType(tree.expr.type, tree.clazz.type)
591                && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
592                && !is292targetTypeCast(tree)) {
593            deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
594                @Override
595                public void report() {
596                    if (lint.isEnabled(Lint.LintCategory.CAST))
597                        log.warning(Lint.LintCategory.CAST,
598                                tree.pos(), "redundant.cast", tree.clazz.type);
599                }
600            });
601        }
602    }
603    //where
604        private boolean is292targetTypeCast(JCTypeCast tree) {
605            boolean is292targetTypeCast = false;
606            JCExpression expr = TreeInfo.skipParens(tree.expr);
607            if (expr.hasTag(APPLY)) {
608                JCMethodInvocation apply = (JCMethodInvocation)expr;
609                Symbol sym = TreeInfo.symbol(apply.meth);
610                is292targetTypeCast = sym != null &&
611                    sym.kind == MTH &&
612                    (sym.flags() & HYPOTHETICAL) != 0;
613            }
614            return is292targetTypeCast;
615        }
616
617        private static final boolean ignoreAnnotatedCasts = true;
618
619    /** Check that a type is within some bounds.
620     *
621     *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
622     *  type argument.
623     *  @param a             The type that should be bounded by bs.
624     *  @param bound         The bound.
625     */
626    private boolean checkExtends(Type a, Type bound) {
627         if (a.isUnbound()) {
628             return true;
629         } else if (!a.hasTag(WILDCARD)) {
630             a = types.cvarUpperBound(a);
631             return types.isSubtype(a, bound);
632         } else if (a.isExtendsBound()) {
633             return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
634         } else if (a.isSuperBound()) {
635             return !types.notSoftSubtype(types.wildLowerBound(a), bound);
636         }
637         return true;
638     }
639
640    /** Check that type is different from 'void'.
641     *  @param pos           Position to be used for error reporting.
642     *  @param t             The type to be checked.
643     */
644    Type checkNonVoid(DiagnosticPosition pos, Type t) {
645        if (t.hasTag(VOID)) {
646            log.error(pos, "void.not.allowed.here");
647            return types.createErrorType(t);
648        } else {
649            return t;
650        }
651    }
652
653    Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
654        if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
655            return typeTagError(pos,
656                                diags.fragment("type.req.class.array"),
657                                asTypeParam(t));
658        } else {
659            return t;
660        }
661    }
662
663    /** Check that type is a class or interface type.
664     *  @param pos           Position to be used for error reporting.
665     *  @param t             The type to be checked.
666     */
667    Type checkClassType(DiagnosticPosition pos, Type t) {
668        if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
669            return typeTagError(pos,
670                                diags.fragment("type.req.class"),
671                                asTypeParam(t));
672        } else {
673            return t;
674        }
675    }
676    //where
677        private Object asTypeParam(Type t) {
678            return (t.hasTag(TYPEVAR))
679                                    ? diags.fragment("type.parameter", t)
680                                    : t;
681        }
682
683    /** Check that type is a valid qualifier for a constructor reference expression
684     */
685    Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
686        t = checkClassOrArrayType(pos, t);
687        if (t.hasTag(CLASS)) {
688            if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
689                log.error(pos, "abstract.cant.be.instantiated", t.tsym);
690                t = types.createErrorType(t);
691            } else if ((t.tsym.flags() & ENUM) != 0) {
692                log.error(pos, "enum.cant.be.instantiated");
693                t = types.createErrorType(t);
694            } else {
695                t = checkClassType(pos, t, true);
696            }
697        } else if (t.hasTag(ARRAY)) {
698            if (!types.isReifiable(((ArrayType)t).elemtype)) {
699                log.error(pos, "generic.array.creation");
700                t = types.createErrorType(t);
701            }
702        }
703        return t;
704    }
705
706    /** Check that type is a class or interface type.
707     *  @param pos           Position to be used for error reporting.
708     *  @param t             The type to be checked.
709     *  @param noBounds    True if type bounds are illegal here.
710     */
711    Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
712        t = checkClassType(pos, t);
713        if (noBounds && t.isParameterized()) {
714            List<Type> args = t.getTypeArguments();
715            while (args.nonEmpty()) {
716                if (args.head.hasTag(WILDCARD))
717                    return typeTagError(pos,
718                                        diags.fragment("type.req.exact"),
719                                        args.head);
720                args = args.tail;
721            }
722        }
723        return t;
724    }
725
726    /** Check that type is a reference type, i.e. a class, interface or array type
727     *  or a type variable.
728     *  @param pos           Position to be used for error reporting.
729     *  @param t             The type to be checked.
730     */
731    Type checkRefType(DiagnosticPosition pos, Type t) {
732        if (t.isReference())
733            return t;
734        else
735            return typeTagError(pos,
736                                diags.fragment("type.req.ref"),
737                                t);
738    }
739
740    /** Check that each type is a reference type, i.e. a class, interface or array type
741     *  or a type variable.
742     *  @param trees         Original trees, used for error reporting.
743     *  @param types         The types to be checked.
744     */
745    List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
746        List<JCExpression> tl = trees;
747        for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
748            l.head = checkRefType(tl.head.pos(), l.head);
749            tl = tl.tail;
750        }
751        return types;
752    }
753
754    /** Check that type is a null or reference type.
755     *  @param pos           Position to be used for error reporting.
756     *  @param t             The type to be checked.
757     */
758    Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
759        if (t.isReference() || t.hasTag(BOT))
760            return t;
761        else
762            return typeTagError(pos,
763                                diags.fragment("type.req.ref"),
764                                t);
765    }
766
767    /** Check that flag set does not contain elements of two conflicting sets. s
768     *  Return true if it doesn't.
769     *  @param pos           Position to be used for error reporting.
770     *  @param flags         The set of flags to be checked.
771     *  @param set1          Conflicting flags set #1.
772     *  @param set2          Conflicting flags set #2.
773     */
774    boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
775        if ((flags & set1) != 0 && (flags & set2) != 0) {
776            log.error(pos,
777                      "illegal.combination.of.modifiers",
778                      asFlagSet(TreeInfo.firstFlag(flags & set1)),
779                      asFlagSet(TreeInfo.firstFlag(flags & set2)));
780            return false;
781        } else
782            return true;
783    }
784
785    /** Check that usage of diamond operator is correct (i.e. diamond should not
786     * be used with non-generic classes or in anonymous class creation expressions)
787     */
788    Type checkDiamond(JCNewClass tree, Type t) {
789        if (!TreeInfo.isDiamond(tree) ||
790                t.isErroneous()) {
791            return checkClassType(tree.clazz.pos(), t, true);
792        } else if (tree.def != null && !allowDiamondWithAnonymousClassCreation) {
793            log.error(tree.clazz.pos(),
794                    Errors.CantApplyDiamond1(t, Fragments.DiamondAndAnonClassNotSupportedInSource(source.name)));
795            return types.createErrorType(t);
796        } else if (t.tsym.type.getTypeArguments().isEmpty()) {
797            log.error(tree.clazz.pos(),
798                "cant.apply.diamond.1",
799                t, diags.fragment("diamond.non.generic", t));
800            return types.createErrorType(t);
801        } else if (tree.typeargs != null &&
802                tree.typeargs.nonEmpty()) {
803            log.error(tree.clazz.pos(),
804                "cant.apply.diamond.1",
805                t, diags.fragment("diamond.and.explicit.params", t));
806            return types.createErrorType(t);
807        } else {
808            return t;
809        }
810    }
811
812    /** Check that the type inferred using the diamond operator does not contain
813     *  non-denotable types such as captured types or intersection types.
814     *  @param t the type inferred using the diamond operator
815     *  @return  the (possibly empty) list of non-denotable types.
816     */
817    List<Type> checkDiamondDenotable(ClassType t) {
818        ListBuffer<Type> buf = new ListBuffer<>();
819        for (Type arg : t.allparams()) {
820            if (!diamondTypeChecker.visit(arg, null)) {
821                buf.append(arg);
822            }
823        }
824        return buf.toList();
825    }
826        // where
827
828        /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
829         *  types. The visit methods return false as soon as a non-denotable type is encountered and true
830         *  otherwise.
831         */
832        private static final Types.SimpleVisitor<Boolean, Void> diamondTypeChecker = new Types.SimpleVisitor<Boolean, Void>() {
833            @Override
834            public Boolean visitType(Type t, Void s) {
835                return true;
836            }
837            @Override
838            public Boolean visitClassType(ClassType t, Void s) {
839                if (t.isCompound()) {
840                    return false;
841                }
842                for (Type targ : t.allparams()) {
843                    if (!visit(targ, s)) {
844                        return false;
845                    }
846                }
847                return true;
848            }
849
850            @Override
851            public Boolean visitTypeVar(TypeVar t, Void s) {
852                /* Any type variable mentioned in the inferred type must have been declared as a type parameter
853                  (i.e cannot have been produced by inference (18.4))
854                */
855                return t.tsym.owner.type.getTypeArguments().contains(t);
856            }
857
858            @Override
859            public Boolean visitCapturedType(CapturedType t, Void s) {
860                /* Any type variable mentioned in the inferred type must have been declared as a type parameter
861                  (i.e cannot have been produced by capture conversion (5.1.10))
862                */
863                return false;
864            }
865
866            @Override
867            public Boolean visitArrayType(ArrayType t, Void s) {
868                return visit(t.elemtype, s);
869            }
870
871            @Override
872            public Boolean visitWildcardType(WildcardType t, Void s) {
873                return visit(t.type, s);
874            }
875        };
876
877    void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
878        MethodSymbol m = tree.sym;
879        if (!allowSimplifiedVarargs) return;
880        boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
881        Type varargElemType = null;
882        if (m.isVarArgs()) {
883            varargElemType = types.elemtype(tree.params.last().type);
884        }
885        if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
886            if (varargElemType != null) {
887                log.error(tree,
888                        "varargs.invalid.trustme.anno",
889                          syms.trustMeType.tsym,
890                          allowPrivateSafeVarargs ?
891                          diags.fragment("varargs.trustme.on.virtual.varargs", m) :
892                          diags.fragment("varargs.trustme.on.virtual.varargs.final.only", m));
893            } else {
894                log.error(tree,
895                            "varargs.invalid.trustme.anno",
896                            syms.trustMeType.tsym,
897                            diags.fragment("varargs.trustme.on.non.varargs.meth", m));
898            }
899        } else if (hasTrustMeAnno && varargElemType != null &&
900                            types.isReifiable(varargElemType)) {
901            warnUnsafeVararg(tree,
902                            "varargs.redundant.trustme.anno",
903                            syms.trustMeType.tsym,
904                            diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
905        }
906        else if (!hasTrustMeAnno && varargElemType != null &&
907                !types.isReifiable(varargElemType)) {
908            warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
909        }
910    }
911    //where
912        private boolean isTrustMeAllowedOnMethod(Symbol s) {
913            return (s.flags() & VARARGS) != 0 &&
914                (s.isConstructor() ||
915                    (s.flags() & (STATIC | FINAL |
916                                  (allowPrivateSafeVarargs ? PRIVATE : 0) )) != 0);
917        }
918
919    Type checkMethod(final Type mtype,
920            final Symbol sym,
921            final Env<AttrContext> env,
922            final List<JCExpression> argtrees,
923            final List<Type> argtypes,
924            final boolean useVarargs,
925            InferenceContext inferenceContext) {
926        // System.out.println("call   : " + env.tree);
927        // System.out.println("method : " + owntype);
928        // System.out.println("actuals: " + argtypes);
929        if (inferenceContext.free(mtype)) {
930            inferenceContext.addFreeTypeListener(List.of(mtype), new FreeTypeListener() {
931                public void typesInferred(InferenceContext inferenceContext) {
932                    checkMethod(inferenceContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, inferenceContext);
933                }
934            });
935            return mtype;
936        }
937        Type owntype = mtype;
938        List<Type> formals = owntype.getParameterTypes();
939        List<Type> nonInferred = sym.type.getParameterTypes();
940        if (nonInferred.length() != formals.length()) nonInferred = formals;
941        Type last = useVarargs ? formals.last() : null;
942        if (sym.name == names.init && sym.owner == syms.enumSym) {
943            formals = formals.tail.tail;
944            nonInferred = nonInferred.tail.tail;
945        }
946        List<JCExpression> args = argtrees;
947        if (args != null) {
948            //this is null when type-checking a method reference
949            while (formals.head != last) {
950                JCTree arg = args.head;
951                Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
952                assertConvertible(arg, arg.type, formals.head, warn);
953                args = args.tail;
954                formals = formals.tail;
955                nonInferred = nonInferred.tail;
956            }
957            if (useVarargs) {
958                Type varArg = types.elemtype(last);
959                while (args.tail != null) {
960                    JCTree arg = args.head;
961                    Warner warn = convertWarner(arg.pos(), arg.type, varArg);
962                    assertConvertible(arg, arg.type, varArg, warn);
963                    args = args.tail;
964                }
965            } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
966                // non-varargs call to varargs method
967                Type varParam = owntype.getParameterTypes().last();
968                Type lastArg = argtypes.last();
969                if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
970                    !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
971                    log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
972                                types.elemtype(varParam), varParam);
973            }
974        }
975        if (useVarargs) {
976            Type argtype = owntype.getParameterTypes().last();
977            if (!types.isReifiable(argtype) &&
978                (!allowSimplifiedVarargs ||
979                 sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
980                 !isTrustMeAllowedOnMethod(sym))) {
981                warnUnchecked(env.tree.pos(),
982                                  "unchecked.generic.array.creation",
983                                  argtype);
984            }
985            if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) {
986                TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
987            }
988         }
989         return owntype;
990    }
991    //where
992    private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
993        if (types.isConvertible(actual, formal, warn))
994            return;
995
996        if (formal.isCompound()
997            && types.isSubtype(actual, types.supertype(formal))
998            && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
999            return;
1000    }
1001
1002    /**
1003     * Check that type 't' is a valid instantiation of a generic class
1004     * (see JLS 4.5)
1005     *
1006     * @param t class type to be checked
1007     * @return true if 't' is well-formed
1008     */
1009    public boolean checkValidGenericType(Type t) {
1010        return firstIncompatibleTypeArg(t) == null;
1011    }
1012    //WHERE
1013        private Type firstIncompatibleTypeArg(Type type) {
1014            List<Type> formals = type.tsym.type.allparams();
1015            List<Type> actuals = type.allparams();
1016            List<Type> args = type.getTypeArguments();
1017            List<Type> forms = type.tsym.type.getTypeArguments();
1018            ListBuffer<Type> bounds_buf = new ListBuffer<>();
1019
1020            // For matching pairs of actual argument types `a' and
1021            // formal type parameters with declared bound `b' ...
1022            while (args.nonEmpty() && forms.nonEmpty()) {
1023                // exact type arguments needs to know their
1024                // bounds (for upper and lower bound
1025                // calculations).  So we create new bounds where
1026                // type-parameters are replaced with actuals argument types.
1027                bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1028                args = args.tail;
1029                forms = forms.tail;
1030            }
1031
1032            args = type.getTypeArguments();
1033            List<Type> tvars_cap = types.substBounds(formals,
1034                                      formals,
1035                                      types.capture(type).allparams());
1036            while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1037                // Let the actual arguments know their bound
1038                args.head.withTypeVar((TypeVar)tvars_cap.head);
1039                args = args.tail;
1040                tvars_cap = tvars_cap.tail;
1041            }
1042
1043            args = type.getTypeArguments();
1044            List<Type> bounds = bounds_buf.toList();
1045
1046            while (args.nonEmpty() && bounds.nonEmpty()) {
1047                Type actual = args.head;
1048                if (!isTypeArgErroneous(actual) &&
1049                        !bounds.head.isErroneous() &&
1050                        !checkExtends(actual, bounds.head)) {
1051                    return args.head;
1052                }
1053                args = args.tail;
1054                bounds = bounds.tail;
1055            }
1056
1057            args = type.getTypeArguments();
1058            bounds = bounds_buf.toList();
1059
1060            for (Type arg : types.capture(type).getTypeArguments()) {
1061                if (arg.hasTag(TYPEVAR) &&
1062                        arg.getUpperBound().isErroneous() &&
1063                        !bounds.head.isErroneous() &&
1064                        !isTypeArgErroneous(args.head)) {
1065                    return args.head;
1066                }
1067                bounds = bounds.tail;
1068                args = args.tail;
1069            }
1070
1071            return null;
1072        }
1073        //where
1074        boolean isTypeArgErroneous(Type t) {
1075            return isTypeArgErroneous.visit(t);
1076        }
1077
1078        Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1079            public Boolean visitType(Type t, Void s) {
1080                return t.isErroneous();
1081            }
1082            @Override
1083            public Boolean visitTypeVar(TypeVar t, Void s) {
1084                return visit(t.getUpperBound());
1085            }
1086            @Override
1087            public Boolean visitCapturedType(CapturedType t, Void s) {
1088                return visit(t.getUpperBound()) ||
1089                        visit(t.getLowerBound());
1090            }
1091            @Override
1092            public Boolean visitWildcardType(WildcardType t, Void s) {
1093                return visit(t.type);
1094            }
1095        };
1096
1097    /** Check that given modifiers are legal for given symbol and
1098     *  return modifiers together with any implicit modifiers for that symbol.
1099     *  Warning: we can't use flags() here since this method
1100     *  is called during class enter, when flags() would cause a premature
1101     *  completion.
1102     *  @param pos           Position to be used for error reporting.
1103     *  @param flags         The set of modifiers given in a definition.
1104     *  @param sym           The defined symbol.
1105     */
1106    long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1107        long mask;
1108        long implicit = 0;
1109
1110        switch (sym.kind) {
1111        case VAR:
1112            if (TreeInfo.isReceiverParam(tree))
1113                mask = ReceiverParamFlags;
1114            else if (sym.owner.kind != TYP)
1115                mask = LocalVarFlags;
1116            else if ((sym.owner.flags_field & INTERFACE) != 0)
1117                mask = implicit = InterfaceVarFlags;
1118            else
1119                mask = VarFlags;
1120            break;
1121        case MTH:
1122            if (sym.name == names.init) {
1123                if ((sym.owner.flags_field & ENUM) != 0) {
1124                    // enum constructors cannot be declared public or
1125                    // protected and must be implicitly or explicitly
1126                    // private
1127                    implicit = PRIVATE;
1128                    mask = PRIVATE;
1129                } else
1130                    mask = ConstructorFlags;
1131            }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
1132                if ((sym.owner.flags_field & ANNOTATION) != 0) {
1133                    mask = AnnotationTypeElementMask;
1134                    implicit = PUBLIC | ABSTRACT;
1135                } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1136                    mask = InterfaceMethodMask;
1137                    implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1138                    if ((flags & DEFAULT) != 0) {
1139                        implicit |= ABSTRACT;
1140                    }
1141                } else {
1142                    mask = implicit = InterfaceMethodFlags;
1143                }
1144            } else {
1145                mask = MethodFlags;
1146            }
1147            // Imply STRICTFP if owner has STRICTFP set.
1148            if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1149                ((flags) & Flags.DEFAULT) != 0)
1150                implicit |= sym.owner.flags_field & STRICTFP;
1151            break;
1152        case TYP:
1153            if (sym.isLocal()) {
1154                mask = LocalClassFlags;
1155                if ((sym.owner.flags_field & STATIC) == 0 &&
1156                    (flags & ENUM) != 0)
1157                    log.error(pos, "enums.must.be.static");
1158            } else if (sym.owner.kind == TYP) {
1159                mask = MemberClassFlags;
1160                if (sym.owner.owner.kind == PCK ||
1161                    (sym.owner.flags_field & STATIC) != 0)
1162                    mask |= STATIC;
1163                else if ((flags & ENUM) != 0)
1164                    log.error(pos, "enums.must.be.static");
1165                // Nested interfaces and enums are always STATIC (Spec ???)
1166                if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1167            } else {
1168                mask = ClassFlags;
1169            }
1170            // Interfaces are always ABSTRACT
1171            if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1172
1173            if ((flags & ENUM) != 0) {
1174                // enums can't be declared abstract or final
1175                mask &= ~(ABSTRACT | FINAL);
1176                implicit |= implicitEnumFinalFlag(tree);
1177            }
1178            // Imply STRICTFP if owner has STRICTFP set.
1179            implicit |= sym.owner.flags_field & STRICTFP;
1180            break;
1181        default:
1182            throw new AssertionError();
1183        }
1184        long illegal = flags & ExtendedStandardFlags & ~mask;
1185        if (illegal != 0) {
1186            if ((illegal & INTERFACE) != 0) {
1187                log.error(pos, "intf.not.allowed.here");
1188                mask |= INTERFACE;
1189            }
1190            else {
1191                log.error(pos,
1192                          "mod.not.allowed.here", asFlagSet(illegal));
1193            }
1194        }
1195        else if ((sym.kind == TYP ||
1196                  // ISSUE: Disallowing abstract&private is no longer appropriate
1197                  // in the presence of inner classes. Should it be deleted here?
1198                  checkDisjoint(pos, flags,
1199                                ABSTRACT,
1200                                PRIVATE | STATIC | DEFAULT))
1201                 &&
1202                 checkDisjoint(pos, flags,
1203                                STATIC | PRIVATE,
1204                                DEFAULT)
1205                 &&
1206                 checkDisjoint(pos, flags,
1207                               ABSTRACT | INTERFACE,
1208                               FINAL | NATIVE | SYNCHRONIZED)
1209                 &&
1210                 checkDisjoint(pos, flags,
1211                               PUBLIC,
1212                               PRIVATE | PROTECTED)
1213                 &&
1214                 checkDisjoint(pos, flags,
1215                               PRIVATE,
1216                               PUBLIC | PROTECTED)
1217                 &&
1218                 checkDisjoint(pos, flags,
1219                               FINAL,
1220                               VOLATILE)
1221                 &&
1222                 (sym.kind == TYP ||
1223                  checkDisjoint(pos, flags,
1224                                ABSTRACT | NATIVE,
1225                                STRICTFP))) {
1226            // skip
1227        }
1228        return flags & (mask | ~ExtendedStandardFlags) | implicit;
1229    }
1230
1231
1232    /** Determine if this enum should be implicitly final.
1233     *
1234     *  If the enum has no specialized enum contants, it is final.
1235     *
1236     *  If the enum does have specialized enum contants, it is
1237     *  <i>not</i> final.
1238     */
1239    private long implicitEnumFinalFlag(JCTree tree) {
1240        if (!tree.hasTag(CLASSDEF)) return 0;
1241        class SpecialTreeVisitor extends JCTree.Visitor {
1242            boolean specialized;
1243            SpecialTreeVisitor() {
1244                this.specialized = false;
1245            }
1246
1247            @Override
1248            public void visitTree(JCTree tree) { /* no-op */ }
1249
1250            @Override
1251            public void visitVarDef(JCVariableDecl tree) {
1252                if ((tree.mods.flags & ENUM) != 0) {
1253                    if (tree.init instanceof JCNewClass &&
1254                        ((JCNewClass) tree.init).def != null) {
1255                        specialized = true;
1256                    }
1257                }
1258            }
1259        }
1260
1261        SpecialTreeVisitor sts = new SpecialTreeVisitor();
1262        JCClassDecl cdef = (JCClassDecl) tree;
1263        for (JCTree defs: cdef.defs) {
1264            defs.accept(sts);
1265            if (sts.specialized) return 0;
1266        }
1267        return FINAL;
1268    }
1269
1270/* *************************************************************************
1271 * Type Validation
1272 **************************************************************************/
1273
1274    /** Validate a type expression. That is,
1275     *  check that all type arguments of a parametric type are within
1276     *  their bounds. This must be done in a second phase after type attribution
1277     *  since a class might have a subclass as type parameter bound. E.g:
1278     *
1279     *  <pre>{@code
1280     *  class B<A extends C> { ... }
1281     *  class C extends B<C> { ... }
1282     *  }</pre>
1283     *
1284     *  and we can't make sure that the bound is already attributed because
1285     *  of possible cycles.
1286     *
1287     * Visitor method: Validate a type expression, if it is not null, catching
1288     *  and reporting any completion failures.
1289     */
1290    void validate(JCTree tree, Env<AttrContext> env) {
1291        validate(tree, env, true);
1292    }
1293    void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1294        new Validator(env).validateTree(tree, checkRaw, true);
1295    }
1296
1297    /** Visitor method: Validate a list of type expressions.
1298     */
1299    void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1300        for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1301            validate(l.head, env);
1302    }
1303
1304    /** A visitor class for type validation.
1305     */
1306    class Validator extends JCTree.Visitor {
1307
1308        boolean checkRaw;
1309        boolean isOuter;
1310        Env<AttrContext> env;
1311
1312        Validator(Env<AttrContext> env) {
1313            this.env = env;
1314        }
1315
1316        @Override
1317        public void visitTypeArray(JCArrayTypeTree tree) {
1318            validateTree(tree.elemtype, checkRaw, isOuter);
1319        }
1320
1321        @Override
1322        public void visitTypeApply(JCTypeApply tree) {
1323            if (tree.type.hasTag(CLASS)) {
1324                List<JCExpression> args = tree.arguments;
1325                List<Type> forms = tree.type.tsym.type.getTypeArguments();
1326
1327                Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1328                if (incompatibleArg != null) {
1329                    for (JCTree arg : tree.arguments) {
1330                        if (arg.type == incompatibleArg) {
1331                            log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1332                        }
1333                        forms = forms.tail;
1334                     }
1335                 }
1336
1337                forms = tree.type.tsym.type.getTypeArguments();
1338
1339                boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1340
1341                // For matching pairs of actual argument types `a' and
1342                // formal type parameters with declared bound `b' ...
1343                while (args.nonEmpty() && forms.nonEmpty()) {
1344                    validateTree(args.head,
1345                            !(isOuter && is_java_lang_Class),
1346                            false);
1347                    args = args.tail;
1348                    forms = forms.tail;
1349                }
1350
1351                // Check that this type is either fully parameterized, or
1352                // not parameterized at all.
1353                if (tree.type.getEnclosingType().isRaw())
1354                    log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1355                if (tree.clazz.hasTag(SELECT))
1356                    visitSelectInternal((JCFieldAccess)tree.clazz);
1357            }
1358        }
1359
1360        @Override
1361        public void visitTypeParameter(JCTypeParameter tree) {
1362            validateTrees(tree.bounds, true, isOuter);
1363            checkClassBounds(tree.pos(), tree.type);
1364        }
1365
1366        @Override
1367        public void visitWildcard(JCWildcard tree) {
1368            if (tree.inner != null)
1369                validateTree(tree.inner, true, isOuter);
1370        }
1371
1372        @Override
1373        public void visitSelect(JCFieldAccess tree) {
1374            if (tree.type.hasTag(CLASS)) {
1375                visitSelectInternal(tree);
1376
1377                // Check that this type is either fully parameterized, or
1378                // not parameterized at all.
1379                if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1380                    log.error(tree.pos(), "improperly.formed.type.param.missing");
1381            }
1382        }
1383
1384        public void visitSelectInternal(JCFieldAccess tree) {
1385            if (tree.type.tsym.isStatic() &&
1386                tree.selected.type.isParameterized()) {
1387                // The enclosing type is not a class, so we are
1388                // looking at a static member type.  However, the
1389                // qualifying expression is parameterized.
1390                log.error(tree.pos(), "cant.select.static.class.from.param.type");
1391            } else {
1392                // otherwise validate the rest of the expression
1393                tree.selected.accept(this);
1394            }
1395        }
1396
1397        @Override
1398        public void visitAnnotatedType(JCAnnotatedType tree) {
1399            tree.underlyingType.accept(this);
1400        }
1401
1402        @Override
1403        public void visitTypeIdent(JCPrimitiveTypeTree that) {
1404            if (that.type.hasTag(TypeTag.VOID)) {
1405                log.error(that.pos(), "void.not.allowed.here");
1406            }
1407            super.visitTypeIdent(that);
1408        }
1409
1410        /** Default visitor method: do nothing.
1411         */
1412        @Override
1413        public void visitTree(JCTree tree) {
1414        }
1415
1416        public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1417            if (tree != null) {
1418                boolean prevCheckRaw = this.checkRaw;
1419                this.checkRaw = checkRaw;
1420                this.isOuter = isOuter;
1421
1422                try {
1423                    tree.accept(this);
1424                    if (checkRaw)
1425                        checkRaw(tree, env);
1426                } catch (CompletionFailure ex) {
1427                    completionError(tree.pos(), ex);
1428                } finally {
1429                    this.checkRaw = prevCheckRaw;
1430                }
1431            }
1432        }
1433
1434        public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1435            for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1436                validateTree(l.head, checkRaw, isOuter);
1437        }
1438    }
1439
1440    void checkRaw(JCTree tree, Env<AttrContext> env) {
1441        if (lint.isEnabled(LintCategory.RAW) &&
1442            tree.type.hasTag(CLASS) &&
1443            !TreeInfo.isDiamond(tree) &&
1444            !withinAnonConstr(env) &&
1445            tree.type.isRaw()) {
1446            log.warning(LintCategory.RAW,
1447                    tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1448        }
1449    }
1450    //where
1451        private boolean withinAnonConstr(Env<AttrContext> env) {
1452            return env.enclClass.name.isEmpty() &&
1453                    env.enclMethod != null && env.enclMethod.name == names.init;
1454        }
1455
1456/* *************************************************************************
1457 * Exception checking
1458 **************************************************************************/
1459
1460    /* The following methods treat classes as sets that contain
1461     * the class itself and all their subclasses
1462     */
1463
1464    /** Is given type a subtype of some of the types in given list?
1465     */
1466    boolean subset(Type t, List<Type> ts) {
1467        for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1468            if (types.isSubtype(t, l.head)) return true;
1469        return false;
1470    }
1471
1472    /** Is given type a subtype or supertype of
1473     *  some of the types in given list?
1474     */
1475    boolean intersects(Type t, List<Type> ts) {
1476        for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1477            if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1478        return false;
1479    }
1480
1481    /** Add type set to given type list, unless it is a subclass of some class
1482     *  in the list.
1483     */
1484    List<Type> incl(Type t, List<Type> ts) {
1485        return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1486    }
1487
1488    /** Remove type set from type set list.
1489     */
1490    List<Type> excl(Type t, List<Type> ts) {
1491        if (ts.isEmpty()) {
1492            return ts;
1493        } else {
1494            List<Type> ts1 = excl(t, ts.tail);
1495            if (types.isSubtype(ts.head, t)) return ts1;
1496            else if (ts1 == ts.tail) return ts;
1497            else return ts1.prepend(ts.head);
1498        }
1499    }
1500
1501    /** Form the union of two type set lists.
1502     */
1503    List<Type> union(List<Type> ts1, List<Type> ts2) {
1504        List<Type> ts = ts1;
1505        for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1506            ts = incl(l.head, ts);
1507        return ts;
1508    }
1509
1510    /** Form the difference of two type lists.
1511     */
1512    List<Type> diff(List<Type> ts1, List<Type> ts2) {
1513        List<Type> ts = ts1;
1514        for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1515            ts = excl(l.head, ts);
1516        return ts;
1517    }
1518
1519    /** Form the intersection of two type lists.
1520     */
1521    public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1522        List<Type> ts = List.nil();
1523        for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1524            if (subset(l.head, ts2)) ts = incl(l.head, ts);
1525        for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1526            if (subset(l.head, ts1)) ts = incl(l.head, ts);
1527        return ts;
1528    }
1529
1530    /** Is exc an exception symbol that need not be declared?
1531     */
1532    boolean isUnchecked(ClassSymbol exc) {
1533        return
1534            exc.kind == ERR ||
1535            exc.isSubClass(syms.errorType.tsym, types) ||
1536            exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1537    }
1538
1539    /** Is exc an exception type that need not be declared?
1540     */
1541    boolean isUnchecked(Type exc) {
1542        return
1543            (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1544            (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1545            exc.hasTag(BOT);
1546    }
1547
1548    /** Same, but handling completion failures.
1549     */
1550    boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1551        try {
1552            return isUnchecked(exc);
1553        } catch (CompletionFailure ex) {
1554            completionError(pos, ex);
1555            return true;
1556        }
1557    }
1558
1559    /** Is exc handled by given exception list?
1560     */
1561    boolean isHandled(Type exc, List<Type> handled) {
1562        return isUnchecked(exc) || subset(exc, handled);
1563    }
1564
1565    /** Return all exceptions in thrown list that are not in handled list.
1566     *  @param thrown     The list of thrown exceptions.
1567     *  @param handled    The list of handled exceptions.
1568     */
1569    List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1570        List<Type> unhandled = List.nil();
1571        for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1572            if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1573        return unhandled;
1574    }
1575
1576/* *************************************************************************
1577 * Overriding/Implementation checking
1578 **************************************************************************/
1579
1580    /** The level of access protection given by a flag set,
1581     *  where PRIVATE is highest and PUBLIC is lowest.
1582     */
1583    static int protection(long flags) {
1584        switch ((short)(flags & AccessFlags)) {
1585        case PRIVATE: return 3;
1586        case PROTECTED: return 1;
1587        default:
1588        case PUBLIC: return 0;
1589        case 0: return 2;
1590        }
1591    }
1592
1593    /** A customized "cannot override" error message.
1594     *  @param m      The overriding method.
1595     *  @param other  The overridden method.
1596     *  @return       An internationalized string.
1597     */
1598    Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1599        String key;
1600        if ((other.owner.flags() & INTERFACE) == 0)
1601            key = "cant.override";
1602        else if ((m.owner.flags() & INTERFACE) == 0)
1603            key = "cant.implement";
1604        else
1605            key = "clashes.with";
1606        return diags.fragment(key, m, m.location(), other, other.location());
1607    }
1608
1609    /** A customized "override" warning message.
1610     *  @param m      The overriding method.
1611     *  @param other  The overridden method.
1612     *  @return       An internationalized string.
1613     */
1614    Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1615        String key;
1616        if ((other.owner.flags() & INTERFACE) == 0)
1617            key = "unchecked.override";
1618        else if ((m.owner.flags() & INTERFACE) == 0)
1619            key = "unchecked.implement";
1620        else
1621            key = "unchecked.clash.with";
1622        return diags.fragment(key, m, m.location(), other, other.location());
1623    }
1624
1625    /** A customized "override" warning message.
1626     *  @param m      The overriding method.
1627     *  @param other  The overridden method.
1628     *  @return       An internationalized string.
1629     */
1630    Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1631        String key;
1632        if ((other.owner.flags() & INTERFACE) == 0)
1633            key = "varargs.override";
1634        else  if ((m.owner.flags() & INTERFACE) == 0)
1635            key = "varargs.implement";
1636        else
1637            key = "varargs.clash.with";
1638        return diags.fragment(key, m, m.location(), other, other.location());
1639    }
1640
1641    /** Check that this method conforms with overridden method 'other'.
1642     *  where `origin' is the class where checking started.
1643     *  Complications:
1644     *  (1) Do not check overriding of synthetic methods
1645     *      (reason: they might be final).
1646     *      todo: check whether this is still necessary.
1647     *  (2) Admit the case where an interface proxy throws fewer exceptions
1648     *      than the method it implements. Augment the proxy methods with the
1649     *      undeclared exceptions in this case.
1650     *  (3) When generics are enabled, admit the case where an interface proxy
1651     *      has a result type
1652     *      extended by the result type of the method it implements.
1653     *      Change the proxies result type to the smaller type in this case.
1654     *
1655     *  @param tree         The tree from which positions
1656     *                      are extracted for errors.
1657     *  @param m            The overriding method.
1658     *  @param other        The overridden method.
1659     *  @param origin       The class of which the overriding method
1660     *                      is a member.
1661     */
1662    void checkOverride(JCTree tree,
1663                       MethodSymbol m,
1664                       MethodSymbol other,
1665                       ClassSymbol origin) {
1666        // Don't check overriding of synthetic methods or by bridge methods.
1667        if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1668            return;
1669        }
1670
1671        // Error if static method overrides instance method (JLS 8.4.6.2).
1672        if ((m.flags() & STATIC) != 0 &&
1673                   (other.flags() & STATIC) == 0) {
1674            log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1675                      cannotOverride(m, other));
1676            m.flags_field |= BAD_OVERRIDE;
1677            return;
1678        }
1679
1680        // Error if instance method overrides static or final
1681        // method (JLS 8.4.6.1).
1682        if ((other.flags() & FINAL) != 0 ||
1683                 (m.flags() & STATIC) == 0 &&
1684                 (other.flags() & STATIC) != 0) {
1685            log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1686                      cannotOverride(m, other),
1687                      asFlagSet(other.flags() & (FINAL | STATIC)));
1688            m.flags_field |= BAD_OVERRIDE;
1689            return;
1690        }
1691
1692        if ((m.owner.flags() & ANNOTATION) != 0) {
1693            // handled in validateAnnotationMethod
1694            return;
1695        }
1696
1697        // Error if overriding method has weaker access (JLS 8.4.6.3).
1698        if (protection(m.flags()) > protection(other.flags())) {
1699            log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1700                      cannotOverride(m, other),
1701                      (other.flags() & AccessFlags) == 0 ?
1702                          "package" :
1703                          asFlagSet(other.flags() & AccessFlags));
1704            m.flags_field |= BAD_OVERRIDE;
1705            return;
1706        }
1707
1708        Type mt = types.memberType(origin.type, m);
1709        Type ot = types.memberType(origin.type, other);
1710        // Error if overriding result type is different
1711        // (or, in the case of generics mode, not a subtype) of
1712        // overridden result type. We have to rename any type parameters
1713        // before comparing types.
1714        List<Type> mtvars = mt.getTypeArguments();
1715        List<Type> otvars = ot.getTypeArguments();
1716        Type mtres = mt.getReturnType();
1717        Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1718
1719        overrideWarner.clear();
1720        boolean resultTypesOK =
1721            types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1722        if (!resultTypesOK) {
1723            if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1724                log.error(TreeInfo.diagnosticPositionFor(m, tree),
1725                        Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1726                                        other.location()), mtres, otres));
1727                m.flags_field |= BAD_OVERRIDE;
1728            } else {
1729                log.error(TreeInfo.diagnosticPositionFor(m, tree),
1730                        "override.incompatible.ret",
1731                        cannotOverride(m, other),
1732                        mtres, otres);
1733                m.flags_field |= BAD_OVERRIDE;
1734            }
1735            return;
1736        } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1737            warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1738                    "override.unchecked.ret",
1739                    uncheckedOverrides(m, other),
1740                    mtres, otres);
1741        }
1742
1743        // Error if overriding method throws an exception not reported
1744        // by overridden method.
1745        List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1746        List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1747        List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1748        if (unhandledErased.nonEmpty()) {
1749            log.error(TreeInfo.diagnosticPositionFor(m, tree),
1750                      "override.meth.doesnt.throw",
1751                      cannotOverride(m, other),
1752                      unhandledUnerased.head);
1753            m.flags_field |= BAD_OVERRIDE;
1754            return;
1755        }
1756        else if (unhandledUnerased.nonEmpty()) {
1757            warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1758                          "override.unchecked.thrown",
1759                         cannotOverride(m, other),
1760                         unhandledUnerased.head);
1761            return;
1762        }
1763
1764        // Optional warning if varargs don't agree
1765        if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1766            && lint.isEnabled(LintCategory.OVERRIDES)) {
1767            log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1768                        ((m.flags() & Flags.VARARGS) != 0)
1769                        ? "override.varargs.missing"
1770                        : "override.varargs.extra",
1771                        varargsOverrides(m, other));
1772        }
1773
1774        // Warn if instance method overrides bridge method (compiler spec ??)
1775        if ((other.flags() & BRIDGE) != 0) {
1776            log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1777                        uncheckedOverrides(m, other));
1778        }
1779
1780        // Warn if a deprecated method overridden by a non-deprecated one.
1781        if (!isDeprecatedOverrideIgnorable(other, origin)) {
1782            Lint prevLint = setLint(lint.augment(m));
1783            try {
1784                checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1785            } finally {
1786                setLint(prevLint);
1787            }
1788        }
1789    }
1790    // where
1791        private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1792            // If the method, m, is defined in an interface, then ignore the issue if the method
1793            // is only inherited via a supertype and also implemented in the supertype,
1794            // because in that case, we will rediscover the issue when examining the method
1795            // in the supertype.
1796            // If the method, m, is not defined in an interface, then the only time we need to
1797            // address the issue is when the method is the supertype implemementation: any other
1798            // case, we will have dealt with when examining the supertype classes
1799            ClassSymbol mc = m.enclClass();
1800            Type st = types.supertype(origin.type);
1801            if (!st.hasTag(CLASS))
1802                return true;
1803            MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1804
1805            if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1806                List<Type> intfs = types.interfaces(origin.type);
1807                return (intfs.contains(mc.type) ? false : (stimpl != null));
1808            }
1809            else
1810                return (stimpl != m);
1811        }
1812
1813
1814    // used to check if there were any unchecked conversions
1815    Warner overrideWarner = new Warner();
1816
1817    /** Check that a class does not inherit two concrete methods
1818     *  with the same signature.
1819     *  @param pos          Position to be used for error reporting.
1820     *  @param site         The class type to be checked.
1821     */
1822    public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1823        Type sup = types.supertype(site);
1824        if (!sup.hasTag(CLASS)) return;
1825
1826        for (Type t1 = sup;
1827             t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1828             t1 = types.supertype(t1)) {
1829            for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1830                if (s1.kind != MTH ||
1831                    (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1832                    !s1.isInheritedIn(site.tsym, types) ||
1833                    ((MethodSymbol)s1).implementation(site.tsym,
1834                                                      types,
1835                                                      true) != s1)
1836                    continue;
1837                Type st1 = types.memberType(t1, s1);
1838                int s1ArgsLength = st1.getParameterTypes().length();
1839                if (st1 == s1.type) continue;
1840
1841                for (Type t2 = sup;
1842                     t2.hasTag(CLASS);
1843                     t2 = types.supertype(t2)) {
1844                    for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1845                        if (s2 == s1 ||
1846                            s2.kind != MTH ||
1847                            (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1848                            s2.type.getParameterTypes().length() != s1ArgsLength ||
1849                            !s2.isInheritedIn(site.tsym, types) ||
1850                            ((MethodSymbol)s2).implementation(site.tsym,
1851                                                              types,
1852                                                              true) != s2)
1853                            continue;
1854                        Type st2 = types.memberType(t2, s2);
1855                        if (types.overrideEquivalent(st1, st2))
1856                            log.error(pos, "concrete.inheritance.conflict",
1857                                      s1, t1, s2, t2, sup);
1858                    }
1859                }
1860            }
1861        }
1862    }
1863
1864    /** Check that classes (or interfaces) do not each define an abstract
1865     *  method with same name and arguments but incompatible return types.
1866     *  @param pos          Position to be used for error reporting.
1867     *  @param t1           The first argument type.
1868     *  @param t2           The second argument type.
1869     */
1870    public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1871                                            Type t1,
1872                                            Type t2,
1873                                            Type site) {
1874        if ((site.tsym.flags() & COMPOUND) != 0) {
1875            // special case for intersections: need to eliminate wildcards in supertypes
1876            t1 = types.capture(t1);
1877            t2 = types.capture(t2);
1878        }
1879        return firstIncompatibility(pos, t1, t2, site) == null;
1880    }
1881
1882    /** Return the first method which is defined with same args
1883     *  but different return types in two given interfaces, or null if none
1884     *  exists.
1885     *  @param t1     The first type.
1886     *  @param t2     The second type.
1887     *  @param site   The most derived type.
1888     *  @returns symbol from t2 that conflicts with one in t1.
1889     */
1890    private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1891        Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1892        closure(t1, interfaces1);
1893        Map<TypeSymbol,Type> interfaces2;
1894        if (t1 == t2)
1895            interfaces2 = interfaces1;
1896        else
1897            closure(t2, interfaces1, interfaces2 = new HashMap<>());
1898
1899        for (Type t3 : interfaces1.values()) {
1900            for (Type t4 : interfaces2.values()) {
1901                Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1902                if (s != null) return s;
1903            }
1904        }
1905        return null;
1906    }
1907
1908    /** Compute all the supertypes of t, indexed by type symbol. */
1909    private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1910        if (!t.hasTag(CLASS)) return;
1911        if (typeMap.put(t.tsym, t) == null) {
1912            closure(types.supertype(t), typeMap);
1913            for (Type i : types.interfaces(t))
1914                closure(i, typeMap);
1915        }
1916    }
1917
1918    /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1919    private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1920        if (!t.hasTag(CLASS)) return;
1921        if (typesSkip.get(t.tsym) != null) return;
1922        if (typeMap.put(t.tsym, t) == null) {
1923            closure(types.supertype(t), typesSkip, typeMap);
1924            for (Type i : types.interfaces(t))
1925                closure(i, typesSkip, typeMap);
1926        }
1927    }
1928
1929    /** Return the first method in t2 that conflicts with a method from t1. */
1930    private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1931        for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1932            Type st1 = null;
1933            if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1934                    (s1.flags() & SYNTHETIC) != 0) continue;
1935            Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1936            if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1937            for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1938                if (s1 == s2) continue;
1939                if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1940                        (s2.flags() & SYNTHETIC) != 0) continue;
1941                if (st1 == null) st1 = types.memberType(t1, s1);
1942                Type st2 = types.memberType(t2, s2);
1943                if (types.overrideEquivalent(st1, st2)) {
1944                    List<Type> tvars1 = st1.getTypeArguments();
1945                    List<Type> tvars2 = st2.getTypeArguments();
1946                    Type rt1 = st1.getReturnType();
1947                    Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1948                    boolean compat =
1949                        types.isSameType(rt1, rt2) ||
1950                        !rt1.isPrimitiveOrVoid() &&
1951                        !rt2.isPrimitiveOrVoid() &&
1952                        (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1953                         types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1954                         checkCommonOverriderIn(s1,s2,site);
1955                    if (!compat) {
1956                        log.error(pos, "types.incompatible.diff.ret",
1957                            t1, t2, s2.name +
1958                            "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1959                        return s2;
1960                    }
1961                } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1962                        !checkCommonOverriderIn(s1, s2, site)) {
1963                    log.error(pos,
1964                            "name.clash.same.erasure.no.override",
1965                            s1, s1.location(),
1966                            s2, s2.location());
1967                    return s2;
1968                }
1969            }
1970        }
1971        return null;
1972    }
1973    //WHERE
1974    boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1975        Map<TypeSymbol,Type> supertypes = new HashMap<>();
1976        Type st1 = types.memberType(site, s1);
1977        Type st2 = types.memberType(site, s2);
1978        closure(site, supertypes);
1979        for (Type t : supertypes.values()) {
1980            for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
1981                if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1982                Type st3 = types.memberType(site,s3);
1983                if (types.overrideEquivalent(st3, st1) &&
1984                        types.overrideEquivalent(st3, st2) &&
1985                        types.returnTypeSubstitutable(st3, st1) &&
1986                        types.returnTypeSubstitutable(st3, st2)) {
1987                    return true;
1988                }
1989            }
1990        }
1991        return false;
1992    }
1993
1994    /** Check that a given method conforms with any method it overrides.
1995     *  @param tree         The tree from which positions are extracted
1996     *                      for errors.
1997     *  @param m            The overriding method.
1998     */
1999    void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2000        ClassSymbol origin = (ClassSymbol)m.owner;
2001        if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
2002            if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2003                log.error(tree.pos(), "enum.no.finalize");
2004                return;
2005            }
2006        for (Type t = origin.type; t.hasTag(CLASS);
2007             t = types.supertype(t)) {
2008            if (t != origin.type) {
2009                checkOverride(tree, t, origin, m);
2010            }
2011            for (Type t2 : types.interfaces(t)) {
2012                checkOverride(tree, t2, origin, m);
2013            }
2014        }
2015
2016        final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2017        // Check if this method must override a super method due to being annotated with @Override
2018        // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2019        // be treated "as if as they were annotated" with @Override.
2020        boolean mustOverride = explicitOverride ||
2021                (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2022        if (mustOverride && !isOverrider(m)) {
2023            DiagnosticPosition pos = tree.pos();
2024            for (JCAnnotation a : tree.getModifiers().annotations) {
2025                if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2026                    pos = a.pos();
2027                    break;
2028                }
2029            }
2030            log.error(pos,
2031                      explicitOverride ? Errors.MethodDoesNotOverrideSuperclass :
2032                                Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2033        }
2034    }
2035
2036    void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2037        TypeSymbol c = site.tsym;
2038        for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2039            if (m.overrides(sym, origin, types, false)) {
2040                if ((sym.flags() & ABSTRACT) == 0) {
2041                    checkOverride(tree, m, (MethodSymbol)sym, origin);
2042                }
2043            }
2044        }
2045    }
2046
2047    private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
2048        public boolean accepts(Symbol s) {
2049            return MethodSymbol.implementation_filter.accepts(s) &&
2050                    (s.flags() & BAD_OVERRIDE) == 0;
2051
2052        }
2053    };
2054
2055    public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2056            ClassSymbol someClass) {
2057        /* At present, annotations cannot possibly have a method that is override
2058         * equivalent with Object.equals(Object) but in any case the condition is
2059         * fine for completeness.
2060         */
2061        if (someClass == (ClassSymbol)syms.objectType.tsym ||
2062            someClass.isInterface() || someClass.isEnum() ||
2063            (someClass.flags() & ANNOTATION) != 0 ||
2064            (someClass.flags() & ABSTRACT) != 0) return;
2065        //anonymous inner classes implementing interfaces need especial treatment
2066        if (someClass.isAnonymous()) {
2067            List<Type> interfaces =  types.interfaces(someClass.type);
2068            if (interfaces != null && !interfaces.isEmpty() &&
2069                interfaces.head.tsym == syms.comparatorType.tsym) return;
2070        }
2071        checkClassOverrideEqualsAndHash(pos, someClass);
2072    }
2073
2074    private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2075            ClassSymbol someClass) {
2076        if (lint.isEnabled(LintCategory.OVERRIDES)) {
2077            MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2078                    .tsym.members().findFirst(names.equals);
2079            MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2080                    .tsym.members().findFirst(names.hashCode);
2081            boolean overridesEquals = types.implementation(equalsAtObject,
2082                someClass, false, equalsHasCodeFilter).owner == someClass;
2083            boolean overridesHashCode = types.implementation(hashCodeAtObject,
2084                someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2085
2086            if (overridesEquals && !overridesHashCode) {
2087                log.warning(LintCategory.OVERRIDES, pos,
2088                        "override.equals.but.not.hashcode", someClass);
2089            }
2090        }
2091    }
2092
2093    private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2094        ClashFilter cf = new ClashFilter(origin.type);
2095        return (cf.accepts(s1) &&
2096                cf.accepts(s2) &&
2097                types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2098    }
2099
2100
2101    /** Check that all abstract members of given class have definitions.
2102     *  @param pos          Position to be used for error reporting.
2103     *  @param c            The class.
2104     */
2105    void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2106        MethodSymbol undef = types.firstUnimplementedAbstract(c);
2107        if (undef != null) {
2108            MethodSymbol undef1 =
2109                new MethodSymbol(undef.flags(), undef.name,
2110                                 types.memberType(c.type, undef), undef.owner);
2111            log.error(pos, "does.not.override.abstract",
2112                      c, undef1, undef1.location());
2113        }
2114    }
2115
2116    void checkNonCyclicDecl(JCClassDecl tree) {
2117        CycleChecker cc = new CycleChecker();
2118        cc.scan(tree);
2119        if (!cc.errorFound && !cc.partialCheck) {
2120            tree.sym.flags_field |= ACYCLIC;
2121        }
2122    }
2123
2124    class CycleChecker extends TreeScanner {
2125
2126        List<Symbol> seenClasses = List.nil();
2127        boolean errorFound = false;
2128        boolean partialCheck = false;
2129
2130        private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2131            if (sym != null && sym.kind == TYP) {
2132                Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2133                if (classEnv != null) {
2134                    DiagnosticSource prevSource = log.currentSource();
2135                    try {
2136                        log.useSource(classEnv.toplevel.sourcefile);
2137                        scan(classEnv.tree);
2138                    }
2139                    finally {
2140                        log.useSource(prevSource.getFile());
2141                    }
2142                } else if (sym.kind == TYP) {
2143                    checkClass(pos, sym, List.<JCTree>nil());
2144                }
2145            } else {
2146                //not completed yet
2147                partialCheck = true;
2148            }
2149        }
2150
2151        @Override
2152        public void visitSelect(JCFieldAccess tree) {
2153            super.visitSelect(tree);
2154            checkSymbol(tree.pos(), tree.sym);
2155        }
2156
2157        @Override
2158        public void visitIdent(JCIdent tree) {
2159            checkSymbol(tree.pos(), tree.sym);
2160        }
2161
2162        @Override
2163        public void visitTypeApply(JCTypeApply tree) {
2164            scan(tree.clazz);
2165        }
2166
2167        @Override
2168        public void visitTypeArray(JCArrayTypeTree tree) {
2169            scan(tree.elemtype);
2170        }
2171
2172        @Override
2173        public void visitClassDef(JCClassDecl tree) {
2174            List<JCTree> supertypes = List.nil();
2175            if (tree.getExtendsClause() != null) {
2176                supertypes = supertypes.prepend(tree.getExtendsClause());
2177            }
2178            if (tree.getImplementsClause() != null) {
2179                for (JCTree intf : tree.getImplementsClause()) {
2180                    supertypes = supertypes.prepend(intf);
2181                }
2182            }
2183            checkClass(tree.pos(), tree.sym, supertypes);
2184        }
2185
2186        void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2187            if ((c.flags_field & ACYCLIC) != 0)
2188                return;
2189            if (seenClasses.contains(c)) {
2190                errorFound = true;
2191                noteCyclic(pos, (ClassSymbol)c);
2192            } else if (!c.type.isErroneous()) {
2193                try {
2194                    seenClasses = seenClasses.prepend(c);
2195                    if (c.type.hasTag(CLASS)) {
2196                        if (supertypes.nonEmpty()) {
2197                            scan(supertypes);
2198                        }
2199                        else {
2200                            ClassType ct = (ClassType)c.type;
2201                            if (ct.supertype_field == null ||
2202                                    ct.interfaces_field == null) {
2203                                //not completed yet
2204                                partialCheck = true;
2205                                return;
2206                            }
2207                            checkSymbol(pos, ct.supertype_field.tsym);
2208                            for (Type intf : ct.interfaces_field) {
2209                                checkSymbol(pos, intf.tsym);
2210                            }
2211                        }
2212                        if (c.owner.kind == TYP) {
2213                            checkSymbol(pos, c.owner);
2214                        }
2215                    }
2216                } finally {
2217                    seenClasses = seenClasses.tail;
2218                }
2219            }
2220        }
2221    }
2222
2223    /** Check for cyclic references. Issue an error if the
2224     *  symbol of the type referred to has a LOCKED flag set.
2225     *
2226     *  @param pos      Position to be used for error reporting.
2227     *  @param t        The type referred to.
2228     */
2229    void checkNonCyclic(DiagnosticPosition pos, Type t) {
2230        checkNonCyclicInternal(pos, t);
2231    }
2232
2233
2234    void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2235        checkNonCyclic1(pos, t, List.<TypeVar>nil());
2236    }
2237
2238    private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2239        final TypeVar tv;
2240        if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2241            return;
2242        if (seen.contains(t)) {
2243            tv = (TypeVar)t;
2244            tv.bound = types.createErrorType(t);
2245            log.error(pos, "cyclic.inheritance", t);
2246        } else if (t.hasTag(TYPEVAR)) {
2247            tv = (TypeVar)t;
2248            seen = seen.prepend(tv);
2249            for (Type b : types.getBounds(tv))
2250                checkNonCyclic1(pos, b, seen);
2251        }
2252    }
2253
2254    /** Check for cyclic references. Issue an error if the
2255     *  symbol of the type referred to has a LOCKED flag set.
2256     *
2257     *  @param pos      Position to be used for error reporting.
2258     *  @param t        The type referred to.
2259     *  @returns        True if the check completed on all attributed classes
2260     */
2261    private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2262        boolean complete = true; // was the check complete?
2263        //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2264        Symbol c = t.tsym;
2265        if ((c.flags_field & ACYCLIC) != 0) return true;
2266
2267        if ((c.flags_field & LOCKED) != 0) {
2268            noteCyclic(pos, (ClassSymbol)c);
2269        } else if (!c.type.isErroneous()) {
2270            try {
2271                c.flags_field |= LOCKED;
2272                if (c.type.hasTag(CLASS)) {
2273                    ClassType clazz = (ClassType)c.type;
2274                    if (clazz.interfaces_field != null)
2275                        for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2276                            complete &= checkNonCyclicInternal(pos, l.head);
2277                    if (clazz.supertype_field != null) {
2278                        Type st = clazz.supertype_field;
2279                        if (st != null && st.hasTag(CLASS))
2280                            complete &= checkNonCyclicInternal(pos, st);
2281                    }
2282                    if (c.owner.kind == TYP)
2283                        complete &= checkNonCyclicInternal(pos, c.owner.type);
2284                }
2285            } finally {
2286                c.flags_field &= ~LOCKED;
2287            }
2288        }
2289        if (complete)
2290            complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2291        if (complete) c.flags_field |= ACYCLIC;
2292        return complete;
2293    }
2294
2295    /** Note that we found an inheritance cycle. */
2296    private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2297        log.error(pos, "cyclic.inheritance", c);
2298        for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2299            l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2300        Type st = types.supertype(c.type);
2301        if (st.hasTag(CLASS))
2302            ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2303        c.type = types.createErrorType(c, c.type);
2304        c.flags_field |= ACYCLIC;
2305    }
2306
2307    /** Check that all methods which implement some
2308     *  method conform to the method they implement.
2309     *  @param tree         The class definition whose members are checked.
2310     */
2311    void checkImplementations(JCClassDecl tree) {
2312        checkImplementations(tree, tree.sym, tree.sym);
2313    }
2314    //where
2315        /** Check that all methods which implement some
2316         *  method in `ic' conform to the method they implement.
2317         */
2318        void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2319            for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2320                ClassSymbol lc = (ClassSymbol)l.head.tsym;
2321                if ((lc.flags() & ABSTRACT) != 0) {
2322                    for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2323                        if (sym.kind == MTH &&
2324                            (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2325                            MethodSymbol absmeth = (MethodSymbol)sym;
2326                            MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2327                            if (implmeth != null && implmeth != absmeth &&
2328                                (implmeth.owner.flags() & INTERFACE) ==
2329                                (origin.flags() & INTERFACE)) {
2330                                // don't check if implmeth is in a class, yet
2331                                // origin is an interface. This case arises only
2332                                // if implmeth is declared in Object. The reason is
2333                                // that interfaces really don't inherit from
2334                                // Object it's just that the compiler represents
2335                                // things that way.
2336                                checkOverride(tree, implmeth, absmeth, origin);
2337                            }
2338                        }
2339                    }
2340                }
2341            }
2342        }
2343
2344    /** Check that all abstract methods implemented by a class are
2345     *  mutually compatible.
2346     *  @param pos          Position to be used for error reporting.
2347     *  @param c            The class whose interfaces are checked.
2348     */
2349    void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2350        List<Type> supertypes = types.interfaces(c);
2351        Type supertype = types.supertype(c);
2352        if (supertype.hasTag(CLASS) &&
2353            (supertype.tsym.flags() & ABSTRACT) != 0)
2354            supertypes = supertypes.prepend(supertype);
2355        for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2356            if (!l.head.getTypeArguments().isEmpty() &&
2357                !checkCompatibleAbstracts(pos, l.head, l.head, c))
2358                return;
2359            for (List<Type> m = supertypes; m != l; m = m.tail)
2360                if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2361                    return;
2362        }
2363        checkCompatibleConcretes(pos, c);
2364    }
2365
2366    void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2367        for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2368            for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) {
2369                // VM allows methods and variables with differing types
2370                if (sym.kind == sym2.kind &&
2371                    types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) &&
2372                    sym != sym2 &&
2373                    (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) &&
2374                    (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) {
2375                    syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym);
2376                    return;
2377                }
2378            }
2379        }
2380    }
2381
2382    /** Check that all non-override equivalent methods accessible from 'site'
2383     *  are mutually compatible (JLS 8.4.8/9.4.1).
2384     *
2385     *  @param pos  Position to be used for error reporting.
2386     *  @param site The class whose methods are checked.
2387     *  @param sym  The method symbol to be checked.
2388     */
2389    void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2390         ClashFilter cf = new ClashFilter(site);
2391        //for each method m1 that is overridden (directly or indirectly)
2392        //by method 'sym' in 'site'...
2393
2394        List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2395        boolean overridesAny = false;
2396        for (Symbol m1 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2397            if (!sym.overrides(m1, site.tsym, types, false)) {
2398                if (m1 == sym) {
2399                    continue;
2400                }
2401
2402                if (!overridesAny) {
2403                    potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1);
2404                }
2405                continue;
2406            }
2407
2408            if (m1 != sym) {
2409                overridesAny = true;
2410                potentiallyAmbiguousList = List.nil();
2411            }
2412
2413            //...check each method m2 that is a member of 'site'
2414            for (Symbol m2 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2415                if (m2 == m1) continue;
2416                //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2417                //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2418                if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2419                        types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2420                    sym.flags_field |= CLASH;
2421                    String key = m1 == sym ?
2422                            "name.clash.same.erasure.no.override" :
2423                            "name.clash.same.erasure.no.override.1";
2424                    log.error(pos,
2425                            key,
2426                            sym, sym.location(),
2427                            m2, m2.location(),
2428                            m1, m1.location());
2429                    return;
2430                }
2431            }
2432        }
2433
2434        if (!overridesAny) {
2435            for (MethodSymbol m: potentiallyAmbiguousList) {
2436                checkPotentiallyAmbiguousOverloads(pos, site, sym, m);
2437            }
2438        }
2439    }
2440
2441    /** Check that all static methods accessible from 'site' are
2442     *  mutually compatible (JLS 8.4.8).
2443     *
2444     *  @param pos  Position to be used for error reporting.
2445     *  @param site The class whose methods are checked.
2446     *  @param sym  The method symbol to be checked.
2447     */
2448    void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2449        ClashFilter cf = new ClashFilter(site);
2450        //for each method m1 that is a member of 'site'...
2451        for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2452            //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2453            //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2454            if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck)) {
2455                if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2456                    log.error(pos,
2457                            "name.clash.same.erasure.no.hide",
2458                            sym, sym.location(),
2459                            s, s.location());
2460                    return;
2461                } else {
2462                    checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
2463                }
2464            }
2465         }
2466     }
2467
2468     //where
2469     private class ClashFilter implements Filter<Symbol> {
2470
2471         Type site;
2472
2473         ClashFilter(Type site) {
2474             this.site = site;
2475         }
2476
2477         boolean shouldSkip(Symbol s) {
2478             return (s.flags() & CLASH) != 0 &&
2479                s.owner == site.tsym;
2480         }
2481
2482         public boolean accepts(Symbol s) {
2483             return s.kind == MTH &&
2484                     (s.flags() & SYNTHETIC) == 0 &&
2485                     !shouldSkip(s) &&
2486                     s.isInheritedIn(site.tsym, types) &&
2487                     !s.isConstructor();
2488         }
2489     }
2490
2491    void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2492        DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2493        for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2494            Assert.check(m.kind == MTH);
2495            List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2496            if (prov.size() > 1) {
2497                ListBuffer<Symbol> abstracts = new ListBuffer<>();
2498                ListBuffer<Symbol> defaults = new ListBuffer<>();
2499                for (MethodSymbol provSym : prov) {
2500                    if ((provSym.flags() & DEFAULT) != 0) {
2501                        defaults = defaults.append(provSym);
2502                    } else if ((provSym.flags() & ABSTRACT) != 0) {
2503                        abstracts = abstracts.append(provSym);
2504                    }
2505                    if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2506                        //strong semantics - issue an error if two sibling interfaces
2507                        //have two override-equivalent defaults - or if one is abstract
2508                        //and the other is default
2509                        String errKey;
2510                        Symbol s1 = defaults.first();
2511                        Symbol s2;
2512                        if (defaults.size() > 1) {
2513                            errKey = "types.incompatible.unrelated.defaults";
2514                            s2 = defaults.toList().tail.head;
2515                        } else {
2516                            errKey = "types.incompatible.abstract.default";
2517                            s2 = abstracts.first();
2518                        }
2519                        log.error(pos, errKey,
2520                                Kinds.kindName(site.tsym), site,
2521                                m.name, types.memberType(site, m).getParameterTypes(),
2522                                s1.location(), s2.location());
2523                        break;
2524                    }
2525                }
2526            }
2527        }
2528    }
2529
2530    //where
2531     private class DefaultMethodClashFilter implements Filter<Symbol> {
2532
2533         Type site;
2534
2535         DefaultMethodClashFilter(Type site) {
2536             this.site = site;
2537         }
2538
2539         public boolean accepts(Symbol s) {
2540             return s.kind == MTH &&
2541                     (s.flags() & DEFAULT) != 0 &&
2542                     s.isInheritedIn(site.tsym, types) &&
2543                     !s.isConstructor();
2544         }
2545     }
2546
2547    /**
2548      * Report warnings for potentially ambiguous method declarations. Two declarations
2549      * are potentially ambiguous if they feature two unrelated functional interface
2550      * in same argument position (in which case, a call site passing an implicit
2551      * lambda would be ambiguous).
2552      */
2553    void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2554            MethodSymbol msym1, MethodSymbol msym2) {
2555        if (msym1 != msym2 &&
2556                allowDefaultMethods &&
2557                lint.isEnabled(LintCategory.OVERLOADS) &&
2558                (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2559                (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2560            Type mt1 = types.memberType(site, msym1);
2561            Type mt2 = types.memberType(site, msym2);
2562            //if both generic methods, adjust type variables
2563            if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2564                    types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2565                mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2566            }
2567            //expand varargs methods if needed
2568            int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2569            List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2570            List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2571            //if arities don't match, exit
2572            if (args1.length() != args2.length()) return;
2573            boolean potentiallyAmbiguous = false;
2574            while (args1.nonEmpty() && args2.nonEmpty()) {
2575                Type s = args1.head;
2576                Type t = args2.head;
2577                if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2578                    if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2579                            types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2580                            types.findDescriptorType(s).getParameterTypes().length() ==
2581                            types.findDescriptorType(t).getParameterTypes().length()) {
2582                        potentiallyAmbiguous = true;
2583                    } else {
2584                        break;
2585                    }
2586                }
2587                args1 = args1.tail;
2588                args2 = args2.tail;
2589            }
2590            if (potentiallyAmbiguous) {
2591                //we found two incompatible functional interfaces with same arity
2592                //this means a call site passing an implicit lambda would be ambigiuous
2593                msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
2594                msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
2595                log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload",
2596                            msym1, msym1.location(),
2597                            msym2, msym2.location());
2598                return;
2599            }
2600        }
2601    }
2602
2603    void checkElemAccessFromSerializableLambda(final JCTree tree) {
2604        if (warnOnAccessToSensitiveMembers) {
2605            Symbol sym = TreeInfo.symbol(tree);
2606            if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2607                return;
2608            }
2609
2610            if (sym.kind == VAR) {
2611                if ((sym.flags() & PARAMETER) != 0 ||
2612                    sym.isLocal() ||
2613                    sym.name == names._this ||
2614                    sym.name == names._super) {
2615                    return;
2616                }
2617            }
2618
2619            if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
2620                    isEffectivelyNonPublic(sym)) {
2621                log.warning(tree.pos(),
2622                        "access.to.sensitive.member.from.serializable.element", sym);
2623            }
2624        }
2625    }
2626
2627    private boolean isEffectivelyNonPublic(Symbol sym) {
2628        if (sym.packge() == syms.rootPackage) {
2629            return false;
2630        }
2631
2632        while (sym.kind != PCK) {
2633            if ((sym.flags() & PUBLIC) == 0) {
2634                return true;
2635            }
2636            sym = sym.owner;
2637        }
2638        return false;
2639    }
2640
2641    /** Report a conflict between a user symbol and a synthetic symbol.
2642     */
2643    private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2644        if (!sym.type.isErroneous()) {
2645            log.error(pos, "synthetic.name.conflict", sym, sym.location());
2646        }
2647    }
2648
2649    /** Check that class c does not implement directly or indirectly
2650     *  the same parameterized interface with two different argument lists.
2651     *  @param pos          Position to be used for error reporting.
2652     *  @param type         The type whose interfaces are checked.
2653     */
2654    void checkClassBounds(DiagnosticPosition pos, Type type) {
2655        checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2656    }
2657//where
2658        /** Enter all interfaces of type `type' into the hash table `seensofar'
2659         *  with their class symbol as key and their type as value. Make
2660         *  sure no class is entered with two different types.
2661         */
2662        void checkClassBounds(DiagnosticPosition pos,
2663                              Map<TypeSymbol,Type> seensofar,
2664                              Type type) {
2665            if (type.isErroneous()) return;
2666            for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2667                Type it = l.head;
2668                Type oldit = seensofar.put(it.tsym, it);
2669                if (oldit != null) {
2670                    List<Type> oldparams = oldit.allparams();
2671                    List<Type> newparams = it.allparams();
2672                    if (!types.containsTypeEquivalent(oldparams, newparams))
2673                        log.error(pos, "cant.inherit.diff.arg",
2674                                  it.tsym, Type.toString(oldparams),
2675                                  Type.toString(newparams));
2676                }
2677                checkClassBounds(pos, seensofar, it);
2678            }
2679            Type st = types.supertype(type);
2680            if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2681        }
2682
2683    /** Enter interface into into set.
2684     *  If it existed already, issue a "repeated interface" error.
2685     */
2686    void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2687        if (its.contains(it))
2688            log.error(pos, "repeated.interface");
2689        else {
2690            its.add(it);
2691        }
2692    }
2693
2694/* *************************************************************************
2695 * Check annotations
2696 **************************************************************************/
2697
2698    /**
2699     * Recursively validate annotations values
2700     */
2701    void validateAnnotationTree(JCTree tree) {
2702        class AnnotationValidator extends TreeScanner {
2703            @Override
2704            public void visitAnnotation(JCAnnotation tree) {
2705                if (!tree.type.isErroneous()) {
2706                    super.visitAnnotation(tree);
2707                    validateAnnotation(tree);
2708                }
2709            }
2710        }
2711        tree.accept(new AnnotationValidator());
2712    }
2713
2714    /**
2715     *  {@literal
2716     *  Annotation types are restricted to primitives, String, an
2717     *  enum, an annotation, Class, Class<?>, Class<? extends
2718     *  Anything>, arrays of the preceding.
2719     *  }
2720     */
2721    void validateAnnotationType(JCTree restype) {
2722        // restype may be null if an error occurred, so don't bother validating it
2723        if (restype != null) {
2724            validateAnnotationType(restype.pos(), restype.type);
2725        }
2726    }
2727
2728    void validateAnnotationType(DiagnosticPosition pos, Type type) {
2729        if (type.isPrimitive()) return;
2730        if (types.isSameType(type, syms.stringType)) return;
2731        if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2732        if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2733        if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
2734        if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2735            validateAnnotationType(pos, types.elemtype(type));
2736            return;
2737        }
2738        log.error(pos, "invalid.annotation.member.type");
2739    }
2740
2741    /**
2742     * "It is also a compile-time error if any method declared in an
2743     * annotation type has a signature that is override-equivalent to
2744     * that of any public or protected method declared in class Object
2745     * or in the interface annotation.Annotation."
2746     *
2747     * @jls 9.6 Annotation Types
2748     */
2749    void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2750        for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2751            Scope s = sup.tsym.members();
2752            for (Symbol sym : s.getSymbolsByName(m.name)) {
2753                if (sym.kind == MTH &&
2754                    (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2755                    types.overrideEquivalent(m.type, sym.type))
2756                    log.error(pos, "intf.annotation.member.clash", sym, sup);
2757            }
2758        }
2759    }
2760
2761    /** Check the annotations of a symbol.
2762     */
2763    public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2764        for (JCAnnotation a : annotations)
2765            validateAnnotation(a, s);
2766    }
2767
2768    /** Check the type annotations.
2769     */
2770    public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2771        for (JCAnnotation a : annotations)
2772            validateTypeAnnotation(a, isTypeParameter);
2773    }
2774
2775    /** Check an annotation of a symbol.
2776     */
2777    private void validateAnnotation(JCAnnotation a, Symbol s) {
2778        validateAnnotationTree(a);
2779
2780        if (!annotationApplicable(a, s))
2781            log.error(a.pos(), "annotation.type.not.applicable");
2782
2783        if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2784            if (s.kind != TYP) {
2785                log.error(a.pos(), "bad.functional.intf.anno");
2786            } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
2787                log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s));
2788            }
2789        }
2790    }
2791
2792    public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2793        Assert.checkNonNull(a.type);
2794        validateAnnotationTree(a);
2795
2796        if (a.hasTag(TYPE_ANNOTATION) &&
2797                !a.annotationType.type.isErroneous() &&
2798                !isTypeAnnotation(a, isTypeParameter)) {
2799            log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
2800        }
2801    }
2802
2803    /**
2804     * Validate the proposed container 'repeatable' on the
2805     * annotation type symbol 's'. Report errors at position
2806     * 'pos'.
2807     *
2808     * @param s The (annotation)type declaration annotated with a @Repeatable
2809     * @param repeatable the @Repeatable on 's'
2810     * @param pos where to report errors
2811     */
2812    public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2813        Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2814
2815        Type t = null;
2816        List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2817        if (!l.isEmpty()) {
2818            Assert.check(l.head.fst.name == names.value);
2819            t = ((Attribute.Class)l.head.snd).getValue();
2820        }
2821
2822        if (t == null) {
2823            // errors should already have been reported during Annotate
2824            return;
2825        }
2826
2827        validateValue(t.tsym, s, pos);
2828        validateRetention(t.tsym, s, pos);
2829        validateDocumented(t.tsym, s, pos);
2830        validateInherited(t.tsym, s, pos);
2831        validateTarget(t.tsym, s, pos);
2832        validateDefault(t.tsym, pos);
2833    }
2834
2835    private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2836        Symbol sym = container.members().findFirst(names.value);
2837        if (sym != null && sym.kind == MTH) {
2838            MethodSymbol m = (MethodSymbol) sym;
2839            Type ret = m.getReturnType();
2840            if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2841                log.error(pos, "invalid.repeatable.annotation.value.return",
2842                        container, ret, types.makeArrayType(contained.type));
2843            }
2844        } else {
2845            log.error(pos, "invalid.repeatable.annotation.no.value", container);
2846        }
2847    }
2848
2849    private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2850        Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2851        Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2852
2853        boolean error = false;
2854        switch (containedRetention) {
2855        case RUNTIME:
2856            if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2857                error = true;
2858            }
2859            break;
2860        case CLASS:
2861            if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
2862                error = true;
2863            }
2864        }
2865        if (error ) {
2866            log.error(pos, "invalid.repeatable.annotation.retention",
2867                      container, containerRetention,
2868                      contained, containedRetention);
2869        }
2870    }
2871
2872    private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2873        if (contained.attribute(syms.documentedType.tsym) != null) {
2874            if (container.attribute(syms.documentedType.tsym) == null) {
2875                log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2876            }
2877        }
2878    }
2879
2880    private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2881        if (contained.attribute(syms.inheritedType.tsym) != null) {
2882            if (container.attribute(syms.inheritedType.tsym) == null) {
2883                log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2884            }
2885        }
2886    }
2887
2888    private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2889        // The set of targets the container is applicable to must be a subset
2890        // (with respect to annotation target semantics) of the set of targets
2891        // the contained is applicable to. The target sets may be implicit or
2892        // explicit.
2893
2894        Set<Name> containerTargets;
2895        Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2896        if (containerTarget == null) {
2897            containerTargets = getDefaultTargetSet();
2898        } else {
2899            containerTargets = new HashSet<>();
2900            for (Attribute app : containerTarget.values) {
2901                if (!(app instanceof Attribute.Enum)) {
2902                    continue; // recovery
2903                }
2904                Attribute.Enum e = (Attribute.Enum)app;
2905                containerTargets.add(e.value.name);
2906            }
2907        }
2908
2909        Set<Name> containedTargets;
2910        Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2911        if (containedTarget == null) {
2912            containedTargets = getDefaultTargetSet();
2913        } else {
2914            containedTargets = new HashSet<>();
2915            for (Attribute app : containedTarget.values) {
2916                if (!(app instanceof Attribute.Enum)) {
2917                    continue; // recovery
2918                }
2919                Attribute.Enum e = (Attribute.Enum)app;
2920                containedTargets.add(e.value.name);
2921            }
2922        }
2923
2924        if (!isTargetSubsetOf(containerTargets, containedTargets)) {
2925            log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2926        }
2927    }
2928
2929    /* get a set of names for the default target */
2930    private Set<Name> getDefaultTargetSet() {
2931        if (defaultTargets == null) {
2932            Set<Name> targets = new HashSet<>();
2933            targets.add(names.ANNOTATION_TYPE);
2934            targets.add(names.CONSTRUCTOR);
2935            targets.add(names.FIELD);
2936            targets.add(names.LOCAL_VARIABLE);
2937            targets.add(names.METHOD);
2938            targets.add(names.PACKAGE);
2939            targets.add(names.PARAMETER);
2940            targets.add(names.TYPE);
2941
2942            defaultTargets = java.util.Collections.unmodifiableSet(targets);
2943        }
2944
2945        return defaultTargets;
2946    }
2947    private Set<Name> defaultTargets;
2948
2949
2950    /** Checks that s is a subset of t, with respect to ElementType
2951     * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
2952     * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
2953     * TYPE_PARAMETER}.
2954     */
2955    private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
2956        // Check that all elements in s are present in t
2957        for (Name n2 : s) {
2958            boolean currentElementOk = false;
2959            for (Name n1 : t) {
2960                if (n1 == n2) {
2961                    currentElementOk = true;
2962                    break;
2963                } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2964                    currentElementOk = true;
2965                    break;
2966                } else if (n1 == names.TYPE_USE &&
2967                        (n2 == names.TYPE ||
2968                         n2 == names.ANNOTATION_TYPE ||
2969                         n2 == names.TYPE_PARAMETER)) {
2970                    currentElementOk = true;
2971                    break;
2972                }
2973            }
2974            if (!currentElementOk)
2975                return false;
2976        }
2977        return true;
2978    }
2979
2980    private void validateDefault(Symbol container, DiagnosticPosition pos) {
2981        // validate that all other elements of containing type has defaults
2982        Scope scope = container.members();
2983        for(Symbol elm : scope.getSymbols()) {
2984            if (elm.name != names.value &&
2985                elm.kind == MTH &&
2986                ((MethodSymbol)elm).defaultValue == null) {
2987                log.error(pos,
2988                          "invalid.repeatable.annotation.elem.nondefault",
2989                          container,
2990                          elm);
2991            }
2992        }
2993    }
2994
2995    /** Is s a method symbol that overrides a method in a superclass? */
2996    boolean isOverrider(Symbol s) {
2997        if (s.kind != MTH || s.isStatic())
2998            return false;
2999        MethodSymbol m = (MethodSymbol)s;
3000        TypeSymbol owner = (TypeSymbol)m.owner;
3001        for (Type sup : types.closure(owner.type)) {
3002            if (sup == owner.type)
3003                continue; // skip "this"
3004            Scope scope = sup.tsym.members();
3005            for (Symbol sym : scope.getSymbolsByName(m.name)) {
3006                if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3007                    return true;
3008            }
3009        }
3010        return false;
3011    }
3012
3013    /** Is the annotation applicable to types? */
3014    protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3015        List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3016        return (targets == null) ?
3017                false :
3018                targets.stream()
3019                        .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3020    }
3021    //where
3022        boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3023            Attribute.Enum e = (Attribute.Enum)a;
3024            return (e.value.name == names.TYPE_USE ||
3025                    (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3026        }
3027
3028    /** Is the annotation applicable to the symbol? */
3029    boolean annotationApplicable(JCAnnotation a, Symbol s) {
3030        Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3031        Name[] targets;
3032
3033        if (arr == null) {
3034            targets = defaultTargetMetaInfo(a, s);
3035        } else {
3036            // TODO: can we optimize this?
3037            targets = new Name[arr.values.length];
3038            for (int i=0; i<arr.values.length; ++i) {
3039                Attribute app = arr.values[i];
3040                if (!(app instanceof Attribute.Enum)) {
3041                    return true; // recovery
3042                }
3043                Attribute.Enum e = (Attribute.Enum) app;
3044                targets[i] = e.value.name;
3045            }
3046        }
3047        for (Name target : targets) {
3048            if (target == names.TYPE) {
3049                if (s.kind == TYP)
3050                    return true;
3051            } else if (target == names.FIELD) {
3052                if (s.kind == VAR && s.owner.kind != MTH)
3053                    return true;
3054            } else if (target == names.METHOD) {
3055                if (s.kind == MTH && !s.isConstructor())
3056                    return true;
3057            } else if (target == names.PARAMETER) {
3058                if (s.kind == VAR && s.owner.kind == MTH &&
3059                      (s.flags() & PARAMETER) != 0) {
3060                    return true;
3061                }
3062            } else if (target == names.CONSTRUCTOR) {
3063                if (s.kind == MTH && s.isConstructor())
3064                    return true;
3065            } else if (target == names.LOCAL_VARIABLE) {
3066                if (s.kind == VAR && s.owner.kind == MTH &&
3067                      (s.flags() & PARAMETER) == 0) {
3068                    return true;
3069                }
3070            } else if (target == names.ANNOTATION_TYPE) {
3071                if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3072                    return true;
3073                }
3074            } else if (target == names.PACKAGE) {
3075                if (s.kind == PCK)
3076                    return true;
3077            } else if (target == names.TYPE_USE) {
3078                if (s.kind == TYP || s.kind == VAR ||
3079                        (s.kind == MTH && !s.isConstructor() &&
3080                                !s.type.getReturnType().hasTag(VOID)) ||
3081                        (s.kind == MTH && s.isConstructor())) {
3082                    return true;
3083                }
3084            } else if (target == names.TYPE_PARAMETER) {
3085                if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3086                    return true;
3087            } else
3088                return true; // Unknown ElementType. This should be an error at declaration site,
3089                             // assume applicable.
3090        }
3091        return false;
3092    }
3093
3094
3095    Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3096        Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3097        if (atTarget == null) return null; // ok, is applicable
3098        Attribute atValue = atTarget.member(names.value);
3099        if (!(atValue instanceof Attribute.Array)) return null; // error recovery
3100        return (Attribute.Array) atValue;
3101    }
3102
3103    private final Name[] dfltTargetMeta;
3104    private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
3105        return dfltTargetMeta;
3106    }
3107
3108    /** Check an annotation value.
3109     *
3110     * @param a The annotation tree to check
3111     * @return true if this annotation tree is valid, otherwise false
3112     */
3113    public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3114        boolean res = false;
3115        final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3116        try {
3117            res = validateAnnotation(a);
3118        } finally {
3119            log.popDiagnosticHandler(diagHandler);
3120        }
3121        return res;
3122    }
3123
3124    private boolean validateAnnotation(JCAnnotation a) {
3125        boolean isValid = true;
3126        AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3127
3128        // collect an inventory of the annotation elements
3129        Set<MethodSymbol> elements = metadata.getAnnotationElements();
3130
3131        // remove the ones that are assigned values
3132        for (JCTree arg : a.args) {
3133            if (!arg.hasTag(ASSIGN)) continue; // recovery
3134            JCAssign assign = (JCAssign)arg;
3135            Symbol m = TreeInfo.symbol(assign.lhs);
3136            if (m == null || m.type.isErroneous()) continue;
3137            if (!elements.remove(m)) {
3138                isValid = false;
3139                log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3140                        m.name, a.type);
3141            }
3142        }
3143
3144        // all the remaining ones better have default values
3145        List<Name> missingDefaults = List.nil();
3146        Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3147        for (MethodSymbol m : elements) {
3148            if (m.type.isErroneous())
3149                continue;
3150
3151            if (!membersWithDefault.contains(m))
3152                missingDefaults = missingDefaults.append(m.name);
3153        }
3154        missingDefaults = missingDefaults.reverse();
3155        if (missingDefaults.nonEmpty()) {
3156            isValid = false;
3157            String key = (missingDefaults.size() > 1)
3158                    ? "annotation.missing.default.value.1"
3159                    : "annotation.missing.default.value";
3160            log.error(a.pos(), key, a.type, missingDefaults);
3161        }
3162
3163        return isValid && validateTargetAnnotationValue(a);
3164    }
3165
3166    /* Validate the special java.lang.annotation.Target annotation */
3167    boolean validateTargetAnnotationValue(JCAnnotation a) {
3168        // special case: java.lang.annotation.Target must not have
3169        // repeated values in its value member
3170        if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3171                a.args.tail == null)
3172            return true;
3173
3174        boolean isValid = true;
3175        if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3176        JCAssign assign = (JCAssign) a.args.head;
3177        Symbol m = TreeInfo.symbol(assign.lhs);
3178        if (m.name != names.value) return false;
3179        JCTree rhs = assign.rhs;
3180        if (!rhs.hasTag(NEWARRAY)) return false;
3181        JCNewArray na = (JCNewArray) rhs;
3182        Set<Symbol> targets = new HashSet<>();
3183        for (JCTree elem : na.elems) {
3184            if (!targets.add(TreeInfo.symbol(elem))) {
3185                isValid = false;
3186                log.error(elem.pos(), "repeated.annotation.target");
3187            }
3188        }
3189        return isValid;
3190    }
3191
3192    void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3193        if (lint.isEnabled(LintCategory.DEP_ANN) &&
3194            (s.flags() & DEPRECATED) != 0 &&
3195            !syms.deprecatedType.isErroneous() &&
3196            s.attribute(syms.deprecatedType.tsym) == null) {
3197            log.warning(LintCategory.DEP_ANN,
3198                    pos, "missing.deprecated.annotation");
3199        }
3200        // Note: @Deprecated has no effect on local variables, parameters and package decls.
3201        if (lint.isEnabled(LintCategory.DEPRECATION)) {
3202            if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3203                switch (s.getKind()) {
3204                    case LOCAL_VARIABLE:
3205                    case PACKAGE:
3206                    case PARAMETER:
3207                    case RESOURCE_VARIABLE:
3208                    case EXCEPTION_PARAMETER:
3209                        log.warning(LintCategory.DEPRECATION, pos,
3210                                "deprecated.annotation.has.no.effect", Kinds.kindName(s));
3211                        break;
3212                }
3213            }
3214        }
3215    }
3216
3217    void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3218        if ((s.flags() & DEPRECATED) != 0 &&
3219                (other.flags() & DEPRECATED) == 0 &&
3220                s.outermostClass() != other.outermostClass()) {
3221            deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3222                @Override
3223                public void report() {
3224                    warnDeprecated(pos, s);
3225                }
3226            });
3227        }
3228    }
3229
3230    void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3231        if ((s.flags() & PROPRIETARY) != 0) {
3232            deferredLintHandler.report(() -> {
3233                log.mandatoryWarning(pos, "sun.proprietary", s);
3234            });
3235        }
3236    }
3237
3238    void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3239        if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3240            log.error(pos, "not.in.profile", s, profile);
3241        }
3242    }
3243
3244/* *************************************************************************
3245 * Check for recursive annotation elements.
3246 **************************************************************************/
3247
3248    /** Check for cycles in the graph of annotation elements.
3249     */
3250    void checkNonCyclicElements(JCClassDecl tree) {
3251        if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3252        Assert.check((tree.sym.flags_field & LOCKED) == 0);
3253        try {
3254            tree.sym.flags_field |= LOCKED;
3255            for (JCTree def : tree.defs) {
3256                if (!def.hasTag(METHODDEF)) continue;
3257                JCMethodDecl meth = (JCMethodDecl)def;
3258                checkAnnotationResType(meth.pos(), meth.restype.type);
3259            }
3260        } finally {
3261            tree.sym.flags_field &= ~LOCKED;
3262            tree.sym.flags_field |= ACYCLIC_ANN;
3263        }
3264    }
3265
3266    void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3267        if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3268            return;
3269        if ((tsym.flags_field & LOCKED) != 0) {
3270            log.error(pos, "cyclic.annotation.element");
3271            return;
3272        }
3273        try {
3274            tsym.flags_field |= LOCKED;
3275            for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3276                if (s.kind != MTH)
3277                    continue;
3278                checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3279            }
3280        } finally {
3281            tsym.flags_field &= ~LOCKED;
3282            tsym.flags_field |= ACYCLIC_ANN;
3283        }
3284    }
3285
3286    void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3287        switch (type.getTag()) {
3288        case CLASS:
3289            if ((type.tsym.flags() & ANNOTATION) != 0)
3290                checkNonCyclicElementsInternal(pos, type.tsym);
3291            break;
3292        case ARRAY:
3293            checkAnnotationResType(pos, types.elemtype(type));
3294            break;
3295        default:
3296            break; // int etc
3297        }
3298    }
3299
3300/* *************************************************************************
3301 * Check for cycles in the constructor call graph.
3302 **************************************************************************/
3303
3304    /** Check for cycles in the graph of constructors calling other
3305     *  constructors.
3306     */
3307    void checkCyclicConstructors(JCClassDecl tree) {
3308        Map<Symbol,Symbol> callMap = new HashMap<>();
3309
3310        // enter each constructor this-call into the map
3311        for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3312            JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3313            if (app == null) continue;
3314            JCMethodDecl meth = (JCMethodDecl) l.head;
3315            if (TreeInfo.name(app.meth) == names._this) {
3316                callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3317            } else {
3318                meth.sym.flags_field |= ACYCLIC;
3319            }
3320        }
3321
3322        // Check for cycles in the map
3323        Symbol[] ctors = new Symbol[0];
3324        ctors = callMap.keySet().toArray(ctors);
3325        for (Symbol caller : ctors) {
3326            checkCyclicConstructor(tree, caller, callMap);
3327        }
3328    }
3329
3330    /** Look in the map to see if the given constructor is part of a
3331     *  call cycle.
3332     */
3333    private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3334                                        Map<Symbol,Symbol> callMap) {
3335        if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3336            if ((ctor.flags_field & LOCKED) != 0) {
3337                log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3338                          "recursive.ctor.invocation");
3339            } else {
3340                ctor.flags_field |= LOCKED;
3341                checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3342                ctor.flags_field &= ~LOCKED;
3343            }
3344            ctor.flags_field |= ACYCLIC;
3345        }
3346    }
3347
3348/* *************************************************************************
3349 * Miscellaneous
3350 **************************************************************************/
3351
3352    /**
3353     *  Check for division by integer constant zero
3354     *  @param pos           Position for error reporting.
3355     *  @param operator      The operator for the expression
3356     *  @param operand       The right hand operand for the expression
3357     */
3358    void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3359        if (operand.constValue() != null
3360            && operand.getTag().isSubRangeOf(LONG)
3361            && ((Number) (operand.constValue())).longValue() == 0) {
3362            int opc = ((OperatorSymbol)operator).opcode;
3363            if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3364                || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3365                deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3366                    @Override
3367                    public void report() {
3368                        warnDivZero(pos);
3369                    }
3370                });
3371            }
3372        }
3373    }
3374
3375    /**
3376     * Check for empty statements after if
3377     */
3378    void checkEmptyIf(JCIf tree) {
3379        if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3380                lint.isEnabled(LintCategory.EMPTY))
3381            log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3382    }
3383
3384    /** Check that symbol is unique in given scope.
3385     *  @param pos           Position for error reporting.
3386     *  @param sym           The symbol.
3387     *  @param s             The scope.
3388     */
3389    boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3390        if (sym.type.isErroneous())
3391            return true;
3392        if (sym.owner.name == names.any) return false;
3393        for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
3394            if (sym != byName &&
3395                    (byName.flags() & CLASH) == 0 &&
3396                    sym.kind == byName.kind &&
3397                    sym.name != names.error &&
3398                    (sym.kind != MTH ||
3399                     types.hasSameArgs(sym.type, byName.type) ||
3400                     types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
3401                if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
3402                    varargsDuplicateError(pos, sym, byName);
3403                    return true;
3404                } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
3405                    duplicateErasureError(pos, sym, byName);
3406                    sym.flags_field |= CLASH;
3407                    return true;
3408                } else {
3409                    duplicateError(pos, byName);
3410                    return false;
3411                }
3412            }
3413        }
3414        return true;
3415    }
3416
3417    /** Report duplicate declaration error.
3418     */
3419    void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3420        if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3421            log.error(pos, "name.clash.same.erasure", sym1, sym2);
3422        }
3423    }
3424
3425    /**Check that types imported through the ordinary imports don't clash with types imported
3426     * by other (static or ordinary) imports. Note that two static imports may import two clashing
3427     * types without an error on the imports.
3428     * @param toplevel       The toplevel tree for which the test should be performed.
3429     */
3430    void checkImportsUnique(JCCompilationUnit toplevel) {
3431        WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
3432        WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
3433        WriteableScope topLevelScope = toplevel.toplevelScope;
3434
3435        for (JCTree def : toplevel.defs) {
3436            if (!def.hasTag(IMPORT))
3437                continue;
3438
3439            JCImport imp = (JCImport) def;
3440
3441            if (imp.importScope == null)
3442                continue;
3443
3444            for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
3445                if (imp.isStatic()) {
3446                    checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
3447                    staticallyImportedSoFar.enter(sym);
3448                } else {
3449                    checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
3450                    ordinallyImportedSoFar.enter(sym);
3451                }
3452            }
3453
3454            imp.importScope = null;
3455        }
3456    }
3457
3458    /** Check that single-type import is not already imported or top-level defined,
3459     *  but make an exception for two single-type imports which denote the same type.
3460     *  @param pos                     Position for error reporting.
3461     *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
3462     *                                 ordinary imports.
3463     *  @param staticallyImportedSoFar A Scope containing types imported so far through
3464     *                                 static imports.
3465     *  @param topLevelScope           The current file's top-level Scope
3466     *  @param sym                     The symbol.
3467     *  @param staticImport            Whether or not this was a static import
3468     */
3469    private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
3470                                      Scope staticallyImportedSoFar, Scope topLevelScope,
3471                                      Symbol sym, boolean staticImport) {
3472        Filter<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
3473        Symbol clashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
3474        if (clashing == null && !staticImport) {
3475            clashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
3476        }
3477        if (clashing != null) {
3478            if (staticImport)
3479                log.error(pos, "already.defined.static.single.import", clashing);
3480            else
3481                log.error(pos, "already.defined.single.import", clashing);
3482            return false;
3483        }
3484        clashing = topLevelScope.findFirst(sym.name, duplicates);
3485        if (clashing != null) {
3486            log.error(pos, "already.defined.this.unit", clashing);
3487            return false;
3488        }
3489        return true;
3490    }
3491
3492    /** Check that a qualified name is in canonical form (for import decls).
3493     */
3494    public void checkCanonical(JCTree tree) {
3495        if (!isCanonical(tree))
3496            log.error(tree.pos(), "import.requires.canonical",
3497                      TreeInfo.symbol(tree));
3498    }
3499        // where
3500        private boolean isCanonical(JCTree tree) {
3501            while (tree.hasTag(SELECT)) {
3502                JCFieldAccess s = (JCFieldAccess) tree;
3503                if (s.sym.owner.name != TreeInfo.symbol(s.selected).name)
3504                    return false;
3505                tree = s.selected;
3506            }
3507            return true;
3508        }
3509
3510    /** Check that an auxiliary class is not accessed from any other file than its own.
3511     */
3512    void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3513        if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3514            (c.flags() & AUXILIARY) != 0 &&
3515            rs.isAccessible(env, c) &&
3516            !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3517        {
3518            log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3519                        c, c.sourcefile);
3520        }
3521    }
3522
3523    private class ConversionWarner extends Warner {
3524        final String uncheckedKey;
3525        final Type found;
3526        final Type expected;
3527        public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3528            super(pos);
3529            this.uncheckedKey = uncheckedKey;
3530            this.found = found;
3531            this.expected = expected;
3532        }
3533
3534        @Override
3535        public void warn(LintCategory lint) {
3536            boolean warned = this.warned;
3537            super.warn(lint);
3538            if (warned) return; // suppress redundant diagnostics
3539            switch (lint) {
3540                case UNCHECKED:
3541                    Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3542                    break;
3543                case VARARGS:
3544                    if (method != null &&
3545                            method.attribute(syms.trustMeType.tsym) != null &&
3546                            isTrustMeAllowedOnMethod(method) &&
3547                            !types.isReifiable(method.type.getParameterTypes().last())) {
3548                        Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3549                    }
3550                    break;
3551                default:
3552                    throw new AssertionError("Unexpected lint: " + lint);
3553            }
3554        }
3555    }
3556
3557    public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3558        return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3559    }
3560
3561    public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3562        return new ConversionWarner(pos, "unchecked.assign", found, expected);
3563    }
3564
3565    public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
3566        Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
3567
3568        if (functionalType != null) {
3569            try {
3570                types.findDescriptorSymbol((TypeSymbol)cs);
3571            } catch (Types.FunctionDescriptorLookupError ex) {
3572                DiagnosticPosition pos = tree.pos();
3573                for (JCAnnotation a : tree.getModifiers().annotations) {
3574                    if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3575                        pos = a.pos();
3576                        break;
3577                    }
3578                }
3579                log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic());
3580            }
3581        }
3582    }
3583
3584    public void checkImportsResolvable(final JCCompilationUnit toplevel) {
3585        for (final JCImport imp : toplevel.getImports()) {
3586            if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
3587                continue;
3588            final JCFieldAccess select = (JCFieldAccess) imp.qualid;
3589            final Symbol origin;
3590            if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
3591                continue;
3592
3593            TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
3594            if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
3595                log.error(imp.pos(), "cant.resolve.location",
3596                          KindName.STATIC,
3597                          select.name, List.<Type>nil(), List.<Type>nil(),
3598                          Kinds.typeKindName(TreeInfo.symbol(select.selected).type),
3599                          TreeInfo.symbol(select.selected).type);
3600            }
3601        }
3602    }
3603
3604    // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
3605    public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
3606        OUTER: for (JCImport imp : toplevel.getImports()) {
3607            if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) {
3608                TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym;
3609                if (toplevel.modle.visiblePackages != null) {
3610                    //TODO - unclear: selects like javax.* will get resolved from the current module
3611                    //(as javax is not an exported package from any module). And as javax in the current
3612                    //module typically does not contain any classes or subpackages, we need to go through
3613                    //the visible packages to find a sub-package:
3614                    for (PackageSymbol known : toplevel.modle.visiblePackages.values()) {
3615                        if (Convert.packagePart(known.fullname) == tsym.flatName())
3616                            continue OUTER;
3617                    }
3618                }
3619                if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) {
3620                    log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, "doesnt.exist", tsym);
3621                }
3622            }
3623        }
3624    }
3625
3626    private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
3627        if (tsym == null || !processed.add(tsym))
3628            return false;
3629
3630            // also search through inherited names
3631        if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
3632            return true;
3633
3634        for (Type t : types.interfaces(tsym.type))
3635            if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
3636                return true;
3637
3638        for (Symbol sym : tsym.members().getSymbolsByName(name)) {
3639            if (sym.isStatic() &&
3640                importAccessible(sym, packge) &&
3641                sym.isMemberOf(origin, types)) {
3642                return true;
3643            }
3644        }
3645
3646        return false;
3647    }
3648
3649    // is the sym accessible everywhere in packge?
3650    public boolean importAccessible(Symbol sym, PackageSymbol packge) {
3651        try {
3652            int flags = (int)(sym.flags() & AccessFlags);
3653            switch (flags) {
3654            default:
3655            case PUBLIC:
3656                return true;
3657            case PRIVATE:
3658                return false;
3659            case 0:
3660            case PROTECTED:
3661                return sym.packge() == packge;
3662            }
3663        } catch (ClassFinder.BadClassFile err) {
3664            throw err;
3665        } catch (CompletionFailure ex) {
3666            return false;
3667        }
3668    }
3669
3670}
3671