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