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