Check.java revision 2824:e0b35c562008
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)) != 0) {
1060                    mask = InterfaceMethodMask;
1061                    implicit = 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,
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 ((origin.flags() & INTERFACE) == 0 &&
1627                 protection(m.flags()) > protection(other.flags())) {
1628            log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1629                      cannotOverride(m, other),
1630                      (other.flags() & AccessFlags) == 0 ?
1631                          "package" :
1632                          asFlagSet(other.flags() & AccessFlags));
1633            m.flags_field |= BAD_OVERRIDE;
1634            return;
1635        }
1636
1637        Type mt = types.memberType(origin.type, m);
1638        Type ot = types.memberType(origin.type, other);
1639        // Error if overriding result type is different
1640        // (or, in the case of generics mode, not a subtype) of
1641        // overridden result type. We have to rename any type parameters
1642        // before comparing types.
1643        List<Type> mtvars = mt.getTypeArguments();
1644        List<Type> otvars = ot.getTypeArguments();
1645        Type mtres = mt.getReturnType();
1646        Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1647
1648        overrideWarner.clear();
1649        boolean resultTypesOK =
1650            types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1651        if (!resultTypesOK) {
1652            log.error(TreeInfo.diagnosticPositionFor(m, tree),
1653                      "override.incompatible.ret",
1654                      cannotOverride(m, other),
1655                      mtres, otres);
1656            m.flags_field |= BAD_OVERRIDE;
1657            return;
1658        } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1659            warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1660                    "override.unchecked.ret",
1661                    uncheckedOverrides(m, other),
1662                    mtres, otres);
1663        }
1664
1665        // Error if overriding method throws an exception not reported
1666        // by overridden method.
1667        List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1668        List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1669        List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1670        if (unhandledErased.nonEmpty()) {
1671            log.error(TreeInfo.diagnosticPositionFor(m, tree),
1672                      "override.meth.doesnt.throw",
1673                      cannotOverride(m, other),
1674                      unhandledUnerased.head);
1675            m.flags_field |= BAD_OVERRIDE;
1676            return;
1677        }
1678        else if (unhandledUnerased.nonEmpty()) {
1679            warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1680                          "override.unchecked.thrown",
1681                         cannotOverride(m, other),
1682                         unhandledUnerased.head);
1683            return;
1684        }
1685
1686        // Optional warning if varargs don't agree
1687        if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1688            && lint.isEnabled(LintCategory.OVERRIDES)) {
1689            log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1690                        ((m.flags() & Flags.VARARGS) != 0)
1691                        ? "override.varargs.missing"
1692                        : "override.varargs.extra",
1693                        varargsOverrides(m, other));
1694        }
1695
1696        // Warn if instance method overrides bridge method (compiler spec ??)
1697        if ((other.flags() & BRIDGE) != 0) {
1698            log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1699                        uncheckedOverrides(m, other));
1700        }
1701
1702        // Warn if a deprecated method overridden by a non-deprecated one.
1703        if (!isDeprecatedOverrideIgnorable(other, origin)) {
1704            Lint prevLint = setLint(lint.augment(m));
1705            try {
1706                checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1707            } finally {
1708                setLint(prevLint);
1709            }
1710        }
1711    }
1712    // where
1713        private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1714            // If the method, m, is defined in an interface, then ignore the issue if the method
1715            // is only inherited via a supertype and also implemented in the supertype,
1716            // because in that case, we will rediscover the issue when examining the method
1717            // in the supertype.
1718            // If the method, m, is not defined in an interface, then the only time we need to
1719            // address the issue is when the method is the supertype implemementation: any other
1720            // case, we will have dealt with when examining the supertype classes
1721            ClassSymbol mc = m.enclClass();
1722            Type st = types.supertype(origin.type);
1723            if (!st.hasTag(CLASS))
1724                return true;
1725            MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1726
1727            if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1728                List<Type> intfs = types.interfaces(origin.type);
1729                return (intfs.contains(mc.type) ? false : (stimpl != null));
1730            }
1731            else
1732                return (stimpl != m);
1733        }
1734
1735
1736    // used to check if there were any unchecked conversions
1737    Warner overrideWarner = new Warner();
1738
1739    /** Check that a class does not inherit two concrete methods
1740     *  with the same signature.
1741     *  @param pos          Position to be used for error reporting.
1742     *  @param site         The class type to be checked.
1743     */
1744    public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1745        Type sup = types.supertype(site);
1746        if (!sup.hasTag(CLASS)) return;
1747
1748        for (Type t1 = sup;
1749             t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1750             t1 = types.supertype(t1)) {
1751            for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1752                if (s1.kind != MTH ||
1753                    (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1754                    !s1.isInheritedIn(site.tsym, types) ||
1755                    ((MethodSymbol)s1).implementation(site.tsym,
1756                                                      types,
1757                                                      true) != s1)
1758                    continue;
1759                Type st1 = types.memberType(t1, s1);
1760                int s1ArgsLength = st1.getParameterTypes().length();
1761                if (st1 == s1.type) continue;
1762
1763                for (Type t2 = sup;
1764                     t2.hasTag(CLASS);
1765                     t2 = types.supertype(t2)) {
1766                    for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1767                        if (s2 == s1 ||
1768                            s2.kind != MTH ||
1769                            (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1770                            s2.type.getParameterTypes().length() != s1ArgsLength ||
1771                            !s2.isInheritedIn(site.tsym, types) ||
1772                            ((MethodSymbol)s2).implementation(site.tsym,
1773                                                              types,
1774                                                              true) != s2)
1775                            continue;
1776                        Type st2 = types.memberType(t2, s2);
1777                        if (types.overrideEquivalent(st1, st2))
1778                            log.error(pos, "concrete.inheritance.conflict",
1779                                      s1, t1, s2, t2, sup);
1780                    }
1781                }
1782            }
1783        }
1784    }
1785
1786    /** Check that classes (or interfaces) do not each define an abstract
1787     *  method with same name and arguments but incompatible return types.
1788     *  @param pos          Position to be used for error reporting.
1789     *  @param t1           The first argument type.
1790     *  @param t2           The second argument type.
1791     */
1792    public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1793                                            Type t1,
1794                                            Type t2,
1795                                            Type site) {
1796        if ((site.tsym.flags() & COMPOUND) != 0) {
1797            // special case for intersections: need to eliminate wildcards in supertypes
1798            t1 = types.capture(t1);
1799            t2 = types.capture(t2);
1800        }
1801        return firstIncompatibility(pos, t1, t2, site) == null;
1802    }
1803
1804    /** Return the first method which is defined with same args
1805     *  but different return types in two given interfaces, or null if none
1806     *  exists.
1807     *  @param t1     The first type.
1808     *  @param t2     The second type.
1809     *  @param site   The most derived type.
1810     *  @returns symbol from t2 that conflicts with one in t1.
1811     */
1812    private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1813        Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1814        closure(t1, interfaces1);
1815        Map<TypeSymbol,Type> interfaces2;
1816        if (t1 == t2)
1817            interfaces2 = interfaces1;
1818        else
1819            closure(t2, interfaces1, interfaces2 = new HashMap<>());
1820
1821        for (Type t3 : interfaces1.values()) {
1822            for (Type t4 : interfaces2.values()) {
1823                Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1824                if (s != null) return s;
1825            }
1826        }
1827        return null;
1828    }
1829
1830    /** Compute all the supertypes of t, indexed by type symbol. */
1831    private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1832        if (!t.hasTag(CLASS)) return;
1833        if (typeMap.put(t.tsym, t) == null) {
1834            closure(types.supertype(t), typeMap);
1835            for (Type i : types.interfaces(t))
1836                closure(i, typeMap);
1837        }
1838    }
1839
1840    /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1841    private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1842        if (!t.hasTag(CLASS)) return;
1843        if (typesSkip.get(t.tsym) != null) return;
1844        if (typeMap.put(t.tsym, t) == null) {
1845            closure(types.supertype(t), typesSkip, typeMap);
1846            for (Type i : types.interfaces(t))
1847                closure(i, typesSkip, typeMap);
1848        }
1849    }
1850
1851    /** Return the first method in t2 that conflicts with a method from t1. */
1852    private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1853        for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1854            Type st1 = null;
1855            if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1856                    (s1.flags() & SYNTHETIC) != 0) continue;
1857            Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1858            if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1859            for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1860                if (s1 == s2) continue;
1861                if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1862                        (s2.flags() & SYNTHETIC) != 0) continue;
1863                if (st1 == null) st1 = types.memberType(t1, s1);
1864                Type st2 = types.memberType(t2, s2);
1865                if (types.overrideEquivalent(st1, st2)) {
1866                    List<Type> tvars1 = st1.getTypeArguments();
1867                    List<Type> tvars2 = st2.getTypeArguments();
1868                    Type rt1 = st1.getReturnType();
1869                    Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1870                    boolean compat =
1871                        types.isSameType(rt1, rt2) ||
1872                        !rt1.isPrimitiveOrVoid() &&
1873                        !rt2.isPrimitiveOrVoid() &&
1874                        (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1875                         types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1876                         checkCommonOverriderIn(s1,s2,site);
1877                    if (!compat) {
1878                        log.error(pos, "types.incompatible.diff.ret",
1879                            t1, t2, s2.name +
1880                            "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1881                        return s2;
1882                    }
1883                } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1884                        !checkCommonOverriderIn(s1, s2, site)) {
1885                    log.error(pos,
1886                            "name.clash.same.erasure.no.override",
1887                            s1, s1.location(),
1888                            s2, s2.location());
1889                    return s2;
1890                }
1891            }
1892        }
1893        return null;
1894    }
1895    //WHERE
1896    boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1897        Map<TypeSymbol,Type> supertypes = new HashMap<>();
1898        Type st1 = types.memberType(site, s1);
1899        Type st2 = types.memberType(site, s2);
1900        closure(site, supertypes);
1901        for (Type t : supertypes.values()) {
1902            for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
1903                if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1904                Type st3 = types.memberType(site,s3);
1905                if (types.overrideEquivalent(st3, st1) &&
1906                        types.overrideEquivalent(st3, st2) &&
1907                        types.returnTypeSubstitutable(st3, st1) &&
1908                        types.returnTypeSubstitutable(st3, st2)) {
1909                    return true;
1910                }
1911            }
1912        }
1913        return false;
1914    }
1915
1916    /** Check that a given method conforms with any method it overrides.
1917     *  @param tree         The tree from which positions are extracted
1918     *                      for errors.
1919     *  @param m            The overriding method.
1920     */
1921    void checkOverride(JCMethodDecl tree, MethodSymbol m) {
1922        ClassSymbol origin = (ClassSymbol)m.owner;
1923        if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1924            if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1925                log.error(tree.pos(), "enum.no.finalize");
1926                return;
1927            }
1928        for (Type t = origin.type; t.hasTag(CLASS);
1929             t = types.supertype(t)) {
1930            if (t != origin.type) {
1931                checkOverride(tree, t, origin, m);
1932            }
1933            for (Type t2 : types.interfaces(t)) {
1934                checkOverride(tree, t2, origin, m);
1935            }
1936        }
1937
1938        if (m.attribute(syms.overrideType.tsym) != null && !isOverrider(m)) {
1939            DiagnosticPosition pos = tree.pos();
1940            for (JCAnnotation a : tree.getModifiers().annotations) {
1941                if (a.annotationType.type.tsym == syms.overrideType.tsym) {
1942                    pos = a.pos();
1943                    break;
1944                }
1945            }
1946            log.error(pos, "method.does.not.override.superclass");
1947        }
1948    }
1949
1950    void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1951        TypeSymbol c = site.tsym;
1952        for (Symbol sym : c.members().getSymbolsByName(m.name)) {
1953            if (m.overrides(sym, origin, types, false)) {
1954                if ((sym.flags() & ABSTRACT) == 0) {
1955                    checkOverride(tree, m, (MethodSymbol)sym, origin);
1956                }
1957            }
1958        }
1959    }
1960
1961    private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
1962        public boolean accepts(Symbol s) {
1963            return MethodSymbol.implementation_filter.accepts(s) &&
1964                    (s.flags() & BAD_OVERRIDE) == 0;
1965
1966        }
1967    };
1968
1969    public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
1970            ClassSymbol someClass) {
1971        /* At present, annotations cannot possibly have a method that is override
1972         * equivalent with Object.equals(Object) but in any case the condition is
1973         * fine for completeness.
1974         */
1975        if (someClass == (ClassSymbol)syms.objectType.tsym ||
1976            someClass.isInterface() || someClass.isEnum() ||
1977            (someClass.flags() & ANNOTATION) != 0 ||
1978            (someClass.flags() & ABSTRACT) != 0) return;
1979        //anonymous inner classes implementing interfaces need especial treatment
1980        if (someClass.isAnonymous()) {
1981            List<Type> interfaces =  types.interfaces(someClass.type);
1982            if (interfaces != null && !interfaces.isEmpty() &&
1983                interfaces.head.tsym == syms.comparatorType.tsym) return;
1984        }
1985        checkClassOverrideEqualsAndHash(pos, someClass);
1986    }
1987
1988    private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
1989            ClassSymbol someClass) {
1990        if (lint.isEnabled(LintCategory.OVERRIDES)) {
1991            MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
1992                    .tsym.members().findFirst(names.equals);
1993            MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
1994                    .tsym.members().findFirst(names.hashCode);
1995            boolean overridesEquals = types.implementation(equalsAtObject,
1996                someClass, false, equalsHasCodeFilter).owner == someClass;
1997            boolean overridesHashCode = types.implementation(hashCodeAtObject,
1998                someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
1999
2000            if (overridesEquals && !overridesHashCode) {
2001                log.warning(LintCategory.OVERRIDES, pos,
2002                        "override.equals.but.not.hashcode", someClass);
2003            }
2004        }
2005    }
2006
2007    private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2008        ClashFilter cf = new ClashFilter(origin.type);
2009        return (cf.accepts(s1) &&
2010                cf.accepts(s2) &&
2011                types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2012    }
2013
2014
2015    /** Check that all abstract members of given class have definitions.
2016     *  @param pos          Position to be used for error reporting.
2017     *  @param c            The class.
2018     */
2019    void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2020        MethodSymbol undef = types.firstUnimplementedAbstract(c);
2021        if (undef != null) {
2022            MethodSymbol undef1 =
2023                new MethodSymbol(undef.flags(), undef.name,
2024                                 types.memberType(c.type, undef), undef.owner);
2025            log.error(pos, "does.not.override.abstract",
2026                      c, undef1, undef1.location());
2027        }
2028    }
2029
2030    void checkNonCyclicDecl(JCClassDecl tree) {
2031        CycleChecker cc = new CycleChecker();
2032        cc.scan(tree);
2033        if (!cc.errorFound && !cc.partialCheck) {
2034            tree.sym.flags_field |= ACYCLIC;
2035        }
2036    }
2037
2038    class CycleChecker extends TreeScanner {
2039
2040        List<Symbol> seenClasses = List.nil();
2041        boolean errorFound = false;
2042        boolean partialCheck = false;
2043
2044        private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2045            if (sym != null && sym.kind == TYP) {
2046                Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2047                if (classEnv != null) {
2048                    DiagnosticSource prevSource = log.currentSource();
2049                    try {
2050                        log.useSource(classEnv.toplevel.sourcefile);
2051                        scan(classEnv.tree);
2052                    }
2053                    finally {
2054                        log.useSource(prevSource.getFile());
2055                    }
2056                } else if (sym.kind == TYP) {
2057                    checkClass(pos, sym, List.<JCTree>nil());
2058                }
2059            } else {
2060                //not completed yet
2061                partialCheck = true;
2062            }
2063        }
2064
2065        @Override
2066        public void visitSelect(JCFieldAccess tree) {
2067            super.visitSelect(tree);
2068            checkSymbol(tree.pos(), tree.sym);
2069        }
2070
2071        @Override
2072        public void visitIdent(JCIdent tree) {
2073            checkSymbol(tree.pos(), tree.sym);
2074        }
2075
2076        @Override
2077        public void visitTypeApply(JCTypeApply tree) {
2078            scan(tree.clazz);
2079        }
2080
2081        @Override
2082        public void visitTypeArray(JCArrayTypeTree tree) {
2083            scan(tree.elemtype);
2084        }
2085
2086        @Override
2087        public void visitClassDef(JCClassDecl tree) {
2088            List<JCTree> supertypes = List.nil();
2089            if (tree.getExtendsClause() != null) {
2090                supertypes = supertypes.prepend(tree.getExtendsClause());
2091            }
2092            if (tree.getImplementsClause() != null) {
2093                for (JCTree intf : tree.getImplementsClause()) {
2094                    supertypes = supertypes.prepend(intf);
2095                }
2096            }
2097            checkClass(tree.pos(), tree.sym, supertypes);
2098        }
2099
2100        void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2101            if ((c.flags_field & ACYCLIC) != 0)
2102                return;
2103            if (seenClasses.contains(c)) {
2104                errorFound = true;
2105                noteCyclic(pos, (ClassSymbol)c);
2106            } else if (!c.type.isErroneous()) {
2107                try {
2108                    seenClasses = seenClasses.prepend(c);
2109                    if (c.type.hasTag(CLASS)) {
2110                        if (supertypes.nonEmpty()) {
2111                            scan(supertypes);
2112                        }
2113                        else {
2114                            ClassType ct = (ClassType)c.type;
2115                            if (ct.supertype_field == null ||
2116                                    ct.interfaces_field == null) {
2117                                //not completed yet
2118                                partialCheck = true;
2119                                return;
2120                            }
2121                            checkSymbol(pos, ct.supertype_field.tsym);
2122                            for (Type intf : ct.interfaces_field) {
2123                                checkSymbol(pos, intf.tsym);
2124                            }
2125                        }
2126                        if (c.owner.kind == TYP) {
2127                            checkSymbol(pos, c.owner);
2128                        }
2129                    }
2130                } finally {
2131                    seenClasses = seenClasses.tail;
2132                }
2133            }
2134        }
2135    }
2136
2137    /** Check for cyclic references. Issue an error if the
2138     *  symbol of the type referred to has a LOCKED flag set.
2139     *
2140     *  @param pos      Position to be used for error reporting.
2141     *  @param t        The type referred to.
2142     */
2143    void checkNonCyclic(DiagnosticPosition pos, Type t) {
2144        checkNonCyclicInternal(pos, t);
2145    }
2146
2147
2148    void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2149        checkNonCyclic1(pos, t, List.<TypeVar>nil());
2150    }
2151
2152    private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2153        final TypeVar tv;
2154        if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2155            return;
2156        if (seen.contains(t)) {
2157            tv = (TypeVar)t;
2158            tv.bound = types.createErrorType(t);
2159            log.error(pos, "cyclic.inheritance", t);
2160        } else if (t.hasTag(TYPEVAR)) {
2161            tv = (TypeVar)t;
2162            seen = seen.prepend(tv);
2163            for (Type b : types.getBounds(tv))
2164                checkNonCyclic1(pos, b, seen);
2165        }
2166    }
2167
2168    /** Check for cyclic references. Issue an error if the
2169     *  symbol of the type referred to has a LOCKED flag set.
2170     *
2171     *  @param pos      Position to be used for error reporting.
2172     *  @param t        The type referred to.
2173     *  @returns        True if the check completed on all attributed classes
2174     */
2175    private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2176        boolean complete = true; // was the check complete?
2177        //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2178        Symbol c = t.tsym;
2179        if ((c.flags_field & ACYCLIC) != 0) return true;
2180
2181        if ((c.flags_field & LOCKED) != 0) {
2182            noteCyclic(pos, (ClassSymbol)c);
2183        } else if (!c.type.isErroneous()) {
2184            try {
2185                c.flags_field |= LOCKED;
2186                if (c.type.hasTag(CLASS)) {
2187                    ClassType clazz = (ClassType)c.type;
2188                    if (clazz.interfaces_field != null)
2189                        for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2190                            complete &= checkNonCyclicInternal(pos, l.head);
2191                    if (clazz.supertype_field != null) {
2192                        Type st = clazz.supertype_field;
2193                        if (st != null && st.hasTag(CLASS))
2194                            complete &= checkNonCyclicInternal(pos, st);
2195                    }
2196                    if (c.owner.kind == TYP)
2197                        complete &= checkNonCyclicInternal(pos, c.owner.type);
2198                }
2199            } finally {
2200                c.flags_field &= ~LOCKED;
2201            }
2202        }
2203        if (complete)
2204            complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2205        if (complete) c.flags_field |= ACYCLIC;
2206        return complete;
2207    }
2208
2209    /** Note that we found an inheritance cycle. */
2210    private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2211        log.error(pos, "cyclic.inheritance", c);
2212        for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2213            l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2214        Type st = types.supertype(c.type);
2215        if (st.hasTag(CLASS))
2216            ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2217        c.type = types.createErrorType(c, c.type);
2218        c.flags_field |= ACYCLIC;
2219    }
2220
2221    /** Check that all methods which implement some
2222     *  method conform to the method they implement.
2223     *  @param tree         The class definition whose members are checked.
2224     */
2225    void checkImplementations(JCClassDecl tree) {
2226        checkImplementations(tree, tree.sym, tree.sym);
2227    }
2228    //where
2229        /** Check that all methods which implement some
2230         *  method in `ic' conform to the method they implement.
2231         */
2232        void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2233            for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2234                ClassSymbol lc = (ClassSymbol)l.head.tsym;
2235                if ((lc.flags() & ABSTRACT) != 0) {
2236                    for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2237                        if (sym.kind == MTH &&
2238                            (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2239                            MethodSymbol absmeth = (MethodSymbol)sym;
2240                            MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2241                            if (implmeth != null && implmeth != absmeth &&
2242                                (implmeth.owner.flags() & INTERFACE) ==
2243                                (origin.flags() & INTERFACE)) {
2244                                // don't check if implmeth is in a class, yet
2245                                // origin is an interface. This case arises only
2246                                // if implmeth is declared in Object. The reason is
2247                                // that interfaces really don't inherit from
2248                                // Object it's just that the compiler represents
2249                                // things that way.
2250                                checkOverride(tree, implmeth, absmeth, origin);
2251                            }
2252                        }
2253                    }
2254                }
2255            }
2256        }
2257
2258    /** Check that all abstract methods implemented by a class are
2259     *  mutually compatible.
2260     *  @param pos          Position to be used for error reporting.
2261     *  @param c            The class whose interfaces are checked.
2262     */
2263    void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2264        List<Type> supertypes = types.interfaces(c);
2265        Type supertype = types.supertype(c);
2266        if (supertype.hasTag(CLASS) &&
2267            (supertype.tsym.flags() & ABSTRACT) != 0)
2268            supertypes = supertypes.prepend(supertype);
2269        for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2270            if (!l.head.getTypeArguments().isEmpty() &&
2271                !checkCompatibleAbstracts(pos, l.head, l.head, c))
2272                return;
2273            for (List<Type> m = supertypes; m != l; m = m.tail)
2274                if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2275                    return;
2276        }
2277        checkCompatibleConcretes(pos, c);
2278    }
2279
2280    void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2281        for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2282            for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) {
2283                // VM allows methods and variables with differing types
2284                if (sym.kind == sym2.kind &&
2285                    types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) &&
2286                    sym != sym2 &&
2287                    (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) &&
2288                    (sym.flags() & IPROXY) == 0 && (sym2.flags() & IPROXY) == 0 &&
2289                    (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) {
2290                    syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym);
2291                    return;
2292                }
2293            }
2294        }
2295    }
2296
2297    /** Check that all non-override equivalent methods accessible from 'site'
2298     *  are mutually compatible (JLS 8.4.8/9.4.1).
2299     *
2300     *  @param pos  Position to be used for error reporting.
2301     *  @param site The class whose methods are checked.
2302     *  @param sym  The method symbol to be checked.
2303     */
2304    void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2305         ClashFilter cf = new ClashFilter(site);
2306        //for each method m1 that is overridden (directly or indirectly)
2307        //by method 'sym' in 'site'...
2308
2309        List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2310        boolean overridesAny = false;
2311        for (Symbol m1 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2312            if (!sym.overrides(m1, site.tsym, types, false)) {
2313                if (m1 == sym) {
2314                    continue;
2315                }
2316
2317                if (!overridesAny) {
2318                    potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1);
2319                }
2320                continue;
2321            }
2322
2323            if (m1 != sym) {
2324                overridesAny = true;
2325                potentiallyAmbiguousList = List.nil();
2326            }
2327
2328            //...check each method m2 that is a member of 'site'
2329            for (Symbol m2 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2330                if (m2 == m1) continue;
2331                //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2332                //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2333                if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2334                        types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2335                    sym.flags_field |= CLASH;
2336                    String key = m1 == sym ?
2337                            "name.clash.same.erasure.no.override" :
2338                            "name.clash.same.erasure.no.override.1";
2339                    log.error(pos,
2340                            key,
2341                            sym, sym.location(),
2342                            m2, m2.location(),
2343                            m1, m1.location());
2344                    return;
2345                }
2346            }
2347        }
2348
2349        if (!overridesAny) {
2350            for (MethodSymbol m: potentiallyAmbiguousList) {
2351                checkPotentiallyAmbiguousOverloads(pos, site, sym, m);
2352            }
2353        }
2354    }
2355
2356    /** Check that all static methods accessible from 'site' are
2357     *  mutually compatible (JLS 8.4.8).
2358     *
2359     *  @param pos  Position to be used for error reporting.
2360     *  @param site The class whose methods are checked.
2361     *  @param sym  The method symbol to be checked.
2362     */
2363    void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2364        ClashFilter cf = new ClashFilter(site);
2365        //for each method m1 that is a member of 'site'...
2366        for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2367            //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2368            //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2369            if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck)) {
2370                if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2371                    log.error(pos,
2372                            "name.clash.same.erasure.no.hide",
2373                            sym, sym.location(),
2374                            s, s.location());
2375                    return;
2376                } else {
2377                    checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
2378                }
2379            }
2380         }
2381     }
2382
2383     //where
2384     private class ClashFilter implements Filter<Symbol> {
2385
2386         Type site;
2387
2388         ClashFilter(Type site) {
2389             this.site = site;
2390         }
2391
2392         boolean shouldSkip(Symbol s) {
2393             return (s.flags() & CLASH) != 0 &&
2394                s.owner == site.tsym;
2395         }
2396
2397         public boolean accepts(Symbol s) {
2398             return s.kind == MTH &&
2399                     (s.flags() & SYNTHETIC) == 0 &&
2400                     !shouldSkip(s) &&
2401                     s.isInheritedIn(site.tsym, types) &&
2402                     !s.isConstructor();
2403         }
2404     }
2405
2406    void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2407        DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2408        for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2409            Assert.check(m.kind == MTH);
2410            List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2411            if (prov.size() > 1) {
2412                ListBuffer<Symbol> abstracts = new ListBuffer<>();
2413                ListBuffer<Symbol> defaults = new ListBuffer<>();
2414                for (MethodSymbol provSym : prov) {
2415                    if ((provSym.flags() & DEFAULT) != 0) {
2416                        defaults = defaults.append(provSym);
2417                    } else if ((provSym.flags() & ABSTRACT) != 0) {
2418                        abstracts = abstracts.append(provSym);
2419                    }
2420                    if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2421                        //strong semantics - issue an error if two sibling interfaces
2422                        //have two override-equivalent defaults - or if one is abstract
2423                        //and the other is default
2424                        String errKey;
2425                        Symbol s1 = defaults.first();
2426                        Symbol s2;
2427                        if (defaults.size() > 1) {
2428                            errKey = "types.incompatible.unrelated.defaults";
2429                            s2 = defaults.toList().tail.head;
2430                        } else {
2431                            errKey = "types.incompatible.abstract.default";
2432                            s2 = abstracts.first();
2433                        }
2434                        log.error(pos, errKey,
2435                                Kinds.kindName(site.tsym), site,
2436                                m.name, types.memberType(site, m).getParameterTypes(),
2437                                s1.location(), s2.location());
2438                        break;
2439                    }
2440                }
2441            }
2442        }
2443    }
2444
2445    //where
2446     private class DefaultMethodClashFilter implements Filter<Symbol> {
2447
2448         Type site;
2449
2450         DefaultMethodClashFilter(Type site) {
2451             this.site = site;
2452         }
2453
2454         public boolean accepts(Symbol s) {
2455             return s.kind == MTH &&
2456                     (s.flags() & DEFAULT) != 0 &&
2457                     s.isInheritedIn(site.tsym, types) &&
2458                     !s.isConstructor();
2459         }
2460     }
2461
2462    /**
2463      * Report warnings for potentially ambiguous method declarations. Two declarations
2464      * are potentially ambiguous if they feature two unrelated functional interface
2465      * in same argument position (in which case, a call site passing an implicit
2466      * lambda would be ambiguous).
2467      */
2468    void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2469            MethodSymbol msym1, MethodSymbol msym2) {
2470        if (msym1 != msym2 &&
2471                allowDefaultMethods &&
2472                lint.isEnabled(LintCategory.OVERLOADS) &&
2473                (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2474                (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2475            Type mt1 = types.memberType(site, msym1);
2476            Type mt2 = types.memberType(site, msym2);
2477            //if both generic methods, adjust type variables
2478            if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2479                    types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2480                mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2481            }
2482            //expand varargs methods if needed
2483            int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2484            List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2485            List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2486            //if arities don't match, exit
2487            if (args1.length() != args2.length()) return;
2488            boolean potentiallyAmbiguous = false;
2489            while (args1.nonEmpty() && args2.nonEmpty()) {
2490                Type s = args1.head;
2491                Type t = args2.head;
2492                if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2493                    if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2494                            types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2495                            types.findDescriptorType(s).getParameterTypes().length() ==
2496                            types.findDescriptorType(t).getParameterTypes().length()) {
2497                        potentiallyAmbiguous = true;
2498                    } else {
2499                        break;
2500                    }
2501                }
2502                args1 = args1.tail;
2503                args2 = args2.tail;
2504            }
2505            if (potentiallyAmbiguous) {
2506                //we found two incompatible functional interfaces with same arity
2507                //this means a call site passing an implicit lambda would be ambigiuous
2508                msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
2509                msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
2510                log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload",
2511                            msym1, msym1.location(),
2512                            msym2, msym2.location());
2513                return;
2514            }
2515        }
2516    }
2517
2518    void checkElemAccessFromSerializableLambda(final JCTree tree) {
2519        if (warnOnAccessToSensitiveMembers) {
2520            Symbol sym = TreeInfo.symbol(tree);
2521            if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2522                return;
2523            }
2524
2525            if (sym.kind == VAR) {
2526                if ((sym.flags() & PARAMETER) != 0 ||
2527                    sym.isLocal() ||
2528                    sym.name == names._this ||
2529                    sym.name == names._super) {
2530                    return;
2531                }
2532            }
2533
2534            if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
2535                    isEffectivelyNonPublic(sym)) {
2536                log.warning(tree.pos(),
2537                        "access.to.sensitive.member.from.serializable.element", sym);
2538            }
2539        }
2540    }
2541
2542    private boolean isEffectivelyNonPublic(Symbol sym) {
2543        if (sym.packge() == syms.rootPackage) {
2544            return false;
2545        }
2546
2547        while (sym.kind != PCK) {
2548            if ((sym.flags() & PUBLIC) == 0) {
2549                return true;
2550            }
2551            sym = sym.owner;
2552        }
2553        return false;
2554    }
2555
2556    /** Report a conflict between a user symbol and a synthetic symbol.
2557     */
2558    private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2559        if (!sym.type.isErroneous()) {
2560            if (warnOnSyntheticConflicts) {
2561                log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2562            }
2563            else {
2564                log.error(pos, "synthetic.name.conflict", sym, sym.location());
2565            }
2566        }
2567    }
2568
2569    /** Check that class c does not implement directly or indirectly
2570     *  the same parameterized interface with two different argument lists.
2571     *  @param pos          Position to be used for error reporting.
2572     *  @param type         The type whose interfaces are checked.
2573     */
2574    void checkClassBounds(DiagnosticPosition pos, Type type) {
2575        checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2576    }
2577//where
2578        /** Enter all interfaces of type `type' into the hash table `seensofar'
2579         *  with their class symbol as key and their type as value. Make
2580         *  sure no class is entered with two different types.
2581         */
2582        void checkClassBounds(DiagnosticPosition pos,
2583                              Map<TypeSymbol,Type> seensofar,
2584                              Type type) {
2585            if (type.isErroneous()) return;
2586            for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2587                Type it = l.head;
2588                Type oldit = seensofar.put(it.tsym, it);
2589                if (oldit != null) {
2590                    List<Type> oldparams = oldit.allparams();
2591                    List<Type> newparams = it.allparams();
2592                    if (!types.containsTypeEquivalent(oldparams, newparams))
2593                        log.error(pos, "cant.inherit.diff.arg",
2594                                  it.tsym, Type.toString(oldparams),
2595                                  Type.toString(newparams));
2596                }
2597                checkClassBounds(pos, seensofar, it);
2598            }
2599            Type st = types.supertype(type);
2600            if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2601        }
2602
2603    /** Enter interface into into set.
2604     *  If it existed already, issue a "repeated interface" error.
2605     */
2606    void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2607        if (its.contains(it))
2608            log.error(pos, "repeated.interface");
2609        else {
2610            its.add(it);
2611        }
2612    }
2613
2614/* *************************************************************************
2615 * Check annotations
2616 **************************************************************************/
2617
2618    /**
2619     * Recursively validate annotations values
2620     */
2621    void validateAnnotationTree(JCTree tree) {
2622        class AnnotationValidator extends TreeScanner {
2623            @Override
2624            public void visitAnnotation(JCAnnotation tree) {
2625                if (!tree.type.isErroneous()) {
2626                    super.visitAnnotation(tree);
2627                    validateAnnotation(tree);
2628                }
2629            }
2630        }
2631        tree.accept(new AnnotationValidator());
2632    }
2633
2634    /**
2635     *  {@literal
2636     *  Annotation types are restricted to primitives, String, an
2637     *  enum, an annotation, Class, Class<?>, Class<? extends
2638     *  Anything>, arrays of the preceding.
2639     *  }
2640     */
2641    void validateAnnotationType(JCTree restype) {
2642        // restype may be null if an error occurred, so don't bother validating it
2643        if (restype != null) {
2644            validateAnnotationType(restype.pos(), restype.type);
2645        }
2646    }
2647
2648    void validateAnnotationType(DiagnosticPosition pos, Type type) {
2649        if (type.isPrimitive()) return;
2650        if (types.isSameType(type, syms.stringType)) return;
2651        if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2652        if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2653        if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
2654        if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2655            validateAnnotationType(pos, types.elemtype(type));
2656            return;
2657        }
2658        log.error(pos, "invalid.annotation.member.type");
2659    }
2660
2661    /**
2662     * "It is also a compile-time error if any method declared in an
2663     * annotation type has a signature that is override-equivalent to
2664     * that of any public or protected method declared in class Object
2665     * or in the interface annotation.Annotation."
2666     *
2667     * @jls 9.6 Annotation Types
2668     */
2669    void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2670        for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2671            Scope s = sup.tsym.members();
2672            for (Symbol sym : s.getSymbolsByName(m.name)) {
2673                if (sym.kind == MTH &&
2674                    (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2675                    types.overrideEquivalent(m.type, sym.type))
2676                    log.error(pos, "intf.annotation.member.clash", sym, sup);
2677            }
2678        }
2679    }
2680
2681    /** Check the annotations of a symbol.
2682     */
2683    public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2684        for (JCAnnotation a : annotations)
2685            validateAnnotation(a, s);
2686    }
2687
2688    /** Check the type annotations.
2689     */
2690    public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2691        for (JCAnnotation a : annotations)
2692            validateTypeAnnotation(a, isTypeParameter);
2693    }
2694
2695    /** Check an annotation of a symbol.
2696     */
2697    private void validateAnnotation(JCAnnotation a, Symbol s) {
2698        validateAnnotationTree(a);
2699
2700        if (!annotationApplicable(a, s))
2701            log.error(a.pos(), "annotation.type.not.applicable");
2702
2703        if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2704            if (s.kind != TYP) {
2705                log.error(a.pos(), "bad.functional.intf.anno");
2706            } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
2707                log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s));
2708            }
2709        }
2710    }
2711
2712    public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2713        Assert.checkNonNull(a.type);
2714        validateAnnotationTree(a);
2715
2716        if (a.hasTag(TYPE_ANNOTATION) &&
2717                !a.annotationType.type.isErroneous() &&
2718                !isTypeAnnotation(a, isTypeParameter)) {
2719            log.error(a.pos(), "annotation.type.not.applicable");
2720        }
2721    }
2722
2723    /**
2724     * Validate the proposed container 'repeatable' on the
2725     * annotation type symbol 's'. Report errors at position
2726     * 'pos'.
2727     *
2728     * @param s The (annotation)type declaration annotated with a @Repeatable
2729     * @param repeatable the @Repeatable on 's'
2730     * @param pos where to report errors
2731     */
2732    public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2733        Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2734
2735        Type t = null;
2736        List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2737        if (!l.isEmpty()) {
2738            Assert.check(l.head.fst.name == names.value);
2739            t = ((Attribute.Class)l.head.snd).getValue();
2740        }
2741
2742        if (t == null) {
2743            // errors should already have been reported during Annotate
2744            return;
2745        }
2746
2747        validateValue(t.tsym, s, pos);
2748        validateRetention(t.tsym, s, pos);
2749        validateDocumented(t.tsym, s, pos);
2750        validateInherited(t.tsym, s, pos);
2751        validateTarget(t.tsym, s, pos);
2752        validateDefault(t.tsym, pos);
2753    }
2754
2755    private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2756        Symbol sym = container.members().findFirst(names.value);
2757        if (sym != null && sym.kind == MTH) {
2758            MethodSymbol m = (MethodSymbol) sym;
2759            Type ret = m.getReturnType();
2760            if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2761                log.error(pos, "invalid.repeatable.annotation.value.return",
2762                        container, ret, types.makeArrayType(contained.type));
2763            }
2764        } else {
2765            log.error(pos, "invalid.repeatable.annotation.no.value", container);
2766        }
2767    }
2768
2769    private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2770        Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2771        Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2772
2773        boolean error = false;
2774        switch (containedRetention) {
2775        case RUNTIME:
2776            if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2777                error = true;
2778            }
2779            break;
2780        case CLASS:
2781            if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
2782                error = true;
2783            }
2784        }
2785        if (error ) {
2786            log.error(pos, "invalid.repeatable.annotation.retention",
2787                      container, containerRetention,
2788                      contained, containedRetention);
2789        }
2790    }
2791
2792    private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2793        if (contained.attribute(syms.documentedType.tsym) != null) {
2794            if (container.attribute(syms.documentedType.tsym) == null) {
2795                log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2796            }
2797        }
2798    }
2799
2800    private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2801        if (contained.attribute(syms.inheritedType.tsym) != null) {
2802            if (container.attribute(syms.inheritedType.tsym) == null) {
2803                log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2804            }
2805        }
2806    }
2807
2808    private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2809        // The set of targets the container is applicable to must be a subset
2810        // (with respect to annotation target semantics) of the set of targets
2811        // the contained is applicable to. The target sets may be implicit or
2812        // explicit.
2813
2814        Set<Name> containerTargets;
2815        Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2816        if (containerTarget == null) {
2817            containerTargets = getDefaultTargetSet();
2818        } else {
2819            containerTargets = new HashSet<>();
2820            for (Attribute app : containerTarget.values) {
2821                if (!(app instanceof Attribute.Enum)) {
2822                    continue; // recovery
2823                }
2824                Attribute.Enum e = (Attribute.Enum)app;
2825                containerTargets.add(e.value.name);
2826            }
2827        }
2828
2829        Set<Name> containedTargets;
2830        Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2831        if (containedTarget == null) {
2832            containedTargets = getDefaultTargetSet();
2833        } else {
2834            containedTargets = new HashSet<>();
2835            for (Attribute app : containedTarget.values) {
2836                if (!(app instanceof Attribute.Enum)) {
2837                    continue; // recovery
2838                }
2839                Attribute.Enum e = (Attribute.Enum)app;
2840                containedTargets.add(e.value.name);
2841            }
2842        }
2843
2844        if (!isTargetSubsetOf(containerTargets, containedTargets)) {
2845            log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2846        }
2847    }
2848
2849    /* get a set of names for the default target */
2850    private Set<Name> getDefaultTargetSet() {
2851        if (defaultTargets == null) {
2852            Set<Name> targets = new HashSet<>();
2853            targets.add(names.ANNOTATION_TYPE);
2854            targets.add(names.CONSTRUCTOR);
2855            targets.add(names.FIELD);
2856            targets.add(names.LOCAL_VARIABLE);
2857            targets.add(names.METHOD);
2858            targets.add(names.PACKAGE);
2859            targets.add(names.PARAMETER);
2860            targets.add(names.TYPE);
2861
2862            defaultTargets = java.util.Collections.unmodifiableSet(targets);
2863        }
2864
2865        return defaultTargets;
2866    }
2867    private Set<Name> defaultTargets;
2868
2869
2870    /** Checks that s is a subset of t, with respect to ElementType
2871     * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
2872     * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
2873     * TYPE_PARAMETER}.
2874     */
2875    private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
2876        // Check that all elements in s are present in t
2877        for (Name n2 : s) {
2878            boolean currentElementOk = false;
2879            for (Name n1 : t) {
2880                if (n1 == n2) {
2881                    currentElementOk = true;
2882                    break;
2883                } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2884                    currentElementOk = true;
2885                    break;
2886                } else if (n1 == names.TYPE_USE &&
2887                        (n2 == names.TYPE ||
2888                         n2 == names.ANNOTATION_TYPE ||
2889                         n2 == names.TYPE_PARAMETER)) {
2890                    currentElementOk = true;
2891                    break;
2892                }
2893            }
2894            if (!currentElementOk)
2895                return false;
2896        }
2897        return true;
2898    }
2899
2900    private void validateDefault(Symbol container, DiagnosticPosition pos) {
2901        // validate that all other elements of containing type has defaults
2902        Scope scope = container.members();
2903        for(Symbol elm : scope.getSymbols()) {
2904            if (elm.name != names.value &&
2905                elm.kind == MTH &&
2906                ((MethodSymbol)elm).defaultValue == null) {
2907                log.error(pos,
2908                          "invalid.repeatable.annotation.elem.nondefault",
2909                          container,
2910                          elm);
2911            }
2912        }
2913    }
2914
2915    /** Is s a method symbol that overrides a method in a superclass? */
2916    boolean isOverrider(Symbol s) {
2917        if (s.kind != MTH || s.isStatic())
2918            return false;
2919        MethodSymbol m = (MethodSymbol)s;
2920        TypeSymbol owner = (TypeSymbol)m.owner;
2921        for (Type sup : types.closure(owner.type)) {
2922            if (sup == owner.type)
2923                continue; // skip "this"
2924            Scope scope = sup.tsym.members();
2925            for (Symbol sym : scope.getSymbolsByName(m.name)) {
2926                if (!sym.isStatic() && m.overrides(sym, owner, types, true))
2927                    return true;
2928            }
2929        }
2930        return false;
2931    }
2932
2933    /** Is the annotation applicable to types? */
2934    protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2935        Attribute.Compound atTarget =
2936            a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2937        if (atTarget == null) {
2938            // An annotation without @Target is not a type annotation.
2939            return false;
2940        }
2941
2942        Attribute atValue = atTarget.member(names.value);
2943        if (!(atValue instanceof Attribute.Array)) {
2944            return false; // error recovery
2945        }
2946
2947        Attribute.Array arr = (Attribute.Array) atValue;
2948        for (Attribute app : arr.values) {
2949            if (!(app instanceof Attribute.Enum)) {
2950                return false; // recovery
2951            }
2952            Attribute.Enum e = (Attribute.Enum) app;
2953
2954            if (e.value.name == names.TYPE_USE)
2955                return true;
2956            else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2957                return true;
2958        }
2959        return false;
2960    }
2961
2962    /** Is the annotation applicable to the symbol? */
2963    boolean annotationApplicable(JCAnnotation a, Symbol s) {
2964        Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2965        Name[] targets;
2966
2967        if (arr == null) {
2968            targets = defaultTargetMetaInfo(a, s);
2969        } else {
2970            // TODO: can we optimize this?
2971            targets = new Name[arr.values.length];
2972            for (int i=0; i<arr.values.length; ++i) {
2973                Attribute app = arr.values[i];
2974                if (!(app instanceof Attribute.Enum)) {
2975                    return true; // recovery
2976                }
2977                Attribute.Enum e = (Attribute.Enum) app;
2978                targets[i] = e.value.name;
2979            }
2980        }
2981        for (Name target : targets) {
2982            if (target == names.TYPE)
2983                { if (s.kind == TYP) return true; }
2984            else if (target == names.FIELD)
2985                { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2986            else if (target == names.METHOD)
2987                { if (s.kind == MTH && !s.isConstructor()) return true; }
2988            else if (target == names.PARAMETER)
2989                { if (s.kind == VAR && s.owner.kind == MTH &&
2990                      (s.flags() & PARAMETER) != 0)
2991                    return true;
2992                }
2993            else if (target == names.CONSTRUCTOR)
2994                { if (s.kind == MTH && s.isConstructor()) return true; }
2995            else if (target == names.LOCAL_VARIABLE)
2996                { if (s.kind == VAR && s.owner.kind == MTH &&
2997                      (s.flags() & PARAMETER) == 0)
2998                    return true;
2999                }
3000            else if (target == names.ANNOTATION_TYPE)
3001                { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
3002                    return true;
3003                }
3004            else if (target == names.PACKAGE)
3005                { if (s.kind == PCK) return true; }
3006            else if (target == names.TYPE_USE)
3007                { if (s.kind == TYP || s.kind == VAR ||
3008                      (s.kind == MTH && !s.isConstructor() &&
3009                      !s.type.getReturnType().hasTag(VOID)) ||
3010                      (s.kind == MTH && s.isConstructor()))
3011                    return true;
3012                }
3013            else if (target == names.TYPE_PARAMETER)
3014                { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3015                    return true;
3016                }
3017            else
3018                return true; // recovery
3019        }
3020        return false;
3021    }
3022
3023
3024    Attribute.Array getAttributeTargetAttribute(Symbol s) {
3025        Attribute.Compound atTarget =
3026            s.attribute(syms.annotationTargetType.tsym);
3027        if (atTarget == null) return null; // ok, is applicable
3028        Attribute atValue = atTarget.member(names.value);
3029        if (!(atValue instanceof Attribute.Array)) return null; // error recovery
3030        return (Attribute.Array) atValue;
3031    }
3032
3033    private final Name[] dfltTargetMeta;
3034    private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
3035        return dfltTargetMeta;
3036    }
3037
3038    /** Check an annotation value.
3039     *
3040     * @param a The annotation tree to check
3041     * @return true if this annotation tree is valid, otherwise false
3042     */
3043    public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3044        boolean res = false;
3045        final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3046        try {
3047            res = validateAnnotation(a);
3048        } finally {
3049            log.popDiagnosticHandler(diagHandler);
3050        }
3051        return res;
3052    }
3053
3054    private boolean validateAnnotation(JCAnnotation a) {
3055        boolean isValid = true;
3056        // collect an inventory of the annotation elements
3057        Set<MethodSymbol> members = new LinkedHashSet<>();
3058        for (Symbol sym : a.annotationType.type.tsym.members().getSymbols(NON_RECURSIVE))
3059            if (sym.kind == MTH && sym.name != names.clinit &&
3060                    (sym.flags() & SYNTHETIC) == 0)
3061                members.add((MethodSymbol) sym);
3062
3063        // remove the ones that are assigned values
3064        for (JCTree arg : a.args) {
3065            if (!arg.hasTag(ASSIGN)) continue; // recovery
3066            JCAssign assign = (JCAssign) arg;
3067            Symbol m = TreeInfo.symbol(assign.lhs);
3068            if (m == null || m.type.isErroneous()) continue;
3069            if (!members.remove(m)) {
3070                isValid = false;
3071                log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3072                          m.name, a.type);
3073            }
3074        }
3075
3076        // all the remaining ones better have default values
3077        List<Name> missingDefaults = List.nil();
3078        for (MethodSymbol m : members) {
3079            if (m.defaultValue == null && !m.type.isErroneous()) {
3080                missingDefaults = missingDefaults.append(m.name);
3081            }
3082        }
3083        missingDefaults = missingDefaults.reverse();
3084        if (missingDefaults.nonEmpty()) {
3085            isValid = false;
3086            String key = (missingDefaults.size() > 1)
3087                    ? "annotation.missing.default.value.1"
3088                    : "annotation.missing.default.value";
3089            log.error(a.pos(), key, a.type, missingDefaults);
3090        }
3091
3092        // special case: java.lang.annotation.Target must not have
3093        // repeated values in its value member
3094        if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3095            a.args.tail == null)
3096            return isValid;
3097
3098        if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3099        JCAssign assign = (JCAssign) a.args.head;
3100        Symbol m = TreeInfo.symbol(assign.lhs);
3101        if (m.name != names.value) return false;
3102        JCTree rhs = assign.rhs;
3103        if (!rhs.hasTag(NEWARRAY)) return false;
3104        JCNewArray na = (JCNewArray) rhs;
3105        Set<Symbol> targets = new HashSet<>();
3106        for (JCTree elem : na.elems) {
3107            if (!targets.add(TreeInfo.symbol(elem))) {
3108                isValid = false;
3109                log.error(elem.pos(), "repeated.annotation.target");
3110            }
3111        }
3112        return isValid;
3113    }
3114
3115    void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3116        if (lint.isEnabled(LintCategory.DEP_ANN) &&
3117            (s.flags() & DEPRECATED) != 0 &&
3118            !syms.deprecatedType.isErroneous() &&
3119            s.attribute(syms.deprecatedType.tsym) == null) {
3120            log.warning(LintCategory.DEP_ANN,
3121                    pos, "missing.deprecated.annotation");
3122        }
3123    }
3124
3125    void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3126        if ((s.flags() & DEPRECATED) != 0 &&
3127                (other.flags() & DEPRECATED) == 0 &&
3128                s.outermostClass() != other.outermostClass()) {
3129            deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3130                @Override
3131                public void report() {
3132                    warnDeprecated(pos, s);
3133                }
3134            });
3135        }
3136    }
3137
3138    void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3139        if ((s.flags() & PROPRIETARY) != 0) {
3140            deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3141                public void report() {
3142                    if (enableSunApiLintControl)
3143                      warnSunApi(pos, "sun.proprietary", s);
3144                    else
3145                      log.mandatoryWarning(pos, "sun.proprietary", s);
3146                }
3147            });
3148        }
3149    }
3150
3151    void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3152        if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3153            log.error(pos, "not.in.profile", s, profile);
3154        }
3155    }
3156
3157/* *************************************************************************
3158 * Check for recursive annotation elements.
3159 **************************************************************************/
3160
3161    /** Check for cycles in the graph of annotation elements.
3162     */
3163    void checkNonCyclicElements(JCClassDecl tree) {
3164        if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3165        Assert.check((tree.sym.flags_field & LOCKED) == 0);
3166        try {
3167            tree.sym.flags_field |= LOCKED;
3168            for (JCTree def : tree.defs) {
3169                if (!def.hasTag(METHODDEF)) continue;
3170                JCMethodDecl meth = (JCMethodDecl)def;
3171                checkAnnotationResType(meth.pos(), meth.restype.type);
3172            }
3173        } finally {
3174            tree.sym.flags_field &= ~LOCKED;
3175            tree.sym.flags_field |= ACYCLIC_ANN;
3176        }
3177    }
3178
3179    void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3180        if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3181            return;
3182        if ((tsym.flags_field & LOCKED) != 0) {
3183            log.error(pos, "cyclic.annotation.element");
3184            return;
3185        }
3186        try {
3187            tsym.flags_field |= LOCKED;
3188            for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3189                if (s.kind != MTH)
3190                    continue;
3191                checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3192            }
3193        } finally {
3194            tsym.flags_field &= ~LOCKED;
3195            tsym.flags_field |= ACYCLIC_ANN;
3196        }
3197    }
3198
3199    void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3200        switch (type.getTag()) {
3201        case CLASS:
3202            if ((type.tsym.flags() & ANNOTATION) != 0)
3203                checkNonCyclicElementsInternal(pos, type.tsym);
3204            break;
3205        case ARRAY:
3206            checkAnnotationResType(pos, types.elemtype(type));
3207            break;
3208        default:
3209            break; // int etc
3210        }
3211    }
3212
3213/* *************************************************************************
3214 * Check for cycles in the constructor call graph.
3215 **************************************************************************/
3216
3217    /** Check for cycles in the graph of constructors calling other
3218     *  constructors.
3219     */
3220    void checkCyclicConstructors(JCClassDecl tree) {
3221        Map<Symbol,Symbol> callMap = new HashMap<>();
3222
3223        // enter each constructor this-call into the map
3224        for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3225            JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3226            if (app == null) continue;
3227            JCMethodDecl meth = (JCMethodDecl) l.head;
3228            if (TreeInfo.name(app.meth) == names._this) {
3229                callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3230            } else {
3231                meth.sym.flags_field |= ACYCLIC;
3232            }
3233        }
3234
3235        // Check for cycles in the map
3236        Symbol[] ctors = new Symbol[0];
3237        ctors = callMap.keySet().toArray(ctors);
3238        for (Symbol caller : ctors) {
3239            checkCyclicConstructor(tree, caller, callMap);
3240        }
3241    }
3242
3243    /** Look in the map to see if the given constructor is part of a
3244     *  call cycle.
3245     */
3246    private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3247                                        Map<Symbol,Symbol> callMap) {
3248        if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3249            if ((ctor.flags_field & LOCKED) != 0) {
3250                log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3251                          "recursive.ctor.invocation");
3252            } else {
3253                ctor.flags_field |= LOCKED;
3254                checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3255                ctor.flags_field &= ~LOCKED;
3256            }
3257            ctor.flags_field |= ACYCLIC;
3258        }
3259    }
3260
3261/* *************************************************************************
3262 * Miscellaneous
3263 **************************************************************************/
3264
3265    /**
3266     *  Check for division by integer constant zero
3267     *  @param pos           Position for error reporting.
3268     *  @param operator      The operator for the expression
3269     *  @param operand       The right hand operand for the expression
3270     */
3271    void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3272        if (operand.constValue() != null
3273            && operand.getTag().isSubRangeOf(LONG)
3274            && ((Number) (operand.constValue())).longValue() == 0) {
3275            int opc = ((OperatorSymbol)operator).opcode;
3276            if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3277                || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3278                deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3279                    @Override
3280                    public void report() {
3281                        warnDivZero(pos);
3282                    }
3283                });
3284            }
3285        }
3286    }
3287
3288    /**
3289     * Check for empty statements after if
3290     */
3291    void checkEmptyIf(JCIf tree) {
3292        if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3293                lint.isEnabled(LintCategory.EMPTY))
3294            log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3295    }
3296
3297    /** Check that symbol is unique in given scope.
3298     *  @param pos           Position for error reporting.
3299     *  @param sym           The symbol.
3300     *  @param s             The scope.
3301     */
3302    boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3303        if (sym.type.isErroneous())
3304            return true;
3305        if (sym.owner.name == names.any) return false;
3306        for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
3307            if (sym != byName &&
3308                    (byName.flags() & CLASH) == 0 &&
3309                    sym.kind == byName.kind &&
3310                    sym.name != names.error &&
3311                    (sym.kind != MTH ||
3312                     types.hasSameArgs(sym.type, byName.type) ||
3313                     types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
3314                if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
3315                    varargsDuplicateError(pos, sym, byName);
3316                    return true;
3317                } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
3318                    duplicateErasureError(pos, sym, byName);
3319                    sym.flags_field |= CLASH;
3320                    return true;
3321                } else {
3322                    duplicateError(pos, byName);
3323                    return false;
3324                }
3325            }
3326        }
3327        return true;
3328    }
3329
3330    /** Report duplicate declaration error.
3331     */
3332    void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3333        if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3334            log.error(pos, "name.clash.same.erasure", sym1, sym2);
3335        }
3336    }
3337
3338    /**Check that types imported through the ordinary imports don't clash with types imported
3339     * by other (static or ordinary) imports. Note that two static imports may import two clashing
3340     * types without an error on the imports.
3341     * @param toplevel       The toplevel tree for which the test should be performed.
3342     */
3343    void checkImportsUnique(JCCompilationUnit toplevel) {
3344        WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
3345        WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
3346        WriteableScope topLevelScope = toplevel.toplevelScope;
3347
3348        for (JCTree def : toplevel.defs) {
3349            if (!def.hasTag(IMPORT))
3350                continue;
3351
3352            JCImport imp = (JCImport) def;
3353
3354            if (imp.importScope == null)
3355                continue;
3356
3357            for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
3358                if (imp.isStatic()) {
3359                    checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
3360                    staticallyImportedSoFar.enter(sym);
3361                } else {
3362                    checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
3363                    ordinallyImportedSoFar.enter(sym);
3364                }
3365            }
3366
3367            imp.importScope = null;
3368        }
3369    }
3370
3371    /** Check that single-type import is not already imported or top-level defined,
3372     *  but make an exception for two single-type imports which denote the same type.
3373     *  @param pos                     Position for error reporting.
3374     *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
3375     *                                 ordinary imports.
3376     *  @param staticallyImportedSoFar A Scope containing types imported so far through
3377     *                                 static imports.
3378     *  @param topLevelScope           The current file's top-level Scope
3379     *  @param sym                     The symbol.
3380     *  @param staticImport            Whether or not this was a static import
3381     */
3382    private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
3383                                      Scope staticallyImportedSoFar, Scope topLevelScope,
3384                                      Symbol sym, boolean staticImport) {
3385        Filter<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
3386        Symbol clashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
3387        if (clashing == null && !staticImport) {
3388            clashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
3389        }
3390        if (clashing != null) {
3391            if (staticImport)
3392                log.error(pos, "already.defined.static.single.import", clashing);
3393            else
3394                log.error(pos, "already.defined.single.import", clashing);
3395            return false;
3396        }
3397        clashing = topLevelScope.findFirst(sym.name, duplicates);
3398        if (clashing != null) {
3399            log.error(pos, "already.defined.this.unit", clashing);
3400            return false;
3401        }
3402        return true;
3403    }
3404
3405    /** Check that a qualified name is in canonical form (for import decls).
3406     */
3407    public void checkCanonical(JCTree tree) {
3408        if (!isCanonical(tree))
3409            log.error(tree.pos(), "import.requires.canonical",
3410                      TreeInfo.symbol(tree));
3411    }
3412        // where
3413        private boolean isCanonical(JCTree tree) {
3414            while (tree.hasTag(SELECT)) {
3415                JCFieldAccess s = (JCFieldAccess) tree;
3416                if (s.sym.owner != TreeInfo.symbol(s.selected))
3417                    return false;
3418                tree = s.selected;
3419            }
3420            return true;
3421        }
3422
3423    /** Check that an auxiliary class is not accessed from any other file than its own.
3424     */
3425    void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3426        if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3427            (c.flags() & AUXILIARY) != 0 &&
3428            rs.isAccessible(env, c) &&
3429            !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3430        {
3431            log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3432                        c, c.sourcefile);
3433        }
3434    }
3435
3436    private class ConversionWarner extends Warner {
3437        final String uncheckedKey;
3438        final Type found;
3439        final Type expected;
3440        public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3441            super(pos);
3442            this.uncheckedKey = uncheckedKey;
3443            this.found = found;
3444            this.expected = expected;
3445        }
3446
3447        @Override
3448        public void warn(LintCategory lint) {
3449            boolean warned = this.warned;
3450            super.warn(lint);
3451            if (warned) return; // suppress redundant diagnostics
3452            switch (lint) {
3453                case UNCHECKED:
3454                    Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3455                    break;
3456                case VARARGS:
3457                    if (method != null &&
3458                            method.attribute(syms.trustMeType.tsym) != null &&
3459                            isTrustMeAllowedOnMethod(method) &&
3460                            !types.isReifiable(method.type.getParameterTypes().last())) {
3461                        Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3462                    }
3463                    break;
3464                default:
3465                    throw new AssertionError("Unexpected lint: " + lint);
3466            }
3467        }
3468    }
3469
3470    public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3471        return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3472    }
3473
3474    public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3475        return new ConversionWarner(pos, "unchecked.assign", found, expected);
3476    }
3477
3478    public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
3479        Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
3480
3481        if (functionalType != null) {
3482            try {
3483                types.findDescriptorSymbol((TypeSymbol)cs);
3484            } catch (Types.FunctionDescriptorLookupError ex) {
3485                DiagnosticPosition pos = tree.pos();
3486                for (JCAnnotation a : tree.getModifiers().annotations) {
3487                    if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3488                        pos = a.pos();
3489                        break;
3490                    }
3491                }
3492                log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic());
3493            }
3494        }
3495    }
3496
3497    public void checkImportsResolvable(final JCCompilationUnit toplevel) {
3498        for (final JCImport imp : toplevel.getImports()) {
3499            if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
3500                continue;
3501            final JCFieldAccess select = (JCFieldAccess) imp.qualid;
3502            final Symbol origin;
3503            if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
3504                continue;
3505
3506            TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
3507            if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
3508                log.error(imp.pos(), "cant.resolve.location",
3509                          KindName.STATIC,
3510                          select.name, List.<Type>nil(), List.<Type>nil(),
3511                          Kinds.typeKindName(TreeInfo.symbol(select.selected).type),
3512                          TreeInfo.symbol(select.selected).type);
3513            }
3514        }
3515    }
3516
3517    private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
3518        if (tsym == null || !processed.add(tsym))
3519            return false;
3520
3521            // also search through inherited names
3522        if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
3523            return true;
3524
3525        for (Type t : types.interfaces(tsym.type))
3526            if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
3527                return true;
3528
3529        for (Symbol sym : tsym.members().getSymbolsByName(name)) {
3530            if (sym.isStatic() &&
3531                staticImportAccessible(sym, packge) &&
3532                sym.isMemberOf(origin, types)) {
3533                return true;
3534            }
3535        }
3536
3537        return false;
3538    }
3539
3540    // is the sym accessible everywhere in packge?
3541    public boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
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    }
3554
3555}
3556