Tue, 06 Mar 2012 13:28:05 +0000
7144506: Attr.checkMethod should be called after inference variables have been fixed
Summary: Unify post-inference sanity check with Attr.checkMethod
Reviewed-by: jjg, dlsmith
1 /*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. 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. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * 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.Flags.ANNOTATION;
46 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
47 import static com.sun.tools.javac.code.Kinds.*;
48 import static com.sun.tools.javac.code.TypeTags.*;
49 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
53 /** Type checking helper class for the attribution phase.
54 *
55 * <p><b>This is NOT part of any supported API.
56 * If you write code that depends on this, you do so at your own risk.
57 * This code and its internal interfaces are subject to change or
58 * deletion without notice.</b>
59 */
60 public class Check {
61 protected static final Context.Key<Check> checkKey =
62 new Context.Key<Check>();
64 private final Names names;
65 private final Log log;
66 private final Resolve rs;
67 private final Symtab syms;
68 private final Enter enter;
69 private final Infer infer;
70 private final Types types;
71 private final JCDiagnostic.Factory diags;
72 private final boolean skipAnnotations;
73 private boolean warnOnSyntheticConflicts;
74 private boolean suppressAbortOnBadClassFile;
75 private boolean enableSunApiLintControl;
76 private final TreeInfo treeinfo;
78 // The set of lint options currently in effect. It is initialized
79 // from the context, and then is set/reset as needed by Attr as it
80 // visits all the various parts of the trees during attribution.
81 private Lint lint;
83 // The method being analyzed in Attr - it is set/reset as needed by
84 // Attr as it visits new method declarations.
85 private MethodSymbol method;
87 public static Check instance(Context context) {
88 Check instance = context.get(checkKey);
89 if (instance == null)
90 instance = new Check(context);
91 return instance;
92 }
94 protected Check(Context context) {
95 context.put(checkKey, this);
97 names = Names.instance(context);
98 log = Log.instance(context);
99 rs = Resolve.instance(context);
100 syms = Symtab.instance(context);
101 enter = Enter.instance(context);
102 infer = Infer.instance(context);
103 this.types = Types.instance(context);
104 diags = JCDiagnostic.Factory.instance(context);
105 Options options = Options.instance(context);
106 lint = Lint.instance(context);
107 treeinfo = TreeInfo.instance(context);
109 Source source = Source.instance(context);
110 allowGenerics = source.allowGenerics();
111 allowVarargs = source.allowVarargs();
112 allowAnnotations = source.allowAnnotations();
113 allowCovariantReturns = source.allowCovariantReturns();
114 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
115 complexInference = options.isSet("complexinference");
116 skipAnnotations = options.isSet("skipAnnotations");
117 warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
118 suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
119 enableSunApiLintControl = options.isSet("enableSunApiLintControl");
121 Target target = Target.instance(context);
122 syntheticNameChar = target.syntheticNameChar();
124 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
125 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
126 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
127 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
129 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
130 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
131 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
132 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
133 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
134 enforceMandatoryWarnings, "sunapi", null);
136 deferredLintHandler = DeferredLintHandler.immediateHandler;
137 }
139 /** Switch: generics enabled?
140 */
141 boolean allowGenerics;
143 /** Switch: varargs enabled?
144 */
145 boolean allowVarargs;
147 /** Switch: annotations enabled?
148 */
149 boolean allowAnnotations;
151 /** Switch: covariant returns enabled?
152 */
153 boolean allowCovariantReturns;
155 /** Switch: simplified varargs enabled?
156 */
157 boolean allowSimplifiedVarargs;
159 /** Switch: -complexinference option set?
160 */
161 boolean complexInference;
163 /** Character for synthetic names
164 */
165 char syntheticNameChar;
167 /** A table mapping flat names of all compiled classes in this run to their
168 * symbols; maintained from outside.
169 */
170 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
172 /** A handler for messages about deprecated usage.
173 */
174 private MandatoryWarningHandler deprecationHandler;
176 /** A handler for messages about unchecked or unsafe usage.
177 */
178 private MandatoryWarningHandler uncheckedHandler;
180 /** A handler for messages about using proprietary API.
181 */
182 private MandatoryWarningHandler sunApiHandler;
184 /** A handler for deferred lint warnings.
185 */
186 private DeferredLintHandler deferredLintHandler;
188 /* *************************************************************************
189 * Errors and Warnings
190 **************************************************************************/
192 Lint setLint(Lint newLint) {
193 Lint prev = lint;
194 lint = newLint;
195 return prev;
196 }
198 DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
199 DeferredLintHandler prev = deferredLintHandler;
200 deferredLintHandler = newDeferredLintHandler;
201 return prev;
202 }
204 MethodSymbol setMethod(MethodSymbol newMethod) {
205 MethodSymbol prev = method;
206 method = newMethod;
207 return prev;
208 }
210 /** Warn about deprecated symbol.
211 * @param pos Position to be used for error reporting.
212 * @param sym The deprecated symbol.
213 */
214 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
215 if (!lint.isSuppressed(LintCategory.DEPRECATION))
216 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
217 }
219 /** Warn about unchecked operation.
220 * @param pos Position to be used for error reporting.
221 * @param msg A string describing the problem.
222 */
223 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
224 if (!lint.isSuppressed(LintCategory.UNCHECKED))
225 uncheckedHandler.report(pos, msg, args);
226 }
228 /** Warn about unsafe vararg method decl.
229 * @param pos Position to be used for error reporting.
230 * @param sym The deprecated symbol.
231 */
232 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
233 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
234 log.warning(LintCategory.VARARGS, pos, key, args);
235 }
237 /** Warn about using proprietary API.
238 * @param pos Position to be used for error reporting.
239 * @param msg A string describing the problem.
240 */
241 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
242 if (!lint.isSuppressed(LintCategory.SUNAPI))
243 sunApiHandler.report(pos, msg, args);
244 }
246 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
247 if (lint.isEnabled(LintCategory.STATIC))
248 log.warning(LintCategory.STATIC, pos, msg, args);
249 }
251 /**
252 * Report any deferred diagnostics.
253 */
254 public void reportDeferredDiagnostics() {
255 deprecationHandler.reportDeferredDiagnostic();
256 uncheckedHandler.reportDeferredDiagnostic();
257 sunApiHandler.reportDeferredDiagnostic();
258 }
261 /** Report a failure to complete a class.
262 * @param pos Position to be used for error reporting.
263 * @param ex The failure to report.
264 */
265 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
266 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
267 if (ex instanceof ClassReader.BadClassFile
268 && !suppressAbortOnBadClassFile) throw new Abort();
269 else return syms.errType;
270 }
272 /** Report a type error.
273 * @param pos Position to be used for error reporting.
274 * @param problem A string describing the error.
275 * @param found The type that was found.
276 * @param req The type that was required.
277 */
278 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
279 log.error(pos, "prob.found.req",
280 problem, found, req);
281 return types.createErrorType(found);
282 }
284 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
285 log.error(pos, "prob.found.req.1", problem, found, req, explanation);
286 return types.createErrorType(found);
287 }
289 /** Report an error that wrong type tag was found.
290 * @param pos Position to be used for error reporting.
291 * @param required An internationalized string describing the type tag
292 * required.
293 * @param found The type that was found.
294 */
295 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
296 // this error used to be raised by the parser,
297 // but has been delayed to this point:
298 if (found instanceof Type && ((Type)found).tag == VOID) {
299 log.error(pos, "illegal.start.of.type");
300 return syms.errType;
301 }
302 log.error(pos, "type.found.req", found, required);
303 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
304 }
306 /** Report an error that symbol cannot be referenced before super
307 * has been called.
308 * @param pos Position to be used for error reporting.
309 * @param sym The referenced symbol.
310 */
311 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
312 log.error(pos, "cant.ref.before.ctor.called", sym);
313 }
315 /** Report duplicate declaration error.
316 */
317 void duplicateError(DiagnosticPosition pos, Symbol sym) {
318 if (!sym.type.isErroneous()) {
319 Symbol location = sym.location();
320 if (location.kind == MTH &&
321 ((MethodSymbol)location).isStaticOrInstanceInit()) {
322 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
323 kindName(sym.location()), kindName(sym.location().enclClass()),
324 sym.location().enclClass());
325 } else {
326 log.error(pos, "already.defined", kindName(sym), sym,
327 kindName(sym.location()), sym.location());
328 }
329 }
330 }
332 /** Report array/varargs duplicate declaration
333 */
334 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
335 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
336 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
337 }
338 }
340 /* ************************************************************************
341 * duplicate declaration checking
342 *************************************************************************/
344 /** Check that variable does not hide variable with same name in
345 * immediately enclosing local scope.
346 * @param pos Position for error reporting.
347 * @param v The symbol.
348 * @param s The scope.
349 */
350 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
351 if (s.next != null) {
352 for (Scope.Entry e = s.next.lookup(v.name);
353 e.scope != null && e.sym.owner == v.owner;
354 e = e.next()) {
355 if (e.sym.kind == VAR &&
356 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
357 v.name != names.error) {
358 duplicateError(pos, e.sym);
359 return;
360 }
361 }
362 }
363 }
365 /** Check that a class or interface does not hide a class or
366 * interface with same name in immediately enclosing local scope.
367 * @param pos Position for error reporting.
368 * @param c The symbol.
369 * @param s The scope.
370 */
371 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
372 if (s.next != null) {
373 for (Scope.Entry e = s.next.lookup(c.name);
374 e.scope != null && e.sym.owner == c.owner;
375 e = e.next()) {
376 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
377 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
378 c.name != names.error) {
379 duplicateError(pos, e.sym);
380 return;
381 }
382 }
383 }
384 }
386 /** Check that class does not have the same name as one of
387 * its enclosing classes, or as a class defined in its enclosing scope.
388 * return true if class is unique in its enclosing scope.
389 * @param pos Position for error reporting.
390 * @param name The class name.
391 * @param s The enclosing scope.
392 */
393 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
394 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
395 if (e.sym.kind == TYP && e.sym.name != names.error) {
396 duplicateError(pos, e.sym);
397 return false;
398 }
399 }
400 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
401 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
402 duplicateError(pos, sym);
403 return true;
404 }
405 }
406 return true;
407 }
409 /* *************************************************************************
410 * Class name generation
411 **************************************************************************/
413 /** Return name of local class.
414 * This is of the form <enclClass> $ n <classname>
415 * where
416 * enclClass is the flat name of the enclosing class,
417 * classname is the simple name of the local class
418 */
419 Name localClassName(ClassSymbol c) {
420 for (int i=1; ; i++) {
421 Name flatname = names.
422 fromString("" + c.owner.enclClass().flatname +
423 syntheticNameChar + i +
424 c.name);
425 if (compiled.get(flatname) == null) return flatname;
426 }
427 }
429 /* *************************************************************************
430 * Type Checking
431 **************************************************************************/
433 /** Check that a given type is assignable to a given proto-type.
434 * If it is, return the type, otherwise return errType.
435 * @param pos Position to be used for error reporting.
436 * @param found The type that was found.
437 * @param req The type that was required.
438 */
439 Type checkType(DiagnosticPosition pos, Type found, Type req) {
440 return checkType(pos, found, req, "incompatible.types");
441 }
443 Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
444 if (req.tag == ERROR)
445 return req;
446 if (found.tag == FORALL)
447 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
448 if (req.tag == NONE)
449 return found;
450 if (types.isAssignable(found, req, convertWarner(pos, found, req)))
451 return found;
452 if (found.tag <= DOUBLE && req.tag <= DOUBLE)
453 return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
454 if (found.isSuperBound()) {
455 log.error(pos, "assignment.from.super-bound", found);
456 return types.createErrorType(found);
457 }
458 if (req.isExtendsBound()) {
459 log.error(pos, "assignment.to.extends-bound", req);
460 return types.createErrorType(found);
461 }
462 return typeError(pos, diags.fragment(errKey), found, req);
463 }
465 /** Instantiate polymorphic type to some prototype, unless
466 * prototype is `anyPoly' in which case polymorphic type
467 * is returned unchanged.
468 */
469 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
470 if (pt == Infer.anyPoly && complexInference) {
471 return t;
472 } else if (pt == Infer.anyPoly || pt.tag == NONE) {
473 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
474 return instantiatePoly(pos, t, newpt, warn);
475 } else if (pt.tag == ERROR) {
476 return pt;
477 } else {
478 try {
479 return infer.instantiateExpr(t, pt, warn);
480 } catch (Infer.NoInstanceException ex) {
481 if (ex.isAmbiguous) {
482 JCDiagnostic d = ex.getDiagnostic();
483 log.error(pos,
484 "undetermined.type" + (d!=null ? ".1" : ""),
485 t, d);
486 return types.createErrorType(pt);
487 } else {
488 JCDiagnostic d = ex.getDiagnostic();
489 return typeError(pos,
490 diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
491 t, pt);
492 }
493 } catch (Infer.InvalidInstanceException ex) {
494 JCDiagnostic d = ex.getDiagnostic();
495 log.error(pos, "invalid.inferred.types", t.tvars, d);
496 return types.createErrorType(pt);
497 }
498 }
499 }
501 /** Check that a given type can be cast to a given target type.
502 * Return the result of the cast.
503 * @param pos Position to be used for error reporting.
504 * @param found The type that is being cast.
505 * @param req The target type of the cast.
506 */
507 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
508 if (found.tag == FORALL) {
509 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
510 return req;
511 } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
512 return req;
513 } else {
514 return typeError(pos,
515 diags.fragment("inconvertible.types"),
516 found, req);
517 }
518 }
519 //where
520 /** Is type a type variable, or a (possibly multi-dimensional) array of
521 * type variables?
522 */
523 boolean isTypeVar(Type t) {
524 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
525 }
527 /** Check that a type is within some bounds.
528 *
529 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
530 * type argument.
531 * @param pos Position to be used for error reporting.
532 * @param a The type that should be bounded by bs.
533 * @param bs The bound.
534 */
535 private boolean checkExtends(Type a, Type bound) {
536 if (a.isUnbound()) {
537 return true;
538 } else if (a.tag != WILDCARD) {
539 a = types.upperBound(a);
540 return types.isSubtype(a, bound);
541 } else if (a.isExtendsBound()) {
542 return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
543 } else if (a.isSuperBound()) {
544 return !types.notSoftSubtype(types.lowerBound(a), bound);
545 }
546 return true;
547 }
549 /** Check that type is different from 'void'.
550 * @param pos Position to be used for error reporting.
551 * @param t The type to be checked.
552 */
553 Type checkNonVoid(DiagnosticPosition pos, Type t) {
554 if (t.tag == VOID) {
555 log.error(pos, "void.not.allowed.here");
556 return types.createErrorType(t);
557 } else {
558 return t;
559 }
560 }
562 /** Check that type is a class or interface type.
563 * @param pos Position to be used for error reporting.
564 * @param t The type to be checked.
565 */
566 Type checkClassType(DiagnosticPosition pos, Type t) {
567 if (t.tag != CLASS && t.tag != ERROR)
568 return typeTagError(pos,
569 diags.fragment("type.req.class"),
570 (t.tag == TYPEVAR)
571 ? diags.fragment("type.parameter", t)
572 : t);
573 else
574 return t;
575 }
577 /** Check that type is a class or interface type.
578 * @param pos Position to be used for error reporting.
579 * @param t The type to be checked.
580 * @param noBounds True if type bounds are illegal here.
581 */
582 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
583 t = checkClassType(pos, t);
584 if (noBounds && t.isParameterized()) {
585 List<Type> args = t.getTypeArguments();
586 while (args.nonEmpty()) {
587 if (args.head.tag == WILDCARD)
588 return typeTagError(pos,
589 diags.fragment("type.req.exact"),
590 args.head);
591 args = args.tail;
592 }
593 }
594 return t;
595 }
597 /** Check that type is a reifiable class, interface or array type.
598 * @param pos Position to be used for error reporting.
599 * @param t The type to be checked.
600 */
601 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
602 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
603 return typeTagError(pos,
604 diags.fragment("type.req.class.array"),
605 t);
606 } else if (!types.isReifiable(t)) {
607 log.error(pos, "illegal.generic.type.for.instof");
608 return types.createErrorType(t);
609 } else {
610 return t;
611 }
612 }
614 /** Check that type is a reference type, i.e. a class, interface or array type
615 * or a type variable.
616 * @param pos Position to be used for error reporting.
617 * @param t The type to be checked.
618 */
619 Type checkRefType(DiagnosticPosition pos, Type t) {
620 switch (t.tag) {
621 case CLASS:
622 case ARRAY:
623 case TYPEVAR:
624 case WILDCARD:
625 case ERROR:
626 return t;
627 default:
628 return typeTagError(pos,
629 diags.fragment("type.req.ref"),
630 t);
631 }
632 }
634 /** Check that each type is a reference type, i.e. a class, interface or array type
635 * or a type variable.
636 * @param trees Original trees, used for error reporting.
637 * @param types The types to be checked.
638 */
639 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
640 List<JCExpression> tl = trees;
641 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
642 l.head = checkRefType(tl.head.pos(), l.head);
643 tl = tl.tail;
644 }
645 return types;
646 }
648 /** Check that type is a null or reference type.
649 * @param pos Position to be used for error reporting.
650 * @param t The type to be checked.
651 */
652 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
653 switch (t.tag) {
654 case CLASS:
655 case ARRAY:
656 case TYPEVAR:
657 case WILDCARD:
658 case BOT:
659 case ERROR:
660 return t;
661 default:
662 return typeTagError(pos,
663 diags.fragment("type.req.ref"),
664 t);
665 }
666 }
668 /** Check that flag set does not contain elements of two conflicting sets. s
669 * Return true if it doesn't.
670 * @param pos Position to be used for error reporting.
671 * @param flags The set of flags to be checked.
672 * @param set1 Conflicting flags set #1.
673 * @param set2 Conflicting flags set #2.
674 */
675 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
676 if ((flags & set1) != 0 && (flags & set2) != 0) {
677 log.error(pos,
678 "illegal.combination.of.modifiers",
679 asFlagSet(TreeInfo.firstFlag(flags & set1)),
680 asFlagSet(TreeInfo.firstFlag(flags & set2)));
681 return false;
682 } else
683 return true;
684 }
686 /** Check that usage of diamond operator is correct (i.e. diamond should not
687 * be used with non-generic classes or in anonymous class creation expressions)
688 */
689 Type checkDiamond(JCNewClass tree, Type t) {
690 if (!TreeInfo.isDiamond(tree) ||
691 t.isErroneous()) {
692 return checkClassType(tree.clazz.pos(), t, true);
693 } else if (tree.def != null) {
694 log.error(tree.clazz.pos(),
695 "cant.apply.diamond.1",
696 t, diags.fragment("diamond.and.anon.class", t));
697 return types.createErrorType(t);
698 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
699 log.error(tree.clazz.pos(),
700 "cant.apply.diamond.1",
701 t, diags.fragment("diamond.non.generic", t));
702 return types.createErrorType(t);
703 } else if (tree.typeargs != null &&
704 tree.typeargs.nonEmpty()) {
705 log.error(tree.clazz.pos(),
706 "cant.apply.diamond.1",
707 t, diags.fragment("diamond.and.explicit.params", t));
708 return types.createErrorType(t);
709 } else {
710 return t;
711 }
712 }
714 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
715 MethodSymbol m = tree.sym;
716 if (!allowSimplifiedVarargs) return;
717 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
718 Type varargElemType = null;
719 if (m.isVarArgs()) {
720 varargElemType = types.elemtype(tree.params.last().type);
721 }
722 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
723 if (varargElemType != null) {
724 log.error(tree,
725 "varargs.invalid.trustme.anno",
726 syms.trustMeType.tsym,
727 diags.fragment("varargs.trustme.on.virtual.varargs", m));
728 } else {
729 log.error(tree,
730 "varargs.invalid.trustme.anno",
731 syms.trustMeType.tsym,
732 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
733 }
734 } else if (hasTrustMeAnno && varargElemType != null &&
735 types.isReifiable(varargElemType)) {
736 warnUnsafeVararg(tree,
737 "varargs.redundant.trustme.anno",
738 syms.trustMeType.tsym,
739 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
740 }
741 else if (!hasTrustMeAnno && varargElemType != null &&
742 !types.isReifiable(varargElemType)) {
743 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
744 }
745 }
746 //where
747 private boolean isTrustMeAllowedOnMethod(Symbol s) {
748 return (s.flags() & VARARGS) != 0 &&
749 (s.isConstructor() ||
750 (s.flags() & (STATIC | FINAL)) != 0);
751 }
753 Type checkMethod(Type owntype,
754 Symbol sym,
755 Env<AttrContext> env,
756 final List<JCExpression> argtrees,
757 List<Type> argtypes,
758 boolean useVarargs) {
759 boolean warned = false;
760 // System.out.println("call : " + env.tree);
761 // System.out.println("method : " + owntype);
762 // System.out.println("actuals: " + argtypes);
763 List<Type> formals = owntype.getParameterTypes();
764 Type last = useVarargs ? formals.last() : null;
765 if (sym.name==names.init &&
766 sym.owner == syms.enumSym)
767 formals = formals.tail.tail;
768 List<JCExpression> args = argtrees;
769 while (formals.head != last) {
770 JCTree arg = args.head;
771 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
772 assertConvertible(arg, arg.type, formals.head, warn);
773 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
774 args = args.tail;
775 formals = formals.tail;
776 }
777 if (useVarargs) {
778 Type varArg = types.elemtype(last);
779 while (args.tail != null) {
780 JCTree arg = args.head;
781 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
782 assertConvertible(arg, arg.type, varArg, warn);
783 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
784 args = args.tail;
785 }
786 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
787 // non-varargs call to varargs method
788 Type varParam = owntype.getParameterTypes().last();
789 Type lastArg = argtypes.last();
790 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
791 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
792 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
793 types.elemtype(varParam), varParam);
794 }
795 if (warned) {
796 warnUnchecked(env.tree.pos(),
797 "unchecked.meth.invocation.applied",
798 kindName(sym),
799 sym.name,
800 rs.methodArguments(sym.type.getParameterTypes()),
801 rs.methodArguments(argtypes),
802 kindName(sym.location()),
803 sym.location());
804 owntype = new MethodType(owntype.getParameterTypes(),
805 types.erasure(owntype.getReturnType()),
806 types.erasure(owntype.getThrownTypes()),
807 syms.methodClass);
808 }
809 if (useVarargs) {
810 JCTree tree = env.tree;
811 Type argtype = owntype.getParameterTypes().last();
812 if (!types.isReifiable(argtype) &&
813 (!allowSimplifiedVarargs ||
814 sym.attribute(syms.trustMeType.tsym) == null ||
815 !isTrustMeAllowedOnMethod(sym))) {
816 warnUnchecked(env.tree.pos(),
817 "unchecked.generic.array.creation",
818 argtype);
819 }
820 Type elemtype = types.elemtype(argtype);
821 switch (tree.getTag()) {
822 case APPLY:
823 ((JCMethodInvocation) tree).varargsElement = elemtype;
824 break;
825 case NEWCLASS:
826 ((JCNewClass) tree).varargsElement = elemtype;
827 break;
828 default:
829 throw new AssertionError(""+tree);
830 }
831 }
832 return owntype;
833 }
834 //where
835 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
836 if (types.isConvertible(actual, formal, warn))
837 return;
839 if (formal.isCompound()
840 && types.isSubtype(actual, types.supertype(formal))
841 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
842 return;
844 if (false) {
845 // TODO: make assertConvertible work
846 typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
847 throw new AssertionError("Tree: " + tree
848 + " actual:" + actual
849 + " formal: " + formal);
850 }
851 }
853 /**
854 * Check that type 't' is a valid instantiation of a generic class
855 * (see JLS 4.5)
856 *
857 * @param t class type to be checked
858 * @return true if 't' is well-formed
859 */
860 public boolean checkValidGenericType(Type t) {
861 return firstIncompatibleTypeArg(t) == null;
862 }
863 //WHERE
864 private Type firstIncompatibleTypeArg(Type type) {
865 List<Type> formals = type.tsym.type.allparams();
866 List<Type> actuals = type.allparams();
867 List<Type> args = type.getTypeArguments();
868 List<Type> forms = type.tsym.type.getTypeArguments();
869 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
871 // For matching pairs of actual argument types `a' and
872 // formal type parameters with declared bound `b' ...
873 while (args.nonEmpty() && forms.nonEmpty()) {
874 // exact type arguments needs to know their
875 // bounds (for upper and lower bound
876 // calculations). So we create new bounds where
877 // type-parameters are replaced with actuals argument types.
878 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
879 args = args.tail;
880 forms = forms.tail;
881 }
883 args = type.getTypeArguments();
884 List<Type> tvars_cap = types.substBounds(formals,
885 formals,
886 types.capture(type).allparams());
887 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
888 // Let the actual arguments know their bound
889 args.head.withTypeVar((TypeVar)tvars_cap.head);
890 args = args.tail;
891 tvars_cap = tvars_cap.tail;
892 }
894 args = type.getTypeArguments();
895 List<Type> bounds = bounds_buf.toList();
897 while (args.nonEmpty() && bounds.nonEmpty()) {
898 Type actual = args.head;
899 if (!isTypeArgErroneous(actual) &&
900 !bounds.head.isErroneous() &&
901 !checkExtends(actual, bounds.head)) {
902 return args.head;
903 }
904 args = args.tail;
905 bounds = bounds.tail;
906 }
908 args = type.getTypeArguments();
909 bounds = bounds_buf.toList();
911 for (Type arg : types.capture(type).getTypeArguments()) {
912 if (arg.tag == TYPEVAR &&
913 arg.getUpperBound().isErroneous() &&
914 !bounds.head.isErroneous() &&
915 !isTypeArgErroneous(args.head)) {
916 return args.head;
917 }
918 bounds = bounds.tail;
919 args = args.tail;
920 }
922 return null;
923 }
924 //where
925 boolean isTypeArgErroneous(Type t) {
926 return isTypeArgErroneous.visit(t);
927 }
929 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
930 public Boolean visitType(Type t, Void s) {
931 return t.isErroneous();
932 }
933 @Override
934 public Boolean visitTypeVar(TypeVar t, Void s) {
935 return visit(t.getUpperBound());
936 }
937 @Override
938 public Boolean visitCapturedType(CapturedType t, Void s) {
939 return visit(t.getUpperBound()) ||
940 visit(t.getLowerBound());
941 }
942 @Override
943 public Boolean visitWildcardType(WildcardType t, Void s) {
944 return visit(t.type);
945 }
946 };
948 /** Check that given modifiers are legal for given symbol and
949 * return modifiers together with any implicit modififiers for that symbol.
950 * Warning: we can't use flags() here since this method
951 * is called during class enter, when flags() would cause a premature
952 * completion.
953 * @param pos Position to be used for error reporting.
954 * @param flags The set of modifiers given in a definition.
955 * @param sym The defined symbol.
956 */
957 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
958 long mask;
959 long implicit = 0;
960 switch (sym.kind) {
961 case VAR:
962 if (sym.owner.kind != TYP)
963 mask = LocalVarFlags;
964 else if ((sym.owner.flags_field & INTERFACE) != 0)
965 mask = implicit = InterfaceVarFlags;
966 else
967 mask = VarFlags;
968 break;
969 case MTH:
970 if (sym.name == names.init) {
971 if ((sym.owner.flags_field & ENUM) != 0) {
972 // enum constructors cannot be declared public or
973 // protected and must be implicitly or explicitly
974 // private
975 implicit = PRIVATE;
976 mask = PRIVATE;
977 } else
978 mask = ConstructorFlags;
979 } else if ((sym.owner.flags_field & INTERFACE) != 0)
980 mask = implicit = InterfaceMethodFlags;
981 else {
982 mask = MethodFlags;
983 }
984 // Imply STRICTFP if owner has STRICTFP set.
985 if (((flags|implicit) & Flags.ABSTRACT) == 0)
986 implicit |= sym.owner.flags_field & STRICTFP;
987 break;
988 case TYP:
989 if (sym.isLocal()) {
990 mask = LocalClassFlags;
991 if (sym.name.isEmpty()) { // Anonymous class
992 // Anonymous classes in static methods are themselves static;
993 // that's why we admit STATIC here.
994 mask |= STATIC;
995 // JLS: Anonymous classes are final.
996 implicit |= FINAL;
997 }
998 if ((sym.owner.flags_field & STATIC) == 0 &&
999 (flags & ENUM) != 0)
1000 log.error(pos, "enums.must.be.static");
1001 } else if (sym.owner.kind == TYP) {
1002 mask = MemberClassFlags;
1003 if (sym.owner.owner.kind == PCK ||
1004 (sym.owner.flags_field & STATIC) != 0)
1005 mask |= STATIC;
1006 else if ((flags & ENUM) != 0)
1007 log.error(pos, "enums.must.be.static");
1008 // Nested interfaces and enums are always STATIC (Spec ???)
1009 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1010 } else {
1011 mask = ClassFlags;
1012 }
1013 // Interfaces are always ABSTRACT
1014 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1016 if ((flags & ENUM) != 0) {
1017 // enums can't be declared abstract or final
1018 mask &= ~(ABSTRACT | FINAL);
1019 implicit |= implicitEnumFinalFlag(tree);
1020 }
1021 // Imply STRICTFP if owner has STRICTFP set.
1022 implicit |= sym.owner.flags_field & STRICTFP;
1023 break;
1024 default:
1025 throw new AssertionError();
1026 }
1027 long illegal = flags & StandardFlags & ~mask;
1028 if (illegal != 0) {
1029 if ((illegal & INTERFACE) != 0) {
1030 log.error(pos, "intf.not.allowed.here");
1031 mask |= INTERFACE;
1032 }
1033 else {
1034 log.error(pos,
1035 "mod.not.allowed.here", asFlagSet(illegal));
1036 }
1037 }
1038 else if ((sym.kind == TYP ||
1039 // ISSUE: Disallowing abstract&private is no longer appropriate
1040 // in the presence of inner classes. Should it be deleted here?
1041 checkDisjoint(pos, flags,
1042 ABSTRACT,
1043 PRIVATE | STATIC))
1044 &&
1045 checkDisjoint(pos, flags,
1046 ABSTRACT | INTERFACE,
1047 FINAL | NATIVE | SYNCHRONIZED)
1048 &&
1049 checkDisjoint(pos, flags,
1050 PUBLIC,
1051 PRIVATE | PROTECTED)
1052 &&
1053 checkDisjoint(pos, flags,
1054 PRIVATE,
1055 PUBLIC | PROTECTED)
1056 &&
1057 checkDisjoint(pos, flags,
1058 FINAL,
1059 VOLATILE)
1060 &&
1061 (sym.kind == TYP ||
1062 checkDisjoint(pos, flags,
1063 ABSTRACT | NATIVE,
1064 STRICTFP))) {
1065 // skip
1066 }
1067 return flags & (mask | ~StandardFlags) | implicit;
1068 }
1071 /** Determine if this enum should be implicitly final.
1072 *
1073 * If the enum has no specialized enum contants, it is final.
1074 *
1075 * If the enum does have specialized enum contants, it is
1076 * <i>not</i> final.
1077 */
1078 private long implicitEnumFinalFlag(JCTree tree) {
1079 if (!tree.hasTag(CLASSDEF)) return 0;
1080 class SpecialTreeVisitor extends JCTree.Visitor {
1081 boolean specialized;
1082 SpecialTreeVisitor() {
1083 this.specialized = false;
1084 };
1086 @Override
1087 public void visitTree(JCTree tree) { /* no-op */ }
1089 @Override
1090 public void visitVarDef(JCVariableDecl tree) {
1091 if ((tree.mods.flags & ENUM) != 0) {
1092 if (tree.init instanceof JCNewClass &&
1093 ((JCNewClass) tree.init).def != null) {
1094 specialized = true;
1095 }
1096 }
1097 }
1098 }
1100 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1101 JCClassDecl cdef = (JCClassDecl) tree;
1102 for (JCTree defs: cdef.defs) {
1103 defs.accept(sts);
1104 if (sts.specialized) return 0;
1105 }
1106 return FINAL;
1107 }
1109 /* *************************************************************************
1110 * Type Validation
1111 **************************************************************************/
1113 /** Validate a type expression. That is,
1114 * check that all type arguments of a parametric type are within
1115 * their bounds. This must be done in a second phase after type attributon
1116 * since a class might have a subclass as type parameter bound. E.g:
1117 *
1118 * class B<A extends C> { ... }
1119 * class C extends B<C> { ... }
1120 *
1121 * and we can't make sure that the bound is already attributed because
1122 * of possible cycles.
1123 *
1124 * Visitor method: Validate a type expression, if it is not null, catching
1125 * and reporting any completion failures.
1126 */
1127 void validate(JCTree tree, Env<AttrContext> env) {
1128 validate(tree, env, true);
1129 }
1130 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1131 new Validator(env).validateTree(tree, checkRaw, true);
1132 }
1134 /** Visitor method: Validate a list of type expressions.
1135 */
1136 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1137 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1138 validate(l.head, env);
1139 }
1141 /** A visitor class for type validation.
1142 */
1143 class Validator extends JCTree.Visitor {
1145 boolean isOuter;
1146 Env<AttrContext> env;
1148 Validator(Env<AttrContext> env) {
1149 this.env = env;
1150 }
1152 @Override
1153 public void visitTypeArray(JCArrayTypeTree tree) {
1154 tree.elemtype.accept(this);
1155 }
1157 @Override
1158 public void visitTypeApply(JCTypeApply tree) {
1159 if (tree.type.tag == CLASS) {
1160 List<JCExpression> args = tree.arguments;
1161 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1163 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1164 if (incompatibleArg != null) {
1165 for (JCTree arg : tree.arguments) {
1166 if (arg.type == incompatibleArg) {
1167 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1168 }
1169 forms = forms.tail;
1170 }
1171 }
1173 forms = tree.type.tsym.type.getTypeArguments();
1175 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1177 // For matching pairs of actual argument types `a' and
1178 // formal type parameters with declared bound `b' ...
1179 while (args.nonEmpty() && forms.nonEmpty()) {
1180 validateTree(args.head,
1181 !(isOuter && is_java_lang_Class),
1182 false);
1183 args = args.tail;
1184 forms = forms.tail;
1185 }
1187 // Check that this type is either fully parameterized, or
1188 // not parameterized at all.
1189 if (tree.type.getEnclosingType().isRaw())
1190 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1191 if (tree.clazz.hasTag(SELECT))
1192 visitSelectInternal((JCFieldAccess)tree.clazz);
1193 }
1194 }
1196 @Override
1197 public void visitTypeParameter(JCTypeParameter tree) {
1198 validateTrees(tree.bounds, true, isOuter);
1199 checkClassBounds(tree.pos(), tree.type);
1200 }
1202 @Override
1203 public void visitWildcard(JCWildcard tree) {
1204 if (tree.inner != null)
1205 validateTree(tree.inner, true, isOuter);
1206 }
1208 @Override
1209 public void visitSelect(JCFieldAccess tree) {
1210 if (tree.type.tag == CLASS) {
1211 visitSelectInternal(tree);
1213 // Check that this type is either fully parameterized, or
1214 // not parameterized at all.
1215 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1216 log.error(tree.pos(), "improperly.formed.type.param.missing");
1217 }
1218 }
1220 public void visitSelectInternal(JCFieldAccess tree) {
1221 if (tree.type.tsym.isStatic() &&
1222 tree.selected.type.isParameterized()) {
1223 // The enclosing type is not a class, so we are
1224 // looking at a static member type. However, the
1225 // qualifying expression is parameterized.
1226 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1227 } else {
1228 // otherwise validate the rest of the expression
1229 tree.selected.accept(this);
1230 }
1231 }
1233 /** Default visitor method: do nothing.
1234 */
1235 @Override
1236 public void visitTree(JCTree tree) {
1237 }
1239 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1240 try {
1241 if (tree != null) {
1242 this.isOuter = isOuter;
1243 tree.accept(this);
1244 if (checkRaw)
1245 checkRaw(tree, env);
1246 }
1247 } catch (CompletionFailure ex) {
1248 completionError(tree.pos(), ex);
1249 }
1250 }
1252 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1253 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1254 validateTree(l.head, checkRaw, isOuter);
1255 }
1257 void checkRaw(JCTree tree, Env<AttrContext> env) {
1258 if (lint.isEnabled(LintCategory.RAW) &&
1259 tree.type.tag == CLASS &&
1260 !TreeInfo.isDiamond(tree) &&
1261 !withinAnonConstr(env) &&
1262 tree.type.isRaw()) {
1263 log.warning(LintCategory.RAW,
1264 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1265 }
1266 }
1268 boolean withinAnonConstr(Env<AttrContext> env) {
1269 return env.enclClass.name.isEmpty() &&
1270 env.enclMethod != null && env.enclMethod.name == names.init;
1271 }
1272 }
1274 /* *************************************************************************
1275 * Exception checking
1276 **************************************************************************/
1278 /* The following methods treat classes as sets that contain
1279 * the class itself and all their subclasses
1280 */
1282 /** Is given type a subtype of some of the types in given list?
1283 */
1284 boolean subset(Type t, List<Type> ts) {
1285 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1286 if (types.isSubtype(t, l.head)) return true;
1287 return false;
1288 }
1290 /** Is given type a subtype or supertype of
1291 * some of the types in given list?
1292 */
1293 boolean intersects(Type t, List<Type> ts) {
1294 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1295 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1296 return false;
1297 }
1299 /** Add type set to given type list, unless it is a subclass of some class
1300 * in the list.
1301 */
1302 List<Type> incl(Type t, List<Type> ts) {
1303 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1304 }
1306 /** Remove type set from type set list.
1307 */
1308 List<Type> excl(Type t, List<Type> ts) {
1309 if (ts.isEmpty()) {
1310 return ts;
1311 } else {
1312 List<Type> ts1 = excl(t, ts.tail);
1313 if (types.isSubtype(ts.head, t)) return ts1;
1314 else if (ts1 == ts.tail) return ts;
1315 else return ts1.prepend(ts.head);
1316 }
1317 }
1319 /** Form the union of two type set lists.
1320 */
1321 List<Type> union(List<Type> ts1, List<Type> ts2) {
1322 List<Type> ts = ts1;
1323 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1324 ts = incl(l.head, ts);
1325 return ts;
1326 }
1328 /** Form the difference of two type lists.
1329 */
1330 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1331 List<Type> ts = ts1;
1332 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1333 ts = excl(l.head, ts);
1334 return ts;
1335 }
1337 /** Form the intersection of two type lists.
1338 */
1339 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1340 List<Type> ts = List.nil();
1341 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1342 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1343 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1344 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1345 return ts;
1346 }
1348 /** Is exc an exception symbol that need not be declared?
1349 */
1350 boolean isUnchecked(ClassSymbol exc) {
1351 return
1352 exc.kind == ERR ||
1353 exc.isSubClass(syms.errorType.tsym, types) ||
1354 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1355 }
1357 /** Is exc an exception type that need not be declared?
1358 */
1359 boolean isUnchecked(Type exc) {
1360 return
1361 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1362 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1363 exc.tag == BOT;
1364 }
1366 /** Same, but handling completion failures.
1367 */
1368 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1369 try {
1370 return isUnchecked(exc);
1371 } catch (CompletionFailure ex) {
1372 completionError(pos, ex);
1373 return true;
1374 }
1375 }
1377 /** Is exc handled by given exception list?
1378 */
1379 boolean isHandled(Type exc, List<Type> handled) {
1380 return isUnchecked(exc) || subset(exc, handled);
1381 }
1383 /** Return all exceptions in thrown list that are not in handled list.
1384 * @param thrown The list of thrown exceptions.
1385 * @param handled The list of handled exceptions.
1386 */
1387 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1388 List<Type> unhandled = List.nil();
1389 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1390 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1391 return unhandled;
1392 }
1394 /* *************************************************************************
1395 * Overriding/Implementation checking
1396 **************************************************************************/
1398 /** The level of access protection given by a flag set,
1399 * where PRIVATE is highest and PUBLIC is lowest.
1400 */
1401 static int protection(long flags) {
1402 switch ((short)(flags & AccessFlags)) {
1403 case PRIVATE: return 3;
1404 case PROTECTED: return 1;
1405 default:
1406 case PUBLIC: return 0;
1407 case 0: return 2;
1408 }
1409 }
1411 /** A customized "cannot override" error message.
1412 * @param m The overriding method.
1413 * @param other The overridden method.
1414 * @return An internationalized string.
1415 */
1416 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1417 String key;
1418 if ((other.owner.flags() & INTERFACE) == 0)
1419 key = "cant.override";
1420 else if ((m.owner.flags() & INTERFACE) == 0)
1421 key = "cant.implement";
1422 else
1423 key = "clashes.with";
1424 return diags.fragment(key, m, m.location(), other, other.location());
1425 }
1427 /** A customized "override" warning message.
1428 * @param m The overriding method.
1429 * @param other The overridden method.
1430 * @return An internationalized string.
1431 */
1432 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1433 String key;
1434 if ((other.owner.flags() & INTERFACE) == 0)
1435 key = "unchecked.override";
1436 else if ((m.owner.flags() & INTERFACE) == 0)
1437 key = "unchecked.implement";
1438 else
1439 key = "unchecked.clash.with";
1440 return diags.fragment(key, m, m.location(), other, other.location());
1441 }
1443 /** A customized "override" warning message.
1444 * @param m The overriding method.
1445 * @param other The overridden method.
1446 * @return An internationalized string.
1447 */
1448 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1449 String key;
1450 if ((other.owner.flags() & INTERFACE) == 0)
1451 key = "varargs.override";
1452 else if ((m.owner.flags() & INTERFACE) == 0)
1453 key = "varargs.implement";
1454 else
1455 key = "varargs.clash.with";
1456 return diags.fragment(key, m, m.location(), other, other.location());
1457 }
1459 /** Check that this method conforms with overridden method 'other'.
1460 * where `origin' is the class where checking started.
1461 * Complications:
1462 * (1) Do not check overriding of synthetic methods
1463 * (reason: they might be final).
1464 * todo: check whether this is still necessary.
1465 * (2) Admit the case where an interface proxy throws fewer exceptions
1466 * than the method it implements. Augment the proxy methods with the
1467 * undeclared exceptions in this case.
1468 * (3) When generics are enabled, admit the case where an interface proxy
1469 * has a result type
1470 * extended by the result type of the method it implements.
1471 * Change the proxies result type to the smaller type in this case.
1472 *
1473 * @param tree The tree from which positions
1474 * are extracted for errors.
1475 * @param m The overriding method.
1476 * @param other The overridden method.
1477 * @param origin The class of which the overriding method
1478 * is a member.
1479 */
1480 void checkOverride(JCTree tree,
1481 MethodSymbol m,
1482 MethodSymbol other,
1483 ClassSymbol origin) {
1484 // Don't check overriding of synthetic methods or by bridge methods.
1485 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1486 return;
1487 }
1489 // Error if static method overrides instance method (JLS 8.4.6.2).
1490 if ((m.flags() & STATIC) != 0 &&
1491 (other.flags() & STATIC) == 0) {
1492 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1493 cannotOverride(m, other));
1494 return;
1495 }
1497 // Error if instance method overrides static or final
1498 // method (JLS 8.4.6.1).
1499 if ((other.flags() & FINAL) != 0 ||
1500 (m.flags() & STATIC) == 0 &&
1501 (other.flags() & STATIC) != 0) {
1502 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1503 cannotOverride(m, other),
1504 asFlagSet(other.flags() & (FINAL | STATIC)));
1505 return;
1506 }
1508 if ((m.owner.flags() & ANNOTATION) != 0) {
1509 // handled in validateAnnotationMethod
1510 return;
1511 }
1513 // Error if overriding method has weaker access (JLS 8.4.6.3).
1514 if ((origin.flags() & INTERFACE) == 0 &&
1515 protection(m.flags()) > protection(other.flags())) {
1516 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1517 cannotOverride(m, other),
1518 other.flags() == 0 ?
1519 Flag.PACKAGE :
1520 asFlagSet(other.flags() & AccessFlags));
1521 return;
1522 }
1524 Type mt = types.memberType(origin.type, m);
1525 Type ot = types.memberType(origin.type, other);
1526 // Error if overriding result type is different
1527 // (or, in the case of generics mode, not a subtype) of
1528 // overridden result type. We have to rename any type parameters
1529 // before comparing types.
1530 List<Type> mtvars = mt.getTypeArguments();
1531 List<Type> otvars = ot.getTypeArguments();
1532 Type mtres = mt.getReturnType();
1533 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1535 overrideWarner.clear();
1536 boolean resultTypesOK =
1537 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1538 if (!resultTypesOK) {
1539 if (!allowCovariantReturns &&
1540 m.owner != origin &&
1541 m.owner.isSubClass(other.owner, types)) {
1542 // allow limited interoperability with covariant returns
1543 } else {
1544 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1545 "override.incompatible.ret",
1546 cannotOverride(m, other),
1547 mtres, otres);
1548 return;
1549 }
1550 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1551 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1552 "override.unchecked.ret",
1553 uncheckedOverrides(m, other),
1554 mtres, otres);
1555 }
1557 // Error if overriding method throws an exception not reported
1558 // by overridden method.
1559 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1560 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1561 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1562 if (unhandledErased.nonEmpty()) {
1563 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1564 "override.meth.doesnt.throw",
1565 cannotOverride(m, other),
1566 unhandledUnerased.head);
1567 return;
1568 }
1569 else if (unhandledUnerased.nonEmpty()) {
1570 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1571 "override.unchecked.thrown",
1572 cannotOverride(m, other),
1573 unhandledUnerased.head);
1574 return;
1575 }
1577 // Optional warning if varargs don't agree
1578 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1579 && lint.isEnabled(LintCategory.OVERRIDES)) {
1580 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1581 ((m.flags() & Flags.VARARGS) != 0)
1582 ? "override.varargs.missing"
1583 : "override.varargs.extra",
1584 varargsOverrides(m, other));
1585 }
1587 // Warn if instance method overrides bridge method (compiler spec ??)
1588 if ((other.flags() & BRIDGE) != 0) {
1589 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1590 uncheckedOverrides(m, other));
1591 }
1593 // Warn if a deprecated method overridden by a non-deprecated one.
1594 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1595 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1596 }
1597 }
1598 // where
1599 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1600 // If the method, m, is defined in an interface, then ignore the issue if the method
1601 // is only inherited via a supertype and also implemented in the supertype,
1602 // because in that case, we will rediscover the issue when examining the method
1603 // in the supertype.
1604 // If the method, m, is not defined in an interface, then the only time we need to
1605 // address the issue is when the method is the supertype implemementation: any other
1606 // case, we will have dealt with when examining the supertype classes
1607 ClassSymbol mc = m.enclClass();
1608 Type st = types.supertype(origin.type);
1609 if (st.tag != CLASS)
1610 return true;
1611 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1613 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1614 List<Type> intfs = types.interfaces(origin.type);
1615 return (intfs.contains(mc.type) ? false : (stimpl != null));
1616 }
1617 else
1618 return (stimpl != m);
1619 }
1622 // used to check if there were any unchecked conversions
1623 Warner overrideWarner = new Warner();
1625 /** Check that a class does not inherit two concrete methods
1626 * with the same signature.
1627 * @param pos Position to be used for error reporting.
1628 * @param site The class type to be checked.
1629 */
1630 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1631 Type sup = types.supertype(site);
1632 if (sup.tag != CLASS) return;
1634 for (Type t1 = sup;
1635 t1.tsym.type.isParameterized();
1636 t1 = types.supertype(t1)) {
1637 for (Scope.Entry e1 = t1.tsym.members().elems;
1638 e1 != null;
1639 e1 = e1.sibling) {
1640 Symbol s1 = e1.sym;
1641 if (s1.kind != MTH ||
1642 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1643 !s1.isInheritedIn(site.tsym, types) ||
1644 ((MethodSymbol)s1).implementation(site.tsym,
1645 types,
1646 true) != s1)
1647 continue;
1648 Type st1 = types.memberType(t1, s1);
1649 int s1ArgsLength = st1.getParameterTypes().length();
1650 if (st1 == s1.type) continue;
1652 for (Type t2 = sup;
1653 t2.tag == CLASS;
1654 t2 = types.supertype(t2)) {
1655 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1656 e2.scope != null;
1657 e2 = e2.next()) {
1658 Symbol s2 = e2.sym;
1659 if (s2 == s1 ||
1660 s2.kind != MTH ||
1661 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1662 s2.type.getParameterTypes().length() != s1ArgsLength ||
1663 !s2.isInheritedIn(site.tsym, types) ||
1664 ((MethodSymbol)s2).implementation(site.tsym,
1665 types,
1666 true) != s2)
1667 continue;
1668 Type st2 = types.memberType(t2, s2);
1669 if (types.overrideEquivalent(st1, st2))
1670 log.error(pos, "concrete.inheritance.conflict",
1671 s1, t1, s2, t2, sup);
1672 }
1673 }
1674 }
1675 }
1676 }
1678 /** Check that classes (or interfaces) do not each define an abstract
1679 * method with same name and arguments but incompatible return types.
1680 * @param pos Position to be used for error reporting.
1681 * @param t1 The first argument type.
1682 * @param t2 The second argument type.
1683 */
1684 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1685 Type t1,
1686 Type t2) {
1687 return checkCompatibleAbstracts(pos, t1, t2,
1688 types.makeCompoundType(t1, t2));
1689 }
1691 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1692 Type t1,
1693 Type t2,
1694 Type site) {
1695 return firstIncompatibility(pos, t1, t2, site) == null;
1696 }
1698 /** Return the first method which is defined with same args
1699 * but different return types in two given interfaces, or null if none
1700 * exists.
1701 * @param t1 The first type.
1702 * @param t2 The second type.
1703 * @param site The most derived type.
1704 * @returns symbol from t2 that conflicts with one in t1.
1705 */
1706 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1707 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1708 closure(t1, interfaces1);
1709 Map<TypeSymbol,Type> interfaces2;
1710 if (t1 == t2)
1711 interfaces2 = interfaces1;
1712 else
1713 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1715 for (Type t3 : interfaces1.values()) {
1716 for (Type t4 : interfaces2.values()) {
1717 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1718 if (s != null) return s;
1719 }
1720 }
1721 return null;
1722 }
1724 /** Compute all the supertypes of t, indexed by type symbol. */
1725 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1726 if (t.tag != CLASS) return;
1727 if (typeMap.put(t.tsym, t) == null) {
1728 closure(types.supertype(t), typeMap);
1729 for (Type i : types.interfaces(t))
1730 closure(i, typeMap);
1731 }
1732 }
1734 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1735 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1736 if (t.tag != CLASS) return;
1737 if (typesSkip.get(t.tsym) != null) return;
1738 if (typeMap.put(t.tsym, t) == null) {
1739 closure(types.supertype(t), typesSkip, typeMap);
1740 for (Type i : types.interfaces(t))
1741 closure(i, typesSkip, typeMap);
1742 }
1743 }
1745 /** Return the first method in t2 that conflicts with a method from t1. */
1746 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1747 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1748 Symbol s1 = e1.sym;
1749 Type st1 = null;
1750 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1751 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1752 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1753 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1754 Symbol s2 = e2.sym;
1755 if (s1 == s2) continue;
1756 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1757 if (st1 == null) st1 = types.memberType(t1, s1);
1758 Type st2 = types.memberType(t2, s2);
1759 if (types.overrideEquivalent(st1, st2)) {
1760 List<Type> tvars1 = st1.getTypeArguments();
1761 List<Type> tvars2 = st2.getTypeArguments();
1762 Type rt1 = st1.getReturnType();
1763 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1764 boolean compat =
1765 types.isSameType(rt1, rt2) ||
1766 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1767 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1768 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1769 checkCommonOverriderIn(s1,s2,site);
1770 if (!compat) {
1771 log.error(pos, "types.incompatible.diff.ret",
1772 t1, t2, s2.name +
1773 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1774 return s2;
1775 }
1776 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1777 !checkCommonOverriderIn(s1, s2, site)) {
1778 log.error(pos,
1779 "name.clash.same.erasure.no.override",
1780 s1, s1.location(),
1781 s2, s2.location());
1782 return s2;
1783 }
1784 }
1785 }
1786 return null;
1787 }
1788 //WHERE
1789 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1790 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1791 Type st1 = types.memberType(site, s1);
1792 Type st2 = types.memberType(site, s2);
1793 closure(site, supertypes);
1794 for (Type t : supertypes.values()) {
1795 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1796 Symbol s3 = e.sym;
1797 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1798 Type st3 = types.memberType(site,s3);
1799 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1800 if (s3.owner == site.tsym) {
1801 return true;
1802 }
1803 List<Type> tvars1 = st1.getTypeArguments();
1804 List<Type> tvars2 = st2.getTypeArguments();
1805 List<Type> tvars3 = st3.getTypeArguments();
1806 Type rt1 = st1.getReturnType();
1807 Type rt2 = st2.getReturnType();
1808 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1809 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1810 boolean compat =
1811 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1812 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1813 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1814 if (compat)
1815 return true;
1816 }
1817 }
1818 }
1819 return false;
1820 }
1822 /** Check that a given method conforms with any method it overrides.
1823 * @param tree The tree from which positions are extracted
1824 * for errors.
1825 * @param m The overriding method.
1826 */
1827 void checkOverride(JCTree tree, MethodSymbol m) {
1828 ClassSymbol origin = (ClassSymbol)m.owner;
1829 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1830 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1831 log.error(tree.pos(), "enum.no.finalize");
1832 return;
1833 }
1834 for (Type t = origin.type; t.tag == CLASS;
1835 t = types.supertype(t)) {
1836 if (t != origin.type) {
1837 checkOverride(tree, t, origin, m);
1838 }
1839 for (Type t2 : types.interfaces(t)) {
1840 checkOverride(tree, t2, origin, m);
1841 }
1842 }
1843 }
1845 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1846 TypeSymbol c = site.tsym;
1847 Scope.Entry e = c.members().lookup(m.name);
1848 while (e.scope != null) {
1849 if (m.overrides(e.sym, origin, types, false)) {
1850 if ((e.sym.flags() & ABSTRACT) == 0) {
1851 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1852 }
1853 }
1854 e = e.next();
1855 }
1856 }
1858 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1859 ClashFilter cf = new ClashFilter(origin.type);
1860 return (cf.accepts(s1) &&
1861 cf.accepts(s2) &&
1862 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1863 }
1866 /** Check that all abstract members of given class have definitions.
1867 * @param pos Position to be used for error reporting.
1868 * @param c The class.
1869 */
1870 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1871 try {
1872 MethodSymbol undef = firstUndef(c, c);
1873 if (undef != null) {
1874 if ((c.flags() & ENUM) != 0 &&
1875 types.supertype(c.type).tsym == syms.enumSym &&
1876 (c.flags() & FINAL) == 0) {
1877 // add the ABSTRACT flag to an enum
1878 c.flags_field |= ABSTRACT;
1879 } else {
1880 MethodSymbol undef1 =
1881 new MethodSymbol(undef.flags(), undef.name,
1882 types.memberType(c.type, undef), undef.owner);
1883 log.error(pos, "does.not.override.abstract",
1884 c, undef1, undef1.location());
1885 }
1886 }
1887 } catch (CompletionFailure ex) {
1888 completionError(pos, ex);
1889 }
1890 }
1891 //where
1892 /** Return first abstract member of class `c' that is not defined
1893 * in `impl', null if there is none.
1894 */
1895 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1896 MethodSymbol undef = null;
1897 // Do not bother to search in classes that are not abstract,
1898 // since they cannot have abstract members.
1899 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1900 Scope s = c.members();
1901 for (Scope.Entry e = s.elems;
1902 undef == null && e != null;
1903 e = e.sibling) {
1904 if (e.sym.kind == MTH &&
1905 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1906 MethodSymbol absmeth = (MethodSymbol)e.sym;
1907 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1908 if (implmeth == null || implmeth == absmeth)
1909 undef = absmeth;
1910 }
1911 }
1912 if (undef == null) {
1913 Type st = types.supertype(c.type);
1914 if (st.tag == CLASS)
1915 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1916 }
1917 for (List<Type> l = types.interfaces(c.type);
1918 undef == null && l.nonEmpty();
1919 l = l.tail) {
1920 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1921 }
1922 }
1923 return undef;
1924 }
1926 void checkNonCyclicDecl(JCClassDecl tree) {
1927 CycleChecker cc = new CycleChecker();
1928 cc.scan(tree);
1929 if (!cc.errorFound && !cc.partialCheck) {
1930 tree.sym.flags_field |= ACYCLIC;
1931 }
1932 }
1934 class CycleChecker extends TreeScanner {
1936 List<Symbol> seenClasses = List.nil();
1937 boolean errorFound = false;
1938 boolean partialCheck = false;
1940 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1941 if (sym != null && sym.kind == TYP) {
1942 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1943 if (classEnv != null) {
1944 DiagnosticSource prevSource = log.currentSource();
1945 try {
1946 log.useSource(classEnv.toplevel.sourcefile);
1947 scan(classEnv.tree);
1948 }
1949 finally {
1950 log.useSource(prevSource.getFile());
1951 }
1952 } else if (sym.kind == TYP) {
1953 checkClass(pos, sym, List.<JCTree>nil());
1954 }
1955 } else {
1956 //not completed yet
1957 partialCheck = true;
1958 }
1959 }
1961 @Override
1962 public void visitSelect(JCFieldAccess tree) {
1963 super.visitSelect(tree);
1964 checkSymbol(tree.pos(), tree.sym);
1965 }
1967 @Override
1968 public void visitIdent(JCIdent tree) {
1969 checkSymbol(tree.pos(), tree.sym);
1970 }
1972 @Override
1973 public void visitTypeApply(JCTypeApply tree) {
1974 scan(tree.clazz);
1975 }
1977 @Override
1978 public void visitTypeArray(JCArrayTypeTree tree) {
1979 scan(tree.elemtype);
1980 }
1982 @Override
1983 public void visitClassDef(JCClassDecl tree) {
1984 List<JCTree> supertypes = List.nil();
1985 if (tree.getExtendsClause() != null) {
1986 supertypes = supertypes.prepend(tree.getExtendsClause());
1987 }
1988 if (tree.getImplementsClause() != null) {
1989 for (JCTree intf : tree.getImplementsClause()) {
1990 supertypes = supertypes.prepend(intf);
1991 }
1992 }
1993 checkClass(tree.pos(), tree.sym, supertypes);
1994 }
1996 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
1997 if ((c.flags_field & ACYCLIC) != 0)
1998 return;
1999 if (seenClasses.contains(c)) {
2000 errorFound = true;
2001 noteCyclic(pos, (ClassSymbol)c);
2002 } else if (!c.type.isErroneous()) {
2003 try {
2004 seenClasses = seenClasses.prepend(c);
2005 if (c.type.tag == CLASS) {
2006 if (supertypes.nonEmpty()) {
2007 scan(supertypes);
2008 }
2009 else {
2010 ClassType ct = (ClassType)c.type;
2011 if (ct.supertype_field == null ||
2012 ct.interfaces_field == null) {
2013 //not completed yet
2014 partialCheck = true;
2015 return;
2016 }
2017 checkSymbol(pos, ct.supertype_field.tsym);
2018 for (Type intf : ct.interfaces_field) {
2019 checkSymbol(pos, intf.tsym);
2020 }
2021 }
2022 if (c.owner.kind == TYP) {
2023 checkSymbol(pos, c.owner);
2024 }
2025 }
2026 } finally {
2027 seenClasses = seenClasses.tail;
2028 }
2029 }
2030 }
2031 }
2033 /** Check for cyclic references. Issue an error if the
2034 * symbol of the type referred to has a LOCKED flag set.
2035 *
2036 * @param pos Position to be used for error reporting.
2037 * @param t The type referred to.
2038 */
2039 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2040 checkNonCyclicInternal(pos, t);
2041 }
2044 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2045 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2046 }
2048 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2049 final TypeVar tv;
2050 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
2051 return;
2052 if (seen.contains(t)) {
2053 tv = (TypeVar)t;
2054 tv.bound = types.createErrorType(t);
2055 log.error(pos, "cyclic.inheritance", t);
2056 } else if (t.tag == TYPEVAR) {
2057 tv = (TypeVar)t;
2058 seen = seen.prepend(tv);
2059 for (Type b : types.getBounds(tv))
2060 checkNonCyclic1(pos, b, seen);
2061 }
2062 }
2064 /** Check for cyclic references. Issue an error if the
2065 * symbol of the type referred to has a LOCKED flag set.
2066 *
2067 * @param pos Position to be used for error reporting.
2068 * @param t The type referred to.
2069 * @returns True if the check completed on all attributed classes
2070 */
2071 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2072 boolean complete = true; // was the check complete?
2073 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2074 Symbol c = t.tsym;
2075 if ((c.flags_field & ACYCLIC) != 0) return true;
2077 if ((c.flags_field & LOCKED) != 0) {
2078 noteCyclic(pos, (ClassSymbol)c);
2079 } else if (!c.type.isErroneous()) {
2080 try {
2081 c.flags_field |= LOCKED;
2082 if (c.type.tag == CLASS) {
2083 ClassType clazz = (ClassType)c.type;
2084 if (clazz.interfaces_field != null)
2085 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2086 complete &= checkNonCyclicInternal(pos, l.head);
2087 if (clazz.supertype_field != null) {
2088 Type st = clazz.supertype_field;
2089 if (st != null && st.tag == CLASS)
2090 complete &= checkNonCyclicInternal(pos, st);
2091 }
2092 if (c.owner.kind == TYP)
2093 complete &= checkNonCyclicInternal(pos, c.owner.type);
2094 }
2095 } finally {
2096 c.flags_field &= ~LOCKED;
2097 }
2098 }
2099 if (complete)
2100 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2101 if (complete) c.flags_field |= ACYCLIC;
2102 return complete;
2103 }
2105 /** Note that we found an inheritance cycle. */
2106 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2107 log.error(pos, "cyclic.inheritance", c);
2108 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2109 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2110 Type st = types.supertype(c.type);
2111 if (st.tag == CLASS)
2112 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2113 c.type = types.createErrorType(c, c.type);
2114 c.flags_field |= ACYCLIC;
2115 }
2117 /** Check that all methods which implement some
2118 * method conform to the method they implement.
2119 * @param tree The class definition whose members are checked.
2120 */
2121 void checkImplementations(JCClassDecl tree) {
2122 checkImplementations(tree, tree.sym);
2123 }
2124 //where
2125 /** Check that all methods which implement some
2126 * method in `ic' conform to the method they implement.
2127 */
2128 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2129 ClassSymbol origin = tree.sym;
2130 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2131 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2132 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2133 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2134 if (e.sym.kind == MTH &&
2135 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2136 MethodSymbol absmeth = (MethodSymbol)e.sym;
2137 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2138 if (implmeth != null && implmeth != absmeth &&
2139 (implmeth.owner.flags() & INTERFACE) ==
2140 (origin.flags() & INTERFACE)) {
2141 // don't check if implmeth is in a class, yet
2142 // origin is an interface. This case arises only
2143 // if implmeth is declared in Object. The reason is
2144 // that interfaces really don't inherit from
2145 // Object it's just that the compiler represents
2146 // things that way.
2147 checkOverride(tree, implmeth, absmeth, origin);
2148 }
2149 }
2150 }
2151 }
2152 }
2153 }
2155 /** Check that all abstract methods implemented by a class are
2156 * mutually compatible.
2157 * @param pos Position to be used for error reporting.
2158 * @param c The class whose interfaces are checked.
2159 */
2160 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2161 List<Type> supertypes = types.interfaces(c);
2162 Type supertype = types.supertype(c);
2163 if (supertype.tag == CLASS &&
2164 (supertype.tsym.flags() & ABSTRACT) != 0)
2165 supertypes = supertypes.prepend(supertype);
2166 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2167 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2168 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2169 return;
2170 for (List<Type> m = supertypes; m != l; m = m.tail)
2171 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2172 return;
2173 }
2174 checkCompatibleConcretes(pos, c);
2175 }
2177 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2178 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2179 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2180 // VM allows methods and variables with differing types
2181 if (sym.kind == e.sym.kind &&
2182 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2183 sym != e.sym &&
2184 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2185 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2186 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2187 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2188 return;
2189 }
2190 }
2191 }
2192 }
2194 /** Check that all non-override equivalent methods accessible from 'site'
2195 * are mutually compatible (JLS 8.4.8/9.4.1).
2196 *
2197 * @param pos Position to be used for error reporting.
2198 * @param site The class whose methods are checked.
2199 * @param sym The method symbol to be checked.
2200 */
2201 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2202 ClashFilter cf = new ClashFilter(site);
2203 //for each method m1 that is overridden (directly or indirectly)
2204 //by method 'sym' in 'site'...
2205 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2206 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2207 //...check each method m2 that is a member of 'site'
2208 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2209 if (m2 == m1) continue;
2210 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2211 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2212 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
2213 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2214 sym.flags_field |= CLASH;
2215 String key = m1 == sym ?
2216 "name.clash.same.erasure.no.override" :
2217 "name.clash.same.erasure.no.override.1";
2218 log.error(pos,
2219 key,
2220 sym, sym.location(),
2221 m2, m2.location(),
2222 m1, m1.location());
2223 return;
2224 }
2225 }
2226 }
2227 }
2231 /** Check that all static methods accessible from 'site' are
2232 * mutually compatible (JLS 8.4.8).
2233 *
2234 * @param pos Position to be used for error reporting.
2235 * @param site The class whose methods are checked.
2236 * @param sym The method symbol to be checked.
2237 */
2238 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2239 ClashFilter cf = new ClashFilter(site);
2240 //for each method m1 that is a member of 'site'...
2241 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2242 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2243 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2244 if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
2245 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2246 log.error(pos,
2247 "name.clash.same.erasure.no.hide",
2248 sym, sym.location(),
2249 s, s.location());
2250 return;
2251 }
2252 }
2253 }
2255 //where
2256 private class ClashFilter implements Filter<Symbol> {
2258 Type site;
2260 ClashFilter(Type site) {
2261 this.site = site;
2262 }
2264 boolean shouldSkip(Symbol s) {
2265 return (s.flags() & CLASH) != 0 &&
2266 s.owner == site.tsym;
2267 }
2269 public boolean accepts(Symbol s) {
2270 return s.kind == MTH &&
2271 (s.flags() & SYNTHETIC) == 0 &&
2272 !shouldSkip(s) &&
2273 s.isInheritedIn(site.tsym, types) &&
2274 !s.isConstructor();
2275 }
2276 }
2278 /** Report a conflict between a user symbol and a synthetic symbol.
2279 */
2280 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2281 if (!sym.type.isErroneous()) {
2282 if (warnOnSyntheticConflicts) {
2283 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2284 }
2285 else {
2286 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2287 }
2288 }
2289 }
2291 /** Check that class c does not implement directly or indirectly
2292 * the same parameterized interface with two different argument lists.
2293 * @param pos Position to be used for error reporting.
2294 * @param type The type whose interfaces are checked.
2295 */
2296 void checkClassBounds(DiagnosticPosition pos, Type type) {
2297 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2298 }
2299 //where
2300 /** Enter all interfaces of type `type' into the hash table `seensofar'
2301 * with their class symbol as key and their type as value. Make
2302 * sure no class is entered with two different types.
2303 */
2304 void checkClassBounds(DiagnosticPosition pos,
2305 Map<TypeSymbol,Type> seensofar,
2306 Type type) {
2307 if (type.isErroneous()) return;
2308 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2309 Type it = l.head;
2310 Type oldit = seensofar.put(it.tsym, it);
2311 if (oldit != null) {
2312 List<Type> oldparams = oldit.allparams();
2313 List<Type> newparams = it.allparams();
2314 if (!types.containsTypeEquivalent(oldparams, newparams))
2315 log.error(pos, "cant.inherit.diff.arg",
2316 it.tsym, Type.toString(oldparams),
2317 Type.toString(newparams));
2318 }
2319 checkClassBounds(pos, seensofar, it);
2320 }
2321 Type st = types.supertype(type);
2322 if (st != null) checkClassBounds(pos, seensofar, st);
2323 }
2325 /** Enter interface into into set.
2326 * If it existed already, issue a "repeated interface" error.
2327 */
2328 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2329 if (its.contains(it))
2330 log.error(pos, "repeated.interface");
2331 else {
2332 its.add(it);
2333 }
2334 }
2336 /* *************************************************************************
2337 * Check annotations
2338 **************************************************************************/
2340 /**
2341 * Recursively validate annotations values
2342 */
2343 void validateAnnotationTree(JCTree tree) {
2344 class AnnotationValidator extends TreeScanner {
2345 @Override
2346 public void visitAnnotation(JCAnnotation tree) {
2347 if (!tree.type.isErroneous()) {
2348 super.visitAnnotation(tree);
2349 validateAnnotation(tree);
2350 }
2351 }
2352 }
2353 tree.accept(new AnnotationValidator());
2354 }
2356 /** Annotation types are restricted to primitives, String, an
2357 * enum, an annotation, Class, Class<?>, Class<? extends
2358 * Anything>, arrays of the preceding.
2359 */
2360 void validateAnnotationType(JCTree restype) {
2361 // restype may be null if an error occurred, so don't bother validating it
2362 if (restype != null) {
2363 validateAnnotationType(restype.pos(), restype.type);
2364 }
2365 }
2367 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2368 if (type.isPrimitive()) return;
2369 if (types.isSameType(type, syms.stringType)) return;
2370 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2371 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2372 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2373 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2374 validateAnnotationType(pos, types.elemtype(type));
2375 return;
2376 }
2377 log.error(pos, "invalid.annotation.member.type");
2378 }
2380 /**
2381 * "It is also a compile-time error if any method declared in an
2382 * annotation type has a signature that is override-equivalent to
2383 * that of any public or protected method declared in class Object
2384 * or in the interface annotation.Annotation."
2385 *
2386 * @jls 9.6 Annotation Types
2387 */
2388 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2389 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2390 Scope s = sup.tsym.members();
2391 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2392 if (e.sym.kind == MTH &&
2393 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2394 types.overrideEquivalent(m.type, e.sym.type))
2395 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2396 }
2397 }
2398 }
2400 /** Check the annotations of a symbol.
2401 */
2402 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2403 if (skipAnnotations) return;
2404 for (JCAnnotation a : annotations)
2405 validateAnnotation(a, s);
2406 }
2408 /** Check an annotation of a symbol.
2409 */
2410 public void validateAnnotation(JCAnnotation a, Symbol s) {
2411 validateAnnotationTree(a);
2413 if (!annotationApplicable(a, s))
2414 log.error(a.pos(), "annotation.type.not.applicable");
2416 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2417 if (!isOverrider(s))
2418 log.error(a.pos(), "method.does.not.override.superclass");
2419 }
2420 }
2422 /** Is s a method symbol that overrides a method in a superclass? */
2423 boolean isOverrider(Symbol s) {
2424 if (s.kind != MTH || s.isStatic())
2425 return false;
2426 MethodSymbol m = (MethodSymbol)s;
2427 TypeSymbol owner = (TypeSymbol)m.owner;
2428 for (Type sup : types.closure(owner.type)) {
2429 if (sup == owner.type)
2430 continue; // skip "this"
2431 Scope scope = sup.tsym.members();
2432 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2433 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2434 return true;
2435 }
2436 }
2437 return false;
2438 }
2440 /** Is the annotation applicable to the symbol? */
2441 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2442 Attribute.Compound atTarget =
2443 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2444 if (atTarget == null) return true;
2445 Attribute atValue = atTarget.member(names.value);
2446 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2447 Attribute.Array arr = (Attribute.Array) atValue;
2448 for (Attribute app : arr.values) {
2449 if (!(app instanceof Attribute.Enum)) return true; // recovery
2450 Attribute.Enum e = (Attribute.Enum) app;
2451 if (e.value.name == names.TYPE)
2452 { if (s.kind == TYP) return true; }
2453 else if (e.value.name == names.FIELD)
2454 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2455 else if (e.value.name == names.METHOD)
2456 { if (s.kind == MTH && !s.isConstructor()) return true; }
2457 else if (e.value.name == names.PARAMETER)
2458 { if (s.kind == VAR &&
2459 s.owner.kind == MTH &&
2460 (s.flags() & PARAMETER) != 0)
2461 return true;
2462 }
2463 else if (e.value.name == names.CONSTRUCTOR)
2464 { if (s.kind == MTH && s.isConstructor()) return true; }
2465 else if (e.value.name == names.LOCAL_VARIABLE)
2466 { if (s.kind == VAR && s.owner.kind == MTH &&
2467 (s.flags() & PARAMETER) == 0)
2468 return true;
2469 }
2470 else if (e.value.name == names.ANNOTATION_TYPE)
2471 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2472 return true;
2473 }
2474 else if (e.value.name == names.PACKAGE)
2475 { if (s.kind == PCK) return true; }
2476 else if (e.value.name == names.TYPE_USE)
2477 { if (s.kind == TYP ||
2478 s.kind == VAR ||
2479 (s.kind == MTH && !s.isConstructor() &&
2480 s.type.getReturnType().tag != VOID))
2481 return true;
2482 }
2483 else
2484 return true; // recovery
2485 }
2486 return false;
2487 }
2489 /** Check an annotation value.
2490 */
2491 public void validateAnnotation(JCAnnotation a) {
2492 // collect an inventory of the members (sorted alphabetically)
2493 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2494 public int compare(Symbol t, Symbol t1) {
2495 return t.name.compareTo(t1.name);
2496 }
2497 });
2498 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2499 e != null;
2500 e = e.sibling)
2501 if (e.sym.kind == MTH)
2502 members.add((MethodSymbol) e.sym);
2504 // count them off as they're annotated
2505 for (JCTree arg : a.args) {
2506 if (!arg.hasTag(ASSIGN)) continue; // recovery
2507 JCAssign assign = (JCAssign) arg;
2508 Symbol m = TreeInfo.symbol(assign.lhs);
2509 if (m == null || m.type.isErroneous()) continue;
2510 if (!members.remove(m))
2511 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2512 m.name, a.type);
2513 }
2515 // all the remaining ones better have default values
2516 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2517 for (MethodSymbol m : members) {
2518 if (m.defaultValue == null && !m.type.isErroneous()) {
2519 missingDefaults.append(m.name);
2520 }
2521 }
2522 if (missingDefaults.nonEmpty()) {
2523 String key = (missingDefaults.size() > 1)
2524 ? "annotation.missing.default.value.1"
2525 : "annotation.missing.default.value";
2526 log.error(a.pos(), key, a.type, missingDefaults);
2527 }
2529 // special case: java.lang.annotation.Target must not have
2530 // repeated values in its value member
2531 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2532 a.args.tail == null)
2533 return;
2535 if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
2536 JCAssign assign = (JCAssign) a.args.head;
2537 Symbol m = TreeInfo.symbol(assign.lhs);
2538 if (m.name != names.value) return;
2539 JCTree rhs = assign.rhs;
2540 if (!rhs.hasTag(NEWARRAY)) return;
2541 JCNewArray na = (JCNewArray) rhs;
2542 Set<Symbol> targets = new HashSet<Symbol>();
2543 for (JCTree elem : na.elems) {
2544 if (!targets.add(TreeInfo.symbol(elem))) {
2545 log.error(elem.pos(), "repeated.annotation.target");
2546 }
2547 }
2548 }
2550 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2551 if (allowAnnotations &&
2552 lint.isEnabled(LintCategory.DEP_ANN) &&
2553 (s.flags() & DEPRECATED) != 0 &&
2554 !syms.deprecatedType.isErroneous() &&
2555 s.attribute(syms.deprecatedType.tsym) == null) {
2556 log.warning(LintCategory.DEP_ANN,
2557 pos, "missing.deprecated.annotation");
2558 }
2559 }
2561 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2562 if ((s.flags() & DEPRECATED) != 0 &&
2563 (other.flags() & DEPRECATED) == 0 &&
2564 s.outermostClass() != other.outermostClass()) {
2565 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2566 @Override
2567 public void report() {
2568 warnDeprecated(pos, s);
2569 }
2570 });
2571 }
2572 }
2574 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2575 if ((s.flags() & PROPRIETARY) != 0) {
2576 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2577 public void report() {
2578 if (enableSunApiLintControl)
2579 warnSunApi(pos, "sun.proprietary", s);
2580 else
2581 log.mandatoryWarning(pos, "sun.proprietary", s);
2582 }
2583 });
2584 }
2585 }
2587 /* *************************************************************************
2588 * Check for recursive annotation elements.
2589 **************************************************************************/
2591 /** Check for cycles in the graph of annotation elements.
2592 */
2593 void checkNonCyclicElements(JCClassDecl tree) {
2594 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2595 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2596 try {
2597 tree.sym.flags_field |= LOCKED;
2598 for (JCTree def : tree.defs) {
2599 if (!def.hasTag(METHODDEF)) continue;
2600 JCMethodDecl meth = (JCMethodDecl)def;
2601 checkAnnotationResType(meth.pos(), meth.restype.type);
2602 }
2603 } finally {
2604 tree.sym.flags_field &= ~LOCKED;
2605 tree.sym.flags_field |= ACYCLIC_ANN;
2606 }
2607 }
2609 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2610 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2611 return;
2612 if ((tsym.flags_field & LOCKED) != 0) {
2613 log.error(pos, "cyclic.annotation.element");
2614 return;
2615 }
2616 try {
2617 tsym.flags_field |= LOCKED;
2618 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2619 Symbol s = e.sym;
2620 if (s.kind != Kinds.MTH)
2621 continue;
2622 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2623 }
2624 } finally {
2625 tsym.flags_field &= ~LOCKED;
2626 tsym.flags_field |= ACYCLIC_ANN;
2627 }
2628 }
2630 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2631 switch (type.tag) {
2632 case TypeTags.CLASS:
2633 if ((type.tsym.flags() & ANNOTATION) != 0)
2634 checkNonCyclicElementsInternal(pos, type.tsym);
2635 break;
2636 case TypeTags.ARRAY:
2637 checkAnnotationResType(pos, types.elemtype(type));
2638 break;
2639 default:
2640 break; // int etc
2641 }
2642 }
2644 /* *************************************************************************
2645 * Check for cycles in the constructor call graph.
2646 **************************************************************************/
2648 /** Check for cycles in the graph of constructors calling other
2649 * constructors.
2650 */
2651 void checkCyclicConstructors(JCClassDecl tree) {
2652 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2654 // enter each constructor this-call into the map
2655 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2656 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2657 if (app == null) continue;
2658 JCMethodDecl meth = (JCMethodDecl) l.head;
2659 if (TreeInfo.name(app.meth) == names._this) {
2660 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2661 } else {
2662 meth.sym.flags_field |= ACYCLIC;
2663 }
2664 }
2666 // Check for cycles in the map
2667 Symbol[] ctors = new Symbol[0];
2668 ctors = callMap.keySet().toArray(ctors);
2669 for (Symbol caller : ctors) {
2670 checkCyclicConstructor(tree, caller, callMap);
2671 }
2672 }
2674 /** Look in the map to see if the given constructor is part of a
2675 * call cycle.
2676 */
2677 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2678 Map<Symbol,Symbol> callMap) {
2679 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2680 if ((ctor.flags_field & LOCKED) != 0) {
2681 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2682 "recursive.ctor.invocation");
2683 } else {
2684 ctor.flags_field |= LOCKED;
2685 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2686 ctor.flags_field &= ~LOCKED;
2687 }
2688 ctor.flags_field |= ACYCLIC;
2689 }
2690 }
2692 /* *************************************************************************
2693 * Miscellaneous
2694 **************************************************************************/
2696 /**
2697 * Return the opcode of the operator but emit an error if it is an
2698 * error.
2699 * @param pos position for error reporting.
2700 * @param operator an operator
2701 * @param tag a tree tag
2702 * @param left type of left hand side
2703 * @param right type of right hand side
2704 */
2705 int checkOperator(DiagnosticPosition pos,
2706 OperatorSymbol operator,
2707 JCTree.Tag tag,
2708 Type left,
2709 Type right) {
2710 if (operator.opcode == ByteCodes.error) {
2711 log.error(pos,
2712 "operator.cant.be.applied.1",
2713 treeinfo.operatorName(tag),
2714 left, right);
2715 }
2716 return operator.opcode;
2717 }
2720 /**
2721 * Check for division by integer constant zero
2722 * @param pos Position for error reporting.
2723 * @param operator The operator for the expression
2724 * @param operand The right hand operand for the expression
2725 */
2726 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2727 if (operand.constValue() != null
2728 && lint.isEnabled(LintCategory.DIVZERO)
2729 && operand.tag <= LONG
2730 && ((Number) (operand.constValue())).longValue() == 0) {
2731 int opc = ((OperatorSymbol)operator).opcode;
2732 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2733 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2734 log.warning(LintCategory.DIVZERO, pos, "div.zero");
2735 }
2736 }
2737 }
2739 /**
2740 * Check for empty statements after if
2741 */
2742 void checkEmptyIf(JCIf tree) {
2743 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
2744 lint.isEnabled(LintCategory.EMPTY))
2745 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
2746 }
2748 /** Check that symbol is unique in given scope.
2749 * @param pos Position for error reporting.
2750 * @param sym The symbol.
2751 * @param s The scope.
2752 */
2753 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2754 if (sym.type.isErroneous())
2755 return true;
2756 if (sym.owner.name == names.any) return false;
2757 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2758 if (sym != e.sym &&
2759 (e.sym.flags() & CLASH) == 0 &&
2760 sym.kind == e.sym.kind &&
2761 sym.name != names.error &&
2762 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2763 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
2764 varargsDuplicateError(pos, sym, e.sym);
2765 return true;
2766 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
2767 duplicateErasureError(pos, sym, e.sym);
2768 sym.flags_field |= CLASH;
2769 return true;
2770 } else {
2771 duplicateError(pos, e.sym);
2772 return false;
2773 }
2774 }
2775 }
2776 return true;
2777 }
2779 /** Report duplicate declaration error.
2780 */
2781 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2782 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2783 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2784 }
2785 }
2787 /** Check that single-type import is not already imported or top-level defined,
2788 * but make an exception for two single-type imports which denote the same type.
2789 * @param pos Position for error reporting.
2790 * @param sym The symbol.
2791 * @param s The scope
2792 */
2793 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2794 return checkUniqueImport(pos, sym, s, false);
2795 }
2797 /** Check that static single-type import is not already imported or top-level defined,
2798 * but make an exception for two single-type imports which denote the same type.
2799 * @param pos Position for error reporting.
2800 * @param sym The symbol.
2801 * @param s The scope
2802 * @param staticImport Whether or not this was a static import
2803 */
2804 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2805 return checkUniqueImport(pos, sym, s, true);
2806 }
2808 /** Check that single-type import is not already imported or top-level defined,
2809 * but make an exception for two single-type imports which denote the same type.
2810 * @param pos Position for error reporting.
2811 * @param sym The symbol.
2812 * @param s The scope.
2813 * @param staticImport Whether or not this was a static import
2814 */
2815 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2816 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2817 // is encountered class entered via a class declaration?
2818 boolean isClassDecl = e.scope == s;
2819 if ((isClassDecl || sym != e.sym) &&
2820 sym.kind == e.sym.kind &&
2821 sym.name != names.error) {
2822 if (!e.sym.type.isErroneous()) {
2823 String what = e.sym.toString();
2824 if (!isClassDecl) {
2825 if (staticImport)
2826 log.error(pos, "already.defined.static.single.import", what);
2827 else
2828 log.error(pos, "already.defined.single.import", what);
2829 }
2830 else if (sym != e.sym)
2831 log.error(pos, "already.defined.this.unit", what);
2832 }
2833 return false;
2834 }
2835 }
2836 return true;
2837 }
2839 /** Check that a qualified name is in canonical form (for import decls).
2840 */
2841 public void checkCanonical(JCTree tree) {
2842 if (!isCanonical(tree))
2843 log.error(tree.pos(), "import.requires.canonical",
2844 TreeInfo.symbol(tree));
2845 }
2846 // where
2847 private boolean isCanonical(JCTree tree) {
2848 while (tree.hasTag(SELECT)) {
2849 JCFieldAccess s = (JCFieldAccess) tree;
2850 if (s.sym.owner != TreeInfo.symbol(s.selected))
2851 return false;
2852 tree = s.selected;
2853 }
2854 return true;
2855 }
2857 private class ConversionWarner extends Warner {
2858 final String uncheckedKey;
2859 final Type found;
2860 final Type expected;
2861 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
2862 super(pos);
2863 this.uncheckedKey = uncheckedKey;
2864 this.found = found;
2865 this.expected = expected;
2866 }
2868 @Override
2869 public void warn(LintCategory lint) {
2870 boolean warned = this.warned;
2871 super.warn(lint);
2872 if (warned) return; // suppress redundant diagnostics
2873 switch (lint) {
2874 case UNCHECKED:
2875 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
2876 break;
2877 case VARARGS:
2878 if (method != null &&
2879 method.attribute(syms.trustMeType.tsym) != null &&
2880 isTrustMeAllowedOnMethod(method) &&
2881 !types.isReifiable(method.type.getParameterTypes().last())) {
2882 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
2883 }
2884 break;
2885 default:
2886 throw new AssertionError("Unexpected lint: " + lint);
2887 }
2888 }
2889 }
2891 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2892 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2893 }
2895 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2896 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2897 }
2898 }