Mon, 26 Mar 2012 15:27:51 +0100
7151580: Separate DA/DU logic from exception checking logic in Flow.java
Summary: DA/DU analysis and exception checking analysis should live in two separate tree visitors
Reviewed-by: gafter, dlsmith, jjg
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 }
520 /** Check for redundant casts (i.e. where source type is a subtype of target type)
521 * The problem should only be reported for non-292 cast
522 */
523 public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
524 if (!tree.type.isErroneous() &&
525 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
526 && types.isSameType(tree.expr.type, tree.clazz.type)
527 && !is292targetTypeCast(tree)) {
528 log.warning(Lint.LintCategory.CAST,
529 tree.pos(), "redundant.cast", tree.expr.type);
530 }
531 }
532 //where
533 private boolean is292targetTypeCast(JCTypeCast tree) {
534 boolean is292targetTypeCast = false;
535 JCExpression expr = TreeInfo.skipParens(tree.expr);
536 if (expr.hasTag(APPLY)) {
537 JCMethodInvocation apply = (JCMethodInvocation)expr;
538 Symbol sym = TreeInfo.symbol(apply.meth);
539 is292targetTypeCast = sym != null &&
540 sym.kind == MTH &&
541 (sym.flags() & POLYMORPHIC_SIGNATURE) != 0;
542 }
543 return is292targetTypeCast;
544 }
548 //where
549 /** Is type a type variable, or a (possibly multi-dimensional) array of
550 * type variables?
551 */
552 boolean isTypeVar(Type t) {
553 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
554 }
556 /** Check that a type is within some bounds.
557 *
558 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
559 * type argument.
560 * @param pos Position to be used for error reporting.
561 * @param a The type that should be bounded by bs.
562 * @param bs The bound.
563 */
564 private boolean checkExtends(Type a, Type bound) {
565 if (a.isUnbound()) {
566 return true;
567 } else if (a.tag != WILDCARD) {
568 a = types.upperBound(a);
569 return types.isSubtype(a, bound);
570 } else if (a.isExtendsBound()) {
571 return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
572 } else if (a.isSuperBound()) {
573 return !types.notSoftSubtype(types.lowerBound(a), bound);
574 }
575 return true;
576 }
578 /** Check that type is different from 'void'.
579 * @param pos Position to be used for error reporting.
580 * @param t The type to be checked.
581 */
582 Type checkNonVoid(DiagnosticPosition pos, Type t) {
583 if (t.tag == VOID) {
584 log.error(pos, "void.not.allowed.here");
585 return types.createErrorType(t);
586 } else {
587 return t;
588 }
589 }
591 /** Check that type is a class or interface type.
592 * @param pos Position to be used for error reporting.
593 * @param t The type to be checked.
594 */
595 Type checkClassType(DiagnosticPosition pos, Type t) {
596 if (t.tag != CLASS && t.tag != ERROR)
597 return typeTagError(pos,
598 diags.fragment("type.req.class"),
599 (t.tag == TYPEVAR)
600 ? diags.fragment("type.parameter", t)
601 : t);
602 else
603 return t;
604 }
606 /** Check that type is a class or interface type.
607 * @param pos Position to be used for error reporting.
608 * @param t The type to be checked.
609 * @param noBounds True if type bounds are illegal here.
610 */
611 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
612 t = checkClassType(pos, t);
613 if (noBounds && t.isParameterized()) {
614 List<Type> args = t.getTypeArguments();
615 while (args.nonEmpty()) {
616 if (args.head.tag == WILDCARD)
617 return typeTagError(pos,
618 diags.fragment("type.req.exact"),
619 args.head);
620 args = args.tail;
621 }
622 }
623 return t;
624 }
626 /** Check that type is a reifiable class, interface or array type.
627 * @param pos Position to be used for error reporting.
628 * @param t The type to be checked.
629 */
630 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
631 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
632 return typeTagError(pos,
633 diags.fragment("type.req.class.array"),
634 t);
635 } else if (!types.isReifiable(t)) {
636 log.error(pos, "illegal.generic.type.for.instof");
637 return types.createErrorType(t);
638 } else {
639 return t;
640 }
641 }
643 /** Check that type is a reference type, i.e. a class, interface or array type
644 * or a type variable.
645 * @param pos Position to be used for error reporting.
646 * @param t The type to be checked.
647 */
648 Type checkRefType(DiagnosticPosition pos, Type t) {
649 switch (t.tag) {
650 case CLASS:
651 case ARRAY:
652 case TYPEVAR:
653 case WILDCARD:
654 case ERROR:
655 return t;
656 default:
657 return typeTagError(pos,
658 diags.fragment("type.req.ref"),
659 t);
660 }
661 }
663 /** Check that each type is a reference type, i.e. a class, interface or array type
664 * or a type variable.
665 * @param trees Original trees, used for error reporting.
666 * @param types The types to be checked.
667 */
668 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
669 List<JCExpression> tl = trees;
670 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
671 l.head = checkRefType(tl.head.pos(), l.head);
672 tl = tl.tail;
673 }
674 return types;
675 }
677 /** Check that type is a null or reference type.
678 * @param pos Position to be used for error reporting.
679 * @param t The type to be checked.
680 */
681 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
682 switch (t.tag) {
683 case CLASS:
684 case ARRAY:
685 case TYPEVAR:
686 case WILDCARD:
687 case BOT:
688 case ERROR:
689 return t;
690 default:
691 return typeTagError(pos,
692 diags.fragment("type.req.ref"),
693 t);
694 }
695 }
697 /** Check that flag set does not contain elements of two conflicting sets. s
698 * Return true if it doesn't.
699 * @param pos Position to be used for error reporting.
700 * @param flags The set of flags to be checked.
701 * @param set1 Conflicting flags set #1.
702 * @param set2 Conflicting flags set #2.
703 */
704 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
705 if ((flags & set1) != 0 && (flags & set2) != 0) {
706 log.error(pos,
707 "illegal.combination.of.modifiers",
708 asFlagSet(TreeInfo.firstFlag(flags & set1)),
709 asFlagSet(TreeInfo.firstFlag(flags & set2)));
710 return false;
711 } else
712 return true;
713 }
715 /** Check that usage of diamond operator is correct (i.e. diamond should not
716 * be used with non-generic classes or in anonymous class creation expressions)
717 */
718 Type checkDiamond(JCNewClass tree, Type t) {
719 if (!TreeInfo.isDiamond(tree) ||
720 t.isErroneous()) {
721 return checkClassType(tree.clazz.pos(), t, true);
722 } else if (tree.def != null) {
723 log.error(tree.clazz.pos(),
724 "cant.apply.diamond.1",
725 t, diags.fragment("diamond.and.anon.class", t));
726 return types.createErrorType(t);
727 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
728 log.error(tree.clazz.pos(),
729 "cant.apply.diamond.1",
730 t, diags.fragment("diamond.non.generic", t));
731 return types.createErrorType(t);
732 } else if (tree.typeargs != null &&
733 tree.typeargs.nonEmpty()) {
734 log.error(tree.clazz.pos(),
735 "cant.apply.diamond.1",
736 t, diags.fragment("diamond.and.explicit.params", t));
737 return types.createErrorType(t);
738 } else {
739 return t;
740 }
741 }
743 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
744 MethodSymbol m = tree.sym;
745 if (!allowSimplifiedVarargs) return;
746 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
747 Type varargElemType = null;
748 if (m.isVarArgs()) {
749 varargElemType = types.elemtype(tree.params.last().type);
750 }
751 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
752 if (varargElemType != null) {
753 log.error(tree,
754 "varargs.invalid.trustme.anno",
755 syms.trustMeType.tsym,
756 diags.fragment("varargs.trustme.on.virtual.varargs", m));
757 } else {
758 log.error(tree,
759 "varargs.invalid.trustme.anno",
760 syms.trustMeType.tsym,
761 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
762 }
763 } else if (hasTrustMeAnno && varargElemType != null &&
764 types.isReifiable(varargElemType)) {
765 warnUnsafeVararg(tree,
766 "varargs.redundant.trustme.anno",
767 syms.trustMeType.tsym,
768 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
769 }
770 else if (!hasTrustMeAnno && varargElemType != null &&
771 !types.isReifiable(varargElemType)) {
772 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
773 }
774 }
775 //where
776 private boolean isTrustMeAllowedOnMethod(Symbol s) {
777 return (s.flags() & VARARGS) != 0 &&
778 (s.isConstructor() ||
779 (s.flags() & (STATIC | FINAL)) != 0);
780 }
782 Type checkMethod(Type owntype,
783 Symbol sym,
784 Env<AttrContext> env,
785 final List<JCExpression> argtrees,
786 List<Type> argtypes,
787 boolean useVarargs,
788 boolean unchecked) {
789 // System.out.println("call : " + env.tree);
790 // System.out.println("method : " + owntype);
791 // System.out.println("actuals: " + argtypes);
792 List<Type> formals = owntype.getParameterTypes();
793 Type last = useVarargs ? formals.last() : null;
794 if (sym.name==names.init &&
795 sym.owner == syms.enumSym)
796 formals = formals.tail.tail;
797 List<JCExpression> args = argtrees;
798 while (formals.head != last) {
799 JCTree arg = args.head;
800 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
801 assertConvertible(arg, arg.type, formals.head, warn);
802 args = args.tail;
803 formals = formals.tail;
804 }
805 if (useVarargs) {
806 Type varArg = types.elemtype(last);
807 while (args.tail != null) {
808 JCTree arg = args.head;
809 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
810 assertConvertible(arg, arg.type, varArg, warn);
811 args = args.tail;
812 }
813 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
814 // non-varargs call to varargs method
815 Type varParam = owntype.getParameterTypes().last();
816 Type lastArg = argtypes.last();
817 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
818 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
819 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
820 types.elemtype(varParam), varParam);
821 }
822 if (unchecked) {
823 warnUnchecked(env.tree.pos(),
824 "unchecked.meth.invocation.applied",
825 kindName(sym),
826 sym.name,
827 rs.methodArguments(sym.type.getParameterTypes()),
828 rs.methodArguments(argtypes),
829 kindName(sym.location()),
830 sym.location());
831 owntype = new MethodType(owntype.getParameterTypes(),
832 types.erasure(owntype.getReturnType()),
833 types.erasure(owntype.getThrownTypes()),
834 syms.methodClass);
835 }
836 if (useVarargs) {
837 JCTree tree = env.tree;
838 Type argtype = owntype.getParameterTypes().last();
839 if (!types.isReifiable(argtype) &&
840 (!allowSimplifiedVarargs ||
841 sym.attribute(syms.trustMeType.tsym) == null ||
842 !isTrustMeAllowedOnMethod(sym))) {
843 warnUnchecked(env.tree.pos(),
844 "unchecked.generic.array.creation",
845 argtype);
846 }
847 Type elemtype = types.elemtype(argtype);
848 switch (tree.getTag()) {
849 case APPLY:
850 ((JCMethodInvocation) tree).varargsElement = elemtype;
851 break;
852 case NEWCLASS:
853 ((JCNewClass) tree).varargsElement = elemtype;
854 break;
855 default:
856 throw new AssertionError(""+tree);
857 }
858 }
859 return owntype;
860 }
861 //where
862 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
863 if (types.isConvertible(actual, formal, warn))
864 return;
866 if (formal.isCompound()
867 && types.isSubtype(actual, types.supertype(formal))
868 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
869 return;
871 if (false) {
872 // TODO: make assertConvertible work
873 typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
874 throw new AssertionError("Tree: " + tree
875 + " actual:" + actual
876 + " formal: " + formal);
877 }
878 }
880 /**
881 * Check that type 't' is a valid instantiation of a generic class
882 * (see JLS 4.5)
883 *
884 * @param t class type to be checked
885 * @return true if 't' is well-formed
886 */
887 public boolean checkValidGenericType(Type t) {
888 return firstIncompatibleTypeArg(t) == null;
889 }
890 //WHERE
891 private Type firstIncompatibleTypeArg(Type type) {
892 List<Type> formals = type.tsym.type.allparams();
893 List<Type> actuals = type.allparams();
894 List<Type> args = type.getTypeArguments();
895 List<Type> forms = type.tsym.type.getTypeArguments();
896 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
898 // For matching pairs of actual argument types `a' and
899 // formal type parameters with declared bound `b' ...
900 while (args.nonEmpty() && forms.nonEmpty()) {
901 // exact type arguments needs to know their
902 // bounds (for upper and lower bound
903 // calculations). So we create new bounds where
904 // type-parameters are replaced with actuals argument types.
905 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
906 args = args.tail;
907 forms = forms.tail;
908 }
910 args = type.getTypeArguments();
911 List<Type> tvars_cap = types.substBounds(formals,
912 formals,
913 types.capture(type).allparams());
914 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
915 // Let the actual arguments know their bound
916 args.head.withTypeVar((TypeVar)tvars_cap.head);
917 args = args.tail;
918 tvars_cap = tvars_cap.tail;
919 }
921 args = type.getTypeArguments();
922 List<Type> bounds = bounds_buf.toList();
924 while (args.nonEmpty() && bounds.nonEmpty()) {
925 Type actual = args.head;
926 if (!isTypeArgErroneous(actual) &&
927 !bounds.head.isErroneous() &&
928 !checkExtends(actual, bounds.head)) {
929 return args.head;
930 }
931 args = args.tail;
932 bounds = bounds.tail;
933 }
935 args = type.getTypeArguments();
936 bounds = bounds_buf.toList();
938 for (Type arg : types.capture(type).getTypeArguments()) {
939 if (arg.tag == TYPEVAR &&
940 arg.getUpperBound().isErroneous() &&
941 !bounds.head.isErroneous() &&
942 !isTypeArgErroneous(args.head)) {
943 return args.head;
944 }
945 bounds = bounds.tail;
946 args = args.tail;
947 }
949 return null;
950 }
951 //where
952 boolean isTypeArgErroneous(Type t) {
953 return isTypeArgErroneous.visit(t);
954 }
956 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
957 public Boolean visitType(Type t, Void s) {
958 return t.isErroneous();
959 }
960 @Override
961 public Boolean visitTypeVar(TypeVar t, Void s) {
962 return visit(t.getUpperBound());
963 }
964 @Override
965 public Boolean visitCapturedType(CapturedType t, Void s) {
966 return visit(t.getUpperBound()) ||
967 visit(t.getLowerBound());
968 }
969 @Override
970 public Boolean visitWildcardType(WildcardType t, Void s) {
971 return visit(t.type);
972 }
973 };
975 /** Check that given modifiers are legal for given symbol and
976 * return modifiers together with any implicit modififiers for that symbol.
977 * Warning: we can't use flags() here since this method
978 * is called during class enter, when flags() would cause a premature
979 * completion.
980 * @param pos Position to be used for error reporting.
981 * @param flags The set of modifiers given in a definition.
982 * @param sym The defined symbol.
983 */
984 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
985 long mask;
986 long implicit = 0;
987 switch (sym.kind) {
988 case VAR:
989 if (sym.owner.kind != TYP)
990 mask = LocalVarFlags;
991 else if ((sym.owner.flags_field & INTERFACE) != 0)
992 mask = implicit = InterfaceVarFlags;
993 else
994 mask = VarFlags;
995 break;
996 case MTH:
997 if (sym.name == names.init) {
998 if ((sym.owner.flags_field & ENUM) != 0) {
999 // enum constructors cannot be declared public or
1000 // protected and must be implicitly or explicitly
1001 // private
1002 implicit = PRIVATE;
1003 mask = PRIVATE;
1004 } else
1005 mask = ConstructorFlags;
1006 } else if ((sym.owner.flags_field & INTERFACE) != 0)
1007 mask = implicit = InterfaceMethodFlags;
1008 else {
1009 mask = MethodFlags;
1010 }
1011 // Imply STRICTFP if owner has STRICTFP set.
1012 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1013 implicit |= sym.owner.flags_field & STRICTFP;
1014 break;
1015 case TYP:
1016 if (sym.isLocal()) {
1017 mask = LocalClassFlags;
1018 if (sym.name.isEmpty()) { // Anonymous class
1019 // Anonymous classes in static methods are themselves static;
1020 // that's why we admit STATIC here.
1021 mask |= STATIC;
1022 // JLS: Anonymous classes are final.
1023 implicit |= FINAL;
1024 }
1025 if ((sym.owner.flags_field & STATIC) == 0 &&
1026 (flags & ENUM) != 0)
1027 log.error(pos, "enums.must.be.static");
1028 } else if (sym.owner.kind == TYP) {
1029 mask = MemberClassFlags;
1030 if (sym.owner.owner.kind == PCK ||
1031 (sym.owner.flags_field & STATIC) != 0)
1032 mask |= STATIC;
1033 else if ((flags & ENUM) != 0)
1034 log.error(pos, "enums.must.be.static");
1035 // Nested interfaces and enums are always STATIC (Spec ???)
1036 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1037 } else {
1038 mask = ClassFlags;
1039 }
1040 // Interfaces are always ABSTRACT
1041 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1043 if ((flags & ENUM) != 0) {
1044 // enums can't be declared abstract or final
1045 mask &= ~(ABSTRACT | FINAL);
1046 implicit |= implicitEnumFinalFlag(tree);
1047 }
1048 // Imply STRICTFP if owner has STRICTFP set.
1049 implicit |= sym.owner.flags_field & STRICTFP;
1050 break;
1051 default:
1052 throw new AssertionError();
1053 }
1054 long illegal = flags & StandardFlags & ~mask;
1055 if (illegal != 0) {
1056 if ((illegal & INTERFACE) != 0) {
1057 log.error(pos, "intf.not.allowed.here");
1058 mask |= INTERFACE;
1059 }
1060 else {
1061 log.error(pos,
1062 "mod.not.allowed.here", asFlagSet(illegal));
1063 }
1064 }
1065 else if ((sym.kind == TYP ||
1066 // ISSUE: Disallowing abstract&private is no longer appropriate
1067 // in the presence of inner classes. Should it be deleted here?
1068 checkDisjoint(pos, flags,
1069 ABSTRACT,
1070 PRIVATE | STATIC))
1071 &&
1072 checkDisjoint(pos, flags,
1073 ABSTRACT | INTERFACE,
1074 FINAL | NATIVE | SYNCHRONIZED)
1075 &&
1076 checkDisjoint(pos, flags,
1077 PUBLIC,
1078 PRIVATE | PROTECTED)
1079 &&
1080 checkDisjoint(pos, flags,
1081 PRIVATE,
1082 PUBLIC | PROTECTED)
1083 &&
1084 checkDisjoint(pos, flags,
1085 FINAL,
1086 VOLATILE)
1087 &&
1088 (sym.kind == TYP ||
1089 checkDisjoint(pos, flags,
1090 ABSTRACT | NATIVE,
1091 STRICTFP))) {
1092 // skip
1093 }
1094 return flags & (mask | ~StandardFlags) | implicit;
1095 }
1098 /** Determine if this enum should be implicitly final.
1099 *
1100 * If the enum has no specialized enum contants, it is final.
1101 *
1102 * If the enum does have specialized enum contants, it is
1103 * <i>not</i> final.
1104 */
1105 private long implicitEnumFinalFlag(JCTree tree) {
1106 if (!tree.hasTag(CLASSDEF)) return 0;
1107 class SpecialTreeVisitor extends JCTree.Visitor {
1108 boolean specialized;
1109 SpecialTreeVisitor() {
1110 this.specialized = false;
1111 };
1113 @Override
1114 public void visitTree(JCTree tree) { /* no-op */ }
1116 @Override
1117 public void visitVarDef(JCVariableDecl tree) {
1118 if ((tree.mods.flags & ENUM) != 0) {
1119 if (tree.init instanceof JCNewClass &&
1120 ((JCNewClass) tree.init).def != null) {
1121 specialized = true;
1122 }
1123 }
1124 }
1125 }
1127 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1128 JCClassDecl cdef = (JCClassDecl) tree;
1129 for (JCTree defs: cdef.defs) {
1130 defs.accept(sts);
1131 if (sts.specialized) return 0;
1132 }
1133 return FINAL;
1134 }
1136 /* *************************************************************************
1137 * Type Validation
1138 **************************************************************************/
1140 /** Validate a type expression. That is,
1141 * check that all type arguments of a parametric type are within
1142 * their bounds. This must be done in a second phase after type attributon
1143 * since a class might have a subclass as type parameter bound. E.g:
1144 *
1145 * class B<A extends C> { ... }
1146 * class C extends B<C> { ... }
1147 *
1148 * and we can't make sure that the bound is already attributed because
1149 * of possible cycles.
1150 *
1151 * Visitor method: Validate a type expression, if it is not null, catching
1152 * and reporting any completion failures.
1153 */
1154 void validate(JCTree tree, Env<AttrContext> env) {
1155 validate(tree, env, true);
1156 }
1157 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1158 new Validator(env).validateTree(tree, checkRaw, true);
1159 }
1161 /** Visitor method: Validate a list of type expressions.
1162 */
1163 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1164 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1165 validate(l.head, env);
1166 }
1168 /** A visitor class for type validation.
1169 */
1170 class Validator extends JCTree.Visitor {
1172 boolean isOuter;
1173 Env<AttrContext> env;
1175 Validator(Env<AttrContext> env) {
1176 this.env = env;
1177 }
1179 @Override
1180 public void visitTypeArray(JCArrayTypeTree tree) {
1181 tree.elemtype.accept(this);
1182 }
1184 @Override
1185 public void visitTypeApply(JCTypeApply tree) {
1186 if (tree.type.tag == CLASS) {
1187 List<JCExpression> args = tree.arguments;
1188 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1190 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1191 if (incompatibleArg != null) {
1192 for (JCTree arg : tree.arguments) {
1193 if (arg.type == incompatibleArg) {
1194 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1195 }
1196 forms = forms.tail;
1197 }
1198 }
1200 forms = tree.type.tsym.type.getTypeArguments();
1202 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1204 // For matching pairs of actual argument types `a' and
1205 // formal type parameters with declared bound `b' ...
1206 while (args.nonEmpty() && forms.nonEmpty()) {
1207 validateTree(args.head,
1208 !(isOuter && is_java_lang_Class),
1209 false);
1210 args = args.tail;
1211 forms = forms.tail;
1212 }
1214 // Check that this type is either fully parameterized, or
1215 // not parameterized at all.
1216 if (tree.type.getEnclosingType().isRaw())
1217 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1218 if (tree.clazz.hasTag(SELECT))
1219 visitSelectInternal((JCFieldAccess)tree.clazz);
1220 }
1221 }
1223 @Override
1224 public void visitTypeParameter(JCTypeParameter tree) {
1225 validateTrees(tree.bounds, true, isOuter);
1226 checkClassBounds(tree.pos(), tree.type);
1227 }
1229 @Override
1230 public void visitWildcard(JCWildcard tree) {
1231 if (tree.inner != null)
1232 validateTree(tree.inner, true, isOuter);
1233 }
1235 @Override
1236 public void visitSelect(JCFieldAccess tree) {
1237 if (tree.type.tag == CLASS) {
1238 visitSelectInternal(tree);
1240 // Check that this type is either fully parameterized, or
1241 // not parameterized at all.
1242 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1243 log.error(tree.pos(), "improperly.formed.type.param.missing");
1244 }
1245 }
1247 public void visitSelectInternal(JCFieldAccess tree) {
1248 if (tree.type.tsym.isStatic() &&
1249 tree.selected.type.isParameterized()) {
1250 // The enclosing type is not a class, so we are
1251 // looking at a static member type. However, the
1252 // qualifying expression is parameterized.
1253 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1254 } else {
1255 // otherwise validate the rest of the expression
1256 tree.selected.accept(this);
1257 }
1258 }
1260 /** Default visitor method: do nothing.
1261 */
1262 @Override
1263 public void visitTree(JCTree tree) {
1264 }
1266 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1267 try {
1268 if (tree != null) {
1269 this.isOuter = isOuter;
1270 tree.accept(this);
1271 if (checkRaw)
1272 checkRaw(tree, env);
1273 }
1274 } catch (CompletionFailure ex) {
1275 completionError(tree.pos(), ex);
1276 }
1277 }
1279 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1280 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1281 validateTree(l.head, checkRaw, isOuter);
1282 }
1284 void checkRaw(JCTree tree, Env<AttrContext> env) {
1285 if (lint.isEnabled(LintCategory.RAW) &&
1286 tree.type.tag == CLASS &&
1287 !TreeInfo.isDiamond(tree) &&
1288 !withinAnonConstr(env) &&
1289 tree.type.isRaw()) {
1290 log.warning(LintCategory.RAW,
1291 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1292 }
1293 }
1295 boolean withinAnonConstr(Env<AttrContext> env) {
1296 return env.enclClass.name.isEmpty() &&
1297 env.enclMethod != null && env.enclMethod.name == names.init;
1298 }
1299 }
1301 /* *************************************************************************
1302 * Exception checking
1303 **************************************************************************/
1305 /* The following methods treat classes as sets that contain
1306 * the class itself and all their subclasses
1307 */
1309 /** Is given type a subtype of some of the types in given list?
1310 */
1311 boolean subset(Type t, List<Type> ts) {
1312 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1313 if (types.isSubtype(t, l.head)) return true;
1314 return false;
1315 }
1317 /** Is given type a subtype or supertype of
1318 * some of the types in given list?
1319 */
1320 boolean intersects(Type t, List<Type> ts) {
1321 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1322 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1323 return false;
1324 }
1326 /** Add type set to given type list, unless it is a subclass of some class
1327 * in the list.
1328 */
1329 List<Type> incl(Type t, List<Type> ts) {
1330 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1331 }
1333 /** Remove type set from type set list.
1334 */
1335 List<Type> excl(Type t, List<Type> ts) {
1336 if (ts.isEmpty()) {
1337 return ts;
1338 } else {
1339 List<Type> ts1 = excl(t, ts.tail);
1340 if (types.isSubtype(ts.head, t)) return ts1;
1341 else if (ts1 == ts.tail) return ts;
1342 else return ts1.prepend(ts.head);
1343 }
1344 }
1346 /** Form the union of two type set lists.
1347 */
1348 List<Type> union(List<Type> ts1, List<Type> ts2) {
1349 List<Type> ts = ts1;
1350 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1351 ts = incl(l.head, ts);
1352 return ts;
1353 }
1355 /** Form the difference of two type lists.
1356 */
1357 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1358 List<Type> ts = ts1;
1359 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1360 ts = excl(l.head, ts);
1361 return ts;
1362 }
1364 /** Form the intersection of two type lists.
1365 */
1366 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1367 List<Type> ts = List.nil();
1368 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1369 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1370 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1371 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1372 return ts;
1373 }
1375 /** Is exc an exception symbol that need not be declared?
1376 */
1377 boolean isUnchecked(ClassSymbol exc) {
1378 return
1379 exc.kind == ERR ||
1380 exc.isSubClass(syms.errorType.tsym, types) ||
1381 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1382 }
1384 /** Is exc an exception type that need not be declared?
1385 */
1386 boolean isUnchecked(Type exc) {
1387 return
1388 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1389 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1390 exc.tag == BOT;
1391 }
1393 /** Same, but handling completion failures.
1394 */
1395 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1396 try {
1397 return isUnchecked(exc);
1398 } catch (CompletionFailure ex) {
1399 completionError(pos, ex);
1400 return true;
1401 }
1402 }
1404 /** Is exc handled by given exception list?
1405 */
1406 boolean isHandled(Type exc, List<Type> handled) {
1407 return isUnchecked(exc) || subset(exc, handled);
1408 }
1410 /** Return all exceptions in thrown list that are not in handled list.
1411 * @param thrown The list of thrown exceptions.
1412 * @param handled The list of handled exceptions.
1413 */
1414 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1415 List<Type> unhandled = List.nil();
1416 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1417 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1418 return unhandled;
1419 }
1421 /* *************************************************************************
1422 * Overriding/Implementation checking
1423 **************************************************************************/
1425 /** The level of access protection given by a flag set,
1426 * where PRIVATE is highest and PUBLIC is lowest.
1427 */
1428 static int protection(long flags) {
1429 switch ((short)(flags & AccessFlags)) {
1430 case PRIVATE: return 3;
1431 case PROTECTED: return 1;
1432 default:
1433 case PUBLIC: return 0;
1434 case 0: return 2;
1435 }
1436 }
1438 /** A customized "cannot override" error message.
1439 * @param m The overriding method.
1440 * @param other The overridden method.
1441 * @return An internationalized string.
1442 */
1443 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1444 String key;
1445 if ((other.owner.flags() & INTERFACE) == 0)
1446 key = "cant.override";
1447 else if ((m.owner.flags() & INTERFACE) == 0)
1448 key = "cant.implement";
1449 else
1450 key = "clashes.with";
1451 return diags.fragment(key, m, m.location(), other, other.location());
1452 }
1454 /** A customized "override" warning message.
1455 * @param m The overriding method.
1456 * @param other The overridden method.
1457 * @return An internationalized string.
1458 */
1459 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1460 String key;
1461 if ((other.owner.flags() & INTERFACE) == 0)
1462 key = "unchecked.override";
1463 else if ((m.owner.flags() & INTERFACE) == 0)
1464 key = "unchecked.implement";
1465 else
1466 key = "unchecked.clash.with";
1467 return diags.fragment(key, m, m.location(), other, other.location());
1468 }
1470 /** A customized "override" warning message.
1471 * @param m The overriding method.
1472 * @param other The overridden method.
1473 * @return An internationalized string.
1474 */
1475 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1476 String key;
1477 if ((other.owner.flags() & INTERFACE) == 0)
1478 key = "varargs.override";
1479 else if ((m.owner.flags() & INTERFACE) == 0)
1480 key = "varargs.implement";
1481 else
1482 key = "varargs.clash.with";
1483 return diags.fragment(key, m, m.location(), other, other.location());
1484 }
1486 /** Check that this method conforms with overridden method 'other'.
1487 * where `origin' is the class where checking started.
1488 * Complications:
1489 * (1) Do not check overriding of synthetic methods
1490 * (reason: they might be final).
1491 * todo: check whether this is still necessary.
1492 * (2) Admit the case where an interface proxy throws fewer exceptions
1493 * than the method it implements. Augment the proxy methods with the
1494 * undeclared exceptions in this case.
1495 * (3) When generics are enabled, admit the case where an interface proxy
1496 * has a result type
1497 * extended by the result type of the method it implements.
1498 * Change the proxies result type to the smaller type in this case.
1499 *
1500 * @param tree The tree from which positions
1501 * are extracted for errors.
1502 * @param m The overriding method.
1503 * @param other The overridden method.
1504 * @param origin The class of which the overriding method
1505 * is a member.
1506 */
1507 void checkOverride(JCTree tree,
1508 MethodSymbol m,
1509 MethodSymbol other,
1510 ClassSymbol origin) {
1511 // Don't check overriding of synthetic methods or by bridge methods.
1512 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1513 return;
1514 }
1516 // Error if static method overrides instance method (JLS 8.4.6.2).
1517 if ((m.flags() & STATIC) != 0 &&
1518 (other.flags() & STATIC) == 0) {
1519 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1520 cannotOverride(m, other));
1521 return;
1522 }
1524 // Error if instance method overrides static or final
1525 // method (JLS 8.4.6.1).
1526 if ((other.flags() & FINAL) != 0 ||
1527 (m.flags() & STATIC) == 0 &&
1528 (other.flags() & STATIC) != 0) {
1529 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1530 cannotOverride(m, other),
1531 asFlagSet(other.flags() & (FINAL | STATIC)));
1532 return;
1533 }
1535 if ((m.owner.flags() & ANNOTATION) != 0) {
1536 // handled in validateAnnotationMethod
1537 return;
1538 }
1540 // Error if overriding method has weaker access (JLS 8.4.6.3).
1541 if ((origin.flags() & INTERFACE) == 0 &&
1542 protection(m.flags()) > protection(other.flags())) {
1543 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1544 cannotOverride(m, other),
1545 other.flags() == 0 ?
1546 Flag.PACKAGE :
1547 asFlagSet(other.flags() & AccessFlags));
1548 return;
1549 }
1551 Type mt = types.memberType(origin.type, m);
1552 Type ot = types.memberType(origin.type, other);
1553 // Error if overriding result type is different
1554 // (or, in the case of generics mode, not a subtype) of
1555 // overridden result type. We have to rename any type parameters
1556 // before comparing types.
1557 List<Type> mtvars = mt.getTypeArguments();
1558 List<Type> otvars = ot.getTypeArguments();
1559 Type mtres = mt.getReturnType();
1560 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1562 overrideWarner.clear();
1563 boolean resultTypesOK =
1564 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1565 if (!resultTypesOK) {
1566 if (!allowCovariantReturns &&
1567 m.owner != origin &&
1568 m.owner.isSubClass(other.owner, types)) {
1569 // allow limited interoperability with covariant returns
1570 } else {
1571 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1572 "override.incompatible.ret",
1573 cannotOverride(m, other),
1574 mtres, otres);
1575 return;
1576 }
1577 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1578 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1579 "override.unchecked.ret",
1580 uncheckedOverrides(m, other),
1581 mtres, otres);
1582 }
1584 // Error if overriding method throws an exception not reported
1585 // by overridden method.
1586 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1587 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1588 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1589 if (unhandledErased.nonEmpty()) {
1590 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1591 "override.meth.doesnt.throw",
1592 cannotOverride(m, other),
1593 unhandledUnerased.head);
1594 return;
1595 }
1596 else if (unhandledUnerased.nonEmpty()) {
1597 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1598 "override.unchecked.thrown",
1599 cannotOverride(m, other),
1600 unhandledUnerased.head);
1601 return;
1602 }
1604 // Optional warning if varargs don't agree
1605 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1606 && lint.isEnabled(LintCategory.OVERRIDES)) {
1607 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1608 ((m.flags() & Flags.VARARGS) != 0)
1609 ? "override.varargs.missing"
1610 : "override.varargs.extra",
1611 varargsOverrides(m, other));
1612 }
1614 // Warn if instance method overrides bridge method (compiler spec ??)
1615 if ((other.flags() & BRIDGE) != 0) {
1616 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1617 uncheckedOverrides(m, other));
1618 }
1620 // Warn if a deprecated method overridden by a non-deprecated one.
1621 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1622 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1623 }
1624 }
1625 // where
1626 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1627 // If the method, m, is defined in an interface, then ignore the issue if the method
1628 // is only inherited via a supertype and also implemented in the supertype,
1629 // because in that case, we will rediscover the issue when examining the method
1630 // in the supertype.
1631 // If the method, m, is not defined in an interface, then the only time we need to
1632 // address the issue is when the method is the supertype implemementation: any other
1633 // case, we will have dealt with when examining the supertype classes
1634 ClassSymbol mc = m.enclClass();
1635 Type st = types.supertype(origin.type);
1636 if (st.tag != CLASS)
1637 return true;
1638 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1640 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1641 List<Type> intfs = types.interfaces(origin.type);
1642 return (intfs.contains(mc.type) ? false : (stimpl != null));
1643 }
1644 else
1645 return (stimpl != m);
1646 }
1649 // used to check if there were any unchecked conversions
1650 Warner overrideWarner = new Warner();
1652 /** Check that a class does not inherit two concrete methods
1653 * with the same signature.
1654 * @param pos Position to be used for error reporting.
1655 * @param site The class type to be checked.
1656 */
1657 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1658 Type sup = types.supertype(site);
1659 if (sup.tag != CLASS) return;
1661 for (Type t1 = sup;
1662 t1.tsym.type.isParameterized();
1663 t1 = types.supertype(t1)) {
1664 for (Scope.Entry e1 = t1.tsym.members().elems;
1665 e1 != null;
1666 e1 = e1.sibling) {
1667 Symbol s1 = e1.sym;
1668 if (s1.kind != MTH ||
1669 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1670 !s1.isInheritedIn(site.tsym, types) ||
1671 ((MethodSymbol)s1).implementation(site.tsym,
1672 types,
1673 true) != s1)
1674 continue;
1675 Type st1 = types.memberType(t1, s1);
1676 int s1ArgsLength = st1.getParameterTypes().length();
1677 if (st1 == s1.type) continue;
1679 for (Type t2 = sup;
1680 t2.tag == CLASS;
1681 t2 = types.supertype(t2)) {
1682 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1683 e2.scope != null;
1684 e2 = e2.next()) {
1685 Symbol s2 = e2.sym;
1686 if (s2 == s1 ||
1687 s2.kind != MTH ||
1688 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1689 s2.type.getParameterTypes().length() != s1ArgsLength ||
1690 !s2.isInheritedIn(site.tsym, types) ||
1691 ((MethodSymbol)s2).implementation(site.tsym,
1692 types,
1693 true) != s2)
1694 continue;
1695 Type st2 = types.memberType(t2, s2);
1696 if (types.overrideEquivalent(st1, st2))
1697 log.error(pos, "concrete.inheritance.conflict",
1698 s1, t1, s2, t2, sup);
1699 }
1700 }
1701 }
1702 }
1703 }
1705 /** Check that classes (or interfaces) do not each define an abstract
1706 * method with same name and arguments but incompatible return types.
1707 * @param pos Position to be used for error reporting.
1708 * @param t1 The first argument type.
1709 * @param t2 The second argument type.
1710 */
1711 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1712 Type t1,
1713 Type t2) {
1714 return checkCompatibleAbstracts(pos, t1, t2,
1715 types.makeCompoundType(t1, t2));
1716 }
1718 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1719 Type t1,
1720 Type t2,
1721 Type site) {
1722 return firstIncompatibility(pos, t1, t2, site) == null;
1723 }
1725 /** Return the first method which is defined with same args
1726 * but different return types in two given interfaces, or null if none
1727 * exists.
1728 * @param t1 The first type.
1729 * @param t2 The second type.
1730 * @param site The most derived type.
1731 * @returns symbol from t2 that conflicts with one in t1.
1732 */
1733 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1734 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1735 closure(t1, interfaces1);
1736 Map<TypeSymbol,Type> interfaces2;
1737 if (t1 == t2)
1738 interfaces2 = interfaces1;
1739 else
1740 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1742 for (Type t3 : interfaces1.values()) {
1743 for (Type t4 : interfaces2.values()) {
1744 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1745 if (s != null) return s;
1746 }
1747 }
1748 return null;
1749 }
1751 /** Compute all the supertypes of t, indexed by type symbol. */
1752 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1753 if (t.tag != CLASS) return;
1754 if (typeMap.put(t.tsym, t) == null) {
1755 closure(types.supertype(t), typeMap);
1756 for (Type i : types.interfaces(t))
1757 closure(i, typeMap);
1758 }
1759 }
1761 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1762 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1763 if (t.tag != CLASS) return;
1764 if (typesSkip.get(t.tsym) != null) return;
1765 if (typeMap.put(t.tsym, t) == null) {
1766 closure(types.supertype(t), typesSkip, typeMap);
1767 for (Type i : types.interfaces(t))
1768 closure(i, typesSkip, typeMap);
1769 }
1770 }
1772 /** Return the first method in t2 that conflicts with a method from t1. */
1773 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1774 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1775 Symbol s1 = e1.sym;
1776 Type st1 = null;
1777 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1778 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1779 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1780 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1781 Symbol s2 = e2.sym;
1782 if (s1 == s2) continue;
1783 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1784 if (st1 == null) st1 = types.memberType(t1, s1);
1785 Type st2 = types.memberType(t2, s2);
1786 if (types.overrideEquivalent(st1, st2)) {
1787 List<Type> tvars1 = st1.getTypeArguments();
1788 List<Type> tvars2 = st2.getTypeArguments();
1789 Type rt1 = st1.getReturnType();
1790 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1791 boolean compat =
1792 types.isSameType(rt1, rt2) ||
1793 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1794 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1795 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1796 checkCommonOverriderIn(s1,s2,site);
1797 if (!compat) {
1798 log.error(pos, "types.incompatible.diff.ret",
1799 t1, t2, s2.name +
1800 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1801 return s2;
1802 }
1803 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1804 !checkCommonOverriderIn(s1, s2, site)) {
1805 log.error(pos,
1806 "name.clash.same.erasure.no.override",
1807 s1, s1.location(),
1808 s2, s2.location());
1809 return s2;
1810 }
1811 }
1812 }
1813 return null;
1814 }
1815 //WHERE
1816 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1817 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1818 Type st1 = types.memberType(site, s1);
1819 Type st2 = types.memberType(site, s2);
1820 closure(site, supertypes);
1821 for (Type t : supertypes.values()) {
1822 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1823 Symbol s3 = e.sym;
1824 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1825 Type st3 = types.memberType(site,s3);
1826 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1827 if (s3.owner == site.tsym) {
1828 return true;
1829 }
1830 List<Type> tvars1 = st1.getTypeArguments();
1831 List<Type> tvars2 = st2.getTypeArguments();
1832 List<Type> tvars3 = st3.getTypeArguments();
1833 Type rt1 = st1.getReturnType();
1834 Type rt2 = st2.getReturnType();
1835 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1836 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1837 boolean compat =
1838 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1839 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1840 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1841 if (compat)
1842 return true;
1843 }
1844 }
1845 }
1846 return false;
1847 }
1849 /** Check that a given method conforms with any method it overrides.
1850 * @param tree The tree from which positions are extracted
1851 * for errors.
1852 * @param m The overriding method.
1853 */
1854 void checkOverride(JCTree tree, MethodSymbol m) {
1855 ClassSymbol origin = (ClassSymbol)m.owner;
1856 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1857 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1858 log.error(tree.pos(), "enum.no.finalize");
1859 return;
1860 }
1861 for (Type t = origin.type; t.tag == CLASS;
1862 t = types.supertype(t)) {
1863 if (t != origin.type) {
1864 checkOverride(tree, t, origin, m);
1865 }
1866 for (Type t2 : types.interfaces(t)) {
1867 checkOverride(tree, t2, origin, m);
1868 }
1869 }
1870 }
1872 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1873 TypeSymbol c = site.tsym;
1874 Scope.Entry e = c.members().lookup(m.name);
1875 while (e.scope != null) {
1876 if (m.overrides(e.sym, origin, types, false)) {
1877 if ((e.sym.flags() & ABSTRACT) == 0) {
1878 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1879 }
1880 }
1881 e = e.next();
1882 }
1883 }
1885 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1886 ClashFilter cf = new ClashFilter(origin.type);
1887 return (cf.accepts(s1) &&
1888 cf.accepts(s2) &&
1889 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1890 }
1893 /** Check that all abstract members of given class have definitions.
1894 * @param pos Position to be used for error reporting.
1895 * @param c The class.
1896 */
1897 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1898 try {
1899 MethodSymbol undef = firstUndef(c, c);
1900 if (undef != null) {
1901 if ((c.flags() & ENUM) != 0 &&
1902 types.supertype(c.type).tsym == syms.enumSym &&
1903 (c.flags() & FINAL) == 0) {
1904 // add the ABSTRACT flag to an enum
1905 c.flags_field |= ABSTRACT;
1906 } else {
1907 MethodSymbol undef1 =
1908 new MethodSymbol(undef.flags(), undef.name,
1909 types.memberType(c.type, undef), undef.owner);
1910 log.error(pos, "does.not.override.abstract",
1911 c, undef1, undef1.location());
1912 }
1913 }
1914 } catch (CompletionFailure ex) {
1915 completionError(pos, ex);
1916 }
1917 }
1918 //where
1919 /** Return first abstract member of class `c' that is not defined
1920 * in `impl', null if there is none.
1921 */
1922 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1923 MethodSymbol undef = null;
1924 // Do not bother to search in classes that are not abstract,
1925 // since they cannot have abstract members.
1926 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1927 Scope s = c.members();
1928 for (Scope.Entry e = s.elems;
1929 undef == null && e != null;
1930 e = e.sibling) {
1931 if (e.sym.kind == MTH &&
1932 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1933 MethodSymbol absmeth = (MethodSymbol)e.sym;
1934 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1935 if (implmeth == null || implmeth == absmeth)
1936 undef = absmeth;
1937 }
1938 }
1939 if (undef == null) {
1940 Type st = types.supertype(c.type);
1941 if (st.tag == CLASS)
1942 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1943 }
1944 for (List<Type> l = types.interfaces(c.type);
1945 undef == null && l.nonEmpty();
1946 l = l.tail) {
1947 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1948 }
1949 }
1950 return undef;
1951 }
1953 void checkNonCyclicDecl(JCClassDecl tree) {
1954 CycleChecker cc = new CycleChecker();
1955 cc.scan(tree);
1956 if (!cc.errorFound && !cc.partialCheck) {
1957 tree.sym.flags_field |= ACYCLIC;
1958 }
1959 }
1961 class CycleChecker extends TreeScanner {
1963 List<Symbol> seenClasses = List.nil();
1964 boolean errorFound = false;
1965 boolean partialCheck = false;
1967 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1968 if (sym != null && sym.kind == TYP) {
1969 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1970 if (classEnv != null) {
1971 DiagnosticSource prevSource = log.currentSource();
1972 try {
1973 log.useSource(classEnv.toplevel.sourcefile);
1974 scan(classEnv.tree);
1975 }
1976 finally {
1977 log.useSource(prevSource.getFile());
1978 }
1979 } else if (sym.kind == TYP) {
1980 checkClass(pos, sym, List.<JCTree>nil());
1981 }
1982 } else {
1983 //not completed yet
1984 partialCheck = true;
1985 }
1986 }
1988 @Override
1989 public void visitSelect(JCFieldAccess tree) {
1990 super.visitSelect(tree);
1991 checkSymbol(tree.pos(), tree.sym);
1992 }
1994 @Override
1995 public void visitIdent(JCIdent tree) {
1996 checkSymbol(tree.pos(), tree.sym);
1997 }
1999 @Override
2000 public void visitTypeApply(JCTypeApply tree) {
2001 scan(tree.clazz);
2002 }
2004 @Override
2005 public void visitTypeArray(JCArrayTypeTree tree) {
2006 scan(tree.elemtype);
2007 }
2009 @Override
2010 public void visitClassDef(JCClassDecl tree) {
2011 List<JCTree> supertypes = List.nil();
2012 if (tree.getExtendsClause() != null) {
2013 supertypes = supertypes.prepend(tree.getExtendsClause());
2014 }
2015 if (tree.getImplementsClause() != null) {
2016 for (JCTree intf : tree.getImplementsClause()) {
2017 supertypes = supertypes.prepend(intf);
2018 }
2019 }
2020 checkClass(tree.pos(), tree.sym, supertypes);
2021 }
2023 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2024 if ((c.flags_field & ACYCLIC) != 0)
2025 return;
2026 if (seenClasses.contains(c)) {
2027 errorFound = true;
2028 noteCyclic(pos, (ClassSymbol)c);
2029 } else if (!c.type.isErroneous()) {
2030 try {
2031 seenClasses = seenClasses.prepend(c);
2032 if (c.type.tag == CLASS) {
2033 if (supertypes.nonEmpty()) {
2034 scan(supertypes);
2035 }
2036 else {
2037 ClassType ct = (ClassType)c.type;
2038 if (ct.supertype_field == null ||
2039 ct.interfaces_field == null) {
2040 //not completed yet
2041 partialCheck = true;
2042 return;
2043 }
2044 checkSymbol(pos, ct.supertype_field.tsym);
2045 for (Type intf : ct.interfaces_field) {
2046 checkSymbol(pos, intf.tsym);
2047 }
2048 }
2049 if (c.owner.kind == TYP) {
2050 checkSymbol(pos, c.owner);
2051 }
2052 }
2053 } finally {
2054 seenClasses = seenClasses.tail;
2055 }
2056 }
2057 }
2058 }
2060 /** Check for cyclic references. Issue an error if the
2061 * symbol of the type referred to has a LOCKED flag set.
2062 *
2063 * @param pos Position to be used for error reporting.
2064 * @param t The type referred to.
2065 */
2066 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2067 checkNonCyclicInternal(pos, t);
2068 }
2071 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2072 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2073 }
2075 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2076 final TypeVar tv;
2077 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
2078 return;
2079 if (seen.contains(t)) {
2080 tv = (TypeVar)t;
2081 tv.bound = types.createErrorType(t);
2082 log.error(pos, "cyclic.inheritance", t);
2083 } else if (t.tag == TYPEVAR) {
2084 tv = (TypeVar)t;
2085 seen = seen.prepend(tv);
2086 for (Type b : types.getBounds(tv))
2087 checkNonCyclic1(pos, b, seen);
2088 }
2089 }
2091 /** Check for cyclic references. Issue an error if the
2092 * symbol of the type referred to has a LOCKED flag set.
2093 *
2094 * @param pos Position to be used for error reporting.
2095 * @param t The type referred to.
2096 * @returns True if the check completed on all attributed classes
2097 */
2098 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2099 boolean complete = true; // was the check complete?
2100 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2101 Symbol c = t.tsym;
2102 if ((c.flags_field & ACYCLIC) != 0) return true;
2104 if ((c.flags_field & LOCKED) != 0) {
2105 noteCyclic(pos, (ClassSymbol)c);
2106 } else if (!c.type.isErroneous()) {
2107 try {
2108 c.flags_field |= LOCKED;
2109 if (c.type.tag == CLASS) {
2110 ClassType clazz = (ClassType)c.type;
2111 if (clazz.interfaces_field != null)
2112 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2113 complete &= checkNonCyclicInternal(pos, l.head);
2114 if (clazz.supertype_field != null) {
2115 Type st = clazz.supertype_field;
2116 if (st != null && st.tag == CLASS)
2117 complete &= checkNonCyclicInternal(pos, st);
2118 }
2119 if (c.owner.kind == TYP)
2120 complete &= checkNonCyclicInternal(pos, c.owner.type);
2121 }
2122 } finally {
2123 c.flags_field &= ~LOCKED;
2124 }
2125 }
2126 if (complete)
2127 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2128 if (complete) c.flags_field |= ACYCLIC;
2129 return complete;
2130 }
2132 /** Note that we found an inheritance cycle. */
2133 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2134 log.error(pos, "cyclic.inheritance", c);
2135 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2136 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2137 Type st = types.supertype(c.type);
2138 if (st.tag == CLASS)
2139 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2140 c.type = types.createErrorType(c, c.type);
2141 c.flags_field |= ACYCLIC;
2142 }
2144 /** Check that all methods which implement some
2145 * method conform to the method they implement.
2146 * @param tree The class definition whose members are checked.
2147 */
2148 void checkImplementations(JCClassDecl tree) {
2149 checkImplementations(tree, tree.sym);
2150 }
2151 //where
2152 /** Check that all methods which implement some
2153 * method in `ic' conform to the method they implement.
2154 */
2155 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2156 ClassSymbol origin = tree.sym;
2157 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2158 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2159 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2160 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2161 if (e.sym.kind == MTH &&
2162 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2163 MethodSymbol absmeth = (MethodSymbol)e.sym;
2164 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2165 if (implmeth != null && implmeth != absmeth &&
2166 (implmeth.owner.flags() & INTERFACE) ==
2167 (origin.flags() & INTERFACE)) {
2168 // don't check if implmeth is in a class, yet
2169 // origin is an interface. This case arises only
2170 // if implmeth is declared in Object. The reason is
2171 // that interfaces really don't inherit from
2172 // Object it's just that the compiler represents
2173 // things that way.
2174 checkOverride(tree, implmeth, absmeth, origin);
2175 }
2176 }
2177 }
2178 }
2179 }
2180 }
2182 /** Check that all abstract methods implemented by a class are
2183 * mutually compatible.
2184 * @param pos Position to be used for error reporting.
2185 * @param c The class whose interfaces are checked.
2186 */
2187 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2188 List<Type> supertypes = types.interfaces(c);
2189 Type supertype = types.supertype(c);
2190 if (supertype.tag == CLASS &&
2191 (supertype.tsym.flags() & ABSTRACT) != 0)
2192 supertypes = supertypes.prepend(supertype);
2193 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2194 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2195 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2196 return;
2197 for (List<Type> m = supertypes; m != l; m = m.tail)
2198 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2199 return;
2200 }
2201 checkCompatibleConcretes(pos, c);
2202 }
2204 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2205 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2206 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2207 // VM allows methods and variables with differing types
2208 if (sym.kind == e.sym.kind &&
2209 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2210 sym != e.sym &&
2211 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2212 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2213 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2214 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2215 return;
2216 }
2217 }
2218 }
2219 }
2221 /** Check that all non-override equivalent methods accessible from 'site'
2222 * are mutually compatible (JLS 8.4.8/9.4.1).
2223 *
2224 * @param pos Position to be used for error reporting.
2225 * @param site The class whose methods are checked.
2226 * @param sym The method symbol to be checked.
2227 */
2228 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2229 ClashFilter cf = new ClashFilter(site);
2230 //for each method m1 that is overridden (directly or indirectly)
2231 //by method 'sym' in 'site'...
2232 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2233 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2234 //...check each method m2 that is a member of 'site'
2235 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2236 if (m2 == m1) continue;
2237 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2238 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2239 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
2240 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2241 sym.flags_field |= CLASH;
2242 String key = m1 == sym ?
2243 "name.clash.same.erasure.no.override" :
2244 "name.clash.same.erasure.no.override.1";
2245 log.error(pos,
2246 key,
2247 sym, sym.location(),
2248 m2, m2.location(),
2249 m1, m1.location());
2250 return;
2251 }
2252 }
2253 }
2254 }
2258 /** Check that all static methods accessible from 'site' are
2259 * mutually compatible (JLS 8.4.8).
2260 *
2261 * @param pos Position to be used for error reporting.
2262 * @param site The class whose methods are checked.
2263 * @param sym The method symbol to be checked.
2264 */
2265 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2266 ClashFilter cf = new ClashFilter(site);
2267 //for each method m1 that is a member of 'site'...
2268 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2269 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2270 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2271 if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
2272 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2273 log.error(pos,
2274 "name.clash.same.erasure.no.hide",
2275 sym, sym.location(),
2276 s, s.location());
2277 return;
2278 }
2279 }
2280 }
2282 //where
2283 private class ClashFilter implements Filter<Symbol> {
2285 Type site;
2287 ClashFilter(Type site) {
2288 this.site = site;
2289 }
2291 boolean shouldSkip(Symbol s) {
2292 return (s.flags() & CLASH) != 0 &&
2293 s.owner == site.tsym;
2294 }
2296 public boolean accepts(Symbol s) {
2297 return s.kind == MTH &&
2298 (s.flags() & SYNTHETIC) == 0 &&
2299 !shouldSkip(s) &&
2300 s.isInheritedIn(site.tsym, types) &&
2301 !s.isConstructor();
2302 }
2303 }
2305 /** Report a conflict between a user symbol and a synthetic symbol.
2306 */
2307 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2308 if (!sym.type.isErroneous()) {
2309 if (warnOnSyntheticConflicts) {
2310 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2311 }
2312 else {
2313 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2314 }
2315 }
2316 }
2318 /** Check that class c does not implement directly or indirectly
2319 * the same parameterized interface with two different argument lists.
2320 * @param pos Position to be used for error reporting.
2321 * @param type The type whose interfaces are checked.
2322 */
2323 void checkClassBounds(DiagnosticPosition pos, Type type) {
2324 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2325 }
2326 //where
2327 /** Enter all interfaces of type `type' into the hash table `seensofar'
2328 * with their class symbol as key and their type as value. Make
2329 * sure no class is entered with two different types.
2330 */
2331 void checkClassBounds(DiagnosticPosition pos,
2332 Map<TypeSymbol,Type> seensofar,
2333 Type type) {
2334 if (type.isErroneous()) return;
2335 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2336 Type it = l.head;
2337 Type oldit = seensofar.put(it.tsym, it);
2338 if (oldit != null) {
2339 List<Type> oldparams = oldit.allparams();
2340 List<Type> newparams = it.allparams();
2341 if (!types.containsTypeEquivalent(oldparams, newparams))
2342 log.error(pos, "cant.inherit.diff.arg",
2343 it.tsym, Type.toString(oldparams),
2344 Type.toString(newparams));
2345 }
2346 checkClassBounds(pos, seensofar, it);
2347 }
2348 Type st = types.supertype(type);
2349 if (st != null) checkClassBounds(pos, seensofar, st);
2350 }
2352 /** Enter interface into into set.
2353 * If it existed already, issue a "repeated interface" error.
2354 */
2355 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2356 if (its.contains(it))
2357 log.error(pos, "repeated.interface");
2358 else {
2359 its.add(it);
2360 }
2361 }
2363 /* *************************************************************************
2364 * Check annotations
2365 **************************************************************************/
2367 /**
2368 * Recursively validate annotations values
2369 */
2370 void validateAnnotationTree(JCTree tree) {
2371 class AnnotationValidator extends TreeScanner {
2372 @Override
2373 public void visitAnnotation(JCAnnotation tree) {
2374 if (!tree.type.isErroneous()) {
2375 super.visitAnnotation(tree);
2376 validateAnnotation(tree);
2377 }
2378 }
2379 }
2380 tree.accept(new AnnotationValidator());
2381 }
2383 /** Annotation types are restricted to primitives, String, an
2384 * enum, an annotation, Class, Class<?>, Class<? extends
2385 * Anything>, arrays of the preceding.
2386 */
2387 void validateAnnotationType(JCTree restype) {
2388 // restype may be null if an error occurred, so don't bother validating it
2389 if (restype != null) {
2390 validateAnnotationType(restype.pos(), restype.type);
2391 }
2392 }
2394 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2395 if (type.isPrimitive()) return;
2396 if (types.isSameType(type, syms.stringType)) return;
2397 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2398 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2399 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2400 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2401 validateAnnotationType(pos, types.elemtype(type));
2402 return;
2403 }
2404 log.error(pos, "invalid.annotation.member.type");
2405 }
2407 /**
2408 * "It is also a compile-time error if any method declared in an
2409 * annotation type has a signature that is override-equivalent to
2410 * that of any public or protected method declared in class Object
2411 * or in the interface annotation.Annotation."
2412 *
2413 * @jls 9.6 Annotation Types
2414 */
2415 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2416 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2417 Scope s = sup.tsym.members();
2418 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2419 if (e.sym.kind == MTH &&
2420 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2421 types.overrideEquivalent(m.type, e.sym.type))
2422 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2423 }
2424 }
2425 }
2427 /** Check the annotations of a symbol.
2428 */
2429 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2430 if (skipAnnotations) return;
2431 for (JCAnnotation a : annotations)
2432 validateAnnotation(a, s);
2433 }
2435 /** Check an annotation of a symbol.
2436 */
2437 public void validateAnnotation(JCAnnotation a, Symbol s) {
2438 validateAnnotationTree(a);
2440 if (!annotationApplicable(a, s))
2441 log.error(a.pos(), "annotation.type.not.applicable");
2443 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2444 if (!isOverrider(s))
2445 log.error(a.pos(), "method.does.not.override.superclass");
2446 }
2447 }
2449 /** Is s a method symbol that overrides a method in a superclass? */
2450 boolean isOverrider(Symbol s) {
2451 if (s.kind != MTH || s.isStatic())
2452 return false;
2453 MethodSymbol m = (MethodSymbol)s;
2454 TypeSymbol owner = (TypeSymbol)m.owner;
2455 for (Type sup : types.closure(owner.type)) {
2456 if (sup == owner.type)
2457 continue; // skip "this"
2458 Scope scope = sup.tsym.members();
2459 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2460 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2461 return true;
2462 }
2463 }
2464 return false;
2465 }
2467 /** Is the annotation applicable to the symbol? */
2468 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2469 Attribute.Compound atTarget =
2470 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2471 if (atTarget == null) return true;
2472 Attribute atValue = atTarget.member(names.value);
2473 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2474 Attribute.Array arr = (Attribute.Array) atValue;
2475 for (Attribute app : arr.values) {
2476 if (!(app instanceof Attribute.Enum)) return true; // recovery
2477 Attribute.Enum e = (Attribute.Enum) app;
2478 if (e.value.name == names.TYPE)
2479 { if (s.kind == TYP) return true; }
2480 else if (e.value.name == names.FIELD)
2481 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2482 else if (e.value.name == names.METHOD)
2483 { if (s.kind == MTH && !s.isConstructor()) return true; }
2484 else if (e.value.name == names.PARAMETER)
2485 { if (s.kind == VAR &&
2486 s.owner.kind == MTH &&
2487 (s.flags() & PARAMETER) != 0)
2488 return true;
2489 }
2490 else if (e.value.name == names.CONSTRUCTOR)
2491 { if (s.kind == MTH && s.isConstructor()) return true; }
2492 else if (e.value.name == names.LOCAL_VARIABLE)
2493 { if (s.kind == VAR && s.owner.kind == MTH &&
2494 (s.flags() & PARAMETER) == 0)
2495 return true;
2496 }
2497 else if (e.value.name == names.ANNOTATION_TYPE)
2498 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2499 return true;
2500 }
2501 else if (e.value.name == names.PACKAGE)
2502 { if (s.kind == PCK) return true; }
2503 else if (e.value.name == names.TYPE_USE)
2504 { if (s.kind == TYP ||
2505 s.kind == VAR ||
2506 (s.kind == MTH && !s.isConstructor() &&
2507 s.type.getReturnType().tag != VOID))
2508 return true;
2509 }
2510 else
2511 return true; // recovery
2512 }
2513 return false;
2514 }
2516 /** Check an annotation value.
2517 */
2518 public void validateAnnotation(JCAnnotation a) {
2519 // collect an inventory of the members (sorted alphabetically)
2520 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2521 public int compare(Symbol t, Symbol t1) {
2522 return t.name.compareTo(t1.name);
2523 }
2524 });
2525 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2526 e != null;
2527 e = e.sibling)
2528 if (e.sym.kind == MTH)
2529 members.add((MethodSymbol) e.sym);
2531 // count them off as they're annotated
2532 for (JCTree arg : a.args) {
2533 if (!arg.hasTag(ASSIGN)) continue; // recovery
2534 JCAssign assign = (JCAssign) arg;
2535 Symbol m = TreeInfo.symbol(assign.lhs);
2536 if (m == null || m.type.isErroneous()) continue;
2537 if (!members.remove(m))
2538 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2539 m.name, a.type);
2540 }
2542 // all the remaining ones better have default values
2543 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2544 for (MethodSymbol m : members) {
2545 if (m.defaultValue == null && !m.type.isErroneous()) {
2546 missingDefaults.append(m.name);
2547 }
2548 }
2549 if (missingDefaults.nonEmpty()) {
2550 String key = (missingDefaults.size() > 1)
2551 ? "annotation.missing.default.value.1"
2552 : "annotation.missing.default.value";
2553 log.error(a.pos(), key, a.type, missingDefaults);
2554 }
2556 // special case: java.lang.annotation.Target must not have
2557 // repeated values in its value member
2558 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2559 a.args.tail == null)
2560 return;
2562 if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
2563 JCAssign assign = (JCAssign) a.args.head;
2564 Symbol m = TreeInfo.symbol(assign.lhs);
2565 if (m.name != names.value) return;
2566 JCTree rhs = assign.rhs;
2567 if (!rhs.hasTag(NEWARRAY)) return;
2568 JCNewArray na = (JCNewArray) rhs;
2569 Set<Symbol> targets = new HashSet<Symbol>();
2570 for (JCTree elem : na.elems) {
2571 if (!targets.add(TreeInfo.symbol(elem))) {
2572 log.error(elem.pos(), "repeated.annotation.target");
2573 }
2574 }
2575 }
2577 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2578 if (allowAnnotations &&
2579 lint.isEnabled(LintCategory.DEP_ANN) &&
2580 (s.flags() & DEPRECATED) != 0 &&
2581 !syms.deprecatedType.isErroneous() &&
2582 s.attribute(syms.deprecatedType.tsym) == null) {
2583 log.warning(LintCategory.DEP_ANN,
2584 pos, "missing.deprecated.annotation");
2585 }
2586 }
2588 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2589 if ((s.flags() & DEPRECATED) != 0 &&
2590 (other.flags() & DEPRECATED) == 0 &&
2591 s.outermostClass() != other.outermostClass()) {
2592 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2593 @Override
2594 public void report() {
2595 warnDeprecated(pos, s);
2596 }
2597 });
2598 }
2599 }
2601 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2602 if ((s.flags() & PROPRIETARY) != 0) {
2603 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2604 public void report() {
2605 if (enableSunApiLintControl)
2606 warnSunApi(pos, "sun.proprietary", s);
2607 else
2608 log.mandatoryWarning(pos, "sun.proprietary", s);
2609 }
2610 });
2611 }
2612 }
2614 /* *************************************************************************
2615 * Check for recursive annotation elements.
2616 **************************************************************************/
2618 /** Check for cycles in the graph of annotation elements.
2619 */
2620 void checkNonCyclicElements(JCClassDecl tree) {
2621 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2622 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2623 try {
2624 tree.sym.flags_field |= LOCKED;
2625 for (JCTree def : tree.defs) {
2626 if (!def.hasTag(METHODDEF)) continue;
2627 JCMethodDecl meth = (JCMethodDecl)def;
2628 checkAnnotationResType(meth.pos(), meth.restype.type);
2629 }
2630 } finally {
2631 tree.sym.flags_field &= ~LOCKED;
2632 tree.sym.flags_field |= ACYCLIC_ANN;
2633 }
2634 }
2636 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2637 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2638 return;
2639 if ((tsym.flags_field & LOCKED) != 0) {
2640 log.error(pos, "cyclic.annotation.element");
2641 return;
2642 }
2643 try {
2644 tsym.flags_field |= LOCKED;
2645 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2646 Symbol s = e.sym;
2647 if (s.kind != Kinds.MTH)
2648 continue;
2649 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2650 }
2651 } finally {
2652 tsym.flags_field &= ~LOCKED;
2653 tsym.flags_field |= ACYCLIC_ANN;
2654 }
2655 }
2657 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2658 switch (type.tag) {
2659 case TypeTags.CLASS:
2660 if ((type.tsym.flags() & ANNOTATION) != 0)
2661 checkNonCyclicElementsInternal(pos, type.tsym);
2662 break;
2663 case TypeTags.ARRAY:
2664 checkAnnotationResType(pos, types.elemtype(type));
2665 break;
2666 default:
2667 break; // int etc
2668 }
2669 }
2671 /* *************************************************************************
2672 * Check for cycles in the constructor call graph.
2673 **************************************************************************/
2675 /** Check for cycles in the graph of constructors calling other
2676 * constructors.
2677 */
2678 void checkCyclicConstructors(JCClassDecl tree) {
2679 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2681 // enter each constructor this-call into the map
2682 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2683 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2684 if (app == null) continue;
2685 JCMethodDecl meth = (JCMethodDecl) l.head;
2686 if (TreeInfo.name(app.meth) == names._this) {
2687 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2688 } else {
2689 meth.sym.flags_field |= ACYCLIC;
2690 }
2691 }
2693 // Check for cycles in the map
2694 Symbol[] ctors = new Symbol[0];
2695 ctors = callMap.keySet().toArray(ctors);
2696 for (Symbol caller : ctors) {
2697 checkCyclicConstructor(tree, caller, callMap);
2698 }
2699 }
2701 /** Look in the map to see if the given constructor is part of a
2702 * call cycle.
2703 */
2704 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2705 Map<Symbol,Symbol> callMap) {
2706 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2707 if ((ctor.flags_field & LOCKED) != 0) {
2708 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2709 "recursive.ctor.invocation");
2710 } else {
2711 ctor.flags_field |= LOCKED;
2712 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2713 ctor.flags_field &= ~LOCKED;
2714 }
2715 ctor.flags_field |= ACYCLIC;
2716 }
2717 }
2719 /* *************************************************************************
2720 * Miscellaneous
2721 **************************************************************************/
2723 /**
2724 * Return the opcode of the operator but emit an error if it is an
2725 * error.
2726 * @param pos position for error reporting.
2727 * @param operator an operator
2728 * @param tag a tree tag
2729 * @param left type of left hand side
2730 * @param right type of right hand side
2731 */
2732 int checkOperator(DiagnosticPosition pos,
2733 OperatorSymbol operator,
2734 JCTree.Tag tag,
2735 Type left,
2736 Type right) {
2737 if (operator.opcode == ByteCodes.error) {
2738 log.error(pos,
2739 "operator.cant.be.applied.1",
2740 treeinfo.operatorName(tag),
2741 left, right);
2742 }
2743 return operator.opcode;
2744 }
2747 /**
2748 * Check for division by integer constant zero
2749 * @param pos Position for error reporting.
2750 * @param operator The operator for the expression
2751 * @param operand The right hand operand for the expression
2752 */
2753 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2754 if (operand.constValue() != null
2755 && lint.isEnabled(LintCategory.DIVZERO)
2756 && operand.tag <= LONG
2757 && ((Number) (operand.constValue())).longValue() == 0) {
2758 int opc = ((OperatorSymbol)operator).opcode;
2759 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2760 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2761 log.warning(LintCategory.DIVZERO, pos, "div.zero");
2762 }
2763 }
2764 }
2766 /**
2767 * Check for empty statements after if
2768 */
2769 void checkEmptyIf(JCIf tree) {
2770 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
2771 lint.isEnabled(LintCategory.EMPTY))
2772 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
2773 }
2775 /** Check that symbol is unique in given scope.
2776 * @param pos Position for error reporting.
2777 * @param sym The symbol.
2778 * @param s The scope.
2779 */
2780 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2781 if (sym.type.isErroneous())
2782 return true;
2783 if (sym.owner.name == names.any) return false;
2784 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2785 if (sym != e.sym &&
2786 (e.sym.flags() & CLASH) == 0 &&
2787 sym.kind == e.sym.kind &&
2788 sym.name != names.error &&
2789 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2790 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
2791 varargsDuplicateError(pos, sym, e.sym);
2792 return true;
2793 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
2794 duplicateErasureError(pos, sym, e.sym);
2795 sym.flags_field |= CLASH;
2796 return true;
2797 } else {
2798 duplicateError(pos, e.sym);
2799 return false;
2800 }
2801 }
2802 }
2803 return true;
2804 }
2806 /** Report duplicate declaration error.
2807 */
2808 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2809 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2810 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2811 }
2812 }
2814 /** Check that single-type import is not already imported or top-level defined,
2815 * but make an exception for two single-type imports which denote the same type.
2816 * @param pos Position for error reporting.
2817 * @param sym The symbol.
2818 * @param s The scope
2819 */
2820 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2821 return checkUniqueImport(pos, sym, s, false);
2822 }
2824 /** Check that static single-type import is not already imported or top-level defined,
2825 * but make an exception for two single-type imports which denote the same type.
2826 * @param pos Position for error reporting.
2827 * @param sym The symbol.
2828 * @param s The scope
2829 * @param staticImport Whether or not this was a static import
2830 */
2831 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2832 return checkUniqueImport(pos, sym, s, true);
2833 }
2835 /** Check that single-type import is not already imported or top-level defined,
2836 * but make an exception for two single-type imports which denote the same type.
2837 * @param pos Position for error reporting.
2838 * @param sym The symbol.
2839 * @param s The scope.
2840 * @param staticImport Whether or not this was a static import
2841 */
2842 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2843 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2844 // is encountered class entered via a class declaration?
2845 boolean isClassDecl = e.scope == s;
2846 if ((isClassDecl || sym != e.sym) &&
2847 sym.kind == e.sym.kind &&
2848 sym.name != names.error) {
2849 if (!e.sym.type.isErroneous()) {
2850 String what = e.sym.toString();
2851 if (!isClassDecl) {
2852 if (staticImport)
2853 log.error(pos, "already.defined.static.single.import", what);
2854 else
2855 log.error(pos, "already.defined.single.import", what);
2856 }
2857 else if (sym != e.sym)
2858 log.error(pos, "already.defined.this.unit", what);
2859 }
2860 return false;
2861 }
2862 }
2863 return true;
2864 }
2866 /** Check that a qualified name is in canonical form (for import decls).
2867 */
2868 public void checkCanonical(JCTree tree) {
2869 if (!isCanonical(tree))
2870 log.error(tree.pos(), "import.requires.canonical",
2871 TreeInfo.symbol(tree));
2872 }
2873 // where
2874 private boolean isCanonical(JCTree tree) {
2875 while (tree.hasTag(SELECT)) {
2876 JCFieldAccess s = (JCFieldAccess) tree;
2877 if (s.sym.owner != TreeInfo.symbol(s.selected))
2878 return false;
2879 tree = s.selected;
2880 }
2881 return true;
2882 }
2884 private class ConversionWarner extends Warner {
2885 final String uncheckedKey;
2886 final Type found;
2887 final Type expected;
2888 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
2889 super(pos);
2890 this.uncheckedKey = uncheckedKey;
2891 this.found = found;
2892 this.expected = expected;
2893 }
2895 @Override
2896 public void warn(LintCategory lint) {
2897 boolean warned = this.warned;
2898 super.warn(lint);
2899 if (warned) return; // suppress redundant diagnostics
2900 switch (lint) {
2901 case UNCHECKED:
2902 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
2903 break;
2904 case VARARGS:
2905 if (method != null &&
2906 method.attribute(syms.trustMeType.tsym) != null &&
2907 isTrustMeAllowedOnMethod(method) &&
2908 !types.isReifiable(method.type.getParameterTypes().last())) {
2909 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
2910 }
2911 break;
2912 default:
2913 throw new AssertionError("Unexpected lint: " + lint);
2914 }
2915 }
2916 }
2918 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2919 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2920 }
2922 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2923 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2924 }
2925 }