Wed, 15 May 2013 14:00:31 +0100
8012003: Method diagnostics resolution need to be simplified in some cases
Summary: Unfold method resolution diagnostics when they mention errors in poly expressions
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.immediateHandler;
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 DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
222 DeferredLintHandler prev = deferredLintHandler;
223 deferredLintHandler = newDeferredLintHandler;
224 return prev;
225 }
227 MethodSymbol setMethod(MethodSymbol newMethod) {
228 MethodSymbol prev = method;
229 method = newMethod;
230 return prev;
231 }
233 /** Warn about deprecated symbol.
234 * @param pos Position to be used for error reporting.
235 * @param sym The deprecated symbol.
236 */
237 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
238 if (!lint.isSuppressed(LintCategory.DEPRECATION))
239 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
240 }
242 /** Warn about unchecked operation.
243 * @param pos Position to be used for error reporting.
244 * @param msg A string describing the problem.
245 */
246 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
247 if (!lint.isSuppressed(LintCategory.UNCHECKED))
248 uncheckedHandler.report(pos, msg, args);
249 }
251 /** Warn about unsafe vararg method decl.
252 * @param pos Position to be used for error reporting.
253 */
254 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
255 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
256 log.warning(LintCategory.VARARGS, pos, key, args);
257 }
259 /** Warn about using proprietary API.
260 * @param pos Position to be used for error reporting.
261 * @param msg A string describing the problem.
262 */
263 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
264 if (!lint.isSuppressed(LintCategory.SUNAPI))
265 sunApiHandler.report(pos, msg, args);
266 }
268 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
269 if (lint.isEnabled(LintCategory.STATIC))
270 log.warning(LintCategory.STATIC, pos, msg, args);
271 }
273 /**
274 * Report any deferred diagnostics.
275 */
276 public void reportDeferredDiagnostics() {
277 deprecationHandler.reportDeferredDiagnostic();
278 uncheckedHandler.reportDeferredDiagnostic();
279 sunApiHandler.reportDeferredDiagnostic();
280 }
283 /** Report a failure to complete a class.
284 * @param pos Position to be used for error reporting.
285 * @param ex The failure to report.
286 */
287 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
288 log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue());
289 if (ex instanceof ClassReader.BadClassFile
290 && !suppressAbortOnBadClassFile) throw new Abort();
291 else return syms.errType;
292 }
294 /** Report an error that wrong type tag was found.
295 * @param pos Position to be used for error reporting.
296 * @param required An internationalized string describing the type tag
297 * required.
298 * @param found The type that was found.
299 */
300 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
301 // this error used to be raised by the parser,
302 // but has been delayed to this point:
303 if (found instanceof Type && ((Type)found).hasTag(VOID)) {
304 log.error(pos, "illegal.start.of.type");
305 return syms.errType;
306 }
307 log.error(pos, "type.found.req", found, required);
308 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
309 }
311 /** Report an error that symbol cannot be referenced before super
312 * has been called.
313 * @param pos Position to be used for error reporting.
314 * @param sym The referenced symbol.
315 */
316 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
317 log.error(pos, "cant.ref.before.ctor.called", sym);
318 }
320 /** Report duplicate declaration error.
321 */
322 void duplicateError(DiagnosticPosition pos, Symbol sym) {
323 if (!sym.type.isErroneous()) {
324 Symbol location = sym.location();
325 if (location.kind == MTH &&
326 ((MethodSymbol)location).isStaticOrInstanceInit()) {
327 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
328 kindName(sym.location()), kindName(sym.location().enclClass()),
329 sym.location().enclClass());
330 } else {
331 log.error(pos, "already.defined", kindName(sym), sym,
332 kindName(sym.location()), sym.location());
333 }
334 }
335 }
337 /** Report array/varargs duplicate declaration
338 */
339 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
340 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
341 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
342 }
343 }
345 /* ************************************************************************
346 * duplicate declaration checking
347 *************************************************************************/
349 /** Check that variable does not hide variable with same name in
350 * immediately enclosing local scope.
351 * @param pos Position for error reporting.
352 * @param v The symbol.
353 * @param s The scope.
354 */
355 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
356 if (s.next != null) {
357 for (Scope.Entry e = s.next.lookup(v.name);
358 e.scope != null && e.sym.owner == v.owner;
359 e = e.next()) {
360 if (e.sym.kind == VAR &&
361 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
362 v.name != names.error) {
363 duplicateError(pos, e.sym);
364 return;
365 }
366 }
367 }
368 }
370 /** Check that a class or interface does not hide a class or
371 * interface with same name in immediately enclosing local scope.
372 * @param pos Position for error reporting.
373 * @param c The symbol.
374 * @param s The scope.
375 */
376 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
377 if (s.next != null) {
378 for (Scope.Entry e = s.next.lookup(c.name);
379 e.scope != null && e.sym.owner == c.owner;
380 e = e.next()) {
381 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
382 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
383 c.name != names.error) {
384 duplicateError(pos, e.sym);
385 return;
386 }
387 }
388 }
389 }
391 /** Check that class does not have the same name as one of
392 * its enclosing classes, or as a class defined in its enclosing scope.
393 * return true if class is unique in its enclosing scope.
394 * @param pos Position for error reporting.
395 * @param name The class name.
396 * @param s The enclosing scope.
397 */
398 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
399 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
400 if (e.sym.kind == TYP && e.sym.name != names.error) {
401 duplicateError(pos, e.sym);
402 return false;
403 }
404 }
405 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
406 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
407 duplicateError(pos, sym);
408 return true;
409 }
410 }
411 return true;
412 }
414 /* *************************************************************************
415 * Class name generation
416 **************************************************************************/
418 /** Return name of local class.
419 * This is of the form {@code <enclClass> $ n <classname> }
420 * where
421 * enclClass is the flat name of the enclosing class,
422 * classname is the simple name of the local class
423 */
424 Name localClassName(ClassSymbol c) {
425 for (int i=1; ; i++) {
426 Name flatname = names.
427 fromString("" + c.owner.enclClass().flatname +
428 syntheticNameChar + i +
429 c.name);
430 if (compiled.get(flatname) == null) return flatname;
431 }
432 }
434 /* *************************************************************************
435 * Type Checking
436 **************************************************************************/
438 /**
439 * A check context is an object that can be used to perform compatibility
440 * checks - depending on the check context, meaning of 'compatibility' might
441 * vary significantly.
442 */
443 public interface CheckContext {
444 /**
445 * Is type 'found' compatible with type 'req' in given context
446 */
447 boolean compatible(Type found, Type req, Warner warn);
448 /**
449 * Report a check error
450 */
451 void report(DiagnosticPosition pos, JCDiagnostic details);
452 /**
453 * Obtain a warner for this check context
454 */
455 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
457 public Infer.InferenceContext inferenceContext();
459 public DeferredAttr.DeferredAttrContext deferredAttrContext();
460 }
462 /**
463 * This class represent a check context that is nested within another check
464 * context - useful to check sub-expressions. The default behavior simply
465 * redirects all method calls to the enclosing check context leveraging
466 * the forwarding pattern.
467 */
468 static class NestedCheckContext implements CheckContext {
469 CheckContext enclosingContext;
471 NestedCheckContext(CheckContext enclosingContext) {
472 this.enclosingContext = enclosingContext;
473 }
475 public boolean compatible(Type found, Type req, Warner warn) {
476 return enclosingContext.compatible(found, req, warn);
477 }
479 public void report(DiagnosticPosition pos, JCDiagnostic details) {
480 enclosingContext.report(pos, details);
481 }
483 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
484 return enclosingContext.checkWarner(pos, found, req);
485 }
487 public Infer.InferenceContext inferenceContext() {
488 return enclosingContext.inferenceContext();
489 }
491 public DeferredAttrContext deferredAttrContext() {
492 return enclosingContext.deferredAttrContext();
493 }
494 }
496 /**
497 * Check context to be used when evaluating assignment/return statements
498 */
499 CheckContext basicHandler = new CheckContext() {
500 public void report(DiagnosticPosition pos, JCDiagnostic details) {
501 log.error(pos, "prob.found.req", details);
502 }
503 public boolean compatible(Type found, Type req, Warner warn) {
504 return types.isAssignable(found, req, warn);
505 }
507 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
508 return convertWarner(pos, found, req);
509 }
511 public InferenceContext inferenceContext() {
512 return infer.emptyContext;
513 }
515 public DeferredAttrContext deferredAttrContext() {
516 return deferredAttr.emptyDeferredAttrContext;
517 }
518 };
520 /** Check that a given type is assignable to a given proto-type.
521 * If it is, return the type, otherwise return errType.
522 * @param pos Position to be used for error reporting.
523 * @param found The type that was found.
524 * @param req The type that was required.
525 */
526 Type checkType(DiagnosticPosition pos, Type found, Type req) {
527 return checkType(pos, found, req, basicHandler);
528 }
530 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
531 final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
532 if (inferenceContext.free(req)) {
533 inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
534 @Override
535 public void typesInferred(InferenceContext inferenceContext) {
536 checkType(pos, found, inferenceContext.asInstType(req), checkContext);
537 }
538 });
539 }
540 if (req.hasTag(ERROR))
541 return req;
542 if (req.hasTag(NONE))
543 return found;
544 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
545 return found;
546 } else {
547 if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
548 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
549 return types.createErrorType(found);
550 }
551 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
552 return types.createErrorType(found);
553 }
554 }
556 /** Check that a given type can be cast to a given target type.
557 * Return the result of the cast.
558 * @param pos Position to be used for error reporting.
559 * @param found The type that is being cast.
560 * @param req The target type of the cast.
561 */
562 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
563 return checkCastable(pos, found, req, basicHandler);
564 }
565 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
566 if (types.isCastable(found, req, castWarner(pos, found, req))) {
567 return req;
568 } else {
569 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
570 return types.createErrorType(found);
571 }
572 }
574 /** Check for redundant casts (i.e. where source type is a subtype of target type)
575 * The problem should only be reported for non-292 cast
576 */
577 public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
578 if (!tree.type.isErroneous() &&
579 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
580 && types.isSameType(tree.expr.type, tree.clazz.type)
581 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
582 && !is292targetTypeCast(tree)) {
583 log.warning(Lint.LintCategory.CAST,
584 tree.pos(), "redundant.cast", tree.expr.type);
585 }
586 }
587 //where
588 private boolean is292targetTypeCast(JCTypeCast tree) {
589 boolean is292targetTypeCast = false;
590 JCExpression expr = TreeInfo.skipParens(tree.expr);
591 if (expr.hasTag(APPLY)) {
592 JCMethodInvocation apply = (JCMethodInvocation)expr;
593 Symbol sym = TreeInfo.symbol(apply.meth);
594 is292targetTypeCast = sym != null &&
595 sym.kind == MTH &&
596 (sym.flags() & HYPOTHETICAL) != 0;
597 }
598 return is292targetTypeCast;
599 }
601 private static final boolean ignoreAnnotatedCasts = true;
603 /** Check that a type is within some bounds.
604 *
605 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
606 * type argument.
607 * @param a The type that should be bounded by bs.
608 * @param bound The bound.
609 */
610 private boolean checkExtends(Type a, Type bound) {
611 if (a.isUnbound()) {
612 return true;
613 } else if (!a.hasTag(WILDCARD)) {
614 a = types.upperBound(a);
615 return types.isSubtype(a, bound);
616 } else if (a.isExtendsBound()) {
617 return types.isCastable(bound, types.upperBound(a), types.noWarnings);
618 } else if (a.isSuperBound()) {
619 return !types.notSoftSubtype(types.lowerBound(a), bound);
620 }
621 return true;
622 }
624 /** Check that type is different from 'void'.
625 * @param pos Position to be used for error reporting.
626 * @param t The type to be checked.
627 */
628 Type checkNonVoid(DiagnosticPosition pos, Type t) {
629 if (t.hasTag(VOID)) {
630 log.error(pos, "void.not.allowed.here");
631 return types.createErrorType(t);
632 } else {
633 return t;
634 }
635 }
637 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
638 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
639 return typeTagError(pos,
640 diags.fragment("type.req.class.array"),
641 asTypeParam(t));
642 } else {
643 return t;
644 }
645 }
647 /** Check that type is a class or interface type.
648 * @param pos Position to be used for error reporting.
649 * @param t The type to be checked.
650 */
651 Type checkClassType(DiagnosticPosition pos, Type t) {
652 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
653 return typeTagError(pos,
654 diags.fragment("type.req.class"),
655 asTypeParam(t));
656 } else {
657 return t;
658 }
659 }
660 //where
661 private Object asTypeParam(Type t) {
662 return (t.hasTag(TYPEVAR))
663 ? diags.fragment("type.parameter", t)
664 : t;
665 }
667 /** Check that type is a valid qualifier for a constructor reference expression
668 */
669 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
670 t = checkClassOrArrayType(pos, t);
671 if (t.hasTag(CLASS)) {
672 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
673 log.error(pos, "abstract.cant.be.instantiated", t.tsym);
674 t = types.createErrorType(t);
675 } else if ((t.tsym.flags() & ENUM) != 0) {
676 log.error(pos, "enum.cant.be.instantiated");
677 t = types.createErrorType(t);
678 } else {
679 t = checkClassType(pos, t, true);
680 }
681 } else if (t.hasTag(ARRAY)) {
682 if (!types.isReifiable(((ArrayType)t).elemtype)) {
683 log.error(pos, "generic.array.creation");
684 t = types.createErrorType(t);
685 }
686 }
687 return t;
688 }
690 /** Check that type is a class or interface type.
691 * @param pos Position to be used for error reporting.
692 * @param t The type to be checked.
693 * @param noBounds True if type bounds are illegal here.
694 */
695 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
696 t = checkClassType(pos, t);
697 if (noBounds && t.isParameterized()) {
698 List<Type> args = t.getTypeArguments();
699 while (args.nonEmpty()) {
700 if (args.head.hasTag(WILDCARD))
701 return typeTagError(pos,
702 diags.fragment("type.req.exact"),
703 args.head);
704 args = args.tail;
705 }
706 }
707 return t;
708 }
710 /** Check that type is a reifiable class, interface or array type.
711 * @param pos Position to be used for error reporting.
712 * @param t The type to be checked.
713 */
714 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
715 t = checkClassOrArrayType(pos, t);
716 if (!t.isErroneous() && !types.isReifiable(t)) {
717 log.error(pos, "illegal.generic.type.for.instof");
718 return types.createErrorType(t);
719 } else {
720 return t;
721 }
722 }
724 /** Check that type is a reference type, i.e. a class, interface or array type
725 * or a type variable.
726 * @param pos Position to be used for error reporting.
727 * @param t The type to be checked.
728 */
729 Type checkRefType(DiagnosticPosition pos, Type t) {
730 if (t.isReference())
731 return t;
732 else
733 return typeTagError(pos,
734 diags.fragment("type.req.ref"),
735 t);
736 }
738 /** Check that each type is a reference type, i.e. a class, interface or array type
739 * or a type variable.
740 * @param trees Original trees, used for error reporting.
741 * @param types The types to be checked.
742 */
743 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
744 List<JCExpression> tl = trees;
745 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
746 l.head = checkRefType(tl.head.pos(), l.head);
747 tl = tl.tail;
748 }
749 return types;
750 }
752 /** Check that type is a null or reference type.
753 * @param pos Position to be used for error reporting.
754 * @param t The type to be checked.
755 */
756 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
757 if (t.isNullOrReference())
758 return t;
759 else
760 return typeTagError(pos,
761 diags.fragment("type.req.ref"),
762 t);
763 }
765 /** Check that flag set does not contain elements of two conflicting sets. s
766 * Return true if it doesn't.
767 * @param pos Position to be used for error reporting.
768 * @param flags The set of flags to be checked.
769 * @param set1 Conflicting flags set #1.
770 * @param set2 Conflicting flags set #2.
771 */
772 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
773 if ((flags & set1) != 0 && (flags & set2) != 0) {
774 log.error(pos,
775 "illegal.combination.of.modifiers",
776 asFlagSet(TreeInfo.firstFlag(flags & set1)),
777 asFlagSet(TreeInfo.firstFlag(flags & set2)));
778 return false;
779 } else
780 return true;
781 }
783 /** Check that usage of diamond operator is correct (i.e. diamond should not
784 * be used with non-generic classes or in anonymous class creation expressions)
785 */
786 Type checkDiamond(JCNewClass tree, Type t) {
787 if (!TreeInfo.isDiamond(tree) ||
788 t.isErroneous()) {
789 return checkClassType(tree.clazz.pos(), t, true);
790 } else if (tree.def != null) {
791 log.error(tree.clazz.pos(),
792 "cant.apply.diamond.1",
793 t, diags.fragment("diamond.and.anon.class", t));
794 return types.createErrorType(t);
795 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
796 log.error(tree.clazz.pos(),
797 "cant.apply.diamond.1",
798 t, diags.fragment("diamond.non.generic", t));
799 return types.createErrorType(t);
800 } else if (tree.typeargs != null &&
801 tree.typeargs.nonEmpty()) {
802 log.error(tree.clazz.pos(),
803 "cant.apply.diamond.1",
804 t, diags.fragment("diamond.and.explicit.params", t));
805 return types.createErrorType(t);
806 } else {
807 return t;
808 }
809 }
811 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
812 MethodSymbol m = tree.sym;
813 if (!allowSimplifiedVarargs) return;
814 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
815 Type varargElemType = null;
816 if (m.isVarArgs()) {
817 varargElemType = types.elemtype(tree.params.last().type);
818 }
819 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
820 if (varargElemType != null) {
821 log.error(tree,
822 "varargs.invalid.trustme.anno",
823 syms.trustMeType.tsym,
824 diags.fragment("varargs.trustme.on.virtual.varargs", m));
825 } else {
826 log.error(tree,
827 "varargs.invalid.trustme.anno",
828 syms.trustMeType.tsym,
829 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
830 }
831 } else if (hasTrustMeAnno && varargElemType != null &&
832 types.isReifiable(varargElemType)) {
833 warnUnsafeVararg(tree,
834 "varargs.redundant.trustme.anno",
835 syms.trustMeType.tsym,
836 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
837 }
838 else if (!hasTrustMeAnno && varargElemType != null &&
839 !types.isReifiable(varargElemType)) {
840 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
841 }
842 }
843 //where
844 private boolean isTrustMeAllowedOnMethod(Symbol s) {
845 return (s.flags() & VARARGS) != 0 &&
846 (s.isConstructor() ||
847 (s.flags() & (STATIC | FINAL)) != 0);
848 }
850 Type checkMethod(Type owntype,
851 Symbol sym,
852 Env<AttrContext> env,
853 final List<JCExpression> argtrees,
854 List<Type> argtypes,
855 boolean useVarargs,
856 boolean unchecked) {
857 // System.out.println("call : " + env.tree);
858 // System.out.println("method : " + owntype);
859 // System.out.println("actuals: " + argtypes);
860 List<Type> formals = owntype.getParameterTypes();
861 Type last = useVarargs ? formals.last() : null;
862 if (sym.name == names.init &&
863 sym.owner == syms.enumSym)
864 formals = formals.tail.tail;
865 List<JCExpression> args = argtrees;
866 DeferredAttr.DeferredTypeMap checkDeferredMap =
867 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
868 if (args != null) {
869 //this is null when type-checking a method reference
870 while (formals.head != last) {
871 JCTree arg = args.head;
872 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
873 assertConvertible(arg, arg.type, formals.head, warn);
874 args = args.tail;
875 formals = formals.tail;
876 }
877 if (useVarargs) {
878 Type varArg = types.elemtype(last);
879 while (args.tail != null) {
880 JCTree arg = args.head;
881 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
882 assertConvertible(arg, arg.type, varArg, warn);
883 args = args.tail;
884 }
885 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
886 // non-varargs call to varargs method
887 Type varParam = owntype.getParameterTypes().last();
888 Type lastArg = checkDeferredMap.apply(argtypes.last());
889 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
890 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
891 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
892 types.elemtype(varParam), varParam);
893 }
894 }
895 if (unchecked) {
896 warnUnchecked(env.tree.pos(),
897 "unchecked.meth.invocation.applied",
898 kindName(sym),
899 sym.name,
900 rs.methodArguments(sym.type.getParameterTypes()),
901 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
902 kindName(sym.location()),
903 sym.location());
904 owntype = new MethodType(owntype.getParameterTypes(),
905 types.erasure(owntype.getReturnType()),
906 types.erasure(owntype.getThrownTypes()),
907 syms.methodClass);
908 }
909 if (useVarargs) {
910 Type argtype = owntype.getParameterTypes().last();
911 if (!types.isReifiable(argtype) &&
912 (!allowSimplifiedVarargs ||
913 sym.attribute(syms.trustMeType.tsym) == null ||
914 !isTrustMeAllowedOnMethod(sym))) {
915 warnUnchecked(env.tree.pos(),
916 "unchecked.generic.array.creation",
917 argtype);
918 }
919 if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
920 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
921 }
922 }
923 PolyKind pkind = (sym.type.hasTag(FORALL) &&
924 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
925 PolyKind.POLY : PolyKind.STANDALONE;
926 TreeInfo.setPolyKind(env.tree, pkind);
927 return owntype;
928 }
929 //where
930 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
931 if (types.isConvertible(actual, formal, warn))
932 return;
934 if (formal.isCompound()
935 && types.isSubtype(actual, types.supertype(formal))
936 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
937 return;
938 }
940 /**
941 * Check that type 't' is a valid instantiation of a generic class
942 * (see JLS 4.5)
943 *
944 * @param t class type to be checked
945 * @return true if 't' is well-formed
946 */
947 public boolean checkValidGenericType(Type t) {
948 return firstIncompatibleTypeArg(t) == null;
949 }
950 //WHERE
951 private Type firstIncompatibleTypeArg(Type type) {
952 List<Type> formals = type.tsym.type.allparams();
953 List<Type> actuals = type.allparams();
954 List<Type> args = type.getTypeArguments();
955 List<Type> forms = type.tsym.type.getTypeArguments();
956 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
958 // For matching pairs of actual argument types `a' and
959 // formal type parameters with declared bound `b' ...
960 while (args.nonEmpty() && forms.nonEmpty()) {
961 // exact type arguments needs to know their
962 // bounds (for upper and lower bound
963 // calculations). So we create new bounds where
964 // type-parameters are replaced with actuals argument types.
965 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
966 args = args.tail;
967 forms = forms.tail;
968 }
970 args = type.getTypeArguments();
971 List<Type> tvars_cap = types.substBounds(formals,
972 formals,
973 types.capture(type).allparams());
974 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
975 // Let the actual arguments know their bound
976 args.head.withTypeVar((TypeVar)tvars_cap.head);
977 args = args.tail;
978 tvars_cap = tvars_cap.tail;
979 }
981 args = type.getTypeArguments();
982 List<Type> bounds = bounds_buf.toList();
984 while (args.nonEmpty() && bounds.nonEmpty()) {
985 Type actual = args.head;
986 if (!isTypeArgErroneous(actual) &&
987 !bounds.head.isErroneous() &&
988 !checkExtends(actual, bounds.head)) {
989 return args.head;
990 }
991 args = args.tail;
992 bounds = bounds.tail;
993 }
995 args = type.getTypeArguments();
996 bounds = bounds_buf.toList();
998 for (Type arg : types.capture(type).getTypeArguments()) {
999 if (arg.hasTag(TYPEVAR) &&
1000 arg.getUpperBound().isErroneous() &&
1001 !bounds.head.isErroneous() &&
1002 !isTypeArgErroneous(args.head)) {
1003 return args.head;
1004 }
1005 bounds = bounds.tail;
1006 args = args.tail;
1007 }
1009 return null;
1010 }
1011 //where
1012 boolean isTypeArgErroneous(Type t) {
1013 return isTypeArgErroneous.visit(t);
1014 }
1016 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1017 public Boolean visitType(Type t, Void s) {
1018 return t.isErroneous();
1019 }
1020 @Override
1021 public Boolean visitTypeVar(TypeVar t, Void s) {
1022 return visit(t.getUpperBound());
1023 }
1024 @Override
1025 public Boolean visitCapturedType(CapturedType t, Void s) {
1026 return visit(t.getUpperBound()) ||
1027 visit(t.getLowerBound());
1028 }
1029 @Override
1030 public Boolean visitWildcardType(WildcardType t, Void s) {
1031 return visit(t.type);
1032 }
1033 };
1035 /** Check that given modifiers are legal for given symbol and
1036 * return modifiers together with any implicit modifiers for that symbol.
1037 * Warning: we can't use flags() here since this method
1038 * is called during class enter, when flags() would cause a premature
1039 * completion.
1040 * @param pos Position to be used for error reporting.
1041 * @param flags The set of modifiers given in a definition.
1042 * @param sym The defined symbol.
1043 */
1044 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1045 long mask;
1046 long implicit = 0;
1047 switch (sym.kind) {
1048 case VAR:
1049 if (sym.owner.kind != TYP)
1050 mask = LocalVarFlags;
1051 else if ((sym.owner.flags_field & INTERFACE) != 0)
1052 mask = implicit = InterfaceVarFlags;
1053 else
1054 mask = VarFlags;
1055 break;
1056 case MTH:
1057 if (sym.name == names.init) {
1058 if ((sym.owner.flags_field & ENUM) != 0) {
1059 // enum constructors cannot be declared public or
1060 // protected and must be implicitly or explicitly
1061 // private
1062 implicit = PRIVATE;
1063 mask = PRIVATE;
1064 } else
1065 mask = ConstructorFlags;
1066 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1067 if ((flags & (DEFAULT | STATIC)) != 0) {
1068 mask = InterfaceMethodMask;
1069 implicit = PUBLIC;
1070 if ((flags & DEFAULT) != 0) {
1071 implicit |= ABSTRACT;
1072 }
1073 } else {
1074 mask = implicit = InterfaceMethodFlags;
1075 }
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 }
1365 void checkRaw(JCTree tree, Env<AttrContext> env) {
1366 if (lint.isEnabled(LintCategory.RAW) &&
1367 tree.type.hasTag(CLASS) &&
1368 !TreeInfo.isDiamond(tree) &&
1369 !withinAnonConstr(env) &&
1370 tree.type.isRaw()) {
1371 log.warning(LintCategory.RAW,
1372 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1373 }
1374 }
1376 boolean withinAnonConstr(Env<AttrContext> env) {
1377 return env.enclClass.name.isEmpty() &&
1378 env.enclMethod != null && env.enclMethod.name == names.init;
1379 }
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 Flag.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.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) && types.overrideEquivalent(st3, st2)) {
1916 if (s3.owner == site.tsym) {
1917 return true;
1918 }
1919 List<Type> tvars1 = st1.getTypeArguments();
1920 List<Type> tvars2 = st2.getTypeArguments();
1921 List<Type> tvars3 = st3.getTypeArguments();
1922 Type rt1 = st1.getReturnType();
1923 Type rt2 = st2.getReturnType();
1924 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1925 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1926 boolean compat =
1927 !rt13.isPrimitiveOrVoid() &&
1928 !rt23.isPrimitiveOrVoid() &&
1929 (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
1930 types.covariantReturnType(rt23, rt2, types.noWarnings));
1931 if (compat)
1932 return true;
1933 }
1934 }
1935 }
1936 return false;
1937 }
1939 /** Check that a given method conforms with any method it overrides.
1940 * @param tree The tree from which positions are extracted
1941 * for errors.
1942 * @param m The overriding method.
1943 */
1944 void checkOverride(JCTree tree, MethodSymbol m) {
1945 ClassSymbol origin = (ClassSymbol)m.owner;
1946 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1947 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1948 log.error(tree.pos(), "enum.no.finalize");
1949 return;
1950 }
1951 for (Type t = origin.type; t.hasTag(CLASS);
1952 t = types.supertype(t)) {
1953 if (t != origin.type) {
1954 checkOverride(tree, t, origin, m);
1955 }
1956 for (Type t2 : types.interfaces(t)) {
1957 checkOverride(tree, t2, origin, m);
1958 }
1959 }
1960 }
1962 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1963 TypeSymbol c = site.tsym;
1964 Scope.Entry e = c.members().lookup(m.name);
1965 while (e.scope != null) {
1966 if (m.overrides(e.sym, origin, types, false)) {
1967 if ((e.sym.flags() & ABSTRACT) == 0) {
1968 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1969 }
1970 }
1971 e = e.next();
1972 }
1973 }
1975 private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
1976 public boolean accepts(Symbol s) {
1977 return MethodSymbol.implementation_filter.accepts(s) &&
1978 (s.flags() & BAD_OVERRIDE) == 0;
1980 }
1981 };
1983 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
1984 ClassSymbol someClass) {
1985 /* At present, annotations cannot possibly have a method that is override
1986 * equivalent with Object.equals(Object) but in any case the condition is
1987 * fine for completeness.
1988 */
1989 if (someClass == (ClassSymbol)syms.objectType.tsym ||
1990 someClass.isInterface() || someClass.isEnum() ||
1991 (someClass.flags() & ANNOTATION) != 0 ||
1992 (someClass.flags() & ABSTRACT) != 0) return;
1993 //anonymous inner classes implementing interfaces need especial treatment
1994 if (someClass.isAnonymous()) {
1995 List<Type> interfaces = types.interfaces(someClass.type);
1996 if (interfaces != null && !interfaces.isEmpty() &&
1997 interfaces.head.tsym == syms.comparatorType.tsym) return;
1998 }
1999 checkClassOverrideEqualsAndHash(pos, someClass);
2000 }
2002 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2003 ClassSymbol someClass) {
2004 if (lint.isEnabled(LintCategory.OVERRIDES)) {
2005 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2006 .tsym.members().lookup(names.equals).sym;
2007 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2008 .tsym.members().lookup(names.hashCode).sym;
2009 boolean overridesEquals = types.implementation(equalsAtObject,
2010 someClass, false, equalsHasCodeFilter).owner == someClass;
2011 boolean overridesHashCode = types.implementation(hashCodeAtObject,
2012 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2014 if (overridesEquals && !overridesHashCode) {
2015 log.warning(LintCategory.OVERRIDES, pos,
2016 "override.equals.but.not.hashcode", someClass);
2017 }
2018 }
2019 }
2021 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2022 ClashFilter cf = new ClashFilter(origin.type);
2023 return (cf.accepts(s1) &&
2024 cf.accepts(s2) &&
2025 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2026 }
2029 /** Check that all abstract members of given class have definitions.
2030 * @param pos Position to be used for error reporting.
2031 * @param c The class.
2032 */
2033 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2034 try {
2035 MethodSymbol undef = firstUndef(c, c);
2036 if (undef != null) {
2037 if ((c.flags() & ENUM) != 0 &&
2038 types.supertype(c.type).tsym == syms.enumSym &&
2039 (c.flags() & FINAL) == 0) {
2040 // add the ABSTRACT flag to an enum
2041 c.flags_field |= ABSTRACT;
2042 } else {
2043 MethodSymbol undef1 =
2044 new MethodSymbol(undef.flags(), undef.name,
2045 types.memberType(c.type, undef), undef.owner);
2046 log.error(pos, "does.not.override.abstract",
2047 c, undef1, undef1.location());
2048 }
2049 }
2050 } catch (CompletionFailure ex) {
2051 completionError(pos, ex);
2052 }
2053 }
2054 //where
2055 /** Return first abstract member of class `c' that is not defined
2056 * in `impl', null if there is none.
2057 */
2058 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
2059 MethodSymbol undef = null;
2060 // Do not bother to search in classes that are not abstract,
2061 // since they cannot have abstract members.
2062 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2063 Scope s = c.members();
2064 for (Scope.Entry e = s.elems;
2065 undef == null && e != null;
2066 e = e.sibling) {
2067 if (e.sym.kind == MTH &&
2068 (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
2069 MethodSymbol absmeth = (MethodSymbol)e.sym;
2070 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
2071 if (implmeth == null || implmeth == absmeth) {
2072 //look for default implementations
2073 if (allowDefaultMethods) {
2074 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
2075 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
2076 implmeth = prov;
2077 }
2078 }
2079 }
2080 if (implmeth == null || implmeth == absmeth) {
2081 undef = absmeth;
2082 }
2083 }
2084 }
2085 if (undef == null) {
2086 Type st = types.supertype(c.type);
2087 if (st.hasTag(CLASS))
2088 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2089 }
2090 for (List<Type> l = types.interfaces(c.type);
2091 undef == null && l.nonEmpty();
2092 l = l.tail) {
2093 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2094 }
2095 }
2096 return undef;
2097 }
2099 void checkNonCyclicDecl(JCClassDecl tree) {
2100 CycleChecker cc = new CycleChecker();
2101 cc.scan(tree);
2102 if (!cc.errorFound && !cc.partialCheck) {
2103 tree.sym.flags_field |= ACYCLIC;
2104 }
2105 }
2107 class CycleChecker extends TreeScanner {
2109 List<Symbol> seenClasses = List.nil();
2110 boolean errorFound = false;
2111 boolean partialCheck = false;
2113 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2114 if (sym != null && sym.kind == TYP) {
2115 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2116 if (classEnv != null) {
2117 DiagnosticSource prevSource = log.currentSource();
2118 try {
2119 log.useSource(classEnv.toplevel.sourcefile);
2120 scan(classEnv.tree);
2121 }
2122 finally {
2123 log.useSource(prevSource.getFile());
2124 }
2125 } else if (sym.kind == TYP) {
2126 checkClass(pos, sym, List.<JCTree>nil());
2127 }
2128 } else {
2129 //not completed yet
2130 partialCheck = true;
2131 }
2132 }
2134 @Override
2135 public void visitSelect(JCFieldAccess tree) {
2136 super.visitSelect(tree);
2137 checkSymbol(tree.pos(), tree.sym);
2138 }
2140 @Override
2141 public void visitIdent(JCIdent tree) {
2142 checkSymbol(tree.pos(), tree.sym);
2143 }
2145 @Override
2146 public void visitTypeApply(JCTypeApply tree) {
2147 scan(tree.clazz);
2148 }
2150 @Override
2151 public void visitTypeArray(JCArrayTypeTree tree) {
2152 scan(tree.elemtype);
2153 }
2155 @Override
2156 public void visitClassDef(JCClassDecl tree) {
2157 List<JCTree> supertypes = List.nil();
2158 if (tree.getExtendsClause() != null) {
2159 supertypes = supertypes.prepend(tree.getExtendsClause());
2160 }
2161 if (tree.getImplementsClause() != null) {
2162 for (JCTree intf : tree.getImplementsClause()) {
2163 supertypes = supertypes.prepend(intf);
2164 }
2165 }
2166 checkClass(tree.pos(), tree.sym, supertypes);
2167 }
2169 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2170 if ((c.flags_field & ACYCLIC) != 0)
2171 return;
2172 if (seenClasses.contains(c)) {
2173 errorFound = true;
2174 noteCyclic(pos, (ClassSymbol)c);
2175 } else if (!c.type.isErroneous()) {
2176 try {
2177 seenClasses = seenClasses.prepend(c);
2178 if (c.type.hasTag(CLASS)) {
2179 if (supertypes.nonEmpty()) {
2180 scan(supertypes);
2181 }
2182 else {
2183 ClassType ct = (ClassType)c.type;
2184 if (ct.supertype_field == null ||
2185 ct.interfaces_field == null) {
2186 //not completed yet
2187 partialCheck = true;
2188 return;
2189 }
2190 checkSymbol(pos, ct.supertype_field.tsym);
2191 for (Type intf : ct.interfaces_field) {
2192 checkSymbol(pos, intf.tsym);
2193 }
2194 }
2195 if (c.owner.kind == TYP) {
2196 checkSymbol(pos, c.owner);
2197 }
2198 }
2199 } finally {
2200 seenClasses = seenClasses.tail;
2201 }
2202 }
2203 }
2204 }
2206 /** Check for cyclic references. Issue an error if the
2207 * symbol of the type referred to has a LOCKED flag set.
2208 *
2209 * @param pos Position to be used for error reporting.
2210 * @param t The type referred to.
2211 */
2212 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2213 checkNonCyclicInternal(pos, t);
2214 }
2217 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2218 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2219 }
2221 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2222 final TypeVar tv;
2223 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2224 return;
2225 if (seen.contains(t)) {
2226 tv = (TypeVar)t;
2227 tv.bound = types.createErrorType(t);
2228 log.error(pos, "cyclic.inheritance", t);
2229 } else if (t.hasTag(TYPEVAR)) {
2230 tv = (TypeVar)t;
2231 seen = seen.prepend(tv);
2232 for (Type b : types.getBounds(tv))
2233 checkNonCyclic1(pos, b, seen);
2234 }
2235 }
2237 /** Check for cyclic references. Issue an error if the
2238 * symbol of the type referred to has a LOCKED flag set.
2239 *
2240 * @param pos Position to be used for error reporting.
2241 * @param t The type referred to.
2242 * @returns True if the check completed on all attributed classes
2243 */
2244 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2245 boolean complete = true; // was the check complete?
2246 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2247 Symbol c = t.tsym;
2248 if ((c.flags_field & ACYCLIC) != 0) return true;
2250 if ((c.flags_field & LOCKED) != 0) {
2251 noteCyclic(pos, (ClassSymbol)c);
2252 } else if (!c.type.isErroneous()) {
2253 try {
2254 c.flags_field |= LOCKED;
2255 if (c.type.hasTag(CLASS)) {
2256 ClassType clazz = (ClassType)c.type;
2257 if (clazz.interfaces_field != null)
2258 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2259 complete &= checkNonCyclicInternal(pos, l.head);
2260 if (clazz.supertype_field != null) {
2261 Type st = clazz.supertype_field;
2262 if (st != null && st.hasTag(CLASS))
2263 complete &= checkNonCyclicInternal(pos, st);
2264 }
2265 if (c.owner.kind == TYP)
2266 complete &= checkNonCyclicInternal(pos, c.owner.type);
2267 }
2268 } finally {
2269 c.flags_field &= ~LOCKED;
2270 }
2271 }
2272 if (complete)
2273 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2274 if (complete) c.flags_field |= ACYCLIC;
2275 return complete;
2276 }
2278 /** Note that we found an inheritance cycle. */
2279 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2280 log.error(pos, "cyclic.inheritance", c);
2281 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2282 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2283 Type st = types.supertype(c.type);
2284 if (st.hasTag(CLASS))
2285 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2286 c.type = types.createErrorType(c, c.type);
2287 c.flags_field |= ACYCLIC;
2288 }
2290 /**
2291 * Check that functional interface methods would make sense when seen
2292 * from the perspective of the implementing class
2293 */
2294 void checkFunctionalInterface(JCTree tree, Type funcInterface) {
2295 ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
2296 ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
2297 c.interfaces_field = List.of(types.removeWildcards(funcInterface));
2298 c.supertype_field = syms.objectType;
2299 c.tsym = csym;
2300 csym.members_field = new Scope(csym);
2301 Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
2302 Type descType = types.findDescriptorType(funcInterface);
2303 csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
2304 csym.completer = null;
2305 checkImplementations(tree, csym, csym);
2306 }
2308 /** Check that all methods which implement some
2309 * method conform to the method they implement.
2310 * @param tree The class definition whose members are checked.
2311 */
2312 void checkImplementations(JCClassDecl tree) {
2313 checkImplementations(tree, tree.sym, tree.sym);
2314 }
2315 //where
2316 /** Check that all methods which implement some
2317 * method in `ic' conform to the method they implement.
2318 */
2319 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2320 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2321 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2322 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2323 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2324 if (e.sym.kind == MTH &&
2325 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2326 MethodSymbol absmeth = (MethodSymbol)e.sym;
2327 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2328 if (implmeth != null && implmeth != absmeth &&
2329 (implmeth.owner.flags() & INTERFACE) ==
2330 (origin.flags() & INTERFACE)) {
2331 // don't check if implmeth is in a class, yet
2332 // origin is an interface. This case arises only
2333 // if implmeth is declared in Object. The reason is
2334 // that interfaces really don't inherit from
2335 // Object it's just that the compiler represents
2336 // things that way.
2337 checkOverride(tree, implmeth, absmeth, origin);
2338 }
2339 }
2340 }
2341 }
2342 }
2343 }
2345 /** Check that all abstract methods implemented by a class are
2346 * mutually compatible.
2347 * @param pos Position to be used for error reporting.
2348 * @param c The class whose interfaces are checked.
2349 */
2350 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2351 List<Type> supertypes = types.interfaces(c);
2352 Type supertype = types.supertype(c);
2353 if (supertype.hasTag(CLASS) &&
2354 (supertype.tsym.flags() & ABSTRACT) != 0)
2355 supertypes = supertypes.prepend(supertype);
2356 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2357 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2358 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2359 return;
2360 for (List<Type> m = supertypes; m != l; m = m.tail)
2361 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2362 return;
2363 }
2364 checkCompatibleConcretes(pos, c);
2365 }
2367 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2368 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2369 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2370 // VM allows methods and variables with differing types
2371 if (sym.kind == e.sym.kind &&
2372 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2373 sym != e.sym &&
2374 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2375 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2376 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2377 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2378 return;
2379 }
2380 }
2381 }
2382 }
2384 /** Check that all non-override equivalent methods accessible from 'site'
2385 * are mutually compatible (JLS 8.4.8/9.4.1).
2386 *
2387 * @param pos Position to be used for error reporting.
2388 * @param site The class whose methods are checked.
2389 * @param sym The method symbol to be checked.
2390 */
2391 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2392 ClashFilter cf = new ClashFilter(site);
2393 //for each method m1 that is overridden (directly or indirectly)
2394 //by method 'sym' in 'site'...
2395 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2396 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2397 //...check each method m2 that is a member of 'site'
2398 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2399 if (m2 == m1) continue;
2400 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2401 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2402 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2403 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2404 sym.flags_field |= CLASH;
2405 String key = m1 == sym ?
2406 "name.clash.same.erasure.no.override" :
2407 "name.clash.same.erasure.no.override.1";
2408 log.error(pos,
2409 key,
2410 sym, sym.location(),
2411 m2, m2.location(),
2412 m1, m1.location());
2413 return;
2414 }
2415 }
2416 }
2417 }
2421 /** Check that all static methods accessible from 'site' are
2422 * mutually compatible (JLS 8.4.8).
2423 *
2424 * @param pos Position to be used for error reporting.
2425 * @param site The class whose methods are checked.
2426 * @param sym The method symbol to be checked.
2427 */
2428 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2429 ClashFilter cf = new ClashFilter(site);
2430 //for each method m1 that is a member of 'site'...
2431 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2432 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2433 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2434 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
2435 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2436 log.error(pos,
2437 "name.clash.same.erasure.no.hide",
2438 sym, sym.location(),
2439 s, s.location());
2440 return;
2441 }
2442 }
2443 }
2445 //where
2446 private class ClashFilter implements Filter<Symbol> {
2448 Type site;
2450 ClashFilter(Type site) {
2451 this.site = site;
2452 }
2454 boolean shouldSkip(Symbol s) {
2455 return (s.flags() & CLASH) != 0 &&
2456 s.owner == site.tsym;
2457 }
2459 public boolean accepts(Symbol s) {
2460 return s.kind == MTH &&
2461 (s.flags() & SYNTHETIC) == 0 &&
2462 !shouldSkip(s) &&
2463 s.isInheritedIn(site.tsym, types) &&
2464 !s.isConstructor();
2465 }
2466 }
2468 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2469 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2470 for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
2471 Assert.check(m.kind == MTH);
2472 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2473 if (prov.size() > 1) {
2474 ListBuffer<Symbol> abstracts = ListBuffer.lb();
2475 ListBuffer<Symbol> defaults = ListBuffer.lb();
2476 for (MethodSymbol provSym : prov) {
2477 if ((provSym.flags() & DEFAULT) != 0) {
2478 defaults = defaults.append(provSym);
2479 } else if ((provSym.flags() & ABSTRACT) != 0) {
2480 abstracts = abstracts.append(provSym);
2481 }
2482 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2483 //strong semantics - issue an error if two sibling interfaces
2484 //have two override-equivalent defaults - or if one is abstract
2485 //and the other is default
2486 String errKey;
2487 Symbol s1 = defaults.first();
2488 Symbol s2;
2489 if (defaults.size() > 1) {
2490 errKey = "types.incompatible.unrelated.defaults";
2491 s2 = defaults.toList().tail.head;
2492 } else {
2493 errKey = "types.incompatible.abstract.default";
2494 s2 = abstracts.first();
2495 }
2496 log.error(pos, errKey,
2497 Kinds.kindName(site.tsym), site,
2498 m.name, types.memberType(site, m).getParameterTypes(),
2499 s1.location(), s2.location());
2500 break;
2501 }
2502 }
2503 }
2504 }
2505 }
2507 //where
2508 private class DefaultMethodClashFilter implements Filter<Symbol> {
2510 Type site;
2512 DefaultMethodClashFilter(Type site) {
2513 this.site = site;
2514 }
2516 public boolean accepts(Symbol s) {
2517 return s.kind == MTH &&
2518 (s.flags() & DEFAULT) != 0 &&
2519 s.isInheritedIn(site.tsym, types) &&
2520 !s.isConstructor();
2521 }
2522 }
2524 /** Report a conflict between a user symbol and a synthetic symbol.
2525 */
2526 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2527 if (!sym.type.isErroneous()) {
2528 if (warnOnSyntheticConflicts) {
2529 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2530 }
2531 else {
2532 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2533 }
2534 }
2535 }
2537 /** Check that class c does not implement directly or indirectly
2538 * the same parameterized interface with two different argument lists.
2539 * @param pos Position to be used for error reporting.
2540 * @param type The type whose interfaces are checked.
2541 */
2542 void checkClassBounds(DiagnosticPosition pos, Type type) {
2543 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2544 }
2545 //where
2546 /** Enter all interfaces of type `type' into the hash table `seensofar'
2547 * with their class symbol as key and their type as value. Make
2548 * sure no class is entered with two different types.
2549 */
2550 void checkClassBounds(DiagnosticPosition pos,
2551 Map<TypeSymbol,Type> seensofar,
2552 Type type) {
2553 if (type.isErroneous()) return;
2554 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2555 Type it = l.head;
2556 Type oldit = seensofar.put(it.tsym, it);
2557 if (oldit != null) {
2558 List<Type> oldparams = oldit.allparams();
2559 List<Type> newparams = it.allparams();
2560 if (!types.containsTypeEquivalent(oldparams, newparams))
2561 log.error(pos, "cant.inherit.diff.arg",
2562 it.tsym, Type.toString(oldparams),
2563 Type.toString(newparams));
2564 }
2565 checkClassBounds(pos, seensofar, it);
2566 }
2567 Type st = types.supertype(type);
2568 if (st != null) checkClassBounds(pos, seensofar, st);
2569 }
2571 /** Enter interface into into set.
2572 * If it existed already, issue a "repeated interface" error.
2573 */
2574 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2575 if (its.contains(it))
2576 log.error(pos, "repeated.interface");
2577 else {
2578 its.add(it);
2579 }
2580 }
2582 /* *************************************************************************
2583 * Check annotations
2584 **************************************************************************/
2586 /**
2587 * Recursively validate annotations values
2588 */
2589 void validateAnnotationTree(JCTree tree) {
2590 class AnnotationValidator extends TreeScanner {
2591 @Override
2592 public void visitAnnotation(JCAnnotation tree) {
2593 if (!tree.type.isErroneous()) {
2594 super.visitAnnotation(tree);
2595 validateAnnotation(tree);
2596 }
2597 }
2598 }
2599 tree.accept(new AnnotationValidator());
2600 }
2602 /**
2603 * {@literal
2604 * Annotation types are restricted to primitives, String, an
2605 * enum, an annotation, Class, Class<?>, Class<? extends
2606 * Anything>, arrays of the preceding.
2607 * }
2608 */
2609 void validateAnnotationType(JCTree restype) {
2610 // restype may be null if an error occurred, so don't bother validating it
2611 if (restype != null) {
2612 validateAnnotationType(restype.pos(), restype.type);
2613 }
2614 }
2616 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2617 if (type.isPrimitive()) return;
2618 if (types.isSameType(type, syms.stringType)) return;
2619 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2620 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2621 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2622 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2623 validateAnnotationType(pos, types.elemtype(type));
2624 return;
2625 }
2626 log.error(pos, "invalid.annotation.member.type");
2627 }
2629 /**
2630 * "It is also a compile-time error if any method declared in an
2631 * annotation type has a signature that is override-equivalent to
2632 * that of any public or protected method declared in class Object
2633 * or in the interface annotation.Annotation."
2634 *
2635 * @jls 9.6 Annotation Types
2636 */
2637 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2638 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2639 Scope s = sup.tsym.members();
2640 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2641 if (e.sym.kind == MTH &&
2642 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2643 types.overrideEquivalent(m.type, e.sym.type))
2644 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2645 }
2646 }
2647 }
2649 /** Check the annotations of a symbol.
2650 */
2651 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2652 for (JCAnnotation a : annotations)
2653 validateAnnotation(a, s);
2654 }
2656 /** Check the type annotations.
2657 */
2658 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2659 for (JCAnnotation a : annotations)
2660 validateTypeAnnotation(a, isTypeParameter);
2661 }
2663 /** Check an annotation of a symbol.
2664 */
2665 private void validateAnnotation(JCAnnotation a, Symbol s) {
2666 validateAnnotationTree(a);
2668 if (!annotationApplicable(a, s))
2669 log.error(a.pos(), "annotation.type.not.applicable");
2671 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2672 if (!isOverrider(s))
2673 log.error(a.pos(), "method.does.not.override.superclass");
2674 }
2676 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2677 if (s.kind != TYP) {
2678 log.error(a.pos(), "bad.functional.intf.anno");
2679 } else {
2680 try {
2681 types.findDescriptorSymbol((TypeSymbol)s);
2682 } catch (Types.FunctionDescriptorLookupError ex) {
2683 log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
2684 }
2685 }
2686 }
2687 }
2689 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2690 Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
2691 validateAnnotationTree(a);
2693 if (!isTypeAnnotation(a, isTypeParameter))
2694 log.error(a.pos(), "annotation.type.not.applicable");
2695 }
2697 /**
2698 * Validate the proposed container 'repeatable' on the
2699 * annotation type symbol 's'. Report errors at position
2700 * 'pos'.
2701 *
2702 * @param s The (annotation)type declaration annotated with a @Repeatable
2703 * @param repeatable the @Repeatable on 's'
2704 * @param pos where to report errors
2705 */
2706 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2707 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2709 Type t = null;
2710 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2711 if (!l.isEmpty()) {
2712 Assert.check(l.head.fst.name == names.value);
2713 t = ((Attribute.Class)l.head.snd).getValue();
2714 }
2716 if (t == null) {
2717 // errors should already have been reported during Annotate
2718 return;
2719 }
2721 validateValue(t.tsym, s, pos);
2722 validateRetention(t.tsym, s, pos);
2723 validateDocumented(t.tsym, s, pos);
2724 validateInherited(t.tsym, s, pos);
2725 validateTarget(t.tsym, s, pos);
2726 validateDefault(t.tsym, s, pos);
2727 }
2729 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2730 Scope.Entry e = container.members().lookup(names.value);
2731 if (e.scope != null && e.sym.kind == MTH) {
2732 MethodSymbol m = (MethodSymbol) e.sym;
2733 Type ret = m.getReturnType();
2734 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2735 log.error(pos, "invalid.repeatable.annotation.value.return",
2736 container, ret, types.makeArrayType(contained.type));
2737 }
2738 } else {
2739 log.error(pos, "invalid.repeatable.annotation.no.value", container);
2740 }
2741 }
2743 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2744 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2745 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2747 boolean error = false;
2748 switch (containedRetention) {
2749 case RUNTIME:
2750 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2751 error = true;
2752 }
2753 break;
2754 case CLASS:
2755 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2756 error = true;
2757 }
2758 }
2759 if (error ) {
2760 log.error(pos, "invalid.repeatable.annotation.retention",
2761 container, containerRetention,
2762 contained, containedRetention);
2763 }
2764 }
2766 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2767 if (contained.attribute(syms.documentedType.tsym) != null) {
2768 if (container.attribute(syms.documentedType.tsym) == null) {
2769 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2770 }
2771 }
2772 }
2774 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2775 if (contained.attribute(syms.inheritedType.tsym) != null) {
2776 if (container.attribute(syms.inheritedType.tsym) == null) {
2777 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2778 }
2779 }
2780 }
2782 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2783 // The set of targets the container is applicable to must be a subset
2784 // (with respect to annotation target semantics) of the set of targets
2785 // the contained is applicable to. The target sets may be implicit or
2786 // explicit.
2788 Set<Name> containerTargets;
2789 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2790 if (containerTarget == null) {
2791 containerTargets = getDefaultTargetSet();
2792 } else {
2793 containerTargets = new HashSet<Name>();
2794 for (Attribute app : containerTarget.values) {
2795 if (!(app instanceof Attribute.Enum)) {
2796 continue; // recovery
2797 }
2798 Attribute.Enum e = (Attribute.Enum)app;
2799 containerTargets.add(e.value.name);
2800 }
2801 }
2803 Set<Name> containedTargets;
2804 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2805 if (containedTarget == null) {
2806 containedTargets = getDefaultTargetSet();
2807 } else {
2808 containedTargets = new HashSet<Name>();
2809 for (Attribute app : containedTarget.values) {
2810 if (!(app instanceof Attribute.Enum)) {
2811 continue; // recovery
2812 }
2813 Attribute.Enum e = (Attribute.Enum)app;
2814 containedTargets.add(e.value.name);
2815 }
2816 }
2818 if (!isTargetSubsetOf(containerTargets, containedTargets)) {
2819 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2820 }
2821 }
2823 /* get a set of names for the default target */
2824 private Set<Name> getDefaultTargetSet() {
2825 if (defaultTargets == null) {
2826 Set<Name> targets = new HashSet<Name>();
2827 targets.add(names.ANNOTATION_TYPE);
2828 targets.add(names.CONSTRUCTOR);
2829 targets.add(names.FIELD);
2830 targets.add(names.LOCAL_VARIABLE);
2831 targets.add(names.METHOD);
2832 targets.add(names.PACKAGE);
2833 targets.add(names.PARAMETER);
2834 targets.add(names.TYPE);
2836 defaultTargets = java.util.Collections.unmodifiableSet(targets);
2837 }
2839 return defaultTargets;
2840 }
2841 private Set<Name> defaultTargets;
2844 /** Checks that s is a subset of t, with respect to ElementType
2845 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2846 */
2847 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
2848 // Check that all elements in s are present in t
2849 for (Name n2 : s) {
2850 boolean currentElementOk = false;
2851 for (Name n1 : t) {
2852 if (n1 == n2) {
2853 currentElementOk = true;
2854 break;
2855 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2856 currentElementOk = true;
2857 break;
2858 }
2859 }
2860 if (!currentElementOk)
2861 return false;
2862 }
2863 return true;
2864 }
2866 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2867 // validate that all other elements of containing type has defaults
2868 Scope scope = container.members();
2869 for(Symbol elm : scope.getElements()) {
2870 if (elm.name != names.value &&
2871 elm.kind == Kinds.MTH &&
2872 ((MethodSymbol)elm).defaultValue == null) {
2873 log.error(pos,
2874 "invalid.repeatable.annotation.elem.nondefault",
2875 container,
2876 elm);
2877 }
2878 }
2879 }
2881 /** Is s a method symbol that overrides a method in a superclass? */
2882 boolean isOverrider(Symbol s) {
2883 if (s.kind != MTH || s.isStatic())
2884 return false;
2885 MethodSymbol m = (MethodSymbol)s;
2886 TypeSymbol owner = (TypeSymbol)m.owner;
2887 for (Type sup : types.closure(owner.type)) {
2888 if (sup == owner.type)
2889 continue; // skip "this"
2890 Scope scope = sup.tsym.members();
2891 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2892 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2893 return true;
2894 }
2895 }
2896 return false;
2897 }
2899 /** Is the annotation applicable to type annotations? */
2900 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2901 Attribute.Compound atTarget =
2902 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2903 if (atTarget == null) {
2904 // An annotation without @Target is not a type annotation.
2905 return false;
2906 }
2908 Attribute atValue = atTarget.member(names.value);
2909 if (!(atValue instanceof Attribute.Array)) {
2910 return false; // error recovery
2911 }
2913 Attribute.Array arr = (Attribute.Array) atValue;
2914 for (Attribute app : arr.values) {
2915 if (!(app instanceof Attribute.Enum)) {
2916 return false; // recovery
2917 }
2918 Attribute.Enum e = (Attribute.Enum) app;
2920 if (e.value.name == names.TYPE_USE)
2921 return true;
2922 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2923 return true;
2924 }
2925 return false;
2926 }
2928 /** Is the annotation applicable to the symbol? */
2929 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2930 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2931 Name[] targets;
2933 if (arr == null) {
2934 targets = defaultTargetMetaInfo(a, s);
2935 } else {
2936 // TODO: can we optimize this?
2937 targets = new Name[arr.values.length];
2938 for (int i=0; i<arr.values.length; ++i) {
2939 Attribute app = arr.values[i];
2940 if (!(app instanceof Attribute.Enum)) {
2941 return true; // recovery
2942 }
2943 Attribute.Enum e = (Attribute.Enum) app;
2944 targets[i] = e.value.name;
2945 }
2946 }
2947 for (Name target : targets) {
2948 if (target == names.TYPE)
2949 { if (s.kind == TYP) return true; }
2950 else if (target == names.FIELD)
2951 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2952 else if (target == names.METHOD)
2953 { if (s.kind == MTH && !s.isConstructor()) return true; }
2954 else if (target == names.PARAMETER)
2955 { if (s.kind == VAR &&
2956 s.owner.kind == MTH &&
2957 (s.flags() & PARAMETER) != 0)
2958 return true;
2959 }
2960 else if (target == names.CONSTRUCTOR)
2961 { if (s.kind == MTH && s.isConstructor()) return true; }
2962 else if (target == names.LOCAL_VARIABLE)
2963 { if (s.kind == VAR && s.owner.kind == MTH &&
2964 (s.flags() & PARAMETER) == 0)
2965 return true;
2966 }
2967 else if (target == names.ANNOTATION_TYPE)
2968 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2969 return true;
2970 }
2971 else if (target == names.PACKAGE)
2972 { if (s.kind == PCK) return true; }
2973 else if (target == names.TYPE_USE)
2974 { if (s.kind == TYP ||
2975 s.kind == VAR ||
2976 (s.kind == MTH && !s.isConstructor() &&
2977 !s.type.getReturnType().hasTag(VOID)) ||
2978 (s.kind == MTH && s.isConstructor()))
2979 return true;
2980 }
2981 else if (target == names.TYPE_PARAMETER)
2982 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
2983 return true;
2984 }
2985 else
2986 return true; // recovery
2987 }
2988 return false;
2989 }
2992 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2993 Attribute.Compound atTarget =
2994 s.attribute(syms.annotationTargetType.tsym);
2995 if (atTarget == null) return null; // ok, is applicable
2996 Attribute atValue = atTarget.member(names.value);
2997 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2998 return (Attribute.Array) atValue;
2999 }
3001 private final Name[] dfltTargetMeta;
3002 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
3003 return dfltTargetMeta;
3004 }
3006 /** Check an annotation value.
3007 *
3008 * @param a The annotation tree to check
3009 * @return true if this annotation tree is valid, otherwise false
3010 */
3011 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3012 boolean res = false;
3013 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3014 try {
3015 res = validateAnnotation(a);
3016 } finally {
3017 log.popDiagnosticHandler(diagHandler);
3018 }
3019 return res;
3020 }
3022 private boolean validateAnnotation(JCAnnotation a) {
3023 boolean isValid = true;
3024 // collect an inventory of the annotation elements
3025 Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
3026 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
3027 e != null;
3028 e = e.sibling)
3029 if (e.sym.kind == MTH && e.sym.name != names.clinit)
3030 members.add((MethodSymbol) e.sym);
3032 // remove the ones that are assigned values
3033 for (JCTree arg : a.args) {
3034 if (!arg.hasTag(ASSIGN)) continue; // recovery
3035 JCAssign assign = (JCAssign) arg;
3036 Symbol m = TreeInfo.symbol(assign.lhs);
3037 if (m == null || m.type.isErroneous()) continue;
3038 if (!members.remove(m)) {
3039 isValid = false;
3040 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3041 m.name, a.type);
3042 }
3043 }
3045 // all the remaining ones better have default values
3046 List<Name> missingDefaults = List.nil();
3047 for (MethodSymbol m : members) {
3048 if (m.defaultValue == null && !m.type.isErroneous()) {
3049 missingDefaults = missingDefaults.append(m.name);
3050 }
3051 }
3052 missingDefaults = missingDefaults.reverse();
3053 if (missingDefaults.nonEmpty()) {
3054 isValid = false;
3055 String key = (missingDefaults.size() > 1)
3056 ? "annotation.missing.default.value.1"
3057 : "annotation.missing.default.value";
3058 log.error(a.pos(), key, a.type, missingDefaults);
3059 }
3061 // special case: java.lang.annotation.Target must not have
3062 // repeated values in its value member
3063 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3064 a.args.tail == null)
3065 return isValid;
3067 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3068 JCAssign assign = (JCAssign) a.args.head;
3069 Symbol m = TreeInfo.symbol(assign.lhs);
3070 if (m.name != names.value) return false;
3071 JCTree rhs = assign.rhs;
3072 if (!rhs.hasTag(NEWARRAY)) return false;
3073 JCNewArray na = (JCNewArray) rhs;
3074 Set<Symbol> targets = new HashSet<Symbol>();
3075 for (JCTree elem : na.elems) {
3076 if (!targets.add(TreeInfo.symbol(elem))) {
3077 isValid = false;
3078 log.error(elem.pos(), "repeated.annotation.target");
3079 }
3080 }
3081 return isValid;
3082 }
3084 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3085 if (allowAnnotations &&
3086 lint.isEnabled(LintCategory.DEP_ANN) &&
3087 (s.flags() & DEPRECATED) != 0 &&
3088 !syms.deprecatedType.isErroneous() &&
3089 s.attribute(syms.deprecatedType.tsym) == null) {
3090 log.warning(LintCategory.DEP_ANN,
3091 pos, "missing.deprecated.annotation");
3092 }
3093 }
3095 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3096 if ((s.flags() & DEPRECATED) != 0 &&
3097 (other.flags() & DEPRECATED) == 0 &&
3098 s.outermostClass() != other.outermostClass()) {
3099 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3100 @Override
3101 public void report() {
3102 warnDeprecated(pos, s);
3103 }
3104 });
3105 }
3106 }
3108 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3109 if ((s.flags() & PROPRIETARY) != 0) {
3110 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3111 public void report() {
3112 if (enableSunApiLintControl)
3113 warnSunApi(pos, "sun.proprietary", s);
3114 else
3115 log.mandatoryWarning(pos, "sun.proprietary", s);
3116 }
3117 });
3118 }
3119 }
3121 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3122 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3123 log.error(pos, "not.in.profile", s, profile);
3124 }
3125 }
3127 /* *************************************************************************
3128 * Check for recursive annotation elements.
3129 **************************************************************************/
3131 /** Check for cycles in the graph of annotation elements.
3132 */
3133 void checkNonCyclicElements(JCClassDecl tree) {
3134 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3135 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3136 try {
3137 tree.sym.flags_field |= LOCKED;
3138 for (JCTree def : tree.defs) {
3139 if (!def.hasTag(METHODDEF)) continue;
3140 JCMethodDecl meth = (JCMethodDecl)def;
3141 checkAnnotationResType(meth.pos(), meth.restype.type);
3142 }
3143 } finally {
3144 tree.sym.flags_field &= ~LOCKED;
3145 tree.sym.flags_field |= ACYCLIC_ANN;
3146 }
3147 }
3149 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3150 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3151 return;
3152 if ((tsym.flags_field & LOCKED) != 0) {
3153 log.error(pos, "cyclic.annotation.element");
3154 return;
3155 }
3156 try {
3157 tsym.flags_field |= LOCKED;
3158 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3159 Symbol s = e.sym;
3160 if (s.kind != Kinds.MTH)
3161 continue;
3162 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3163 }
3164 } finally {
3165 tsym.flags_field &= ~LOCKED;
3166 tsym.flags_field |= ACYCLIC_ANN;
3167 }
3168 }
3170 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3171 switch (type.getTag()) {
3172 case CLASS:
3173 if ((type.tsym.flags() & ANNOTATION) != 0)
3174 checkNonCyclicElementsInternal(pos, type.tsym);
3175 break;
3176 case ARRAY:
3177 checkAnnotationResType(pos, types.elemtype(type));
3178 break;
3179 default:
3180 break; // int etc
3181 }
3182 }
3184 /* *************************************************************************
3185 * Check for cycles in the constructor call graph.
3186 **************************************************************************/
3188 /** Check for cycles in the graph of constructors calling other
3189 * constructors.
3190 */
3191 void checkCyclicConstructors(JCClassDecl tree) {
3192 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3194 // enter each constructor this-call into the map
3195 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3196 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3197 if (app == null) continue;
3198 JCMethodDecl meth = (JCMethodDecl) l.head;
3199 if (TreeInfo.name(app.meth) == names._this) {
3200 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3201 } else {
3202 meth.sym.flags_field |= ACYCLIC;
3203 }
3204 }
3206 // Check for cycles in the map
3207 Symbol[] ctors = new Symbol[0];
3208 ctors = callMap.keySet().toArray(ctors);
3209 for (Symbol caller : ctors) {
3210 checkCyclicConstructor(tree, caller, callMap);
3211 }
3212 }
3214 /** Look in the map to see if the given constructor is part of a
3215 * call cycle.
3216 */
3217 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3218 Map<Symbol,Symbol> callMap) {
3219 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3220 if ((ctor.flags_field & LOCKED) != 0) {
3221 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3222 "recursive.ctor.invocation");
3223 } else {
3224 ctor.flags_field |= LOCKED;
3225 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3226 ctor.flags_field &= ~LOCKED;
3227 }
3228 ctor.flags_field |= ACYCLIC;
3229 }
3230 }
3232 /* *************************************************************************
3233 * Miscellaneous
3234 **************************************************************************/
3236 /**
3237 * Return the opcode of the operator but emit an error if it is an
3238 * error.
3239 * @param pos position for error reporting.
3240 * @param operator an operator
3241 * @param tag a tree tag
3242 * @param left type of left hand side
3243 * @param right type of right hand side
3244 */
3245 int checkOperator(DiagnosticPosition pos,
3246 OperatorSymbol operator,
3247 JCTree.Tag tag,
3248 Type left,
3249 Type right) {
3250 if (operator.opcode == ByteCodes.error) {
3251 log.error(pos,
3252 "operator.cant.be.applied.1",
3253 treeinfo.operatorName(tag),
3254 left, right);
3255 }
3256 return operator.opcode;
3257 }
3260 /**
3261 * Check for division by integer constant zero
3262 * @param pos Position for error reporting.
3263 * @param operator The operator for the expression
3264 * @param operand The right hand operand for the expression
3265 */
3266 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3267 if (operand.constValue() != null
3268 && lint.isEnabled(LintCategory.DIVZERO)
3269 && (operand.getTag().isSubRangeOf(LONG))
3270 && ((Number) (operand.constValue())).longValue() == 0) {
3271 int opc = ((OperatorSymbol)operator).opcode;
3272 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3273 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3274 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3275 }
3276 }
3277 }
3279 /**
3280 * Check for empty statements after if
3281 */
3282 void checkEmptyIf(JCIf tree) {
3283 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3284 lint.isEnabled(LintCategory.EMPTY))
3285 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3286 }
3288 /** Check that symbol is unique in given scope.
3289 * @param pos Position for error reporting.
3290 * @param sym The symbol.
3291 * @param s The scope.
3292 */
3293 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3294 if (sym.type.isErroneous())
3295 return true;
3296 if (sym.owner.name == names.any) return false;
3297 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3298 if (sym != e.sym &&
3299 (e.sym.flags() & CLASH) == 0 &&
3300 sym.kind == e.sym.kind &&
3301 sym.name != names.error &&
3302 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3303 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3304 varargsDuplicateError(pos, sym, e.sym);
3305 return true;
3306 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3307 duplicateErasureError(pos, sym, e.sym);
3308 sym.flags_field |= CLASH;
3309 return true;
3310 } else {
3311 duplicateError(pos, e.sym);
3312 return false;
3313 }
3314 }
3315 }
3316 return true;
3317 }
3319 /** Report duplicate declaration error.
3320 */
3321 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3322 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3323 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3324 }
3325 }
3327 /** Check that single-type import is not already imported or top-level defined,
3328 * but make an exception for two single-type imports which denote the same type.
3329 * @param pos Position for error reporting.
3330 * @param sym The symbol.
3331 * @param s The scope
3332 */
3333 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3334 return checkUniqueImport(pos, sym, s, false);
3335 }
3337 /** Check that static single-type import is not already imported or top-level defined,
3338 * but make an exception for two single-type imports which denote the same type.
3339 * @param pos Position for error reporting.
3340 * @param sym The symbol.
3341 * @param s The scope
3342 */
3343 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3344 return checkUniqueImport(pos, sym, s, true);
3345 }
3347 /** Check that single-type import is not already imported or top-level defined,
3348 * but make an exception for two single-type imports which denote the same type.
3349 * @param pos Position for error reporting.
3350 * @param sym The symbol.
3351 * @param s The scope.
3352 * @param staticImport Whether or not this was a static import
3353 */
3354 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3355 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3356 // is encountered class entered via a class declaration?
3357 boolean isClassDecl = e.scope == s;
3358 if ((isClassDecl || sym != e.sym) &&
3359 sym.kind == e.sym.kind &&
3360 sym.name != names.error) {
3361 if (!e.sym.type.isErroneous()) {
3362 String what = e.sym.toString();
3363 if (!isClassDecl) {
3364 if (staticImport)
3365 log.error(pos, "already.defined.static.single.import", what);
3366 else
3367 log.error(pos, "already.defined.single.import", what);
3368 }
3369 else if (sym != e.sym)
3370 log.error(pos, "already.defined.this.unit", what);
3371 }
3372 return false;
3373 }
3374 }
3375 return true;
3376 }
3378 /** Check that a qualified name is in canonical form (for import decls).
3379 */
3380 public void checkCanonical(JCTree tree) {
3381 if (!isCanonical(tree))
3382 log.error(tree.pos(), "import.requires.canonical",
3383 TreeInfo.symbol(tree));
3384 }
3385 // where
3386 private boolean isCanonical(JCTree tree) {
3387 while (tree.hasTag(SELECT)) {
3388 JCFieldAccess s = (JCFieldAccess) tree;
3389 if (s.sym.owner != TreeInfo.symbol(s.selected))
3390 return false;
3391 tree = s.selected;
3392 }
3393 return true;
3394 }
3396 /** Check that an auxiliary class is not accessed from any other file than its own.
3397 */
3398 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3399 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3400 (c.flags() & AUXILIARY) != 0 &&
3401 rs.isAccessible(env, c) &&
3402 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3403 {
3404 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3405 c, c.sourcefile);
3406 }
3407 }
3409 private class ConversionWarner extends Warner {
3410 final String uncheckedKey;
3411 final Type found;
3412 final Type expected;
3413 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3414 super(pos);
3415 this.uncheckedKey = uncheckedKey;
3416 this.found = found;
3417 this.expected = expected;
3418 }
3420 @Override
3421 public void warn(LintCategory lint) {
3422 boolean warned = this.warned;
3423 super.warn(lint);
3424 if (warned) return; // suppress redundant diagnostics
3425 switch (lint) {
3426 case UNCHECKED:
3427 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3428 break;
3429 case VARARGS:
3430 if (method != null &&
3431 method.attribute(syms.trustMeType.tsym) != null &&
3432 isTrustMeAllowedOnMethod(method) &&
3433 !types.isReifiable(method.type.getParameterTypes().last())) {
3434 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3435 }
3436 break;
3437 default:
3438 throw new AssertionError("Unexpected lint: " + lint);
3439 }
3440 }
3441 }
3443 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3444 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3445 }
3447 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3448 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3449 }
3450 }