Sat, 18 Sep 2010 14:24:09 -0700
6863465: javac doesn't detect circular subclass dependencies via qualified names
Summary: class inheritance circularity check should look at trees, not just symbols
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2009, 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 com.sun.source.tree.AssignmentTree;
29 import java.util.*;
30 import java.util.Set;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.jvm.*;
34 import com.sun.tools.javac.tree.*;
35 import com.sun.tools.javac.util.*;
36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
37 import com.sun.tools.javac.util.List;
39 import com.sun.tools.javac.tree.JCTree.*;
40 import com.sun.tools.javac.code.Lint;
41 import com.sun.tools.javac.code.Lint.LintCategory;
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.code.Symbol.*;
45 import static com.sun.tools.javac.code.Flags.*;
46 import static com.sun.tools.javac.code.Kinds.*;
47 import static com.sun.tools.javac.code.TypeTags.*;
49 /** Type checking helper class for the attribution phase.
50 *
51 * <p><b>This is NOT part of any supported API.
52 * If you write code that depends on this, you do so at your own risk.
53 * This code and its internal interfaces are subject to change or
54 * deletion without notice.</b>
55 */
56 public class Check {
57 protected static final Context.Key<Check> checkKey =
58 new Context.Key<Check>();
60 private final Names names;
61 private final Log log;
62 private final Symtab syms;
63 private final Enter enter;
64 private final Infer infer;
65 private final Types types;
66 private final JCDiagnostic.Factory diags;
67 private final boolean skipAnnotations;
68 private boolean warnOnSyntheticConflicts;
69 private boolean suppressAbortOnBadClassFile;
70 private final TreeInfo treeinfo;
72 // The set of lint options currently in effect. It is initialized
73 // from the context, and then is set/reset as needed by Attr as it
74 // visits all the various parts of the trees during attribution.
75 private Lint lint;
77 public static Check instance(Context context) {
78 Check instance = context.get(checkKey);
79 if (instance == null)
80 instance = new Check(context);
81 return instance;
82 }
84 protected Check(Context context) {
85 context.put(checkKey, this);
87 names = Names.instance(context);
88 log = Log.instance(context);
89 syms = Symtab.instance(context);
90 enter = Enter.instance(context);
91 infer = Infer.instance(context);
92 this.types = Types.instance(context);
93 diags = JCDiagnostic.Factory.instance(context);
94 Options options = Options.instance(context);
95 lint = Lint.instance(context);
96 treeinfo = TreeInfo.instance(context);
98 Source source = Source.instance(context);
99 allowGenerics = source.allowGenerics();
100 allowAnnotations = source.allowAnnotations();
101 allowCovariantReturns = source.allowCovariantReturns();
102 complexInference = options.get("-complexinference") != null;
103 skipAnnotations = options.get("skipAnnotations") != null;
104 warnOnSyntheticConflicts = options.get("warnOnSyntheticConflicts") != null;
105 suppressAbortOnBadClassFile = options.get("suppressAbortOnBadClassFile") != null;
107 Target target = Target.instance(context);
108 syntheticNameChar = target.syntheticNameChar();
110 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
111 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
112 boolean verboseVarargs = lint.isEnabled(LintCategory.VARARGS);
113 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
114 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
116 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
117 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
118 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
119 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
120 unsafeVarargsHandler = new MandatoryWarningHandler(log, verboseVarargs,
121 enforceMandatoryWarnings, "varargs", LintCategory.VARARGS);
122 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
123 enforceMandatoryWarnings, "sunapi", null);
124 }
126 /** Switch: generics enabled?
127 */
128 boolean allowGenerics;
130 /** Switch: annotations enabled?
131 */
132 boolean allowAnnotations;
134 /** Switch: covariant returns enabled?
135 */
136 boolean allowCovariantReturns;
138 /** Switch: -complexinference option set?
139 */
140 boolean complexInference;
142 /** Character for synthetic names
143 */
144 char syntheticNameChar;
146 /** A table mapping flat names of all compiled classes in this run to their
147 * symbols; maintained from outside.
148 */
149 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
151 /** A handler for messages about deprecated usage.
152 */
153 private MandatoryWarningHandler deprecationHandler;
155 /** A handler for messages about unchecked or unsafe usage.
156 */
157 private MandatoryWarningHandler uncheckedHandler;
159 /** A handler for messages about unchecked or unsafe vararg method decl.
160 */
161 private MandatoryWarningHandler unsafeVarargsHandler;
163 /** A handler for messages about using proprietary API.
164 */
165 private MandatoryWarningHandler sunApiHandler;
167 /* *************************************************************************
168 * Errors and Warnings
169 **************************************************************************/
171 Lint setLint(Lint newLint) {
172 Lint prev = lint;
173 lint = newLint;
174 return prev;
175 }
177 /** Warn about deprecated symbol.
178 * @param pos Position to be used for error reporting.
179 * @param sym The deprecated symbol.
180 */
181 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
182 if (!lint.isSuppressed(LintCategory.DEPRECATION))
183 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
184 }
186 /** Warn about unchecked operation.
187 * @param pos Position to be used for error reporting.
188 * @param msg A string describing the problem.
189 */
190 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
191 if (!lint.isSuppressed(LintCategory.UNCHECKED))
192 uncheckedHandler.report(pos, msg, args);
193 }
195 /** Warn about unsafe vararg method decl.
196 * @param pos Position to be used for error reporting.
197 * @param sym The deprecated symbol.
198 */
199 void warnUnsafeVararg(DiagnosticPosition pos, Type elemType) {
200 if (!lint.isSuppressed(LintCategory.VARARGS))
201 unsafeVarargsHandler.report(pos, "varargs.non.reifiable.type", elemType);
202 }
204 /** Warn about using proprietary API.
205 * @param pos Position to be used for error reporting.
206 * @param msg A string describing the problem.
207 */
208 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
209 if (!lint.isSuppressed(LintCategory.SUNAPI))
210 sunApiHandler.report(pos, msg, args);
211 }
213 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
214 if (lint.isEnabled(LintCategory.STATIC))
215 log.warning(LintCategory.STATIC, pos, msg, args);
216 }
218 /**
219 * Report any deferred diagnostics.
220 */
221 public void reportDeferredDiagnostics() {
222 deprecationHandler.reportDeferredDiagnostic();
223 uncheckedHandler.reportDeferredDiagnostic();
224 unsafeVarargsHandler.reportDeferredDiagnostic();
225 sunApiHandler.reportDeferredDiagnostic();
226 }
229 /** Report a failure to complete a class.
230 * @param pos Position to be used for error reporting.
231 * @param ex The failure to report.
232 */
233 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
234 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
235 if (ex instanceof ClassReader.BadClassFile
236 && !suppressAbortOnBadClassFile) throw new Abort();
237 else return syms.errType;
238 }
240 /** Report a type error.
241 * @param pos Position to be used for error reporting.
242 * @param problem A string describing the error.
243 * @param found The type that was found.
244 * @param req The type that was required.
245 */
246 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
247 log.error(pos, "prob.found.req",
248 problem, found, req);
249 return types.createErrorType(found);
250 }
252 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
253 log.error(pos, "prob.found.req.1", problem, found, req, explanation);
254 return types.createErrorType(found);
255 }
257 /** Report an error that wrong type tag was found.
258 * @param pos Position to be used for error reporting.
259 * @param required An internationalized string describing the type tag
260 * required.
261 * @param found The type that was found.
262 */
263 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
264 // this error used to be raised by the parser,
265 // but has been delayed to this point:
266 if (found instanceof Type && ((Type)found).tag == VOID) {
267 log.error(pos, "illegal.start.of.type");
268 return syms.errType;
269 }
270 log.error(pos, "type.found.req", found, required);
271 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
272 }
274 /** Report an error that symbol cannot be referenced before super
275 * has been called.
276 * @param pos Position to be used for error reporting.
277 * @param sym The referenced symbol.
278 */
279 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
280 log.error(pos, "cant.ref.before.ctor.called", sym);
281 }
283 /** Report duplicate declaration error.
284 */
285 void duplicateError(DiagnosticPosition pos, Symbol sym) {
286 if (!sym.type.isErroneous()) {
287 log.error(pos, "already.defined", sym, sym.location());
288 }
289 }
291 /** Report array/varargs duplicate declaration
292 */
293 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
294 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
295 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
296 }
297 }
299 /* ************************************************************************
300 * duplicate declaration checking
301 *************************************************************************/
303 /** Check that variable does not hide variable with same name in
304 * immediately enclosing local scope.
305 * @param pos Position for error reporting.
306 * @param v The symbol.
307 * @param s The scope.
308 */
309 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
310 if (s.next != null) {
311 for (Scope.Entry e = s.next.lookup(v.name);
312 e.scope != null && e.sym.owner == v.owner;
313 e = e.next()) {
314 if (e.sym.kind == VAR &&
315 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
316 v.name != names.error) {
317 duplicateError(pos, e.sym);
318 return;
319 }
320 }
321 }
322 }
324 /** Check that a class or interface does not hide a class or
325 * interface with same name in immediately enclosing local scope.
326 * @param pos Position for error reporting.
327 * @param c The symbol.
328 * @param s The scope.
329 */
330 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
331 if (s.next != null) {
332 for (Scope.Entry e = s.next.lookup(c.name);
333 e.scope != null && e.sym.owner == c.owner;
334 e = e.next()) {
335 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
336 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
337 c.name != names.error) {
338 duplicateError(pos, e.sym);
339 return;
340 }
341 }
342 }
343 }
345 /** Check that class does not have the same name as one of
346 * its enclosing classes, or as a class defined in its enclosing scope.
347 * return true if class is unique in its enclosing scope.
348 * @param pos Position for error reporting.
349 * @param name The class name.
350 * @param s The enclosing scope.
351 */
352 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
353 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
354 if (e.sym.kind == TYP && e.sym.name != names.error) {
355 duplicateError(pos, e.sym);
356 return false;
357 }
358 }
359 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
360 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
361 duplicateError(pos, sym);
362 return true;
363 }
364 }
365 return true;
366 }
368 /* *************************************************************************
369 * Class name generation
370 **************************************************************************/
372 /** Return name of local class.
373 * This is of the form <enclClass> $ n <classname>
374 * where
375 * enclClass is the flat name of the enclosing class,
376 * classname is the simple name of the local class
377 */
378 Name localClassName(ClassSymbol c) {
379 for (int i=1; ; i++) {
380 Name flatname = names.
381 fromString("" + c.owner.enclClass().flatname +
382 syntheticNameChar + i +
383 c.name);
384 if (compiled.get(flatname) == null) return flatname;
385 }
386 }
388 /* *************************************************************************
389 * Type Checking
390 **************************************************************************/
392 /** Check that a given type is assignable to a given proto-type.
393 * If it is, return the type, otherwise return errType.
394 * @param pos Position to be used for error reporting.
395 * @param found The type that was found.
396 * @param req The type that was required.
397 */
398 Type checkType(DiagnosticPosition pos, Type found, Type req) {
399 return checkType(pos, found, req, "incompatible.types");
400 }
402 Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
403 if (req.tag == ERROR)
404 return req;
405 if (found.tag == FORALL)
406 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
407 if (req.tag == NONE)
408 return found;
409 if (types.isAssignable(found, req, convertWarner(pos, found, req)))
410 return found;
411 if (found.tag <= DOUBLE && req.tag <= DOUBLE)
412 return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
413 if (found.isSuperBound()) {
414 log.error(pos, "assignment.from.super-bound", found);
415 return types.createErrorType(found);
416 }
417 if (req.isExtendsBound()) {
418 log.error(pos, "assignment.to.extends-bound", req);
419 return types.createErrorType(found);
420 }
421 return typeError(pos, diags.fragment(errKey), found, req);
422 }
424 /** Instantiate polymorphic type to some prototype, unless
425 * prototype is `anyPoly' in which case polymorphic type
426 * is returned unchanged.
427 */
428 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
429 if (pt == Infer.anyPoly && complexInference) {
430 return t;
431 } else if (pt == Infer.anyPoly || pt.tag == NONE) {
432 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
433 return instantiatePoly(pos, t, newpt, warn);
434 } else if (pt.tag == ERROR) {
435 return pt;
436 } else {
437 try {
438 return infer.instantiateExpr(t, pt, warn);
439 } catch (Infer.NoInstanceException ex) {
440 if (ex.isAmbiguous) {
441 JCDiagnostic d = ex.getDiagnostic();
442 log.error(pos,
443 "undetermined.type" + (d!=null ? ".1" : ""),
444 t, d);
445 return types.createErrorType(pt);
446 } else {
447 JCDiagnostic d = ex.getDiagnostic();
448 return typeError(pos,
449 diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
450 t, pt);
451 }
452 } catch (Infer.InvalidInstanceException ex) {
453 JCDiagnostic d = ex.getDiagnostic();
454 log.error(pos, "invalid.inferred.types", t.tvars, d);
455 return types.createErrorType(pt);
456 }
457 }
458 }
460 /** Check that a given type can be cast to a given target type.
461 * Return the result of the cast.
462 * @param pos Position to be used for error reporting.
463 * @param found The type that is being cast.
464 * @param req The target type of the cast.
465 */
466 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
467 if (found.tag == FORALL) {
468 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
469 return req;
470 } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
471 return req;
472 } else {
473 return typeError(pos,
474 diags.fragment("inconvertible.types"),
475 found, req);
476 }
477 }
478 //where
479 /** Is type a type variable, or a (possibly multi-dimensional) array of
480 * type variables?
481 */
482 boolean isTypeVar(Type t) {
483 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
484 }
486 /** Check that a type is within some bounds.
487 *
488 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
489 * type argument.
490 * @param pos Position to be used for error reporting.
491 * @param a The type that should be bounded by bs.
492 * @param bs The bound.
493 */
494 private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
495 if (a.isUnbound()) {
496 return;
497 } else if (a.tag != WILDCARD) {
498 a = types.upperBound(a);
499 for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
500 if (!types.isSubtype(a, l.head)) {
501 log.error(pos, "not.within.bounds", a);
502 return;
503 }
504 }
505 } else if (a.isExtendsBound()) {
506 if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
507 log.error(pos, "not.within.bounds", a);
508 } else if (a.isSuperBound()) {
509 if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
510 log.error(pos, "not.within.bounds", a);
511 }
512 }
514 /** Check that a type is within some bounds.
515 *
516 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
517 * type argument.
518 * @param pos Position to be used for error reporting.
519 * @param a The type that should be bounded by bs.
520 * @param bs The bound.
521 */
522 private void checkCapture(JCTypeApply tree) {
523 List<JCExpression> args = tree.getTypeArguments();
524 for (Type arg : types.capture(tree.type).getTypeArguments()) {
525 if (arg.tag == TYPEVAR && arg.getUpperBound().isErroneous()) {
526 log.error(args.head.pos, "not.within.bounds", args.head.type);
527 break;
528 }
529 args = args.tail;
530 }
531 }
533 /** Check that type is different from 'void'.
534 * @param pos Position to be used for error reporting.
535 * @param t The type to be checked.
536 */
537 Type checkNonVoid(DiagnosticPosition pos, Type t) {
538 if (t.tag == VOID) {
539 log.error(pos, "void.not.allowed.here");
540 return types.createErrorType(t);
541 } else {
542 return t;
543 }
544 }
546 /** Check that type is a class or interface type.
547 * @param pos Position to be used for error reporting.
548 * @param t The type to be checked.
549 */
550 Type checkClassType(DiagnosticPosition pos, Type t) {
551 if (t.tag != CLASS && t.tag != ERROR)
552 return typeTagError(pos,
553 diags.fragment("type.req.class"),
554 (t.tag == TYPEVAR)
555 ? diags.fragment("type.parameter", t)
556 : t);
557 else
558 return t;
559 }
561 /** Check that type is a class or interface type.
562 * @param pos Position to be used for error reporting.
563 * @param t The type to be checked.
564 * @param noBounds True if type bounds are illegal here.
565 */
566 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
567 t = checkClassType(pos, t);
568 if (noBounds && t.isParameterized()) {
569 List<Type> args = t.getTypeArguments();
570 while (args.nonEmpty()) {
571 if (args.head.tag == WILDCARD)
572 return typeTagError(pos,
573 diags.fragment("type.req.exact"),
574 args.head);
575 args = args.tail;
576 }
577 }
578 return t;
579 }
581 /** Check that type is a reifiable class, interface or array type.
582 * @param pos Position to be used for error reporting.
583 * @param t The type to be checked.
584 */
585 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
586 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
587 return typeTagError(pos,
588 diags.fragment("type.req.class.array"),
589 t);
590 } else if (!types.isReifiable(t)) {
591 log.error(pos, "illegal.generic.type.for.instof");
592 return types.createErrorType(t);
593 } else {
594 return t;
595 }
596 }
598 /** Check that type is a reference type, i.e. a class, interface or array type
599 * or a type variable.
600 * @param pos Position to be used for error reporting.
601 * @param t The type to be checked.
602 */
603 Type checkRefType(DiagnosticPosition pos, Type t) {
604 switch (t.tag) {
605 case CLASS:
606 case ARRAY:
607 case TYPEVAR:
608 case WILDCARD:
609 case ERROR:
610 return t;
611 default:
612 return typeTagError(pos,
613 diags.fragment("type.req.ref"),
614 t);
615 }
616 }
618 /** Check that each type is a reference type, i.e. a class, interface or array type
619 * or a type variable.
620 * @param trees Original trees, used for error reporting.
621 * @param types The types to be checked.
622 */
623 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
624 List<JCExpression> tl = trees;
625 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
626 l.head = checkRefType(tl.head.pos(), l.head);
627 tl = tl.tail;
628 }
629 return types;
630 }
632 /** Check that type is a null or reference type.
633 * @param pos Position to be used for error reporting.
634 * @param t The type to be checked.
635 */
636 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
637 switch (t.tag) {
638 case CLASS:
639 case ARRAY:
640 case TYPEVAR:
641 case WILDCARD:
642 case BOT:
643 case ERROR:
644 return t;
645 default:
646 return typeTagError(pos,
647 diags.fragment("type.req.ref"),
648 t);
649 }
650 }
652 /** Check that flag set does not contain elements of two conflicting sets. s
653 * Return true if it doesn't.
654 * @param pos Position to be used for error reporting.
655 * @param flags The set of flags to be checked.
656 * @param set1 Conflicting flags set #1.
657 * @param set2 Conflicting flags set #2.
658 */
659 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
660 if ((flags & set1) != 0 && (flags & set2) != 0) {
661 log.error(pos,
662 "illegal.combination.of.modifiers",
663 asFlagSet(TreeInfo.firstFlag(flags & set1)),
664 asFlagSet(TreeInfo.firstFlag(flags & set2)));
665 return false;
666 } else
667 return true;
668 }
670 /** Check that the type inferred using the diamond operator does not contain
671 * non-denotable types such as captured types or intersection types.
672 * @param t the type inferred using the diamond operator
673 */
674 List<Type> checkDiamond(ClassType t) {
675 DiamondTypeChecker dtc = new DiamondTypeChecker();
676 ListBuffer<Type> buf = ListBuffer.lb();
677 for (Type arg : t.getTypeArguments()) {
678 if (!dtc.visit(arg, null)) {
679 buf.append(arg);
680 }
681 }
682 return buf.toList();
683 }
685 static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
686 public Boolean visitType(Type t, Void s) {
687 return true;
688 }
689 @Override
690 public Boolean visitClassType(ClassType t, Void s) {
691 if (t.isCompound()) {
692 return false;
693 }
694 for (Type targ : t.getTypeArguments()) {
695 if (!visit(targ, s)) {
696 return false;
697 }
698 }
699 return true;
700 }
701 @Override
702 public Boolean visitCapturedType(CapturedType t, Void s) {
703 return false;
704 }
705 }
707 void checkVarargMethodDecl(JCMethodDecl tree) {
708 MethodSymbol m = tree.sym;
709 //check the element type of the vararg
710 if (m.isVarArgs()) {
711 Type varargElemType = types.elemtype(tree.params.last().type);
712 if (!types.isReifiable(varargElemType)) {
713 warnUnsafeVararg(tree.params.head.pos(), varargElemType);
714 }
715 }
716 }
718 /**
719 * Check that vararg method call is sound
720 * @param pos Position to be used for error reporting.
721 * @param argtypes Actual arguments supplied to vararg method.
722 */
723 void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym, Env<AttrContext> env) {
724 Env<AttrContext> calleeLintEnv = env;
725 while (calleeLintEnv.info.lint == null)
726 calleeLintEnv = calleeLintEnv.next;
727 Lint calleeLint = calleeLintEnv.info.lint.augment(msym.attributes_field, msym.flags());
728 Type argtype = argtypes.last();
729 if (!types.isReifiable(argtype) && !calleeLint.isSuppressed(Lint.LintCategory.VARARGS)) {
730 warnUnchecked(pos,
731 "unchecked.generic.array.creation",
732 argtype);
733 }
734 }
736 /** Check that given modifiers are legal for given symbol and
737 * return modifiers together with any implicit modififiers for that symbol.
738 * Warning: we can't use flags() here since this method
739 * is called during class enter, when flags() would cause a premature
740 * completion.
741 * @param pos Position to be used for error reporting.
742 * @param flags The set of modifiers given in a definition.
743 * @param sym The defined symbol.
744 */
745 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
746 long mask;
747 long implicit = 0;
748 switch (sym.kind) {
749 case VAR:
750 if (sym.owner.kind != TYP)
751 mask = LocalVarFlags;
752 else if ((sym.owner.flags_field & INTERFACE) != 0)
753 mask = implicit = InterfaceVarFlags;
754 else
755 mask = VarFlags;
756 break;
757 case MTH:
758 if (sym.name == names.init) {
759 if ((sym.owner.flags_field & ENUM) != 0) {
760 // enum constructors cannot be declared public or
761 // protected and must be implicitly or explicitly
762 // private
763 implicit = PRIVATE;
764 mask = PRIVATE;
765 } else
766 mask = ConstructorFlags;
767 } else if ((sym.owner.flags_field & INTERFACE) != 0)
768 mask = implicit = InterfaceMethodFlags;
769 else {
770 mask = MethodFlags;
771 }
772 // Imply STRICTFP if owner has STRICTFP set.
773 if (((flags|implicit) & Flags.ABSTRACT) == 0)
774 implicit |= sym.owner.flags_field & STRICTFP;
775 break;
776 case TYP:
777 if (sym.isLocal()) {
778 mask = LocalClassFlags;
779 if (sym.name.isEmpty()) { // Anonymous class
780 // Anonymous classes in static methods are themselves static;
781 // that's why we admit STATIC here.
782 mask |= STATIC;
783 // JLS: Anonymous classes are final.
784 implicit |= FINAL;
785 }
786 if ((sym.owner.flags_field & STATIC) == 0 &&
787 (flags & ENUM) != 0)
788 log.error(pos, "enums.must.be.static");
789 } else if (sym.owner.kind == TYP) {
790 mask = MemberClassFlags;
791 if (sym.owner.owner.kind == PCK ||
792 (sym.owner.flags_field & STATIC) != 0)
793 mask |= STATIC;
794 else if ((flags & ENUM) != 0)
795 log.error(pos, "enums.must.be.static");
796 // Nested interfaces and enums are always STATIC (Spec ???)
797 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
798 } else {
799 mask = ClassFlags;
800 }
801 // Interfaces are always ABSTRACT
802 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
804 if ((flags & ENUM) != 0) {
805 // enums can't be declared abstract or final
806 mask &= ~(ABSTRACT | FINAL);
807 implicit |= implicitEnumFinalFlag(tree);
808 }
809 // Imply STRICTFP if owner has STRICTFP set.
810 implicit |= sym.owner.flags_field & STRICTFP;
811 break;
812 default:
813 throw new AssertionError();
814 }
815 long illegal = flags & StandardFlags & ~mask;
816 if (illegal != 0) {
817 if ((illegal & INTERFACE) != 0) {
818 log.error(pos, "intf.not.allowed.here");
819 mask |= INTERFACE;
820 }
821 else {
822 log.error(pos,
823 "mod.not.allowed.here", asFlagSet(illegal));
824 }
825 }
826 else if ((sym.kind == TYP ||
827 // ISSUE: Disallowing abstract&private is no longer appropriate
828 // in the presence of inner classes. Should it be deleted here?
829 checkDisjoint(pos, flags,
830 ABSTRACT,
831 PRIVATE | STATIC))
832 &&
833 checkDisjoint(pos, flags,
834 ABSTRACT | INTERFACE,
835 FINAL | NATIVE | SYNCHRONIZED)
836 &&
837 checkDisjoint(pos, flags,
838 PUBLIC,
839 PRIVATE | PROTECTED)
840 &&
841 checkDisjoint(pos, flags,
842 PRIVATE,
843 PUBLIC | PROTECTED)
844 &&
845 checkDisjoint(pos, flags,
846 FINAL,
847 VOLATILE)
848 &&
849 (sym.kind == TYP ||
850 checkDisjoint(pos, flags,
851 ABSTRACT | NATIVE,
852 STRICTFP))) {
853 // skip
854 }
855 return flags & (mask | ~StandardFlags) | implicit;
856 }
859 /** Determine if this enum should be implicitly final.
860 *
861 * If the enum has no specialized enum contants, it is final.
862 *
863 * If the enum does have specialized enum contants, it is
864 * <i>not</i> final.
865 */
866 private long implicitEnumFinalFlag(JCTree tree) {
867 if (tree.getTag() != JCTree.CLASSDEF) return 0;
868 class SpecialTreeVisitor extends JCTree.Visitor {
869 boolean specialized;
870 SpecialTreeVisitor() {
871 this.specialized = false;
872 };
874 @Override
875 public void visitTree(JCTree tree) { /* no-op */ }
877 @Override
878 public void visitVarDef(JCVariableDecl tree) {
879 if ((tree.mods.flags & ENUM) != 0) {
880 if (tree.init instanceof JCNewClass &&
881 ((JCNewClass) tree.init).def != null) {
882 specialized = true;
883 }
884 }
885 }
886 }
888 SpecialTreeVisitor sts = new SpecialTreeVisitor();
889 JCClassDecl cdef = (JCClassDecl) tree;
890 for (JCTree defs: cdef.defs) {
891 defs.accept(sts);
892 if (sts.specialized) return 0;
893 }
894 return FINAL;
895 }
897 /* *************************************************************************
898 * Type Validation
899 **************************************************************************/
901 /** Validate a type expression. That is,
902 * check that all type arguments of a parametric type are within
903 * their bounds. This must be done in a second phase after type attributon
904 * since a class might have a subclass as type parameter bound. E.g:
905 *
906 * class B<A extends C> { ... }
907 * class C extends B<C> { ... }
908 *
909 * and we can't make sure that the bound is already attributed because
910 * of possible cycles.
911 *
912 * Visitor method: Validate a type expression, if it is not null, catching
913 * and reporting any completion failures.
914 */
915 void validate(JCTree tree, Env<AttrContext> env) {
916 validate(tree, env, true);
917 }
918 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
919 new Validator(env).validateTree(tree, checkRaw, true);
920 }
922 /** Visitor method: Validate a list of type expressions.
923 */
924 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
925 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
926 validate(l.head, env);
927 }
929 /** A visitor class for type validation.
930 */
931 class Validator extends JCTree.Visitor {
933 boolean isOuter;
934 Env<AttrContext> env;
936 Validator(Env<AttrContext> env) {
937 this.env = env;
938 }
940 @Override
941 public void visitTypeArray(JCArrayTypeTree tree) {
942 tree.elemtype.accept(this);
943 }
945 @Override
946 public void visitTypeApply(JCTypeApply tree) {
947 if (tree.type.tag == CLASS) {
948 List<Type> formals = tree.type.tsym.type.allparams();
949 List<Type> actuals = tree.type.allparams();
950 List<JCExpression> args = tree.arguments;
951 List<Type> forms = tree.type.tsym.type.getTypeArguments();
952 ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
954 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
956 // For matching pairs of actual argument types `a' and
957 // formal type parameters with declared bound `b' ...
958 while (args.nonEmpty() && forms.nonEmpty()) {
959 validateTree(args.head,
960 !(isOuter && is_java_lang_Class),
961 false);
963 // exact type arguments needs to know their
964 // bounds (for upper and lower bound
965 // calculations). So we create new TypeVars with
966 // bounds substed with actuals.
967 tvars_buf.append(types.substBound(((TypeVar)forms.head),
968 formals,
969 actuals));
971 args = args.tail;
972 forms = forms.tail;
973 }
975 args = tree.arguments;
976 List<Type> tvars_cap = types.substBounds(formals,
977 formals,
978 types.capture(tree.type).allparams());
979 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
980 // Let the actual arguments know their bound
981 args.head.type.withTypeVar((TypeVar)tvars_cap.head);
982 args = args.tail;
983 tvars_cap = tvars_cap.tail;
984 }
986 args = tree.arguments;
987 List<Type> tvars = tvars_buf.toList();
989 while (args.nonEmpty() && tvars.nonEmpty()) {
990 Type actual = types.subst(args.head.type,
991 tree.type.tsym.type.getTypeArguments(),
992 tvars_buf.toList());
993 checkExtends(args.head.pos(),
994 actual,
995 (TypeVar)tvars.head);
996 args = args.tail;
997 tvars = tvars.tail;
998 }
1000 checkCapture(tree);
1002 // Check that this type is either fully parameterized, or
1003 // not parameterized at all.
1004 if (tree.type.getEnclosingType().isRaw())
1005 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1006 if (tree.clazz.getTag() == JCTree.SELECT)
1007 visitSelectInternal((JCFieldAccess)tree.clazz);
1008 }
1009 }
1011 @Override
1012 public void visitTypeParameter(JCTypeParameter tree) {
1013 validateTrees(tree.bounds, true, isOuter);
1014 checkClassBounds(tree.pos(), tree.type);
1015 }
1017 @Override
1018 public void visitWildcard(JCWildcard tree) {
1019 if (tree.inner != null)
1020 validateTree(tree.inner, true, isOuter);
1021 }
1023 @Override
1024 public void visitSelect(JCFieldAccess tree) {
1025 if (tree.type.tag == CLASS) {
1026 visitSelectInternal(tree);
1028 // Check that this type is either fully parameterized, or
1029 // not parameterized at all.
1030 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1031 log.error(tree.pos(), "improperly.formed.type.param.missing");
1032 }
1033 }
1034 public void visitSelectInternal(JCFieldAccess tree) {
1035 if (tree.type.tsym.isStatic() &&
1036 tree.selected.type.isParameterized()) {
1037 // The enclosing type is not a class, so we are
1038 // looking at a static member type. However, the
1039 // qualifying expression is parameterized.
1040 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1041 } else {
1042 // otherwise validate the rest of the expression
1043 tree.selected.accept(this);
1044 }
1045 }
1047 @Override
1048 public void visitAnnotatedType(JCAnnotatedType tree) {
1049 tree.underlyingType.accept(this);
1050 }
1052 /** Default visitor method: do nothing.
1053 */
1054 @Override
1055 public void visitTree(JCTree tree) {
1056 }
1058 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1059 try {
1060 if (tree != null) {
1061 this.isOuter = isOuter;
1062 tree.accept(this);
1063 if (checkRaw)
1064 checkRaw(tree, env);
1065 }
1066 } catch (CompletionFailure ex) {
1067 completionError(tree.pos(), ex);
1068 }
1069 }
1071 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1072 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1073 validateTree(l.head, checkRaw, isOuter);
1074 }
1076 void checkRaw(JCTree tree, Env<AttrContext> env) {
1077 if (lint.isEnabled(Lint.LintCategory.RAW) &&
1078 tree.type.tag == CLASS &&
1079 !TreeInfo.isDiamond(tree) &&
1080 !env.enclClass.name.isEmpty() && //anonymous or intersection
1081 tree.type.isRaw()) {
1082 log.warning(Lint.LintCategory.RAW,
1083 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1084 }
1085 }
1086 }
1088 /* *************************************************************************
1089 * Exception checking
1090 **************************************************************************/
1092 /* The following methods treat classes as sets that contain
1093 * the class itself and all their subclasses
1094 */
1096 /** Is given type a subtype of some of the types in given list?
1097 */
1098 boolean subset(Type t, List<Type> ts) {
1099 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1100 if (types.isSubtype(t, l.head)) return true;
1101 return false;
1102 }
1104 /** Is given type a subtype or supertype of
1105 * some of the types in given list?
1106 */
1107 boolean intersects(Type t, List<Type> ts) {
1108 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1109 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1110 return false;
1111 }
1113 /** Add type set to given type list, unless it is a subclass of some class
1114 * in the list.
1115 */
1116 List<Type> incl(Type t, List<Type> ts) {
1117 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1118 }
1120 /** Remove type set from type set list.
1121 */
1122 List<Type> excl(Type t, List<Type> ts) {
1123 if (ts.isEmpty()) {
1124 return ts;
1125 } else {
1126 List<Type> ts1 = excl(t, ts.tail);
1127 if (types.isSubtype(ts.head, t)) return ts1;
1128 else if (ts1 == ts.tail) return ts;
1129 else return ts1.prepend(ts.head);
1130 }
1131 }
1133 /** Form the union of two type set lists.
1134 */
1135 List<Type> union(List<Type> ts1, List<Type> ts2) {
1136 List<Type> ts = ts1;
1137 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1138 ts = incl(l.head, ts);
1139 return ts;
1140 }
1142 /** Form the difference of two type lists.
1143 */
1144 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1145 List<Type> ts = ts1;
1146 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1147 ts = excl(l.head, ts);
1148 return ts;
1149 }
1151 /** Form the intersection of two type lists.
1152 */
1153 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1154 List<Type> ts = List.nil();
1155 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1156 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1157 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1158 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1159 return ts;
1160 }
1162 /** Is exc an exception symbol that need not be declared?
1163 */
1164 boolean isUnchecked(ClassSymbol exc) {
1165 return
1166 exc.kind == ERR ||
1167 exc.isSubClass(syms.errorType.tsym, types) ||
1168 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1169 }
1171 /** Is exc an exception type that need not be declared?
1172 */
1173 boolean isUnchecked(Type exc) {
1174 return
1175 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1176 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1177 exc.tag == BOT;
1178 }
1180 /** Same, but handling completion failures.
1181 */
1182 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1183 try {
1184 return isUnchecked(exc);
1185 } catch (CompletionFailure ex) {
1186 completionError(pos, ex);
1187 return true;
1188 }
1189 }
1191 /** Is exc handled by given exception list?
1192 */
1193 boolean isHandled(Type exc, List<Type> handled) {
1194 return isUnchecked(exc) || subset(exc, handled);
1195 }
1197 /** Return all exceptions in thrown list that are not in handled list.
1198 * @param thrown The list of thrown exceptions.
1199 * @param handled The list of handled exceptions.
1200 */
1201 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1202 List<Type> unhandled = List.nil();
1203 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1204 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1205 return unhandled;
1206 }
1208 /* *************************************************************************
1209 * Overriding/Implementation checking
1210 **************************************************************************/
1212 /** The level of access protection given by a flag set,
1213 * where PRIVATE is highest and PUBLIC is lowest.
1214 */
1215 static int protection(long flags) {
1216 switch ((short)(flags & AccessFlags)) {
1217 case PRIVATE: return 3;
1218 case PROTECTED: return 1;
1219 default:
1220 case PUBLIC: return 0;
1221 case 0: return 2;
1222 }
1223 }
1225 /** A customized "cannot override" error message.
1226 * @param m The overriding method.
1227 * @param other The overridden method.
1228 * @return An internationalized string.
1229 */
1230 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1231 String key;
1232 if ((other.owner.flags() & INTERFACE) == 0)
1233 key = "cant.override";
1234 else if ((m.owner.flags() & INTERFACE) == 0)
1235 key = "cant.implement";
1236 else
1237 key = "clashes.with";
1238 return diags.fragment(key, m, m.location(), other, other.location());
1239 }
1241 /** A customized "override" warning message.
1242 * @param m The overriding method.
1243 * @param other The overridden method.
1244 * @return An internationalized string.
1245 */
1246 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1247 String key;
1248 if ((other.owner.flags() & INTERFACE) == 0)
1249 key = "unchecked.override";
1250 else if ((m.owner.flags() & INTERFACE) == 0)
1251 key = "unchecked.implement";
1252 else
1253 key = "unchecked.clash.with";
1254 return diags.fragment(key, m, m.location(), other, other.location());
1255 }
1257 /** A customized "override" warning message.
1258 * @param m The overriding method.
1259 * @param other The overridden method.
1260 * @return An internationalized string.
1261 */
1262 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1263 String key;
1264 if ((other.owner.flags() & INTERFACE) == 0)
1265 key = "varargs.override";
1266 else if ((m.owner.flags() & INTERFACE) == 0)
1267 key = "varargs.implement";
1268 else
1269 key = "varargs.clash.with";
1270 return diags.fragment(key, m, m.location(), other, other.location());
1271 }
1273 /** Check that this method conforms with overridden method 'other'.
1274 * where `origin' is the class where checking started.
1275 * Complications:
1276 * (1) Do not check overriding of synthetic methods
1277 * (reason: they might be final).
1278 * todo: check whether this is still necessary.
1279 * (2) Admit the case where an interface proxy throws fewer exceptions
1280 * than the method it implements. Augment the proxy methods with the
1281 * undeclared exceptions in this case.
1282 * (3) When generics are enabled, admit the case where an interface proxy
1283 * has a result type
1284 * extended by the result type of the method it implements.
1285 * Change the proxies result type to the smaller type in this case.
1286 *
1287 * @param tree The tree from which positions
1288 * are extracted for errors.
1289 * @param m The overriding method.
1290 * @param other The overridden method.
1291 * @param origin The class of which the overriding method
1292 * is a member.
1293 */
1294 void checkOverride(JCTree tree,
1295 MethodSymbol m,
1296 MethodSymbol other,
1297 ClassSymbol origin) {
1298 // Don't check overriding of synthetic methods or by bridge methods.
1299 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1300 return;
1301 }
1303 // Error if static method overrides instance method (JLS 8.4.6.2).
1304 if ((m.flags() & STATIC) != 0 &&
1305 (other.flags() & STATIC) == 0) {
1306 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1307 cannotOverride(m, other));
1308 return;
1309 }
1311 // Error if instance method overrides static or final
1312 // method (JLS 8.4.6.1).
1313 if ((other.flags() & FINAL) != 0 ||
1314 (m.flags() & STATIC) == 0 &&
1315 (other.flags() & STATIC) != 0) {
1316 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1317 cannotOverride(m, other),
1318 asFlagSet(other.flags() & (FINAL | STATIC)));
1319 return;
1320 }
1322 if ((m.owner.flags() & ANNOTATION) != 0) {
1323 // handled in validateAnnotationMethod
1324 return;
1325 }
1327 // Error if overriding method has weaker access (JLS 8.4.6.3).
1328 if ((origin.flags() & INTERFACE) == 0 &&
1329 protection(m.flags()) > protection(other.flags())) {
1330 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1331 cannotOverride(m, other),
1332 other.flags() == 0 ?
1333 Flag.PACKAGE :
1334 asFlagSet(other.flags() & AccessFlags));
1335 return;
1336 }
1338 Type mt = types.memberType(origin.type, m);
1339 Type ot = types.memberType(origin.type, other);
1340 // Error if overriding result type is different
1341 // (or, in the case of generics mode, not a subtype) of
1342 // overridden result type. We have to rename any type parameters
1343 // before comparing types.
1344 List<Type> mtvars = mt.getTypeArguments();
1345 List<Type> otvars = ot.getTypeArguments();
1346 Type mtres = mt.getReturnType();
1347 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1349 overrideWarner.warned = false;
1350 boolean resultTypesOK =
1351 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1352 if (!resultTypesOK) {
1353 if (!allowCovariantReturns &&
1354 m.owner != origin &&
1355 m.owner.isSubClass(other.owner, types)) {
1356 // allow limited interoperability with covariant returns
1357 } else {
1358 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1359 "override.incompatible.ret",
1360 cannotOverride(m, other),
1361 mtres, otres);
1362 return;
1363 }
1364 } else if (overrideWarner.warned) {
1365 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1366 "override.unchecked.ret",
1367 uncheckedOverrides(m, other),
1368 mtres, otres);
1369 }
1371 // Error if overriding method throws an exception not reported
1372 // by overridden method.
1373 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1374 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1375 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1376 if (unhandledErased.nonEmpty()) {
1377 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1378 "override.meth.doesnt.throw",
1379 cannotOverride(m, other),
1380 unhandledUnerased.head);
1381 return;
1382 }
1383 else if (unhandledUnerased.nonEmpty()) {
1384 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1385 "override.unchecked.thrown",
1386 cannotOverride(m, other),
1387 unhandledUnerased.head);
1388 return;
1389 }
1391 // Optional warning if varargs don't agree
1392 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1393 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
1394 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1395 ((m.flags() & Flags.VARARGS) != 0)
1396 ? "override.varargs.missing"
1397 : "override.varargs.extra",
1398 varargsOverrides(m, other));
1399 }
1401 // Warn if instance method overrides bridge method (compiler spec ??)
1402 if ((other.flags() & BRIDGE) != 0) {
1403 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1404 uncheckedOverrides(m, other));
1405 }
1407 // Warn if a deprecated method overridden by a non-deprecated one.
1408 if ((other.flags() & DEPRECATED) != 0
1409 && (m.flags() & DEPRECATED) == 0
1410 && m.outermostClass() != other.outermostClass()
1411 && !isDeprecatedOverrideIgnorable(other, origin)) {
1412 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1413 }
1414 }
1415 // where
1416 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1417 // If the method, m, is defined in an interface, then ignore the issue if the method
1418 // is only inherited via a supertype and also implemented in the supertype,
1419 // because in that case, we will rediscover the issue when examining the method
1420 // in the supertype.
1421 // If the method, m, is not defined in an interface, then the only time we need to
1422 // address the issue is when the method is the supertype implemementation: any other
1423 // case, we will have dealt with when examining the supertype classes
1424 ClassSymbol mc = m.enclClass();
1425 Type st = types.supertype(origin.type);
1426 if (st.tag != CLASS)
1427 return true;
1428 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1430 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1431 List<Type> intfs = types.interfaces(origin.type);
1432 return (intfs.contains(mc.type) ? false : (stimpl != null));
1433 }
1434 else
1435 return (stimpl != m);
1436 }
1439 // used to check if there were any unchecked conversions
1440 Warner overrideWarner = new Warner();
1442 /** Check that a class does not inherit two concrete methods
1443 * with the same signature.
1444 * @param pos Position to be used for error reporting.
1445 * @param site The class type to be checked.
1446 */
1447 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1448 Type sup = types.supertype(site);
1449 if (sup.tag != CLASS) return;
1451 for (Type t1 = sup;
1452 t1.tsym.type.isParameterized();
1453 t1 = types.supertype(t1)) {
1454 for (Scope.Entry e1 = t1.tsym.members().elems;
1455 e1 != null;
1456 e1 = e1.sibling) {
1457 Symbol s1 = e1.sym;
1458 if (s1.kind != MTH ||
1459 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1460 !s1.isInheritedIn(site.tsym, types) ||
1461 ((MethodSymbol)s1).implementation(site.tsym,
1462 types,
1463 true) != s1)
1464 continue;
1465 Type st1 = types.memberType(t1, s1);
1466 int s1ArgsLength = st1.getParameterTypes().length();
1467 if (st1 == s1.type) continue;
1469 for (Type t2 = sup;
1470 t2.tag == CLASS;
1471 t2 = types.supertype(t2)) {
1472 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1473 e2.scope != null;
1474 e2 = e2.next()) {
1475 Symbol s2 = e2.sym;
1476 if (s2 == s1 ||
1477 s2.kind != MTH ||
1478 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1479 s2.type.getParameterTypes().length() != s1ArgsLength ||
1480 !s2.isInheritedIn(site.tsym, types) ||
1481 ((MethodSymbol)s2).implementation(site.tsym,
1482 types,
1483 true) != s2)
1484 continue;
1485 Type st2 = types.memberType(t2, s2);
1486 if (types.overrideEquivalent(st1, st2))
1487 log.error(pos, "concrete.inheritance.conflict",
1488 s1, t1, s2, t2, sup);
1489 }
1490 }
1491 }
1492 }
1493 }
1495 /** Check that classes (or interfaces) do not each define an abstract
1496 * method with same name and arguments but incompatible return types.
1497 * @param pos Position to be used for error reporting.
1498 * @param t1 The first argument type.
1499 * @param t2 The second argument type.
1500 */
1501 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1502 Type t1,
1503 Type t2) {
1504 return checkCompatibleAbstracts(pos, t1, t2,
1505 types.makeCompoundType(t1, t2));
1506 }
1508 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1509 Type t1,
1510 Type t2,
1511 Type site) {
1512 Symbol sym = firstIncompatibility(t1, t2, site);
1513 if (sym != null) {
1514 log.error(pos, "types.incompatible.diff.ret",
1515 t1, t2, sym.name +
1516 "(" + types.memberType(t2, sym).getParameterTypes() + ")");
1517 return false;
1518 }
1519 return true;
1520 }
1522 /** Return the first method which is defined with same args
1523 * but different return types in two given interfaces, or null if none
1524 * exists.
1525 * @param t1 The first type.
1526 * @param t2 The second type.
1527 * @param site The most derived type.
1528 * @returns symbol from t2 that conflicts with one in t1.
1529 */
1530 private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
1531 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1532 closure(t1, interfaces1);
1533 Map<TypeSymbol,Type> interfaces2;
1534 if (t1 == t2)
1535 interfaces2 = interfaces1;
1536 else
1537 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1539 for (Type t3 : interfaces1.values()) {
1540 for (Type t4 : interfaces2.values()) {
1541 Symbol s = firstDirectIncompatibility(t3, t4, site);
1542 if (s != null) return s;
1543 }
1544 }
1545 return null;
1546 }
1548 /** Compute all the supertypes of t, indexed by type symbol. */
1549 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1550 if (t.tag != CLASS) return;
1551 if (typeMap.put(t.tsym, t) == null) {
1552 closure(types.supertype(t), typeMap);
1553 for (Type i : types.interfaces(t))
1554 closure(i, typeMap);
1555 }
1556 }
1558 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1559 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1560 if (t.tag != CLASS) return;
1561 if (typesSkip.get(t.tsym) != null) return;
1562 if (typeMap.put(t.tsym, t) == null) {
1563 closure(types.supertype(t), typesSkip, typeMap);
1564 for (Type i : types.interfaces(t))
1565 closure(i, typesSkip, typeMap);
1566 }
1567 }
1569 /** Return the first method in t2 that conflicts with a method from t1. */
1570 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
1571 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1572 Symbol s1 = e1.sym;
1573 Type st1 = null;
1574 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1575 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1576 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1577 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1578 Symbol s2 = e2.sym;
1579 if (s1 == s2) continue;
1580 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1581 if (st1 == null) st1 = types.memberType(t1, s1);
1582 Type st2 = types.memberType(t2, s2);
1583 if (types.overrideEquivalent(st1, st2)) {
1584 List<Type> tvars1 = st1.getTypeArguments();
1585 List<Type> tvars2 = st2.getTypeArguments();
1586 Type rt1 = st1.getReturnType();
1587 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1588 boolean compat =
1589 types.isSameType(rt1, rt2) ||
1590 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1591 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1592 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1593 checkCommonOverriderIn(s1,s2,site);
1594 if (!compat) return s2;
1595 }
1596 }
1597 }
1598 return null;
1599 }
1600 //WHERE
1601 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1602 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1603 Type st1 = types.memberType(site, s1);
1604 Type st2 = types.memberType(site, s2);
1605 closure(site, supertypes);
1606 for (Type t : supertypes.values()) {
1607 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1608 Symbol s3 = e.sym;
1609 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1610 Type st3 = types.memberType(site,s3);
1611 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1612 if (s3.owner == site.tsym) {
1613 return true;
1614 }
1615 List<Type> tvars1 = st1.getTypeArguments();
1616 List<Type> tvars2 = st2.getTypeArguments();
1617 List<Type> tvars3 = st3.getTypeArguments();
1618 Type rt1 = st1.getReturnType();
1619 Type rt2 = st2.getReturnType();
1620 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1621 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1622 boolean compat =
1623 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1624 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1625 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1626 if (compat)
1627 return true;
1628 }
1629 }
1630 }
1631 return false;
1632 }
1634 /** Check that a given method conforms with any method it overrides.
1635 * @param tree The tree from which positions are extracted
1636 * for errors.
1637 * @param m The overriding method.
1638 */
1639 void checkOverride(JCTree tree, MethodSymbol m) {
1640 ClassSymbol origin = (ClassSymbol)m.owner;
1641 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1642 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1643 log.error(tree.pos(), "enum.no.finalize");
1644 return;
1645 }
1646 for (Type t = types.supertype(origin.type); t.tag == CLASS;
1647 t = types.supertype(t)) {
1648 TypeSymbol c = t.tsym;
1649 Scope.Entry e = c.members().lookup(m.name);
1650 while (e.scope != null) {
1651 if (m.overrides(e.sym, origin, types, false))
1652 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1653 else if (e.sym.kind == MTH &&
1654 e.sym.isInheritedIn(origin, types) &&
1655 (e.sym.flags() & SYNTHETIC) == 0 &&
1656 !m.isConstructor()) {
1657 Type er1 = m.erasure(types);
1658 Type er2 = e.sym.erasure(types);
1659 if (types.isSameTypes(er1.getParameterTypes(),
1660 er2.getParameterTypes())) {
1661 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1662 "name.clash.same.erasure.no.override",
1663 m, m.location(),
1664 e.sym, e.sym.location());
1665 }
1666 }
1667 e = e.next();
1668 }
1669 }
1670 }
1672 /** Check that all abstract members of given class have definitions.
1673 * @param pos Position to be used for error reporting.
1674 * @param c The class.
1675 */
1676 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1677 try {
1678 MethodSymbol undef = firstUndef(c, c);
1679 if (undef != null) {
1680 if ((c.flags() & ENUM) != 0 &&
1681 types.supertype(c.type).tsym == syms.enumSym &&
1682 (c.flags() & FINAL) == 0) {
1683 // add the ABSTRACT flag to an enum
1684 c.flags_field |= ABSTRACT;
1685 } else {
1686 MethodSymbol undef1 =
1687 new MethodSymbol(undef.flags(), undef.name,
1688 types.memberType(c.type, undef), undef.owner);
1689 log.error(pos, "does.not.override.abstract",
1690 c, undef1, undef1.location());
1691 }
1692 }
1693 } catch (CompletionFailure ex) {
1694 completionError(pos, ex);
1695 }
1696 }
1697 //where
1698 /** Return first abstract member of class `c' that is not defined
1699 * in `impl', null if there is none.
1700 */
1701 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1702 MethodSymbol undef = null;
1703 // Do not bother to search in classes that are not abstract,
1704 // since they cannot have abstract members.
1705 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1706 Scope s = c.members();
1707 for (Scope.Entry e = s.elems;
1708 undef == null && e != null;
1709 e = e.sibling) {
1710 if (e.sym.kind == MTH &&
1711 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1712 MethodSymbol absmeth = (MethodSymbol)e.sym;
1713 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1714 if (implmeth == null || implmeth == absmeth)
1715 undef = absmeth;
1716 }
1717 }
1718 if (undef == null) {
1719 Type st = types.supertype(c.type);
1720 if (st.tag == CLASS)
1721 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1722 }
1723 for (List<Type> l = types.interfaces(c.type);
1724 undef == null && l.nonEmpty();
1725 l = l.tail) {
1726 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1727 }
1728 }
1729 return undef;
1730 }
1732 void checkNonCyclicDecl(JCClassDecl tree) {
1733 CycleChecker cc = new CycleChecker();
1734 cc.scan(tree);
1735 if (!cc.errorFound && !cc.partialCheck) {
1736 tree.sym.flags_field |= ACYCLIC;
1737 }
1738 }
1740 class CycleChecker extends TreeScanner {
1742 List<Symbol> seenClasses = List.nil();
1743 boolean errorFound = false;
1744 boolean partialCheck = false;
1746 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1747 if (sym != null && sym.kind == TYP) {
1748 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1749 if (classEnv != null) {
1750 DiagnosticSource prevSource = log.currentSource();
1751 try {
1752 log.useSource(classEnv.toplevel.sourcefile);
1753 scan(classEnv.tree);
1754 }
1755 finally {
1756 log.useSource(prevSource.getFile());
1757 }
1758 } else if (sym.kind == TYP) {
1759 checkClass(pos, sym, List.<JCTree>nil());
1760 }
1761 } else {
1762 //not completed yet
1763 partialCheck = true;
1764 }
1765 }
1767 @Override
1768 public void visitSelect(JCFieldAccess tree) {
1769 super.visitSelect(tree);
1770 checkSymbol(tree.pos(), tree.sym);
1771 }
1773 @Override
1774 public void visitIdent(JCIdent tree) {
1775 checkSymbol(tree.pos(), tree.sym);
1776 }
1778 @Override
1779 public void visitTypeApply(JCTypeApply tree) {
1780 scan(tree.clazz);
1781 }
1783 @Override
1784 public void visitTypeArray(JCArrayTypeTree tree) {
1785 scan(tree.elemtype);
1786 }
1788 @Override
1789 public void visitClassDef(JCClassDecl tree) {
1790 List<JCTree> supertypes = List.nil();
1791 if (tree.getExtendsClause() != null) {
1792 supertypes = supertypes.prepend(tree.getExtendsClause());
1793 }
1794 if (tree.getImplementsClause() != null) {
1795 for (JCTree intf : tree.getImplementsClause()) {
1796 supertypes = supertypes.prepend(intf);
1797 }
1798 }
1799 checkClass(tree.pos(), tree.sym, supertypes);
1800 }
1802 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
1803 if ((c.flags_field & ACYCLIC) != 0)
1804 return;
1805 if (seenClasses.contains(c)) {
1806 errorFound = true;
1807 noteCyclic(pos, (ClassSymbol)c);
1808 } else if (!c.type.isErroneous()) {
1809 try {
1810 seenClasses = seenClasses.prepend(c);
1811 if (c.type.tag == CLASS) {
1812 if (supertypes.nonEmpty()) {
1813 scan(supertypes);
1814 }
1815 else {
1816 ClassType ct = (ClassType)c.type;
1817 if (ct.supertype_field == null ||
1818 ct.interfaces_field == null) {
1819 //not completed yet
1820 partialCheck = true;
1821 return;
1822 }
1823 checkSymbol(pos, ct.supertype_field.tsym);
1824 for (Type intf : ct.interfaces_field) {
1825 checkSymbol(pos, intf.tsym);
1826 }
1827 }
1828 if (c.owner.kind == TYP) {
1829 checkSymbol(pos, c.owner);
1830 }
1831 }
1832 } finally {
1833 seenClasses = seenClasses.tail;
1834 }
1835 }
1836 }
1837 }
1839 /** Check for cyclic references. Issue an error if the
1840 * symbol of the type referred to has a LOCKED flag set.
1841 *
1842 * @param pos Position to be used for error reporting.
1843 * @param t The type referred to.
1844 */
1845 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1846 checkNonCyclicInternal(pos, t);
1847 }
1850 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1851 checkNonCyclic1(pos, t, List.<TypeVar>nil());
1852 }
1854 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
1855 final TypeVar tv;
1856 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1857 return;
1858 if (seen.contains(t)) {
1859 tv = (TypeVar)t;
1860 tv.bound = types.createErrorType(t);
1861 log.error(pos, "cyclic.inheritance", t);
1862 } else if (t.tag == TYPEVAR) {
1863 tv = (TypeVar)t;
1864 seen = seen.prepend(tv);
1865 for (Type b : types.getBounds(tv))
1866 checkNonCyclic1(pos, b, seen);
1867 }
1868 }
1870 /** Check for cyclic references. Issue an error if the
1871 * symbol of the type referred to has a LOCKED flag set.
1872 *
1873 * @param pos Position to be used for error reporting.
1874 * @param t The type referred to.
1875 * @returns True if the check completed on all attributed classes
1876 */
1877 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1878 boolean complete = true; // was the check complete?
1879 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1880 Symbol c = t.tsym;
1881 if ((c.flags_field & ACYCLIC) != 0) return true;
1883 if ((c.flags_field & LOCKED) != 0) {
1884 noteCyclic(pos, (ClassSymbol)c);
1885 } else if (!c.type.isErroneous()) {
1886 try {
1887 c.flags_field |= LOCKED;
1888 if (c.type.tag == CLASS) {
1889 ClassType clazz = (ClassType)c.type;
1890 if (clazz.interfaces_field != null)
1891 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1892 complete &= checkNonCyclicInternal(pos, l.head);
1893 if (clazz.supertype_field != null) {
1894 Type st = clazz.supertype_field;
1895 if (st != null && st.tag == CLASS)
1896 complete &= checkNonCyclicInternal(pos, st);
1897 }
1898 if (c.owner.kind == TYP)
1899 complete &= checkNonCyclicInternal(pos, c.owner.type);
1900 }
1901 } finally {
1902 c.flags_field &= ~LOCKED;
1903 }
1904 }
1905 if (complete)
1906 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1907 if (complete) c.flags_field |= ACYCLIC;
1908 return complete;
1909 }
1911 /** Note that we found an inheritance cycle. */
1912 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1913 log.error(pos, "cyclic.inheritance", c);
1914 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1915 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
1916 Type st = types.supertype(c.type);
1917 if (st.tag == CLASS)
1918 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
1919 c.type = types.createErrorType(c, c.type);
1920 c.flags_field |= ACYCLIC;
1921 }
1923 /** Check that all methods which implement some
1924 * method conform to the method they implement.
1925 * @param tree The class definition whose members are checked.
1926 */
1927 void checkImplementations(JCClassDecl tree) {
1928 checkImplementations(tree, tree.sym);
1929 }
1930 //where
1931 /** Check that all methods which implement some
1932 * method in `ic' conform to the method they implement.
1933 */
1934 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
1935 ClassSymbol origin = tree.sym;
1936 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
1937 ClassSymbol lc = (ClassSymbol)l.head.tsym;
1938 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
1939 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
1940 if (e.sym.kind == MTH &&
1941 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
1942 MethodSymbol absmeth = (MethodSymbol)e.sym;
1943 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
1944 if (implmeth != null && implmeth != absmeth &&
1945 (implmeth.owner.flags() & INTERFACE) ==
1946 (origin.flags() & INTERFACE)) {
1947 // don't check if implmeth is in a class, yet
1948 // origin is an interface. This case arises only
1949 // if implmeth is declared in Object. The reason is
1950 // that interfaces really don't inherit from
1951 // Object it's just that the compiler represents
1952 // things that way.
1953 checkOverride(tree, implmeth, absmeth, origin);
1954 }
1955 }
1956 }
1957 }
1958 }
1959 }
1961 /** Check that all abstract methods implemented by a class are
1962 * mutually compatible.
1963 * @param pos Position to be used for error reporting.
1964 * @param c The class whose interfaces are checked.
1965 */
1966 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
1967 List<Type> supertypes = types.interfaces(c);
1968 Type supertype = types.supertype(c);
1969 if (supertype.tag == CLASS &&
1970 (supertype.tsym.flags() & ABSTRACT) != 0)
1971 supertypes = supertypes.prepend(supertype);
1972 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
1973 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
1974 !checkCompatibleAbstracts(pos, l.head, l.head, c))
1975 return;
1976 for (List<Type> m = supertypes; m != l; m = m.tail)
1977 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
1978 return;
1979 }
1980 checkCompatibleConcretes(pos, c);
1981 }
1983 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
1984 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
1985 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
1986 // VM allows methods and variables with differing types
1987 if (sym.kind == e.sym.kind &&
1988 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
1989 sym != e.sym &&
1990 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
1991 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
1992 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
1993 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
1994 return;
1995 }
1996 }
1997 }
1998 }
2000 /** Report a conflict between a user symbol and a synthetic symbol.
2001 */
2002 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2003 if (!sym.type.isErroneous()) {
2004 if (warnOnSyntheticConflicts) {
2005 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2006 }
2007 else {
2008 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2009 }
2010 }
2011 }
2013 /** Check that class c does not implement directly or indirectly
2014 * the same parameterized interface with two different argument lists.
2015 * @param pos Position to be used for error reporting.
2016 * @param type The type whose interfaces are checked.
2017 */
2018 void checkClassBounds(DiagnosticPosition pos, Type type) {
2019 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2020 }
2021 //where
2022 /** Enter all interfaces of type `type' into the hash table `seensofar'
2023 * with their class symbol as key and their type as value. Make
2024 * sure no class is entered with two different types.
2025 */
2026 void checkClassBounds(DiagnosticPosition pos,
2027 Map<TypeSymbol,Type> seensofar,
2028 Type type) {
2029 if (type.isErroneous()) return;
2030 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2031 Type it = l.head;
2032 Type oldit = seensofar.put(it.tsym, it);
2033 if (oldit != null) {
2034 List<Type> oldparams = oldit.allparams();
2035 List<Type> newparams = it.allparams();
2036 if (!types.containsTypeEquivalent(oldparams, newparams))
2037 log.error(pos, "cant.inherit.diff.arg",
2038 it.tsym, Type.toString(oldparams),
2039 Type.toString(newparams));
2040 }
2041 checkClassBounds(pos, seensofar, it);
2042 }
2043 Type st = types.supertype(type);
2044 if (st != null) checkClassBounds(pos, seensofar, st);
2045 }
2047 /** Enter interface into into set.
2048 * If it existed already, issue a "repeated interface" error.
2049 */
2050 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2051 if (its.contains(it))
2052 log.error(pos, "repeated.interface");
2053 else {
2054 its.add(it);
2055 }
2056 }
2058 /* *************************************************************************
2059 * Check annotations
2060 **************************************************************************/
2062 /**
2063 * Recursively validate annotations values
2064 */
2065 void validateAnnotationTree(JCTree tree) {
2066 class AnnotationValidator extends TreeScanner {
2067 @Override
2068 public void visitAnnotation(JCAnnotation tree) {
2069 super.visitAnnotation(tree);
2070 validateAnnotation(tree);
2071 }
2072 }
2073 tree.accept(new AnnotationValidator());
2074 }
2076 /** Annotation types are restricted to primitives, String, an
2077 * enum, an annotation, Class, Class<?>, Class<? extends
2078 * Anything>, arrays of the preceding.
2079 */
2080 void validateAnnotationType(JCTree restype) {
2081 // restype may be null if an error occurred, so don't bother validating it
2082 if (restype != null) {
2083 validateAnnotationType(restype.pos(), restype.type);
2084 }
2085 }
2087 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2088 if (type.isPrimitive()) return;
2089 if (types.isSameType(type, syms.stringType)) return;
2090 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2091 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2092 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2093 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2094 validateAnnotationType(pos, types.elemtype(type));
2095 return;
2096 }
2097 log.error(pos, "invalid.annotation.member.type");
2098 }
2100 /**
2101 * "It is also a compile-time error if any method declared in an
2102 * annotation type has a signature that is override-equivalent to
2103 * that of any public or protected method declared in class Object
2104 * or in the interface annotation.Annotation."
2105 *
2106 * @jls3 9.6 Annotation Types
2107 */
2108 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2109 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2110 Scope s = sup.tsym.members();
2111 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2112 if (e.sym.kind == MTH &&
2113 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2114 types.overrideEquivalent(m.type, e.sym.type))
2115 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2116 }
2117 }
2118 }
2120 /** Check the annotations of a symbol.
2121 */
2122 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2123 if (skipAnnotations) return;
2124 for (JCAnnotation a : annotations)
2125 validateAnnotation(a, s);
2126 }
2128 /** Check the type annotations
2129 */
2130 public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
2131 if (skipAnnotations) return;
2132 for (JCTypeAnnotation a : annotations)
2133 validateTypeAnnotation(a, isTypeParameter);
2134 }
2136 /** Check an annotation of a symbol.
2137 */
2138 public void validateAnnotation(JCAnnotation a, Symbol s) {
2139 validateAnnotationTree(a);
2141 if (!annotationApplicable(a, s))
2142 log.error(a.pos(), "annotation.type.not.applicable");
2144 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2145 if (!isOverrider(s))
2146 log.error(a.pos(), "method.does.not.override.superclass");
2147 }
2148 }
2150 public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
2151 if (a.type == null)
2152 throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
2153 validateAnnotationTree(a);
2155 if (!isTypeAnnotation(a, isTypeParameter))
2156 log.error(a.pos(), "annotation.type.not.applicable");
2157 }
2159 /** Is s a method symbol that overrides a method in a superclass? */
2160 boolean isOverrider(Symbol s) {
2161 if (s.kind != MTH || s.isStatic())
2162 return false;
2163 MethodSymbol m = (MethodSymbol)s;
2164 TypeSymbol owner = (TypeSymbol)m.owner;
2165 for (Type sup : types.closure(owner.type)) {
2166 if (sup == owner.type)
2167 continue; // skip "this"
2168 Scope scope = sup.tsym.members();
2169 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2170 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2171 return true;
2172 }
2173 }
2174 return false;
2175 }
2177 /** Is the annotation applicable to type annotations */
2178 boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
2179 Attribute.Compound atTarget =
2180 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2181 if (atTarget == null) return true;
2182 Attribute atValue = atTarget.member(names.value);
2183 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2184 Attribute.Array arr = (Attribute.Array) atValue;
2185 for (Attribute app : arr.values) {
2186 if (!(app instanceof Attribute.Enum)) return true; // recovery
2187 Attribute.Enum e = (Attribute.Enum) app;
2188 if (!isTypeParameter && e.value.name == names.TYPE_USE)
2189 return true;
2190 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2191 return true;
2192 }
2193 return false;
2194 }
2196 /** Is the annotation applicable to the symbol? */
2197 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2198 Attribute.Compound atTarget =
2199 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2200 if (atTarget == null) return true;
2201 Attribute atValue = atTarget.member(names.value);
2202 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2203 Attribute.Array arr = (Attribute.Array) atValue;
2204 for (Attribute app : arr.values) {
2205 if (!(app instanceof Attribute.Enum)) return true; // recovery
2206 Attribute.Enum e = (Attribute.Enum) app;
2207 if (e.value.name == names.TYPE)
2208 { if (s.kind == TYP) return true; }
2209 else if (e.value.name == names.FIELD)
2210 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2211 else if (e.value.name == names.METHOD)
2212 { if (s.kind == MTH && !s.isConstructor()) return true; }
2213 else if (e.value.name == names.PARAMETER)
2214 { if (s.kind == VAR &&
2215 s.owner.kind == MTH &&
2216 (s.flags() & PARAMETER) != 0)
2217 return true;
2218 }
2219 else if (e.value.name == names.CONSTRUCTOR)
2220 { if (s.kind == MTH && s.isConstructor()) return true; }
2221 else if (e.value.name == names.LOCAL_VARIABLE)
2222 { if (s.kind == VAR && s.owner.kind == MTH &&
2223 (s.flags() & PARAMETER) == 0)
2224 return true;
2225 }
2226 else if (e.value.name == names.ANNOTATION_TYPE)
2227 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2228 return true;
2229 }
2230 else if (e.value.name == names.PACKAGE)
2231 { if (s.kind == PCK) return true; }
2232 else if (e.value.name == names.TYPE_USE)
2233 { if (s.kind == TYP ||
2234 s.kind == VAR ||
2235 (s.kind == MTH && !s.isConstructor() &&
2236 s.type.getReturnType().tag != VOID))
2237 return true;
2238 }
2239 else
2240 return true; // recovery
2241 }
2242 return false;
2243 }
2245 /** Check an annotation value.
2246 */
2247 public void validateAnnotation(JCAnnotation a) {
2248 if (a.type.isErroneous()) return;
2250 // collect an inventory of the members (sorted alphabetically)
2251 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2252 public int compare(Symbol t, Symbol t1) {
2253 return t.name.compareTo(t1.name);
2254 }
2255 });
2256 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2257 e != null;
2258 e = e.sibling)
2259 if (e.sym.kind == MTH)
2260 members.add((MethodSymbol) e.sym);
2262 // count them off as they're annotated
2263 for (JCTree arg : a.args) {
2264 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
2265 JCAssign assign = (JCAssign) arg;
2266 Symbol m = TreeInfo.symbol(assign.lhs);
2267 if (m == null || m.type.isErroneous()) continue;
2268 if (!members.remove(m))
2269 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2270 m.name, a.type);
2271 }
2273 // all the remaining ones better have default values
2274 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2275 for (MethodSymbol m : members) {
2276 if (m.defaultValue == null && !m.type.isErroneous()) {
2277 missingDefaults.append(m.name);
2278 }
2279 }
2280 if (missingDefaults.nonEmpty()) {
2281 String key = (missingDefaults.size() > 1)
2282 ? "annotation.missing.default.value.1"
2283 : "annotation.missing.default.value";
2284 log.error(a.pos(), key, a.type, missingDefaults);
2285 }
2287 // special case: java.lang.annotation.Target must not have
2288 // repeated values in its value member
2289 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2290 a.args.tail == null)
2291 return;
2293 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
2294 JCAssign assign = (JCAssign) a.args.head;
2295 Symbol m = TreeInfo.symbol(assign.lhs);
2296 if (m.name != names.value) return;
2297 JCTree rhs = assign.rhs;
2298 if (rhs.getTag() != JCTree.NEWARRAY) return;
2299 JCNewArray na = (JCNewArray) rhs;
2300 Set<Symbol> targets = new HashSet<Symbol>();
2301 for (JCTree elem : na.elems) {
2302 if (!targets.add(TreeInfo.symbol(elem))) {
2303 log.error(elem.pos(), "repeated.annotation.target");
2304 }
2305 }
2306 }
2308 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2309 if (allowAnnotations &&
2310 lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
2311 (s.flags() & DEPRECATED) != 0 &&
2312 !syms.deprecatedType.isErroneous() &&
2313 s.attribute(syms.deprecatedType.tsym) == null) {
2314 log.warning(Lint.LintCategory.DEP_ANN,
2315 pos, "missing.deprecated.annotation");
2316 }
2317 }
2319 /* *************************************************************************
2320 * Check for recursive annotation elements.
2321 **************************************************************************/
2323 /** Check for cycles in the graph of annotation elements.
2324 */
2325 void checkNonCyclicElements(JCClassDecl tree) {
2326 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2327 assert (tree.sym.flags_field & LOCKED) == 0;
2328 try {
2329 tree.sym.flags_field |= LOCKED;
2330 for (JCTree def : tree.defs) {
2331 if (def.getTag() != JCTree.METHODDEF) continue;
2332 JCMethodDecl meth = (JCMethodDecl)def;
2333 checkAnnotationResType(meth.pos(), meth.restype.type);
2334 }
2335 } finally {
2336 tree.sym.flags_field &= ~LOCKED;
2337 tree.sym.flags_field |= ACYCLIC_ANN;
2338 }
2339 }
2341 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2342 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2343 return;
2344 if ((tsym.flags_field & LOCKED) != 0) {
2345 log.error(pos, "cyclic.annotation.element");
2346 return;
2347 }
2348 try {
2349 tsym.flags_field |= LOCKED;
2350 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2351 Symbol s = e.sym;
2352 if (s.kind != Kinds.MTH)
2353 continue;
2354 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2355 }
2356 } finally {
2357 tsym.flags_field &= ~LOCKED;
2358 tsym.flags_field |= ACYCLIC_ANN;
2359 }
2360 }
2362 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2363 switch (type.tag) {
2364 case TypeTags.CLASS:
2365 if ((type.tsym.flags() & ANNOTATION) != 0)
2366 checkNonCyclicElementsInternal(pos, type.tsym);
2367 break;
2368 case TypeTags.ARRAY:
2369 checkAnnotationResType(pos, types.elemtype(type));
2370 break;
2371 default:
2372 break; // int etc
2373 }
2374 }
2376 /* *************************************************************************
2377 * Check for cycles in the constructor call graph.
2378 **************************************************************************/
2380 /** Check for cycles in the graph of constructors calling other
2381 * constructors.
2382 */
2383 void checkCyclicConstructors(JCClassDecl tree) {
2384 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2386 // enter each constructor this-call into the map
2387 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2388 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2389 if (app == null) continue;
2390 JCMethodDecl meth = (JCMethodDecl) l.head;
2391 if (TreeInfo.name(app.meth) == names._this) {
2392 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2393 } else {
2394 meth.sym.flags_field |= ACYCLIC;
2395 }
2396 }
2398 // Check for cycles in the map
2399 Symbol[] ctors = new Symbol[0];
2400 ctors = callMap.keySet().toArray(ctors);
2401 for (Symbol caller : ctors) {
2402 checkCyclicConstructor(tree, caller, callMap);
2403 }
2404 }
2406 /** Look in the map to see if the given constructor is part of a
2407 * call cycle.
2408 */
2409 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2410 Map<Symbol,Symbol> callMap) {
2411 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2412 if ((ctor.flags_field & LOCKED) != 0) {
2413 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2414 "recursive.ctor.invocation");
2415 } else {
2416 ctor.flags_field |= LOCKED;
2417 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2418 ctor.flags_field &= ~LOCKED;
2419 }
2420 ctor.flags_field |= ACYCLIC;
2421 }
2422 }
2424 /* *************************************************************************
2425 * Miscellaneous
2426 **************************************************************************/
2428 /**
2429 * Return the opcode of the operator but emit an error if it is an
2430 * error.
2431 * @param pos position for error reporting.
2432 * @param operator an operator
2433 * @param tag a tree tag
2434 * @param left type of left hand side
2435 * @param right type of right hand side
2436 */
2437 int checkOperator(DiagnosticPosition pos,
2438 OperatorSymbol operator,
2439 int tag,
2440 Type left,
2441 Type right) {
2442 if (operator.opcode == ByteCodes.error) {
2443 log.error(pos,
2444 "operator.cant.be.applied",
2445 treeinfo.operatorName(tag),
2446 List.of(left, right));
2447 }
2448 return operator.opcode;
2449 }
2452 /**
2453 * Check for division by integer constant zero
2454 * @param pos Position for error reporting.
2455 * @param operator The operator for the expression
2456 * @param operand The right hand operand for the expression
2457 */
2458 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2459 if (operand.constValue() != null
2460 && lint.isEnabled(Lint.LintCategory.DIVZERO)
2461 && operand.tag <= LONG
2462 && ((Number) (operand.constValue())).longValue() == 0) {
2463 int opc = ((OperatorSymbol)operator).opcode;
2464 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2465 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2466 log.warning(Lint.LintCategory.DIVZERO, pos, "div.zero");
2467 }
2468 }
2469 }
2471 /**
2472 * Check for empty statements after if
2473 */
2474 void checkEmptyIf(JCIf tree) {
2475 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
2476 log.warning(Lint.LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
2477 }
2479 /** Check that symbol is unique in given scope.
2480 * @param pos Position for error reporting.
2481 * @param sym The symbol.
2482 * @param s The scope.
2483 */
2484 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2485 if (sym.type.isErroneous())
2486 return true;
2487 if (sym.owner.name == names.any) return false;
2488 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2489 if (sym != e.sym &&
2490 sym.kind == e.sym.kind &&
2491 sym.name != names.error &&
2492 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2493 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
2494 varargsDuplicateError(pos, sym, e.sym);
2495 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
2496 duplicateErasureError(pos, sym, e.sym);
2497 else
2498 duplicateError(pos, e.sym);
2499 return false;
2500 }
2501 }
2502 return true;
2503 }
2504 //where
2505 /** Report duplicate declaration error.
2506 */
2507 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2508 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2509 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2510 }
2511 }
2513 /** Check that single-type import is not already imported or top-level defined,
2514 * but make an exception for two single-type imports which denote the same type.
2515 * @param pos Position for error reporting.
2516 * @param sym The symbol.
2517 * @param s The scope
2518 */
2519 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2520 return checkUniqueImport(pos, sym, s, false);
2521 }
2523 /** Check that static single-type import is not already imported or top-level defined,
2524 * but make an exception for two single-type imports which denote the same type.
2525 * @param pos Position for error reporting.
2526 * @param sym The symbol.
2527 * @param s The scope
2528 * @param staticImport Whether or not this was a static import
2529 */
2530 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2531 return checkUniqueImport(pos, sym, s, true);
2532 }
2534 /** Check that single-type import is not already imported or top-level defined,
2535 * but make an exception for two single-type imports which denote the same type.
2536 * @param pos Position for error reporting.
2537 * @param sym The symbol.
2538 * @param s The scope.
2539 * @param staticImport Whether or not this was a static import
2540 */
2541 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2542 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2543 // is encountered class entered via a class declaration?
2544 boolean isClassDecl = e.scope == s;
2545 if ((isClassDecl || sym != e.sym) &&
2546 sym.kind == e.sym.kind &&
2547 sym.name != names.error) {
2548 if (!e.sym.type.isErroneous()) {
2549 String what = e.sym.toString();
2550 if (!isClassDecl) {
2551 if (staticImport)
2552 log.error(pos, "already.defined.static.single.import", what);
2553 else
2554 log.error(pos, "already.defined.single.import", what);
2555 }
2556 else if (sym != e.sym)
2557 log.error(pos, "already.defined.this.unit", what);
2558 }
2559 return false;
2560 }
2561 }
2562 return true;
2563 }
2565 /** Check that a qualified name is in canonical form (for import decls).
2566 */
2567 public void checkCanonical(JCTree tree) {
2568 if (!isCanonical(tree))
2569 log.error(tree.pos(), "import.requires.canonical",
2570 TreeInfo.symbol(tree));
2571 }
2572 // where
2573 private boolean isCanonical(JCTree tree) {
2574 while (tree.getTag() == JCTree.SELECT) {
2575 JCFieldAccess s = (JCFieldAccess) tree;
2576 if (s.sym.owner != TreeInfo.symbol(s.selected))
2577 return false;
2578 tree = s.selected;
2579 }
2580 return true;
2581 }
2583 private class ConversionWarner extends Warner {
2584 final String key;
2585 final Type found;
2586 final Type expected;
2587 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
2588 super(pos);
2589 this.key = key;
2590 this.found = found;
2591 this.expected = expected;
2592 }
2594 @Override
2595 public void warnUnchecked() {
2596 boolean warned = this.warned;
2597 super.warnUnchecked();
2598 if (warned) return; // suppress redundant diagnostics
2599 Object problem = diags.fragment(key);
2600 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
2601 }
2602 }
2604 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2605 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2606 }
2608 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2609 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2610 }
2611 }