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