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