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