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