Fri, 26 Jun 2009 18:51:39 -0700
6843077: JSR 308: Annotations on types
Reviewed-by: jjg, mcimadamore, darcy
Contributed-by: mernst@cs.washington.edu, mali@csail.mit.edu, mpapi@csail.mit.edu
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 public void visitAnnotatedType(JCAnnotatedType tree) {
920 tree.underlyingType.accept(this);
921 }
923 /** Default visitor method: do nothing.
924 */
925 public void visitTree(JCTree tree) {
926 }
928 Env<AttrContext> env;
929 }
931 /* *************************************************************************
932 * Exception checking
933 **************************************************************************/
935 /* The following methods treat classes as sets that contain
936 * the class itself and all their subclasses
937 */
939 /** Is given type a subtype of some of the types in given list?
940 */
941 boolean subset(Type t, List<Type> ts) {
942 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
943 if (types.isSubtype(t, l.head)) return true;
944 return false;
945 }
947 /** Is given type a subtype or supertype of
948 * some of the types in given list?
949 */
950 boolean intersects(Type t, List<Type> ts) {
951 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
952 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
953 return false;
954 }
956 /** Add type set to given type list, unless it is a subclass of some class
957 * in the list.
958 */
959 List<Type> incl(Type t, List<Type> ts) {
960 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
961 }
963 /** Remove type set from type set list.
964 */
965 List<Type> excl(Type t, List<Type> ts) {
966 if (ts.isEmpty()) {
967 return ts;
968 } else {
969 List<Type> ts1 = excl(t, ts.tail);
970 if (types.isSubtype(ts.head, t)) return ts1;
971 else if (ts1 == ts.tail) return ts;
972 else return ts1.prepend(ts.head);
973 }
974 }
976 /** Form the union of two type set lists.
977 */
978 List<Type> union(List<Type> ts1, List<Type> ts2) {
979 List<Type> ts = ts1;
980 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
981 ts = incl(l.head, ts);
982 return ts;
983 }
985 /** Form the difference of two type lists.
986 */
987 List<Type> diff(List<Type> ts1, List<Type> ts2) {
988 List<Type> ts = ts1;
989 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
990 ts = excl(l.head, ts);
991 return ts;
992 }
994 /** Form the intersection of two type lists.
995 */
996 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
997 List<Type> ts = List.nil();
998 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
999 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1000 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1001 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1002 return ts;
1003 }
1005 /** Is exc an exception symbol that need not be declared?
1006 */
1007 boolean isUnchecked(ClassSymbol exc) {
1008 return
1009 exc.kind == ERR ||
1010 exc.isSubClass(syms.errorType.tsym, types) ||
1011 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1012 }
1014 /** Is exc an exception type that need not be declared?
1015 */
1016 boolean isUnchecked(Type exc) {
1017 return
1018 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1019 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1020 exc.tag == BOT;
1021 }
1023 /** Same, but handling completion failures.
1024 */
1025 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1026 try {
1027 return isUnchecked(exc);
1028 } catch (CompletionFailure ex) {
1029 completionError(pos, ex);
1030 return true;
1031 }
1032 }
1034 /** Is exc handled by given exception list?
1035 */
1036 boolean isHandled(Type exc, List<Type> handled) {
1037 return isUnchecked(exc) || subset(exc, handled);
1038 }
1040 /** Return all exceptions in thrown list that are not in handled list.
1041 * @param thrown The list of thrown exceptions.
1042 * @param handled The list of handled exceptions.
1043 */
1044 List<Type> unHandled(List<Type> thrown, List<Type> handled) {
1045 List<Type> unhandled = List.nil();
1046 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1047 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1048 return unhandled;
1049 }
1051 /* *************************************************************************
1052 * Overriding/Implementation checking
1053 **************************************************************************/
1055 /** The level of access protection given by a flag set,
1056 * where PRIVATE is highest and PUBLIC is lowest.
1057 */
1058 static int protection(long flags) {
1059 switch ((short)(flags & AccessFlags)) {
1060 case PRIVATE: return 3;
1061 case PROTECTED: return 1;
1062 default:
1063 case PUBLIC: return 0;
1064 case 0: return 2;
1065 }
1066 }
1068 /** A customized "cannot override" error message.
1069 * @param m The overriding method.
1070 * @param other The overridden method.
1071 * @return An internationalized string.
1072 */
1073 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1074 String key;
1075 if ((other.owner.flags() & INTERFACE) == 0)
1076 key = "cant.override";
1077 else if ((m.owner.flags() & INTERFACE) == 0)
1078 key = "cant.implement";
1079 else
1080 key = "clashes.with";
1081 return diags.fragment(key, m, m.location(), other, other.location());
1082 }
1084 /** A customized "override" warning message.
1085 * @param m The overriding method.
1086 * @param other The overridden method.
1087 * @return An internationalized string.
1088 */
1089 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1090 String key;
1091 if ((other.owner.flags() & INTERFACE) == 0)
1092 key = "unchecked.override";
1093 else if ((m.owner.flags() & INTERFACE) == 0)
1094 key = "unchecked.implement";
1095 else
1096 key = "unchecked.clash.with";
1097 return diags.fragment(key, m, m.location(), other, other.location());
1098 }
1100 /** A customized "override" warning message.
1101 * @param m The overriding method.
1102 * @param other The overridden method.
1103 * @return An internationalized string.
1104 */
1105 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1106 String key;
1107 if ((other.owner.flags() & INTERFACE) == 0)
1108 key = "varargs.override";
1109 else if ((m.owner.flags() & INTERFACE) == 0)
1110 key = "varargs.implement";
1111 else
1112 key = "varargs.clash.with";
1113 return diags.fragment(key, m, m.location(), other, other.location());
1114 }
1116 /** Check that this method conforms with overridden method 'other'.
1117 * where `origin' is the class where checking started.
1118 * Complications:
1119 * (1) Do not check overriding of synthetic methods
1120 * (reason: they might be final).
1121 * todo: check whether this is still necessary.
1122 * (2) Admit the case where an interface proxy throws fewer exceptions
1123 * than the method it implements. Augment the proxy methods with the
1124 * undeclared exceptions in this case.
1125 * (3) When generics are enabled, admit the case where an interface proxy
1126 * has a result type
1127 * extended by the result type of the method it implements.
1128 * Change the proxies result type to the smaller type in this case.
1129 *
1130 * @param tree The tree from which positions
1131 * are extracted for errors.
1132 * @param m The overriding method.
1133 * @param other The overridden method.
1134 * @param origin The class of which the overriding method
1135 * is a member.
1136 */
1137 void checkOverride(JCTree tree,
1138 MethodSymbol m,
1139 MethodSymbol other,
1140 ClassSymbol origin) {
1141 // Don't check overriding of synthetic methods or by bridge methods.
1142 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1143 return;
1144 }
1146 // Error if static method overrides instance method (JLS 8.4.6.2).
1147 if ((m.flags() & STATIC) != 0 &&
1148 (other.flags() & STATIC) == 0) {
1149 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1150 cannotOverride(m, other));
1151 return;
1152 }
1154 // Error if instance method overrides static or final
1155 // method (JLS 8.4.6.1).
1156 if ((other.flags() & FINAL) != 0 ||
1157 (m.flags() & STATIC) == 0 &&
1158 (other.flags() & STATIC) != 0) {
1159 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1160 cannotOverride(m, other),
1161 asFlagSet(other.flags() & (FINAL | STATIC)));
1162 return;
1163 }
1165 if ((m.owner.flags() & ANNOTATION) != 0) {
1166 // handled in validateAnnotationMethod
1167 return;
1168 }
1170 // Error if overriding method has weaker access (JLS 8.4.6.3).
1171 if ((origin.flags() & INTERFACE) == 0 &&
1172 protection(m.flags()) > protection(other.flags())) {
1173 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1174 cannotOverride(m, other),
1175 other.flags() == 0 ?
1176 Flag.PACKAGE :
1177 asFlagSet(other.flags() & AccessFlags));
1178 return;
1179 }
1181 Type mt = types.memberType(origin.type, m);
1182 Type ot = types.memberType(origin.type, other);
1183 // Error if overriding result type is different
1184 // (or, in the case of generics mode, not a subtype) of
1185 // overridden result type. We have to rename any type parameters
1186 // before comparing types.
1187 List<Type> mtvars = mt.getTypeArguments();
1188 List<Type> otvars = ot.getTypeArguments();
1189 Type mtres = mt.getReturnType();
1190 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1192 overrideWarner.warned = false;
1193 boolean resultTypesOK =
1194 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1195 if (!resultTypesOK) {
1196 if (!source.allowCovariantReturns() &&
1197 m.owner != origin &&
1198 m.owner.isSubClass(other.owner, types)) {
1199 // allow limited interoperability with covariant returns
1200 } else {
1201 typeError(TreeInfo.diagnosticPositionFor(m, tree),
1202 diags.fragment("override.incompatible.ret",
1203 cannotOverride(m, other)),
1204 mtres, otres);
1205 return;
1206 }
1207 } else if (overrideWarner.warned) {
1208 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1209 "prob.found.req",
1210 diags.fragment("override.unchecked.ret",
1211 uncheckedOverrides(m, other)),
1212 mtres, otres);
1213 }
1215 // Error if overriding method throws an exception not reported
1216 // by overridden method.
1217 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1218 List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
1219 if (unhandled.nonEmpty()) {
1220 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1221 "override.meth.doesnt.throw",
1222 cannotOverride(m, other),
1223 unhandled.head);
1224 return;
1225 }
1227 // Optional warning if varargs don't agree
1228 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1229 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
1230 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1231 ((m.flags() & Flags.VARARGS) != 0)
1232 ? "override.varargs.missing"
1233 : "override.varargs.extra",
1234 varargsOverrides(m, other));
1235 }
1237 // Warn if instance method overrides bridge method (compiler spec ??)
1238 if ((other.flags() & BRIDGE) != 0) {
1239 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1240 uncheckedOverrides(m, other));
1241 }
1243 // Warn if a deprecated method overridden by a non-deprecated one.
1244 if ((other.flags() & DEPRECATED) != 0
1245 && (m.flags() & DEPRECATED) == 0
1246 && m.outermostClass() != other.outermostClass()
1247 && !isDeprecatedOverrideIgnorable(other, origin)) {
1248 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1249 }
1250 }
1251 // where
1252 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1253 // If the method, m, is defined in an interface, then ignore the issue if the method
1254 // is only inherited via a supertype and also implemented in the supertype,
1255 // because in that case, we will rediscover the issue when examining the method
1256 // in the supertype.
1257 // If the method, m, is not defined in an interface, then the only time we need to
1258 // address the issue is when the method is the supertype implemementation: any other
1259 // case, we will have dealt with when examining the supertype classes
1260 ClassSymbol mc = m.enclClass();
1261 Type st = types.supertype(origin.type);
1262 if (st.tag != CLASS)
1263 return true;
1264 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1266 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1267 List<Type> intfs = types.interfaces(origin.type);
1268 return (intfs.contains(mc.type) ? false : (stimpl != null));
1269 }
1270 else
1271 return (stimpl != m);
1272 }
1275 // used to check if there were any unchecked conversions
1276 Warner overrideWarner = new Warner();
1278 /** Check that a class does not inherit two concrete methods
1279 * with the same signature.
1280 * @param pos Position to be used for error reporting.
1281 * @param site The class type to be checked.
1282 */
1283 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1284 Type sup = types.supertype(site);
1285 if (sup.tag != CLASS) return;
1287 for (Type t1 = sup;
1288 t1.tsym.type.isParameterized();
1289 t1 = types.supertype(t1)) {
1290 for (Scope.Entry e1 = t1.tsym.members().elems;
1291 e1 != null;
1292 e1 = e1.sibling) {
1293 Symbol s1 = e1.sym;
1294 if (s1.kind != MTH ||
1295 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1296 !s1.isInheritedIn(site.tsym, types) ||
1297 ((MethodSymbol)s1).implementation(site.tsym,
1298 types,
1299 true) != s1)
1300 continue;
1301 Type st1 = types.memberType(t1, s1);
1302 int s1ArgsLength = st1.getParameterTypes().length();
1303 if (st1 == s1.type) continue;
1305 for (Type t2 = sup;
1306 t2.tag == CLASS;
1307 t2 = types.supertype(t2)) {
1308 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1309 e2.scope != null;
1310 e2 = e2.next()) {
1311 Symbol s2 = e2.sym;
1312 if (s2 == s1 ||
1313 s2.kind != MTH ||
1314 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1315 s2.type.getParameterTypes().length() != s1ArgsLength ||
1316 !s2.isInheritedIn(site.tsym, types) ||
1317 ((MethodSymbol)s2).implementation(site.tsym,
1318 types,
1319 true) != s2)
1320 continue;
1321 Type st2 = types.memberType(t2, s2);
1322 if (types.overrideEquivalent(st1, st2))
1323 log.error(pos, "concrete.inheritance.conflict",
1324 s1, t1, s2, t2, sup);
1325 }
1326 }
1327 }
1328 }
1329 }
1331 /** Check that classes (or interfaces) do not each define an abstract
1332 * method with same name and arguments but incompatible return types.
1333 * @param pos Position to be used for error reporting.
1334 * @param t1 The first argument type.
1335 * @param t2 The second argument type.
1336 */
1337 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1338 Type t1,
1339 Type t2) {
1340 return checkCompatibleAbstracts(pos, t1, t2,
1341 types.makeCompoundType(t1, t2));
1342 }
1344 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1345 Type t1,
1346 Type t2,
1347 Type site) {
1348 Symbol sym = firstIncompatibility(t1, t2, site);
1349 if (sym != null) {
1350 log.error(pos, "types.incompatible.diff.ret",
1351 t1, t2, sym.name +
1352 "(" + types.memberType(t2, sym).getParameterTypes() + ")");
1353 return false;
1354 }
1355 return true;
1356 }
1358 /** Return the first method which is defined with same args
1359 * but different return types in two given interfaces, or null if none
1360 * exists.
1361 * @param t1 The first type.
1362 * @param t2 The second type.
1363 * @param site The most derived type.
1364 * @returns symbol from t2 that conflicts with one in t1.
1365 */
1366 private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
1367 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1368 closure(t1, interfaces1);
1369 Map<TypeSymbol,Type> interfaces2;
1370 if (t1 == t2)
1371 interfaces2 = interfaces1;
1372 else
1373 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1375 for (Type t3 : interfaces1.values()) {
1376 for (Type t4 : interfaces2.values()) {
1377 Symbol s = firstDirectIncompatibility(t3, t4, site);
1378 if (s != null) return s;
1379 }
1380 }
1381 return null;
1382 }
1384 /** Compute all the supertypes of t, indexed by type symbol. */
1385 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1386 if (t.tag != CLASS) return;
1387 if (typeMap.put(t.tsym, t) == null) {
1388 closure(types.supertype(t), typeMap);
1389 for (Type i : types.interfaces(t))
1390 closure(i, typeMap);
1391 }
1392 }
1394 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1395 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1396 if (t.tag != CLASS) return;
1397 if (typesSkip.get(t.tsym) != null) return;
1398 if (typeMap.put(t.tsym, t) == null) {
1399 closure(types.supertype(t), typesSkip, typeMap);
1400 for (Type i : types.interfaces(t))
1401 closure(i, typesSkip, typeMap);
1402 }
1403 }
1405 /** Return the first method in t2 that conflicts with a method from t1. */
1406 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
1407 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1408 Symbol s1 = e1.sym;
1409 Type st1 = null;
1410 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1411 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1412 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1413 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1414 Symbol s2 = e2.sym;
1415 if (s1 == s2) continue;
1416 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1417 if (st1 == null) st1 = types.memberType(t1, s1);
1418 Type st2 = types.memberType(t2, s2);
1419 if (types.overrideEquivalent(st1, st2)) {
1420 List<Type> tvars1 = st1.getTypeArguments();
1421 List<Type> tvars2 = st2.getTypeArguments();
1422 Type rt1 = st1.getReturnType();
1423 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1424 boolean compat =
1425 types.isSameType(rt1, rt2) ||
1426 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1427 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1428 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1429 checkCommonOverriderIn(s1,s2,site);
1430 if (!compat) return s2;
1431 }
1432 }
1433 }
1434 return null;
1435 }
1436 //WHERE
1437 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1438 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1439 Type st1 = types.memberType(site, s1);
1440 Type st2 = types.memberType(site, s2);
1441 closure(site, supertypes);
1442 for (Type t : supertypes.values()) {
1443 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1444 Symbol s3 = e.sym;
1445 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1446 Type st3 = types.memberType(site,s3);
1447 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1448 if (s3.owner == site.tsym) {
1449 return true;
1450 }
1451 List<Type> tvars1 = st1.getTypeArguments();
1452 List<Type> tvars2 = st2.getTypeArguments();
1453 List<Type> tvars3 = st3.getTypeArguments();
1454 Type rt1 = st1.getReturnType();
1455 Type rt2 = st2.getReturnType();
1456 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1457 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1458 boolean compat =
1459 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1460 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1461 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1462 if (compat)
1463 return true;
1464 }
1465 }
1466 }
1467 return false;
1468 }
1470 /** Check that a given method conforms with any method it overrides.
1471 * @param tree The tree from which positions are extracted
1472 * for errors.
1473 * @param m The overriding method.
1474 */
1475 void checkOverride(JCTree tree, MethodSymbol m) {
1476 ClassSymbol origin = (ClassSymbol)m.owner;
1477 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1478 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1479 log.error(tree.pos(), "enum.no.finalize");
1480 return;
1481 }
1482 for (Type t = types.supertype(origin.type); t.tag == CLASS;
1483 t = types.supertype(t)) {
1484 TypeSymbol c = t.tsym;
1485 Scope.Entry e = c.members().lookup(m.name);
1486 while (e.scope != null) {
1487 if (m.overrides(e.sym, origin, types, false))
1488 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1489 else if (e.sym.kind == MTH &&
1490 e.sym.isInheritedIn(origin, types) &&
1491 (e.sym.flags() & SYNTHETIC) == 0 &&
1492 !m.isConstructor()) {
1493 Type er1 = m.erasure(types);
1494 Type er2 = e.sym.erasure(types);
1495 if (types.isSameTypes(er1.getParameterTypes(),
1496 er2.getParameterTypes())) {
1497 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1498 "name.clash.same.erasure.no.override",
1499 m, m.location(),
1500 e.sym, e.sym.location());
1501 }
1502 }
1503 e = e.next();
1504 }
1505 }
1506 }
1508 /** Check that all abstract members of given class have definitions.
1509 * @param pos Position to be used for error reporting.
1510 * @param c The class.
1511 */
1512 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1513 try {
1514 MethodSymbol undef = firstUndef(c, c);
1515 if (undef != null) {
1516 if ((c.flags() & ENUM) != 0 &&
1517 types.supertype(c.type).tsym == syms.enumSym &&
1518 (c.flags() & FINAL) == 0) {
1519 // add the ABSTRACT flag to an enum
1520 c.flags_field |= ABSTRACT;
1521 } else {
1522 MethodSymbol undef1 =
1523 new MethodSymbol(undef.flags(), undef.name,
1524 types.memberType(c.type, undef), undef.owner);
1525 log.error(pos, "does.not.override.abstract",
1526 c, undef1, undef1.location());
1527 }
1528 }
1529 } catch (CompletionFailure ex) {
1530 completionError(pos, ex);
1531 }
1532 }
1533 //where
1534 /** Return first abstract member of class `c' that is not defined
1535 * in `impl', null if there is none.
1536 */
1537 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1538 MethodSymbol undef = null;
1539 // Do not bother to search in classes that are not abstract,
1540 // since they cannot have abstract members.
1541 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1542 Scope s = c.members();
1543 for (Scope.Entry e = s.elems;
1544 undef == null && e != null;
1545 e = e.sibling) {
1546 if (e.sym.kind == MTH &&
1547 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1548 MethodSymbol absmeth = (MethodSymbol)e.sym;
1549 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1550 if (implmeth == null || implmeth == absmeth)
1551 undef = absmeth;
1552 }
1553 }
1554 if (undef == null) {
1555 Type st = types.supertype(c.type);
1556 if (st.tag == CLASS)
1557 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1558 }
1559 for (List<Type> l = types.interfaces(c.type);
1560 undef == null && l.nonEmpty();
1561 l = l.tail) {
1562 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1563 }
1564 }
1565 return undef;
1566 }
1568 /** Check for cyclic references. Issue an error if the
1569 * symbol of the type referred to has a LOCKED flag set.
1570 *
1571 * @param pos Position to be used for error reporting.
1572 * @param t The type referred to.
1573 */
1574 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1575 checkNonCyclicInternal(pos, t);
1576 }
1579 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1580 checkNonCyclic1(pos, t, List.<TypeVar>nil());
1581 }
1583 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
1584 final TypeVar tv;
1585 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1586 return;
1587 if (seen.contains(t)) {
1588 tv = (TypeVar)t;
1589 tv.bound = types.createErrorType(t);
1590 log.error(pos, "cyclic.inheritance", t);
1591 } else if (t.tag == TYPEVAR) {
1592 tv = (TypeVar)t;
1593 seen = seen.prepend(tv);
1594 for (Type b : types.getBounds(tv))
1595 checkNonCyclic1(pos, b, seen);
1596 }
1597 }
1599 /** Check for cyclic references. Issue an error if the
1600 * symbol of the type referred to has a LOCKED flag set.
1601 *
1602 * @param pos Position to be used for error reporting.
1603 * @param t The type referred to.
1604 * @returns True if the check completed on all attributed classes
1605 */
1606 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1607 boolean complete = true; // was the check complete?
1608 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1609 Symbol c = t.tsym;
1610 if ((c.flags_field & ACYCLIC) != 0) return true;
1612 if ((c.flags_field & LOCKED) != 0) {
1613 noteCyclic(pos, (ClassSymbol)c);
1614 } else if (!c.type.isErroneous()) {
1615 try {
1616 c.flags_field |= LOCKED;
1617 if (c.type.tag == CLASS) {
1618 ClassType clazz = (ClassType)c.type;
1619 if (clazz.interfaces_field != null)
1620 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1621 complete &= checkNonCyclicInternal(pos, l.head);
1622 if (clazz.supertype_field != null) {
1623 Type st = clazz.supertype_field;
1624 if (st != null && st.tag == CLASS)
1625 complete &= checkNonCyclicInternal(pos, st);
1626 }
1627 if (c.owner.kind == TYP)
1628 complete &= checkNonCyclicInternal(pos, c.owner.type);
1629 }
1630 } finally {
1631 c.flags_field &= ~LOCKED;
1632 }
1633 }
1634 if (complete)
1635 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1636 if (complete) c.flags_field |= ACYCLIC;
1637 return complete;
1638 }
1640 /** Note that we found an inheritance cycle. */
1641 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1642 log.error(pos, "cyclic.inheritance", c);
1643 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1644 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
1645 Type st = types.supertype(c.type);
1646 if (st.tag == CLASS)
1647 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
1648 c.type = types.createErrorType(c, c.type);
1649 c.flags_field |= ACYCLIC;
1650 }
1652 /** Check that all methods which implement some
1653 * method conform to the method they implement.
1654 * @param tree The class definition whose members are checked.
1655 */
1656 void checkImplementations(JCClassDecl tree) {
1657 checkImplementations(tree, tree.sym);
1658 }
1659 //where
1660 /** Check that all methods which implement some
1661 * method in `ic' conform to the method they implement.
1662 */
1663 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
1664 ClassSymbol origin = tree.sym;
1665 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
1666 ClassSymbol lc = (ClassSymbol)l.head.tsym;
1667 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
1668 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
1669 if (e.sym.kind == MTH &&
1670 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
1671 MethodSymbol absmeth = (MethodSymbol)e.sym;
1672 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
1673 if (implmeth != null && implmeth != absmeth &&
1674 (implmeth.owner.flags() & INTERFACE) ==
1675 (origin.flags() & INTERFACE)) {
1676 // don't check if implmeth is in a class, yet
1677 // origin is an interface. This case arises only
1678 // if implmeth is declared in Object. The reason is
1679 // that interfaces really don't inherit from
1680 // Object it's just that the compiler represents
1681 // things that way.
1682 checkOverride(tree, implmeth, absmeth, origin);
1683 }
1684 }
1685 }
1686 }
1687 }
1688 }
1690 /** Check that all abstract methods implemented by a class are
1691 * mutually compatible.
1692 * @param pos Position to be used for error reporting.
1693 * @param c The class whose interfaces are checked.
1694 */
1695 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
1696 List<Type> supertypes = types.interfaces(c);
1697 Type supertype = types.supertype(c);
1698 if (supertype.tag == CLASS &&
1699 (supertype.tsym.flags() & ABSTRACT) != 0)
1700 supertypes = supertypes.prepend(supertype);
1701 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
1702 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
1703 !checkCompatibleAbstracts(pos, l.head, l.head, c))
1704 return;
1705 for (List<Type> m = supertypes; m != l; m = m.tail)
1706 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
1707 return;
1708 }
1709 checkCompatibleConcretes(pos, c);
1710 }
1712 /** Check that class c does not implement directly or indirectly
1713 * the same parameterized interface with two different argument lists.
1714 * @param pos Position to be used for error reporting.
1715 * @param type The type whose interfaces are checked.
1716 */
1717 void checkClassBounds(DiagnosticPosition pos, Type type) {
1718 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
1719 }
1720 //where
1721 /** Enter all interfaces of type `type' into the hash table `seensofar'
1722 * with their class symbol as key and their type as value. Make
1723 * sure no class is entered with two different types.
1724 */
1725 void checkClassBounds(DiagnosticPosition pos,
1726 Map<TypeSymbol,Type> seensofar,
1727 Type type) {
1728 if (type.isErroneous()) return;
1729 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
1730 Type it = l.head;
1731 Type oldit = seensofar.put(it.tsym, it);
1732 if (oldit != null) {
1733 List<Type> oldparams = oldit.allparams();
1734 List<Type> newparams = it.allparams();
1735 if (!types.containsTypeEquivalent(oldparams, newparams))
1736 log.error(pos, "cant.inherit.diff.arg",
1737 it.tsym, Type.toString(oldparams),
1738 Type.toString(newparams));
1739 }
1740 checkClassBounds(pos, seensofar, it);
1741 }
1742 Type st = types.supertype(type);
1743 if (st != null) checkClassBounds(pos, seensofar, st);
1744 }
1746 /** Enter interface into into set.
1747 * If it existed already, issue a "repeated interface" error.
1748 */
1749 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
1750 if (its.contains(it))
1751 log.error(pos, "repeated.interface");
1752 else {
1753 its.add(it);
1754 }
1755 }
1757 /* *************************************************************************
1758 * Check annotations
1759 **************************************************************************/
1761 /** Annotation types are restricted to primitives, String, an
1762 * enum, an annotation, Class, Class<?>, Class<? extends
1763 * Anything>, arrays of the preceding.
1764 */
1765 void validateAnnotationType(JCTree restype) {
1766 // restype may be null if an error occurred, so don't bother validating it
1767 if (restype != null) {
1768 validateAnnotationType(restype.pos(), restype.type);
1769 }
1770 }
1772 void validateAnnotationType(DiagnosticPosition pos, Type type) {
1773 if (type.isPrimitive()) return;
1774 if (types.isSameType(type, syms.stringType)) return;
1775 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
1776 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
1777 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
1778 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
1779 validateAnnotationType(pos, types.elemtype(type));
1780 return;
1781 }
1782 log.error(pos, "invalid.annotation.member.type");
1783 }
1785 /**
1786 * "It is also a compile-time error if any method declared in an
1787 * annotation type has a signature that is override-equivalent to
1788 * that of any public or protected method declared in class Object
1789 * or in the interface annotation.Annotation."
1790 *
1791 * @jls3 9.6 Annotation Types
1792 */
1793 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
1794 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
1795 Scope s = sup.tsym.members();
1796 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
1797 if (e.sym.kind == MTH &&
1798 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
1799 types.overrideEquivalent(m.type, e.sym.type))
1800 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
1801 }
1802 }
1803 }
1805 /** Check the annotations of a symbol.
1806 */
1807 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
1808 if (skipAnnotations) return;
1809 for (JCAnnotation a : annotations)
1810 validateAnnotation(a, s);
1811 }
1813 /** Check the type annotations
1814 */
1815 public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
1816 if (skipAnnotations) return;
1817 for (JCTypeAnnotation a : annotations)
1818 validateTypeAnnotation(a, isTypeParameter);
1819 }
1821 /** Check an annotation of a symbol.
1822 */
1823 public void validateAnnotation(JCAnnotation a, Symbol s) {
1824 validateAnnotation(a);
1826 if (!annotationApplicable(a, s))
1827 log.error(a.pos(), "annotation.type.not.applicable");
1829 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
1830 if (!isOverrider(s))
1831 log.error(a.pos(), "method.does.not.override.superclass");
1832 }
1833 }
1835 public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
1836 if (a.type == null)
1837 throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
1838 validateAnnotation(a);
1840 if (!isTypeAnnotation(a, isTypeParameter))
1841 log.error(a.pos(), "annotation.type.not.applicable");
1842 }
1844 /** Is s a method symbol that overrides a method in a superclass? */
1845 boolean isOverrider(Symbol s) {
1846 if (s.kind != MTH || s.isStatic())
1847 return false;
1848 MethodSymbol m = (MethodSymbol)s;
1849 TypeSymbol owner = (TypeSymbol)m.owner;
1850 for (Type sup : types.closure(owner.type)) {
1851 if (sup == owner.type)
1852 continue; // skip "this"
1853 Scope scope = sup.tsym.members();
1854 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
1855 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
1856 return true;
1857 }
1858 }
1859 return false;
1860 }
1862 /** Is the annotation applicable to type annotations */
1863 boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
1864 Attribute.Compound atTarget =
1865 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
1866 if (atTarget == null) return true;
1867 Attribute atValue = atTarget.member(names.value);
1868 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
1869 Attribute.Array arr = (Attribute.Array) atValue;
1870 for (Attribute app : arr.values) {
1871 if (!(app instanceof Attribute.Enum)) return true; // recovery
1872 Attribute.Enum e = (Attribute.Enum) app;
1873 if (!isTypeParameter && e.value.name == names.TYPE_USE)
1874 return true;
1875 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
1876 return true;
1877 }
1878 return false;
1879 }
1881 /** Is the annotation applicable to the symbol? */
1882 boolean annotationApplicable(JCAnnotation a, Symbol s) {
1883 Attribute.Compound atTarget =
1884 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
1885 if (atTarget == null) return true;
1886 Attribute atValue = atTarget.member(names.value);
1887 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
1888 Attribute.Array arr = (Attribute.Array) atValue;
1889 for (Attribute app : arr.values) {
1890 if (!(app instanceof Attribute.Enum)) return true; // recovery
1891 Attribute.Enum e = (Attribute.Enum) app;
1892 if (e.value.name == names.TYPE)
1893 { if (s.kind == TYP) return true; }
1894 else if (e.value.name == names.FIELD)
1895 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
1896 else if (e.value.name == names.METHOD)
1897 { if (s.kind == MTH && !s.isConstructor()) return true; }
1898 else if (e.value.name == names.PARAMETER)
1899 { if (s.kind == VAR &&
1900 s.owner.kind == MTH &&
1901 (s.flags() & PARAMETER) != 0)
1902 return true;
1903 }
1904 else if (e.value.name == names.CONSTRUCTOR)
1905 { if (s.kind == MTH && s.isConstructor()) return true; }
1906 else if (e.value.name == names.LOCAL_VARIABLE)
1907 { if (s.kind == VAR && s.owner.kind == MTH &&
1908 (s.flags() & PARAMETER) == 0)
1909 return true;
1910 }
1911 else if (e.value.name == names.ANNOTATION_TYPE)
1912 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
1913 return true;
1914 }
1915 else if (e.value.name == names.PACKAGE)
1916 { if (s.kind == PCK) return true; }
1917 else if (e.value.name == names.TYPE_USE)
1918 { if (s.kind == TYP ||
1919 s.kind == VAR ||
1920 (s.kind == MTH && !s.isConstructor() &&
1921 s.type.getReturnType().tag != VOID))
1922 return true;
1923 }
1924 else
1925 return true; // recovery
1926 }
1927 return false;
1928 }
1930 /** Check an annotation value.
1931 */
1932 public void validateAnnotation(JCAnnotation a) {
1933 if (a.type.isErroneous()) return;
1935 // collect an inventory of the members
1936 Set<MethodSymbol> members = new HashSet<MethodSymbol>();
1937 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
1938 e != null;
1939 e = e.sibling)
1940 if (e.sym.kind == MTH)
1941 members.add((MethodSymbol) e.sym);
1943 // count them off as they're annotated
1944 for (JCTree arg : a.args) {
1945 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
1946 JCAssign assign = (JCAssign) arg;
1947 Symbol m = TreeInfo.symbol(assign.lhs);
1948 if (m == null || m.type.isErroneous()) continue;
1949 if (!members.remove(m))
1950 log.error(arg.pos(), "duplicate.annotation.member.value",
1951 m.name, a.type);
1952 if (assign.rhs.getTag() == ANNOTATION)
1953 validateAnnotation((JCAnnotation)assign.rhs);
1954 }
1956 // all the remaining ones better have default values
1957 for (MethodSymbol m : members)
1958 if (m.defaultValue == null && !m.type.isErroneous())
1959 log.error(a.pos(), "annotation.missing.default.value",
1960 a.type, m.name);
1962 // special case: java.lang.annotation.Target must not have
1963 // repeated values in its value member
1964 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
1965 a.args.tail == null)
1966 return;
1968 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
1969 JCAssign assign = (JCAssign) a.args.head;
1970 Symbol m = TreeInfo.symbol(assign.lhs);
1971 if (m.name != names.value) return;
1972 JCTree rhs = assign.rhs;
1973 if (rhs.getTag() != JCTree.NEWARRAY) return;
1974 JCNewArray na = (JCNewArray) rhs;
1975 Set<Symbol> targets = new HashSet<Symbol>();
1976 for (JCTree elem : na.elems) {
1977 if (!targets.add(TreeInfo.symbol(elem))) {
1978 log.error(elem.pos(), "repeated.annotation.target");
1979 }
1980 }
1981 }
1983 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
1984 if (allowAnnotations &&
1985 lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
1986 (s.flags() & DEPRECATED) != 0 &&
1987 !syms.deprecatedType.isErroneous() &&
1988 s.attribute(syms.deprecatedType.tsym) == null) {
1989 log.warning(pos, "missing.deprecated.annotation");
1990 }
1991 }
1993 /* *************************************************************************
1994 * Check for recursive annotation elements.
1995 **************************************************************************/
1997 /** Check for cycles in the graph of annotation elements.
1998 */
1999 void checkNonCyclicElements(JCClassDecl tree) {
2000 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2001 assert (tree.sym.flags_field & LOCKED) == 0;
2002 try {
2003 tree.sym.flags_field |= LOCKED;
2004 for (JCTree def : tree.defs) {
2005 if (def.getTag() != JCTree.METHODDEF) continue;
2006 JCMethodDecl meth = (JCMethodDecl)def;
2007 checkAnnotationResType(meth.pos(), meth.restype.type);
2008 }
2009 } finally {
2010 tree.sym.flags_field &= ~LOCKED;
2011 tree.sym.flags_field |= ACYCLIC_ANN;
2012 }
2013 }
2015 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2016 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2017 return;
2018 if ((tsym.flags_field & LOCKED) != 0) {
2019 log.error(pos, "cyclic.annotation.element");
2020 return;
2021 }
2022 try {
2023 tsym.flags_field |= LOCKED;
2024 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2025 Symbol s = e.sym;
2026 if (s.kind != Kinds.MTH)
2027 continue;
2028 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2029 }
2030 } finally {
2031 tsym.flags_field &= ~LOCKED;
2032 tsym.flags_field |= ACYCLIC_ANN;
2033 }
2034 }
2036 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2037 switch (type.tag) {
2038 case TypeTags.CLASS:
2039 if ((type.tsym.flags() & ANNOTATION) != 0)
2040 checkNonCyclicElementsInternal(pos, type.tsym);
2041 break;
2042 case TypeTags.ARRAY:
2043 checkAnnotationResType(pos, types.elemtype(type));
2044 break;
2045 default:
2046 break; // int etc
2047 }
2048 }
2050 /* *************************************************************************
2051 * Check for cycles in the constructor call graph.
2052 **************************************************************************/
2054 /** Check for cycles in the graph of constructors calling other
2055 * constructors.
2056 */
2057 void checkCyclicConstructors(JCClassDecl tree) {
2058 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2060 // enter each constructor this-call into the map
2061 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2062 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2063 if (app == null) continue;
2064 JCMethodDecl meth = (JCMethodDecl) l.head;
2065 if (TreeInfo.name(app.meth) == names._this) {
2066 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2067 } else {
2068 meth.sym.flags_field |= ACYCLIC;
2069 }
2070 }
2072 // Check for cycles in the map
2073 Symbol[] ctors = new Symbol[0];
2074 ctors = callMap.keySet().toArray(ctors);
2075 for (Symbol caller : ctors) {
2076 checkCyclicConstructor(tree, caller, callMap);
2077 }
2078 }
2080 /** Look in the map to see if the given constructor is part of a
2081 * call cycle.
2082 */
2083 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2084 Map<Symbol,Symbol> callMap) {
2085 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2086 if ((ctor.flags_field & LOCKED) != 0) {
2087 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2088 "recursive.ctor.invocation");
2089 } else {
2090 ctor.flags_field |= LOCKED;
2091 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2092 ctor.flags_field &= ~LOCKED;
2093 }
2094 ctor.flags_field |= ACYCLIC;
2095 }
2096 }
2098 /* *************************************************************************
2099 * Miscellaneous
2100 **************************************************************************/
2102 /**
2103 * Return the opcode of the operator but emit an error if it is an
2104 * error.
2105 * @param pos position for error reporting.
2106 * @param operator an operator
2107 * @param tag a tree tag
2108 * @param left type of left hand side
2109 * @param right type of right hand side
2110 */
2111 int checkOperator(DiagnosticPosition pos,
2112 OperatorSymbol operator,
2113 int tag,
2114 Type left,
2115 Type right) {
2116 if (operator.opcode == ByteCodes.error) {
2117 log.error(pos,
2118 "operator.cant.be.applied",
2119 treeinfo.operatorName(tag),
2120 List.of(left, right));
2121 }
2122 return operator.opcode;
2123 }
2126 /**
2127 * Check for division by integer constant zero
2128 * @param pos Position for error reporting.
2129 * @param operator The operator for the expression
2130 * @param operand The right hand operand for the expression
2131 */
2132 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2133 if (operand.constValue() != null
2134 && lint.isEnabled(Lint.LintCategory.DIVZERO)
2135 && operand.tag <= LONG
2136 && ((Number) (operand.constValue())).longValue() == 0) {
2137 int opc = ((OperatorSymbol)operator).opcode;
2138 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2139 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2140 log.warning(pos, "div.zero");
2141 }
2142 }
2143 }
2145 /**
2146 * Check for empty statements after if
2147 */
2148 void checkEmptyIf(JCIf tree) {
2149 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
2150 log.warning(tree.thenpart.pos(), "empty.if");
2151 }
2153 /** Check that symbol is unique in given scope.
2154 * @param pos Position for error reporting.
2155 * @param sym The symbol.
2156 * @param s The scope.
2157 */
2158 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2159 if (sym.type.isErroneous())
2160 return true;
2161 if (sym.owner.name == names.any) return false;
2162 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2163 if (sym != e.sym &&
2164 sym.kind == e.sym.kind &&
2165 sym.name != names.error &&
2166 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2167 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
2168 varargsDuplicateError(pos, sym, e.sym);
2169 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
2170 duplicateErasureError(pos, sym, e.sym);
2171 else
2172 duplicateError(pos, e.sym);
2173 return false;
2174 }
2175 }
2176 return true;
2177 }
2178 //where
2179 /** Report duplicate declaration error.
2180 */
2181 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2182 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2183 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2184 }
2185 }
2187 /** Check that single-type import is not already imported or top-level defined,
2188 * but make an exception for two single-type imports which denote the same type.
2189 * @param pos Position for error reporting.
2190 * @param sym The symbol.
2191 * @param s The scope
2192 */
2193 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2194 return checkUniqueImport(pos, sym, s, false);
2195 }
2197 /** Check that static single-type import is not already imported or top-level defined,
2198 * but make an exception for two single-type imports which denote the same type.
2199 * @param pos Position for error reporting.
2200 * @param sym The symbol.
2201 * @param s The scope
2202 * @param staticImport Whether or not this was a static import
2203 */
2204 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2205 return checkUniqueImport(pos, sym, s, true);
2206 }
2208 /** Check that single-type import is not already imported or top-level defined,
2209 * but make an exception for two single-type imports which denote the same type.
2210 * @param pos Position for error reporting.
2211 * @param sym The symbol.
2212 * @param s The scope.
2213 * @param staticImport Whether or not this was a static import
2214 */
2215 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2216 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2217 // is encountered class entered via a class declaration?
2218 boolean isClassDecl = e.scope == s;
2219 if ((isClassDecl || sym != e.sym) &&
2220 sym.kind == e.sym.kind &&
2221 sym.name != names.error) {
2222 if (!e.sym.type.isErroneous()) {
2223 String what = e.sym.toString();
2224 if (!isClassDecl) {
2225 if (staticImport)
2226 log.error(pos, "already.defined.static.single.import", what);
2227 else
2228 log.error(pos, "already.defined.single.import", what);
2229 }
2230 else if (sym != e.sym)
2231 log.error(pos, "already.defined.this.unit", what);
2232 }
2233 return false;
2234 }
2235 }
2236 return true;
2237 }
2239 /** Check that a qualified name is in canonical form (for import decls).
2240 */
2241 public void checkCanonical(JCTree tree) {
2242 if (!isCanonical(tree))
2243 log.error(tree.pos(), "import.requires.canonical",
2244 TreeInfo.symbol(tree));
2245 }
2246 // where
2247 private boolean isCanonical(JCTree tree) {
2248 while (tree.getTag() == JCTree.SELECT) {
2249 JCFieldAccess s = (JCFieldAccess) tree;
2250 if (s.sym.owner != TreeInfo.symbol(s.selected))
2251 return false;
2252 tree = s.selected;
2253 }
2254 return true;
2255 }
2257 private class ConversionWarner extends Warner {
2258 final String key;
2259 final Type found;
2260 final Type expected;
2261 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
2262 super(pos);
2263 this.key = key;
2264 this.found = found;
2265 this.expected = expected;
2266 }
2268 public void warnUnchecked() {
2269 boolean warned = this.warned;
2270 super.warnUnchecked();
2271 if (warned) return; // suppress redundant diagnostics
2272 Object problem = diags.fragment(key);
2273 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
2274 }
2275 }
2277 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2278 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2279 }
2281 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2282 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2283 }
2284 }