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