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