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