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