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