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