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