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