Fri, 31 Aug 2012 10:37:46 +0100
7151010: Add compiler support for repeating annotations
Reviewed-by: jjg, mcimadamore
1 /*
2 * Copyright (c) 1999, 2012, 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.*;
29 import java.util.Set;
31 import com.sun.tools.javac.code.*;
32 import com.sun.tools.javac.jvm.*;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
38 import com.sun.tools.javac.tree.JCTree.*;
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.*;
44 import static com.sun.tools.javac.code.Flags.*;
45 import static com.sun.tools.javac.code.Flags.ANNOTATION;
46 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
47 import static com.sun.tools.javac.code.Kinds.*;
48 import static com.sun.tools.javac.code.TypeTags.*;
49 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
53 /** Type checking helper class for the attribution phase.
54 *
55 * <p><b>This is NOT part of any supported API.
56 * If you write code that depends on this, you do so at your own risk.
57 * This code and its internal interfaces are subject to change or
58 * deletion without notice.</b>
59 */
60 public class Check {
61 protected static final Context.Key<Check> checkKey =
62 new Context.Key<Check>();
64 private final Names names;
65 private final Log log;
66 private final Resolve rs;
67 private final Symtab syms;
68 private final Enter enter;
69 private final Infer infer;
70 private final Types types;
71 private final JCDiagnostic.Factory diags;
72 private boolean warnOnSyntheticConflicts;
73 private boolean suppressAbortOnBadClassFile;
74 private boolean enableSunApiLintControl;
75 private final TreeInfo treeinfo;
77 // The set of lint options currently in effect. It is initialized
78 // from the context, and then is set/reset as needed by Attr as it
79 // visits all the various parts of the trees during attribution.
80 private Lint lint;
82 // The method being analyzed in Attr - it is set/reset as needed by
83 // Attr as it visits new method declarations.
84 private MethodSymbol method;
86 public static Check instance(Context context) {
87 Check instance = context.get(checkKey);
88 if (instance == null)
89 instance = new Check(context);
90 return instance;
91 }
93 protected Check(Context context) {
94 context.put(checkKey, this);
96 names = Names.instance(context);
97 log = Log.instance(context);
98 rs = Resolve.instance(context);
99 syms = Symtab.instance(context);
100 enter = Enter.instance(context);
101 infer = Infer.instance(context);
102 this.types = Types.instance(context);
103 diags = JCDiagnostic.Factory.instance(context);
104 Options options = Options.instance(context);
105 lint = Lint.instance(context);
106 treeinfo = TreeInfo.instance(context);
108 Source source = Source.instance(context);
109 allowGenerics = source.allowGenerics();
110 allowVarargs = source.allowVarargs();
111 allowAnnotations = source.allowAnnotations();
112 allowCovariantReturns = source.allowCovariantReturns();
113 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
114 complexInference = options.isSet("complexinference");
115 warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
116 suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
117 enableSunApiLintControl = options.isSet("enableSunApiLintControl");
119 Target target = Target.instance(context);
120 syntheticNameChar = target.syntheticNameChar();
122 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
123 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
124 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
125 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
127 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
128 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
129 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
130 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
131 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
132 enforceMandatoryWarnings, "sunapi", null);
134 deferredLintHandler = DeferredLintHandler.immediateHandler;
135 }
137 /** Switch: generics enabled?
138 */
139 boolean allowGenerics;
141 /** Switch: varargs enabled?
142 */
143 boolean allowVarargs;
145 /** Switch: annotations enabled?
146 */
147 boolean allowAnnotations;
149 /** Switch: covariant returns enabled?
150 */
151 boolean allowCovariantReturns;
153 /** Switch: simplified varargs enabled?
154 */
155 boolean allowSimplifiedVarargs;
157 /** Switch: -complexinference option set?
158 */
159 boolean complexInference;
161 /** Character for synthetic names
162 */
163 char syntheticNameChar;
165 /** A table mapping flat names of all compiled classes in this run to their
166 * symbols; maintained from outside.
167 */
168 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
170 /** A handler for messages about deprecated usage.
171 */
172 private MandatoryWarningHandler deprecationHandler;
174 /** A handler for messages about unchecked or unsafe usage.
175 */
176 private MandatoryWarningHandler uncheckedHandler;
178 /** A handler for messages about using proprietary API.
179 */
180 private MandatoryWarningHandler sunApiHandler;
182 /** A handler for deferred lint warnings.
183 */
184 private DeferredLintHandler deferredLintHandler;
186 /* *************************************************************************
187 * Errors and Warnings
188 **************************************************************************/
190 Lint setLint(Lint newLint) {
191 Lint prev = lint;
192 lint = newLint;
193 return prev;
194 }
196 DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
197 DeferredLintHandler prev = deferredLintHandler;
198 deferredLintHandler = newDeferredLintHandler;
199 return prev;
200 }
202 MethodSymbol setMethod(MethodSymbol newMethod) {
203 MethodSymbol prev = method;
204 method = newMethod;
205 return prev;
206 }
208 /** Warn about deprecated symbol.
209 * @param pos Position to be used for error reporting.
210 * @param sym The deprecated symbol.
211 */
212 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
213 if (!lint.isSuppressed(LintCategory.DEPRECATION))
214 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
215 }
217 /** Warn about unchecked operation.
218 * @param pos Position to be used for error reporting.
219 * @param msg A string describing the problem.
220 */
221 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
222 if (!lint.isSuppressed(LintCategory.UNCHECKED))
223 uncheckedHandler.report(pos, msg, args);
224 }
226 /** Warn about unsafe vararg method decl.
227 * @param pos Position to be used for error reporting.
228 * @param sym The deprecated symbol.
229 */
230 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
231 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
232 log.warning(LintCategory.VARARGS, pos, key, args);
233 }
235 /** Warn about using proprietary API.
236 * @param pos Position to be used for error reporting.
237 * @param msg A string describing the problem.
238 */
239 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
240 if (!lint.isSuppressed(LintCategory.SUNAPI))
241 sunApiHandler.report(pos, msg, args);
242 }
244 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
245 if (lint.isEnabled(LintCategory.STATIC))
246 log.warning(LintCategory.STATIC, pos, msg, args);
247 }
249 /**
250 * Report any deferred diagnostics.
251 */
252 public void reportDeferredDiagnostics() {
253 deprecationHandler.reportDeferredDiagnostic();
254 uncheckedHandler.reportDeferredDiagnostic();
255 sunApiHandler.reportDeferredDiagnostic();
256 }
259 /** Report a failure to complete a class.
260 * @param pos Position to be used for error reporting.
261 * @param ex The failure to report.
262 */
263 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
264 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
265 if (ex instanceof ClassReader.BadClassFile
266 && !suppressAbortOnBadClassFile) throw new Abort();
267 else return syms.errType;
268 }
270 /** Report an error that wrong type tag was found.
271 * @param pos Position to be used for error reporting.
272 * @param required An internationalized string describing the type tag
273 * required.
274 * @param found The type that was found.
275 */
276 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
277 // this error used to be raised by the parser,
278 // but has been delayed to this point:
279 if (found instanceof Type && ((Type)found).tag == VOID) {
280 log.error(pos, "illegal.start.of.type");
281 return syms.errType;
282 }
283 log.error(pos, "type.found.req", found, required);
284 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
285 }
287 /** Report an error that symbol cannot be referenced before super
288 * has been called.
289 * @param pos Position to be used for error reporting.
290 * @param sym The referenced symbol.
291 */
292 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
293 log.error(pos, "cant.ref.before.ctor.called", sym);
294 }
296 /** Report duplicate declaration error.
297 */
298 void duplicateError(DiagnosticPosition pos, Symbol sym) {
299 if (!sym.type.isErroneous()) {
300 Symbol location = sym.location();
301 if (location.kind == MTH &&
302 ((MethodSymbol)location).isStaticOrInstanceInit()) {
303 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
304 kindName(sym.location()), kindName(sym.location().enclClass()),
305 sym.location().enclClass());
306 } else {
307 log.error(pos, "already.defined", kindName(sym), sym,
308 kindName(sym.location()), sym.location());
309 }
310 }
311 }
313 /** Report array/varargs duplicate declaration
314 */
315 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
316 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
317 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
318 }
319 }
321 /* ************************************************************************
322 * duplicate declaration checking
323 *************************************************************************/
325 /** Check that variable does not hide variable with same name in
326 * immediately enclosing local scope.
327 * @param pos Position for error reporting.
328 * @param v The symbol.
329 * @param s The scope.
330 */
331 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
332 if (s.next != null) {
333 for (Scope.Entry e = s.next.lookup(v.name);
334 e.scope != null && e.sym.owner == v.owner;
335 e = e.next()) {
336 if (e.sym.kind == VAR &&
337 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
338 v.name != names.error) {
339 duplicateError(pos, e.sym);
340 return;
341 }
342 }
343 }
344 }
346 /** Check that a class or interface does not hide a class or
347 * interface with same name in immediately enclosing local scope.
348 * @param pos Position for error reporting.
349 * @param c The symbol.
350 * @param s The scope.
351 */
352 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
353 if (s.next != null) {
354 for (Scope.Entry e = s.next.lookup(c.name);
355 e.scope != null && e.sym.owner == c.owner;
356 e = e.next()) {
357 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
358 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
359 c.name != names.error) {
360 duplicateError(pos, e.sym);
361 return;
362 }
363 }
364 }
365 }
367 /** Check that class does not have the same name as one of
368 * its enclosing classes, or as a class defined in its enclosing scope.
369 * return true if class is unique in its enclosing scope.
370 * @param pos Position for error reporting.
371 * @param name The class name.
372 * @param s The enclosing scope.
373 */
374 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
375 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
376 if (e.sym.kind == TYP && e.sym.name != names.error) {
377 duplicateError(pos, e.sym);
378 return false;
379 }
380 }
381 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
382 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
383 duplicateError(pos, sym);
384 return true;
385 }
386 }
387 return true;
388 }
390 /* *************************************************************************
391 * Class name generation
392 **************************************************************************/
394 /** Return name of local class.
395 * This is of the form <enclClass> $ n <classname>
396 * where
397 * enclClass is the flat name of the enclosing class,
398 * classname is the simple name of the local class
399 */
400 Name localClassName(ClassSymbol c) {
401 for (int i=1; ; i++) {
402 Name flatname = names.
403 fromString("" + c.owner.enclClass().flatname +
404 syntheticNameChar + i +
405 c.name);
406 if (compiled.get(flatname) == null) return flatname;
407 }
408 }
410 /* *************************************************************************
411 * Type Checking
412 **************************************************************************/
414 /**
415 * A check context is an object that can be used to perform compatibility
416 * checks - depending on the check context, meaning of 'compatibility' might
417 * vary significantly.
418 */
419 interface CheckContext {
420 /**
421 * Is type 'found' compatible with type 'req' in given context
422 */
423 boolean compatible(Type found, Type req, Warner warn);
424 /**
425 * Report a check error
426 */
427 void report(DiagnosticPosition pos, JCDiagnostic details);
428 /**
429 * Obtain a warner for this check context
430 */
431 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
432 }
434 /**
435 * This class represent a check context that is nested within another check
436 * context - useful to check sub-expressions. The default behavior simply
437 * redirects all method calls to the enclosing check context leveraging
438 * the forwarding pattern.
439 */
440 static class NestedCheckContext implements CheckContext {
441 CheckContext enclosingContext;
443 NestedCheckContext(CheckContext enclosingContext) {
444 this.enclosingContext = enclosingContext;
445 }
447 public boolean compatible(Type found, Type req, Warner warn) {
448 return enclosingContext.compatible(found, req, warn);
449 }
451 public void report(DiagnosticPosition pos, JCDiagnostic details) {
452 enclosingContext.report(pos, details);
453 }
455 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
456 return enclosingContext.checkWarner(pos, found, req);
457 }
458 }
460 /**
461 * Check context to be used when evaluating assignment/return statements
462 */
463 CheckContext basicHandler = new CheckContext() {
464 public void report(DiagnosticPosition pos, JCDiagnostic details) {
465 log.error(pos, "prob.found.req", details);
466 }
467 public boolean compatible(Type found, Type req, Warner warn) {
468 return types.isAssignable(found, req, warn);
469 }
471 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
472 return convertWarner(pos, found, req);
473 }
474 };
476 /** Check that a given type is assignable to a given proto-type.
477 * If it is, return the type, otherwise return errType.
478 * @param pos Position to be used for error reporting.
479 * @param found The type that was found.
480 * @param req The type that was required.
481 */
482 Type checkType(DiagnosticPosition pos, Type found, Type req) {
483 return checkType(pos, found, req, basicHandler);
484 }
486 Type checkType(final DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
487 if (req.tag == ERROR)
488 return req;
489 if (req.tag == NONE)
490 return found;
491 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
492 return found;
493 } else {
494 if (found.tag <= DOUBLE && req.tag <= DOUBLE) {
495 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
496 return types.createErrorType(found);
497 }
498 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
499 return types.createErrorType(found);
500 }
501 }
503 /** Check that a given type can be cast to a given target type.
504 * Return the result of the cast.
505 * @param pos Position to be used for error reporting.
506 * @param found The type that is being cast.
507 * @param req The target type of the cast.
508 */
509 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
510 return checkCastable(pos, found, req, basicHandler);
511 }
512 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
513 if (types.isCastable(found, req, castWarner(pos, found, req))) {
514 return req;
515 } else {
516 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
517 return types.createErrorType(found);
518 }
519 }
521 /** Check for redundant casts (i.e. where source type is a subtype of target type)
522 * The problem should only be reported for non-292 cast
523 */
524 public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
525 if (!tree.type.isErroneous() &&
526 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
527 && types.isSameType(tree.expr.type, tree.clazz.type)
528 && !is292targetTypeCast(tree)) {
529 log.warning(Lint.LintCategory.CAST,
530 tree.pos(), "redundant.cast", tree.expr.type);
531 }
532 }
533 //where
534 private boolean is292targetTypeCast(JCTypeCast tree) {
535 boolean is292targetTypeCast = false;
536 JCExpression expr = TreeInfo.skipParens(tree.expr);
537 if (expr.hasTag(APPLY)) {
538 JCMethodInvocation apply = (JCMethodInvocation)expr;
539 Symbol sym = TreeInfo.symbol(apply.meth);
540 is292targetTypeCast = sym != null &&
541 sym.kind == MTH &&
542 (sym.flags() & HYPOTHETICAL) != 0;
543 }
544 return is292targetTypeCast;
545 }
549 //where
550 /** Is type a type variable, or a (possibly multi-dimensional) array of
551 * type variables?
552 */
553 boolean isTypeVar(Type t) {
554 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
555 }
557 /** Check that a type is within some bounds.
558 *
559 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
560 * type argument.
561 * @param pos Position to be used for error reporting.
562 * @param a The type that should be bounded by bs.
563 * @param bs The bound.
564 */
565 private boolean checkExtends(Type a, Type bound) {
566 if (a.isUnbound()) {
567 return true;
568 } else if (a.tag != WILDCARD) {
569 a = types.upperBound(a);
570 return types.isSubtype(a, bound);
571 } else if (a.isExtendsBound()) {
572 return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
573 } else if (a.isSuperBound()) {
574 return !types.notSoftSubtype(types.lowerBound(a), bound);
575 }
576 return true;
577 }
579 /** Check that type is different from 'void'.
580 * @param pos Position to be used for error reporting.
581 * @param t The type to be checked.
582 */
583 Type checkNonVoid(DiagnosticPosition pos, Type t) {
584 if (t.tag == VOID) {
585 log.error(pos, "void.not.allowed.here");
586 return types.createErrorType(t);
587 } else {
588 return t;
589 }
590 }
592 /** Check that type is a class or interface type.
593 * @param pos Position to be used for error reporting.
594 * @param t The type to be checked.
595 */
596 Type checkClassType(DiagnosticPosition pos, Type t) {
597 if (t.tag != CLASS && t.tag != ERROR)
598 return typeTagError(pos,
599 diags.fragment("type.req.class"),
600 (t.tag == TYPEVAR)
601 ? diags.fragment("type.parameter", t)
602 : t);
603 else
604 return t;
605 }
607 /** Check that type is a class or interface type.
608 * @param pos Position to be used for error reporting.
609 * @param t The type to be checked.
610 * @param noBounds True if type bounds are illegal here.
611 */
612 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
613 t = checkClassType(pos, t);
614 if (noBounds && t.isParameterized()) {
615 List<Type> args = t.getTypeArguments();
616 while (args.nonEmpty()) {
617 if (args.head.tag == WILDCARD)
618 return typeTagError(pos,
619 diags.fragment("type.req.exact"),
620 args.head);
621 args = args.tail;
622 }
623 }
624 return t;
625 }
627 /** Check that type is a reifiable class, interface or array type.
628 * @param pos Position to be used for error reporting.
629 * @param t The type to be checked.
630 */
631 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
632 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
633 return typeTagError(pos,
634 diags.fragment("type.req.class.array"),
635 t);
636 } else if (!types.isReifiable(t)) {
637 log.error(pos, "illegal.generic.type.for.instof");
638 return types.createErrorType(t);
639 } else {
640 return t;
641 }
642 }
644 /** Check that type is a reference type, i.e. a class, interface or array type
645 * or a type variable.
646 * @param pos Position to be used for error reporting.
647 * @param t The type to be checked.
648 */
649 Type checkRefType(DiagnosticPosition pos, Type t) {
650 switch (t.tag) {
651 case CLASS:
652 case ARRAY:
653 case TYPEVAR:
654 case WILDCARD:
655 case ERROR:
656 return t;
657 default:
658 return typeTagError(pos,
659 diags.fragment("type.req.ref"),
660 t);
661 }
662 }
664 /** Check that each type is a reference type, i.e. a class, interface or array type
665 * or a type variable.
666 * @param trees Original trees, used for error reporting.
667 * @param types The types to be checked.
668 */
669 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
670 List<JCExpression> tl = trees;
671 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
672 l.head = checkRefType(tl.head.pos(), l.head);
673 tl = tl.tail;
674 }
675 return types;
676 }
678 /** Check that type is a null or reference type.
679 * @param pos Position to be used for error reporting.
680 * @param t The type to be checked.
681 */
682 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
683 switch (t.tag) {
684 case CLASS:
685 case ARRAY:
686 case TYPEVAR:
687 case WILDCARD:
688 case BOT:
689 case ERROR:
690 return t;
691 default:
692 return typeTagError(pos,
693 diags.fragment("type.req.ref"),
694 t);
695 }
696 }
698 /** Check that flag set does not contain elements of two conflicting sets. s
699 * Return true if it doesn't.
700 * @param pos Position to be used for error reporting.
701 * @param flags The set of flags to be checked.
702 * @param set1 Conflicting flags set #1.
703 * @param set2 Conflicting flags set #2.
704 */
705 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
706 if ((flags & set1) != 0 && (flags & set2) != 0) {
707 log.error(pos,
708 "illegal.combination.of.modifiers",
709 asFlagSet(TreeInfo.firstFlag(flags & set1)),
710 asFlagSet(TreeInfo.firstFlag(flags & set2)));
711 return false;
712 } else
713 return true;
714 }
716 /** Check that usage of diamond operator is correct (i.e. diamond should not
717 * be used with non-generic classes or in anonymous class creation expressions)
718 */
719 Type checkDiamond(JCNewClass tree, Type t) {
720 if (!TreeInfo.isDiamond(tree) ||
721 t.isErroneous()) {
722 return checkClassType(tree.clazz.pos(), t, true);
723 } else if (tree.def != null) {
724 log.error(tree.clazz.pos(),
725 "cant.apply.diamond.1",
726 t, diags.fragment("diamond.and.anon.class", t));
727 return types.createErrorType(t);
728 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
729 log.error(tree.clazz.pos(),
730 "cant.apply.diamond.1",
731 t, diags.fragment("diamond.non.generic", t));
732 return types.createErrorType(t);
733 } else if (tree.typeargs != null &&
734 tree.typeargs.nonEmpty()) {
735 log.error(tree.clazz.pos(),
736 "cant.apply.diamond.1",
737 t, diags.fragment("diamond.and.explicit.params", t));
738 return types.createErrorType(t);
739 } else {
740 return t;
741 }
742 }
744 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
745 MethodSymbol m = tree.sym;
746 if (!allowSimplifiedVarargs) return;
747 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
748 Type varargElemType = null;
749 if (m.isVarArgs()) {
750 varargElemType = types.elemtype(tree.params.last().type);
751 }
752 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
753 if (varargElemType != null) {
754 log.error(tree,
755 "varargs.invalid.trustme.anno",
756 syms.trustMeType.tsym,
757 diags.fragment("varargs.trustme.on.virtual.varargs", m));
758 } else {
759 log.error(tree,
760 "varargs.invalid.trustme.anno",
761 syms.trustMeType.tsym,
762 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
763 }
764 } else if (hasTrustMeAnno && varargElemType != null &&
765 types.isReifiable(varargElemType)) {
766 warnUnsafeVararg(tree,
767 "varargs.redundant.trustme.anno",
768 syms.trustMeType.tsym,
769 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
770 }
771 else if (!hasTrustMeAnno && varargElemType != null &&
772 !types.isReifiable(varargElemType)) {
773 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
774 }
775 }
776 //where
777 private boolean isTrustMeAllowedOnMethod(Symbol s) {
778 return (s.flags() & VARARGS) != 0 &&
779 (s.isConstructor() ||
780 (s.flags() & (STATIC | FINAL)) != 0);
781 }
783 Type checkMethod(Type owntype,
784 Symbol sym,
785 Env<AttrContext> env,
786 final List<JCExpression> argtrees,
787 List<Type> argtypes,
788 boolean useVarargs,
789 boolean unchecked) {
790 // System.out.println("call : " + env.tree);
791 // System.out.println("method : " + owntype);
792 // System.out.println("actuals: " + argtypes);
793 List<Type> formals = owntype.getParameterTypes();
794 Type last = useVarargs ? formals.last() : null;
795 if (sym.name==names.init &&
796 sym.owner == syms.enumSym)
797 formals = formals.tail.tail;
798 List<JCExpression> args = argtrees;
799 while (formals.head != last) {
800 JCTree arg = args.head;
801 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
802 assertConvertible(arg, arg.type, formals.head, warn);
803 args = args.tail;
804 formals = formals.tail;
805 }
806 if (useVarargs) {
807 Type varArg = types.elemtype(last);
808 while (args.tail != null) {
809 JCTree arg = args.head;
810 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
811 assertConvertible(arg, arg.type, varArg, warn);
812 args = args.tail;
813 }
814 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
815 // non-varargs call to varargs method
816 Type varParam = owntype.getParameterTypes().last();
817 Type lastArg = argtypes.last();
818 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
819 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
820 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
821 types.elemtype(varParam), varParam);
822 }
823 if (unchecked) {
824 warnUnchecked(env.tree.pos(),
825 "unchecked.meth.invocation.applied",
826 kindName(sym),
827 sym.name,
828 rs.methodArguments(sym.type.getParameterTypes()),
829 rs.methodArguments(argtypes),
830 kindName(sym.location()),
831 sym.location());
832 owntype = new MethodType(owntype.getParameterTypes(),
833 types.erasure(owntype.getReturnType()),
834 types.erasure(owntype.getThrownTypes()),
835 syms.methodClass);
836 }
837 if (useVarargs) {
838 JCTree tree = env.tree;
839 Type argtype = owntype.getParameterTypes().last();
840 if (!types.isReifiable(argtype) &&
841 (!allowSimplifiedVarargs ||
842 sym.attribute(syms.trustMeType.tsym) == null ||
843 !isTrustMeAllowedOnMethod(sym))) {
844 warnUnchecked(env.tree.pos(),
845 "unchecked.generic.array.creation",
846 argtype);
847 }
848 Type elemtype = types.elemtype(argtype);
849 switch (tree.getTag()) {
850 case APPLY:
851 ((JCMethodInvocation) tree).varargsElement = elemtype;
852 break;
853 case NEWCLASS:
854 ((JCNewClass) tree).varargsElement = elemtype;
855 break;
856 default:
857 throw new AssertionError(""+tree);
858 }
859 }
860 return owntype;
861 }
862 //where
863 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
864 if (types.isConvertible(actual, formal, warn))
865 return;
867 if (formal.isCompound()
868 && types.isSubtype(actual, types.supertype(formal))
869 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
870 return;
871 }
873 /**
874 * Check that type 't' is a valid instantiation of a generic class
875 * (see JLS 4.5)
876 *
877 * @param t class type to be checked
878 * @return true if 't' is well-formed
879 */
880 public boolean checkValidGenericType(Type t) {
881 return firstIncompatibleTypeArg(t) == null;
882 }
883 //WHERE
884 private Type firstIncompatibleTypeArg(Type type) {
885 List<Type> formals = type.tsym.type.allparams();
886 List<Type> actuals = type.allparams();
887 List<Type> args = type.getTypeArguments();
888 List<Type> forms = type.tsym.type.getTypeArguments();
889 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
891 // For matching pairs of actual argument types `a' and
892 // formal type parameters with declared bound `b' ...
893 while (args.nonEmpty() && forms.nonEmpty()) {
894 // exact type arguments needs to know their
895 // bounds (for upper and lower bound
896 // calculations). So we create new bounds where
897 // type-parameters are replaced with actuals argument types.
898 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
899 args = args.tail;
900 forms = forms.tail;
901 }
903 args = type.getTypeArguments();
904 List<Type> tvars_cap = types.substBounds(formals,
905 formals,
906 types.capture(type).allparams());
907 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
908 // Let the actual arguments know their bound
909 args.head.withTypeVar((TypeVar)tvars_cap.head);
910 args = args.tail;
911 tvars_cap = tvars_cap.tail;
912 }
914 args = type.getTypeArguments();
915 List<Type> bounds = bounds_buf.toList();
917 while (args.nonEmpty() && bounds.nonEmpty()) {
918 Type actual = args.head;
919 if (!isTypeArgErroneous(actual) &&
920 !bounds.head.isErroneous() &&
921 !checkExtends(actual, bounds.head)) {
922 return args.head;
923 }
924 args = args.tail;
925 bounds = bounds.tail;
926 }
928 args = type.getTypeArguments();
929 bounds = bounds_buf.toList();
931 for (Type arg : types.capture(type).getTypeArguments()) {
932 if (arg.tag == TYPEVAR &&
933 arg.getUpperBound().isErroneous() &&
934 !bounds.head.isErroneous() &&
935 !isTypeArgErroneous(args.head)) {
936 return args.head;
937 }
938 bounds = bounds.tail;
939 args = args.tail;
940 }
942 return null;
943 }
944 //where
945 boolean isTypeArgErroneous(Type t) {
946 return isTypeArgErroneous.visit(t);
947 }
949 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
950 public Boolean visitType(Type t, Void s) {
951 return t.isErroneous();
952 }
953 @Override
954 public Boolean visitTypeVar(TypeVar t, Void s) {
955 return visit(t.getUpperBound());
956 }
957 @Override
958 public Boolean visitCapturedType(CapturedType t, Void s) {
959 return visit(t.getUpperBound()) ||
960 visit(t.getLowerBound());
961 }
962 @Override
963 public Boolean visitWildcardType(WildcardType t, Void s) {
964 return visit(t.type);
965 }
966 };
968 /** Check that given modifiers are legal for given symbol and
969 * return modifiers together with any implicit modififiers for that symbol.
970 * Warning: we can't use flags() here since this method
971 * is called during class enter, when flags() would cause a premature
972 * completion.
973 * @param pos Position to be used for error reporting.
974 * @param flags The set of modifiers given in a definition.
975 * @param sym The defined symbol.
976 */
977 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
978 long mask;
979 long implicit = 0;
980 switch (sym.kind) {
981 case VAR:
982 if (sym.owner.kind != TYP)
983 mask = LocalVarFlags;
984 else if ((sym.owner.flags_field & INTERFACE) != 0)
985 mask = implicit = InterfaceVarFlags;
986 else
987 mask = VarFlags;
988 break;
989 case MTH:
990 if (sym.name == names.init) {
991 if ((sym.owner.flags_field & ENUM) != 0) {
992 // enum constructors cannot be declared public or
993 // protected and must be implicitly or explicitly
994 // private
995 implicit = PRIVATE;
996 mask = PRIVATE;
997 } else
998 mask = ConstructorFlags;
999 } else if ((sym.owner.flags_field & INTERFACE) != 0)
1000 mask = implicit = InterfaceMethodFlags;
1001 else {
1002 mask = MethodFlags;
1003 }
1004 // Imply STRICTFP if owner has STRICTFP set.
1005 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1006 implicit |= sym.owner.flags_field & STRICTFP;
1007 break;
1008 case TYP:
1009 if (sym.isLocal()) {
1010 mask = LocalClassFlags;
1011 if (sym.name.isEmpty()) { // Anonymous class
1012 // Anonymous classes in static methods are themselves static;
1013 // that's why we admit STATIC here.
1014 mask |= STATIC;
1015 // JLS: Anonymous classes are final.
1016 implicit |= FINAL;
1017 }
1018 if ((sym.owner.flags_field & STATIC) == 0 &&
1019 (flags & ENUM) != 0)
1020 log.error(pos, "enums.must.be.static");
1021 } else if (sym.owner.kind == TYP) {
1022 mask = MemberClassFlags;
1023 if (sym.owner.owner.kind == PCK ||
1024 (sym.owner.flags_field & STATIC) != 0)
1025 mask |= STATIC;
1026 else if ((flags & ENUM) != 0)
1027 log.error(pos, "enums.must.be.static");
1028 // Nested interfaces and enums are always STATIC (Spec ???)
1029 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1030 } else {
1031 mask = ClassFlags;
1032 }
1033 // Interfaces are always ABSTRACT
1034 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1036 if ((flags & ENUM) != 0) {
1037 // enums can't be declared abstract or final
1038 mask &= ~(ABSTRACT | FINAL);
1039 implicit |= implicitEnumFinalFlag(tree);
1040 }
1041 // Imply STRICTFP if owner has STRICTFP set.
1042 implicit |= sym.owner.flags_field & STRICTFP;
1043 break;
1044 default:
1045 throw new AssertionError();
1046 }
1047 long illegal = flags & StandardFlags & ~mask;
1048 if (illegal != 0) {
1049 if ((illegal & INTERFACE) != 0) {
1050 log.error(pos, "intf.not.allowed.here");
1051 mask |= INTERFACE;
1052 }
1053 else {
1054 log.error(pos,
1055 "mod.not.allowed.here", asFlagSet(illegal));
1056 }
1057 }
1058 else if ((sym.kind == TYP ||
1059 // ISSUE: Disallowing abstract&private is no longer appropriate
1060 // in the presence of inner classes. Should it be deleted here?
1061 checkDisjoint(pos, flags,
1062 ABSTRACT,
1063 PRIVATE | STATIC))
1064 &&
1065 checkDisjoint(pos, flags,
1066 ABSTRACT | INTERFACE,
1067 FINAL | NATIVE | SYNCHRONIZED)
1068 &&
1069 checkDisjoint(pos, flags,
1070 PUBLIC,
1071 PRIVATE | PROTECTED)
1072 &&
1073 checkDisjoint(pos, flags,
1074 PRIVATE,
1075 PUBLIC | PROTECTED)
1076 &&
1077 checkDisjoint(pos, flags,
1078 FINAL,
1079 VOLATILE)
1080 &&
1081 (sym.kind == TYP ||
1082 checkDisjoint(pos, flags,
1083 ABSTRACT | NATIVE,
1084 STRICTFP))) {
1085 // skip
1086 }
1087 return flags & (mask | ~StandardFlags) | implicit;
1088 }
1091 /** Determine if this enum should be implicitly final.
1092 *
1093 * If the enum has no specialized enum contants, it is final.
1094 *
1095 * If the enum does have specialized enum contants, it is
1096 * <i>not</i> final.
1097 */
1098 private long implicitEnumFinalFlag(JCTree tree) {
1099 if (!tree.hasTag(CLASSDEF)) return 0;
1100 class SpecialTreeVisitor extends JCTree.Visitor {
1101 boolean specialized;
1102 SpecialTreeVisitor() {
1103 this.specialized = false;
1104 };
1106 @Override
1107 public void visitTree(JCTree tree) { /* no-op */ }
1109 @Override
1110 public void visitVarDef(JCVariableDecl tree) {
1111 if ((tree.mods.flags & ENUM) != 0) {
1112 if (tree.init instanceof JCNewClass &&
1113 ((JCNewClass) tree.init).def != null) {
1114 specialized = true;
1115 }
1116 }
1117 }
1118 }
1120 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1121 JCClassDecl cdef = (JCClassDecl) tree;
1122 for (JCTree defs: cdef.defs) {
1123 defs.accept(sts);
1124 if (sts.specialized) return 0;
1125 }
1126 return FINAL;
1127 }
1129 /* *************************************************************************
1130 * Type Validation
1131 **************************************************************************/
1133 /** Validate a type expression. That is,
1134 * check that all type arguments of a parametric type are within
1135 * their bounds. This must be done in a second phase after type attributon
1136 * since a class might have a subclass as type parameter bound. E.g:
1137 *
1138 * class B<A extends C> { ... }
1139 * class C extends B<C> { ... }
1140 *
1141 * and we can't make sure that the bound is already attributed because
1142 * of possible cycles.
1143 *
1144 * Visitor method: Validate a type expression, if it is not null, catching
1145 * and reporting any completion failures.
1146 */
1147 void validate(JCTree tree, Env<AttrContext> env) {
1148 validate(tree, env, true);
1149 }
1150 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1151 new Validator(env).validateTree(tree, checkRaw, true);
1152 }
1154 /** Visitor method: Validate a list of type expressions.
1155 */
1156 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1157 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1158 validate(l.head, env);
1159 }
1161 /** A visitor class for type validation.
1162 */
1163 class Validator extends JCTree.Visitor {
1165 boolean isOuter;
1166 Env<AttrContext> env;
1168 Validator(Env<AttrContext> env) {
1169 this.env = env;
1170 }
1172 @Override
1173 public void visitTypeArray(JCArrayTypeTree tree) {
1174 tree.elemtype.accept(this);
1175 }
1177 @Override
1178 public void visitTypeApply(JCTypeApply tree) {
1179 if (tree.type.tag == CLASS) {
1180 List<JCExpression> args = tree.arguments;
1181 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1183 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1184 if (incompatibleArg != null) {
1185 for (JCTree arg : tree.arguments) {
1186 if (arg.type == incompatibleArg) {
1187 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1188 }
1189 forms = forms.tail;
1190 }
1191 }
1193 forms = tree.type.tsym.type.getTypeArguments();
1195 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1197 // For matching pairs of actual argument types `a' and
1198 // formal type parameters with declared bound `b' ...
1199 while (args.nonEmpty() && forms.nonEmpty()) {
1200 validateTree(args.head,
1201 !(isOuter && is_java_lang_Class),
1202 false);
1203 args = args.tail;
1204 forms = forms.tail;
1205 }
1207 // Check that this type is either fully parameterized, or
1208 // not parameterized at all.
1209 if (tree.type.getEnclosingType().isRaw())
1210 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1211 if (tree.clazz.hasTag(SELECT))
1212 visitSelectInternal((JCFieldAccess)tree.clazz);
1213 }
1214 }
1216 @Override
1217 public void visitTypeParameter(JCTypeParameter tree) {
1218 validateTrees(tree.bounds, true, isOuter);
1219 checkClassBounds(tree.pos(), tree.type);
1220 }
1222 @Override
1223 public void visitWildcard(JCWildcard tree) {
1224 if (tree.inner != null)
1225 validateTree(tree.inner, true, isOuter);
1226 }
1228 @Override
1229 public void visitSelect(JCFieldAccess tree) {
1230 if (tree.type.tag == CLASS) {
1231 visitSelectInternal(tree);
1233 // Check that this type is either fully parameterized, or
1234 // not parameterized at all.
1235 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1236 log.error(tree.pos(), "improperly.formed.type.param.missing");
1237 }
1238 }
1240 public void visitSelectInternal(JCFieldAccess tree) {
1241 if (tree.type.tsym.isStatic() &&
1242 tree.selected.type.isParameterized()) {
1243 // The enclosing type is not a class, so we are
1244 // looking at a static member type. However, the
1245 // qualifying expression is parameterized.
1246 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1247 } else {
1248 // otherwise validate the rest of the expression
1249 tree.selected.accept(this);
1250 }
1251 }
1253 /** Default visitor method: do nothing.
1254 */
1255 @Override
1256 public void visitTree(JCTree tree) {
1257 }
1259 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1260 try {
1261 if (tree != null) {
1262 this.isOuter = isOuter;
1263 tree.accept(this);
1264 if (checkRaw)
1265 checkRaw(tree, env);
1266 }
1267 } catch (CompletionFailure ex) {
1268 completionError(tree.pos(), ex);
1269 }
1270 }
1272 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1273 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1274 validateTree(l.head, checkRaw, isOuter);
1275 }
1277 void checkRaw(JCTree tree, Env<AttrContext> env) {
1278 if (lint.isEnabled(LintCategory.RAW) &&
1279 tree.type.tag == CLASS &&
1280 !TreeInfo.isDiamond(tree) &&
1281 !withinAnonConstr(env) &&
1282 tree.type.isRaw()) {
1283 log.warning(LintCategory.RAW,
1284 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1285 }
1286 }
1288 boolean withinAnonConstr(Env<AttrContext> env) {
1289 return env.enclClass.name.isEmpty() &&
1290 env.enclMethod != null && env.enclMethod.name == names.init;
1291 }
1292 }
1294 /* *************************************************************************
1295 * Exception checking
1296 **************************************************************************/
1298 /* The following methods treat classes as sets that contain
1299 * the class itself and all their subclasses
1300 */
1302 /** Is given type a subtype of some of the types in given list?
1303 */
1304 boolean subset(Type t, List<Type> ts) {
1305 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1306 if (types.isSubtype(t, l.head)) return true;
1307 return false;
1308 }
1310 /** Is given type a subtype or supertype of
1311 * some of the types in given list?
1312 */
1313 boolean intersects(Type t, List<Type> ts) {
1314 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1315 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1316 return false;
1317 }
1319 /** Add type set to given type list, unless it is a subclass of some class
1320 * in the list.
1321 */
1322 List<Type> incl(Type t, List<Type> ts) {
1323 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1324 }
1326 /** Remove type set from type set list.
1327 */
1328 List<Type> excl(Type t, List<Type> ts) {
1329 if (ts.isEmpty()) {
1330 return ts;
1331 } else {
1332 List<Type> ts1 = excl(t, ts.tail);
1333 if (types.isSubtype(ts.head, t)) return ts1;
1334 else if (ts1 == ts.tail) return ts;
1335 else return ts1.prepend(ts.head);
1336 }
1337 }
1339 /** Form the union of two type set lists.
1340 */
1341 List<Type> union(List<Type> ts1, List<Type> ts2) {
1342 List<Type> ts = ts1;
1343 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1344 ts = incl(l.head, ts);
1345 return ts;
1346 }
1348 /** Form the difference of two type lists.
1349 */
1350 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1351 List<Type> ts = ts1;
1352 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1353 ts = excl(l.head, ts);
1354 return ts;
1355 }
1357 /** Form the intersection of two type lists.
1358 */
1359 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1360 List<Type> ts = List.nil();
1361 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1362 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1363 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1364 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1365 return ts;
1366 }
1368 /** Is exc an exception symbol that need not be declared?
1369 */
1370 boolean isUnchecked(ClassSymbol exc) {
1371 return
1372 exc.kind == ERR ||
1373 exc.isSubClass(syms.errorType.tsym, types) ||
1374 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1375 }
1377 /** Is exc an exception type that need not be declared?
1378 */
1379 boolean isUnchecked(Type exc) {
1380 return
1381 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1382 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1383 exc.tag == BOT;
1384 }
1386 /** Same, but handling completion failures.
1387 */
1388 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1389 try {
1390 return isUnchecked(exc);
1391 } catch (CompletionFailure ex) {
1392 completionError(pos, ex);
1393 return true;
1394 }
1395 }
1397 /** Is exc handled by given exception list?
1398 */
1399 boolean isHandled(Type exc, List<Type> handled) {
1400 return isUnchecked(exc) || subset(exc, handled);
1401 }
1403 /** Return all exceptions in thrown list that are not in handled list.
1404 * @param thrown The list of thrown exceptions.
1405 * @param handled The list of handled exceptions.
1406 */
1407 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1408 List<Type> unhandled = List.nil();
1409 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1410 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1411 return unhandled;
1412 }
1414 /* *************************************************************************
1415 * Overriding/Implementation checking
1416 **************************************************************************/
1418 /** The level of access protection given by a flag set,
1419 * where PRIVATE is highest and PUBLIC is lowest.
1420 */
1421 static int protection(long flags) {
1422 switch ((short)(flags & AccessFlags)) {
1423 case PRIVATE: return 3;
1424 case PROTECTED: return 1;
1425 default:
1426 case PUBLIC: return 0;
1427 case 0: return 2;
1428 }
1429 }
1431 /** A customized "cannot override" error message.
1432 * @param m The overriding method.
1433 * @param other The overridden method.
1434 * @return An internationalized string.
1435 */
1436 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1437 String key;
1438 if ((other.owner.flags() & INTERFACE) == 0)
1439 key = "cant.override";
1440 else if ((m.owner.flags() & INTERFACE) == 0)
1441 key = "cant.implement";
1442 else
1443 key = "clashes.with";
1444 return diags.fragment(key, m, m.location(), other, other.location());
1445 }
1447 /** A customized "override" warning message.
1448 * @param m The overriding method.
1449 * @param other The overridden method.
1450 * @return An internationalized string.
1451 */
1452 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1453 String key;
1454 if ((other.owner.flags() & INTERFACE) == 0)
1455 key = "unchecked.override";
1456 else if ((m.owner.flags() & INTERFACE) == 0)
1457 key = "unchecked.implement";
1458 else
1459 key = "unchecked.clash.with";
1460 return diags.fragment(key, m, m.location(), other, other.location());
1461 }
1463 /** A customized "override" warning message.
1464 * @param m The overriding method.
1465 * @param other The overridden method.
1466 * @return An internationalized string.
1467 */
1468 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1469 String key;
1470 if ((other.owner.flags() & INTERFACE) == 0)
1471 key = "varargs.override";
1472 else if ((m.owner.flags() & INTERFACE) == 0)
1473 key = "varargs.implement";
1474 else
1475 key = "varargs.clash.with";
1476 return diags.fragment(key, m, m.location(), other, other.location());
1477 }
1479 /** Check that this method conforms with overridden method 'other'.
1480 * where `origin' is the class where checking started.
1481 * Complications:
1482 * (1) Do not check overriding of synthetic methods
1483 * (reason: they might be final).
1484 * todo: check whether this is still necessary.
1485 * (2) Admit the case where an interface proxy throws fewer exceptions
1486 * than the method it implements. Augment the proxy methods with the
1487 * undeclared exceptions in this case.
1488 * (3) When generics are enabled, admit the case where an interface proxy
1489 * has a result type
1490 * extended by the result type of the method it implements.
1491 * Change the proxies result type to the smaller type in this case.
1492 *
1493 * @param tree The tree from which positions
1494 * are extracted for errors.
1495 * @param m The overriding method.
1496 * @param other The overridden method.
1497 * @param origin The class of which the overriding method
1498 * is a member.
1499 */
1500 void checkOverride(JCTree tree,
1501 MethodSymbol m,
1502 MethodSymbol other,
1503 ClassSymbol origin) {
1504 // Don't check overriding of synthetic methods or by bridge methods.
1505 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1506 return;
1507 }
1509 // Error if static method overrides instance method (JLS 8.4.6.2).
1510 if ((m.flags() & STATIC) != 0 &&
1511 (other.flags() & STATIC) == 0) {
1512 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1513 cannotOverride(m, other));
1514 return;
1515 }
1517 // Error if instance method overrides static or final
1518 // method (JLS 8.4.6.1).
1519 if ((other.flags() & FINAL) != 0 ||
1520 (m.flags() & STATIC) == 0 &&
1521 (other.flags() & STATIC) != 0) {
1522 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1523 cannotOverride(m, other),
1524 asFlagSet(other.flags() & (FINAL | STATIC)));
1525 return;
1526 }
1528 if ((m.owner.flags() & ANNOTATION) != 0) {
1529 // handled in validateAnnotationMethod
1530 return;
1531 }
1533 // Error if overriding method has weaker access (JLS 8.4.6.3).
1534 if ((origin.flags() & INTERFACE) == 0 &&
1535 protection(m.flags()) > protection(other.flags())) {
1536 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1537 cannotOverride(m, other),
1538 other.flags() == 0 ?
1539 Flag.PACKAGE :
1540 asFlagSet(other.flags() & AccessFlags));
1541 return;
1542 }
1544 Type mt = types.memberType(origin.type, m);
1545 Type ot = types.memberType(origin.type, other);
1546 // Error if overriding result type is different
1547 // (or, in the case of generics mode, not a subtype) of
1548 // overridden result type. We have to rename any type parameters
1549 // before comparing types.
1550 List<Type> mtvars = mt.getTypeArguments();
1551 List<Type> otvars = ot.getTypeArguments();
1552 Type mtres = mt.getReturnType();
1553 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1555 overrideWarner.clear();
1556 boolean resultTypesOK =
1557 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1558 if (!resultTypesOK) {
1559 if (!allowCovariantReturns &&
1560 m.owner != origin &&
1561 m.owner.isSubClass(other.owner, types)) {
1562 // allow limited interoperability with covariant returns
1563 } else {
1564 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1565 "override.incompatible.ret",
1566 cannotOverride(m, other),
1567 mtres, otres);
1568 return;
1569 }
1570 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1571 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1572 "override.unchecked.ret",
1573 uncheckedOverrides(m, other),
1574 mtres, otres);
1575 }
1577 // Error if overriding method throws an exception not reported
1578 // by overridden method.
1579 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1580 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1581 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1582 if (unhandledErased.nonEmpty()) {
1583 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1584 "override.meth.doesnt.throw",
1585 cannotOverride(m, other),
1586 unhandledUnerased.head);
1587 return;
1588 }
1589 else if (unhandledUnerased.nonEmpty()) {
1590 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1591 "override.unchecked.thrown",
1592 cannotOverride(m, other),
1593 unhandledUnerased.head);
1594 return;
1595 }
1597 // Optional warning if varargs don't agree
1598 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1599 && lint.isEnabled(LintCategory.OVERRIDES)) {
1600 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1601 ((m.flags() & Flags.VARARGS) != 0)
1602 ? "override.varargs.missing"
1603 : "override.varargs.extra",
1604 varargsOverrides(m, other));
1605 }
1607 // Warn if instance method overrides bridge method (compiler spec ??)
1608 if ((other.flags() & BRIDGE) != 0) {
1609 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1610 uncheckedOverrides(m, other));
1611 }
1613 // Warn if a deprecated method overridden by a non-deprecated one.
1614 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1615 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1616 }
1617 }
1618 // where
1619 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1620 // If the method, m, is defined in an interface, then ignore the issue if the method
1621 // is only inherited via a supertype and also implemented in the supertype,
1622 // because in that case, we will rediscover the issue when examining the method
1623 // in the supertype.
1624 // If the method, m, is not defined in an interface, then the only time we need to
1625 // address the issue is when the method is the supertype implemementation: any other
1626 // case, we will have dealt with when examining the supertype classes
1627 ClassSymbol mc = m.enclClass();
1628 Type st = types.supertype(origin.type);
1629 if (st.tag != CLASS)
1630 return true;
1631 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1633 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1634 List<Type> intfs = types.interfaces(origin.type);
1635 return (intfs.contains(mc.type) ? false : (stimpl != null));
1636 }
1637 else
1638 return (stimpl != m);
1639 }
1642 // used to check if there were any unchecked conversions
1643 Warner overrideWarner = new Warner();
1645 /** Check that a class does not inherit two concrete methods
1646 * with the same signature.
1647 * @param pos Position to be used for error reporting.
1648 * @param site The class type to be checked.
1649 */
1650 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1651 Type sup = types.supertype(site);
1652 if (sup.tag != CLASS) return;
1654 for (Type t1 = sup;
1655 t1.tsym.type.isParameterized();
1656 t1 = types.supertype(t1)) {
1657 for (Scope.Entry e1 = t1.tsym.members().elems;
1658 e1 != null;
1659 e1 = e1.sibling) {
1660 Symbol s1 = e1.sym;
1661 if (s1.kind != MTH ||
1662 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1663 !s1.isInheritedIn(site.tsym, types) ||
1664 ((MethodSymbol)s1).implementation(site.tsym,
1665 types,
1666 true) != s1)
1667 continue;
1668 Type st1 = types.memberType(t1, s1);
1669 int s1ArgsLength = st1.getParameterTypes().length();
1670 if (st1 == s1.type) continue;
1672 for (Type t2 = sup;
1673 t2.tag == CLASS;
1674 t2 = types.supertype(t2)) {
1675 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1676 e2.scope != null;
1677 e2 = e2.next()) {
1678 Symbol s2 = e2.sym;
1679 if (s2 == s1 ||
1680 s2.kind != MTH ||
1681 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1682 s2.type.getParameterTypes().length() != s1ArgsLength ||
1683 !s2.isInheritedIn(site.tsym, types) ||
1684 ((MethodSymbol)s2).implementation(site.tsym,
1685 types,
1686 true) != s2)
1687 continue;
1688 Type st2 = types.memberType(t2, s2);
1689 if (types.overrideEquivalent(st1, st2))
1690 log.error(pos, "concrete.inheritance.conflict",
1691 s1, t1, s2, t2, sup);
1692 }
1693 }
1694 }
1695 }
1696 }
1698 /** Check that classes (or interfaces) do not each define an abstract
1699 * method with same name and arguments but incompatible return types.
1700 * @param pos Position to be used for error reporting.
1701 * @param t1 The first argument type.
1702 * @param t2 The second argument type.
1703 */
1704 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1705 Type t1,
1706 Type t2) {
1707 return checkCompatibleAbstracts(pos, t1, t2,
1708 types.makeCompoundType(t1, t2));
1709 }
1711 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1712 Type t1,
1713 Type t2,
1714 Type site) {
1715 return firstIncompatibility(pos, t1, t2, site) == null;
1716 }
1718 /** Return the first method which is defined with same args
1719 * but different return types in two given interfaces, or null if none
1720 * exists.
1721 * @param t1 The first type.
1722 * @param t2 The second type.
1723 * @param site The most derived type.
1724 * @returns symbol from t2 that conflicts with one in t1.
1725 */
1726 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1727 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1728 closure(t1, interfaces1);
1729 Map<TypeSymbol,Type> interfaces2;
1730 if (t1 == t2)
1731 interfaces2 = interfaces1;
1732 else
1733 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1735 for (Type t3 : interfaces1.values()) {
1736 for (Type t4 : interfaces2.values()) {
1737 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1738 if (s != null) return s;
1739 }
1740 }
1741 return null;
1742 }
1744 /** Compute all the supertypes of t, indexed by type symbol. */
1745 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1746 if (t.tag != CLASS) return;
1747 if (typeMap.put(t.tsym, t) == null) {
1748 closure(types.supertype(t), typeMap);
1749 for (Type i : types.interfaces(t))
1750 closure(i, typeMap);
1751 }
1752 }
1754 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1755 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1756 if (t.tag != CLASS) return;
1757 if (typesSkip.get(t.tsym) != null) return;
1758 if (typeMap.put(t.tsym, t) == null) {
1759 closure(types.supertype(t), typesSkip, typeMap);
1760 for (Type i : types.interfaces(t))
1761 closure(i, typesSkip, typeMap);
1762 }
1763 }
1765 /** Return the first method in t2 that conflicts with a method from t1. */
1766 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1767 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1768 Symbol s1 = e1.sym;
1769 Type st1 = null;
1770 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1771 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1772 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1773 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1774 Symbol s2 = e2.sym;
1775 if (s1 == s2) continue;
1776 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1777 if (st1 == null) st1 = types.memberType(t1, s1);
1778 Type st2 = types.memberType(t2, s2);
1779 if (types.overrideEquivalent(st1, st2)) {
1780 List<Type> tvars1 = st1.getTypeArguments();
1781 List<Type> tvars2 = st2.getTypeArguments();
1782 Type rt1 = st1.getReturnType();
1783 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1784 boolean compat =
1785 types.isSameType(rt1, rt2) ||
1786 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1787 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1788 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1789 checkCommonOverriderIn(s1,s2,site);
1790 if (!compat) {
1791 log.error(pos, "types.incompatible.diff.ret",
1792 t1, t2, s2.name +
1793 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1794 return s2;
1795 }
1796 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1797 !checkCommonOverriderIn(s1, s2, site)) {
1798 log.error(pos,
1799 "name.clash.same.erasure.no.override",
1800 s1, s1.location(),
1801 s2, s2.location());
1802 return s2;
1803 }
1804 }
1805 }
1806 return null;
1807 }
1808 //WHERE
1809 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1810 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1811 Type st1 = types.memberType(site, s1);
1812 Type st2 = types.memberType(site, s2);
1813 closure(site, supertypes);
1814 for (Type t : supertypes.values()) {
1815 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1816 Symbol s3 = e.sym;
1817 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1818 Type st3 = types.memberType(site,s3);
1819 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1820 if (s3.owner == site.tsym) {
1821 return true;
1822 }
1823 List<Type> tvars1 = st1.getTypeArguments();
1824 List<Type> tvars2 = st2.getTypeArguments();
1825 List<Type> tvars3 = st3.getTypeArguments();
1826 Type rt1 = st1.getReturnType();
1827 Type rt2 = st2.getReturnType();
1828 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1829 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1830 boolean compat =
1831 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1832 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1833 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1834 if (compat)
1835 return true;
1836 }
1837 }
1838 }
1839 return false;
1840 }
1842 /** Check that a given method conforms with any method it overrides.
1843 * @param tree The tree from which positions are extracted
1844 * for errors.
1845 * @param m The overriding method.
1846 */
1847 void checkOverride(JCTree tree, MethodSymbol m) {
1848 ClassSymbol origin = (ClassSymbol)m.owner;
1849 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1850 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1851 log.error(tree.pos(), "enum.no.finalize");
1852 return;
1853 }
1854 for (Type t = origin.type; t.tag == CLASS;
1855 t = types.supertype(t)) {
1856 if (t != origin.type) {
1857 checkOverride(tree, t, origin, m);
1858 }
1859 for (Type t2 : types.interfaces(t)) {
1860 checkOverride(tree, t2, origin, m);
1861 }
1862 }
1863 }
1865 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1866 TypeSymbol c = site.tsym;
1867 Scope.Entry e = c.members().lookup(m.name);
1868 while (e.scope != null) {
1869 if (m.overrides(e.sym, origin, types, false)) {
1870 if ((e.sym.flags() & ABSTRACT) == 0) {
1871 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1872 }
1873 }
1874 e = e.next();
1875 }
1876 }
1878 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1879 ClashFilter cf = new ClashFilter(origin.type);
1880 return (cf.accepts(s1) &&
1881 cf.accepts(s2) &&
1882 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1883 }
1886 /** Check that all abstract members of given class have definitions.
1887 * @param pos Position to be used for error reporting.
1888 * @param c The class.
1889 */
1890 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1891 try {
1892 MethodSymbol undef = firstUndef(c, c);
1893 if (undef != null) {
1894 if ((c.flags() & ENUM) != 0 &&
1895 types.supertype(c.type).tsym == syms.enumSym &&
1896 (c.flags() & FINAL) == 0) {
1897 // add the ABSTRACT flag to an enum
1898 c.flags_field |= ABSTRACT;
1899 } else {
1900 MethodSymbol undef1 =
1901 new MethodSymbol(undef.flags(), undef.name,
1902 types.memberType(c.type, undef), undef.owner);
1903 log.error(pos, "does.not.override.abstract",
1904 c, undef1, undef1.location());
1905 }
1906 }
1907 } catch (CompletionFailure ex) {
1908 completionError(pos, ex);
1909 }
1910 }
1911 //where
1912 /** Return first abstract member of class `c' that is not defined
1913 * in `impl', null if there is none.
1914 */
1915 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1916 MethodSymbol undef = null;
1917 // Do not bother to search in classes that are not abstract,
1918 // since they cannot have abstract members.
1919 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1920 Scope s = c.members();
1921 for (Scope.Entry e = s.elems;
1922 undef == null && e != null;
1923 e = e.sibling) {
1924 if (e.sym.kind == MTH &&
1925 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1926 MethodSymbol absmeth = (MethodSymbol)e.sym;
1927 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1928 if (implmeth == null || implmeth == absmeth)
1929 undef = absmeth;
1930 }
1931 }
1932 if (undef == null) {
1933 Type st = types.supertype(c.type);
1934 if (st.tag == CLASS)
1935 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1936 }
1937 for (List<Type> l = types.interfaces(c.type);
1938 undef == null && l.nonEmpty();
1939 l = l.tail) {
1940 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1941 }
1942 }
1943 return undef;
1944 }
1946 void checkNonCyclicDecl(JCClassDecl tree) {
1947 CycleChecker cc = new CycleChecker();
1948 cc.scan(tree);
1949 if (!cc.errorFound && !cc.partialCheck) {
1950 tree.sym.flags_field |= ACYCLIC;
1951 }
1952 }
1954 class CycleChecker extends TreeScanner {
1956 List<Symbol> seenClasses = List.nil();
1957 boolean errorFound = false;
1958 boolean partialCheck = false;
1960 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1961 if (sym != null && sym.kind == TYP) {
1962 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1963 if (classEnv != null) {
1964 DiagnosticSource prevSource = log.currentSource();
1965 try {
1966 log.useSource(classEnv.toplevel.sourcefile);
1967 scan(classEnv.tree);
1968 }
1969 finally {
1970 log.useSource(prevSource.getFile());
1971 }
1972 } else if (sym.kind == TYP) {
1973 checkClass(pos, sym, List.<JCTree>nil());
1974 }
1975 } else {
1976 //not completed yet
1977 partialCheck = true;
1978 }
1979 }
1981 @Override
1982 public void visitSelect(JCFieldAccess tree) {
1983 super.visitSelect(tree);
1984 checkSymbol(tree.pos(), tree.sym);
1985 }
1987 @Override
1988 public void visitIdent(JCIdent tree) {
1989 checkSymbol(tree.pos(), tree.sym);
1990 }
1992 @Override
1993 public void visitTypeApply(JCTypeApply tree) {
1994 scan(tree.clazz);
1995 }
1997 @Override
1998 public void visitTypeArray(JCArrayTypeTree tree) {
1999 scan(tree.elemtype);
2000 }
2002 @Override
2003 public void visitClassDef(JCClassDecl tree) {
2004 List<JCTree> supertypes = List.nil();
2005 if (tree.getExtendsClause() != null) {
2006 supertypes = supertypes.prepend(tree.getExtendsClause());
2007 }
2008 if (tree.getImplementsClause() != null) {
2009 for (JCTree intf : tree.getImplementsClause()) {
2010 supertypes = supertypes.prepend(intf);
2011 }
2012 }
2013 checkClass(tree.pos(), tree.sym, supertypes);
2014 }
2016 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2017 if ((c.flags_field & ACYCLIC) != 0)
2018 return;
2019 if (seenClasses.contains(c)) {
2020 errorFound = true;
2021 noteCyclic(pos, (ClassSymbol)c);
2022 } else if (!c.type.isErroneous()) {
2023 try {
2024 seenClasses = seenClasses.prepend(c);
2025 if (c.type.tag == CLASS) {
2026 if (supertypes.nonEmpty()) {
2027 scan(supertypes);
2028 }
2029 else {
2030 ClassType ct = (ClassType)c.type;
2031 if (ct.supertype_field == null ||
2032 ct.interfaces_field == null) {
2033 //not completed yet
2034 partialCheck = true;
2035 return;
2036 }
2037 checkSymbol(pos, ct.supertype_field.tsym);
2038 for (Type intf : ct.interfaces_field) {
2039 checkSymbol(pos, intf.tsym);
2040 }
2041 }
2042 if (c.owner.kind == TYP) {
2043 checkSymbol(pos, c.owner);
2044 }
2045 }
2046 } finally {
2047 seenClasses = seenClasses.tail;
2048 }
2049 }
2050 }
2051 }
2053 /** Check for cyclic references. Issue an error if the
2054 * symbol of the type referred to has a LOCKED flag set.
2055 *
2056 * @param pos Position to be used for error reporting.
2057 * @param t The type referred to.
2058 */
2059 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2060 checkNonCyclicInternal(pos, t);
2061 }
2064 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2065 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2066 }
2068 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2069 final TypeVar tv;
2070 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
2071 return;
2072 if (seen.contains(t)) {
2073 tv = (TypeVar)t;
2074 tv.bound = types.createErrorType(t);
2075 log.error(pos, "cyclic.inheritance", t);
2076 } else if (t.tag == TYPEVAR) {
2077 tv = (TypeVar)t;
2078 seen = seen.prepend(tv);
2079 for (Type b : types.getBounds(tv))
2080 checkNonCyclic1(pos, b, seen);
2081 }
2082 }
2084 /** Check for cyclic references. Issue an error if the
2085 * symbol of the type referred to has a LOCKED flag set.
2086 *
2087 * @param pos Position to be used for error reporting.
2088 * @param t The type referred to.
2089 * @returns True if the check completed on all attributed classes
2090 */
2091 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2092 boolean complete = true; // was the check complete?
2093 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2094 Symbol c = t.tsym;
2095 if ((c.flags_field & ACYCLIC) != 0) return true;
2097 if ((c.flags_field & LOCKED) != 0) {
2098 noteCyclic(pos, (ClassSymbol)c);
2099 } else if (!c.type.isErroneous()) {
2100 try {
2101 c.flags_field |= LOCKED;
2102 if (c.type.tag == CLASS) {
2103 ClassType clazz = (ClassType)c.type;
2104 if (clazz.interfaces_field != null)
2105 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2106 complete &= checkNonCyclicInternal(pos, l.head);
2107 if (clazz.supertype_field != null) {
2108 Type st = clazz.supertype_field;
2109 if (st != null && st.tag == CLASS)
2110 complete &= checkNonCyclicInternal(pos, st);
2111 }
2112 if (c.owner.kind == TYP)
2113 complete &= checkNonCyclicInternal(pos, c.owner.type);
2114 }
2115 } finally {
2116 c.flags_field &= ~LOCKED;
2117 }
2118 }
2119 if (complete)
2120 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2121 if (complete) c.flags_field |= ACYCLIC;
2122 return complete;
2123 }
2125 /** Note that we found an inheritance cycle. */
2126 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2127 log.error(pos, "cyclic.inheritance", c);
2128 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2129 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2130 Type st = types.supertype(c.type);
2131 if (st.tag == CLASS)
2132 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2133 c.type = types.createErrorType(c, c.type);
2134 c.flags_field |= ACYCLIC;
2135 }
2137 /** Check that all methods which implement some
2138 * method conform to the method they implement.
2139 * @param tree The class definition whose members are checked.
2140 */
2141 void checkImplementations(JCClassDecl tree) {
2142 checkImplementations(tree, tree.sym);
2143 }
2144 //where
2145 /** Check that all methods which implement some
2146 * method in `ic' conform to the method they implement.
2147 */
2148 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2149 ClassSymbol origin = tree.sym;
2150 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2151 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2152 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2153 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2154 if (e.sym.kind == MTH &&
2155 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2156 MethodSymbol absmeth = (MethodSymbol)e.sym;
2157 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2158 if (implmeth != null && implmeth != absmeth &&
2159 (implmeth.owner.flags() & INTERFACE) ==
2160 (origin.flags() & INTERFACE)) {
2161 // don't check if implmeth is in a class, yet
2162 // origin is an interface. This case arises only
2163 // if implmeth is declared in Object. The reason is
2164 // that interfaces really don't inherit from
2165 // Object it's just that the compiler represents
2166 // things that way.
2167 checkOverride(tree, implmeth, absmeth, origin);
2168 }
2169 }
2170 }
2171 }
2172 }
2173 }
2175 /** Check that all abstract methods implemented by a class are
2176 * mutually compatible.
2177 * @param pos Position to be used for error reporting.
2178 * @param c The class whose interfaces are checked.
2179 */
2180 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2181 List<Type> supertypes = types.interfaces(c);
2182 Type supertype = types.supertype(c);
2183 if (supertype.tag == CLASS &&
2184 (supertype.tsym.flags() & ABSTRACT) != 0)
2185 supertypes = supertypes.prepend(supertype);
2186 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2187 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2188 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2189 return;
2190 for (List<Type> m = supertypes; m != l; m = m.tail)
2191 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2192 return;
2193 }
2194 checkCompatibleConcretes(pos, c);
2195 }
2197 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2198 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2199 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2200 // VM allows methods and variables with differing types
2201 if (sym.kind == e.sym.kind &&
2202 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2203 sym != e.sym &&
2204 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2205 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2206 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2207 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2208 return;
2209 }
2210 }
2211 }
2212 }
2214 /** Check that all non-override equivalent methods accessible from 'site'
2215 * are mutually compatible (JLS 8.4.8/9.4.1).
2216 *
2217 * @param pos Position to be used for error reporting.
2218 * @param site The class whose methods are checked.
2219 * @param sym The method symbol to be checked.
2220 */
2221 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2222 ClashFilter cf = new ClashFilter(site);
2223 //for each method m1 that is overridden (directly or indirectly)
2224 //by method 'sym' in 'site'...
2225 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2226 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2227 //...check each method m2 that is a member of 'site'
2228 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2229 if (m2 == m1) continue;
2230 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2231 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2232 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
2233 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2234 sym.flags_field |= CLASH;
2235 String key = m1 == sym ?
2236 "name.clash.same.erasure.no.override" :
2237 "name.clash.same.erasure.no.override.1";
2238 log.error(pos,
2239 key,
2240 sym, sym.location(),
2241 m2, m2.location(),
2242 m1, m1.location());
2243 return;
2244 }
2245 }
2246 }
2247 }
2251 /** Check that all static methods accessible from 'site' are
2252 * mutually compatible (JLS 8.4.8).
2253 *
2254 * @param pos Position to be used for error reporting.
2255 * @param site The class whose methods are checked.
2256 * @param sym The method symbol to be checked.
2257 */
2258 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2259 ClashFilter cf = new ClashFilter(site);
2260 //for each method m1 that is a member of 'site'...
2261 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2262 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2263 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2264 if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
2265 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2266 log.error(pos,
2267 "name.clash.same.erasure.no.hide",
2268 sym, sym.location(),
2269 s, s.location());
2270 return;
2271 }
2272 }
2273 }
2275 //where
2276 private class ClashFilter implements Filter<Symbol> {
2278 Type site;
2280 ClashFilter(Type site) {
2281 this.site = site;
2282 }
2284 boolean shouldSkip(Symbol s) {
2285 return (s.flags() & CLASH) != 0 &&
2286 s.owner == site.tsym;
2287 }
2289 public boolean accepts(Symbol s) {
2290 return s.kind == MTH &&
2291 (s.flags() & SYNTHETIC) == 0 &&
2292 !shouldSkip(s) &&
2293 s.isInheritedIn(site.tsym, types) &&
2294 !s.isConstructor();
2295 }
2296 }
2298 /** Report a conflict between a user symbol and a synthetic symbol.
2299 */
2300 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2301 if (!sym.type.isErroneous()) {
2302 if (warnOnSyntheticConflicts) {
2303 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2304 }
2305 else {
2306 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2307 }
2308 }
2309 }
2311 /** Check that class c does not implement directly or indirectly
2312 * the same parameterized interface with two different argument lists.
2313 * @param pos Position to be used for error reporting.
2314 * @param type The type whose interfaces are checked.
2315 */
2316 void checkClassBounds(DiagnosticPosition pos, Type type) {
2317 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2318 }
2319 //where
2320 /** Enter all interfaces of type `type' into the hash table `seensofar'
2321 * with their class symbol as key and their type as value. Make
2322 * sure no class is entered with two different types.
2323 */
2324 void checkClassBounds(DiagnosticPosition pos,
2325 Map<TypeSymbol,Type> seensofar,
2326 Type type) {
2327 if (type.isErroneous()) return;
2328 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2329 Type it = l.head;
2330 Type oldit = seensofar.put(it.tsym, it);
2331 if (oldit != null) {
2332 List<Type> oldparams = oldit.allparams();
2333 List<Type> newparams = it.allparams();
2334 if (!types.containsTypeEquivalent(oldparams, newparams))
2335 log.error(pos, "cant.inherit.diff.arg",
2336 it.tsym, Type.toString(oldparams),
2337 Type.toString(newparams));
2338 }
2339 checkClassBounds(pos, seensofar, it);
2340 }
2341 Type st = types.supertype(type);
2342 if (st != null) checkClassBounds(pos, seensofar, st);
2343 }
2345 /** Enter interface into into set.
2346 * If it existed already, issue a "repeated interface" error.
2347 */
2348 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2349 if (its.contains(it))
2350 log.error(pos, "repeated.interface");
2351 else {
2352 its.add(it);
2353 }
2354 }
2356 /* *************************************************************************
2357 * Check annotations
2358 **************************************************************************/
2360 /**
2361 * Recursively validate annotations values
2362 */
2363 void validateAnnotationTree(JCTree tree) {
2364 class AnnotationValidator extends TreeScanner {
2365 @Override
2366 public void visitAnnotation(JCAnnotation tree) {
2367 if (!tree.type.isErroneous()) {
2368 super.visitAnnotation(tree);
2369 validateAnnotation(tree);
2370 }
2371 }
2372 }
2373 tree.accept(new AnnotationValidator());
2374 }
2376 /** Annotation types are restricted to primitives, String, an
2377 * enum, an annotation, Class, Class<?>, Class<? extends
2378 * Anything>, arrays of the preceding.
2379 */
2380 void validateAnnotationType(JCTree restype) {
2381 // restype may be null if an error occurred, so don't bother validating it
2382 if (restype != null) {
2383 validateAnnotationType(restype.pos(), restype.type);
2384 }
2385 }
2387 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2388 if (type.isPrimitive()) return;
2389 if (types.isSameType(type, syms.stringType)) return;
2390 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2391 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2392 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2393 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2394 validateAnnotationType(pos, types.elemtype(type));
2395 return;
2396 }
2397 log.error(pos, "invalid.annotation.member.type");
2398 }
2400 /**
2401 * "It is also a compile-time error if any method declared in an
2402 * annotation type has a signature that is override-equivalent to
2403 * that of any public or protected method declared in class Object
2404 * or in the interface annotation.Annotation."
2405 *
2406 * @jls 9.6 Annotation Types
2407 */
2408 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2409 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2410 Scope s = sup.tsym.members();
2411 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2412 if (e.sym.kind == MTH &&
2413 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2414 types.overrideEquivalent(m.type, e.sym.type))
2415 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2416 }
2417 }
2418 }
2420 /** Check the annotations of a symbol.
2421 */
2422 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2423 for (JCAnnotation a : annotations)
2424 validateAnnotation(a, s);
2425 }
2427 /** Check an annotation of a symbol.
2428 */
2429 private void validateAnnotation(JCAnnotation a, Symbol s) {
2430 validateAnnotationTree(a);
2432 if (!annotationApplicable(a, s))
2433 log.error(a.pos(), "annotation.type.not.applicable");
2435 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2436 if (!isOverrider(s))
2437 log.error(a.pos(), "method.does.not.override.superclass");
2438 }
2439 }
2441 /**
2442 * Validate the proposed container 'containedBy' on the
2443 * annotation type symbol 's'. Report errors at position
2444 * 'pos'.
2445 *
2446 * @param s The (annotation)type declaration annotated with a @ContainedBy
2447 * @param containerAnno the @ContainedBy on 's'
2448 * @param pos where to report errors
2449 */
2450 public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
2451 Assert.check(types.isSameType(containedBy.type, syms.containedByType));
2453 Type t = null;
2454 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2455 if (!l.isEmpty()) {
2456 Assert.check(l.head.fst.name == names.value);
2457 t = ((Attribute.Class)l.head.snd).getValue();
2458 }
2460 if (t == null) {
2461 log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
2462 return;
2463 }
2465 validateHasContainerFor(t.tsym, s, pos);
2466 validateRetention(t.tsym, s, pos);
2467 validateDocumented(t.tsym, s, pos);
2468 validateInherited(t.tsym, s, pos);
2469 validateTarget(t.tsym, s, pos);
2470 }
2472 /**
2473 * Validate the proposed container 'containerFor' on the
2474 * annotation type symbol 's'. Report errors at position
2475 * 'pos'.
2476 *
2477 * @param s The (annotation)type declaration annotated with a @ContainerFor
2478 * @param containerFor the @ContainedFor on 's'
2479 * @param pos where to report errors
2480 */
2481 public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
2482 Assert.check(types.isSameType(containerFor.type, syms.containerForType));
2484 Type t = null;
2485 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2486 if (!l.isEmpty()) {
2487 Assert.check(l.head.fst.name == names.value);
2488 t = ((Attribute.Class)l.head.snd).getValue();
2489 }
2491 if (t == null) {
2492 log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
2493 return;
2494 }
2496 validateHasContainedBy(t.tsym, s, pos);
2497 }
2499 private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2500 Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
2502 if (containedBy == null) {
2503 log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
2504 return;
2505 }
2507 Type t = null;
2508 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2509 if (!l.isEmpty()) {
2510 Assert.check(l.head.fst.name == names.value);
2511 t = ((Attribute.Class)l.head.snd).getValue();
2512 }
2514 if (t == null) {
2515 log.error(pos, "invalid.container.wrong.containedby", container, contained);
2516 return;
2517 }
2519 if (!types.isSameType(t, contained.type))
2520 log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
2521 }
2523 private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2524 Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
2526 if (containerFor == null) {
2527 log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
2528 return;
2529 }
2531 Type t = null;
2532 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2533 if (!l.isEmpty()) {
2534 Assert.check(l.head.fst.name == names.value);
2535 t = ((Attribute.Class)l.head.snd).getValue();
2536 }
2538 if (t == null) {
2539 log.error(pos, "invalid.container.wrong.containerfor", container, contained);
2540 return;
2541 }
2543 if (!types.isSameType(t, contained.type))
2544 log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
2545 }
2547 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2548 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2549 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2551 boolean error = false;
2552 switch (containedRetention) {
2553 case RUNTIME:
2554 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2555 error = true;
2556 }
2557 break;
2558 case CLASS:
2559 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2560 error = true;
2561 }
2562 }
2563 if (error ) {
2564 log.error(pos, "invalid.containedby.annotation.retention",
2565 container, containerRetention,
2566 contained, containedRetention);
2567 }
2568 }
2570 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2571 if (contained.attribute(syms.documentedType.tsym) != null) {
2572 if (container.attribute(syms.documentedType.tsym) == null) {
2573 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
2574 }
2575 }
2576 }
2578 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2579 if (contained.attribute(syms.inheritedType.tsym) != null) {
2580 if (container.attribute(syms.inheritedType.tsym) == null) {
2581 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
2582 }
2583 }
2584 }
2586 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2587 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2589 // If contained has no Target, we are done
2590 if (containedTarget == null) {
2591 return;
2592 }
2594 // If contained has Target m1, container must have a Target
2595 // annotation, m2, and m2 must be a subset of m1. (This is
2596 // trivially true if contained has no target as per above).
2598 // contained has target, but container has not, error
2599 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2600 if (containerTarget == null) {
2601 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2602 return;
2603 }
2605 Set<Name> containerTargets = new HashSet<Name>();
2606 for (Attribute app : containerTarget.values) {
2607 if (!(app instanceof Attribute.Enum)) {
2608 continue; // recovery
2609 }
2610 Attribute.Enum e = (Attribute.Enum)app;
2611 containerTargets.add(e.value.name);
2612 }
2614 Set<Name> containedTargets = new HashSet<Name>();
2615 for (Attribute app : containedTarget.values) {
2616 if (!(app instanceof Attribute.Enum)) {
2617 continue; // recovery
2618 }
2619 Attribute.Enum e = (Attribute.Enum)app;
2620 containedTargets.add(e.value.name);
2621 }
2623 if (!isTargetSubset(containedTargets, containerTargets)) {
2624 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2625 }
2626 }
2628 /** Checks that t is a subset of s, with respect to ElementType
2629 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2630 */
2631 private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
2632 // Check that all elements in t are present in s
2633 for (Name n2 : t) {
2634 boolean currentElementOk = false;
2635 for (Name n1 : s) {
2636 if (n1 == n2) {
2637 currentElementOk = true;
2638 break;
2639 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2640 currentElementOk = true;
2641 break;
2642 }
2643 }
2644 if (!currentElementOk)
2645 return false;
2646 }
2647 return true;
2648 }
2650 /** Is s a method symbol that overrides a method in a superclass? */
2651 boolean isOverrider(Symbol s) {
2652 if (s.kind != MTH || s.isStatic())
2653 return false;
2654 MethodSymbol m = (MethodSymbol)s;
2655 TypeSymbol owner = (TypeSymbol)m.owner;
2656 for (Type sup : types.closure(owner.type)) {
2657 if (sup == owner.type)
2658 continue; // skip "this"
2659 Scope scope = sup.tsym.members();
2660 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2661 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2662 return true;
2663 }
2664 }
2665 return false;
2666 }
2668 /** Is the annotation applicable to the symbol? */
2669 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2670 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2671 if (arr == null) {
2672 return true;
2673 }
2674 for (Attribute app : arr.values) {
2675 if (!(app instanceof Attribute.Enum)) return true; // recovery
2676 Attribute.Enum e = (Attribute.Enum) app;
2677 if (e.value.name == names.TYPE)
2678 { if (s.kind == TYP) return true; }
2679 else if (e.value.name == names.FIELD)
2680 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2681 else if (e.value.name == names.METHOD)
2682 { if (s.kind == MTH && !s.isConstructor()) return true; }
2683 else if (e.value.name == names.PARAMETER)
2684 { if (s.kind == VAR &&
2685 s.owner.kind == MTH &&
2686 (s.flags() & PARAMETER) != 0)
2687 return true;
2688 }
2689 else if (e.value.name == names.CONSTRUCTOR)
2690 { if (s.kind == MTH && s.isConstructor()) return true; }
2691 else if (e.value.name == names.LOCAL_VARIABLE)
2692 { if (s.kind == VAR && s.owner.kind == MTH &&
2693 (s.flags() & PARAMETER) == 0)
2694 return true;
2695 }
2696 else if (e.value.name == names.ANNOTATION_TYPE)
2697 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2698 return true;
2699 }
2700 else if (e.value.name == names.PACKAGE)
2701 { if (s.kind == PCK) return true; }
2702 else if (e.value.name == names.TYPE_USE)
2703 { if (s.kind == TYP ||
2704 s.kind == VAR ||
2705 (s.kind == MTH && !s.isConstructor() &&
2706 s.type.getReturnType().tag != VOID))
2707 return true;
2708 }
2709 else
2710 return true; // recovery
2711 }
2712 return false;
2713 }
2716 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2717 Attribute.Compound atTarget =
2718 s.attribute(syms.annotationTargetType.tsym);
2719 if (atTarget == null) return null; // ok, is applicable
2720 Attribute atValue = atTarget.member(names.value);
2721 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2722 return (Attribute.Array) atValue;
2723 }
2725 /** Check an annotation value.
2726 */
2727 public void validateAnnotation(JCAnnotation a) {
2728 // collect an inventory of the members (sorted alphabetically)
2729 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2730 public int compare(Symbol t, Symbol t1) {
2731 return t.name.compareTo(t1.name);
2732 }
2733 });
2734 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2735 e != null;
2736 e = e.sibling)
2737 if (e.sym.kind == MTH)
2738 members.add((MethodSymbol) e.sym);
2740 // count them off as they're annotated
2741 for (JCTree arg : a.args) {
2742 if (!arg.hasTag(ASSIGN)) continue; // recovery
2743 JCAssign assign = (JCAssign) arg;
2744 Symbol m = TreeInfo.symbol(assign.lhs);
2745 if (m == null || m.type.isErroneous()) continue;
2746 if (!members.remove(m))
2747 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2748 m.name, a.type);
2749 }
2751 // all the remaining ones better have default values
2752 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2753 for (MethodSymbol m : members) {
2754 if (m.defaultValue == null && !m.type.isErroneous()) {
2755 missingDefaults.append(m.name);
2756 }
2757 }
2758 if (missingDefaults.nonEmpty()) {
2759 String key = (missingDefaults.size() > 1)
2760 ? "annotation.missing.default.value.1"
2761 : "annotation.missing.default.value";
2762 log.error(a.pos(), key, a.type, missingDefaults);
2763 }
2765 // special case: java.lang.annotation.Target must not have
2766 // repeated values in its value member
2767 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2768 a.args.tail == null)
2769 return;
2771 if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
2772 JCAssign assign = (JCAssign) a.args.head;
2773 Symbol m = TreeInfo.symbol(assign.lhs);
2774 if (m.name != names.value) return;
2775 JCTree rhs = assign.rhs;
2776 if (!rhs.hasTag(NEWARRAY)) return;
2777 JCNewArray na = (JCNewArray) rhs;
2778 Set<Symbol> targets = new HashSet<Symbol>();
2779 for (JCTree elem : na.elems) {
2780 if (!targets.add(TreeInfo.symbol(elem))) {
2781 log.error(elem.pos(), "repeated.annotation.target");
2782 }
2783 }
2784 }
2786 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2787 if (allowAnnotations &&
2788 lint.isEnabled(LintCategory.DEP_ANN) &&
2789 (s.flags() & DEPRECATED) != 0 &&
2790 !syms.deprecatedType.isErroneous() &&
2791 s.attribute(syms.deprecatedType.tsym) == null) {
2792 log.warning(LintCategory.DEP_ANN,
2793 pos, "missing.deprecated.annotation");
2794 }
2795 }
2797 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2798 if ((s.flags() & DEPRECATED) != 0 &&
2799 (other.flags() & DEPRECATED) == 0 &&
2800 s.outermostClass() != other.outermostClass()) {
2801 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2802 @Override
2803 public void report() {
2804 warnDeprecated(pos, s);
2805 }
2806 });
2807 }
2808 }
2810 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2811 if ((s.flags() & PROPRIETARY) != 0) {
2812 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2813 public void report() {
2814 if (enableSunApiLintControl)
2815 warnSunApi(pos, "sun.proprietary", s);
2816 else
2817 log.mandatoryWarning(pos, "sun.proprietary", s);
2818 }
2819 });
2820 }
2821 }
2823 /* *************************************************************************
2824 * Check for recursive annotation elements.
2825 **************************************************************************/
2827 /** Check for cycles in the graph of annotation elements.
2828 */
2829 void checkNonCyclicElements(JCClassDecl tree) {
2830 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2831 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2832 try {
2833 tree.sym.flags_field |= LOCKED;
2834 for (JCTree def : tree.defs) {
2835 if (!def.hasTag(METHODDEF)) continue;
2836 JCMethodDecl meth = (JCMethodDecl)def;
2837 checkAnnotationResType(meth.pos(), meth.restype.type);
2838 }
2839 } finally {
2840 tree.sym.flags_field &= ~LOCKED;
2841 tree.sym.flags_field |= ACYCLIC_ANN;
2842 }
2843 }
2845 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2846 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2847 return;
2848 if ((tsym.flags_field & LOCKED) != 0) {
2849 log.error(pos, "cyclic.annotation.element");
2850 return;
2851 }
2852 try {
2853 tsym.flags_field |= LOCKED;
2854 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2855 Symbol s = e.sym;
2856 if (s.kind != Kinds.MTH)
2857 continue;
2858 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2859 }
2860 } finally {
2861 tsym.flags_field &= ~LOCKED;
2862 tsym.flags_field |= ACYCLIC_ANN;
2863 }
2864 }
2866 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2867 switch (type.tag) {
2868 case TypeTags.CLASS:
2869 if ((type.tsym.flags() & ANNOTATION) != 0)
2870 checkNonCyclicElementsInternal(pos, type.tsym);
2871 break;
2872 case TypeTags.ARRAY:
2873 checkAnnotationResType(pos, types.elemtype(type));
2874 break;
2875 default:
2876 break; // int etc
2877 }
2878 }
2880 /* *************************************************************************
2881 * Check for cycles in the constructor call graph.
2882 **************************************************************************/
2884 /** Check for cycles in the graph of constructors calling other
2885 * constructors.
2886 */
2887 void checkCyclicConstructors(JCClassDecl tree) {
2888 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2890 // enter each constructor this-call into the map
2891 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2892 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2893 if (app == null) continue;
2894 JCMethodDecl meth = (JCMethodDecl) l.head;
2895 if (TreeInfo.name(app.meth) == names._this) {
2896 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2897 } else {
2898 meth.sym.flags_field |= ACYCLIC;
2899 }
2900 }
2902 // Check for cycles in the map
2903 Symbol[] ctors = new Symbol[0];
2904 ctors = callMap.keySet().toArray(ctors);
2905 for (Symbol caller : ctors) {
2906 checkCyclicConstructor(tree, caller, callMap);
2907 }
2908 }
2910 /** Look in the map to see if the given constructor is part of a
2911 * call cycle.
2912 */
2913 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2914 Map<Symbol,Symbol> callMap) {
2915 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2916 if ((ctor.flags_field & LOCKED) != 0) {
2917 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2918 "recursive.ctor.invocation");
2919 } else {
2920 ctor.flags_field |= LOCKED;
2921 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2922 ctor.flags_field &= ~LOCKED;
2923 }
2924 ctor.flags_field |= ACYCLIC;
2925 }
2926 }
2928 /* *************************************************************************
2929 * Miscellaneous
2930 **************************************************************************/
2932 /**
2933 * Return the opcode of the operator but emit an error if it is an
2934 * error.
2935 * @param pos position for error reporting.
2936 * @param operator an operator
2937 * @param tag a tree tag
2938 * @param left type of left hand side
2939 * @param right type of right hand side
2940 */
2941 int checkOperator(DiagnosticPosition pos,
2942 OperatorSymbol operator,
2943 JCTree.Tag tag,
2944 Type left,
2945 Type right) {
2946 if (operator.opcode == ByteCodes.error) {
2947 log.error(pos,
2948 "operator.cant.be.applied.1",
2949 treeinfo.operatorName(tag),
2950 left, right);
2951 }
2952 return operator.opcode;
2953 }
2956 /**
2957 * Check for division by integer constant zero
2958 * @param pos Position for error reporting.
2959 * @param operator The operator for the expression
2960 * @param operand The right hand operand for the expression
2961 */
2962 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2963 if (operand.constValue() != null
2964 && lint.isEnabled(LintCategory.DIVZERO)
2965 && operand.tag <= LONG
2966 && ((Number) (operand.constValue())).longValue() == 0) {
2967 int opc = ((OperatorSymbol)operator).opcode;
2968 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2969 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2970 log.warning(LintCategory.DIVZERO, pos, "div.zero");
2971 }
2972 }
2973 }
2975 /**
2976 * Check for empty statements after if
2977 */
2978 void checkEmptyIf(JCIf tree) {
2979 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
2980 lint.isEnabled(LintCategory.EMPTY))
2981 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
2982 }
2984 /** Check that symbol is unique in given scope.
2985 * @param pos Position for error reporting.
2986 * @param sym The symbol.
2987 * @param s The scope.
2988 */
2989 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2990 if (sym.type.isErroneous())
2991 return true;
2992 if (sym.owner.name == names.any) return false;
2993 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2994 if (sym != e.sym &&
2995 (e.sym.flags() & CLASH) == 0 &&
2996 sym.kind == e.sym.kind &&
2997 sym.name != names.error &&
2998 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2999 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3000 varargsDuplicateError(pos, sym, e.sym);
3001 return true;
3002 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3003 duplicateErasureError(pos, sym, e.sym);
3004 sym.flags_field |= CLASH;
3005 return true;
3006 } else {
3007 duplicateError(pos, e.sym);
3008 return false;
3009 }
3010 }
3011 }
3012 return true;
3013 }
3015 /** Report duplicate declaration error.
3016 */
3017 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3018 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3019 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3020 }
3021 }
3023 /** Check that single-type import is not already imported or top-level defined,
3024 * but make an exception for two single-type imports which denote the same type.
3025 * @param pos Position for error reporting.
3026 * @param sym The symbol.
3027 * @param s The scope
3028 */
3029 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3030 return checkUniqueImport(pos, sym, s, false);
3031 }
3033 /** Check that static single-type import is not already imported or top-level defined,
3034 * but make an exception for two single-type imports which denote the same type.
3035 * @param pos Position for error reporting.
3036 * @param sym The symbol.
3037 * @param s The scope
3038 * @param staticImport Whether or not this was a static import
3039 */
3040 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3041 return checkUniqueImport(pos, sym, s, true);
3042 }
3044 /** Check that single-type import is not already imported or top-level defined,
3045 * but make an exception for two single-type imports which denote the same type.
3046 * @param pos Position for error reporting.
3047 * @param sym The symbol.
3048 * @param s The scope.
3049 * @param staticImport Whether or not this was a static import
3050 */
3051 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3052 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3053 // is encountered class entered via a class declaration?
3054 boolean isClassDecl = e.scope == s;
3055 if ((isClassDecl || sym != e.sym) &&
3056 sym.kind == e.sym.kind &&
3057 sym.name != names.error) {
3058 if (!e.sym.type.isErroneous()) {
3059 String what = e.sym.toString();
3060 if (!isClassDecl) {
3061 if (staticImport)
3062 log.error(pos, "already.defined.static.single.import", what);
3063 else
3064 log.error(pos, "already.defined.single.import", what);
3065 }
3066 else if (sym != e.sym)
3067 log.error(pos, "already.defined.this.unit", what);
3068 }
3069 return false;
3070 }
3071 }
3072 return true;
3073 }
3075 /** Check that a qualified name is in canonical form (for import decls).
3076 */
3077 public void checkCanonical(JCTree tree) {
3078 if (!isCanonical(tree))
3079 log.error(tree.pos(), "import.requires.canonical",
3080 TreeInfo.symbol(tree));
3081 }
3082 // where
3083 private boolean isCanonical(JCTree tree) {
3084 while (tree.hasTag(SELECT)) {
3085 JCFieldAccess s = (JCFieldAccess) tree;
3086 if (s.sym.owner != TreeInfo.symbol(s.selected))
3087 return false;
3088 tree = s.selected;
3089 }
3090 return true;
3091 }
3093 private class ConversionWarner extends Warner {
3094 final String uncheckedKey;
3095 final Type found;
3096 final Type expected;
3097 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3098 super(pos);
3099 this.uncheckedKey = uncheckedKey;
3100 this.found = found;
3101 this.expected = expected;
3102 }
3104 @Override
3105 public void warn(LintCategory lint) {
3106 boolean warned = this.warned;
3107 super.warn(lint);
3108 if (warned) return; // suppress redundant diagnostics
3109 switch (lint) {
3110 case UNCHECKED:
3111 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3112 break;
3113 case VARARGS:
3114 if (method != null &&
3115 method.attribute(syms.trustMeType.tsym) != null &&
3116 isTrustMeAllowedOnMethod(method) &&
3117 !types.isReifiable(method.type.getParameterTypes().last())) {
3118 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3119 }
3120 break;
3121 default:
3122 throw new AssertionError("Unexpected lint: " + lint);
3123 }
3124 }
3125 }
3127 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3128 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3129 }
3131 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3132 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3133 }
3134 }