Mon, 18 Mar 2013 14:40:32 -0700
8008425: Remove interim new javax.lang.model API for type-annotations
Reviewed-by: darcy
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 implicit |= sym.owner.flags_field & STRICTFP;
1083 break;
1084 case TYP:
1085 if (sym.isLocal()) {
1086 mask = LocalClassFlags;
1087 if (sym.name.isEmpty()) { // Anonymous class
1088 // Anonymous classes in static methods are themselves static;
1089 // that's why we admit STATIC here.
1090 mask |= STATIC;
1091 // JLS: Anonymous classes are final.
1092 implicit |= FINAL;
1093 }
1094 if ((sym.owner.flags_field & STATIC) == 0 &&
1095 (flags & ENUM) != 0)
1096 log.error(pos, "enums.must.be.static");
1097 } else if (sym.owner.kind == TYP) {
1098 mask = MemberClassFlags;
1099 if (sym.owner.owner.kind == PCK ||
1100 (sym.owner.flags_field & STATIC) != 0)
1101 mask |= STATIC;
1102 else if ((flags & ENUM) != 0)
1103 log.error(pos, "enums.must.be.static");
1104 // Nested interfaces and enums are always STATIC (Spec ???)
1105 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1106 } else {
1107 mask = ClassFlags;
1108 }
1109 // Interfaces are always ABSTRACT
1110 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1112 if ((flags & ENUM) != 0) {
1113 // enums can't be declared abstract or final
1114 mask &= ~(ABSTRACT | FINAL);
1115 implicit |= implicitEnumFinalFlag(tree);
1116 }
1117 // Imply STRICTFP if owner has STRICTFP set.
1118 implicit |= sym.owner.flags_field & STRICTFP;
1119 break;
1120 default:
1121 throw new AssertionError();
1122 }
1123 long illegal = flags & ExtendedStandardFlags & ~mask;
1124 if (illegal != 0) {
1125 if ((illegal & INTERFACE) != 0) {
1126 log.error(pos, "intf.not.allowed.here");
1127 mask |= INTERFACE;
1128 }
1129 else {
1130 log.error(pos,
1131 "mod.not.allowed.here", asFlagSet(illegal));
1132 }
1133 }
1134 else if ((sym.kind == TYP ||
1135 // ISSUE: Disallowing abstract&private is no longer appropriate
1136 // in the presence of inner classes. Should it be deleted here?
1137 checkDisjoint(pos, flags,
1138 ABSTRACT,
1139 PRIVATE | STATIC | DEFAULT))
1140 &&
1141 checkDisjoint(pos, flags,
1142 STATIC,
1143 DEFAULT)
1144 &&
1145 checkDisjoint(pos, flags,
1146 ABSTRACT | INTERFACE,
1147 FINAL | NATIVE | SYNCHRONIZED)
1148 &&
1149 checkDisjoint(pos, flags,
1150 PUBLIC,
1151 PRIVATE | PROTECTED)
1152 &&
1153 checkDisjoint(pos, flags,
1154 PRIVATE,
1155 PUBLIC | PROTECTED)
1156 &&
1157 checkDisjoint(pos, flags,
1158 FINAL,
1159 VOLATILE)
1160 &&
1161 (sym.kind == TYP ||
1162 checkDisjoint(pos, flags,
1163 ABSTRACT | NATIVE,
1164 STRICTFP))) {
1165 // skip
1166 }
1167 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1168 }
1171 /** Determine if this enum should be implicitly final.
1172 *
1173 * If the enum has no specialized enum contants, it is final.
1174 *
1175 * If the enum does have specialized enum contants, it is
1176 * <i>not</i> final.
1177 */
1178 private long implicitEnumFinalFlag(JCTree tree) {
1179 if (!tree.hasTag(CLASSDEF)) return 0;
1180 class SpecialTreeVisitor extends JCTree.Visitor {
1181 boolean specialized;
1182 SpecialTreeVisitor() {
1183 this.specialized = false;
1184 };
1186 @Override
1187 public void visitTree(JCTree tree) { /* no-op */ }
1189 @Override
1190 public void visitVarDef(JCVariableDecl tree) {
1191 if ((tree.mods.flags & ENUM) != 0) {
1192 if (tree.init instanceof JCNewClass &&
1193 ((JCNewClass) tree.init).def != null) {
1194 specialized = true;
1195 }
1196 }
1197 }
1198 }
1200 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1201 JCClassDecl cdef = (JCClassDecl) tree;
1202 for (JCTree defs: cdef.defs) {
1203 defs.accept(sts);
1204 if (sts.specialized) return 0;
1205 }
1206 return FINAL;
1207 }
1209 /* *************************************************************************
1210 * Type Validation
1211 **************************************************************************/
1213 /** Validate a type expression. That is,
1214 * check that all type arguments of a parametric type are within
1215 * their bounds. This must be done in a second phase after type attributon
1216 * since a class might have a subclass as type parameter bound. E.g:
1217 *
1218 * <pre>{@code
1219 * class B<A extends C> { ... }
1220 * class C extends B<C> { ... }
1221 * }</pre>
1222 *
1223 * and we can't make sure that the bound is already attributed because
1224 * of possible cycles.
1225 *
1226 * Visitor method: Validate a type expression, if it is not null, catching
1227 * and reporting any completion failures.
1228 */
1229 void validate(JCTree tree, Env<AttrContext> env) {
1230 validate(tree, env, true);
1231 }
1232 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1233 new Validator(env).validateTree(tree, checkRaw, true);
1234 }
1236 /** Visitor method: Validate a list of type expressions.
1237 */
1238 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1239 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1240 validate(l.head, env);
1241 }
1243 /** A visitor class for type validation.
1244 */
1245 class Validator extends JCTree.Visitor {
1247 boolean isOuter;
1248 Env<AttrContext> env;
1250 Validator(Env<AttrContext> env) {
1251 this.env = env;
1252 }
1254 @Override
1255 public void visitTypeArray(JCArrayTypeTree tree) {
1256 tree.elemtype.accept(this);
1257 }
1259 @Override
1260 public void visitTypeApply(JCTypeApply tree) {
1261 if (tree.type.hasTag(CLASS)) {
1262 List<JCExpression> args = tree.arguments;
1263 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1265 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1266 if (incompatibleArg != null) {
1267 for (JCTree arg : tree.arguments) {
1268 if (arg.type == incompatibleArg) {
1269 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1270 }
1271 forms = forms.tail;
1272 }
1273 }
1275 forms = tree.type.tsym.type.getTypeArguments();
1277 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1279 // For matching pairs of actual argument types `a' and
1280 // formal type parameters with declared bound `b' ...
1281 while (args.nonEmpty() && forms.nonEmpty()) {
1282 validateTree(args.head,
1283 !(isOuter && is_java_lang_Class),
1284 false);
1285 args = args.tail;
1286 forms = forms.tail;
1287 }
1289 // Check that this type is either fully parameterized, or
1290 // not parameterized at all.
1291 if (tree.type.getEnclosingType().isRaw())
1292 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1293 if (tree.clazz.hasTag(SELECT))
1294 visitSelectInternal((JCFieldAccess)tree.clazz);
1295 }
1296 }
1298 @Override
1299 public void visitTypeParameter(JCTypeParameter tree) {
1300 validateTrees(tree.bounds, true, isOuter);
1301 checkClassBounds(tree.pos(), tree.type);
1302 }
1304 @Override
1305 public void visitWildcard(JCWildcard tree) {
1306 if (tree.inner != null)
1307 validateTree(tree.inner, true, isOuter);
1308 }
1310 @Override
1311 public void visitSelect(JCFieldAccess tree) {
1312 if (tree.type.hasTag(CLASS)) {
1313 visitSelectInternal(tree);
1315 // Check that this type is either fully parameterized, or
1316 // not parameterized at all.
1317 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1318 log.error(tree.pos(), "improperly.formed.type.param.missing");
1319 }
1320 }
1322 public void visitSelectInternal(JCFieldAccess tree) {
1323 if (tree.type.tsym.isStatic() &&
1324 tree.selected.type.isParameterized()) {
1325 // The enclosing type is not a class, so we are
1326 // looking at a static member type. However, the
1327 // qualifying expression is parameterized.
1328 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1329 } else {
1330 // otherwise validate the rest of the expression
1331 tree.selected.accept(this);
1332 }
1333 }
1335 @Override
1336 public void visitAnnotatedType(JCAnnotatedType tree) {
1337 tree.underlyingType.accept(this);
1338 }
1340 /** Default visitor method: do nothing.
1341 */
1342 @Override
1343 public void visitTree(JCTree tree) {
1344 }
1346 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1347 try {
1348 if (tree != null) {
1349 this.isOuter = isOuter;
1350 tree.accept(this);
1351 if (checkRaw)
1352 checkRaw(tree, env);
1353 }
1354 } catch (CompletionFailure ex) {
1355 completionError(tree.pos(), ex);
1356 }
1357 }
1359 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1360 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1361 validateTree(l.head, checkRaw, isOuter);
1362 }
1364 void checkRaw(JCTree tree, Env<AttrContext> env) {
1365 if (lint.isEnabled(LintCategory.RAW) &&
1366 tree.type.hasTag(CLASS) &&
1367 !TreeInfo.isDiamond(tree) &&
1368 !withinAnonConstr(env) &&
1369 tree.type.isRaw()) {
1370 log.warning(LintCategory.RAW,
1371 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1372 }
1373 }
1375 boolean withinAnonConstr(Env<AttrContext> env) {
1376 return env.enclClass.name.isEmpty() &&
1377 env.enclMethod != null && env.enclMethod.name == names.init;
1378 }
1379 }
1381 /* *************************************************************************
1382 * Exception checking
1383 **************************************************************************/
1385 /* The following methods treat classes as sets that contain
1386 * the class itself and all their subclasses
1387 */
1389 /** Is given type a subtype of some of the types in given list?
1390 */
1391 boolean subset(Type t, List<Type> ts) {
1392 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1393 if (types.isSubtype(t, l.head)) return true;
1394 return false;
1395 }
1397 /** Is given type a subtype or supertype of
1398 * some of the types in given list?
1399 */
1400 boolean intersects(Type t, List<Type> ts) {
1401 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1402 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1403 return false;
1404 }
1406 /** Add type set to given type list, unless it is a subclass of some class
1407 * in the list.
1408 */
1409 List<Type> incl(Type t, List<Type> ts) {
1410 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1411 }
1413 /** Remove type set from type set list.
1414 */
1415 List<Type> excl(Type t, List<Type> ts) {
1416 if (ts.isEmpty()) {
1417 return ts;
1418 } else {
1419 List<Type> ts1 = excl(t, ts.tail);
1420 if (types.isSubtype(ts.head, t)) return ts1;
1421 else if (ts1 == ts.tail) return ts;
1422 else return ts1.prepend(ts.head);
1423 }
1424 }
1426 /** Form the union of two type set lists.
1427 */
1428 List<Type> union(List<Type> ts1, List<Type> ts2) {
1429 List<Type> ts = ts1;
1430 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1431 ts = incl(l.head, ts);
1432 return ts;
1433 }
1435 /** Form the difference of two type lists.
1436 */
1437 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1438 List<Type> ts = ts1;
1439 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1440 ts = excl(l.head, ts);
1441 return ts;
1442 }
1444 /** Form the intersection of two type lists.
1445 */
1446 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1447 List<Type> ts = List.nil();
1448 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1449 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1450 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1451 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1452 return ts;
1453 }
1455 /** Is exc an exception symbol that need not be declared?
1456 */
1457 boolean isUnchecked(ClassSymbol exc) {
1458 return
1459 exc.kind == ERR ||
1460 exc.isSubClass(syms.errorType.tsym, types) ||
1461 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1462 }
1464 /** Is exc an exception type that need not be declared?
1465 */
1466 boolean isUnchecked(Type exc) {
1467 return
1468 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1469 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1470 exc.hasTag(BOT);
1471 }
1473 /** Same, but handling completion failures.
1474 */
1475 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1476 try {
1477 return isUnchecked(exc);
1478 } catch (CompletionFailure ex) {
1479 completionError(pos, ex);
1480 return true;
1481 }
1482 }
1484 /** Is exc handled by given exception list?
1485 */
1486 boolean isHandled(Type exc, List<Type> handled) {
1487 return isUnchecked(exc) || subset(exc, handled);
1488 }
1490 /** Return all exceptions in thrown list that are not in handled list.
1491 * @param thrown The list of thrown exceptions.
1492 * @param handled The list of handled exceptions.
1493 */
1494 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1495 List<Type> unhandled = List.nil();
1496 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1497 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1498 return unhandled;
1499 }
1501 /* *************************************************************************
1502 * Overriding/Implementation checking
1503 **************************************************************************/
1505 /** The level of access protection given by a flag set,
1506 * where PRIVATE is highest and PUBLIC is lowest.
1507 */
1508 static int protection(long flags) {
1509 switch ((short)(flags & AccessFlags)) {
1510 case PRIVATE: return 3;
1511 case PROTECTED: return 1;
1512 default:
1513 case PUBLIC: return 0;
1514 case 0: return 2;
1515 }
1516 }
1518 /** A customized "cannot override" error message.
1519 * @param m The overriding method.
1520 * @param other The overridden method.
1521 * @return An internationalized string.
1522 */
1523 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1524 String key;
1525 if ((other.owner.flags() & INTERFACE) == 0)
1526 key = "cant.override";
1527 else if ((m.owner.flags() & INTERFACE) == 0)
1528 key = "cant.implement";
1529 else
1530 key = "clashes.with";
1531 return diags.fragment(key, m, m.location(), other, other.location());
1532 }
1534 /** A customized "override" warning message.
1535 * @param m The overriding method.
1536 * @param other The overridden method.
1537 * @return An internationalized string.
1538 */
1539 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1540 String key;
1541 if ((other.owner.flags() & INTERFACE) == 0)
1542 key = "unchecked.override";
1543 else if ((m.owner.flags() & INTERFACE) == 0)
1544 key = "unchecked.implement";
1545 else
1546 key = "unchecked.clash.with";
1547 return diags.fragment(key, m, m.location(), other, other.location());
1548 }
1550 /** A customized "override" warning message.
1551 * @param m The overriding method.
1552 * @param other The overridden method.
1553 * @return An internationalized string.
1554 */
1555 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1556 String key;
1557 if ((other.owner.flags() & INTERFACE) == 0)
1558 key = "varargs.override";
1559 else if ((m.owner.flags() & INTERFACE) == 0)
1560 key = "varargs.implement";
1561 else
1562 key = "varargs.clash.with";
1563 return diags.fragment(key, m, m.location(), other, other.location());
1564 }
1566 /** Check that this method conforms with overridden method 'other'.
1567 * where `origin' is the class where checking started.
1568 * Complications:
1569 * (1) Do not check overriding of synthetic methods
1570 * (reason: they might be final).
1571 * todo: check whether this is still necessary.
1572 * (2) Admit the case where an interface proxy throws fewer exceptions
1573 * than the method it implements. Augment the proxy methods with the
1574 * undeclared exceptions in this case.
1575 * (3) When generics are enabled, admit the case where an interface proxy
1576 * has a result type
1577 * extended by the result type of the method it implements.
1578 * Change the proxies result type to the smaller type in this case.
1579 *
1580 * @param tree The tree from which positions
1581 * are extracted for errors.
1582 * @param m The overriding method.
1583 * @param other The overridden method.
1584 * @param origin The class of which the overriding method
1585 * is a member.
1586 */
1587 void checkOverride(JCTree tree,
1588 MethodSymbol m,
1589 MethodSymbol other,
1590 ClassSymbol origin) {
1591 // Don't check overriding of synthetic methods or by bridge methods.
1592 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1593 return;
1594 }
1596 // Error if static method overrides instance method (JLS 8.4.6.2).
1597 if ((m.flags() & STATIC) != 0 &&
1598 (other.flags() & STATIC) == 0) {
1599 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1600 cannotOverride(m, other));
1601 m.flags_field |= BAD_OVERRIDE;
1602 return;
1603 }
1605 // Error if instance method overrides static or final
1606 // method (JLS 8.4.6.1).
1607 if ((other.flags() & FINAL) != 0 ||
1608 (m.flags() & STATIC) == 0 &&
1609 (other.flags() & STATIC) != 0) {
1610 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1611 cannotOverride(m, other),
1612 asFlagSet(other.flags() & (FINAL | STATIC)));
1613 m.flags_field |= BAD_OVERRIDE;
1614 return;
1615 }
1617 if ((m.owner.flags() & ANNOTATION) != 0) {
1618 // handled in validateAnnotationMethod
1619 return;
1620 }
1622 // Error if overriding method has weaker access (JLS 8.4.6.3).
1623 if ((origin.flags() & INTERFACE) == 0 &&
1624 protection(m.flags()) > protection(other.flags())) {
1625 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1626 cannotOverride(m, other),
1627 other.flags() == 0 ?
1628 Flag.PACKAGE :
1629 asFlagSet(other.flags() & AccessFlags));
1630 m.flags_field |= BAD_OVERRIDE;
1631 return;
1632 }
1634 Type mt = types.memberType(origin.type, m);
1635 Type ot = types.memberType(origin.type, other);
1636 // Error if overriding result type is different
1637 // (or, in the case of generics mode, not a subtype) of
1638 // overridden result type. We have to rename any type parameters
1639 // before comparing types.
1640 List<Type> mtvars = mt.getTypeArguments();
1641 List<Type> otvars = ot.getTypeArguments();
1642 Type mtres = mt.getReturnType();
1643 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1645 overrideWarner.clear();
1646 boolean resultTypesOK =
1647 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1648 if (!resultTypesOK) {
1649 if (!allowCovariantReturns &&
1650 m.owner != origin &&
1651 m.owner.isSubClass(other.owner, types)) {
1652 // allow limited interoperability with covariant returns
1653 } else {
1654 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1655 "override.incompatible.ret",
1656 cannotOverride(m, other),
1657 mtres, otres);
1658 m.flags_field |= BAD_OVERRIDE;
1659 return;
1660 }
1661 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1662 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1663 "override.unchecked.ret",
1664 uncheckedOverrides(m, other),
1665 mtres, otres);
1666 }
1668 // Error if overriding method throws an exception not reported
1669 // by overridden method.
1670 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1671 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1672 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1673 if (unhandledErased.nonEmpty()) {
1674 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1675 "override.meth.doesnt.throw",
1676 cannotOverride(m, other),
1677 unhandledUnerased.head);
1678 m.flags_field |= BAD_OVERRIDE;
1679 return;
1680 }
1681 else if (unhandledUnerased.nonEmpty()) {
1682 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1683 "override.unchecked.thrown",
1684 cannotOverride(m, other),
1685 unhandledUnerased.head);
1686 return;
1687 }
1689 // Optional warning if varargs don't agree
1690 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1691 && lint.isEnabled(LintCategory.OVERRIDES)) {
1692 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1693 ((m.flags() & Flags.VARARGS) != 0)
1694 ? "override.varargs.missing"
1695 : "override.varargs.extra",
1696 varargsOverrides(m, other));
1697 }
1699 // Warn if instance method overrides bridge method (compiler spec ??)
1700 if ((other.flags() & BRIDGE) != 0) {
1701 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1702 uncheckedOverrides(m, other));
1703 }
1705 // Warn if a deprecated method overridden by a non-deprecated one.
1706 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1707 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1708 }
1709 }
1710 // where
1711 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1712 // If the method, m, is defined in an interface, then ignore the issue if the method
1713 // is only inherited via a supertype and also implemented in the supertype,
1714 // because in that case, we will rediscover the issue when examining the method
1715 // in the supertype.
1716 // If the method, m, is not defined in an interface, then the only time we need to
1717 // address the issue is when the method is the supertype implemementation: any other
1718 // case, we will have dealt with when examining the supertype classes
1719 ClassSymbol mc = m.enclClass();
1720 Type st = types.supertype(origin.type);
1721 if (!st.hasTag(CLASS))
1722 return true;
1723 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1725 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1726 List<Type> intfs = types.interfaces(origin.type);
1727 return (intfs.contains(mc.type) ? false : (stimpl != null));
1728 }
1729 else
1730 return (stimpl != m);
1731 }
1734 // used to check if there were any unchecked conversions
1735 Warner overrideWarner = new Warner();
1737 /** Check that a class does not inherit two concrete methods
1738 * with the same signature.
1739 * @param pos Position to be used for error reporting.
1740 * @param site The class type to be checked.
1741 */
1742 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1743 Type sup = types.supertype(site);
1744 if (!sup.hasTag(CLASS)) return;
1746 for (Type t1 = sup;
1747 t1.tsym.type.isParameterized();
1748 t1 = types.supertype(t1)) {
1749 for (Scope.Entry e1 = t1.tsym.members().elems;
1750 e1 != null;
1751 e1 = e1.sibling) {
1752 Symbol s1 = e1.sym;
1753 if (s1.kind != MTH ||
1754 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1755 !s1.isInheritedIn(site.tsym, types) ||
1756 ((MethodSymbol)s1).implementation(site.tsym,
1757 types,
1758 true) != s1)
1759 continue;
1760 Type st1 = types.memberType(t1, s1);
1761 int s1ArgsLength = st1.getParameterTypes().length();
1762 if (st1 == s1.type) continue;
1764 for (Type t2 = sup;
1765 t2.hasTag(CLASS);
1766 t2 = types.supertype(t2)) {
1767 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1768 e2.scope != null;
1769 e2 = e2.next()) {
1770 Symbol s2 = e2.sym;
1771 if (s2 == s1 ||
1772 s2.kind != MTH ||
1773 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1774 s2.type.getParameterTypes().length() != s1ArgsLength ||
1775 !s2.isInheritedIn(site.tsym, types) ||
1776 ((MethodSymbol)s2).implementation(site.tsym,
1777 types,
1778 true) != s2)
1779 continue;
1780 Type st2 = types.memberType(t2, s2);
1781 if (types.overrideEquivalent(st1, st2))
1782 log.error(pos, "concrete.inheritance.conflict",
1783 s1, t1, s2, t2, sup);
1784 }
1785 }
1786 }
1787 }
1788 }
1790 /** Check that classes (or interfaces) do not each define an abstract
1791 * method with same name and arguments but incompatible return types.
1792 * @param pos Position to be used for error reporting.
1793 * @param t1 The first argument type.
1794 * @param t2 The second argument type.
1795 */
1796 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1797 Type t1,
1798 Type t2) {
1799 return checkCompatibleAbstracts(pos, t1, t2,
1800 types.makeCompoundType(t1, t2));
1801 }
1803 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1804 Type t1,
1805 Type t2,
1806 Type site) {
1807 return firstIncompatibility(pos, t1, t2, site) == null;
1808 }
1810 /** Return the first method which is defined with same args
1811 * but different return types in two given interfaces, or null if none
1812 * exists.
1813 * @param t1 The first type.
1814 * @param t2 The second type.
1815 * @param site The most derived type.
1816 * @returns symbol from t2 that conflicts with one in t1.
1817 */
1818 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1819 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1820 closure(t1, interfaces1);
1821 Map<TypeSymbol,Type> interfaces2;
1822 if (t1 == t2)
1823 interfaces2 = interfaces1;
1824 else
1825 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1827 for (Type t3 : interfaces1.values()) {
1828 for (Type t4 : interfaces2.values()) {
1829 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1830 if (s != null) return s;
1831 }
1832 }
1833 return null;
1834 }
1836 /** Compute all the supertypes of t, indexed by type symbol. */
1837 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1838 if (!t.hasTag(CLASS)) return;
1839 if (typeMap.put(t.tsym, t) == null) {
1840 closure(types.supertype(t), typeMap);
1841 for (Type i : types.interfaces(t))
1842 closure(i, typeMap);
1843 }
1844 }
1846 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1847 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1848 if (!t.hasTag(CLASS)) return;
1849 if (typesSkip.get(t.tsym) != null) return;
1850 if (typeMap.put(t.tsym, t) == null) {
1851 closure(types.supertype(t), typesSkip, typeMap);
1852 for (Type i : types.interfaces(t))
1853 closure(i, typesSkip, typeMap);
1854 }
1855 }
1857 /** Return the first method in t2 that conflicts with a method from t1. */
1858 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1859 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1860 Symbol s1 = e1.sym;
1861 Type st1 = null;
1862 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1863 (s1.flags() & SYNTHETIC) != 0) continue;
1864 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1865 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1866 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1867 Symbol s2 = e2.sym;
1868 if (s1 == s2) continue;
1869 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1870 (s2.flags() & SYNTHETIC) != 0) continue;
1871 if (st1 == null) st1 = types.memberType(t1, s1);
1872 Type st2 = types.memberType(t2, s2);
1873 if (types.overrideEquivalent(st1, st2)) {
1874 List<Type> tvars1 = st1.getTypeArguments();
1875 List<Type> tvars2 = st2.getTypeArguments();
1876 Type rt1 = st1.getReturnType();
1877 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1878 boolean compat =
1879 types.isSameType(rt1, rt2) ||
1880 !rt1.isPrimitiveOrVoid() &&
1881 !rt2.isPrimitiveOrVoid() &&
1882 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1883 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1884 checkCommonOverriderIn(s1,s2,site);
1885 if (!compat) {
1886 log.error(pos, "types.incompatible.diff.ret",
1887 t1, t2, s2.name +
1888 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1889 return s2;
1890 }
1891 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1892 !checkCommonOverriderIn(s1, s2, site)) {
1893 log.error(pos,
1894 "name.clash.same.erasure.no.override",
1895 s1, s1.location(),
1896 s2, s2.location());
1897 return s2;
1898 }
1899 }
1900 }
1901 return null;
1902 }
1903 //WHERE
1904 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1905 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1906 Type st1 = types.memberType(site, s1);
1907 Type st2 = types.memberType(site, s2);
1908 closure(site, supertypes);
1909 for (Type t : supertypes.values()) {
1910 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1911 Symbol s3 = e.sym;
1912 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1913 Type st3 = types.memberType(site,s3);
1914 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1915 if (s3.owner == site.tsym) {
1916 return true;
1917 }
1918 List<Type> tvars1 = st1.getTypeArguments();
1919 List<Type> tvars2 = st2.getTypeArguments();
1920 List<Type> tvars3 = st3.getTypeArguments();
1921 Type rt1 = st1.getReturnType();
1922 Type rt2 = st2.getReturnType();
1923 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1924 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1925 boolean compat =
1926 !rt13.isPrimitiveOrVoid() &&
1927 !rt23.isPrimitiveOrVoid() &&
1928 (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
1929 types.covariantReturnType(rt23, rt2, types.noWarnings));
1930 if (compat)
1931 return true;
1932 }
1933 }
1934 }
1935 return false;
1936 }
1938 /** Check that a given method conforms with any method it overrides.
1939 * @param tree The tree from which positions are extracted
1940 * for errors.
1941 * @param m The overriding method.
1942 */
1943 void checkOverride(JCTree tree, MethodSymbol m) {
1944 ClassSymbol origin = (ClassSymbol)m.owner;
1945 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1946 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1947 log.error(tree.pos(), "enum.no.finalize");
1948 return;
1949 }
1950 for (Type t = origin.type; t.hasTag(CLASS);
1951 t = types.supertype(t)) {
1952 if (t != origin.type) {
1953 checkOverride(tree, t, origin, m);
1954 }
1955 for (Type t2 : types.interfaces(t)) {
1956 checkOverride(tree, t2, origin, m);
1957 }
1958 }
1959 }
1961 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1962 TypeSymbol c = site.tsym;
1963 Scope.Entry e = c.members().lookup(m.name);
1964 while (e.scope != null) {
1965 if (m.overrides(e.sym, origin, types, false)) {
1966 if ((e.sym.flags() & ABSTRACT) == 0) {
1967 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1968 }
1969 }
1970 e = e.next();
1971 }
1972 }
1974 private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
1975 public boolean accepts(Symbol s) {
1976 return MethodSymbol.implementation_filter.accepts(s) &&
1977 (s.flags() & BAD_OVERRIDE) == 0;
1979 }
1980 };
1982 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
1983 ClassSymbol someClass) {
1984 /* At present, annotations cannot possibly have a method that is override
1985 * equivalent with Object.equals(Object) but in any case the condition is
1986 * fine for completeness.
1987 */
1988 if (someClass == (ClassSymbol)syms.objectType.tsym ||
1989 someClass.isInterface() || someClass.isEnum() ||
1990 (someClass.flags() & ANNOTATION) != 0 ||
1991 (someClass.flags() & ABSTRACT) != 0) return;
1992 //anonymous inner classes implementing interfaces need especial treatment
1993 if (someClass.isAnonymous()) {
1994 List<Type> interfaces = types.interfaces(someClass.type);
1995 if (interfaces != null && !interfaces.isEmpty() &&
1996 interfaces.head.tsym == syms.comparatorType.tsym) return;
1997 }
1998 checkClassOverrideEqualsAndHash(pos, someClass);
1999 }
2001 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2002 ClassSymbol someClass) {
2003 if (lint.isEnabled(LintCategory.OVERRIDES)) {
2004 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2005 .tsym.members().lookup(names.equals).sym;
2006 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2007 .tsym.members().lookup(names.hashCode).sym;
2008 boolean overridesEquals = types.implementation(equalsAtObject,
2009 someClass, false, equalsHasCodeFilter).owner == someClass;
2010 boolean overridesHashCode = types.implementation(hashCodeAtObject,
2011 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2013 if (overridesEquals && !overridesHashCode) {
2014 log.warning(LintCategory.OVERRIDES, pos,
2015 "override.equals.but.not.hashcode", someClass);
2016 }
2017 }
2018 }
2020 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2021 ClashFilter cf = new ClashFilter(origin.type);
2022 return (cf.accepts(s1) &&
2023 cf.accepts(s2) &&
2024 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2025 }
2028 /** Check that all abstract members of given class have definitions.
2029 * @param pos Position to be used for error reporting.
2030 * @param c The class.
2031 */
2032 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2033 try {
2034 MethodSymbol undef = firstUndef(c, c);
2035 if (undef != null) {
2036 if ((c.flags() & ENUM) != 0 &&
2037 types.supertype(c.type).tsym == syms.enumSym &&
2038 (c.flags() & FINAL) == 0) {
2039 // add the ABSTRACT flag to an enum
2040 c.flags_field |= ABSTRACT;
2041 } else {
2042 MethodSymbol undef1 =
2043 new MethodSymbol(undef.flags(), undef.name,
2044 types.memberType(c.type, undef), undef.owner);
2045 log.error(pos, "does.not.override.abstract",
2046 c, undef1, undef1.location());
2047 }
2048 }
2049 } catch (CompletionFailure ex) {
2050 completionError(pos, ex);
2051 }
2052 }
2053 //where
2054 /** Return first abstract member of class `c' that is not defined
2055 * in `impl', null if there is none.
2056 */
2057 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
2058 MethodSymbol undef = null;
2059 // Do not bother to search in classes that are not abstract,
2060 // since they cannot have abstract members.
2061 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2062 Scope s = c.members();
2063 for (Scope.Entry e = s.elems;
2064 undef == null && e != null;
2065 e = e.sibling) {
2066 if (e.sym.kind == MTH &&
2067 (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
2068 MethodSymbol absmeth = (MethodSymbol)e.sym;
2069 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
2070 if (implmeth == null || implmeth == absmeth) {
2071 //look for default implementations
2072 if (allowDefaultMethods) {
2073 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
2074 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
2075 implmeth = prov;
2076 }
2077 }
2078 }
2079 if (implmeth == null || implmeth == absmeth) {
2080 undef = absmeth;
2081 }
2082 }
2083 }
2084 if (undef == null) {
2085 Type st = types.supertype(c.type);
2086 if (st.hasTag(CLASS))
2087 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2088 }
2089 for (List<Type> l = types.interfaces(c.type);
2090 undef == null && l.nonEmpty();
2091 l = l.tail) {
2092 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2093 }
2094 }
2095 return undef;
2096 }
2098 void checkNonCyclicDecl(JCClassDecl tree) {
2099 CycleChecker cc = new CycleChecker();
2100 cc.scan(tree);
2101 if (!cc.errorFound && !cc.partialCheck) {
2102 tree.sym.flags_field |= ACYCLIC;
2103 }
2104 }
2106 class CycleChecker extends TreeScanner {
2108 List<Symbol> seenClasses = List.nil();
2109 boolean errorFound = false;
2110 boolean partialCheck = false;
2112 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2113 if (sym != null && sym.kind == TYP) {
2114 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2115 if (classEnv != null) {
2116 DiagnosticSource prevSource = log.currentSource();
2117 try {
2118 log.useSource(classEnv.toplevel.sourcefile);
2119 scan(classEnv.tree);
2120 }
2121 finally {
2122 log.useSource(prevSource.getFile());
2123 }
2124 } else if (sym.kind == TYP) {
2125 checkClass(pos, sym, List.<JCTree>nil());
2126 }
2127 } else {
2128 //not completed yet
2129 partialCheck = true;
2130 }
2131 }
2133 @Override
2134 public void visitSelect(JCFieldAccess tree) {
2135 super.visitSelect(tree);
2136 checkSymbol(tree.pos(), tree.sym);
2137 }
2139 @Override
2140 public void visitIdent(JCIdent tree) {
2141 checkSymbol(tree.pos(), tree.sym);
2142 }
2144 @Override
2145 public void visitTypeApply(JCTypeApply tree) {
2146 scan(tree.clazz);
2147 }
2149 @Override
2150 public void visitTypeArray(JCArrayTypeTree tree) {
2151 scan(tree.elemtype);
2152 }
2154 @Override
2155 public void visitClassDef(JCClassDecl tree) {
2156 List<JCTree> supertypes = List.nil();
2157 if (tree.getExtendsClause() != null) {
2158 supertypes = supertypes.prepend(tree.getExtendsClause());
2159 }
2160 if (tree.getImplementsClause() != null) {
2161 for (JCTree intf : tree.getImplementsClause()) {
2162 supertypes = supertypes.prepend(intf);
2163 }
2164 }
2165 checkClass(tree.pos(), tree.sym, supertypes);
2166 }
2168 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2169 if ((c.flags_field & ACYCLIC) != 0)
2170 return;
2171 if (seenClasses.contains(c)) {
2172 errorFound = true;
2173 noteCyclic(pos, (ClassSymbol)c);
2174 } else if (!c.type.isErroneous()) {
2175 try {
2176 seenClasses = seenClasses.prepend(c);
2177 if (c.type.hasTag(CLASS)) {
2178 if (supertypes.nonEmpty()) {
2179 scan(supertypes);
2180 }
2181 else {
2182 ClassType ct = (ClassType)c.type;
2183 if (ct.supertype_field == null ||
2184 ct.interfaces_field == null) {
2185 //not completed yet
2186 partialCheck = true;
2187 return;
2188 }
2189 checkSymbol(pos, ct.supertype_field.tsym);
2190 for (Type intf : ct.interfaces_field) {
2191 checkSymbol(pos, intf.tsym);
2192 }
2193 }
2194 if (c.owner.kind == TYP) {
2195 checkSymbol(pos, c.owner);
2196 }
2197 }
2198 } finally {
2199 seenClasses = seenClasses.tail;
2200 }
2201 }
2202 }
2203 }
2205 /** Check for cyclic references. Issue an error if the
2206 * symbol of the type referred to has a LOCKED flag set.
2207 *
2208 * @param pos Position to be used for error reporting.
2209 * @param t The type referred to.
2210 */
2211 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2212 checkNonCyclicInternal(pos, t);
2213 }
2216 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2217 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2218 }
2220 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2221 final TypeVar tv;
2222 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2223 return;
2224 if (seen.contains(t)) {
2225 tv = (TypeVar)t;
2226 tv.bound = types.createErrorType(t);
2227 log.error(pos, "cyclic.inheritance", t);
2228 } else if (t.hasTag(TYPEVAR)) {
2229 tv = (TypeVar)t;
2230 seen = seen.prepend(tv);
2231 for (Type b : types.getBounds(tv))
2232 checkNonCyclic1(pos, b, seen);
2233 }
2234 }
2236 /** Check for cyclic references. Issue an error if the
2237 * symbol of the type referred to has a LOCKED flag set.
2238 *
2239 * @param pos Position to be used for error reporting.
2240 * @param t The type referred to.
2241 * @returns True if the check completed on all attributed classes
2242 */
2243 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2244 boolean complete = true; // was the check complete?
2245 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2246 Symbol c = t.tsym;
2247 if ((c.flags_field & ACYCLIC) != 0) return true;
2249 if ((c.flags_field & LOCKED) != 0) {
2250 noteCyclic(pos, (ClassSymbol)c);
2251 } else if (!c.type.isErroneous()) {
2252 try {
2253 c.flags_field |= LOCKED;
2254 if (c.type.hasTag(CLASS)) {
2255 ClassType clazz = (ClassType)c.type;
2256 if (clazz.interfaces_field != null)
2257 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2258 complete &= checkNonCyclicInternal(pos, l.head);
2259 if (clazz.supertype_field != null) {
2260 Type st = clazz.supertype_field;
2261 if (st != null && st.hasTag(CLASS))
2262 complete &= checkNonCyclicInternal(pos, st);
2263 }
2264 if (c.owner.kind == TYP)
2265 complete &= checkNonCyclicInternal(pos, c.owner.type);
2266 }
2267 } finally {
2268 c.flags_field &= ~LOCKED;
2269 }
2270 }
2271 if (complete)
2272 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2273 if (complete) c.flags_field |= ACYCLIC;
2274 return complete;
2275 }
2277 /** Note that we found an inheritance cycle. */
2278 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2279 log.error(pos, "cyclic.inheritance", c);
2280 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2281 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2282 Type st = types.supertype(c.type);
2283 if (st.hasTag(CLASS))
2284 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2285 c.type = types.createErrorType(c, c.type);
2286 c.flags_field |= ACYCLIC;
2287 }
2289 /**
2290 * Check that functional interface methods would make sense when seen
2291 * from the perspective of the implementing class
2292 */
2293 void checkFunctionalInterface(JCTree tree, Type funcInterface) {
2294 ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
2295 ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
2296 c.interfaces_field = List.of(types.removeWildcards(funcInterface));
2297 c.supertype_field = syms.objectType;
2298 c.tsym = csym;
2299 csym.members_field = new Scope(csym);
2300 Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
2301 Type descType = types.findDescriptorType(funcInterface);
2302 csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
2303 csym.completer = null;
2304 checkImplementations(tree, csym, csym);
2305 }
2307 /** Check that all methods which implement some
2308 * method conform to the method they implement.
2309 * @param tree The class definition whose members are checked.
2310 */
2311 void checkImplementations(JCClassDecl tree) {
2312 checkImplementations(tree, tree.sym, tree.sym);
2313 }
2314 //where
2315 /** Check that all methods which implement some
2316 * method in `ic' conform to the method they implement.
2317 */
2318 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2319 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2320 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2321 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2322 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2323 if (e.sym.kind == MTH &&
2324 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2325 MethodSymbol absmeth = (MethodSymbol)e.sym;
2326 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2327 if (implmeth != null && implmeth != absmeth &&
2328 (implmeth.owner.flags() & INTERFACE) ==
2329 (origin.flags() & INTERFACE)) {
2330 // don't check if implmeth is in a class, yet
2331 // origin is an interface. This case arises only
2332 // if implmeth is declared in Object. The reason is
2333 // that interfaces really don't inherit from
2334 // Object it's just that the compiler represents
2335 // things that way.
2336 checkOverride(tree, implmeth, absmeth, origin);
2337 }
2338 }
2339 }
2340 }
2341 }
2342 }
2344 /** Check that all abstract methods implemented by a class are
2345 * mutually compatible.
2346 * @param pos Position to be used for error reporting.
2347 * @param c The class whose interfaces are checked.
2348 */
2349 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2350 List<Type> supertypes = types.interfaces(c);
2351 Type supertype = types.supertype(c);
2352 if (supertype.hasTag(CLASS) &&
2353 (supertype.tsym.flags() & ABSTRACT) != 0)
2354 supertypes = supertypes.prepend(supertype);
2355 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2356 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2357 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2358 return;
2359 for (List<Type> m = supertypes; m != l; m = m.tail)
2360 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2361 return;
2362 }
2363 checkCompatibleConcretes(pos, c);
2364 }
2366 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2367 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2368 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2369 // VM allows methods and variables with differing types
2370 if (sym.kind == e.sym.kind &&
2371 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2372 sym != e.sym &&
2373 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2374 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2375 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2376 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2377 return;
2378 }
2379 }
2380 }
2381 }
2383 /** Check that all non-override equivalent methods accessible from 'site'
2384 * are mutually compatible (JLS 8.4.8/9.4.1).
2385 *
2386 * @param pos Position to be used for error reporting.
2387 * @param site The class whose methods are checked.
2388 * @param sym The method symbol to be checked.
2389 */
2390 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2391 ClashFilter cf = new ClashFilter(site);
2392 //for each method m1 that is overridden (directly or indirectly)
2393 //by method 'sym' in 'site'...
2394 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2395 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2396 //...check each method m2 that is a member of 'site'
2397 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2398 if (m2 == m1) continue;
2399 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2400 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2401 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2402 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2403 sym.flags_field |= CLASH;
2404 String key = m1 == sym ?
2405 "name.clash.same.erasure.no.override" :
2406 "name.clash.same.erasure.no.override.1";
2407 log.error(pos,
2408 key,
2409 sym, sym.location(),
2410 m2, m2.location(),
2411 m1, m1.location());
2412 return;
2413 }
2414 }
2415 }
2416 }
2420 /** Check that all static methods accessible from 'site' are
2421 * mutually compatible (JLS 8.4.8).
2422 *
2423 * @param pos Position to be used for error reporting.
2424 * @param site The class whose methods are checked.
2425 * @param sym The method symbol to be checked.
2426 */
2427 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2428 ClashFilter cf = new ClashFilter(site);
2429 //for each method m1 that is a member of 'site'...
2430 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2431 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2432 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2433 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
2434 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2435 log.error(pos,
2436 "name.clash.same.erasure.no.hide",
2437 sym, sym.location(),
2438 s, s.location());
2439 return;
2440 }
2441 }
2442 }
2444 //where
2445 private class ClashFilter implements Filter<Symbol> {
2447 Type site;
2449 ClashFilter(Type site) {
2450 this.site = site;
2451 }
2453 boolean shouldSkip(Symbol s) {
2454 return (s.flags() & CLASH) != 0 &&
2455 s.owner == site.tsym;
2456 }
2458 public boolean accepts(Symbol s) {
2459 return s.kind == MTH &&
2460 (s.flags() & SYNTHETIC) == 0 &&
2461 !shouldSkip(s) &&
2462 s.isInheritedIn(site.tsym, types) &&
2463 !s.isConstructor();
2464 }
2465 }
2467 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2468 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2469 for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
2470 Assert.check(m.kind == MTH);
2471 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2472 if (prov.size() > 1) {
2473 ListBuffer<Symbol> abstracts = ListBuffer.lb();
2474 ListBuffer<Symbol> defaults = ListBuffer.lb();
2475 for (MethodSymbol provSym : prov) {
2476 if ((provSym.flags() & DEFAULT) != 0) {
2477 defaults = defaults.append(provSym);
2478 } else if ((provSym.flags() & ABSTRACT) != 0) {
2479 abstracts = abstracts.append(provSym);
2480 }
2481 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2482 //strong semantics - issue an error if two sibling interfaces
2483 //have two override-equivalent defaults - or if one is abstract
2484 //and the other is default
2485 String errKey;
2486 Symbol s1 = defaults.first();
2487 Symbol s2;
2488 if (defaults.size() > 1) {
2489 errKey = "types.incompatible.unrelated.defaults";
2490 s2 = defaults.toList().tail.head;
2491 } else {
2492 errKey = "types.incompatible.abstract.default";
2493 s2 = abstracts.first();
2494 }
2495 log.error(pos, errKey,
2496 Kinds.kindName(site.tsym), site,
2497 m.name, types.memberType(site, m).getParameterTypes(),
2498 s1.location(), s2.location());
2499 break;
2500 }
2501 }
2502 }
2503 }
2504 }
2506 //where
2507 private class DefaultMethodClashFilter implements Filter<Symbol> {
2509 Type site;
2511 DefaultMethodClashFilter(Type site) {
2512 this.site = site;
2513 }
2515 public boolean accepts(Symbol s) {
2516 return s.kind == MTH &&
2517 (s.flags() & DEFAULT) != 0 &&
2518 s.isInheritedIn(site.tsym, types) &&
2519 !s.isConstructor();
2520 }
2521 }
2523 /** Report a conflict between a user symbol and a synthetic symbol.
2524 */
2525 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2526 if (!sym.type.isErroneous()) {
2527 if (warnOnSyntheticConflicts) {
2528 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2529 }
2530 else {
2531 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2532 }
2533 }
2534 }
2536 /** Check that class c does not implement directly or indirectly
2537 * the same parameterized interface with two different argument lists.
2538 * @param pos Position to be used for error reporting.
2539 * @param type The type whose interfaces are checked.
2540 */
2541 void checkClassBounds(DiagnosticPosition pos, Type type) {
2542 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2543 }
2544 //where
2545 /** Enter all interfaces of type `type' into the hash table `seensofar'
2546 * with their class symbol as key and their type as value. Make
2547 * sure no class is entered with two different types.
2548 */
2549 void checkClassBounds(DiagnosticPosition pos,
2550 Map<TypeSymbol,Type> seensofar,
2551 Type type) {
2552 if (type.isErroneous()) return;
2553 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2554 Type it = l.head;
2555 Type oldit = seensofar.put(it.tsym, it);
2556 if (oldit != null) {
2557 List<Type> oldparams = oldit.allparams();
2558 List<Type> newparams = it.allparams();
2559 if (!types.containsTypeEquivalent(oldparams, newparams))
2560 log.error(pos, "cant.inherit.diff.arg",
2561 it.tsym, Type.toString(oldparams),
2562 Type.toString(newparams));
2563 }
2564 checkClassBounds(pos, seensofar, it);
2565 }
2566 Type st = types.supertype(type);
2567 if (st != null) checkClassBounds(pos, seensofar, st);
2568 }
2570 /** Enter interface into into set.
2571 * If it existed already, issue a "repeated interface" error.
2572 */
2573 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2574 if (its.contains(it))
2575 log.error(pos, "repeated.interface");
2576 else {
2577 its.add(it);
2578 }
2579 }
2581 /* *************************************************************************
2582 * Check annotations
2583 **************************************************************************/
2585 /**
2586 * Recursively validate annotations values
2587 */
2588 void validateAnnotationTree(JCTree tree) {
2589 class AnnotationValidator extends TreeScanner {
2590 @Override
2591 public void visitAnnotation(JCAnnotation tree) {
2592 if (!tree.type.isErroneous()) {
2593 super.visitAnnotation(tree);
2594 validateAnnotation(tree);
2595 }
2596 }
2597 }
2598 tree.accept(new AnnotationValidator());
2599 }
2601 /**
2602 * {@literal
2603 * Annotation types are restricted to primitives, String, an
2604 * enum, an annotation, Class, Class<?>, Class<? extends
2605 * Anything>, arrays of the preceding.
2606 * }
2607 */
2608 void validateAnnotationType(JCTree restype) {
2609 // restype may be null if an error occurred, so don't bother validating it
2610 if (restype != null) {
2611 validateAnnotationType(restype.pos(), restype.type);
2612 }
2613 }
2615 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2616 if (type.isPrimitive()) return;
2617 if (types.isSameType(type, syms.stringType)) return;
2618 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2619 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2620 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2621 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2622 validateAnnotationType(pos, types.elemtype(type));
2623 return;
2624 }
2625 log.error(pos, "invalid.annotation.member.type");
2626 }
2628 /**
2629 * "It is also a compile-time error if any method declared in an
2630 * annotation type has a signature that is override-equivalent to
2631 * that of any public or protected method declared in class Object
2632 * or in the interface annotation.Annotation."
2633 *
2634 * @jls 9.6 Annotation Types
2635 */
2636 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2637 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2638 Scope s = sup.tsym.members();
2639 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2640 if (e.sym.kind == MTH &&
2641 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2642 types.overrideEquivalent(m.type, e.sym.type))
2643 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2644 }
2645 }
2646 }
2648 /** Check the annotations of a symbol.
2649 */
2650 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2651 for (JCAnnotation a : annotations)
2652 validateAnnotation(a, s);
2653 }
2655 /** Check the type annotations.
2656 */
2657 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2658 for (JCAnnotation a : annotations)
2659 validateTypeAnnotation(a, isTypeParameter);
2660 }
2662 /** Check an annotation of a symbol.
2663 */
2664 private void validateAnnotation(JCAnnotation a, Symbol s) {
2665 validateAnnotationTree(a);
2667 if (!annotationApplicable(a, s))
2668 log.error(a.pos(), "annotation.type.not.applicable");
2670 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2671 if (!isOverrider(s))
2672 log.error(a.pos(), "method.does.not.override.superclass");
2673 }
2675 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2676 if (s.kind != TYP) {
2677 log.error(a.pos(), "bad.functional.intf.anno");
2678 } else {
2679 try {
2680 types.findDescriptorSymbol((TypeSymbol)s);
2681 } catch (Types.FunctionDescriptorLookupError ex) {
2682 log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
2683 }
2684 }
2685 }
2686 }
2688 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2689 Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
2690 validateAnnotationTree(a);
2692 if (!isTypeAnnotation(a, isTypeParameter))
2693 log.error(a.pos(), "annotation.type.not.applicable");
2694 }
2696 /**
2697 * Validate the proposed container 'repeatable' on the
2698 * annotation type symbol 's'. Report errors at position
2699 * 'pos'.
2700 *
2701 * @param s The (annotation)type declaration annotated with a @Repeatable
2702 * @param repeatable the @Repeatable on 's'
2703 * @param pos where to report errors
2704 */
2705 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2706 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2708 Type t = null;
2709 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2710 if (!l.isEmpty()) {
2711 Assert.check(l.head.fst.name == names.value);
2712 t = ((Attribute.Class)l.head.snd).getValue();
2713 }
2715 if (t == null) {
2716 // errors should already have been reported during Annotate
2717 return;
2718 }
2720 validateValue(t.tsym, s, pos);
2721 validateRetention(t.tsym, s, pos);
2722 validateDocumented(t.tsym, s, pos);
2723 validateInherited(t.tsym, s, pos);
2724 validateTarget(t.tsym, s, pos);
2725 validateDefault(t.tsym, s, pos);
2726 }
2728 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2729 Scope.Entry e = container.members().lookup(names.value);
2730 if (e.scope != null && e.sym.kind == MTH) {
2731 MethodSymbol m = (MethodSymbol) e.sym;
2732 Type ret = m.getReturnType();
2733 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2734 log.error(pos, "invalid.repeatable.annotation.value.return",
2735 container, ret, types.makeArrayType(contained.type));
2736 }
2737 } else {
2738 log.error(pos, "invalid.repeatable.annotation.no.value", container);
2739 }
2740 }
2742 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2743 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2744 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2746 boolean error = false;
2747 switch (containedRetention) {
2748 case RUNTIME:
2749 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2750 error = true;
2751 }
2752 break;
2753 case CLASS:
2754 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2755 error = true;
2756 }
2757 }
2758 if (error ) {
2759 log.error(pos, "invalid.repeatable.annotation.retention",
2760 container, containerRetention,
2761 contained, containedRetention);
2762 }
2763 }
2765 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2766 if (contained.attribute(syms.documentedType.tsym) != null) {
2767 if (container.attribute(syms.documentedType.tsym) == null) {
2768 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2769 }
2770 }
2771 }
2773 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2774 if (contained.attribute(syms.inheritedType.tsym) != null) {
2775 if (container.attribute(syms.inheritedType.tsym) == null) {
2776 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2777 }
2778 }
2779 }
2781 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2782 // The set of targets the container is applicable to must be a subset
2783 // (with respect to annotation target semantics) of the set of targets
2784 // the contained is applicable to. The target sets may be implicit or
2785 // explicit.
2787 Set<Name> containerTargets;
2788 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2789 if (containerTarget == null) {
2790 containerTargets = getDefaultTargetSet();
2791 } else {
2792 containerTargets = new HashSet<Name>();
2793 for (Attribute app : containerTarget.values) {
2794 if (!(app instanceof Attribute.Enum)) {
2795 continue; // recovery
2796 }
2797 Attribute.Enum e = (Attribute.Enum)app;
2798 containerTargets.add(e.value.name);
2799 }
2800 }
2802 Set<Name> containedTargets;
2803 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2804 if (containedTarget == null) {
2805 containedTargets = getDefaultTargetSet();
2806 } else {
2807 containedTargets = new HashSet<Name>();
2808 for (Attribute app : containedTarget.values) {
2809 if (!(app instanceof Attribute.Enum)) {
2810 continue; // recovery
2811 }
2812 Attribute.Enum e = (Attribute.Enum)app;
2813 containedTargets.add(e.value.name);
2814 }
2815 }
2817 if (!isTargetSubsetOf(containerTargets, containedTargets)) {
2818 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2819 }
2820 }
2822 /* get a set of names for the default target */
2823 private Set<Name> getDefaultTargetSet() {
2824 if (defaultTargets == null) {
2825 Set<Name> targets = new HashSet<Name>();
2826 targets.add(names.ANNOTATION_TYPE);
2827 targets.add(names.CONSTRUCTOR);
2828 targets.add(names.FIELD);
2829 targets.add(names.LOCAL_VARIABLE);
2830 targets.add(names.METHOD);
2831 targets.add(names.PACKAGE);
2832 targets.add(names.PARAMETER);
2833 targets.add(names.TYPE);
2835 defaultTargets = java.util.Collections.unmodifiableSet(targets);
2836 }
2838 return defaultTargets;
2839 }
2840 private Set<Name> defaultTargets;
2843 /** Checks that s is a subset of t, with respect to ElementType
2844 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2845 */
2846 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
2847 // Check that all elements in s are present in t
2848 for (Name n2 : s) {
2849 boolean currentElementOk = false;
2850 for (Name n1 : t) {
2851 if (n1 == n2) {
2852 currentElementOk = true;
2853 break;
2854 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2855 currentElementOk = true;
2856 break;
2857 }
2858 }
2859 if (!currentElementOk)
2860 return false;
2861 }
2862 return true;
2863 }
2865 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2866 // validate that all other elements of containing type has defaults
2867 Scope scope = container.members();
2868 for(Symbol elm : scope.getElements()) {
2869 if (elm.name != names.value &&
2870 elm.kind == Kinds.MTH &&
2871 ((MethodSymbol)elm).defaultValue == null) {
2872 log.error(pos,
2873 "invalid.repeatable.annotation.elem.nondefault",
2874 container,
2875 elm);
2876 }
2877 }
2878 }
2880 /** Is s a method symbol that overrides a method in a superclass? */
2881 boolean isOverrider(Symbol s) {
2882 if (s.kind != MTH || s.isStatic())
2883 return false;
2884 MethodSymbol m = (MethodSymbol)s;
2885 TypeSymbol owner = (TypeSymbol)m.owner;
2886 for (Type sup : types.closure(owner.type)) {
2887 if (sup == owner.type)
2888 continue; // skip "this"
2889 Scope scope = sup.tsym.members();
2890 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2891 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2892 return true;
2893 }
2894 }
2895 return false;
2896 }
2898 /** Is the annotation applicable to type annotations? */
2899 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2900 Attribute.Compound atTarget =
2901 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2902 if (atTarget == null) {
2903 // An annotation without @Target is not a type annotation.
2904 return false;
2905 }
2907 Attribute atValue = atTarget.member(names.value);
2908 if (!(atValue instanceof Attribute.Array)) {
2909 return false; // error recovery
2910 }
2912 Attribute.Array arr = (Attribute.Array) atValue;
2913 for (Attribute app : arr.values) {
2914 if (!(app instanceof Attribute.Enum)) {
2915 return false; // recovery
2916 }
2917 Attribute.Enum e = (Attribute.Enum) app;
2919 if (e.value.name == names.TYPE_USE)
2920 return true;
2921 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2922 return true;
2923 }
2924 return false;
2925 }
2927 /** Is the annotation applicable to the symbol? */
2928 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2929 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2930 Name[] targets;
2932 if (arr == null) {
2933 targets = defaultTargetMetaInfo(a, s);
2934 } else {
2935 // TODO: can we optimize this?
2936 targets = new Name[arr.values.length];
2937 for (int i=0; i<arr.values.length; ++i) {
2938 Attribute app = arr.values[i];
2939 if (!(app instanceof Attribute.Enum)) {
2940 return true; // recovery
2941 }
2942 Attribute.Enum e = (Attribute.Enum) app;
2943 targets[i] = e.value.name;
2944 }
2945 }
2946 for (Name target : targets) {
2947 if (target == names.TYPE)
2948 { if (s.kind == TYP) return true; }
2949 else if (target == names.FIELD)
2950 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2951 else if (target == names.METHOD)
2952 { if (s.kind == MTH && !s.isConstructor()) return true; }
2953 else if (target == names.PARAMETER)
2954 { if (s.kind == VAR &&
2955 s.owner.kind == MTH &&
2956 (s.flags() & PARAMETER) != 0)
2957 return true;
2958 }
2959 else if (target == names.CONSTRUCTOR)
2960 { if (s.kind == MTH && s.isConstructor()) return true; }
2961 else if (target == names.LOCAL_VARIABLE)
2962 { if (s.kind == VAR && s.owner.kind == MTH &&
2963 (s.flags() & PARAMETER) == 0)
2964 return true;
2965 }
2966 else if (target == names.ANNOTATION_TYPE)
2967 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2968 return true;
2969 }
2970 else if (target == names.PACKAGE)
2971 { if (s.kind == PCK) return true; }
2972 else if (target == names.TYPE_USE)
2973 { if (s.kind == TYP ||
2974 s.kind == VAR ||
2975 (s.kind == MTH && !s.isConstructor() &&
2976 !s.type.getReturnType().hasTag(VOID)) ||
2977 (s.kind == MTH && s.isConstructor()))
2978 return true;
2979 }
2980 else if (target == names.TYPE_PARAMETER)
2981 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
2982 return true;
2983 }
2984 else
2985 return true; // recovery
2986 }
2987 return false;
2988 }
2991 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2992 Attribute.Compound atTarget =
2993 s.attribute(syms.annotationTargetType.tsym);
2994 if (atTarget == null) return null; // ok, is applicable
2995 Attribute atValue = atTarget.member(names.value);
2996 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2997 return (Attribute.Array) atValue;
2998 }
3000 private final Name[] dfltTargetMeta;
3001 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
3002 return dfltTargetMeta;
3003 }
3005 /** Check an annotation value.
3006 *
3007 * @param a The annotation tree to check
3008 * @return true if this annotation tree is valid, otherwise false
3009 */
3010 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3011 boolean res = false;
3012 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3013 try {
3014 res = validateAnnotation(a);
3015 } finally {
3016 log.popDiagnosticHandler(diagHandler);
3017 }
3018 return res;
3019 }
3021 private boolean validateAnnotation(JCAnnotation a) {
3022 boolean isValid = true;
3023 // collect an inventory of the annotation elements
3024 Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
3025 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
3026 e != null;
3027 e = e.sibling)
3028 if (e.sym.kind == MTH)
3029 members.add((MethodSymbol) e.sym);
3031 // remove the ones that are assigned values
3032 for (JCTree arg : a.args) {
3033 if (!arg.hasTag(ASSIGN)) continue; // recovery
3034 JCAssign assign = (JCAssign) arg;
3035 Symbol m = TreeInfo.symbol(assign.lhs);
3036 if (m == null || m.type.isErroneous()) continue;
3037 if (!members.remove(m)) {
3038 isValid = false;
3039 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3040 m.name, a.type);
3041 }
3042 }
3044 // all the remaining ones better have default values
3045 List<Name> missingDefaults = List.nil();
3046 for (MethodSymbol m : members) {
3047 if (m.defaultValue == null && !m.type.isErroneous()) {
3048 missingDefaults = missingDefaults.append(m.name);
3049 }
3050 }
3051 missingDefaults = missingDefaults.reverse();
3052 if (missingDefaults.nonEmpty()) {
3053 isValid = false;
3054 String key = (missingDefaults.size() > 1)
3055 ? "annotation.missing.default.value.1"
3056 : "annotation.missing.default.value";
3057 log.error(a.pos(), key, a.type, missingDefaults);
3058 }
3060 // special case: java.lang.annotation.Target must not have
3061 // repeated values in its value member
3062 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3063 a.args.tail == null)
3064 return isValid;
3066 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3067 JCAssign assign = (JCAssign) a.args.head;
3068 Symbol m = TreeInfo.symbol(assign.lhs);
3069 if (m.name != names.value) return false;
3070 JCTree rhs = assign.rhs;
3071 if (!rhs.hasTag(NEWARRAY)) return false;
3072 JCNewArray na = (JCNewArray) rhs;
3073 Set<Symbol> targets = new HashSet<Symbol>();
3074 for (JCTree elem : na.elems) {
3075 if (!targets.add(TreeInfo.symbol(elem))) {
3076 isValid = false;
3077 log.error(elem.pos(), "repeated.annotation.target");
3078 }
3079 }
3080 return isValid;
3081 }
3083 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3084 if (allowAnnotations &&
3085 lint.isEnabled(LintCategory.DEP_ANN) &&
3086 (s.flags() & DEPRECATED) != 0 &&
3087 !syms.deprecatedType.isErroneous() &&
3088 s.attribute(syms.deprecatedType.tsym) == null) {
3089 log.warning(LintCategory.DEP_ANN,
3090 pos, "missing.deprecated.annotation");
3091 }
3092 }
3094 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3095 if ((s.flags() & DEPRECATED) != 0 &&
3096 (other.flags() & DEPRECATED) == 0 &&
3097 s.outermostClass() != other.outermostClass()) {
3098 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3099 @Override
3100 public void report() {
3101 warnDeprecated(pos, s);
3102 }
3103 });
3104 }
3105 }
3107 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3108 if ((s.flags() & PROPRIETARY) != 0) {
3109 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3110 public void report() {
3111 if (enableSunApiLintControl)
3112 warnSunApi(pos, "sun.proprietary", s);
3113 else
3114 log.mandatoryWarning(pos, "sun.proprietary", s);
3115 }
3116 });
3117 }
3118 }
3120 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3121 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3122 log.error(pos, "not.in.profile", s, profile);
3123 }
3124 }
3126 /* *************************************************************************
3127 * Check for recursive annotation elements.
3128 **************************************************************************/
3130 /** Check for cycles in the graph of annotation elements.
3131 */
3132 void checkNonCyclicElements(JCClassDecl tree) {
3133 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3134 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3135 try {
3136 tree.sym.flags_field |= LOCKED;
3137 for (JCTree def : tree.defs) {
3138 if (!def.hasTag(METHODDEF)) continue;
3139 JCMethodDecl meth = (JCMethodDecl)def;
3140 checkAnnotationResType(meth.pos(), meth.restype.type);
3141 }
3142 } finally {
3143 tree.sym.flags_field &= ~LOCKED;
3144 tree.sym.flags_field |= ACYCLIC_ANN;
3145 }
3146 }
3148 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3149 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3150 return;
3151 if ((tsym.flags_field & LOCKED) != 0) {
3152 log.error(pos, "cyclic.annotation.element");
3153 return;
3154 }
3155 try {
3156 tsym.flags_field |= LOCKED;
3157 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3158 Symbol s = e.sym;
3159 if (s.kind != Kinds.MTH)
3160 continue;
3161 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3162 }
3163 } finally {
3164 tsym.flags_field &= ~LOCKED;
3165 tsym.flags_field |= ACYCLIC_ANN;
3166 }
3167 }
3169 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3170 switch (type.getTag()) {
3171 case CLASS:
3172 if ((type.tsym.flags() & ANNOTATION) != 0)
3173 checkNonCyclicElementsInternal(pos, type.tsym);
3174 break;
3175 case ARRAY:
3176 checkAnnotationResType(pos, types.elemtype(type));
3177 break;
3178 default:
3179 break; // int etc
3180 }
3181 }
3183 /* *************************************************************************
3184 * Check for cycles in the constructor call graph.
3185 **************************************************************************/
3187 /** Check for cycles in the graph of constructors calling other
3188 * constructors.
3189 */
3190 void checkCyclicConstructors(JCClassDecl tree) {
3191 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3193 // enter each constructor this-call into the map
3194 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3195 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3196 if (app == null) continue;
3197 JCMethodDecl meth = (JCMethodDecl) l.head;
3198 if (TreeInfo.name(app.meth) == names._this) {
3199 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3200 } else {
3201 meth.sym.flags_field |= ACYCLIC;
3202 }
3203 }
3205 // Check for cycles in the map
3206 Symbol[] ctors = new Symbol[0];
3207 ctors = callMap.keySet().toArray(ctors);
3208 for (Symbol caller : ctors) {
3209 checkCyclicConstructor(tree, caller, callMap);
3210 }
3211 }
3213 /** Look in the map to see if the given constructor is part of a
3214 * call cycle.
3215 */
3216 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3217 Map<Symbol,Symbol> callMap) {
3218 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3219 if ((ctor.flags_field & LOCKED) != 0) {
3220 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3221 "recursive.ctor.invocation");
3222 } else {
3223 ctor.flags_field |= LOCKED;
3224 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3225 ctor.flags_field &= ~LOCKED;
3226 }
3227 ctor.flags_field |= ACYCLIC;
3228 }
3229 }
3231 /* *************************************************************************
3232 * Miscellaneous
3233 **************************************************************************/
3235 /**
3236 * Return the opcode of the operator but emit an error if it is an
3237 * error.
3238 * @param pos position for error reporting.
3239 * @param operator an operator
3240 * @param tag a tree tag
3241 * @param left type of left hand side
3242 * @param right type of right hand side
3243 */
3244 int checkOperator(DiagnosticPosition pos,
3245 OperatorSymbol operator,
3246 JCTree.Tag tag,
3247 Type left,
3248 Type right) {
3249 if (operator.opcode == ByteCodes.error) {
3250 log.error(pos,
3251 "operator.cant.be.applied.1",
3252 treeinfo.operatorName(tag),
3253 left, right);
3254 }
3255 return operator.opcode;
3256 }
3259 /**
3260 * Check for division by integer constant zero
3261 * @param pos Position for error reporting.
3262 * @param operator The operator for the expression
3263 * @param operand The right hand operand for the expression
3264 */
3265 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3266 if (operand.constValue() != null
3267 && lint.isEnabled(LintCategory.DIVZERO)
3268 && (operand.getTag().isSubRangeOf(LONG))
3269 && ((Number) (operand.constValue())).longValue() == 0) {
3270 int opc = ((OperatorSymbol)operator).opcode;
3271 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3272 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3273 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3274 }
3275 }
3276 }
3278 /**
3279 * Check for empty statements after if
3280 */
3281 void checkEmptyIf(JCIf tree) {
3282 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3283 lint.isEnabled(LintCategory.EMPTY))
3284 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3285 }
3287 /** Check that symbol is unique in given scope.
3288 * @param pos Position for error reporting.
3289 * @param sym The symbol.
3290 * @param s The scope.
3291 */
3292 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3293 if (sym.type.isErroneous())
3294 return true;
3295 if (sym.owner.name == names.any) return false;
3296 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3297 if (sym != e.sym &&
3298 (e.sym.flags() & CLASH) == 0 &&
3299 sym.kind == e.sym.kind &&
3300 sym.name != names.error &&
3301 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3302 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3303 varargsDuplicateError(pos, sym, e.sym);
3304 return true;
3305 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3306 duplicateErasureError(pos, sym, e.sym);
3307 sym.flags_field |= CLASH;
3308 return true;
3309 } else {
3310 duplicateError(pos, e.sym);
3311 return false;
3312 }
3313 }
3314 }
3315 return true;
3316 }
3318 /** Report duplicate declaration error.
3319 */
3320 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3321 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3322 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3323 }
3324 }
3326 /** Check that single-type import is not already imported or top-level defined,
3327 * but make an exception for two single-type imports which denote the same type.
3328 * @param pos Position for error reporting.
3329 * @param sym The symbol.
3330 * @param s The scope
3331 */
3332 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3333 return checkUniqueImport(pos, sym, s, false);
3334 }
3336 /** Check that static single-type import is not already imported or top-level defined,
3337 * but make an exception for two single-type imports which denote the same type.
3338 * @param pos Position for error reporting.
3339 * @param sym The symbol.
3340 * @param s The scope
3341 */
3342 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3343 return checkUniqueImport(pos, sym, s, true);
3344 }
3346 /** Check that single-type import is not already imported or top-level defined,
3347 * but make an exception for two single-type imports which denote the same type.
3348 * @param pos Position for error reporting.
3349 * @param sym The symbol.
3350 * @param s The scope.
3351 * @param staticImport Whether or not this was a static import
3352 */
3353 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3354 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3355 // is encountered class entered via a class declaration?
3356 boolean isClassDecl = e.scope == s;
3357 if ((isClassDecl || sym != e.sym) &&
3358 sym.kind == e.sym.kind &&
3359 sym.name != names.error) {
3360 if (!e.sym.type.isErroneous()) {
3361 String what = e.sym.toString();
3362 if (!isClassDecl) {
3363 if (staticImport)
3364 log.error(pos, "already.defined.static.single.import", what);
3365 else
3366 log.error(pos, "already.defined.single.import", what);
3367 }
3368 else if (sym != e.sym)
3369 log.error(pos, "already.defined.this.unit", what);
3370 }
3371 return false;
3372 }
3373 }
3374 return true;
3375 }
3377 /** Check that a qualified name is in canonical form (for import decls).
3378 */
3379 public void checkCanonical(JCTree tree) {
3380 if (!isCanonical(tree))
3381 log.error(tree.pos(), "import.requires.canonical",
3382 TreeInfo.symbol(tree));
3383 }
3384 // where
3385 private boolean isCanonical(JCTree tree) {
3386 while (tree.hasTag(SELECT)) {
3387 JCFieldAccess s = (JCFieldAccess) tree;
3388 if (s.sym.owner != TreeInfo.symbol(s.selected))
3389 return false;
3390 tree = s.selected;
3391 }
3392 return true;
3393 }
3395 /** Check that an auxiliary class is not accessed from any other file than its own.
3396 */
3397 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3398 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3399 (c.flags() & AUXILIARY) != 0 &&
3400 rs.isAccessible(env, c) &&
3401 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3402 {
3403 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3404 c, c.sourcefile);
3405 }
3406 }
3408 private class ConversionWarner extends Warner {
3409 final String uncheckedKey;
3410 final Type found;
3411 final Type expected;
3412 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3413 super(pos);
3414 this.uncheckedKey = uncheckedKey;
3415 this.found = found;
3416 this.expected = expected;
3417 }
3419 @Override
3420 public void warn(LintCategory lint) {
3421 boolean warned = this.warned;
3422 super.warn(lint);
3423 if (warned) return; // suppress redundant diagnostics
3424 switch (lint) {
3425 case UNCHECKED:
3426 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3427 break;
3428 case VARARGS:
3429 if (method != null &&
3430 method.attribute(syms.trustMeType.tsym) != null &&
3431 isTrustMeAllowedOnMethod(method) &&
3432 !types.isReifiable(method.type.getParameterTypes().last())) {
3433 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3434 }
3435 break;
3436 default:
3437 throw new AssertionError("Unexpected lint: " + lint);
3438 }
3439 }
3440 }
3442 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3443 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3444 }
3446 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3447 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3448 }
3449 }