Sat, 06 Oct 2012 10:35:38 +0100
7177386: Add attribution support for method references
Summary: Add type-checking/lookup routines for method references
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 valid qualifier for a constructor reference expression
652 */
653 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
654 t = checkClassType(pos, t);
655 if (t.tag == CLASS) {
656 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
657 log.error(pos, "abstract.cant.be.instantiated");
658 t = types.createErrorType(t);
659 } else if ((t.tsym.flags() & ENUM) != 0) {
660 log.error(pos, "enum.cant.be.instantiated");
661 t = types.createErrorType(t);
662 }
663 }
664 return t;
665 }
667 /** Check that type is a class or interface type.
668 * @param pos Position to be used for error reporting.
669 * @param t The type to be checked.
670 * @param noBounds True if type bounds are illegal here.
671 */
672 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
673 t = checkClassType(pos, t);
674 if (noBounds && t.isParameterized()) {
675 List<Type> args = t.getTypeArguments();
676 while (args.nonEmpty()) {
677 if (args.head.tag == WILDCARD)
678 return typeTagError(pos,
679 diags.fragment("type.req.exact"),
680 args.head);
681 args = args.tail;
682 }
683 }
684 return t;
685 }
687 /** Check that type is a reifiable class, interface or array type.
688 * @param pos Position to be used for error reporting.
689 * @param t The type to be checked.
690 */
691 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
692 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
693 return typeTagError(pos,
694 diags.fragment("type.req.class.array"),
695 t);
696 } else if (!types.isReifiable(t)) {
697 log.error(pos, "illegal.generic.type.for.instof");
698 return types.createErrorType(t);
699 } else {
700 return t;
701 }
702 }
704 /** Check that type is a reference type, i.e. a class, interface or array type
705 * or a type variable.
706 * @param pos Position to be used for error reporting.
707 * @param t The type to be checked.
708 */
709 Type checkRefType(DiagnosticPosition pos, Type t) {
710 switch (t.tag) {
711 case CLASS:
712 case ARRAY:
713 case TYPEVAR:
714 case WILDCARD:
715 case ERROR:
716 return t;
717 default:
718 return typeTagError(pos,
719 diags.fragment("type.req.ref"),
720 t);
721 }
722 }
724 /** Check that each type is a reference type, i.e. a class, interface or array type
725 * or a type variable.
726 * @param trees Original trees, used for error reporting.
727 * @param types The types to be checked.
728 */
729 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
730 List<JCExpression> tl = trees;
731 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
732 l.head = checkRefType(tl.head.pos(), l.head);
733 tl = tl.tail;
734 }
735 return types;
736 }
738 /** Check that type is a null or reference type.
739 * @param pos Position to be used for error reporting.
740 * @param t The type to be checked.
741 */
742 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
743 switch (t.tag) {
744 case CLASS:
745 case ARRAY:
746 case TYPEVAR:
747 case WILDCARD:
748 case BOT:
749 case ERROR:
750 return t;
751 default:
752 return typeTagError(pos,
753 diags.fragment("type.req.ref"),
754 t);
755 }
756 }
758 /** Check that flag set does not contain elements of two conflicting sets. s
759 * Return true if it doesn't.
760 * @param pos Position to be used for error reporting.
761 * @param flags The set of flags to be checked.
762 * @param set1 Conflicting flags set #1.
763 * @param set2 Conflicting flags set #2.
764 */
765 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
766 if ((flags & set1) != 0 && (flags & set2) != 0) {
767 log.error(pos,
768 "illegal.combination.of.modifiers",
769 asFlagSet(TreeInfo.firstFlag(flags & set1)),
770 asFlagSet(TreeInfo.firstFlag(flags & set2)));
771 return false;
772 } else
773 return true;
774 }
776 /** Check that usage of diamond operator is correct (i.e. diamond should not
777 * be used with non-generic classes or in anonymous class creation expressions)
778 */
779 Type checkDiamond(JCNewClass tree, Type t) {
780 if (!TreeInfo.isDiamond(tree) ||
781 t.isErroneous()) {
782 return checkClassType(tree.clazz.pos(), t, true);
783 } else if (tree.def != null) {
784 log.error(tree.clazz.pos(),
785 "cant.apply.diamond.1",
786 t, diags.fragment("diamond.and.anon.class", t));
787 return types.createErrorType(t);
788 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
789 log.error(tree.clazz.pos(),
790 "cant.apply.diamond.1",
791 t, diags.fragment("diamond.non.generic", t));
792 return types.createErrorType(t);
793 } else if (tree.typeargs != null &&
794 tree.typeargs.nonEmpty()) {
795 log.error(tree.clazz.pos(),
796 "cant.apply.diamond.1",
797 t, diags.fragment("diamond.and.explicit.params", t));
798 return types.createErrorType(t);
799 } else {
800 return t;
801 }
802 }
804 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
805 MethodSymbol m = tree.sym;
806 if (!allowSimplifiedVarargs) return;
807 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
808 Type varargElemType = null;
809 if (m.isVarArgs()) {
810 varargElemType = types.elemtype(tree.params.last().type);
811 }
812 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
813 if (varargElemType != null) {
814 log.error(tree,
815 "varargs.invalid.trustme.anno",
816 syms.trustMeType.tsym,
817 diags.fragment("varargs.trustme.on.virtual.varargs", m));
818 } else {
819 log.error(tree,
820 "varargs.invalid.trustme.anno",
821 syms.trustMeType.tsym,
822 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
823 }
824 } else if (hasTrustMeAnno && varargElemType != null &&
825 types.isReifiable(varargElemType)) {
826 warnUnsafeVararg(tree,
827 "varargs.redundant.trustme.anno",
828 syms.trustMeType.tsym,
829 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
830 }
831 else if (!hasTrustMeAnno && varargElemType != null &&
832 !types.isReifiable(varargElemType)) {
833 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
834 }
835 }
836 //where
837 private boolean isTrustMeAllowedOnMethod(Symbol s) {
838 return (s.flags() & VARARGS) != 0 &&
839 (s.isConstructor() ||
840 (s.flags() & (STATIC | FINAL)) != 0);
841 }
843 Type checkMethod(Type owntype,
844 Symbol sym,
845 Env<AttrContext> env,
846 final List<JCExpression> argtrees,
847 List<Type> argtypes,
848 boolean useVarargs,
849 boolean unchecked) {
850 // System.out.println("call : " + env.tree);
851 // System.out.println("method : " + owntype);
852 // System.out.println("actuals: " + argtypes);
853 List<Type> formals = owntype.getParameterTypes();
854 Type last = useVarargs ? formals.last() : null;
855 if (sym.name==names.init &&
856 sym.owner == syms.enumSym)
857 formals = formals.tail.tail;
858 List<JCExpression> args = argtrees;
859 DeferredAttr.DeferredTypeMap checkDeferredMap =
860 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
861 if (args != null) {
862 //this is null when type-checking a method reference
863 while (formals.head != last) {
864 JCTree arg = args.head;
865 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
866 assertConvertible(arg, arg.type, formals.head, warn);
867 args = args.tail;
868 formals = formals.tail;
869 }
870 if (useVarargs) {
871 Type varArg = types.elemtype(last);
872 while (args.tail != null) {
873 JCTree arg = args.head;
874 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
875 assertConvertible(arg, arg.type, varArg, warn);
876 args = args.tail;
877 }
878 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
879 // non-varargs call to varargs method
880 Type varParam = owntype.getParameterTypes().last();
881 Type lastArg = checkDeferredMap.apply(argtypes.last());
882 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
883 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
884 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
885 types.elemtype(varParam), varParam);
886 }
887 }
888 if (unchecked) {
889 warnUnchecked(env.tree.pos(),
890 "unchecked.meth.invocation.applied",
891 kindName(sym),
892 sym.name,
893 rs.methodArguments(sym.type.getParameterTypes()),
894 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
895 kindName(sym.location()),
896 sym.location());
897 owntype = new MethodType(owntype.getParameterTypes(),
898 types.erasure(owntype.getReturnType()),
899 types.erasure(owntype.getThrownTypes()),
900 syms.methodClass);
901 }
902 if (useVarargs) {
903 JCTree tree = env.tree;
904 Type argtype = owntype.getParameterTypes().last();
905 if (!types.isReifiable(argtype) &&
906 (!allowSimplifiedVarargs ||
907 sym.attribute(syms.trustMeType.tsym) == null ||
908 !isTrustMeAllowedOnMethod(sym))) {
909 warnUnchecked(env.tree.pos(),
910 "unchecked.generic.array.creation",
911 argtype);
912 }
913 Type elemtype = types.elemtype(argtype);
914 switch (tree.getTag()) {
915 case APPLY:
916 ((JCMethodInvocation) tree).varargsElement = elemtype;
917 break;
918 case NEWCLASS:
919 ((JCNewClass) tree).varargsElement = elemtype;
920 break;
921 case REFERENCE:
922 ((JCMemberReference) tree).varargsElement = elemtype;
923 break;
924 default:
925 throw new AssertionError(""+tree);
926 }
927 }
928 return owntype;
929 }
930 //where
931 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
932 if (types.isConvertible(actual, formal, warn))
933 return;
935 if (formal.isCompound()
936 && types.isSubtype(actual, types.supertype(formal))
937 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
938 return;
939 }
941 void checkAccessibleFunctionalDescriptor(DiagnosticPosition pos, Env<AttrContext> env, Type desc) {
942 AccessChecker accessChecker = new AccessChecker(env);
943 //check args accessibility (only if implicit parameter types)
944 for (Type arg : desc.getParameterTypes()) {
945 if (!accessChecker.visit(arg)) {
946 log.error(pos, "cant.access.arg.type.in.functional.desc", arg);
947 return;
948 }
949 }
950 //check return type accessibility
951 if (!accessChecker.visit(desc.getReturnType())) {
952 log.error(pos, "cant.access.return.in.functional.desc", desc.getReturnType());
953 return;
954 }
955 //check thrown types accessibility
956 for (Type thrown : desc.getThrownTypes()) {
957 if (!accessChecker.visit(thrown)) {
958 log.error(pos, "cant.access.thrown.in.functional.desc", thrown);
959 return;
960 }
961 }
962 }
964 class AccessChecker extends Types.UnaryVisitor<Boolean> {
966 Env<AttrContext> env;
968 AccessChecker(Env<AttrContext> env) {
969 this.env = env;
970 }
972 Boolean visit(List<Type> ts) {
973 for (Type t : ts) {
974 if (!visit(t))
975 return false;
976 }
977 return true;
978 }
980 public Boolean visitType(Type t, Void s) {
981 return true;
982 }
984 @Override
985 public Boolean visitArrayType(ArrayType t, Void s) {
986 return visit(t.elemtype);
987 }
989 @Override
990 public Boolean visitClassType(ClassType t, Void s) {
991 return rs.isAccessible(env, t, true) &&
992 visit(t.getTypeArguments());
993 }
995 @Override
996 public Boolean visitWildcardType(WildcardType t, Void s) {
997 return visit(t.type);
998 }
999 };
1000 /**
1001 * Check that type 't' is a valid instantiation of a generic class
1002 * (see JLS 4.5)
1003 *
1004 * @param t class type to be checked
1005 * @return true if 't' is well-formed
1006 */
1007 public boolean checkValidGenericType(Type t) {
1008 return firstIncompatibleTypeArg(t) == null;
1009 }
1010 //WHERE
1011 private Type firstIncompatibleTypeArg(Type type) {
1012 List<Type> formals = type.tsym.type.allparams();
1013 List<Type> actuals = type.allparams();
1014 List<Type> args = type.getTypeArguments();
1015 List<Type> forms = type.tsym.type.getTypeArguments();
1016 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
1018 // For matching pairs of actual argument types `a' and
1019 // formal type parameters with declared bound `b' ...
1020 while (args.nonEmpty() && forms.nonEmpty()) {
1021 // exact type arguments needs to know their
1022 // bounds (for upper and lower bound
1023 // calculations). So we create new bounds where
1024 // type-parameters are replaced with actuals argument types.
1025 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1026 args = args.tail;
1027 forms = forms.tail;
1028 }
1030 args = type.getTypeArguments();
1031 List<Type> tvars_cap = types.substBounds(formals,
1032 formals,
1033 types.capture(type).allparams());
1034 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1035 // Let the actual arguments know their bound
1036 args.head.withTypeVar((TypeVar)tvars_cap.head);
1037 args = args.tail;
1038 tvars_cap = tvars_cap.tail;
1039 }
1041 args = type.getTypeArguments();
1042 List<Type> bounds = bounds_buf.toList();
1044 while (args.nonEmpty() && bounds.nonEmpty()) {
1045 Type actual = args.head;
1046 if (!isTypeArgErroneous(actual) &&
1047 !bounds.head.isErroneous() &&
1048 !checkExtends(actual, bounds.head)) {
1049 return args.head;
1050 }
1051 args = args.tail;
1052 bounds = bounds.tail;
1053 }
1055 args = type.getTypeArguments();
1056 bounds = bounds_buf.toList();
1058 for (Type arg : types.capture(type).getTypeArguments()) {
1059 if (arg.tag == TYPEVAR &&
1060 arg.getUpperBound().isErroneous() &&
1061 !bounds.head.isErroneous() &&
1062 !isTypeArgErroneous(args.head)) {
1063 return args.head;
1064 }
1065 bounds = bounds.tail;
1066 args = args.tail;
1067 }
1069 return null;
1070 }
1071 //where
1072 boolean isTypeArgErroneous(Type t) {
1073 return isTypeArgErroneous.visit(t);
1074 }
1076 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1077 public Boolean visitType(Type t, Void s) {
1078 return t.isErroneous();
1079 }
1080 @Override
1081 public Boolean visitTypeVar(TypeVar t, Void s) {
1082 return visit(t.getUpperBound());
1083 }
1084 @Override
1085 public Boolean visitCapturedType(CapturedType t, Void s) {
1086 return visit(t.getUpperBound()) ||
1087 visit(t.getLowerBound());
1088 }
1089 @Override
1090 public Boolean visitWildcardType(WildcardType t, Void s) {
1091 return visit(t.type);
1092 }
1093 };
1095 /** Check that given modifiers are legal for given symbol and
1096 * return modifiers together with any implicit modififiers for that symbol.
1097 * Warning: we can't use flags() here since this method
1098 * is called during class enter, when flags() would cause a premature
1099 * completion.
1100 * @param pos Position to be used for error reporting.
1101 * @param flags The set of modifiers given in a definition.
1102 * @param sym The defined symbol.
1103 */
1104 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1105 long mask;
1106 long implicit = 0;
1107 switch (sym.kind) {
1108 case VAR:
1109 if (sym.owner.kind != TYP)
1110 mask = LocalVarFlags;
1111 else if ((sym.owner.flags_field & INTERFACE) != 0)
1112 mask = implicit = InterfaceVarFlags;
1113 else
1114 mask = VarFlags;
1115 break;
1116 case MTH:
1117 if (sym.name == names.init) {
1118 if ((sym.owner.flags_field & ENUM) != 0) {
1119 // enum constructors cannot be declared public or
1120 // protected and must be implicitly or explicitly
1121 // private
1122 implicit = PRIVATE;
1123 mask = PRIVATE;
1124 } else
1125 mask = ConstructorFlags;
1126 } else if ((sym.owner.flags_field & INTERFACE) != 0)
1127 mask = implicit = InterfaceMethodFlags;
1128 else {
1129 mask = MethodFlags;
1130 }
1131 // Imply STRICTFP if owner has STRICTFP set.
1132 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1133 implicit |= sym.owner.flags_field & STRICTFP;
1134 break;
1135 case TYP:
1136 if (sym.isLocal()) {
1137 mask = LocalClassFlags;
1138 if (sym.name.isEmpty()) { // Anonymous class
1139 // Anonymous classes in static methods are themselves static;
1140 // that's why we admit STATIC here.
1141 mask |= STATIC;
1142 // JLS: Anonymous classes are final.
1143 implicit |= FINAL;
1144 }
1145 if ((sym.owner.flags_field & STATIC) == 0 &&
1146 (flags & ENUM) != 0)
1147 log.error(pos, "enums.must.be.static");
1148 } else if (sym.owner.kind == TYP) {
1149 mask = MemberClassFlags;
1150 if (sym.owner.owner.kind == PCK ||
1151 (sym.owner.flags_field & STATIC) != 0)
1152 mask |= STATIC;
1153 else if ((flags & ENUM) != 0)
1154 log.error(pos, "enums.must.be.static");
1155 // Nested interfaces and enums are always STATIC (Spec ???)
1156 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1157 } else {
1158 mask = ClassFlags;
1159 }
1160 // Interfaces are always ABSTRACT
1161 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1163 if ((flags & ENUM) != 0) {
1164 // enums can't be declared abstract or final
1165 mask &= ~(ABSTRACT | FINAL);
1166 implicit |= implicitEnumFinalFlag(tree);
1167 }
1168 // Imply STRICTFP if owner has STRICTFP set.
1169 implicit |= sym.owner.flags_field & STRICTFP;
1170 break;
1171 default:
1172 throw new AssertionError();
1173 }
1174 long illegal = flags & StandardFlags & ~mask;
1175 if (illegal != 0) {
1176 if ((illegal & INTERFACE) != 0) {
1177 log.error(pos, "intf.not.allowed.here");
1178 mask |= INTERFACE;
1179 }
1180 else {
1181 log.error(pos,
1182 "mod.not.allowed.here", asFlagSet(illegal));
1183 }
1184 }
1185 else if ((sym.kind == TYP ||
1186 // ISSUE: Disallowing abstract&private is no longer appropriate
1187 // in the presence of inner classes. Should it be deleted here?
1188 checkDisjoint(pos, flags,
1189 ABSTRACT,
1190 PRIVATE | STATIC))
1191 &&
1192 checkDisjoint(pos, flags,
1193 ABSTRACT | INTERFACE,
1194 FINAL | NATIVE | SYNCHRONIZED)
1195 &&
1196 checkDisjoint(pos, flags,
1197 PUBLIC,
1198 PRIVATE | PROTECTED)
1199 &&
1200 checkDisjoint(pos, flags,
1201 PRIVATE,
1202 PUBLIC | PROTECTED)
1203 &&
1204 checkDisjoint(pos, flags,
1205 FINAL,
1206 VOLATILE)
1207 &&
1208 (sym.kind == TYP ||
1209 checkDisjoint(pos, flags,
1210 ABSTRACT | NATIVE,
1211 STRICTFP))) {
1212 // skip
1213 }
1214 return flags & (mask | ~StandardFlags) | implicit;
1215 }
1218 /** Determine if this enum should be implicitly final.
1219 *
1220 * If the enum has no specialized enum contants, it is final.
1221 *
1222 * If the enum does have specialized enum contants, it is
1223 * <i>not</i> final.
1224 */
1225 private long implicitEnumFinalFlag(JCTree tree) {
1226 if (!tree.hasTag(CLASSDEF)) return 0;
1227 class SpecialTreeVisitor extends JCTree.Visitor {
1228 boolean specialized;
1229 SpecialTreeVisitor() {
1230 this.specialized = false;
1231 };
1233 @Override
1234 public void visitTree(JCTree tree) { /* no-op */ }
1236 @Override
1237 public void visitVarDef(JCVariableDecl tree) {
1238 if ((tree.mods.flags & ENUM) != 0) {
1239 if (tree.init instanceof JCNewClass &&
1240 ((JCNewClass) tree.init).def != null) {
1241 specialized = true;
1242 }
1243 }
1244 }
1245 }
1247 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1248 JCClassDecl cdef = (JCClassDecl) tree;
1249 for (JCTree defs: cdef.defs) {
1250 defs.accept(sts);
1251 if (sts.specialized) return 0;
1252 }
1253 return FINAL;
1254 }
1256 /* *************************************************************************
1257 * Type Validation
1258 **************************************************************************/
1260 /** Validate a type expression. That is,
1261 * check that all type arguments of a parametric type are within
1262 * their bounds. This must be done in a second phase after type attributon
1263 * since a class might have a subclass as type parameter bound. E.g:
1264 *
1265 * class B<A extends C> { ... }
1266 * class C extends B<C> { ... }
1267 *
1268 * and we can't make sure that the bound is already attributed because
1269 * of possible cycles.
1270 *
1271 * Visitor method: Validate a type expression, if it is not null, catching
1272 * and reporting any completion failures.
1273 */
1274 void validate(JCTree tree, Env<AttrContext> env) {
1275 validate(tree, env, true);
1276 }
1277 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1278 new Validator(env).validateTree(tree, checkRaw, true);
1279 }
1281 /** Visitor method: Validate a list of type expressions.
1282 */
1283 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1284 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1285 validate(l.head, env);
1286 }
1288 /** A visitor class for type validation.
1289 */
1290 class Validator extends JCTree.Visitor {
1292 boolean isOuter;
1293 Env<AttrContext> env;
1295 Validator(Env<AttrContext> env) {
1296 this.env = env;
1297 }
1299 @Override
1300 public void visitTypeArray(JCArrayTypeTree tree) {
1301 tree.elemtype.accept(this);
1302 }
1304 @Override
1305 public void visitTypeApply(JCTypeApply tree) {
1306 if (tree.type.tag == CLASS) {
1307 List<JCExpression> args = tree.arguments;
1308 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1310 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1311 if (incompatibleArg != null) {
1312 for (JCTree arg : tree.arguments) {
1313 if (arg.type == incompatibleArg) {
1314 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1315 }
1316 forms = forms.tail;
1317 }
1318 }
1320 forms = tree.type.tsym.type.getTypeArguments();
1322 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1324 // For matching pairs of actual argument types `a' and
1325 // formal type parameters with declared bound `b' ...
1326 while (args.nonEmpty() && forms.nonEmpty()) {
1327 validateTree(args.head,
1328 !(isOuter && is_java_lang_Class),
1329 false);
1330 args = args.tail;
1331 forms = forms.tail;
1332 }
1334 // Check that this type is either fully parameterized, or
1335 // not parameterized at all.
1336 if (tree.type.getEnclosingType().isRaw())
1337 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1338 if (tree.clazz.hasTag(SELECT))
1339 visitSelectInternal((JCFieldAccess)tree.clazz);
1340 }
1341 }
1343 @Override
1344 public void visitTypeParameter(JCTypeParameter tree) {
1345 validateTrees(tree.bounds, true, isOuter);
1346 checkClassBounds(tree.pos(), tree.type);
1347 }
1349 @Override
1350 public void visitWildcard(JCWildcard tree) {
1351 if (tree.inner != null)
1352 validateTree(tree.inner, true, isOuter);
1353 }
1355 @Override
1356 public void visitSelect(JCFieldAccess tree) {
1357 if (tree.type.tag == CLASS) {
1358 visitSelectInternal(tree);
1360 // Check that this type is either fully parameterized, or
1361 // not parameterized at all.
1362 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1363 log.error(tree.pos(), "improperly.formed.type.param.missing");
1364 }
1365 }
1367 public void visitSelectInternal(JCFieldAccess tree) {
1368 if (tree.type.tsym.isStatic() &&
1369 tree.selected.type.isParameterized()) {
1370 // The enclosing type is not a class, so we are
1371 // looking at a static member type. However, the
1372 // qualifying expression is parameterized.
1373 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1374 } else {
1375 // otherwise validate the rest of the expression
1376 tree.selected.accept(this);
1377 }
1378 }
1380 /** Default visitor method: do nothing.
1381 */
1382 @Override
1383 public void visitTree(JCTree tree) {
1384 }
1386 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1387 try {
1388 if (tree != null) {
1389 this.isOuter = isOuter;
1390 tree.accept(this);
1391 if (checkRaw)
1392 checkRaw(tree, env);
1393 }
1394 } catch (CompletionFailure ex) {
1395 completionError(tree.pos(), ex);
1396 }
1397 }
1399 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1400 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1401 validateTree(l.head, checkRaw, isOuter);
1402 }
1404 void checkRaw(JCTree tree, Env<AttrContext> env) {
1405 if (lint.isEnabled(LintCategory.RAW) &&
1406 tree.type.tag == CLASS &&
1407 !TreeInfo.isDiamond(tree) &&
1408 !withinAnonConstr(env) &&
1409 tree.type.isRaw()) {
1410 log.warning(LintCategory.RAW,
1411 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1412 }
1413 }
1415 boolean withinAnonConstr(Env<AttrContext> env) {
1416 return env.enclClass.name.isEmpty() &&
1417 env.enclMethod != null && env.enclMethod.name == names.init;
1418 }
1419 }
1421 /* *************************************************************************
1422 * Exception checking
1423 **************************************************************************/
1425 /* The following methods treat classes as sets that contain
1426 * the class itself and all their subclasses
1427 */
1429 /** Is given type a subtype of some of the types in given list?
1430 */
1431 boolean subset(Type t, List<Type> ts) {
1432 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1433 if (types.isSubtype(t, l.head)) return true;
1434 return false;
1435 }
1437 /** Is given type a subtype or supertype of
1438 * some of the types in given list?
1439 */
1440 boolean intersects(Type t, List<Type> ts) {
1441 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1442 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1443 return false;
1444 }
1446 /** Add type set to given type list, unless it is a subclass of some class
1447 * in the list.
1448 */
1449 List<Type> incl(Type t, List<Type> ts) {
1450 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1451 }
1453 /** Remove type set from type set list.
1454 */
1455 List<Type> excl(Type t, List<Type> ts) {
1456 if (ts.isEmpty()) {
1457 return ts;
1458 } else {
1459 List<Type> ts1 = excl(t, ts.tail);
1460 if (types.isSubtype(ts.head, t)) return ts1;
1461 else if (ts1 == ts.tail) return ts;
1462 else return ts1.prepend(ts.head);
1463 }
1464 }
1466 /** Form the union of two type set lists.
1467 */
1468 List<Type> union(List<Type> ts1, List<Type> ts2) {
1469 List<Type> ts = ts1;
1470 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1471 ts = incl(l.head, ts);
1472 return ts;
1473 }
1475 /** Form the difference of two type lists.
1476 */
1477 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1478 List<Type> ts = ts1;
1479 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1480 ts = excl(l.head, ts);
1481 return ts;
1482 }
1484 /** Form the intersection of two type lists.
1485 */
1486 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1487 List<Type> ts = List.nil();
1488 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1489 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1490 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1491 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1492 return ts;
1493 }
1495 /** Is exc an exception symbol that need not be declared?
1496 */
1497 boolean isUnchecked(ClassSymbol exc) {
1498 return
1499 exc.kind == ERR ||
1500 exc.isSubClass(syms.errorType.tsym, types) ||
1501 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1502 }
1504 /** Is exc an exception type that need not be declared?
1505 */
1506 boolean isUnchecked(Type exc) {
1507 return
1508 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1509 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1510 exc.tag == BOT;
1511 }
1513 /** Same, but handling completion failures.
1514 */
1515 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1516 try {
1517 return isUnchecked(exc);
1518 } catch (CompletionFailure ex) {
1519 completionError(pos, ex);
1520 return true;
1521 }
1522 }
1524 /** Is exc handled by given exception list?
1525 */
1526 boolean isHandled(Type exc, List<Type> handled) {
1527 return isUnchecked(exc) || subset(exc, handled);
1528 }
1530 /** Return all exceptions in thrown list that are not in handled list.
1531 * @param thrown The list of thrown exceptions.
1532 * @param handled The list of handled exceptions.
1533 */
1534 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1535 List<Type> unhandled = List.nil();
1536 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1537 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1538 return unhandled;
1539 }
1541 /* *************************************************************************
1542 * Overriding/Implementation checking
1543 **************************************************************************/
1545 /** The level of access protection given by a flag set,
1546 * where PRIVATE is highest and PUBLIC is lowest.
1547 */
1548 static int protection(long flags) {
1549 switch ((short)(flags & AccessFlags)) {
1550 case PRIVATE: return 3;
1551 case PROTECTED: return 1;
1552 default:
1553 case PUBLIC: return 0;
1554 case 0: return 2;
1555 }
1556 }
1558 /** A customized "cannot override" error message.
1559 * @param m The overriding method.
1560 * @param other The overridden method.
1561 * @return An internationalized string.
1562 */
1563 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1564 String key;
1565 if ((other.owner.flags() & INTERFACE) == 0)
1566 key = "cant.override";
1567 else if ((m.owner.flags() & INTERFACE) == 0)
1568 key = "cant.implement";
1569 else
1570 key = "clashes.with";
1571 return diags.fragment(key, m, m.location(), other, other.location());
1572 }
1574 /** A customized "override" warning message.
1575 * @param m The overriding method.
1576 * @param other The overridden method.
1577 * @return An internationalized string.
1578 */
1579 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1580 String key;
1581 if ((other.owner.flags() & INTERFACE) == 0)
1582 key = "unchecked.override";
1583 else if ((m.owner.flags() & INTERFACE) == 0)
1584 key = "unchecked.implement";
1585 else
1586 key = "unchecked.clash.with";
1587 return diags.fragment(key, m, m.location(), other, other.location());
1588 }
1590 /** A customized "override" warning message.
1591 * @param m The overriding method.
1592 * @param other The overridden method.
1593 * @return An internationalized string.
1594 */
1595 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1596 String key;
1597 if ((other.owner.flags() & INTERFACE) == 0)
1598 key = "varargs.override";
1599 else if ((m.owner.flags() & INTERFACE) == 0)
1600 key = "varargs.implement";
1601 else
1602 key = "varargs.clash.with";
1603 return diags.fragment(key, m, m.location(), other, other.location());
1604 }
1606 /** Check that this method conforms with overridden method 'other'.
1607 * where `origin' is the class where checking started.
1608 * Complications:
1609 * (1) Do not check overriding of synthetic methods
1610 * (reason: they might be final).
1611 * todo: check whether this is still necessary.
1612 * (2) Admit the case where an interface proxy throws fewer exceptions
1613 * than the method it implements. Augment the proxy methods with the
1614 * undeclared exceptions in this case.
1615 * (3) When generics are enabled, admit the case where an interface proxy
1616 * has a result type
1617 * extended by the result type of the method it implements.
1618 * Change the proxies result type to the smaller type in this case.
1619 *
1620 * @param tree The tree from which positions
1621 * are extracted for errors.
1622 * @param m The overriding method.
1623 * @param other The overridden method.
1624 * @param origin The class of which the overriding method
1625 * is a member.
1626 */
1627 void checkOverride(JCTree tree,
1628 MethodSymbol m,
1629 MethodSymbol other,
1630 ClassSymbol origin) {
1631 // Don't check overriding of synthetic methods or by bridge methods.
1632 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1633 return;
1634 }
1636 // Error if static method overrides instance method (JLS 8.4.6.2).
1637 if ((m.flags() & STATIC) != 0 &&
1638 (other.flags() & STATIC) == 0) {
1639 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1640 cannotOverride(m, other));
1641 return;
1642 }
1644 // Error if instance method overrides static or final
1645 // method (JLS 8.4.6.1).
1646 if ((other.flags() & FINAL) != 0 ||
1647 (m.flags() & STATIC) == 0 &&
1648 (other.flags() & STATIC) != 0) {
1649 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1650 cannotOverride(m, other),
1651 asFlagSet(other.flags() & (FINAL | STATIC)));
1652 return;
1653 }
1655 if ((m.owner.flags() & ANNOTATION) != 0) {
1656 // handled in validateAnnotationMethod
1657 return;
1658 }
1660 // Error if overriding method has weaker access (JLS 8.4.6.3).
1661 if ((origin.flags() & INTERFACE) == 0 &&
1662 protection(m.flags()) > protection(other.flags())) {
1663 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1664 cannotOverride(m, other),
1665 other.flags() == 0 ?
1666 Flag.PACKAGE :
1667 asFlagSet(other.flags() & AccessFlags));
1668 return;
1669 }
1671 Type mt = types.memberType(origin.type, m);
1672 Type ot = types.memberType(origin.type, other);
1673 // Error if overriding result type is different
1674 // (or, in the case of generics mode, not a subtype) of
1675 // overridden result type. We have to rename any type parameters
1676 // before comparing types.
1677 List<Type> mtvars = mt.getTypeArguments();
1678 List<Type> otvars = ot.getTypeArguments();
1679 Type mtres = mt.getReturnType();
1680 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1682 overrideWarner.clear();
1683 boolean resultTypesOK =
1684 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1685 if (!resultTypesOK) {
1686 if (!allowCovariantReturns &&
1687 m.owner != origin &&
1688 m.owner.isSubClass(other.owner, types)) {
1689 // allow limited interoperability with covariant returns
1690 } else {
1691 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1692 "override.incompatible.ret",
1693 cannotOverride(m, other),
1694 mtres, otres);
1695 return;
1696 }
1697 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1698 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1699 "override.unchecked.ret",
1700 uncheckedOverrides(m, other),
1701 mtres, otres);
1702 }
1704 // Error if overriding method throws an exception not reported
1705 // by overridden method.
1706 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1707 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1708 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1709 if (unhandledErased.nonEmpty()) {
1710 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1711 "override.meth.doesnt.throw",
1712 cannotOverride(m, other),
1713 unhandledUnerased.head);
1714 return;
1715 }
1716 else if (unhandledUnerased.nonEmpty()) {
1717 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1718 "override.unchecked.thrown",
1719 cannotOverride(m, other),
1720 unhandledUnerased.head);
1721 return;
1722 }
1724 // Optional warning if varargs don't agree
1725 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1726 && lint.isEnabled(LintCategory.OVERRIDES)) {
1727 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1728 ((m.flags() & Flags.VARARGS) != 0)
1729 ? "override.varargs.missing"
1730 : "override.varargs.extra",
1731 varargsOverrides(m, other));
1732 }
1734 // Warn if instance method overrides bridge method (compiler spec ??)
1735 if ((other.flags() & BRIDGE) != 0) {
1736 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1737 uncheckedOverrides(m, other));
1738 }
1740 // Warn if a deprecated method overridden by a non-deprecated one.
1741 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1742 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1743 }
1744 }
1745 // where
1746 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1747 // If the method, m, is defined in an interface, then ignore the issue if the method
1748 // is only inherited via a supertype and also implemented in the supertype,
1749 // because in that case, we will rediscover the issue when examining the method
1750 // in the supertype.
1751 // If the method, m, is not defined in an interface, then the only time we need to
1752 // address the issue is when the method is the supertype implemementation: any other
1753 // case, we will have dealt with when examining the supertype classes
1754 ClassSymbol mc = m.enclClass();
1755 Type st = types.supertype(origin.type);
1756 if (st.tag != CLASS)
1757 return true;
1758 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1760 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1761 List<Type> intfs = types.interfaces(origin.type);
1762 return (intfs.contains(mc.type) ? false : (stimpl != null));
1763 }
1764 else
1765 return (stimpl != m);
1766 }
1769 // used to check if there were any unchecked conversions
1770 Warner overrideWarner = new Warner();
1772 /** Check that a class does not inherit two concrete methods
1773 * with the same signature.
1774 * @param pos Position to be used for error reporting.
1775 * @param site The class type to be checked.
1776 */
1777 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1778 Type sup = types.supertype(site);
1779 if (sup.tag != CLASS) return;
1781 for (Type t1 = sup;
1782 t1.tsym.type.isParameterized();
1783 t1 = types.supertype(t1)) {
1784 for (Scope.Entry e1 = t1.tsym.members().elems;
1785 e1 != null;
1786 e1 = e1.sibling) {
1787 Symbol s1 = e1.sym;
1788 if (s1.kind != MTH ||
1789 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1790 !s1.isInheritedIn(site.tsym, types) ||
1791 ((MethodSymbol)s1).implementation(site.tsym,
1792 types,
1793 true) != s1)
1794 continue;
1795 Type st1 = types.memberType(t1, s1);
1796 int s1ArgsLength = st1.getParameterTypes().length();
1797 if (st1 == s1.type) continue;
1799 for (Type t2 = sup;
1800 t2.tag == CLASS;
1801 t2 = types.supertype(t2)) {
1802 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1803 e2.scope != null;
1804 e2 = e2.next()) {
1805 Symbol s2 = e2.sym;
1806 if (s2 == s1 ||
1807 s2.kind != MTH ||
1808 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1809 s2.type.getParameterTypes().length() != s1ArgsLength ||
1810 !s2.isInheritedIn(site.tsym, types) ||
1811 ((MethodSymbol)s2).implementation(site.tsym,
1812 types,
1813 true) != s2)
1814 continue;
1815 Type st2 = types.memberType(t2, s2);
1816 if (types.overrideEquivalent(st1, st2))
1817 log.error(pos, "concrete.inheritance.conflict",
1818 s1, t1, s2, t2, sup);
1819 }
1820 }
1821 }
1822 }
1823 }
1825 /** Check that classes (or interfaces) do not each define an abstract
1826 * method with same name and arguments but incompatible return types.
1827 * @param pos Position to be used for error reporting.
1828 * @param t1 The first argument type.
1829 * @param t2 The second argument type.
1830 */
1831 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1832 Type t1,
1833 Type t2) {
1834 return checkCompatibleAbstracts(pos, t1, t2,
1835 types.makeCompoundType(t1, t2));
1836 }
1838 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1839 Type t1,
1840 Type t2,
1841 Type site) {
1842 return firstIncompatibility(pos, t1, t2, site) == null;
1843 }
1845 /** Return the first method which is defined with same args
1846 * but different return types in two given interfaces, or null if none
1847 * exists.
1848 * @param t1 The first type.
1849 * @param t2 The second type.
1850 * @param site The most derived type.
1851 * @returns symbol from t2 that conflicts with one in t1.
1852 */
1853 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1854 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1855 closure(t1, interfaces1);
1856 Map<TypeSymbol,Type> interfaces2;
1857 if (t1 == t2)
1858 interfaces2 = interfaces1;
1859 else
1860 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1862 for (Type t3 : interfaces1.values()) {
1863 for (Type t4 : interfaces2.values()) {
1864 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1865 if (s != null) return s;
1866 }
1867 }
1868 return null;
1869 }
1871 /** Compute all the supertypes of t, indexed by type symbol. */
1872 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1873 if (t.tag != CLASS) return;
1874 if (typeMap.put(t.tsym, t) == null) {
1875 closure(types.supertype(t), typeMap);
1876 for (Type i : types.interfaces(t))
1877 closure(i, typeMap);
1878 }
1879 }
1881 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1882 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1883 if (t.tag != CLASS) return;
1884 if (typesSkip.get(t.tsym) != null) return;
1885 if (typeMap.put(t.tsym, t) == null) {
1886 closure(types.supertype(t), typesSkip, typeMap);
1887 for (Type i : types.interfaces(t))
1888 closure(i, typesSkip, typeMap);
1889 }
1890 }
1892 /** Return the first method in t2 that conflicts with a method from t1. */
1893 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1894 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1895 Symbol s1 = e1.sym;
1896 Type st1 = null;
1897 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1898 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1899 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1900 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1901 Symbol s2 = e2.sym;
1902 if (s1 == s2) continue;
1903 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1904 if (st1 == null) st1 = types.memberType(t1, s1);
1905 Type st2 = types.memberType(t2, s2);
1906 if (types.overrideEquivalent(st1, st2)) {
1907 List<Type> tvars1 = st1.getTypeArguments();
1908 List<Type> tvars2 = st2.getTypeArguments();
1909 Type rt1 = st1.getReturnType();
1910 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1911 boolean compat =
1912 types.isSameType(rt1, rt2) ||
1913 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1914 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1915 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1916 checkCommonOverriderIn(s1,s2,site);
1917 if (!compat) {
1918 log.error(pos, "types.incompatible.diff.ret",
1919 t1, t2, s2.name +
1920 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1921 return s2;
1922 }
1923 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1924 !checkCommonOverriderIn(s1, s2, site)) {
1925 log.error(pos,
1926 "name.clash.same.erasure.no.override",
1927 s1, s1.location(),
1928 s2, s2.location());
1929 return s2;
1930 }
1931 }
1932 }
1933 return null;
1934 }
1935 //WHERE
1936 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1937 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1938 Type st1 = types.memberType(site, s1);
1939 Type st2 = types.memberType(site, s2);
1940 closure(site, supertypes);
1941 for (Type t : supertypes.values()) {
1942 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1943 Symbol s3 = e.sym;
1944 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1945 Type st3 = types.memberType(site,s3);
1946 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1947 if (s3.owner == site.tsym) {
1948 return true;
1949 }
1950 List<Type> tvars1 = st1.getTypeArguments();
1951 List<Type> tvars2 = st2.getTypeArguments();
1952 List<Type> tvars3 = st3.getTypeArguments();
1953 Type rt1 = st1.getReturnType();
1954 Type rt2 = st2.getReturnType();
1955 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1956 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1957 boolean compat =
1958 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1959 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1960 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1961 if (compat)
1962 return true;
1963 }
1964 }
1965 }
1966 return false;
1967 }
1969 /** Check that a given method conforms with any method it overrides.
1970 * @param tree The tree from which positions are extracted
1971 * for errors.
1972 * @param m The overriding method.
1973 */
1974 void checkOverride(JCTree tree, MethodSymbol m) {
1975 ClassSymbol origin = (ClassSymbol)m.owner;
1976 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1977 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1978 log.error(tree.pos(), "enum.no.finalize");
1979 return;
1980 }
1981 for (Type t = origin.type; t.tag == CLASS;
1982 t = types.supertype(t)) {
1983 if (t != origin.type) {
1984 checkOverride(tree, t, origin, m);
1985 }
1986 for (Type t2 : types.interfaces(t)) {
1987 checkOverride(tree, t2, origin, m);
1988 }
1989 }
1990 }
1992 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1993 TypeSymbol c = site.tsym;
1994 Scope.Entry e = c.members().lookup(m.name);
1995 while (e.scope != null) {
1996 if (m.overrides(e.sym, origin, types, false)) {
1997 if ((e.sym.flags() & ABSTRACT) == 0) {
1998 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1999 }
2000 }
2001 e = e.next();
2002 }
2003 }
2005 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2006 ClashFilter cf = new ClashFilter(origin.type);
2007 return (cf.accepts(s1) &&
2008 cf.accepts(s2) &&
2009 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2010 }
2013 /** Check that all abstract members of given class have definitions.
2014 * @param pos Position to be used for error reporting.
2015 * @param c The class.
2016 */
2017 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2018 try {
2019 MethodSymbol undef = firstUndef(c, c);
2020 if (undef != null) {
2021 if ((c.flags() & ENUM) != 0 &&
2022 types.supertype(c.type).tsym == syms.enumSym &&
2023 (c.flags() & FINAL) == 0) {
2024 // add the ABSTRACT flag to an enum
2025 c.flags_field |= ABSTRACT;
2026 } else {
2027 MethodSymbol undef1 =
2028 new MethodSymbol(undef.flags(), undef.name,
2029 types.memberType(c.type, undef), undef.owner);
2030 log.error(pos, "does.not.override.abstract",
2031 c, undef1, undef1.location());
2032 }
2033 }
2034 } catch (CompletionFailure ex) {
2035 completionError(pos, ex);
2036 }
2037 }
2038 //where
2039 /** Return first abstract member of class `c' that is not defined
2040 * in `impl', null if there is none.
2041 */
2042 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
2043 MethodSymbol undef = null;
2044 // Do not bother to search in classes that are not abstract,
2045 // since they cannot have abstract members.
2046 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2047 Scope s = c.members();
2048 for (Scope.Entry e = s.elems;
2049 undef == null && e != null;
2050 e = e.sibling) {
2051 if (e.sym.kind == MTH &&
2052 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
2053 MethodSymbol absmeth = (MethodSymbol)e.sym;
2054 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
2055 if (implmeth == null || implmeth == absmeth)
2056 undef = absmeth;
2057 }
2058 }
2059 if (undef == null) {
2060 Type st = types.supertype(c.type);
2061 if (st.tag == CLASS)
2062 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2063 }
2064 for (List<Type> l = types.interfaces(c.type);
2065 undef == null && l.nonEmpty();
2066 l = l.tail) {
2067 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2068 }
2069 }
2070 return undef;
2071 }
2073 void checkNonCyclicDecl(JCClassDecl tree) {
2074 CycleChecker cc = new CycleChecker();
2075 cc.scan(tree);
2076 if (!cc.errorFound && !cc.partialCheck) {
2077 tree.sym.flags_field |= ACYCLIC;
2078 }
2079 }
2081 class CycleChecker extends TreeScanner {
2083 List<Symbol> seenClasses = List.nil();
2084 boolean errorFound = false;
2085 boolean partialCheck = false;
2087 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2088 if (sym != null && sym.kind == TYP) {
2089 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2090 if (classEnv != null) {
2091 DiagnosticSource prevSource = log.currentSource();
2092 try {
2093 log.useSource(classEnv.toplevel.sourcefile);
2094 scan(classEnv.tree);
2095 }
2096 finally {
2097 log.useSource(prevSource.getFile());
2098 }
2099 } else if (sym.kind == TYP) {
2100 checkClass(pos, sym, List.<JCTree>nil());
2101 }
2102 } else {
2103 //not completed yet
2104 partialCheck = true;
2105 }
2106 }
2108 @Override
2109 public void visitSelect(JCFieldAccess tree) {
2110 super.visitSelect(tree);
2111 checkSymbol(tree.pos(), tree.sym);
2112 }
2114 @Override
2115 public void visitIdent(JCIdent tree) {
2116 checkSymbol(tree.pos(), tree.sym);
2117 }
2119 @Override
2120 public void visitTypeApply(JCTypeApply tree) {
2121 scan(tree.clazz);
2122 }
2124 @Override
2125 public void visitTypeArray(JCArrayTypeTree tree) {
2126 scan(tree.elemtype);
2127 }
2129 @Override
2130 public void visitClassDef(JCClassDecl tree) {
2131 List<JCTree> supertypes = List.nil();
2132 if (tree.getExtendsClause() != null) {
2133 supertypes = supertypes.prepend(tree.getExtendsClause());
2134 }
2135 if (tree.getImplementsClause() != null) {
2136 for (JCTree intf : tree.getImplementsClause()) {
2137 supertypes = supertypes.prepend(intf);
2138 }
2139 }
2140 checkClass(tree.pos(), tree.sym, supertypes);
2141 }
2143 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2144 if ((c.flags_field & ACYCLIC) != 0)
2145 return;
2146 if (seenClasses.contains(c)) {
2147 errorFound = true;
2148 noteCyclic(pos, (ClassSymbol)c);
2149 } else if (!c.type.isErroneous()) {
2150 try {
2151 seenClasses = seenClasses.prepend(c);
2152 if (c.type.tag == CLASS) {
2153 if (supertypes.nonEmpty()) {
2154 scan(supertypes);
2155 }
2156 else {
2157 ClassType ct = (ClassType)c.type;
2158 if (ct.supertype_field == null ||
2159 ct.interfaces_field == null) {
2160 //not completed yet
2161 partialCheck = true;
2162 return;
2163 }
2164 checkSymbol(pos, ct.supertype_field.tsym);
2165 for (Type intf : ct.interfaces_field) {
2166 checkSymbol(pos, intf.tsym);
2167 }
2168 }
2169 if (c.owner.kind == TYP) {
2170 checkSymbol(pos, c.owner);
2171 }
2172 }
2173 } finally {
2174 seenClasses = seenClasses.tail;
2175 }
2176 }
2177 }
2178 }
2180 /** Check for cyclic references. Issue an error if the
2181 * symbol of the type referred to has a LOCKED flag set.
2182 *
2183 * @param pos Position to be used for error reporting.
2184 * @param t The type referred to.
2185 */
2186 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2187 checkNonCyclicInternal(pos, t);
2188 }
2191 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2192 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2193 }
2195 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2196 final TypeVar tv;
2197 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
2198 return;
2199 if (seen.contains(t)) {
2200 tv = (TypeVar)t;
2201 tv.bound = types.createErrorType(t);
2202 log.error(pos, "cyclic.inheritance", t);
2203 } else if (t.tag == TYPEVAR) {
2204 tv = (TypeVar)t;
2205 seen = seen.prepend(tv);
2206 for (Type b : types.getBounds(tv))
2207 checkNonCyclic1(pos, b, seen);
2208 }
2209 }
2211 /** Check for cyclic references. Issue an error if the
2212 * symbol of the type referred to has a LOCKED flag set.
2213 *
2214 * @param pos Position to be used for error reporting.
2215 * @param t The type referred to.
2216 * @returns True if the check completed on all attributed classes
2217 */
2218 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2219 boolean complete = true; // was the check complete?
2220 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2221 Symbol c = t.tsym;
2222 if ((c.flags_field & ACYCLIC) != 0) return true;
2224 if ((c.flags_field & LOCKED) != 0) {
2225 noteCyclic(pos, (ClassSymbol)c);
2226 } else if (!c.type.isErroneous()) {
2227 try {
2228 c.flags_field |= LOCKED;
2229 if (c.type.tag == CLASS) {
2230 ClassType clazz = (ClassType)c.type;
2231 if (clazz.interfaces_field != null)
2232 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2233 complete &= checkNonCyclicInternal(pos, l.head);
2234 if (clazz.supertype_field != null) {
2235 Type st = clazz.supertype_field;
2236 if (st != null && st.tag == CLASS)
2237 complete &= checkNonCyclicInternal(pos, st);
2238 }
2239 if (c.owner.kind == TYP)
2240 complete &= checkNonCyclicInternal(pos, c.owner.type);
2241 }
2242 } finally {
2243 c.flags_field &= ~LOCKED;
2244 }
2245 }
2246 if (complete)
2247 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2248 if (complete) c.flags_field |= ACYCLIC;
2249 return complete;
2250 }
2252 /** Note that we found an inheritance cycle. */
2253 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2254 log.error(pos, "cyclic.inheritance", c);
2255 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2256 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2257 Type st = types.supertype(c.type);
2258 if (st.tag == CLASS)
2259 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2260 c.type = types.createErrorType(c, c.type);
2261 c.flags_field |= ACYCLIC;
2262 }
2264 /** Check that all methods which implement some
2265 * method conform to the method they implement.
2266 * @param tree The class definition whose members are checked.
2267 */
2268 void checkImplementations(JCClassDecl tree) {
2269 checkImplementations(tree, tree.sym);
2270 }
2271 //where
2272 /** Check that all methods which implement some
2273 * method in `ic' conform to the method they implement.
2274 */
2275 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2276 ClassSymbol origin = tree.sym;
2277 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2278 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2279 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2280 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2281 if (e.sym.kind == MTH &&
2282 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2283 MethodSymbol absmeth = (MethodSymbol)e.sym;
2284 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2285 if (implmeth != null && implmeth != absmeth &&
2286 (implmeth.owner.flags() & INTERFACE) ==
2287 (origin.flags() & INTERFACE)) {
2288 // don't check if implmeth is in a class, yet
2289 // origin is an interface. This case arises only
2290 // if implmeth is declared in Object. The reason is
2291 // that interfaces really don't inherit from
2292 // Object it's just that the compiler represents
2293 // things that way.
2294 checkOverride(tree, implmeth, absmeth, origin);
2295 }
2296 }
2297 }
2298 }
2299 }
2300 }
2302 /** Check that all abstract methods implemented by a class are
2303 * mutually compatible.
2304 * @param pos Position to be used for error reporting.
2305 * @param c The class whose interfaces are checked.
2306 */
2307 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2308 List<Type> supertypes = types.interfaces(c);
2309 Type supertype = types.supertype(c);
2310 if (supertype.tag == CLASS &&
2311 (supertype.tsym.flags() & ABSTRACT) != 0)
2312 supertypes = supertypes.prepend(supertype);
2313 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2314 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2315 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2316 return;
2317 for (List<Type> m = supertypes; m != l; m = m.tail)
2318 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2319 return;
2320 }
2321 checkCompatibleConcretes(pos, c);
2322 }
2324 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2325 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2326 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2327 // VM allows methods and variables with differing types
2328 if (sym.kind == e.sym.kind &&
2329 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2330 sym != e.sym &&
2331 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2332 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2333 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2334 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2335 return;
2336 }
2337 }
2338 }
2339 }
2341 /** Check that all non-override equivalent methods accessible from 'site'
2342 * are mutually compatible (JLS 8.4.8/9.4.1).
2343 *
2344 * @param pos Position to be used for error reporting.
2345 * @param site The class whose methods are checked.
2346 * @param sym The method symbol to be checked.
2347 */
2348 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2349 ClashFilter cf = new ClashFilter(site);
2350 //for each method m1 that is overridden (directly or indirectly)
2351 //by method 'sym' in 'site'...
2352 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2353 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2354 //...check each method m2 that is a member of 'site'
2355 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2356 if (m2 == m1) continue;
2357 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2358 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2359 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
2360 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2361 sym.flags_field |= CLASH;
2362 String key = m1 == sym ?
2363 "name.clash.same.erasure.no.override" :
2364 "name.clash.same.erasure.no.override.1";
2365 log.error(pos,
2366 key,
2367 sym, sym.location(),
2368 m2, m2.location(),
2369 m1, m1.location());
2370 return;
2371 }
2372 }
2373 }
2374 }
2378 /** Check that all static methods accessible from 'site' are
2379 * mutually compatible (JLS 8.4.8).
2380 *
2381 * @param pos Position to be used for error reporting.
2382 * @param site The class whose methods are checked.
2383 * @param sym The method symbol to be checked.
2384 */
2385 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2386 ClashFilter cf = new ClashFilter(site);
2387 //for each method m1 that is a member of 'site'...
2388 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2389 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2390 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2391 if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
2392 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2393 log.error(pos,
2394 "name.clash.same.erasure.no.hide",
2395 sym, sym.location(),
2396 s, s.location());
2397 return;
2398 }
2399 }
2400 }
2402 //where
2403 private class ClashFilter implements Filter<Symbol> {
2405 Type site;
2407 ClashFilter(Type site) {
2408 this.site = site;
2409 }
2411 boolean shouldSkip(Symbol s) {
2412 return (s.flags() & CLASH) != 0 &&
2413 s.owner == site.tsym;
2414 }
2416 public boolean accepts(Symbol s) {
2417 return s.kind == MTH &&
2418 (s.flags() & SYNTHETIC) == 0 &&
2419 !shouldSkip(s) &&
2420 s.isInheritedIn(site.tsym, types) &&
2421 !s.isConstructor();
2422 }
2423 }
2425 /** Report a conflict between a user symbol and a synthetic symbol.
2426 */
2427 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2428 if (!sym.type.isErroneous()) {
2429 if (warnOnSyntheticConflicts) {
2430 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2431 }
2432 else {
2433 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2434 }
2435 }
2436 }
2438 /** Check that class c does not implement directly or indirectly
2439 * the same parameterized interface with two different argument lists.
2440 * @param pos Position to be used for error reporting.
2441 * @param type The type whose interfaces are checked.
2442 */
2443 void checkClassBounds(DiagnosticPosition pos, Type type) {
2444 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2445 }
2446 //where
2447 /** Enter all interfaces of type `type' into the hash table `seensofar'
2448 * with their class symbol as key and their type as value. Make
2449 * sure no class is entered with two different types.
2450 */
2451 void checkClassBounds(DiagnosticPosition pos,
2452 Map<TypeSymbol,Type> seensofar,
2453 Type type) {
2454 if (type.isErroneous()) return;
2455 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2456 Type it = l.head;
2457 Type oldit = seensofar.put(it.tsym, it);
2458 if (oldit != null) {
2459 List<Type> oldparams = oldit.allparams();
2460 List<Type> newparams = it.allparams();
2461 if (!types.containsTypeEquivalent(oldparams, newparams))
2462 log.error(pos, "cant.inherit.diff.arg",
2463 it.tsym, Type.toString(oldparams),
2464 Type.toString(newparams));
2465 }
2466 checkClassBounds(pos, seensofar, it);
2467 }
2468 Type st = types.supertype(type);
2469 if (st != null) checkClassBounds(pos, seensofar, st);
2470 }
2472 /** Enter interface into into set.
2473 * If it existed already, issue a "repeated interface" error.
2474 */
2475 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2476 if (its.contains(it))
2477 log.error(pos, "repeated.interface");
2478 else {
2479 its.add(it);
2480 }
2481 }
2483 /* *************************************************************************
2484 * Check annotations
2485 **************************************************************************/
2487 /**
2488 * Recursively validate annotations values
2489 */
2490 void validateAnnotationTree(JCTree tree) {
2491 class AnnotationValidator extends TreeScanner {
2492 @Override
2493 public void visitAnnotation(JCAnnotation tree) {
2494 if (!tree.type.isErroneous()) {
2495 super.visitAnnotation(tree);
2496 validateAnnotation(tree);
2497 }
2498 }
2499 }
2500 tree.accept(new AnnotationValidator());
2501 }
2503 /**
2504 * {@literal
2505 * Annotation types are restricted to primitives, String, an
2506 * enum, an annotation, Class, Class<?>, Class<? extends
2507 * Anything>, arrays of the preceding.
2508 * }
2509 */
2510 void validateAnnotationType(JCTree restype) {
2511 // restype may be null if an error occurred, so don't bother validating it
2512 if (restype != null) {
2513 validateAnnotationType(restype.pos(), restype.type);
2514 }
2515 }
2517 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2518 if (type.isPrimitive()) return;
2519 if (types.isSameType(type, syms.stringType)) return;
2520 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2521 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2522 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2523 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2524 validateAnnotationType(pos, types.elemtype(type));
2525 return;
2526 }
2527 log.error(pos, "invalid.annotation.member.type");
2528 }
2530 /**
2531 * "It is also a compile-time error if any method declared in an
2532 * annotation type has a signature that is override-equivalent to
2533 * that of any public or protected method declared in class Object
2534 * or in the interface annotation.Annotation."
2535 *
2536 * @jls 9.6 Annotation Types
2537 */
2538 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2539 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2540 Scope s = sup.tsym.members();
2541 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2542 if (e.sym.kind == MTH &&
2543 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2544 types.overrideEquivalent(m.type, e.sym.type))
2545 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2546 }
2547 }
2548 }
2550 /** Check the annotations of a symbol.
2551 */
2552 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2553 for (JCAnnotation a : annotations)
2554 validateAnnotation(a, s);
2555 }
2557 /** Check an annotation of a symbol.
2558 */
2559 private void validateAnnotation(JCAnnotation a, Symbol s) {
2560 validateAnnotationTree(a);
2562 if (!annotationApplicable(a, s))
2563 log.error(a.pos(), "annotation.type.not.applicable");
2565 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2566 if (!isOverrider(s))
2567 log.error(a.pos(), "method.does.not.override.superclass");
2568 }
2569 }
2571 /**
2572 * Validate the proposed container 'containedBy' on the
2573 * annotation type symbol 's'. Report errors at position
2574 * 'pos'.
2575 *
2576 * @param s The (annotation)type declaration annotated with a @ContainedBy
2577 * @param containerAnno the @ContainedBy on 's'
2578 * @param pos where to report errors
2579 */
2580 public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
2581 Assert.check(types.isSameType(containedBy.type, syms.containedByType));
2583 Type t = null;
2584 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2585 if (!l.isEmpty()) {
2586 Assert.check(l.head.fst.name == names.value);
2587 t = ((Attribute.Class)l.head.snd).getValue();
2588 }
2590 if (t == null) {
2591 log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
2592 return;
2593 }
2595 validateHasContainerFor(t.tsym, s, pos);
2596 validateRetention(t.tsym, s, pos);
2597 validateDocumented(t.tsym, s, pos);
2598 validateInherited(t.tsym, s, pos);
2599 validateTarget(t.tsym, s, pos);
2600 validateDefault(t.tsym, s, pos);
2601 }
2603 /**
2604 * Validate the proposed container 'containerFor' on the
2605 * annotation type symbol 's'. Report errors at position
2606 * 'pos'.
2607 *
2608 * @param s The (annotation)type declaration annotated with a @ContainerFor
2609 * @param containerFor the @ContainedFor on 's'
2610 * @param pos where to report errors
2611 */
2612 public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
2613 Assert.check(types.isSameType(containerFor.type, syms.containerForType));
2615 Type t = null;
2616 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2617 if (!l.isEmpty()) {
2618 Assert.check(l.head.fst.name == names.value);
2619 t = ((Attribute.Class)l.head.snd).getValue();
2620 }
2622 if (t == null) {
2623 log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
2624 return;
2625 }
2627 validateHasContainedBy(t.tsym, s, pos);
2628 }
2630 private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2631 Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
2633 if (containedBy == null) {
2634 log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
2635 return;
2636 }
2638 Type t = null;
2639 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2640 if (!l.isEmpty()) {
2641 Assert.check(l.head.fst.name == names.value);
2642 t = ((Attribute.Class)l.head.snd).getValue();
2643 }
2645 if (t == null) {
2646 log.error(pos, "invalid.container.wrong.containedby", container, contained);
2647 return;
2648 }
2650 if (!types.isSameType(t, contained.type))
2651 log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
2652 }
2654 private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2655 Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
2657 if (containerFor == null) {
2658 log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
2659 return;
2660 }
2662 Type t = null;
2663 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2664 if (!l.isEmpty()) {
2665 Assert.check(l.head.fst.name == names.value);
2666 t = ((Attribute.Class)l.head.snd).getValue();
2667 }
2669 if (t == null) {
2670 log.error(pos, "invalid.container.wrong.containerfor", container, contained);
2671 return;
2672 }
2674 if (!types.isSameType(t, contained.type))
2675 log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
2676 }
2678 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2679 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2680 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2682 boolean error = false;
2683 switch (containedRetention) {
2684 case RUNTIME:
2685 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2686 error = true;
2687 }
2688 break;
2689 case CLASS:
2690 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2691 error = true;
2692 }
2693 }
2694 if (error ) {
2695 log.error(pos, "invalid.containedby.annotation.retention",
2696 container, containerRetention,
2697 contained, containedRetention);
2698 }
2699 }
2701 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2702 if (contained.attribute(syms.documentedType.tsym) != null) {
2703 if (container.attribute(syms.documentedType.tsym) == null) {
2704 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
2705 }
2706 }
2707 }
2709 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2710 if (contained.attribute(syms.inheritedType.tsym) != null) {
2711 if (container.attribute(syms.inheritedType.tsym) == null) {
2712 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
2713 }
2714 }
2715 }
2717 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2718 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2720 // If contained has no Target, we are done
2721 if (containedTarget == null) {
2722 return;
2723 }
2725 // If contained has Target m1, container must have a Target
2726 // annotation, m2, and m2 must be a subset of m1. (This is
2727 // trivially true if contained has no target as per above).
2729 // contained has target, but container has not, error
2730 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2731 if (containerTarget == null) {
2732 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2733 return;
2734 }
2736 Set<Name> containerTargets = new HashSet<Name>();
2737 for (Attribute app : containerTarget.values) {
2738 if (!(app instanceof Attribute.Enum)) {
2739 continue; // recovery
2740 }
2741 Attribute.Enum e = (Attribute.Enum)app;
2742 containerTargets.add(e.value.name);
2743 }
2745 Set<Name> containedTargets = new HashSet<Name>();
2746 for (Attribute app : containedTarget.values) {
2747 if (!(app instanceof Attribute.Enum)) {
2748 continue; // recovery
2749 }
2750 Attribute.Enum e = (Attribute.Enum)app;
2751 containedTargets.add(e.value.name);
2752 }
2754 if (!isTargetSubset(containedTargets, containerTargets)) {
2755 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2756 }
2757 }
2759 /** Checks that t is a subset of s, with respect to ElementType
2760 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2761 */
2762 private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
2763 // Check that all elements in t are present in s
2764 for (Name n2 : t) {
2765 boolean currentElementOk = false;
2766 for (Name n1 : s) {
2767 if (n1 == n2) {
2768 currentElementOk = true;
2769 break;
2770 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2771 currentElementOk = true;
2772 break;
2773 }
2774 }
2775 if (!currentElementOk)
2776 return false;
2777 }
2778 return true;
2779 }
2781 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2782 // validate that all other elements of containing type has defaults
2783 Scope scope = container.members();
2784 for(Symbol elm : scope.getElements()) {
2785 if (elm.name != names.value &&
2786 elm.kind == Kinds.MTH &&
2787 ((MethodSymbol)elm).defaultValue == null) {
2788 log.error(pos,
2789 "invalid.containedby.annotation.elem.nondefault",
2790 container,
2791 elm);
2792 }
2793 }
2794 }
2796 /** Is s a method symbol that overrides a method in a superclass? */
2797 boolean isOverrider(Symbol s) {
2798 if (s.kind != MTH || s.isStatic())
2799 return false;
2800 MethodSymbol m = (MethodSymbol)s;
2801 TypeSymbol owner = (TypeSymbol)m.owner;
2802 for (Type sup : types.closure(owner.type)) {
2803 if (sup == owner.type)
2804 continue; // skip "this"
2805 Scope scope = sup.tsym.members();
2806 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2807 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2808 return true;
2809 }
2810 }
2811 return false;
2812 }
2814 /** Is the annotation applicable to the symbol? */
2815 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2816 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2817 if (arr == null) {
2818 return true;
2819 }
2820 for (Attribute app : arr.values) {
2821 if (!(app instanceof Attribute.Enum)) return true; // recovery
2822 Attribute.Enum e = (Attribute.Enum) app;
2823 if (e.value.name == names.TYPE)
2824 { if (s.kind == TYP) return true; }
2825 else if (e.value.name == names.FIELD)
2826 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2827 else if (e.value.name == names.METHOD)
2828 { if (s.kind == MTH && !s.isConstructor()) return true; }
2829 else if (e.value.name == names.PARAMETER)
2830 { if (s.kind == VAR &&
2831 s.owner.kind == MTH &&
2832 (s.flags() & PARAMETER) != 0)
2833 return true;
2834 }
2835 else if (e.value.name == names.CONSTRUCTOR)
2836 { if (s.kind == MTH && s.isConstructor()) return true; }
2837 else if (e.value.name == names.LOCAL_VARIABLE)
2838 { if (s.kind == VAR && s.owner.kind == MTH &&
2839 (s.flags() & PARAMETER) == 0)
2840 return true;
2841 }
2842 else if (e.value.name == names.ANNOTATION_TYPE)
2843 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2844 return true;
2845 }
2846 else if (e.value.name == names.PACKAGE)
2847 { if (s.kind == PCK) return true; }
2848 else if (e.value.name == names.TYPE_USE)
2849 { if (s.kind == TYP ||
2850 s.kind == VAR ||
2851 (s.kind == MTH && !s.isConstructor() &&
2852 s.type.getReturnType().tag != VOID))
2853 return true;
2854 }
2855 else
2856 return true; // recovery
2857 }
2858 return false;
2859 }
2862 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2863 Attribute.Compound atTarget =
2864 s.attribute(syms.annotationTargetType.tsym);
2865 if (atTarget == null) return null; // ok, is applicable
2866 Attribute atValue = atTarget.member(names.value);
2867 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2868 return (Attribute.Array) atValue;
2869 }
2871 /** Check an annotation value.
2872 */
2873 public void validateAnnotation(JCAnnotation a) {
2874 // collect an inventory of the members (sorted alphabetically)
2875 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2876 public int compare(Symbol t, Symbol t1) {
2877 return t.name.compareTo(t1.name);
2878 }
2879 });
2880 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2881 e != null;
2882 e = e.sibling)
2883 if (e.sym.kind == MTH)
2884 members.add((MethodSymbol) e.sym);
2886 // count them off as they're annotated
2887 for (JCTree arg : a.args) {
2888 if (!arg.hasTag(ASSIGN)) continue; // recovery
2889 JCAssign assign = (JCAssign) arg;
2890 Symbol m = TreeInfo.symbol(assign.lhs);
2891 if (m == null || m.type.isErroneous()) continue;
2892 if (!members.remove(m))
2893 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2894 m.name, a.type);
2895 }
2897 // all the remaining ones better have default values
2898 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2899 for (MethodSymbol m : members) {
2900 if (m.defaultValue == null && !m.type.isErroneous()) {
2901 missingDefaults.append(m.name);
2902 }
2903 }
2904 if (missingDefaults.nonEmpty()) {
2905 String key = (missingDefaults.size() > 1)
2906 ? "annotation.missing.default.value.1"
2907 : "annotation.missing.default.value";
2908 log.error(a.pos(), key, a.type, missingDefaults);
2909 }
2911 // special case: java.lang.annotation.Target must not have
2912 // repeated values in its value member
2913 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2914 a.args.tail == null)
2915 return;
2917 if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
2918 JCAssign assign = (JCAssign) a.args.head;
2919 Symbol m = TreeInfo.symbol(assign.lhs);
2920 if (m.name != names.value) return;
2921 JCTree rhs = assign.rhs;
2922 if (!rhs.hasTag(NEWARRAY)) return;
2923 JCNewArray na = (JCNewArray) rhs;
2924 Set<Symbol> targets = new HashSet<Symbol>();
2925 for (JCTree elem : na.elems) {
2926 if (!targets.add(TreeInfo.symbol(elem))) {
2927 log.error(elem.pos(), "repeated.annotation.target");
2928 }
2929 }
2930 }
2932 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2933 if (allowAnnotations &&
2934 lint.isEnabled(LintCategory.DEP_ANN) &&
2935 (s.flags() & DEPRECATED) != 0 &&
2936 !syms.deprecatedType.isErroneous() &&
2937 s.attribute(syms.deprecatedType.tsym) == null) {
2938 log.warning(LintCategory.DEP_ANN,
2939 pos, "missing.deprecated.annotation");
2940 }
2941 }
2943 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2944 if ((s.flags() & DEPRECATED) != 0 &&
2945 (other.flags() & DEPRECATED) == 0 &&
2946 s.outermostClass() != other.outermostClass()) {
2947 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2948 @Override
2949 public void report() {
2950 warnDeprecated(pos, s);
2951 }
2952 });
2953 }
2954 }
2956 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2957 if ((s.flags() & PROPRIETARY) != 0) {
2958 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2959 public void report() {
2960 if (enableSunApiLintControl)
2961 warnSunApi(pos, "sun.proprietary", s);
2962 else
2963 log.mandatoryWarning(pos, "sun.proprietary", s);
2964 }
2965 });
2966 }
2967 }
2969 /* *************************************************************************
2970 * Check for recursive annotation elements.
2971 **************************************************************************/
2973 /** Check for cycles in the graph of annotation elements.
2974 */
2975 void checkNonCyclicElements(JCClassDecl tree) {
2976 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2977 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2978 try {
2979 tree.sym.flags_field |= LOCKED;
2980 for (JCTree def : tree.defs) {
2981 if (!def.hasTag(METHODDEF)) continue;
2982 JCMethodDecl meth = (JCMethodDecl)def;
2983 checkAnnotationResType(meth.pos(), meth.restype.type);
2984 }
2985 } finally {
2986 tree.sym.flags_field &= ~LOCKED;
2987 tree.sym.flags_field |= ACYCLIC_ANN;
2988 }
2989 }
2991 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2992 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2993 return;
2994 if ((tsym.flags_field & LOCKED) != 0) {
2995 log.error(pos, "cyclic.annotation.element");
2996 return;
2997 }
2998 try {
2999 tsym.flags_field |= LOCKED;
3000 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3001 Symbol s = e.sym;
3002 if (s.kind != Kinds.MTH)
3003 continue;
3004 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3005 }
3006 } finally {
3007 tsym.flags_field &= ~LOCKED;
3008 tsym.flags_field |= ACYCLIC_ANN;
3009 }
3010 }
3012 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3013 switch (type.tag) {
3014 case TypeTags.CLASS:
3015 if ((type.tsym.flags() & ANNOTATION) != 0)
3016 checkNonCyclicElementsInternal(pos, type.tsym);
3017 break;
3018 case TypeTags.ARRAY:
3019 checkAnnotationResType(pos, types.elemtype(type));
3020 break;
3021 default:
3022 break; // int etc
3023 }
3024 }
3026 /* *************************************************************************
3027 * Check for cycles in the constructor call graph.
3028 **************************************************************************/
3030 /** Check for cycles in the graph of constructors calling other
3031 * constructors.
3032 */
3033 void checkCyclicConstructors(JCClassDecl tree) {
3034 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3036 // enter each constructor this-call into the map
3037 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3038 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3039 if (app == null) continue;
3040 JCMethodDecl meth = (JCMethodDecl) l.head;
3041 if (TreeInfo.name(app.meth) == names._this) {
3042 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3043 } else {
3044 meth.sym.flags_field |= ACYCLIC;
3045 }
3046 }
3048 // Check for cycles in the map
3049 Symbol[] ctors = new Symbol[0];
3050 ctors = callMap.keySet().toArray(ctors);
3051 for (Symbol caller : ctors) {
3052 checkCyclicConstructor(tree, caller, callMap);
3053 }
3054 }
3056 /** Look in the map to see if the given constructor is part of a
3057 * call cycle.
3058 */
3059 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3060 Map<Symbol,Symbol> callMap) {
3061 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3062 if ((ctor.flags_field & LOCKED) != 0) {
3063 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3064 "recursive.ctor.invocation");
3065 } else {
3066 ctor.flags_field |= LOCKED;
3067 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3068 ctor.flags_field &= ~LOCKED;
3069 }
3070 ctor.flags_field |= ACYCLIC;
3071 }
3072 }
3074 /* *************************************************************************
3075 * Miscellaneous
3076 **************************************************************************/
3078 /**
3079 * Return the opcode of the operator but emit an error if it is an
3080 * error.
3081 * @param pos position for error reporting.
3082 * @param operator an operator
3083 * @param tag a tree tag
3084 * @param left type of left hand side
3085 * @param right type of right hand side
3086 */
3087 int checkOperator(DiagnosticPosition pos,
3088 OperatorSymbol operator,
3089 JCTree.Tag tag,
3090 Type left,
3091 Type right) {
3092 if (operator.opcode == ByteCodes.error) {
3093 log.error(pos,
3094 "operator.cant.be.applied.1",
3095 treeinfo.operatorName(tag),
3096 left, right);
3097 }
3098 return operator.opcode;
3099 }
3102 /**
3103 * Check for division by integer constant zero
3104 * @param pos Position for error reporting.
3105 * @param operator The operator for the expression
3106 * @param operand The right hand operand for the expression
3107 */
3108 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3109 if (operand.constValue() != null
3110 && lint.isEnabled(LintCategory.DIVZERO)
3111 && operand.tag <= LONG
3112 && ((Number) (operand.constValue())).longValue() == 0) {
3113 int opc = ((OperatorSymbol)operator).opcode;
3114 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3115 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3116 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3117 }
3118 }
3119 }
3121 /**
3122 * Check for empty statements after if
3123 */
3124 void checkEmptyIf(JCIf tree) {
3125 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3126 lint.isEnabled(LintCategory.EMPTY))
3127 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3128 }
3130 /** Check that symbol is unique in given scope.
3131 * @param pos Position for error reporting.
3132 * @param sym The symbol.
3133 * @param s The scope.
3134 */
3135 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3136 if (sym.type.isErroneous())
3137 return true;
3138 if (sym.owner.name == names.any) return false;
3139 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3140 if (sym != e.sym &&
3141 (e.sym.flags() & CLASH) == 0 &&
3142 sym.kind == e.sym.kind &&
3143 sym.name != names.error &&
3144 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3145 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3146 varargsDuplicateError(pos, sym, e.sym);
3147 return true;
3148 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3149 duplicateErasureError(pos, sym, e.sym);
3150 sym.flags_field |= CLASH;
3151 return true;
3152 } else {
3153 duplicateError(pos, e.sym);
3154 return false;
3155 }
3156 }
3157 }
3158 return true;
3159 }
3161 /** Report duplicate declaration error.
3162 */
3163 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3164 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3165 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3166 }
3167 }
3169 /** Check that single-type import is not already imported or top-level defined,
3170 * but make an exception for two single-type imports which denote the same type.
3171 * @param pos Position for error reporting.
3172 * @param sym The symbol.
3173 * @param s The scope
3174 */
3175 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3176 return checkUniqueImport(pos, sym, s, false);
3177 }
3179 /** Check that static single-type import is not already imported or top-level defined,
3180 * but make an exception for two single-type imports which denote the same type.
3181 * @param pos Position for error reporting.
3182 * @param sym The symbol.
3183 * @param s The scope
3184 * @param staticImport Whether or not this was a static import
3185 */
3186 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3187 return checkUniqueImport(pos, sym, s, true);
3188 }
3190 /** Check that single-type import is not already imported or top-level defined,
3191 * but make an exception for two single-type imports which denote the same type.
3192 * @param pos Position for error reporting.
3193 * @param sym The symbol.
3194 * @param s The scope.
3195 * @param staticImport Whether or not this was a static import
3196 */
3197 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3198 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3199 // is encountered class entered via a class declaration?
3200 boolean isClassDecl = e.scope == s;
3201 if ((isClassDecl || sym != e.sym) &&
3202 sym.kind == e.sym.kind &&
3203 sym.name != names.error) {
3204 if (!e.sym.type.isErroneous()) {
3205 String what = e.sym.toString();
3206 if (!isClassDecl) {
3207 if (staticImport)
3208 log.error(pos, "already.defined.static.single.import", what);
3209 else
3210 log.error(pos, "already.defined.single.import", what);
3211 }
3212 else if (sym != e.sym)
3213 log.error(pos, "already.defined.this.unit", what);
3214 }
3215 return false;
3216 }
3217 }
3218 return true;
3219 }
3221 /** Check that a qualified name is in canonical form (for import decls).
3222 */
3223 public void checkCanonical(JCTree tree) {
3224 if (!isCanonical(tree))
3225 log.error(tree.pos(), "import.requires.canonical",
3226 TreeInfo.symbol(tree));
3227 }
3228 // where
3229 private boolean isCanonical(JCTree tree) {
3230 while (tree.hasTag(SELECT)) {
3231 JCFieldAccess s = (JCFieldAccess) tree;
3232 if (s.sym.owner != TreeInfo.symbol(s.selected))
3233 return false;
3234 tree = s.selected;
3235 }
3236 return true;
3237 }
3239 private class ConversionWarner extends Warner {
3240 final String uncheckedKey;
3241 final Type found;
3242 final Type expected;
3243 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3244 super(pos);
3245 this.uncheckedKey = uncheckedKey;
3246 this.found = found;
3247 this.expected = expected;
3248 }
3250 @Override
3251 public void warn(LintCategory lint) {
3252 boolean warned = this.warned;
3253 super.warn(lint);
3254 if (warned) return; // suppress redundant diagnostics
3255 switch (lint) {
3256 case UNCHECKED:
3257 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3258 break;
3259 case VARARGS:
3260 if (method != null &&
3261 method.attribute(syms.trustMeType.tsym) != null &&
3262 isTrustMeAllowedOnMethod(method) &&
3263 !types.isReifiable(method.type.getParameterTypes().last())) {
3264 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3265 }
3266 break;
3267 default:
3268 throw new AssertionError("Unexpected lint: " + lint);
3269 }
3270 }
3271 }
3273 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3274 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3275 }
3277 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3278 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3279 }
3280 }