Fri, 04 Jul 2008 15:06:27 -0700
Merge
1 /*
2 * Copyright 1999-2008 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any 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.Kinds.*;
46 import static com.sun.tools.javac.code.TypeTags.*;
48 /** Type checking helper class for the attribution phase.
49 *
50 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
51 * you write code that depends on this, you do so at your own risk.
52 * This code and its internal interfaces are subject to change or
53 * deletion without notice.</b>
54 */
55 public class Check {
56 protected static final Context.Key<Check> checkKey =
57 new Context.Key<Check>();
59 private final Name.Table names;
60 private final Log log;
61 private final Symtab syms;
62 private final Infer infer;
63 private final Target target;
64 private final Source source;
65 private final Types types;
66 private final boolean skipAnnotations;
67 private final TreeInfo treeinfo;
69 // The set of lint options currently in effect. It is initialized
70 // from the context, and then is set/reset as needed by Attr as it
71 // visits all the various parts of the trees during attribution.
72 private Lint lint;
74 public static Check instance(Context context) {
75 Check instance = context.get(checkKey);
76 if (instance == null)
77 instance = new Check(context);
78 return instance;
79 }
81 protected Check(Context context) {
82 context.put(checkKey, this);
84 names = Name.Table.instance(context);
85 log = Log.instance(context);
86 syms = Symtab.instance(context);
87 infer = Infer.instance(context);
88 this.types = Types.instance(context);
89 Options options = Options.instance(context);
90 target = Target.instance(context);
91 source = Source.instance(context);
92 lint = Lint.instance(context);
93 treeinfo = TreeInfo.instance(context);
95 Source source = Source.instance(context);
96 allowGenerics = source.allowGenerics();
97 allowAnnotations = source.allowAnnotations();
98 complexInference = options.get("-complexinference") != null;
99 skipAnnotations = options.get("skipAnnotations") != null;
101 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
102 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
103 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
105 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
106 enforceMandatoryWarnings, "deprecated");
107 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
108 enforceMandatoryWarnings, "unchecked");
109 }
111 /** Switch: generics enabled?
112 */
113 boolean allowGenerics;
115 /** Switch: annotations enabled?
116 */
117 boolean allowAnnotations;
119 /** Switch: -complexinference option set?
120 */
121 boolean complexInference;
123 /** A table mapping flat names of all compiled classes in this run to their
124 * symbols; maintained from outside.
125 */
126 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
128 /** A handler for messages about deprecated usage.
129 */
130 private MandatoryWarningHandler deprecationHandler;
132 /** A handler for messages about unchecked or unsafe usage.
133 */
134 private MandatoryWarningHandler uncheckedHandler;
137 /* *************************************************************************
138 * Errors and Warnings
139 **************************************************************************/
141 Lint setLint(Lint newLint) {
142 Lint prev = lint;
143 lint = newLint;
144 return prev;
145 }
147 /** Warn about deprecated symbol.
148 * @param pos Position to be used for error reporting.
149 * @param sym The deprecated symbol.
150 */
151 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
152 if (!lint.isSuppressed(LintCategory.DEPRECATION))
153 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
154 }
156 /** Warn about unchecked operation.
157 * @param pos Position to be used for error reporting.
158 * @param msg A string describing the problem.
159 */
160 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
161 if (!lint.isSuppressed(LintCategory.UNCHECKED))
162 uncheckedHandler.report(pos, msg, args);
163 }
165 /**
166 * Report any deferred diagnostics.
167 */
168 public void reportDeferredDiagnostics() {
169 deprecationHandler.reportDeferredDiagnostic();
170 uncheckedHandler.reportDeferredDiagnostic();
171 }
174 /** Report a failure to complete a class.
175 * @param pos Position to be used for error reporting.
176 * @param ex The failure to report.
177 */
178 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
179 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
180 if (ex instanceof ClassReader.BadClassFile) throw new Abort();
181 else return syms.errType;
182 }
184 /** Report a type error.
185 * @param pos Position to be used for error reporting.
186 * @param problem A string describing the error.
187 * @param found The type that was found.
188 * @param req The type that was required.
189 */
190 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
191 log.error(pos, "prob.found.req",
192 problem, found, req);
193 return syms.errType;
194 }
196 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
197 log.error(pos, "prob.found.req.1", problem, found, req, explanation);
198 return syms.errType;
199 }
201 /** Report an error that wrong type tag was found.
202 * @param pos Position to be used for error reporting.
203 * @param required An internationalized string describing the type tag
204 * required.
205 * @param found The type that was found.
206 */
207 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
208 log.error(pos, "type.found.req", found, required);
209 return syms.errType;
210 }
212 /** Report an error that symbol cannot be referenced before super
213 * has been called.
214 * @param pos Position to be used for error reporting.
215 * @param sym The referenced symbol.
216 */
217 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
218 log.error(pos, "cant.ref.before.ctor.called", sym);
219 }
221 /** Report duplicate declaration error.
222 */
223 void duplicateError(DiagnosticPosition pos, Symbol sym) {
224 if (!sym.type.isErroneous()) {
225 log.error(pos, "already.defined", sym, sym.location());
226 }
227 }
229 /** Report array/varargs duplicate declaration
230 */
231 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
232 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
233 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
234 }
235 }
237 /* ************************************************************************
238 * duplicate declaration checking
239 *************************************************************************/
241 /** Check that variable does not hide variable with same name in
242 * immediately enclosing local scope.
243 * @param pos Position for error reporting.
244 * @param v The symbol.
245 * @param s The scope.
246 */
247 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
248 if (s.next != null) {
249 for (Scope.Entry e = s.next.lookup(v.name);
250 e.scope != null && e.sym.owner == v.owner;
251 e = e.next()) {
252 if (e.sym.kind == VAR &&
253 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
254 v.name != names.error) {
255 duplicateError(pos, e.sym);
256 return;
257 }
258 }
259 }
260 }
262 /** Check that a class or interface does not hide a class or
263 * interface with same name in immediately enclosing local scope.
264 * @param pos Position for error reporting.
265 * @param c The symbol.
266 * @param s The scope.
267 */
268 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
269 if (s.next != null) {
270 for (Scope.Entry e = s.next.lookup(c.name);
271 e.scope != null && e.sym.owner == c.owner;
272 e = e.next()) {
273 if (e.sym.kind == TYP &&
274 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
275 c.name != names.error) {
276 duplicateError(pos, e.sym);
277 return;
278 }
279 }
280 }
281 }
283 /** Check that class does not have the same name as one of
284 * its enclosing classes, or as a class defined in its enclosing scope.
285 * return true if class is unique in its enclosing scope.
286 * @param pos Position for error reporting.
287 * @param name The class name.
288 * @param s The enclosing scope.
289 */
290 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
291 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
292 if (e.sym.kind == TYP && e.sym.name != names.error) {
293 duplicateError(pos, e.sym);
294 return false;
295 }
296 }
297 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
298 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
299 duplicateError(pos, sym);
300 return true;
301 }
302 }
303 return true;
304 }
306 /* *************************************************************************
307 * Class name generation
308 **************************************************************************/
310 /** Return name of local class.
311 * This is of the form <enclClass> $ n <classname>
312 * where
313 * enclClass is the flat name of the enclosing class,
314 * classname is the simple name of the local class
315 */
316 Name localClassName(ClassSymbol c) {
317 for (int i=1; ; i++) {
318 Name flatname = names.
319 fromString("" + c.owner.enclClass().flatname +
320 target.syntheticNameChar() + i +
321 c.name);
322 if (compiled.get(flatname) == null) return flatname;
323 }
324 }
326 /* *************************************************************************
327 * Type Checking
328 **************************************************************************/
330 /** Check that a given type is assignable to a given proto-type.
331 * If it is, return the type, otherwise return errType.
332 * @param pos Position to be used for error reporting.
333 * @param found The type that was found.
334 * @param req The type that was required.
335 */
336 Type checkType(DiagnosticPosition pos, Type found, Type req) {
337 if (req.tag == ERROR)
338 return req;
339 if (found.tag == FORALL)
340 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
341 if (req.tag == NONE)
342 return found;
343 if (types.isAssignable(found, req, convertWarner(pos, found, req)))
344 return found;
345 if (found.tag <= DOUBLE && req.tag <= DOUBLE)
346 return typeError(pos, JCDiagnostic.fragment("possible.loss.of.precision"), found, req);
347 if (found.isSuperBound()) {
348 log.error(pos, "assignment.from.super-bound", found);
349 return syms.errType;
350 }
351 if (req.isExtendsBound()) {
352 log.error(pos, "assignment.to.extends-bound", req);
353 return syms.errType;
354 }
355 return typeError(pos, JCDiagnostic.fragment("incompatible.types"), found, req);
356 }
358 /** Instantiate polymorphic type to some prototype, unless
359 * prototype is `anyPoly' in which case polymorphic type
360 * is returned unchanged.
361 */
362 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) {
363 if (pt == Infer.anyPoly && complexInference) {
364 return t;
365 } else if (pt == Infer.anyPoly || pt.tag == NONE) {
366 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
367 return instantiatePoly(pos, t, newpt, warn);
368 } else if (pt.tag == ERROR) {
369 return pt;
370 } else {
371 try {
372 return infer.instantiateExpr(t, pt, warn);
373 } catch (Infer.NoInstanceException ex) {
374 if (ex.isAmbiguous) {
375 JCDiagnostic d = ex.getDiagnostic();
376 log.error(pos,
377 "undetermined.type" + (d!=null ? ".1" : ""),
378 t, d);
379 return syms.errType;
380 } else {
381 JCDiagnostic d = ex.getDiagnostic();
382 return typeError(pos,
383 JCDiagnostic.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
384 t, pt);
385 }
386 }
387 }
388 }
390 /** Check that a given type can be cast to a given target type.
391 * Return the result of the cast.
392 * @param pos Position to be used for error reporting.
393 * @param found The type that is being cast.
394 * @param req The target type of the cast.
395 */
396 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
397 if (found.tag == FORALL) {
398 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
399 return req;
400 } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
401 return req;
402 } else {
403 return typeError(pos,
404 JCDiagnostic.fragment("inconvertible.types"),
405 found, req);
406 }
407 }
408 //where
409 /** Is type a type variable, or a (possibly multi-dimensional) array of
410 * type variables?
411 */
412 boolean isTypeVar(Type t) {
413 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
414 }
416 /** Check that a type is within some bounds.
417 *
418 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
419 * type argument.
420 * @param pos Position to be used for error reporting.
421 * @param a The type that should be bounded by bs.
422 * @param bs The bound.
423 */
424 private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
425 if (a.isUnbound()) {
426 return;
427 } else if (a.tag != WILDCARD) {
428 a = types.upperBound(a);
429 for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
430 if (!types.isSubtype(a, l.head)) {
431 log.error(pos, "not.within.bounds", a);
432 return;
433 }
434 }
435 } else if (a.isExtendsBound()) {
436 if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
437 log.error(pos, "not.within.bounds", a);
438 } else if (a.isSuperBound()) {
439 if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
440 log.error(pos, "not.within.bounds", a);
441 }
442 }
444 /** Check that type is different from 'void'.
445 * @param pos Position to be used for error reporting.
446 * @param t The type to be checked.
447 */
448 Type checkNonVoid(DiagnosticPosition pos, Type t) {
449 if (t.tag == VOID) {
450 log.error(pos, "void.not.allowed.here");
451 return syms.errType;
452 } else {
453 return t;
454 }
455 }
457 /** Check that type is a class or interface type.
458 * @param pos Position to be used for error reporting.
459 * @param t The type to be checked.
460 */
461 Type checkClassType(DiagnosticPosition pos, Type t) {
462 if (t.tag != CLASS && t.tag != ERROR)
463 return typeTagError(pos,
464 JCDiagnostic.fragment("type.req.class"),
465 (t.tag == TYPEVAR)
466 ? JCDiagnostic.fragment("type.parameter", t)
467 : t);
468 else
469 return t;
470 }
472 /** Check that type is a class or interface type.
473 * @param pos Position to be used for error reporting.
474 * @param t The type to be checked.
475 * @param noBounds True if type bounds are illegal here.
476 */
477 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
478 t = checkClassType(pos, t);
479 if (noBounds && t.isParameterized()) {
480 List<Type> args = t.getTypeArguments();
481 while (args.nonEmpty()) {
482 if (args.head.tag == WILDCARD)
483 return typeTagError(pos,
484 log.getLocalizedString("type.req.exact"),
485 args.head);
486 args = args.tail;
487 }
488 }
489 return t;
490 }
492 /** Check that type is a reifiable class, interface or array type.
493 * @param pos Position to be used for error reporting.
494 * @param t The type to be checked.
495 */
496 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
497 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
498 return typeTagError(pos,
499 JCDiagnostic.fragment("type.req.class.array"),
500 t);
501 } else if (!types.isReifiable(t)) {
502 log.error(pos, "illegal.generic.type.for.instof");
503 return syms.errType;
504 } else {
505 return t;
506 }
507 }
509 /** Check that type is a reference type, i.e. a class, interface or array type
510 * or a type variable.
511 * @param pos Position to be used for error reporting.
512 * @param t The type to be checked.
513 */
514 Type checkRefType(DiagnosticPosition pos, Type t) {
515 switch (t.tag) {
516 case CLASS:
517 case ARRAY:
518 case TYPEVAR:
519 case WILDCARD:
520 case ERROR:
521 return t;
522 default:
523 return typeTagError(pos,
524 JCDiagnostic.fragment("type.req.ref"),
525 t);
526 }
527 }
529 /** Check that type is a null or reference type.
530 * @param pos Position to be used for error reporting.
531 * @param t The type to be checked.
532 */
533 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
534 switch (t.tag) {
535 case CLASS:
536 case ARRAY:
537 case TYPEVAR:
538 case WILDCARD:
539 case BOT:
540 case ERROR:
541 return t;
542 default:
543 return typeTagError(pos,
544 JCDiagnostic.fragment("type.req.ref"),
545 t);
546 }
547 }
549 /** Check that flag set does not contain elements of two conflicting sets. s
550 * Return true if it doesn't.
551 * @param pos Position to be used for error reporting.
552 * @param flags The set of flags to be checked.
553 * @param set1 Conflicting flags set #1.
554 * @param set2 Conflicting flags set #2.
555 */
556 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
557 if ((flags & set1) != 0 && (flags & set2) != 0) {
558 log.error(pos,
559 "illegal.combination.of.modifiers",
560 TreeInfo.flagNames(TreeInfo.firstFlag(flags & set1)),
561 TreeInfo.flagNames(TreeInfo.firstFlag(flags & set2)));
562 return false;
563 } else
564 return true;
565 }
567 /** Check that given modifiers are legal for given symbol and
568 * return modifiers together with any implicit modififiers for that symbol.
569 * Warning: we can't use flags() here since this method
570 * is called during class enter, when flags() would cause a premature
571 * completion.
572 * @param pos Position to be used for error reporting.
573 * @param flags The set of modifiers given in a definition.
574 * @param sym The defined symbol.
575 */
576 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
577 long mask;
578 long implicit = 0;
579 switch (sym.kind) {
580 case VAR:
581 if (sym.owner.kind != TYP)
582 mask = LocalVarFlags;
583 else if ((sym.owner.flags_field & INTERFACE) != 0)
584 mask = implicit = InterfaceVarFlags;
585 else
586 mask = VarFlags;
587 break;
588 case MTH:
589 if (sym.name == names.init) {
590 if ((sym.owner.flags_field & ENUM) != 0) {
591 // enum constructors cannot be declared public or
592 // protected and must be implicitly or explicitly
593 // private
594 implicit = PRIVATE;
595 mask = PRIVATE;
596 } else
597 mask = ConstructorFlags;
598 } else if ((sym.owner.flags_field & INTERFACE) != 0)
599 mask = implicit = InterfaceMethodFlags;
600 else {
601 mask = MethodFlags;
602 }
603 // Imply STRICTFP if owner has STRICTFP set.
604 if (((flags|implicit) & Flags.ABSTRACT) == 0)
605 implicit |= sym.owner.flags_field & STRICTFP;
606 break;
607 case TYP:
608 if (sym.isLocal()) {
609 mask = LocalClassFlags;
610 if (sym.name.len == 0) { // Anonymous class
611 // Anonymous classes in static methods are themselves static;
612 // that's why we admit STATIC here.
613 mask |= STATIC;
614 // JLS: Anonymous classes are final.
615 implicit |= FINAL;
616 }
617 if ((sym.owner.flags_field & STATIC) == 0 &&
618 (flags & ENUM) != 0)
619 log.error(pos, "enums.must.be.static");
620 } else if (sym.owner.kind == TYP) {
621 mask = MemberClassFlags;
622 if (sym.owner.owner.kind == PCK ||
623 (sym.owner.flags_field & STATIC) != 0)
624 mask |= STATIC;
625 else if ((flags & ENUM) != 0)
626 log.error(pos, "enums.must.be.static");
627 // Nested interfaces and enums are always STATIC (Spec ???)
628 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
629 } else {
630 mask = ClassFlags;
631 }
632 // Interfaces are always ABSTRACT
633 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
635 if ((flags & ENUM) != 0) {
636 // enums can't be declared abstract or final
637 mask &= ~(ABSTRACT | FINAL);
638 implicit |= implicitEnumFinalFlag(tree);
639 }
640 // Imply STRICTFP if owner has STRICTFP set.
641 implicit |= sym.owner.flags_field & STRICTFP;
642 break;
643 default:
644 throw new AssertionError();
645 }
646 long illegal = flags & StandardFlags & ~mask;
647 if (illegal != 0) {
648 if ((illegal & INTERFACE) != 0) {
649 log.error(pos, "intf.not.allowed.here");
650 mask |= INTERFACE;
651 }
652 else {
653 log.error(pos,
654 "mod.not.allowed.here", TreeInfo.flagNames(illegal));
655 }
656 }
657 else if ((sym.kind == TYP ||
658 // ISSUE: Disallowing abstract&private is no longer appropriate
659 // in the presence of inner classes. Should it be deleted here?
660 checkDisjoint(pos, flags,
661 ABSTRACT,
662 PRIVATE | STATIC))
663 &&
664 checkDisjoint(pos, flags,
665 ABSTRACT | INTERFACE,
666 FINAL | NATIVE | SYNCHRONIZED)
667 &&
668 checkDisjoint(pos, flags,
669 PUBLIC,
670 PRIVATE | PROTECTED)
671 &&
672 checkDisjoint(pos, flags,
673 PRIVATE,
674 PUBLIC | PROTECTED)
675 &&
676 checkDisjoint(pos, flags,
677 FINAL,
678 VOLATILE)
679 &&
680 (sym.kind == TYP ||
681 checkDisjoint(pos, flags,
682 ABSTRACT | NATIVE,
683 STRICTFP))) {
684 // skip
685 }
686 return flags & (mask | ~StandardFlags) | implicit;
687 }
690 /** Determine if this enum should be implicitly final.
691 *
692 * If the enum has no specialized enum contants, it is final.
693 *
694 * If the enum does have specialized enum contants, it is
695 * <i>not</i> final.
696 */
697 private long implicitEnumFinalFlag(JCTree tree) {
698 if (tree.getTag() != JCTree.CLASSDEF) return 0;
699 class SpecialTreeVisitor extends JCTree.Visitor {
700 boolean specialized;
701 SpecialTreeVisitor() {
702 this.specialized = false;
703 };
705 public void visitTree(JCTree tree) { /* no-op */ }
707 public void visitVarDef(JCVariableDecl tree) {
708 if ((tree.mods.flags & ENUM) != 0) {
709 if (tree.init instanceof JCNewClass &&
710 ((JCNewClass) tree.init).def != null) {
711 specialized = true;
712 }
713 }
714 }
715 }
717 SpecialTreeVisitor sts = new SpecialTreeVisitor();
718 JCClassDecl cdef = (JCClassDecl) tree;
719 for (JCTree defs: cdef.defs) {
720 defs.accept(sts);
721 if (sts.specialized) return 0;
722 }
723 return FINAL;
724 }
726 /* *************************************************************************
727 * Type Validation
728 **************************************************************************/
730 /** Validate a type expression. That is,
731 * check that all type arguments of a parametric type are within
732 * their bounds. This must be done in a second phase after type attributon
733 * since a class might have a subclass as type parameter bound. E.g:
734 *
735 * class B<A extends C> { ... }
736 * class C extends B<C> { ... }
737 *
738 * and we can't make sure that the bound is already attributed because
739 * of possible cycles.
740 */
741 private Validator validator = new Validator();
743 /** Visitor method: Validate a type expression, if it is not null, catching
744 * and reporting any completion failures.
745 */
746 void validate(JCTree tree) {
747 try {
748 if (tree != null) tree.accept(validator);
749 } catch (CompletionFailure ex) {
750 completionError(tree.pos(), ex);
751 }
752 }
754 /** Visitor method: Validate a list of type expressions.
755 */
756 void validate(List<? extends JCTree> trees) {
757 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
758 validate(l.head);
759 }
761 /** Visitor method: Validate a list of type parameters.
762 */
763 void validateTypeParams(List<JCTypeParameter> trees) {
764 for (List<JCTypeParameter> l = trees; l.nonEmpty(); l = l.tail)
765 validate(l.head);
766 }
768 /** A visitor class for type validation.
769 */
770 class Validator extends JCTree.Visitor {
772 public void visitTypeArray(JCArrayTypeTree tree) {
773 validate(tree.elemtype);
774 }
776 public void visitTypeApply(JCTypeApply tree) {
777 if (tree.type.tag == CLASS) {
778 List<Type> formals = tree.type.tsym.type.getTypeArguments();
779 List<Type> actuals = tree.type.getTypeArguments();
780 List<JCExpression> args = tree.arguments;
781 List<Type> forms = formals;
782 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
784 // For matching pairs of actual argument types `a' and
785 // formal type parameters with declared bound `b' ...
786 while (args.nonEmpty() && forms.nonEmpty()) {
787 validate(args.head);
789 // exact type arguments needs to know their
790 // bounds (for upper and lower bound
791 // calculations). So we create new TypeVars with
792 // bounds substed with actuals.
793 tvars_buf.append(types.substBound(((TypeVar)forms.head),
794 formals,
795 Type.removeBounds(actuals)));
797 args = args.tail;
798 forms = forms.tail;
799 }
801 args = tree.arguments;
802 List<TypeVar> tvars = tvars_buf.toList();
803 while (args.nonEmpty() && tvars.nonEmpty()) {
804 // Let the actual arguments know their bound
805 args.head.type.withTypeVar(tvars.head);
806 args = args.tail;
807 tvars = tvars.tail;
808 }
810 args = tree.arguments;
811 tvars = tvars_buf.toList();
812 while (args.nonEmpty() && tvars.nonEmpty()) {
813 checkExtends(args.head.pos(),
814 args.head.type,
815 tvars.head);
816 args = args.tail;
817 tvars = tvars.tail;
818 }
820 // Check that this type is either fully parameterized, or
821 // not parameterized at all.
822 if (tree.type.getEnclosingType().isRaw())
823 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
824 if (tree.clazz.getTag() == JCTree.SELECT)
825 visitSelectInternal((JCFieldAccess)tree.clazz);
826 }
827 }
829 public void visitTypeParameter(JCTypeParameter tree) {
830 validate(tree.bounds);
831 checkClassBounds(tree.pos(), tree.type);
832 }
834 @Override
835 public void visitWildcard(JCWildcard tree) {
836 if (tree.inner != null)
837 validate(tree.inner);
838 }
840 public void visitSelect(JCFieldAccess tree) {
841 if (tree.type.tag == CLASS) {
842 visitSelectInternal(tree);
844 // Check that this type is either fully parameterized, or
845 // not parameterized at all.
846 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
847 log.error(tree.pos(), "improperly.formed.type.param.missing");
848 }
849 }
850 public void visitSelectInternal(JCFieldAccess tree) {
851 if (tree.type.getEnclosingType().tag != CLASS &&
852 tree.selected.type.isParameterized()) {
853 // The enclosing type is not a class, so we are
854 // looking at a static member type. However, the
855 // qualifying expression is parameterized.
856 log.error(tree.pos(), "cant.select.static.class.from.param.type");
857 } else {
858 // otherwise validate the rest of the expression
859 validate(tree.selected);
860 }
861 }
863 /** Default visitor method: do nothing.
864 */
865 public void visitTree(JCTree tree) {
866 }
867 }
869 /* *************************************************************************
870 * Exception checking
871 **************************************************************************/
873 /* The following methods treat classes as sets that contain
874 * the class itself and all their subclasses
875 */
877 /** Is given type a subtype of some of the types in given list?
878 */
879 boolean subset(Type t, List<Type> ts) {
880 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
881 if (types.isSubtype(t, l.head)) return true;
882 return false;
883 }
885 /** Is given type a subtype or supertype of
886 * some of the types in given list?
887 */
888 boolean intersects(Type t, List<Type> ts) {
889 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
890 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
891 return false;
892 }
894 /** Add type set to given type list, unless it is a subclass of some class
895 * in the list.
896 */
897 List<Type> incl(Type t, List<Type> ts) {
898 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
899 }
901 /** Remove type set from type set list.
902 */
903 List<Type> excl(Type t, List<Type> ts) {
904 if (ts.isEmpty()) {
905 return ts;
906 } else {
907 List<Type> ts1 = excl(t, ts.tail);
908 if (types.isSubtype(ts.head, t)) return ts1;
909 else if (ts1 == ts.tail) return ts;
910 else return ts1.prepend(ts.head);
911 }
912 }
914 /** Form the union of two type set lists.
915 */
916 List<Type> union(List<Type> ts1, List<Type> ts2) {
917 List<Type> ts = ts1;
918 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
919 ts = incl(l.head, ts);
920 return ts;
921 }
923 /** Form the difference of two type lists.
924 */
925 List<Type> diff(List<Type> ts1, List<Type> ts2) {
926 List<Type> ts = ts1;
927 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
928 ts = excl(l.head, ts);
929 return ts;
930 }
932 /** Form the intersection of two type lists.
933 */
934 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
935 List<Type> ts = List.nil();
936 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
937 if (subset(l.head, ts2)) ts = incl(l.head, ts);
938 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
939 if (subset(l.head, ts1)) ts = incl(l.head, ts);
940 return ts;
941 }
943 /** Is exc an exception symbol that need not be declared?
944 */
945 boolean isUnchecked(ClassSymbol exc) {
946 return
947 exc.kind == ERR ||
948 exc.isSubClass(syms.errorType.tsym, types) ||
949 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
950 }
952 /** Is exc an exception type that need not be declared?
953 */
954 boolean isUnchecked(Type exc) {
955 return
956 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
957 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
958 exc.tag == BOT;
959 }
961 /** Same, but handling completion failures.
962 */
963 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
964 try {
965 return isUnchecked(exc);
966 } catch (CompletionFailure ex) {
967 completionError(pos, ex);
968 return true;
969 }
970 }
972 /** Is exc handled by given exception list?
973 */
974 boolean isHandled(Type exc, List<Type> handled) {
975 return isUnchecked(exc) || subset(exc, handled);
976 }
978 /** Return all exceptions in thrown list that are not in handled list.
979 * @param thrown The list of thrown exceptions.
980 * @param handled The list of handled exceptions.
981 */
982 List<Type> unHandled(List<Type> thrown, List<Type> handled) {
983 List<Type> unhandled = List.nil();
984 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
985 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
986 return unhandled;
987 }
989 /* *************************************************************************
990 * Overriding/Implementation checking
991 **************************************************************************/
993 /** The level of access protection given by a flag set,
994 * where PRIVATE is highest and PUBLIC is lowest.
995 */
996 static int protection(long flags) {
997 switch ((short)(flags & AccessFlags)) {
998 case PRIVATE: return 3;
999 case PROTECTED: return 1;
1000 default:
1001 case PUBLIC: return 0;
1002 case 0: return 2;
1003 }
1004 }
1006 /** A string describing the access permission given by a flag set.
1007 * This always returns a space-separated list of Java Keywords.
1008 */
1009 private static String protectionString(long flags) {
1010 long flags1 = flags & AccessFlags;
1011 return (flags1 == 0) ? "package" : TreeInfo.flagNames(flags1);
1012 }
1014 /** A customized "cannot override" error message.
1015 * @param m The overriding method.
1016 * @param other The overridden method.
1017 * @return An internationalized string.
1018 */
1019 static Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1020 String key;
1021 if ((other.owner.flags() & INTERFACE) == 0)
1022 key = "cant.override";
1023 else if ((m.owner.flags() & INTERFACE) == 0)
1024 key = "cant.implement";
1025 else
1026 key = "clashes.with";
1027 return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
1028 }
1030 /** A customized "override" warning message.
1031 * @param m The overriding method.
1032 * @param other The overridden method.
1033 * @return An internationalized string.
1034 */
1035 static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1036 String key;
1037 if ((other.owner.flags() & INTERFACE) == 0)
1038 key = "unchecked.override";
1039 else if ((m.owner.flags() & INTERFACE) == 0)
1040 key = "unchecked.implement";
1041 else
1042 key = "unchecked.clash.with";
1043 return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
1044 }
1046 /** A customized "override" warning message.
1047 * @param m The overriding method.
1048 * @param other The overridden method.
1049 * @return An internationalized string.
1050 */
1051 static Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1052 String key;
1053 if ((other.owner.flags() & INTERFACE) == 0)
1054 key = "varargs.override";
1055 else if ((m.owner.flags() & INTERFACE) == 0)
1056 key = "varargs.implement";
1057 else
1058 key = "varargs.clash.with";
1059 return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
1060 }
1062 /** Check that this method conforms with overridden method 'other'.
1063 * where `origin' is the class where checking started.
1064 * Complications:
1065 * (1) Do not check overriding of synthetic methods
1066 * (reason: they might be final).
1067 * todo: check whether this is still necessary.
1068 * (2) Admit the case where an interface proxy throws fewer exceptions
1069 * than the method it implements. Augment the proxy methods with the
1070 * undeclared exceptions in this case.
1071 * (3) When generics are enabled, admit the case where an interface proxy
1072 * has a result type
1073 * extended by the result type of the method it implements.
1074 * Change the proxies result type to the smaller type in this case.
1075 *
1076 * @param tree The tree from which positions
1077 * are extracted for errors.
1078 * @param m The overriding method.
1079 * @param other The overridden method.
1080 * @param origin The class of which the overriding method
1081 * is a member.
1082 */
1083 void checkOverride(JCTree tree,
1084 MethodSymbol m,
1085 MethodSymbol other,
1086 ClassSymbol origin) {
1087 // Don't check overriding of synthetic methods or by bridge methods.
1088 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1089 return;
1090 }
1092 // Error if static method overrides instance method (JLS 8.4.6.2).
1093 if ((m.flags() & STATIC) != 0 &&
1094 (other.flags() & STATIC) == 0) {
1095 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1096 cannotOverride(m, other));
1097 return;
1098 }
1100 // Error if instance method overrides static or final
1101 // method (JLS 8.4.6.1).
1102 if ((other.flags() & FINAL) != 0 ||
1103 (m.flags() & STATIC) == 0 &&
1104 (other.flags() & STATIC) != 0) {
1105 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1106 cannotOverride(m, other),
1107 TreeInfo.flagNames(other.flags() & (FINAL | STATIC)));
1108 return;
1109 }
1111 if ((m.owner.flags() & ANNOTATION) != 0) {
1112 // handled in validateAnnotationMethod
1113 return;
1114 }
1116 // Error if overriding method has weaker access (JLS 8.4.6.3).
1117 if ((origin.flags() & INTERFACE) == 0 &&
1118 protection(m.flags()) > protection(other.flags())) {
1119 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1120 cannotOverride(m, other),
1121 protectionString(other.flags()));
1122 return;
1124 }
1126 Type mt = types.memberType(origin.type, m);
1127 Type ot = types.memberType(origin.type, other);
1128 // Error if overriding result type is different
1129 // (or, in the case of generics mode, not a subtype) of
1130 // overridden result type. We have to rename any type parameters
1131 // before comparing types.
1132 List<Type> mtvars = mt.getTypeArguments();
1133 List<Type> otvars = ot.getTypeArguments();
1134 Type mtres = mt.getReturnType();
1135 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1137 overrideWarner.warned = false;
1138 boolean resultTypesOK =
1139 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1140 if (!resultTypesOK) {
1141 if (!source.allowCovariantReturns() &&
1142 m.owner != origin &&
1143 m.owner.isSubClass(other.owner, types)) {
1144 // allow limited interoperability with covariant returns
1145 } else {
1146 typeError(TreeInfo.diagnosticPositionFor(m, tree),
1147 JCDiagnostic.fragment("override.incompatible.ret",
1148 cannotOverride(m, other)),
1149 mtres, otres);
1150 return;
1151 }
1152 } else if (overrideWarner.warned) {
1153 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1154 "prob.found.req",
1155 JCDiagnostic.fragment("override.unchecked.ret",
1156 uncheckedOverrides(m, other)),
1157 mtres, otres);
1158 }
1160 // Error if overriding method throws an exception not reported
1161 // by overridden method.
1162 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1163 List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
1164 if (unhandled.nonEmpty()) {
1165 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1166 "override.meth.doesnt.throw",
1167 cannotOverride(m, other),
1168 unhandled.head);
1169 return;
1170 }
1172 // Optional warning if varargs don't agree
1173 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1174 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
1175 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1176 ((m.flags() & Flags.VARARGS) != 0)
1177 ? "override.varargs.missing"
1178 : "override.varargs.extra",
1179 varargsOverrides(m, other));
1180 }
1182 // Warn if instance method overrides bridge method (compiler spec ??)
1183 if ((other.flags() & BRIDGE) != 0) {
1184 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1185 uncheckedOverrides(m, other));
1186 }
1188 // Warn if a deprecated method overridden by a non-deprecated one.
1189 if ((other.flags() & DEPRECATED) != 0
1190 && (m.flags() & DEPRECATED) == 0
1191 && m.outermostClass() != other.outermostClass()
1192 && !isDeprecatedOverrideIgnorable(other, origin)) {
1193 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1194 }
1195 }
1196 // where
1197 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1198 // If the method, m, is defined in an interface, then ignore the issue if the method
1199 // is only inherited via a supertype and also implemented in the supertype,
1200 // because in that case, we will rediscover the issue when examining the method
1201 // in the supertype.
1202 // If the method, m, is not defined in an interface, then the only time we need to
1203 // address the issue is when the method is the supertype implemementation: any other
1204 // case, we will have dealt with when examining the supertype classes
1205 ClassSymbol mc = m.enclClass();
1206 Type st = types.supertype(origin.type);
1207 if (st.tag != CLASS)
1208 return true;
1209 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1211 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1212 List<Type> intfs = types.interfaces(origin.type);
1213 return (intfs.contains(mc.type) ? false : (stimpl != null));
1214 }
1215 else
1216 return (stimpl != m);
1217 }
1220 // used to check if there were any unchecked conversions
1221 Warner overrideWarner = new Warner();
1223 /** Check that a class does not inherit two concrete methods
1224 * with the same signature.
1225 * @param pos Position to be used for error reporting.
1226 * @param site The class type to be checked.
1227 */
1228 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1229 Type sup = types.supertype(site);
1230 if (sup.tag != CLASS) return;
1232 for (Type t1 = sup;
1233 t1.tsym.type.isParameterized();
1234 t1 = types.supertype(t1)) {
1235 for (Scope.Entry e1 = t1.tsym.members().elems;
1236 e1 != null;
1237 e1 = e1.sibling) {
1238 Symbol s1 = e1.sym;
1239 if (s1.kind != MTH ||
1240 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1241 !s1.isInheritedIn(site.tsym, types) ||
1242 ((MethodSymbol)s1).implementation(site.tsym,
1243 types,
1244 true) != s1)
1245 continue;
1246 Type st1 = types.memberType(t1, s1);
1247 int s1ArgsLength = st1.getParameterTypes().length();
1248 if (st1 == s1.type) continue;
1250 for (Type t2 = sup;
1251 t2.tag == CLASS;
1252 t2 = types.supertype(t2)) {
1253 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1254 e2.scope != null;
1255 e2 = e2.next()) {
1256 Symbol s2 = e2.sym;
1257 if (s2 == s1 ||
1258 s2.kind != MTH ||
1259 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1260 s2.type.getParameterTypes().length() != s1ArgsLength ||
1261 !s2.isInheritedIn(site.tsym, types) ||
1262 ((MethodSymbol)s2).implementation(site.tsym,
1263 types,
1264 true) != s2)
1265 continue;
1266 Type st2 = types.memberType(t2, s2);
1267 if (types.overrideEquivalent(st1, st2))
1268 log.error(pos, "concrete.inheritance.conflict",
1269 s1, t1, s2, t2, sup);
1270 }
1271 }
1272 }
1273 }
1274 }
1276 /** Check that classes (or interfaces) do not each define an abstract
1277 * method with same name and arguments but incompatible return types.
1278 * @param pos Position to be used for error reporting.
1279 * @param t1 The first argument type.
1280 * @param t2 The second argument type.
1281 */
1282 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1283 Type t1,
1284 Type t2) {
1285 return checkCompatibleAbstracts(pos, t1, t2,
1286 types.makeCompoundType(t1, t2));
1287 }
1289 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1290 Type t1,
1291 Type t2,
1292 Type site) {
1293 Symbol sym = firstIncompatibility(t1, t2, site);
1294 if (sym != null) {
1295 log.error(pos, "types.incompatible.diff.ret",
1296 t1, t2, sym.name +
1297 "(" + types.memberType(t2, sym).getParameterTypes() + ")");
1298 return false;
1299 }
1300 return true;
1301 }
1303 /** Return the first method which is defined with same args
1304 * but different return types in two given interfaces, or null if none
1305 * exists.
1306 * @param t1 The first type.
1307 * @param t2 The second type.
1308 * @param site The most derived type.
1309 * @returns symbol from t2 that conflicts with one in t1.
1310 */
1311 private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
1312 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1313 closure(t1, interfaces1);
1314 Map<TypeSymbol,Type> interfaces2;
1315 if (t1 == t2)
1316 interfaces2 = interfaces1;
1317 else
1318 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1320 for (Type t3 : interfaces1.values()) {
1321 for (Type t4 : interfaces2.values()) {
1322 Symbol s = firstDirectIncompatibility(t3, t4, site);
1323 if (s != null) return s;
1324 }
1325 }
1326 return null;
1327 }
1329 /** Compute all the supertypes of t, indexed by type symbol. */
1330 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1331 if (t.tag != CLASS) return;
1332 if (typeMap.put(t.tsym, t) == null) {
1333 closure(types.supertype(t), typeMap);
1334 for (Type i : types.interfaces(t))
1335 closure(i, typeMap);
1336 }
1337 }
1339 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1340 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1341 if (t.tag != CLASS) return;
1342 if (typesSkip.get(t.tsym) != null) return;
1343 if (typeMap.put(t.tsym, t) == null) {
1344 closure(types.supertype(t), typesSkip, typeMap);
1345 for (Type i : types.interfaces(t))
1346 closure(i, typesSkip, typeMap);
1347 }
1348 }
1350 /** Return the first method in t2 that conflicts with a method from t1. */
1351 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
1352 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1353 Symbol s1 = e1.sym;
1354 Type st1 = null;
1355 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1356 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1357 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1358 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1359 Symbol s2 = e2.sym;
1360 if (s1 == s2) continue;
1361 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1362 if (st1 == null) st1 = types.memberType(t1, s1);
1363 Type st2 = types.memberType(t2, s2);
1364 if (types.overrideEquivalent(st1, st2)) {
1365 List<Type> tvars1 = st1.getTypeArguments();
1366 List<Type> tvars2 = st2.getTypeArguments();
1367 Type rt1 = st1.getReturnType();
1368 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1369 boolean compat =
1370 types.isSameType(rt1, rt2) ||
1371 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1372 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1373 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1374 checkCommonOverriderIn(s1,s2,site);
1375 if (!compat) return s2;
1376 }
1377 }
1378 }
1379 return null;
1380 }
1381 //WHERE
1382 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1383 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1384 Type st1 = types.memberType(site, s1);
1385 Type st2 = types.memberType(site, s2);
1386 closure(site, supertypes);
1387 for (Type t : supertypes.values()) {
1388 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1389 Symbol s3 = e.sym;
1390 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1391 Type st3 = types.memberType(site,s3);
1392 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1393 if (s3.owner == site.tsym) {
1394 return true;
1395 }
1396 List<Type> tvars1 = st1.getTypeArguments();
1397 List<Type> tvars2 = st2.getTypeArguments();
1398 List<Type> tvars3 = st3.getTypeArguments();
1399 Type rt1 = st1.getReturnType();
1400 Type rt2 = st2.getReturnType();
1401 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1402 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1403 boolean compat =
1404 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1405 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1406 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1407 if (compat)
1408 return true;
1409 }
1410 }
1411 }
1412 return false;
1413 }
1415 /** Check that a given method conforms with any method it overrides.
1416 * @param tree The tree from which positions are extracted
1417 * for errors.
1418 * @param m The overriding method.
1419 */
1420 void checkOverride(JCTree tree, MethodSymbol m) {
1421 ClassSymbol origin = (ClassSymbol)m.owner;
1422 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1423 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1424 log.error(tree.pos(), "enum.no.finalize");
1425 return;
1426 }
1427 for (Type t = types.supertype(origin.type); t.tag == CLASS;
1428 t = types.supertype(t)) {
1429 TypeSymbol c = t.tsym;
1430 Scope.Entry e = c.members().lookup(m.name);
1431 while (e.scope != null) {
1432 if (m.overrides(e.sym, origin, types, false))
1433 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1434 else if (e.sym.isInheritedIn(origin, types) && !m.isConstructor()) {
1435 Type er1 = m.erasure(types);
1436 Type er2 = e.sym.erasure(types);
1437 if (types.isSameType(er1,er2)) {
1438 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1439 "name.clash.same.erasure.no.override",
1440 m, m.location(),
1441 e.sym, e.sym.location());
1442 }
1443 }
1444 e = e.next();
1445 }
1446 }
1447 }
1449 /** Check that all abstract members of given class have definitions.
1450 * @param pos Position to be used for error reporting.
1451 * @param c The class.
1452 */
1453 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1454 try {
1455 MethodSymbol undef = firstUndef(c, c);
1456 if (undef != null) {
1457 if ((c.flags() & ENUM) != 0 &&
1458 types.supertype(c.type).tsym == syms.enumSym &&
1459 (c.flags() & FINAL) == 0) {
1460 // add the ABSTRACT flag to an enum
1461 c.flags_field |= ABSTRACT;
1462 } else {
1463 MethodSymbol undef1 =
1464 new MethodSymbol(undef.flags(), undef.name,
1465 types.memberType(c.type, undef), undef.owner);
1466 log.error(pos, "does.not.override.abstract",
1467 c, undef1, undef1.location());
1468 }
1469 }
1470 } catch (CompletionFailure ex) {
1471 completionError(pos, ex);
1472 }
1473 }
1474 //where
1475 /** Return first abstract member of class `c' that is not defined
1476 * in `impl', null if there is none.
1477 */
1478 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1479 MethodSymbol undef = null;
1480 // Do not bother to search in classes that are not abstract,
1481 // since they cannot have abstract members.
1482 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1483 Scope s = c.members();
1484 for (Scope.Entry e = s.elems;
1485 undef == null && e != null;
1486 e = e.sibling) {
1487 if (e.sym.kind == MTH &&
1488 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1489 MethodSymbol absmeth = (MethodSymbol)e.sym;
1490 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1491 if (implmeth == null || implmeth == absmeth)
1492 undef = absmeth;
1493 }
1494 }
1495 if (undef == null) {
1496 Type st = types.supertype(c.type);
1497 if (st.tag == CLASS)
1498 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1499 }
1500 for (List<Type> l = types.interfaces(c.type);
1501 undef == null && l.nonEmpty();
1502 l = l.tail) {
1503 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1504 }
1505 }
1506 return undef;
1507 }
1509 /** Check for cyclic references. Issue an error if the
1510 * symbol of the type referred to has a LOCKED flag set.
1511 *
1512 * @param pos Position to be used for error reporting.
1513 * @param t The type referred to.
1514 */
1515 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1516 checkNonCyclicInternal(pos, t);
1517 }
1520 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1521 checkNonCyclic1(pos, t, new HashSet<TypeVar>());
1522 }
1524 private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
1525 final TypeVar tv;
1526 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1527 return;
1528 if (seen.contains(t)) {
1529 tv = (TypeVar)t;
1530 tv.bound = new ErrorType();
1531 log.error(pos, "cyclic.inheritance", t);
1532 } else if (t.tag == TYPEVAR) {
1533 tv = (TypeVar)t;
1534 seen.add(tv);
1535 for (Type b : types.getBounds(tv))
1536 checkNonCyclic1(pos, b, seen);
1537 }
1538 }
1540 /** Check for cyclic references. Issue an error if the
1541 * symbol of the type referred to has a LOCKED flag set.
1542 *
1543 * @param pos Position to be used for error reporting.
1544 * @param t The type referred to.
1545 * @returns True if the check completed on all attributed classes
1546 */
1547 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1548 boolean complete = true; // was the check complete?
1549 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1550 Symbol c = t.tsym;
1551 if ((c.flags_field & ACYCLIC) != 0) return true;
1553 if ((c.flags_field & LOCKED) != 0) {
1554 noteCyclic(pos, (ClassSymbol)c);
1555 } else if (!c.type.isErroneous()) {
1556 try {
1557 c.flags_field |= LOCKED;
1558 if (c.type.tag == CLASS) {
1559 ClassType clazz = (ClassType)c.type;
1560 if (clazz.interfaces_field != null)
1561 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1562 complete &= checkNonCyclicInternal(pos, l.head);
1563 if (clazz.supertype_field != null) {
1564 Type st = clazz.supertype_field;
1565 if (st != null && st.tag == CLASS)
1566 complete &= checkNonCyclicInternal(pos, st);
1567 }
1568 if (c.owner.kind == TYP)
1569 complete &= checkNonCyclicInternal(pos, c.owner.type);
1570 }
1571 } finally {
1572 c.flags_field &= ~LOCKED;
1573 }
1574 }
1575 if (complete)
1576 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1577 if (complete) c.flags_field |= ACYCLIC;
1578 return complete;
1579 }
1581 /** Note that we found an inheritance cycle. */
1582 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1583 log.error(pos, "cyclic.inheritance", c);
1584 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1585 l.head = new ErrorType((ClassSymbol)l.head.tsym);
1586 Type st = types.supertype(c.type);
1587 if (st.tag == CLASS)
1588 ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
1589 c.type = new ErrorType(c);
1590 c.flags_field |= ACYCLIC;
1591 }
1593 /** Check that all methods which implement some
1594 * method conform to the method they implement.
1595 * @param tree The class definition whose members are checked.
1596 */
1597 void checkImplementations(JCClassDecl tree) {
1598 checkImplementations(tree, tree.sym);
1599 }
1600 //where
1601 /** Check that all methods which implement some
1602 * method in `ic' conform to the method they implement.
1603 */
1604 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
1605 ClassSymbol origin = tree.sym;
1606 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
1607 ClassSymbol lc = (ClassSymbol)l.head.tsym;
1608 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
1609 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
1610 if (e.sym.kind == MTH &&
1611 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
1612 MethodSymbol absmeth = (MethodSymbol)e.sym;
1613 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
1614 if (implmeth != null && implmeth != absmeth &&
1615 (implmeth.owner.flags() & INTERFACE) ==
1616 (origin.flags() & INTERFACE)) {
1617 // don't check if implmeth is in a class, yet
1618 // origin is an interface. This case arises only
1619 // if implmeth is declared in Object. The reason is
1620 // that interfaces really don't inherit from
1621 // Object it's just that the compiler represents
1622 // things that way.
1623 checkOverride(tree, implmeth, absmeth, origin);
1624 }
1625 }
1626 }
1627 }
1628 }
1629 }
1631 /** Check that all abstract methods implemented by a class are
1632 * mutually compatible.
1633 * @param pos Position to be used for error reporting.
1634 * @param c The class whose interfaces are checked.
1635 */
1636 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
1637 List<Type> supertypes = types.interfaces(c);
1638 Type supertype = types.supertype(c);
1639 if (supertype.tag == CLASS &&
1640 (supertype.tsym.flags() & ABSTRACT) != 0)
1641 supertypes = supertypes.prepend(supertype);
1642 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
1643 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
1644 !checkCompatibleAbstracts(pos, l.head, l.head, c))
1645 return;
1646 for (List<Type> m = supertypes; m != l; m = m.tail)
1647 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
1648 return;
1649 }
1650 checkCompatibleConcretes(pos, c);
1651 }
1653 /** Check that class c does not implement directly or indirectly
1654 * the same parameterized interface with two different argument lists.
1655 * @param pos Position to be used for error reporting.
1656 * @param type The type whose interfaces are checked.
1657 */
1658 void checkClassBounds(DiagnosticPosition pos, Type type) {
1659 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
1660 }
1661 //where
1662 /** Enter all interfaces of type `type' into the hash table `seensofar'
1663 * with their class symbol as key and their type as value. Make
1664 * sure no class is entered with two different types.
1665 */
1666 void checkClassBounds(DiagnosticPosition pos,
1667 Map<TypeSymbol,Type> seensofar,
1668 Type type) {
1669 if (type.isErroneous()) return;
1670 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
1671 Type it = l.head;
1672 Type oldit = seensofar.put(it.tsym, it);
1673 if (oldit != null) {
1674 List<Type> oldparams = oldit.allparams();
1675 List<Type> newparams = it.allparams();
1676 if (!types.containsTypeEquivalent(oldparams, newparams))
1677 log.error(pos, "cant.inherit.diff.arg",
1678 it.tsym, Type.toString(oldparams),
1679 Type.toString(newparams));
1680 }
1681 checkClassBounds(pos, seensofar, it);
1682 }
1683 Type st = types.supertype(type);
1684 if (st != null) checkClassBounds(pos, seensofar, st);
1685 }
1687 /** Enter interface into into set.
1688 * If it existed already, issue a "repeated interface" error.
1689 */
1690 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
1691 if (its.contains(it))
1692 log.error(pos, "repeated.interface");
1693 else {
1694 its.add(it);
1695 }
1696 }
1698 /* *************************************************************************
1699 * Check annotations
1700 **************************************************************************/
1702 /** Annotation types are restricted to primitives, String, an
1703 * enum, an annotation, Class, Class<?>, Class<? extends
1704 * Anything>, arrays of the preceding.
1705 */
1706 void validateAnnotationType(JCTree restype) {
1707 // restype may be null if an error occurred, so don't bother validating it
1708 if (restype != null) {
1709 validateAnnotationType(restype.pos(), restype.type);
1710 }
1711 }
1713 void validateAnnotationType(DiagnosticPosition pos, Type type) {
1714 if (type.isPrimitive()) return;
1715 if (types.isSameType(type, syms.stringType)) return;
1716 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
1717 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
1718 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
1719 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
1720 validateAnnotationType(pos, types.elemtype(type));
1721 return;
1722 }
1723 log.error(pos, "invalid.annotation.member.type");
1724 }
1726 /**
1727 * "It is also a compile-time error if any method declared in an
1728 * annotation type has a signature that is override-equivalent to
1729 * that of any public or protected method declared in class Object
1730 * or in the interface annotation.Annotation."
1731 *
1732 * @jls3 9.6 Annotation Types
1733 */
1734 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
1735 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
1736 Scope s = sup.tsym.members();
1737 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
1738 if (e.sym.kind == MTH &&
1739 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
1740 types.overrideEquivalent(m.type, e.sym.type))
1741 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
1742 }
1743 }
1744 }
1746 /** Check the annotations of a symbol.
1747 */
1748 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
1749 if (skipAnnotations) return;
1750 for (JCAnnotation a : annotations)
1751 validateAnnotation(a, s);
1752 }
1754 /** Check an annotation of a symbol.
1755 */
1756 public void validateAnnotation(JCAnnotation a, Symbol s) {
1757 validateAnnotation(a);
1759 if (!annotationApplicable(a, s))
1760 log.error(a.pos(), "annotation.type.not.applicable");
1762 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
1763 if (!isOverrider(s))
1764 log.error(a.pos(), "method.does.not.override.superclass");
1765 }
1766 }
1768 /** Is s a method symbol that overrides a method in a superclass? */
1769 boolean isOverrider(Symbol s) {
1770 if (s.kind != MTH || s.isStatic())
1771 return false;
1772 MethodSymbol m = (MethodSymbol)s;
1773 TypeSymbol owner = (TypeSymbol)m.owner;
1774 for (Type sup : types.closure(owner.type)) {
1775 if (sup == owner.type)
1776 continue; // skip "this"
1777 Scope scope = sup.tsym.members();
1778 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
1779 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
1780 return true;
1781 }
1782 }
1783 return false;
1784 }
1786 /** Is the annotation applicable to the symbol? */
1787 boolean annotationApplicable(JCAnnotation a, Symbol s) {
1788 Attribute.Compound atTarget =
1789 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
1790 if (atTarget == null) return true;
1791 Attribute atValue = atTarget.member(names.value);
1792 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
1793 Attribute.Array arr = (Attribute.Array) atValue;
1794 for (Attribute app : arr.values) {
1795 if (!(app instanceof Attribute.Enum)) return true; // recovery
1796 Attribute.Enum e = (Attribute.Enum) app;
1797 if (e.value.name == names.TYPE)
1798 { if (s.kind == TYP) return true; }
1799 else if (e.value.name == names.FIELD)
1800 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
1801 else if (e.value.name == names.METHOD)
1802 { if (s.kind == MTH && !s.isConstructor()) return true; }
1803 else if (e.value.name == names.PARAMETER)
1804 { if (s.kind == VAR &&
1805 s.owner.kind == MTH &&
1806 (s.flags() & PARAMETER) != 0)
1807 return true;
1808 }
1809 else if (e.value.name == names.CONSTRUCTOR)
1810 { if (s.kind == MTH && s.isConstructor()) return true; }
1811 else if (e.value.name == names.LOCAL_VARIABLE)
1812 { if (s.kind == VAR && s.owner.kind == MTH &&
1813 (s.flags() & PARAMETER) == 0)
1814 return true;
1815 }
1816 else if (e.value.name == names.ANNOTATION_TYPE)
1817 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
1818 return true;
1819 }
1820 else if (e.value.name == names.PACKAGE)
1821 { if (s.kind == PCK) return true; }
1822 else
1823 return true; // recovery
1824 }
1825 return false;
1826 }
1828 /** Check an annotation value.
1829 */
1830 public void validateAnnotation(JCAnnotation a) {
1831 if (a.type.isErroneous()) return;
1833 // collect an inventory of the members
1834 Set<MethodSymbol> members = new HashSet<MethodSymbol>();
1835 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
1836 e != null;
1837 e = e.sibling)
1838 if (e.sym.kind == MTH)
1839 members.add((MethodSymbol) e.sym);
1841 // count them off as they're annotated
1842 for (JCTree arg : a.args) {
1843 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
1844 JCAssign assign = (JCAssign) arg;
1845 Symbol m = TreeInfo.symbol(assign.lhs);
1846 if (m == null || m.type.isErroneous()) continue;
1847 if (!members.remove(m))
1848 log.error(arg.pos(), "duplicate.annotation.member.value",
1849 m.name, a.type);
1850 if (assign.rhs.getTag() == ANNOTATION)
1851 validateAnnotation((JCAnnotation)assign.rhs);
1852 }
1854 // all the remaining ones better have default values
1855 for (MethodSymbol m : members)
1856 if (m.defaultValue == null && !m.type.isErroneous())
1857 log.error(a.pos(), "annotation.missing.default.value",
1858 a.type, m.name);
1860 // special case: java.lang.annotation.Target must not have
1861 // repeated values in its value member
1862 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
1863 a.args.tail == null)
1864 return;
1866 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
1867 JCAssign assign = (JCAssign) a.args.head;
1868 Symbol m = TreeInfo.symbol(assign.lhs);
1869 if (m.name != names.value) return;
1870 JCTree rhs = assign.rhs;
1871 if (rhs.getTag() != JCTree.NEWARRAY) return;
1872 JCNewArray na = (JCNewArray) rhs;
1873 Set<Symbol> targets = new HashSet<Symbol>();
1874 for (JCTree elem : na.elems) {
1875 if (!targets.add(TreeInfo.symbol(elem))) {
1876 log.error(elem.pos(), "repeated.annotation.target");
1877 }
1878 }
1879 }
1881 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
1882 if (allowAnnotations &&
1883 lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
1884 (s.flags() & DEPRECATED) != 0 &&
1885 !syms.deprecatedType.isErroneous() &&
1886 s.attribute(syms.deprecatedType.tsym) == null) {
1887 log.warning(pos, "missing.deprecated.annotation");
1888 }
1889 }
1891 /* *************************************************************************
1892 * Check for recursive annotation elements.
1893 **************************************************************************/
1895 /** Check for cycles in the graph of annotation elements.
1896 */
1897 void checkNonCyclicElements(JCClassDecl tree) {
1898 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
1899 assert (tree.sym.flags_field & LOCKED) == 0;
1900 try {
1901 tree.sym.flags_field |= LOCKED;
1902 for (JCTree def : tree.defs) {
1903 if (def.getTag() != JCTree.METHODDEF) continue;
1904 JCMethodDecl meth = (JCMethodDecl)def;
1905 checkAnnotationResType(meth.pos(), meth.restype.type);
1906 }
1907 } finally {
1908 tree.sym.flags_field &= ~LOCKED;
1909 tree.sym.flags_field |= ACYCLIC_ANN;
1910 }
1911 }
1913 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
1914 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
1915 return;
1916 if ((tsym.flags_field & LOCKED) != 0) {
1917 log.error(pos, "cyclic.annotation.element");
1918 return;
1919 }
1920 try {
1921 tsym.flags_field |= LOCKED;
1922 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
1923 Symbol s = e.sym;
1924 if (s.kind != Kinds.MTH)
1925 continue;
1926 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
1927 }
1928 } finally {
1929 tsym.flags_field &= ~LOCKED;
1930 tsym.flags_field |= ACYCLIC_ANN;
1931 }
1932 }
1934 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
1935 switch (type.tag) {
1936 case TypeTags.CLASS:
1937 if ((type.tsym.flags() & ANNOTATION) != 0)
1938 checkNonCyclicElementsInternal(pos, type.tsym);
1939 break;
1940 case TypeTags.ARRAY:
1941 checkAnnotationResType(pos, types.elemtype(type));
1942 break;
1943 default:
1944 break; // int etc
1945 }
1946 }
1948 /* *************************************************************************
1949 * Check for cycles in the constructor call graph.
1950 **************************************************************************/
1952 /** Check for cycles in the graph of constructors calling other
1953 * constructors.
1954 */
1955 void checkCyclicConstructors(JCClassDecl tree) {
1956 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
1958 // enter each constructor this-call into the map
1959 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1960 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
1961 if (app == null) continue;
1962 JCMethodDecl meth = (JCMethodDecl) l.head;
1963 if (TreeInfo.name(app.meth) == names._this) {
1964 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
1965 } else {
1966 meth.sym.flags_field |= ACYCLIC;
1967 }
1968 }
1970 // Check for cycles in the map
1971 Symbol[] ctors = new Symbol[0];
1972 ctors = callMap.keySet().toArray(ctors);
1973 for (Symbol caller : ctors) {
1974 checkCyclicConstructor(tree, caller, callMap);
1975 }
1976 }
1978 /** Look in the map to see if the given constructor is part of a
1979 * call cycle.
1980 */
1981 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
1982 Map<Symbol,Symbol> callMap) {
1983 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
1984 if ((ctor.flags_field & LOCKED) != 0) {
1985 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
1986 "recursive.ctor.invocation");
1987 } else {
1988 ctor.flags_field |= LOCKED;
1989 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
1990 ctor.flags_field &= ~LOCKED;
1991 }
1992 ctor.flags_field |= ACYCLIC;
1993 }
1994 }
1996 /* *************************************************************************
1997 * Miscellaneous
1998 **************************************************************************/
2000 /**
2001 * Return the opcode of the operator but emit an error if it is an
2002 * error.
2003 * @param pos position for error reporting.
2004 * @param operator an operator
2005 * @param tag a tree tag
2006 * @param left type of left hand side
2007 * @param right type of right hand side
2008 */
2009 int checkOperator(DiagnosticPosition pos,
2010 OperatorSymbol operator,
2011 int tag,
2012 Type left,
2013 Type right) {
2014 if (operator.opcode == ByteCodes.error) {
2015 log.error(pos,
2016 "operator.cant.be.applied",
2017 treeinfo.operatorName(tag),
2018 left + "," + right);
2019 }
2020 return operator.opcode;
2021 }
2024 /**
2025 * Check for division by integer constant zero
2026 * @param pos Position for error reporting.
2027 * @param operator The operator for the expression
2028 * @param operand The right hand operand for the expression
2029 */
2030 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2031 if (operand.constValue() != null
2032 && lint.isEnabled(Lint.LintCategory.DIVZERO)
2033 && operand.tag <= LONG
2034 && ((Number) (operand.constValue())).longValue() == 0) {
2035 int opc = ((OperatorSymbol)operator).opcode;
2036 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2037 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2038 log.warning(pos, "div.zero");
2039 }
2040 }
2041 }
2043 /**
2044 * Check for empty statements after if
2045 */
2046 void checkEmptyIf(JCIf tree) {
2047 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
2048 log.warning(tree.thenpart.pos(), "empty.if");
2049 }
2051 /** Check that symbol is unique in given scope.
2052 * @param pos Position for error reporting.
2053 * @param sym The symbol.
2054 * @param s The scope.
2055 */
2056 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2057 if (sym.type.isErroneous())
2058 return true;
2059 if (sym.owner.name == names.any) return false;
2060 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2061 if (sym != e.sym &&
2062 sym.kind == e.sym.kind &&
2063 sym.name != names.error &&
2064 (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
2065 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
2066 varargsDuplicateError(pos, sym, e.sym);
2067 else
2068 duplicateError(pos, e.sym);
2069 return false;
2070 }
2071 }
2072 return true;
2073 }
2075 /** Check that single-type import is not already imported or top-level defined,
2076 * but make an exception for two single-type imports which denote the same type.
2077 * @param pos Position for error reporting.
2078 * @param sym The symbol.
2079 * @param s The scope
2080 */
2081 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2082 return checkUniqueImport(pos, sym, s, false);
2083 }
2085 /** Check that static single-type import is not already imported or top-level defined,
2086 * but make an exception for two single-type imports which denote the same type.
2087 * @param pos Position for error reporting.
2088 * @param sym The symbol.
2089 * @param s The scope
2090 * @param staticImport Whether or not this was a static import
2091 */
2092 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2093 return checkUniqueImport(pos, sym, s, true);
2094 }
2096 /** Check that single-type import is not already imported or top-level defined,
2097 * but make an exception for two single-type imports which denote the same type.
2098 * @param pos Position for error reporting.
2099 * @param sym The symbol.
2100 * @param s The scope.
2101 * @param staticImport Whether or not this was a static import
2102 */
2103 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2104 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2105 // is encountered class entered via a class declaration?
2106 boolean isClassDecl = e.scope == s;
2107 if ((isClassDecl || sym != e.sym) &&
2108 sym.kind == e.sym.kind &&
2109 sym.name != names.error) {
2110 if (!e.sym.type.isErroneous()) {
2111 String what = e.sym.toString();
2112 if (!isClassDecl) {
2113 if (staticImport)
2114 log.error(pos, "already.defined.static.single.import", what);
2115 else
2116 log.error(pos, "already.defined.single.import", what);
2117 }
2118 else if (sym != e.sym)
2119 log.error(pos, "already.defined.this.unit", what);
2120 }
2121 return false;
2122 }
2123 }
2124 return true;
2125 }
2127 /** Check that a qualified name is in canonical form (for import decls).
2128 */
2129 public void checkCanonical(JCTree tree) {
2130 if (!isCanonical(tree))
2131 log.error(tree.pos(), "import.requires.canonical",
2132 TreeInfo.symbol(tree));
2133 }
2134 // where
2135 private boolean isCanonical(JCTree tree) {
2136 while (tree.getTag() == JCTree.SELECT) {
2137 JCFieldAccess s = (JCFieldAccess) tree;
2138 if (s.sym.owner != TreeInfo.symbol(s.selected))
2139 return false;
2140 tree = s.selected;
2141 }
2142 return true;
2143 }
2145 private class ConversionWarner extends Warner {
2146 final String key;
2147 final Type found;
2148 final Type expected;
2149 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
2150 super(pos);
2151 this.key = key;
2152 this.found = found;
2153 this.expected = expected;
2154 }
2156 public void warnUnchecked() {
2157 boolean warned = this.warned;
2158 super.warnUnchecked();
2159 if (warned) return; // suppress redundant diagnostics
2160 Object problem = JCDiagnostic.fragment(key);
2161 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
2162 }
2163 }
2165 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2166 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2167 }
2169 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2170 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2171 }
2172 }