Fri, 28 Jan 2011 12:03:49 +0000
6313164: javac generates code that fails byte code verification for the varargs feature
Summary: method applicability check should fail if formal varargs element type is not accessible
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2011, 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;
31 import com.sun.tools.javac.code.*;
32 import com.sun.tools.javac.jvm.*;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
38 import com.sun.tools.javac.tree.JCTree.*;
39 import com.sun.tools.javac.code.Lint;
40 import com.sun.tools.javac.code.Lint.LintCategory;
41 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.code.Symbol.*;
44 import static com.sun.tools.javac.code.Flags.*;
45 import static com.sun.tools.javac.code.Kinds.*;
46 import static com.sun.tools.javac.code.TypeTags.*;
48 import static com.sun.tools.javac.main.OptionName.*;
50 /** Type checking helper class for the attribution phase.
51 *
52 * <p><b>This is NOT part of any supported API.
53 * If you write code that depends on this, you do so at your own risk.
54 * This code and its internal interfaces are subject to change or
55 * deletion without notice.</b>
56 */
57 public class Check {
58 protected static final Context.Key<Check> checkKey =
59 new Context.Key<Check>();
61 private final Names names;
62 private final Log log;
63 private final Resolve rs;
64 private final Symtab syms;
65 private final Enter enter;
66 private final Infer infer;
67 private final Types types;
68 private final JCDiagnostic.Factory diags;
69 private final boolean skipAnnotations;
70 private boolean warnOnSyntheticConflicts;
71 private boolean suppressAbortOnBadClassFile;
72 private final TreeInfo treeinfo;
74 // The set of lint options currently in effect. It is initialized
75 // from the context, and then is set/reset as needed by Attr as it
76 // visits all the various parts of the trees during attribution.
77 private Lint lint;
79 // The method being analyzed in Attr - it is set/reset as needed by
80 // Attr as it visits new method declarations.
81 private MethodSymbol method;
83 public static Check instance(Context context) {
84 Check instance = context.get(checkKey);
85 if (instance == null)
86 instance = new Check(context);
87 return instance;
88 }
90 protected Check(Context context) {
91 context.put(checkKey, this);
93 names = Names.instance(context);
94 log = Log.instance(context);
95 rs = Resolve.instance(context);
96 syms = Symtab.instance(context);
97 enter = Enter.instance(context);
98 infer = Infer.instance(context);
99 this.types = Types.instance(context);
100 diags = JCDiagnostic.Factory.instance(context);
101 Options options = Options.instance(context);
102 lint = Lint.instance(context);
103 treeinfo = TreeInfo.instance(context);
105 Source source = Source.instance(context);
106 allowGenerics = source.allowGenerics();
107 allowAnnotations = source.allowAnnotations();
108 allowCovariantReturns = source.allowCovariantReturns();
109 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
110 complexInference = options.isSet(COMPLEXINFERENCE);
111 skipAnnotations = options.isSet("skipAnnotations");
112 warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
113 suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
115 Target target = Target.instance(context);
116 syntheticNameChar = target.syntheticNameChar();
118 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
119 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
120 boolean verboseVarargs = lint.isEnabled(LintCategory.VARARGS);
121 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
122 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
124 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
125 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
126 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
127 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
128 unsafeVarargsHandler = new MandatoryWarningHandler(log, verboseVarargs,
129 enforceMandatoryWarnings, "varargs", LintCategory.VARARGS);
130 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
131 enforceMandatoryWarnings, "sunapi", null);
132 }
134 /** Switch: generics enabled?
135 */
136 boolean allowGenerics;
138 /** Switch: annotations enabled?
139 */
140 boolean allowAnnotations;
142 /** Switch: covariant returns enabled?
143 */
144 boolean allowCovariantReturns;
146 /** Switch: simplified varargs enabled?
147 */
148 boolean allowSimplifiedVarargs;
150 /** Switch: -complexinference option set?
151 */
152 boolean complexInference;
154 /** Character for synthetic names
155 */
156 char syntheticNameChar;
158 /** A table mapping flat names of all compiled classes in this run to their
159 * symbols; maintained from outside.
160 */
161 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
163 /** A handler for messages about deprecated usage.
164 */
165 private MandatoryWarningHandler deprecationHandler;
167 /** A handler for messages about unchecked or unsafe usage.
168 */
169 private MandatoryWarningHandler uncheckedHandler;
171 /** A handler for messages about unchecked or unsafe vararg method decl.
172 */
173 private MandatoryWarningHandler unsafeVarargsHandler;
175 /** A handler for messages about using proprietary API.
176 */
177 private MandatoryWarningHandler sunApiHandler;
179 /* *************************************************************************
180 * Errors and Warnings
181 **************************************************************************/
183 Lint setLint(Lint newLint) {
184 Lint prev = lint;
185 lint = newLint;
186 return prev;
187 }
189 MethodSymbol setMethod(MethodSymbol newMethod) {
190 MethodSymbol prev = method;
191 method = newMethod;
192 return prev;
193 }
195 /** Warn about deprecated symbol.
196 * @param pos Position to be used for error reporting.
197 * @param sym The deprecated symbol.
198 */
199 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
200 if (!lint.isSuppressed(LintCategory.DEPRECATION))
201 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
202 }
204 /** Warn about unchecked operation.
205 * @param pos Position to be used for error reporting.
206 * @param msg A string describing the problem.
207 */
208 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
209 if (!lint.isSuppressed(LintCategory.UNCHECKED))
210 uncheckedHandler.report(pos, msg, args);
211 }
213 /** Warn about unsafe vararg method decl.
214 * @param pos Position to be used for error reporting.
215 * @param sym The deprecated symbol.
216 */
217 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
218 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
219 log.warning(LintCategory.VARARGS, pos, key, args);
220 }
222 /** Warn about using proprietary API.
223 * @param pos Position to be used for error reporting.
224 * @param msg A string describing the problem.
225 */
226 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
227 if (!lint.isSuppressed(LintCategory.SUNAPI))
228 sunApiHandler.report(pos, msg, args);
229 }
231 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
232 if (lint.isEnabled(LintCategory.STATIC))
233 log.warning(LintCategory.STATIC, pos, msg, args);
234 }
236 /**
237 * Report any deferred diagnostics.
238 */
239 public void reportDeferredDiagnostics() {
240 deprecationHandler.reportDeferredDiagnostic();
241 uncheckedHandler.reportDeferredDiagnostic();
242 sunApiHandler.reportDeferredDiagnostic();
243 }
246 /** Report a failure to complete a class.
247 * @param pos Position to be used for error reporting.
248 * @param ex The failure to report.
249 */
250 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
251 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
252 if (ex instanceof ClassReader.BadClassFile
253 && !suppressAbortOnBadClassFile) throw new Abort();
254 else return syms.errType;
255 }
257 /** Report a type error.
258 * @param pos Position to be used for error reporting.
259 * @param problem A string describing the error.
260 * @param found The type that was found.
261 * @param req The type that was required.
262 */
263 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
264 log.error(pos, "prob.found.req",
265 problem, found, req);
266 return types.createErrorType(found);
267 }
269 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
270 log.error(pos, "prob.found.req.1", problem, found, req, explanation);
271 return types.createErrorType(found);
272 }
274 /** Report an error that wrong type tag was found.
275 * @param pos Position to be used for error reporting.
276 * @param required An internationalized string describing the type tag
277 * required.
278 * @param found The type that was found.
279 */
280 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
281 // this error used to be raised by the parser,
282 // but has been delayed to this point:
283 if (found instanceof Type && ((Type)found).tag == VOID) {
284 log.error(pos, "illegal.start.of.type");
285 return syms.errType;
286 }
287 log.error(pos, "type.found.req", found, required);
288 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
289 }
291 /** Report an error that symbol cannot be referenced before super
292 * has been called.
293 * @param pos Position to be used for error reporting.
294 * @param sym The referenced symbol.
295 */
296 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
297 log.error(pos, "cant.ref.before.ctor.called", sym);
298 }
300 /** Report duplicate declaration error.
301 */
302 void duplicateError(DiagnosticPosition pos, Symbol sym) {
303 if (!sym.type.isErroneous()) {
304 log.error(pos, "already.defined", sym, sym.location());
305 }
306 }
308 /** Report array/varargs duplicate declaration
309 */
310 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
311 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
312 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
313 }
314 }
316 /* ************************************************************************
317 * duplicate declaration checking
318 *************************************************************************/
320 /** Check that variable does not hide variable with same name in
321 * immediately enclosing local scope.
322 * @param pos Position for error reporting.
323 * @param v The symbol.
324 * @param s The scope.
325 */
326 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
327 if (s.next != null) {
328 for (Scope.Entry e = s.next.lookup(v.name);
329 e.scope != null && e.sym.owner == v.owner;
330 e = e.next()) {
331 if (e.sym.kind == VAR &&
332 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
333 v.name != names.error) {
334 duplicateError(pos, e.sym);
335 return;
336 }
337 }
338 }
339 }
341 /** Check that a class or interface does not hide a class or
342 * interface with same name in immediately enclosing local scope.
343 * @param pos Position for error reporting.
344 * @param c The symbol.
345 * @param s The scope.
346 */
347 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
348 if (s.next != null) {
349 for (Scope.Entry e = s.next.lookup(c.name);
350 e.scope != null && e.sym.owner == c.owner;
351 e = e.next()) {
352 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
353 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
354 c.name != names.error) {
355 duplicateError(pos, e.sym);
356 return;
357 }
358 }
359 }
360 }
362 /** Check that class does not have the same name as one of
363 * its enclosing classes, or as a class defined in its enclosing scope.
364 * return true if class is unique in its enclosing scope.
365 * @param pos Position for error reporting.
366 * @param name The class name.
367 * @param s The enclosing scope.
368 */
369 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
370 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
371 if (e.sym.kind == TYP && e.sym.name != names.error) {
372 duplicateError(pos, e.sym);
373 return false;
374 }
375 }
376 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
377 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
378 duplicateError(pos, sym);
379 return true;
380 }
381 }
382 return true;
383 }
385 /* *************************************************************************
386 * Class name generation
387 **************************************************************************/
389 /** Return name of local class.
390 * This is of the form <enclClass> $ n <classname>
391 * where
392 * enclClass is the flat name of the enclosing class,
393 * classname is the simple name of the local class
394 */
395 Name localClassName(ClassSymbol c) {
396 for (int i=1; ; i++) {
397 Name flatname = names.
398 fromString("" + c.owner.enclClass().flatname +
399 syntheticNameChar + i +
400 c.name);
401 if (compiled.get(flatname) == null) return flatname;
402 }
403 }
405 /* *************************************************************************
406 * Type Checking
407 **************************************************************************/
409 /** Check that a given type is assignable to a given proto-type.
410 * If it is, return the type, otherwise return errType.
411 * @param pos Position to be used for error reporting.
412 * @param found The type that was found.
413 * @param req The type that was required.
414 */
415 Type checkType(DiagnosticPosition pos, Type found, Type req) {
416 return checkType(pos, found, req, "incompatible.types");
417 }
419 Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
420 if (req.tag == ERROR)
421 return req;
422 if (found.tag == FORALL)
423 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
424 if (req.tag == NONE)
425 return found;
426 if (types.isAssignable(found, req, convertWarner(pos, found, req)))
427 return found;
428 if (found.tag <= DOUBLE && req.tag <= DOUBLE)
429 return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
430 if (found.isSuperBound()) {
431 log.error(pos, "assignment.from.super-bound", found);
432 return types.createErrorType(found);
433 }
434 if (req.isExtendsBound()) {
435 log.error(pos, "assignment.to.extends-bound", req);
436 return types.createErrorType(found);
437 }
438 return typeError(pos, diags.fragment(errKey), found, req);
439 }
441 /** Instantiate polymorphic type to some prototype, unless
442 * prototype is `anyPoly' in which case polymorphic type
443 * is returned unchanged.
444 */
445 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
446 if (pt == Infer.anyPoly && complexInference) {
447 return t;
448 } else if (pt == Infer.anyPoly || pt.tag == NONE) {
449 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
450 return instantiatePoly(pos, t, newpt, warn);
451 } else if (pt.tag == ERROR) {
452 return pt;
453 } else {
454 try {
455 return infer.instantiateExpr(t, pt, warn);
456 } catch (Infer.NoInstanceException ex) {
457 if (ex.isAmbiguous) {
458 JCDiagnostic d = ex.getDiagnostic();
459 log.error(pos,
460 "undetermined.type" + (d!=null ? ".1" : ""),
461 t, d);
462 return types.createErrorType(pt);
463 } else {
464 JCDiagnostic d = ex.getDiagnostic();
465 return typeError(pos,
466 diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
467 t, pt);
468 }
469 } catch (Infer.InvalidInstanceException ex) {
470 JCDiagnostic d = ex.getDiagnostic();
471 log.error(pos, "invalid.inferred.types", t.tvars, d);
472 return types.createErrorType(pt);
473 }
474 }
475 }
477 /** Check that a given type can be cast to a given target type.
478 * Return the result of the cast.
479 * @param pos Position to be used for error reporting.
480 * @param found The type that is being cast.
481 * @param req The target type of the cast.
482 */
483 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
484 if (found.tag == FORALL) {
485 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
486 return req;
487 } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
488 return req;
489 } else {
490 return typeError(pos,
491 diags.fragment("inconvertible.types"),
492 found, req);
493 }
494 }
495 //where
496 /** Is type a type variable, or a (possibly multi-dimensional) array of
497 * type variables?
498 */
499 boolean isTypeVar(Type t) {
500 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
501 }
503 /** Check that a type is within some bounds.
504 *
505 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
506 * type argument.
507 * @param pos Position to be used for error reporting.
508 * @param a The type that should be bounded by bs.
509 * @param bs The bound.
510 */
511 private boolean checkExtends(Type a, TypeVar bs) {
512 if (a.isUnbound()) {
513 return true;
514 } else if (a.tag != WILDCARD) {
515 a = types.upperBound(a);
516 return types.isSubtype(a, bs.bound);
517 } else if (a.isExtendsBound()) {
518 return types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings);
519 } else if (a.isSuperBound()) {
520 return !types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound());
521 }
522 return true;
523 }
525 /** Check that type is different from 'void'.
526 * @param pos Position to be used for error reporting.
527 * @param t The type to be checked.
528 */
529 Type checkNonVoid(DiagnosticPosition pos, Type t) {
530 if (t.tag == VOID) {
531 log.error(pos, "void.not.allowed.here");
532 return types.createErrorType(t);
533 } else {
534 return t;
535 }
536 }
538 /** Check that type is a class or interface type.
539 * @param pos Position to be used for error reporting.
540 * @param t The type to be checked.
541 */
542 Type checkClassType(DiagnosticPosition pos, Type t) {
543 if (t.tag != CLASS && t.tag != ERROR)
544 return typeTagError(pos,
545 diags.fragment("type.req.class"),
546 (t.tag == TYPEVAR)
547 ? diags.fragment("type.parameter", t)
548 : t);
549 else
550 return t;
551 }
553 /** Check that type is a class or interface type.
554 * @param pos Position to be used for error reporting.
555 * @param t The type to be checked.
556 * @param noBounds True if type bounds are illegal here.
557 */
558 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
559 t = checkClassType(pos, t);
560 if (noBounds && t.isParameterized()) {
561 List<Type> args = t.getTypeArguments();
562 while (args.nonEmpty()) {
563 if (args.head.tag == WILDCARD)
564 return typeTagError(pos,
565 diags.fragment("type.req.exact"),
566 args.head);
567 args = args.tail;
568 }
569 }
570 return t;
571 }
573 /** Check that type is a reifiable class, interface or array type.
574 * @param pos Position to be used for error reporting.
575 * @param t The type to be checked.
576 */
577 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
578 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
579 return typeTagError(pos,
580 diags.fragment("type.req.class.array"),
581 t);
582 } else if (!types.isReifiable(t)) {
583 log.error(pos, "illegal.generic.type.for.instof");
584 return types.createErrorType(t);
585 } else {
586 return t;
587 }
588 }
590 /** Check that type is a reference type, i.e. a class, interface or array type
591 * or a type variable.
592 * @param pos Position to be used for error reporting.
593 * @param t The type to be checked.
594 */
595 Type checkRefType(DiagnosticPosition pos, Type t) {
596 switch (t.tag) {
597 case CLASS:
598 case ARRAY:
599 case TYPEVAR:
600 case WILDCARD:
601 case ERROR:
602 return t;
603 default:
604 return typeTagError(pos,
605 diags.fragment("type.req.ref"),
606 t);
607 }
608 }
610 /** Check that each type is a reference type, i.e. a class, interface or array type
611 * or a type variable.
612 * @param trees Original trees, used for error reporting.
613 * @param types The types to be checked.
614 */
615 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
616 List<JCExpression> tl = trees;
617 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
618 l.head = checkRefType(tl.head.pos(), l.head);
619 tl = tl.tail;
620 }
621 return types;
622 }
624 /** Check that type is a null or reference type.
625 * @param pos Position to be used for error reporting.
626 * @param t The type to be checked.
627 */
628 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
629 switch (t.tag) {
630 case CLASS:
631 case ARRAY:
632 case TYPEVAR:
633 case WILDCARD:
634 case BOT:
635 case ERROR:
636 return t;
637 default:
638 return typeTagError(pos,
639 diags.fragment("type.req.ref"),
640 t);
641 }
642 }
644 /** Check that flag set does not contain elements of two conflicting sets. s
645 * Return true if it doesn't.
646 * @param pos Position to be used for error reporting.
647 * @param flags The set of flags to be checked.
648 * @param set1 Conflicting flags set #1.
649 * @param set2 Conflicting flags set #2.
650 */
651 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
652 if ((flags & set1) != 0 && (flags & set2) != 0) {
653 log.error(pos,
654 "illegal.combination.of.modifiers",
655 asFlagSet(TreeInfo.firstFlag(flags & set1)),
656 asFlagSet(TreeInfo.firstFlag(flags & set2)));
657 return false;
658 } else
659 return true;
660 }
662 /** Check that the type inferred using the diamond operator does not contain
663 * non-denotable types such as captured types or intersection types.
664 * @param t the type inferred using the diamond operator
665 */
666 List<Type> checkDiamond(ClassType t) {
667 DiamondTypeChecker dtc = new DiamondTypeChecker();
668 ListBuffer<Type> buf = ListBuffer.lb();
669 for (Type arg : t.getTypeArguments()) {
670 if (!dtc.visit(arg, null)) {
671 buf.append(arg);
672 }
673 }
674 return buf.toList();
675 }
677 static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
678 public Boolean visitType(Type t, Void s) {
679 return true;
680 }
681 @Override
682 public Boolean visitClassType(ClassType t, Void s) {
683 if (t.isCompound()) {
684 return false;
685 }
686 for (Type targ : t.getTypeArguments()) {
687 if (!visit(targ, s)) {
688 return false;
689 }
690 }
691 return true;
692 }
693 @Override
694 public Boolean visitCapturedType(CapturedType t, Void s) {
695 return false;
696 }
697 }
699 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
700 MethodSymbol m = tree.sym;
701 if (!allowSimplifiedVarargs) return;
702 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
703 Type varargElemType = null;
704 if (m.isVarArgs()) {
705 varargElemType = types.elemtype(tree.params.last().type);
706 }
707 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
708 if (varargElemType != null) {
709 log.error(tree,
710 "varargs.invalid.trustme.anno",
711 syms.trustMeType.tsym,
712 diags.fragment("varargs.trustme.on.virtual.varargs", m));
713 } else {
714 log.error(tree,
715 "varargs.invalid.trustme.anno",
716 syms.trustMeType.tsym,
717 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
718 }
719 } else if (hasTrustMeAnno && varargElemType != null &&
720 types.isReifiable(varargElemType)) {
721 warnUnsafeVararg(tree,
722 "varargs.redundant.trustme.anno",
723 syms.trustMeType.tsym,
724 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
725 }
726 else if (!hasTrustMeAnno && varargElemType != null &&
727 !types.isReifiable(varargElemType)) {
728 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
729 }
730 }
731 //where
732 private boolean isTrustMeAllowedOnMethod(Symbol s) {
733 return (s.flags() & VARARGS) != 0 &&
734 (s.isConstructor() ||
735 (s.flags() & (STATIC | FINAL)) != 0);
736 }
738 /**
739 * Check that vararg method call is sound
740 * @param pos Position to be used for error reporting.
741 * @param argtypes Actual arguments supplied to vararg method.
742 */
743 void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
744 Type argtype = argtypes.last();
745 if (!types.isReifiable(argtype) &&
746 (!allowSimplifiedVarargs ||
747 msym.attribute(syms.trustMeType.tsym) == null ||
748 !isTrustMeAllowedOnMethod(msym))) {
749 warnUnchecked(pos,
750 "unchecked.generic.array.creation",
751 argtype);
752 }
753 }
755 /**
756 * Check that type 't' is a valid instantiation of a generic class
757 * (see JLS 4.5)
758 *
759 * @param t class type to be checked
760 * @return true if 't' is well-formed
761 */
762 public boolean checkValidGenericType(Type t) {
763 return firstIncompatibleTypeArg(t) == null;
764 }
765 //WHERE
766 private Type firstIncompatibleTypeArg(Type type) {
767 List<Type> formals = type.tsym.type.allparams();
768 List<Type> actuals = type.allparams();
769 List<Type> args = type.getTypeArguments();
770 List<Type> forms = type.tsym.type.getTypeArguments();
771 ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
773 // For matching pairs of actual argument types `a' and
774 // formal type parameters with declared bound `b' ...
775 while (args.nonEmpty() && forms.nonEmpty()) {
776 // exact type arguments needs to know their
777 // bounds (for upper and lower bound
778 // calculations). So we create new TypeVars with
779 // bounds substed with actuals.
780 tvars_buf.append(types.substBound(((TypeVar)forms.head),
781 formals,
782 actuals));
783 args = args.tail;
784 forms = forms.tail;
785 }
787 args = type.getTypeArguments();
788 List<Type> tvars_cap = types.substBounds(formals,
789 formals,
790 types.capture(type).allparams());
791 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
792 // Let the actual arguments know their bound
793 args.head.withTypeVar((TypeVar)tvars_cap.head);
794 args = args.tail;
795 tvars_cap = tvars_cap.tail;
796 }
798 args = type.getTypeArguments();
799 List<Type> tvars = tvars_buf.toList();
801 while (args.nonEmpty() && tvars.nonEmpty()) {
802 Type actual = types.subst(args.head,
803 type.tsym.type.getTypeArguments(),
804 tvars_buf.toList());
805 if (!checkExtends(actual, (TypeVar)tvars.head) &&
806 !tvars.head.getUpperBound().isErroneous()) {
807 return args.head;
808 }
809 args = args.tail;
810 tvars = tvars.tail;
811 }
813 args = type.getTypeArguments();
814 tvars = tvars_buf.toList();
816 for (Type arg : types.capture(type).getTypeArguments()) {
817 if (arg.tag == TYPEVAR &&
818 arg.getUpperBound().isErroneous() &&
819 !tvars.head.getUpperBound().isErroneous()) {
820 return args.head;
821 }
822 tvars = tvars.tail;
823 }
825 return null;
826 }
828 /** Check that given modifiers are legal for given symbol and
829 * return modifiers together with any implicit modififiers for that symbol.
830 * Warning: we can't use flags() here since this method
831 * is called during class enter, when flags() would cause a premature
832 * completion.
833 * @param pos Position to be used for error reporting.
834 * @param flags The set of modifiers given in a definition.
835 * @param sym The defined symbol.
836 */
837 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
838 long mask;
839 long implicit = 0;
840 switch (sym.kind) {
841 case VAR:
842 if (sym.owner.kind != TYP)
843 mask = LocalVarFlags;
844 else if ((sym.owner.flags_field & INTERFACE) != 0)
845 mask = implicit = InterfaceVarFlags;
846 else
847 mask = VarFlags;
848 break;
849 case MTH:
850 if (sym.name == names.init) {
851 if ((sym.owner.flags_field & ENUM) != 0) {
852 // enum constructors cannot be declared public or
853 // protected and must be implicitly or explicitly
854 // private
855 implicit = PRIVATE;
856 mask = PRIVATE;
857 } else
858 mask = ConstructorFlags;
859 } else if ((sym.owner.flags_field & INTERFACE) != 0)
860 mask = implicit = InterfaceMethodFlags;
861 else {
862 mask = MethodFlags;
863 }
864 // Imply STRICTFP if owner has STRICTFP set.
865 if (((flags|implicit) & Flags.ABSTRACT) == 0)
866 implicit |= sym.owner.flags_field & STRICTFP;
867 break;
868 case TYP:
869 if (sym.isLocal()) {
870 mask = LocalClassFlags;
871 if (sym.name.isEmpty()) { // Anonymous class
872 // Anonymous classes in static methods are themselves static;
873 // that's why we admit STATIC here.
874 mask |= STATIC;
875 // JLS: Anonymous classes are final.
876 implicit |= FINAL;
877 }
878 if ((sym.owner.flags_field & STATIC) == 0 &&
879 (flags & ENUM) != 0)
880 log.error(pos, "enums.must.be.static");
881 } else if (sym.owner.kind == TYP) {
882 mask = MemberClassFlags;
883 if (sym.owner.owner.kind == PCK ||
884 (sym.owner.flags_field & STATIC) != 0)
885 mask |= STATIC;
886 else if ((flags & ENUM) != 0)
887 log.error(pos, "enums.must.be.static");
888 // Nested interfaces and enums are always STATIC (Spec ???)
889 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
890 } else {
891 mask = ClassFlags;
892 }
893 // Interfaces are always ABSTRACT
894 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
896 if ((flags & ENUM) != 0) {
897 // enums can't be declared abstract or final
898 mask &= ~(ABSTRACT | FINAL);
899 implicit |= implicitEnumFinalFlag(tree);
900 }
901 // Imply STRICTFP if owner has STRICTFP set.
902 implicit |= sym.owner.flags_field & STRICTFP;
903 break;
904 default:
905 throw new AssertionError();
906 }
907 long illegal = flags & StandardFlags & ~mask;
908 if (illegal != 0) {
909 if ((illegal & INTERFACE) != 0) {
910 log.error(pos, "intf.not.allowed.here");
911 mask |= INTERFACE;
912 }
913 else {
914 log.error(pos,
915 "mod.not.allowed.here", asFlagSet(illegal));
916 }
917 }
918 else if ((sym.kind == TYP ||
919 // ISSUE: Disallowing abstract&private is no longer appropriate
920 // in the presence of inner classes. Should it be deleted here?
921 checkDisjoint(pos, flags,
922 ABSTRACT,
923 PRIVATE | STATIC))
924 &&
925 checkDisjoint(pos, flags,
926 ABSTRACT | INTERFACE,
927 FINAL | NATIVE | SYNCHRONIZED)
928 &&
929 checkDisjoint(pos, flags,
930 PUBLIC,
931 PRIVATE | PROTECTED)
932 &&
933 checkDisjoint(pos, flags,
934 PRIVATE,
935 PUBLIC | PROTECTED)
936 &&
937 checkDisjoint(pos, flags,
938 FINAL,
939 VOLATILE)
940 &&
941 (sym.kind == TYP ||
942 checkDisjoint(pos, flags,
943 ABSTRACT | NATIVE,
944 STRICTFP))) {
945 // skip
946 }
947 return flags & (mask | ~StandardFlags) | implicit;
948 }
951 /** Determine if this enum should be implicitly final.
952 *
953 * If the enum has no specialized enum contants, it is final.
954 *
955 * If the enum does have specialized enum contants, it is
956 * <i>not</i> final.
957 */
958 private long implicitEnumFinalFlag(JCTree tree) {
959 if (tree.getTag() != JCTree.CLASSDEF) return 0;
960 class SpecialTreeVisitor extends JCTree.Visitor {
961 boolean specialized;
962 SpecialTreeVisitor() {
963 this.specialized = false;
964 };
966 @Override
967 public void visitTree(JCTree tree) { /* no-op */ }
969 @Override
970 public void visitVarDef(JCVariableDecl tree) {
971 if ((tree.mods.flags & ENUM) != 0) {
972 if (tree.init instanceof JCNewClass &&
973 ((JCNewClass) tree.init).def != null) {
974 specialized = true;
975 }
976 }
977 }
978 }
980 SpecialTreeVisitor sts = new SpecialTreeVisitor();
981 JCClassDecl cdef = (JCClassDecl) tree;
982 for (JCTree defs: cdef.defs) {
983 defs.accept(sts);
984 if (sts.specialized) return 0;
985 }
986 return FINAL;
987 }
989 /* *************************************************************************
990 * Type Validation
991 **************************************************************************/
993 /** Validate a type expression. That is,
994 * check that all type arguments of a parametric type are within
995 * their bounds. This must be done in a second phase after type attributon
996 * since a class might have a subclass as type parameter bound. E.g:
997 *
998 * class B<A extends C> { ... }
999 * class C extends B<C> { ... }
1000 *
1001 * and we can't make sure that the bound is already attributed because
1002 * of possible cycles.
1003 *
1004 * Visitor method: Validate a type expression, if it is not null, catching
1005 * and reporting any completion failures.
1006 */
1007 void validate(JCTree tree, Env<AttrContext> env) {
1008 validate(tree, env, true);
1009 }
1010 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1011 new Validator(env).validateTree(tree, checkRaw, true);
1012 }
1014 /** Visitor method: Validate a list of type expressions.
1015 */
1016 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1017 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1018 validate(l.head, env);
1019 }
1021 /** A visitor class for type validation.
1022 */
1023 class Validator extends JCTree.Visitor {
1025 boolean isOuter;
1026 Env<AttrContext> env;
1028 Validator(Env<AttrContext> env) {
1029 this.env = env;
1030 }
1032 @Override
1033 public void visitTypeArray(JCArrayTypeTree tree) {
1034 tree.elemtype.accept(this);
1035 }
1037 @Override
1038 public void visitTypeApply(JCTypeApply tree) {
1039 if (tree.type.tag == CLASS) {
1040 List<JCExpression> args = tree.arguments;
1041 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1043 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1044 if (incompatibleArg != null) {
1045 for (JCTree arg : tree.arguments) {
1046 if (arg.type == incompatibleArg) {
1047 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1048 }
1049 forms = forms.tail;
1050 }
1051 }
1053 forms = tree.type.tsym.type.getTypeArguments();
1055 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1057 // For matching pairs of actual argument types `a' and
1058 // formal type parameters with declared bound `b' ...
1059 while (args.nonEmpty() && forms.nonEmpty()) {
1060 validateTree(args.head,
1061 !(isOuter && is_java_lang_Class),
1062 false);
1063 args = args.tail;
1064 forms = forms.tail;
1065 }
1067 // Check that this type is either fully parameterized, or
1068 // not parameterized at all.
1069 if (tree.type.getEnclosingType().isRaw())
1070 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1071 if (tree.clazz.getTag() == JCTree.SELECT)
1072 visitSelectInternal((JCFieldAccess)tree.clazz);
1073 }
1074 }
1076 @Override
1077 public void visitTypeParameter(JCTypeParameter tree) {
1078 validateTrees(tree.bounds, true, isOuter);
1079 checkClassBounds(tree.pos(), tree.type);
1080 }
1082 @Override
1083 public void visitWildcard(JCWildcard tree) {
1084 if (tree.inner != null)
1085 validateTree(tree.inner, true, isOuter);
1086 }
1088 @Override
1089 public void visitSelect(JCFieldAccess tree) {
1090 if (tree.type.tag == CLASS) {
1091 visitSelectInternal(tree);
1093 // Check that this type is either fully parameterized, or
1094 // not parameterized at all.
1095 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1096 log.error(tree.pos(), "improperly.formed.type.param.missing");
1097 }
1098 }
1099 public void visitSelectInternal(JCFieldAccess tree) {
1100 if (tree.type.tsym.isStatic() &&
1101 tree.selected.type.isParameterized()) {
1102 // The enclosing type is not a class, so we are
1103 // looking at a static member type. However, the
1104 // qualifying expression is parameterized.
1105 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1106 } else {
1107 // otherwise validate the rest of the expression
1108 tree.selected.accept(this);
1109 }
1110 }
1112 /** Default visitor method: do nothing.
1113 */
1114 @Override
1115 public void visitTree(JCTree tree) {
1116 }
1118 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1119 try {
1120 if (tree != null) {
1121 this.isOuter = isOuter;
1122 tree.accept(this);
1123 if (checkRaw)
1124 checkRaw(tree, env);
1125 }
1126 } catch (CompletionFailure ex) {
1127 completionError(tree.pos(), ex);
1128 }
1129 }
1131 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1132 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1133 validateTree(l.head, checkRaw, isOuter);
1134 }
1136 void checkRaw(JCTree tree, Env<AttrContext> env) {
1137 if (lint.isEnabled(LintCategory.RAW) &&
1138 tree.type.tag == CLASS &&
1139 !TreeInfo.isDiamond(tree) &&
1140 !env.enclClass.name.isEmpty() && //anonymous or intersection
1141 tree.type.isRaw()) {
1142 log.warning(LintCategory.RAW,
1143 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1144 }
1145 }
1146 }
1148 /* *************************************************************************
1149 * Exception checking
1150 **************************************************************************/
1152 /* The following methods treat classes as sets that contain
1153 * the class itself and all their subclasses
1154 */
1156 /** Is given type a subtype of some of the types in given list?
1157 */
1158 boolean subset(Type t, List<Type> ts) {
1159 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1160 if (types.isSubtype(t, l.head)) return true;
1161 return false;
1162 }
1164 /** Is given type a subtype or supertype of
1165 * some of the types in given list?
1166 */
1167 boolean intersects(Type t, List<Type> ts) {
1168 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1169 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1170 return false;
1171 }
1173 /** Add type set to given type list, unless it is a subclass of some class
1174 * in the list.
1175 */
1176 List<Type> incl(Type t, List<Type> ts) {
1177 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1178 }
1180 /** Remove type set from type set list.
1181 */
1182 List<Type> excl(Type t, List<Type> ts) {
1183 if (ts.isEmpty()) {
1184 return ts;
1185 } else {
1186 List<Type> ts1 = excl(t, ts.tail);
1187 if (types.isSubtype(ts.head, t)) return ts1;
1188 else if (ts1 == ts.tail) return ts;
1189 else return ts1.prepend(ts.head);
1190 }
1191 }
1193 /** Form the union of two type set lists.
1194 */
1195 List<Type> union(List<Type> ts1, List<Type> ts2) {
1196 List<Type> ts = ts1;
1197 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1198 ts = incl(l.head, ts);
1199 return ts;
1200 }
1202 /** Form the difference of two type lists.
1203 */
1204 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1205 List<Type> ts = ts1;
1206 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1207 ts = excl(l.head, ts);
1208 return ts;
1209 }
1211 /** Form the intersection of two type lists.
1212 */
1213 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1214 List<Type> ts = List.nil();
1215 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1216 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1217 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1218 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1219 return ts;
1220 }
1222 /** Is exc an exception symbol that need not be declared?
1223 */
1224 boolean isUnchecked(ClassSymbol exc) {
1225 return
1226 exc.kind == ERR ||
1227 exc.isSubClass(syms.errorType.tsym, types) ||
1228 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1229 }
1231 /** Is exc an exception type that need not be declared?
1232 */
1233 boolean isUnchecked(Type exc) {
1234 return
1235 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1236 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1237 exc.tag == BOT;
1238 }
1240 /** Same, but handling completion failures.
1241 */
1242 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1243 try {
1244 return isUnchecked(exc);
1245 } catch (CompletionFailure ex) {
1246 completionError(pos, ex);
1247 return true;
1248 }
1249 }
1251 /** Is exc handled by given exception list?
1252 */
1253 boolean isHandled(Type exc, List<Type> handled) {
1254 return isUnchecked(exc) || subset(exc, handled);
1255 }
1257 /** Return all exceptions in thrown list that are not in handled list.
1258 * @param thrown The list of thrown exceptions.
1259 * @param handled The list of handled exceptions.
1260 */
1261 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1262 List<Type> unhandled = List.nil();
1263 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1264 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1265 return unhandled;
1266 }
1268 /* *************************************************************************
1269 * Overriding/Implementation checking
1270 **************************************************************************/
1272 /** The level of access protection given by a flag set,
1273 * where PRIVATE is highest and PUBLIC is lowest.
1274 */
1275 static int protection(long flags) {
1276 switch ((short)(flags & AccessFlags)) {
1277 case PRIVATE: return 3;
1278 case PROTECTED: return 1;
1279 default:
1280 case PUBLIC: return 0;
1281 case 0: return 2;
1282 }
1283 }
1285 /** A customized "cannot override" error message.
1286 * @param m The overriding method.
1287 * @param other The overridden method.
1288 * @return An internationalized string.
1289 */
1290 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1291 String key;
1292 if ((other.owner.flags() & INTERFACE) == 0)
1293 key = "cant.override";
1294 else if ((m.owner.flags() & INTERFACE) == 0)
1295 key = "cant.implement";
1296 else
1297 key = "clashes.with";
1298 return diags.fragment(key, m, m.location(), other, other.location());
1299 }
1301 /** A customized "override" warning message.
1302 * @param m The overriding method.
1303 * @param other The overridden method.
1304 * @return An internationalized string.
1305 */
1306 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1307 String key;
1308 if ((other.owner.flags() & INTERFACE) == 0)
1309 key = "unchecked.override";
1310 else if ((m.owner.flags() & INTERFACE) == 0)
1311 key = "unchecked.implement";
1312 else
1313 key = "unchecked.clash.with";
1314 return diags.fragment(key, m, m.location(), other, other.location());
1315 }
1317 /** A customized "override" warning message.
1318 * @param m The overriding method.
1319 * @param other The overridden method.
1320 * @return An internationalized string.
1321 */
1322 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1323 String key;
1324 if ((other.owner.flags() & INTERFACE) == 0)
1325 key = "varargs.override";
1326 else if ((m.owner.flags() & INTERFACE) == 0)
1327 key = "varargs.implement";
1328 else
1329 key = "varargs.clash.with";
1330 return diags.fragment(key, m, m.location(), other, other.location());
1331 }
1333 /** Check that this method conforms with overridden method 'other'.
1334 * where `origin' is the class where checking started.
1335 * Complications:
1336 * (1) Do not check overriding of synthetic methods
1337 * (reason: they might be final).
1338 * todo: check whether this is still necessary.
1339 * (2) Admit the case where an interface proxy throws fewer exceptions
1340 * than the method it implements. Augment the proxy methods with the
1341 * undeclared exceptions in this case.
1342 * (3) When generics are enabled, admit the case where an interface proxy
1343 * has a result type
1344 * extended by the result type of the method it implements.
1345 * Change the proxies result type to the smaller type in this case.
1346 *
1347 * @param tree The tree from which positions
1348 * are extracted for errors.
1349 * @param m The overriding method.
1350 * @param other The overridden method.
1351 * @param origin The class of which the overriding method
1352 * is a member.
1353 */
1354 void checkOverride(JCTree tree,
1355 MethodSymbol m,
1356 MethodSymbol other,
1357 ClassSymbol origin) {
1358 // Don't check overriding of synthetic methods or by bridge methods.
1359 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1360 return;
1361 }
1363 // Error if static method overrides instance method (JLS 8.4.6.2).
1364 if ((m.flags() & STATIC) != 0 &&
1365 (other.flags() & STATIC) == 0) {
1366 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1367 cannotOverride(m, other));
1368 return;
1369 }
1371 // Error if instance method overrides static or final
1372 // method (JLS 8.4.6.1).
1373 if ((other.flags() & FINAL) != 0 ||
1374 (m.flags() & STATIC) == 0 &&
1375 (other.flags() & STATIC) != 0) {
1376 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1377 cannotOverride(m, other),
1378 asFlagSet(other.flags() & (FINAL | STATIC)));
1379 return;
1380 }
1382 if ((m.owner.flags() & ANNOTATION) != 0) {
1383 // handled in validateAnnotationMethod
1384 return;
1385 }
1387 // Error if overriding method has weaker access (JLS 8.4.6.3).
1388 if ((origin.flags() & INTERFACE) == 0 &&
1389 protection(m.flags()) > protection(other.flags())) {
1390 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1391 cannotOverride(m, other),
1392 other.flags() == 0 ?
1393 Flag.PACKAGE :
1394 asFlagSet(other.flags() & AccessFlags));
1395 return;
1396 }
1398 Type mt = types.memberType(origin.type, m);
1399 Type ot = types.memberType(origin.type, other);
1400 // Error if overriding result type is different
1401 // (or, in the case of generics mode, not a subtype) of
1402 // overridden result type. We have to rename any type parameters
1403 // before comparing types.
1404 List<Type> mtvars = mt.getTypeArguments();
1405 List<Type> otvars = ot.getTypeArguments();
1406 Type mtres = mt.getReturnType();
1407 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1409 overrideWarner.clear();
1410 boolean resultTypesOK =
1411 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1412 if (!resultTypesOK) {
1413 if (!allowCovariantReturns &&
1414 m.owner != origin &&
1415 m.owner.isSubClass(other.owner, types)) {
1416 // allow limited interoperability with covariant returns
1417 } else {
1418 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1419 "override.incompatible.ret",
1420 cannotOverride(m, other),
1421 mtres, otres);
1422 return;
1423 }
1424 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1425 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1426 "override.unchecked.ret",
1427 uncheckedOverrides(m, other),
1428 mtres, otres);
1429 }
1431 // Error if overriding method throws an exception not reported
1432 // by overridden method.
1433 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1434 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1435 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1436 if (unhandledErased.nonEmpty()) {
1437 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1438 "override.meth.doesnt.throw",
1439 cannotOverride(m, other),
1440 unhandledUnerased.head);
1441 return;
1442 }
1443 else if (unhandledUnerased.nonEmpty()) {
1444 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1445 "override.unchecked.thrown",
1446 cannotOverride(m, other),
1447 unhandledUnerased.head);
1448 return;
1449 }
1451 // Optional warning if varargs don't agree
1452 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1453 && lint.isEnabled(LintCategory.OVERRIDES)) {
1454 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1455 ((m.flags() & Flags.VARARGS) != 0)
1456 ? "override.varargs.missing"
1457 : "override.varargs.extra",
1458 varargsOverrides(m, other));
1459 }
1461 // Warn if instance method overrides bridge method (compiler spec ??)
1462 if ((other.flags() & BRIDGE) != 0) {
1463 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1464 uncheckedOverrides(m, other));
1465 }
1467 // Warn if a deprecated method overridden by a non-deprecated one.
1468 if ((other.flags() & DEPRECATED) != 0
1469 && (m.flags() & DEPRECATED) == 0
1470 && m.outermostClass() != other.outermostClass()
1471 && !isDeprecatedOverrideIgnorable(other, origin)) {
1472 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1473 }
1474 }
1475 // where
1476 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1477 // If the method, m, is defined in an interface, then ignore the issue if the method
1478 // is only inherited via a supertype and also implemented in the supertype,
1479 // because in that case, we will rediscover the issue when examining the method
1480 // in the supertype.
1481 // If the method, m, is not defined in an interface, then the only time we need to
1482 // address the issue is when the method is the supertype implemementation: any other
1483 // case, we will have dealt with when examining the supertype classes
1484 ClassSymbol mc = m.enclClass();
1485 Type st = types.supertype(origin.type);
1486 if (st.tag != CLASS)
1487 return true;
1488 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1490 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1491 List<Type> intfs = types.interfaces(origin.type);
1492 return (intfs.contains(mc.type) ? false : (stimpl != null));
1493 }
1494 else
1495 return (stimpl != m);
1496 }
1499 // used to check if there were any unchecked conversions
1500 Warner overrideWarner = new Warner();
1502 /** Check that a class does not inherit two concrete methods
1503 * with the same signature.
1504 * @param pos Position to be used for error reporting.
1505 * @param site The class type to be checked.
1506 */
1507 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1508 Type sup = types.supertype(site);
1509 if (sup.tag != CLASS) return;
1511 for (Type t1 = sup;
1512 t1.tsym.type.isParameterized();
1513 t1 = types.supertype(t1)) {
1514 for (Scope.Entry e1 = t1.tsym.members().elems;
1515 e1 != null;
1516 e1 = e1.sibling) {
1517 Symbol s1 = e1.sym;
1518 if (s1.kind != MTH ||
1519 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1520 !s1.isInheritedIn(site.tsym, types) ||
1521 ((MethodSymbol)s1).implementation(site.tsym,
1522 types,
1523 true) != s1)
1524 continue;
1525 Type st1 = types.memberType(t1, s1);
1526 int s1ArgsLength = st1.getParameterTypes().length();
1527 if (st1 == s1.type) continue;
1529 for (Type t2 = sup;
1530 t2.tag == CLASS;
1531 t2 = types.supertype(t2)) {
1532 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1533 e2.scope != null;
1534 e2 = e2.next()) {
1535 Symbol s2 = e2.sym;
1536 if (s2 == s1 ||
1537 s2.kind != MTH ||
1538 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1539 s2.type.getParameterTypes().length() != s1ArgsLength ||
1540 !s2.isInheritedIn(site.tsym, types) ||
1541 ((MethodSymbol)s2).implementation(site.tsym,
1542 types,
1543 true) != s2)
1544 continue;
1545 Type st2 = types.memberType(t2, s2);
1546 if (types.overrideEquivalent(st1, st2))
1547 log.error(pos, "concrete.inheritance.conflict",
1548 s1, t1, s2, t2, sup);
1549 }
1550 }
1551 }
1552 }
1553 }
1555 /** Check that classes (or interfaces) do not each define an abstract
1556 * method with same name and arguments but incompatible return types.
1557 * @param pos Position to be used for error reporting.
1558 * @param t1 The first argument type.
1559 * @param t2 The second argument type.
1560 */
1561 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1562 Type t1,
1563 Type t2) {
1564 return checkCompatibleAbstracts(pos, t1, t2,
1565 types.makeCompoundType(t1, t2));
1566 }
1568 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1569 Type t1,
1570 Type t2,
1571 Type site) {
1572 return firstIncompatibility(pos, t1, t2, site) == null;
1573 }
1575 /** Return the first method which is defined with same args
1576 * but different return types in two given interfaces, or null if none
1577 * exists.
1578 * @param t1 The first type.
1579 * @param t2 The second type.
1580 * @param site The most derived type.
1581 * @returns symbol from t2 that conflicts with one in t1.
1582 */
1583 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1584 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1585 closure(t1, interfaces1);
1586 Map<TypeSymbol,Type> interfaces2;
1587 if (t1 == t2)
1588 interfaces2 = interfaces1;
1589 else
1590 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1592 for (Type t3 : interfaces1.values()) {
1593 for (Type t4 : interfaces2.values()) {
1594 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1595 if (s != null) return s;
1596 }
1597 }
1598 return null;
1599 }
1601 /** Compute all the supertypes of t, indexed by type symbol. */
1602 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1603 if (t.tag != CLASS) return;
1604 if (typeMap.put(t.tsym, t) == null) {
1605 closure(types.supertype(t), typeMap);
1606 for (Type i : types.interfaces(t))
1607 closure(i, typeMap);
1608 }
1609 }
1611 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1612 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1613 if (t.tag != CLASS) return;
1614 if (typesSkip.get(t.tsym) != null) return;
1615 if (typeMap.put(t.tsym, t) == null) {
1616 closure(types.supertype(t), typesSkip, typeMap);
1617 for (Type i : types.interfaces(t))
1618 closure(i, typesSkip, typeMap);
1619 }
1620 }
1622 /** Return the first method in t2 that conflicts with a method from t1. */
1623 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1624 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1625 Symbol s1 = e1.sym;
1626 Type st1 = null;
1627 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1628 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1629 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1630 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1631 Symbol s2 = e2.sym;
1632 if (s1 == s2) continue;
1633 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1634 if (st1 == null) st1 = types.memberType(t1, s1);
1635 Type st2 = types.memberType(t2, s2);
1636 if (types.overrideEquivalent(st1, st2)) {
1637 List<Type> tvars1 = st1.getTypeArguments();
1638 List<Type> tvars2 = st2.getTypeArguments();
1639 Type rt1 = st1.getReturnType();
1640 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1641 boolean compat =
1642 types.isSameType(rt1, rt2) ||
1643 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1644 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1645 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1646 checkCommonOverriderIn(s1,s2,site);
1647 if (!compat) {
1648 log.error(pos, "types.incompatible.diff.ret",
1649 t1, t2, s2.name +
1650 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
1651 return s2;
1652 }
1653 } else if (!checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
1654 log.error(pos,
1655 "name.clash.same.erasure.no.override",
1656 s1, s1.location(),
1657 s2, s2.location());
1658 return s2;
1659 }
1660 }
1661 }
1662 return null;
1663 }
1664 //WHERE
1665 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1666 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1667 Type st1 = types.memberType(site, s1);
1668 Type st2 = types.memberType(site, s2);
1669 closure(site, supertypes);
1670 for (Type t : supertypes.values()) {
1671 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1672 Symbol s3 = e.sym;
1673 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1674 Type st3 = types.memberType(site,s3);
1675 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1676 if (s3.owner == site.tsym) {
1677 return true;
1678 }
1679 List<Type> tvars1 = st1.getTypeArguments();
1680 List<Type> tvars2 = st2.getTypeArguments();
1681 List<Type> tvars3 = st3.getTypeArguments();
1682 Type rt1 = st1.getReturnType();
1683 Type rt2 = st2.getReturnType();
1684 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1685 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1686 boolean compat =
1687 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1688 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1689 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1690 if (compat)
1691 return true;
1692 }
1693 }
1694 }
1695 return false;
1696 }
1698 /** Check that a given method conforms with any method it overrides.
1699 * @param tree The tree from which positions are extracted
1700 * for errors.
1701 * @param m The overriding method.
1702 */
1703 void checkOverride(JCTree tree, MethodSymbol m) {
1704 ClassSymbol origin = (ClassSymbol)m.owner;
1705 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1706 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1707 log.error(tree.pos(), "enum.no.finalize");
1708 return;
1709 }
1710 for (Type t = origin.type; t.tag == CLASS;
1711 t = types.supertype(t)) {
1712 if (t != origin.type) {
1713 checkOverride(tree, t, origin, m);
1714 }
1715 for (Type t2 : types.interfaces(t)) {
1716 checkOverride(tree, t2, origin, m);
1717 }
1718 }
1719 }
1721 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
1722 TypeSymbol c = site.tsym;
1723 Scope.Entry e = c.members().lookup(m.name);
1724 while (e.scope != null) {
1725 if (m.overrides(e.sym, origin, types, false)) {
1726 if ((e.sym.flags() & ABSTRACT) == 0) {
1727 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1728 }
1729 }
1730 e = e.next();
1731 }
1732 }
1734 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
1735 if (s1.kind == MTH &&
1736 s1.isInheritedIn(origin, types) &&
1737 (s1.flags() & SYNTHETIC) == 0 &&
1738 !s2.isConstructor()) {
1739 Type er1 = s2.erasure(types);
1740 Type er2 = s1.erasure(types);
1741 if (types.isSameTypes(er1.getParameterTypes(),
1742 er2.getParameterTypes())) {
1743 return false;
1744 }
1745 }
1746 return true;
1747 }
1750 /** Check that all abstract members of given class have definitions.
1751 * @param pos Position to be used for error reporting.
1752 * @param c The class.
1753 */
1754 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1755 try {
1756 MethodSymbol undef = firstUndef(c, c);
1757 if (undef != null) {
1758 if ((c.flags() & ENUM) != 0 &&
1759 types.supertype(c.type).tsym == syms.enumSym &&
1760 (c.flags() & FINAL) == 0) {
1761 // add the ABSTRACT flag to an enum
1762 c.flags_field |= ABSTRACT;
1763 } else {
1764 MethodSymbol undef1 =
1765 new MethodSymbol(undef.flags(), undef.name,
1766 types.memberType(c.type, undef), undef.owner);
1767 log.error(pos, "does.not.override.abstract",
1768 c, undef1, undef1.location());
1769 }
1770 }
1771 } catch (CompletionFailure ex) {
1772 completionError(pos, ex);
1773 }
1774 }
1775 //where
1776 /** Return first abstract member of class `c' that is not defined
1777 * in `impl', null if there is none.
1778 */
1779 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1780 MethodSymbol undef = null;
1781 // Do not bother to search in classes that are not abstract,
1782 // since they cannot have abstract members.
1783 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1784 Scope s = c.members();
1785 for (Scope.Entry e = s.elems;
1786 undef == null && e != null;
1787 e = e.sibling) {
1788 if (e.sym.kind == MTH &&
1789 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1790 MethodSymbol absmeth = (MethodSymbol)e.sym;
1791 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1792 if (implmeth == null || implmeth == absmeth)
1793 undef = absmeth;
1794 }
1795 }
1796 if (undef == null) {
1797 Type st = types.supertype(c.type);
1798 if (st.tag == CLASS)
1799 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1800 }
1801 for (List<Type> l = types.interfaces(c.type);
1802 undef == null && l.nonEmpty();
1803 l = l.tail) {
1804 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1805 }
1806 }
1807 return undef;
1808 }
1810 void checkNonCyclicDecl(JCClassDecl tree) {
1811 CycleChecker cc = new CycleChecker();
1812 cc.scan(tree);
1813 if (!cc.errorFound && !cc.partialCheck) {
1814 tree.sym.flags_field |= ACYCLIC;
1815 }
1816 }
1818 class CycleChecker extends TreeScanner {
1820 List<Symbol> seenClasses = List.nil();
1821 boolean errorFound = false;
1822 boolean partialCheck = false;
1824 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
1825 if (sym != null && sym.kind == TYP) {
1826 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
1827 if (classEnv != null) {
1828 DiagnosticSource prevSource = log.currentSource();
1829 try {
1830 log.useSource(classEnv.toplevel.sourcefile);
1831 scan(classEnv.tree);
1832 }
1833 finally {
1834 log.useSource(prevSource.getFile());
1835 }
1836 } else if (sym.kind == TYP) {
1837 checkClass(pos, sym, List.<JCTree>nil());
1838 }
1839 } else {
1840 //not completed yet
1841 partialCheck = true;
1842 }
1843 }
1845 @Override
1846 public void visitSelect(JCFieldAccess tree) {
1847 super.visitSelect(tree);
1848 checkSymbol(tree.pos(), tree.sym);
1849 }
1851 @Override
1852 public void visitIdent(JCIdent tree) {
1853 checkSymbol(tree.pos(), tree.sym);
1854 }
1856 @Override
1857 public void visitTypeApply(JCTypeApply tree) {
1858 scan(tree.clazz);
1859 }
1861 @Override
1862 public void visitTypeArray(JCArrayTypeTree tree) {
1863 scan(tree.elemtype);
1864 }
1866 @Override
1867 public void visitClassDef(JCClassDecl tree) {
1868 List<JCTree> supertypes = List.nil();
1869 if (tree.getExtendsClause() != null) {
1870 supertypes = supertypes.prepend(tree.getExtendsClause());
1871 }
1872 if (tree.getImplementsClause() != null) {
1873 for (JCTree intf : tree.getImplementsClause()) {
1874 supertypes = supertypes.prepend(intf);
1875 }
1876 }
1877 checkClass(tree.pos(), tree.sym, supertypes);
1878 }
1880 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
1881 if ((c.flags_field & ACYCLIC) != 0)
1882 return;
1883 if (seenClasses.contains(c)) {
1884 errorFound = true;
1885 noteCyclic(pos, (ClassSymbol)c);
1886 } else if (!c.type.isErroneous()) {
1887 try {
1888 seenClasses = seenClasses.prepend(c);
1889 if (c.type.tag == CLASS) {
1890 if (supertypes.nonEmpty()) {
1891 scan(supertypes);
1892 }
1893 else {
1894 ClassType ct = (ClassType)c.type;
1895 if (ct.supertype_field == null ||
1896 ct.interfaces_field == null) {
1897 //not completed yet
1898 partialCheck = true;
1899 return;
1900 }
1901 checkSymbol(pos, ct.supertype_field.tsym);
1902 for (Type intf : ct.interfaces_field) {
1903 checkSymbol(pos, intf.tsym);
1904 }
1905 }
1906 if (c.owner.kind == TYP) {
1907 checkSymbol(pos, c.owner);
1908 }
1909 }
1910 } finally {
1911 seenClasses = seenClasses.tail;
1912 }
1913 }
1914 }
1915 }
1917 /** Check for cyclic references. Issue an error if the
1918 * symbol of the type referred to has a LOCKED flag set.
1919 *
1920 * @param pos Position to be used for error reporting.
1921 * @param t The type referred to.
1922 */
1923 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1924 checkNonCyclicInternal(pos, t);
1925 }
1928 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1929 checkNonCyclic1(pos, t, List.<TypeVar>nil());
1930 }
1932 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
1933 final TypeVar tv;
1934 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1935 return;
1936 if (seen.contains(t)) {
1937 tv = (TypeVar)t;
1938 tv.bound = types.createErrorType(t);
1939 log.error(pos, "cyclic.inheritance", t);
1940 } else if (t.tag == TYPEVAR) {
1941 tv = (TypeVar)t;
1942 seen = seen.prepend(tv);
1943 for (Type b : types.getBounds(tv))
1944 checkNonCyclic1(pos, b, seen);
1945 }
1946 }
1948 /** Check for cyclic references. Issue an error if the
1949 * symbol of the type referred to has a LOCKED flag set.
1950 *
1951 * @param pos Position to be used for error reporting.
1952 * @param t The type referred to.
1953 * @returns True if the check completed on all attributed classes
1954 */
1955 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1956 boolean complete = true; // was the check complete?
1957 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1958 Symbol c = t.tsym;
1959 if ((c.flags_field & ACYCLIC) != 0) return true;
1961 if ((c.flags_field & LOCKED) != 0) {
1962 noteCyclic(pos, (ClassSymbol)c);
1963 } else if (!c.type.isErroneous()) {
1964 try {
1965 c.flags_field |= LOCKED;
1966 if (c.type.tag == CLASS) {
1967 ClassType clazz = (ClassType)c.type;
1968 if (clazz.interfaces_field != null)
1969 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1970 complete &= checkNonCyclicInternal(pos, l.head);
1971 if (clazz.supertype_field != null) {
1972 Type st = clazz.supertype_field;
1973 if (st != null && st.tag == CLASS)
1974 complete &= checkNonCyclicInternal(pos, st);
1975 }
1976 if (c.owner.kind == TYP)
1977 complete &= checkNonCyclicInternal(pos, c.owner.type);
1978 }
1979 } finally {
1980 c.flags_field &= ~LOCKED;
1981 }
1982 }
1983 if (complete)
1984 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1985 if (complete) c.flags_field |= ACYCLIC;
1986 return complete;
1987 }
1989 /** Note that we found an inheritance cycle. */
1990 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1991 log.error(pos, "cyclic.inheritance", c);
1992 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1993 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
1994 Type st = types.supertype(c.type);
1995 if (st.tag == CLASS)
1996 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
1997 c.type = types.createErrorType(c, c.type);
1998 c.flags_field |= ACYCLIC;
1999 }
2001 /** Check that all methods which implement some
2002 * method conform to the method they implement.
2003 * @param tree The class definition whose members are checked.
2004 */
2005 void checkImplementations(JCClassDecl tree) {
2006 checkImplementations(tree, tree.sym);
2007 }
2008 //where
2009 /** Check that all methods which implement some
2010 * method in `ic' conform to the method they implement.
2011 */
2012 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
2013 ClassSymbol origin = tree.sym;
2014 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2015 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2016 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
2017 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
2018 if (e.sym.kind == MTH &&
2019 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2020 MethodSymbol absmeth = (MethodSymbol)e.sym;
2021 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2022 if (implmeth != null && implmeth != absmeth &&
2023 (implmeth.owner.flags() & INTERFACE) ==
2024 (origin.flags() & INTERFACE)) {
2025 // don't check if implmeth is in a class, yet
2026 // origin is an interface. This case arises only
2027 // if implmeth is declared in Object. The reason is
2028 // that interfaces really don't inherit from
2029 // Object it's just that the compiler represents
2030 // things that way.
2031 checkOverride(tree, implmeth, absmeth, origin);
2032 }
2033 }
2034 }
2035 }
2036 }
2037 }
2039 /** Check that all abstract methods implemented by a class are
2040 * mutually compatible.
2041 * @param pos Position to be used for error reporting.
2042 * @param c The class whose interfaces are checked.
2043 */
2044 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2045 List<Type> supertypes = types.interfaces(c);
2046 Type supertype = types.supertype(c);
2047 if (supertype.tag == CLASS &&
2048 (supertype.tsym.flags() & ABSTRACT) != 0)
2049 supertypes = supertypes.prepend(supertype);
2050 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2051 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
2052 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2053 return;
2054 for (List<Type> m = supertypes; m != l; m = m.tail)
2055 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2056 return;
2057 }
2058 checkCompatibleConcretes(pos, c);
2059 }
2061 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2062 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
2063 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
2064 // VM allows methods and variables with differing types
2065 if (sym.kind == e.sym.kind &&
2066 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
2067 sym != e.sym &&
2068 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
2069 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
2070 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
2071 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
2072 return;
2073 }
2074 }
2075 }
2076 }
2078 /** Check that all non-override equivalent methods accessible from 'site'
2079 * are mutually compatible (JLS 8.4.8/9.4.1).
2080 *
2081 * @param pos Position to be used for error reporting.
2082 * @param site The class whose methods are checked.
2083 * @param sym The method symbol to be checked.
2084 */
2085 void checkClashes(DiagnosticPosition pos, Type site, Symbol sym) {
2086 List<Type> supertypes = types.closure(site);
2087 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2088 for (List<Type> m = supertypes; m.nonEmpty(); m = m.tail) {
2089 checkClashes(pos, l.head, m.head, site, sym);
2090 }
2091 }
2092 }
2094 /** Reports an error whenever 'sym' seen as a member of type 't1' clashes with
2095 * some unrelated method defined in 't2'.
2096 */
2097 private void checkClashes(DiagnosticPosition pos, Type t1, Type t2, Type site, Symbol s1) {
2098 ClashFilter cf = new ClashFilter(site);
2099 s1 = ((MethodSymbol)s1).implementedIn(t1.tsym, types);
2100 if (s1 == null) return;
2101 Type st1 = types.memberType(site, s1);
2102 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name, cf); e2.scope != null; e2 = e2.next(cf)) {
2103 Symbol s2 = e2.sym;
2104 if (s1 == s2) continue;
2105 Type st2 = types.memberType(site, s2);
2106 if (!types.overrideEquivalent(st1, st2) &&
2107 !checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
2108 log.error(pos,
2109 "name.clash.same.erasure.no.override",
2110 s1, s1.location(),
2111 s2, s2.location());
2112 }
2113 }
2114 }
2115 //where
2116 private class ClashFilter implements Filter<Symbol> {
2118 Type site;
2120 ClashFilter(Type site) {
2121 this.site = site;
2122 }
2124 public boolean accepts(Symbol s) {
2125 return s.kind == MTH &&
2126 (s.flags() & (SYNTHETIC | CLASH)) == 0 &&
2127 s.isInheritedIn(site.tsym, types) &&
2128 !s.isConstructor();
2129 }
2130 }
2132 /** Report a conflict between a user symbol and a synthetic symbol.
2133 */
2134 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2135 if (!sym.type.isErroneous()) {
2136 if (warnOnSyntheticConflicts) {
2137 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
2138 }
2139 else {
2140 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2141 }
2142 }
2143 }
2145 /** Check that class c does not implement directly or indirectly
2146 * the same parameterized interface with two different argument lists.
2147 * @param pos Position to be used for error reporting.
2148 * @param type The type whose interfaces are checked.
2149 */
2150 void checkClassBounds(DiagnosticPosition pos, Type type) {
2151 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2152 }
2153 //where
2154 /** Enter all interfaces of type `type' into the hash table `seensofar'
2155 * with their class symbol as key and their type as value. Make
2156 * sure no class is entered with two different types.
2157 */
2158 void checkClassBounds(DiagnosticPosition pos,
2159 Map<TypeSymbol,Type> seensofar,
2160 Type type) {
2161 if (type.isErroneous()) return;
2162 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2163 Type it = l.head;
2164 Type oldit = seensofar.put(it.tsym, it);
2165 if (oldit != null) {
2166 List<Type> oldparams = oldit.allparams();
2167 List<Type> newparams = it.allparams();
2168 if (!types.containsTypeEquivalent(oldparams, newparams))
2169 log.error(pos, "cant.inherit.diff.arg",
2170 it.tsym, Type.toString(oldparams),
2171 Type.toString(newparams));
2172 }
2173 checkClassBounds(pos, seensofar, it);
2174 }
2175 Type st = types.supertype(type);
2176 if (st != null) checkClassBounds(pos, seensofar, st);
2177 }
2179 /** Enter interface into into set.
2180 * If it existed already, issue a "repeated interface" error.
2181 */
2182 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2183 if (its.contains(it))
2184 log.error(pos, "repeated.interface");
2185 else {
2186 its.add(it);
2187 }
2188 }
2190 /* *************************************************************************
2191 * Check annotations
2192 **************************************************************************/
2194 /**
2195 * Recursively validate annotations values
2196 */
2197 void validateAnnotationTree(JCTree tree) {
2198 class AnnotationValidator extends TreeScanner {
2199 @Override
2200 public void visitAnnotation(JCAnnotation tree) {
2201 super.visitAnnotation(tree);
2202 validateAnnotation(tree);
2203 }
2204 }
2205 tree.accept(new AnnotationValidator());
2206 }
2208 /** Annotation types are restricted to primitives, String, an
2209 * enum, an annotation, Class, Class<?>, Class<? extends
2210 * Anything>, arrays of the preceding.
2211 */
2212 void validateAnnotationType(JCTree restype) {
2213 // restype may be null if an error occurred, so don't bother validating it
2214 if (restype != null) {
2215 validateAnnotationType(restype.pos(), restype.type);
2216 }
2217 }
2219 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2220 if (type.isPrimitive()) return;
2221 if (types.isSameType(type, syms.stringType)) return;
2222 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2223 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2224 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
2225 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2226 validateAnnotationType(pos, types.elemtype(type));
2227 return;
2228 }
2229 log.error(pos, "invalid.annotation.member.type");
2230 }
2232 /**
2233 * "It is also a compile-time error if any method declared in an
2234 * annotation type has a signature that is override-equivalent to
2235 * that of any public or protected method declared in class Object
2236 * or in the interface annotation.Annotation."
2237 *
2238 * @jls3 9.6 Annotation Types
2239 */
2240 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2241 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
2242 Scope s = sup.tsym.members();
2243 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
2244 if (e.sym.kind == MTH &&
2245 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2246 types.overrideEquivalent(m.type, e.sym.type))
2247 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
2248 }
2249 }
2250 }
2252 /** Check the annotations of a symbol.
2253 */
2254 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2255 if (skipAnnotations) return;
2256 for (JCAnnotation a : annotations)
2257 validateAnnotation(a, s);
2258 }
2260 /** Check an annotation of a symbol.
2261 */
2262 public void validateAnnotation(JCAnnotation a, Symbol s) {
2263 validateAnnotationTree(a);
2265 if (!annotationApplicable(a, s))
2266 log.error(a.pos(), "annotation.type.not.applicable");
2268 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2269 if (!isOverrider(s))
2270 log.error(a.pos(), "method.does.not.override.superclass");
2271 }
2272 }
2274 /** Is s a method symbol that overrides a method in a superclass? */
2275 boolean isOverrider(Symbol s) {
2276 if (s.kind != MTH || s.isStatic())
2277 return false;
2278 MethodSymbol m = (MethodSymbol)s;
2279 TypeSymbol owner = (TypeSymbol)m.owner;
2280 for (Type sup : types.closure(owner.type)) {
2281 if (sup == owner.type)
2282 continue; // skip "this"
2283 Scope scope = sup.tsym.members();
2284 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2285 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2286 return true;
2287 }
2288 }
2289 return false;
2290 }
2292 /** Is the annotation applicable to the symbol? */
2293 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2294 Attribute.Compound atTarget =
2295 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2296 if (atTarget == null) return true;
2297 Attribute atValue = atTarget.member(names.value);
2298 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2299 Attribute.Array arr = (Attribute.Array) atValue;
2300 for (Attribute app : arr.values) {
2301 if (!(app instanceof Attribute.Enum)) return true; // recovery
2302 Attribute.Enum e = (Attribute.Enum) app;
2303 if (e.value.name == names.TYPE)
2304 { if (s.kind == TYP) return true; }
2305 else if (e.value.name == names.FIELD)
2306 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2307 else if (e.value.name == names.METHOD)
2308 { if (s.kind == MTH && !s.isConstructor()) return true; }
2309 else if (e.value.name == names.PARAMETER)
2310 { if (s.kind == VAR &&
2311 s.owner.kind == MTH &&
2312 (s.flags() & PARAMETER) != 0)
2313 return true;
2314 }
2315 else if (e.value.name == names.CONSTRUCTOR)
2316 { if (s.kind == MTH && s.isConstructor()) return true; }
2317 else if (e.value.name == names.LOCAL_VARIABLE)
2318 { if (s.kind == VAR && s.owner.kind == MTH &&
2319 (s.flags() & PARAMETER) == 0)
2320 return true;
2321 }
2322 else if (e.value.name == names.ANNOTATION_TYPE)
2323 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2324 return true;
2325 }
2326 else if (e.value.name == names.PACKAGE)
2327 { if (s.kind == PCK) return true; }
2328 else if (e.value.name == names.TYPE_USE)
2329 { if (s.kind == TYP ||
2330 s.kind == VAR ||
2331 (s.kind == MTH && !s.isConstructor() &&
2332 s.type.getReturnType().tag != VOID))
2333 return true;
2334 }
2335 else
2336 return true; // recovery
2337 }
2338 return false;
2339 }
2341 /** Check an annotation value.
2342 */
2343 public void validateAnnotation(JCAnnotation a) {
2344 if (a.type.isErroneous()) return;
2346 // collect an inventory of the members (sorted alphabetically)
2347 Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
2348 public int compare(Symbol t, Symbol t1) {
2349 return t.name.compareTo(t1.name);
2350 }
2351 });
2352 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2353 e != null;
2354 e = e.sibling)
2355 if (e.sym.kind == MTH)
2356 members.add((MethodSymbol) e.sym);
2358 // count them off as they're annotated
2359 for (JCTree arg : a.args) {
2360 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
2361 JCAssign assign = (JCAssign) arg;
2362 Symbol m = TreeInfo.symbol(assign.lhs);
2363 if (m == null || m.type.isErroneous()) continue;
2364 if (!members.remove(m))
2365 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2366 m.name, a.type);
2367 }
2369 // all the remaining ones better have default values
2370 ListBuffer<Name> missingDefaults = ListBuffer.lb();
2371 for (MethodSymbol m : members) {
2372 if (m.defaultValue == null && !m.type.isErroneous()) {
2373 missingDefaults.append(m.name);
2374 }
2375 }
2376 if (missingDefaults.nonEmpty()) {
2377 String key = (missingDefaults.size() > 1)
2378 ? "annotation.missing.default.value.1"
2379 : "annotation.missing.default.value";
2380 log.error(a.pos(), key, a.type, missingDefaults);
2381 }
2383 // special case: java.lang.annotation.Target must not have
2384 // repeated values in its value member
2385 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2386 a.args.tail == null)
2387 return;
2389 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
2390 JCAssign assign = (JCAssign) a.args.head;
2391 Symbol m = TreeInfo.symbol(assign.lhs);
2392 if (m.name != names.value) return;
2393 JCTree rhs = assign.rhs;
2394 if (rhs.getTag() != JCTree.NEWARRAY) return;
2395 JCNewArray na = (JCNewArray) rhs;
2396 Set<Symbol> targets = new HashSet<Symbol>();
2397 for (JCTree elem : na.elems) {
2398 if (!targets.add(TreeInfo.symbol(elem))) {
2399 log.error(elem.pos(), "repeated.annotation.target");
2400 }
2401 }
2402 }
2404 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2405 if (allowAnnotations &&
2406 lint.isEnabled(LintCategory.DEP_ANN) &&
2407 (s.flags() & DEPRECATED) != 0 &&
2408 !syms.deprecatedType.isErroneous() &&
2409 s.attribute(syms.deprecatedType.tsym) == null) {
2410 log.warning(LintCategory.DEP_ANN,
2411 pos, "missing.deprecated.annotation");
2412 }
2413 }
2415 /* *************************************************************************
2416 * Check for recursive annotation elements.
2417 **************************************************************************/
2419 /** Check for cycles in the graph of annotation elements.
2420 */
2421 void checkNonCyclicElements(JCClassDecl tree) {
2422 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2423 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2424 try {
2425 tree.sym.flags_field |= LOCKED;
2426 for (JCTree def : tree.defs) {
2427 if (def.getTag() != JCTree.METHODDEF) continue;
2428 JCMethodDecl meth = (JCMethodDecl)def;
2429 checkAnnotationResType(meth.pos(), meth.restype.type);
2430 }
2431 } finally {
2432 tree.sym.flags_field &= ~LOCKED;
2433 tree.sym.flags_field |= ACYCLIC_ANN;
2434 }
2435 }
2437 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2438 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2439 return;
2440 if ((tsym.flags_field & LOCKED) != 0) {
2441 log.error(pos, "cyclic.annotation.element");
2442 return;
2443 }
2444 try {
2445 tsym.flags_field |= LOCKED;
2446 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2447 Symbol s = e.sym;
2448 if (s.kind != Kinds.MTH)
2449 continue;
2450 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2451 }
2452 } finally {
2453 tsym.flags_field &= ~LOCKED;
2454 tsym.flags_field |= ACYCLIC_ANN;
2455 }
2456 }
2458 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2459 switch (type.tag) {
2460 case TypeTags.CLASS:
2461 if ((type.tsym.flags() & ANNOTATION) != 0)
2462 checkNonCyclicElementsInternal(pos, type.tsym);
2463 break;
2464 case TypeTags.ARRAY:
2465 checkAnnotationResType(pos, types.elemtype(type));
2466 break;
2467 default:
2468 break; // int etc
2469 }
2470 }
2472 /* *************************************************************************
2473 * Check for cycles in the constructor call graph.
2474 **************************************************************************/
2476 /** Check for cycles in the graph of constructors calling other
2477 * constructors.
2478 */
2479 void checkCyclicConstructors(JCClassDecl tree) {
2480 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2482 // enter each constructor this-call into the map
2483 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2484 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2485 if (app == null) continue;
2486 JCMethodDecl meth = (JCMethodDecl) l.head;
2487 if (TreeInfo.name(app.meth) == names._this) {
2488 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2489 } else {
2490 meth.sym.flags_field |= ACYCLIC;
2491 }
2492 }
2494 // Check for cycles in the map
2495 Symbol[] ctors = new Symbol[0];
2496 ctors = callMap.keySet().toArray(ctors);
2497 for (Symbol caller : ctors) {
2498 checkCyclicConstructor(tree, caller, callMap);
2499 }
2500 }
2502 /** Look in the map to see if the given constructor is part of a
2503 * call cycle.
2504 */
2505 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2506 Map<Symbol,Symbol> callMap) {
2507 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2508 if ((ctor.flags_field & LOCKED) != 0) {
2509 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2510 "recursive.ctor.invocation");
2511 } else {
2512 ctor.flags_field |= LOCKED;
2513 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2514 ctor.flags_field &= ~LOCKED;
2515 }
2516 ctor.flags_field |= ACYCLIC;
2517 }
2518 }
2520 /* *************************************************************************
2521 * Miscellaneous
2522 **************************************************************************/
2524 /**
2525 * Return the opcode of the operator but emit an error if it is an
2526 * error.
2527 * @param pos position for error reporting.
2528 * @param operator an operator
2529 * @param tag a tree tag
2530 * @param left type of left hand side
2531 * @param right type of right hand side
2532 */
2533 int checkOperator(DiagnosticPosition pos,
2534 OperatorSymbol operator,
2535 int tag,
2536 Type left,
2537 Type right) {
2538 if (operator.opcode == ByteCodes.error) {
2539 log.error(pos,
2540 "operator.cant.be.applied",
2541 treeinfo.operatorName(tag),
2542 List.of(left, right));
2543 }
2544 return operator.opcode;
2545 }
2548 /**
2549 * Check for division by integer constant zero
2550 * @param pos Position for error reporting.
2551 * @param operator The operator for the expression
2552 * @param operand The right hand operand for the expression
2553 */
2554 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2555 if (operand.constValue() != null
2556 && lint.isEnabled(LintCategory.DIVZERO)
2557 && operand.tag <= LONG
2558 && ((Number) (operand.constValue())).longValue() == 0) {
2559 int opc = ((OperatorSymbol)operator).opcode;
2560 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2561 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2562 log.warning(LintCategory.DIVZERO, pos, "div.zero");
2563 }
2564 }
2565 }
2567 /**
2568 * Check for empty statements after if
2569 */
2570 void checkEmptyIf(JCIf tree) {
2571 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(LintCategory.EMPTY))
2572 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
2573 }
2575 /** Check that symbol is unique in given scope.
2576 * @param pos Position for error reporting.
2577 * @param sym The symbol.
2578 * @param s The scope.
2579 */
2580 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2581 if (sym.type.isErroneous())
2582 return true;
2583 if (sym.owner.name == names.any) return false;
2584 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2585 if (sym != e.sym &&
2586 (e.sym.flags() & CLASH) == 0 &&
2587 sym.kind == e.sym.kind &&
2588 sym.name != names.error &&
2589 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2590 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
2591 varargsDuplicateError(pos, sym, e.sym);
2592 return true;
2593 } else if (sym.kind == MTH && !hasSameSignature(sym.type, e.sym.type)) {
2594 duplicateErasureError(pos, sym, e.sym);
2595 sym.flags_field |= CLASH;
2596 return true;
2597 } else {
2598 duplicateError(pos, e.sym);
2599 return false;
2600 }
2601 }
2602 }
2603 return true;
2604 }
2605 //where
2606 boolean hasSameSignature(Type mt1, Type mt2) {
2607 if (mt1.tag == FORALL && mt2.tag == FORALL) {
2608 ForAll fa1 = (ForAll)mt1;
2609 ForAll fa2 = (ForAll)mt2;
2610 mt2 = types.subst(fa2, fa2.tvars, fa1.tvars);
2611 }
2612 return types.hasSameArgs(mt1.asMethodType(), mt2.asMethodType());
2613 }
2615 /** Report duplicate declaration error.
2616 */
2617 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2618 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2619 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2620 }
2621 }
2623 /** Check that single-type import is not already imported or top-level defined,
2624 * but make an exception for two single-type imports which denote the same type.
2625 * @param pos Position for error reporting.
2626 * @param sym The symbol.
2627 * @param s The scope
2628 */
2629 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2630 return checkUniqueImport(pos, sym, s, false);
2631 }
2633 /** Check that static single-type import is not already imported or top-level defined,
2634 * but make an exception for two single-type imports which denote the same type.
2635 * @param pos Position for error reporting.
2636 * @param sym The symbol.
2637 * @param s The scope
2638 * @param staticImport Whether or not this was a static import
2639 */
2640 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2641 return checkUniqueImport(pos, sym, s, true);
2642 }
2644 /** Check that single-type import is not already imported or top-level defined,
2645 * but make an exception for two single-type imports which denote the same type.
2646 * @param pos Position for error reporting.
2647 * @param sym The symbol.
2648 * @param s The scope.
2649 * @param staticImport Whether or not this was a static import
2650 */
2651 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2652 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2653 // is encountered class entered via a class declaration?
2654 boolean isClassDecl = e.scope == s;
2655 if ((isClassDecl || sym != e.sym) &&
2656 sym.kind == e.sym.kind &&
2657 sym.name != names.error) {
2658 if (!e.sym.type.isErroneous()) {
2659 String what = e.sym.toString();
2660 if (!isClassDecl) {
2661 if (staticImport)
2662 log.error(pos, "already.defined.static.single.import", what);
2663 else
2664 log.error(pos, "already.defined.single.import", what);
2665 }
2666 else if (sym != e.sym)
2667 log.error(pos, "already.defined.this.unit", what);
2668 }
2669 return false;
2670 }
2671 }
2672 return true;
2673 }
2675 /** Check that a qualified name is in canonical form (for import decls).
2676 */
2677 public void checkCanonical(JCTree tree) {
2678 if (!isCanonical(tree))
2679 log.error(tree.pos(), "import.requires.canonical",
2680 TreeInfo.symbol(tree));
2681 }
2682 // where
2683 private boolean isCanonical(JCTree tree) {
2684 while (tree.getTag() == JCTree.SELECT) {
2685 JCFieldAccess s = (JCFieldAccess) tree;
2686 if (s.sym.owner != TreeInfo.symbol(s.selected))
2687 return false;
2688 tree = s.selected;
2689 }
2690 return true;
2691 }
2693 private class ConversionWarner extends Warner {
2694 final String uncheckedKey;
2695 final Type found;
2696 final Type expected;
2697 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
2698 super(pos);
2699 this.uncheckedKey = uncheckedKey;
2700 this.found = found;
2701 this.expected = expected;
2702 }
2704 @Override
2705 public void warn(LintCategory lint) {
2706 boolean warned = this.warned;
2707 super.warn(lint);
2708 if (warned) return; // suppress redundant diagnostics
2709 switch (lint) {
2710 case UNCHECKED:
2711 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
2712 break;
2713 case VARARGS:
2714 if (method != null &&
2715 method.attribute(syms.trustMeType.tsym) != null &&
2716 isTrustMeAllowedOnMethod(method) &&
2717 !types.isReifiable(method.type.getParameterTypes().last())) {
2718 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
2719 }
2720 break;
2721 default:
2722 throw new AssertionError("Unexpected lint: " + lint);
2723 }
2724 }
2725 }
2727 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2728 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2729 }
2731 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2732 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2733 }
2734 }