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