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