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