Mon, 17 Dec 2012 07:47:05 -0800
8004832: Add new doclint package
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2012, 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 /** Check that type is a class or interface type.
638 * @param pos Position to be used for error reporting.
639 * @param t The type to be checked.
640 */
641 Type checkClassType(DiagnosticPosition pos, Type t) {
642 if (!t.hasTag(CLASS) && !t.hasTag(ERROR))
643 return typeTagError(pos,
644 diags.fragment("type.req.class"),
645 (t.hasTag(TYPEVAR))
646 ? diags.fragment("type.parameter", t)
647 : t);
648 else
649 return t;
650 }
652 /** Check that type is a valid qualifier for a constructor reference expression
653 */
654 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
655 t = checkClassType(pos, t);
656 if (t.hasTag(CLASS)) {
657 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
658 log.error(pos, "abstract.cant.be.instantiated");
659 t = types.createErrorType(t);
660 } else if ((t.tsym.flags() & ENUM) != 0) {
661 log.error(pos, "enum.cant.be.instantiated");
662 t = types.createErrorType(t);
663 }
664 }
665 return t;
666 }
668 /** Check that type is a class or interface type.
669 * @param pos Position to be used for error reporting.
670 * @param t The type to be checked.
671 * @param noBounds True if type bounds are illegal here.
672 */
673 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
674 t = checkClassType(pos, t);
675 if (noBounds && t.isParameterized()) {
676 List<Type> args = t.getTypeArguments();
677 while (args.nonEmpty()) {
678 if (args.head.hasTag(WILDCARD))
679 return typeTagError(pos,
680 diags.fragment("type.req.exact"),
681 args.head);
682 args = args.tail;
683 }
684 }
685 return t;
686 }
688 /** Check that type is a reifiable class, interface or array type.
689 * @param pos Position to be used for error reporting.
690 * @param t The type to be checked.
691 */
692 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
693 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
694 return typeTagError(pos,
695 diags.fragment("type.req.class.array"),
696 t);
697 } else if (!types.isReifiable(t)) {
698 log.error(pos, "illegal.generic.type.for.instof");
699 return types.createErrorType(t);
700 } else {
701 return t;
702 }
703 }
705 /** Check that type is a reference type, i.e. a class, interface or array type
706 * or a type variable.
707 * @param pos Position to be used for error reporting.
708 * @param t The type to be checked.
709 */
710 Type checkRefType(DiagnosticPosition pos, Type t) {
711 if (t.isReference())
712 return t;
713 else
714 return typeTagError(pos,
715 diags.fragment("type.req.ref"),
716 t);
717 }
719 /** Check that each type is a reference type, i.e. a class, interface or array type
720 * or a type variable.
721 * @param trees Original trees, used for error reporting.
722 * @param types The types to be checked.
723 */
724 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
725 List<JCExpression> tl = trees;
726 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
727 l.head = checkRefType(tl.head.pos(), l.head);
728 tl = tl.tail;
729 }
730 return types;
731 }
733 /** Check that type is a null or reference type.
734 * @param pos Position to be used for error reporting.
735 * @param t The type to be checked.
736 */
737 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
738 if (t.isNullOrReference())
739 return t;
740 else
741 return typeTagError(pos,
742 diags.fragment("type.req.ref"),
743 t);
744 }
746 /** Check that flag set does not contain elements of two conflicting sets. s
747 * Return true if it doesn't.
748 * @param pos Position to be used for error reporting.
749 * @param flags The set of flags to be checked.
750 * @param set1 Conflicting flags set #1.
751 * @param set2 Conflicting flags set #2.
752 */
753 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
754 if ((flags & set1) != 0 && (flags & set2) != 0) {
755 log.error(pos,
756 "illegal.combination.of.modifiers",
757 asFlagSet(TreeInfo.firstFlag(flags & set1)),
758 asFlagSet(TreeInfo.firstFlag(flags & set2)));
759 return false;
760 } else
761 return true;
762 }
764 /** Check that usage of diamond operator is correct (i.e. diamond should not
765 * be used with non-generic classes or in anonymous class creation expressions)
766 */
767 Type checkDiamond(JCNewClass tree, Type t) {
768 if (!TreeInfo.isDiamond(tree) ||
769 t.isErroneous()) {
770 return checkClassType(tree.clazz.pos(), t, true);
771 } else if (tree.def != null) {
772 log.error(tree.clazz.pos(),
773 "cant.apply.diamond.1",
774 t, diags.fragment("diamond.and.anon.class", t));
775 return types.createErrorType(t);
776 } else if (t.tsym.type.getTypeArguments().isEmpty()) {
777 log.error(tree.clazz.pos(),
778 "cant.apply.diamond.1",
779 t, diags.fragment("diamond.non.generic", t));
780 return types.createErrorType(t);
781 } else if (tree.typeargs != null &&
782 tree.typeargs.nonEmpty()) {
783 log.error(tree.clazz.pos(),
784 "cant.apply.diamond.1",
785 t, diags.fragment("diamond.and.explicit.params", t));
786 return types.createErrorType(t);
787 } else {
788 return t;
789 }
790 }
792 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
793 MethodSymbol m = tree.sym;
794 if (!allowSimplifiedVarargs) return;
795 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
796 Type varargElemType = null;
797 if (m.isVarArgs()) {
798 varargElemType = types.elemtype(tree.params.last().type);
799 }
800 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
801 if (varargElemType != null) {
802 log.error(tree,
803 "varargs.invalid.trustme.anno",
804 syms.trustMeType.tsym,
805 diags.fragment("varargs.trustme.on.virtual.varargs", m));
806 } else {
807 log.error(tree,
808 "varargs.invalid.trustme.anno",
809 syms.trustMeType.tsym,
810 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
811 }
812 } else if (hasTrustMeAnno && varargElemType != null &&
813 types.isReifiable(varargElemType)) {
814 warnUnsafeVararg(tree,
815 "varargs.redundant.trustme.anno",
816 syms.trustMeType.tsym,
817 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
818 }
819 else if (!hasTrustMeAnno && varargElemType != null &&
820 !types.isReifiable(varargElemType)) {
821 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
822 }
823 }
824 //where
825 private boolean isTrustMeAllowedOnMethod(Symbol s) {
826 return (s.flags() & VARARGS) != 0 &&
827 (s.isConstructor() ||
828 (s.flags() & (STATIC | FINAL)) != 0);
829 }
831 Type checkMethod(Type owntype,
832 Symbol sym,
833 Env<AttrContext> env,
834 final List<JCExpression> argtrees,
835 List<Type> argtypes,
836 boolean useVarargs,
837 boolean unchecked) {
838 // System.out.println("call : " + env.tree);
839 // System.out.println("method : " + owntype);
840 // System.out.println("actuals: " + argtypes);
841 List<Type> formals = owntype.getParameterTypes();
842 Type last = useVarargs ? formals.last() : null;
843 if (sym.name==names.init &&
844 sym.owner == syms.enumSym)
845 formals = formals.tail.tail;
846 List<JCExpression> args = argtrees;
847 DeferredAttr.DeferredTypeMap checkDeferredMap =
848 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
849 if (args != null) {
850 //this is null when type-checking a method reference
851 while (formals.head != last) {
852 JCTree arg = args.head;
853 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
854 assertConvertible(arg, arg.type, formals.head, warn);
855 args = args.tail;
856 formals = formals.tail;
857 }
858 if (useVarargs) {
859 Type varArg = types.elemtype(last);
860 while (args.tail != null) {
861 JCTree arg = args.head;
862 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
863 assertConvertible(arg, arg.type, varArg, warn);
864 args = args.tail;
865 }
866 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
867 // non-varargs call to varargs method
868 Type varParam = owntype.getParameterTypes().last();
869 Type lastArg = checkDeferredMap.apply(argtypes.last());
870 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
871 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
872 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
873 types.elemtype(varParam), varParam);
874 }
875 }
876 if (unchecked) {
877 warnUnchecked(env.tree.pos(),
878 "unchecked.meth.invocation.applied",
879 kindName(sym),
880 sym.name,
881 rs.methodArguments(sym.type.getParameterTypes()),
882 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
883 kindName(sym.location()),
884 sym.location());
885 owntype = new MethodType(owntype.getParameterTypes(),
886 types.erasure(owntype.getReturnType()),
887 types.erasure(owntype.getThrownTypes()),
888 syms.methodClass);
889 }
890 if (useVarargs) {
891 JCTree tree = env.tree;
892 Type argtype = owntype.getParameterTypes().last();
893 if (!types.isReifiable(argtype) &&
894 (!allowSimplifiedVarargs ||
895 sym.attribute(syms.trustMeType.tsym) == null ||
896 !isTrustMeAllowedOnMethod(sym))) {
897 warnUnchecked(env.tree.pos(),
898 "unchecked.generic.array.creation",
899 argtype);
900 }
901 if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
902 Type elemtype = types.elemtype(argtype);
903 switch (tree.getTag()) {
904 case APPLY:
905 ((JCMethodInvocation) tree).varargsElement = elemtype;
906 break;
907 case NEWCLASS:
908 ((JCNewClass) tree).varargsElement = elemtype;
909 break;
910 case REFERENCE:
911 ((JCMemberReference) tree).varargsElement = elemtype;
912 break;
913 default:
914 throw new AssertionError(""+tree);
915 }
916 }
917 }
918 return owntype;
919 }
920 //where
921 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
922 if (types.isConvertible(actual, formal, warn))
923 return;
925 if (formal.isCompound()
926 && types.isSubtype(actual, types.supertype(formal))
927 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
928 return;
929 }
931 /**
932 * Check that type 't' is a valid instantiation of a generic class
933 * (see JLS 4.5)
934 *
935 * @param t class type to be checked
936 * @return true if 't' is well-formed
937 */
938 public boolean checkValidGenericType(Type t) {
939 return firstIncompatibleTypeArg(t) == null;
940 }
941 //WHERE
942 private Type firstIncompatibleTypeArg(Type type) {
943 List<Type> formals = type.tsym.type.allparams();
944 List<Type> actuals = type.allparams();
945 List<Type> args = type.getTypeArguments();
946 List<Type> forms = type.tsym.type.getTypeArguments();
947 ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
949 // For matching pairs of actual argument types `a' and
950 // formal type parameters with declared bound `b' ...
951 while (args.nonEmpty() && forms.nonEmpty()) {
952 // exact type arguments needs to know their
953 // bounds (for upper and lower bound
954 // calculations). So we create new bounds where
955 // type-parameters are replaced with actuals argument types.
956 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
957 args = args.tail;
958 forms = forms.tail;
959 }
961 args = type.getTypeArguments();
962 List<Type> tvars_cap = types.substBounds(formals,
963 formals,
964 types.capture(type).allparams());
965 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
966 // Let the actual arguments know their bound
967 args.head.withTypeVar((TypeVar)tvars_cap.head);
968 args = args.tail;
969 tvars_cap = tvars_cap.tail;
970 }
972 args = type.getTypeArguments();
973 List<Type> bounds = bounds_buf.toList();
975 while (args.nonEmpty() && bounds.nonEmpty()) {
976 Type actual = args.head;
977 if (!isTypeArgErroneous(actual) &&
978 !bounds.head.isErroneous() &&
979 !checkExtends(actual, bounds.head)) {
980 return args.head;
981 }
982 args = args.tail;
983 bounds = bounds.tail;
984 }
986 args = type.getTypeArguments();
987 bounds = bounds_buf.toList();
989 for (Type arg : types.capture(type).getTypeArguments()) {
990 if (arg.hasTag(TYPEVAR) &&
991 arg.getUpperBound().isErroneous() &&
992 !bounds.head.isErroneous() &&
993 !isTypeArgErroneous(args.head)) {
994 return args.head;
995 }
996 bounds = bounds.tail;
997 args = args.tail;
998 }
1000 return null;
1001 }
1002 //where
1003 boolean isTypeArgErroneous(Type t) {
1004 return isTypeArgErroneous.visit(t);
1005 }
1007 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1008 public Boolean visitType(Type t, Void s) {
1009 return t.isErroneous();
1010 }
1011 @Override
1012 public Boolean visitTypeVar(TypeVar t, Void s) {
1013 return visit(t.getUpperBound());
1014 }
1015 @Override
1016 public Boolean visitCapturedType(CapturedType t, Void s) {
1017 return visit(t.getUpperBound()) ||
1018 visit(t.getLowerBound());
1019 }
1020 @Override
1021 public Boolean visitWildcardType(WildcardType t, Void s) {
1022 return visit(t.type);
1023 }
1024 };
1026 /** Check that given modifiers are legal for given symbol and
1027 * return modifiers together with any implicit modififiers for that symbol.
1028 * Warning: we can't use flags() here since this method
1029 * is called during class enter, when flags() would cause a premature
1030 * completion.
1031 * @param pos Position to be used for error reporting.
1032 * @param flags The set of modifiers given in a definition.
1033 * @param sym The defined symbol.
1034 */
1035 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1036 long mask;
1037 long implicit = 0;
1038 switch (sym.kind) {
1039 case VAR:
1040 if (sym.owner.kind != TYP)
1041 mask = LocalVarFlags;
1042 else if ((sym.owner.flags_field & INTERFACE) != 0)
1043 mask = implicit = InterfaceVarFlags;
1044 else
1045 mask = VarFlags;
1046 break;
1047 case MTH:
1048 if (sym.name == names.init) {
1049 if ((sym.owner.flags_field & ENUM) != 0) {
1050 // enum constructors cannot be declared public or
1051 // protected and must be implicitly or explicitly
1052 // private
1053 implicit = PRIVATE;
1054 mask = PRIVATE;
1055 } else
1056 mask = ConstructorFlags;
1057 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1058 if ((flags & DEFAULT) != 0) {
1059 mask = InterfaceDefaultMethodMask;
1060 implicit = PUBLIC | ABSTRACT;
1061 } else {
1062 mask = implicit = InterfaceMethodFlags;
1063 }
1064 }
1065 else {
1066 mask = MethodFlags;
1067 }
1068 // Imply STRICTFP if owner has STRICTFP set.
1069 if (((flags|implicit) & Flags.ABSTRACT) == 0)
1070 implicit |= sym.owner.flags_field & STRICTFP;
1071 break;
1072 case TYP:
1073 if (sym.isLocal()) {
1074 mask = LocalClassFlags;
1075 if (sym.name.isEmpty()) { // Anonymous class
1076 // Anonymous classes in static methods are themselves static;
1077 // that's why we admit STATIC here.
1078 mask |= STATIC;
1079 // JLS: Anonymous classes are final.
1080 implicit |= FINAL;
1081 }
1082 if ((sym.owner.flags_field & STATIC) == 0 &&
1083 (flags & ENUM) != 0)
1084 log.error(pos, "enums.must.be.static");
1085 } else if (sym.owner.kind == TYP) {
1086 mask = MemberClassFlags;
1087 if (sym.owner.owner.kind == PCK ||
1088 (sym.owner.flags_field & STATIC) != 0)
1089 mask |= STATIC;
1090 else if ((flags & ENUM) != 0)
1091 log.error(pos, "enums.must.be.static");
1092 // Nested interfaces and enums are always STATIC (Spec ???)
1093 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1094 } else {
1095 mask = ClassFlags;
1096 }
1097 // Interfaces are always ABSTRACT
1098 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1100 if ((flags & ENUM) != 0) {
1101 // enums can't be declared abstract or final
1102 mask &= ~(ABSTRACT | FINAL);
1103 implicit |= implicitEnumFinalFlag(tree);
1104 }
1105 // Imply STRICTFP if owner has STRICTFP set.
1106 implicit |= sym.owner.flags_field & STRICTFP;
1107 break;
1108 default:
1109 throw new AssertionError();
1110 }
1111 long illegal = flags & ExtendedStandardFlags & ~mask;
1112 if (illegal != 0) {
1113 if ((illegal & INTERFACE) != 0) {
1114 log.error(pos, "intf.not.allowed.here");
1115 mask |= INTERFACE;
1116 }
1117 else {
1118 log.error(pos,
1119 "mod.not.allowed.here", asFlagSet(illegal));
1120 }
1121 }
1122 else if ((sym.kind == TYP ||
1123 // ISSUE: Disallowing abstract&private is no longer appropriate
1124 // in the presence of inner classes. Should it be deleted here?
1125 checkDisjoint(pos, flags,
1126 ABSTRACT,
1127 PRIVATE | STATIC | DEFAULT))
1128 &&
1129 checkDisjoint(pos, flags,
1130 ABSTRACT | INTERFACE,
1131 FINAL | NATIVE | SYNCHRONIZED)
1132 &&
1133 checkDisjoint(pos, flags,
1134 PUBLIC,
1135 PRIVATE | PROTECTED)
1136 &&
1137 checkDisjoint(pos, flags,
1138 PRIVATE,
1139 PUBLIC | PROTECTED)
1140 &&
1141 checkDisjoint(pos, flags,
1142 FINAL,
1143 VOLATILE)
1144 &&
1145 (sym.kind == TYP ||
1146 checkDisjoint(pos, flags,
1147 ABSTRACT | NATIVE,
1148 STRICTFP))) {
1149 // skip
1150 }
1151 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1152 }
1155 /** Determine if this enum should be implicitly final.
1156 *
1157 * If the enum has no specialized enum contants, it is final.
1158 *
1159 * If the enum does have specialized enum contants, it is
1160 * <i>not</i> final.
1161 */
1162 private long implicitEnumFinalFlag(JCTree tree) {
1163 if (!tree.hasTag(CLASSDEF)) return 0;
1164 class SpecialTreeVisitor extends JCTree.Visitor {
1165 boolean specialized;
1166 SpecialTreeVisitor() {
1167 this.specialized = false;
1168 };
1170 @Override
1171 public void visitTree(JCTree tree) { /* no-op */ }
1173 @Override
1174 public void visitVarDef(JCVariableDecl tree) {
1175 if ((tree.mods.flags & ENUM) != 0) {
1176 if (tree.init instanceof JCNewClass &&
1177 ((JCNewClass) tree.init).def != null) {
1178 specialized = true;
1179 }
1180 }
1181 }
1182 }
1184 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1185 JCClassDecl cdef = (JCClassDecl) tree;
1186 for (JCTree defs: cdef.defs) {
1187 defs.accept(sts);
1188 if (sts.specialized) return 0;
1189 }
1190 return FINAL;
1191 }
1193 /* *************************************************************************
1194 * Type Validation
1195 **************************************************************************/
1197 /** Validate a type expression. That is,
1198 * check that all type arguments of a parametric type are within
1199 * their bounds. This must be done in a second phase after type attributon
1200 * since a class might have a subclass as type parameter bound. E.g:
1201 *
1202 * <pre>{@code
1203 * class B<A extends C> { ... }
1204 * class C extends B<C> { ... }
1205 * }</pre>
1206 *
1207 * and we can't make sure that the bound is already attributed because
1208 * of possible cycles.
1209 *
1210 * Visitor method: Validate a type expression, if it is not null, catching
1211 * and reporting any completion failures.
1212 */
1213 void validate(JCTree tree, Env<AttrContext> env) {
1214 validate(tree, env, true);
1215 }
1216 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1217 new Validator(env).validateTree(tree, checkRaw, true);
1218 }
1220 /** Visitor method: Validate a list of type expressions.
1221 */
1222 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1223 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1224 validate(l.head, env);
1225 }
1227 /** A visitor class for type validation.
1228 */
1229 class Validator extends JCTree.Visitor {
1231 boolean isOuter;
1232 Env<AttrContext> env;
1234 Validator(Env<AttrContext> env) {
1235 this.env = env;
1236 }
1238 @Override
1239 public void visitTypeArray(JCArrayTypeTree tree) {
1240 tree.elemtype.accept(this);
1241 }
1243 @Override
1244 public void visitTypeApply(JCTypeApply tree) {
1245 if (tree.type.hasTag(CLASS)) {
1246 List<JCExpression> args = tree.arguments;
1247 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1249 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1250 if (incompatibleArg != null) {
1251 for (JCTree arg : tree.arguments) {
1252 if (arg.type == incompatibleArg) {
1253 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1254 }
1255 forms = forms.tail;
1256 }
1257 }
1259 forms = tree.type.tsym.type.getTypeArguments();
1261 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1263 // For matching pairs of actual argument types `a' and
1264 // formal type parameters with declared bound `b' ...
1265 while (args.nonEmpty() && forms.nonEmpty()) {
1266 validateTree(args.head,
1267 !(isOuter && is_java_lang_Class),
1268 false);
1269 args = args.tail;
1270 forms = forms.tail;
1271 }
1273 // Check that this type is either fully parameterized, or
1274 // not parameterized at all.
1275 if (tree.type.getEnclosingType().isRaw())
1276 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1277 if (tree.clazz.hasTag(SELECT))
1278 visitSelectInternal((JCFieldAccess)tree.clazz);
1279 }
1280 }
1282 @Override
1283 public void visitTypeParameter(JCTypeParameter tree) {
1284 validateTrees(tree.bounds, true, isOuter);
1285 checkClassBounds(tree.pos(), tree.type);
1286 }
1288 @Override
1289 public void visitWildcard(JCWildcard tree) {
1290 if (tree.inner != null)
1291 validateTree(tree.inner, true, isOuter);
1292 }
1294 @Override
1295 public void visitSelect(JCFieldAccess tree) {
1296 if (tree.type.hasTag(CLASS)) {
1297 visitSelectInternal(tree);
1299 // Check that this type is either fully parameterized, or
1300 // not parameterized at all.
1301 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1302 log.error(tree.pos(), "improperly.formed.type.param.missing");
1303 }
1304 }
1306 public void visitSelectInternal(JCFieldAccess tree) {
1307 if (tree.type.tsym.isStatic() &&
1308 tree.selected.type.isParameterized()) {
1309 // The enclosing type is not a class, so we are
1310 // looking at a static member type. However, the
1311 // qualifying expression is parameterized.
1312 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1313 } else {
1314 // otherwise validate the rest of the expression
1315 tree.selected.accept(this);
1316 }
1317 }
1319 /** Default visitor method: do nothing.
1320 */
1321 @Override
1322 public void visitTree(JCTree tree) {
1323 }
1325 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1326 try {
1327 if (tree != null) {
1328 this.isOuter = isOuter;
1329 tree.accept(this);
1330 if (checkRaw)
1331 checkRaw(tree, env);
1332 }
1333 } catch (CompletionFailure ex) {
1334 completionError(tree.pos(), ex);
1335 }
1336 }
1338 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1339 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1340 validateTree(l.head, checkRaw, isOuter);
1341 }
1343 void checkRaw(JCTree tree, Env<AttrContext> env) {
1344 if (lint.isEnabled(LintCategory.RAW) &&
1345 tree.type.hasTag(CLASS) &&
1346 !TreeInfo.isDiamond(tree) &&
1347 !withinAnonConstr(env) &&
1348 tree.type.isRaw()) {
1349 log.warning(LintCategory.RAW,
1350 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1351 }
1352 }
1354 boolean withinAnonConstr(Env<AttrContext> env) {
1355 return env.enclClass.name.isEmpty() &&
1356 env.enclMethod != null && env.enclMethod.name == names.init;
1357 }
1358 }
1360 /* *************************************************************************
1361 * Exception checking
1362 **************************************************************************/
1364 /* The following methods treat classes as sets that contain
1365 * the class itself and all their subclasses
1366 */
1368 /** Is given type a subtype of some of the types in given list?
1369 */
1370 boolean subset(Type t, List<Type> ts) {
1371 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1372 if (types.isSubtype(t, l.head)) return true;
1373 return false;
1374 }
1376 /** Is given type a subtype or supertype of
1377 * some of the types in given list?
1378 */
1379 boolean intersects(Type t, List<Type> ts) {
1380 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1381 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1382 return false;
1383 }
1385 /** Add type set to given type list, unless it is a subclass of some class
1386 * in the list.
1387 */
1388 List<Type> incl(Type t, List<Type> ts) {
1389 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1390 }
1392 /** Remove type set from type set list.
1393 */
1394 List<Type> excl(Type t, List<Type> ts) {
1395 if (ts.isEmpty()) {
1396 return ts;
1397 } else {
1398 List<Type> ts1 = excl(t, ts.tail);
1399 if (types.isSubtype(ts.head, t)) return ts1;
1400 else if (ts1 == ts.tail) return ts;
1401 else return ts1.prepend(ts.head);
1402 }
1403 }
1405 /** Form the union of two type set lists.
1406 */
1407 List<Type> union(List<Type> ts1, List<Type> ts2) {
1408 List<Type> ts = ts1;
1409 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1410 ts = incl(l.head, ts);
1411 return ts;
1412 }
1414 /** Form the difference of two type lists.
1415 */
1416 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1417 List<Type> ts = ts1;
1418 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1419 ts = excl(l.head, ts);
1420 return ts;
1421 }
1423 /** Form the intersection of two type lists.
1424 */
1425 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1426 List<Type> ts = List.nil();
1427 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1428 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1429 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1430 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1431 return ts;
1432 }
1434 /** Is exc an exception symbol that need not be declared?
1435 */
1436 boolean isUnchecked(ClassSymbol exc) {
1437 return
1438 exc.kind == ERR ||
1439 exc.isSubClass(syms.errorType.tsym, types) ||
1440 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1441 }
1443 /** Is exc an exception type that need not be declared?
1444 */
1445 boolean isUnchecked(Type exc) {
1446 return
1447 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1448 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1449 exc.hasTag(BOT);
1450 }
1452 /** Same, but handling completion failures.
1453 */
1454 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1455 try {
1456 return isUnchecked(exc);
1457 } catch (CompletionFailure ex) {
1458 completionError(pos, ex);
1459 return true;
1460 }
1461 }
1463 /** Is exc handled by given exception list?
1464 */
1465 boolean isHandled(Type exc, List<Type> handled) {
1466 return isUnchecked(exc) || subset(exc, handled);
1467 }
1469 /** Return all exceptions in thrown list that are not in handled list.
1470 * @param thrown The list of thrown exceptions.
1471 * @param handled The list of handled exceptions.
1472 */
1473 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1474 List<Type> unhandled = List.nil();
1475 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1476 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1477 return unhandled;
1478 }
1480 /* *************************************************************************
1481 * Overriding/Implementation checking
1482 **************************************************************************/
1484 /** The level of access protection given by a flag set,
1485 * where PRIVATE is highest and PUBLIC is lowest.
1486 */
1487 static int protection(long flags) {
1488 switch ((short)(flags & AccessFlags)) {
1489 case PRIVATE: return 3;
1490 case PROTECTED: return 1;
1491 default:
1492 case PUBLIC: return 0;
1493 case 0: return 2;
1494 }
1495 }
1497 /** A customized "cannot override" error message.
1498 * @param m The overriding method.
1499 * @param other The overridden method.
1500 * @return An internationalized string.
1501 */
1502 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1503 String key;
1504 if ((other.owner.flags() & INTERFACE) == 0)
1505 key = "cant.override";
1506 else if ((m.owner.flags() & INTERFACE) == 0)
1507 key = "cant.implement";
1508 else
1509 key = "clashes.with";
1510 return diags.fragment(key, m, m.location(), other, other.location());
1511 }
1513 /** A customized "override" warning message.
1514 * @param m The overriding method.
1515 * @param other The overridden method.
1516 * @return An internationalized string.
1517 */
1518 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1519 String key;
1520 if ((other.owner.flags() & INTERFACE) == 0)
1521 key = "unchecked.override";
1522 else if ((m.owner.flags() & INTERFACE) == 0)
1523 key = "unchecked.implement";
1524 else
1525 key = "unchecked.clash.with";
1526 return diags.fragment(key, m, m.location(), other, other.location());
1527 }
1529 /** A customized "override" warning message.
1530 * @param m The overriding method.
1531 * @param other The overridden method.
1532 * @return An internationalized string.
1533 */
1534 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1535 String key;
1536 if ((other.owner.flags() & INTERFACE) == 0)
1537 key = "varargs.override";
1538 else if ((m.owner.flags() & INTERFACE) == 0)
1539 key = "varargs.implement";
1540 else
1541 key = "varargs.clash.with";
1542 return diags.fragment(key, m, m.location(), other, other.location());
1543 }
1545 /** Check that this method conforms with overridden method 'other'.
1546 * where `origin' is the class where checking started.
1547 * Complications:
1548 * (1) Do not check overriding of synthetic methods
1549 * (reason: they might be final).
1550 * todo: check whether this is still necessary.
1551 * (2) Admit the case where an interface proxy throws fewer exceptions
1552 * than the method it implements. Augment the proxy methods with the
1553 * undeclared exceptions in this case.
1554 * (3) When generics are enabled, admit the case where an interface proxy
1555 * has a result type
1556 * extended by the result type of the method it implements.
1557 * Change the proxies result type to the smaller type in this case.
1558 *
1559 * @param tree The tree from which positions
1560 * are extracted for errors.
1561 * @param m The overriding method.
1562 * @param other The overridden method.
1563 * @param origin The class of which the overriding method
1564 * is a member.
1565 */
1566 void checkOverride(JCTree tree,
1567 MethodSymbol m,
1568 MethodSymbol other,
1569 ClassSymbol origin) {
1570 // Don't check overriding of synthetic methods or by bridge methods.
1571 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1572 return;
1573 }
1575 // Error if static method overrides instance method (JLS 8.4.6.2).
1576 if ((m.flags() & STATIC) != 0 &&
1577 (other.flags() & STATIC) == 0) {
1578 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1579 cannotOverride(m, other));
1580 return;
1581 }
1583 // Error if instance method overrides static or final
1584 // method (JLS 8.4.6.1).
1585 if ((other.flags() & FINAL) != 0 ||
1586 (m.flags() & STATIC) == 0 &&
1587 (other.flags() & STATIC) != 0) {
1588 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1589 cannotOverride(m, other),
1590 asFlagSet(other.flags() & (FINAL | STATIC)));
1591 return;
1592 }
1594 if ((m.owner.flags() & ANNOTATION) != 0) {
1595 // handled in validateAnnotationMethod
1596 return;
1597 }
1599 // Error if overriding method has weaker access (JLS 8.4.6.3).
1600 if ((origin.flags() & INTERFACE) == 0 &&
1601 protection(m.flags()) > protection(other.flags())) {
1602 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1603 cannotOverride(m, other),
1604 other.flags() == 0 ?
1605 Flag.PACKAGE :
1606 asFlagSet(other.flags() & AccessFlags));
1607 return;
1608 }
1610 Type mt = types.memberType(origin.type, m);
1611 Type ot = types.memberType(origin.type, other);
1612 // Error if overriding result type is different
1613 // (or, in the case of generics mode, not a subtype) of
1614 // overridden result type. We have to rename any type parameters
1615 // before comparing types.
1616 List<Type> mtvars = mt.getTypeArguments();
1617 List<Type> otvars = ot.getTypeArguments();
1618 Type mtres = mt.getReturnType();
1619 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1621 overrideWarner.clear();
1622 boolean resultTypesOK =
1623 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1624 if (!resultTypesOK) {
1625 if (!allowCovariantReturns &&
1626 m.owner != origin &&
1627 m.owner.isSubClass(other.owner, types)) {
1628 // allow limited interoperability with covariant returns
1629 } else {
1630 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1631 "override.incompatible.ret",
1632 cannotOverride(m, other),
1633 mtres, otres);
1634 return;
1635 }
1636 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1637 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1638 "override.unchecked.ret",
1639 uncheckedOverrides(m, other),
1640 mtres, otres);
1641 }
1643 // Error if overriding method throws an exception not reported
1644 // by overridden method.
1645 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1646 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1647 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1648 if (unhandledErased.nonEmpty()) {
1649 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1650 "override.meth.doesnt.throw",
1651 cannotOverride(m, other),
1652 unhandledUnerased.head);
1653 return;
1654 }
1655 else if (unhandledUnerased.nonEmpty()) {
1656 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1657 "override.unchecked.thrown",
1658 cannotOverride(m, other),
1659 unhandledUnerased.head);
1660 return;
1661 }
1663 // Optional warning if varargs don't agree
1664 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1665 && lint.isEnabled(LintCategory.OVERRIDES)) {
1666 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1667 ((m.flags() & Flags.VARARGS) != 0)
1668 ? "override.varargs.missing"
1669 : "override.varargs.extra",
1670 varargsOverrides(m, other));
1671 }
1673 // Warn if instance method overrides bridge method (compiler spec ??)
1674 if ((other.flags() & BRIDGE) != 0) {
1675 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1676 uncheckedOverrides(m, other));
1677 }
1679 // Warn if a deprecated method overridden by a non-deprecated one.
1680 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1681 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1682 }
1683 }
1684 // where
1685 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1686 // If the method, m, is defined in an interface, then ignore the issue if the method
1687 // is only inherited via a supertype and also implemented in the supertype,
1688 // because in that case, we will rediscover the issue when examining the method
1689 // in the supertype.
1690 // If the method, m, is not defined in an interface, then the only time we need to
1691 // address the issue is when the method is the supertype implemementation: any other
1692 // case, we will have dealt with when examining the supertype classes
1693 ClassSymbol mc = m.enclClass();
1694 Type st = types.supertype(origin.type);
1695 if (!st.hasTag(CLASS))
1696 return true;
1697 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1699 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1700 List<Type> intfs = types.interfaces(origin.type);
1701 return (intfs.contains(mc.type) ? false : (stimpl != null));
1702 }
1703 else
1704 return (stimpl != m);
1705 }
1708 // used to check if there were any unchecked conversions
1709 Warner overrideWarner = new Warner();
1711 /** Check that a class does not inherit two concrete methods
1712 * with the same signature.
1713 * @param pos Position to be used for error reporting.
1714 * @param site The class type to be checked.
1715 */
1716 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1717 Type sup = types.supertype(site);
1718 if (!sup.hasTag(CLASS)) return;
1720 for (Type t1 = sup;
1721 t1.tsym.type.isParameterized();
1722 t1 = types.supertype(t1)) {
1723 for (Scope.Entry e1 = t1.tsym.members().elems;
1724 e1 != null;
1725 e1 = e1.sibling) {
1726 Symbol s1 = e1.sym;
1727 if (s1.kind != MTH ||
1728 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1729 !s1.isInheritedIn(site.tsym, types) ||
1730 ((MethodSymbol)s1).implementation(site.tsym,
1731 types,
1732 true) != s1)
1733 continue;
1734 Type st1 = types.memberType(t1, s1);
1735 int s1ArgsLength = st1.getParameterTypes().length();
1736 if (st1 == s1.type) continue;
1738 for (Type t2 = sup;
1739 t2.hasTag(CLASS);
1740 t2 = types.supertype(t2)) {
1741 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1742 e2.scope != null;
1743 e2 = e2.next()) {
1744 Symbol s2 = e2.sym;
1745 if (s2 == s1 ||
1746 s2.kind != MTH ||
1747 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1748 s2.type.getParameterTypes().length() != s1ArgsLength ||
1749 !s2.isInheritedIn(site.tsym, types) ||
1750 ((MethodSymbol)s2).implementation(site.tsym,
1751 types,
1752 true) != s2)
1753 continue;
1754 Type st2 = types.memberType(t2, s2);
1755 if (types.overrideEquivalent(st1, st2))
1756 log.error(pos, "concrete.inheritance.conflict",
1757 s1, t1, s2, t2, sup);
1758 }
1759 }
1760 }
1761 }
1762 }
1764 /** Check that classes (or interfaces) do not each define an abstract
1765 * method with same name and arguments but incompatible return types.
1766 * @param pos Position to be used for error reporting.
1767 * @param t1 The first argument type.
1768 * @param t2 The second argument type.
1769 */
1770 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1771 Type t1,
1772 Type t2) {
1773 return checkCompatibleAbstracts(pos, t1, t2,
1774 types.makeCompoundType(t1, t2));
1775 }
1777 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1778 Type t1,
1779 Type t2,
1780 Type site) {
1781 return firstIncompatibility(pos, t1, t2, site) == null;
1782 }
1784 /** Return the first method which is defined with same args
1785 * but different return types in two given interfaces, or null if none
1786 * exists.
1787 * @param t1 The first type.
1788 * @param t2 The second type.
1789 * @param site The most derived type.
1790 * @returns symbol from t2 that conflicts with one in t1.
1791 */
1792 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1793 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1794 closure(t1, interfaces1);
1795 Map<TypeSymbol,Type> interfaces2;
1796 if (t1 == t2)
1797 interfaces2 = interfaces1;
1798 else
1799 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1801 for (Type t3 : interfaces1.values()) {
1802 for (Type t4 : interfaces2.values()) {
1803 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1804 if (s != null) return s;
1805 }
1806 }
1807 return null;
1808 }
1810 /** Compute all the supertypes of t, indexed by type symbol. */
1811 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1812 if (!t.hasTag(CLASS)) return;
1813 if (typeMap.put(t.tsym, t) == null) {
1814 closure(types.supertype(t), typeMap);
1815 for (Type i : types.interfaces(t))
1816 closure(i, typeMap);
1817 }
1818 }
1820 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1821 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1822 if (!t.hasTag(CLASS)) return;
1823 if (typesSkip.get(t.tsym) != null) return;
1824 if (typeMap.put(t.tsym, t) == null) {
1825 closure(types.supertype(t), typesSkip, typeMap);
1826 for (Type i : types.interfaces(t))
1827 closure(i, typesSkip, typeMap);
1828 }
1829 }
1831 /** Return the first method in t2 that conflicts with a method from t1. */
1832 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1833 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1834 Symbol s1 = e1.sym;
1835 Type st1 = null;
1836 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1837 (s1.flags() & SYNTHETIC) != 0) continue;
1838 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1839 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1840 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1841 Symbol s2 = e2.sym;
1842 if (s1 == s2) continue;
1843 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
1844 (s2.flags() & SYNTHETIC) != 0) continue;
1845 if (st1 == null) st1 = types.memberType(t1, s1);
1846 Type st2 = types.memberType(t2, s2);
1847 if (types.overrideEquivalent(st1, st2)) {
1848 List<Type> tvars1 = st1.getTypeArguments();
1849 List<Type> tvars2 = st2.getTypeArguments();
1850 Type rt1 = st1.getReturnType();
1851 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1852 boolean compat =
1853 types.isSameType(rt1, rt2) ||
1854 !rt1.isPrimitiveOrVoid() &&
1855 !rt2.isPrimitiveOrVoid() &&
1856 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
1857 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
1858 checkCommonOverriderIn(s1,s2,site);
1859 if (!compat) {
1860 log.error(pos, "types.incompatible.diff.ret",
1861 t1, t2, s2.name +
1862 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1863 return s2;
1864 }
1865 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
1866 !checkCommonOverriderIn(s1, s2, site)) {
1867 log.error(pos,
1868 "name.clash.same.erasure.no.override",
1869 s1, s1.location(),
1870 s2, s2.location());
1871 return s2;
1872 }
1873 }
1874 }
1875 return null;
1876 }
1877 //WHERE
1878 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1879 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1880 Type st1 = types.memberType(site, s1);
1881 Type st2 = types.memberType(site, s2);
1882 closure(site, supertypes);
1883 for (Type t : supertypes.values()) {
1884 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1885 Symbol s3 = e.sym;
1886 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1887 Type st3 = types.memberType(site,s3);
1888 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1889 if (s3.owner == site.tsym) {
1890 return true;
1891 }
1892 List<Type> tvars1 = st1.getTypeArguments();
1893 List<Type> tvars2 = st2.getTypeArguments();
1894 List<Type> tvars3 = st3.getTypeArguments();
1895 Type rt1 = st1.getReturnType();
1896 Type rt2 = st2.getReturnType();
1897 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1898 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1899 boolean compat =
1900 !rt13.isPrimitiveOrVoid() &&
1901 !rt23.isPrimitiveOrVoid() &&
1902 (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
1903 types.covariantReturnType(rt23, rt2, types.noWarnings));
1904 if (compat)
1905 return true;
1906 }
1907 }
1908 }
1909 return false;
1910 }
1912 /** Check that a given method conforms with any method it overrides.
1913 * @param tree The tree from which positions are extracted
1914 * for errors.
1915 * @param m The overriding method.
1916 */
1917 void checkOverride(JCTree tree, MethodSymbol m) {
1918 ClassSymbol origin = (ClassSymbol)m.owner;
1919 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1920 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1921 log.error(tree.pos(), "enum.no.finalize");
1922 return;
1923 }
1924 for (Type t = origin.type; t.hasTag(CLASS);
1925 t = types.supertype(t)) {
1926 if (t != origin.type) {
1927 checkOverride(tree, t, origin, m);
1928 }
1929 for (Type t2 : types.interfaces(t)) {
1930 checkOverride(tree, t2, origin, m);
1931 }
1932 }
1933 }
1935 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1936 TypeSymbol c = site.tsym;
1937 Scope.Entry e = c.members().lookup(m.name);
1938 while (e.scope != null) {
1939 if (m.overrides(e.sym, origin, types, false)) {
1940 if ((e.sym.flags() & ABSTRACT) == 0) {
1941 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1942 }
1943 }
1944 e = e.next();
1945 }
1946 }
1948 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1949 ClashFilter cf = new ClashFilter(origin.type);
1950 return (cf.accepts(s1) &&
1951 cf.accepts(s2) &&
1952 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
1953 }
1956 /** Check that all abstract members of given class have definitions.
1957 * @param pos Position to be used for error reporting.
1958 * @param c The class.
1959 */
1960 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1961 try {
1962 MethodSymbol undef = firstUndef(c, c);
1963 if (undef != null) {
1964 if ((c.flags() & ENUM) != 0 &&
1965 types.supertype(c.type).tsym == syms.enumSym &&
1966 (c.flags() & FINAL) == 0) {
1967 // add the ABSTRACT flag to an enum
1968 c.flags_field |= ABSTRACT;
1969 } else {
1970 MethodSymbol undef1 =
1971 new MethodSymbol(undef.flags(), undef.name,
1972 types.memberType(c.type, undef), undef.owner);
1973 log.error(pos, "does.not.override.abstract",
1974 c, undef1, undef1.location());
1975 }
1976 }
1977 } catch (CompletionFailure ex) {
1978 completionError(pos, ex);
1979 }
1980 }
1981 //where
1982 /** Return first abstract member of class `c' that is not defined
1983 * in `impl', null if there is none.
1984 */
1985 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1986 MethodSymbol undef = null;
1987 // Do not bother to search in classes that are not abstract,
1988 // since they cannot have abstract members.
1989 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1990 Scope s = c.members();
1991 for (Scope.Entry e = s.elems;
1992 undef == null && e != null;
1993 e = e.sibling) {
1994 if (e.sym.kind == MTH &&
1995 (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
1996 MethodSymbol absmeth = (MethodSymbol)e.sym;
1997 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1998 if (implmeth == null || implmeth == absmeth) {
1999 //look for default implementations
2000 if (allowDefaultMethods) {
2001 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
2002 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
2003 implmeth = prov;
2004 }
2005 }
2006 }
2007 if (implmeth == null || implmeth == absmeth) {
2008 undef = absmeth;
2009 }
2010 }
2011 }
2012 if (undef == null) {
2013 Type st = types.supertype(c.type);
2014 if (st.hasTag(CLASS))
2015 undef = firstUndef(impl, (ClassSymbol)st.tsym);
2016 }
2017 for (List<Type> l = types.interfaces(c.type);
2018 undef == null && l.nonEmpty();
2019 l = l.tail) {
2020 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
2021 }
2022 }
2023 return undef;
2024 }
2026 void checkNonCyclicDecl(JCClassDecl tree) {
2027 CycleChecker cc = new CycleChecker();
2028 cc.scan(tree);
2029 if (!cc.errorFound && !cc.partialCheck) {
2030 tree.sym.flags_field |= ACYCLIC;
2031 }
2032 }
2034 class CycleChecker extends TreeScanner {
2036 List<Symbol> seenClasses = List.nil();
2037 boolean errorFound = false;
2038 boolean partialCheck = false;
2040 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2041 if (sym != null && sym.kind == TYP) {
2042 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2043 if (classEnv != null) {
2044 DiagnosticSource prevSource = log.currentSource();
2045 try {
2046 log.useSource(classEnv.toplevel.sourcefile);
2047 scan(classEnv.tree);
2048 }
2049 finally {
2050 log.useSource(prevSource.getFile());
2051 }
2052 } else if (sym.kind == TYP) {
2053 checkClass(pos, sym, List.<JCTree>nil());
2054 }
2055 } else {
2056 //not completed yet
2057 partialCheck = true;
2058 }
2059 }
2061 @Override
2062 public void visitSelect(JCFieldAccess tree) {
2063 super.visitSelect(tree);
2064 checkSymbol(tree.pos(), tree.sym);
2065 }
2067 @Override
2068 public void visitIdent(JCIdent tree) {
2069 checkSymbol(tree.pos(), tree.sym);
2070 }
2072 @Override
2073 public void visitTypeApply(JCTypeApply tree) {
2074 scan(tree.clazz);
2075 }
2077 @Override
2078 public void visitTypeArray(JCArrayTypeTree tree) {
2079 scan(tree.elemtype);
2080 }
2082 @Override
2083 public void visitClassDef(JCClassDecl tree) {
2084 List<JCTree> supertypes = List.nil();
2085 if (tree.getExtendsClause() != null) {
2086 supertypes = supertypes.prepend(tree.getExtendsClause());
2087 }
2088 if (tree.getImplementsClause() != null) {
2089 for (JCTree intf : tree.getImplementsClause()) {
2090 supertypes = supertypes.prepend(intf);
2091 }
2092 }
2093 checkClass(tree.pos(), tree.sym, supertypes);
2094 }
2096 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2097 if ((c.flags_field & ACYCLIC) != 0)
2098 return;
2099 if (seenClasses.contains(c)) {
2100 errorFound = true;
2101 noteCyclic(pos, (ClassSymbol)c);
2102 } else if (!c.type.isErroneous()) {
2103 try {
2104 seenClasses = seenClasses.prepend(c);
2105 if (c.type.hasTag(CLASS)) {
2106 if (supertypes.nonEmpty()) {
2107 scan(supertypes);
2108 }
2109 else {
2110 ClassType ct = (ClassType)c.type;
2111 if (ct.supertype_field == null ||
2112 ct.interfaces_field == null) {
2113 //not completed yet
2114 partialCheck = true;
2115 return;
2116 }
2117 checkSymbol(pos, ct.supertype_field.tsym);
2118 for (Type intf : ct.interfaces_field) {
2119 checkSymbol(pos, intf.tsym);
2120 }
2121 }
2122 if (c.owner.kind == TYP) {
2123 checkSymbol(pos, c.owner);
2124 }
2125 }
2126 } finally {
2127 seenClasses = seenClasses.tail;
2128 }
2129 }
2130 }
2131 }
2133 /** Check for cyclic references. Issue an error if the
2134 * symbol of the type referred to has a LOCKED flag set.
2135 *
2136 * @param pos Position to be used for error reporting.
2137 * @param t The type referred to.
2138 */
2139 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2140 checkNonCyclicInternal(pos, t);
2141 }
2144 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2145 checkNonCyclic1(pos, t, List.<TypeVar>nil());
2146 }
2148 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2149 final TypeVar tv;
2150 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2151 return;
2152 if (seen.contains(t)) {
2153 tv = (TypeVar)t;
2154 tv.bound = types.createErrorType(t);
2155 log.error(pos, "cyclic.inheritance", t);
2156 } else if (t.hasTag(TYPEVAR)) {
2157 tv = (TypeVar)t;
2158 seen = seen.prepend(tv);
2159 for (Type b : types.getBounds(tv))
2160 checkNonCyclic1(pos, b, seen);
2161 }
2162 }
2164 /** Check for cyclic references. Issue an error if the
2165 * symbol of the type referred to has a LOCKED flag set.
2166 *
2167 * @param pos Position to be used for error reporting.
2168 * @param t The type referred to.
2169 * @returns True if the check completed on all attributed classes
2170 */
2171 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2172 boolean complete = true; // was the check complete?
2173 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2174 Symbol c = t.tsym;
2175 if ((c.flags_field & ACYCLIC) != 0) return true;
2177 if ((c.flags_field & LOCKED) != 0) {
2178 noteCyclic(pos, (ClassSymbol)c);
2179 } else if (!c.type.isErroneous()) {
2180 try {
2181 c.flags_field |= LOCKED;
2182 if (c.type.hasTag(CLASS)) {
2183 ClassType clazz = (ClassType)c.type;
2184 if (clazz.interfaces_field != null)
2185 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2186 complete &= checkNonCyclicInternal(pos, l.head);
2187 if (clazz.supertype_field != null) {
2188 Type st = clazz.supertype_field;
2189 if (st != null && st.hasTag(CLASS))
2190 complete &= checkNonCyclicInternal(pos, st);
2191 }
2192 if (c.owner.kind == TYP)
2193 complete &= checkNonCyclicInternal(pos, c.owner.type);
2194 }
2195 } finally {
2196 c.flags_field &= ~LOCKED;
2197 }
2198 }
2199 if (complete)
2200 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
2201 if (complete) c.flags_field |= ACYCLIC;
2202 return complete;
2203 }
2205 /** Note that we found an inheritance cycle. */
2206 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2207 log.error(pos, "cyclic.inheritance", c);
2208 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2209 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2210 Type st = types.supertype(c.type);
2211 if (st.hasTag(CLASS))
2212 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2213 c.type = types.createErrorType(c, c.type);
2214 c.flags_field |= ACYCLIC;
2215 }
2217 /**
2218 * Check that functional interface methods would make sense when seen
2219 * from the perspective of the implementing class
2220 */
2221 void checkFunctionalInterface(JCTree tree, Type funcInterface) {
2222 ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
2223 ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
2224 c.interfaces_field = List.of(funcInterface);
2225 c.supertype_field = syms.objectType;
2226 c.tsym = csym;
2227 csym.members_field = new Scope(csym);
2228 csym.completer = null;
2229 checkImplementations(tree, csym, csym);
2230 }
2232 /** Check that all methods which implement some
2233 * method conform to the method they implement.
2234 * @param tree The class definition whose members are checked.
2235 */
2236 void checkImplementations(JCClassDecl tree) {
2237 checkImplementations(tree, tree.sym, tree.sym);
2238 }
2239 //where
2240 /** Check that all methods which implement some
2241 * method in `ic' conform to the method they implement.
2242 */
2243 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2244 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2245 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2246 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2247 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2248 if (e.sym.kind == MTH &&
2249 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2250 MethodSymbol absmeth = (MethodSymbol)e.sym;
2251 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2252 if (implmeth != null && implmeth != absmeth &&
2253 (implmeth.owner.flags() & INTERFACE) ==
2254 (origin.flags() & INTERFACE)) {
2255 // don't check if implmeth is in a class, yet
2256 // origin is an interface. This case arises only
2257 // if implmeth is declared in Object. The reason is
2258 // that interfaces really don't inherit from
2259 // Object it's just that the compiler represents
2260 // things that way.
2261 checkOverride(tree, implmeth, absmeth, origin);
2262 }
2263 }
2264 }
2265 }
2266 }
2267 }
2269 /** Check that all abstract methods implemented by a class are
2270 * mutually compatible.
2271 * @param pos Position to be used for error reporting.
2272 * @param c The class whose interfaces are checked.
2273 */
2274 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2275 List<Type> supertypes = types.interfaces(c);
2276 Type supertype = types.supertype(c);
2277 if (supertype.hasTag(CLASS) &&
2278 (supertype.tsym.flags() & ABSTRACT) != 0)
2279 supertypes = supertypes.prepend(supertype);
2280 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2281 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2282 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2283 return;
2284 for (List<Type> m = supertypes; m != l; m = m.tail)
2285 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2286 return;
2287 }
2288 checkCompatibleConcretes(pos, c);
2289 }
2291 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2292 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2293 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2294 // VM allows methods and variables with differing types
2295 if (sym.kind == e.sym.kind &&
2296 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2297 sym != e.sym &&
2298 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2299 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2300 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2301 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2302 return;
2303 }
2304 }
2305 }
2306 }
2308 /** Check that all non-override equivalent methods accessible from 'site'
2309 * are mutually compatible (JLS 8.4.8/9.4.1).
2310 *
2311 * @param pos Position to be used for error reporting.
2312 * @param site The class whose methods are checked.
2313 * @param sym The method symbol to be checked.
2314 */
2315 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2316 ClashFilter cf = new ClashFilter(site);
2317 //for each method m1 that is overridden (directly or indirectly)
2318 //by method 'sym' in 'site'...
2319 for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2320 if (!sym.overrides(m1, site.tsym, types, false)) continue;
2321 //...check each method m2 that is a member of 'site'
2322 for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
2323 if (m2 == m1) continue;
2324 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2325 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2326 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2327 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2328 sym.flags_field |= CLASH;
2329 String key = m1 == sym ?
2330 "name.clash.same.erasure.no.override" :
2331 "name.clash.same.erasure.no.override.1";
2332 log.error(pos,
2333 key,
2334 sym, sym.location(),
2335 m2, m2.location(),
2336 m1, m1.location());
2337 return;
2338 }
2339 }
2340 }
2341 }
2345 /** Check that all static methods accessible from 'site' are
2346 * mutually compatible (JLS 8.4.8).
2347 *
2348 * @param pos Position to be used for error reporting.
2349 * @param site The class whose methods are checked.
2350 * @param sym The method symbol to be checked.
2351 */
2352 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2353 ClashFilter cf = new ClashFilter(site);
2354 //for each method m1 that is a member of 'site'...
2355 for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
2356 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2357 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2358 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
2359 types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2360 log.error(pos,
2361 "name.clash.same.erasure.no.hide",
2362 sym, sym.location(),
2363 s, s.location());
2364 return;
2365 }
2366 }
2367 }
2369 //where
2370 private class ClashFilter implements Filter<Symbol> {
2372 Type site;
2374 ClashFilter(Type site) {
2375 this.site = site;
2376 }
2378 boolean shouldSkip(Symbol s) {
2379 return (s.flags() & CLASH) != 0 &&
2380 s.owner == site.tsym;
2381 }
2383 public boolean accepts(Symbol s) {
2384 return s.kind == MTH &&
2385 (s.flags() & SYNTHETIC) == 0 &&
2386 !shouldSkip(s) &&
2387 s.isInheritedIn(site.tsym, types) &&
2388 !s.isConstructor();
2389 }
2390 }
2392 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2393 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2394 for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
2395 Assert.check(m.kind == MTH);
2396 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2397 if (prov.size() > 1) {
2398 ListBuffer<Symbol> abstracts = ListBuffer.lb();
2399 ListBuffer<Symbol> defaults = ListBuffer.lb();
2400 for (MethodSymbol provSym : prov) {
2401 if ((provSym.flags() & DEFAULT) != 0) {
2402 defaults = defaults.append(provSym);
2403 } else if ((provSym.flags() & ABSTRACT) != 0) {
2404 abstracts = abstracts.append(provSym);
2405 }
2406 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2407 //strong semantics - issue an error if two sibling interfaces
2408 //have two override-equivalent defaults - or if one is abstract
2409 //and the other is default
2410 String errKey;
2411 Symbol s1 = defaults.first();
2412 Symbol s2;
2413 if (defaults.size() > 1) {
2414 errKey = "types.incompatible.unrelated.defaults";
2415 s2 = defaults.toList().tail.head;
2416 } else {
2417 errKey = "types.incompatible.abstract.default";
2418 s2 = abstracts.first();
2419 }
2420 log.error(pos, errKey,
2421 Kinds.kindName(site.tsym), site,
2422 m.name, types.memberType(site, m).getParameterTypes(),
2423 s1.location(), s2.location());
2424 break;
2425 }
2426 }
2427 }
2428 }
2429 }
2431 //where
2432 private class DefaultMethodClashFilter implements Filter<Symbol> {
2434 Type site;
2436 DefaultMethodClashFilter(Type site) {
2437 this.site = site;
2438 }
2440 public boolean accepts(Symbol s) {
2441 return s.kind == MTH &&
2442 (s.flags() & DEFAULT) != 0 &&
2443 s.isInheritedIn(site.tsym, types) &&
2444 !s.isConstructor();
2445 }
2446 }
2448 /** Report a conflict between a user symbol and a synthetic symbol.
2449 */
2450 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2451 if (!sym.type.isErroneous()) {
2452 if (warnOnSyntheticConflicts) {
2453 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2454 }
2455 else {
2456 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2457 }
2458 }
2459 }
2461 /** Check that class c does not implement directly or indirectly
2462 * the same parameterized interface with two different argument lists.
2463 * @param pos Position to be used for error reporting.
2464 * @param type The type whose interfaces are checked.
2465 */
2466 void checkClassBounds(DiagnosticPosition pos, Type type) {
2467 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2468 }
2469 //where
2470 /** Enter all interfaces of type `type' into the hash table `seensofar'
2471 * with their class symbol as key and their type as value. Make
2472 * sure no class is entered with two different types.
2473 */
2474 void checkClassBounds(DiagnosticPosition pos,
2475 Map<TypeSymbol,Type> seensofar,
2476 Type type) {
2477 if (type.isErroneous()) return;
2478 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2479 Type it = l.head;
2480 Type oldit = seensofar.put(it.tsym, it);
2481 if (oldit != null) {
2482 List<Type> oldparams = oldit.allparams();
2483 List<Type> newparams = it.allparams();
2484 if (!types.containsTypeEquivalent(oldparams, newparams))
2485 log.error(pos, "cant.inherit.diff.arg",
2486 it.tsym, Type.toString(oldparams),
2487 Type.toString(newparams));
2488 }
2489 checkClassBounds(pos, seensofar, it);
2490 }
2491 Type st = types.supertype(type);
2492 if (st != null) checkClassBounds(pos, seensofar, st);
2493 }
2495 /** Enter interface into into set.
2496 * If it existed already, issue a "repeated interface" error.
2497 */
2498 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2499 if (its.contains(it))
2500 log.error(pos, "repeated.interface");
2501 else {
2502 its.add(it);
2503 }
2504 }
2506 /* *************************************************************************
2507 * Check annotations
2508 **************************************************************************/
2510 /**
2511 * Recursively validate annotations values
2512 */
2513 void validateAnnotationTree(JCTree tree) {
2514 class AnnotationValidator extends TreeScanner {
2515 @Override
2516 public void visitAnnotation(JCAnnotation tree) {
2517 if (!tree.type.isErroneous()) {
2518 super.visitAnnotation(tree);
2519 validateAnnotation(tree);
2520 }
2521 }
2522 }
2523 tree.accept(new AnnotationValidator());
2524 }
2526 /**
2527 * {@literal
2528 * Annotation types are restricted to primitives, String, an
2529 * enum, an annotation, Class, Class<?>, Class<? extends
2530 * Anything>, arrays of the preceding.
2531 * }
2532 */
2533 void validateAnnotationType(JCTree restype) {
2534 // restype may be null if an error occurred, so don't bother validating it
2535 if (restype != null) {
2536 validateAnnotationType(restype.pos(), restype.type);
2537 }
2538 }
2540 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2541 if (type.isPrimitive()) return;
2542 if (types.isSameType(type, syms.stringType)) return;
2543 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2544 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2545 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2546 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2547 validateAnnotationType(pos, types.elemtype(type));
2548 return;
2549 }
2550 log.error(pos, "invalid.annotation.member.type");
2551 }
2553 /**
2554 * "It is also a compile-time error if any method declared in an
2555 * annotation type has a signature that is override-equivalent to
2556 * that of any public or protected method declared in class Object
2557 * or in the interface annotation.Annotation."
2558 *
2559 * @jls 9.6 Annotation Types
2560 */
2561 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2562 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2563 Scope s = sup.tsym.members();
2564 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2565 if (e.sym.kind == MTH &&
2566 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2567 types.overrideEquivalent(m.type, e.sym.type))
2568 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2569 }
2570 }
2571 }
2573 /** Check the annotations of a symbol.
2574 */
2575 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2576 for (JCAnnotation a : annotations)
2577 validateAnnotation(a, s);
2578 }
2580 /** Check an annotation of a symbol.
2581 */
2582 private void validateAnnotation(JCAnnotation a, Symbol s) {
2583 validateAnnotationTree(a);
2585 if (!annotationApplicable(a, s))
2586 log.error(a.pos(), "annotation.type.not.applicable");
2588 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2589 if (!isOverrider(s))
2590 log.error(a.pos(), "method.does.not.override.superclass");
2591 }
2592 }
2594 /**
2595 * Validate the proposed container 'containedBy' on the
2596 * annotation type symbol 's'. Report errors at position
2597 * 'pos'.
2598 *
2599 * @param s The (annotation)type declaration annotated with a @ContainedBy
2600 * @param containedBy the @ContainedBy on 's'
2601 * @param pos where to report errors
2602 */
2603 public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
2604 Assert.check(types.isSameType(containedBy.type, syms.containedByType));
2606 Type t = null;
2607 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2608 if (!l.isEmpty()) {
2609 Assert.check(l.head.fst.name == names.value);
2610 t = ((Attribute.Class)l.head.snd).getValue();
2611 }
2613 if (t == null) {
2614 log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
2615 return;
2616 }
2618 validateHasContainerFor(t.tsym, s, pos);
2619 validateRetention(t.tsym, s, pos);
2620 validateDocumented(t.tsym, s, pos);
2621 validateInherited(t.tsym, s, pos);
2622 validateTarget(t.tsym, s, pos);
2623 validateDefault(t.tsym, s, pos);
2624 }
2626 /**
2627 * Validate the proposed container 'containerFor' on the
2628 * annotation type symbol 's'. Report errors at position
2629 * 'pos'.
2630 *
2631 * @param s The (annotation)type declaration annotated with a @ContainerFor
2632 * @param containerFor the @ContainedFor on 's'
2633 * @param pos where to report errors
2634 */
2635 public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
2636 Assert.check(types.isSameType(containerFor.type, syms.containerForType));
2638 Type t = null;
2639 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2640 if (!l.isEmpty()) {
2641 Assert.check(l.head.fst.name == names.value);
2642 t = ((Attribute.Class)l.head.snd).getValue();
2643 }
2645 if (t == null) {
2646 log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
2647 return;
2648 }
2650 validateHasContainedBy(t.tsym, s, pos);
2651 }
2653 private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2654 Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
2656 if (containedBy == null) {
2657 log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
2658 return;
2659 }
2661 Type t = null;
2662 List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
2663 if (!l.isEmpty()) {
2664 Assert.check(l.head.fst.name == names.value);
2665 t = ((Attribute.Class)l.head.snd).getValue();
2666 }
2668 if (t == null) {
2669 log.error(pos, "invalid.container.wrong.containedby", container, contained);
2670 return;
2671 }
2673 if (!types.isSameType(t, contained.type))
2674 log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
2675 }
2677 private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2678 Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
2680 if (containerFor == null) {
2681 log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
2682 return;
2683 }
2685 Type t = null;
2686 List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
2687 if (!l.isEmpty()) {
2688 Assert.check(l.head.fst.name == names.value);
2689 t = ((Attribute.Class)l.head.snd).getValue();
2690 }
2692 if (t == null) {
2693 log.error(pos, "invalid.container.wrong.containerfor", container, contained);
2694 return;
2695 }
2697 if (!types.isSameType(t, contained.type))
2698 log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
2699 }
2701 private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
2702 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2703 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2705 boolean error = false;
2706 switch (containedRetention) {
2707 case RUNTIME:
2708 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2709 error = true;
2710 }
2711 break;
2712 case CLASS:
2713 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2714 error = true;
2715 }
2716 }
2717 if (error ) {
2718 log.error(pos, "invalid.containedby.annotation.retention",
2719 container, containerRetention,
2720 contained, containedRetention);
2721 }
2722 }
2724 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
2725 if (contained.attribute(syms.documentedType.tsym) != null) {
2726 if (container.attribute(syms.documentedType.tsym) == null) {
2727 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
2728 }
2729 }
2730 }
2732 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
2733 if (contained.attribute(syms.inheritedType.tsym) != null) {
2734 if (container.attribute(syms.inheritedType.tsym) == null) {
2735 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
2736 }
2737 }
2738 }
2740 private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
2741 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
2743 // If contained has no Target, we are done
2744 if (containedTarget == null) {
2745 return;
2746 }
2748 // If contained has Target m1, container must have a Target
2749 // annotation, m2, and m2 must be a subset of m1. (This is
2750 // trivially true if contained has no target as per above).
2752 // contained has target, but container has not, error
2753 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
2754 if (containerTarget == null) {
2755 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2756 return;
2757 }
2759 Set<Name> containerTargets = new HashSet<Name>();
2760 for (Attribute app : containerTarget.values) {
2761 if (!(app instanceof Attribute.Enum)) {
2762 continue; // recovery
2763 }
2764 Attribute.Enum e = (Attribute.Enum)app;
2765 containerTargets.add(e.value.name);
2766 }
2768 Set<Name> containedTargets = new HashSet<Name>();
2769 for (Attribute app : containedTarget.values) {
2770 if (!(app instanceof Attribute.Enum)) {
2771 continue; // recovery
2772 }
2773 Attribute.Enum e = (Attribute.Enum)app;
2774 containedTargets.add(e.value.name);
2775 }
2777 if (!isTargetSubset(containedTargets, containerTargets)) {
2778 log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
2779 }
2780 }
2782 /** Checks that t is a subset of s, with respect to ElementType
2783 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
2784 */
2785 private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
2786 // Check that all elements in t are present in s
2787 for (Name n2 : t) {
2788 boolean currentElementOk = false;
2789 for (Name n1 : s) {
2790 if (n1 == n2) {
2791 currentElementOk = true;
2792 break;
2793 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
2794 currentElementOk = true;
2795 break;
2796 }
2797 }
2798 if (!currentElementOk)
2799 return false;
2800 }
2801 return true;
2802 }
2804 private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
2805 // validate that all other elements of containing type has defaults
2806 Scope scope = container.members();
2807 for(Symbol elm : scope.getElements()) {
2808 if (elm.name != names.value &&
2809 elm.kind == Kinds.MTH &&
2810 ((MethodSymbol)elm).defaultValue == null) {
2811 log.error(pos,
2812 "invalid.containedby.annotation.elem.nondefault",
2813 container,
2814 elm);
2815 }
2816 }
2817 }
2819 /** Is s a method symbol that overrides a method in a superclass? */
2820 boolean isOverrider(Symbol s) {
2821 if (s.kind != MTH || s.isStatic())
2822 return false;
2823 MethodSymbol m = (MethodSymbol)s;
2824 TypeSymbol owner = (TypeSymbol)m.owner;
2825 for (Type sup : types.closure(owner.type)) {
2826 if (sup == owner.type)
2827 continue; // skip "this"
2828 Scope scope = sup.tsym.members();
2829 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2830 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2831 return true;
2832 }
2833 }
2834 return false;
2835 }
2837 /** Is the annotation applicable to the symbol? */
2838 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2839 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
2840 if (arr == null) {
2841 return true;
2842 }
2843 for (Attribute app : arr.values) {
2844 if (!(app instanceof Attribute.Enum)) return true; // recovery
2845 Attribute.Enum e = (Attribute.Enum) app;
2846 if (e.value.name == names.TYPE)
2847 { if (s.kind == TYP) return true; }
2848 else if (e.value.name == names.FIELD)
2849 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2850 else if (e.value.name == names.METHOD)
2851 { if (s.kind == MTH && !s.isConstructor()) return true; }
2852 else if (e.value.name == names.PARAMETER)
2853 { if (s.kind == VAR &&
2854 s.owner.kind == MTH &&
2855 (s.flags() & PARAMETER) != 0)
2856 return true;
2857 }
2858 else if (e.value.name == names.CONSTRUCTOR)
2859 { if (s.kind == MTH && s.isConstructor()) return true; }
2860 else if (e.value.name == names.LOCAL_VARIABLE)
2861 { if (s.kind == VAR && s.owner.kind == MTH &&
2862 (s.flags() & PARAMETER) == 0)
2863 return true;
2864 }
2865 else if (e.value.name == names.ANNOTATION_TYPE)
2866 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2867 return true;
2868 }
2869 else if (e.value.name == names.PACKAGE)
2870 { if (s.kind == PCK) return true; }
2871 else if (e.value.name == names.TYPE_USE)
2872 { if (s.kind == TYP ||
2873 s.kind == VAR ||
2874 (s.kind == MTH && !s.isConstructor() &&
2875 !s.type.getReturnType().hasTag(VOID)))
2876 return true;
2877 }
2878 else
2879 return true; // recovery
2880 }
2881 return false;
2882 }
2885 Attribute.Array getAttributeTargetAttribute(Symbol s) {
2886 Attribute.Compound atTarget =
2887 s.attribute(syms.annotationTargetType.tsym);
2888 if (atTarget == null) return null; // ok, is applicable
2889 Attribute atValue = atTarget.member(names.value);
2890 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
2891 return (Attribute.Array) atValue;
2892 }
2894 /** Check an annotation value.
2895 *
2896 * @param a The annotation tree to check
2897 * @return true if this annotation tree is valid, otherwise false
2898 */
2899 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
2900 boolean res = false;
2901 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
2902 try {
2903 res = validateAnnotation(a);
2904 } finally {
2905 log.popDiagnosticHandler(diagHandler);
2906 }
2907 return res;
2908 }
2910 private boolean validateAnnotation(JCAnnotation a) {
2911 boolean isValid = true;
2912 // collect an inventory of the annotation elements
2913 Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
2914 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2915 e != null;
2916 e = e.sibling)
2917 if (e.sym.kind == MTH)
2918 members.add((MethodSymbol) e.sym);
2920 // remove the ones that are assigned values
2921 for (JCTree arg : a.args) {
2922 if (!arg.hasTag(ASSIGN)) continue; // recovery
2923 JCAssign assign = (JCAssign) arg;
2924 Symbol m = TreeInfo.symbol(assign.lhs);
2925 if (m == null || m.type.isErroneous()) continue;
2926 if (!members.remove(m)) {
2927 isValid = false;
2928 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2929 m.name, a.type);
2930 }
2931 }
2933 // all the remaining ones better have default values
2934 List<Name> missingDefaults = List.nil();
2935 for (MethodSymbol m : members) {
2936 if (m.defaultValue == null && !m.type.isErroneous()) {
2937 missingDefaults = missingDefaults.append(m.name);
2938 }
2939 }
2940 missingDefaults = missingDefaults.reverse();
2941 if (missingDefaults.nonEmpty()) {
2942 isValid = false;
2943 String key = (missingDefaults.size() > 1)
2944 ? "annotation.missing.default.value.1"
2945 : "annotation.missing.default.value";
2946 log.error(a.pos(), key, a.type, missingDefaults);
2947 }
2949 // special case: java.lang.annotation.Target must not have
2950 // repeated values in its value member
2951 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2952 a.args.tail == null)
2953 return isValid;
2955 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
2956 JCAssign assign = (JCAssign) a.args.head;
2957 Symbol m = TreeInfo.symbol(assign.lhs);
2958 if (m.name != names.value) return false;
2959 JCTree rhs = assign.rhs;
2960 if (!rhs.hasTag(NEWARRAY)) return false;
2961 JCNewArray na = (JCNewArray) rhs;
2962 Set<Symbol> targets = new HashSet<Symbol>();
2963 for (JCTree elem : na.elems) {
2964 if (!targets.add(TreeInfo.symbol(elem))) {
2965 isValid = false;
2966 log.error(elem.pos(), "repeated.annotation.target");
2967 }
2968 }
2969 return isValid;
2970 }
2972 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2973 if (allowAnnotations &&
2974 lint.isEnabled(LintCategory.DEP_ANN) &&
2975 (s.flags() & DEPRECATED) != 0 &&
2976 !syms.deprecatedType.isErroneous() &&
2977 s.attribute(syms.deprecatedType.tsym) == null) {
2978 log.warning(LintCategory.DEP_ANN,
2979 pos, "missing.deprecated.annotation");
2980 }
2981 }
2983 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
2984 if ((s.flags() & DEPRECATED) != 0 &&
2985 (other.flags() & DEPRECATED) == 0 &&
2986 s.outermostClass() != other.outermostClass()) {
2987 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2988 @Override
2989 public void report() {
2990 warnDeprecated(pos, s);
2991 }
2992 });
2993 }
2994 }
2996 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
2997 if ((s.flags() & PROPRIETARY) != 0) {
2998 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
2999 public void report() {
3000 if (enableSunApiLintControl)
3001 warnSunApi(pos, "sun.proprietary", s);
3002 else
3003 log.mandatoryWarning(pos, "sun.proprietary", s);
3004 }
3005 });
3006 }
3007 }
3009 /* *************************************************************************
3010 * Check for recursive annotation elements.
3011 **************************************************************************/
3013 /** Check for cycles in the graph of annotation elements.
3014 */
3015 void checkNonCyclicElements(JCClassDecl tree) {
3016 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3017 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3018 try {
3019 tree.sym.flags_field |= LOCKED;
3020 for (JCTree def : tree.defs) {
3021 if (!def.hasTag(METHODDEF)) continue;
3022 JCMethodDecl meth = (JCMethodDecl)def;
3023 checkAnnotationResType(meth.pos(), meth.restype.type);
3024 }
3025 } finally {
3026 tree.sym.flags_field &= ~LOCKED;
3027 tree.sym.flags_field |= ACYCLIC_ANN;
3028 }
3029 }
3031 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3032 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3033 return;
3034 if ((tsym.flags_field & LOCKED) != 0) {
3035 log.error(pos, "cyclic.annotation.element");
3036 return;
3037 }
3038 try {
3039 tsym.flags_field |= LOCKED;
3040 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
3041 Symbol s = e.sym;
3042 if (s.kind != Kinds.MTH)
3043 continue;
3044 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3045 }
3046 } finally {
3047 tsym.flags_field &= ~LOCKED;
3048 tsym.flags_field |= ACYCLIC_ANN;
3049 }
3050 }
3052 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3053 switch (type.getTag()) {
3054 case CLASS:
3055 if ((type.tsym.flags() & ANNOTATION) != 0)
3056 checkNonCyclicElementsInternal(pos, type.tsym);
3057 break;
3058 case ARRAY:
3059 checkAnnotationResType(pos, types.elemtype(type));
3060 break;
3061 default:
3062 break; // int etc
3063 }
3064 }
3066 /* *************************************************************************
3067 * Check for cycles in the constructor call graph.
3068 **************************************************************************/
3070 /** Check for cycles in the graph of constructors calling other
3071 * constructors.
3072 */
3073 void checkCyclicConstructors(JCClassDecl tree) {
3074 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
3076 // enter each constructor this-call into the map
3077 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3078 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3079 if (app == null) continue;
3080 JCMethodDecl meth = (JCMethodDecl) l.head;
3081 if (TreeInfo.name(app.meth) == names._this) {
3082 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3083 } else {
3084 meth.sym.flags_field |= ACYCLIC;
3085 }
3086 }
3088 // Check for cycles in the map
3089 Symbol[] ctors = new Symbol[0];
3090 ctors = callMap.keySet().toArray(ctors);
3091 for (Symbol caller : ctors) {
3092 checkCyclicConstructor(tree, caller, callMap);
3093 }
3094 }
3096 /** Look in the map to see if the given constructor is part of a
3097 * call cycle.
3098 */
3099 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3100 Map<Symbol,Symbol> callMap) {
3101 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3102 if ((ctor.flags_field & LOCKED) != 0) {
3103 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3104 "recursive.ctor.invocation");
3105 } else {
3106 ctor.flags_field |= LOCKED;
3107 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3108 ctor.flags_field &= ~LOCKED;
3109 }
3110 ctor.flags_field |= ACYCLIC;
3111 }
3112 }
3114 /* *************************************************************************
3115 * Miscellaneous
3116 **************************************************************************/
3118 /**
3119 * Return the opcode of the operator but emit an error if it is an
3120 * error.
3121 * @param pos position for error reporting.
3122 * @param operator an operator
3123 * @param tag a tree tag
3124 * @param left type of left hand side
3125 * @param right type of right hand side
3126 */
3127 int checkOperator(DiagnosticPosition pos,
3128 OperatorSymbol operator,
3129 JCTree.Tag tag,
3130 Type left,
3131 Type right) {
3132 if (operator.opcode == ByteCodes.error) {
3133 log.error(pos,
3134 "operator.cant.be.applied.1",
3135 treeinfo.operatorName(tag),
3136 left, right);
3137 }
3138 return operator.opcode;
3139 }
3142 /**
3143 * Check for division by integer constant zero
3144 * @param pos Position for error reporting.
3145 * @param operator The operator for the expression
3146 * @param operand The right hand operand for the expression
3147 */
3148 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
3149 if (operand.constValue() != null
3150 && lint.isEnabled(LintCategory.DIVZERO)
3151 && (operand.getTag().isSubRangeOf(LONG))
3152 && ((Number) (operand.constValue())).longValue() == 0) {
3153 int opc = ((OperatorSymbol)operator).opcode;
3154 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3155 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3156 log.warning(LintCategory.DIVZERO, pos, "div.zero");
3157 }
3158 }
3159 }
3161 /**
3162 * Check for empty statements after if
3163 */
3164 void checkEmptyIf(JCIf tree) {
3165 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3166 lint.isEnabled(LintCategory.EMPTY))
3167 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3168 }
3170 /** Check that symbol is unique in given scope.
3171 * @param pos Position for error reporting.
3172 * @param sym The symbol.
3173 * @param s The scope.
3174 */
3175 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3176 if (sym.type.isErroneous())
3177 return true;
3178 if (sym.owner.name == names.any) return false;
3179 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
3180 if (sym != e.sym &&
3181 (e.sym.flags() & CLASH) == 0 &&
3182 sym.kind == e.sym.kind &&
3183 sym.name != names.error &&
3184 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
3185 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
3186 varargsDuplicateError(pos, sym, e.sym);
3187 return true;
3188 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
3189 duplicateErasureError(pos, sym, e.sym);
3190 sym.flags_field |= CLASH;
3191 return true;
3192 } else {
3193 duplicateError(pos, e.sym);
3194 return false;
3195 }
3196 }
3197 }
3198 return true;
3199 }
3201 /** Report duplicate declaration error.
3202 */
3203 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3204 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3205 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3206 }
3207 }
3209 /** Check that single-type import is not already imported or top-level defined,
3210 * but make an exception for two single-type imports which denote the same type.
3211 * @param pos Position for error reporting.
3212 * @param sym The symbol.
3213 * @param s The scope
3214 */
3215 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3216 return checkUniqueImport(pos, sym, s, false);
3217 }
3219 /** Check that static single-type import is not already imported or top-level defined,
3220 * but make an exception for two single-type imports which denote the same type.
3221 * @param pos Position for error reporting.
3222 * @param sym The symbol.
3223 * @param s The scope
3224 */
3225 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
3226 return checkUniqueImport(pos, sym, s, true);
3227 }
3229 /** Check that single-type import is not already imported or top-level defined,
3230 * but make an exception for two single-type imports which denote the same type.
3231 * @param pos Position for error reporting.
3232 * @param sym The symbol.
3233 * @param s The scope.
3234 * @param staticImport Whether or not this was a static import
3235 */
3236 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
3237 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
3238 // is encountered class entered via a class declaration?
3239 boolean isClassDecl = e.scope == s;
3240 if ((isClassDecl || sym != e.sym) &&
3241 sym.kind == e.sym.kind &&
3242 sym.name != names.error) {
3243 if (!e.sym.type.isErroneous()) {
3244 String what = e.sym.toString();
3245 if (!isClassDecl) {
3246 if (staticImport)
3247 log.error(pos, "already.defined.static.single.import", what);
3248 else
3249 log.error(pos, "already.defined.single.import", what);
3250 }
3251 else if (sym != e.sym)
3252 log.error(pos, "already.defined.this.unit", what);
3253 }
3254 return false;
3255 }
3256 }
3257 return true;
3258 }
3260 /** Check that a qualified name is in canonical form (for import decls).
3261 */
3262 public void checkCanonical(JCTree tree) {
3263 if (!isCanonical(tree))
3264 log.error(tree.pos(), "import.requires.canonical",
3265 TreeInfo.symbol(tree));
3266 }
3267 // where
3268 private boolean isCanonical(JCTree tree) {
3269 while (tree.hasTag(SELECT)) {
3270 JCFieldAccess s = (JCFieldAccess) tree;
3271 if (s.sym.owner != TreeInfo.symbol(s.selected))
3272 return false;
3273 tree = s.selected;
3274 }
3275 return true;
3276 }
3278 /** Check that an auxiliary class is not accessed from any other file than its own.
3279 */
3280 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3281 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3282 (c.flags() & AUXILIARY) != 0 &&
3283 rs.isAccessible(env, c) &&
3284 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3285 {
3286 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3287 c, c.sourcefile);
3288 }
3289 }
3291 private class ConversionWarner extends Warner {
3292 final String uncheckedKey;
3293 final Type found;
3294 final Type expected;
3295 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3296 super(pos);
3297 this.uncheckedKey = uncheckedKey;
3298 this.found = found;
3299 this.expected = expected;
3300 }
3302 @Override
3303 public void warn(LintCategory lint) {
3304 boolean warned = this.warned;
3305 super.warn(lint);
3306 if (warned) return; // suppress redundant diagnostics
3307 switch (lint) {
3308 case UNCHECKED:
3309 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3310 break;
3311 case VARARGS:
3312 if (method != null &&
3313 method.attribute(syms.trustMeType.tsym) != null &&
3314 isTrustMeAllowedOnMethod(method) &&
3315 !types.isReifiable(method.type.getParameterTypes().last())) {
3316 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3317 }
3318 break;
3319 default:
3320 throw new AssertionError("Unexpected lint: " + lint);
3321 }
3322 }
3323 }
3325 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3326 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3327 }
3329 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3330 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3331 }
3332 }