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