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