Fri, 12 Jul 2013 13:11:12 -0700
8020278: NPE in javadoc
Reviewed-by: mcimadamore, vromero
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) != 0 && allowVarargs) {
901 // non-varargs call to varargs method
902 Type varParam = owntype.getParameterTypes().last();
903 Type lastArg = argtypes.last();
904 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
905 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
906 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
907 types.elemtype(varParam), varParam);
908 }
909 }
910 if (useVarargs) {
911 Type argtype = owntype.getParameterTypes().last();
912 if (!types.isReifiable(argtype) &&
913 (!allowSimplifiedVarargs ||
914 sym.attribute(syms.trustMeType.tsym) == null ||
915 !isTrustMeAllowedOnMethod(sym))) {
916 warnUnchecked(env.tree.pos(),
917 "unchecked.generic.array.creation",
918 argtype);
919 }
920 if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) {
921 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
922 }
923 }
924 PolyKind pkind = (sym.type.hasTag(FORALL) &&
925 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
926 PolyKind.POLY : PolyKind.STANDALONE;
927 TreeInfo.setPolyKind(env.tree, pkind);
928 return owntype;
929 }
930 //where
931 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
932 if (types.isConvertible(actual, formal, warn))
933 return;
935 if (formal.isCompound()
936 && types.isSubtype(actual, types.supertype(formal))
937 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
938 return;
939 }
941 /**
942 * Check that type 't' is a valid instantiation of a generic class
943 * (see JLS 4.5)
944 *
945 * @param t class type to be checked
946 * @return true if 't' is well-formed
947 */
948 public boolean checkValidGenericType(Type t) {
949 return firstIncompatibleTypeArg(t) == null;
950 }
951 //WHERE
952 private Type firstIncompatibleTypeArg(Type type) {
953 List<Type> formals = type.tsym.type.allparams();
954 List<Type> actuals = type.allparams();
955 List<Type> args = type.getTypeArguments();
956 List<Type> forms = type.tsym.type.getTypeArguments();
957 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
959 // For matching pairs of actual argument types `a' and
960 // formal type parameters with declared bound `b' ...
961 while (args.nonEmpty() && forms.nonEmpty()) {
962 // exact type arguments needs to know their
963 // bounds (for upper and lower bound
964 // calculations). So we create new bounds where
965 // type-parameters are replaced with actuals argument types.
966 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
967 args = args.tail;
968 forms = forms.tail;
969 }
971 args = type.getTypeArguments();
972 List<Type> tvars_cap = types.substBounds(formals,
973 formals,
974 types.capture(type).allparams());
975 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
976 // Let the actual arguments know their bound
977 args.head.withTypeVar((TypeVar)tvars_cap.head);
978 args = args.tail;
979 tvars_cap = tvars_cap.tail;
980 }
982 args = type.getTypeArguments();
983 List<Type> bounds = bounds_buf.toList();
985 while (args.nonEmpty() && bounds.nonEmpty()) {
986 Type actual = args.head;
987 if (!isTypeArgErroneous(actual) &&
988 !bounds.head.isErroneous() &&
989 !checkExtends(actual, bounds.head)) {
990 return args.head;
991 }
992 args = args.tail;
993 bounds = bounds.tail;
994 }
996 args = type.getTypeArguments();
997 bounds = bounds_buf.toList();
999 for (Type arg : types.capture(type).getTypeArguments()) {
1000 if (arg.hasTag(TYPEVAR) &&
1001 arg.getUpperBound().isErroneous() &&
1002 !bounds.head.isErroneous() &&
1003 !isTypeArgErroneous(args.head)) {
1004 return args.head;
1005 }
1006 bounds = bounds.tail;
1007 args = args.tail;
1008 }
1010 return null;
1011 }
1012 //where
1013 boolean isTypeArgErroneous(Type t) {
1014 return isTypeArgErroneous.visit(t);
1015 }
1017 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1018 public Boolean visitType(Type t, Void s) {
1019 return t.isErroneous();
1020 }
1021 @Override
1022 public Boolean visitTypeVar(TypeVar t, Void s) {
1023 return visit(t.getUpperBound());
1024 }
1025 @Override
1026 public Boolean visitCapturedType(CapturedType t, Void s) {
1027 return visit(t.getUpperBound()) ||
1028 visit(t.getLowerBound());
1029 }
1030 @Override
1031 public Boolean visitWildcardType(WildcardType t, Void s) {
1032 return visit(t.type);
1033 }
1034 };
1036 /** Check that given modifiers are legal for given symbol and
1037 * return modifiers together with any implicit modifiers for that symbol.
1038 * Warning: we can't use flags() here since this method
1039 * is called during class enter, when flags() would cause a premature
1040 * completion.
1041 * @param pos Position to be used for error reporting.
1042 * @param flags The set of modifiers given in a definition.
1043 * @param sym The defined symbol.
1044 */
1045 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1046 long mask;
1047 long implicit = 0;
1048 switch (sym.kind) {
1049 case VAR:
1050 if (sym.owner.kind != TYP)
1051 mask = LocalVarFlags;
1052 else if ((sym.owner.flags_field & INTERFACE) != 0)
1053 mask = implicit = InterfaceVarFlags;
1054 else
1055 mask = VarFlags;
1056 break;
1057 case MTH:
1058 if (sym.name == names.init) {
1059 if ((sym.owner.flags_field & ENUM) != 0) {
1060 // enum constructors cannot be declared public or
1061 // protected and must be implicitly or explicitly
1062 // private
1063 implicit = PRIVATE;
1064 mask = PRIVATE;
1065 } else
1066 mask = ConstructorFlags;
1067 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1068 if ((flags & (DEFAULT | STATIC)) != 0) {
1069 mask = InterfaceMethodMask;
1070 implicit = PUBLIC;
1071 if ((flags & DEFAULT) != 0) {
1072 implicit |= ABSTRACT;
1073 }
1074 } else {
1075 mask = implicit = InterfaceMethodFlags;
1076 }
1077 }
1078 else {
1079 mask = MethodFlags;
1080 }
1081 // Imply STRICTFP if owner has STRICTFP set.
1082 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1083 ((flags) & Flags.DEFAULT) != 0)
1084 implicit |= sym.owner.flags_field & STRICTFP;
1085 break;
1086 case TYP:
1087 if (sym.isLocal()) {
1088 mask = LocalClassFlags;
1089 if (sym.name.isEmpty()) { // Anonymous class
1090 // Anonymous classes in static methods are themselves static;
1091 // that's why we admit STATIC here.
1092 mask |= STATIC;
1093 // JLS: Anonymous classes are final.
1094 implicit |= FINAL;
1095 }
1096 if ((sym.owner.flags_field & STATIC) == 0 &&
1097 (flags & ENUM) != 0)
1098 log.error(pos, "enums.must.be.static");
1099 } else if (sym.owner.kind == TYP) {
1100 mask = MemberClassFlags;
1101 if (sym.owner.owner.kind == PCK ||
1102 (sym.owner.flags_field & STATIC) != 0)
1103 mask |= STATIC;
1104 else if ((flags & ENUM) != 0)
1105 log.error(pos, "enums.must.be.static");
1106 // Nested interfaces and enums are always STATIC (Spec ???)
1107 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1108 } else {
1109 mask = ClassFlags;
1110 }
1111 // Interfaces are always ABSTRACT
1112 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1114 if ((flags & ENUM) != 0) {
1115 // enums can't be declared abstract or final
1116 mask &= ~(ABSTRACT | FINAL);
1117 implicit |= implicitEnumFinalFlag(tree);
1118 }
1119 // Imply STRICTFP if owner has STRICTFP set.
1120 implicit |= sym.owner.flags_field & STRICTFP;
1121 break;
1122 default:
1123 throw new AssertionError();
1124 }
1125 long illegal = flags & ExtendedStandardFlags & ~mask;
1126 if (illegal != 0) {
1127 if ((illegal & INTERFACE) != 0) {
1128 log.error(pos, "intf.not.allowed.here");
1129 mask |= INTERFACE;
1130 }
1131 else {
1132 log.error(pos,
1133 "mod.not.allowed.here", asFlagSet(illegal));
1134 }
1135 }
1136 else if ((sym.kind == TYP ||
1137 // ISSUE: Disallowing abstract&private is no longer appropriate
1138 // in the presence of inner classes. Should it be deleted here?
1139 checkDisjoint(pos, flags,
1140 ABSTRACT,
1141 PRIVATE | STATIC | DEFAULT))
1142 &&
1143 checkDisjoint(pos, flags,
1144 STATIC,
1145 DEFAULT)
1146 &&
1147 checkDisjoint(pos, flags,
1148 ABSTRACT | INTERFACE,
1149 FINAL | NATIVE | SYNCHRONIZED)
1150 &&
1151 checkDisjoint(pos, flags,
1152 PUBLIC,
1153 PRIVATE | PROTECTED)
1154 &&
1155 checkDisjoint(pos, flags,
1156 PRIVATE,
1157 PUBLIC | PROTECTED)
1158 &&
1159 checkDisjoint(pos, flags,
1160 FINAL,
1161 VOLATILE)
1162 &&
1163 (sym.kind == TYP ||
1164 checkDisjoint(pos, flags,
1165 ABSTRACT | NATIVE,
1166 STRICTFP))) {
1167 // skip
1168 }
1169 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1170 }
1173 /** Determine if this enum should be implicitly final.
1174 *
1175 * If the enum has no specialized enum contants, it is final.
1176 *
1177 * If the enum does have specialized enum contants, it is
1178 * <i>not</i> final.
1179 */
1180 private long implicitEnumFinalFlag(JCTree tree) {
1181 if (!tree.hasTag(CLASSDEF)) return 0;
1182 class SpecialTreeVisitor extends JCTree.Visitor {
1183 boolean specialized;
1184 SpecialTreeVisitor() {
1185 this.specialized = false;
1186 };
1188 @Override
1189 public void visitTree(JCTree tree) { /* no-op */ }
1191 @Override
1192 public void visitVarDef(JCVariableDecl tree) {
1193 if ((tree.mods.flags & ENUM) != 0) {
1194 if (tree.init instanceof JCNewClass &&
1195 ((JCNewClass) tree.init).def != null) {
1196 specialized = true;
1197 }
1198 }
1199 }
1200 }
1202 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1203 JCClassDecl cdef = (JCClassDecl) tree;
1204 for (JCTree defs: cdef.defs) {
1205 defs.accept(sts);
1206 if (sts.specialized) return 0;
1207 }
1208 return FINAL;
1209 }
1211 /* *************************************************************************
1212 * Type Validation
1213 **************************************************************************/
1215 /** Validate a type expression. That is,
1216 * check that all type arguments of a parametric type are within
1217 * their bounds. This must be done in a second phase after type attribution
1218 * since a class might have a subclass as type parameter bound. E.g:
1219 *
1220 * <pre>{@code
1221 * class B<A extends C> { ... }
1222 * class C extends B<C> { ... }
1223 * }</pre>
1224 *
1225 * and we can't make sure that the bound is already attributed because
1226 * of possible cycles.
1227 *
1228 * Visitor method: Validate a type expression, if it is not null, catching
1229 * and reporting any completion failures.
1230 */
1231 void validate(JCTree tree, Env<AttrContext> env) {
1232 validate(tree, env, true);
1233 }
1234 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1235 new Validator(env).validateTree(tree, checkRaw, true);
1236 }
1238 /** Visitor method: Validate a list of type expressions.
1239 */
1240 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1241 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1242 validate(l.head, env);
1243 }
1245 /** A visitor class for type validation.
1246 */
1247 class Validator extends JCTree.Visitor {
1249 boolean isOuter;
1250 Env<AttrContext> env;
1252 Validator(Env<AttrContext> env) {
1253 this.env = env;
1254 }
1256 @Override
1257 public void visitTypeArray(JCArrayTypeTree tree) {
1258 tree.elemtype.accept(this);
1259 }
1261 @Override
1262 public void visitTypeApply(JCTypeApply tree) {
1263 if (tree.type.hasTag(CLASS)) {
1264 List<JCExpression> args = tree.arguments;
1265 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1267 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1268 if (incompatibleArg != null) {
1269 for (JCTree arg : tree.arguments) {
1270 if (arg.type == incompatibleArg) {
1271 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1272 }
1273 forms = forms.tail;
1274 }
1275 }
1277 forms = tree.type.tsym.type.getTypeArguments();
1279 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1281 // For matching pairs of actual argument types `a' and
1282 // formal type parameters with declared bound `b' ...
1283 while (args.nonEmpty() && forms.nonEmpty()) {
1284 validateTree(args.head,
1285 !(isOuter && is_java_lang_Class),
1286 false);
1287 args = args.tail;
1288 forms = forms.tail;
1289 }
1291 // Check that this type is either fully parameterized, or
1292 // not parameterized at all.
1293 if (tree.type.getEnclosingType().isRaw())
1294 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1295 if (tree.clazz.hasTag(SELECT))
1296 visitSelectInternal((JCFieldAccess)tree.clazz);
1297 }
1298 }
1300 @Override
1301 public void visitTypeParameter(JCTypeParameter tree) {
1302 validateTrees(tree.bounds, true, isOuter);
1303 checkClassBounds(tree.pos(), tree.type);
1304 }
1306 @Override
1307 public void visitWildcard(JCWildcard tree) {
1308 if (tree.inner != null)
1309 validateTree(tree.inner, true, isOuter);
1310 }
1312 @Override
1313 public void visitSelect(JCFieldAccess tree) {
1314 if (tree.type.hasTag(CLASS)) {
1315 visitSelectInternal(tree);
1317 // Check that this type is either fully parameterized, or
1318 // not parameterized at all.
1319 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1320 log.error(tree.pos(), "improperly.formed.type.param.missing");
1321 }
1322 }
1324 public void visitSelectInternal(JCFieldAccess tree) {
1325 if (tree.type.tsym.isStatic() &&
1326 tree.selected.type.isParameterized()) {
1327 // The enclosing type is not a class, so we are
1328 // looking at a static member type. However, the
1329 // qualifying expression is parameterized.
1330 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1331 } else {
1332 // otherwise validate the rest of the expression
1333 tree.selected.accept(this);
1334 }
1335 }
1337 @Override
1338 public void visitAnnotatedType(JCAnnotatedType tree) {
1339 tree.underlyingType.accept(this);
1340 }
1342 /** Default visitor method: do nothing.
1343 */
1344 @Override
1345 public void visitTree(JCTree tree) {
1346 }
1348 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1349 try {
1350 if (tree != null) {
1351 this.isOuter = isOuter;
1352 tree.accept(this);
1353 if (checkRaw)
1354 checkRaw(tree, env);
1355 }
1356 } catch (CompletionFailure ex) {
1357 completionError(tree.pos(), ex);
1358 }
1359 }
1361 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1362 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1363 validateTree(l.head, checkRaw, isOuter);
1364 }
1365 }
1367 void checkRaw(JCTree tree, Env<AttrContext> env) {
1368 if (lint.isEnabled(LintCategory.RAW) &&
1369 tree.type.hasTag(CLASS) &&
1370 !TreeInfo.isDiamond(tree) &&
1371 !withinAnonConstr(env) &&
1372 tree.type.isRaw()) {
1373 log.warning(LintCategory.RAW,
1374 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1375 }
1376 }
1377 //where
1378 private boolean withinAnonConstr(Env<AttrContext> env) {
1379 return env.enclClass.name.isEmpty() &&
1380 env.enclMethod != null && env.enclMethod.name == names.init;
1381 }
1383 /* *************************************************************************
1384 * Exception checking
1385 **************************************************************************/
1387 /* The following methods treat classes as sets that contain
1388 * the class itself and all their subclasses
1389 */
1391 /** Is given type a subtype of some of the types in given list?
1392 */
1393 boolean subset(Type t, List<Type> ts) {
1394 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1395 if (types.isSubtype(t, l.head)) return true;
1396 return false;
1397 }
1399 /** Is given type a subtype or supertype of
1400 * some of the types in given list?
1401 */
1402 boolean intersects(Type t, List<Type> ts) {
1403 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1404 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1405 return false;
1406 }
1408 /** Add type set to given type list, unless it is a subclass of some class
1409 * in the list.
1410 */
1411 List<Type> incl(Type t, List<Type> ts) {
1412 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1413 }
1415 /** Remove type set from type set list.
1416 */
1417 List<Type> excl(Type t, List<Type> ts) {
1418 if (ts.isEmpty()) {
1419 return ts;
1420 } else {
1421 List<Type> ts1 = excl(t, ts.tail);
1422 if (types.isSubtype(ts.head, t)) return ts1;
1423 else if (ts1 == ts.tail) return ts;
1424 else return ts1.prepend(ts.head);
1425 }
1426 }
1428 /** Form the union of two type set lists.
1429 */
1430 List<Type> union(List<Type> ts1, List<Type> ts2) {
1431 List<Type> ts = ts1;
1432 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1433 ts = incl(l.head, ts);
1434 return ts;
1435 }
1437 /** Form the difference of two type lists.
1438 */
1439 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1440 List<Type> ts = ts1;
1441 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1442 ts = excl(l.head, ts);
1443 return ts;
1444 }
1446 /** Form the intersection of two type lists.
1447 */
1448 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1449 List<Type> ts = List.nil();
1450 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1451 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1452 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1453 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1454 return ts;
1455 }
1457 /** Is exc an exception symbol that need not be declared?
1458 */
1459 boolean isUnchecked(ClassSymbol exc) {
1460 return
1461 exc.kind == ERR ||
1462 exc.isSubClass(syms.errorType.tsym, types) ||
1463 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1464 }
1466 /** Is exc an exception type that need not be declared?
1467 */
1468 boolean isUnchecked(Type exc) {
1469 return
1470 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1471 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1472 exc.hasTag(BOT);
1473 }
1475 /** Same, but handling completion failures.
1476 */
1477 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1478 try {
1479 return isUnchecked(exc);
1480 } catch (CompletionFailure ex) {
1481 completionError(pos, ex);
1482 return true;
1483 }
1484 }
1486 /** Is exc handled by given exception list?
1487 */
1488 boolean isHandled(Type exc, List<Type> handled) {
1489 return isUnchecked(exc) || subset(exc, handled);
1490 }
1492 /** Return all exceptions in thrown list that are not in handled list.
1493 * @param thrown The list of thrown exceptions.
1494 * @param handled The list of handled exceptions.
1495 */
1496 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1497 List<Type> unhandled = List.nil();
1498 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1499 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1500 return unhandled;
1501 }
1503 /* *************************************************************************
1504 * Overriding/Implementation checking
1505 **************************************************************************/
1507 /** The level of access protection given by a flag set,
1508 * where PRIVATE is highest and PUBLIC is lowest.
1509 */
1510 static int protection(long flags) {
1511 switch ((short)(flags & AccessFlags)) {
1512 case PRIVATE: return 3;
1513 case PROTECTED: return 1;
1514 default:
1515 case PUBLIC: return 0;
1516 case 0: return 2;
1517 }
1518 }
1520 /** A customized "cannot override" error message.
1521 * @param m The overriding method.
1522 * @param other The overridden method.
1523 * @return An internationalized string.
1524 */
1525 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1526 String key;
1527 if ((other.owner.flags() & INTERFACE) == 0)
1528 key = "cant.override";
1529 else if ((m.owner.flags() & INTERFACE) == 0)
1530 key = "cant.implement";
1531 else
1532 key = "clashes.with";
1533 return diags.fragment(key, m, m.location(), other, other.location());
1534 }
1536 /** A customized "override" warning message.
1537 * @param m The overriding method.
1538 * @param other The overridden method.
1539 * @return An internationalized string.
1540 */
1541 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1542 String key;
1543 if ((other.owner.flags() & INTERFACE) == 0)
1544 key = "unchecked.override";
1545 else if ((m.owner.flags() & INTERFACE) == 0)
1546 key = "unchecked.implement";
1547 else
1548 key = "unchecked.clash.with";
1549 return diags.fragment(key, m, m.location(), other, other.location());
1550 }
1552 /** A customized "override" warning message.
1553 * @param m The overriding method.
1554 * @param other The overridden method.
1555 * @return An internationalized string.
1556 */
1557 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1558 String key;
1559 if ((other.owner.flags() & INTERFACE) == 0)
1560 key = "varargs.override";
1561 else if ((m.owner.flags() & INTERFACE) == 0)
1562 key = "varargs.implement";
1563 else
1564 key = "varargs.clash.with";
1565 return diags.fragment(key, m, m.location(), other, other.location());
1566 }
1568 /** Check that this method conforms with overridden method 'other'.
1569 * where `origin' is the class where checking started.
1570 * Complications:
1571 * (1) Do not check overriding of synthetic methods
1572 * (reason: they might be final).
1573 * todo: check whether this is still necessary.
1574 * (2) Admit the case where an interface proxy throws fewer exceptions
1575 * than the method it implements. Augment the proxy methods with the
1576 * undeclared exceptions in this case.
1577 * (3) When generics are enabled, admit the case where an interface proxy
1578 * has a result type
1579 * extended by the result type of the method it implements.
1580 * Change the proxies result type to the smaller type in this case.
1581 *
1582 * @param tree The tree from which positions
1583 * are extracted for errors.
1584 * @param m The overriding method.
1585 * @param other The overridden method.
1586 * @param origin The class of which the overriding method
1587 * is a member.
1588 */
1589 void checkOverride(JCTree tree,
1590 MethodSymbol m,
1591 MethodSymbol other,
1592 ClassSymbol origin) {
1593 // Don't check overriding of synthetic methods or by bridge methods.
1594 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1595 return;
1596 }
1598 // Error if static method overrides instance method (JLS 8.4.6.2).
1599 if ((m.flags() & STATIC) != 0 &&
1600 (other.flags() & STATIC) == 0) {
1601 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1602 cannotOverride(m, other));
1603 m.flags_field |= BAD_OVERRIDE;
1604 return;
1605 }
1607 // Error if instance method overrides static or final
1608 // method (JLS 8.4.6.1).
1609 if ((other.flags() & FINAL) != 0 ||
1610 (m.flags() & STATIC) == 0 &&
1611 (other.flags() & STATIC) != 0) {
1612 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1613 cannotOverride(m, other),
1614 asFlagSet(other.flags() & (FINAL | STATIC)));
1615 m.flags_field |= BAD_OVERRIDE;
1616 return;
1617 }
1619 if ((m.owner.flags() & ANNOTATION) != 0) {
1620 // handled in validateAnnotationMethod
1621 return;
1622 }
1624 // Error if overriding method has weaker access (JLS 8.4.6.3).
1625 if ((origin.flags() & INTERFACE) == 0 &&
1626 protection(m.flags()) > protection(other.flags())) {
1627 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1628 cannotOverride(m, other),
1629 other.flags() == 0 ?
1630 "package" :
1631 asFlagSet(other.flags() & AccessFlags));
1632 m.flags_field |= BAD_OVERRIDE;
1633 return;
1634 }
1636 Type mt = types.memberType(origin.type, m);
1637 Type ot = types.memberType(origin.type, other);
1638 // Error if overriding result type is different
1639 // (or, in the case of generics mode, not a subtype) of
1640 // overridden result type. We have to rename any type parameters
1641 // before comparing types.
1642 List<Type> mtvars = mt.getTypeArguments();
1643 List<Type> otvars = ot.getTypeArguments();
1644 Type mtres = mt.getReturnType();
1645 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1647 overrideWarner.clear();
1648 boolean resultTypesOK =
1649 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1650 if (!resultTypesOK) {
1651 if (!allowCovariantReturns &&
1652 m.owner != origin &&
1653 m.owner.isSubClass(other.owner, types)) {
1654 // allow limited interoperability with covariant returns
1655 } else {
1656 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1657 "override.incompatible.ret",
1658 cannotOverride(m, other),
1659 mtres, otres);
1660 m.flags_field |= BAD_OVERRIDE;
1661 return;
1662 }
1663 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1664 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1665 "override.unchecked.ret",
1666 uncheckedOverrides(m, other),
1667 mtres, otres);
1668 }
1670 // Error if overriding method throws an exception not reported
1671 // by overridden method.
1672 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1673 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1674 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1675 if (unhandledErased.nonEmpty()) {
1676 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1677 "override.meth.doesnt.throw",
1678 cannotOverride(m, other),
1679 unhandledUnerased.head);
1680 m.flags_field |= BAD_OVERRIDE;
1681 return;
1682 }
1683 else if (unhandledUnerased.nonEmpty()) {
1684 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1685 "override.unchecked.thrown",
1686 cannotOverride(m, other),
1687 unhandledUnerased.head);
1688 return;
1689 }
1691 // Optional warning if varargs don't agree
1692 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1693 && lint.isEnabled(LintCategory.OVERRIDES)) {
1694 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1695 ((m.flags() & Flags.VARARGS) != 0)
1696 ? "override.varargs.missing"
1697 : "override.varargs.extra",
1698 varargsOverrides(m, other));
1699 }
1701 // Warn if instance method overrides bridge method (compiler spec ??)
1702 if ((other.flags() & BRIDGE) != 0) {
1703 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1704 uncheckedOverrides(m, other));
1705 }
1707 // Warn if a deprecated method overridden by a non-deprecated one.
1708 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1709 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1710 }
1711 }
1712 // where
1713 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1714 // If the method, m, is defined in an interface, then ignore the issue if the method
1715 // is only inherited via a supertype and also implemented in the supertype,
1716 // because in that case, we will rediscover the issue when examining the method
1717 // in the supertype.
1718 // If the method, m, is not defined in an interface, then the only time we need to
1719 // address the issue is when the method is the supertype implemementation: any other
1720 // case, we will have dealt with when examining the supertype classes
1721 ClassSymbol mc = m.enclClass();
1722 Type st = types.supertype(origin.type);
1723 if (!st.hasTag(CLASS))
1724 return true;
1725 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1727 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1728 List<Type> intfs = types.interfaces(origin.type);
1729 return (intfs.contains(mc.type) ? false : (stimpl != null));
1730 }
1731 else
1732 return (stimpl != m);
1733 }
1736 // used to check if there were any unchecked conversions
1737 Warner overrideWarner = new Warner();
1739 /** Check that a class does not inherit two concrete methods
1740 * with the same signature.
1741 * @param pos Position to be used for error reporting.
1742 * @param site The class type to be checked.
1743 */
1744 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1745 Type sup = types.supertype(site);
1746 if (!sup.hasTag(CLASS)) return;
1748 for (Type t1 = sup;
1749 t1.tsym.type.isParameterized();
1750 t1 = types.supertype(t1)) {
1751 for (Scope.Entry e1 = t1.tsym.members().elems;
1752 e1 != null;
1753 e1 = e1.sibling) {
1754 Symbol s1 = e1.sym;
1755 if (s1.kind != MTH ||
1756 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1757 !s1.isInheritedIn(site.tsym, types) ||
1758 ((MethodSymbol)s1).implementation(site.tsym,
1759 types,
1760 true) != s1)
1761 continue;
1762 Type st1 = types.memberType(t1, s1);
1763 int s1ArgsLength = st1.getParameterTypes().length();
1764 if (st1 == s1.type) continue;
1766 for (Type t2 = sup;
1767 t2.hasTag(CLASS);
1768 t2 = types.supertype(t2)) {
1769 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1770 e2.scope != null;
1771 e2 = e2.next()) {
1772 Symbol s2 = e2.sym;
1773 if (s2 == s1 ||
1774 s2.kind != MTH ||
1775 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1776 s2.type.getParameterTypes().length() != s1ArgsLength ||
1777 !s2.isInheritedIn(site.tsym, types) ||
1778 ((MethodSymbol)s2).implementation(site.tsym,
1779 types,
1780 true) != s2)
1781 continue;
1782 Type st2 = types.memberType(t2, s2);
1783 if (types.overrideEquivalent(st1, st2))
1784 log.error(pos, "concrete.inheritance.conflict",
1785 s1, t1, s2, t2, sup);
1786 }
1787 }
1788 }
1789 }
1790 }
1792 /** Check that classes (or interfaces) do not each define an abstract
1793 * method with same name and arguments but incompatible return types.
1794 * @param pos Position to be used for error reporting.
1795 * @param t1 The first argument type.
1796 * @param t2 The second argument type.
1797 */
1798 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1799 Type t1,
1800 Type t2) {
1801 return checkCompatibleAbstracts(pos, t1, t2,
1802 types.makeCompoundType(t1, t2));
1803 }
1805 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1806 Type t1,
1807 Type t2,
1808 Type site) {
1809 return firstIncompatibility(pos, t1, t2, site) == null;
1810 }
1812 /** Return the first method which is defined with same args
1813 * but different return types in two given interfaces, or null if none
1814 * exists.
1815 * @param t1 The first type.
1816 * @param t2 The second type.
1817 * @param site The most derived type.
1818 * @returns symbol from t2 that conflicts with one in t1.
1819 */
1820 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1821 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1822 closure(t1, interfaces1);
1823 Map<TypeSymbol,Type> interfaces2;
1824 if (t1 == t2)
1825 interfaces2 = interfaces1;
1826 else
1827 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1829 for (Type t3 : interfaces1.values()) {
1830 for (Type t4 : interfaces2.values()) {
1831 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1832 if (s != null) return s;
1833 }
1834 }
1835 return null;
1836 }
1838 /** Compute all the supertypes of t, indexed by type symbol. */
1839 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1840 if (!t.hasTag(CLASS)) return;
1841 if (typeMap.put(t.tsym, t) == null) {
1842 closure(types.supertype(t), typeMap);
1843 for (Type i : types.interfaces(t))
1844 closure(i, typeMap);
1845 }
1846 }
1848 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1849 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1850 if (!t.hasTag(CLASS)) return;
1851 if (typesSkip.get(t.tsym) != null) return;
1852 if (typeMap.put(t.tsym, t) == null) {
1853 closure(types.supertype(t), typesSkip, typeMap);
1854 for (Type i : types.interfaces(t))
1855 closure(i, typesSkip, typeMap);
1856 }
1857 }
1859 /** Return the first method in t2 that conflicts with a method from t1. */
1860 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1861 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1862 Symbol s1 = e1.sym;
1863 Type st1 = null;
1864 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1865 (s1.flags() & SYNTHETIC) != 0) continue;
1866 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1867 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1868 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1869 Symbol s2 = e2.sym;
1870 if (s1 == s2) continue;
1871 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1872 (s2.flags() & SYNTHETIC) != 0) continue;
1873 if (st1 == null) st1 = types.memberType(t1, s1);
1874 Type st2 = types.memberType(t2, s2);
1875 if (types.overrideEquivalent(st1, st2)) {
1876 List<Type> tvars1 = st1.getTypeArguments();
1877 List<Type> tvars2 = st2.getTypeArguments();
1878 Type rt1 = st1.getReturnType();
1879 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1880 boolean compat =
1881 types.isSameType(rt1, rt2) ||
1882 !rt1.isPrimitiveOrVoid() &&
1883 !rt2.isPrimitiveOrVoid() &&
1884 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1885 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1886 checkCommonOverriderIn(s1,s2,site);
1887 if (!compat) {
1888 log.error(pos, "types.incompatible.diff.ret",
1889 t1, t2, s2.name +
1890 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1891 return s2;
1892 }
1893 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1894 !checkCommonOverriderIn(s1, s2, site)) {
1895 log.error(pos,
1896 "name.clash.same.erasure.no.override",
1897 s1, s1.location(),
1898 s2, s2.location());
1899 return s2;
1900 }
1901 }
1902 }
1903 return null;
1904 }
1905 //WHERE
1906 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1907 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1908 Type st1 = types.memberType(site, s1);
1909 Type st2 = types.memberType(site, s2);
1910 closure(site, supertypes);
1911 for (Type t : supertypes.values()) {
1912 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1913 Symbol s3 = e.sym;
1914 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1915 Type st3 = types.memberType(site,s3);
1916 if (types.overrideEquivalent(st3, st1) &&
1917 types.overrideEquivalent(st3, st2) &&
1918 types.returnTypeSubstitutable(st3, st1) &&
1919 types.returnTypeSubstitutable(st3, st2)) {
1920 return true;
1921 }
1922 }
1923 }
1924 return false;
1925 }
1927 /** Check that a given method conforms with any method it overrides.
1928 * @param tree The tree from which positions are extracted
1929 * for errors.
1930 * @param m The overriding method.
1931 */
1932 void checkOverride(JCTree tree, MethodSymbol m) {
1933 ClassSymbol origin = (ClassSymbol)m.owner;
1934 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1935 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1936 log.error(tree.pos(), "enum.no.finalize");
1937 return;
1938 }
1939 for (Type t = origin.type; t.hasTag(CLASS);
1940 t = types.supertype(t)) {
1941 if (t != origin.type) {
1942 checkOverride(tree, t, origin, m);
1943 }
1944 for (Type t2 : types.interfaces(t)) {
1945 checkOverride(tree, t2, origin, m);
1946 }
1947 }
1948 }
1950 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1951 TypeSymbol c = site.tsym;
1952 Scope.Entry e = c.members().lookup(m.name);
1953 while (e.scope != null) {
1954 if (m.overrides(e.sym, origin, types, false)) {
1955 if ((e.sym.flags() & ABSTRACT) == 0) {
1956 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1957 }
1958 }
1959 e = e.next();
1960 }
1961 }
1963 private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
1964 public boolean accepts(Symbol s) {
1965 return MethodSymbol.implementation_filter.accepts(s) &&
1966 (s.flags() & BAD_OVERRIDE) == 0;
1968 }
1969 };
1971 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
1972 ClassSymbol someClass) {
1973 /* At present, annotations cannot possibly have a method that is override
1974 * equivalent with Object.equals(Object) but in any case the condition is
1975 * fine for completeness.
1976 */
1977 if (someClass == (ClassSymbol)syms.objectType.tsym ||
1978 someClass.isInterface() || someClass.isEnum() ||
1979 (someClass.flags() & ANNOTATION) != 0 ||
1980 (someClass.flags() & ABSTRACT) != 0) return;
1981 //anonymous inner classes implementing interfaces need especial treatment
1982 if (someClass.isAnonymous()) {
1983 List<Type> interfaces = types.interfaces(someClass.type);
1984 if (interfaces != null && !interfaces.isEmpty() &&
1985 interfaces.head.tsym == syms.comparatorType.tsym) return;
1986 }
1987 checkClassOverrideEqualsAndHash(pos, someClass);
1988 }
1990 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
1991 ClassSymbol someClass) {
1992 if (lint.isEnabled(LintCategory.OVERRIDES)) {
1993 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
1994 .tsym.members().lookup(names.equals).sym;
1995 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
1996 .tsym.members().lookup(names.hashCode).sym;
1997 boolean overridesEquals = types.implementation(equalsAtObject,
1998 someClass, false, equalsHasCodeFilter).owner == someClass;
1999 boolean overridesHashCode = types.implementation(hashCodeAtObject,
2000 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2002 if (overridesEquals && !overridesHashCode) {
2003 log.warning(LintCategory.OVERRIDES, pos,
2004 "override.equals.but.not.hashcode", someClass);
2005 }
2006 }
2007 }
2009 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2010 ClashFilter cf = new ClashFilter(origin.type);
2011 return (cf.accepts(s1) &&
2012 cf.accepts(s2) &&
2013 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2014 }
2017 /** Check that all abstract members of given class have definitions.
2018 * @param pos Position to be used for error reporting.
2019 * @param c The class.
2020 */
2021 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2022 try {
2023 MethodSymbol undef = firstUndef(c, c);
2024 if (undef != null) {
2025 if ((c.flags() & ENUM) != 0 &&
2026 types.supertype(c.type).tsym == syms.enumSym &&
2027 (c.flags() & FINAL) == 0) {
2028 // add the ABSTRACT flag to an enum
2029 c.flags_field |= ABSTRACT;
2030 } else {
2031 MethodSymbol undef1 =
2032 new MethodSymbol(undef.flags(), undef.name,
2033 types.memberType(c.type, undef), undef.owner);
2034 log.error(pos, "does.not.override.abstract",
2035 c, undef1, undef1.location());
2036 }
2037 }
2038 } catch (CompletionFailure ex) {
2039 completionError(pos, ex);
2040 }
2041 }
2042 //where
2043 /** Return first abstract member of class `c' that is not defined
2044 * in `impl', null if there is none.
2045 */
2046 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
2047 MethodSymbol undef = null;
2048 // Do not bother to search in classes that are not abstract,
2049 // since they cannot have abstract members.
2050 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2051 Scope s = c.members();
2052 for (Scope.Entry e = s.elems;
2053 undef == null && e != null;
2054 e = e.sibling) {
2055 if (e.sym.kind == MTH &&
2056 (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
2057 MethodSymbol absmeth = (MethodSymbol)e.sym;
2058 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
2059 if (implmeth == null || implmeth == absmeth) {
2060 //look for default implementations
2061 if (allowDefaultMethods) {
2062 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
2063 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
2064 implmeth = prov;
2065 }
2066 }
2067 }
2068 if (implmeth == null || implmeth == absmeth) {
2069 undef = absmeth;
2070 }
2071 }
2072 }
2073 if (undef == null) {
2074 Type st = types.supertype(c.type);
2075 if (st.hasTag(CLASS))
2076 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2077 }
2078 for (List<Type> l = types.interfaces(c.type);
2079 undef == null && l.nonEmpty();
2080 l = l.tail) {
2081 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2082 }
2083 }
2084 return undef;
2085 }
2087 void checkNonCyclicDecl(JCClassDecl tree) {
2088 CycleChecker cc = new CycleChecker();
2089 cc.scan(tree);
2090 if (!cc.errorFound && !cc.partialCheck) {
2091 tree.sym.flags_field |= ACYCLIC;
2092 }
2093 }
2095 class CycleChecker extends TreeScanner {
2097 List<Symbol> seenClasses = List.nil();
2098 boolean errorFound = false;
2099 boolean partialCheck = false;
2101 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2102 if (sym != null && sym.kind == TYP) {
2103 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2104 if (classEnv != null) {
2105 DiagnosticSource prevSource = log.currentSource();
2106 try {
2107 log.useSource(classEnv.toplevel.sourcefile);
2108 scan(classEnv.tree);
2109 }
2110 finally {
2111 log.useSource(prevSource.getFile());
2112 }
2113 } else if (sym.kind == TYP) {
2114 checkClass(pos, sym, List.<JCTree>nil());
2115 }
2116 } else {
2117 //not completed yet
2118 partialCheck = true;
2119 }
2120 }
2122 @Override
2123 public void visitSelect(JCFieldAccess tree) {
2124 super.visitSelect(tree);
2125 checkSymbol(tree.pos(), tree.sym);
2126 }
2128 @Override
2129 public void visitIdent(JCIdent tree) {
2130 checkSymbol(tree.pos(), tree.sym);
2131 }
2133 @Override
2134 public void visitTypeApply(JCTypeApply tree) {
2135 scan(tree.clazz);
2136 }
2138 @Override
2139 public void visitTypeArray(JCArrayTypeTree tree) {
2140 scan(tree.elemtype);
2141 }
2143 @Override
2144 public void visitClassDef(JCClassDecl tree) {
2145 List<JCTree> supertypes = List.nil();
2146 if (tree.getExtendsClause() != null) {
2147 supertypes = supertypes.prepend(tree.getExtendsClause());
2148 }
2149 if (tree.getImplementsClause() != null) {
2150 for (JCTree intf : tree.getImplementsClause()) {
2151 supertypes = supertypes.prepend(intf);
2152 }
2153 }
2154 checkClass(tree.pos(), tree.sym, supertypes);
2155 }
2157 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2158 if ((c.flags_field & ACYCLIC) != 0)
2159 return;
2160 if (seenClasses.contains(c)) {
2161 errorFound = true;
2162 noteCyclic(pos, (ClassSymbol)c);
2163 } else if (!c.type.isErroneous()) {
2164 try {
2165 seenClasses = seenClasses.prepend(c);
2166 if (c.type.hasTag(CLASS)) {
2167 if (supertypes.nonEmpty()) {
2168 scan(supertypes);
2169 }
2170 else {
2171 ClassType ct = (ClassType)c.type;
2172 if (ct.supertype_field == null ||
2173 ct.interfaces_field == null) {
2174 //not completed yet
2175 partialCheck = true;
2176 return;
2177 }
2178 checkSymbol(pos, ct.supertype_field.tsym);
2179 for (Type intf : ct.interfaces_field) {
2180 checkSymbol(pos, intf.tsym);
2181 }
2182 }
2183 if (c.owner.kind == TYP) {
2184 checkSymbol(pos, c.owner);
2185 }
2186 }
2187 } finally {
2188 seenClasses = seenClasses.tail;
2189 }
2190 }
2191 }
2192 }
2194 /** Check for cyclic references. Issue an error if the
2195 * symbol of the type referred to has a LOCKED flag set.
2196 *
2197 * @param pos Position to be used for error reporting.
2198 * @param t The type referred to.
2199 */
2200 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2201 checkNonCyclicInternal(pos, t);
2202 }
2205 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2206 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2207 }
2209 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2210 final TypeVar tv;
2211 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2212 return;
2213 if (seen.contains(t)) {
2214 tv = (TypeVar)t;
2215 tv.bound = types.createErrorType(t);
2216 log.error(pos, "cyclic.inheritance", t);
2217 } else if (t.hasTag(TYPEVAR)) {
2218 tv = (TypeVar)t;
2219 seen = seen.prepend(tv);
2220 for (Type b : types.getBounds(tv))
2221 checkNonCyclic1(pos, b, seen);
2222 }
2223 }
2225 /** Check for cyclic references. Issue an error if the
2226 * symbol of the type referred to has a LOCKED flag set.
2227 *
2228 * @param pos Position to be used for error reporting.
2229 * @param t The type referred to.
2230 * @returns True if the check completed on all attributed classes
2231 */
2232 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2233 boolean complete = true; // was the check complete?
2234 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2235 Symbol c = t.tsym;
2236 if ((c.flags_field & ACYCLIC) != 0) return true;
2238 if ((c.flags_field & LOCKED) != 0) {
2239 noteCyclic(pos, (ClassSymbol)c);
2240 } else if (!c.type.isErroneous()) {
2241 try {
2242 c.flags_field |= LOCKED;
2243 if (c.type.hasTag(CLASS)) {
2244 ClassType clazz = (ClassType)c.type;
2245 if (clazz.interfaces_field != null)
2246 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2247 complete &= checkNonCyclicInternal(pos, l.head);
2248 if (clazz.supertype_field != null) {
2249 Type st = clazz.supertype_field;
2250 if (st != null && st.hasTag(CLASS))
2251 complete &= checkNonCyclicInternal(pos, st);
2252 }
2253 if (c.owner.kind == TYP)
2254 complete &= checkNonCyclicInternal(pos, c.owner.type);
2255 }
2256 } finally {
2257 c.flags_field &= ~LOCKED;
2258 }
2259 }
2260 if (complete)
2261 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2262 if (complete) c.flags_field |= ACYCLIC;
2263 return complete;
2264 }
2266 /** Note that we found an inheritance cycle. */
2267 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2268 log.error(pos, "cyclic.inheritance", c);
2269 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2270 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2271 Type st = types.supertype(c.type);
2272 if (st.hasTag(CLASS))
2273 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2274 c.type = types.createErrorType(c, c.type);
2275 c.flags_field |= ACYCLIC;
2276 }
2278 /**
2279 * Check that functional interface methods would make sense when seen
2280 * from the perspective of the implementing class
2281 */
2282 void checkFunctionalInterface(JCTree tree, Type funcInterface) {
2283 ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
2284 ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
2285 c.interfaces_field = List.of(types.removeWildcards(funcInterface));
2286 c.supertype_field = syms.objectType;
2287 c.tsym = csym;
2288 csym.members_field = new Scope(csym);
2289 Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
2290 Type descType = types.findDescriptorType(funcInterface);
2291 csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
2292 csym.completer = null;
2293 checkImplementations(tree, csym, csym);
2294 }
2296 /** Check that all methods which implement some
2297 * method conform to the method they implement.
2298 * @param tree The class definition whose members are checked.
2299 */
2300 void checkImplementations(JCClassDecl tree) {
2301 checkImplementations(tree, tree.sym, tree.sym);
2302 }
2303 //where
2304 /** Check that all methods which implement some
2305 * method in `ic' conform to the method they implement.
2306 */
2307 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2308 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2309 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2310 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2311 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2312 if (e.sym.kind == MTH &&
2313 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2314 MethodSymbol absmeth = (MethodSymbol)e.sym;
2315 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2316 if (implmeth != null && implmeth != absmeth &&
2317 (implmeth.owner.flags() & INTERFACE) ==
2318 (origin.flags() & INTERFACE)) {
2319 // don't check if implmeth is in a class, yet
2320 // origin is an interface. This case arises only
2321 // if implmeth is declared in Object. The reason is
2322 // that interfaces really don't inherit from
2323 // Object it's just that the compiler represents
2324 // things that way.
2325 checkOverride(tree, implmeth, absmeth, origin);
2326 }
2327 }
2328 }
2329 }
2330 }
2331 }
2333 /** Check that all abstract methods implemented by a class are
2334 * mutually compatible.
2335 * @param pos Position to be used for error reporting.
2336 * @param c The class whose interfaces are checked.
2337 */
2338 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2339 List<Type> supertypes = types.interfaces(c);
2340 Type supertype = types.supertype(c);
2341 if (supertype.hasTag(CLASS) &&
2342 (supertype.tsym.flags() & ABSTRACT) != 0)
2343 supertypes = supertypes.prepend(supertype);
2344 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2345 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2346 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2347 return;
2348 for (List<Type> m = supertypes; m != l; m = m.tail)
2349 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2350 return;
2351 }
2352 checkCompatibleConcretes(pos, c);
2353 }
2355 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2356 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2357 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2358 // VM allows methods and variables with differing types
2359 if (sym.kind == e.sym.kind &&
2360 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2361 sym != e.sym &&
2362 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2363 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2364 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2365 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2366 return;
2367 }
2368 }
2369 }
2370 }
2372 /** Check that all non-override equivalent methods accessible from 'site'
2373 * are mutually compatible (JLS 8.4.8/9.4.1).
2374 *
2375 * @param pos Position to be used for error reporting.
2376 * @param site The class whose methods are checked.
2377 * @param sym The method symbol to be checked.
2378 */
2379 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2380 ClashFilter cf = new ClashFilter(site);
2381 //for each method m1 that is overridden (directly or indirectly)
2382 //by method 'sym' in 'site'...
2383 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2384 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2385 //...check each method m2 that is a member of 'site'
2386 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2387 if (m2 == m1) continue;
2388 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2389 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2390 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2391 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2392 sym.flags_field |= CLASH;
2393 String key = m1 == sym ?
2394 "name.clash.same.erasure.no.override" :
2395 "name.clash.same.erasure.no.override.1";
2396 log.error(pos,
2397 key,
2398 sym, sym.location(),
2399 m2, m2.location(),
2400 m1, m1.location());
2401 return;
2402 }
2403 }
2404 }
2405 }
2409 /** Check that all static methods accessible from 'site' are
2410 * mutually compatible (JLS 8.4.8).
2411 *
2412 * @param pos Position to be used for error reporting.
2413 * @param site The class whose methods are checked.
2414 * @param sym The method symbol to be checked.
2415 */
2416 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2417 ClashFilter cf = new ClashFilter(site);
2418 //for each method m1 that is a member of 'site'...
2419 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2420 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2421 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2422 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
2423 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2424 log.error(pos,
2425 "name.clash.same.erasure.no.hide",
2426 sym, sym.location(),
2427 s, s.location());
2428 return;
2429 }
2430 }
2431 }
2433 //where
2434 private class ClashFilter implements Filter<Symbol> {
2436 Type site;
2438 ClashFilter(Type site) {
2439 this.site = site;
2440 }
2442 boolean shouldSkip(Symbol s) {
2443 return (s.flags() & CLASH) != 0 &&
2444 s.owner == site.tsym;
2445 }
2447 public boolean accepts(Symbol s) {
2448 return s.kind == MTH &&
2449 (s.flags() & SYNTHETIC) == 0 &&
2450 !shouldSkip(s) &&
2451 s.isInheritedIn(site.tsym, types) &&
2452 !s.isConstructor();
2453 }
2454 }
2456 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2457 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2458 for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
2459 Assert.check(m.kind == MTH);
2460 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2461 if (prov.size() > 1) {
2462 ListBuffer<Symbol> abstracts = ListBuffer.lb();
2463 ListBuffer<Symbol> defaults = ListBuffer.lb();
2464 for (MethodSymbol provSym : prov) {
2465 if ((provSym.flags() & DEFAULT) != 0) {
2466 defaults = defaults.append(provSym);
2467 } else if ((provSym.flags() & ABSTRACT) != 0) {
2468 abstracts = abstracts.append(provSym);
2469 }
2470 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2471 //strong semantics - issue an error if two sibling interfaces
2472 //have two override-equivalent defaults - or if one is abstract
2473 //and the other is default
2474 String errKey;
2475 Symbol s1 = defaults.first();
2476 Symbol s2;
2477 if (defaults.size() > 1) {
2478 errKey = "types.incompatible.unrelated.defaults";
2479 s2 = defaults.toList().tail.head;
2480 } else {
2481 errKey = "types.incompatible.abstract.default";
2482 s2 = abstracts.first();
2483 }
2484 log.error(pos, errKey,
2485 Kinds.kindName(site.tsym), site,
2486 m.name, types.memberType(site, m).getParameterTypes(),
2487 s1.location(), s2.location());
2488 break;
2489 }
2490 }
2491 }
2492 }
2493 }
2495 //where
2496 private class DefaultMethodClashFilter implements Filter<Symbol> {
2498 Type site;
2500 DefaultMethodClashFilter(Type site) {
2501 this.site = site;
2502 }
2504 public boolean accepts(Symbol s) {
2505 return s.kind == MTH &&
2506 (s.flags() & DEFAULT) != 0 &&
2507 s.isInheritedIn(site.tsym, types) &&
2508 !s.isConstructor();
2509 }
2510 }
2512 /** Report a conflict between a user symbol and a synthetic symbol.
2513 */
2514 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2515 if (!sym.type.isErroneous()) {
2516 if (warnOnSyntheticConflicts) {
2517 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2518 }
2519 else {
2520 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2521 }
2522 }
2523 }
2525 /** Check that class c does not implement directly or indirectly
2526 * the same parameterized interface with two different argument lists.
2527 * @param pos Position to be used for error reporting.
2528 * @param type The type whose interfaces are checked.
2529 */
2530 void checkClassBounds(DiagnosticPosition pos, Type type) {
2531 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2532 }
2533 //where
2534 /** Enter all interfaces of type `type' into the hash table `seensofar'
2535 * with their class symbol as key and their type as value. Make
2536 * sure no class is entered with two different types.
2537 */
2538 void checkClassBounds(DiagnosticPosition pos,
2539 Map<TypeSymbol,Type> seensofar,
2540 Type type) {
2541 if (type.isErroneous()) return;
2542 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2543 Type it = l.head;
2544 Type oldit = seensofar.put(it.tsym, it);
2545 if (oldit != null) {
2546 List<Type> oldparams = oldit.allparams();
2547 List<Type> newparams = it.allparams();
2548 if (!types.containsTypeEquivalent(oldparams, newparams))
2549 log.error(pos, "cant.inherit.diff.arg",
2550 it.tsym, Type.toString(oldparams),
2551 Type.toString(newparams));
2552 }
2553 checkClassBounds(pos, seensofar, it);
2554 }
2555 Type st = types.supertype(type);
2556 if (st != null) checkClassBounds(pos, seensofar, st);
2557 }
2559 /** Enter interface into into set.
2560 * If it existed already, issue a "repeated interface" error.
2561 */
2562 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2563 if (its.contains(it))
2564 log.error(pos, "repeated.interface");
2565 else {
2566 its.add(it);
2567 }
2568 }
2570 /* *************************************************************************
2571 * Check annotations
2572 **************************************************************************/
2574 /**
2575 * Recursively validate annotations values
2576 */
2577 void validateAnnotationTree(JCTree tree) {
2578 class AnnotationValidator extends TreeScanner {
2579 @Override
2580 public void visitAnnotation(JCAnnotation tree) {
2581 if (!tree.type.isErroneous()) {
2582 super.visitAnnotation(tree);
2583 validateAnnotation(tree);
2584 }
2585 }
2586 }
2587 tree.accept(new AnnotationValidator());
2588 }
2590 /**
2591 * {@literal
2592 * Annotation types are restricted to primitives, String, an
2593 * enum, an annotation, Class, Class<?>, Class<? extends
2594 * Anything>, arrays of the preceding.
2595 * }
2596 */
2597 void validateAnnotationType(JCTree restype) {
2598 // restype may be null if an error occurred, so don't bother validating it
2599 if (restype != null) {
2600 validateAnnotationType(restype.pos(), restype.type);
2601 }
2602 }
2604 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2605 if (type.isPrimitive()) return;
2606 if (types.isSameType(type, syms.stringType)) return;
2607 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2608 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2609 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2610 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2611 validateAnnotationType(pos, types.elemtype(type));
2612 return;
2613 }
2614 log.error(pos, "invalid.annotation.member.type");
2615 }
2617 /**
2618 * "It is also a compile-time error if any method declared in an
2619 * annotation type has a signature that is override-equivalent to
2620 * that of any public or protected method declared in class Object
2621 * or in the interface annotation.Annotation."
2622 *
2623 * @jls 9.6 Annotation Types
2624 */
2625 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2626 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2627 Scope s = sup.tsym.members();
2628 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2629 if (e.sym.kind == MTH &&
2630 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2631 types.overrideEquivalent(m.type, e.sym.type))
2632 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2633 }
2634 }
2635 }
2637 /** Check the annotations of a symbol.
2638 */
2639 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2640 for (JCAnnotation a : annotations)
2641 validateAnnotation(a, s);
2642 }
2644 /** Check the type annotations.
2645 */
2646 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2647 for (JCAnnotation a : annotations)
2648 validateTypeAnnotation(a, isTypeParameter);
2649 }
2651 /** Check an annotation of a symbol.
2652 */
2653 private void validateAnnotation(JCAnnotation a, Symbol s) {
2654 validateAnnotationTree(a);
2656 if (!annotationApplicable(a, s))
2657 log.error(a.pos(), "annotation.type.not.applicable");
2659 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2660 if (!isOverrider(s))
2661 log.error(a.pos(), "method.does.not.override.superclass");
2662 }
2664 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2665 if (s.kind != TYP) {
2666 log.error(a.pos(), "bad.functional.intf.anno");
2667 } else {
2668 try {
2669 types.findDescriptorSymbol((TypeSymbol)s);
2670 } catch (Types.FunctionDescriptorLookupError ex) {
2671 log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
2672 }
2673 }
2674 }
2675 }
2677 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2678 Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
2679 validateAnnotationTree(a);
2681 if (!isTypeAnnotation(a, isTypeParameter))
2682 log.error(a.pos(), "annotation.type.not.applicable");
2683 }
2685 /**
2686 * Validate the proposed container 'repeatable' on the
2687 * annotation type symbol 's'. Report errors at position
2688 * 'pos'.
2689 *
2690 * @param s The (annotation)type declaration annotated with a @Repeatable
2691 * @param repeatable the @Repeatable on 's'
2692 * @param pos where to report errors
2693 */
2694 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2695 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2697 Type t = null;
2698 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2699 if (!l.isEmpty()) {
2700 Assert.check(l.head.fst.name == names.value);
2701 t = ((Attribute.Class)l.head.snd).getValue();
2702 }
2704 if (t == null) {
2705 // errors should already have been reported during Annotate
2706 return;
2707 }
2709 validateValue(t.tsym, s, pos);
2710 validateRetention(t.tsym, s, pos);
2711 validateDocumented(t.tsym, s, pos);
2712 validateInherited(t.tsym, s, pos);
2713 validateTarget(t.tsym, s, pos);
2714 validateDefault(t.tsym, s, pos);
2715 }
2717 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2718 Scope.Entry e = container.members().lookup(names.value);
2719 if (e.scope != null && e.sym.kind == MTH) {
2720 MethodSymbol m = (MethodSymbol) e.sym;
2721 Type ret = m.getReturnType();
2722 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2723 log.error(pos, "invalid.repeatable.annotation.value.return",
2724 container, ret, types.makeArrayType(contained.type));
2725 }
2726 } else {
2727 log.error(pos, "invalid.repeatable.annotation.no.value", container);
2728 }
2729 }
2731 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2732 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2733 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2735 boolean error = false;
2736 switch (containedRetention) {
2737 case RUNTIME:
2738 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2739 error = true;
2740 }
2741 break;
2742 case CLASS:
2743 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2744 error = true;
2745 }
2746 }
2747 if (error ) {
2748 log.error(pos, "invalid.repeatable.annotation.retention",
2749 container, containerRetention,
2750 contained, containedRetention);
2751 }
2752 }
2754 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2755 if (contained.attribute(syms.documentedType.tsym) != null) {
2756 if (container.attribute(syms.documentedType.tsym) == null) {
2757 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2758 }
2759 }
2760 }
2762 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2763 if (contained.attribute(syms.inheritedType.tsym) != null) {
2764 if (container.attribute(syms.inheritedType.tsym) == null) {
2765 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2766 }
2767 }
2768 }
2770 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2771 // The set of targets the container is applicable to must be a subset
2772 // (with respect to annotation target semantics) of the set of targets
2773 // the contained is applicable to. The target sets may be implicit or
2774 // explicit.
2776 Set<Name> containerTargets;
2777 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2778 if (containerTarget == null) {
2779 containerTargets = getDefaultTargetSet();
2780 } else {
2781 containerTargets = new HashSet<Name>();
2782 for (Attribute app : containerTarget.values) {
2783 if (!(app instanceof Attribute.Enum)) {
2784 continue; // recovery
2785 }
2786 Attribute.Enum e = (Attribute.Enum)app;
2787 containerTargets.add(e.value.name);
2788 }
2789 }
2791 Set<Name> containedTargets;
2792 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2793 if (containedTarget == null) {
2794 containedTargets = getDefaultTargetSet();
2795 } else {
2796 containedTargets = new HashSet<Name>();
2797 for (Attribute app : containedTarget.values) {
2798 if (!(app instanceof Attribute.Enum)) {
2799 continue; // recovery
2800 }
2801 Attribute.Enum e = (Attribute.Enum)app;
2802 containedTargets.add(e.value.name);
2803 }
2804 }
2806 if (!isTargetSubsetOf(containerTargets, containedTargets)) {
2807 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2808 }
2809 }
2811 /* get a set of names for the default target */
2812 private Set<Name> getDefaultTargetSet() {
2813 if (defaultTargets == null) {
2814 Set<Name> targets = new HashSet<Name>();
2815 targets.add(names.ANNOTATION_TYPE);
2816 targets.add(names.CONSTRUCTOR);
2817 targets.add(names.FIELD);
2818 targets.add(names.LOCAL_VARIABLE);
2819 targets.add(names.METHOD);
2820 targets.add(names.PACKAGE);
2821 targets.add(names.PARAMETER);
2822 targets.add(names.TYPE);
2824 defaultTargets = java.util.Collections.unmodifiableSet(targets);
2825 }
2827 return defaultTargets;
2828 }
2829 private Set<Name> defaultTargets;
2832 /** Checks that s is a subset of t, with respect to ElementType
2833 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2834 */
2835 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
2836 // Check that all elements in s are present in t
2837 for (Name n2 : s) {
2838 boolean currentElementOk = false;
2839 for (Name n1 : t) {
2840 if (n1 == n2) {
2841 currentElementOk = true;
2842 break;
2843 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2844 currentElementOk = true;
2845 break;
2846 }
2847 }
2848 if (!currentElementOk)
2849 return false;
2850 }
2851 return true;
2852 }
2854 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2855 // validate that all other elements of containing type has defaults
2856 Scope scope = container.members();
2857 for(Symbol elm : scope.getElements()) {
2858 if (elm.name != names.value &&
2859 elm.kind == Kinds.MTH &&
2860 ((MethodSymbol)elm).defaultValue == null) {
2861 log.error(pos,
2862 "invalid.repeatable.annotation.elem.nondefault",
2863 container,
2864 elm);
2865 }
2866 }
2867 }
2869 /** Is s a method symbol that overrides a method in a superclass? */
2870 boolean isOverrider(Symbol s) {
2871 if (s.kind != MTH || s.isStatic())
2872 return false;
2873 MethodSymbol m = (MethodSymbol)s;
2874 TypeSymbol owner = (TypeSymbol)m.owner;
2875 for (Type sup : types.closure(owner.type)) {
2876 if (sup == owner.type)
2877 continue; // skip "this"
2878 Scope scope = sup.tsym.members();
2879 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2880 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2881 return true;
2882 }
2883 }
2884 return false;
2885 }
2887 /** Is the annotation applicable to type annotations? */
2888 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2889 Attribute.Compound atTarget =
2890 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2891 if (atTarget == null) {
2892 // An annotation without @Target is not a type annotation.
2893 return false;
2894 }
2896 Attribute atValue = atTarget.member(names.value);
2897 if (!(atValue instanceof Attribute.Array)) {
2898 return false; // error recovery
2899 }
2901 Attribute.Array arr = (Attribute.Array) atValue;
2902 for (Attribute app : arr.values) {
2903 if (!(app instanceof Attribute.Enum)) {
2904 return false; // recovery
2905 }
2906 Attribute.Enum e = (Attribute.Enum) app;
2908 if (e.value.name == names.TYPE_USE)
2909 return true;
2910 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2911 return true;
2912 }
2913 return false;
2914 }
2916 /** Is the annotation applicable to the symbol? */
2917 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2918 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2919 Name[] targets;
2921 if (arr == null) {
2922 targets = defaultTargetMetaInfo(a, s);
2923 } else {
2924 // TODO: can we optimize this?
2925 targets = new Name[arr.values.length];
2926 for (int i=0; i<arr.values.length; ++i) {
2927 Attribute app = arr.values[i];
2928 if (!(app instanceof Attribute.Enum)) {
2929 return true; // recovery
2930 }
2931 Attribute.Enum e = (Attribute.Enum) app;
2932 targets[i] = e.value.name;
2933 }
2934 }
2935 for (Name target : targets) {
2936 if (target == names.TYPE)
2937 { if (s.kind == TYP) return true; }
2938 else if (target == names.FIELD)
2939 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2940 else if (target == names.METHOD)
2941 { if (s.kind == MTH && !s.isConstructor()) return true; }
2942 else if (target == names.PARAMETER)
2943 { if (s.kind == VAR &&
2944 s.owner.kind == MTH &&
2945 (s.flags() & PARAMETER) != 0)
2946 return true;
2947 }
2948 else if (target == names.CONSTRUCTOR)
2949 { if (s.kind == MTH && s.isConstructor()) return true; }
2950 else if (target == names.LOCAL_VARIABLE)
2951 { if (s.kind == VAR && s.owner.kind == MTH &&
2952 (s.flags() & PARAMETER) == 0)
2953 return true;
2954 }
2955 else if (target == names.ANNOTATION_TYPE)
2956 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2957 return true;
2958 }
2959 else if (target == names.PACKAGE)
2960 { if (s.kind == PCK) return true; }
2961 else if (target == names.TYPE_USE)
2962 { if (s.kind == TYP ||
2963 s.kind == VAR ||
2964 (s.kind == MTH && !s.isConstructor() &&
2965 !s.type.getReturnType().hasTag(VOID)) ||
2966 (s.kind == MTH && s.isConstructor()))
2967 return true;
2968 }
2969 else if (target == names.TYPE_PARAMETER)
2970 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
2971 return true;
2972 }
2973 else
2974 return true; // recovery
2975 }
2976 return false;
2977 }
2980 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2981 Attribute.Compound atTarget =
2982 s.attribute(syms.annotationTargetType.tsym);
2983 if (atTarget == null) return null; // ok, is applicable
2984 Attribute atValue = atTarget.member(names.value);
2985 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2986 return (Attribute.Array) atValue;
2987 }
2989 private final Name[] dfltTargetMeta;
2990 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
2991 return dfltTargetMeta;
2992 }
2994 /** Check an annotation value.
2995 *
2996 * @param a The annotation tree to check
2997 * @return true if this annotation tree is valid, otherwise false
2998 */
2999 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3000 boolean res = false;
3001 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3002 try {
3003 res = validateAnnotation(a);
3004 } finally {
3005 log.popDiagnosticHandler(diagHandler);
3006 }
3007 return res;
3008 }
3010 private boolean validateAnnotation(JCAnnotation a) {
3011 boolean isValid = true;
3012 // collect an inventory of the annotation elements
3013 Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
3014 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
3015 e != null;
3016 e = e.sibling)
3017 if (e.sym.kind == MTH && e.sym.name != names.clinit)
3018 members.add((MethodSymbol) e.sym);
3020 // remove the ones that are assigned values
3021 for (JCTree arg : a.args) {
3022 if (!arg.hasTag(ASSIGN)) continue; // recovery
3023 JCAssign assign = (JCAssign) arg;
3024 Symbol m = TreeInfo.symbol(assign.lhs);
3025 if (m == null || m.type.isErroneous()) continue;
3026 if (!members.remove(m)) {
3027 isValid = false;
3028 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3029 m.name, a.type);
3030 }
3031 }
3033 // all the remaining ones better have default values
3034 List<Name> missingDefaults = List.nil();
3035 for (MethodSymbol m : members) {
3036 if (m.defaultValue == null && !m.type.isErroneous()) {
3037 missingDefaults = missingDefaults.append(m.name);
3038 }
3039 }
3040 missingDefaults = missingDefaults.reverse();
3041 if (missingDefaults.nonEmpty()) {
3042 isValid = false;
3043 String key = (missingDefaults.size() > 1)
3044 ? "annotation.missing.default.value.1"
3045 : "annotation.missing.default.value";
3046 log.error(a.pos(), key, a.type, missingDefaults);
3047 }
3049 // special case: java.lang.annotation.Target must not have
3050 // repeated values in its value member
3051 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3052 a.args.tail == null)
3053 return isValid;
3055 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3056 JCAssign assign = (JCAssign) a.args.head;
3057 Symbol m = TreeInfo.symbol(assign.lhs);
3058 if (m.name != names.value) return false;
3059 JCTree rhs = assign.rhs;
3060 if (!rhs.hasTag(NEWARRAY)) return false;
3061 JCNewArray na = (JCNewArray) rhs;
3062 Set<Symbol> targets = new HashSet<Symbol>();
3063 for (JCTree elem : na.elems) {
3064 if (!targets.add(TreeInfo.symbol(elem))) {
3065 isValid = false;
3066 log.error(elem.pos(), "repeated.annotation.target");
3067 }
3068 }
3069 return isValid;
3070 }
3072 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3073 if (allowAnnotations &&
3074 lint.isEnabled(LintCategory.DEP_ANN) &&
3075 (s.flags() & DEPRECATED) != 0 &&
3076 !syms.deprecatedType.isErroneous() &&
3077 s.attribute(syms.deprecatedType.tsym) == null) {
3078 log.warning(LintCategory.DEP_ANN,
3079 pos, "missing.deprecated.annotation");
3080 }
3081 }
3083 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3084 if ((s.flags() & DEPRECATED) != 0 &&
3085 (other.flags() & DEPRECATED) == 0 &&
3086 s.outermostClass() != other.outermostClass()) {
3087 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3088 @Override
3089 public void report() {
3090 warnDeprecated(pos, s);
3091 }
3092 });
3093 }
3094 }
3096 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3097 if ((s.flags() & PROPRIETARY) != 0) {
3098 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
3099 public void report() {
3100 if (enableSunApiLintControl)
3101 warnSunApi(pos, "sun.proprietary", s);
3102 else
3103 log.mandatoryWarning(pos, "sun.proprietary", s);
3104 }
3105 });
3106 }
3107 }
3109 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3110 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3111 log.error(pos, "not.in.profile", s, profile);
3112 }
3113 }
3115 /* *************************************************************************
3116 * Check for recursive annotation elements.
3117 **************************************************************************/
3119 /** Check for cycles in the graph of annotation elements.
3120 */
3121 void checkNonCyclicElements(JCClassDecl tree) {
3122 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3123 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3124 try {
3125 tree.sym.flags_field |= LOCKED;
3126 for (JCTree def : tree.defs) {
3127 if (!def.hasTag(METHODDEF)) continue;
3128 JCMethodDecl meth = (JCMethodDecl)def;
3129 checkAnnotationResType(meth.pos(), meth.restype.type);
3130 }
3131 } finally {
3132 tree.sym.flags_field &= ~LOCKED;
3133 tree.sym.flags_field |= ACYCLIC_ANN;
3134 }
3135 }
3137 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3138 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3139 return;
3140 if ((tsym.flags_field & LOCKED) != 0) {
3141 log.error(pos, "cyclic.annotation.element");
3142 return;
3143 }
3144 try {
3145 tsym.flags_field |= LOCKED;
3146 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3147 Symbol s = e.sym;
3148 if (s.kind != Kinds.MTH)
3149 continue;
3150 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3151 }
3152 } finally {
3153 tsym.flags_field &= ~LOCKED;
3154 tsym.flags_field |= ACYCLIC_ANN;
3155 }
3156 }
3158 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3159 switch (type.getTag()) {
3160 case CLASS:
3161 if ((type.tsym.flags() & ANNOTATION) != 0)
3162 checkNonCyclicElementsInternal(pos, type.tsym);
3163 break;
3164 case ARRAY:
3165 checkAnnotationResType(pos, types.elemtype(type));
3166 break;
3167 default:
3168 break; // int etc
3169 }
3170 }
3172 /* *************************************************************************
3173 * Check for cycles in the constructor call graph.
3174 **************************************************************************/
3176 /** Check for cycles in the graph of constructors calling other
3177 * constructors.
3178 */
3179 void checkCyclicConstructors(JCClassDecl tree) {
3180 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3182 // enter each constructor this-call into the map
3183 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3184 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3185 if (app == null) continue;
3186 JCMethodDecl meth = (JCMethodDecl) l.head;
3187 if (TreeInfo.name(app.meth) == names._this) {
3188 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3189 } else {
3190 meth.sym.flags_field |= ACYCLIC;
3191 }
3192 }
3194 // Check for cycles in the map
3195 Symbol[] ctors = new Symbol[0];
3196 ctors = callMap.keySet().toArray(ctors);
3197 for (Symbol caller : ctors) {
3198 checkCyclicConstructor(tree, caller, callMap);
3199 }
3200 }
3202 /** Look in the map to see if the given constructor is part of a
3203 * call cycle.
3204 */
3205 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3206 Map<Symbol,Symbol> callMap) {
3207 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3208 if ((ctor.flags_field & LOCKED) != 0) {
3209 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3210 "recursive.ctor.invocation");
3211 } else {
3212 ctor.flags_field |= LOCKED;
3213 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3214 ctor.flags_field &= ~LOCKED;
3215 }
3216 ctor.flags_field |= ACYCLIC;
3217 }
3218 }
3220 /* *************************************************************************
3221 * Miscellaneous
3222 **************************************************************************/
3224 /**
3225 * Return the opcode of the operator but emit an error if it is an
3226 * error.
3227 * @param pos position for error reporting.
3228 * @param operator an operator
3229 * @param tag a tree tag
3230 * @param left type of left hand side
3231 * @param right type of right hand side
3232 */
3233 int checkOperator(DiagnosticPosition pos,
3234 OperatorSymbol operator,
3235 JCTree.Tag tag,
3236 Type left,
3237 Type right) {
3238 if (operator.opcode == ByteCodes.error) {
3239 log.error(pos,
3240 "operator.cant.be.applied.1",
3241 treeinfo.operatorName(tag),
3242 left, right);
3243 }
3244 return operator.opcode;
3245 }
3248 /**
3249 * Check for division by integer constant zero
3250 * @param pos Position for error reporting.
3251 * @param operator The operator for the expression
3252 * @param operand The right hand operand for the expression
3253 */
3254 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3255 if (operand.constValue() != null
3256 && lint.isEnabled(LintCategory.DIVZERO)
3257 && operand.getTag().isSubRangeOf(LONG)
3258 && ((Number) (operand.constValue())).longValue() == 0) {
3259 int opc = ((OperatorSymbol)operator).opcode;
3260 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3261 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3262 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3263 }
3264 }
3265 }
3267 /**
3268 * Check for empty statements after if
3269 */
3270 void checkEmptyIf(JCIf tree) {
3271 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3272 lint.isEnabled(LintCategory.EMPTY))
3273 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3274 }
3276 /** Check that symbol is unique in given scope.
3277 * @param pos Position for error reporting.
3278 * @param sym The symbol.
3279 * @param s The scope.
3280 */
3281 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3282 if (sym.type.isErroneous())
3283 return true;
3284 if (sym.owner.name == names.any) return false;
3285 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3286 if (sym != e.sym &&
3287 (e.sym.flags() & CLASH) == 0 &&
3288 sym.kind == e.sym.kind &&
3289 sym.name != names.error &&
3290 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3291 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3292 varargsDuplicateError(pos, sym, e.sym);
3293 return true;
3294 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3295 duplicateErasureError(pos, sym, e.sym);
3296 sym.flags_field |= CLASH;
3297 return true;
3298 } else {
3299 duplicateError(pos, e.sym);
3300 return false;
3301 }
3302 }
3303 }
3304 return true;
3305 }
3307 /** Report duplicate declaration error.
3308 */
3309 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3310 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3311 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3312 }
3313 }
3315 /** Check that single-type import is not already imported or top-level defined,
3316 * but make an exception for two single-type imports which denote the same type.
3317 * @param pos Position for error reporting.
3318 * @param sym The symbol.
3319 * @param s The scope
3320 */
3321 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3322 return checkUniqueImport(pos, sym, s, false);
3323 }
3325 /** Check that static single-type import is not already imported or top-level defined,
3326 * but make an exception for two single-type imports which denote the same type.
3327 * @param pos Position for error reporting.
3328 * @param sym The symbol.
3329 * @param s The scope
3330 */
3331 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3332 return checkUniqueImport(pos, sym, s, true);
3333 }
3335 /** Check that single-type import is not already imported or top-level defined,
3336 * but make an exception for two single-type imports which denote the same type.
3337 * @param pos Position for error reporting.
3338 * @param sym The symbol.
3339 * @param s The scope.
3340 * @param staticImport Whether or not this was a static import
3341 */
3342 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3343 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3344 // is encountered class entered via a class declaration?
3345 boolean isClassDecl = e.scope == s;
3346 if ((isClassDecl || sym != e.sym) &&
3347 sym.kind == e.sym.kind &&
3348 sym.name != names.error) {
3349 if (!e.sym.type.isErroneous()) {
3350 String what = e.sym.toString();
3351 if (!isClassDecl) {
3352 if (staticImport)
3353 log.error(pos, "already.defined.static.single.import", what);
3354 else
3355 log.error(pos, "already.defined.single.import", what);
3356 }
3357 else if (sym != e.sym)
3358 log.error(pos, "already.defined.this.unit", what);
3359 }
3360 return false;
3361 }
3362 }
3363 return true;
3364 }
3366 /** Check that a qualified name is in canonical form (for import decls).
3367 */
3368 public void checkCanonical(JCTree tree) {
3369 if (!isCanonical(tree))
3370 log.error(tree.pos(), "import.requires.canonical",
3371 TreeInfo.symbol(tree));
3372 }
3373 // where
3374 private boolean isCanonical(JCTree tree) {
3375 while (tree.hasTag(SELECT)) {
3376 JCFieldAccess s = (JCFieldAccess) tree;
3377 if (s.sym.owner != TreeInfo.symbol(s.selected))
3378 return false;
3379 tree = s.selected;
3380 }
3381 return true;
3382 }
3384 /** Check that an auxiliary class is not accessed from any other file than its own.
3385 */
3386 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3387 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3388 (c.flags() & AUXILIARY) != 0 &&
3389 rs.isAccessible(env, c) &&
3390 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3391 {
3392 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3393 c, c.sourcefile);
3394 }
3395 }
3397 private class ConversionWarner extends Warner {
3398 final String uncheckedKey;
3399 final Type found;
3400 final Type expected;
3401 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3402 super(pos);
3403 this.uncheckedKey = uncheckedKey;
3404 this.found = found;
3405 this.expected = expected;
3406 }
3408 @Override
3409 public void warn(LintCategory lint) {
3410 boolean warned = this.warned;
3411 super.warn(lint);
3412 if (warned) return; // suppress redundant diagnostics
3413 switch (lint) {
3414 case UNCHECKED:
3415 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3416 break;
3417 case VARARGS:
3418 if (method != null &&
3419 method.attribute(syms.trustMeType.tsym) != null &&
3420 isTrustMeAllowedOnMethod(method) &&
3421 !types.isReifiable(method.type.getParameterTypes().last())) {
3422 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3423 }
3424 break;
3425 default:
3426 throw new AssertionError("Unexpected lint: " + lint);
3427 }
3428 }
3429 }
3431 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3432 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3433 }
3435 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3436 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3437 }
3438 }