1 /*
2 * Copyright (c) 1999, 2026, 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.BiConsumer;
30 import java.util.function.BiPredicate;
31 import java.util.function.Predicate;
32 import java.util.function.Supplier;
33 import java.util.function.ToIntBiFunction;
34 import java.util.stream.Collectors;
35 import java.util.stream.StreamSupport;
36
37 import javax.lang.model.element.ElementKind;
38 import javax.lang.model.element.NestingKind;
39 import javax.tools.JavaFileManager;
40
41 import com.sun.source.tree.CaseTree;
42 import com.sun.tools.javac.code.*;
43 import com.sun.tools.javac.code.Attribute.Compound;
44 import com.sun.tools.javac.code.Directive.ExportsDirective;
45 import com.sun.tools.javac.code.Directive.RequiresDirective;
46 import com.sun.tools.javac.code.Source.Feature;
47 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
48 import com.sun.tools.javac.jvm.*;
49 import com.sun.tools.javac.resources.CompilerProperties;
50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
51 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
52 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
53 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
54 import com.sun.tools.javac.tree.*;
55 import com.sun.tools.javac.util.*;
56 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
57 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
58 import com.sun.tools.javac.util.JCDiagnostic.Error;
59 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
60 import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
61 import com.sun.tools.javac.util.List;
62
63 import com.sun.tools.javac.code.Lint;
64 import com.sun.tools.javac.code.Lint.LintCategory;
65 import com.sun.tools.javac.code.Scope.WriteableScope;
66 import com.sun.tools.javac.code.Type.*;
67 import com.sun.tools.javac.code.Symbol.*;
68 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
69 import com.sun.tools.javac.tree.JCTree.*;
70
71 import static com.sun.tools.javac.code.Flags.*;
72 import static com.sun.tools.javac.code.Flags.ANNOTATION;
73 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
74 import static com.sun.tools.javac.code.Kinds.*;
75 import static com.sun.tools.javac.code.Kinds.Kind.*;
76 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
77 import static com.sun.tools.javac.code.Scope.LookupKind.RECURSIVE;
78 import static com.sun.tools.javac.code.TypeTag.*;
79 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
80
81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
82 import javax.lang.model.element.Element;
83 import javax.lang.model.element.TypeElement;
84 import javax.lang.model.type.DeclaredType;
85 import javax.lang.model.util.ElementKindVisitor14;
86
87 /** Type checking helper class for the attribution phase.
88 *
89 * <p><b>This is NOT part of any supported API.
90 * If you write code that depends on this, you do so at your own risk.
91 * This code and its internal interfaces are subject to change or
92 * deletion without notice.</b>
93 */
94 public class Check {
95 protected static final Context.Key<Check> checkKey = new Context.Key<>();
96
97 // Flag bits indicating which item(s) chosen from a pair of items
98 private static final int FIRST = 0x01;
99 private static final int SECOND = 0x02;
100
101 private final Names names;
102 private final Log log;
103 private final Resolve rs;
104 private final Symtab syms;
105 private final Enter enter;
106 private final DeferredAttr deferredAttr;
107 private final Infer infer;
108 private final Types types;
109 private final TypeAnnotations typeAnnotations;
110 private final JCDiagnostic.Factory diags;
111 private final JavaFileManager fileManager;
112 private final Source source;
113 private final Target target;
114 private final Profile profile;
115 private final Preview preview;
116 private final boolean warnOnAnyAccessToMembers;
117
118 public boolean disablePreviewCheck;
119
120 // The set of lint options currently in effect. It is initialized
121 // from the context, and then is set/reset as needed by Attr as it
122 // visits all the various parts of the trees during attribution.
123 private Lint lint;
124
125 // The method being analyzed in Attr - it is set/reset as needed by
126 // Attr as it visits new method declarations.
127 private MethodSymbol method;
128
129 public static Check instance(Context context) {
130 Check instance = context.get(checkKey);
131 if (instance == null)
132 instance = new Check(context);
133 return instance;
134 }
135
136 @SuppressWarnings("this-escape")
137 protected Check(Context context) {
138 context.put(checkKey, this);
139
140 names = Names.instance(context);
141 log = Log.instance(context);
142 rs = Resolve.instance(context);
143 syms = Symtab.instance(context);
144 enter = Enter.instance(context);
145 deferredAttr = DeferredAttr.instance(context);
146 infer = Infer.instance(context);
147 types = Types.instance(context);
148 typeAnnotations = TypeAnnotations.instance(context);
149 diags = JCDiagnostic.Factory.instance(context);
150 Options options = Options.instance(context);
151 lint = Lint.instance(context);
152 fileManager = context.get(JavaFileManager.class);
153
154 source = Source.instance(context);
155 target = Target.instance(context);
156 warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
157
158 disablePreviewCheck = false;
159
160 Target target = Target.instance(context);
161 syntheticNameChar = target.syntheticNameChar();
162
163 profile = Profile.instance(context);
164 preview = Preview.instance(context);
165
166 allowModules = Feature.MODULES.allowedInSource(source);
167 allowRecords = Feature.RECORDS.allowedInSource(source);
168 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
169 allowPrimitivePatterns = preview.isEnabled() && Feature.PRIMITIVE_PATTERNS.allowedInSource(source);
170 }
171
172 /** Character for synthetic names
173 */
174 char syntheticNameChar;
175
176 /** A table mapping flat names of all compiled classes for each module in this run
177 * to their symbols; maintained from outside.
178 */
179 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
180
181 /** Are modules allowed
182 */
183 private final boolean allowModules;
184
185 /** Are records allowed
186 */
187 private final boolean allowRecords;
188
189 /** Are sealed classes allowed
190 */
191 private final boolean allowSealed;
192
193 /** Are primitive patterns allowed
194 */
195 private final boolean allowPrimitivePatterns;
196
197 /** Whether to force suppression of deprecation and preview warnings.
198 * This happens when attributing import statements for JDK 9+.
199 * @see Feature#DEPRECATION_ON_IMPORT
200 */
201 private boolean importSuppression;
202
203 /* *************************************************************************
204 * Errors and Warnings
205 **************************************************************************/
206
207 Lint setLint(Lint newLint) {
208 Lint prev = lint;
209 lint = newLint;
210 return prev;
211 }
212
213 boolean setImportSuppression(boolean newImportSuppression) {
214 boolean prev = importSuppression;
215 importSuppression = newImportSuppression;
216 return prev;
217 }
218
219 MethodSymbol setMethod(MethodSymbol newMethod) {
220 MethodSymbol prev = method;
221 method = newMethod;
222 return prev;
223 }
224
225 /** Warn about deprecated symbol.
226 * @param pos Position to be used for error reporting.
227 * @param sym The deprecated symbol.
228 */
229 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
230 Assert.check(!importSuppression);
231 LintWarning warningKey = sym.isDeprecatedForRemoval() ?
232 (sym.kind == MDL ?
233 LintWarnings.HasBeenDeprecatedForRemovalModule(sym) :
234 LintWarnings.HasBeenDeprecatedForRemoval(sym, sym.location())) :
235 (sym.kind == MDL ?
236 LintWarnings.HasBeenDeprecatedModule(sym) :
237 LintWarnings.HasBeenDeprecated(sym, sym.location()));
238 log.warning(pos, warningKey);
239 }
240
241 /** Log a preview warning.
242 * @param pos Position to be used for error reporting.
243 * @param msg A Warning describing the problem.
244 */
245 public void warnPreviewAPI(DiagnosticPosition pos, LintWarning warnKey) {
246 if (!importSuppression)
247 log.warning(pos, warnKey);
248 }
249
250 /** Warn about unchecked operation.
251 * @param pos Position to be used for error reporting.
252 * @param msg A string describing the problem.
253 */
254 public void warnUnchecked(DiagnosticPosition pos, LintWarning warnKey) {
255 log.warning(pos, warnKey);
256 }
257
258 /** Report a failure to complete a class.
259 * @param pos Position to be used for error reporting.
260 * @param ex The failure to report.
261 */
262 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
263 log.error(DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
264 return syms.errType;
265 }
266
267 /** Report an error that wrong type tag was found.
268 * @param pos Position to be used for error reporting.
269 * @param required An internationalized string describing the type tag
270 * required.
271 * @param found The type that was found.
272 */
273 Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
274 // this error used to be raised by the parser,
275 // but has been delayed to this point:
276 if (found instanceof Type type && type.hasTag(VOID)) {
277 log.error(pos, Errors.IllegalStartOfType);
278 return syms.errType;
279 }
280 log.error(pos, Errors.TypeFoundReq(found, required));
281 return types.createErrorType(found instanceof Type type ? type : syms.errType);
282 }
283
284 /** Report duplicate declaration error.
285 */
286 void duplicateError(DiagnosticPosition pos, Symbol sym) {
287 if (!sym.type.isErroneous()) {
288 Symbol location = sym.location();
289 if (location.kind == MTH &&
290 ((MethodSymbol)location).isStaticOrInstanceInit()) {
291 log.error(pos,
292 Errors.AlreadyDefinedInClinit(kindName(sym),
293 sym,
294 kindName(sym.location()),
295 kindName(sym.location().enclClass()),
296 sym.location().enclClass()));
297 } else {
298 /* dont error if this is a duplicated parameter of a generated canonical constructor
299 * as we should have issued an error for the duplicated fields
300 */
301 if (location.kind != MTH ||
302 ((sym.owner.flags_field & GENERATEDCONSTR) == 0) ||
303 ((sym.owner.flags_field & RECORD) == 0)) {
304 log.error(pos,
305 Errors.AlreadyDefined(kindName(sym),
306 sym,
307 kindName(sym.location()),
308 sym.location()));
309 }
310 }
311 }
312 }
313
314 /** Report array/varargs duplicate declaration
315 */
316 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
317 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
318 log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location()));
319 }
320 }
321
322 /* ************************************************************************
323 * duplicate declaration checking
324 *************************************************************************/
325
326 /** Check that variable does not hide variable with same name in
327 * immediately enclosing local scope.
328 * @param pos Position for error reporting.
329 * @param v The symbol.
330 * @param s The scope.
331 */
332 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
333 for (Symbol sym : s.getSymbolsByName(v.name)) {
334 if (sym.owner != v.owner) break;
335 if (sym.kind == VAR &&
336 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
337 v.name != names.error) {
338 duplicateError(pos, sym);
339 return;
340 }
341 }
342 }
343
344 /** Check that a class or interface does not hide a class or
345 * interface with same name in immediately enclosing local scope.
346 * @param pos Position for error reporting.
347 * @param c The symbol.
348 * @param s The scope.
349 */
350 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
351 for (Symbol sym : s.getSymbolsByName(c.name)) {
352 if (sym.owner != c.owner) break;
353 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
354 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
355 c.name != names.error) {
356 duplicateError(pos, sym);
357 return;
358 }
359 }
360 }
361
362 /** Check that class does not have the same name as one of
363 * its enclosing classes, or as a class defined in its enclosing scope.
364 * return true if class is unique in its enclosing scope.
365 * @param pos Position for error reporting.
366 * @param name The class name.
367 * @param s The enclosing scope.
368 */
369 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
370 for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
371 if (sym.kind == TYP && sym.name != names.error) {
372 duplicateError(pos, sym);
373 return false;
374 }
375 }
376 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
377 if (sym.kind == TYP && sym.name == name && sym.name != names.error &&
378 !sym.isImplicit()) {
379 duplicateError(pos, sym);
380 return true;
381 }
382 }
383 return true;
384 }
385
386 /* *************************************************************************
387 * Class name generation
388 **************************************************************************/
389
390
391 private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
392
393 /** Return name of local class.
394 * This is of the form {@code <enclClass> $ n <classname> }
395 * where
396 * enclClass is the flat name of the enclosing class,
397 * classname is the simple name of the local class
398 */
399 public Name localClassName(ClassSymbol c) {
400 Name enclFlatname = c.owner.enclClass().flatname;
401 String enclFlatnameStr = enclFlatname.toString();
402 Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
403 Integer index = localClassNameIndexes.get(key);
404 for (int i = (index == null) ? 1 : index; ; i++) {
405 Name flatname = names.fromString(enclFlatnameStr
406 + syntheticNameChar + i + c.name);
407 if (getCompiled(c.packge().modle, flatname) == null) {
408 localClassNameIndexes.put(key, i + 1);
409 return flatname;
410 }
411 }
412 }
413
414 public void clearLocalClassNameIndexes(ClassSymbol c) {
415 if (c.owner != null && c.owner.kind != NIL) {
416 localClassNameIndexes.remove(new Pair<>(
417 c.owner.enclClass().flatname, c.name));
418 }
419 }
420
421 public void newRound() {
422 compiled.clear();
423 localClassNameIndexes.clear();
424 }
425
426 public void putCompiled(ClassSymbol csym) {
427 compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
428 }
429
430 public ClassSymbol getCompiled(ClassSymbol csym) {
431 return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
432 }
433
434 public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
435 return compiled.get(Pair.of(msym, flatname));
436 }
437
438 public void removeCompiled(ClassSymbol csym) {
439 compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
440 }
441
442 /* *************************************************************************
443 * Type Checking
444 **************************************************************************/
445
446 /**
447 * A check context is an object that can be used to perform compatibility
448 * checks - depending on the check context, meaning of 'compatibility' might
449 * vary significantly.
450 */
451 public interface CheckContext {
452 /**
453 * Is type 'found' compatible with type 'req' in given context
454 */
455 boolean compatible(Type found, Type req, Warner warn);
456 /**
457 * Report a check error
458 */
459 void report(DiagnosticPosition pos, JCDiagnostic details);
460 /**
461 * Obtain a warner for this check context
462 */
463 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
464
465 public InferenceContext inferenceContext();
466
467 public DeferredAttr.DeferredAttrContext deferredAttrContext();
468 }
469
470 /**
471 * This class represent a check context that is nested within another check
472 * context - useful to check sub-expressions. The default behavior simply
473 * redirects all method calls to the enclosing check context leveraging
474 * the forwarding pattern.
475 */
476 static class NestedCheckContext implements CheckContext {
477 CheckContext enclosingContext;
478
479 NestedCheckContext(CheckContext enclosingContext) {
480 this.enclosingContext = enclosingContext;
481 }
482
483 public boolean compatible(Type found, Type req, Warner warn) {
484 return enclosingContext.compatible(found, req, warn);
485 }
486
487 public void report(DiagnosticPosition pos, JCDiagnostic details) {
488 enclosingContext.report(pos, details);
489 }
490
491 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
492 return enclosingContext.checkWarner(pos, found, req);
493 }
494
495 public InferenceContext inferenceContext() {
496 return enclosingContext.inferenceContext();
497 }
498
499 public DeferredAttrContext deferredAttrContext() {
500 return enclosingContext.deferredAttrContext();
501 }
502 }
503
504 /**
505 * Check context to be used when evaluating assignment/return statements
506 */
507 CheckContext basicHandler = new CheckContext() {
508 public void report(DiagnosticPosition pos, JCDiagnostic details) {
509 log.error(pos, Errors.ProbFoundReq(details));
510 }
511 public boolean compatible(Type found, Type req, Warner warn) {
512 return types.isAssignable(found, req, warn);
513 }
514
515 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
516 return convertWarner(pos, found, req);
517 }
518
519 public InferenceContext inferenceContext() {
520 return infer.emptyContext;
521 }
522
523 public DeferredAttrContext deferredAttrContext() {
524 return deferredAttr.emptyDeferredAttrContext;
525 }
526
527 @Override
528 public String toString() {
529 return "CheckContext: basicHandler";
530 }
531 };
532
533 /** Check that a given type is assignable to a given proto-type.
534 * If it is, return the type, otherwise return errType.
535 * @param pos Position to be used for error reporting.
536 * @param found The type that was found.
537 * @param req The type that was required.
538 */
539 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
540 return checkType(pos, found, req, basicHandler);
541 }
542
543 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
544 final InferenceContext inferenceContext = checkContext.inferenceContext();
545 if (inferenceContext.free(req) || inferenceContext.free(found)) {
546 inferenceContext.addFreeTypeListener(List.of(req, found),
547 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
548 }
549 if (req.hasTag(ERROR))
550 return req;
551 if (req.hasTag(NONE))
552 return found;
553 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
554 return found;
555 } else {
556 if (found.isNumeric() && req.isNumeric()) {
557 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
558 return types.createErrorType(found);
559 }
560 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
561 return types.createErrorType(found);
562 }
563 }
564
565 /** Check that a given type can be cast to a given target type.
566 * Return the result of the cast.
567 * @param pos Position to be used for error reporting.
568 * @param found The type that is being cast.
569 * @param req The target type of the cast.
570 */
571 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
572 return checkCastable(pos, found, req, basicHandler);
573 }
574 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
575 if (types.isCastable(found, req, castWarner(pos, found, req))) {
576 return req;
577 } else {
578 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
579 return types.createErrorType(found);
580 }
581 }
582
583 /** Check for redundant casts (i.e. where source type is a subtype of target type)
584 * The problem should only be reported for non-292 cast
585 */
586 public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
587 if (!tree.type.isErroneous()
588 && types.isSameType(tree.expr.type, tree.clazz.type)
589 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
590 && !is292targetTypeCast(tree)) {
591 log.warning(tree.pos(), LintWarnings.RedundantCast(tree.clazz.type));
592 }
593 }
594 //where
595 private boolean is292targetTypeCast(JCTypeCast tree) {
596 boolean is292targetTypeCast = false;
597 JCExpression expr = TreeInfo.skipParens(tree.expr);
598 if (expr.hasTag(APPLY)) {
599 JCMethodInvocation apply = (JCMethodInvocation)expr;
600 Symbol sym = TreeInfo.symbol(apply.meth);
601 is292targetTypeCast = sym != null &&
602 sym.kind == MTH &&
603 (sym.flags() & HYPOTHETICAL) != 0;
604 }
605 return is292targetTypeCast;
606 }
607
608 private static final boolean ignoreAnnotatedCasts = true;
609
610 /** Check that a type is within some bounds.
611 *
612 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
613 * type argument.
614 * @param a The type that should be bounded by bs.
615 * @param bound The bound.
616 */
617 private boolean checkExtends(Type a, Type bound) {
618 if (a.isUnbound()) {
619 return true;
620 } else if (!a.hasTag(WILDCARD)) {
621 a = types.cvarUpperBound(a);
622 return types.isSubtype(a, bound);
623 } else if (a.isExtendsBound()) {
624 return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
625 } else if (a.isSuperBound()) {
626 return !types.notSoftSubtype(types.wildLowerBound(a), bound);
627 }
628 return true;
629 }
630
631 /** Check that type is different from 'void'.
632 * @param pos Position to be used for error reporting.
633 * @param t The type to be checked.
634 */
635 Type checkNonVoid(DiagnosticPosition pos, Type t) {
636 if (t.hasTag(VOID)) {
637 log.error(pos, Errors.VoidNotAllowedHere);
638 return types.createErrorType(t);
639 } else {
640 return t;
641 }
642 }
643
644 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
645 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
646 return typeTagError(pos,
647 diags.fragment(Fragments.TypeReqClassArray),
648 asTypeParam(t));
649 } else {
650 return t;
651 }
652 }
653
654 /** Check that type is a class or interface type.
655 * @param pos Position to be used for error reporting.
656 * @param t The type to be checked.
657 */
658 Type checkClassType(DiagnosticPosition pos, Type t) {
659 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
660 return typeTagError(pos,
661 diags.fragment(Fragments.TypeReqClass),
662 asTypeParam(t));
663 } else {
664 return t;
665 }
666 }
667 //where
668 private Object asTypeParam(Type t) {
669 return (t.hasTag(TYPEVAR))
670 ? diags.fragment(Fragments.TypeParameter(t))
671 : t;
672 }
673
674 /** Check that type is a valid qualifier for a constructor reference expression
675 */
676 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
677 t = checkClassOrArrayType(pos, t);
678 if (t.hasTag(CLASS)) {
679 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
680 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
681 t = types.createErrorType(t);
682 } else if ((t.tsym.flags() & ENUM) != 0) {
683 log.error(pos, Errors.EnumCantBeInstantiated);
684 t = types.createErrorType(t);
685 } else {
686 t = checkClassType(pos, t, true);
687 }
688 } else if (t.hasTag(ARRAY)) {
689 if (!types.isReifiable(((ArrayType)t).elemtype)) {
690 log.error(pos, Errors.GenericArrayCreation);
691 t = types.createErrorType(t);
692 }
693 }
694 return t;
695 }
696
697 /** Check that type is a class or interface type.
698 * @param pos Position to be used for error reporting.
699 * @param t The type to be checked.
700 * @param noBounds True if type bounds are illegal here.
701 */
702 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
703 t = checkClassType(pos, t);
704 if (noBounds && t.isParameterized()) {
705 List<Type> args = t.getTypeArguments();
706 while (args.nonEmpty()) {
707 if (args.head.hasTag(WILDCARD))
708 return typeTagError(pos,
709 diags.fragment(Fragments.TypeReqExact),
710 args.head);
711 args = args.tail;
712 }
713 }
714 return t;
715 }
716
717 /** Check that type is a reference type, i.e. a class, interface or array type
718 * or a type variable.
719 * @param pos Position to be used for error reporting.
720 * @param t The type to be checked.
721 */
722 Type checkRefType(DiagnosticPosition pos, Type t) {
723 if (t.isReference())
724 return t;
725 else
726 return typeTagError(pos,
727 diags.fragment(Fragments.TypeReqRef),
728 t);
729 }
730
731 /** Check that each type is a reference type, i.e. a class, interface or array type
732 * or a type variable.
733 * @param trees Original trees, used for error reporting.
734 * @param types The types to be checked.
735 */
736 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
737 List<JCExpression> tl = trees;
738 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
739 l.head = checkRefType(tl.head.pos(), l.head);
740 tl = tl.tail;
741 }
742 return types;
743 }
744
745 /** Check that type is a null or reference type.
746 * @param pos Position to be used for error reporting.
747 * @param t The type to be checked.
748 */
749 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
750 if (t.isReference() || t.hasTag(BOT))
751 return t;
752 else
753 return typeTagError(pos,
754 diags.fragment(Fragments.TypeReqRef),
755 t);
756 }
757
758 /** Check that flag set does not contain elements of two conflicting sets. s
759 * Return true if it doesn't.
760 * @param pos Position to be used for error reporting.
761 * @param flags The set of flags to be checked.
762 * @param set1 Conflicting flags set #1.
763 * @param set2 Conflicting flags set #2.
764 */
765 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
766 if ((flags & set1) != 0 && (flags & set2) != 0) {
767 log.error(pos,
768 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
769 asFlagSet(TreeInfo.firstFlag(flags & set2))));
770 return false;
771 } else
772 return true;
773 }
774
775 /** Check that usage of diamond operator is correct (i.e. diamond should not
776 * be used with non-generic classes or in anonymous class creation expressions)
777 */
778 Type checkDiamond(JCNewClass tree, Type t) {
779 if (!TreeInfo.isDiamond(tree) ||
780 t.isErroneous()) {
781 return checkClassType(tree.clazz.pos(), t, true);
782 } else {
783 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
784 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
785 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
786 }
787 if (t.tsym.type.getTypeArguments().isEmpty()) {
788 log.error(tree.clazz.pos(),
789 Errors.CantApplyDiamond1(t,
790 Fragments.DiamondNonGeneric(t)));
791 return types.createErrorType(t);
792 } else if (tree.typeargs != null &&
793 tree.typeargs.nonEmpty()) {
794 log.error(tree.clazz.pos(),
795 Errors.CantApplyDiamond1(t,
796 Fragments.DiamondAndExplicitParams(t)));
797 return types.createErrorType(t);
798 } else {
799 return t;
800 }
801 }
802 }
803
804 /** Check that the type inferred using the diamond operator does not contain
805 * non-denotable types such as captured types or intersection types.
806 * @param t the type inferred using the diamond operator
807 * @return the (possibly empty) list of non-denotable types.
808 */
809 List<Type> checkDiamondDenotable(ClassType t) {
810 ListBuffer<Type> buf = new ListBuffer<>();
811 for (Type arg : t.allparams()) {
812 if (!checkDenotable(arg)) {
813 buf.append(arg);
814 }
815 }
816 return buf.toList();
817 }
818
819 public boolean checkDenotable(Type t) {
820 return denotableChecker.visit(t, null);
821 }
822 // where
823
824 /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
825 * types. The visit methods return false as soon as a non-denotable type is encountered and true
826 * otherwise.
827 */
828 private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() {
829 @Override
830 public Boolean visitType(Type t, Void s) {
831 return true;
832 }
833 @Override
834 public Boolean visitClassType(ClassType t, Void s) {
835 if (t.isUnion() || t.isIntersection()) {
836 return false;
837 }
838 for (Type targ : t.allparams()) {
839 if (!visit(targ, s)) {
840 return false;
841 }
842 }
843 return true;
844 }
845
846 @Override
847 public Boolean visitTypeVar(TypeVar t, Void s) {
848 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
849 (i.e cannot have been produced by inference (18.4))
850 */
851 return (t.tsym.flags() & SYNTHETIC) == 0;
852 }
853
854 @Override
855 public Boolean visitCapturedType(CapturedType t, Void s) {
856 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
857 (i.e cannot have been produced by capture conversion (5.1.10))
858 */
859 return false;
860 }
861
862 @Override
863 public Boolean visitArrayType(ArrayType t, Void s) {
864 return visit(t.elemtype, s);
865 }
866
867 @Override
868 public Boolean visitWildcardType(WildcardType t, Void s) {
869 return visit(t.type, s);
870 }
871 };
872
873 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
874 MethodSymbol m = tree.sym;
875 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
876 Type varargElemType = null;
877 if (m.isVarArgs()) {
878 varargElemType = types.elemtype(tree.params.last().type);
879 }
880 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
881 if (varargElemType != null) {
882 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ?
883 diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
884 diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
885 log.error(tree,
886 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
887 msg));
888 } else {
889 log.error(tree,
890 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
891 Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
892 }
893 } else if (hasTrustMeAnno && varargElemType != null &&
894 types.isReifiable(varargElemType)) {
895 log.warning(tree.pos(), LintWarnings.VarargsRedundantTrustmeAnno(
896 syms.trustMeType.tsym,
897 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
898 }
899 else if (!hasTrustMeAnno && varargElemType != null &&
900 !types.isReifiable(varargElemType)) {
901 warnUnchecked(tree.params.head.pos(), LintWarnings.UncheckedVarargsNonReifiableType(varargElemType));
902 }
903 }
904 //where
905 private boolean isTrustMeAllowedOnMethod(Symbol s) {
906 return (s.flags() & VARARGS) != 0 &&
907 (s.isConstructor() ||
908 (s.flags() & (STATIC | FINAL |
909 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
910 }
911
912 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
913 //check that resulting type is not the null type
914 if (t.hasTag(BOT)) {
915 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
916 return types.createErrorType(t);
917 } else if (t.hasTag(VOID)) {
918 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
919 return types.createErrorType(t);
920 }
921
922 //upward project the initializer type
923 return types.upward(t, types.captures(t)).baseType();
924 }
925
926 Type checkMethod(final Type mtype,
927 final Symbol sym,
928 final Env<AttrContext> env,
929 final List<JCExpression> argtrees,
930 final List<Type> argtypes,
931 final boolean useVarargs,
932 InferenceContext inferenceContext) {
933 // System.out.println("call : " + env.tree);
934 // System.out.println("method : " + owntype);
935 // System.out.println("actuals: " + argtypes);
936 if (inferenceContext.free(mtype)) {
937 inferenceContext.addFreeTypeListener(List.of(mtype),
938 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
939 return mtype;
940 }
941 Type owntype = mtype;
942 List<Type> formals = owntype.getParameterTypes();
943 List<Type> nonInferred = sym.type.getParameterTypes();
944 if (nonInferred.length() != formals.length()) nonInferred = formals;
945 Type last = useVarargs ? formals.last() : null;
946 if (sym.name == names.init && sym.owner == syms.enumSym) {
947 formals = formals.tail.tail;
948 nonInferred = nonInferred.tail.tail;
949 }
950 if ((sym.flags() & ANONCONSTR_BASED) != 0) {
951 formals = formals.tail;
952 nonInferred = nonInferred.tail;
953 }
954 List<JCExpression> args = argtrees;
955 if (args != null) {
956 //this is null when type-checking a method reference
957 while (formals.head != last) {
958 JCTree arg = args.head;
959 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
960 assertConvertible(arg, arg.type, formals.head, warn);
961 args = args.tail;
962 formals = formals.tail;
963 nonInferred = nonInferred.tail;
964 }
965 if (useVarargs) {
966 Type varArg = types.elemtype(last);
967 while (args.tail != null) {
968 JCTree arg = args.head;
969 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
970 assertConvertible(arg, arg.type, varArg, warn);
971 args = args.tail;
972 }
973 } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
974 // non-varargs call to varargs method
975 Type varParam = owntype.getParameterTypes().last();
976 Type lastArg = argtypes.last();
977 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
978 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
979 log.warning(argtrees.last().pos(),
980 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam));
981 }
982 }
983 if (useVarargs) {
984 Type argtype = owntype.getParameterTypes().last();
985 if (!types.isReifiable(argtype) &&
986 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
987 !isTrustMeAllowedOnMethod(sym))) {
988 warnUnchecked(env.tree.pos(), LintWarnings.UncheckedGenericArrayCreation(argtype));
989 }
990 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
991 }
992 return owntype;
993 }
994 //where
995 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
996 if (types.isConvertible(actual, formal, warn))
997 return;
998
999 if (formal.isCompound()
1000 && types.isSubtype(actual, types.supertype(formal))
1001 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1002 return;
1003 }
1004
1005 /**
1006 * Check that type 't' is a valid instantiation of a generic class
1007 * (see JLS 4.5)
1008 *
1009 * @param t class type to be checked
1010 * @return true if 't' is well-formed
1011 */
1012 public boolean checkValidGenericType(Type t) {
1013 return firstIncompatibleTypeArg(t) == null;
1014 }
1015 //WHERE
1016 private Type firstIncompatibleTypeArg(Type type) {
1017 List<Type> formals = type.tsym.type.allparams();
1018 List<Type> actuals = type.allparams();
1019 List<Type> args = type.getTypeArguments();
1020 List<Type> forms = type.tsym.type.getTypeArguments();
1021 ListBuffer<Type> bounds_buf = new ListBuffer<>();
1022
1023 // For matching pairs of actual argument types `a' and
1024 // formal type parameters with declared bound `b' ...
1025 while (args.nonEmpty() && forms.nonEmpty()) {
1026 // exact type arguments needs to know their
1027 // bounds (for upper and lower bound
1028 // calculations). So we create new bounds where
1029 // type-parameters are replaced with actuals argument types.
1030 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1031 args = args.tail;
1032 forms = forms.tail;
1033 }
1034
1035 args = type.getTypeArguments();
1036 List<Type> tvars_cap = types.substBounds(formals,
1037 formals,
1038 types.capture(type).allparams());
1039 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1040 // Let the actual arguments know their bound
1041 args.head.withTypeVar((TypeVar)tvars_cap.head);
1042 args = args.tail;
1043 tvars_cap = tvars_cap.tail;
1044 }
1045
1046 args = type.getTypeArguments();
1047 List<Type> bounds = bounds_buf.toList();
1048
1049 while (args.nonEmpty() && bounds.nonEmpty()) {
1050 Type actual = args.head;
1051 if (!isTypeArgErroneous(actual) &&
1052 !bounds.head.isErroneous() &&
1053 !checkExtends(actual, bounds.head)) {
1054 return args.head;
1055 }
1056 args = args.tail;
1057 bounds = bounds.tail;
1058 }
1059
1060 args = type.getTypeArguments();
1061 bounds = bounds_buf.toList();
1062
1063 for (Type arg : types.capture(type).getTypeArguments()) {
1064 if (arg.hasTag(TYPEVAR) &&
1065 arg.getUpperBound().isErroneous() &&
1066 !bounds.head.isErroneous() &&
1067 !isTypeArgErroneous(args.head)) {
1068 return args.head;
1069 }
1070 bounds = bounds.tail;
1071 args = args.tail;
1072 }
1073
1074 return null;
1075 }
1076 //where
1077 boolean isTypeArgErroneous(Type t) {
1078 return isTypeArgErroneous.visit(t);
1079 }
1080
1081 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1082 public Boolean visitType(Type t, Void s) {
1083 return t.isErroneous();
1084 }
1085 @Override
1086 public Boolean visitTypeVar(TypeVar t, Void s) {
1087 return visit(t.getUpperBound());
1088 }
1089 @Override
1090 public Boolean visitCapturedType(CapturedType t, Void s) {
1091 return visit(t.getUpperBound()) ||
1092 visit(t.getLowerBound());
1093 }
1094 @Override
1095 public Boolean visitWildcardType(WildcardType t, Void s) {
1096 return visit(t.type);
1097 }
1098 };
1099
1100 /** Check that given modifiers are legal for given symbol and
1101 * return modifiers together with any implicit modifiers for that symbol.
1102 * Warning: we can't use flags() here since this method
1103 * is called during class enter, when flags() would cause a premature
1104 * completion.
1105 * @param flags The set of modifiers given in a definition.
1106 * @param sym The defined symbol.
1107 * @param tree The declaration
1108 */
1109 long checkFlags(long flags, Symbol sym, JCTree tree) {
1110 final DiagnosticPosition pos = tree.pos();
1111 long mask;
1112 long implicit = 0;
1113
1114 switch (sym.kind) {
1115 case VAR:
1116 if (TreeInfo.isReceiverParam(tree))
1117 mask = ReceiverParamFlags;
1118 else if (sym.owner.kind != TYP)
1119 mask = LocalVarFlags;
1120 else if ((sym.owner.flags_field & INTERFACE) != 0)
1121 mask = implicit = InterfaceVarFlags;
1122 else
1123 mask = VarFlags;
1124 break;
1125 case MTH:
1126 if (sym.name == names.init) {
1127 if ((sym.owner.flags_field & ENUM) != 0) {
1128 // enum constructors cannot be declared public or
1129 // protected and must be implicitly or explicitly
1130 // private
1131 implicit = PRIVATE;
1132 mask = PRIVATE;
1133 } else
1134 mask = ConstructorFlags;
1135 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1136 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1137 mask = AnnotationTypeElementMask;
1138 implicit = PUBLIC | ABSTRACT;
1139 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1140 mask = InterfaceMethodMask;
1141 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1142 if ((flags & DEFAULT) != 0) {
1143 implicit |= ABSTRACT;
1144 }
1145 } else {
1146 mask = implicit = InterfaceMethodFlags;
1147 }
1148 } else if ((sym.owner.flags_field & RECORD) != 0) {
1149 mask = RecordMethodFlags;
1150 } else {
1151 mask = MethodFlags;
1152 }
1153 if ((flags & STRICTFP) != 0) {
1154 log.warning(tree.pos(), LintWarnings.Strictfp);
1155 }
1156 // Imply STRICTFP if owner has STRICTFP set.
1157 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1158 ((flags) & Flags.DEFAULT) != 0)
1159 implicit |= sym.owner.flags_field & STRICTFP;
1160 break;
1161 case TYP:
1162 if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1163 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1164 boolean implicitlyStatic = !sym.isAnonymous() &&
1165 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1166 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1167 // local statics are allowed only if records are allowed too
1168 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1169 implicit = implicitlyStatic ? STATIC : implicit;
1170 } else if (sym.owner.kind == TYP) {
1171 // statics in inner classes are allowed only if records are allowed too
1172 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1173 if (sym.owner.owner.kind == PCK ||
1174 (sym.owner.flags_field & STATIC) != 0) {
1175 mask |= STATIC;
1176 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1177 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1178 }
1179 // Nested interfaces and enums are always STATIC (Spec ???)
1180 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1181 } else {
1182 mask = ExtendedClassFlags;
1183 }
1184 // Interfaces are always ABSTRACT
1185 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1186
1187 if ((flags & ENUM) != 0) {
1188 // enums can't be declared abstract, final, sealed or non-sealed
1189 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1190 implicit |= implicitEnumFinalFlag(tree);
1191 }
1192 if ((flags & RECORD) != 0) {
1193 // records can't be declared abstract
1194 mask &= ~ABSTRACT;
1195 implicit |= FINAL;
1196 }
1197 if ((flags & STRICTFP) != 0) {
1198 log.warning(tree.pos(), LintWarnings.Strictfp);
1199 }
1200 // Imply STRICTFP if owner has STRICTFP set.
1201 implicit |= sym.owner.flags_field & STRICTFP;
1202 break;
1203 default:
1204 throw new AssertionError();
1205 }
1206 long illegal = flags & ExtendedStandardFlags & ~mask;
1207 if (illegal != 0) {
1208 if ((illegal & INTERFACE) != 0) {
1209 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1210 mask |= INTERFACE;
1211 }
1212 else {
1213 log.error(pos,
1214 Errors.ModNotAllowedHere(asFlagSet(illegal)));
1215 }
1216 }
1217 else if ((sym.kind == TYP ||
1218 // ISSUE: Disallowing abstract&private is no longer appropriate
1219 // in the presence of inner classes. Should it be deleted here?
1220 checkDisjoint(pos, flags,
1221 ABSTRACT,
1222 PRIVATE | STATIC | DEFAULT))
1223 &&
1224 checkDisjoint(pos, flags,
1225 STATIC | PRIVATE,
1226 DEFAULT)
1227 &&
1228 checkDisjoint(pos, flags,
1229 ABSTRACT | INTERFACE,
1230 FINAL | NATIVE | SYNCHRONIZED)
1231 &&
1232 checkDisjoint(pos, flags,
1233 PUBLIC,
1234 PRIVATE | PROTECTED)
1235 &&
1236 checkDisjoint(pos, flags,
1237 PRIVATE,
1238 PUBLIC | PROTECTED)
1239 &&
1240 checkDisjoint(pos, flags,
1241 FINAL,
1242 VOLATILE)
1243 &&
1244 (sym.kind == TYP ||
1245 checkDisjoint(pos, flags,
1246 ABSTRACT | NATIVE,
1247 STRICTFP))
1248 && checkDisjoint(pos, flags,
1249 FINAL,
1250 SEALED | NON_SEALED)
1251 && checkDisjoint(pos, flags,
1252 SEALED,
1253 FINAL | NON_SEALED)
1254 && checkDisjoint(pos, flags,
1255 SEALED,
1256 ANNOTATION)) {
1257 // skip
1258 }
1259 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1260 }
1261
1262 /** Determine if this enum should be implicitly final.
1263 *
1264 * If the enum has no specialized enum constants, it is final.
1265 *
1266 * If the enum does have specialized enum constants, it is
1267 * <i>not</i> final.
1268 */
1269 private long implicitEnumFinalFlag(JCTree tree) {
1270 if (!tree.hasTag(CLASSDEF)) return 0;
1271 class SpecialTreeVisitor extends JCTree.Visitor {
1272 boolean specialized;
1273 SpecialTreeVisitor() {
1274 this.specialized = false;
1275 }
1276
1277 @Override
1278 public void visitTree(JCTree tree) { /* no-op */ }
1279
1280 @Override
1281 public void visitVarDef(JCVariableDecl tree) {
1282 if ((tree.mods.flags & ENUM) != 0) {
1283 if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
1284 specialized = true;
1285 }
1286 }
1287 }
1288 }
1289
1290 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1291 JCClassDecl cdef = (JCClassDecl) tree;
1292 for (JCTree defs: cdef.defs) {
1293 defs.accept(sts);
1294 if (sts.specialized) return allowSealed ? SEALED : 0;
1295 }
1296 return FINAL;
1297 }
1298
1299 /* *************************************************************************
1300 * Type Validation
1301 **************************************************************************/
1302
1303 /** Validate a type expression. That is,
1304 * check that all type arguments of a parametric type are within
1305 * their bounds. This must be done in a second phase after type attribution
1306 * since a class might have a subclass as type parameter bound. E.g:
1307 *
1308 * <pre>{@code
1309 * class B<A extends C> { ... }
1310 * class C extends B<C> { ... }
1311 * }</pre>
1312 *
1313 * and we can't make sure that the bound is already attributed because
1314 * of possible cycles.
1315 *
1316 * Visitor method: Validate a type expression, if it is not null, catching
1317 * and reporting any completion failures.
1318 */
1319 void validate(JCTree tree, Env<AttrContext> env) {
1320 validate(tree, env, true);
1321 }
1322 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1323 new Validator(env).validateTree(tree, checkRaw, true);
1324 }
1325
1326 /** Visitor method: Validate a list of type expressions.
1327 */
1328 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1329 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1330 validate(l.head, env);
1331 }
1332
1333 /** A visitor class for type validation.
1334 */
1335 class Validator extends JCTree.Visitor {
1336
1337 boolean checkRaw;
1338 boolean isOuter;
1339 Env<AttrContext> env;
1340
1341 Validator(Env<AttrContext> env) {
1342 this.env = env;
1343 }
1344
1345 @Override
1346 public void visitTypeArray(JCArrayTypeTree tree) {
1347 validateTree(tree.elemtype, checkRaw, isOuter);
1348 }
1349
1350 @Override
1351 public void visitTypeApply(JCTypeApply tree) {
1352 if (tree.type.hasTag(CLASS)) {
1353 List<JCExpression> args = tree.arguments;
1354 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1355
1356 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1357 if (incompatibleArg != null) {
1358 for (JCTree arg : tree.arguments) {
1359 if (arg.type == incompatibleArg) {
1360 log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
1361 }
1362 forms = forms.tail;
1363 }
1364 }
1365
1366 forms = tree.type.tsym.type.getTypeArguments();
1367
1368 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1369
1370 // For matching pairs of actual argument types `a' and
1371 // formal type parameters with declared bound `b' ...
1372 while (args.nonEmpty() && forms.nonEmpty()) {
1373 validateTree(args.head,
1374 !(isOuter && is_java_lang_Class),
1375 false);
1376 args = args.tail;
1377 forms = forms.tail;
1378 }
1379
1380 // Check that this type is either fully parameterized, or
1381 // not parameterized at all.
1382 if (tree.type.getEnclosingType().isRaw())
1383 log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
1384 if (tree.clazz.hasTag(SELECT))
1385 visitSelectInternal((JCFieldAccess)tree.clazz);
1386 }
1387 }
1388
1389 @Override
1390 public void visitTypeParameter(JCTypeParameter tree) {
1391 validateTrees(tree.bounds, true, isOuter);
1392 checkClassBounds(tree.pos(), tree.type);
1393 }
1394
1395 @Override
1396 public void visitWildcard(JCWildcard tree) {
1397 if (tree.inner != null)
1398 validateTree(tree.inner, true, isOuter);
1399 }
1400
1401 @Override
1402 public void visitSelect(JCFieldAccess tree) {
1403 if (tree.type.hasTag(CLASS)) {
1404 visitSelectInternal(tree);
1405
1406 // Check that this type is either fully parameterized, or
1407 // not parameterized at all.
1408 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1409 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1410 }
1411 }
1412
1413 public void visitSelectInternal(JCFieldAccess tree) {
1414 if (tree.type.tsym.isStatic() &&
1415 tree.selected.type.isParameterized()) {
1416 // The enclosing type is not a class, so we are
1417 // looking at a static member type. However, the
1418 // qualifying expression is parameterized.
1419 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1420 } else {
1421 // otherwise validate the rest of the expression
1422 tree.selected.accept(this);
1423 }
1424 }
1425
1426 @Override
1427 public void visitAnnotatedType(JCAnnotatedType tree) {
1428 tree.underlyingType.accept(this);
1429 }
1430
1431 @Override
1432 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1433 if (that.type.hasTag(TypeTag.VOID)) {
1434 log.error(that.pos(), Errors.VoidNotAllowedHere);
1435 }
1436 super.visitTypeIdent(that);
1437 }
1438
1439 /** Default visitor method: do nothing.
1440 */
1441 @Override
1442 public void visitTree(JCTree tree) {
1443 }
1444
1445 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1446 if (tree != null) {
1447 boolean prevCheckRaw = this.checkRaw;
1448 this.checkRaw = checkRaw;
1449 this.isOuter = isOuter;
1450
1451 try {
1452 tree.accept(this);
1453 if (checkRaw)
1454 checkRaw(tree, env);
1455 } catch (CompletionFailure ex) {
1456 completionError(tree.pos(), ex);
1457 } finally {
1458 this.checkRaw = prevCheckRaw;
1459 }
1460 }
1461 }
1462
1463 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1464 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1465 validateTree(l.head, checkRaw, isOuter);
1466 }
1467 }
1468
1469 void checkRaw(JCTree tree, Env<AttrContext> env) {
1470 if (tree.type.hasTag(CLASS) &&
1471 !TreeInfo.isDiamond(tree) &&
1472 !withinAnonConstr(env) &&
1473 tree.type.isRaw()) {
1474 log.warning(tree.pos(), LintWarnings.RawClassUse(tree.type, tree.type.tsym.type));
1475 }
1476 }
1477 //where
1478 private boolean withinAnonConstr(Env<AttrContext> env) {
1479 return env.enclClass.name.isEmpty() &&
1480 env.enclMethod != null && env.enclMethod.name == names.init;
1481 }
1482
1483 /* *************************************************************************
1484 * Exception checking
1485 **************************************************************************/
1486
1487 /* The following methods treat classes as sets that contain
1488 * the class itself and all their subclasses
1489 */
1490
1491 /** Is given type a subtype of some of the types in given list?
1492 */
1493 boolean subset(Type t, List<Type> ts) {
1494 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1495 if (types.isSubtype(t, l.head)) return true;
1496 return false;
1497 }
1498
1499 /** Is given type a subtype or supertype of
1500 * some of the types in given list?
1501 */
1502 boolean intersects(Type t, List<Type> ts) {
1503 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1504 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1505 return false;
1506 }
1507
1508 /** Add type set to given type list, unless it is a subclass of some class
1509 * in the list.
1510 */
1511 List<Type> incl(Type t, List<Type> ts) {
1512 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1513 }
1514
1515 /** Remove type set from type set list.
1516 */
1517 List<Type> excl(Type t, List<Type> ts) {
1518 if (ts.isEmpty()) {
1519 return ts;
1520 } else {
1521 List<Type> ts1 = excl(t, ts.tail);
1522 if (types.isSubtype(ts.head, t)) return ts1;
1523 else if (ts1 == ts.tail) return ts;
1524 else return ts1.prepend(ts.head);
1525 }
1526 }
1527
1528 /** Form the union of two type set lists.
1529 */
1530 List<Type> union(List<Type> ts1, List<Type> ts2) {
1531 List<Type> ts = ts1;
1532 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1533 ts = incl(l.head, ts);
1534 return ts;
1535 }
1536
1537 /** Form the difference of two type lists.
1538 */
1539 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1540 List<Type> ts = ts1;
1541 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1542 ts = excl(l.head, ts);
1543 return ts;
1544 }
1545
1546 /** Form the intersection of two type lists.
1547 */
1548 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1549 List<Type> ts = List.nil();
1550 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1551 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1552 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1553 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1554 return ts;
1555 }
1556
1557 /** Is exc an exception symbol that need not be declared?
1558 */
1559 boolean isUnchecked(ClassSymbol exc) {
1560 return
1561 exc.kind == ERR ||
1562 exc.isSubClass(syms.errorType.tsym, types) ||
1563 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1564 }
1565
1566 /** Is exc an exception type that need not be declared?
1567 */
1568 boolean isUnchecked(Type exc) {
1569 return
1570 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1571 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1572 exc.hasTag(BOT);
1573 }
1574
1575 boolean isChecked(Type exc) {
1576 return !isUnchecked(exc);
1577 }
1578
1579 /** Same, but handling completion failures.
1580 */
1581 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1582 try {
1583 return isUnchecked(exc);
1584 } catch (CompletionFailure ex) {
1585 completionError(pos, ex);
1586 return true;
1587 }
1588 }
1589
1590 /** Is exc handled by given exception list?
1591 */
1592 boolean isHandled(Type exc, List<Type> handled) {
1593 return isUnchecked(exc) || subset(exc, handled);
1594 }
1595
1596 /** Return all exceptions in thrown list that are not in handled list.
1597 * @param thrown The list of thrown exceptions.
1598 * @param handled The list of handled exceptions.
1599 */
1600 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1601 List<Type> unhandled = List.nil();
1602 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1603 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1604 return unhandled;
1605 }
1606
1607 /* *************************************************************************
1608 * Overriding/Implementation checking
1609 **************************************************************************/
1610
1611 /** The level of access protection given by a flag set,
1612 * where PRIVATE is highest and PUBLIC is lowest.
1613 */
1614 static int protection(long flags) {
1615 switch ((short)(flags & AccessFlags)) {
1616 case PRIVATE: return 3;
1617 case PROTECTED: return 1;
1618 default:
1619 case PUBLIC: return 0;
1620 case 0: return 2;
1621 }
1622 }
1623
1624 /** A customized "cannot override" error message.
1625 * @param m The overriding method.
1626 * @param other The overridden method.
1627 * @return An internationalized string.
1628 */
1629 Fragment cannotOverride(MethodSymbol m, MethodSymbol other) {
1630 Symbol mloc = m.location();
1631 Symbol oloc = other.location();
1632
1633 if ((other.owner.flags() & INTERFACE) == 0)
1634 return Fragments.CantOverride(m, mloc, other, oloc);
1635 else if ((m.owner.flags() & INTERFACE) == 0)
1636 return Fragments.CantImplement(m, mloc, other, oloc);
1637 else
1638 return Fragments.ClashesWith(m, mloc, other, oloc);
1639 }
1640
1641 /** A customized "override" warning message.
1642 * @param m The overriding method.
1643 * @param other The overridden method.
1644 * @return An internationalized string.
1645 */
1646 Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1647 Symbol mloc = m.location();
1648 Symbol oloc = other.location();
1649
1650 if ((other.owner.flags() & INTERFACE) == 0)
1651 return Fragments.UncheckedOverride(m, mloc, other, oloc);
1652 else if ((m.owner.flags() & INTERFACE) == 0)
1653 return Fragments.UncheckedImplement(m, mloc, other, oloc);
1654 else
1655 return Fragments.UncheckedClashWith(m, mloc, other, oloc);
1656 }
1657
1658 /** A customized "override" warning message.
1659 * @param m The overriding method.
1660 * @param other The overridden method.
1661 * @return An internationalized string.
1662 */
1663 Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) {
1664 Symbol mloc = m.location();
1665 Symbol oloc = other.location();
1666
1667 if ((other.owner.flags() & INTERFACE) == 0)
1668 return Fragments.VarargsOverride(m, mloc, other, oloc);
1669 else if ((m.owner.flags() & INTERFACE) == 0)
1670 return Fragments.VarargsImplement(m, mloc, other, oloc);
1671 else
1672 return Fragments.VarargsClashWith(m, mloc, other, oloc);
1673 }
1674
1675 /** Check that this method conforms with overridden method 'other'.
1676 * where `origin' is the class where checking started.
1677 * Complications:
1678 * (1) Do not check overriding of synthetic methods
1679 * (reason: they might be final).
1680 * todo: check whether this is still necessary.
1681 * (2) Admit the case where an interface proxy throws fewer exceptions
1682 * than the method it implements. Augment the proxy methods with the
1683 * undeclared exceptions in this case.
1684 * (3) When generics are enabled, admit the case where an interface proxy
1685 * has a result type
1686 * extended by the result type of the method it implements.
1687 * Change the proxies result type to the smaller type in this case.
1688 *
1689 * @param tree The tree from which positions
1690 * are extracted for errors.
1691 * @param m The overriding method.
1692 * @param other The overridden method.
1693 * @param origin The class of which the overriding method
1694 * is a member.
1695 */
1696 void checkOverride(JCTree tree,
1697 MethodSymbol m,
1698 MethodSymbol other,
1699 ClassSymbol origin) {
1700 // Don't check overriding of synthetic methods or by bridge methods.
1701 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1702 return;
1703 }
1704
1705 // Error if static method overrides instance method (JLS 8.4.8.2).
1706 if ((m.flags() & STATIC) != 0 &&
1707 (other.flags() & STATIC) == 0) {
1708 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1709 Errors.OverrideStatic(cannotOverride(m, other)));
1710 m.flags_field |= BAD_OVERRIDE;
1711 return;
1712 }
1713
1714 // Error if instance method overrides static or final
1715 // method (JLS 8.4.8.1).
1716 if ((other.flags() & FINAL) != 0 ||
1717 (m.flags() & STATIC) == 0 &&
1718 (other.flags() & STATIC) != 0) {
1719 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1720 Errors.OverrideMeth(cannotOverride(m, other),
1721 asFlagSet(other.flags() & (FINAL | STATIC))));
1722 m.flags_field |= BAD_OVERRIDE;
1723 return;
1724 }
1725
1726 if ((m.owner.flags() & ANNOTATION) != 0) {
1727 // handled in validateAnnotationMethod
1728 return;
1729 }
1730
1731 // Error if overriding method has weaker access (JLS 8.4.8.3).
1732 if (protection(m.flags()) > protection(other.flags())) {
1733 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1734 (other.flags() & AccessFlags) == 0 ?
1735 Errors.OverrideWeakerAccess(cannotOverride(m, other),
1736 "package") :
1737 Errors.OverrideWeakerAccess(cannotOverride(m, other),
1738 asFlagSet(other.flags() & AccessFlags)));
1739 m.flags_field |= BAD_OVERRIDE;
1740 return;
1741 }
1742
1743 if (shouldCheckPreview(m, other, origin)) {
1744 checkPreview(TreeInfo.diagnosticPositionFor(m, tree),
1745 m, origin.type, other);
1746 }
1747
1748 Type mt = types.memberType(origin.type, m);
1749 Type ot = types.memberType(origin.type, other);
1750 // Error if overriding result type is different
1751 // (or, in the case of generics mode, not a subtype) of
1752 // overridden result type. We have to rename any type parameters
1753 // before comparing types.
1754 List<Type> mtvars = mt.getTypeArguments();
1755 List<Type> otvars = ot.getTypeArguments();
1756 Type mtres = mt.getReturnType();
1757 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1758
1759 overrideWarner.clear();
1760 boolean resultTypesOK =
1761 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1762 if (!resultTypesOK) {
1763 if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1764 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1765 Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1766 other.location()), mtres, otres));
1767 m.flags_field |= BAD_OVERRIDE;
1768 } else {
1769 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1770 Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres));
1771 m.flags_field |= BAD_OVERRIDE;
1772 }
1773 return;
1774 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1775 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1776 LintWarnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
1777 }
1778
1779 // Error if overriding method throws an exception not reported
1780 // by overridden method.
1781 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1782 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1783 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1784 if (unhandledErased.nonEmpty()) {
1785 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1786 Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head));
1787 m.flags_field |= BAD_OVERRIDE;
1788 return;
1789 }
1790 else if (unhandledUnerased.nonEmpty()) {
1791 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1792 LintWarnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
1793 return;
1794 }
1795
1796 // Optional warning if varargs don't agree
1797 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)) {
1798 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1799 ((m.flags() & Flags.VARARGS) != 0)
1800 ? LintWarnings.OverrideVarargsMissing(varargsOverrides(m, other))
1801 : LintWarnings.OverrideVarargsExtra(varargsOverrides(m, other)));
1802 }
1803
1804 // Warn if instance method overrides bridge method (compiler spec ??)
1805 if ((other.flags() & BRIDGE) != 0) {
1806 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1807 Warnings.OverrideBridge(uncheckedOverrides(m, other)));
1808 }
1809
1810 // Warn if a deprecated method overridden by a non-deprecated one.
1811 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1812 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other);
1813 }
1814 }
1815 // where
1816 private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) {
1817 if (m.owner != origin ||
1818 //performance - only do the expensive checks when the overridden method is a Preview API:
1819 ((other.flags() & PREVIEW_API) == 0 &&
1820 (other.owner.flags() & PREVIEW_API) == 0)) {
1821 return false;
1822 }
1823
1824 for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) {
1825 if (m != s && m.overrides(s, origin, types, false)) {
1826 //only produce preview warnings or errors if "m" immediatelly overrides "other"
1827 //without intermediate overriding methods:
1828 return s == other;
1829 }
1830 }
1831
1832 return false;
1833 }
1834 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1835 // If the method, m, is defined in an interface, then ignore the issue if the method
1836 // is only inherited via a supertype and also implemented in the supertype,
1837 // because in that case, we will rediscover the issue when examining the method
1838 // in the supertype.
1839 // If the method, m, is not defined in an interface, then the only time we need to
1840 // address the issue is when the method is the supertype implementation: any other
1841 // case, we will have dealt with when examining the supertype classes
1842 ClassSymbol mc = m.enclClass();
1843 Type st = types.supertype(origin.type);
1844 if (!st.hasTag(CLASS))
1845 return true;
1846 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1847
1848 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1849 List<Type> intfs = types.interfaces(origin.type);
1850 return (intfs.contains(mc.type) ? false : (stimpl != null));
1851 }
1852 else
1853 return (stimpl != m);
1854 }
1855
1856
1857 // used to check if there were any unchecked conversions
1858 Warner overrideWarner = new Warner();
1859
1860 /** Check that a class does not inherit two concrete methods
1861 * with the same signature.
1862 * @param pos Position to be used for error reporting.
1863 * @param site The class type to be checked.
1864 */
1865 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1866 Type sup = types.supertype(site);
1867 if (!sup.hasTag(CLASS)) return;
1868
1869 for (Type t1 = sup;
1870 t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1871 t1 = types.supertype(t1)) {
1872 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1873 if (s1.kind != MTH ||
1874 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1875 !s1.isInheritedIn(site.tsym, types) ||
1876 ((MethodSymbol)s1).implementation(site.tsym,
1877 types,
1878 true) != s1)
1879 continue;
1880 Type st1 = types.memberType(t1, s1);
1881 int s1ArgsLength = st1.getParameterTypes().length();
1882 if (st1 == s1.type) continue;
1883
1884 for (Type t2 = sup;
1885 t2.hasTag(CLASS);
1886 t2 = types.supertype(t2)) {
1887 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1888 if (s2 == s1 ||
1889 s2.kind != MTH ||
1890 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1891 s2.type.getParameterTypes().length() != s1ArgsLength ||
1892 !s2.isInheritedIn(site.tsym, types) ||
1893 ((MethodSymbol)s2).implementation(site.tsym,
1894 types,
1895 true) != s2)
1896 continue;
1897 Type st2 = types.memberType(t2, s2);
1898 if (types.overrideEquivalent(st1, st2))
1899 log.error(pos,
1900 Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup));
1901 }
1902 }
1903 }
1904 }
1905 }
1906
1907 /** Check that classes (or interfaces) do not each define an abstract
1908 * method with same name and arguments but incompatible return types.
1909 * @param pos Position to be used for error reporting.
1910 * @param t1 The first argument type.
1911 * @param t2 The second argument type.
1912 */
1913 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1914 Type t1,
1915 Type t2,
1916 Type site) {
1917 if ((site.tsym.flags() & COMPOUND) != 0) {
1918 // special case for intersections: need to eliminate wildcards in supertypes
1919 t1 = types.capture(t1);
1920 t2 = types.capture(t2);
1921 }
1922 return firstIncompatibility(pos, t1, t2, site) == null;
1923 }
1924
1925 /** Return the first method which is defined with same args
1926 * but different return types in two given interfaces, or null if none
1927 * exists.
1928 * @param t1 The first type.
1929 * @param t2 The second type.
1930 * @param site The most derived type.
1931 * @return symbol from t2 that conflicts with one in t1.
1932 */
1933 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1934 Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1935 closure(t1, interfaces1);
1936 Map<TypeSymbol,Type> interfaces2;
1937 if (t1 == t2)
1938 interfaces2 = interfaces1;
1939 else
1940 closure(t2, interfaces1, interfaces2 = new HashMap<>());
1941
1942 for (Type t3 : interfaces1.values()) {
1943 for (Type t4 : interfaces2.values()) {
1944 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1945 if (s != null) return s;
1946 }
1947 }
1948 return null;
1949 }
1950
1951 /** Compute all the supertypes of t, indexed by type symbol. */
1952 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1953 if (!t.hasTag(CLASS)) return;
1954 if (typeMap.put(t.tsym, t) == null) {
1955 closure(types.supertype(t), typeMap);
1956 for (Type i : types.interfaces(t))
1957 closure(i, typeMap);
1958 }
1959 }
1960
1961 /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */
1962 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1963 if (!t.hasTag(CLASS)) return;
1964 if (typesSkip.get(t.tsym) != null) return;
1965 if (typeMap.put(t.tsym, t) == null) {
1966 closure(types.supertype(t), typesSkip, typeMap);
1967 for (Type i : types.interfaces(t))
1968 closure(i, typesSkip, typeMap);
1969 }
1970 }
1971
1972 /** Return the first method in t2 that conflicts with a method from t1. */
1973 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1974 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1975 Type st1 = null;
1976 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1977 (s1.flags() & SYNTHETIC) != 0) continue;
1978 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1979 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1980 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1981 if (s1 == s2) continue;
1982 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1983 (s2.flags() & SYNTHETIC) != 0) continue;
1984 if (st1 == null) st1 = types.memberType(t1, s1);
1985 Type st2 = types.memberType(t2, s2);
1986 if (types.overrideEquivalent(st1, st2)) {
1987 List<Type> tvars1 = st1.getTypeArguments();
1988 List<Type> tvars2 = st2.getTypeArguments();
1989 Type rt1 = st1.getReturnType();
1990 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1991 boolean compat =
1992 types.isSameType(rt1, rt2) ||
1993 !rt1.isPrimitiveOrVoid() &&
1994 !rt2.isPrimitiveOrVoid() &&
1995 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1996 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1997 checkCommonOverriderIn(s1,s2,site);
1998 if (!compat) {
1999 if (types.isSameType(t1, t2)) {
2000 log.error(pos, Errors.IncompatibleDiffRetSameType(t1,
2001 s2.name, types.memberType(t2, s2).getParameterTypes()));
2002 } else {
2003 log.error(pos, Errors.TypesIncompatible(t1, t2,
2004 Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes())));
2005 }
2006 return s2;
2007 }
2008 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2009 !checkCommonOverriderIn(s1, s2, site)) {
2010 log.error(pos, Errors.NameClashSameErasureNoOverride(
2011 s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
2012 s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
2013 return s2;
2014 }
2015 }
2016 }
2017 return null;
2018 }
2019 //WHERE
2020 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2021 Map<TypeSymbol,Type> supertypes = new HashMap<>();
2022 Type st1 = types.memberType(site, s1);
2023 Type st2 = types.memberType(site, s2);
2024 closure(site, supertypes);
2025 for (Type t : supertypes.values()) {
2026 for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2027 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2028 Type st3 = types.memberType(site,s3);
2029 if (types.overrideEquivalent(st3, st1) &&
2030 types.overrideEquivalent(st3, st2) &&
2031 types.returnTypeSubstitutable(st3, st1) &&
2032 types.returnTypeSubstitutable(st3, st2)) {
2033 return true;
2034 }
2035 }
2036 }
2037 return false;
2038 }
2039
2040 /** Check that a given method conforms with any method it overrides.
2041 * @param tree The tree from which positions are extracted
2042 * for errors.
2043 * @param m The overriding method.
2044 */
2045 void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2046 ClassSymbol origin = (ClassSymbol)m.owner;
2047 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
2048 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2049 log.error(tree.pos(), Errors.EnumNoFinalize);
2050 return;
2051 }
2052 }
2053 if (allowRecords && origin.isRecord()) {
2054 // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable
2055 Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream()
2056 .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
2057 if (recordComponent.isPresent()) {
2058 return;
2059 }
2060 }
2061
2062 for (Type t = origin.type; t.hasTag(CLASS);
2063 t = types.supertype(t)) {
2064 if (t != origin.type) {
2065 checkOverride(tree, t, origin, m);
2066 }
2067 for (Type t2 : types.interfaces(t)) {
2068 checkOverride(tree, t2, origin, m);
2069 }
2070 }
2071
2072 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2073 // Check if this method must override a super method due to being annotated with @Override
2074 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2075 // be treated "as if as they were annotated" with @Override.
2076 boolean mustOverride = explicitOverride ||
2077 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2078 if (mustOverride && !isOverrider(m)) {
2079 DiagnosticPosition pos = tree.pos();
2080 for (JCAnnotation a : tree.getModifiers().annotations) {
2081 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2082 pos = a.pos();
2083 break;
2084 }
2085 }
2086 log.error(pos,
2087 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride(m, m.enclClass()) : Errors.MethodDoesNotOverrideSuperclass(m, m.enclClass())) :
2088 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2089 }
2090 }
2091
2092 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2093 TypeSymbol c = site.tsym;
2094 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2095 if (m.overrides(sym, origin, types, false)) {
2096 if ((sym.flags() & ABSTRACT) == 0) {
2097 checkOverride(tree, m, (MethodSymbol)sym, origin);
2098 }
2099 }
2100 }
2101 }
2102
2103 private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) &&
2104 (s.flags() & BAD_OVERRIDE) == 0;
2105
2106 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2107 ClassSymbol someClass) {
2108 /* At present, annotations cannot possibly have a method that is override
2109 * equivalent with Object.equals(Object) but in any case the condition is
2110 * fine for completeness.
2111 */
2112 if (someClass == (ClassSymbol)syms.objectType.tsym ||
2113 someClass.isInterface() || someClass.isEnum() ||
2114 (someClass.flags() & ANNOTATION) != 0 ||
2115 (someClass.flags() & ABSTRACT) != 0) return;
2116 //anonymous inner classes implementing interfaces need especial treatment
2117 if (someClass.isAnonymous()) {
2118 List<Type> interfaces = types.interfaces(someClass.type);
2119 if (interfaces != null && !interfaces.isEmpty() &&
2120 interfaces.head.tsym == syms.comparatorType.tsym) return;
2121 }
2122 checkClassOverrideEqualsAndHash(pos, someClass);
2123 }
2124
2125 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2126 ClassSymbol someClass) {
2127 if (lint.isEnabled(LintCategory.OVERRIDES)) {
2128 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2129 .tsym.members().findFirst(names.equals);
2130 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2131 .tsym.members().findFirst(names.hashCode);
2132 MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2133 someClass, false, equalsHasCodeFilter);
2134 boolean overridesEquals = equalsImpl != null &&
2135 equalsImpl.owner == someClass;
2136 boolean overridesHashCode = types.implementation(hashCodeAtObject,
2137 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2138
2139 if (overridesEquals && !overridesHashCode) {
2140 log.warning(pos,
2141 LintWarnings.OverrideEqualsButNotHashcode(someClass));
2142 }
2143 }
2144 }
2145
2146 public void checkHasMain(DiagnosticPosition pos, ClassSymbol c) {
2147 boolean found = false;
2148
2149 for (Symbol sym : c.members().getSymbolsByName(names.main)) {
2150 if (sym.kind == MTH && (sym.flags() & PRIVATE) == 0) {
2151 MethodSymbol meth = (MethodSymbol)sym;
2152 if (!types.isSameType(meth.getReturnType(), syms.voidType)) {
2153 continue;
2154 }
2155 if (meth.params.isEmpty()) {
2156 found = true;
2157 break;
2158 }
2159 if (meth.params.size() != 1) {
2160 continue;
2161 }
2162 if (!types.isSameType(meth.params.head.type, types.makeArrayType(syms.stringType))) {
2163 continue;
2164 }
2165
2166 found = true;
2167 break;
2168 }
2169 }
2170
2171 if (!found) {
2172 log.error(pos, Errors.ImplicitClassDoesNotHaveMainMethod);
2173 }
2174 }
2175
2176 public void checkModuleName (JCModuleDecl tree) {
2177 Name moduleName = tree.sym.name;
2178 Assert.checkNonNull(moduleName);
2179 if (lint.isEnabled(LintCategory.MODULE)) {
2180 JCExpression qualId = tree.qualId;
2181 while (qualId != null) {
2182 Name componentName;
2183 DiagnosticPosition pos;
2184 switch (qualId.getTag()) {
2185 case SELECT:
2186 JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2187 componentName = selectNode.name;
2188 pos = selectNode.pos();
2189 qualId = selectNode.selected;
2190 break;
2191 case IDENT:
2192 componentName = ((JCIdent) qualId).name;
2193 pos = qualId.pos();
2194 qualId = null;
2195 break;
2196 default:
2197 throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2198 }
2199 if (componentName != null) {
2200 String moduleNameComponentString = componentName.toString();
2201 int nameLength = moduleNameComponentString.length();
2202 if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2203 log.warning(pos, LintWarnings.PoorChoiceForModuleName(componentName));
2204 }
2205 }
2206 }
2207 }
2208 }
2209
2210 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2211 ClashFilter cf = new ClashFilter(origin.type);
2212 return (cf.test(s1) &&
2213 cf.test(s2) &&
2214 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2215 }
2216
2217
2218 /** Check that all abstract members of given class have definitions.
2219 * @param pos Position to be used for error reporting.
2220 * @param c The class.
2221 */
2222 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2223 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2224 if (undef != null) {
2225 MethodSymbol undef1 =
2226 new MethodSymbol(undef.flags(), undef.name,
2227 types.memberType(c.type, undef), undef.owner);
2228 log.error(pos,
2229 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2230 }
2231 }
2232
2233 void checkNonCyclicDecl(JCClassDecl tree) {
2234 CycleChecker cc = new CycleChecker();
2235 cc.scan(tree);
2236 if (!cc.errorFound && !cc.partialCheck) {
2237 tree.sym.flags_field |= ACYCLIC;
2238 }
2239 }
2240
2241 class CycleChecker extends TreeScanner {
2242
2243 Set<Symbol> seenClasses = new HashSet<>();
2244 boolean errorFound = false;
2245 boolean partialCheck = false;
2246
2247 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2248 if (sym != null && sym.kind == TYP) {
2249 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2250 if (classEnv != null) {
2251 DiagnosticSource prevSource = log.currentSource();
2252 try {
2253 log.useSource(classEnv.toplevel.sourcefile);
2254 scan(classEnv.tree);
2255 }
2256 finally {
2257 log.useSource(prevSource.getFile());
2258 }
2259 } else if (sym.kind == TYP) {
2260 checkClass(pos, sym, List.nil());
2261 }
2262 } else if (sym == null || sym.kind != PCK) {
2263 //not completed yet
2264 partialCheck = true;
2265 }
2266 }
2267
2268 @Override
2269 public void visitSelect(JCFieldAccess tree) {
2270 super.visitSelect(tree);
2271 checkSymbol(tree.pos(), tree.sym);
2272 }
2273
2274 @Override
2275 public void visitIdent(JCIdent tree) {
2276 checkSymbol(tree.pos(), tree.sym);
2277 }
2278
2279 @Override
2280 public void visitTypeApply(JCTypeApply tree) {
2281 scan(tree.clazz);
2282 }
2283
2284 @Override
2285 public void visitTypeArray(JCArrayTypeTree tree) {
2286 scan(tree.elemtype);
2287 }
2288
2289 @Override
2290 public void visitClassDef(JCClassDecl tree) {
2291 List<JCTree> supertypes = List.nil();
2292 if (tree.getExtendsClause() != null) {
2293 supertypes = supertypes.prepend(tree.getExtendsClause());
2294 }
2295 if (tree.getImplementsClause() != null) {
2296 for (JCTree intf : tree.getImplementsClause()) {
2297 supertypes = supertypes.prepend(intf);
2298 }
2299 }
2300 checkClass(tree.pos(), tree.sym, supertypes);
2301 }
2302
2303 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2304 if ((c.flags_field & ACYCLIC) != 0)
2305 return;
2306 if (seenClasses.contains(c)) {
2307 errorFound = true;
2308 log.error(pos, Errors.CyclicInheritance(c));
2309 seenClasses.stream()
2310 .filter(s -> !s.type.isErroneous())
2311 .filter(ClassSymbol.class::isInstance)
2312 .map(ClassSymbol.class::cast)
2313 .forEach(Check.this::handleCyclic);
2314 } else if (!c.type.isErroneous()) {
2315 try {
2316 seenClasses.add(c);
2317 if (c.type.hasTag(CLASS)) {
2318 if (supertypes.nonEmpty()) {
2319 scan(supertypes);
2320 }
2321 else {
2322 ClassType ct = (ClassType)c.type;
2323 if (ct.supertype_field == null ||
2324 ct.interfaces_field == null) {
2325 //not completed yet
2326 partialCheck = true;
2327 return;
2328 }
2329 checkSymbol(pos, ct.supertype_field.tsym);
2330 for (Type intf : ct.interfaces_field) {
2331 checkSymbol(pos, intf.tsym);
2332 }
2333 }
2334 if (c.owner.kind == TYP) {
2335 checkSymbol(pos, c.owner);
2336 }
2337 }
2338 } finally {
2339 seenClasses.remove(c);
2340 }
2341 }
2342 }
2343 }
2344
2345 /** Check for cyclic references. Issue an error if the
2346 * symbol of the type referred to has a LOCKED flag set.
2347 *
2348 * @param pos Position to be used for error reporting.
2349 * @param t The type referred to.
2350 */
2351 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2352 checkNonCyclicInternal(pos, t);
2353 }
2354
2355
2356 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2357 checkNonCyclic1(pos, t, List.nil());
2358 }
2359
2360 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2361 final TypeVar tv;
2362 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2363 return;
2364 if (seen.contains(t)) {
2365 tv = (TypeVar)t;
2366 tv.setUpperBound(types.createErrorType(t));
2367 log.error(pos, Errors.CyclicInheritance(t));
2368 } else if (t.hasTag(TYPEVAR)) {
2369 tv = (TypeVar)t;
2370 seen = seen.prepend(tv);
2371 for (Type b : types.getBounds(tv))
2372 checkNonCyclic1(pos, b, seen);
2373 }
2374 }
2375
2376 /** Check for cyclic references. Issue an error if the
2377 * symbol of the type referred to has a LOCKED flag set.
2378 *
2379 * @param pos Position to be used for error reporting.
2380 * @param t The type referred to.
2381 * @return True if the check completed on all attributed classes
2382 */
2383 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2384 boolean complete = true; // was the check complete?
2385 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2386 Symbol c = t.tsym;
2387 if ((c.flags_field & ACYCLIC) != 0) return true;
2388
2389 if ((c.flags_field & LOCKED) != 0) {
2390 log.error(pos, Errors.CyclicInheritance(c));
2391 handleCyclic((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 /** Handle finding an inheritance cycle on a class by setting
2419 * the class' and its supertypes' types to the error type.
2420 **/
2421 private void handleCyclic(ClassSymbol c) {
2422 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2423 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2424 Type st = types.supertype(c.type);
2425 if (st.hasTag(CLASS))
2426 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2427 c.type = types.createErrorType(c, c.type);
2428 c.flags_field |= ACYCLIC;
2429 }
2430
2431 /** Check that all methods which implement some
2432 * method conform to the method they implement.
2433 * @param tree The class definition whose members are checked.
2434 */
2435 void checkImplementations(JCClassDecl tree) {
2436 checkImplementations(tree, tree.sym, tree.sym);
2437 }
2438 //where
2439 /** Check that all methods which implement some
2440 * method in `ic' conform to the method they implement.
2441 */
2442 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2443 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2444 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2445 if ((lc.flags() & ABSTRACT) != 0) {
2446 for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2447 if (sym.kind == MTH &&
2448 (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2449 MethodSymbol absmeth = (MethodSymbol)sym;
2450 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2451 if (implmeth != null && implmeth != absmeth &&
2452 (implmeth.owner.flags() & INTERFACE) ==
2453 (origin.flags() & INTERFACE)) {
2454 // don't check if implmeth is in a class, yet
2455 // origin is an interface. This case arises only
2456 // if implmeth is declared in Object. The reason is
2457 // that interfaces really don't inherit from
2458 // Object it's just that the compiler represents
2459 // things that way.
2460 checkOverride(tree, implmeth, absmeth, origin);
2461 }
2462 }
2463 }
2464 }
2465 }
2466 }
2467
2468 /** Check that all abstract methods implemented by a class are
2469 * mutually compatible.
2470 * @param pos Position to be used for error reporting.
2471 * @param c The class whose interfaces are checked.
2472 */
2473 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2474 List<Type> supertypes = types.interfaces(c);
2475 Type supertype = types.supertype(c);
2476 if (supertype.hasTag(CLASS) &&
2477 (supertype.tsym.flags() & ABSTRACT) != 0)
2478 supertypes = supertypes.prepend(supertype);
2479 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2480 if (!l.head.getTypeArguments().isEmpty() &&
2481 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2482 return;
2483 for (List<Type> m = supertypes; m != l; m = m.tail)
2484 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2485 return;
2486 }
2487 checkCompatibleConcretes(pos, c);
2488 }
2489
2490 /** Check that all non-override equivalent methods accessible from 'site'
2491 * are mutually compatible (JLS 8.4.8/9.4.1).
2492 *
2493 * @param pos Position to be used for error reporting.
2494 * @param site The class whose methods are checked.
2495 * @param sym The method symbol to be checked.
2496 */
2497 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2498 ClashFilter cf = new ClashFilter(site);
2499 //for each method m1 that is overridden (directly or indirectly)
2500 //by method 'sym' in 'site'...
2501
2502 ArrayList<Symbol> symbolsByName = new ArrayList<>();
2503 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2504 for (Symbol m1 : symbolsByName) {
2505 if (!sym.overrides(m1, site.tsym, types, false)) {
2506 continue;
2507 }
2508
2509 //...check each method m2 that is a member of 'site'
2510 for (Symbol m2 : symbolsByName) {
2511 if (m2 == m1) continue;
2512 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2513 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2514 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) &&
2515 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2516 sym.flags_field |= CLASH;
2517 if (m1 == sym) {
2518 log.error(pos, Errors.NameClashSameErasureNoOverride(
2519 m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(),
2520 m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location()));
2521 } else {
2522 ClassType ct = (ClassType)site;
2523 String kind = ct.isInterface() ? "interface" : "class";
2524 log.error(pos, Errors.NameClashSameErasureNoOverride1(
2525 kind,
2526 ct.tsym.name,
2527 m1.name,
2528 types.memberType(site, m1).asMethodType().getParameterTypes(),
2529 m1.location(),
2530 m2.name,
2531 types.memberType(site, m2).asMethodType().getParameterTypes(),
2532 m2.location()));
2533 }
2534 return;
2535 }
2536 }
2537 }
2538 }
2539
2540 /** Check that all static methods accessible from 'site' are
2541 * mutually compatible (JLS 8.4.8).
2542 *
2543 * @param pos Position to be used for error reporting.
2544 * @param site The class whose methods are checked.
2545 * @param sym The method symbol to be checked.
2546 */
2547 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2548 ClashFilter cf = new ClashFilter(site);
2549 //for each method m1 that is a member of 'site'...
2550 for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2551 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2552 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2553 if (!types.isSubSignature(sym.type, types.memberType(site, s))) {
2554 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2555 log.error(pos,
2556 Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location()));
2557 return;
2558 }
2559 }
2560 }
2561 }
2562
2563 //where
2564 private class ClashFilter implements Predicate<Symbol> {
2565
2566 Type site;
2567
2568 ClashFilter(Type site) {
2569 this.site = site;
2570 }
2571
2572 boolean shouldSkip(Symbol s) {
2573 return (s.flags() & CLASH) != 0 &&
2574 s.owner == site.tsym;
2575 }
2576
2577 @Override
2578 public boolean test(Symbol s) {
2579 return s.kind == MTH &&
2580 (s.flags() & SYNTHETIC) == 0 &&
2581 !shouldSkip(s) &&
2582 s.isInheritedIn(site.tsym, types) &&
2583 !s.isConstructor();
2584 }
2585 }
2586
2587 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2588 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2589 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2590 Assert.check(m.kind == MTH);
2591 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2592 if (prov.size() > 1) {
2593 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2594 ListBuffer<Symbol> defaults = new ListBuffer<>();
2595 for (MethodSymbol provSym : prov) {
2596 if ((provSym.flags() & DEFAULT) != 0) {
2597 defaults = defaults.append(provSym);
2598 } else if ((provSym.flags() & ABSTRACT) != 0) {
2599 abstracts = abstracts.append(provSym);
2600 }
2601 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2602 //strong semantics - issue an error if two sibling interfaces
2603 //have two override-equivalent defaults - or if one is abstract
2604 //and the other is default
2605 Fragment diagKey;
2606 Symbol s1 = defaults.first();
2607 Symbol s2;
2608 if (defaults.size() > 1) {
2609 s2 = defaults.toList().tail.head;
2610 diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site,
2611 m.name, types.memberType(site, m).getParameterTypes(),
2612 s1.location(), s2.location());
2613
2614 } else {
2615 s2 = abstracts.first();
2616 diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site,
2617 m.name, types.memberType(site, m).getParameterTypes(),
2618 s1.location(), s2.location());
2619 }
2620 log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey));
2621 break;
2622 }
2623 }
2624 }
2625 }
2626 }
2627
2628 //where
2629 private class DefaultMethodClashFilter implements Predicate<Symbol> {
2630
2631 Type site;
2632
2633 DefaultMethodClashFilter(Type site) {
2634 this.site = site;
2635 }
2636
2637 @Override
2638 public boolean test(Symbol s) {
2639 return s.kind == MTH &&
2640 (s.flags() & DEFAULT) != 0 &&
2641 s.isInheritedIn(site.tsym, types) &&
2642 !s.isConstructor();
2643 }
2644 }
2645
2646 /** Report warnings for potentially ambiguous method declarations in the given site. */
2647 void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) {
2648
2649 // Skip if warning not enabled
2650 if (!lint.isEnabled(LintCategory.OVERLOADS))
2651 return;
2652
2653 // Gather all of site's methods, including overridden methods, grouped by name (except Object methods)
2654 List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site,
2655 new PotentiallyAmbiguousFilter(site), ArrayList::new);
2656
2657 // Build the predicate that determines if site is responsible for an ambiguity
2658 BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups);
2659
2660 // Now remove overridden methods from each group, leaving only site's actual members
2661 methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false)));
2662
2663 // Allow site's own declared methods (only) to apply @SuppressWarnings("overloads")
2664 methodGroups.forEach(list -> list.removeIf(
2665 m -> m.owner == site.tsym && !lint.augment(m).isEnabled(LintCategory.OVERLOADS)));
2666
2667 // Warn about ambiguous overload method pairs for which site is responsible
2668 methodGroups.forEach(list -> compareAndRemove(list, (m1, m2) -> {
2669
2670 // See if this is an ambiguous overload for which "site" is responsible
2671 if (!potentiallyAmbiguousOverload(site, m1, m2) || !responsible.test(m1, m2))
2672 return 0;
2673
2674 // Locate the warning at one of the methods, if possible
2675 DiagnosticPosition pos =
2676 m1.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m1, tree) :
2677 m2.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m2, tree) :
2678 tree.pos();
2679
2680 // Log the warning
2681 log.warning(pos,
2682 LintWarnings.PotentiallyAmbiguousOverload(
2683 m1.asMemberOf(site, types), m1.location(),
2684 m2.asMemberOf(site, types), m2.location()));
2685
2686 // Don't warn again for either of these two methods
2687 return FIRST | SECOND;
2688 }));
2689 }
2690
2691 /** Build a predicate that determines, given two methods that are members of the given class,
2692 * whether the class should be held "responsible" if the methods are potentially ambiguous.
2693 *
2694 * Sometimes ambiguous methods are unavoidable because they're inherited from a supertype.
2695 * For example, any subtype of Spliterator.OfInt will have ambiguities for both
2696 * forEachRemaining() and tryAdvance() (in both cases the overloads are IntConsumer and
2697 * Consumer<? super Integer>). So we only want to "blame" a class when that class is
2698 * itself responsible for creating the ambiguity. We declare that a class C is "responsible"
2699 * for the ambiguity between two methods m1 and m2 if there is no direct supertype T of C
2700 * such that m1 and m2, or some overrides thereof, both exist in T and are ambiguous in T.
2701 * As an optimization, we first check if either method is declared in C and does not override
2702 * any other methods; in this case the class is definitely responsible.
2703 */
2704 BiPredicate<MethodSymbol, MethodSymbol> buildResponsiblePredicate(Type site,
2705 List<? extends Collection<MethodSymbol>> methodGroups) {
2706
2707 // Define the "overrides" predicate
2708 BiPredicate<MethodSymbol, MethodSymbol> overrides = (m1, m2) -> m1.overrides(m2, site.tsym, types, false);
2709
2710 // Map each method declared in site to a list of the supertype method(s) it directly overrides
2711 HashMap<MethodSymbol, ArrayList<MethodSymbol>> overriddenMethodsMap = new HashMap<>();
2712 methodGroups.forEach(list -> {
2713 for (MethodSymbol m : list) {
2714
2715 // Skip methods not declared in site
2716 if (m.owner != site.tsym)
2717 continue;
2718
2719 // Gather all supertype methods overridden by m, directly or indirectly
2720 ArrayList<MethodSymbol> overriddenMethods = list.stream()
2721 .filter(m2 -> m2 != m && overrides.test(m, m2))
2722 .collect(Collectors.toCollection(ArrayList::new));
2723
2724 // Eliminate non-direct overrides
2725 removePreempted(overriddenMethods, overrides);
2726
2727 // Add to map
2728 overriddenMethodsMap.put(m, overriddenMethods);
2729 }
2730 });
2731
2732 // Build the predicate
2733 return (m1, m2) -> {
2734
2735 // Get corresponding supertype methods (if declared in site)
2736 java.util.List<MethodSymbol> overriddenMethods1 = overriddenMethodsMap.get(m1);
2737 java.util.List<MethodSymbol> overriddenMethods2 = overriddenMethodsMap.get(m2);
2738
2739 // Quick check for the case where a method was added by site itself
2740 if (overriddenMethods1 != null && overriddenMethods1.isEmpty())
2741 return true;
2742 if (overriddenMethods2 != null && overriddenMethods2.isEmpty())
2743 return true;
2744
2745 // Get each method's corresponding method(s) from supertypes of site
2746 java.util.List<MethodSymbol> supertypeMethods1 = overriddenMethods1 != null ?
2747 overriddenMethods1 : Collections.singletonList(m1);
2748 java.util.List<MethodSymbol> supertypeMethods2 = overriddenMethods2 != null ?
2749 overriddenMethods2 : Collections.singletonList(m2);
2750
2751 // See if we can blame some direct supertype instead
2752 return types.directSupertypes(site).stream()
2753 .filter(stype -> stype != syms.objectType)
2754 .map(stype -> stype.tsym.type) // view supertype in its original form
2755 .noneMatch(stype -> {
2756 for (MethodSymbol sm1 : supertypeMethods1) {
2757 if (!types.isSubtype(types.erasure(stype), types.erasure(sm1.owner.type)))
2758 continue;
2759 for (MethodSymbol sm2 : supertypeMethods2) {
2760 if (!types.isSubtype(types.erasure(stype), types.erasure(sm2.owner.type)))
2761 continue;
2762 if (potentiallyAmbiguousOverload(stype, sm1, sm2))
2763 return true;
2764 }
2765 }
2766 return false;
2767 });
2768 };
2769 }
2770
2771 /** Gather all of site's methods, including overridden methods, grouped and sorted by name,
2772 * after applying the given filter.
2773 */
2774 <C extends Collection<MethodSymbol>> List<C> methodsGroupedByName(Type site,
2775 Predicate<Symbol> filter, Supplier<? extends C> groupMaker) {
2776 Iterable<Symbol> symbols = types.membersClosure(site, false).getSymbols(filter, RECURSIVE);
2777 return StreamSupport.stream(symbols.spliterator(), false)
2778 .map(MethodSymbol.class::cast)
2779 .collect(Collectors.groupingBy(m -> m.name, Collectors.toCollection(groupMaker)))
2780 .entrySet()
2781 .stream()
2782 .sorted(Comparator.comparing(e -> e.getKey().toString()))
2783 .map(Map.Entry::getValue)
2784 .collect(List.collector());
2785 }
2786
2787 /** Compare elements in a list pair-wise in order to remove some of them.
2788 * @param list mutable list of items
2789 * @param comparer returns flag bit(s) to remove FIRST and/or SECOND
2790 */
2791 <T> void compareAndRemove(java.util.List<T> list, ToIntBiFunction<? super T, ? super T> comparer) {
2792 for (int index1 = 0; index1 < list.size() - 1; index1++) {
2793 T item1 = list.get(index1);
2794 for (int index2 = index1 + 1; index2 < list.size(); index2++) {
2795 T item2 = list.get(index2);
2796 int flags = comparer.applyAsInt(item1, item2);
2797 if ((flags & SECOND) != 0)
2798 list.remove(index2--); // remove item2
2799 if ((flags & FIRST) != 0) {
2800 list.remove(index1--); // remove item1
2801 break;
2802 }
2803 }
2804 }
2805 }
2806
2807 /** Remove elements in a list that are preempted by some other element in the list.
2808 * @param list mutable list of items
2809 * @param preempts decides if one item preempts another, causing the second one to be removed
2810 */
2811 <T> void removePreempted(java.util.List<T> list, BiPredicate<? super T, ? super T> preempts) {
2812 compareAndRemove(list, (item1, item2) -> {
2813 int flags = 0;
2814 if (preempts.test(item1, item2))
2815 flags |= SECOND;
2816 if (preempts.test(item2, item1))
2817 flags |= FIRST;
2818 return flags;
2819 });
2820 }
2821
2822 /** Filters method candidates for the "potentially ambiguous method" check */
2823 class PotentiallyAmbiguousFilter extends ClashFilter {
2824
2825 PotentiallyAmbiguousFilter(Type site) {
2826 super(site);
2827 }
2828
2829 @Override
2830 boolean shouldSkip(Symbol s) {
2831 return s.owner.type.tsym == syms.objectType.tsym || super.shouldSkip(s);
2832 }
2833 }
2834
2835 /**
2836 * Report warnings for potentially ambiguous method declarations. Two declarations
2837 * are potentially ambiguous if they feature two unrelated functional interface
2838 * in same argument position (in which case, a call site passing an implicit
2839 * lambda would be ambiguous). This assumes they already have the same name.
2840 */
2841 boolean potentiallyAmbiguousOverload(Type site, MethodSymbol msym1, MethodSymbol msym2) {
2842 Assert.check(msym1.name == msym2.name);
2843 if (msym1 == msym2)
2844 return false;
2845 Type mt1 = types.memberType(site, msym1);
2846 Type mt2 = types.memberType(site, msym2);
2847 //if both generic methods, adjust type variables
2848 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2849 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2850 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2851 }
2852 //expand varargs methods if needed
2853 int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2854 List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2855 List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2856 //if arities don't match, exit
2857 if (args1.length() != args2.length())
2858 return false;
2859 boolean potentiallyAmbiguous = false;
2860 while (args1.nonEmpty() && args2.nonEmpty()) {
2861 Type s = args1.head;
2862 Type t = args2.head;
2863 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2864 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2865 types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2866 types.findDescriptorType(s).getParameterTypes().length() ==
2867 types.findDescriptorType(t).getParameterTypes().length()) {
2868 potentiallyAmbiguous = true;
2869 } else {
2870 return false;
2871 }
2872 }
2873 args1 = args1.tail;
2874 args2 = args2.tail;
2875 }
2876 return potentiallyAmbiguous;
2877 }
2878
2879 // Apply special flag "-XDwarnOnAccessToMembers" which turns on just this particular warning for all types of access
2880 void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2881 if (warnOnAnyAccessToMembers || isLambda)
2882 checkAccessFromSerializableElementInner(tree, isLambda);
2883 }
2884
2885 private void checkAccessFromSerializableElementInner(final JCTree tree, boolean isLambda) {
2886 Symbol sym = TreeInfo.symbol(tree);
2887 if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2888 return;
2889 }
2890
2891 if (sym.kind == VAR) {
2892 if ((sym.flags() & PARAMETER) != 0 ||
2893 sym.isDirectlyOrIndirectlyLocal() ||
2894 sym.name == names._this ||
2895 sym.name == names._super) {
2896 return;
2897 }
2898 }
2899
2900 if (!types.isSubtype(sym.owner.type, syms.serializableType) && isEffectivelyNonPublic(sym)) {
2901 DiagnosticFlag flag = warnOnAnyAccessToMembers ? DiagnosticFlag.DEFAULT_ENABLED : null;
2902 if (isLambda) {
2903 if (belongsToRestrictedPackage(sym)) {
2904 log.warning(flag, tree.pos(), LintWarnings.AccessToMemberFromSerializableLambda(sym));
2905 }
2906 } else {
2907 log.warning(flag, tree.pos(), LintWarnings.AccessToMemberFromSerializableElement(sym));
2908 }
2909 }
2910 }
2911
2912 private boolean isEffectivelyNonPublic(Symbol sym) {
2913 if (sym.packge() == syms.rootPackage) {
2914 return false;
2915 }
2916
2917 while (sym.kind != PCK) {
2918 if ((sym.flags() & PUBLIC) == 0) {
2919 return true;
2920 }
2921 sym = sym.owner;
2922 }
2923 return false;
2924 }
2925
2926 private boolean belongsToRestrictedPackage(Symbol sym) {
2927 String fullName = sym.packge().fullname.toString();
2928 return fullName.startsWith("java.") ||
2929 fullName.startsWith("javax.") ||
2930 fullName.startsWith("sun.") ||
2931 fullName.contains(".internal.");
2932 }
2933
2934 /** Check that class c does not implement directly or indirectly
2935 * the same parameterized interface with two different argument lists.
2936 * @param pos Position to be used for error reporting.
2937 * @param type The type whose interfaces are checked.
2938 */
2939 void checkClassBounds(DiagnosticPosition pos, Type type) {
2940 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2941 }
2942 //where
2943 /** Enter all interfaces of type `type' into the hash table `seensofar'
2944 * with their class symbol as key and their type as value. Make
2945 * sure no class is entered with two different types.
2946 */
2947 void checkClassBounds(DiagnosticPosition pos,
2948 Map<TypeSymbol,Type> seensofar,
2949 Type type) {
2950 if (type.isErroneous()) return;
2951 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2952 Type it = l.head;
2953 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5
2954
2955 Type oldit = seensofar.put(it.tsym, it);
2956 if (oldit != null) {
2957 List<Type> oldparams = oldit.allparams();
2958 List<Type> newparams = it.allparams();
2959 if (!types.containsTypeEquivalent(oldparams, newparams))
2960 log.error(pos,
2961 Errors.CantInheritDiffArg(it.tsym,
2962 Type.toString(oldparams),
2963 Type.toString(newparams)));
2964 }
2965 checkClassBounds(pos, seensofar, it);
2966 }
2967 Type st = types.supertype(type);
2968 if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4
2969 if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2970 }
2971
2972 /** Enter interface into into set.
2973 * If it existed already, issue a "repeated interface" error.
2974 */
2975 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Symbol> its) {
2976 if (its.contains(it.tsym))
2977 log.error(pos, Errors.RepeatedInterface);
2978 else {
2979 its.add(it.tsym);
2980 }
2981 }
2982
2983 /* *************************************************************************
2984 * Check annotations
2985 **************************************************************************/
2986
2987 /**
2988 * Recursively validate annotations values
2989 */
2990 void validateAnnotationTree(JCTree tree) {
2991 class AnnotationValidator extends TreeScanner {
2992 @Override
2993 public void visitAnnotation(JCAnnotation tree) {
2994 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) {
2995 super.visitAnnotation(tree);
2996 validateAnnotation(tree);
2997 }
2998 }
2999 }
3000 tree.accept(new AnnotationValidator());
3001 }
3002
3003 /**
3004 * {@literal
3005 * Annotation types are restricted to primitives, String, an
3006 * enum, an annotation, Class, Class<?>, Class<? extends
3007 * Anything>, arrays of the preceding.
3008 * }
3009 */
3010 void validateAnnotationType(JCTree restype) {
3011 // restype may be null if an error occurred, so don't bother validating it
3012 if (restype != null) {
3013 validateAnnotationType(restype.pos(), restype.type);
3014 }
3015 }
3016
3017 void validateAnnotationType(DiagnosticPosition pos, Type type) {
3018 if (type.isPrimitive()) return;
3019 if (types.isSameType(type, syms.stringType)) return;
3020 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
3021 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
3022 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
3023 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
3024 validateAnnotationType(pos, types.elemtype(type));
3025 return;
3026 }
3027 log.error(pos, Errors.InvalidAnnotationMemberType);
3028 }
3029
3030 /**
3031 * "It is also a compile-time error if any method declared in an
3032 * annotation type has a signature that is override-equivalent to
3033 * that of any public or protected method declared in class Object
3034 * or in the interface annotation.Annotation."
3035 *
3036 * @jls 9.6 Annotation Types
3037 */
3038 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
3039 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
3040 Scope s = sup.tsym.members();
3041 for (Symbol sym : s.getSymbolsByName(m.name)) {
3042 if (sym.kind == MTH &&
3043 (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
3044 types.overrideEquivalent(m.type, sym.type))
3045 log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup));
3046 }
3047 }
3048 }
3049
3050 /** Check the annotations of a symbol.
3051 */
3052 public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) {
3053 for (JCAnnotation a : annotations)
3054 validateAnnotation(a, declarationTree, s);
3055 }
3056
3057 /** Check the type annotations.
3058 */
3059 public void validateTypeAnnotations(List<JCAnnotation> annotations, Symbol s, boolean isTypeParameter) {
3060 for (JCAnnotation a : annotations)
3061 validateTypeAnnotation(a, s, isTypeParameter);
3062 }
3063
3064 /** Check an annotation of a symbol.
3065 */
3066 private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) {
3067 /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method,
3068 * this can impact in particular records for which annotations are forcibly propagated.
3069 */
3070 validateAnnotationTree(a);
3071 boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord());
3072
3073 boolean isRecordField = (s.flags_field & RECORD) != 0 &&
3074 declarationTree.hasTag(VARDEF) &&
3075 s.owner.kind == TYP;
3076
3077 if (isRecordField) {
3078 // first we need to check if the annotation is applicable to records
3079 Name[] targets = getTargetNames(a);
3080 boolean appliesToRecords = false;
3081 for (Name target : targets) {
3082 appliesToRecords =
3083 target == names.FIELD ||
3084 target == names.PARAMETER ||
3085 target == names.METHOD ||
3086 target == names.TYPE_USE ||
3087 target == names.RECORD_COMPONENT;
3088 if (appliesToRecords) {
3089 break;
3090 }
3091 }
3092 if (!appliesToRecords) {
3093 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3094 } else {
3095 /* lets now find the annotations in the field that are targeted to record components and append them to
3096 * the corresponding record component
3097 */
3098 ClassSymbol recordClass = (ClassSymbol) s.owner;
3099 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s);
3100 SymbolMetadata metadata = rc.getMetadata();
3101 if (metadata == null || metadata.isEmpty()) {
3102 /* if not is empty then we have already been here, which is the case if multiple annotations are applied
3103 * to the record component declaration
3104 */
3105 rc.appendAttributes(s.getRawAttributes().stream().filter(anno ->
3106 Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT)
3107 ).collect(List.collector()));
3108
3109 JCVariableDecl fieldAST = (JCVariableDecl) declarationTree;
3110 for (JCAnnotation fieldAnnot : fieldAST.mods.annotations) {
3111 for (JCAnnotation rcAnnot : rc.declarationFor().mods.annotations) {
3112 if (rcAnnot.pos == fieldAnnot.pos) {
3113 rcAnnot.setType(fieldAnnot.type);
3114 break;
3115 }
3116 }
3117 }
3118
3119 /* At this point, we used to carry over any type annotations from the VARDEF to the record component, but
3120 * that is problematic, since we get here only when *some* annotation is applied to the SE5 (declaration)
3121 * annotation location, inadvertently failing to carry over the type annotations when the VarDef has no
3122 * annotations in the SE5 annotation location.
3123 *
3124 * Now type annotations are assigned to record components in a method that would execute irrespective of
3125 * whether there are SE5 annotations on a VarDef viz com.sun.tools.javac.code.TypeAnnotations.TypeAnnotationPositions.visitVarDef
3126 */
3127 }
3128 }
3129 }
3130
3131 /* the section below is tricky. Annotations applied to record components are propagated to the corresponding
3132 * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has
3133 * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated
3134 * there is no enough information to propagate only the right annotations. So all the annotations are propagated
3135 * to all the possible locations.
3136 *
3137 * At this point we need to remove all the annotations that are not in place before going on with the annotation
3138 * party. On top of the above there is the issue that there is no AST representing record components, just symbols
3139 * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it
3140 * was both a field and a record component.
3141 *
3142 * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers
3143 * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could
3144 * be see by annotation processors.
3145 *
3146 * The metadata contains both type annotations and declaration annotations. At this point of the game we don't
3147 * need to care about type annotations, they are all in the right place. But we could need to remove declaration
3148 * annotations. So for declaration annotations if they are not applicable to the record member, excluding type
3149 * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not
3150 * applicable either as type annotation and or declaration annotation, only in that case it will be removed.
3151 *
3152 * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for
3153 * further inspection by annotation processors.
3154 *
3155 * For example:
3156 *
3157 * import java.lang.annotation.*;
3158 *
3159 * @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT})
3160 * @Retention(RetentionPolicy.RUNTIME)
3161 * @interface Anno { }
3162 *
3163 * record R(@Anno String s) {}
3164 *
3165 * at this point we will have for the case of the generated field:
3166 * - @Anno in the modifier
3167 * - @Anno as a type annotation
3168 * - @Anno as a declaration annotation
3169 *
3170 * the last one should be removed because the annotation has not FIELD as target but it was applied as a
3171 * declaration annotation because the field was being treated both as a field and as a record component
3172 * as we have already copied the annotations to the record component, now the field doesn't need to hold
3173 * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it
3174 * is applicable as a type annotation to the type of the field.
3175 */
3176
3177 if (a.type.tsym.isAnnotationType()) {
3178 Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s);
3179 if (!applicableTargetsOp.isEmpty()) {
3180 Set<Name> applicableTargets = applicableTargetsOp.get();
3181 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() ||
3182 applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE);
3183 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0;
3184 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly;
3185
3186 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) {
3187 if (isCompRecordElementWithNonApplicableDeclAnno) {
3188 /* so we have found an annotation that is not applicable to a record member that was generated by the
3189 * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations
3190 * that are not applicable to the given record member
3191 */
3192 JCModifiers modifiers = TreeInfo.getModifiers(declarationTree);
3193 /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as
3194 * it could be a type annotation
3195 */
3196 if (modifiers != null && applicableTargets.isEmpty()) {
3197 ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>();
3198 for (JCAnnotation anno : modifiers.annotations) {
3199 if (anno != a) {
3200 newAnnotations.add(anno);
3201 }
3202 }
3203 modifiers.annotations = newAnnotations.toList();
3204 }
3205 // now lets remove it from the symbol
3206 s.getMetadata().removeDeclarationMetadata(a.attribute);
3207 } else {
3208 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3209 }
3210 }
3211 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor,
3212 * then this is an error as we know that no compiler generated accessor will be a varargs
3213 * method, better to fail asap
3214 */
3215 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) {
3216 log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s)));
3217 }
3218 }
3219 }
3220
3221 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3222 if (s.kind != TYP) {
3223 log.error(a.pos(), Errors.BadFunctionalIntfAnno);
3224 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
3225 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s)));
3226 }
3227 }
3228 }
3229
3230 public void validateTypeAnnotation(JCAnnotation a, Symbol s, boolean isTypeParameter) {
3231 Assert.checkNonNull(a.type);
3232 // we just want to validate that the anotation doesn't have any wrong target
3233 if (s != null) getApplicableTargets(a, s);
3234 validateAnnotationTree(a);
3235
3236 if (a.hasTag(TYPE_ANNOTATION) &&
3237 !a.annotationType.type.isErroneous() &&
3238 !isTypeAnnotation(a, isTypeParameter)) {
3239 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
3240 }
3241 }
3242
3243 /**
3244 * Validate the proposed container 'repeatable' on the
3245 * annotation type symbol 's'. Report errors at position
3246 * 'pos'.
3247 *
3248 * @param s The (annotation)type declaration annotated with a @Repeatable
3249 * @param repeatable the @Repeatable on 's'
3250 * @param pos where to report errors
3251 */
3252 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
3253 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
3254
3255 Type t = null;
3256 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
3257 if (!l.isEmpty()) {
3258 Assert.check(l.head.fst.name == names.value);
3259 if (l.head.snd instanceof Attribute.Class) {
3260 t = ((Attribute.Class)l.head.snd).getValue();
3261 }
3262 }
3263
3264 if (t == null) {
3265 // errors should already have been reported during Annotate
3266 return;
3267 }
3268
3269 validateValue(t.tsym, s, pos);
3270 validateRetention(t.tsym, s, pos);
3271 validateDocumented(t.tsym, s, pos);
3272 validateInherited(t.tsym, s, pos);
3273 validateTarget(t.tsym, s, pos);
3274 validateDefault(t.tsym, pos);
3275 }
3276
3277 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3278 Symbol sym = container.members().findFirst(names.value);
3279 if (sym != null && sym.kind == MTH) {
3280 MethodSymbol m = (MethodSymbol) sym;
3281 Type ret = m.getReturnType();
3282 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
3283 log.error(pos,
3284 Errors.InvalidRepeatableAnnotationValueReturn(container,
3285 ret,
3286 types.makeArrayType(contained.type)));
3287 }
3288 } else {
3289 log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container));
3290 }
3291 }
3292
3293 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3294 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
3295 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
3296
3297 boolean error = false;
3298 switch (containedRetention) {
3299 case RUNTIME:
3300 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
3301 error = true;
3302 }
3303 break;
3304 case CLASS:
3305 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
3306 error = true;
3307 }
3308 }
3309 if (error ) {
3310 log.error(pos,
3311 Errors.InvalidRepeatableAnnotationRetention(container,
3312 containerRetention.name(),
3313 contained,
3314 containedRetention.name()));
3315 }
3316 }
3317
3318 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3319 if (contained.attribute(syms.documentedType.tsym) != null) {
3320 if (container.attribute(syms.documentedType.tsym) == null) {
3321 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained));
3322 }
3323 }
3324 }
3325
3326 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3327 if (contained.attribute(syms.inheritedType.tsym) != null) {
3328 if (container.attribute(syms.inheritedType.tsym) == null) {
3329 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained));
3330 }
3331 }
3332 }
3333
3334 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3335 // The set of targets the container is applicable to must be a subset
3336 // (with respect to annotation target semantics) of the set of targets
3337 // the contained is applicable to. The target sets may be implicit or
3338 // explicit.
3339
3340 Set<Name> containerTargets;
3341 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3342 if (containerTarget == null) {
3343 containerTargets = getDefaultTargetSet();
3344 } else {
3345 containerTargets = new HashSet<>();
3346 for (Attribute app : containerTarget.values) {
3347 if (!(app instanceof Attribute.Enum attributeEnum)) {
3348 continue; // recovery
3349 }
3350 containerTargets.add(attributeEnum.value.name);
3351 }
3352 }
3353
3354 Set<Name> containedTargets;
3355 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3356 if (containedTarget == null) {
3357 containedTargets = getDefaultTargetSet();
3358 } else {
3359 containedTargets = new HashSet<>();
3360 for (Attribute app : containedTarget.values) {
3361 if (!(app instanceof Attribute.Enum attributeEnum)) {
3362 continue; // recovery
3363 }
3364 containedTargets.add(attributeEnum.value.name);
3365 }
3366 }
3367
3368 if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3369 log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained));
3370 }
3371 }
3372
3373 /* get a set of names for the default target */
3374 private Set<Name> getDefaultTargetSet() {
3375 if (defaultTargets == null) {
3376 defaultTargets = Set.of(defaultTargetMetaInfo());
3377 }
3378
3379 return defaultTargets;
3380 }
3381 private Set<Name> defaultTargets;
3382
3383
3384 /** Checks that s is a subset of t, with respect to ElementType
3385 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3386 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3387 * TYPE_PARAMETER}.
3388 */
3389 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3390 // Check that all elements in s are present in t
3391 for (Name n2 : s) {
3392 boolean currentElementOk = false;
3393 for (Name n1 : t) {
3394 if (n1 == n2) {
3395 currentElementOk = true;
3396 break;
3397 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3398 currentElementOk = true;
3399 break;
3400 } else if (n1 == names.TYPE_USE &&
3401 (n2 == names.TYPE ||
3402 n2 == names.ANNOTATION_TYPE ||
3403 n2 == names.TYPE_PARAMETER)) {
3404 currentElementOk = true;
3405 break;
3406 }
3407 }
3408 if (!currentElementOk)
3409 return false;
3410 }
3411 return true;
3412 }
3413
3414 private void validateDefault(Symbol container, DiagnosticPosition pos) {
3415 // validate that all other elements of containing type has defaults
3416 Scope scope = container.members();
3417 for(Symbol elm : scope.getSymbols()) {
3418 if (elm.name != names.value &&
3419 elm.kind == MTH &&
3420 ((MethodSymbol)elm).defaultValue == null) {
3421 log.error(pos,
3422 Errors.InvalidRepeatableAnnotationElemNondefault(container, elm));
3423 }
3424 }
3425 }
3426
3427 /** Is s a method symbol that overrides a method in a superclass? */
3428 boolean isOverrider(Symbol s) {
3429 if (s.kind != MTH || s.isStatic())
3430 return false;
3431 MethodSymbol m = (MethodSymbol)s;
3432 TypeSymbol owner = (TypeSymbol)m.owner;
3433 for (Type sup : types.closure(owner.type)) {
3434 if (sup == owner.type)
3435 continue; // skip "this"
3436 Scope scope = sup.tsym.members();
3437 for (Symbol sym : scope.getSymbolsByName(m.name)) {
3438 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3439 return true;
3440 }
3441 }
3442 return false;
3443 }
3444
3445 /** Is the annotation applicable to types? */
3446 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3447 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3448 return (targets == null) ?
3449 (Feature.NO_TARGET_ANNOTATION_APPLICABILITY.allowedInSource(source) && isTypeParameter) :
3450 targets.stream()
3451 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3452 }
3453 //where
3454 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3455 Attribute.Enum e = (Attribute.Enum)a;
3456 return (e.value.name == names.TYPE_USE ||
3457 (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3458 }
3459
3460 /** Is the annotation applicable to the symbol? */
3461 Name[] getTargetNames(JCAnnotation a) {
3462 return getTargetNames(a.annotationType.type.tsym);
3463 }
3464
3465 public Name[] getTargetNames(TypeSymbol annoSym) {
3466 Attribute.Array arr = getAttributeTargetAttribute(annoSym);
3467 Name[] targets;
3468 if (arr == null) {
3469 targets = defaultTargetMetaInfo();
3470 } else {
3471 // TODO: can we optimize this?
3472 targets = new Name[arr.values.length];
3473 for (int i=0; i<arr.values.length; ++i) {
3474 Attribute app = arr.values[i];
3475 if (!(app instanceof Attribute.Enum attributeEnum)) {
3476 return new Name[0];
3477 }
3478 targets[i] = attributeEnum.value.name;
3479 }
3480 }
3481 return targets;
3482 }
3483
3484 boolean annotationApplicable(JCAnnotation a, Symbol s) {
3485 Optional<Set<Name>> targets = getApplicableTargets(a, s);
3486 /* the optional could be empty if the annotation is unknown in that case
3487 * we return that it is applicable and if it is erroneous that should imply
3488 * an error at the declaration site
3489 */
3490 return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty();
3491 }
3492
3493 Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) {
3494 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3495 Name[] targets;
3496 Set<Name> applicableTargets = new HashSet<>();
3497
3498 if (arr == null) {
3499 targets = defaultTargetMetaInfo();
3500 } else {
3501 // TODO: can we optimize this?
3502 targets = new Name[arr.values.length];
3503 for (int i=0; i<arr.values.length; ++i) {
3504 Attribute app = arr.values[i];
3505 if (!(app instanceof Attribute.Enum attributeEnum)) {
3506 // recovery
3507 return Optional.empty();
3508 }
3509 targets[i] = attributeEnum.value.name;
3510 }
3511 }
3512 for (Name target : targets) {
3513 if (target == names.TYPE) {
3514 if (s.kind == TYP)
3515 applicableTargets.add(names.TYPE);
3516 } else if (target == names.FIELD) {
3517 if (s.kind == VAR && s.owner.kind != MTH)
3518 applicableTargets.add(names.FIELD);
3519 } else if (target == names.RECORD_COMPONENT) {
3520 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3521 applicableTargets.add(names.RECORD_COMPONENT);
3522 }
3523 } else if (target == names.METHOD) {
3524 if (s.kind == MTH && !s.isConstructor())
3525 applicableTargets.add(names.METHOD);
3526 } else if (target == names.PARAMETER) {
3527 if (s.kind == VAR &&
3528 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3529 applicableTargets.add(names.PARAMETER);
3530 }
3531 } else if (target == names.CONSTRUCTOR) {
3532 if (s.kind == MTH && s.isConstructor())
3533 applicableTargets.add(names.CONSTRUCTOR);
3534 } else if (target == names.LOCAL_VARIABLE) {
3535 if (s.kind == VAR && s.owner.kind == MTH &&
3536 (s.flags() & PARAMETER) == 0) {
3537 applicableTargets.add(names.LOCAL_VARIABLE);
3538 }
3539 } else if (target == names.ANNOTATION_TYPE) {
3540 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3541 applicableTargets.add(names.ANNOTATION_TYPE);
3542 }
3543 } else if (target == names.PACKAGE) {
3544 if (s.kind == PCK)
3545 applicableTargets.add(names.PACKAGE);
3546 } else if (target == names.TYPE_USE) {
3547 if (s.kind == VAR &&
3548 (s.flags() & Flags.VAR_VARIABLE) != 0 &&
3549 (!Feature.TYPE_ANNOTATIONS_ON_VAR_LAMBDA_PARAMETER.allowedInSource(source) ||
3550 ((s.flags() & Flags.LAMBDA_PARAMETER) == 0))) {
3551 //cannot type annotate implicitly typed locals
3552 continue;
3553 } else if (s.kind == TYP || s.kind == VAR ||
3554 (s.kind == MTH && !s.isConstructor() &&
3555 !s.type.getReturnType().hasTag(VOID)) ||
3556 (s.kind == MTH && s.isConstructor())) {
3557 applicableTargets.add(names.TYPE_USE);
3558 }
3559 } else if (target == names.TYPE_PARAMETER) {
3560 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3561 applicableTargets.add(names.TYPE_PARAMETER);
3562 } else if (target == names.MODULE) {
3563 if (s.kind == MDL)
3564 applicableTargets.add(names.MODULE);
3565 } else {
3566 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3567 return Optional.empty(); // Unknown ElementType
3568 }
3569 }
3570 return Optional.of(applicableTargets);
3571 }
3572
3573 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3574 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3575 if (atTarget == null) return null; // ok, is applicable
3576 Attribute atValue = atTarget.member(names.value);
3577 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3578 }
3579
3580 private Name[] dfltTargetMeta;
3581 private Name[] defaultTargetMetaInfo() {
3582 if (dfltTargetMeta == null) {
3583 ArrayList<Name> defaultTargets = new ArrayList<>();
3584 defaultTargets.add(names.PACKAGE);
3585 defaultTargets.add(names.TYPE);
3586 defaultTargets.add(names.FIELD);
3587 defaultTargets.add(names.METHOD);
3588 defaultTargets.add(names.CONSTRUCTOR);
3589 defaultTargets.add(names.ANNOTATION_TYPE);
3590 defaultTargets.add(names.LOCAL_VARIABLE);
3591 defaultTargets.add(names.PARAMETER);
3592 if (allowRecords) {
3593 defaultTargets.add(names.RECORD_COMPONENT);
3594 }
3595 if (allowModules) {
3596 defaultTargets.add(names.MODULE);
3597 }
3598 dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3599 }
3600 return dfltTargetMeta;
3601 }
3602
3603 /** Check an annotation value.
3604 *
3605 * @param a The annotation tree to check
3606 * @return true if this annotation tree is valid, otherwise false
3607 */
3608 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3609 boolean res = false;
3610 final Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
3611 try {
3612 res = validateAnnotation(a);
3613 } finally {
3614 log.popDiagnosticHandler(diagHandler);
3615 }
3616 return res;
3617 }
3618
3619 private boolean validateAnnotation(JCAnnotation a) {
3620 boolean isValid = true;
3621 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3622
3623 // collect an inventory of the annotation elements
3624 Set<MethodSymbol> elements = metadata.getAnnotationElements();
3625
3626 // remove the ones that are assigned values
3627 for (JCTree arg : a.args) {
3628 if (!arg.hasTag(ASSIGN)) continue; // recovery
3629 JCAssign assign = (JCAssign)arg;
3630 Symbol m = TreeInfo.symbol(assign.lhs);
3631 if (m == null || m.type.isErroneous()) continue;
3632 if (!elements.remove(m)) {
3633 isValid = false;
3634 log.error(assign.lhs.pos(),
3635 Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3636 }
3637 }
3638
3639 // all the remaining ones better have default values
3640 List<Name> missingDefaults = List.nil();
3641 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3642 for (MethodSymbol m : elements) {
3643 if (m.type.isErroneous())
3644 continue;
3645
3646 if (!membersWithDefault.contains(m))
3647 missingDefaults = missingDefaults.append(m.name);
3648 }
3649 missingDefaults = missingDefaults.reverse();
3650 if (missingDefaults.nonEmpty()) {
3651 isValid = false;
3652 Error errorKey = (missingDefaults.size() > 1)
3653 ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3654 : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3655 log.error(a.pos(), errorKey);
3656 }
3657
3658 return isValid && validateTargetAnnotationValue(a);
3659 }
3660
3661 /* Validate the special java.lang.annotation.Target annotation */
3662 boolean validateTargetAnnotationValue(JCAnnotation a) {
3663 // special case: java.lang.annotation.Target must not have
3664 // repeated values in its value member
3665 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3666 a.args.tail == null)
3667 return true;
3668
3669 boolean isValid = true;
3670 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3671 JCAssign assign = (JCAssign) a.args.head;
3672 Symbol m = TreeInfo.symbol(assign.lhs);
3673 if (m.name != names.value) return false;
3674 JCTree rhs = assign.rhs;
3675 if (!rhs.hasTag(NEWARRAY)) return false;
3676 JCNewArray na = (JCNewArray) rhs;
3677 Set<Symbol> targets = new HashSet<>();
3678 for (JCTree elem : na.elems) {
3679 if (!targets.add(TreeInfo.symbol(elem))) {
3680 isValid = false;
3681 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3682 }
3683 }
3684 return isValid;
3685 }
3686
3687 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3688 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3689 (s.flags() & DEPRECATED) != 0 &&
3690 !syms.deprecatedType.isErroneous() &&
3691 s.attribute(syms.deprecatedType.tsym) == null) {
3692 log.warning(pos, LintWarnings.MissingDeprecatedAnnotation);
3693 }
3694 // Note: @Deprecated has no effect on local variables, parameters and package decls.
3695 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3696 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3697 log.warning(pos, LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3698 }
3699 }
3700 }
3701
3702 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3703 checkDeprecated(() -> pos, other, s);
3704 }
3705
3706 void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3707 if (!importSuppression
3708 && (s.isDeprecatedForRemoval() || s.isDeprecated() && !other.isDeprecated())
3709 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3710 && s.kind != Kind.PCK) {
3711 warnDeprecated(pos.get(), s);
3712 }
3713 }
3714
3715 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3716 if ((s.flags() & PROPRIETARY) != 0) {
3717 log.warning(pos, Warnings.SunProprietary(s));
3718 }
3719 }
3720
3721 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3722 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3723 log.error(pos, Errors.NotInProfile(s, profile));
3724 }
3725 }
3726
3727 void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3728 checkPreview(pos, other, Type.noType, s);
3729 }
3730
3731 void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) {
3732 boolean sIsPreview;
3733 Symbol previewSymbol;
3734 if ((s.flags() & PREVIEW_API) != 0) {
3735 sIsPreview = true;
3736 previewSymbol= s;
3737 } else if ((s.kind == Kind.MTH || s.kind == Kind.VAR) &&
3738 site.tsym != null &&
3739 (site.tsym.flags() & PREVIEW_API) == 0 &&
3740 (s.owner.flags() & PREVIEW_API) != 0) {
3741 //calling a method, or using a field, whose owner is a preview, but
3742 //using a site that is not a preview. Also produce an error or warning:
3743 sIsPreview = true;
3744 previewSymbol = s.owner;
3745 } else {
3746 sIsPreview = false;
3747 previewSymbol = null;
3748 }
3749 if (sIsPreview && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) {
3750 if ((previewSymbol.flags() & PREVIEW_REFLECTIVE) == 0) {
3751 if (!preview.isEnabled()) {
3752 log.error(pos, Errors.IsPreview(s));
3753 } else {
3754 preview.markUsesPreview(pos);
3755 warnPreviewAPI(pos, LintWarnings.IsPreview(s));
3756 }
3757 } else {
3758 warnPreviewAPI(pos, LintWarnings.IsPreviewReflective(s));
3759 }
3760 }
3761 if (preview.declaredUsingPreviewFeature(s)) {
3762 if (preview.isEnabled()) {
3763 //for preview disabled do presumably so not need to do anything?
3764 //If "s" is compiled from source, then there was an error for it already;
3765 //if "s" is from classfile, there already was an error for the classfile.
3766 preview.markUsesPreview(pos);
3767 warnPreviewAPI(pos, LintWarnings.DeclaredUsingPreview(kindName(s), s));
3768 }
3769 }
3770 }
3771
3772 void checkRestricted(DiagnosticPosition pos, Symbol s) {
3773 if (s.kind == MTH && (s.flags() & RESTRICTED) != 0) {
3774 log.warning(pos, LintWarnings.RestrictedMethod(s.enclClass(), s));
3775 }
3776 }
3777
3778 /* *************************************************************************
3779 * Check for recursive annotation elements.
3780 **************************************************************************/
3781
3782 /** Check for cycles in the graph of annotation elements.
3783 */
3784 void checkNonCyclicElements(JCClassDecl tree) {
3785 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3786 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3787 try {
3788 tree.sym.flags_field |= LOCKED;
3789 for (JCTree def : tree.defs) {
3790 if (!def.hasTag(METHODDEF)) continue;
3791 JCMethodDecl meth = (JCMethodDecl)def;
3792 checkAnnotationResType(meth.pos(), meth.restype.type);
3793 }
3794 } finally {
3795 tree.sym.flags_field &= ~LOCKED;
3796 tree.sym.flags_field |= ACYCLIC_ANN;
3797 }
3798 }
3799
3800 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3801 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3802 return;
3803 if ((tsym.flags_field & LOCKED) != 0) {
3804 log.error(pos, Errors.CyclicAnnotationElement(tsym));
3805 return;
3806 }
3807 try {
3808 tsym.flags_field |= LOCKED;
3809 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3810 if (s.kind != MTH)
3811 continue;
3812 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3813 }
3814 } finally {
3815 tsym.flags_field &= ~LOCKED;
3816 tsym.flags_field |= ACYCLIC_ANN;
3817 }
3818 }
3819
3820 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3821 switch (type.getTag()) {
3822 case CLASS:
3823 if ((type.tsym.flags() & ANNOTATION) != 0)
3824 checkNonCyclicElementsInternal(pos, type.tsym);
3825 break;
3826 case ARRAY:
3827 checkAnnotationResType(pos, types.elemtype(type));
3828 break;
3829 default:
3830 break; // int etc
3831 }
3832 }
3833
3834 /* *************************************************************************
3835 * Check for cycles in the constructor call graph.
3836 **************************************************************************/
3837
3838 /** Check for cycles in the graph of constructors calling other
3839 * constructors.
3840 */
3841 void checkCyclicConstructors(JCClassDecl tree) {
3842 // use LinkedHashMap so we generate errors deterministically
3843 Map<Symbol,Symbol> callMap = new LinkedHashMap<>();
3844
3845 // enter each constructor this-call into the map
3846 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3847 if (!TreeInfo.isConstructor(l.head))
3848 continue;
3849 JCMethodDecl meth = (JCMethodDecl)l.head;
3850 JCMethodInvocation app = TreeInfo.findConstructorCall(meth);
3851 if (app != null && TreeInfo.name(app.meth) == names._this) {
3852 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3853 } else {
3854 meth.sym.flags_field |= ACYCLIC;
3855 }
3856 }
3857
3858 // Check for cycles in the map
3859 Symbol[] ctors = new Symbol[0];
3860 ctors = callMap.keySet().toArray(ctors);
3861 for (Symbol caller : ctors) {
3862 checkCyclicConstructor(tree, caller, callMap);
3863 }
3864 }
3865
3866 /** Look in the map to see if the given constructor is part of a
3867 * call cycle.
3868 */
3869 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3870 Map<Symbol,Symbol> callMap) {
3871 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3872 if ((ctor.flags_field & LOCKED) != 0) {
3873 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)),
3874 Errors.RecursiveCtorInvocation);
3875 } else {
3876 ctor.flags_field |= LOCKED;
3877 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3878 ctor.flags_field &= ~LOCKED;
3879 }
3880 ctor.flags_field |= ACYCLIC;
3881 }
3882 }
3883
3884 /* *************************************************************************
3885 * Verify the proper placement of super()/this() calls.
3886 *
3887 * - super()/this() may only appear in constructors
3888 * - There must be at most one super()/this() call per constructor
3889 * - The super()/this() call, if any, must be a top-level statement in the
3890 * constructor, i.e., not nested inside any other statement or block
3891 * - There must be no return statements prior to the super()/this() call
3892 **************************************************************************/
3893
3894 void checkSuperInitCalls(JCClassDecl tree) {
3895 new SuperThisChecker().check(tree);
3896 }
3897
3898 private class SuperThisChecker extends TreeScanner {
3899
3900 // Match this scan stack: 1=JCMethodDecl, 2=JCExpressionStatement, 3=JCMethodInvocation
3901 private static final int MATCH_SCAN_DEPTH = 3;
3902
3903 private boolean constructor; // is this method a constructor?
3904 private boolean firstStatement; // at the first statement in method?
3905 private JCReturn earlyReturn; // first return prior to the super()/init(), if any
3906 private Name initCall; // whichever of "super" or "init" we've seen already
3907 private int scanDepth; // current scan recursion depth in method body
3908
3909 public void check(JCClassDecl classDef) {
3910 scan(classDef.defs);
3911 }
3912
3913 @Override
3914 public void visitMethodDef(JCMethodDecl tree) {
3915 Assert.check(!constructor);
3916 Assert.check(earlyReturn == null);
3917 Assert.check(initCall == null);
3918 Assert.check(scanDepth == 1);
3919
3920 // Initialize state for this method
3921 constructor = TreeInfo.isConstructor(tree);
3922 try {
3923
3924 // Scan method body
3925 if (tree.body != null) {
3926 firstStatement = true;
3927 for (List<JCStatement> l = tree.body.stats; l.nonEmpty(); l = l.tail) {
3928 scan(l.head);
3929 firstStatement = false;
3930 }
3931 }
3932
3933 // Verify no 'return' seen prior to an explicit super()/this() call
3934 if (constructor && earlyReturn != null && initCall != null)
3935 log.error(earlyReturn.pos(), Errors.ReturnBeforeSuperclassInitialized);
3936 } finally {
3937 firstStatement = false;
3938 constructor = false;
3939 earlyReturn = null;
3940 initCall = null;
3941 }
3942 }
3943
3944 @Override
3945 public void scan(JCTree tree) {
3946 scanDepth++;
3947 try {
3948 super.scan(tree);
3949 } finally {
3950 scanDepth--;
3951 }
3952 }
3953
3954 @Override
3955 public void visitApply(JCMethodInvocation apply) {
3956 do {
3957
3958 // Is this a super() or this() call?
3959 Name methodName = TreeInfo.name(apply.meth);
3960 if (methodName != names._super && methodName != names._this)
3961 break;
3962
3963 // super()/this() calls must only appear in a constructor
3964 if (!constructor) {
3965 log.error(apply.pos(), Errors.CallMustOnlyAppearInCtor);
3966 break;
3967 }
3968
3969 // super()/this() calls must be a top level statement
3970 if (scanDepth != MATCH_SCAN_DEPTH) {
3971 log.error(apply.pos(), Errors.CtorCallsNotAllowedHere);
3972 break;
3973 }
3974
3975 // super()/this() calls must not appear more than once
3976 if (initCall != null) {
3977 log.error(apply.pos(), Errors.RedundantSuperclassInit);
3978 break;
3979 }
3980
3981 // If super()/this() isn't first, require flexible constructors feature
3982 if (!firstStatement)
3983 preview.checkSourceLevel(apply.pos(), Feature.FLEXIBLE_CONSTRUCTORS);
3984
3985 // We found a legitimate super()/this() call; remember it
3986 initCall = methodName;
3987 } while (false);
3988
3989 // Proceed
3990 super.visitApply(apply);
3991 }
3992
3993 @Override
3994 public void visitReturn(JCReturn tree) {
3995 if (constructor && initCall == null && earlyReturn == null)
3996 earlyReturn = tree; // we have seen a return but not (yet) a super()/this()
3997 super.visitReturn(tree);
3998 }
3999
4000 @Override
4001 public void visitClassDef(JCClassDecl tree) {
4002 // don't descend any further
4003 }
4004
4005 @Override
4006 public void visitLambda(JCLambda tree) {
4007 final boolean constructorPrev = constructor;
4008 final boolean firstStatementPrev = firstStatement;
4009 final JCReturn earlyReturnPrev = earlyReturn;
4010 final Name initCallPrev = initCall;
4011 final int scanDepthPrev = scanDepth;
4012 constructor = false;
4013 firstStatement = false;
4014 earlyReturn = null;
4015 initCall = null;
4016 scanDepth = 0;
4017 try {
4018 super.visitLambda(tree);
4019 } finally {
4020 constructor = constructorPrev;
4021 firstStatement = firstStatementPrev;
4022 earlyReturn = earlyReturnPrev;
4023 initCall = initCallPrev;
4024 scanDepth = scanDepthPrev;
4025 }
4026 }
4027 }
4028
4029 /* *************************************************************************
4030 * Miscellaneous
4031 **************************************************************************/
4032
4033 /**
4034 * Check for division by integer constant zero
4035 * @param pos Position for error reporting.
4036 * @param operator The operator for the expression
4037 * @param operand The right hand operand for the expression
4038 */
4039 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
4040 if (operand.constValue() != null
4041 && operand.getTag().isSubRangeOf(LONG)
4042 && ((Number) (operand.constValue())).longValue() == 0) {
4043 int opc = ((OperatorSymbol)operator).opcode;
4044 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
4045 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
4046 log.warning(pos, LintWarnings.DivZero);
4047 }
4048 }
4049 }
4050
4051 /**
4052 * Check for bit shifts using an out-of-range bit count.
4053 * @param pos Position for error reporting.
4054 * @param operator The operator for the expression
4055 * @param operand The right hand operand for the expression
4056 */
4057 void checkOutOfRangeShift(final DiagnosticPosition pos, Symbol operator, Type operand) {
4058 if (operand.constValue() instanceof Number shiftAmount) {
4059 Type targetType;
4060 int maximumShift;
4061 switch (((OperatorSymbol)operator).opcode) {
4062 case ByteCodes.ishl, ByteCodes.ishr, ByteCodes.iushr, ByteCodes.ishll, ByteCodes.ishrl, ByteCodes.iushrl -> {
4063 targetType = syms.intType;
4064 maximumShift = 0x1f;
4065 }
4066 case ByteCodes.lshl, ByteCodes.lshr, ByteCodes.lushr, ByteCodes.lshll, ByteCodes.lshrl, ByteCodes.lushrl -> {
4067 targetType = syms.longType;
4068 maximumShift = 0x3f;
4069 }
4070 default -> {
4071 return;
4072 }
4073 }
4074 long specifiedShift = shiftAmount.longValue();
4075 if (specifiedShift > maximumShift || specifiedShift < -maximumShift) {
4076 int actualShift = (int)specifiedShift & (maximumShift - 1);
4077 log.warning(pos, LintWarnings.BitShiftOutOfRange(targetType, specifiedShift, actualShift));
4078 }
4079 }
4080 }
4081
4082 /**
4083 * Check for possible loss of precission
4084 * @param pos Position for error reporting.
4085 * @param found The computed type of the tree
4086 * @param req The computed type of the tree
4087 */
4088 void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
4089 if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
4090 log.warning(pos, LintWarnings.PossibleLossOfPrecision(found, req));
4091 }
4092 }
4093
4094 /**
4095 * Check for empty statements after if
4096 */
4097 void checkEmptyIf(JCIf tree) {
4098 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) {
4099 log.warning(tree.thenpart.pos(), LintWarnings.EmptyIf);
4100 }
4101 }
4102
4103 /** Check that symbol is unique in given scope.
4104 * @param pos Position for error reporting.
4105 * @param sym The symbol.
4106 * @param s The scope.
4107 */
4108 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
4109 if (sym.type.isErroneous())
4110 return true;
4111 if (sym.owner.name == names.any) return false;
4112 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
4113 if (sym != byName &&
4114 (byName.flags() & CLASH) == 0 &&
4115 sym.kind == byName.kind &&
4116 sym.name != names.error &&
4117 (sym.kind != MTH ||
4118 types.hasSameArgs(sym.type, byName.type) ||
4119 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
4120 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
4121 sym.flags_field |= CLASH;
4122 varargsDuplicateError(pos, sym, byName);
4123 return true;
4124 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
4125 duplicateErasureError(pos, sym, byName);
4126 sym.flags_field |= CLASH;
4127 return true;
4128 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
4129 (byName.flags() & MATCH_BINDING) != 0 &&
4130 (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
4131 if (!sym.type.isErroneous()) {
4132 log.error(pos, Errors.MatchBindingExists);
4133 sym.flags_field |= CLASH;
4134 }
4135 return false;
4136 } else {
4137 duplicateError(pos, byName);
4138 return false;
4139 }
4140 }
4141 }
4142 return true;
4143 }
4144
4145 /** Report duplicate declaration error.
4146 */
4147 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
4148 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
4149 log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
4150 }
4151 }
4152
4153 /**Check that types imported through the ordinary imports don't clash with types imported
4154 * by other (static or ordinary) imports. Note that two static imports may import two clashing
4155 * types without an error on the imports.
4156 * @param toplevel The toplevel tree for which the test should be performed.
4157 */
4158 void checkImportsUnique(JCCompilationUnit toplevel) {
4159 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
4160 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
4161 WriteableScope topLevelScope = toplevel.toplevelScope;
4162
4163 for (JCTree def : toplevel.defs) {
4164 if (!def.hasTag(IMPORT))
4165 continue;
4166
4167 JCImport imp = (JCImport) def;
4168
4169 if (imp.importScope == null)
4170 continue;
4171
4172 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
4173 if (imp.isStatic()) {
4174 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
4175 staticallyImportedSoFar.enter(sym);
4176 } else {
4177 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
4178 ordinallyImportedSoFar.enter(sym);
4179 }
4180 }
4181
4182 imp.importScope = null;
4183 }
4184 }
4185
4186 /** Check that single-type import is not already imported or top-level defined,
4187 * but make an exception for two single-type imports which denote the same type.
4188 * @param pos Position for error reporting.
4189 * @param ordinallyImportedSoFar A Scope containing types imported so far through
4190 * ordinary imports.
4191 * @param staticallyImportedSoFar A Scope containing types imported so far through
4192 * static imports.
4193 * @param topLevelScope The current file's top-level Scope
4194 * @param sym The symbol.
4195 * @param staticImport Whether or not this was a static import
4196 */
4197 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
4198 Scope staticallyImportedSoFar, Scope topLevelScope,
4199 Symbol sym, boolean staticImport) {
4200 Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
4201 Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
4202 Symbol staticClashing = null;
4203 if (ordinaryClashing == null && !staticImport) {
4204 staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
4205 }
4206 if (ordinaryClashing != null || staticClashing != null) {
4207 if (ordinaryClashing != null)
4208 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
4209 else
4210 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
4211 return false;
4212 }
4213 Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
4214 if (clashing != null) {
4215 log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
4216 return false;
4217 }
4218 return true;
4219 }
4220
4221 /** Check that a qualified name is in canonical form (for import decls).
4222 */
4223 public void checkCanonical(JCTree tree) {
4224 if (!isCanonical(tree))
4225 log.error(tree.pos(),
4226 Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
4227 }
4228 // where
4229 private boolean isCanonical(JCTree tree) {
4230 while (tree.hasTag(SELECT)) {
4231 JCFieldAccess s = (JCFieldAccess) tree;
4232 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
4233 return false;
4234 tree = s.selected;
4235 }
4236 return true;
4237 }
4238
4239 /** Check that an auxiliary class is not accessed from any other file than its own.
4240 */
4241 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
4242 if ((c.flags() & AUXILIARY) != 0 &&
4243 rs.isAccessible(env, c) &&
4244 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
4245 {
4246 log.warning(pos, LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
4247 }
4248 }
4249
4250 /**
4251 * Check for a default constructor in an exported package.
4252 */
4253 void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
4254 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
4255 ((c.flags() & (ENUM | RECORD)) == 0) &&
4256 !c.isAnonymous() &&
4257 ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
4258 Feature.MODULES.allowedInSource(source)) {
4259 NestingKind nestingKind = c.getNestingKind();
4260 switch (nestingKind) {
4261 case ANONYMOUS,
4262 LOCAL -> {return;}
4263 case TOP_LEVEL -> {;} // No additional checks needed
4264 case MEMBER -> {
4265 // For nested member classes, all the enclosing
4266 // classes must be public or protected.
4267 Symbol owner = c.owner;
4268 while (owner != null && owner.kind == TYP) {
4269 if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
4270 return;
4271 owner = owner.owner;
4272 }
4273 }
4274 }
4275
4276 // Only check classes in named packages exported by its module
4277 PackageSymbol pkg = c.packge();
4278 if (!pkg.isUnnamed()) {
4279 ModuleSymbol modle = pkg.modle;
4280 for (ExportsDirective exportDir : modle.exports) {
4281 // Report warning only if the containing
4282 // package is unconditionally exported
4283 if (exportDir.packge.equals(pkg)) {
4284 if (exportDir.modules == null || exportDir.modules.isEmpty()) {
4285 // Warning may be suppressed by
4286 // annotations; check again for being
4287 // enabled in the deferred context.
4288 log.warning(pos, LintWarnings.MissingExplicitCtor(c, pkg, modle));
4289 } else {
4290 return;
4291 }
4292 }
4293 }
4294 }
4295 }
4296 return;
4297 }
4298
4299 private class ConversionWarner extends Warner {
4300 final String uncheckedKey;
4301 final Type found;
4302 final Type expected;
4303 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
4304 super(pos);
4305 this.uncheckedKey = uncheckedKey;
4306 this.found = found;
4307 this.expected = expected;
4308 }
4309
4310 @Override
4311 public void warn(LintCategory lint) {
4312 boolean warned = this.warned;
4313 super.warn(lint);
4314 if (warned) return; // suppress redundant diagnostics
4315 switch (lint) {
4316 case UNCHECKED:
4317 Check.this.warnUnchecked(pos(), LintWarnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
4318 break;
4319 case VARARGS:
4320 if (method != null &&
4321 method.attribute(syms.trustMeType.tsym) != null &&
4322 isTrustMeAllowedOnMethod(method) &&
4323 !types.isReifiable(method.type.getParameterTypes().last())) {
4324 log.warning(pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last()));
4325 }
4326 break;
4327 default:
4328 throw new AssertionError("Unexpected lint: " + lint);
4329 }
4330 }
4331 }
4332
4333 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
4334 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
4335 }
4336
4337 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
4338 return new ConversionWarner(pos, "unchecked.assign", found, expected);
4339 }
4340
4341 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
4342 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
4343
4344 if (functionalType != null) {
4345 try {
4346 types.findDescriptorSymbol((TypeSymbol)cs);
4347 } catch (Types.FunctionDescriptorLookupError ex) {
4348 DiagnosticPosition pos = tree.pos();
4349 for (JCAnnotation a : tree.getModifiers().annotations) {
4350 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
4351 pos = a.pos();
4352 break;
4353 }
4354 }
4355 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
4356 }
4357 }
4358 }
4359
4360 public void checkImportsResolvable(final JCCompilationUnit toplevel) {
4361 for (final JCImportBase impBase : toplevel.getImports()) {
4362 if (!(impBase instanceof JCImport imp))
4363 continue;
4364 if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
4365 continue;
4366 final JCFieldAccess select = imp.qualid;
4367 final Symbol origin;
4368 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4369 continue;
4370
4371 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4372 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4373 log.error(imp.pos(),
4374 Errors.CantResolveLocation(KindName.STATIC,
4375 select.name,
4376 null,
4377 null,
4378 Fragments.Location(kindName(site),
4379 site,
4380 null)));
4381 }
4382 }
4383 }
4384
4385 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
4386 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4387 OUTER: for (JCImportBase impBase : toplevel.getImports()) {
4388 if (impBase instanceof JCImport imp && !imp.staticImport &&
4389 TreeInfo.name(imp.qualid) == names.asterisk) {
4390 TypeSymbol tsym = imp.qualid.selected.type.tsym;
4391 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4392 !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4393 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.qualid.selected.pos(), Errors.DoesntExist(tsym));
4394 }
4395 }
4396 }
4397 }
4398
4399 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4400 if (tsym == null || !processed.add(tsym))
4401 return false;
4402
4403 // also search through inherited names
4404 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4405 return true;
4406
4407 for (Type t : types.interfaces(tsym.type))
4408 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4409 return true;
4410
4411 for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4412 if (sym.isStatic() &&
4413 importAccessible(sym, packge) &&
4414 sym.isMemberOf(origin, types)) {
4415 return true;
4416 }
4417 }
4418
4419 return false;
4420 }
4421
4422 // is the sym accessible everywhere in packge?
4423 public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4424 try {
4425 int flags = (int)(sym.flags() & AccessFlags);
4426 switch (flags) {
4427 default:
4428 case PUBLIC:
4429 return true;
4430 case PRIVATE:
4431 return false;
4432 case 0:
4433 case PROTECTED:
4434 return sym.packge() == packge;
4435 }
4436 } catch (ClassFinder.BadClassFile err) {
4437 throw err;
4438 } catch (CompletionFailure ex) {
4439 return false;
4440 }
4441 }
4442
4443 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4444 JCCompilationUnit toplevel = env.toplevel;
4445
4446 if ( toplevel.modle == syms.unnamedModule
4447 || toplevel.modle == syms.noModule
4448 || (check.sym.flags() & COMPOUND) != 0) {
4449 return ;
4450 }
4451
4452 ExportsDirective currentExport = findExport(toplevel.packge);
4453
4454 if ( currentExport == null //not exported
4455 || currentExport.modules != null) //don't check classes in qualified export
4456 return ;
4457
4458 new TreeScanner() {
4459 Lint lint = env.info.lint;
4460 boolean inSuperType;
4461
4462 @Override
4463 public void visitBlock(JCBlock tree) {
4464 }
4465 @Override
4466 public void visitMethodDef(JCMethodDecl tree) {
4467 if (!isAPISymbol(tree.sym))
4468 return;
4469 Lint prevLint = lint;
4470 try {
4471 lint = lint.augment(tree.sym);
4472 if (lint.isEnabled(LintCategory.EXPORTS)) {
4473 super.visitMethodDef(tree);
4474 }
4475 } finally {
4476 lint = prevLint;
4477 }
4478 }
4479 @Override
4480 public void visitVarDef(JCVariableDecl tree) {
4481 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4482 return;
4483 Lint prevLint = lint;
4484 try {
4485 lint = lint.augment(tree.sym);
4486 if (lint.isEnabled(LintCategory.EXPORTS)) {
4487 scan(tree.mods);
4488 scan(tree.vartype);
4489 }
4490 } finally {
4491 lint = prevLint;
4492 }
4493 }
4494 @Override
4495 public void visitClassDef(JCClassDecl tree) {
4496 if (tree != check)
4497 return ;
4498
4499 if (!isAPISymbol(tree.sym))
4500 return ;
4501
4502 Lint prevLint = lint;
4503 try {
4504 lint = lint.augment(tree.sym);
4505 if (lint.isEnabled(LintCategory.EXPORTS)) {
4506 scan(tree.mods);
4507 scan(tree.typarams);
4508 try {
4509 inSuperType = true;
4510 scan(tree.extending);
4511 scan(tree.implementing);
4512 } finally {
4513 inSuperType = false;
4514 }
4515 scan(tree.defs);
4516 }
4517 } finally {
4518 lint = prevLint;
4519 }
4520 }
4521 @Override
4522 public void visitTypeApply(JCTypeApply tree) {
4523 scan(tree.clazz);
4524 boolean oldInSuperType = inSuperType;
4525 try {
4526 inSuperType = false;
4527 scan(tree.arguments);
4528 } finally {
4529 inSuperType = oldInSuperType;
4530 }
4531 }
4532 @Override
4533 public void visitIdent(JCIdent tree) {
4534 Symbol sym = TreeInfo.symbol(tree);
4535 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4536 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4537 }
4538 }
4539
4540 @Override
4541 public void visitSelect(JCFieldAccess tree) {
4542 Symbol sym = TreeInfo.symbol(tree);
4543 Symbol sitesym = TreeInfo.symbol(tree.selected);
4544 if (sym.kind == TYP && sitesym.kind == PCK) {
4545 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4546 } else {
4547 super.visitSelect(tree);
4548 }
4549 }
4550
4551 @Override
4552 public void visitAnnotation(JCAnnotation tree) {
4553 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4554 super.visitAnnotation(tree);
4555 }
4556
4557 }.scan(check);
4558 }
4559 //where:
4560 private ExportsDirective findExport(PackageSymbol pack) {
4561 for (ExportsDirective d : pack.modle.exports) {
4562 if (d.packge == pack)
4563 return d;
4564 }
4565
4566 return null;
4567 }
4568 private boolean isAPISymbol(Symbol sym) {
4569 while (sym.kind != PCK) {
4570 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4571 return false;
4572 }
4573 sym = sym.owner;
4574 }
4575 return true;
4576 }
4577 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4578 if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4579 log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4580 return ;
4581 }
4582
4583 PackageSymbol whatPackage = what.packge();
4584 ExportsDirective whatExport = findExport(whatPackage);
4585 ExportsDirective inExport = findExport(inPackage);
4586
4587 if (whatExport == null) { //package not exported:
4588 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4589 return ;
4590 }
4591
4592 if (whatExport.modules != null) {
4593 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4594 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4595 }
4596 }
4597
4598 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4599 //check that relativeTo.modle requires transitive what.modle, somehow:
4600 List<ModuleSymbol> todo = List.of(inPackage.modle);
4601
4602 while (todo.nonEmpty()) {
4603 ModuleSymbol current = todo.head;
4604 todo = todo.tail;
4605 if (current == whatPackage.modle)
4606 return ; //OK
4607 if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4608 continue; //for automatic modules, don't look into their dependencies
4609 for (RequiresDirective req : current.requires) {
4610 if (req.isTransitive()) {
4611 todo = todo.prepend(req.module);
4612 }
4613 }
4614 }
4615
4616 log.warning(pos, LintWarnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4617 }
4618 }
4619
4620 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4621 if (msym.kind != MDL) {
4622 log.warning(pos, LintWarnings.ModuleNotFound(msym));
4623 }
4624 }
4625
4626 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4627 if (packge.members().isEmpty() &&
4628 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4629 log.warning(pos, LintWarnings.PackageEmptyOrNotFound(packge));
4630 }
4631 }
4632
4633 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4634 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4635 if (rd.isTransitive()) { // see comment in Log.applyLint() for special logic that applies
4636 log.warning(pos, LintWarnings.RequiresTransitiveAutomatic);
4637 } else {
4638 log.warning(pos, LintWarnings.RequiresAutomatic);
4639 }
4640 }
4641 }
4642
4643 /**
4644 * Verify the case labels conform to the constraints. Checks constraints related
4645 * combinations of patterns and other labels.
4646 *
4647 * @param cases the cases that should be checked.
4648 */
4649 void checkSwitchCaseStructure(List<JCCase> cases) {
4650 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4651 JCCase c = l.head;
4652 if (c.labels.head instanceof JCConstantCaseLabel constLabel) {
4653 if (TreeInfo.isNull(constLabel.expr)) {
4654 if (c.labels.tail.nonEmpty()) {
4655 if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) {
4656 if (c.labels.tail.tail.nonEmpty()) {
4657 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4658 }
4659 } else {
4660 log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4661 }
4662 }
4663 } else {
4664 for (JCCaseLabel label : c.labels.tail) {
4665 if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) {
4666 log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4667 break;
4668 }
4669 }
4670 }
4671 } else if (c.labels.tail.nonEmpty()) {
4672 var patterCaseLabels = c.labels.stream().filter(ll -> ll instanceof JCPatternCaseLabel).map(cl -> (JCPatternCaseLabel)cl);
4673 var allUnderscore = patterCaseLabels.allMatch(pcl -> !hasBindings(pcl.getPattern()));
4674
4675 if (!allUnderscore) {
4676 log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern);
4677 }
4678
4679 boolean allPatternCaseLabels = c.labels.stream().allMatch(p -> p instanceof JCPatternCaseLabel);
4680
4681 if (allPatternCaseLabels) {
4682 preview.checkSourceLevel(c.labels.tail.head.pos(), Feature.UNNAMED_VARIABLES);
4683 }
4684
4685 for (JCCaseLabel label : c.labels.tail) {
4686 if (label instanceof JCConstantCaseLabel) {
4687 log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4688 break;
4689 }
4690 }
4691 }
4692 }
4693
4694 boolean isCaseStatementGroup = cases.nonEmpty() &&
4695 cases.head.caseKind == CaseTree.CaseKind.STATEMENT;
4696
4697 if (isCaseStatementGroup) {
4698 boolean previousCompletessNormally = false;
4699 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4700 JCCase c = l.head;
4701 if (previousCompletessNormally &&
4702 c.stats.nonEmpty() &&
4703 c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4704 (hasBindings(patternLabel.pat) || hasBindings(c.guard))) {
4705 log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern);
4706 } else if (c.stats.isEmpty() &&
4707 c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4708 (hasBindings(patternLabel.pat) || hasBindings(c.guard)) &&
4709 hasStatements(l.tail)) {
4710 log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern);
4711 }
4712 previousCompletessNormally = c.completesNormally;
4713 }
4714 }
4715 }
4716
4717 boolean hasBindings(JCTree p) {
4718 boolean[] bindings = new boolean[1];
4719
4720 new TreeScanner() {
4721 @Override
4722 public void visitBindingPattern(JCBindingPattern tree) {
4723 bindings[0] |= !tree.var.sym.isUnnamedVariable();
4724 super.visitBindingPattern(tree);
4725 }
4726 }.scan(p);
4727
4728 return bindings[0];
4729 }
4730
4731 boolean hasStatements(List<JCCase> cases) {
4732 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4733 if (l.head.stats.nonEmpty()) {
4734 return true;
4735 }
4736 }
4737
4738 return false;
4739 }
4740 void checkSwitchCaseLabelDominated(JCCaseLabel unconditionalCaseLabel, List<JCCase> cases) {
4741 List<Pair<JCCase, JCCaseLabel>> caseLabels = List.nil();
4742 boolean seenDefault = false;
4743 boolean seenDefaultLabel = false;
4744 boolean warnDominatedByDefault = false;
4745 boolean unconditionalFound = false;
4746
4747 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4748 JCCase c = l.head;
4749 for (JCCaseLabel label : c.labels) {
4750 if (label.hasTag(DEFAULTCASELABEL)) {
4751 seenDefault = true;
4752 seenDefaultLabel |=
4753 TreeInfo.isNullCaseLabel(c.labels.head);
4754 continue;
4755 }
4756 if (TreeInfo.isNullCaseLabel(label)) {
4757 if (seenDefault) {
4758 log.error(label.pos(), Errors.PatternDominated);
4759 }
4760 continue;
4761 }
4762 if (seenDefault && !warnDominatedByDefault) {
4763 if (label.hasTag(PATTERNCASELABEL) ||
4764 (label instanceof JCConstantCaseLabel && seenDefaultLabel)) {
4765 log.error(label.pos(), Errors.PatternDominated);
4766 warnDominatedByDefault = true;
4767 }
4768 }
4769 Type currentType = labelType(label);
4770 for (Pair<JCCase, JCCaseLabel> caseAndLabel : caseLabels) {
4771 JCCase testCase = caseAndLabel.fst;
4772 JCCaseLabel testCaseLabel = caseAndLabel.snd;
4773 Type testType = labelType(testCaseLabel);
4774
4775 // an unconditional pattern cannot be followed by any other label
4776 if (allowPrimitivePatterns && unconditionalCaseLabel == testCaseLabel && unconditionalCaseLabel != label) {
4777 log.error(label.pos(), Errors.PatternDominated);
4778 continue;
4779 }
4780
4781 boolean dominated = false;
4782 if (!currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) {
4783 // the current label is potentially dominated by the existing (test) label, check:
4784 if (types.isUnconditionallyExactCombined(currentType, testType) &&
4785 label instanceof JCConstantCaseLabel) {
4786 dominated = !(testCaseLabel instanceof JCConstantCaseLabel) &&
4787 TreeInfo.unguardedCase(testCase);
4788 } else if (label instanceof JCPatternCaseLabel patternCL &&
4789 testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel &&
4790 (testCase.equals(c) || TreeInfo.unguardedCase(testCase))) {
4791 dominated = patternDominated(testPatternCaseLabel.pat, patternCL.pat);
4792 }
4793 }
4794 if (dominated) {
4795 log.error(label.pos(), Errors.PatternDominated);
4796 }
4797 }
4798 caseLabels = caseLabels.prepend(Pair.of(c, label));
4799 }
4800 }
4801 }
4802 //where:
4803 private Type labelType(JCCaseLabel label) {
4804 return types.erasure(switch (label.getTag()) {
4805 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type;
4806 case CONSTANTCASELABEL -> ((JCConstantCaseLabel) label).expr.type;
4807 default -> throw Assert.error("Unexpected tree kind: " + label.getTag());
4808 });
4809 }
4810 private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) {
4811 Type existingPatternType = types.erasure(existingPattern.type);
4812 Type currentPatternType = types.erasure(currentPattern.type);
4813 if (!types.isUnconditionallyExactTypeBased(currentPatternType, existingPatternType)) {
4814 return false;
4815 }
4816 if (currentPattern instanceof JCBindingPattern ||
4817 currentPattern instanceof JCAnyPattern) {
4818 return existingPattern instanceof JCBindingPattern ||
4819 existingPattern instanceof JCAnyPattern;
4820 } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) {
4821 if (existingPattern instanceof JCBindingPattern ||
4822 existingPattern instanceof JCAnyPattern) {
4823 return true;
4824 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) {
4825 List<JCPattern> existingNested = existingRecordPattern.nested;
4826 List<JCPattern> currentNested = currentRecordPattern.nested;
4827 if (existingNested.size() != currentNested.size()) {
4828 return false;
4829 }
4830 while (existingNested.nonEmpty()) {
4831 if (!patternDominated(existingNested.head, currentNested.head)) {
4832 return false;
4833 }
4834 existingNested = existingNested.tail;
4835 currentNested = currentNested.tail;
4836 }
4837 return true;
4838 } else {
4839 Assert.error("Unknown pattern: " + existingPattern.getTag());
4840 }
4841 } else {
4842 Assert.error("Unknown pattern: " + currentPattern.getTag());
4843 }
4844 return false;
4845 }
4846
4847 /** check if a type is a subtype of Externalizable, if that is available. */
4848 boolean isExternalizable(Type t) {
4849 try {
4850 syms.externalizableType.complete();
4851 } catch (CompletionFailure e) {
4852 return false;
4853 }
4854 return types.isSubtype(t, syms.externalizableType);
4855 }
4856
4857 /**
4858 * Check structure of serialization declarations.
4859 */
4860 public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) {
4861 (new SerialTypeVisitor()).visit(c, tree);
4862 }
4863
4864 /**
4865 * This visitor will warn if a serialization-related field or
4866 * method is declared in a suspicious or incorrect way. In
4867 * particular, it will warn for cases where the runtime
4868 * serialization mechanism will silently ignore a mis-declared
4869 * entity.
4870 *
4871 * Distinguished serialization-related fields and methods:
4872 *
4873 * Methods:
4874 *
4875 * private void writeObject(ObjectOutputStream stream) throws IOException
4876 * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
4877 *
4878 * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
4879 * private void readObjectNoData() throws ObjectStreamException
4880 * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
4881 *
4882 * Fields:
4883 *
4884 * private static final long serialVersionUID
4885 * private static final ObjectStreamField[] serialPersistentFields
4886 *
4887 * Externalizable: methods defined on the interface
4888 * public void writeExternal(ObjectOutput) throws IOException
4889 * public void readExternal(ObjectInput) throws IOException
4890 */
4891 private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> {
4892 SerialTypeVisitor() {
4893 this.lint = Check.this.lint;
4894 }
4895
4896 private static final Set<String> serialMethodNames =
4897 Set.of("writeObject", "writeReplace",
4898 "readObject", "readObjectNoData",
4899 "readResolve");
4900
4901 private static final Set<String> serialFieldNames =
4902 Set.of("serialVersionUID", "serialPersistentFields");
4903
4904 // Type of serialPersistentFields
4905 private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass);
4906
4907 Lint lint;
4908
4909 @Override
4910 public Void defaultAction(Element e, JCClassDecl p) {
4911 throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), ""));
4912 }
4913
4914 @Override
4915 public Void visitType(TypeElement e, JCClassDecl p) {
4916 runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param));
4917 return null;
4918 }
4919
4920 @Override
4921 public Void visitTypeAsClass(TypeElement e,
4922 JCClassDecl p) {
4923 // Anonymous classes filtered out by caller.
4924
4925 ClassSymbol c = (ClassSymbol)e;
4926
4927 checkCtorAccess(p, c);
4928
4929 // Check for missing serialVersionUID; check *not* done
4930 // for enums or records.
4931 VarSymbol svuidSym = null;
4932 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4933 if (sym.kind == VAR) {
4934 svuidSym = (VarSymbol)sym;
4935 break;
4936 }
4937 }
4938
4939 if (svuidSym == null) {
4940 log.warning(p.pos(), LintWarnings.MissingSVUID(c));
4941 }
4942
4943 // Check for serialPersistentFields to gate checks for
4944 // non-serializable non-transient instance fields
4945 boolean serialPersistentFieldsPresent =
4946 c.members()
4947 .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR)
4948 .iterator()
4949 .hasNext();
4950
4951 // Check declarations of serialization-related methods and
4952 // fields
4953 for(Symbol el : c.getEnclosedElements()) {
4954 runUnderLint(el, p, (enclosed, tree) -> {
4955 String name = null;
4956 switch(enclosed.getKind()) {
4957 case FIELD -> {
4958 if (!serialPersistentFieldsPresent) {
4959 var flags = enclosed.flags();
4960 if ( ((flags & TRANSIENT) == 0) &&
4961 ((flags & STATIC) == 0)) {
4962 Type varType = enclosed.asType();
4963 if (!canBeSerialized(varType)) {
4964 // Note per JLS arrays are
4965 // serializable even if the
4966 // component type is not.
4967 log.warning(
4968 TreeInfo.diagnosticPositionFor(enclosed, tree),
4969 LintWarnings.NonSerializableInstanceField);
4970 } else if (varType.hasTag(ARRAY)) {
4971 ArrayType arrayType = (ArrayType)varType;
4972 Type elementType = arrayType.elemtype;
4973 while (elementType.hasTag(ARRAY)) {
4974 arrayType = (ArrayType)elementType;
4975 elementType = arrayType.elemtype;
4976 }
4977 if (!canBeSerialized(elementType)) {
4978 log.warning(
4979 TreeInfo.diagnosticPositionFor(enclosed, tree),
4980 LintWarnings.NonSerializableInstanceFieldArray(elementType));
4981 }
4982 }
4983 }
4984 }
4985
4986 name = enclosed.getSimpleName().toString();
4987 if (serialFieldNames.contains(name)) {
4988 VarSymbol field = (VarSymbol)enclosed;
4989 switch (name) {
4990 case "serialVersionUID" -> checkSerialVersionUID(tree, e, field);
4991 case "serialPersistentFields" -> checkSerialPersistentFields(tree, e, field);
4992 default -> throw new AssertionError();
4993 }
4994 }
4995 }
4996
4997 // Correctly checking the serialization-related
4998 // methods is subtle. For the methods declared to be
4999 // private or directly declared in the class, the
5000 // enclosed elements of the class can be checked in
5001 // turn. However, writeReplace and readResolve can be
5002 // declared in a superclass and inherited. Note that
5003 // the runtime lookup walks the superclass chain
5004 // looking for writeReplace/readResolve via
5005 // Class.getDeclaredMethod. This differs from calling
5006 // Elements.getAllMembers(TypeElement) as the latter
5007 // will also pull in default methods from
5008 // superinterfaces. In other words, the runtime checks
5009 // (which long predate default methods on interfaces)
5010 // do not admit the possibility of inheriting methods
5011 // this way, a difference from general inheritance.
5012
5013 // The current implementation just checks the enclosed
5014 // elements and does not directly check the inherited
5015 // methods. If all the types are being checked this is
5016 // less of a concern; however, there are cases that
5017 // could be missed. In particular, readResolve and
5018 // writeReplace could, in principle, by inherited from
5019 // a non-serializable superclass and thus not checked
5020 // even if compiled with a serializable child class.
5021 case METHOD -> {
5022 var method = (MethodSymbol)enclosed;
5023 name = method.getSimpleName().toString();
5024 if (serialMethodNames.contains(name)) {
5025 switch (name) {
5026 case "writeObject" -> checkWriteObject(tree, e, method);
5027 case "writeReplace" -> checkWriteReplace(tree,e, method);
5028 case "readObject" -> checkReadObject(tree,e, method);
5029 case "readObjectNoData" -> checkReadObjectNoData(tree, e, method);
5030 case "readResolve" -> checkReadResolve(tree, e, method);
5031 default -> throw new AssertionError();
5032 }
5033 }
5034 }
5035 }
5036 });
5037 }
5038
5039 return null;
5040 }
5041
5042 boolean canBeSerialized(Type type) {
5043 return type.isPrimitive() || rs.isSerializable(type);
5044 }
5045
5046 /**
5047 * Check that Externalizable class needs a public no-arg
5048 * constructor.
5049 *
5050 * Check that a Serializable class has access to the no-arg
5051 * constructor of its first nonserializable superclass.
5052 */
5053 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5054 if (isExternalizable(c.type)) {
5055 for(var sym : c.getEnclosedElements()) {
5056 if (sym.isConstructor() &&
5057 ((sym.flags() & PUBLIC) == PUBLIC)) {
5058 if (((MethodSymbol)sym).getParameters().isEmpty()) {
5059 return;
5060 }
5061 }
5062 }
5063 log.warning(tree.pos(),
5064 LintWarnings.ExternalizableMissingPublicNoArgCtor);
5065 } else {
5066 // Approximate access to the no-arg constructor up in
5067 // the superclass chain by checking that the
5068 // constructor is not private. This may not handle
5069 // some cross-package situations correctly.
5070 Type superClass = c.getSuperclass();
5071 // java.lang.Object is *not* Serializable so this loop
5072 // should terminate.
5073 while (rs.isSerializable(superClass) ) {
5074 try {
5075 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5076 } catch(ClassCastException cce) {
5077 return ; // Don't try to recover
5078 }
5079 }
5080 // Non-Serializable superclass
5081 try {
5082 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5083 for(var sym : supertype.getEnclosedElements()) {
5084 if (sym.isConstructor()) {
5085 MethodSymbol ctor = (MethodSymbol)sym;
5086 if (ctor.getParameters().isEmpty()) {
5087 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5088 // Handle nested classes and implicit this$0
5089 (supertype.getNestingKind() == NestingKind.MEMBER &&
5090 ((supertype.flags() & STATIC) == 0)))
5091 log.warning(tree.pos(),
5092 LintWarnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5093 }
5094 }
5095 }
5096 } catch (ClassCastException cce) {
5097 return ; // Don't try to recover
5098 }
5099 return;
5100 }
5101 }
5102
5103 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5104 // To be effective, serialVersionUID must be marked static
5105 // and final, but private is recommended. But alas, in
5106 // practice there are many non-private serialVersionUID
5107 // fields.
5108 if ((svuid.flags() & (STATIC | FINAL)) !=
5109 (STATIC | FINAL)) {
5110 log.warning(
5111 TreeInfo.diagnosticPositionFor(svuid, tree),
5112 LintWarnings.ImproperSVUID((Symbol)e));
5113 }
5114
5115 // check svuid has type long
5116 if (!svuid.type.hasTag(LONG)) {
5117 log.warning(
5118 TreeInfo.diagnosticPositionFor(svuid, tree),
5119 LintWarnings.LongSVUID((Symbol)e));
5120 }
5121
5122 if (svuid.getConstValue() == null)
5123 log.warning(
5124 TreeInfo.diagnosticPositionFor(svuid, tree),
5125 LintWarnings.ConstantSVUID((Symbol)e));
5126 }
5127
5128 private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
5129 // To be effective, serialPersisentFields must be private, static, and final.
5130 if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
5131 (PRIVATE | STATIC | FINAL)) {
5132 log.warning(
5133 TreeInfo.diagnosticPositionFor(spf, tree),
5134 LintWarnings.ImproperSPF);
5135 }
5136
5137 if (!types.isSameType(spf.type, OSF_TYPE)) {
5138 log.warning(
5139 TreeInfo.diagnosticPositionFor(spf, tree),
5140 LintWarnings.OSFArraySPF);
5141 }
5142
5143 if (isExternalizable((Type)(e.asType()))) {
5144 log.warning(
5145 TreeInfo.diagnosticPositionFor(spf, tree),
5146 LintWarnings.IneffectualSerialFieldExternalizable);
5147 }
5148
5149 // Warn if serialPersistentFields is initialized to a
5150 // literal null.
5151 JCTree spfDecl = TreeInfo.declarationFor(spf, tree);
5152 if (spfDecl != null && spfDecl.getTag() == VARDEF) {
5153 JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
5154 JCExpression initExpr = variableDef.init;
5155 if (initExpr != null && TreeInfo.isNull(initExpr)) {
5156 log.warning(initExpr.pos(),
5157 LintWarnings.SPFNullInit);
5158 }
5159 }
5160 }
5161
5162 private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) {
5163 // The "synchronized" modifier is seen in the wild on
5164 // readObject and writeObject methods and is generally
5165 // innocuous.
5166
5167 // private void writeObject(ObjectOutputStream stream) throws IOException
5168 checkPrivateNonStaticMethod(tree, method);
5169 checkReturnType(tree, e, method, syms.voidType);
5170 checkOneArg(tree, e, method, syms.objectOutputStreamType);
5171 checkExceptions(tree, e, method, syms.ioExceptionType);
5172 checkExternalizable(tree, e, method);
5173 }
5174
5175 private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) {
5176 // ANY-ACCESS-MODIFIER Object writeReplace() throws
5177 // ObjectStreamException
5178
5179 // Excluding abstract, could have a more complicated
5180 // rule based on abstract-ness of the class
5181 checkConcreteInstanceMethod(tree, e, method);
5182 checkReturnType(tree, e, method, syms.objectType);
5183 checkNoArgs(tree, e, method);
5184 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5185 }
5186
5187 private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) {
5188 // The "synchronized" modifier is seen in the wild on
5189 // readObject and writeObject methods and is generally
5190 // innocuous.
5191
5192 // private void readObject(ObjectInputStream stream)
5193 // throws IOException, ClassNotFoundException
5194 checkPrivateNonStaticMethod(tree, method);
5195 checkReturnType(tree, e, method, syms.voidType);
5196 checkOneArg(tree, e, method, syms.objectInputStreamType);
5197 checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType);
5198 checkExternalizable(tree, e, method);
5199 }
5200
5201 private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) {
5202 // private void readObjectNoData() throws ObjectStreamException
5203 checkPrivateNonStaticMethod(tree, method);
5204 checkReturnType(tree, e, method, syms.voidType);
5205 checkNoArgs(tree, e, method);
5206 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5207 checkExternalizable(tree, e, method);
5208 }
5209
5210 private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) {
5211 // ANY-ACCESS-MODIFIER Object readResolve()
5212 // throws ObjectStreamException
5213
5214 // Excluding abstract, could have a more complicated
5215 // rule based on abstract-ness of the class
5216 checkConcreteInstanceMethod(tree, e, method);
5217 checkReturnType(tree,e, method, syms.objectType);
5218 checkNoArgs(tree, e, method);
5219 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5220 }
5221
5222 private void checkWriteExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5223 //public void writeExternal(ObjectOutput) throws IOException
5224 checkExternMethodRecord(tree, e, method, syms.objectOutputType, isExtern);
5225 }
5226
5227 private void checkReadExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5228 // public void readExternal(ObjectInput) throws IOException
5229 checkExternMethodRecord(tree, e, method, syms.objectInputType, isExtern);
5230 }
5231
5232 private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType,
5233 boolean isExtern) {
5234 if (isExtern && isExternMethod(tree, e, method, argType)) {
5235 log.warning(
5236 TreeInfo.diagnosticPositionFor(method, tree),
5237 LintWarnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
5238 }
5239 }
5240
5241 void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
5242 var flags = method.flags();
5243 if ((flags & PRIVATE) == 0) {
5244 log.warning(
5245 TreeInfo.diagnosticPositionFor(method, tree),
5246 LintWarnings.SerialMethodNotPrivate(method.getSimpleName()));
5247 }
5248
5249 if ((flags & STATIC) != 0) {
5250 log.warning(
5251 TreeInfo.diagnosticPositionFor(method, tree),
5252 LintWarnings.SerialMethodStatic(method.getSimpleName()));
5253 }
5254 }
5255
5256 /**
5257 * Per section 1.12 "Serialization of Enum Constants" of
5258 * the serialization specification, due to the special
5259 * serialization handling of enums, any writeObject,
5260 * readObject, writeReplace, and readResolve methods are
5261 * ignored as are serialPersistentFields and
5262 * serialVersionUID fields.
5263 */
5264 @Override
5265 public Void visitTypeAsEnum(TypeElement e,
5266 JCClassDecl p) {
5267 boolean isExtern = isExternalizable((Type)e.asType());
5268 for(Element el : e.getEnclosedElements()) {
5269 runUnderLint(el, p, (enclosed, tree) -> {
5270 String name = enclosed.getSimpleName().toString();
5271 switch(enclosed.getKind()) {
5272 case FIELD -> {
5273 var field = (VarSymbol)enclosed;
5274 if (serialFieldNames.contains(name)) {
5275 log.warning(
5276 TreeInfo.diagnosticPositionFor(field, tree),
5277 LintWarnings.IneffectualSerialFieldEnum(name));
5278 }
5279 }
5280
5281 case METHOD -> {
5282 var method = (MethodSymbol)enclosed;
5283 if (serialMethodNames.contains(name)) {
5284 log.warning(
5285 TreeInfo.diagnosticPositionFor(method, tree),
5286 LintWarnings.IneffectualSerialMethodEnum(name));
5287 }
5288
5289 if (isExtern) {
5290 switch(name) {
5291 case "writeExternal" -> checkWriteExternalEnum(tree, e, method);
5292 case "readExternal" -> checkReadExternalEnum(tree, e, method);
5293 }
5294 }
5295 }
5296
5297 // Also perform checks on any class bodies of enum constants, see JLS 8.9.1.
5298 case ENUM_CONSTANT -> {
5299 var field = (VarSymbol)enclosed;
5300 JCVariableDecl decl = (JCVariableDecl) TreeInfo.declarationFor(field, p);
5301 if (decl.init instanceof JCNewClass nc && nc.def != null) {
5302 ClassSymbol enumConstantType = nc.def.sym;
5303 visitTypeAsEnum(enumConstantType, p);
5304 }
5305 }
5306
5307 }});
5308 }
5309 return null;
5310 }
5311
5312 private void checkWriteExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5313 //public void writeExternal(ObjectOutput) throws IOException
5314 checkExternMethodEnum(tree, e, method, syms.objectOutputType);
5315 }
5316
5317 private void checkReadExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5318 // public void readExternal(ObjectInput) throws IOException
5319 checkExternMethodEnum(tree, e, method, syms.objectInputType);
5320 }
5321
5322 private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5323 if (isExternMethod(tree, e, method, argType)) {
5324 log.warning(
5325 TreeInfo.diagnosticPositionFor(method, tree),
5326 LintWarnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
5327 }
5328 }
5329
5330 private boolean isExternMethod(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5331 long flags = method.flags();
5332 Type rtype = method.getReturnType();
5333
5334 // Not necessary to check throws clause in this context
5335 return (flags & PUBLIC) != 0 && (flags & STATIC) == 0 &&
5336 types.isSameType(syms.voidType, rtype) &&
5337 hasExactlyOneArgWithType(tree, e, method, argType);
5338 }
5339
5340 /**
5341 * Most serialization-related fields and methods on interfaces
5342 * are ineffectual or problematic.
5343 */
5344 @Override
5345 public Void visitTypeAsInterface(TypeElement e,
5346 JCClassDecl p) {
5347 for(Element el : e.getEnclosedElements()) {
5348 runUnderLint(el, p, (enclosed, tree) -> {
5349 String name = null;
5350 switch(enclosed.getKind()) {
5351 case FIELD -> {
5352 var field = (VarSymbol)enclosed;
5353 name = field.getSimpleName().toString();
5354 switch(name) {
5355 case "serialPersistentFields" -> {
5356 log.warning(
5357 TreeInfo.diagnosticPositionFor(field, tree),
5358 LintWarnings.IneffectualSerialFieldInterface);
5359 }
5360
5361 case "serialVersionUID" -> {
5362 checkSerialVersionUID(tree, e, field);
5363 }
5364 }
5365 }
5366
5367 case METHOD -> {
5368 var method = (MethodSymbol)enclosed;
5369 name = enclosed.getSimpleName().toString();
5370 if (serialMethodNames.contains(name)) {
5371 switch (name) {
5372 case
5373 "readObject",
5374 "readObjectNoData",
5375 "writeObject" -> checkPrivateMethod(tree, e, method);
5376
5377 case
5378 "writeReplace",
5379 "readResolve" -> checkDefaultIneffective(tree, e, method);
5380
5381 default -> throw new AssertionError();
5382 }
5383
5384 }
5385 }}
5386 });
5387 }
5388
5389 return null;
5390 }
5391
5392 private void checkPrivateMethod(JCClassDecl tree,
5393 Element e,
5394 MethodSymbol method) {
5395 if ((method.flags() & PRIVATE) == 0) {
5396 log.warning(
5397 TreeInfo.diagnosticPositionFor(method, tree),
5398 LintWarnings.NonPrivateMethodWeakerAccess);
5399 }
5400 }
5401
5402 private void checkDefaultIneffective(JCClassDecl tree,
5403 Element e,
5404 MethodSymbol method) {
5405 if ((method.flags() & DEFAULT) == DEFAULT) {
5406 log.warning(
5407 TreeInfo.diagnosticPositionFor(method, tree),
5408 LintWarnings.DefaultIneffective);
5409
5410 }
5411 }
5412
5413 @Override
5414 public Void visitTypeAsAnnotationType(TypeElement e,
5415 JCClassDecl p) {
5416 // Per the JLS, annotation types are not serializeable
5417 return null;
5418 }
5419
5420 /**
5421 * From the Java Object Serialization Specification, 1.13
5422 * Serialization of Records:
5423 *
5424 * "The process by which record objects are serialized or
5425 * externalized cannot be customized; any class-specific
5426 * writeObject, readObject, readObjectNoData, writeExternal,
5427 * and readExternal methods defined by record classes are
5428 * ignored during serialization and deserialization. However,
5429 * a substitute object to be serialized or a designate
5430 * replacement may be specified, by the writeReplace and
5431 * readResolve methods, respectively. Any
5432 * serialPersistentFields field declaration is
5433 * ignored. Documenting serializable fields and data for
5434 * record classes is unnecessary, since there is no variation
5435 * in the serial form, other than whether a substitute or
5436 * replacement object is used. The serialVersionUID of a
5437 * record class is 0L unless explicitly declared. The
5438 * requirement for matching serialVersionUID values is waived
5439 * for record classes."
5440 */
5441 @Override
5442 public Void visitTypeAsRecord(TypeElement e,
5443 JCClassDecl p) {
5444 boolean isExtern = isExternalizable((Type)e.asType());
5445 for(Element el : e.getEnclosedElements()) {
5446 runUnderLint(el, p, (enclosed, tree) -> {
5447 String name = enclosed.getSimpleName().toString();
5448 switch(enclosed.getKind()) {
5449 case FIELD -> {
5450 var field = (VarSymbol)enclosed;
5451 switch(name) {
5452 case "serialPersistentFields" -> {
5453 log.warning(
5454 TreeInfo.diagnosticPositionFor(field, tree),
5455 LintWarnings.IneffectualSerialFieldRecord);
5456 }
5457
5458 case "serialVersionUID" -> {
5459 // Could generate additional warning that
5460 // svuid value is not checked to match for
5461 // records.
5462 checkSerialVersionUID(tree, e, field);
5463 }}
5464 }
5465
5466 case METHOD -> {
5467 var method = (MethodSymbol)enclosed;
5468 switch(name) {
5469 case "writeReplace" -> checkWriteReplace(tree, e, method);
5470 case "readResolve" -> checkReadResolve(tree, e, method);
5471
5472 case "writeExternal" -> checkWriteExternalRecord(tree, e, method, isExtern);
5473 case "readExternal" -> checkReadExternalRecord(tree, e, method, isExtern);
5474
5475 default -> {
5476 if (serialMethodNames.contains(name)) {
5477 log.warning(
5478 TreeInfo.diagnosticPositionFor(method, tree),
5479 LintWarnings.IneffectualSerialMethodRecord(name));
5480 }
5481 }}
5482 }}});
5483 }
5484 return null;
5485 }
5486
5487 void checkConcreteInstanceMethod(JCClassDecl tree,
5488 Element enclosing,
5489 MethodSymbol method) {
5490 if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
5491 log.warning(
5492 TreeInfo.diagnosticPositionFor(method, tree),
5493 LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName()));
5494 }
5495 }
5496
5497 private void checkReturnType(JCClassDecl tree,
5498 Element enclosing,
5499 MethodSymbol method,
5500 Type expectedReturnType) {
5501 // Note: there may be complications checking writeReplace
5502 // and readResolve since they return Object and could, in
5503 // principle, have covariant overrides and any synthetic
5504 // bridge method would not be represented here for
5505 // checking.
5506 Type rtype = method.getReturnType();
5507 if (!types.isSameType(expectedReturnType, rtype)) {
5508 log.warning(
5509 TreeInfo.diagnosticPositionFor(method, tree),
5510 LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
5511 rtype, expectedReturnType));
5512 }
5513 }
5514
5515 private void checkOneArg(JCClassDecl tree,
5516 Element enclosing,
5517 MethodSymbol method,
5518 Type expectedType) {
5519 String name = method.getSimpleName().toString();
5520
5521 var parameters= method.getParameters();
5522
5523 if (parameters.size() != 1) {
5524 log.warning(
5525 TreeInfo.diagnosticPositionFor(method, tree),
5526 LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
5527 return;
5528 }
5529
5530 Type parameterType = parameters.get(0).asType();
5531 if (!types.isSameType(parameterType, expectedType)) {
5532 log.warning(
5533 TreeInfo.diagnosticPositionFor(method, tree),
5534 LintWarnings.SerialMethodParameterType(method.getSimpleName(),
5535 expectedType,
5536 parameterType));
5537 }
5538 }
5539
5540 private boolean hasExactlyOneArgWithType(JCClassDecl tree,
5541 Element enclosing,
5542 MethodSymbol method,
5543 Type expectedType) {
5544 var parameters = method.getParameters();
5545 return (parameters.size() == 1) &&
5546 types.isSameType(parameters.get(0).asType(), expectedType);
5547 }
5548
5549
5550 private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5551 var parameters = method.getParameters();
5552 if (!parameters.isEmpty()) {
5553 log.warning(
5554 TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
5555 LintWarnings.SerialMethodNoArgs(method.getSimpleName()));
5556 }
5557 }
5558
5559 private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5560 // If the enclosing class is externalizable, warn for the method
5561 if (isExternalizable((Type)enclosing.asType())) {
5562 log.warning(
5563 TreeInfo.diagnosticPositionFor(method, tree),
5564 LintWarnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
5565 }
5566 return;
5567 }
5568
5569 private void checkExceptions(JCClassDecl tree,
5570 Element enclosing,
5571 MethodSymbol method,
5572 Type... declaredExceptions) {
5573 for (Type thrownType: method.getThrownTypes()) {
5574 // For each exception in the throws clause of the
5575 // method, if not an Error and not a RuntimeException,
5576 // check if the exception is a subtype of a declared
5577 // exception from the throws clause of the
5578 // serialization method in question.
5579 if (types.isSubtype(thrownType, syms.runtimeExceptionType) ||
5580 types.isSubtype(thrownType, syms.errorType) ) {
5581 continue;
5582 } else {
5583 boolean declared = false;
5584 for (Type declaredException : declaredExceptions) {
5585 if (types.isSubtype(thrownType, declaredException)) {
5586 declared = true;
5587 continue;
5588 }
5589 }
5590 if (!declared) {
5591 log.warning(
5592 TreeInfo.diagnosticPositionFor(method, tree),
5593 LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(),
5594 thrownType));
5595 }
5596 }
5597 }
5598 return;
5599 }
5600
5601 private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) {
5602 Lint prevLint = lint;
5603 try {
5604 lint = lint.augment((Symbol) symbol);
5605
5606 if (lint.isEnabled(LintCategory.SERIAL)) {
5607 task.accept(symbol, p);
5608 }
5609
5610 return null;
5611 } finally {
5612 lint = prevLint;
5613 }
5614 }
5615
5616 }
5617
5618 void checkRequiresIdentity(JCTree tree, Lint lint) {
5619 switch (tree) {
5620 case JCClassDecl classDecl -> {
5621 Type st = types.supertype(classDecl.sym.type);
5622 if (st != null &&
5623 // no need to recheck j.l.Object, shortcut,
5624 st.tsym != syms.objectType.tsym &&
5625 // this one could be null, no explicit extends
5626 classDecl.extending != null) {
5627 checkIfIdentityIsExpected(classDecl.extending.pos(), st, lint);
5628 }
5629 for (JCExpression intrface: classDecl.implementing) {
5630 checkIfIdentityIsExpected(intrface.pos(), intrface.type, lint);
5631 }
5632 for (JCTypeParameter tp : classDecl.typarams) {
5633 checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5634 }
5635 }
5636 case JCVariableDecl variableDecl -> {
5637 if (variableDecl.vartype != null &&
5638 ((variableDecl.sym.flags_field & RECORD) == 0 ||
5639 (variableDecl.sym.flags_field & ~(Flags.PARAMETER | RECORD | GENERATED_MEMBER)) != 0)) {
5640 /* we don't want to warn twice so if this variable is a compiler generated parameter of
5641 * a canonical record constructor, we don't want to issue a warning as we will warn the
5642 * corresponding compiler generated private record field anyways
5643 */
5644 checkIfIdentityIsExpected(variableDecl.vartype.pos(), variableDecl.vartype.type, lint);
5645 }
5646 }
5647 case JCTypeCast typeCast -> checkIfIdentityIsExpected(typeCast.clazz.pos(), typeCast.clazz.type, lint);
5648 case JCBindingPattern bindingPattern -> {
5649 if (bindingPattern.var.vartype != null) {
5650 checkIfIdentityIsExpected(bindingPattern.var.vartype.pos(), bindingPattern.var.vartype.type, lint);
5651 }
5652 }
5653 case JCMethodDecl methodDecl -> {
5654 for (JCTypeParameter tp : methodDecl.typarams) {
5655 checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5656 }
5657 if (methodDecl.restype != null && !methodDecl.restype.type.hasTag(VOID)) {
5658 checkIfIdentityIsExpected(methodDecl.restype.pos(), methodDecl.restype.type, lint);
5659 }
5660 }
5661 case JCMemberReference mref -> {
5662 checkIfIdentityIsExpected(mref.expr.pos(), mref.target, lint);
5663 checkIfTypeParamsRequiresIdentity(mref.sym.getMetadata(), mref.typeargs, lint);
5664 }
5665 case JCPolyExpression poly
5666 when (poly instanceof JCNewClass || poly instanceof JCMethodInvocation) -> {
5667 if (poly instanceof JCNewClass newClass) {
5668 checkIfIdentityIsExpected(newClass.clazz.pos(), newClass.clazz.type, lint);
5669 }
5670 List<JCExpression> argExps = poly instanceof JCNewClass ?
5671 ((JCNewClass)poly).args :
5672 ((JCMethodInvocation)poly).args;
5673 Symbol msym = TreeInfo.symbolFor(poly);
5674 if (msym != null) {
5675 if (!argExps.isEmpty() && msym instanceof MethodSymbol ms && ms.params != null) {
5676 VarSymbol lastParam = ms.params.head;
5677 for (VarSymbol param: ms.params) {
5678 if ((param.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5679 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5680 }
5681 lastParam = param;
5682 argExps = argExps.tail;
5683 }
5684 while (argExps != null && !argExps.isEmpty() && lastParam != null) {
5685 if ((lastParam.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5686 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5687 }
5688 argExps = argExps.tail;
5689 }
5690 }
5691 checkIfTypeParamsRequiresIdentity(
5692 msym.getMetadata(),
5693 poly instanceof JCNewClass ?
5694 ((JCNewClass)poly).typeargs :
5695 ((JCMethodInvocation)poly).typeargs,
5696 lint);
5697 }
5698 }
5699 default -> throw new AssertionError("unexpected tree " + tree);
5700 }
5701 }
5702
5703 /** Check if a type required an identity class
5704 */
5705 private boolean checkIfIdentityIsExpected(DiagnosticPosition pos, Type t, Lint lint) {
5706 if (t != null &&
5707 lint != null &&
5708 lint.isEnabled(LintCategory.IDENTITY)) {
5709 RequiresIdentityVisitor requiresIdentityVisitor = new RequiresIdentityVisitor();
5710 // we need to avoid recursion due to self referencing type vars or captures, this is why we need a set
5711 requiresIdentityVisitor.visit(t, new HashSet<>());
5712 if (requiresIdentityVisitor.requiresWarning) {
5713 log.warning(pos, LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5714 return true;
5715 }
5716 }
5717 return false;
5718 }
5719
5720 // where
5721 private class RequiresIdentityVisitor extends Types.SimpleVisitor<Void, Set<Type>> {
5722 boolean requiresWarning = false;
5723
5724 @Override
5725 public Void visitType(Type t, Set<Type> seen) {
5726 return null;
5727 }
5728
5729 @Override
5730 public Void visitWildcardType(WildcardType t, Set<Type> seen) {
5731 return visit(t.type, seen);
5732 }
5733
5734 @Override
5735 public Void visitTypeVar(TypeVar t, Set<Type> seen) {
5736 if (seen.add(t)) {
5737 visit(t.getUpperBound(), seen);
5738 }
5739 return null;
5740 }
5741
5742 @Override
5743 public Void visitCapturedType(CapturedType t, Set<Type> seen) {
5744 if (seen.add(t)) {
5745 visit(t.getUpperBound(), seen);
5746 visit(t.getLowerBound(), seen);
5747 }
5748 return null;
5749 }
5750
5751 @Override
5752 public Void visitArrayType(ArrayType t, Set<Type> seen) {
5753 return visit(t.elemtype, seen);
5754 }
5755
5756 @Override
5757 public Void visitClassType(ClassType t, Set<Type> seen) {
5758 if (t != null && t.tsym != null) {
5759 SymbolMetadata sm = t.tsym.getMetadata();
5760 if (sm != null && !t.getTypeArguments().isEmpty()) {
5761 if (sm.getTypeAttributes().stream()
5762 .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5763 t.getTypeArguments().get(ta.position.parameter_index) != null &&
5764 t.getTypeArguments().get(ta.position.parameter_index).isValueBased()).findAny().isPresent()) {
5765 requiresWarning = true;
5766 return null;
5767 }
5768 }
5769 }
5770 visit(t.getEnclosingType(), seen);
5771 for (Type targ : t.getTypeArguments()) {
5772 visit(targ, seen);
5773 }
5774 return null;
5775 }
5776 } // RequiresIdentityVisitor
5777
5778 private void checkIfTypeParamsRequiresIdentity(SymbolMetadata sm,
5779 List<JCExpression> typeParamTrees,
5780 Lint lint) {
5781 if (typeParamTrees != null && !typeParamTrees.isEmpty()) {
5782 for (JCExpression targ : typeParamTrees) {
5783 checkIfIdentityIsExpected(targ.pos(), targ.type, lint);
5784 }
5785 if (sm != null)
5786 sm.getTypeAttributes().stream()
5787 .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5788 typeParamTrees.get(ta.position.parameter_index).type != null &&
5789 typeParamTrees.get(ta.position.parameter_index).type.isValueBased())
5790 .forEach(ta -> log.warning(typeParamTrees.get(ta.position.parameter_index).pos(),
5791 CompilerProperties.LintWarnings.AttemptToUseValueBasedWhereIdentityExpected));
5792 }
5793 }
5794
5795 private boolean isRequiresIdentityAnnotation(TypeSymbol annoType) {
5796 return annoType == syms.requiresIdentityType.tsym ||
5797 annoType.flatName() == syms.requiresIdentityInternalType.tsym.flatName();
5798 }
5799 }