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