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