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