Fri, 28 Sep 2012 11:39:29 -0700
7199925: Separate compilation breaks check that elements have a default for the containing annotation
Reviewed-by: jjg, mcimadamore
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.*;
43 import com.sun.tools.javac.comp.Infer.InferenceContext;
44 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
46 import static com.sun.tools.javac.code.Flags.*;
47 import static com.sun.tools.javac.code.Flags.ANNOTATION;
48 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
49 import static com.sun.tools.javac.code.Kinds.*;
50 import static com.sun.tools.javac.code.TypeTags.*;
51 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
53 import static com.sun.tools.javac.tree.JCTree.Tag.*;
55 /** Type checking helper class for the attribution phase.
56 *
57 * <p><b>This is NOT part of any supported API.
58 * If you write code that depends on this, you do so at your own risk.
59 * This code and its internal interfaces are subject to change or
60 * deletion without notice.</b>
61 */
62 public class Check {
63 protected static final Context.Key<Check> checkKey =
64 new Context.Key<Check>();
66 private final Names names;
67 private final Log log;
68 private final Resolve rs;
69 private final Symtab syms;
70 private final Enter enter;
71 private final Infer infer;
72 private final Types types;
73 private final JCDiagnostic.Factory diags;
74 private boolean warnOnSyntheticConflicts;
75 private boolean suppressAbortOnBadClassFile;
76 private boolean enableSunApiLintControl;
77 private final TreeInfo treeinfo;
79 // The set of lint options currently in effect. It is initialized
80 // from the context, and then is set/reset as needed by Attr as it
81 // visits all the various parts of the trees during attribution.
82 private Lint lint;
84 // The method being analyzed in Attr - it is set/reset as needed by
85 // Attr as it visits new method declarations.
86 private MethodSymbol method;
88 public static Check instance(Context context) {
89 Check instance = context.get(checkKey);
90 if (instance == null)
91 instance = new Check(context);
92 return instance;
93 }
95 protected Check(Context context) {
96 context.put(checkKey, this);
98 names = Names.instance(context);
99 log = Log.instance(context);
100 rs = Resolve.instance(context);
101 syms = Symtab.instance(context);
102 enter = Enter.instance(context);
103 infer = Infer.instance(context);
104 this.types = Types.instance(context);
105 diags = JCDiagnostic.Factory.instance(context);
106 Options options = Options.instance(context);
107 lint = Lint.instance(context);
108 treeinfo = TreeInfo.instance(context);
110 Source source = Source.instance(context);
111 allowGenerics = source.allowGenerics();
112 allowVarargs = source.allowVarargs();
113 allowAnnotations = source.allowAnnotations();
114 allowCovariantReturns = source.allowCovariantReturns();
115 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
116 complexInference = options.isSet("complexinference");
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 an error that wrong type tag was found.
273 * @param pos Position to be used for error reporting.
274 * @param required An internationalized string describing the type tag
275 * required.
276 * @param found The type that was found.
277 */
278 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
279 // this error used to be raised by the parser,
280 // but has been delayed to this point:
281 if (found instanceof Type && ((Type)found).tag == VOID) {
282 log.error(pos, "illegal.start.of.type");
283 return syms.errType;
284 }
285 log.error(pos, "type.found.req", found, required);
286 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
287 }
289 /** Report an error that symbol cannot be referenced before super
290 * has been called.
291 * @param pos Position to be used for error reporting.
292 * @param sym The referenced symbol.
293 */
294 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
295 log.error(pos, "cant.ref.before.ctor.called", sym);
296 }
298 /** Report duplicate declaration error.
299 */
300 void duplicateError(DiagnosticPosition pos, Symbol sym) {
301 if (!sym.type.isErroneous()) {
302 Symbol location = sym.location();
303 if (location.kind == MTH &&
304 ((MethodSymbol)location).isStaticOrInstanceInit()) {
305 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
306 kindName(sym.location()), kindName(sym.location().enclClass()),
307 sym.location().enclClass());
308 } else {
309 log.error(pos, "already.defined", kindName(sym), sym,
310 kindName(sym.location()), sym.location());
311 }
312 }
313 }
315 /** Report array/varargs duplicate declaration
316 */
317 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
318 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
319 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
320 }
321 }
323 /* ************************************************************************
324 * duplicate declaration checking
325 *************************************************************************/
327 /** Check that variable does not hide variable with same name in
328 * immediately enclosing local scope.
329 * @param pos Position for error reporting.
330 * @param v The symbol.
331 * @param s The scope.
332 */
333 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
334 if (s.next != null) {
335 for (Scope.Entry e = s.next.lookup(v.name);
336 e.scope != null && e.sym.owner == v.owner;
337 e = e.next()) {
338 if (e.sym.kind == VAR &&
339 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
340 v.name != names.error) {
341 duplicateError(pos, e.sym);
342 return;
343 }
344 }
345 }
346 }
348 /** Check that a class or interface does not hide a class or
349 * interface with same name in immediately enclosing local scope.
350 * @param pos Position for error reporting.
351 * @param c The symbol.
352 * @param s The scope.
353 */
354 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
355 if (s.next != null) {
356 for (Scope.Entry e = s.next.lookup(c.name);
357 e.scope != null && e.sym.owner == c.owner;
358 e = e.next()) {
359 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
360 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
361 c.name != names.error) {
362 duplicateError(pos, e.sym);
363 return;
364 }
365 }
366 }
367 }
369 /** Check that class does not have the same name as one of
370 * its enclosing classes, or as a class defined in its enclosing scope.
371 * return true if class is unique in its enclosing scope.
372 * @param pos Position for error reporting.
373 * @param name The class name.
374 * @param s The enclosing scope.
375 */
376 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
377 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
378 if (e.sym.kind == TYP && e.sym.name != names.error) {
379 duplicateError(pos, e.sym);
380 return false;
381 }
382 }
383 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
384 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
385 duplicateError(pos, sym);
386 return true;
387 }
388 }
389 return true;
390 }
392 /* *************************************************************************
393 * Class name generation
394 **************************************************************************/
396 /** Return name of local class.
397 * This is of the form <enclClass> $ n <classname>
398 * where
399 * enclClass is the flat name of the enclosing class,
400 * classname is the simple name of the local class
401 */
402 Name localClassName(ClassSymbol c) {
403 for (int i=1; ; i++) {
404 Name flatname = names.
405 fromString("" + c.owner.enclClass().flatname +
406 syntheticNameChar + i +
407 c.name);
408 if (compiled.get(flatname) == null) return flatname;
409 }
410 }
412 /* *************************************************************************
413 * Type Checking
414 **************************************************************************/
416 /**
417 * A check context is an object that can be used to perform compatibility
418 * checks - depending on the check context, meaning of 'compatibility' might
419 * vary significantly.
420 */
421 interface CheckContext {
422 /**
423 * Is type 'found' compatible with type 'req' in given context
424 */
425 boolean compatible(Type found, Type req, Warner warn);
426 /**
427 * Report a check error
428 */
429 void report(DiagnosticPosition pos, JCDiagnostic details);
430 /**
431 * Obtain a warner for this check context
432 */
433 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
435 public Infer.InferenceContext inferenceContext();
436 }
438 /**
439 * This class represent a check context that is nested within another check
440 * context - useful to check sub-expressions. The default behavior simply
441 * redirects all method calls to the enclosing check context leveraging
442 * the forwarding pattern.
443 */
444 static class NestedCheckContext implements CheckContext {
445 CheckContext enclosingContext;
447 NestedCheckContext(CheckContext enclosingContext) {
448 this.enclosingContext = enclosingContext;
449 }
451 public boolean compatible(Type found, Type req, Warner warn) {
452 return enclosingContext.compatible(found, req, warn);
453 }
455 public void report(DiagnosticPosition pos, JCDiagnostic details) {
456 enclosingContext.report(pos, details);
457 }
459 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
460 return enclosingContext.checkWarner(pos, found, req);
461 }
463 public Infer.InferenceContext inferenceContext() {
464 return enclosingContext.inferenceContext();
465 }
466 }
468 /**
469 * Check context to be used when evaluating assignment/return statements
470 */
471 CheckContext basicHandler = new CheckContext() {
472 public void report(DiagnosticPosition pos, JCDiagnostic details) {
473 log.error(pos, "prob.found.req", details);
474 }
475 public boolean compatible(Type found, Type req, Warner warn) {
476 return types.isAssignable(found, req, warn);
477 }
479 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
480 return convertWarner(pos, found, req);
481 }
483 public InferenceContext inferenceContext() {
484 return infer.emptyContext;
485 }
486 };
488 /** Check that a given type is assignable to a given proto-type.
489 * If it is, return the type, otherwise return errType.
490 * @param pos Position to be used for error reporting.
491 * @param found The type that was found.
492 * @param req The type that was required.
493 */
494 Type checkType(DiagnosticPosition pos, Type found, Type req) {
495 return checkType(pos, found, req, basicHandler);
496 }
498 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
499 final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
500 if (inferenceContext.free(req)) {
501 inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
502 @Override
503 public void typesInferred(InferenceContext inferenceContext) {
504 checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
505 }
506 });
507 }
508 if (req.tag == ERROR)
509 return req;
510 if (req.tag == NONE)
511 return found;
512 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
513 return found;
514 } else {
515 if (found.tag <= DOUBLE && req.tag <= DOUBLE) {
516 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
517 return types.createErrorType(found);
518 }
519 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
520 return types.createErrorType(found);
521 }
522 }
524 /** Check that a given type can be cast to a given target type.
525 * Return the result of the cast.
526 * @param pos Position to be used for error reporting.
527 * @param found The type that is being cast.
528 * @param req The target type of the cast.
529 */
530 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
531 return checkCastable(pos, found, req, basicHandler);
532 }
533 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
534 if (types.isCastable(found, req, castWarner(pos, found, req))) {
535 return req;
536 } else {
537 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
538 return types.createErrorType(found);
539 }
540 }
542 /** Check for redundant casts (i.e. where source type is a subtype of target type)
543 * The problem should only be reported for non-292 cast
544 */
545 public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
546 if (!tree.type.isErroneous() &&
547 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
548 && types.isSameType(tree.expr.type, tree.clazz.type)
549 && !is292targetTypeCast(tree)) {
550 log.warning(Lint.LintCategory.CAST,
551 tree.pos(), "redundant.cast", tree.expr.type);
552 }
553 }
554 //where
555 private boolean is292targetTypeCast(JCTypeCast tree) {
556 boolean is292targetTypeCast = false;
557 JCExpression expr = TreeInfo.skipParens(tree.expr);
558 if (expr.hasTag(APPLY)) {
559 JCMethodInvocation apply = (JCMethodInvocation)expr;
560 Symbol sym = TreeInfo.symbol(apply.meth);
561 is292targetTypeCast = sym != null &&
562 sym.kind == MTH &&
563 (sym.flags() & HYPOTHETICAL) != 0;
564 }
565 return is292targetTypeCast;
566 }
570 //where
571 /** Is type a type variable, or a (possibly multi-dimensional) array of
572 * type variables?
573 */
574 boolean isTypeVar(Type t) {
575 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
576 }
578 /** Check that a type is within some bounds.
579 *
580 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
581 * type argument.
582 * @param pos Position to be used for error reporting.
583 * @param a The type that should be bounded by bs.
584 * @param bs The bound.
585 */
586 private boolean checkExtends(Type a, Type bound) {
587 if (a.isUnbound()) {
588 return true;
589 } else if (a.tag != WILDCARD) {
590 a = types.upperBound(a);
591 return types.isSubtype(a, bound);
592 } else if (a.isExtendsBound()) {
593 return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
594 } else if (a.isSuperBound()) {
595 return !types.notSoftSubtype(types.lowerBound(a), bound);
596 }
597 return true;
598 }
600 /** Check that type is different from 'void'.
601 * @param pos Position to be used for error reporting.
602 * @param t The type to be checked.
603 */
604 Type checkNonVoid(DiagnosticPosition pos, Type t) {
605 if (t.tag == VOID) {
606 log.error(pos, "void.not.allowed.here");
607 return types.createErrorType(t);
608 } else {
609 return t;
610 }
611 }
613 /** Check that type is a class or interface type.
614 * @param pos Position to be used for error reporting.
615 * @param t The type to be checked.
616 */
617 Type checkClassType(DiagnosticPosition pos, Type t) {
618 if (t.tag != CLASS && t.tag != ERROR)
619 return typeTagError(pos,
620 diags.fragment("type.req.class"),
621 (t.tag == TYPEVAR)
622 ? diags.fragment("type.parameter", t)
623 : t);
624 else
625 return t;
626 }
628 /** Check that type is a class or interface type.
629 * @param pos Position to be used for error reporting.
630 * @param t The type to be checked.
631 * @param noBounds True if type bounds are illegal here.
632 */
633 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
634 t = checkClassType(pos, t);
635 if (noBounds && t.isParameterized()) {
636 List<Type> args = t.getTypeArguments();
637 while (args.nonEmpty()) {
638 if (args.head.tag == WILDCARD)
639 return typeTagError(pos,
640 diags.fragment("type.req.exact"),
641 args.head);
642 args = args.tail;
643 }
644 }
645 return t;
646 }
648 /** Check that type is a reifiable class, interface or array type.
649 * @param pos Position to be used for error reporting.
650 * @param t The type to be checked.
651 */
652 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
653 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
654 return typeTagError(pos,
655 diags.fragment("type.req.class.array"),
656 t);
657 } else if (!types.isReifiable(t)) {
658 log.error(pos, "illegal.generic.type.for.instof");
659 return types.createErrorType(t);
660 } else {
661 return t;
662 }
663 }
665 /** Check that type is a reference type, i.e. a class, interface or array type
666 * or a type variable.
667 * @param pos Position to be used for error reporting.
668 * @param t The type to be checked.
669 */
670 Type checkRefType(DiagnosticPosition pos, Type t) {
671 switch (t.tag) {
672 case CLASS:
673 case ARRAY:
674 case TYPEVAR:
675 case WILDCARD:
676 case ERROR:
677 return t;
678 default:
679 return typeTagError(pos,
680 diags.fragment("type.req.ref"),
681 t);
682 }
683 }
685 /** Check that each type is a reference type, i.e. a class, interface or array type
686 * or a type variable.
687 * @param trees Original trees, used for error reporting.
688 * @param types The types to be checked.
689 */
690 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
691 List<JCExpression> tl = trees;
692 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
693 l.head = checkRefType(tl.head.pos(), l.head);
694 tl = tl.tail;
695 }
696 return types;
697 }
699 /** Check that type is a null or reference type.
700 * @param pos Position to be used for error reporting.
701 * @param t The type to be checked.
702 */
703 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
704 switch (t.tag) {
705 case CLASS:
706 case ARRAY:
707 case TYPEVAR:
708 case WILDCARD:
709 case BOT:
710 case ERROR:
711 return t;
712 default:
713 return typeTagError(pos,
714 diags.fragment("type.req.ref"),
715 t);
716 }
717 }
719 /** Check that flag set does not contain elements of two conflicting sets. s
720 * Return true if it doesn't.
721 * @param pos Position to be used for error reporting.
722 * @param flags The set of flags to be checked.
723 * @param set1 Conflicting flags set #1.
724 * @param set2 Conflicting flags set #2.
725 */
726 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
727 if ((flags & set1) != 0 && (flags & set2) != 0) {
728 log.error(pos,
729 "illegal.combination.of.modifiers",
730 asFlagSet(TreeInfo.firstFlag(flags & set1)),
731 asFlagSet(TreeInfo.firstFlag(flags & set2)));
732 return false;
733 } else
734 return true;
735 }
737 /** Check that usage of diamond operator is correct (i.e. diamond should not
738 * be used with non-generic classes or in anonymous class creation expressions)
739 */
740 Type checkDiamond(JCNewClass tree, Type t) {
741 if (!TreeInfo.isDiamond(tree) ||
742 t.isErroneous()) {
743 return checkClassType(tree.clazz.pos(), t, true);
744 } else if (tree.def != null) {
745 log.error(tree.clazz.pos(),
746 "cant.apply.diamond.1",
747 t, diags.fragment("diamond.and.anon.class", t));
748 return types.createErrorType(t);
749 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
750 log.error(tree.clazz.pos(),
751 "cant.apply.diamond.1",
752 t, diags.fragment("diamond.non.generic", t));
753 return types.createErrorType(t);
754 } else if (tree.typeargs != null &&
755 tree.typeargs.nonEmpty()) {
756 log.error(tree.clazz.pos(),
757 "cant.apply.diamond.1",
758 t, diags.fragment("diamond.and.explicit.params", t));
759 return types.createErrorType(t);
760 } else {
761 return t;
762 }
763 }
765 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
766 MethodSymbol m = tree.sym;
767 if (!allowSimplifiedVarargs) return;
768 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
769 Type varargElemType = null;
770 if (m.isVarArgs()) {
771 varargElemType = types.elemtype(tree.params.last().type);
772 }
773 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
774 if (varargElemType != null) {
775 log.error(tree,
776 "varargs.invalid.trustme.anno",
777 syms.trustMeType.tsym,
778 diags.fragment("varargs.trustme.on.virtual.varargs", m));
779 } else {
780 log.error(tree,
781 "varargs.invalid.trustme.anno",
782 syms.trustMeType.tsym,
783 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
784 }
785 } else if (hasTrustMeAnno && varargElemType != null &&
786 types.isReifiable(varargElemType)) {
787 warnUnsafeVararg(tree,
788 "varargs.redundant.trustme.anno",
789 syms.trustMeType.tsym,
790 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
791 }
792 else if (!hasTrustMeAnno && varargElemType != null &&
793 !types.isReifiable(varargElemType)) {
794 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
795 }
796 }
797 //where
798 private boolean isTrustMeAllowedOnMethod(Symbol s) {
799 return (s.flags() & VARARGS) != 0 &&
800 (s.isConstructor() ||
801 (s.flags() & (STATIC | FINAL)) != 0);
802 }
804 Type checkMethod(Type owntype,
805 Symbol sym,
806 Env<AttrContext> env,
807 final List<JCExpression> argtrees,
808 List<Type> argtypes,
809 boolean useVarargs,
810 boolean unchecked) {
811 // System.out.println("call : " + env.tree);
812 // System.out.println("method : " + owntype);
813 // System.out.println("actuals: " + argtypes);
814 List<Type> formals = owntype.getParameterTypes();
815 Type last = useVarargs ? formals.last() : null;
816 if (sym.name==names.init &&
817 sym.owner == syms.enumSym)
818 formals = formals.tail.tail;
819 List<JCExpression> args = argtrees;
820 while (formals.head != last) {
821 JCTree arg = args.head;
822 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
823 assertConvertible(arg, arg.type, formals.head, warn);
824 args = args.tail;
825 formals = formals.tail;
826 }
827 if (useVarargs) {
828 Type varArg = types.elemtype(last);
829 while (args.tail != null) {
830 JCTree arg = args.head;
831 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
832 assertConvertible(arg, arg.type, varArg, warn);
833 args = args.tail;
834 }
835 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
836 // non-varargs call to varargs method
837 Type varParam = owntype.getParameterTypes().last();
838 Type lastArg = argtypes.last();
839 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
840 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
841 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
842 types.elemtype(varParam), varParam);
843 }
844 if (unchecked) {
845 warnUnchecked(env.tree.pos(),
846 "unchecked.meth.invocation.applied",
847 kindName(sym),
848 sym.name,
849 rs.methodArguments(sym.type.getParameterTypes()),
850 rs.methodArguments(argtypes),
851 kindName(sym.location()),
852 sym.location());
853 owntype = new MethodType(owntype.getParameterTypes(),
854 types.erasure(owntype.getReturnType()),
855 types.erasure(owntype.getThrownTypes()),
856 syms.methodClass);
857 }
858 if (useVarargs) {
859 JCTree tree = env.tree;
860 Type argtype = owntype.getParameterTypes().last();
861 if (!types.isReifiable(argtype) &&
862 (!allowSimplifiedVarargs ||
863 sym.attribute(syms.trustMeType.tsym) == null ||
864 !isTrustMeAllowedOnMethod(sym))) {
865 warnUnchecked(env.tree.pos(),
866 "unchecked.generic.array.creation",
867 argtype);
868 }
869 Type elemtype = types.elemtype(argtype);
870 switch (tree.getTag()) {
871 case APPLY:
872 ((JCMethodInvocation) tree).varargsElement = elemtype;
873 break;
874 case NEWCLASS:
875 ((JCNewClass) tree).varargsElement = elemtype;
876 break;
877 default:
878 throw new AssertionError(""+tree);
879 }
880 }
881 return owntype;
882 }
883 //where
884 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
885 if (types.isConvertible(actual, formal, warn))
886 return;
888 if (formal.isCompound()
889 && types.isSubtype(actual, types.supertype(formal))
890 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
891 return;
892 }
894 /**
895 * Check that type 't' is a valid instantiation of a generic class
896 * (see JLS 4.5)
897 *
898 * @param t class type to be checked
899 * @return true if 't' is well-formed
900 */
901 public boolean checkValidGenericType(Type t) {
902 return firstIncompatibleTypeArg(t) == null;
903 }
904 //WHERE
905 private Type firstIncompatibleTypeArg(Type type) {
906 List<Type> formals = type.tsym.type.allparams();
907 List<Type> actuals = type.allparams();
908 List<Type> args = type.getTypeArguments();
909 List<Type> forms = type.tsym.type.getTypeArguments();
910 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
912 // For matching pairs of actual argument types `a' and
913 // formal type parameters with declared bound `b' ...
914 while (args.nonEmpty() && forms.nonEmpty()) {
915 // exact type arguments needs to know their
916 // bounds (for upper and lower bound
917 // calculations). So we create new bounds where
918 // type-parameters are replaced with actuals argument types.
919 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
920 args = args.tail;
921 forms = forms.tail;
922 }
924 args = type.getTypeArguments();
925 List<Type> tvars_cap = types.substBounds(formals,
926 formals,
927 types.capture(type).allparams());
928 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
929 // Let the actual arguments know their bound
930 args.head.withTypeVar((TypeVar)tvars_cap.head);
931 args = args.tail;
932 tvars_cap = tvars_cap.tail;
933 }
935 args = type.getTypeArguments();
936 List<Type> bounds = bounds_buf.toList();
938 while (args.nonEmpty() && bounds.nonEmpty()) {
939 Type actual = args.head;
940 if (!isTypeArgErroneous(actual) &&
941 !bounds.head.isErroneous() &&
942 !checkExtends(actual, bounds.head)) {
943 return args.head;
944 }
945 args = args.tail;
946 bounds = bounds.tail;
947 }
949 args = type.getTypeArguments();
950 bounds = bounds_buf.toList();
952 for (Type arg : types.capture(type).getTypeArguments()) {
953 if (arg.tag == TYPEVAR &&
954 arg.getUpperBound().isErroneous() &&
955 !bounds.head.isErroneous() &&
956 !isTypeArgErroneous(args.head)) {
957 return args.head;
958 }
959 bounds = bounds.tail;
960 args = args.tail;
961 }
963 return null;
964 }
965 //where
966 boolean isTypeArgErroneous(Type t) {
967 return isTypeArgErroneous.visit(t);
968 }
970 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
971 public Boolean visitType(Type t, Void s) {
972 return t.isErroneous();
973 }
974 @Override
975 public Boolean visitTypeVar(TypeVar t, Void s) {
976 return visit(t.getUpperBound());
977 }
978 @Override
979 public Boolean visitCapturedType(CapturedType t, Void s) {
980 return visit(t.getUpperBound()) ||
981 visit(t.getLowerBound());
982 }
983 @Override
984 public Boolean visitWildcardType(WildcardType t, Void s) {
985 return visit(t.type);
986 }
987 };
989 /** Check that given modifiers are legal for given symbol and
990 * return modifiers together with any implicit modififiers for that symbol.
991 * Warning: we can't use flags() here since this method
992 * is called during class enter, when flags() would cause a premature
993 * completion.
994 * @param pos Position to be used for error reporting.
995 * @param flags The set of modifiers given in a definition.
996 * @param sym The defined symbol.
997 */
998 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
999 long mask;
1000 long implicit = 0;
1001 switch (sym.kind) {
1002 case VAR:
1003 if (sym.owner.kind != TYP)
1004 mask = LocalVarFlags;
1005 else if ((sym.owner.flags_field & INTERFACE) != 0)
1006 mask = implicit = InterfaceVarFlags;
1007 else
1008 mask = VarFlags;
1009 break;
1010 case MTH:
1011 if (sym.name == names.init) {
1012 if ((sym.owner.flags_field & ENUM) != 0) {
1013 // enum constructors cannot be declared public or
1014 // protected and must be implicitly or explicitly
1015 // private
1016 implicit = PRIVATE;
1017 mask = PRIVATE;
1018 } else
1019 mask = ConstructorFlags;
1020 } else if ((sym.owner.flags_field & INTERFACE) != 0)
1021 mask = implicit = InterfaceMethodFlags;
1022 else {
1023 mask = MethodFlags;
1024 }
1025 // Imply STRICTFP if owner has STRICTFP set.
1026 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1027 implicit |= sym.owner.flags_field & STRICTFP;
1028 break;
1029 case TYP:
1030 if (sym.isLocal()) {
1031 mask = LocalClassFlags;
1032 if (sym.name.isEmpty()) { // Anonymous class
1033 // Anonymous classes in static methods are themselves static;
1034 // that's why we admit STATIC here.
1035 mask |= STATIC;
1036 // JLS: Anonymous classes are final.
1037 implicit |= FINAL;
1038 }
1039 if ((sym.owner.flags_field & STATIC) == 0 &&
1040 (flags & ENUM) != 0)
1041 log.error(pos, "enums.must.be.static");
1042 } else if (sym.owner.kind == TYP) {
1043 mask = MemberClassFlags;
1044 if (sym.owner.owner.kind == PCK ||
1045 (sym.owner.flags_field & STATIC) != 0)
1046 mask |= STATIC;
1047 else if ((flags & ENUM) != 0)
1048 log.error(pos, "enums.must.be.static");
1049 // Nested interfaces and enums are always STATIC (Spec ???)
1050 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1051 } else {
1052 mask = ClassFlags;
1053 }
1054 // Interfaces are always ABSTRACT
1055 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1057 if ((flags & ENUM) != 0) {
1058 // enums can't be declared abstract or final
1059 mask &= ~(ABSTRACT | FINAL);
1060 implicit |= implicitEnumFinalFlag(tree);
1061 }
1062 // Imply STRICTFP if owner has STRICTFP set.
1063 implicit |= sym.owner.flags_field & STRICTFP;
1064 break;
1065 default:
1066 throw new AssertionError();
1067 }
1068 long illegal = flags & StandardFlags & ~mask;
1069 if (illegal != 0) {
1070 if ((illegal & INTERFACE) != 0) {
1071 log.error(pos, "intf.not.allowed.here");
1072 mask |= INTERFACE;
1073 }
1074 else {
1075 log.error(pos,
1076 "mod.not.allowed.here", asFlagSet(illegal));
1077 }
1078 }
1079 else if ((sym.kind == TYP ||
1080 // ISSUE: Disallowing abstract&private is no longer appropriate
1081 // in the presence of inner classes. Should it be deleted here?
1082 checkDisjoint(pos, flags,
1083 ABSTRACT,
1084 PRIVATE | STATIC))
1085 &&
1086 checkDisjoint(pos, flags,
1087 ABSTRACT | INTERFACE,
1088 FINAL | NATIVE | SYNCHRONIZED)
1089 &&
1090 checkDisjoint(pos, flags,
1091 PUBLIC,
1092 PRIVATE | PROTECTED)
1093 &&
1094 checkDisjoint(pos, flags,
1095 PRIVATE,
1096 PUBLIC | PROTECTED)
1097 &&
1098 checkDisjoint(pos, flags,
1099 FINAL,
1100 VOLATILE)
1101 &&
1102 (sym.kind == TYP ||
1103 checkDisjoint(pos, flags,
1104 ABSTRACT | NATIVE,
1105 STRICTFP))) {
1106 // skip
1107 }
1108 return flags & (mask | ~StandardFlags) | implicit;
1109 }
1112 /** Determine if this enum should be implicitly final.
1113 *
1114 * If the enum has no specialized enum contants, it is final.
1115 *
1116 * If the enum does have specialized enum contants, it is
1117 * <i>not</i> final.
1118 */
1119 private long implicitEnumFinalFlag(JCTree tree) {
1120 if (!tree.hasTag(CLASSDEF)) return 0;
1121 class SpecialTreeVisitor extends JCTree.Visitor {
1122 boolean specialized;
1123 SpecialTreeVisitor() {
1124 this.specialized = false;
1125 };
1127 @Override
1128 public void visitTree(JCTree tree) { /* no-op */ }
1130 @Override
1131 public void visitVarDef(JCVariableDecl tree) {
1132 if ((tree.mods.flags & ENUM) != 0) {
1133 if (tree.init instanceof JCNewClass &&
1134 ((JCNewClass) tree.init).def != null) {
1135 specialized = true;
1136 }
1137 }
1138 }
1139 }
1141 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1142 JCClassDecl cdef = (JCClassDecl) tree;
1143 for (JCTree defs: cdef.defs) {
1144 defs.accept(sts);
1145 if (sts.specialized) return 0;
1146 }
1147 return FINAL;
1148 }
1150 /* *************************************************************************
1151 * Type Validation
1152 **************************************************************************/
1154 /** Validate a type expression. That is,
1155 * check that all type arguments of a parametric type are within
1156 * their bounds. This must be done in a second phase after type attributon
1157 * since a class might have a subclass as type parameter bound. E.g:
1158 *
1159 * class B<A extends C> { ... }
1160 * class C extends B<C> { ... }
1161 *
1162 * and we can't make sure that the bound is already attributed because
1163 * of possible cycles.
1164 *
1165 * Visitor method: Validate a type expression, if it is not null, catching
1166 * and reporting any completion failures.
1167 */
1168 void validate(JCTree tree, Env<AttrContext> env) {
1169 validate(tree, env, true);
1170 }
1171 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1172 new Validator(env).validateTree(tree, checkRaw, true);
1173 }
1175 /** Visitor method: Validate a list of type expressions.
1176 */
1177 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1178 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1179 validate(l.head, env);
1180 }
1182 /** A visitor class for type validation.
1183 */
1184 class Validator extends JCTree.Visitor {
1186 boolean isOuter;
1187 Env<AttrContext> env;
1189 Validator(Env<AttrContext> env) {
1190 this.env = env;
1191 }
1193 @Override
1194 public void visitTypeArray(JCArrayTypeTree tree) {
1195 tree.elemtype.accept(this);
1196 }
1198 @Override
1199 public void visitTypeApply(JCTypeApply tree) {
1200 if (tree.type.tag == CLASS) {
1201 List<JCExpression> args = tree.arguments;
1202 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1204 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1205 if (incompatibleArg != null) {
1206 for (JCTree arg : tree.arguments) {
1207 if (arg.type == incompatibleArg) {
1208 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1209 }
1210 forms = forms.tail;
1211 }
1212 }
1214 forms = tree.type.tsym.type.getTypeArguments();
1216 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1218 // For matching pairs of actual argument types `a' and
1219 // formal type parameters with declared bound `b' ...
1220 while (args.nonEmpty() && forms.nonEmpty()) {
1221 validateTree(args.head,
1222 !(isOuter && is_java_lang_Class),
1223 false);
1224 args = args.tail;
1225 forms = forms.tail;
1226 }
1228 // Check that this type is either fully parameterized, or
1229 // not parameterized at all.
1230 if (tree.type.getEnclosingType().isRaw())
1231 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1232 if (tree.clazz.hasTag(SELECT))
1233 visitSelectInternal((JCFieldAccess)tree.clazz);
1234 }
1235 }
1237 @Override
1238 public void visitTypeParameter(JCTypeParameter tree) {
1239 validateTrees(tree.bounds, true, isOuter);
1240 checkClassBounds(tree.pos(), tree.type);
1241 }
1243 @Override
1244 public void visitWildcard(JCWildcard tree) {
1245 if (tree.inner != null)
1246 validateTree(tree.inner, true, isOuter);
1247 }
1249 @Override
1250 public void visitSelect(JCFieldAccess tree) {
1251 if (tree.type.tag == CLASS) {
1252 visitSelectInternal(tree);
1254 // Check that this type is either fully parameterized, or
1255 // not parameterized at all.
1256 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1257 log.error(tree.pos(), "improperly.formed.type.param.missing");
1258 }
1259 }
1261 public void visitSelectInternal(JCFieldAccess tree) {
1262 if (tree.type.tsym.isStatic() &&
1263 tree.selected.type.isParameterized()) {
1264 // The enclosing type is not a class, so we are
1265 // looking at a static member type. However, the
1266 // qualifying expression is parameterized.
1267 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1268 } else {
1269 // otherwise validate the rest of the expression
1270 tree.selected.accept(this);
1271 }
1272 }
1274 /** Default visitor method: do nothing.
1275 */
1276 @Override
1277 public void visitTree(JCTree tree) {
1278 }
1280 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1281 try {
1282 if (tree != null) {
1283 this.isOuter = isOuter;
1284 tree.accept(this);
1285 if (checkRaw)
1286 checkRaw(tree, env);
1287 }
1288 } catch (CompletionFailure ex) {
1289 completionError(tree.pos(), ex);
1290 }
1291 }
1293 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1294 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1295 validateTree(l.head, checkRaw, isOuter);
1296 }
1298 void checkRaw(JCTree tree, Env<AttrContext> env) {
1299 if (lint.isEnabled(LintCategory.RAW) &&
1300 tree.type.tag == CLASS &&
1301 !TreeInfo.isDiamond(tree) &&
1302 !withinAnonConstr(env) &&
1303 tree.type.isRaw()) {
1304 log.warning(LintCategory.RAW,
1305 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1306 }
1307 }
1309 boolean withinAnonConstr(Env<AttrContext> env) {
1310 return env.enclClass.name.isEmpty() &&
1311 env.enclMethod != null && env.enclMethod.name == names.init;
1312 }
1313 }
1315 /* *************************************************************************
1316 * Exception checking
1317 **************************************************************************/
1319 /* The following methods treat classes as sets that contain
1320 * the class itself and all their subclasses
1321 */
1323 /** Is given type a subtype of some of the types in given list?
1324 */
1325 boolean subset(Type t, List<Type> ts) {
1326 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1327 if (types.isSubtype(t, l.head)) return true;
1328 return false;
1329 }
1331 /** Is given type a subtype or supertype of
1332 * some of the types in given list?
1333 */
1334 boolean intersects(Type t, List<Type> ts) {
1335 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1336 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1337 return false;
1338 }
1340 /** Add type set to given type list, unless it is a subclass of some class
1341 * in the list.
1342 */
1343 List<Type> incl(Type t, List<Type> ts) {
1344 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1345 }
1347 /** Remove type set from type set list.
1348 */
1349 List<Type> excl(Type t, List<Type> ts) {
1350 if (ts.isEmpty()) {
1351 return ts;
1352 } else {
1353 List<Type> ts1 = excl(t, ts.tail);
1354 if (types.isSubtype(ts.head, t)) return ts1;
1355 else if (ts1 == ts.tail) return ts;
1356 else return ts1.prepend(ts.head);
1357 }
1358 }
1360 /** Form the union of two type set lists.
1361 */
1362 List<Type> union(List<Type> ts1, List<Type> ts2) {
1363 List<Type> ts = ts1;
1364 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1365 ts = incl(l.head, ts);
1366 return ts;
1367 }
1369 /** Form the difference of two type lists.
1370 */
1371 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1372 List<Type> ts = ts1;
1373 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1374 ts = excl(l.head, ts);
1375 return ts;
1376 }
1378 /** Form the intersection of two type lists.
1379 */
1380 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1381 List<Type> ts = List.nil();
1382 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1383 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1384 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1385 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1386 return ts;
1387 }
1389 /** Is exc an exception symbol that need not be declared?
1390 */
1391 boolean isUnchecked(ClassSymbol exc) {
1392 return
1393 exc.kind == ERR ||
1394 exc.isSubClass(syms.errorType.tsym, types) ||
1395 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1396 }
1398 /** Is exc an exception type that need not be declared?
1399 */
1400 boolean isUnchecked(Type exc) {
1401 return
1402 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1403 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1404 exc.tag == BOT;
1405 }
1407 /** Same, but handling completion failures.
1408 */
1409 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1410 try {
1411 return isUnchecked(exc);
1412 } catch (CompletionFailure ex) {
1413 completionError(pos, ex);
1414 return true;
1415 }
1416 }
1418 /** Is exc handled by given exception list?
1419 */
1420 boolean isHandled(Type exc, List<Type> handled) {
1421 return isUnchecked(exc) || subset(exc, handled);
1422 }
1424 /** Return all exceptions in thrown list that are not in handled list.
1425 * @param thrown The list of thrown exceptions.
1426 * @param handled The list of handled exceptions.
1427 */
1428 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1429 List<Type> unhandled = List.nil();
1430 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1431 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1432 return unhandled;
1433 }
1435 /* *************************************************************************
1436 * Overriding/Implementation checking
1437 **************************************************************************/
1439 /** The level of access protection given by a flag set,
1440 * where PRIVATE is highest and PUBLIC is lowest.
1441 */
1442 static int protection(long flags) {
1443 switch ((short)(flags & AccessFlags)) {
1444 case PRIVATE: return 3;
1445 case PROTECTED: return 1;
1446 default:
1447 case PUBLIC: return 0;
1448 case 0: return 2;
1449 }
1450 }
1452 /** A customized "cannot override" error message.
1453 * @param m The overriding method.
1454 * @param other The overridden method.
1455 * @return An internationalized string.
1456 */
1457 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1458 String key;
1459 if ((other.owner.flags() & INTERFACE) == 0)
1460 key = "cant.override";
1461 else if ((m.owner.flags() & INTERFACE) == 0)
1462 key = "cant.implement";
1463 else
1464 key = "clashes.with";
1465 return diags.fragment(key, m, m.location(), other, other.location());
1466 }
1468 /** A customized "override" warning message.
1469 * @param m The overriding method.
1470 * @param other The overridden method.
1471 * @return An internationalized string.
1472 */
1473 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1474 String key;
1475 if ((other.owner.flags() & INTERFACE) == 0)
1476 key = "unchecked.override";
1477 else if ((m.owner.flags() & INTERFACE) == 0)
1478 key = "unchecked.implement";
1479 else
1480 key = "unchecked.clash.with";
1481 return diags.fragment(key, m, m.location(), other, other.location());
1482 }
1484 /** A customized "override" warning message.
1485 * @param m The overriding method.
1486 * @param other The overridden method.
1487 * @return An internationalized string.
1488 */
1489 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1490 String key;
1491 if ((other.owner.flags() & INTERFACE) == 0)
1492 key = "varargs.override";
1493 else if ((m.owner.flags() & INTERFACE) == 0)
1494 key = "varargs.implement";
1495 else
1496 key = "varargs.clash.with";
1497 return diags.fragment(key, m, m.location(), other, other.location());
1498 }
1500 /** Check that this method conforms with overridden method 'other'.
1501 * where `origin' is the class where checking started.
1502 * Complications:
1503 * (1) Do not check overriding of synthetic methods
1504 * (reason: they might be final).
1505 * todo: check whether this is still necessary.
1506 * (2) Admit the case where an interface proxy throws fewer exceptions
1507 * than the method it implements. Augment the proxy methods with the
1508 * undeclared exceptions in this case.
1509 * (3) When generics are enabled, admit the case where an interface proxy
1510 * has a result type
1511 * extended by the result type of the method it implements.
1512 * Change the proxies result type to the smaller type in this case.
1513 *
1514 * @param tree The tree from which positions
1515 * are extracted for errors.
1516 * @param m The overriding method.
1517 * @param other The overridden method.
1518 * @param origin The class of which the overriding method
1519 * is a member.
1520 */
1521 void checkOverride(JCTree tree,
1522 MethodSymbol m,
1523 MethodSymbol other,
1524 ClassSymbol origin) {
1525 // Don't check overriding of synthetic methods or by bridge methods.
1526 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1527 return;
1528 }
1530 // Error if static method overrides instance method (JLS 8.4.6.2).
1531 if ((m.flags() & STATIC) != 0 &&
1532 (other.flags() & STATIC) == 0) {
1533 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1534 cannotOverride(m, other));
1535 return;
1536 }
1538 // Error if instance method overrides static or final
1539 // method (JLS 8.4.6.1).
1540 if ((other.flags() & FINAL) != 0 ||
1541 (m.flags() & STATIC) == 0 &&
1542 (other.flags() & STATIC) != 0) {
1543 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1544 cannotOverride(m, other),
1545 asFlagSet(other.flags() & (FINAL | STATIC)));
1546 return;
1547 }
1549 if ((m.owner.flags() & ANNOTATION) != 0) {
1550 // handled in validateAnnotationMethod
1551 return;
1552 }
1554 // Error if overriding method has weaker access (JLS 8.4.6.3).
1555 if ((origin.flags() & INTERFACE) == 0 &&
1556 protection(m.flags()) > protection(other.flags())) {
1557 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1558 cannotOverride(m, other),
1559 other.flags() == 0 ?
1560 Flag.PACKAGE :
1561 asFlagSet(other.flags() & AccessFlags));
1562 return;
1563 }
1565 Type mt = types.memberType(origin.type, m);
1566 Type ot = types.memberType(origin.type, other);
1567 // Error if overriding result type is different
1568 // (or, in the case of generics mode, not a subtype) of
1569 // overridden result type. We have to rename any type parameters
1570 // before comparing types.
1571 List<Type> mtvars = mt.getTypeArguments();
1572 List<Type> otvars = ot.getTypeArguments();
1573 Type mtres = mt.getReturnType();
1574 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1576 overrideWarner.clear();
1577 boolean resultTypesOK =
1578 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1579 if (!resultTypesOK) {
1580 if (!allowCovariantReturns &&
1581 m.owner != origin &&
1582 m.owner.isSubClass(other.owner, types)) {
1583 // allow limited interoperability with covariant returns
1584 } else {
1585 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1586 "override.incompatible.ret",
1587 cannotOverride(m, other),
1588 mtres, otres);
1589 return;
1590 }
1591 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1592 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1593 "override.unchecked.ret",
1594 uncheckedOverrides(m, other),
1595 mtres, otres);
1596 }
1598 // Error if overriding method throws an exception not reported
1599 // by overridden method.
1600 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1601 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1602 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1603 if (unhandledErased.nonEmpty()) {
1604 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1605 "override.meth.doesnt.throw",
1606 cannotOverride(m, other),
1607 unhandledUnerased.head);
1608 return;
1609 }
1610 else if (unhandledUnerased.nonEmpty()) {
1611 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1612 "override.unchecked.thrown",
1613 cannotOverride(m, other),
1614 unhandledUnerased.head);
1615 return;
1616 }
1618 // Optional warning if varargs don't agree
1619 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1620 && lint.isEnabled(LintCategory.OVERRIDES)) {
1621 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1622 ((m.flags() & Flags.VARARGS) != 0)
1623 ? "override.varargs.missing"
1624 : "override.varargs.extra",
1625 varargsOverrides(m, other));
1626 }
1628 // Warn if instance method overrides bridge method (compiler spec ??)
1629 if ((other.flags() & BRIDGE) != 0) {
1630 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1631 uncheckedOverrides(m, other));
1632 }
1634 // Warn if a deprecated method overridden by a non-deprecated one.
1635 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1636 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1637 }
1638 }
1639 // where
1640 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1641 // If the method, m, is defined in an interface, then ignore the issue if the method
1642 // is only inherited via a supertype and also implemented in the supertype,
1643 // because in that case, we will rediscover the issue when examining the method
1644 // in the supertype.
1645 // If the method, m, is not defined in an interface, then the only time we need to
1646 // address the issue is when the method is the supertype implemementation: any other
1647 // case, we will have dealt with when examining the supertype classes
1648 ClassSymbol mc = m.enclClass();
1649 Type st = types.supertype(origin.type);
1650 if (st.tag != CLASS)
1651 return true;
1652 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1654 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1655 List<Type> intfs = types.interfaces(origin.type);
1656 return (intfs.contains(mc.type) ? false : (stimpl != null));
1657 }
1658 else
1659 return (stimpl != m);
1660 }
1663 // used to check if there were any unchecked conversions
1664 Warner overrideWarner = new Warner();
1666 /** Check that a class does not inherit two concrete methods
1667 * with the same signature.
1668 * @param pos Position to be used for error reporting.
1669 * @param site The class type to be checked.
1670 */
1671 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1672 Type sup = types.supertype(site);
1673 if (sup.tag != CLASS) return;
1675 for (Type t1 = sup;
1676 t1.tsym.type.isParameterized();
1677 t1 = types.supertype(t1)) {
1678 for (Scope.Entry e1 = t1.tsym.members().elems;
1679 e1 != null;
1680 e1 = e1.sibling) {
1681 Symbol s1 = e1.sym;
1682 if (s1.kind != MTH ||
1683 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1684 !s1.isInheritedIn(site.tsym, types) ||
1685 ((MethodSymbol)s1).implementation(site.tsym,
1686 types,
1687 true) != s1)
1688 continue;
1689 Type st1 = types.memberType(t1, s1);
1690 int s1ArgsLength = st1.getParameterTypes().length();
1691 if (st1 == s1.type) continue;
1693 for (Type t2 = sup;
1694 t2.tag == CLASS;
1695 t2 = types.supertype(t2)) {
1696 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1697 e2.scope != null;
1698 e2 = e2.next()) {
1699 Symbol s2 = e2.sym;
1700 if (s2 == s1 ||
1701 s2.kind != MTH ||
1702 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1703 s2.type.getParameterTypes().length() != s1ArgsLength ||
1704 !s2.isInheritedIn(site.tsym, types) ||
1705 ((MethodSymbol)s2).implementation(site.tsym,
1706 types,
1707 true) != s2)
1708 continue;
1709 Type st2 = types.memberType(t2, s2);
1710 if (types.overrideEquivalent(st1, st2))
1711 log.error(pos, "concrete.inheritance.conflict",
1712 s1, t1, s2, t2, sup);
1713 }
1714 }
1715 }
1716 }
1717 }
1719 /** Check that classes (or interfaces) do not each define an abstract
1720 * method with same name and arguments but incompatible return types.
1721 * @param pos Position to be used for error reporting.
1722 * @param t1 The first argument type.
1723 * @param t2 The second argument type.
1724 */
1725 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1726 Type t1,
1727 Type t2) {
1728 return checkCompatibleAbstracts(pos, t1, t2,
1729 types.makeCompoundType(t1, t2));
1730 }
1732 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1733 Type t1,
1734 Type t2,
1735 Type site) {
1736 return firstIncompatibility(pos, t1, t2, site) == null;
1737 }
1739 /** Return the first method which is defined with same args
1740 * but different return types in two given interfaces, or null if none
1741 * exists.
1742 * @param t1 The first type.
1743 * @param t2 The second type.
1744 * @param site The most derived type.
1745 * @returns symbol from t2 that conflicts with one in t1.
1746 */
1747 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1748 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1749 closure(t1, interfaces1);
1750 Map<TypeSymbol,Type> interfaces2;
1751 if (t1 == t2)
1752 interfaces2 = interfaces1;
1753 else
1754 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1756 for (Type t3 : interfaces1.values()) {
1757 for (Type t4 : interfaces2.values()) {
1758 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1759 if (s != null) return s;
1760 }
1761 }
1762 return null;
1763 }
1765 /** Compute all the supertypes of t, indexed by type symbol. */
1766 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1767 if (t.tag != CLASS) return;
1768 if (typeMap.put(t.tsym, t) == null) {
1769 closure(types.supertype(t), typeMap);
1770 for (Type i : types.interfaces(t))
1771 closure(i, typeMap);
1772 }
1773 }
1775 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1776 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1777 if (t.tag != CLASS) return;
1778 if (typesSkip.get(t.tsym) != null) return;
1779 if (typeMap.put(t.tsym, t) == null) {
1780 closure(types.supertype(t), typesSkip, typeMap);
1781 for (Type i : types.interfaces(t))
1782 closure(i, typesSkip, typeMap);
1783 }
1784 }
1786 /** Return the first method in t2 that conflicts with a method from t1. */
1787 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1788 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1789 Symbol s1 = e1.sym;
1790 Type st1 = null;
1791 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1792 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1793 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1794 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1795 Symbol s2 = e2.sym;
1796 if (s1 == s2) continue;
1797 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1798 if (st1 == null) st1 = types.memberType(t1, s1);
1799 Type st2 = types.memberType(t2, s2);
1800 if (types.overrideEquivalent(st1, st2)) {
1801 List<Type> tvars1 = st1.getTypeArguments();
1802 List<Type> tvars2 = st2.getTypeArguments();
1803 Type rt1 = st1.getReturnType();
1804 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1805 boolean compat =
1806 types.isSameType(rt1, rt2) ||
1807 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1808 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1809 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1810 checkCommonOverriderIn(s1,s2,site);
1811 if (!compat) {
1812 log.error(pos, "types.incompatible.diff.ret",
1813 t1, t2, s2.name +
1814 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1815 return s2;
1816 }
1817 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1818 !checkCommonOverriderIn(s1, s2, site)) {
1819 log.error(pos,
1820 "name.clash.same.erasure.no.override",
1821 s1, s1.location(),
1822 s2, s2.location());
1823 return s2;
1824 }
1825 }
1826 }
1827 return null;
1828 }
1829 //WHERE
1830 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1831 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1832 Type st1 = types.memberType(site, s1);
1833 Type st2 = types.memberType(site, s2);
1834 closure(site, supertypes);
1835 for (Type t : supertypes.values()) {
1836 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1837 Symbol s3 = e.sym;
1838 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1839 Type st3 = types.memberType(site,s3);
1840 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1841 if (s3.owner == site.tsym) {
1842 return true;
1843 }
1844 List<Type> tvars1 = st1.getTypeArguments();
1845 List<Type> tvars2 = st2.getTypeArguments();
1846 List<Type> tvars3 = st3.getTypeArguments();
1847 Type rt1 = st1.getReturnType();
1848 Type rt2 = st2.getReturnType();
1849 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1850 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1851 boolean compat =
1852 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1853 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1854 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1855 if (compat)
1856 return true;
1857 }
1858 }
1859 }
1860 return false;
1861 }
1863 /** Check that a given method conforms with any method it overrides.
1864 * @param tree The tree from which positions are extracted
1865 * for errors.
1866 * @param m The overriding method.
1867 */
1868 void checkOverride(JCTree tree, MethodSymbol m) {
1869 ClassSymbol origin = (ClassSymbol)m.owner;
1870 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1871 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1872 log.error(tree.pos(), "enum.no.finalize");
1873 return;
1874 }
1875 for (Type t = origin.type; t.tag == CLASS;
1876 t = types.supertype(t)) {
1877 if (t != origin.type) {
1878 checkOverride(tree, t, origin, m);
1879 }
1880 for (Type t2 : types.interfaces(t)) {
1881 checkOverride(tree, t2, origin, m);
1882 }
1883 }
1884 }
1886 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1887 TypeSymbol c = site.tsym;
1888 Scope.Entry e = c.members().lookup(m.name);
1889 while (e.scope != null) {
1890 if (m.overrides(e.sym, origin, types, false)) {
1891 if ((e.sym.flags() & ABSTRACT) == 0) {
1892 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1893 }
1894 }
1895 e = e.next();
1896 }
1897 }
1899 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1900 ClashFilter cf = new ClashFilter(origin.type);
1901 return (cf.accepts(s1) &&
1902 cf.accepts(s2) &&
1903 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1904 }
1907 /** Check that all abstract members of given class have definitions.
1908 * @param pos Position to be used for error reporting.
1909 * @param c The class.
1910 */
1911 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1912 try {
1913 MethodSymbol undef = firstUndef(c, c);
1914 if (undef != null) {
1915 if ((c.flags() & ENUM) != 0 &&
1916 types.supertype(c.type).tsym == syms.enumSym &&
1917 (c.flags() & FINAL) == 0) {
1918 // add the ABSTRACT flag to an enum
1919 c.flags_field |= ABSTRACT;
1920 } else {
1921 MethodSymbol undef1 =
1922 new MethodSymbol(undef.flags(), undef.name,
1923 types.memberType(c.type, undef), undef.owner);
1924 log.error(pos, "does.not.override.abstract",
1925 c, undef1, undef1.location());
1926 }
1927 }
1928 } catch (CompletionFailure ex) {
1929 completionError(pos, ex);
1930 }
1931 }
1932 //where
1933 /** Return first abstract member of class `c' that is not defined
1934 * in `impl', null if there is none.
1935 */
1936 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1937 MethodSymbol undef = null;
1938 // Do not bother to search in classes that are not abstract,
1939 // since they cannot have abstract members.
1940 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1941 Scope s = c.members();
1942 for (Scope.Entry e = s.elems;
1943 undef == null && e != null;
1944 e = e.sibling) {
1945 if (e.sym.kind == MTH &&
1946 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1947 MethodSymbol absmeth = (MethodSymbol)e.sym;
1948 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1949 if (implmeth == null || implmeth == absmeth)
1950 undef = absmeth;
1951 }
1952 }
1953 if (undef == null) {
1954 Type st = types.supertype(c.type);
1955 if (st.tag == CLASS)
1956 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1957 }
1958 for (List<Type> l = types.interfaces(c.type);
1959 undef == null && l.nonEmpty();
1960 l = l.tail) {
1961 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1962 }
1963 }
1964 return undef;
1965 }
1967 void checkNonCyclicDecl(JCClassDecl tree) {
1968 CycleChecker cc = new CycleChecker();
1969 cc.scan(tree);
1970 if (!cc.errorFound && !cc.partialCheck) {
1971 tree.sym.flags_field |= ACYCLIC;
1972 }
1973 }
1975 class CycleChecker extends TreeScanner {
1977 List<Symbol> seenClasses = List.nil();
1978 boolean errorFound = false;
1979 boolean partialCheck = false;
1981 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1982 if (sym != null && sym.kind == TYP) {
1983 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1984 if (classEnv != null) {
1985 DiagnosticSource prevSource = log.currentSource();
1986 try {
1987 log.useSource(classEnv.toplevel.sourcefile);
1988 scan(classEnv.tree);
1989 }
1990 finally {
1991 log.useSource(prevSource.getFile());
1992 }
1993 } else if (sym.kind == TYP) {
1994 checkClass(pos, sym, List.<JCTree>nil());
1995 }
1996 } else {
1997 //not completed yet
1998 partialCheck = true;
1999 }
2000 }
2002 @Override
2003 public void visitSelect(JCFieldAccess tree) {
2004 super.visitSelect(tree);
2005 checkSymbol(tree.pos(), tree.sym);
2006 }
2008 @Override
2009 public void visitIdent(JCIdent tree) {
2010 checkSymbol(tree.pos(), tree.sym);
2011 }
2013 @Override
2014 public void visitTypeApply(JCTypeApply tree) {
2015 scan(tree.clazz);
2016 }
2018 @Override
2019 public void visitTypeArray(JCArrayTypeTree tree) {
2020 scan(tree.elemtype);
2021 }
2023 @Override
2024 public void visitClassDef(JCClassDecl tree) {
2025 List<JCTree> supertypes = List.nil();
2026 if (tree.getExtendsClause() != null) {
2027 supertypes = supertypes.prepend(tree.getExtendsClause());
2028 }
2029 if (tree.getImplementsClause() != null) {
2030 for (JCTree intf : tree.getImplementsClause()) {
2031 supertypes = supertypes.prepend(intf);
2032 }
2033 }
2034 checkClass(tree.pos(), tree.sym, supertypes);
2035 }
2037 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2038 if ((c.flags_field & ACYCLIC) != 0)
2039 return;
2040 if (seenClasses.contains(c)) {
2041 errorFound = true;
2042 noteCyclic(pos, (ClassSymbol)c);
2043 } else if (!c.type.isErroneous()) {
2044 try {
2045 seenClasses = seenClasses.prepend(c);
2046 if (c.type.tag == CLASS) {
2047 if (supertypes.nonEmpty()) {
2048 scan(supertypes);
2049 }
2050 else {
2051 ClassType ct = (ClassType)c.type;
2052 if (ct.supertype_field == null ||
2053 ct.interfaces_field == null) {
2054 //not completed yet
2055 partialCheck = true;
2056 return;
2057 }
2058 checkSymbol(pos, ct.supertype_field.tsym);
2059 for (Type intf : ct.interfaces_field) {
2060 checkSymbol(pos, intf.tsym);
2061 }
2062 }
2063 if (c.owner.kind == TYP) {
2064 checkSymbol(pos, c.owner);
2065 }
2066 }
2067 } finally {
2068 seenClasses = seenClasses.tail;
2069 }
2070 }
2071 }
2072 }
2074 /** Check for cyclic references. Issue an error if the
2075 * symbol of the type referred to has a LOCKED flag set.
2076 *
2077 * @param pos Position to be used for error reporting.
2078 * @param t The type referred to.
2079 */
2080 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2081 checkNonCyclicInternal(pos, t);
2082 }
2085 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2086 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2087 }
2089 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2090 final TypeVar tv;
2091 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
2092 return;
2093 if (seen.contains(t)) {
2094 tv = (TypeVar)t;
2095 tv.bound = types.createErrorType(t);
2096 log.error(pos, "cyclic.inheritance", t);
2097 } else if (t.tag == TYPEVAR) {
2098 tv = (TypeVar)t;
2099 seen = seen.prepend(tv);
2100 for (Type b : types.getBounds(tv))
2101 checkNonCyclic1(pos, b, seen);
2102 }
2103 }
2105 /** Check for cyclic references. Issue an error if the
2106 * symbol of the type referred to has a LOCKED flag set.
2107 *
2108 * @param pos Position to be used for error reporting.
2109 * @param t The type referred to.
2110 * @returns True if the check completed on all attributed classes
2111 */
2112 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2113 boolean complete = true; // was the check complete?
2114 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2115 Symbol c = t.tsym;
2116 if ((c.flags_field & ACYCLIC) != 0) return true;
2118 if ((c.flags_field & LOCKED) != 0) {
2119 noteCyclic(pos, (ClassSymbol)c);
2120 } else if (!c.type.isErroneous()) {
2121 try {
2122 c.flags_field |= LOCKED;
2123 if (c.type.tag == CLASS) {
2124 ClassType clazz = (ClassType)c.type;
2125 if (clazz.interfaces_field != null)
2126 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2127 complete &= checkNonCyclicInternal(pos, l.head);
2128 if (clazz.supertype_field != null) {
2129 Type st = clazz.supertype_field;
2130 if (st != null && st.tag == CLASS)
2131 complete &= checkNonCyclicInternal(pos, st);
2132 }
2133 if (c.owner.kind == TYP)
2134 complete &= checkNonCyclicInternal(pos, c.owner.type);
2135 }
2136 } finally {
2137 c.flags_field &= ~LOCKED;
2138 }
2139 }
2140 if (complete)
2141 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2142 if (complete) c.flags_field |= ACYCLIC;
2143 return complete;
2144 }
2146 /** Note that we found an inheritance cycle. */
2147 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2148 log.error(pos, "cyclic.inheritance", c);
2149 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2150 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2151 Type st = types.supertype(c.type);
2152 if (st.tag == CLASS)
2153 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2154 c.type = types.createErrorType(c, c.type);
2155 c.flags_field |= ACYCLIC;
2156 }
2158 /** Check that all methods which implement some
2159 * method conform to the method they implement.
2160 * @param tree The class definition whose members are checked.
2161 */
2162 void checkImplementations(JCClassDecl tree) {
2163 checkImplementations(tree, tree.sym);
2164 }
2165 //where
2166 /** Check that all methods which implement some
2167 * method in `ic' conform to the method they implement.
2168 */
2169 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2170 ClassSymbol origin = tree.sym;
2171 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2172 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2173 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2174 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2175 if (e.sym.kind == MTH &&
2176 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2177 MethodSymbol absmeth = (MethodSymbol)e.sym;
2178 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2179 if (implmeth != null && implmeth != absmeth &&
2180 (implmeth.owner.flags() & INTERFACE) ==
2181 (origin.flags() & INTERFACE)) {
2182 // don't check if implmeth is in a class, yet
2183 // origin is an interface. This case arises only
2184 // if implmeth is declared in Object. The reason is
2185 // that interfaces really don't inherit from
2186 // Object it's just that the compiler represents
2187 // things that way.
2188 checkOverride(tree, implmeth, absmeth, origin);
2189 }
2190 }
2191 }
2192 }
2193 }
2194 }
2196 /** Check that all abstract methods implemented by a class are
2197 * mutually compatible.
2198 * @param pos Position to be used for error reporting.
2199 * @param c The class whose interfaces are checked.
2200 */
2201 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2202 List<Type> supertypes = types.interfaces(c);
2203 Type supertype = types.supertype(c);
2204 if (supertype.tag == CLASS &&
2205 (supertype.tsym.flags() & ABSTRACT) != 0)
2206 supertypes = supertypes.prepend(supertype);
2207 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2208 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2209 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2210 return;
2211 for (List<Type> m = supertypes; m != l; m = m.tail)
2212 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2213 return;
2214 }
2215 checkCompatibleConcretes(pos, c);
2216 }
2218 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2219 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2220 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2221 // VM allows methods and variables with differing types
2222 if (sym.kind == e.sym.kind &&
2223 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2224 sym != e.sym &&
2225 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2226 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2227 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2228 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2229 return;
2230 }
2231 }
2232 }
2233 }
2235 /** Check that all non-override equivalent methods accessible from 'site'
2236 * are mutually compatible (JLS 8.4.8/9.4.1).
2237 *
2238 * @param pos Position to be used for error reporting.
2239 * @param site The class whose methods are checked.
2240 * @param sym The method symbol to be checked.
2241 */
2242 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2243 ClashFilter cf = new ClashFilter(site);
2244 //for each method m1 that is overridden (directly or indirectly)
2245 //by method 'sym' in 'site'...
2246 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2247 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2248 //...check each method m2 that is a member of 'site'
2249 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2250 if (m2 == m1) continue;
2251 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2252 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2253 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
2254 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2255 sym.flags_field |= CLASH;
2256 String key = m1 == sym ?
2257 "name.clash.same.erasure.no.override" :
2258 "name.clash.same.erasure.no.override.1";
2259 log.error(pos,
2260 key,
2261 sym, sym.location(),
2262 m2, m2.location(),
2263 m1, m1.location());
2264 return;
2265 }
2266 }
2267 }
2268 }
2272 /** Check that all static methods accessible from 'site' are
2273 * mutually compatible (JLS 8.4.8).
2274 *
2275 * @param pos Position to be used for error reporting.
2276 * @param site The class whose methods are checked.
2277 * @param sym The method symbol to be checked.
2278 */
2279 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2280 ClashFilter cf = new ClashFilter(site);
2281 //for each method m1 that is a member of 'site'...
2282 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2283 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2284 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2285 if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
2286 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2287 log.error(pos,
2288 "name.clash.same.erasure.no.hide",
2289 sym, sym.location(),
2290 s, s.location());
2291 return;
2292 }
2293 }
2294 }
2296 //where
2297 private class ClashFilter implements Filter<Symbol> {
2299 Type site;
2301 ClashFilter(Type site) {
2302 this.site = site;
2303 }
2305 boolean shouldSkip(Symbol s) {
2306 return (s.flags() & CLASH) != 0 &&
2307 s.owner == site.tsym;
2308 }
2310 public boolean accepts(Symbol s) {
2311 return s.kind == MTH &&
2312 (s.flags() & SYNTHETIC) == 0 &&
2313 !shouldSkip(s) &&
2314 s.isInheritedIn(site.tsym, types) &&
2315 !s.isConstructor();
2316 }
2317 }
2319 /** Report a conflict between a user symbol and a synthetic symbol.
2320 */
2321 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2322 if (!sym.type.isErroneous()) {
2323 if (warnOnSyntheticConflicts) {
2324 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2325 }
2326 else {
2327 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2328 }
2329 }
2330 }
2332 /** Check that class c does not implement directly or indirectly
2333 * the same parameterized interface with two different argument lists.
2334 * @param pos Position to be used for error reporting.
2335 * @param type The type whose interfaces are checked.
2336 */
2337 void checkClassBounds(DiagnosticPosition pos, Type type) {
2338 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2339 }
2340 //where
2341 /** Enter all interfaces of type `type' into the hash table `seensofar'
2342 * with their class symbol as key and their type as value. Make
2343 * sure no class is entered with two different types.
2344 */
2345 void checkClassBounds(DiagnosticPosition pos,
2346 Map<TypeSymbol,Type> seensofar,
2347 Type type) {
2348 if (type.isErroneous()) return;
2349 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2350 Type it = l.head;
2351 Type oldit = seensofar.put(it.tsym, it);
2352 if (oldit != null) {
2353 List<Type> oldparams = oldit.allparams();
2354 List<Type> newparams = it.allparams();
2355 if (!types.containsTypeEquivalent(oldparams, newparams))
2356 log.error(pos, "cant.inherit.diff.arg",
2357 it.tsym, Type.toString(oldparams),
2358 Type.toString(newparams));
2359 }
2360 checkClassBounds(pos, seensofar, it);
2361 }
2362 Type st = types.supertype(type);
2363 if (st != null) checkClassBounds(pos, seensofar, st);
2364 }
2366 /** Enter interface into into set.
2367 * If it existed already, issue a "repeated interface" error.
2368 */
2369 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2370 if (its.contains(it))
2371 log.error(pos, "repeated.interface");
2372 else {
2373 its.add(it);
2374 }
2375 }
2377 /* *************************************************************************
2378 * Check annotations
2379 **************************************************************************/
2381 /**
2382 * Recursively validate annotations values
2383 */
2384 void validateAnnotationTree(JCTree tree) {
2385 class AnnotationValidator extends TreeScanner {
2386 @Override
2387 public void visitAnnotation(JCAnnotation tree) {
2388 if (!tree.type.isErroneous()) {
2389 super.visitAnnotation(tree);
2390 validateAnnotation(tree);
2391 }
2392 }
2393 }
2394 tree.accept(new AnnotationValidator());
2395 }
2397 /**
2398 * {@literal
2399 * Annotation types are restricted to primitives, String, an
2400 * enum, an annotation, Class, Class<?>, Class<? extends
2401 * Anything>, arrays of the preceding.
2402 * }
2403 */
2404 void validateAnnotationType(JCTree restype) {
2405 // restype may be null if an error occurred, so don't bother validating it
2406 if (restype != null) {
2407 validateAnnotationType(restype.pos(), restype.type);
2408 }
2409 }
2411 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2412 if (type.isPrimitive()) return;
2413 if (types.isSameType(type, syms.stringType)) return;
2414 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2415 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2416 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2417 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2418 validateAnnotationType(pos, types.elemtype(type));
2419 return;
2420 }
2421 log.error(pos, "invalid.annotation.member.type");
2422 }
2424 /**
2425 * "It is also a compile-time error if any method declared in an
2426 * annotation type has a signature that is override-equivalent to
2427 * that of any public or protected method declared in class Object
2428 * or in the interface annotation.Annotation."
2429 *
2430 * @jls 9.6 Annotation Types
2431 */
2432 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2433 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2434 Scope s = sup.tsym.members();
2435 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2436 if (e.sym.kind == MTH &&
2437 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2438 types.overrideEquivalent(m.type, e.sym.type))
2439 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2440 }
2441 }
2442 }
2444 /** Check the annotations of a symbol.
2445 */
2446 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2447 for (JCAnnotation a : annotations)
2448 validateAnnotation(a, s);
2449 }
2451 /** Check an annotation of a symbol.
2452 */
2453 private void validateAnnotation(JCAnnotation a, Symbol s) {
2454 validateAnnotationTree(a);
2456 if (!annotationApplicable(a, s))
2457 log.error(a.pos(), "annotation.type.not.applicable");
2459 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2460 if (!isOverrider(s))
2461 log.error(a.pos(), "method.does.not.override.superclass");
2462 }
2463 }
2465 /**
2466 * Validate the proposed container 'containedBy' on the
2467 * annotation type symbol 's'. Report errors at position
2468 * 'pos'.
2469 *
2470 * @param s The (annotation)type declaration annotated with a @ContainedBy
2471 * @param containerAnno the @ContainedBy on 's'
2472 * @param pos where to report errors
2473 */
2474 public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
2475 Assert.check(types.isSameType(containedBy.type, syms.containedByType));
2477 Type t = null;
2478 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2479 if (!l.isEmpty()) {
2480 Assert.check(l.head.fst.name == names.value);
2481 t = ((Attribute.Class)l.head.snd).getValue();
2482 }
2484 if (t == null) {
2485 log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
2486 return;
2487 }
2489 validateHasContainerFor(t.tsym, s, pos);
2490 validateRetention(t.tsym, s, pos);
2491 validateDocumented(t.tsym, s, pos);
2492 validateInherited(t.tsym, s, pos);
2493 validateTarget(t.tsym, s, pos);
2494 validateDefault(t.tsym, s, pos);
2495 }
2497 /**
2498 * Validate the proposed container 'containerFor' on the
2499 * annotation type symbol 's'. Report errors at position
2500 * 'pos'.
2501 *
2502 * @param s The (annotation)type declaration annotated with a @ContainerFor
2503 * @param containerFor the @ContainedFor on 's'
2504 * @param pos where to report errors
2505 */
2506 public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
2507 Assert.check(types.isSameType(containerFor.type, syms.containerForType));
2509 Type t = null;
2510 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2511 if (!l.isEmpty()) {
2512 Assert.check(l.head.fst.name == names.value);
2513 t = ((Attribute.Class)l.head.snd).getValue();
2514 }
2516 if (t == null) {
2517 log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
2518 return;
2519 }
2521 validateHasContainedBy(t.tsym, s, pos);
2522 }
2524 private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2525 Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
2527 if (containedBy == null) {
2528 log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
2529 return;
2530 }
2532 Type t = null;
2533 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2534 if (!l.isEmpty()) {
2535 Assert.check(l.head.fst.name == names.value);
2536 t = ((Attribute.Class)l.head.snd).getValue();
2537 }
2539 if (t == null) {
2540 log.error(pos, "invalid.container.wrong.containedby", container, contained);
2541 return;
2542 }
2544 if (!types.isSameType(t, contained.type))
2545 log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
2546 }
2548 private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2549 Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
2551 if (containerFor == null) {
2552 log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
2553 return;
2554 }
2556 Type t = null;
2557 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2558 if (!l.isEmpty()) {
2559 Assert.check(l.head.fst.name == names.value);
2560 t = ((Attribute.Class)l.head.snd).getValue();
2561 }
2563 if (t == null) {
2564 log.error(pos, "invalid.container.wrong.containerfor", container, contained);
2565 return;
2566 }
2568 if (!types.isSameType(t, contained.type))
2569 log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
2570 }
2572 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2573 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2574 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2576 boolean error = false;
2577 switch (containedRetention) {
2578 case RUNTIME:
2579 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2580 error = true;
2581 }
2582 break;
2583 case CLASS:
2584 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2585 error = true;
2586 }
2587 }
2588 if (error ) {
2589 log.error(pos, "invalid.containedby.annotation.retention",
2590 container, containerRetention,
2591 contained, containedRetention);
2592 }
2593 }
2595 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2596 if (contained.attribute(syms.documentedType.tsym) != null) {
2597 if (container.attribute(syms.documentedType.tsym) == null) {
2598 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
2599 }
2600 }
2601 }
2603 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2604 if (contained.attribute(syms.inheritedType.tsym) != null) {
2605 if (container.attribute(syms.inheritedType.tsym) == null) {
2606 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
2607 }
2608 }
2609 }
2611 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2612 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2614 // If contained has no Target, we are done
2615 if (containedTarget == null) {
2616 return;
2617 }
2619 // If contained has Target m1, container must have a Target
2620 // annotation, m2, and m2 must be a subset of m1. (This is
2621 // trivially true if contained has no target as per above).
2623 // contained has target, but container has not, error
2624 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2625 if (containerTarget == null) {
2626 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2627 return;
2628 }
2630 Set<Name> containerTargets = new HashSet<Name>();
2631 for (Attribute app : containerTarget.values) {
2632 if (!(app instanceof Attribute.Enum)) {
2633 continue; // recovery
2634 }
2635 Attribute.Enum e = (Attribute.Enum)app;
2636 containerTargets.add(e.value.name);
2637 }
2639 Set<Name> containedTargets = new HashSet<Name>();
2640 for (Attribute app : containedTarget.values) {
2641 if (!(app instanceof Attribute.Enum)) {
2642 continue; // recovery
2643 }
2644 Attribute.Enum e = (Attribute.Enum)app;
2645 containedTargets.add(e.value.name);
2646 }
2648 if (!isTargetSubset(containedTargets, containerTargets)) {
2649 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2650 }
2651 }
2653 /** Checks that t is a subset of s, with respect to ElementType
2654 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2655 */
2656 private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
2657 // Check that all elements in t are present in s
2658 for (Name n2 : t) {
2659 boolean currentElementOk = false;
2660 for (Name n1 : s) {
2661 if (n1 == n2) {
2662 currentElementOk = true;
2663 break;
2664 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2665 currentElementOk = true;
2666 break;
2667 }
2668 }
2669 if (!currentElementOk)
2670 return false;
2671 }
2672 return true;
2673 }
2675 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2676 // validate that all other elements of containing type has defaults
2677 Scope scope = container.members();
2678 for(Symbol elm : scope.getElements()) {
2679 if (elm.name != names.value &&
2680 elm.kind == Kinds.MTH &&
2681 ((MethodSymbol)elm).defaultValue == null) {
2682 log.error(pos,
2683 "invalid.containedby.annotation.elem.nondefault",
2684 container,
2685 elm);
2686 }
2687 }
2688 }
2690 /** Is s a method symbol that overrides a method in a superclass? */
2691 boolean isOverrider(Symbol s) {
2692 if (s.kind != MTH || s.isStatic())
2693 return false;
2694 MethodSymbol m = (MethodSymbol)s;
2695 TypeSymbol owner = (TypeSymbol)m.owner;
2696 for (Type sup : types.closure(owner.type)) {
2697 if (sup == owner.type)
2698 continue; // skip "this"
2699 Scope scope = sup.tsym.members();
2700 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2701 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2702 return true;
2703 }
2704 }
2705 return false;
2706 }
2708 /** Is the annotation applicable to the symbol? */
2709 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2710 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2711 if (arr == null) {
2712 return true;
2713 }
2714 for (Attribute app : arr.values) {
2715 if (!(app instanceof Attribute.Enum)) return true; // recovery
2716 Attribute.Enum e = (Attribute.Enum) app;
2717 if (e.value.name == names.TYPE)
2718 { if (s.kind == TYP) return true; }
2719 else if (e.value.name == names.FIELD)
2720 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2721 else if (e.value.name == names.METHOD)
2722 { if (s.kind == MTH && !s.isConstructor()) return true; }
2723 else if (e.value.name == names.PARAMETER)
2724 { if (s.kind == VAR &&
2725 s.owner.kind == MTH &&
2726 (s.flags() & PARAMETER) != 0)
2727 return true;
2728 }
2729 else if (e.value.name == names.CONSTRUCTOR)
2730 { if (s.kind == MTH && s.isConstructor()) return true; }
2731 else if (e.value.name == names.LOCAL_VARIABLE)
2732 { if (s.kind == VAR && s.owner.kind == MTH &&
2733 (s.flags() & PARAMETER) == 0)
2734 return true;
2735 }
2736 else if (e.value.name == names.ANNOTATION_TYPE)
2737 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2738 return true;
2739 }
2740 else if (e.value.name == names.PACKAGE)
2741 { if (s.kind == PCK) return true; }
2742 else if (e.value.name == names.TYPE_USE)
2743 { if (s.kind == TYP ||
2744 s.kind == VAR ||
2745 (s.kind == MTH && !s.isConstructor() &&
2746 s.type.getReturnType().tag != VOID))
2747 return true;
2748 }
2749 else
2750 return true; // recovery
2751 }
2752 return false;
2753 }
2756 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2757 Attribute.Compound atTarget =
2758 s.attribute(syms.annotationTargetType.tsym);
2759 if (atTarget == null) return null; // ok, is applicable
2760 Attribute atValue = atTarget.member(names.value);
2761 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2762 return (Attribute.Array) atValue;
2763 }
2765 /** Check an annotation value.
2766 */
2767 public void validateAnnotation(JCAnnotation a) {
2768 // collect an inventory of the members (sorted alphabetically)
2769 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2770 public int compare(Symbol t, Symbol t1) {
2771 return t.name.compareTo(t1.name);
2772 }
2773 });
2774 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2775 e != null;
2776 e = e.sibling)
2777 if (e.sym.kind == MTH)
2778 members.add((MethodSymbol) e.sym);
2780 // count them off as they're annotated
2781 for (JCTree arg : a.args) {
2782 if (!arg.hasTag(ASSIGN)) continue; // recovery
2783 JCAssign assign = (JCAssign) arg;
2784 Symbol m = TreeInfo.symbol(assign.lhs);
2785 if (m == null || m.type.isErroneous()) continue;
2786 if (!members.remove(m))
2787 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2788 m.name, a.type);
2789 }
2791 // all the remaining ones better have default values
2792 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2793 for (MethodSymbol m : members) {
2794 if (m.defaultValue == null && !m.type.isErroneous()) {
2795 missingDefaults.append(m.name);
2796 }
2797 }
2798 if (missingDefaults.nonEmpty()) {
2799 String key = (missingDefaults.size() > 1)
2800 ? "annotation.missing.default.value.1"
2801 : "annotation.missing.default.value";
2802 log.error(a.pos(), key, a.type, missingDefaults);
2803 }
2805 // special case: java.lang.annotation.Target must not have
2806 // repeated values in its value member
2807 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2808 a.args.tail == null)
2809 return;
2811 if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
2812 JCAssign assign = (JCAssign) a.args.head;
2813 Symbol m = TreeInfo.symbol(assign.lhs);
2814 if (m.name != names.value) return;
2815 JCTree rhs = assign.rhs;
2816 if (!rhs.hasTag(NEWARRAY)) return;
2817 JCNewArray na = (JCNewArray) rhs;
2818 Set<Symbol> targets = new HashSet<Symbol>();
2819 for (JCTree elem : na.elems) {
2820 if (!targets.add(TreeInfo.symbol(elem))) {
2821 log.error(elem.pos(), "repeated.annotation.target");
2822 }
2823 }
2824 }
2826 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2827 if (allowAnnotations &&
2828 lint.isEnabled(LintCategory.DEP_ANN) &&
2829 (s.flags() & DEPRECATED) != 0 &&
2830 !syms.deprecatedType.isErroneous() &&
2831 s.attribute(syms.deprecatedType.tsym) == null) {
2832 log.warning(LintCategory.DEP_ANN,
2833 pos, "missing.deprecated.annotation");
2834 }
2835 }
2837 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2838 if ((s.flags() & DEPRECATED) != 0 &&
2839 (other.flags() & DEPRECATED) == 0 &&
2840 s.outermostClass() != other.outermostClass()) {
2841 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2842 @Override
2843 public void report() {
2844 warnDeprecated(pos, s);
2845 }
2846 });
2847 }
2848 }
2850 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2851 if ((s.flags() & PROPRIETARY) != 0) {
2852 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2853 public void report() {
2854 if (enableSunApiLintControl)
2855 warnSunApi(pos, "sun.proprietary", s);
2856 else
2857 log.mandatoryWarning(pos, "sun.proprietary", s);
2858 }
2859 });
2860 }
2861 }
2863 /* *************************************************************************
2864 * Check for recursive annotation elements.
2865 **************************************************************************/
2867 /** Check for cycles in the graph of annotation elements.
2868 */
2869 void checkNonCyclicElements(JCClassDecl tree) {
2870 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2871 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2872 try {
2873 tree.sym.flags_field |= LOCKED;
2874 for (JCTree def : tree.defs) {
2875 if (!def.hasTag(METHODDEF)) continue;
2876 JCMethodDecl meth = (JCMethodDecl)def;
2877 checkAnnotationResType(meth.pos(), meth.restype.type);
2878 }
2879 } finally {
2880 tree.sym.flags_field &= ~LOCKED;
2881 tree.sym.flags_field |= ACYCLIC_ANN;
2882 }
2883 }
2885 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2886 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2887 return;
2888 if ((tsym.flags_field & LOCKED) != 0) {
2889 log.error(pos, "cyclic.annotation.element");
2890 return;
2891 }
2892 try {
2893 tsym.flags_field |= LOCKED;
2894 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2895 Symbol s = e.sym;
2896 if (s.kind != Kinds.MTH)
2897 continue;
2898 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2899 }
2900 } finally {
2901 tsym.flags_field &= ~LOCKED;
2902 tsym.flags_field |= ACYCLIC_ANN;
2903 }
2904 }
2906 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2907 switch (type.tag) {
2908 case TypeTags.CLASS:
2909 if ((type.tsym.flags() & ANNOTATION) != 0)
2910 checkNonCyclicElementsInternal(pos, type.tsym);
2911 break;
2912 case TypeTags.ARRAY:
2913 checkAnnotationResType(pos, types.elemtype(type));
2914 break;
2915 default:
2916 break; // int etc
2917 }
2918 }
2920 /* *************************************************************************
2921 * Check for cycles in the constructor call graph.
2922 **************************************************************************/
2924 /** Check for cycles in the graph of constructors calling other
2925 * constructors.
2926 */
2927 void checkCyclicConstructors(JCClassDecl tree) {
2928 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2930 // enter each constructor this-call into the map
2931 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2932 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2933 if (app == null) continue;
2934 JCMethodDecl meth = (JCMethodDecl) l.head;
2935 if (TreeInfo.name(app.meth) == names._this) {
2936 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2937 } else {
2938 meth.sym.flags_field |= ACYCLIC;
2939 }
2940 }
2942 // Check for cycles in the map
2943 Symbol[] ctors = new Symbol[0];
2944 ctors = callMap.keySet().toArray(ctors);
2945 for (Symbol caller : ctors) {
2946 checkCyclicConstructor(tree, caller, callMap);
2947 }
2948 }
2950 /** Look in the map to see if the given constructor is part of a
2951 * call cycle.
2952 */
2953 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2954 Map<Symbol,Symbol> callMap) {
2955 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2956 if ((ctor.flags_field & LOCKED) != 0) {
2957 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2958 "recursive.ctor.invocation");
2959 } else {
2960 ctor.flags_field |= LOCKED;
2961 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2962 ctor.flags_field &= ~LOCKED;
2963 }
2964 ctor.flags_field |= ACYCLIC;
2965 }
2966 }
2968 /* *************************************************************************
2969 * Miscellaneous
2970 **************************************************************************/
2972 /**
2973 * Return the opcode of the operator but emit an error if it is an
2974 * error.
2975 * @param pos position for error reporting.
2976 * @param operator an operator
2977 * @param tag a tree tag
2978 * @param left type of left hand side
2979 * @param right type of right hand side
2980 */
2981 int checkOperator(DiagnosticPosition pos,
2982 OperatorSymbol operator,
2983 JCTree.Tag tag,
2984 Type left,
2985 Type right) {
2986 if (operator.opcode == ByteCodes.error) {
2987 log.error(pos,
2988 "operator.cant.be.applied.1",
2989 treeinfo.operatorName(tag),
2990 left, right);
2991 }
2992 return operator.opcode;
2993 }
2996 /**
2997 * Check for division by integer constant zero
2998 * @param pos Position for error reporting.
2999 * @param operator The operator for the expression
3000 * @param operand The right hand operand for the expression
3001 */
3002 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3003 if (operand.constValue() != null
3004 && lint.isEnabled(LintCategory.DIVZERO)
3005 && operand.tag <= LONG
3006 && ((Number) (operand.constValue())).longValue() == 0) {
3007 int opc = ((OperatorSymbol)operator).opcode;
3008 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3009 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3010 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3011 }
3012 }
3013 }
3015 /**
3016 * Check for empty statements after if
3017 */
3018 void checkEmptyIf(JCIf tree) {
3019 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3020 lint.isEnabled(LintCategory.EMPTY))
3021 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3022 }
3024 /** Check that symbol is unique in given scope.
3025 * @param pos Position for error reporting.
3026 * @param sym The symbol.
3027 * @param s The scope.
3028 */
3029 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3030 if (sym.type.isErroneous())
3031 return true;
3032 if (sym.owner.name == names.any) return false;
3033 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3034 if (sym != e.sym &&
3035 (e.sym.flags() & CLASH) == 0 &&
3036 sym.kind == e.sym.kind &&
3037 sym.name != names.error &&
3038 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3039 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3040 varargsDuplicateError(pos, sym, e.sym);
3041 return true;
3042 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3043 duplicateErasureError(pos, sym, e.sym);
3044 sym.flags_field |= CLASH;
3045 return true;
3046 } else {
3047 duplicateError(pos, e.sym);
3048 return false;
3049 }
3050 }
3051 }
3052 return true;
3053 }
3055 /** Report duplicate declaration error.
3056 */
3057 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3058 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3059 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3060 }
3061 }
3063 /** Check that single-type import is not already imported or top-level defined,
3064 * but make an exception for two single-type imports which denote the same type.
3065 * @param pos Position for error reporting.
3066 * @param sym The symbol.
3067 * @param s The scope
3068 */
3069 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3070 return checkUniqueImport(pos, sym, s, false);
3071 }
3073 /** Check that static single-type import is not already imported or top-level defined,
3074 * but make an exception for two single-type imports which denote the same type.
3075 * @param pos Position for error reporting.
3076 * @param sym The symbol.
3077 * @param s The scope
3078 * @param staticImport Whether or not this was a static import
3079 */
3080 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3081 return checkUniqueImport(pos, sym, s, true);
3082 }
3084 /** Check that single-type import is not already imported or top-level defined,
3085 * but make an exception for two single-type imports which denote the same type.
3086 * @param pos Position for error reporting.
3087 * @param sym The symbol.
3088 * @param s The scope.
3089 * @param staticImport Whether or not this was a static import
3090 */
3091 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3092 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3093 // is encountered class entered via a class declaration?
3094 boolean isClassDecl = e.scope == s;
3095 if ((isClassDecl || sym != e.sym) &&
3096 sym.kind == e.sym.kind &&
3097 sym.name != names.error) {
3098 if (!e.sym.type.isErroneous()) {
3099 String what = e.sym.toString();
3100 if (!isClassDecl) {
3101 if (staticImport)
3102 log.error(pos, "already.defined.static.single.import", what);
3103 else
3104 log.error(pos, "already.defined.single.import", what);
3105 }
3106 else if (sym != e.sym)
3107 log.error(pos, "already.defined.this.unit", what);
3108 }
3109 return false;
3110 }
3111 }
3112 return true;
3113 }
3115 /** Check that a qualified name is in canonical form (for import decls).
3116 */
3117 public void checkCanonical(JCTree tree) {
3118 if (!isCanonical(tree))
3119 log.error(tree.pos(), "import.requires.canonical",
3120 TreeInfo.symbol(tree));
3121 }
3122 // where
3123 private boolean isCanonical(JCTree tree) {
3124 while (tree.hasTag(SELECT)) {
3125 JCFieldAccess s = (JCFieldAccess) tree;
3126 if (s.sym.owner != TreeInfo.symbol(s.selected))
3127 return false;
3128 tree = s.selected;
3129 }
3130 return true;
3131 }
3133 private class ConversionWarner extends Warner {
3134 final String uncheckedKey;
3135 final Type found;
3136 final Type expected;
3137 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3138 super(pos);
3139 this.uncheckedKey = uncheckedKey;
3140 this.found = found;
3141 this.expected = expected;
3142 }
3144 @Override
3145 public void warn(LintCategory lint) {
3146 boolean warned = this.warned;
3147 super.warn(lint);
3148 if (warned) return; // suppress redundant diagnostics
3149 switch (lint) {
3150 case UNCHECKED:
3151 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3152 break;
3153 case VARARGS:
3154 if (method != null &&
3155 method.attribute(syms.trustMeType.tsym) != null &&
3156 isTrustMeAllowedOnMethod(method) &&
3157 !types.isReifiable(method.type.getParameterTypes().last())) {
3158 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3159 }
3160 break;
3161 default:
3162 throw new AssertionError("Unexpected lint: " + lint);
3163 }
3164 }
3165 }
3167 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3168 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3169 }
3171 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3172 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3173 }
3174 }