Wed, 16 Jan 2013 16:30:11 +0000
8005299: Add FunctionalInterface checking to javac
Summary: Javac should check that types annotated with @FunctionalInterface are indeed functional interfaces
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
29 import java.util.Set;
30 import javax.tools.JavaFileManager;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.jvm.*;
34 import com.sun.tools.javac.tree.*;
35 import com.sun.tools.javac.util.*;
36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
37 import com.sun.tools.javac.util.List;
39 import com.sun.tools.javac.tree.JCTree.*;
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.InferenceContext.FreeTypeListener;
48 import static com.sun.tools.javac.code.Flags.*;
49 import static com.sun.tools.javac.code.Flags.ANNOTATION;
50 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
51 import static com.sun.tools.javac.code.Kinds.*;
52 import static com.sun.tools.javac.code.TypeTag.*;
53 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
55 import static com.sun.tools.javac.tree.JCTree.Tag.*;
57 /** Type checking helper class for the attribution phase.
58 *
59 * <p><b>This is NOT part of any supported API.
60 * If you write code that depends on this, you do so at your own risk.
61 * This code and its internal interfaces are subject to change or
62 * deletion without notice.</b>
63 */
64 public class Check {
65 protected static final Context.Key<Check> checkKey =
66 new Context.Key<Check>();
68 private final Names names;
69 private final Log log;
70 private final Resolve rs;
71 private final Symtab syms;
72 private final Enter enter;
73 private final DeferredAttr deferredAttr;
74 private final Infer infer;
75 private final Types types;
76 private final JCDiagnostic.Factory diags;
77 private boolean warnOnSyntheticConflicts;
78 private boolean suppressAbortOnBadClassFile;
79 private boolean enableSunApiLintControl;
80 private final TreeInfo treeinfo;
81 private final JavaFileManager fileManager;
83 // The set of lint options currently in effect. It is initialized
84 // from the context, and then is set/reset as needed by Attr as it
85 // visits all the various parts of the trees during attribution.
86 private Lint lint;
88 // The method being analyzed in Attr - it is set/reset as needed by
89 // Attr as it visits new method declarations.
90 private MethodSymbol method;
92 public static Check instance(Context context) {
93 Check instance = context.get(checkKey);
94 if (instance == null)
95 instance = new Check(context);
96 return instance;
97 }
99 protected Check(Context context) {
100 context.put(checkKey, this);
102 names = Names.instance(context);
103 log = Log.instance(context);
104 rs = Resolve.instance(context);
105 syms = Symtab.instance(context);
106 enter = Enter.instance(context);
107 deferredAttr = DeferredAttr.instance(context);
108 infer = Infer.instance(context);
109 this.types = Types.instance(context);
110 diags = JCDiagnostic.Factory.instance(context);
111 Options options = Options.instance(context);
112 lint = Lint.instance(context);
113 treeinfo = TreeInfo.instance(context);
114 fileManager = context.get(JavaFileManager.class);
116 Source source = Source.instance(context);
117 allowGenerics = source.allowGenerics();
118 allowVarargs = source.allowVarargs();
119 allowAnnotations = source.allowAnnotations();
120 allowCovariantReturns = source.allowCovariantReturns();
121 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
122 allowDefaultMethods = source.allowDefaultMethods();
123 allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
124 complexInference = options.isSet("complexinference");
125 warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
126 suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
127 enableSunApiLintControl = options.isSet("enableSunApiLintControl");
129 Target target = Target.instance(context);
130 syntheticNameChar = target.syntheticNameChar();
132 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
133 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
134 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
135 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
137 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
138 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
139 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
140 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
141 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
142 enforceMandatoryWarnings, "sunapi", null);
144 deferredLintHandler = DeferredLintHandler.immediateHandler;
145 }
147 /** Switch: generics enabled?
148 */
149 boolean allowGenerics;
151 /** Switch: varargs enabled?
152 */
153 boolean allowVarargs;
155 /** Switch: annotations enabled?
156 */
157 boolean allowAnnotations;
159 /** Switch: covariant returns enabled?
160 */
161 boolean allowCovariantReturns;
163 /** Switch: simplified varargs enabled?
164 */
165 boolean allowSimplifiedVarargs;
167 /** Switch: default methods enabled?
168 */
169 boolean allowDefaultMethods;
171 /** Switch: should unrelated return types trigger a method clash?
172 */
173 boolean allowStrictMethodClashCheck;
175 /** Switch: -complexinference option set?
176 */
177 boolean complexInference;
179 /** Character for synthetic names
180 */
181 char syntheticNameChar;
183 /** A table mapping flat names of all compiled classes in this run to their
184 * symbols; maintained from outside.
185 */
186 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
188 /** A handler for messages about deprecated usage.
189 */
190 private MandatoryWarningHandler deprecationHandler;
192 /** A handler for messages about unchecked or unsafe usage.
193 */
194 private MandatoryWarningHandler uncheckedHandler;
196 /** A handler for messages about using proprietary API.
197 */
198 private MandatoryWarningHandler sunApiHandler;
200 /** A handler for deferred lint warnings.
201 */
202 private DeferredLintHandler deferredLintHandler;
204 /* *************************************************************************
205 * Errors and Warnings
206 **************************************************************************/
208 Lint setLint(Lint newLint) {
209 Lint prev = lint;
210 lint = newLint;
211 return prev;
212 }
214 DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
215 DeferredLintHandler prev = deferredLintHandler;
216 deferredLintHandler = newDeferredLintHandler;
217 return prev;
218 }
220 MethodSymbol setMethod(MethodSymbol newMethod) {
221 MethodSymbol prev = method;
222 method = newMethod;
223 return prev;
224 }
226 /** Warn about deprecated symbol.
227 * @param pos Position to be used for error reporting.
228 * @param sym The deprecated symbol.
229 */
230 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
231 if (!lint.isSuppressed(LintCategory.DEPRECATION))
232 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
233 }
235 /** Warn about unchecked operation.
236 * @param pos Position to be used for error reporting.
237 * @param msg A string describing the problem.
238 */
239 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
240 if (!lint.isSuppressed(LintCategory.UNCHECKED))
241 uncheckedHandler.report(pos, msg, args);
242 }
244 /** Warn about unsafe vararg method decl.
245 * @param pos Position to be used for error reporting.
246 */
247 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
248 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
249 log.warning(LintCategory.VARARGS, pos, key, args);
250 }
252 /** Warn about using proprietary API.
253 * @param pos Position to be used for error reporting.
254 * @param msg A string describing the problem.
255 */
256 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
257 if (!lint.isSuppressed(LintCategory.SUNAPI))
258 sunApiHandler.report(pos, msg, args);
259 }
261 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
262 if (lint.isEnabled(LintCategory.STATIC))
263 log.warning(LintCategory.STATIC, pos, msg, args);
264 }
266 /**
267 * Report any deferred diagnostics.
268 */
269 public void reportDeferredDiagnostics() {
270 deprecationHandler.reportDeferredDiagnostic();
271 uncheckedHandler.reportDeferredDiagnostic();
272 sunApiHandler.reportDeferredDiagnostic();
273 }
276 /** Report a failure to complete a class.
277 * @param pos Position to be used for error reporting.
278 * @param ex The failure to report.
279 */
280 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
281 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
282 if (ex instanceof ClassReader.BadClassFile
283 && !suppressAbortOnBadClassFile) throw new Abort();
284 else return syms.errType;
285 }
287 /** Report an error that wrong type tag was found.
288 * @param pos Position to be used for error reporting.
289 * @param required An internationalized string describing the type tag
290 * required.
291 * @param found The type that was found.
292 */
293 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
294 // this error used to be raised by the parser,
295 // but has been delayed to this point:
296 if (found instanceof Type && ((Type)found).hasTag(VOID)) {
297 log.error(pos, "illegal.start.of.type");
298 return syms.errType;
299 }
300 log.error(pos, "type.found.req", found, required);
301 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
302 }
304 /** Report an error that symbol cannot be referenced before super
305 * has been called.
306 * @param pos Position to be used for error reporting.
307 * @param sym The referenced symbol.
308 */
309 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
310 log.error(pos, "cant.ref.before.ctor.called", sym);
311 }
313 /** Report duplicate declaration error.
314 */
315 void duplicateError(DiagnosticPosition pos, Symbol sym) {
316 if (!sym.type.isErroneous()) {
317 Symbol location = sym.location();
318 if (location.kind == MTH &&
319 ((MethodSymbol)location).isStaticOrInstanceInit()) {
320 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
321 kindName(sym.location()), kindName(sym.location().enclClass()),
322 sym.location().enclClass());
323 } else {
324 log.error(pos, "already.defined", kindName(sym), sym,
325 kindName(sym.location()), sym.location());
326 }
327 }
328 }
330 /** Report array/varargs duplicate declaration
331 */
332 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
333 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
334 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
335 }
336 }
338 /* ************************************************************************
339 * duplicate declaration checking
340 *************************************************************************/
342 /** Check that variable does not hide variable with same name in
343 * immediately enclosing local scope.
344 * @param pos Position for error reporting.
345 * @param v The symbol.
346 * @param s The scope.
347 */
348 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
349 if (s.next != null) {
350 for (Scope.Entry e = s.next.lookup(v.name);
351 e.scope != null && e.sym.owner == v.owner;
352 e = e.next()) {
353 if (e.sym.kind == VAR &&
354 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
355 v.name != names.error) {
356 duplicateError(pos, e.sym);
357 return;
358 }
359 }
360 }
361 }
363 /** Check that a class or interface does not hide a class or
364 * interface with same name in immediately enclosing local scope.
365 * @param pos Position for error reporting.
366 * @param c The symbol.
367 * @param s The scope.
368 */
369 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
370 if (s.next != null) {
371 for (Scope.Entry e = s.next.lookup(c.name);
372 e.scope != null && e.sym.owner == c.owner;
373 e = e.next()) {
374 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
375 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
376 c.name != names.error) {
377 duplicateError(pos, e.sym);
378 return;
379 }
380 }
381 }
382 }
384 /** Check that class does not have the same name as one of
385 * its enclosing classes, or as a class defined in its enclosing scope.
386 * return true if class is unique in its enclosing scope.
387 * @param pos Position for error reporting.
388 * @param name The class name.
389 * @param s The enclosing scope.
390 */
391 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
392 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
393 if (e.sym.kind == TYP && e.sym.name != names.error) {
394 duplicateError(pos, e.sym);
395 return false;
396 }
397 }
398 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
399 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
400 duplicateError(pos, sym);
401 return true;
402 }
403 }
404 return true;
405 }
407 /* *************************************************************************
408 * Class name generation
409 **************************************************************************/
411 /** Return name of local class.
412 * This is of the form {@code <enclClass> $ n <classname> }
413 * where
414 * enclClass is the flat name of the enclosing class,
415 * classname is the simple name of the local class
416 */
417 Name localClassName(ClassSymbol c) {
418 for (int i=1; ; i++) {
419 Name flatname = names.
420 fromString("" + c.owner.enclClass().flatname +
421 syntheticNameChar + i +
422 c.name);
423 if (compiled.get(flatname) == null) return flatname;
424 }
425 }
427 /* *************************************************************************
428 * Type Checking
429 **************************************************************************/
431 /**
432 * A check context is an object that can be used to perform compatibility
433 * checks - depending on the check context, meaning of 'compatibility' might
434 * vary significantly.
435 */
436 public interface CheckContext {
437 /**
438 * Is type 'found' compatible with type 'req' in given context
439 */
440 boolean compatible(Type found, Type req, Warner warn);
441 /**
442 * Report a check error
443 */
444 void report(DiagnosticPosition pos, JCDiagnostic details);
445 /**
446 * Obtain a warner for this check context
447 */
448 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
450 public Infer.InferenceContext inferenceContext();
452 public DeferredAttr.DeferredAttrContext deferredAttrContext();
453 }
455 /**
456 * This class represent a check context that is nested within another check
457 * context - useful to check sub-expressions. The default behavior simply
458 * redirects all method calls to the enclosing check context leveraging
459 * the forwarding pattern.
460 */
461 static class NestedCheckContext implements CheckContext {
462 CheckContext enclosingContext;
464 NestedCheckContext(CheckContext enclosingContext) {
465 this.enclosingContext = enclosingContext;
466 }
468 public boolean compatible(Type found, Type req, Warner warn) {
469 return enclosingContext.compatible(found, req, warn);
470 }
472 public void report(DiagnosticPosition pos, JCDiagnostic details) {
473 enclosingContext.report(pos, details);
474 }
476 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
477 return enclosingContext.checkWarner(pos, found, req);
478 }
480 public Infer.InferenceContext inferenceContext() {
481 return enclosingContext.inferenceContext();
482 }
484 public DeferredAttrContext deferredAttrContext() {
485 return enclosingContext.deferredAttrContext();
486 }
487 }
489 /**
490 * Check context to be used when evaluating assignment/return statements
491 */
492 CheckContext basicHandler = new CheckContext() {
493 public void report(DiagnosticPosition pos, JCDiagnostic details) {
494 log.error(pos, "prob.found.req", details);
495 }
496 public boolean compatible(Type found, Type req, Warner warn) {
497 return types.isAssignable(found, req, warn);
498 }
500 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
501 return convertWarner(pos, found, req);
502 }
504 public InferenceContext inferenceContext() {
505 return infer.emptyContext;
506 }
508 public DeferredAttrContext deferredAttrContext() {
509 return deferredAttr.emptyDeferredAttrContext;
510 }
511 };
513 /** Check that a given type is assignable to a given proto-type.
514 * If it is, return the type, otherwise return errType.
515 * @param pos Position to be used for error reporting.
516 * @param found The type that was found.
517 * @param req The type that was required.
518 */
519 Type checkType(DiagnosticPosition pos, Type found, Type req) {
520 return checkType(pos, found, req, basicHandler);
521 }
523 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
524 final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
525 if (inferenceContext.free(req)) {
526 inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
527 @Override
528 public void typesInferred(InferenceContext inferenceContext) {
529 checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
530 }
531 });
532 }
533 if (req.hasTag(ERROR))
534 return req;
535 if (req.hasTag(NONE))
536 return found;
537 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
538 return found;
539 } else {
540 if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
541 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
542 return types.createErrorType(found);
543 }
544 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
545 return types.createErrorType(found);
546 }
547 }
549 /** Check that a given type can be cast to a given target type.
550 * Return the result of the cast.
551 * @param pos Position to be used for error reporting.
552 * @param found The type that is being cast.
553 * @param req The target type of the cast.
554 */
555 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
556 return checkCastable(pos, found, req, basicHandler);
557 }
558 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
559 if (types.isCastable(found, req, castWarner(pos, found, req))) {
560 return req;
561 } else {
562 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
563 return types.createErrorType(found);
564 }
565 }
567 /** Check for redundant casts (i.e. where source type is a subtype of target type)
568 * The problem should only be reported for non-292 cast
569 */
570 public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
571 if (!tree.type.isErroneous() &&
572 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
573 && types.isSameType(tree.expr.type, tree.clazz.type)
574 && !is292targetTypeCast(tree)) {
575 log.warning(Lint.LintCategory.CAST,
576 tree.pos(), "redundant.cast", tree.expr.type);
577 }
578 }
579 //where
580 private boolean is292targetTypeCast(JCTypeCast tree) {
581 boolean is292targetTypeCast = false;
582 JCExpression expr = TreeInfo.skipParens(tree.expr);
583 if (expr.hasTag(APPLY)) {
584 JCMethodInvocation apply = (JCMethodInvocation)expr;
585 Symbol sym = TreeInfo.symbol(apply.meth);
586 is292targetTypeCast = sym != null &&
587 sym.kind == MTH &&
588 (sym.flags() & HYPOTHETICAL) != 0;
589 }
590 return is292targetTypeCast;
591 }
595 //where
596 /** Is type a type variable, or a (possibly multi-dimensional) array of
597 * type variables?
598 */
599 boolean isTypeVar(Type t) {
600 return t.hasTag(TYPEVAR) || t.hasTag(ARRAY) && isTypeVar(types.elemtype(t));
601 }
603 /** Check that a type is within some bounds.
604 *
605 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
606 * type argument.
607 * @param a The type that should be bounded by bs.
608 * @param bound The bound.
609 */
610 private boolean checkExtends(Type a, Type bound) {
611 if (a.isUnbound()) {
612 return true;
613 } else if (!a.hasTag(WILDCARD)) {
614 a = types.upperBound(a);
615 return types.isSubtype(a, bound);
616 } else if (a.isExtendsBound()) {
617 return types.isCastable(bound, types.upperBound(a), types.noWarnings);
618 } else if (a.isSuperBound()) {
619 return !types.notSoftSubtype(types.lowerBound(a), bound);
620 }
621 return true;
622 }
624 /** Check that type is different from 'void'.
625 * @param pos Position to be used for error reporting.
626 * @param t The type to be checked.
627 */
628 Type checkNonVoid(DiagnosticPosition pos, Type t) {
629 if (t.hasTag(VOID)) {
630 log.error(pos, "void.not.allowed.here");
631 return types.createErrorType(t);
632 } else {
633 return t;
634 }
635 }
637 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
638 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
639 return typeTagError(pos,
640 diags.fragment("type.req.class.array"),
641 asTypeParam(t));
642 } else {
643 return t;
644 }
645 }
647 /** Check that type is a class or interface type.
648 * @param pos Position to be used for error reporting.
649 * @param t The type to be checked.
650 */
651 Type checkClassType(DiagnosticPosition pos, Type t) {
652 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
653 return typeTagError(pos,
654 diags.fragment("type.req.class"),
655 asTypeParam(t));
656 } else {
657 return t;
658 }
659 }
660 //where
661 private Object asTypeParam(Type t) {
662 return (t.hasTag(TYPEVAR))
663 ? diags.fragment("type.parameter", t)
664 : t;
665 }
667 /** Check that type is a valid qualifier for a constructor reference expression
668 */
669 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
670 t = checkClassOrArrayType(pos, t);
671 if (t.hasTag(CLASS)) {
672 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
673 log.error(pos, "abstract.cant.be.instantiated");
674 t = types.createErrorType(t);
675 } else if ((t.tsym.flags() & ENUM) != 0) {
676 log.error(pos, "enum.cant.be.instantiated");
677 t = types.createErrorType(t);
678 }
679 }
680 return t;
681 }
683 /** Check that type is a class or interface type.
684 * @param pos Position to be used for error reporting.
685 * @param t The type to be checked.
686 * @param noBounds True if type bounds are illegal here.
687 */
688 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
689 t = checkClassType(pos, t);
690 if (noBounds && t.isParameterized()) {
691 List<Type> args = t.getTypeArguments();
692 while (args.nonEmpty()) {
693 if (args.head.hasTag(WILDCARD))
694 return typeTagError(pos,
695 diags.fragment("type.req.exact"),
696 args.head);
697 args = args.tail;
698 }
699 }
700 return t;
701 }
703 /** Check that type is a reifiable class, interface or array type.
704 * @param pos Position to be used for error reporting.
705 * @param t The type to be checked.
706 */
707 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
708 t = checkClassOrArrayType(pos, t);
709 if (!t.isErroneous() && !types.isReifiable(t)) {
710 log.error(pos, "illegal.generic.type.for.instof");
711 return types.createErrorType(t);
712 } else {
713 return t;
714 }
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.isNullOrReference())
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(Type owntype,
844 Symbol sym,
845 Env<AttrContext> env,
846 final List<JCExpression> argtrees,
847 List<Type> argtypes,
848 boolean useVarargs,
849 boolean unchecked) {
850 // System.out.println("call : " + env.tree);
851 // System.out.println("method : " + owntype);
852 // System.out.println("actuals: " + argtypes);
853 List<Type> formals = owntype.getParameterTypes();
854 Type last = useVarargs ? formals.last() : null;
855 if (sym.name==names.init &&
856 sym.owner == syms.enumSym)
857 formals = formals.tail.tail;
858 List<JCExpression> args = argtrees;
859 DeferredAttr.DeferredTypeMap checkDeferredMap =
860 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
861 if (args != null) {
862 //this is null when type-checking a method reference
863 while (formals.head != last) {
864 JCTree arg = args.head;
865 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
866 assertConvertible(arg, arg.type, formals.head, warn);
867 args = args.tail;
868 formals = formals.tail;
869 }
870 if (useVarargs) {
871 Type varArg = types.elemtype(last);
872 while (args.tail != null) {
873 JCTree arg = args.head;
874 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
875 assertConvertible(arg, arg.type, varArg, warn);
876 args = args.tail;
877 }
878 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
879 // non-varargs call to varargs method
880 Type varParam = owntype.getParameterTypes().last();
881 Type lastArg = checkDeferredMap.apply(argtypes.last());
882 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
883 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
884 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
885 types.elemtype(varParam), varParam);
886 }
887 }
888 if (unchecked) {
889 warnUnchecked(env.tree.pos(),
890 "unchecked.meth.invocation.applied",
891 kindName(sym),
892 sym.name,
893 rs.methodArguments(sym.type.getParameterTypes()),
894 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
895 kindName(sym.location()),
896 sym.location());
897 owntype = new MethodType(owntype.getParameterTypes(),
898 types.erasure(owntype.getReturnType()),
899 types.erasure(owntype.getThrownTypes()),
900 syms.methodClass);
901 }
902 if (useVarargs) {
903 JCTree tree = env.tree;
904 Type argtype = owntype.getParameterTypes().last();
905 if (!types.isReifiable(argtype) &&
906 (!allowSimplifiedVarargs ||
907 sym.attribute(syms.trustMeType.tsym) == null ||
908 !isTrustMeAllowedOnMethod(sym))) {
909 warnUnchecked(env.tree.pos(),
910 "unchecked.generic.array.creation",
911 argtype);
912 }
913 if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
914 Type elemtype = types.elemtype(argtype);
915 switch (tree.getTag()) {
916 case APPLY:
917 ((JCMethodInvocation) tree).varargsElement = elemtype;
918 break;
919 case NEWCLASS:
920 ((JCNewClass) tree).varargsElement = elemtype;
921 break;
922 case REFERENCE:
923 ((JCMemberReference) tree).varargsElement = elemtype;
924 break;
925 default:
926 throw new AssertionError(""+tree);
927 }
928 }
929 }
930 return owntype;
931 }
932 //where
933 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
934 if (types.isConvertible(actual, formal, warn))
935 return;
937 if (formal.isCompound()
938 && types.isSubtype(actual, types.supertype(formal))
939 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
940 return;
941 }
943 /**
944 * Check that type 't' is a valid instantiation of a generic class
945 * (see JLS 4.5)
946 *
947 * @param t class type to be checked
948 * @return true if 't' is well-formed
949 */
950 public boolean checkValidGenericType(Type t) {
951 return firstIncompatibleTypeArg(t) == null;
952 }
953 //WHERE
954 private Type firstIncompatibleTypeArg(Type type) {
955 List<Type> formals = type.tsym.type.allparams();
956 List<Type> actuals = type.allparams();
957 List<Type> args = type.getTypeArguments();
958 List<Type> forms = type.tsym.type.getTypeArguments();
959 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
961 // For matching pairs of actual argument types `a' and
962 // formal type parameters with declared bound `b' ...
963 while (args.nonEmpty() && forms.nonEmpty()) {
964 // exact type arguments needs to know their
965 // bounds (for upper and lower bound
966 // calculations). So we create new bounds where
967 // type-parameters are replaced with actuals argument types.
968 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
969 args = args.tail;
970 forms = forms.tail;
971 }
973 args = type.getTypeArguments();
974 List<Type> tvars_cap = types.substBounds(formals,
975 formals,
976 types.capture(type).allparams());
977 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
978 // Let the actual arguments know their bound
979 args.head.withTypeVar((TypeVar)tvars_cap.head);
980 args = args.tail;
981 tvars_cap = tvars_cap.tail;
982 }
984 args = type.getTypeArguments();
985 List<Type> bounds = bounds_buf.toList();
987 while (args.nonEmpty() && bounds.nonEmpty()) {
988 Type actual = args.head;
989 if (!isTypeArgErroneous(actual) &&
990 !bounds.head.isErroneous() &&
991 !checkExtends(actual, bounds.head)) {
992 return args.head;
993 }
994 args = args.tail;
995 bounds = bounds.tail;
996 }
998 args = type.getTypeArguments();
999 bounds = bounds_buf.toList();
1001 for (Type arg : types.capture(type).getTypeArguments()) {
1002 if (arg.hasTag(TYPEVAR) &&
1003 arg.getUpperBound().isErroneous() &&
1004 !bounds.head.isErroneous() &&
1005 !isTypeArgErroneous(args.head)) {
1006 return args.head;
1007 }
1008 bounds = bounds.tail;
1009 args = args.tail;
1010 }
1012 return null;
1013 }
1014 //where
1015 boolean isTypeArgErroneous(Type t) {
1016 return isTypeArgErroneous.visit(t);
1017 }
1019 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1020 public Boolean visitType(Type t, Void s) {
1021 return t.isErroneous();
1022 }
1023 @Override
1024 public Boolean visitTypeVar(TypeVar t, Void s) {
1025 return visit(t.getUpperBound());
1026 }
1027 @Override
1028 public Boolean visitCapturedType(CapturedType t, Void s) {
1029 return visit(t.getUpperBound()) ||
1030 visit(t.getLowerBound());
1031 }
1032 @Override
1033 public Boolean visitWildcardType(WildcardType t, Void s) {
1034 return visit(t.type);
1035 }
1036 };
1038 /** Check that given modifiers are legal for given symbol and
1039 * return modifiers together with any implicit modififiers for that symbol.
1040 * Warning: we can't use flags() here since this method
1041 * is called during class enter, when flags() would cause a premature
1042 * completion.
1043 * @param pos Position to be used for error reporting.
1044 * @param flags The set of modifiers given in a definition.
1045 * @param sym The defined symbol.
1046 */
1047 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1048 long mask;
1049 long implicit = 0;
1050 switch (sym.kind) {
1051 case VAR:
1052 if (sym.owner.kind != TYP)
1053 mask = LocalVarFlags;
1054 else if ((sym.owner.flags_field & INTERFACE) != 0)
1055 mask = implicit = InterfaceVarFlags;
1056 else
1057 mask = VarFlags;
1058 break;
1059 case MTH:
1060 if (sym.name == names.init) {
1061 if ((sym.owner.flags_field & ENUM) != 0) {
1062 // enum constructors cannot be declared public or
1063 // protected and must be implicitly or explicitly
1064 // private
1065 implicit = PRIVATE;
1066 mask = PRIVATE;
1067 } else
1068 mask = ConstructorFlags;
1069 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1070 if ((flags & DEFAULT) != 0) {
1071 mask = InterfaceDefaultMethodMask;
1072 implicit = PUBLIC | ABSTRACT;
1073 } else {
1074 mask = implicit = InterfaceMethodFlags;
1075 }
1076 }
1077 else {
1078 mask = MethodFlags;
1079 }
1080 // Imply STRICTFP if owner has STRICTFP set.
1081 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1082 implicit |= sym.owner.flags_field & STRICTFP;
1083 break;
1084 case TYP:
1085 if (sym.isLocal()) {
1086 mask = LocalClassFlags;
1087 if (sym.name.isEmpty()) { // Anonymous class
1088 // Anonymous classes in static methods are themselves static;
1089 // that's why we admit STATIC here.
1090 mask |= STATIC;
1091 // JLS: Anonymous classes are final.
1092 implicit |= FINAL;
1093 }
1094 if ((sym.owner.flags_field & STATIC) == 0 &&
1095 (flags & ENUM) != 0)
1096 log.error(pos, "enums.must.be.static");
1097 } else if (sym.owner.kind == TYP) {
1098 mask = MemberClassFlags;
1099 if (sym.owner.owner.kind == PCK ||
1100 (sym.owner.flags_field & STATIC) != 0)
1101 mask |= STATIC;
1102 else if ((flags & ENUM) != 0)
1103 log.error(pos, "enums.must.be.static");
1104 // Nested interfaces and enums are always STATIC (Spec ???)
1105 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1106 } else {
1107 mask = ClassFlags;
1108 }
1109 // Interfaces are always ABSTRACT
1110 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1112 if ((flags & ENUM) != 0) {
1113 // enums can't be declared abstract or final
1114 mask &= ~(ABSTRACT | FINAL);
1115 implicit |= implicitEnumFinalFlag(tree);
1116 }
1117 // Imply STRICTFP if owner has STRICTFP set.
1118 implicit |= sym.owner.flags_field & STRICTFP;
1119 break;
1120 default:
1121 throw new AssertionError();
1122 }
1123 long illegal = flags & ExtendedStandardFlags & ~mask;
1124 if (illegal != 0) {
1125 if ((illegal & INTERFACE) != 0) {
1126 log.error(pos, "intf.not.allowed.here");
1127 mask |= INTERFACE;
1128 }
1129 else {
1130 log.error(pos,
1131 "mod.not.allowed.here", asFlagSet(illegal));
1132 }
1133 }
1134 else if ((sym.kind == TYP ||
1135 // ISSUE: Disallowing abstract&private is no longer appropriate
1136 // in the presence of inner classes. Should it be deleted here?
1137 checkDisjoint(pos, flags,
1138 ABSTRACT,
1139 PRIVATE | STATIC | DEFAULT))
1140 &&
1141 checkDisjoint(pos, flags,
1142 ABSTRACT | INTERFACE,
1143 FINAL | NATIVE | SYNCHRONIZED)
1144 &&
1145 checkDisjoint(pos, flags,
1146 PUBLIC,
1147 PRIVATE | PROTECTED)
1148 &&
1149 checkDisjoint(pos, flags,
1150 PRIVATE,
1151 PUBLIC | PROTECTED)
1152 &&
1153 checkDisjoint(pos, flags,
1154 FINAL,
1155 VOLATILE)
1156 &&
1157 (sym.kind == TYP ||
1158 checkDisjoint(pos, flags,
1159 ABSTRACT | NATIVE,
1160 STRICTFP))) {
1161 // skip
1162 }
1163 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1164 }
1167 /** Determine if this enum should be implicitly final.
1168 *
1169 * If the enum has no specialized enum contants, it is final.
1170 *
1171 * If the enum does have specialized enum contants, it is
1172 * <i>not</i> final.
1173 */
1174 private long implicitEnumFinalFlag(JCTree tree) {
1175 if (!tree.hasTag(CLASSDEF)) return 0;
1176 class SpecialTreeVisitor extends JCTree.Visitor {
1177 boolean specialized;
1178 SpecialTreeVisitor() {
1179 this.specialized = false;
1180 };
1182 @Override
1183 public void visitTree(JCTree tree) { /* no-op */ }
1185 @Override
1186 public void visitVarDef(JCVariableDecl tree) {
1187 if ((tree.mods.flags & ENUM) != 0) {
1188 if (tree.init instanceof JCNewClass &&
1189 ((JCNewClass) tree.init).def != null) {
1190 specialized = true;
1191 }
1192 }
1193 }
1194 }
1196 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1197 JCClassDecl cdef = (JCClassDecl) tree;
1198 for (JCTree defs: cdef.defs) {
1199 defs.accept(sts);
1200 if (sts.specialized) return 0;
1201 }
1202 return FINAL;
1203 }
1205 /* *************************************************************************
1206 * Type Validation
1207 **************************************************************************/
1209 /** Validate a type expression. That is,
1210 * check that all type arguments of a parametric type are within
1211 * their bounds. This must be done in a second phase after type attributon
1212 * since a class might have a subclass as type parameter bound. E.g:
1213 *
1214 * <pre>{@code
1215 * class B<A extends C> { ... }
1216 * class C extends B<C> { ... }
1217 * }</pre>
1218 *
1219 * and we can't make sure that the bound is already attributed because
1220 * of possible cycles.
1221 *
1222 * Visitor method: Validate a type expression, if it is not null, catching
1223 * and reporting any completion failures.
1224 */
1225 void validate(JCTree tree, Env<AttrContext> env) {
1226 validate(tree, env, true);
1227 }
1228 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1229 new Validator(env).validateTree(tree, checkRaw, true);
1230 }
1232 /** Visitor method: Validate a list of type expressions.
1233 */
1234 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1235 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1236 validate(l.head, env);
1237 }
1239 /** A visitor class for type validation.
1240 */
1241 class Validator extends JCTree.Visitor {
1243 boolean isOuter;
1244 Env<AttrContext> env;
1246 Validator(Env<AttrContext> env) {
1247 this.env = env;
1248 }
1250 @Override
1251 public void visitTypeArray(JCArrayTypeTree tree) {
1252 tree.elemtype.accept(this);
1253 }
1255 @Override
1256 public void visitTypeApply(JCTypeApply tree) {
1257 if (tree.type.hasTag(CLASS)) {
1258 List<JCExpression> args = tree.arguments;
1259 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1261 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1262 if (incompatibleArg != null) {
1263 for (JCTree arg : tree.arguments) {
1264 if (arg.type == incompatibleArg) {
1265 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1266 }
1267 forms = forms.tail;
1268 }
1269 }
1271 forms = tree.type.tsym.type.getTypeArguments();
1273 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1275 // For matching pairs of actual argument types `a' and
1276 // formal type parameters with declared bound `b' ...
1277 while (args.nonEmpty() && forms.nonEmpty()) {
1278 validateTree(args.head,
1279 !(isOuter && is_java_lang_Class),
1280 false);
1281 args = args.tail;
1282 forms = forms.tail;
1283 }
1285 // Check that this type is either fully parameterized, or
1286 // not parameterized at all.
1287 if (tree.type.getEnclosingType().isRaw())
1288 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1289 if (tree.clazz.hasTag(SELECT))
1290 visitSelectInternal((JCFieldAccess)tree.clazz);
1291 }
1292 }
1294 @Override
1295 public void visitTypeParameter(JCTypeParameter tree) {
1296 validateTrees(tree.bounds, true, isOuter);
1297 checkClassBounds(tree.pos(), tree.type);
1298 }
1300 @Override
1301 public void visitWildcard(JCWildcard tree) {
1302 if (tree.inner != null)
1303 validateTree(tree.inner, true, isOuter);
1304 }
1306 @Override
1307 public void visitSelect(JCFieldAccess tree) {
1308 if (tree.type.hasTag(CLASS)) {
1309 visitSelectInternal(tree);
1311 // Check that this type is either fully parameterized, or
1312 // not parameterized at all.
1313 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1314 log.error(tree.pos(), "improperly.formed.type.param.missing");
1315 }
1316 }
1318 public void visitSelectInternal(JCFieldAccess tree) {
1319 if (tree.type.tsym.isStatic() &&
1320 tree.selected.type.isParameterized()) {
1321 // The enclosing type is not a class, so we are
1322 // looking at a static member type. However, the
1323 // qualifying expression is parameterized.
1324 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1325 } else {
1326 // otherwise validate the rest of the expression
1327 tree.selected.accept(this);
1328 }
1329 }
1331 /** Default visitor method: do nothing.
1332 */
1333 @Override
1334 public void visitTree(JCTree tree) {
1335 }
1337 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1338 try {
1339 if (tree != null) {
1340 this.isOuter = isOuter;
1341 tree.accept(this);
1342 if (checkRaw)
1343 checkRaw(tree, env);
1344 }
1345 } catch (CompletionFailure ex) {
1346 completionError(tree.pos(), ex);
1347 }
1348 }
1350 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1351 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1352 validateTree(l.head, checkRaw, isOuter);
1353 }
1355 void checkRaw(JCTree tree, Env<AttrContext> env) {
1356 if (lint.isEnabled(LintCategory.RAW) &&
1357 tree.type.hasTag(CLASS) &&
1358 !TreeInfo.isDiamond(tree) &&
1359 !withinAnonConstr(env) &&
1360 tree.type.isRaw()) {
1361 log.warning(LintCategory.RAW,
1362 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1363 }
1364 }
1366 boolean withinAnonConstr(Env<AttrContext> env) {
1367 return env.enclClass.name.isEmpty() &&
1368 env.enclMethod != null && env.enclMethod.name == names.init;
1369 }
1370 }
1372 /* *************************************************************************
1373 * Exception checking
1374 **************************************************************************/
1376 /* The following methods treat classes as sets that contain
1377 * the class itself and all their subclasses
1378 */
1380 /** Is given type a subtype of some of the types in given list?
1381 */
1382 boolean subset(Type t, List<Type> ts) {
1383 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1384 if (types.isSubtype(t, l.head)) return true;
1385 return false;
1386 }
1388 /** Is given type a subtype or supertype of
1389 * some of the types in given list?
1390 */
1391 boolean intersects(Type t, List<Type> ts) {
1392 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1393 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1394 return false;
1395 }
1397 /** Add type set to given type list, unless it is a subclass of some class
1398 * in the list.
1399 */
1400 List<Type> incl(Type t, List<Type> ts) {
1401 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1402 }
1404 /** Remove type set from type set list.
1405 */
1406 List<Type> excl(Type t, List<Type> ts) {
1407 if (ts.isEmpty()) {
1408 return ts;
1409 } else {
1410 List<Type> ts1 = excl(t, ts.tail);
1411 if (types.isSubtype(ts.head, t)) return ts1;
1412 else if (ts1 == ts.tail) return ts;
1413 else return ts1.prepend(ts.head);
1414 }
1415 }
1417 /** Form the union of two type set lists.
1418 */
1419 List<Type> union(List<Type> ts1, List<Type> ts2) {
1420 List<Type> ts = ts1;
1421 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1422 ts = incl(l.head, ts);
1423 return ts;
1424 }
1426 /** Form the difference of two type lists.
1427 */
1428 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1429 List<Type> ts = ts1;
1430 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1431 ts = excl(l.head, ts);
1432 return ts;
1433 }
1435 /** Form the intersection of two type lists.
1436 */
1437 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1438 List<Type> ts = List.nil();
1439 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1440 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1441 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1442 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1443 return ts;
1444 }
1446 /** Is exc an exception symbol that need not be declared?
1447 */
1448 boolean isUnchecked(ClassSymbol exc) {
1449 return
1450 exc.kind == ERR ||
1451 exc.isSubClass(syms.errorType.tsym, types) ||
1452 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1453 }
1455 /** Is exc an exception type that need not be declared?
1456 */
1457 boolean isUnchecked(Type exc) {
1458 return
1459 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1460 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1461 exc.hasTag(BOT);
1462 }
1464 /** Same, but handling completion failures.
1465 */
1466 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1467 try {
1468 return isUnchecked(exc);
1469 } catch (CompletionFailure ex) {
1470 completionError(pos, ex);
1471 return true;
1472 }
1473 }
1475 /** Is exc handled by given exception list?
1476 */
1477 boolean isHandled(Type exc, List<Type> handled) {
1478 return isUnchecked(exc) || subset(exc, handled);
1479 }
1481 /** Return all exceptions in thrown list that are not in handled list.
1482 * @param thrown The list of thrown exceptions.
1483 * @param handled The list of handled exceptions.
1484 */
1485 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1486 List<Type> unhandled = List.nil();
1487 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1488 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1489 return unhandled;
1490 }
1492 /* *************************************************************************
1493 * Overriding/Implementation checking
1494 **************************************************************************/
1496 /** The level of access protection given by a flag set,
1497 * where PRIVATE is highest and PUBLIC is lowest.
1498 */
1499 static int protection(long flags) {
1500 switch ((short)(flags & AccessFlags)) {
1501 case PRIVATE: return 3;
1502 case PROTECTED: return 1;
1503 default:
1504 case PUBLIC: return 0;
1505 case 0: return 2;
1506 }
1507 }
1509 /** A customized "cannot override" error message.
1510 * @param m The overriding method.
1511 * @param other The overridden method.
1512 * @return An internationalized string.
1513 */
1514 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1515 String key;
1516 if ((other.owner.flags() & INTERFACE) == 0)
1517 key = "cant.override";
1518 else if ((m.owner.flags() & INTERFACE) == 0)
1519 key = "cant.implement";
1520 else
1521 key = "clashes.with";
1522 return diags.fragment(key, m, m.location(), other, other.location());
1523 }
1525 /** A customized "override" warning message.
1526 * @param m The overriding method.
1527 * @param other The overridden method.
1528 * @return An internationalized string.
1529 */
1530 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1531 String key;
1532 if ((other.owner.flags() & INTERFACE) == 0)
1533 key = "unchecked.override";
1534 else if ((m.owner.flags() & INTERFACE) == 0)
1535 key = "unchecked.implement";
1536 else
1537 key = "unchecked.clash.with";
1538 return diags.fragment(key, m, m.location(), other, other.location());
1539 }
1541 /** A customized "override" warning message.
1542 * @param m The overriding method.
1543 * @param other The overridden method.
1544 * @return An internationalized string.
1545 */
1546 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1547 String key;
1548 if ((other.owner.flags() & INTERFACE) == 0)
1549 key = "varargs.override";
1550 else if ((m.owner.flags() & INTERFACE) == 0)
1551 key = "varargs.implement";
1552 else
1553 key = "varargs.clash.with";
1554 return diags.fragment(key, m, m.location(), other, other.location());
1555 }
1557 /** Check that this method conforms with overridden method 'other'.
1558 * where `origin' is the class where checking started.
1559 * Complications:
1560 * (1) Do not check overriding of synthetic methods
1561 * (reason: they might be final).
1562 * todo: check whether this is still necessary.
1563 * (2) Admit the case where an interface proxy throws fewer exceptions
1564 * than the method it implements. Augment the proxy methods with the
1565 * undeclared exceptions in this case.
1566 * (3) When generics are enabled, admit the case where an interface proxy
1567 * has a result type
1568 * extended by the result type of the method it implements.
1569 * Change the proxies result type to the smaller type in this case.
1570 *
1571 * @param tree The tree from which positions
1572 * are extracted for errors.
1573 * @param m The overriding method.
1574 * @param other The overridden method.
1575 * @param origin The class of which the overriding method
1576 * is a member.
1577 */
1578 void checkOverride(JCTree tree,
1579 MethodSymbol m,
1580 MethodSymbol other,
1581 ClassSymbol origin) {
1582 // Don't check overriding of synthetic methods or by bridge methods.
1583 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1584 return;
1585 }
1587 // Error if static method overrides instance method (JLS 8.4.6.2).
1588 if ((m.flags() & STATIC) != 0 &&
1589 (other.flags() & STATIC) == 0) {
1590 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1591 cannotOverride(m, other));
1592 return;
1593 }
1595 // Error if instance method overrides static or final
1596 // method (JLS 8.4.6.1).
1597 if ((other.flags() & FINAL) != 0 ||
1598 (m.flags() & STATIC) == 0 &&
1599 (other.flags() & STATIC) != 0) {
1600 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1601 cannotOverride(m, other),
1602 asFlagSet(other.flags() & (FINAL | STATIC)));
1603 return;
1604 }
1606 if ((m.owner.flags() & ANNOTATION) != 0) {
1607 // handled in validateAnnotationMethod
1608 return;
1609 }
1611 // Error if overriding method has weaker access (JLS 8.4.6.3).
1612 if ((origin.flags() & INTERFACE) == 0 &&
1613 protection(m.flags()) > protection(other.flags())) {
1614 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1615 cannotOverride(m, other),
1616 other.flags() == 0 ?
1617 Flag.PACKAGE :
1618 asFlagSet(other.flags() & AccessFlags));
1619 return;
1620 }
1622 Type mt = types.memberType(origin.type, m);
1623 Type ot = types.memberType(origin.type, other);
1624 // Error if overriding result type is different
1625 // (or, in the case of generics mode, not a subtype) of
1626 // overridden result type. We have to rename any type parameters
1627 // before comparing types.
1628 List<Type> mtvars = mt.getTypeArguments();
1629 List<Type> otvars = ot.getTypeArguments();
1630 Type mtres = mt.getReturnType();
1631 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1633 overrideWarner.clear();
1634 boolean resultTypesOK =
1635 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1636 if (!resultTypesOK) {
1637 if (!allowCovariantReturns &&
1638 m.owner != origin &&
1639 m.owner.isSubClass(other.owner, types)) {
1640 // allow limited interoperability with covariant returns
1641 } else {
1642 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1643 "override.incompatible.ret",
1644 cannotOverride(m, other),
1645 mtres, otres);
1646 return;
1647 }
1648 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1649 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1650 "override.unchecked.ret",
1651 uncheckedOverrides(m, other),
1652 mtres, otres);
1653 }
1655 // Error if overriding method throws an exception not reported
1656 // by overridden method.
1657 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1658 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1659 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1660 if (unhandledErased.nonEmpty()) {
1661 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1662 "override.meth.doesnt.throw",
1663 cannotOverride(m, other),
1664 unhandledUnerased.head);
1665 return;
1666 }
1667 else if (unhandledUnerased.nonEmpty()) {
1668 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1669 "override.unchecked.thrown",
1670 cannotOverride(m, other),
1671 unhandledUnerased.head);
1672 return;
1673 }
1675 // Optional warning if varargs don't agree
1676 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1677 && lint.isEnabled(LintCategory.OVERRIDES)) {
1678 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1679 ((m.flags() & Flags.VARARGS) != 0)
1680 ? "override.varargs.missing"
1681 : "override.varargs.extra",
1682 varargsOverrides(m, other));
1683 }
1685 // Warn if instance method overrides bridge method (compiler spec ??)
1686 if ((other.flags() & BRIDGE) != 0) {
1687 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1688 uncheckedOverrides(m, other));
1689 }
1691 // Warn if a deprecated method overridden by a non-deprecated one.
1692 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1693 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1694 }
1695 }
1696 // where
1697 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1698 // If the method, m, is defined in an interface, then ignore the issue if the method
1699 // is only inherited via a supertype and also implemented in the supertype,
1700 // because in that case, we will rediscover the issue when examining the method
1701 // in the supertype.
1702 // If the method, m, is not defined in an interface, then the only time we need to
1703 // address the issue is when the method is the supertype implemementation: any other
1704 // case, we will have dealt with when examining the supertype classes
1705 ClassSymbol mc = m.enclClass();
1706 Type st = types.supertype(origin.type);
1707 if (!st.hasTag(CLASS))
1708 return true;
1709 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1711 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1712 List<Type> intfs = types.interfaces(origin.type);
1713 return (intfs.contains(mc.type) ? false : (stimpl != null));
1714 }
1715 else
1716 return (stimpl != m);
1717 }
1720 // used to check if there were any unchecked conversions
1721 Warner overrideWarner = new Warner();
1723 /** Check that a class does not inherit two concrete methods
1724 * with the same signature.
1725 * @param pos Position to be used for error reporting.
1726 * @param site The class type to be checked.
1727 */
1728 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1729 Type sup = types.supertype(site);
1730 if (!sup.hasTag(CLASS)) return;
1732 for (Type t1 = sup;
1733 t1.tsym.type.isParameterized();
1734 t1 = types.supertype(t1)) {
1735 for (Scope.Entry e1 = t1.tsym.members().elems;
1736 e1 != null;
1737 e1 = e1.sibling) {
1738 Symbol s1 = e1.sym;
1739 if (s1.kind != MTH ||
1740 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1741 !s1.isInheritedIn(site.tsym, types) ||
1742 ((MethodSymbol)s1).implementation(site.tsym,
1743 types,
1744 true) != s1)
1745 continue;
1746 Type st1 = types.memberType(t1, s1);
1747 int s1ArgsLength = st1.getParameterTypes().length();
1748 if (st1 == s1.type) continue;
1750 for (Type t2 = sup;
1751 t2.hasTag(CLASS);
1752 t2 = types.supertype(t2)) {
1753 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1754 e2.scope != null;
1755 e2 = e2.next()) {
1756 Symbol s2 = e2.sym;
1757 if (s2 == s1 ||
1758 s2.kind != MTH ||
1759 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1760 s2.type.getParameterTypes().length() != s1ArgsLength ||
1761 !s2.isInheritedIn(site.tsym, types) ||
1762 ((MethodSymbol)s2).implementation(site.tsym,
1763 types,
1764 true) != s2)
1765 continue;
1766 Type st2 = types.memberType(t2, s2);
1767 if (types.overrideEquivalent(st1, st2))
1768 log.error(pos, "concrete.inheritance.conflict",
1769 s1, t1, s2, t2, sup);
1770 }
1771 }
1772 }
1773 }
1774 }
1776 /** Check that classes (or interfaces) do not each define an abstract
1777 * method with same name and arguments but incompatible return types.
1778 * @param pos Position to be used for error reporting.
1779 * @param t1 The first argument type.
1780 * @param t2 The second argument type.
1781 */
1782 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1783 Type t1,
1784 Type t2) {
1785 return checkCompatibleAbstracts(pos, t1, t2,
1786 types.makeCompoundType(t1, t2));
1787 }
1789 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1790 Type t1,
1791 Type t2,
1792 Type site) {
1793 return firstIncompatibility(pos, t1, t2, site) == null;
1794 }
1796 /** Return the first method which is defined with same args
1797 * but different return types in two given interfaces, or null if none
1798 * exists.
1799 * @param t1 The first type.
1800 * @param t2 The second type.
1801 * @param site The most derived type.
1802 * @returns symbol from t2 that conflicts with one in t1.
1803 */
1804 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1805 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1806 closure(t1, interfaces1);
1807 Map<TypeSymbol,Type> interfaces2;
1808 if (t1 == t2)
1809 interfaces2 = interfaces1;
1810 else
1811 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1813 for (Type t3 : interfaces1.values()) {
1814 for (Type t4 : interfaces2.values()) {
1815 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1816 if (s != null) return s;
1817 }
1818 }
1819 return null;
1820 }
1822 /** Compute all the supertypes of t, indexed by type symbol. */
1823 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1824 if (!t.hasTag(CLASS)) return;
1825 if (typeMap.put(t.tsym, t) == null) {
1826 closure(types.supertype(t), typeMap);
1827 for (Type i : types.interfaces(t))
1828 closure(i, typeMap);
1829 }
1830 }
1832 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1833 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1834 if (!t.hasTag(CLASS)) return;
1835 if (typesSkip.get(t.tsym) != null) return;
1836 if (typeMap.put(t.tsym, t) == null) {
1837 closure(types.supertype(t), typesSkip, typeMap);
1838 for (Type i : types.interfaces(t))
1839 closure(i, typesSkip, typeMap);
1840 }
1841 }
1843 /** Return the first method in t2 that conflicts with a method from t1. */
1844 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1845 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1846 Symbol s1 = e1.sym;
1847 Type st1 = null;
1848 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1849 (s1.flags() & SYNTHETIC) != 0) continue;
1850 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1851 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1852 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1853 Symbol s2 = e2.sym;
1854 if (s1 == s2) continue;
1855 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1856 (s2.flags() & SYNTHETIC) != 0) continue;
1857 if (st1 == null) st1 = types.memberType(t1, s1);
1858 Type st2 = types.memberType(t2, s2);
1859 if (types.overrideEquivalent(st1, st2)) {
1860 List<Type> tvars1 = st1.getTypeArguments();
1861 List<Type> tvars2 = st2.getTypeArguments();
1862 Type rt1 = st1.getReturnType();
1863 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1864 boolean compat =
1865 types.isSameType(rt1, rt2) ||
1866 !rt1.isPrimitiveOrVoid() &&
1867 !rt2.isPrimitiveOrVoid() &&
1868 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1869 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1870 checkCommonOverriderIn(s1,s2,site);
1871 if (!compat) {
1872 log.error(pos, "types.incompatible.diff.ret",
1873 t1, t2, s2.name +
1874 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1875 return s2;
1876 }
1877 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1878 !checkCommonOverriderIn(s1, s2, site)) {
1879 log.error(pos,
1880 "name.clash.same.erasure.no.override",
1881 s1, s1.location(),
1882 s2, s2.location());
1883 return s2;
1884 }
1885 }
1886 }
1887 return null;
1888 }
1889 //WHERE
1890 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1891 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1892 Type st1 = types.memberType(site, s1);
1893 Type st2 = types.memberType(site, s2);
1894 closure(site, supertypes);
1895 for (Type t : supertypes.values()) {
1896 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1897 Symbol s3 = e.sym;
1898 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1899 Type st3 = types.memberType(site,s3);
1900 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1901 if (s3.owner == site.tsym) {
1902 return true;
1903 }
1904 List<Type> tvars1 = st1.getTypeArguments();
1905 List<Type> tvars2 = st2.getTypeArguments();
1906 List<Type> tvars3 = st3.getTypeArguments();
1907 Type rt1 = st1.getReturnType();
1908 Type rt2 = st2.getReturnType();
1909 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1910 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1911 boolean compat =
1912 !rt13.isPrimitiveOrVoid() &&
1913 !rt23.isPrimitiveOrVoid() &&
1914 (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
1915 types.covariantReturnType(rt23, rt2, types.noWarnings));
1916 if (compat)
1917 return true;
1918 }
1919 }
1920 }
1921 return false;
1922 }
1924 /** Check that a given method conforms with any method it overrides.
1925 * @param tree The tree from which positions are extracted
1926 * for errors.
1927 * @param m The overriding method.
1928 */
1929 void checkOverride(JCTree tree, MethodSymbol m) {
1930 ClassSymbol origin = (ClassSymbol)m.owner;
1931 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1932 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1933 log.error(tree.pos(), "enum.no.finalize");
1934 return;
1935 }
1936 for (Type t = origin.type; t.hasTag(CLASS);
1937 t = types.supertype(t)) {
1938 if (t != origin.type) {
1939 checkOverride(tree, t, origin, m);
1940 }
1941 for (Type t2 : types.interfaces(t)) {
1942 checkOverride(tree, t2, origin, m);
1943 }
1944 }
1945 }
1947 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1948 TypeSymbol c = site.tsym;
1949 Scope.Entry e = c.members().lookup(m.name);
1950 while (e.scope != null) {
1951 if (m.overrides(e.sym, origin, types, false)) {
1952 if ((e.sym.flags() & ABSTRACT) == 0) {
1953 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1954 }
1955 }
1956 e = e.next();
1957 }
1958 }
1960 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1961 ClashFilter cf = new ClashFilter(origin.type);
1962 return (cf.accepts(s1) &&
1963 cf.accepts(s2) &&
1964 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1965 }
1968 /** Check that all abstract members of given class have definitions.
1969 * @param pos Position to be used for error reporting.
1970 * @param c The class.
1971 */
1972 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1973 try {
1974 MethodSymbol undef = firstUndef(c, c);
1975 if (undef != null) {
1976 if ((c.flags() & ENUM) != 0 &&
1977 types.supertype(c.type).tsym == syms.enumSym &&
1978 (c.flags() & FINAL) == 0) {
1979 // add the ABSTRACT flag to an enum
1980 c.flags_field |= ABSTRACT;
1981 } else {
1982 MethodSymbol undef1 =
1983 new MethodSymbol(undef.flags(), undef.name,
1984 types.memberType(c.type, undef), undef.owner);
1985 log.error(pos, "does.not.override.abstract",
1986 c, undef1, undef1.location());
1987 }
1988 }
1989 } catch (CompletionFailure ex) {
1990 completionError(pos, ex);
1991 }
1992 }
1993 //where
1994 /** Return first abstract member of class `c' that is not defined
1995 * in `impl', null if there is none.
1996 */
1997 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1998 MethodSymbol undef = null;
1999 // Do not bother to search in classes that are not abstract,
2000 // since they cannot have abstract members.
2001 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
2002 Scope s = c.members();
2003 for (Scope.Entry e = s.elems;
2004 undef == null && e != null;
2005 e = e.sibling) {
2006 if (e.sym.kind == MTH &&
2007 (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
2008 MethodSymbol absmeth = (MethodSymbol)e.sym;
2009 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
2010 if (implmeth == null || implmeth == absmeth) {
2011 //look for default implementations
2012 if (allowDefaultMethods) {
2013 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
2014 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
2015 implmeth = prov;
2016 }
2017 }
2018 }
2019 if (implmeth == null || implmeth == absmeth) {
2020 undef = absmeth;
2021 }
2022 }
2023 }
2024 if (undef == null) {
2025 Type st = types.supertype(c.type);
2026 if (st.hasTag(CLASS))
2027 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2028 }
2029 for (List<Type> l = types.interfaces(c.type);
2030 undef == null && l.nonEmpty();
2031 l = l.tail) {
2032 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2033 }
2034 }
2035 return undef;
2036 }
2038 void checkNonCyclicDecl(JCClassDecl tree) {
2039 CycleChecker cc = new CycleChecker();
2040 cc.scan(tree);
2041 if (!cc.errorFound && !cc.partialCheck) {
2042 tree.sym.flags_field |= ACYCLIC;
2043 }
2044 }
2046 class CycleChecker extends TreeScanner {
2048 List<Symbol> seenClasses = List.nil();
2049 boolean errorFound = false;
2050 boolean partialCheck = false;
2052 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2053 if (sym != null && sym.kind == TYP) {
2054 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2055 if (classEnv != null) {
2056 DiagnosticSource prevSource = log.currentSource();
2057 try {
2058 log.useSource(classEnv.toplevel.sourcefile);
2059 scan(classEnv.tree);
2060 }
2061 finally {
2062 log.useSource(prevSource.getFile());
2063 }
2064 } else if (sym.kind == TYP) {
2065 checkClass(pos, sym, List.<JCTree>nil());
2066 }
2067 } else {
2068 //not completed yet
2069 partialCheck = true;
2070 }
2071 }
2073 @Override
2074 public void visitSelect(JCFieldAccess tree) {
2075 super.visitSelect(tree);
2076 checkSymbol(tree.pos(), tree.sym);
2077 }
2079 @Override
2080 public void visitIdent(JCIdent tree) {
2081 checkSymbol(tree.pos(), tree.sym);
2082 }
2084 @Override
2085 public void visitTypeApply(JCTypeApply tree) {
2086 scan(tree.clazz);
2087 }
2089 @Override
2090 public void visitTypeArray(JCArrayTypeTree tree) {
2091 scan(tree.elemtype);
2092 }
2094 @Override
2095 public void visitClassDef(JCClassDecl tree) {
2096 List<JCTree> supertypes = List.nil();
2097 if (tree.getExtendsClause() != null) {
2098 supertypes = supertypes.prepend(tree.getExtendsClause());
2099 }
2100 if (tree.getImplementsClause() != null) {
2101 for (JCTree intf : tree.getImplementsClause()) {
2102 supertypes = supertypes.prepend(intf);
2103 }
2104 }
2105 checkClass(tree.pos(), tree.sym, supertypes);
2106 }
2108 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2109 if ((c.flags_field & ACYCLIC) != 0)
2110 return;
2111 if (seenClasses.contains(c)) {
2112 errorFound = true;
2113 noteCyclic(pos, (ClassSymbol)c);
2114 } else if (!c.type.isErroneous()) {
2115 try {
2116 seenClasses = seenClasses.prepend(c);
2117 if (c.type.hasTag(CLASS)) {
2118 if (supertypes.nonEmpty()) {
2119 scan(supertypes);
2120 }
2121 else {
2122 ClassType ct = (ClassType)c.type;
2123 if (ct.supertype_field == null ||
2124 ct.interfaces_field == null) {
2125 //not completed yet
2126 partialCheck = true;
2127 return;
2128 }
2129 checkSymbol(pos, ct.supertype_field.tsym);
2130 for (Type intf : ct.interfaces_field) {
2131 checkSymbol(pos, intf.tsym);
2132 }
2133 }
2134 if (c.owner.kind == TYP) {
2135 checkSymbol(pos, c.owner);
2136 }
2137 }
2138 } finally {
2139 seenClasses = seenClasses.tail;
2140 }
2141 }
2142 }
2143 }
2145 /** Check for cyclic references. Issue an error if the
2146 * symbol of the type referred to has a LOCKED flag set.
2147 *
2148 * @param pos Position to be used for error reporting.
2149 * @param t The type referred to.
2150 */
2151 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2152 checkNonCyclicInternal(pos, t);
2153 }
2156 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2157 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2158 }
2160 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2161 final TypeVar tv;
2162 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2163 return;
2164 if (seen.contains(t)) {
2165 tv = (TypeVar)t;
2166 tv.bound = types.createErrorType(t);
2167 log.error(pos, "cyclic.inheritance", t);
2168 } else if (t.hasTag(TYPEVAR)) {
2169 tv = (TypeVar)t;
2170 seen = seen.prepend(tv);
2171 for (Type b : types.getBounds(tv))
2172 checkNonCyclic1(pos, b, seen);
2173 }
2174 }
2176 /** Check for cyclic references. Issue an error if the
2177 * symbol of the type referred to has a LOCKED flag set.
2178 *
2179 * @param pos Position to be used for error reporting.
2180 * @param t The type referred to.
2181 * @returns True if the check completed on all attributed classes
2182 */
2183 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2184 boolean complete = true; // was the check complete?
2185 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2186 Symbol c = t.tsym;
2187 if ((c.flags_field & ACYCLIC) != 0) return true;
2189 if ((c.flags_field & LOCKED) != 0) {
2190 noteCyclic(pos, (ClassSymbol)c);
2191 } else if (!c.type.isErroneous()) {
2192 try {
2193 c.flags_field |= LOCKED;
2194 if (c.type.hasTag(CLASS)) {
2195 ClassType clazz = (ClassType)c.type;
2196 if (clazz.interfaces_field != null)
2197 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2198 complete &= checkNonCyclicInternal(pos, l.head);
2199 if (clazz.supertype_field != null) {
2200 Type st = clazz.supertype_field;
2201 if (st != null && st.hasTag(CLASS))
2202 complete &= checkNonCyclicInternal(pos, st);
2203 }
2204 if (c.owner.kind == TYP)
2205 complete &= checkNonCyclicInternal(pos, c.owner.type);
2206 }
2207 } finally {
2208 c.flags_field &= ~LOCKED;
2209 }
2210 }
2211 if (complete)
2212 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2213 if (complete) c.flags_field |= ACYCLIC;
2214 return complete;
2215 }
2217 /** Note that we found an inheritance cycle. */
2218 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2219 log.error(pos, "cyclic.inheritance", c);
2220 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2221 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2222 Type st = types.supertype(c.type);
2223 if (st.hasTag(CLASS))
2224 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2225 c.type = types.createErrorType(c, c.type);
2226 c.flags_field |= ACYCLIC;
2227 }
2229 /**
2230 * Check that functional interface methods would make sense when seen
2231 * from the perspective of the implementing class
2232 */
2233 void checkFunctionalInterface(JCTree tree, Type funcInterface) {
2234 ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
2235 ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
2236 c.interfaces_field = List.of(funcInterface);
2237 c.supertype_field = syms.objectType;
2238 c.tsym = csym;
2239 csym.members_field = new Scope(csym);
2240 csym.completer = null;
2241 checkImplementations(tree, csym, csym);
2242 }
2244 /** Check that all methods which implement some
2245 * method conform to the method they implement.
2246 * @param tree The class definition whose members are checked.
2247 */
2248 void checkImplementations(JCClassDecl tree) {
2249 checkImplementations(tree, tree.sym, tree.sym);
2250 }
2251 //where
2252 /** Check that all methods which implement some
2253 * method in `ic' conform to the method they implement.
2254 */
2255 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2256 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2257 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2258 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2259 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2260 if (e.sym.kind == MTH &&
2261 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2262 MethodSymbol absmeth = (MethodSymbol)e.sym;
2263 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2264 if (implmeth != null && implmeth != absmeth &&
2265 (implmeth.owner.flags() & INTERFACE) ==
2266 (origin.flags() & INTERFACE)) {
2267 // don't check if implmeth is in a class, yet
2268 // origin is an interface. This case arises only
2269 // if implmeth is declared in Object. The reason is
2270 // that interfaces really don't inherit from
2271 // Object it's just that the compiler represents
2272 // things that way.
2273 checkOverride(tree, implmeth, absmeth, origin);
2274 }
2275 }
2276 }
2277 }
2278 }
2279 }
2281 /** Check that all abstract methods implemented by a class are
2282 * mutually compatible.
2283 * @param pos Position to be used for error reporting.
2284 * @param c The class whose interfaces are checked.
2285 */
2286 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2287 List<Type> supertypes = types.interfaces(c);
2288 Type supertype = types.supertype(c);
2289 if (supertype.hasTag(CLASS) &&
2290 (supertype.tsym.flags() & ABSTRACT) != 0)
2291 supertypes = supertypes.prepend(supertype);
2292 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2293 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2294 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2295 return;
2296 for (List<Type> m = supertypes; m != l; m = m.tail)
2297 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2298 return;
2299 }
2300 checkCompatibleConcretes(pos, c);
2301 }
2303 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2304 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2305 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2306 // VM allows methods and variables with differing types
2307 if (sym.kind == e.sym.kind &&
2308 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2309 sym != e.sym &&
2310 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2311 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2312 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2313 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2314 return;
2315 }
2316 }
2317 }
2318 }
2320 /** Check that all non-override equivalent methods accessible from 'site'
2321 * are mutually compatible (JLS 8.4.8/9.4.1).
2322 *
2323 * @param pos Position to be used for error reporting.
2324 * @param site The class whose methods are checked.
2325 * @param sym The method symbol to be checked.
2326 */
2327 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2328 ClashFilter cf = new ClashFilter(site);
2329 //for each method m1 that is overridden (directly or indirectly)
2330 //by method 'sym' in 'site'...
2331 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2332 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2333 //...check each method m2 that is a member of 'site'
2334 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2335 if (m2 == m1) continue;
2336 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2337 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2338 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2339 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2340 sym.flags_field |= CLASH;
2341 String key = m1 == sym ?
2342 "name.clash.same.erasure.no.override" :
2343 "name.clash.same.erasure.no.override.1";
2344 log.error(pos,
2345 key,
2346 sym, sym.location(),
2347 m2, m2.location(),
2348 m1, m1.location());
2349 return;
2350 }
2351 }
2352 }
2353 }
2357 /** Check that all static methods accessible from 'site' are
2358 * mutually compatible (JLS 8.4.8).
2359 *
2360 * @param pos Position to be used for error reporting.
2361 * @param site The class whose methods are checked.
2362 * @param sym The method symbol to be checked.
2363 */
2364 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2365 ClashFilter cf = new ClashFilter(site);
2366 //for each method m1 that is a member of 'site'...
2367 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2368 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2369 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2370 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
2371 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2372 log.error(pos,
2373 "name.clash.same.erasure.no.hide",
2374 sym, sym.location(),
2375 s, s.location());
2376 return;
2377 }
2378 }
2379 }
2381 //where
2382 private class ClashFilter implements Filter<Symbol> {
2384 Type site;
2386 ClashFilter(Type site) {
2387 this.site = site;
2388 }
2390 boolean shouldSkip(Symbol s) {
2391 return (s.flags() & CLASH) != 0 &&
2392 s.owner == site.tsym;
2393 }
2395 public boolean accepts(Symbol s) {
2396 return s.kind == MTH &&
2397 (s.flags() & SYNTHETIC) == 0 &&
2398 !shouldSkip(s) &&
2399 s.isInheritedIn(site.tsym, types) &&
2400 !s.isConstructor();
2401 }
2402 }
2404 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2405 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2406 for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
2407 Assert.check(m.kind == MTH);
2408 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2409 if (prov.size() > 1) {
2410 ListBuffer<Symbol> abstracts = ListBuffer.lb();
2411 ListBuffer<Symbol> defaults = ListBuffer.lb();
2412 for (MethodSymbol provSym : prov) {
2413 if ((provSym.flags() & DEFAULT) != 0) {
2414 defaults = defaults.append(provSym);
2415 } else if ((provSym.flags() & ABSTRACT) != 0) {
2416 abstracts = abstracts.append(provSym);
2417 }
2418 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2419 //strong semantics - issue an error if two sibling interfaces
2420 //have two override-equivalent defaults - or if one is abstract
2421 //and the other is default
2422 String errKey;
2423 Symbol s1 = defaults.first();
2424 Symbol s2;
2425 if (defaults.size() > 1) {
2426 errKey = "types.incompatible.unrelated.defaults";
2427 s2 = defaults.toList().tail.head;
2428 } else {
2429 errKey = "types.incompatible.abstract.default";
2430 s2 = abstracts.first();
2431 }
2432 log.error(pos, errKey,
2433 Kinds.kindName(site.tsym), site,
2434 m.name, types.memberType(site, m).getParameterTypes(),
2435 s1.location(), s2.location());
2436 break;
2437 }
2438 }
2439 }
2440 }
2441 }
2443 //where
2444 private class DefaultMethodClashFilter implements Filter<Symbol> {
2446 Type site;
2448 DefaultMethodClashFilter(Type site) {
2449 this.site = site;
2450 }
2452 public boolean accepts(Symbol s) {
2453 return s.kind == MTH &&
2454 (s.flags() & DEFAULT) != 0 &&
2455 s.isInheritedIn(site.tsym, types) &&
2456 !s.isConstructor();
2457 }
2458 }
2460 /** Report a conflict between a user symbol and a synthetic symbol.
2461 */
2462 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2463 if (!sym.type.isErroneous()) {
2464 if (warnOnSyntheticConflicts) {
2465 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2466 }
2467 else {
2468 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2469 }
2470 }
2471 }
2473 /** Check that class c does not implement directly or indirectly
2474 * the same parameterized interface with two different argument lists.
2475 * @param pos Position to be used for error reporting.
2476 * @param type The type whose interfaces are checked.
2477 */
2478 void checkClassBounds(DiagnosticPosition pos, Type type) {
2479 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2480 }
2481 //where
2482 /** Enter all interfaces of type `type' into the hash table `seensofar'
2483 * with their class symbol as key and their type as value. Make
2484 * sure no class is entered with two different types.
2485 */
2486 void checkClassBounds(DiagnosticPosition pos,
2487 Map<TypeSymbol,Type> seensofar,
2488 Type type) {
2489 if (type.isErroneous()) return;
2490 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2491 Type it = l.head;
2492 Type oldit = seensofar.put(it.tsym, it);
2493 if (oldit != null) {
2494 List<Type> oldparams = oldit.allparams();
2495 List<Type> newparams = it.allparams();
2496 if (!types.containsTypeEquivalent(oldparams, newparams))
2497 log.error(pos, "cant.inherit.diff.arg",
2498 it.tsym, Type.toString(oldparams),
2499 Type.toString(newparams));
2500 }
2501 checkClassBounds(pos, seensofar, it);
2502 }
2503 Type st = types.supertype(type);
2504 if (st != null) checkClassBounds(pos, seensofar, st);
2505 }
2507 /** Enter interface into into set.
2508 * If it existed already, issue a "repeated interface" error.
2509 */
2510 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2511 if (its.contains(it))
2512 log.error(pos, "repeated.interface");
2513 else {
2514 its.add(it);
2515 }
2516 }
2518 /* *************************************************************************
2519 * Check annotations
2520 **************************************************************************/
2522 /**
2523 * Recursively validate annotations values
2524 */
2525 void validateAnnotationTree(JCTree tree) {
2526 class AnnotationValidator extends TreeScanner {
2527 @Override
2528 public void visitAnnotation(JCAnnotation tree) {
2529 if (!tree.type.isErroneous()) {
2530 super.visitAnnotation(tree);
2531 validateAnnotation(tree);
2532 }
2533 }
2534 }
2535 tree.accept(new AnnotationValidator());
2536 }
2538 /**
2539 * {@literal
2540 * Annotation types are restricted to primitives, String, an
2541 * enum, an annotation, Class, Class<?>, Class<? extends
2542 * Anything>, arrays of the preceding.
2543 * }
2544 */
2545 void validateAnnotationType(JCTree restype) {
2546 // restype may be null if an error occurred, so don't bother validating it
2547 if (restype != null) {
2548 validateAnnotationType(restype.pos(), restype.type);
2549 }
2550 }
2552 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2553 if (type.isPrimitive()) return;
2554 if (types.isSameType(type, syms.stringType)) return;
2555 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2556 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2557 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2558 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2559 validateAnnotationType(pos, types.elemtype(type));
2560 return;
2561 }
2562 log.error(pos, "invalid.annotation.member.type");
2563 }
2565 /**
2566 * "It is also a compile-time error if any method declared in an
2567 * annotation type has a signature that is override-equivalent to
2568 * that of any public or protected method declared in class Object
2569 * or in the interface annotation.Annotation."
2570 *
2571 * @jls 9.6 Annotation Types
2572 */
2573 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2574 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2575 Scope s = sup.tsym.members();
2576 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2577 if (e.sym.kind == MTH &&
2578 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2579 types.overrideEquivalent(m.type, e.sym.type))
2580 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2581 }
2582 }
2583 }
2585 /** Check the annotations of a symbol.
2586 */
2587 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2588 for (JCAnnotation a : annotations)
2589 validateAnnotation(a, s);
2590 }
2592 /** Check an annotation of a symbol.
2593 */
2594 private void validateAnnotation(JCAnnotation a, Symbol s) {
2595 validateAnnotationTree(a);
2597 if (!annotationApplicable(a, s))
2598 log.error(a.pos(), "annotation.type.not.applicable");
2600 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2601 if (!isOverrider(s))
2602 log.error(a.pos(), "method.does.not.override.superclass");
2603 }
2605 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2606 if (s.kind != TYP) {
2607 log.error(a.pos(), "bad.functional.intf.anno");
2608 } else {
2609 try {
2610 types.findDescriptorSymbol((TypeSymbol)s);
2611 } catch (Types.FunctionDescriptorLookupError ex) {
2612 log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
2613 }
2614 }
2615 }
2616 }
2618 /**
2619 * Validate the proposed container 'repeatable' on the
2620 * annotation type symbol 's'. Report errors at position
2621 * 'pos'.
2622 *
2623 * @param s The (annotation)type declaration annotated with a @Repeatable
2624 * @param repeatable the @Repeatable on 's'
2625 * @param pos where to report errors
2626 */
2627 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2628 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2630 Type t = null;
2631 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2632 if (!l.isEmpty()) {
2633 Assert.check(l.head.fst.name == names.value);
2634 t = ((Attribute.Class)l.head.snd).getValue();
2635 }
2637 if (t == null) {
2638 // errors should already have been reported during Annotate
2639 return;
2640 }
2642 validateValue(t.tsym, s, pos);
2643 validateRetention(t.tsym, s, pos);
2644 validateDocumented(t.tsym, s, pos);
2645 validateInherited(t.tsym, s, pos);
2646 validateTarget(t.tsym, s, pos);
2647 validateDefault(t.tsym, s, pos);
2648 }
2650 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2651 Scope.Entry e = container.members().lookup(names.value);
2652 if (e.scope != null && e.sym.kind == MTH) {
2653 MethodSymbol m = (MethodSymbol) e.sym;
2654 Type ret = m.getReturnType();
2655 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2656 log.error(pos, "invalid.repeatable.annotation.value.return",
2657 container, ret, types.makeArrayType(contained.type));
2658 }
2659 } else {
2660 log.error(pos, "invalid.repeatable.annotation.no.value", container);
2661 }
2662 }
2664 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2665 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2666 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2668 boolean error = false;
2669 switch (containedRetention) {
2670 case RUNTIME:
2671 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2672 error = true;
2673 }
2674 break;
2675 case CLASS:
2676 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2677 error = true;
2678 }
2679 }
2680 if (error ) {
2681 log.error(pos, "invalid.repeatable.annotation.retention",
2682 container, containerRetention,
2683 contained, containedRetention);
2684 }
2685 }
2687 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2688 if (contained.attribute(syms.documentedType.tsym) != null) {
2689 if (container.attribute(syms.documentedType.tsym) == null) {
2690 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
2691 }
2692 }
2693 }
2695 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2696 if (contained.attribute(syms.inheritedType.tsym) != null) {
2697 if (container.attribute(syms.inheritedType.tsym) == null) {
2698 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
2699 }
2700 }
2701 }
2703 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2704 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2706 // If contained has no Target, we are done
2707 if (containedTarget == null) {
2708 return;
2709 }
2711 // If contained has Target m1, container must have a Target
2712 // annotation, m2, and m2 must be a subset of m1. (This is
2713 // trivially true if contained has no target as per above).
2715 // contained has target, but container has not, error
2716 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2717 if (containerTarget == null) {
2718 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2719 return;
2720 }
2722 Set<Name> containerTargets = new HashSet<Name>();
2723 for (Attribute app : containerTarget.values) {
2724 if (!(app instanceof Attribute.Enum)) {
2725 continue; // recovery
2726 }
2727 Attribute.Enum e = (Attribute.Enum)app;
2728 containerTargets.add(e.value.name);
2729 }
2731 Set<Name> containedTargets = new HashSet<Name>();
2732 for (Attribute app : containedTarget.values) {
2733 if (!(app instanceof Attribute.Enum)) {
2734 continue; // recovery
2735 }
2736 Attribute.Enum e = (Attribute.Enum)app;
2737 containedTargets.add(e.value.name);
2738 }
2740 if (!isTargetSubset(containedTargets, containerTargets)) {
2741 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
2742 }
2743 }
2745 /** Checks that t is a subset of s, with respect to ElementType
2746 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2747 */
2748 private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
2749 // Check that all elements in t are present in s
2750 for (Name n2 : t) {
2751 boolean currentElementOk = false;
2752 for (Name n1 : s) {
2753 if (n1 == n2) {
2754 currentElementOk = true;
2755 break;
2756 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2757 currentElementOk = true;
2758 break;
2759 }
2760 }
2761 if (!currentElementOk)
2762 return false;
2763 }
2764 return true;
2765 }
2767 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2768 // validate that all other elements of containing type has defaults
2769 Scope scope = container.members();
2770 for(Symbol elm : scope.getElements()) {
2771 if (elm.name != names.value &&
2772 elm.kind == Kinds.MTH &&
2773 ((MethodSymbol)elm).defaultValue == null) {
2774 log.error(pos,
2775 "invalid.repeatable.annotation.elem.nondefault",
2776 container,
2777 elm);
2778 }
2779 }
2780 }
2782 /** Is s a method symbol that overrides a method in a superclass? */
2783 boolean isOverrider(Symbol s) {
2784 if (s.kind != MTH || s.isStatic())
2785 return false;
2786 MethodSymbol m = (MethodSymbol)s;
2787 TypeSymbol owner = (TypeSymbol)m.owner;
2788 for (Type sup : types.closure(owner.type)) {
2789 if (sup == owner.type)
2790 continue; // skip "this"
2791 Scope scope = sup.tsym.members();
2792 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2793 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2794 return true;
2795 }
2796 }
2797 return false;
2798 }
2800 /** Is the annotation applicable to the symbol? */
2801 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2802 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2803 if (arr == null) {
2804 return true;
2805 }
2806 for (Attribute app : arr.values) {
2807 if (!(app instanceof Attribute.Enum)) return true; // recovery
2808 Attribute.Enum e = (Attribute.Enum) app;
2809 if (e.value.name == names.TYPE)
2810 { if (s.kind == TYP) return true; }
2811 else if (e.value.name == names.FIELD)
2812 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2813 else if (e.value.name == names.METHOD)
2814 { if (s.kind == MTH && !s.isConstructor()) return true; }
2815 else if (e.value.name == names.PARAMETER)
2816 { if (s.kind == VAR &&
2817 s.owner.kind == MTH &&
2818 (s.flags() & PARAMETER) != 0)
2819 return true;
2820 }
2821 else if (e.value.name == names.CONSTRUCTOR)
2822 { if (s.kind == MTH && s.isConstructor()) return true; }
2823 else if (e.value.name == names.LOCAL_VARIABLE)
2824 { if (s.kind == VAR && s.owner.kind == MTH &&
2825 (s.flags() & PARAMETER) == 0)
2826 return true;
2827 }
2828 else if (e.value.name == names.ANNOTATION_TYPE)
2829 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2830 return true;
2831 }
2832 else if (e.value.name == names.PACKAGE)
2833 { if (s.kind == PCK) return true; }
2834 else if (e.value.name == names.TYPE_USE)
2835 { if (s.kind == TYP ||
2836 s.kind == VAR ||
2837 (s.kind == MTH && !s.isConstructor() &&
2838 !s.type.getReturnType().hasTag(VOID)))
2839 return true;
2840 }
2841 else
2842 return true; // recovery
2843 }
2844 return false;
2845 }
2848 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2849 Attribute.Compound atTarget =
2850 s.attribute(syms.annotationTargetType.tsym);
2851 if (atTarget == null) return null; // ok, is applicable
2852 Attribute atValue = atTarget.member(names.value);
2853 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2854 return (Attribute.Array) atValue;
2855 }
2857 /** Check an annotation value.
2858 *
2859 * @param a The annotation tree to check
2860 * @return true if this annotation tree is valid, otherwise false
2861 */
2862 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
2863 boolean res = false;
2864 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
2865 try {
2866 res = validateAnnotation(a);
2867 } finally {
2868 log.popDiagnosticHandler(diagHandler);
2869 }
2870 return res;
2871 }
2873 private boolean validateAnnotation(JCAnnotation a) {
2874 boolean isValid = true;
2875 // collect an inventory of the annotation elements
2876 Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
2877 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2878 e != null;
2879 e = e.sibling)
2880 if (e.sym.kind == MTH)
2881 members.add((MethodSymbol) e.sym);
2883 // remove the ones that are assigned values
2884 for (JCTree arg : a.args) {
2885 if (!arg.hasTag(ASSIGN)) continue; // recovery
2886 JCAssign assign = (JCAssign) arg;
2887 Symbol m = TreeInfo.symbol(assign.lhs);
2888 if (m == null || m.type.isErroneous()) continue;
2889 if (!members.remove(m)) {
2890 isValid = false;
2891 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2892 m.name, a.type);
2893 }
2894 }
2896 // all the remaining ones better have default values
2897 List<Name> missingDefaults = List.nil();
2898 for (MethodSymbol m : members) {
2899 if (m.defaultValue == null && !m.type.isErroneous()) {
2900 missingDefaults = missingDefaults.append(m.name);
2901 }
2902 }
2903 missingDefaults = missingDefaults.reverse();
2904 if (missingDefaults.nonEmpty()) {
2905 isValid = false;
2906 String key = (missingDefaults.size() > 1)
2907 ? "annotation.missing.default.value.1"
2908 : "annotation.missing.default.value";
2909 log.error(a.pos(), key, a.type, missingDefaults);
2910 }
2912 // special case: java.lang.annotation.Target must not have
2913 // repeated values in its value member
2914 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2915 a.args.tail == null)
2916 return isValid;
2918 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
2919 JCAssign assign = (JCAssign) a.args.head;
2920 Symbol m = TreeInfo.symbol(assign.lhs);
2921 if (m.name != names.value) return false;
2922 JCTree rhs = assign.rhs;
2923 if (!rhs.hasTag(NEWARRAY)) return false;
2924 JCNewArray na = (JCNewArray) rhs;
2925 Set<Symbol> targets = new HashSet<Symbol>();
2926 for (JCTree elem : na.elems) {
2927 if (!targets.add(TreeInfo.symbol(elem))) {
2928 isValid = false;
2929 log.error(elem.pos(), "repeated.annotation.target");
2930 }
2931 }
2932 return isValid;
2933 }
2935 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2936 if (allowAnnotations &&
2937 lint.isEnabled(LintCategory.DEP_ANN) &&
2938 (s.flags() & DEPRECATED) != 0 &&
2939 !syms.deprecatedType.isErroneous() &&
2940 s.attribute(syms.deprecatedType.tsym) == null) {
2941 log.warning(LintCategory.DEP_ANN,
2942 pos, "missing.deprecated.annotation");
2943 }
2944 }
2946 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2947 if ((s.flags() & DEPRECATED) != 0 &&
2948 (other.flags() & DEPRECATED) == 0 &&
2949 s.outermostClass() != other.outermostClass()) {
2950 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2951 @Override
2952 public void report() {
2953 warnDeprecated(pos, s);
2954 }
2955 });
2956 }
2957 }
2959 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2960 if ((s.flags() & PROPRIETARY) != 0) {
2961 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2962 public void report() {
2963 if (enableSunApiLintControl)
2964 warnSunApi(pos, "sun.proprietary", s);
2965 else
2966 log.mandatoryWarning(pos, "sun.proprietary", s);
2967 }
2968 });
2969 }
2970 }
2972 /* *************************************************************************
2973 * Check for recursive annotation elements.
2974 **************************************************************************/
2976 /** Check for cycles in the graph of annotation elements.
2977 */
2978 void checkNonCyclicElements(JCClassDecl tree) {
2979 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2980 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2981 try {
2982 tree.sym.flags_field |= LOCKED;
2983 for (JCTree def : tree.defs) {
2984 if (!def.hasTag(METHODDEF)) continue;
2985 JCMethodDecl meth = (JCMethodDecl)def;
2986 checkAnnotationResType(meth.pos(), meth.restype.type);
2987 }
2988 } finally {
2989 tree.sym.flags_field &= ~LOCKED;
2990 tree.sym.flags_field |= ACYCLIC_ANN;
2991 }
2992 }
2994 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2995 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2996 return;
2997 if ((tsym.flags_field & LOCKED) != 0) {
2998 log.error(pos, "cyclic.annotation.element");
2999 return;
3000 }
3001 try {
3002 tsym.flags_field |= LOCKED;
3003 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3004 Symbol s = e.sym;
3005 if (s.kind != Kinds.MTH)
3006 continue;
3007 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3008 }
3009 } finally {
3010 tsym.flags_field &= ~LOCKED;
3011 tsym.flags_field |= ACYCLIC_ANN;
3012 }
3013 }
3015 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3016 switch (type.getTag()) {
3017 case CLASS:
3018 if ((type.tsym.flags() & ANNOTATION) != 0)
3019 checkNonCyclicElementsInternal(pos, type.tsym);
3020 break;
3021 case ARRAY:
3022 checkAnnotationResType(pos, types.elemtype(type));
3023 break;
3024 default:
3025 break; // int etc
3026 }
3027 }
3029 /* *************************************************************************
3030 * Check for cycles in the constructor call graph.
3031 **************************************************************************/
3033 /** Check for cycles in the graph of constructors calling other
3034 * constructors.
3035 */
3036 void checkCyclicConstructors(JCClassDecl tree) {
3037 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3039 // enter each constructor this-call into the map
3040 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3041 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3042 if (app == null) continue;
3043 JCMethodDecl meth = (JCMethodDecl) l.head;
3044 if (TreeInfo.name(app.meth) == names._this) {
3045 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3046 } else {
3047 meth.sym.flags_field |= ACYCLIC;
3048 }
3049 }
3051 // Check for cycles in the map
3052 Symbol[] ctors = new Symbol[0];
3053 ctors = callMap.keySet().toArray(ctors);
3054 for (Symbol caller : ctors) {
3055 checkCyclicConstructor(tree, caller, callMap);
3056 }
3057 }
3059 /** Look in the map to see if the given constructor is part of a
3060 * call cycle.
3061 */
3062 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3063 Map<Symbol,Symbol> callMap) {
3064 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3065 if ((ctor.flags_field & LOCKED) != 0) {
3066 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3067 "recursive.ctor.invocation");
3068 } else {
3069 ctor.flags_field |= LOCKED;
3070 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3071 ctor.flags_field &= ~LOCKED;
3072 }
3073 ctor.flags_field |= ACYCLIC;
3074 }
3075 }
3077 /* *************************************************************************
3078 * Miscellaneous
3079 **************************************************************************/
3081 /**
3082 * Return the opcode of the operator but emit an error if it is an
3083 * error.
3084 * @param pos position for error reporting.
3085 * @param operator an operator
3086 * @param tag a tree tag
3087 * @param left type of left hand side
3088 * @param right type of right hand side
3089 */
3090 int checkOperator(DiagnosticPosition pos,
3091 OperatorSymbol operator,
3092 JCTree.Tag tag,
3093 Type left,
3094 Type right) {
3095 if (operator.opcode == ByteCodes.error) {
3096 log.error(pos,
3097 "operator.cant.be.applied.1",
3098 treeinfo.operatorName(tag),
3099 left, right);
3100 }
3101 return operator.opcode;
3102 }
3105 /**
3106 * Check for division by integer constant zero
3107 * @param pos Position for error reporting.
3108 * @param operator The operator for the expression
3109 * @param operand The right hand operand for the expression
3110 */
3111 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3112 if (operand.constValue() != null
3113 && lint.isEnabled(LintCategory.DIVZERO)
3114 && (operand.getTag().isSubRangeOf(LONG))
3115 && ((Number) (operand.constValue())).longValue() == 0) {
3116 int opc = ((OperatorSymbol)operator).opcode;
3117 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3118 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3119 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3120 }
3121 }
3122 }
3124 /**
3125 * Check for empty statements after if
3126 */
3127 void checkEmptyIf(JCIf tree) {
3128 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3129 lint.isEnabled(LintCategory.EMPTY))
3130 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3131 }
3133 /** Check that symbol is unique in given scope.
3134 * @param pos Position for error reporting.
3135 * @param sym The symbol.
3136 * @param s The scope.
3137 */
3138 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3139 if (sym.type.isErroneous())
3140 return true;
3141 if (sym.owner.name == names.any) return false;
3142 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3143 if (sym != e.sym &&
3144 (e.sym.flags() & CLASH) == 0 &&
3145 sym.kind == e.sym.kind &&
3146 sym.name != names.error &&
3147 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3148 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3149 varargsDuplicateError(pos, sym, e.sym);
3150 return true;
3151 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3152 duplicateErasureError(pos, sym, e.sym);
3153 sym.flags_field |= CLASH;
3154 return true;
3155 } else {
3156 duplicateError(pos, e.sym);
3157 return false;
3158 }
3159 }
3160 }
3161 return true;
3162 }
3164 /** Report duplicate declaration error.
3165 */
3166 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3167 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3168 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3169 }
3170 }
3172 /** Check that single-type import is not already imported or top-level defined,
3173 * but make an exception for two single-type imports which denote the same type.
3174 * @param pos Position for error reporting.
3175 * @param sym The symbol.
3176 * @param s The scope
3177 */
3178 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3179 return checkUniqueImport(pos, sym, s, false);
3180 }
3182 /** Check that static single-type import is not already imported or top-level defined,
3183 * but make an exception for two single-type imports which denote the same type.
3184 * @param pos Position for error reporting.
3185 * @param sym The symbol.
3186 * @param s The scope
3187 */
3188 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3189 return checkUniqueImport(pos, sym, s, true);
3190 }
3192 /** Check that single-type import is not already imported or top-level defined,
3193 * but make an exception for two single-type imports which denote the same type.
3194 * @param pos Position for error reporting.
3195 * @param sym The symbol.
3196 * @param s The scope.
3197 * @param staticImport Whether or not this was a static import
3198 */
3199 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3200 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3201 // is encountered class entered via a class declaration?
3202 boolean isClassDecl = e.scope == s;
3203 if ((isClassDecl || sym != e.sym) &&
3204 sym.kind == e.sym.kind &&
3205 sym.name != names.error) {
3206 if (!e.sym.type.isErroneous()) {
3207 String what = e.sym.toString();
3208 if (!isClassDecl) {
3209 if (staticImport)
3210 log.error(pos, "already.defined.static.single.import", what);
3211 else
3212 log.error(pos, "already.defined.single.import", what);
3213 }
3214 else if (sym != e.sym)
3215 log.error(pos, "already.defined.this.unit", what);
3216 }
3217 return false;
3218 }
3219 }
3220 return true;
3221 }
3223 /** Check that a qualified name is in canonical form (for import decls).
3224 */
3225 public void checkCanonical(JCTree tree) {
3226 if (!isCanonical(tree))
3227 log.error(tree.pos(), "import.requires.canonical",
3228 TreeInfo.symbol(tree));
3229 }
3230 // where
3231 private boolean isCanonical(JCTree tree) {
3232 while (tree.hasTag(SELECT)) {
3233 JCFieldAccess s = (JCFieldAccess) tree;
3234 if (s.sym.owner != TreeInfo.symbol(s.selected))
3235 return false;
3236 tree = s.selected;
3237 }
3238 return true;
3239 }
3241 /** Check that an auxiliary class is not accessed from any other file than its own.
3242 */
3243 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3244 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3245 (c.flags() & AUXILIARY) != 0 &&
3246 rs.isAccessible(env, c) &&
3247 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3248 {
3249 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3250 c, c.sourcefile);
3251 }
3252 }
3254 private class ConversionWarner extends Warner {
3255 final String uncheckedKey;
3256 final Type found;
3257 final Type expected;
3258 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3259 super(pos);
3260 this.uncheckedKey = uncheckedKey;
3261 this.found = found;
3262 this.expected = expected;
3263 }
3265 @Override
3266 public void warn(LintCategory lint) {
3267 boolean warned = this.warned;
3268 super.warn(lint);
3269 if (warned) return; // suppress redundant diagnostics
3270 switch (lint) {
3271 case UNCHECKED:
3272 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3273 break;
3274 case VARARGS:
3275 if (method != null &&
3276 method.attribute(syms.trustMeType.tsym) != null &&
3277 isTrustMeAllowedOnMethod(method) &&
3278 !types.isReifiable(method.type.getParameterTypes().last())) {
3279 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3280 }
3281 break;
3282 default:
3283 throw new AssertionError("Unexpected lint: " + lint);
3284 }
3285 }
3286 }
3288 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3289 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3290 }
3292 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3293 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3294 }
3295 }