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