1 /*
2 * Copyright (c) 1999, 2025, 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 && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3548 //cannot type annotate implicitly typed locals
3549 continue;
3550 } else if (s.kind == TYP || s.kind == VAR ||
3551 (s.kind == MTH && !s.isConstructor() &&
3552 !s.type.getReturnType().hasTag(VOID)) ||
3553 (s.kind == MTH && s.isConstructor())) {
3554 applicableTargets.add(names.TYPE_USE);
3555 }
3556 } else if (target == names.TYPE_PARAMETER) {
3557 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3558 applicableTargets.add(names.TYPE_PARAMETER);
3559 } else if (target == names.MODULE) {
3560 if (s.kind == MDL)
3561 applicableTargets.add(names.MODULE);
3562 } else {
3563 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3564 return Optional.empty(); // Unknown ElementType
3565 }
3566 }
3567 return Optional.of(applicableTargets);
3568 }
3569
3570 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3571 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3572 if (atTarget == null) return null; // ok, is applicable
3573 Attribute atValue = atTarget.member(names.value);
3574 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3575 }
3576
3577 private Name[] dfltTargetMeta;
3578 private Name[] defaultTargetMetaInfo() {
3579 if (dfltTargetMeta == null) {
3580 ArrayList<Name> defaultTargets = new ArrayList<>();
3581 defaultTargets.add(names.PACKAGE);
3582 defaultTargets.add(names.TYPE);
3583 defaultTargets.add(names.FIELD);
3584 defaultTargets.add(names.METHOD);
3585 defaultTargets.add(names.CONSTRUCTOR);
3586 defaultTargets.add(names.ANNOTATION_TYPE);
3587 defaultTargets.add(names.LOCAL_VARIABLE);
3588 defaultTargets.add(names.PARAMETER);
3589 if (allowRecords) {
3590 defaultTargets.add(names.RECORD_COMPONENT);
3591 }
3592 if (allowModules) {
3593 defaultTargets.add(names.MODULE);
3594 }
3595 dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3596 }
3597 return dfltTargetMeta;
3598 }
3599
3600 /** Check an annotation value.
3601 *
3602 * @param a The annotation tree to check
3603 * @return true if this annotation tree is valid, otherwise false
3604 */
3605 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3606 boolean res = false;
3607 final Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
3608 try {
3609 res = validateAnnotation(a);
3610 } finally {
3611 log.popDiagnosticHandler(diagHandler);
3612 }
3613 return res;
3614 }
3615
3616 private boolean validateAnnotation(JCAnnotation a) {
3617 boolean isValid = true;
3618 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3619
3620 // collect an inventory of the annotation elements
3621 Set<MethodSymbol> elements = metadata.getAnnotationElements();
3622
3623 // remove the ones that are assigned values
3624 for (JCTree arg : a.args) {
3625 if (!arg.hasTag(ASSIGN)) continue; // recovery
3626 JCAssign assign = (JCAssign)arg;
3627 Symbol m = TreeInfo.symbol(assign.lhs);
3628 if (m == null || m.type.isErroneous()) continue;
3629 if (!elements.remove(m)) {
3630 isValid = false;
3631 log.error(assign.lhs.pos(),
3632 Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3633 }
3634 }
3635
3636 // all the remaining ones better have default values
3637 List<Name> missingDefaults = List.nil();
3638 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3639 for (MethodSymbol m : elements) {
3640 if (m.type.isErroneous())
3641 continue;
3642
3643 if (!membersWithDefault.contains(m))
3644 missingDefaults = missingDefaults.append(m.name);
3645 }
3646 missingDefaults = missingDefaults.reverse();
3647 if (missingDefaults.nonEmpty()) {
3648 isValid = false;
3649 Error errorKey = (missingDefaults.size() > 1)
3650 ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3651 : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3652 log.error(a.pos(), errorKey);
3653 }
3654
3655 return isValid && validateTargetAnnotationValue(a);
3656 }
3657
3658 /* Validate the special java.lang.annotation.Target annotation */
3659 boolean validateTargetAnnotationValue(JCAnnotation a) {
3660 // special case: java.lang.annotation.Target must not have
3661 // repeated values in its value member
3662 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3663 a.args.tail == null)
3664 return true;
3665
3666 boolean isValid = true;
3667 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3668 JCAssign assign = (JCAssign) a.args.head;
3669 Symbol m = TreeInfo.symbol(assign.lhs);
3670 if (m.name != names.value) return false;
3671 JCTree rhs = assign.rhs;
3672 if (!rhs.hasTag(NEWARRAY)) return false;
3673 JCNewArray na = (JCNewArray) rhs;
3674 Set<Symbol> targets = new HashSet<>();
3675 for (JCTree elem : na.elems) {
3676 if (!targets.add(TreeInfo.symbol(elem))) {
3677 isValid = false;
3678 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3679 }
3680 }
3681 return isValid;
3682 }
3683
3684 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3685 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3686 (s.flags() & DEPRECATED) != 0 &&
3687 !syms.deprecatedType.isErroneous() &&
3688 s.attribute(syms.deprecatedType.tsym) == null) {
3689 log.warning(pos, LintWarnings.MissingDeprecatedAnnotation);
3690 }
3691 // Note: @Deprecated has no effect on local variables, parameters and package decls.
3692 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3693 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3694 log.warning(pos, LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3695 }
3696 }
3697 }
3698
3699 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3700 checkDeprecated(() -> pos, other, s);
3701 }
3702
3703 void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3704 if (!importSuppression
3705 && (s.isDeprecatedForRemoval() || s.isDeprecated() && !other.isDeprecated())
3706 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3707 && s.kind != Kind.PCK) {
3708 warnDeprecated(pos.get(), s);
3709 }
3710 }
3711
3712 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3713 if ((s.flags() & PROPRIETARY) != 0) {
3714 log.warning(pos, Warnings.SunProprietary(s));
3715 }
3716 }
3717
3718 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3719 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3720 log.error(pos, Errors.NotInProfile(s, profile));
3721 }
3722 }
3723
3724 void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3725 checkPreview(pos, other, Type.noType, s);
3726 }
3727
3728 void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) {
3729 boolean sIsPreview;
3730 Symbol previewSymbol;
3731 if ((s.flags() & PREVIEW_API) != 0) {
3732 sIsPreview = true;
3733 previewSymbol= s;
3734 } else if ((s.kind == Kind.MTH || s.kind == Kind.VAR) &&
3735 site.tsym != null &&
3736 (site.tsym.flags() & PREVIEW_API) == 0 &&
3737 (s.owner.flags() & PREVIEW_API) != 0) {
3738 //calling a method, or using a field, whose owner is a preview, but
3739 //using a site that is not a preview. Also produce an error or warning:
3740 sIsPreview = true;
3741 previewSymbol = s.owner;
3742 } else {
3743 sIsPreview = false;
3744 previewSymbol = null;
3745 }
3746 if (sIsPreview && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) {
3747 if ((previewSymbol.flags() & PREVIEW_REFLECTIVE) == 0) {
3748 if (!preview.isEnabled()) {
3749 log.error(pos, Errors.IsPreview(s));
3750 } else {
3751 preview.markUsesPreview(pos);
3752 warnPreviewAPI(pos, LintWarnings.IsPreview(s));
3753 }
3754 } else {
3755 warnPreviewAPI(pos, LintWarnings.IsPreviewReflective(s));
3756 }
3757 }
3758 if (preview.declaredUsingPreviewFeature(s)) {
3759 if (preview.isEnabled()) {
3760 //for preview disabled do presumably so not need to do anything?
3761 //If "s" is compiled from source, then there was an error for it already;
3762 //if "s" is from classfile, there already was an error for the classfile.
3763 preview.markUsesPreview(pos);
3764 warnPreviewAPI(pos, LintWarnings.DeclaredUsingPreview(kindName(s), s));
3765 }
3766 }
3767 }
3768
3769 void checkRestricted(DiagnosticPosition pos, Symbol s) {
3770 if (s.kind == MTH && (s.flags() & RESTRICTED) != 0) {
3771 log.warning(pos, LintWarnings.RestrictedMethod(s.enclClass(), s));
3772 }
3773 }
3774
3775 /* *************************************************************************
3776 * Check for recursive annotation elements.
3777 **************************************************************************/
3778
3779 /** Check for cycles in the graph of annotation elements.
3780 */
3781 void checkNonCyclicElements(JCClassDecl tree) {
3782 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3783 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3784 try {
3785 tree.sym.flags_field |= LOCKED;
3786 for (JCTree def : tree.defs) {
3787 if (!def.hasTag(METHODDEF)) continue;
3788 JCMethodDecl meth = (JCMethodDecl)def;
3789 checkAnnotationResType(meth.pos(), meth.restype.type);
3790 }
3791 } finally {
3792 tree.sym.flags_field &= ~LOCKED;
3793 tree.sym.flags_field |= ACYCLIC_ANN;
3794 }
3795 }
3796
3797 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3798 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3799 return;
3800 if ((tsym.flags_field & LOCKED) != 0) {
3801 log.error(pos, Errors.CyclicAnnotationElement(tsym));
3802 return;
3803 }
3804 try {
3805 tsym.flags_field |= LOCKED;
3806 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3807 if (s.kind != MTH)
3808 continue;
3809 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3810 }
3811 } finally {
3812 tsym.flags_field &= ~LOCKED;
3813 tsym.flags_field |= ACYCLIC_ANN;
3814 }
3815 }
3816
3817 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3818 switch (type.getTag()) {
3819 case CLASS:
3820 if ((type.tsym.flags() & ANNOTATION) != 0)
3821 checkNonCyclicElementsInternal(pos, type.tsym);
3822 break;
3823 case ARRAY:
3824 checkAnnotationResType(pos, types.elemtype(type));
3825 break;
3826 default:
3827 break; // int etc
3828 }
3829 }
3830
3831 /* *************************************************************************
3832 * Check for cycles in the constructor call graph.
3833 **************************************************************************/
3834
3835 /** Check for cycles in the graph of constructors calling other
3836 * constructors.
3837 */
3838 void checkCyclicConstructors(JCClassDecl tree) {
3839 // use LinkedHashMap so we generate errors deterministically
3840 Map<Symbol,Symbol> callMap = new LinkedHashMap<>();
3841
3842 // enter each constructor this-call into the map
3843 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3844 if (!TreeInfo.isConstructor(l.head))
3845 continue;
3846 JCMethodDecl meth = (JCMethodDecl)l.head;
3847 JCMethodInvocation app = TreeInfo.findConstructorCall(meth);
3848 if (app != null && TreeInfo.name(app.meth) == names._this) {
3849 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3850 } else {
3851 meth.sym.flags_field |= ACYCLIC;
3852 }
3853 }
3854
3855 // Check for cycles in the map
3856 Symbol[] ctors = new Symbol[0];
3857 ctors = callMap.keySet().toArray(ctors);
3858 for (Symbol caller : ctors) {
3859 checkCyclicConstructor(tree, caller, callMap);
3860 }
3861 }
3862
3863 /** Look in the map to see if the given constructor is part of a
3864 * call cycle.
3865 */
3866 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3867 Map<Symbol,Symbol> callMap) {
3868 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3869 if ((ctor.flags_field & LOCKED) != 0) {
3870 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)),
3871 Errors.RecursiveCtorInvocation);
3872 } else {
3873 ctor.flags_field |= LOCKED;
3874 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3875 ctor.flags_field &= ~LOCKED;
3876 }
3877 ctor.flags_field |= ACYCLIC;
3878 }
3879 }
3880
3881 /* *************************************************************************
3882 * Verify the proper placement of super()/this() calls.
3883 *
3884 * - super()/this() may only appear in constructors
3885 * - There must be at most one super()/this() call per constructor
3886 * - The super()/this() call, if any, must be a top-level statement in the
3887 * constructor, i.e., not nested inside any other statement or block
3888 * - There must be no return statements prior to the super()/this() call
3889 **************************************************************************/
3890
3891 void checkSuperInitCalls(JCClassDecl tree) {
3892 new SuperThisChecker().check(tree);
3893 }
3894
3895 private class SuperThisChecker extends TreeScanner {
3896
3897 // Match this scan stack: 1=JCMethodDecl, 2=JCExpressionStatement, 3=JCMethodInvocation
3898 private static final int MATCH_SCAN_DEPTH = 3;
3899
3900 private boolean constructor; // is this method a constructor?
3901 private boolean firstStatement; // at the first statement in method?
3902 private JCReturn earlyReturn; // first return prior to the super()/init(), if any
3903 private Name initCall; // whichever of "super" or "init" we've seen already
3904 private int scanDepth; // current scan recursion depth in method body
3905
3906 public void check(JCClassDecl classDef) {
3907 scan(classDef.defs);
3908 }
3909
3910 @Override
3911 public void visitMethodDef(JCMethodDecl tree) {
3912 Assert.check(!constructor);
3913 Assert.check(earlyReturn == null);
3914 Assert.check(initCall == null);
3915 Assert.check(scanDepth == 1);
3916
3917 // Initialize state for this method
3918 constructor = TreeInfo.isConstructor(tree);
3919 try {
3920
3921 // Scan method body
3922 if (tree.body != null) {
3923 firstStatement = true;
3924 for (List<JCStatement> l = tree.body.stats; l.nonEmpty(); l = l.tail) {
3925 scan(l.head);
3926 firstStatement = false;
3927 }
3928 }
3929
3930 // Verify no 'return' seen prior to an explicit super()/this() call
3931 if (constructor && earlyReturn != null && initCall != null)
3932 log.error(earlyReturn.pos(), Errors.ReturnBeforeSuperclassInitialized);
3933 } finally {
3934 firstStatement = false;
3935 constructor = false;
3936 earlyReturn = null;
3937 initCall = null;
3938 }
3939 }
3940
3941 @Override
3942 public void scan(JCTree tree) {
3943 scanDepth++;
3944 try {
3945 super.scan(tree);
3946 } finally {
3947 scanDepth--;
3948 }
3949 }
3950
3951 @Override
3952 public void visitApply(JCMethodInvocation apply) {
3953 do {
3954
3955 // Is this a super() or this() call?
3956 Name methodName = TreeInfo.name(apply.meth);
3957 if (methodName != names._super && methodName != names._this)
3958 break;
3959
3960 // super()/this() calls must only appear in a constructor
3961 if (!constructor) {
3962 log.error(apply.pos(), Errors.CallMustOnlyAppearInCtor);
3963 break;
3964 }
3965
3966 // super()/this() calls must be a top level statement
3967 if (scanDepth != MATCH_SCAN_DEPTH) {
3968 log.error(apply.pos(), Errors.CtorCallsNotAllowedHere);
3969 break;
3970 }
3971
3972 // super()/this() calls must not appear more than once
3973 if (initCall != null) {
3974 log.error(apply.pos(), Errors.RedundantSuperclassInit);
3975 break;
3976 }
3977
3978 // If super()/this() isn't first, require flexible constructors feature
3979 if (!firstStatement)
3980 preview.checkSourceLevel(apply.pos(), Feature.FLEXIBLE_CONSTRUCTORS);
3981
3982 // We found a legitimate super()/this() call; remember it
3983 initCall = methodName;
3984 } while (false);
3985
3986 // Proceed
3987 super.visitApply(apply);
3988 }
3989
3990 @Override
3991 public void visitReturn(JCReturn tree) {
3992 if (constructor && initCall == null && earlyReturn == null)
3993 earlyReturn = tree; // we have seen a return but not (yet) a super()/this()
3994 super.visitReturn(tree);
3995 }
3996
3997 @Override
3998 public void visitClassDef(JCClassDecl tree) {
3999 // don't descend any further
4000 }
4001
4002 @Override
4003 public void visitLambda(JCLambda tree) {
4004 final boolean constructorPrev = constructor;
4005 final boolean firstStatementPrev = firstStatement;
4006 final JCReturn earlyReturnPrev = earlyReturn;
4007 final Name initCallPrev = initCall;
4008 final int scanDepthPrev = scanDepth;
4009 constructor = false;
4010 firstStatement = false;
4011 earlyReturn = null;
4012 initCall = null;
4013 scanDepth = 0;
4014 try {
4015 super.visitLambda(tree);
4016 } finally {
4017 constructor = constructorPrev;
4018 firstStatement = firstStatementPrev;
4019 earlyReturn = earlyReturnPrev;
4020 initCall = initCallPrev;
4021 scanDepth = scanDepthPrev;
4022 }
4023 }
4024 }
4025
4026 /* *************************************************************************
4027 * Miscellaneous
4028 **************************************************************************/
4029
4030 /**
4031 * Check for division by integer constant zero
4032 * @param pos Position for error reporting.
4033 * @param operator The operator for the expression
4034 * @param operand The right hand operand for the expression
4035 */
4036 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
4037 if (operand.constValue() != null
4038 && operand.getTag().isSubRangeOf(LONG)
4039 && ((Number) (operand.constValue())).longValue() == 0) {
4040 int opc = ((OperatorSymbol)operator).opcode;
4041 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
4042 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
4043 log.warning(pos, LintWarnings.DivZero);
4044 }
4045 }
4046 }
4047
4048 /**
4049 * Check for bit shifts using an out-of-range bit count.
4050 * @param pos Position for error reporting.
4051 * @param operator The operator for the expression
4052 * @param operand The right hand operand for the expression
4053 */
4054 void checkOutOfRangeShift(final DiagnosticPosition pos, Symbol operator, Type operand) {
4055 if (operand.constValue() instanceof Number shiftAmount) {
4056 Type targetType;
4057 int maximumShift;
4058 switch (((OperatorSymbol)operator).opcode) {
4059 case ByteCodes.ishl, ByteCodes.ishr, ByteCodes.iushr, ByteCodes.ishll, ByteCodes.ishrl, ByteCodes.iushrl -> {
4060 targetType = syms.intType;
4061 maximumShift = 0x1f;
4062 }
4063 case ByteCodes.lshl, ByteCodes.lshr, ByteCodes.lushr, ByteCodes.lshll, ByteCodes.lshrl, ByteCodes.lushrl -> {
4064 targetType = syms.longType;
4065 maximumShift = 0x3f;
4066 }
4067 default -> {
4068 return;
4069 }
4070 }
4071 long specifiedShift = shiftAmount.longValue();
4072 if (specifiedShift > maximumShift || specifiedShift < -maximumShift) {
4073 int actualShift = (int)specifiedShift & (maximumShift - 1);
4074 log.warning(pos, LintWarnings.BitShiftOutOfRange(targetType, specifiedShift, actualShift));
4075 }
4076 }
4077 }
4078
4079 /**
4080 * Check for possible loss of precission
4081 * @param pos Position for error reporting.
4082 * @param found The computed type of the tree
4083 * @param req The computed type of the tree
4084 */
4085 void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
4086 if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
4087 log.warning(pos, LintWarnings.PossibleLossOfPrecision(found, req));
4088 }
4089 }
4090
4091 /**
4092 * Check for empty statements after if
4093 */
4094 void checkEmptyIf(JCIf tree) {
4095 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) {
4096 log.warning(tree.thenpart.pos(), LintWarnings.EmptyIf);
4097 }
4098 }
4099
4100 /** Check that symbol is unique in given scope.
4101 * @param pos Position for error reporting.
4102 * @param sym The symbol.
4103 * @param s The scope.
4104 */
4105 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
4106 if (sym.type.isErroneous())
4107 return true;
4108 if (sym.owner.name == names.any) return false;
4109 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
4110 if (sym != byName &&
4111 (byName.flags() & CLASH) == 0 &&
4112 sym.kind == byName.kind &&
4113 sym.name != names.error &&
4114 (sym.kind != MTH ||
4115 types.hasSameArgs(sym.type, byName.type) ||
4116 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
4117 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
4118 sym.flags_field |= CLASH;
4119 varargsDuplicateError(pos, sym, byName);
4120 return true;
4121 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
4122 duplicateErasureError(pos, sym, byName);
4123 sym.flags_field |= CLASH;
4124 return true;
4125 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
4126 (byName.flags() & MATCH_BINDING) != 0 &&
4127 (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
4128 if (!sym.type.isErroneous()) {
4129 log.error(pos, Errors.MatchBindingExists);
4130 sym.flags_field |= CLASH;
4131 }
4132 return false;
4133 } else {
4134 duplicateError(pos, byName);
4135 return false;
4136 }
4137 }
4138 }
4139 return true;
4140 }
4141
4142 /** Report duplicate declaration error.
4143 */
4144 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
4145 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
4146 log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
4147 }
4148 }
4149
4150 /**Check that types imported through the ordinary imports don't clash with types imported
4151 * by other (static or ordinary) imports. Note that two static imports may import two clashing
4152 * types without an error on the imports.
4153 * @param toplevel The toplevel tree for which the test should be performed.
4154 */
4155 void checkImportsUnique(JCCompilationUnit toplevel) {
4156 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
4157 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
4158 WriteableScope topLevelScope = toplevel.toplevelScope;
4159
4160 for (JCTree def : toplevel.defs) {
4161 if (!def.hasTag(IMPORT))
4162 continue;
4163
4164 JCImport imp = (JCImport) def;
4165
4166 if (imp.importScope == null)
4167 continue;
4168
4169 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
4170 if (imp.isStatic()) {
4171 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
4172 staticallyImportedSoFar.enter(sym);
4173 } else {
4174 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
4175 ordinallyImportedSoFar.enter(sym);
4176 }
4177 }
4178
4179 imp.importScope = null;
4180 }
4181 }
4182
4183 /** Check that single-type import is not already imported or top-level defined,
4184 * but make an exception for two single-type imports which denote the same type.
4185 * @param pos Position for error reporting.
4186 * @param ordinallyImportedSoFar A Scope containing types imported so far through
4187 * ordinary imports.
4188 * @param staticallyImportedSoFar A Scope containing types imported so far through
4189 * static imports.
4190 * @param topLevelScope The current file's top-level Scope
4191 * @param sym The symbol.
4192 * @param staticImport Whether or not this was a static import
4193 */
4194 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
4195 Scope staticallyImportedSoFar, Scope topLevelScope,
4196 Symbol sym, boolean staticImport) {
4197 Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
4198 Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
4199 Symbol staticClashing = null;
4200 if (ordinaryClashing == null && !staticImport) {
4201 staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
4202 }
4203 if (ordinaryClashing != null || staticClashing != null) {
4204 if (ordinaryClashing != null)
4205 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
4206 else
4207 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
4208 return false;
4209 }
4210 Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
4211 if (clashing != null) {
4212 log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
4213 return false;
4214 }
4215 return true;
4216 }
4217
4218 /** Check that a qualified name is in canonical form (for import decls).
4219 */
4220 public void checkCanonical(JCTree tree) {
4221 if (!isCanonical(tree))
4222 log.error(tree.pos(),
4223 Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
4224 }
4225 // where
4226 private boolean isCanonical(JCTree tree) {
4227 while (tree.hasTag(SELECT)) {
4228 JCFieldAccess s = (JCFieldAccess) tree;
4229 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
4230 return false;
4231 tree = s.selected;
4232 }
4233 return true;
4234 }
4235
4236 /** Check that an auxiliary class is not accessed from any other file than its own.
4237 */
4238 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
4239 if ((c.flags() & AUXILIARY) != 0 &&
4240 rs.isAccessible(env, c) &&
4241 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
4242 {
4243 log.warning(pos, LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
4244 }
4245 }
4246
4247 /**
4248 * Check for a default constructor in an exported package.
4249 */
4250 void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
4251 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
4252 ((c.flags() & (ENUM | RECORD)) == 0) &&
4253 !c.isAnonymous() &&
4254 ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
4255 Feature.MODULES.allowedInSource(source)) {
4256 NestingKind nestingKind = c.getNestingKind();
4257 switch (nestingKind) {
4258 case ANONYMOUS,
4259 LOCAL -> {return;}
4260 case TOP_LEVEL -> {;} // No additional checks needed
4261 case MEMBER -> {
4262 // For nested member classes, all the enclosing
4263 // classes must be public or protected.
4264 Symbol owner = c.owner;
4265 while (owner != null && owner.kind == TYP) {
4266 if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
4267 return;
4268 owner = owner.owner;
4269 }
4270 }
4271 }
4272
4273 // Only check classes in named packages exported by its module
4274 PackageSymbol pkg = c.packge();
4275 if (!pkg.isUnnamed()) {
4276 ModuleSymbol modle = pkg.modle;
4277 for (ExportsDirective exportDir : modle.exports) {
4278 // Report warning only if the containing
4279 // package is unconditionally exported
4280 if (exportDir.packge.equals(pkg)) {
4281 if (exportDir.modules == null || exportDir.modules.isEmpty()) {
4282 // Warning may be suppressed by
4283 // annotations; check again for being
4284 // enabled in the deferred context.
4285 log.warning(pos, LintWarnings.MissingExplicitCtor(c, pkg, modle));
4286 } else {
4287 return;
4288 }
4289 }
4290 }
4291 }
4292 }
4293 return;
4294 }
4295
4296 private class ConversionWarner extends Warner {
4297 final String uncheckedKey;
4298 final Type found;
4299 final Type expected;
4300 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
4301 super(pos);
4302 this.uncheckedKey = uncheckedKey;
4303 this.found = found;
4304 this.expected = expected;
4305 }
4306
4307 @Override
4308 public void warn(LintCategory lint) {
4309 boolean warned = this.warned;
4310 super.warn(lint);
4311 if (warned) return; // suppress redundant diagnostics
4312 switch (lint) {
4313 case UNCHECKED:
4314 Check.this.warnUnchecked(pos(), LintWarnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
4315 break;
4316 case VARARGS:
4317 if (method != null &&
4318 method.attribute(syms.trustMeType.tsym) != null &&
4319 isTrustMeAllowedOnMethod(method) &&
4320 !types.isReifiable(method.type.getParameterTypes().last())) {
4321 log.warning(pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last()));
4322 }
4323 break;
4324 default:
4325 throw new AssertionError("Unexpected lint: " + lint);
4326 }
4327 }
4328 }
4329
4330 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
4331 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
4332 }
4333
4334 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
4335 return new ConversionWarner(pos, "unchecked.assign", found, expected);
4336 }
4337
4338 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
4339 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
4340
4341 if (functionalType != null) {
4342 try {
4343 types.findDescriptorSymbol((TypeSymbol)cs);
4344 } catch (Types.FunctionDescriptorLookupError ex) {
4345 DiagnosticPosition pos = tree.pos();
4346 for (JCAnnotation a : tree.getModifiers().annotations) {
4347 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
4348 pos = a.pos();
4349 break;
4350 }
4351 }
4352 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
4353 }
4354 }
4355 }
4356
4357 public void checkImportsResolvable(final JCCompilationUnit toplevel) {
4358 for (final JCImportBase impBase : toplevel.getImports()) {
4359 if (!(impBase instanceof JCImport imp))
4360 continue;
4361 if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
4362 continue;
4363 final JCFieldAccess select = imp.qualid;
4364 final Symbol origin;
4365 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4366 continue;
4367
4368 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4369 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4370 log.error(imp.pos(),
4371 Errors.CantResolveLocation(KindName.STATIC,
4372 select.name,
4373 null,
4374 null,
4375 Fragments.Location(kindName(site),
4376 site,
4377 null)));
4378 }
4379 }
4380 }
4381
4382 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
4383 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4384 OUTER: for (JCImportBase impBase : toplevel.getImports()) {
4385 if (impBase instanceof JCImport imp && !imp.staticImport &&
4386 TreeInfo.name(imp.qualid) == names.asterisk) {
4387 TypeSymbol tsym = imp.qualid.selected.type.tsym;
4388 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4389 !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4390 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.qualid.selected.pos(), Errors.DoesntExist(tsym));
4391 }
4392 }
4393 }
4394 }
4395
4396 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4397 if (tsym == null || !processed.add(tsym))
4398 return false;
4399
4400 // also search through inherited names
4401 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4402 return true;
4403
4404 for (Type t : types.interfaces(tsym.type))
4405 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4406 return true;
4407
4408 for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4409 if (sym.isStatic() &&
4410 importAccessible(sym, packge) &&
4411 sym.isMemberOf(origin, types)) {
4412 return true;
4413 }
4414 }
4415
4416 return false;
4417 }
4418
4419 // is the sym accessible everywhere in packge?
4420 public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4421 try {
4422 int flags = (int)(sym.flags() & AccessFlags);
4423 switch (flags) {
4424 default:
4425 case PUBLIC:
4426 return true;
4427 case PRIVATE:
4428 return false;
4429 case 0:
4430 case PROTECTED:
4431 return sym.packge() == packge;
4432 }
4433 } catch (ClassFinder.BadClassFile err) {
4434 throw err;
4435 } catch (CompletionFailure ex) {
4436 return false;
4437 }
4438 }
4439
4440 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4441 JCCompilationUnit toplevel = env.toplevel;
4442
4443 if ( toplevel.modle == syms.unnamedModule
4444 || toplevel.modle == syms.noModule
4445 || (check.sym.flags() & COMPOUND) != 0) {
4446 return ;
4447 }
4448
4449 ExportsDirective currentExport = findExport(toplevel.packge);
4450
4451 if ( currentExport == null //not exported
4452 || currentExport.modules != null) //don't check classes in qualified export
4453 return ;
4454
4455 new TreeScanner() {
4456 Lint lint = env.info.lint;
4457 boolean inSuperType;
4458
4459 @Override
4460 public void visitBlock(JCBlock tree) {
4461 }
4462 @Override
4463 public void visitMethodDef(JCMethodDecl tree) {
4464 if (!isAPISymbol(tree.sym))
4465 return;
4466 Lint prevLint = lint;
4467 try {
4468 lint = lint.augment(tree.sym);
4469 if (lint.isEnabled(LintCategory.EXPORTS)) {
4470 super.visitMethodDef(tree);
4471 }
4472 } finally {
4473 lint = prevLint;
4474 }
4475 }
4476 @Override
4477 public void visitVarDef(JCVariableDecl tree) {
4478 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4479 return;
4480 Lint prevLint = lint;
4481 try {
4482 lint = lint.augment(tree.sym);
4483 if (lint.isEnabled(LintCategory.EXPORTS)) {
4484 scan(tree.mods);
4485 scan(tree.vartype);
4486 }
4487 } finally {
4488 lint = prevLint;
4489 }
4490 }
4491 @Override
4492 public void visitClassDef(JCClassDecl tree) {
4493 if (tree != check)
4494 return ;
4495
4496 if (!isAPISymbol(tree.sym))
4497 return ;
4498
4499 Lint prevLint = lint;
4500 try {
4501 lint = lint.augment(tree.sym);
4502 if (lint.isEnabled(LintCategory.EXPORTS)) {
4503 scan(tree.mods);
4504 scan(tree.typarams);
4505 try {
4506 inSuperType = true;
4507 scan(tree.extending);
4508 scan(tree.implementing);
4509 } finally {
4510 inSuperType = false;
4511 }
4512 scan(tree.defs);
4513 }
4514 } finally {
4515 lint = prevLint;
4516 }
4517 }
4518 @Override
4519 public void visitTypeApply(JCTypeApply tree) {
4520 scan(tree.clazz);
4521 boolean oldInSuperType = inSuperType;
4522 try {
4523 inSuperType = false;
4524 scan(tree.arguments);
4525 } finally {
4526 inSuperType = oldInSuperType;
4527 }
4528 }
4529 @Override
4530 public void visitIdent(JCIdent tree) {
4531 Symbol sym = TreeInfo.symbol(tree);
4532 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4533 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4534 }
4535 }
4536
4537 @Override
4538 public void visitSelect(JCFieldAccess tree) {
4539 Symbol sym = TreeInfo.symbol(tree);
4540 Symbol sitesym = TreeInfo.symbol(tree.selected);
4541 if (sym.kind == TYP && sitesym.kind == PCK) {
4542 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4543 } else {
4544 super.visitSelect(tree);
4545 }
4546 }
4547
4548 @Override
4549 public void visitAnnotation(JCAnnotation tree) {
4550 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4551 super.visitAnnotation(tree);
4552 }
4553
4554 }.scan(check);
4555 }
4556 //where:
4557 private ExportsDirective findExport(PackageSymbol pack) {
4558 for (ExportsDirective d : pack.modle.exports) {
4559 if (d.packge == pack)
4560 return d;
4561 }
4562
4563 return null;
4564 }
4565 private boolean isAPISymbol(Symbol sym) {
4566 while (sym.kind != PCK) {
4567 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4568 return false;
4569 }
4570 sym = sym.owner;
4571 }
4572 return true;
4573 }
4574 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4575 if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4576 log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4577 return ;
4578 }
4579
4580 PackageSymbol whatPackage = what.packge();
4581 ExportsDirective whatExport = findExport(whatPackage);
4582 ExportsDirective inExport = findExport(inPackage);
4583
4584 if (whatExport == null) { //package not exported:
4585 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4586 return ;
4587 }
4588
4589 if (whatExport.modules != null) {
4590 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4591 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4592 }
4593 }
4594
4595 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4596 //check that relativeTo.modle requires transitive what.modle, somehow:
4597 List<ModuleSymbol> todo = List.of(inPackage.modle);
4598
4599 while (todo.nonEmpty()) {
4600 ModuleSymbol current = todo.head;
4601 todo = todo.tail;
4602 if (current == whatPackage.modle)
4603 return ; //OK
4604 if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4605 continue; //for automatic modules, don't look into their dependencies
4606 for (RequiresDirective req : current.requires) {
4607 if (req.isTransitive()) {
4608 todo = todo.prepend(req.module);
4609 }
4610 }
4611 }
4612
4613 log.warning(pos, LintWarnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4614 }
4615 }
4616
4617 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4618 if (msym.kind != MDL) {
4619 log.warning(pos, LintWarnings.ModuleNotFound(msym));
4620 }
4621 }
4622
4623 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4624 if (packge.members().isEmpty() &&
4625 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4626 log.warning(pos, LintWarnings.PackageEmptyOrNotFound(packge));
4627 }
4628 }
4629
4630 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4631 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4632 if (rd.isTransitive()) { // see comment in Log.applyLint() for special logic that applies
4633 log.warning(pos, LintWarnings.RequiresTransitiveAutomatic);
4634 } else {
4635 log.warning(pos, LintWarnings.RequiresAutomatic);
4636 }
4637 }
4638 }
4639
4640 /**
4641 * Verify the case labels conform to the constraints. Checks constraints related
4642 * combinations of patterns and other labels.
4643 *
4644 * @param cases the cases that should be checked.
4645 */
4646 void checkSwitchCaseStructure(List<JCCase> cases) {
4647 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4648 JCCase c = l.head;
4649 if (c.labels.head instanceof JCConstantCaseLabel constLabel) {
4650 if (TreeInfo.isNull(constLabel.expr)) {
4651 if (c.labels.tail.nonEmpty()) {
4652 if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) {
4653 if (c.labels.tail.tail.nonEmpty()) {
4654 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4655 }
4656 } else {
4657 log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4658 }
4659 }
4660 } else {
4661 for (JCCaseLabel label : c.labels.tail) {
4662 if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) {
4663 log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4664 break;
4665 }
4666 }
4667 }
4668 } else if (c.labels.tail.nonEmpty()) {
4669 var patterCaseLabels = c.labels.stream().filter(ll -> ll instanceof JCPatternCaseLabel).map(cl -> (JCPatternCaseLabel)cl);
4670 var allUnderscore = patterCaseLabels.allMatch(pcl -> !hasBindings(pcl.getPattern()));
4671
4672 if (!allUnderscore) {
4673 log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern);
4674 }
4675
4676 boolean allPatternCaseLabels = c.labels.stream().allMatch(p -> p instanceof JCPatternCaseLabel);
4677
4678 if (allPatternCaseLabels) {
4679 preview.checkSourceLevel(c.labels.tail.head.pos(), Feature.UNNAMED_VARIABLES);
4680 }
4681
4682 for (JCCaseLabel label : c.labels.tail) {
4683 if (label instanceof JCConstantCaseLabel) {
4684 log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4685 break;
4686 }
4687 }
4688 }
4689 }
4690
4691 boolean isCaseStatementGroup = cases.nonEmpty() &&
4692 cases.head.caseKind == CaseTree.CaseKind.STATEMENT;
4693
4694 if (isCaseStatementGroup) {
4695 boolean previousCompletessNormally = false;
4696 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4697 JCCase c = l.head;
4698 if (previousCompletessNormally &&
4699 c.stats.nonEmpty() &&
4700 c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4701 (hasBindings(patternLabel.pat) || hasBindings(c.guard))) {
4702 log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern);
4703 } else if (c.stats.isEmpty() &&
4704 c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4705 (hasBindings(patternLabel.pat) || hasBindings(c.guard)) &&
4706 hasStatements(l.tail)) {
4707 log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern);
4708 }
4709 previousCompletessNormally = c.completesNormally;
4710 }
4711 }
4712 }
4713
4714 boolean hasBindings(JCTree p) {
4715 boolean[] bindings = new boolean[1];
4716
4717 new TreeScanner() {
4718 @Override
4719 public void visitBindingPattern(JCBindingPattern tree) {
4720 bindings[0] |= !tree.var.sym.isUnnamedVariable();
4721 super.visitBindingPattern(tree);
4722 }
4723 }.scan(p);
4724
4725 return bindings[0];
4726 }
4727
4728 boolean hasStatements(List<JCCase> cases) {
4729 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4730 if (l.head.stats.nonEmpty()) {
4731 return true;
4732 }
4733 }
4734
4735 return false;
4736 }
4737 void checkSwitchCaseLabelDominated(JCCaseLabel unconditionalCaseLabel, List<JCCase> cases) {
4738 List<Pair<JCCase, JCCaseLabel>> caseLabels = List.nil();
4739 boolean seenDefault = false;
4740 boolean seenDefaultLabel = false;
4741 boolean warnDominatedByDefault = false;
4742 boolean unconditionalFound = false;
4743
4744 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4745 JCCase c = l.head;
4746 for (JCCaseLabel label : c.labels) {
4747 if (label.hasTag(DEFAULTCASELABEL)) {
4748 seenDefault = true;
4749 seenDefaultLabel |=
4750 TreeInfo.isNullCaseLabel(c.labels.head);
4751 continue;
4752 }
4753 if (TreeInfo.isNullCaseLabel(label)) {
4754 if (seenDefault) {
4755 log.error(label.pos(), Errors.PatternDominated);
4756 }
4757 continue;
4758 }
4759 if (seenDefault && !warnDominatedByDefault) {
4760 if (label.hasTag(PATTERNCASELABEL) ||
4761 (label instanceof JCConstantCaseLabel && seenDefaultLabel)) {
4762 log.error(label.pos(), Errors.PatternDominated);
4763 warnDominatedByDefault = true;
4764 }
4765 }
4766 Type currentType = labelType(label);
4767 for (Pair<JCCase, JCCaseLabel> caseAndLabel : caseLabels) {
4768 JCCase testCase = caseAndLabel.fst;
4769 JCCaseLabel testCaseLabel = caseAndLabel.snd;
4770 Type testType = labelType(testCaseLabel);
4771
4772 // an unconditional pattern cannot be followed by any other label
4773 if (allowPrimitivePatterns && unconditionalCaseLabel == testCaseLabel && unconditionalCaseLabel != label) {
4774 log.error(label.pos(), Errors.PatternDominated);
4775 continue;
4776 }
4777
4778 boolean dominated = false;
4779 if (!currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) {
4780 // the current label is potentially dominated by the existing (test) label, check:
4781 if (types.isUnconditionallyExactCombined(currentType, testType) &&
4782 label instanceof JCConstantCaseLabel) {
4783 dominated = !(testCaseLabel instanceof JCConstantCaseLabel) &&
4784 TreeInfo.unguardedCase(testCase);
4785 } else if (label instanceof JCPatternCaseLabel patternCL &&
4786 testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel &&
4787 (testCase.equals(c) || TreeInfo.unguardedCase(testCase))) {
4788 dominated = patternDominated(testPatternCaseLabel.pat, patternCL.pat);
4789 }
4790 }
4791 if (dominated) {
4792 log.error(label.pos(), Errors.PatternDominated);
4793 }
4794 }
4795 caseLabels = caseLabels.prepend(Pair.of(c, label));
4796 }
4797 }
4798 }
4799 //where:
4800 private Type labelType(JCCaseLabel label) {
4801 return types.erasure(switch (label.getTag()) {
4802 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type;
4803 case CONSTANTCASELABEL -> ((JCConstantCaseLabel) label).expr.type;
4804 default -> throw Assert.error("Unexpected tree kind: " + label.getTag());
4805 });
4806 }
4807 private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) {
4808 Type existingPatternType = types.erasure(existingPattern.type);
4809 Type currentPatternType = types.erasure(currentPattern.type);
4810 if (!types.isUnconditionallyExactTypeBased(currentPatternType, existingPatternType)) {
4811 return false;
4812 }
4813 if (currentPattern instanceof JCBindingPattern ||
4814 currentPattern instanceof JCAnyPattern) {
4815 return existingPattern instanceof JCBindingPattern ||
4816 existingPattern instanceof JCAnyPattern;
4817 } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) {
4818 if (existingPattern instanceof JCBindingPattern ||
4819 existingPattern instanceof JCAnyPattern) {
4820 return true;
4821 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) {
4822 List<JCPattern> existingNested = existingRecordPattern.nested;
4823 List<JCPattern> currentNested = currentRecordPattern.nested;
4824 if (existingNested.size() != currentNested.size()) {
4825 return false;
4826 }
4827 while (existingNested.nonEmpty()) {
4828 if (!patternDominated(existingNested.head, currentNested.head)) {
4829 return false;
4830 }
4831 existingNested = existingNested.tail;
4832 currentNested = currentNested.tail;
4833 }
4834 return true;
4835 } else {
4836 Assert.error("Unknown pattern: " + existingPattern.getTag());
4837 }
4838 } else {
4839 Assert.error("Unknown pattern: " + currentPattern.getTag());
4840 }
4841 return false;
4842 }
4843
4844 /** check if a type is a subtype of Externalizable, if that is available. */
4845 boolean isExternalizable(Type t) {
4846 try {
4847 syms.externalizableType.complete();
4848 } catch (CompletionFailure e) {
4849 return false;
4850 }
4851 return types.isSubtype(t, syms.externalizableType);
4852 }
4853
4854 /**
4855 * Check structure of serialization declarations.
4856 */
4857 public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) {
4858 (new SerialTypeVisitor()).visit(c, tree);
4859 }
4860
4861 /**
4862 * This visitor will warn if a serialization-related field or
4863 * method is declared in a suspicious or incorrect way. In
4864 * particular, it will warn for cases where the runtime
4865 * serialization mechanism will silently ignore a mis-declared
4866 * entity.
4867 *
4868 * Distinguished serialization-related fields and methods:
4869 *
4870 * Methods:
4871 *
4872 * private void writeObject(ObjectOutputStream stream) throws IOException
4873 * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
4874 *
4875 * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
4876 * private void readObjectNoData() throws ObjectStreamException
4877 * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
4878 *
4879 * Fields:
4880 *
4881 * private static final long serialVersionUID
4882 * private static final ObjectStreamField[] serialPersistentFields
4883 *
4884 * Externalizable: methods defined on the interface
4885 * public void writeExternal(ObjectOutput) throws IOException
4886 * public void readExternal(ObjectInput) throws IOException
4887 */
4888 private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> {
4889 SerialTypeVisitor() {
4890 this.lint = Check.this.lint;
4891 }
4892
4893 private static final Set<String> serialMethodNames =
4894 Set.of("writeObject", "writeReplace",
4895 "readObject", "readObjectNoData",
4896 "readResolve");
4897
4898 private static final Set<String> serialFieldNames =
4899 Set.of("serialVersionUID", "serialPersistentFields");
4900
4901 // Type of serialPersistentFields
4902 private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass);
4903
4904 Lint lint;
4905
4906 @Override
4907 public Void defaultAction(Element e, JCClassDecl p) {
4908 throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), ""));
4909 }
4910
4911 @Override
4912 public Void visitType(TypeElement e, JCClassDecl p) {
4913 runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param));
4914 return null;
4915 }
4916
4917 @Override
4918 public Void visitTypeAsClass(TypeElement e,
4919 JCClassDecl p) {
4920 // Anonymous classes filtered out by caller.
4921
4922 ClassSymbol c = (ClassSymbol)e;
4923
4924 checkCtorAccess(p, c);
4925
4926 // Check for missing serialVersionUID; check *not* done
4927 // for enums or records.
4928 VarSymbol svuidSym = null;
4929 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4930 if (sym.kind == VAR) {
4931 svuidSym = (VarSymbol)sym;
4932 break;
4933 }
4934 }
4935
4936 if (svuidSym == null) {
4937 log.warning(p.pos(), LintWarnings.MissingSVUID(c));
4938 }
4939
4940 // Check for serialPersistentFields to gate checks for
4941 // non-serializable non-transient instance fields
4942 boolean serialPersistentFieldsPresent =
4943 c.members()
4944 .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR)
4945 .iterator()
4946 .hasNext();
4947
4948 // Check declarations of serialization-related methods and
4949 // fields
4950 for(Symbol el : c.getEnclosedElements()) {
4951 runUnderLint(el, p, (enclosed, tree) -> {
4952 String name = null;
4953 switch(enclosed.getKind()) {
4954 case FIELD -> {
4955 if (!serialPersistentFieldsPresent) {
4956 var flags = enclosed.flags();
4957 if ( ((flags & TRANSIENT) == 0) &&
4958 ((flags & STATIC) == 0)) {
4959 Type varType = enclosed.asType();
4960 if (!canBeSerialized(varType)) {
4961 // Note per JLS arrays are
4962 // serializable even if the
4963 // component type is not.
4964 log.warning(
4965 TreeInfo.diagnosticPositionFor(enclosed, tree),
4966 LintWarnings.NonSerializableInstanceField);
4967 } else if (varType.hasTag(ARRAY)) {
4968 ArrayType arrayType = (ArrayType)varType;
4969 Type elementType = arrayType.elemtype;
4970 while (elementType.hasTag(ARRAY)) {
4971 arrayType = (ArrayType)elementType;
4972 elementType = arrayType.elemtype;
4973 }
4974 if (!canBeSerialized(elementType)) {
4975 log.warning(
4976 TreeInfo.diagnosticPositionFor(enclosed, tree),
4977 LintWarnings.NonSerializableInstanceFieldArray(elementType));
4978 }
4979 }
4980 }
4981 }
4982
4983 name = enclosed.getSimpleName().toString();
4984 if (serialFieldNames.contains(name)) {
4985 VarSymbol field = (VarSymbol)enclosed;
4986 switch (name) {
4987 case "serialVersionUID" -> checkSerialVersionUID(tree, e, field);
4988 case "serialPersistentFields" -> checkSerialPersistentFields(tree, e, field);
4989 default -> throw new AssertionError();
4990 }
4991 }
4992 }
4993
4994 // Correctly checking the serialization-related
4995 // methods is subtle. For the methods declared to be
4996 // private or directly declared in the class, the
4997 // enclosed elements of the class can be checked in
4998 // turn. However, writeReplace and readResolve can be
4999 // declared in a superclass and inherited. Note that
5000 // the runtime lookup walks the superclass chain
5001 // looking for writeReplace/readResolve via
5002 // Class.getDeclaredMethod. This differs from calling
5003 // Elements.getAllMembers(TypeElement) as the latter
5004 // will also pull in default methods from
5005 // superinterfaces. In other words, the runtime checks
5006 // (which long predate default methods on interfaces)
5007 // do not admit the possibility of inheriting methods
5008 // this way, a difference from general inheritance.
5009
5010 // The current implementation just checks the enclosed
5011 // elements and does not directly check the inherited
5012 // methods. If all the types are being checked this is
5013 // less of a concern; however, there are cases that
5014 // could be missed. In particular, readResolve and
5015 // writeReplace could, in principle, by inherited from
5016 // a non-serializable superclass and thus not checked
5017 // even if compiled with a serializable child class.
5018 case METHOD -> {
5019 var method = (MethodSymbol)enclosed;
5020 name = method.getSimpleName().toString();
5021 if (serialMethodNames.contains(name)) {
5022 switch (name) {
5023 case "writeObject" -> checkWriteObject(tree, e, method);
5024 case "writeReplace" -> checkWriteReplace(tree,e, method);
5025 case "readObject" -> checkReadObject(tree,e, method);
5026 case "readObjectNoData" -> checkReadObjectNoData(tree, e, method);
5027 case "readResolve" -> checkReadResolve(tree, e, method);
5028 default -> throw new AssertionError();
5029 }
5030 }
5031 }
5032 }
5033 });
5034 }
5035
5036 return null;
5037 }
5038
5039 boolean canBeSerialized(Type type) {
5040 return type.isPrimitive() || rs.isSerializable(type);
5041 }
5042
5043 /**
5044 * Check that Externalizable class needs a public no-arg
5045 * constructor.
5046 *
5047 * Check that a Serializable class has access to the no-arg
5048 * constructor of its first nonserializable superclass.
5049 */
5050 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5051 if (isExternalizable(c.type)) {
5052 for(var sym : c.getEnclosedElements()) {
5053 if (sym.isConstructor() &&
5054 ((sym.flags() & PUBLIC) == PUBLIC)) {
5055 if (((MethodSymbol)sym).getParameters().isEmpty()) {
5056 return;
5057 }
5058 }
5059 }
5060 log.warning(tree.pos(),
5061 LintWarnings.ExternalizableMissingPublicNoArgCtor);
5062 } else {
5063 // Approximate access to the no-arg constructor up in
5064 // the superclass chain by checking that the
5065 // constructor is not private. This may not handle
5066 // some cross-package situations correctly.
5067 Type superClass = c.getSuperclass();
5068 // java.lang.Object is *not* Serializable so this loop
5069 // should terminate.
5070 while (rs.isSerializable(superClass) ) {
5071 try {
5072 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5073 } catch(ClassCastException cce) {
5074 return ; // Don't try to recover
5075 }
5076 }
5077 // Non-Serializable superclass
5078 try {
5079 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5080 for(var sym : supertype.getEnclosedElements()) {
5081 if (sym.isConstructor()) {
5082 MethodSymbol ctor = (MethodSymbol)sym;
5083 if (ctor.getParameters().isEmpty()) {
5084 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5085 // Handle nested classes and implicit this$0
5086 (supertype.getNestingKind() == NestingKind.MEMBER &&
5087 ((supertype.flags() & STATIC) == 0)))
5088 log.warning(tree.pos(),
5089 LintWarnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5090 }
5091 }
5092 }
5093 } catch (ClassCastException cce) {
5094 return ; // Don't try to recover
5095 }
5096 return;
5097 }
5098 }
5099
5100 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5101 // To be effective, serialVersionUID must be marked static
5102 // and final, but private is recommended. But alas, in
5103 // practice there are many non-private serialVersionUID
5104 // fields.
5105 if ((svuid.flags() & (STATIC | FINAL)) !=
5106 (STATIC | FINAL)) {
5107 log.warning(
5108 TreeInfo.diagnosticPositionFor(svuid, tree),
5109 LintWarnings.ImproperSVUID((Symbol)e));
5110 }
5111
5112 // check svuid has type long
5113 if (!svuid.type.hasTag(LONG)) {
5114 log.warning(
5115 TreeInfo.diagnosticPositionFor(svuid, tree),
5116 LintWarnings.LongSVUID((Symbol)e));
5117 }
5118
5119 if (svuid.getConstValue() == null)
5120 log.warning(
5121 TreeInfo.diagnosticPositionFor(svuid, tree),
5122 LintWarnings.ConstantSVUID((Symbol)e));
5123 }
5124
5125 private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
5126 // To be effective, serialPersisentFields must be private, static, and final.
5127 if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
5128 (PRIVATE | STATIC | FINAL)) {
5129 log.warning(
5130 TreeInfo.diagnosticPositionFor(spf, tree),
5131 LintWarnings.ImproperSPF);
5132 }
5133
5134 if (!types.isSameType(spf.type, OSF_TYPE)) {
5135 log.warning(
5136 TreeInfo.diagnosticPositionFor(spf, tree),
5137 LintWarnings.OSFArraySPF);
5138 }
5139
5140 if (isExternalizable((Type)(e.asType()))) {
5141 log.warning(
5142 TreeInfo.diagnosticPositionFor(spf, tree),
5143 LintWarnings.IneffectualSerialFieldExternalizable);
5144 }
5145
5146 // Warn if serialPersistentFields is initialized to a
5147 // literal null.
5148 JCTree spfDecl = TreeInfo.declarationFor(spf, tree);
5149 if (spfDecl != null && spfDecl.getTag() == VARDEF) {
5150 JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
5151 JCExpression initExpr = variableDef.init;
5152 if (initExpr != null && TreeInfo.isNull(initExpr)) {
5153 log.warning(initExpr.pos(),
5154 LintWarnings.SPFNullInit);
5155 }
5156 }
5157 }
5158
5159 private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) {
5160 // The "synchronized" modifier is seen in the wild on
5161 // readObject and writeObject methods and is generally
5162 // innocuous.
5163
5164 // private void writeObject(ObjectOutputStream stream) throws IOException
5165 checkPrivateNonStaticMethod(tree, method);
5166 checkReturnType(tree, e, method, syms.voidType);
5167 checkOneArg(tree, e, method, syms.objectOutputStreamType);
5168 checkExceptions(tree, e, method, syms.ioExceptionType);
5169 checkExternalizable(tree, e, method);
5170 }
5171
5172 private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) {
5173 // ANY-ACCESS-MODIFIER Object writeReplace() throws
5174 // ObjectStreamException
5175
5176 // Excluding abstract, could have a more complicated
5177 // rule based on abstract-ness of the class
5178 checkConcreteInstanceMethod(tree, e, method);
5179 checkReturnType(tree, e, method, syms.objectType);
5180 checkNoArgs(tree, e, method);
5181 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5182 }
5183
5184 private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) {
5185 // The "synchronized" modifier is seen in the wild on
5186 // readObject and writeObject methods and is generally
5187 // innocuous.
5188
5189 // private void readObject(ObjectInputStream stream)
5190 // throws IOException, ClassNotFoundException
5191 checkPrivateNonStaticMethod(tree, method);
5192 checkReturnType(tree, e, method, syms.voidType);
5193 checkOneArg(tree, e, method, syms.objectInputStreamType);
5194 checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType);
5195 checkExternalizable(tree, e, method);
5196 }
5197
5198 private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) {
5199 // private void readObjectNoData() throws ObjectStreamException
5200 checkPrivateNonStaticMethod(tree, method);
5201 checkReturnType(tree, e, method, syms.voidType);
5202 checkNoArgs(tree, e, method);
5203 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5204 checkExternalizable(tree, e, method);
5205 }
5206
5207 private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) {
5208 // ANY-ACCESS-MODIFIER Object readResolve()
5209 // throws ObjectStreamException
5210
5211 // Excluding abstract, could have a more complicated
5212 // rule based on abstract-ness of the class
5213 checkConcreteInstanceMethod(tree, e, method);
5214 checkReturnType(tree,e, method, syms.objectType);
5215 checkNoArgs(tree, e, method);
5216 checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5217 }
5218
5219 private void checkWriteExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5220 //public void writeExternal(ObjectOutput) throws IOException
5221 checkExternMethodRecord(tree, e, method, syms.objectOutputType, isExtern);
5222 }
5223
5224 private void checkReadExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5225 // public void readExternal(ObjectInput) throws IOException
5226 checkExternMethodRecord(tree, e, method, syms.objectInputType, isExtern);
5227 }
5228
5229 private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType,
5230 boolean isExtern) {
5231 if (isExtern && isExternMethod(tree, e, method, argType)) {
5232 log.warning(
5233 TreeInfo.diagnosticPositionFor(method, tree),
5234 LintWarnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
5235 }
5236 }
5237
5238 void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
5239 var flags = method.flags();
5240 if ((flags & PRIVATE) == 0) {
5241 log.warning(
5242 TreeInfo.diagnosticPositionFor(method, tree),
5243 LintWarnings.SerialMethodNotPrivate(method.getSimpleName()));
5244 }
5245
5246 if ((flags & STATIC) != 0) {
5247 log.warning(
5248 TreeInfo.diagnosticPositionFor(method, tree),
5249 LintWarnings.SerialMethodStatic(method.getSimpleName()));
5250 }
5251 }
5252
5253 /**
5254 * Per section 1.12 "Serialization of Enum Constants" of
5255 * the serialization specification, due to the special
5256 * serialization handling of enums, any writeObject,
5257 * readObject, writeReplace, and readResolve methods are
5258 * ignored as are serialPersistentFields and
5259 * serialVersionUID fields.
5260 */
5261 @Override
5262 public Void visitTypeAsEnum(TypeElement e,
5263 JCClassDecl p) {
5264 boolean isExtern = isExternalizable((Type)e.asType());
5265 for(Element el : e.getEnclosedElements()) {
5266 runUnderLint(el, p, (enclosed, tree) -> {
5267 String name = enclosed.getSimpleName().toString();
5268 switch(enclosed.getKind()) {
5269 case FIELD -> {
5270 var field = (VarSymbol)enclosed;
5271 if (serialFieldNames.contains(name)) {
5272 log.warning(
5273 TreeInfo.diagnosticPositionFor(field, tree),
5274 LintWarnings.IneffectualSerialFieldEnum(name));
5275 }
5276 }
5277
5278 case METHOD -> {
5279 var method = (MethodSymbol)enclosed;
5280 if (serialMethodNames.contains(name)) {
5281 log.warning(
5282 TreeInfo.diagnosticPositionFor(method, tree),
5283 LintWarnings.IneffectualSerialMethodEnum(name));
5284 }
5285
5286 if (isExtern) {
5287 switch(name) {
5288 case "writeExternal" -> checkWriteExternalEnum(tree, e, method);
5289 case "readExternal" -> checkReadExternalEnum(tree, e, method);
5290 }
5291 }
5292 }
5293
5294 // Also perform checks on any class bodies of enum constants, see JLS 8.9.1.
5295 case ENUM_CONSTANT -> {
5296 var field = (VarSymbol)enclosed;
5297 JCVariableDecl decl = (JCVariableDecl) TreeInfo.declarationFor(field, p);
5298 if (decl.init instanceof JCNewClass nc && nc.def != null) {
5299 ClassSymbol enumConstantType = nc.def.sym;
5300 visitTypeAsEnum(enumConstantType, p);
5301 }
5302 }
5303
5304 }});
5305 }
5306 return null;
5307 }
5308
5309 private void checkWriteExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5310 //public void writeExternal(ObjectOutput) throws IOException
5311 checkExternMethodEnum(tree, e, method, syms.objectOutputType);
5312 }
5313
5314 private void checkReadExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5315 // public void readExternal(ObjectInput) throws IOException
5316 checkExternMethodEnum(tree, e, method, syms.objectInputType);
5317 }
5318
5319 private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5320 if (isExternMethod(tree, e, method, argType)) {
5321 log.warning(
5322 TreeInfo.diagnosticPositionFor(method, tree),
5323 LintWarnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
5324 }
5325 }
5326
5327 private boolean isExternMethod(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5328 long flags = method.flags();
5329 Type rtype = method.getReturnType();
5330
5331 // Not necessary to check throws clause in this context
5332 return (flags & PUBLIC) != 0 && (flags & STATIC) == 0 &&
5333 types.isSameType(syms.voidType, rtype) &&
5334 hasExactlyOneArgWithType(tree, e, method, argType);
5335 }
5336
5337 /**
5338 * Most serialization-related fields and methods on interfaces
5339 * are ineffectual or problematic.
5340 */
5341 @Override
5342 public Void visitTypeAsInterface(TypeElement e,
5343 JCClassDecl p) {
5344 for(Element el : e.getEnclosedElements()) {
5345 runUnderLint(el, p, (enclosed, tree) -> {
5346 String name = null;
5347 switch(enclosed.getKind()) {
5348 case FIELD -> {
5349 var field = (VarSymbol)enclosed;
5350 name = field.getSimpleName().toString();
5351 switch(name) {
5352 case "serialPersistentFields" -> {
5353 log.warning(
5354 TreeInfo.diagnosticPositionFor(field, tree),
5355 LintWarnings.IneffectualSerialFieldInterface);
5356 }
5357
5358 case "serialVersionUID" -> {
5359 checkSerialVersionUID(tree, e, field);
5360 }
5361 }
5362 }
5363
5364 case METHOD -> {
5365 var method = (MethodSymbol)enclosed;
5366 name = enclosed.getSimpleName().toString();
5367 if (serialMethodNames.contains(name)) {
5368 switch (name) {
5369 case
5370 "readObject",
5371 "readObjectNoData",
5372 "writeObject" -> checkPrivateMethod(tree, e, method);
5373
5374 case
5375 "writeReplace",
5376 "readResolve" -> checkDefaultIneffective(tree, e, method);
5377
5378 default -> throw new AssertionError();
5379 }
5380
5381 }
5382 }}
5383 });
5384 }
5385
5386 return null;
5387 }
5388
5389 private void checkPrivateMethod(JCClassDecl tree,
5390 Element e,
5391 MethodSymbol method) {
5392 if ((method.flags() & PRIVATE) == 0) {
5393 log.warning(
5394 TreeInfo.diagnosticPositionFor(method, tree),
5395 LintWarnings.NonPrivateMethodWeakerAccess);
5396 }
5397 }
5398
5399 private void checkDefaultIneffective(JCClassDecl tree,
5400 Element e,
5401 MethodSymbol method) {
5402 if ((method.flags() & DEFAULT) == DEFAULT) {
5403 log.warning(
5404 TreeInfo.diagnosticPositionFor(method, tree),
5405 LintWarnings.DefaultIneffective);
5406
5407 }
5408 }
5409
5410 @Override
5411 public Void visitTypeAsAnnotationType(TypeElement e,
5412 JCClassDecl p) {
5413 // Per the JLS, annotation types are not serializeable
5414 return null;
5415 }
5416
5417 /**
5418 * From the Java Object Serialization Specification, 1.13
5419 * Serialization of Records:
5420 *
5421 * "The process by which record objects are serialized or
5422 * externalized cannot be customized; any class-specific
5423 * writeObject, readObject, readObjectNoData, writeExternal,
5424 * and readExternal methods defined by record classes are
5425 * ignored during serialization and deserialization. However,
5426 * a substitute object to be serialized or a designate
5427 * replacement may be specified, by the writeReplace and
5428 * readResolve methods, respectively. Any
5429 * serialPersistentFields field declaration is
5430 * ignored. Documenting serializable fields and data for
5431 * record classes is unnecessary, since there is no variation
5432 * in the serial form, other than whether a substitute or
5433 * replacement object is used. The serialVersionUID of a
5434 * record class is 0L unless explicitly declared. The
5435 * requirement for matching serialVersionUID values is waived
5436 * for record classes."
5437 */
5438 @Override
5439 public Void visitTypeAsRecord(TypeElement e,
5440 JCClassDecl p) {
5441 boolean isExtern = isExternalizable((Type)e.asType());
5442 for(Element el : e.getEnclosedElements()) {
5443 runUnderLint(el, p, (enclosed, tree) -> {
5444 String name = enclosed.getSimpleName().toString();
5445 switch(enclosed.getKind()) {
5446 case FIELD -> {
5447 var field = (VarSymbol)enclosed;
5448 switch(name) {
5449 case "serialPersistentFields" -> {
5450 log.warning(
5451 TreeInfo.diagnosticPositionFor(field, tree),
5452 LintWarnings.IneffectualSerialFieldRecord);
5453 }
5454
5455 case "serialVersionUID" -> {
5456 // Could generate additional warning that
5457 // svuid value is not checked to match for
5458 // records.
5459 checkSerialVersionUID(tree, e, field);
5460 }}
5461 }
5462
5463 case METHOD -> {
5464 var method = (MethodSymbol)enclosed;
5465 switch(name) {
5466 case "writeReplace" -> checkWriteReplace(tree, e, method);
5467 case "readResolve" -> checkReadResolve(tree, e, method);
5468
5469 case "writeExternal" -> checkWriteExternalRecord(tree, e, method, isExtern);
5470 case "readExternal" -> checkReadExternalRecord(tree, e, method, isExtern);
5471
5472 default -> {
5473 if (serialMethodNames.contains(name)) {
5474 log.warning(
5475 TreeInfo.diagnosticPositionFor(method, tree),
5476 LintWarnings.IneffectualSerialMethodRecord(name));
5477 }
5478 }}
5479 }}});
5480 }
5481 return null;
5482 }
5483
5484 void checkConcreteInstanceMethod(JCClassDecl tree,
5485 Element enclosing,
5486 MethodSymbol method) {
5487 if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
5488 log.warning(
5489 TreeInfo.diagnosticPositionFor(method, tree),
5490 LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName()));
5491 }
5492 }
5493
5494 private void checkReturnType(JCClassDecl tree,
5495 Element enclosing,
5496 MethodSymbol method,
5497 Type expectedReturnType) {
5498 // Note: there may be complications checking writeReplace
5499 // and readResolve since they return Object and could, in
5500 // principle, have covariant overrides and any synthetic
5501 // bridge method would not be represented here for
5502 // checking.
5503 Type rtype = method.getReturnType();
5504 if (!types.isSameType(expectedReturnType, rtype)) {
5505 log.warning(
5506 TreeInfo.diagnosticPositionFor(method, tree),
5507 LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
5508 rtype, expectedReturnType));
5509 }
5510 }
5511
5512 private void checkOneArg(JCClassDecl tree,
5513 Element enclosing,
5514 MethodSymbol method,
5515 Type expectedType) {
5516 String name = method.getSimpleName().toString();
5517
5518 var parameters= method.getParameters();
5519
5520 if (parameters.size() != 1) {
5521 log.warning(
5522 TreeInfo.diagnosticPositionFor(method, tree),
5523 LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
5524 return;
5525 }
5526
5527 Type parameterType = parameters.get(0).asType();
5528 if (!types.isSameType(parameterType, expectedType)) {
5529 log.warning(
5530 TreeInfo.diagnosticPositionFor(method, tree),
5531 LintWarnings.SerialMethodParameterType(method.getSimpleName(),
5532 expectedType,
5533 parameterType));
5534 }
5535 }
5536
5537 private boolean hasExactlyOneArgWithType(JCClassDecl tree,
5538 Element enclosing,
5539 MethodSymbol method,
5540 Type expectedType) {
5541 var parameters = method.getParameters();
5542 return (parameters.size() == 1) &&
5543 types.isSameType(parameters.get(0).asType(), expectedType);
5544 }
5545
5546
5547 private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5548 var parameters = method.getParameters();
5549 if (!parameters.isEmpty()) {
5550 log.warning(
5551 TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
5552 LintWarnings.SerialMethodNoArgs(method.getSimpleName()));
5553 }
5554 }
5555
5556 private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5557 // If the enclosing class is externalizable, warn for the method
5558 if (isExternalizable((Type)enclosing.asType())) {
5559 log.warning(
5560 TreeInfo.diagnosticPositionFor(method, tree),
5561 LintWarnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
5562 }
5563 return;
5564 }
5565
5566 private void checkExceptions(JCClassDecl tree,
5567 Element enclosing,
5568 MethodSymbol method,
5569 Type... declaredExceptions) {
5570 for (Type thrownType: method.getThrownTypes()) {
5571 // For each exception in the throws clause of the
5572 // method, if not an Error and not a RuntimeException,
5573 // check if the exception is a subtype of a declared
5574 // exception from the throws clause of the
5575 // serialization method in question.
5576 if (types.isSubtype(thrownType, syms.runtimeExceptionType) ||
5577 types.isSubtype(thrownType, syms.errorType) ) {
5578 continue;
5579 } else {
5580 boolean declared = false;
5581 for (Type declaredException : declaredExceptions) {
5582 if (types.isSubtype(thrownType, declaredException)) {
5583 declared = true;
5584 continue;
5585 }
5586 }
5587 if (!declared) {
5588 log.warning(
5589 TreeInfo.diagnosticPositionFor(method, tree),
5590 LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(),
5591 thrownType));
5592 }
5593 }
5594 }
5595 return;
5596 }
5597
5598 private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) {
5599 Lint prevLint = lint;
5600 try {
5601 lint = lint.augment((Symbol) symbol);
5602
5603 if (lint.isEnabled(LintCategory.SERIAL)) {
5604 task.accept(symbol, p);
5605 }
5606
5607 return null;
5608 } finally {
5609 lint = prevLint;
5610 }
5611 }
5612
5613 }
5614
5615 void checkRequiresIdentity(JCTree tree, Lint lint) {
5616 switch (tree) {
5617 case JCClassDecl classDecl -> {
5618 Type st = types.supertype(classDecl.sym.type);
5619 if (st != null &&
5620 // no need to recheck j.l.Object, shortcut,
5621 st.tsym != syms.objectType.tsym &&
5622 // this one could be null, no explicit extends
5623 classDecl.extending != null) {
5624 checkIfIdentityIsExpected(classDecl.extending.pos(), st, lint);
5625 }
5626 for (JCExpression intrface: classDecl.implementing) {
5627 checkIfIdentityIsExpected(intrface.pos(), intrface.type, lint);
5628 }
5629 for (JCTypeParameter tp : classDecl.typarams) {
5630 checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5631 }
5632 }
5633 case JCVariableDecl variableDecl -> {
5634 if (variableDecl.vartype != null &&
5635 (variableDecl.sym.flags_field & RECORD) == 0 ||
5636 (variableDecl.sym.flags_field & ~(Flags.PARAMETER | RECORD | GENERATED_MEMBER)) != 0) {
5637 /* we don't want to warn twice so if this variable is a compiler generated parameter of
5638 * a canonical record constructor, we don't want to issue a warning as we will warn the
5639 * corresponding compiler generated private record field anyways
5640 */
5641 checkIfIdentityIsExpected(variableDecl.vartype.pos(), variableDecl.vartype.type, lint);
5642 }
5643 }
5644 case JCTypeCast typeCast -> checkIfIdentityIsExpected(typeCast.clazz.pos(), typeCast.clazz.type, lint);
5645 case JCBindingPattern bindingPattern -> {
5646 if (bindingPattern.var.vartype != null) {
5647 checkIfIdentityIsExpected(bindingPattern.var.vartype.pos(), bindingPattern.var.vartype.type, lint);
5648 }
5649 }
5650 case JCMethodDecl methodDecl -> {
5651 for (JCTypeParameter tp : methodDecl.typarams) {
5652 checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5653 }
5654 if (methodDecl.restype != null && !methodDecl.restype.type.hasTag(VOID)) {
5655 checkIfIdentityIsExpected(methodDecl.restype.pos(), methodDecl.restype.type, lint);
5656 }
5657 }
5658 case JCMemberReference mref -> {
5659 checkIfIdentityIsExpected(mref.expr.pos(), mref.target, lint);
5660 checkIfTypeParamsRequiresIdentity(mref.sym.getMetadata(), mref.typeargs, lint);
5661 }
5662 case JCPolyExpression poly
5663 when (poly instanceof JCNewClass || poly instanceof JCMethodInvocation) -> {
5664 if (poly instanceof JCNewClass newClass) {
5665 checkIfIdentityIsExpected(newClass.clazz.pos(), newClass.clazz.type, lint);
5666 }
5667 List<JCExpression> argExps = poly instanceof JCNewClass ?
5668 ((JCNewClass)poly).args :
5669 ((JCMethodInvocation)poly).args;
5670 Symbol msym = TreeInfo.symbolFor(poly);
5671 if (msym != null) {
5672 if (!argExps.isEmpty() && msym instanceof MethodSymbol ms && ms.params != null) {
5673 VarSymbol lastParam = ms.params.head;
5674 for (VarSymbol param: ms.params) {
5675 if ((param.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5676 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5677 }
5678 lastParam = param;
5679 argExps = argExps.tail;
5680 }
5681 while (argExps != null && !argExps.isEmpty() && lastParam != null) {
5682 if ((lastParam.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5683 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5684 }
5685 argExps = argExps.tail;
5686 }
5687 }
5688 checkIfTypeParamsRequiresIdentity(
5689 msym.getMetadata(),
5690 poly instanceof JCNewClass ?
5691 ((JCNewClass)poly).typeargs :
5692 ((JCMethodInvocation)poly).typeargs,
5693 lint);
5694 }
5695 }
5696 default -> throw new AssertionError("unexpected tree " + tree);
5697 }
5698 }
5699
5700 /** Check if a type required an identity class
5701 */
5702 private boolean checkIfIdentityIsExpected(DiagnosticPosition pos, Type t, Lint lint) {
5703 if (t != null &&
5704 lint != null &&
5705 lint.isEnabled(LintCategory.IDENTITY)) {
5706 RequiresIdentityVisitor requiresIdentityVisitor = new RequiresIdentityVisitor();
5707 // we need to avoid recursion due to self referencing type vars or captures, this is why we need a set
5708 requiresIdentityVisitor.visit(t, new HashSet<>());
5709 if (requiresIdentityVisitor.requiresWarning) {
5710 log.warning(pos, LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5711 return true;
5712 }
5713 }
5714 return false;
5715 }
5716
5717 // where
5718 private class RequiresIdentityVisitor extends Types.SimpleVisitor<Void, Set<Type>> {
5719 boolean requiresWarning = false;
5720
5721 @Override
5722 public Void visitType(Type t, Set<Type> seen) {
5723 return null;
5724 }
5725
5726 @Override
5727 public Void visitWildcardType(WildcardType t, Set<Type> seen) {
5728 return visit(t.type, seen);
5729 }
5730
5731 @Override
5732 public Void visitTypeVar(TypeVar t, Set<Type> seen) {
5733 if (seen.add(t)) {
5734 visit(t.getUpperBound(), seen);
5735 }
5736 return null;
5737 }
5738
5739 @Override
5740 public Void visitCapturedType(CapturedType t, Set<Type> seen) {
5741 if (seen.add(t)) {
5742 visit(t.getUpperBound(), seen);
5743 visit(t.getLowerBound(), seen);
5744 }
5745 return null;
5746 }
5747
5748 @Override
5749 public Void visitArrayType(ArrayType t, Set<Type> seen) {
5750 return visit(t.elemtype, seen);
5751 }
5752
5753 @Override
5754 public Void visitClassType(ClassType t, Set<Type> seen) {
5755 if (t != null && t.tsym != null) {
5756 SymbolMetadata sm = t.tsym.getMetadata();
5757 if (sm != null && !t.getTypeArguments().isEmpty()) {
5758 if (sm.getTypeAttributes().stream()
5759 .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5760 t.getTypeArguments().get(ta.position.parameter_index) != null &&
5761 t.getTypeArguments().get(ta.position.parameter_index).isValueBased()).findAny().isPresent()) {
5762 requiresWarning = true;
5763 return null;
5764 }
5765 }
5766 }
5767 visit(t.getEnclosingType(), seen);
5768 for (Type targ : t.getTypeArguments()) {
5769 visit(targ, seen);
5770 }
5771 return null;
5772 }
5773 } // RequiresIdentityVisitor
5774
5775 private void checkIfTypeParamsRequiresIdentity(SymbolMetadata sm,
5776 List<JCExpression> typeParamTrees,
5777 Lint lint) {
5778 if (typeParamTrees != null && !typeParamTrees.isEmpty()) {
5779 for (JCExpression targ : typeParamTrees) {
5780 checkIfIdentityIsExpected(targ.pos(), targ.type, lint);
5781 }
5782 if (sm != null)
5783 sm.getTypeAttributes().stream()
5784 .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5785 typeParamTrees.get(ta.position.parameter_index).type != null &&
5786 typeParamTrees.get(ta.position.parameter_index).type.isValueBased())
5787 .forEach(ta -> log.warning(typeParamTrees.get(ta.position.parameter_index).pos(),
5788 CompilerProperties.LintWarnings.AttemptToUseValueBasedWhereIdentityExpected));
5789 }
5790 }
5791
5792 private boolean isRequiresIdentityAnnotation(TypeSymbol annoType) {
5793 return annoType == syms.requiresIdentityType.tsym ||
5794 annoType.flatName() == syms.requiresIdentityInternalType.tsym.flatName();
5795 }
5796 }