Thu, 03 Jun 2010 17:14:20 -0700
6955264: add option to suppress Abort in Check.completionError
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2009, 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 /** Type checking helper class for the attribution phase.
49 *
50 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
51 * you write code that depends on this, you do so at your own risk.
52 * This code and its internal interfaces are subject to change or
53 * deletion without notice.</b>
54 */
55 public class Check {
56 protected static final Context.Key<Check> checkKey =
57 new Context.Key<Check>();
59 private final Names names;
60 private final Log log;
61 private final Symtab syms;
62 private final Infer infer;
63 private final Types types;
64 private final JCDiagnostic.Factory diags;
65 private final boolean skipAnnotations;
66 private boolean warnOnSyntheticConflicts;
67 private boolean suppressAbortOnBadClassFile;
68 private final TreeInfo treeinfo;
70 // The set of lint options currently in effect. It is initialized
71 // from the context, and then is set/reset as needed by Attr as it
72 // visits all the various parts of the trees during attribution.
73 private Lint lint;
75 public static Check instance(Context context) {
76 Check instance = context.get(checkKey);
77 if (instance == null)
78 instance = new Check(context);
79 return instance;
80 }
82 protected Check(Context context) {
83 context.put(checkKey, this);
85 names = Names.instance(context);
86 log = Log.instance(context);
87 syms = Symtab.instance(context);
88 infer = Infer.instance(context);
89 this.types = Types.instance(context);
90 diags = JCDiagnostic.Factory.instance(context);
91 Options options = Options.instance(context);
92 lint = Lint.instance(context);
93 treeinfo = TreeInfo.instance(context);
95 Source source = Source.instance(context);
96 allowGenerics = source.allowGenerics();
97 allowAnnotations = source.allowAnnotations();
98 allowCovariantReturns = source.allowCovariantReturns();
99 complexInference = options.get("-complexinference") != null;
100 skipAnnotations = options.get("skipAnnotations") != null;
101 warnOnSyntheticConflicts = options.get("warnOnSyntheticConflicts") != null;
102 suppressAbortOnBadClassFile = options.get("suppressAbortOnBadClassFile") != null;
104 Target target = Target.instance(context);
105 syntheticNameChar = target.syntheticNameChar();
107 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
108 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
109 boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
110 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
112 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
113 enforceMandatoryWarnings, "deprecated");
114 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
115 enforceMandatoryWarnings, "unchecked");
116 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
117 enforceMandatoryWarnings, "sunapi");
118 }
120 /** Switch: generics enabled?
121 */
122 boolean allowGenerics;
124 /** Switch: annotations enabled?
125 */
126 boolean allowAnnotations;
128 /** Switch: covariant returns enabled?
129 */
130 boolean allowCovariantReturns;
132 /** Switch: -complexinference option set?
133 */
134 boolean complexInference;
136 /** Character for synthetic names
137 */
138 char syntheticNameChar;
140 /** A table mapping flat names of all compiled classes in this run to their
141 * symbols; maintained from outside.
142 */
143 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
145 /** A handler for messages about deprecated usage.
146 */
147 private MandatoryWarningHandler deprecationHandler;
149 /** A handler for messages about unchecked or unsafe usage.
150 */
151 private MandatoryWarningHandler uncheckedHandler;
153 /** A handler for messages about using Sun proprietary API.
154 */
155 private MandatoryWarningHandler sunApiHandler;
157 /* *************************************************************************
158 * Errors and Warnings
159 **************************************************************************/
161 Lint setLint(Lint newLint) {
162 Lint prev = lint;
163 lint = newLint;
164 return prev;
165 }
167 /** Warn about deprecated symbol.
168 * @param pos Position to be used for error reporting.
169 * @param sym The deprecated symbol.
170 */
171 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
172 if (!lint.isSuppressed(LintCategory.DEPRECATION))
173 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
174 }
176 /** Warn about unchecked operation.
177 * @param pos Position to be used for error reporting.
178 * @param msg A string describing the problem.
179 */
180 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
181 if (!lint.isSuppressed(LintCategory.UNCHECKED))
182 uncheckedHandler.report(pos, msg, args);
183 }
185 /** Warn about using Sun proprietary API.
186 * @param pos Position to be used for error reporting.
187 * @param msg A string describing the problem.
188 */
189 public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
190 if (!lint.isSuppressed(LintCategory.SUNAPI))
191 sunApiHandler.report(pos, msg, args);
192 }
194 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
195 if (lint.isEnabled(LintCategory.STATIC))
196 log.warning(pos, msg, args);
197 }
199 /**
200 * Report any deferred diagnostics.
201 */
202 public void reportDeferredDiagnostics() {
203 deprecationHandler.reportDeferredDiagnostic();
204 uncheckedHandler.reportDeferredDiagnostic();
205 sunApiHandler.reportDeferredDiagnostic();
206 }
209 /** Report a failure to complete a class.
210 * @param pos Position to be used for error reporting.
211 * @param ex The failure to report.
212 */
213 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
214 log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
215 if (ex instanceof ClassReader.BadClassFile
216 && !suppressAbortOnBadClassFile) throw new Abort();
217 else return syms.errType;
218 }
220 /** Report a type error.
221 * @param pos Position to be used for error reporting.
222 * @param problem A string describing the error.
223 * @param found The type that was found.
224 * @param req The type that was required.
225 */
226 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
227 log.error(pos, "prob.found.req",
228 problem, found, req);
229 return types.createErrorType(found);
230 }
232 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
233 log.error(pos, "prob.found.req.1", problem, found, req, explanation);
234 return types.createErrorType(found);
235 }
237 /** Report an error that wrong type tag was found.
238 * @param pos Position to be used for error reporting.
239 * @param required An internationalized string describing the type tag
240 * required.
241 * @param found The type that was found.
242 */
243 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
244 // this error used to be raised by the parser,
245 // but has been delayed to this point:
246 if (found instanceof Type && ((Type)found).tag == VOID) {
247 log.error(pos, "illegal.start.of.type");
248 return syms.errType;
249 }
250 log.error(pos, "type.found.req", found, required);
251 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
252 }
254 /** Report an error that symbol cannot be referenced before super
255 * has been called.
256 * @param pos Position to be used for error reporting.
257 * @param sym The referenced symbol.
258 */
259 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
260 log.error(pos, "cant.ref.before.ctor.called", sym);
261 }
263 /** Report duplicate declaration error.
264 */
265 void duplicateError(DiagnosticPosition pos, Symbol sym) {
266 if (!sym.type.isErroneous()) {
267 log.error(pos, "already.defined", sym, sym.location());
268 }
269 }
271 /** Report array/varargs duplicate declaration
272 */
273 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
274 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
275 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
276 }
277 }
279 /* ************************************************************************
280 * duplicate declaration checking
281 *************************************************************************/
283 /** Check that variable does not hide variable with same name in
284 * immediately enclosing local scope.
285 * @param pos Position for error reporting.
286 * @param v The symbol.
287 * @param s The scope.
288 */
289 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
290 if (s.next != null) {
291 for (Scope.Entry e = s.next.lookup(v.name);
292 e.scope != null && e.sym.owner == v.owner;
293 e = e.next()) {
294 if (e.sym.kind == VAR &&
295 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
296 v.name != names.error) {
297 duplicateError(pos, e.sym);
298 return;
299 }
300 }
301 }
302 }
304 /** Check that a class or interface does not hide a class or
305 * interface with same name in immediately enclosing local scope.
306 * @param pos Position for error reporting.
307 * @param c The symbol.
308 * @param s The scope.
309 */
310 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
311 if (s.next != null) {
312 for (Scope.Entry e = s.next.lookup(c.name);
313 e.scope != null && e.sym.owner == c.owner;
314 e = e.next()) {
315 if (e.sym.kind == TYP &&
316 (e.sym.owner.kind & (VAR | MTH)) != 0 &&
317 c.name != names.error) {
318 duplicateError(pos, e.sym);
319 return;
320 }
321 }
322 }
323 }
325 /** Check that class does not have the same name as one of
326 * its enclosing classes, or as a class defined in its enclosing scope.
327 * return true if class is unique in its enclosing scope.
328 * @param pos Position for error reporting.
329 * @param name The class name.
330 * @param s The enclosing scope.
331 */
332 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
333 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
334 if (e.sym.kind == TYP && e.sym.name != names.error) {
335 duplicateError(pos, e.sym);
336 return false;
337 }
338 }
339 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
340 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
341 duplicateError(pos, sym);
342 return true;
343 }
344 }
345 return true;
346 }
348 /* *************************************************************************
349 * Class name generation
350 **************************************************************************/
352 /** Return name of local class.
353 * This is of the form <enclClass> $ n <classname>
354 * where
355 * enclClass is the flat name of the enclosing class,
356 * classname is the simple name of the local class
357 */
358 Name localClassName(ClassSymbol c) {
359 for (int i=1; ; i++) {
360 Name flatname = names.
361 fromString("" + c.owner.enclClass().flatname +
362 syntheticNameChar + i +
363 c.name);
364 if (compiled.get(flatname) == null) return flatname;
365 }
366 }
368 /* *************************************************************************
369 * Type Checking
370 **************************************************************************/
372 /** Check that a given type is assignable to a given proto-type.
373 * If it is, return the type, otherwise return errType.
374 * @param pos Position to be used for error reporting.
375 * @param found The type that was found.
376 * @param req The type that was required.
377 */
378 Type checkType(DiagnosticPosition pos, Type found, Type req) {
379 if (req.tag == ERROR)
380 return req;
381 if (found.tag == FORALL)
382 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
383 if (req.tag == NONE)
384 return found;
385 if (types.isAssignable(found, req, convertWarner(pos, found, req)))
386 return found;
387 if (found.tag <= DOUBLE && req.tag <= DOUBLE)
388 return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
389 if (found.isSuperBound()) {
390 log.error(pos, "assignment.from.super-bound", found);
391 return types.createErrorType(found);
392 }
393 if (req.isExtendsBound()) {
394 log.error(pos, "assignment.to.extends-bound", req);
395 return types.createErrorType(found);
396 }
397 return typeError(pos, diags.fragment("incompatible.types"), found, req);
398 }
400 /** Instantiate polymorphic type to some prototype, unless
401 * prototype is `anyPoly' in which case polymorphic type
402 * is returned unchanged.
403 */
404 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
405 if (pt == Infer.anyPoly && complexInference) {
406 return t;
407 } else if (pt == Infer.anyPoly || pt.tag == NONE) {
408 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
409 return instantiatePoly(pos, t, newpt, warn);
410 } else if (pt.tag == ERROR) {
411 return pt;
412 } else {
413 try {
414 return infer.instantiateExpr(t, pt, warn);
415 } catch (Infer.NoInstanceException ex) {
416 if (ex.isAmbiguous) {
417 JCDiagnostic d = ex.getDiagnostic();
418 log.error(pos,
419 "undetermined.type" + (d!=null ? ".1" : ""),
420 t, d);
421 return types.createErrorType(pt);
422 } else {
423 JCDiagnostic d = ex.getDiagnostic();
424 return typeError(pos,
425 diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
426 t, pt);
427 }
428 } catch (Infer.InvalidInstanceException ex) {
429 JCDiagnostic d = ex.getDiagnostic();
430 log.error(pos, "invalid.inferred.types", t.tvars, d);
431 return types.createErrorType(pt);
432 }
433 }
434 }
436 /** Check that a given type can be cast to a given target type.
437 * Return the result of the cast.
438 * @param pos Position to be used for error reporting.
439 * @param found The type that is being cast.
440 * @param req The target type of the cast.
441 */
442 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
443 if (found.tag == FORALL) {
444 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
445 return req;
446 } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
447 return req;
448 } else {
449 return typeError(pos,
450 diags.fragment("inconvertible.types"),
451 found, req);
452 }
453 }
454 //where
455 /** Is type a type variable, or a (possibly multi-dimensional) array of
456 * type variables?
457 */
458 boolean isTypeVar(Type t) {
459 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
460 }
462 /** Check that a type is within some bounds.
463 *
464 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
465 * type argument.
466 * @param pos Position to be used for error reporting.
467 * @param a The type that should be bounded by bs.
468 * @param bs The bound.
469 */
470 private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
471 if (a.isUnbound()) {
472 return;
473 } else if (a.tag != WILDCARD) {
474 a = types.upperBound(a);
475 for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
476 if (!types.isSubtype(a, l.head)) {
477 log.error(pos, "not.within.bounds", a);
478 return;
479 }
480 }
481 } else if (a.isExtendsBound()) {
482 if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
483 log.error(pos, "not.within.bounds", a);
484 } else if (a.isSuperBound()) {
485 if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
486 log.error(pos, "not.within.bounds", a);
487 }
488 }
490 /** Check that a type is within some bounds.
491 *
492 * Used in TypeApply to verify that, e.g., X in V<X> is a valid
493 * type argument.
494 * @param pos Position to be used for error reporting.
495 * @param a The type that should be bounded by bs.
496 * @param bs The bound.
497 */
498 private void checkCapture(JCTypeApply tree) {
499 List<JCExpression> args = tree.getTypeArguments();
500 for (Type arg : types.capture(tree.type).getTypeArguments()) {
501 if (arg.tag == TYPEVAR && arg.getUpperBound().isErroneous()) {
502 log.error(args.head.pos, "not.within.bounds", args.head.type);
503 break;
504 }
505 args = args.tail;
506 }
507 }
509 /** Check that type is different from 'void'.
510 * @param pos Position to be used for error reporting.
511 * @param t The type to be checked.
512 */
513 Type checkNonVoid(DiagnosticPosition pos, Type t) {
514 if (t.tag == VOID) {
515 log.error(pos, "void.not.allowed.here");
516 return types.createErrorType(t);
517 } else {
518 return t;
519 }
520 }
522 /** Check that type is a class or interface type.
523 * @param pos Position to be used for error reporting.
524 * @param t The type to be checked.
525 */
526 Type checkClassType(DiagnosticPosition pos, Type t) {
527 if (t.tag != CLASS && t.tag != ERROR)
528 return typeTagError(pos,
529 diags.fragment("type.req.class"),
530 (t.tag == TYPEVAR)
531 ? diags.fragment("type.parameter", t)
532 : t);
533 else
534 return t;
535 }
537 /** Check that type is a class or interface type.
538 * @param pos Position to be used for error reporting.
539 * @param t The type to be checked.
540 * @param noBounds True if type bounds are illegal here.
541 */
542 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
543 t = checkClassType(pos, t);
544 if (noBounds && t.isParameterized()) {
545 List<Type> args = t.getTypeArguments();
546 while (args.nonEmpty()) {
547 if (args.head.tag == WILDCARD)
548 return typeTagError(pos,
549 Log.getLocalizedString("type.req.exact"),
550 args.head);
551 args = args.tail;
552 }
553 }
554 return t;
555 }
557 /** Check that type is a reifiable class, interface or array type.
558 * @param pos Position to be used for error reporting.
559 * @param t The type to be checked.
560 */
561 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
562 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
563 return typeTagError(pos,
564 diags.fragment("type.req.class.array"),
565 t);
566 } else if (!types.isReifiable(t)) {
567 log.error(pos, "illegal.generic.type.for.instof");
568 return types.createErrorType(t);
569 } else {
570 return t;
571 }
572 }
574 /** Check that type is a reference type, i.e. a class, interface or array type
575 * or a type variable.
576 * @param pos Position to be used for error reporting.
577 * @param t The type to be checked.
578 */
579 Type checkRefType(DiagnosticPosition pos, Type t) {
580 switch (t.tag) {
581 case CLASS:
582 case ARRAY:
583 case TYPEVAR:
584 case WILDCARD:
585 case ERROR:
586 return t;
587 default:
588 return typeTagError(pos,
589 diags.fragment("type.req.ref"),
590 t);
591 }
592 }
594 /** Check that each type is a reference type, i.e. a class, interface or array type
595 * or a type variable.
596 * @param trees Original trees, used for error reporting.
597 * @param types The types to be checked.
598 */
599 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
600 List<JCExpression> tl = trees;
601 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
602 l.head = checkRefType(tl.head.pos(), l.head);
603 tl = tl.tail;
604 }
605 return types;
606 }
608 /** Check that type is a null or reference type.
609 * @param pos Position to be used for error reporting.
610 * @param t The type to be checked.
611 */
612 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
613 switch (t.tag) {
614 case CLASS:
615 case ARRAY:
616 case TYPEVAR:
617 case WILDCARD:
618 case BOT:
619 case ERROR:
620 return t;
621 default:
622 return typeTagError(pos,
623 diags.fragment("type.req.ref"),
624 t);
625 }
626 }
628 /** Check that flag set does not contain elements of two conflicting sets. s
629 * Return true if it doesn't.
630 * @param pos Position to be used for error reporting.
631 * @param flags The set of flags to be checked.
632 * @param set1 Conflicting flags set #1.
633 * @param set2 Conflicting flags set #2.
634 */
635 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
636 if ((flags & set1) != 0 && (flags & set2) != 0) {
637 log.error(pos,
638 "illegal.combination.of.modifiers",
639 asFlagSet(TreeInfo.firstFlag(flags & set1)),
640 asFlagSet(TreeInfo.firstFlag(flags & set2)));
641 return false;
642 } else
643 return true;
644 }
646 /** Check that the type inferred using the diamond operator does not contain
647 * non-denotable types such as captured types or intersection types.
648 * @param t the type inferred using the diamond operator
649 */
650 List<Type> checkDiamond(ClassType t) {
651 DiamondTypeChecker dtc = new DiamondTypeChecker();
652 ListBuffer<Type> buf = ListBuffer.lb();
653 for (Type arg : t.getTypeArguments()) {
654 if (!dtc.visit(arg, null)) {
655 buf.append(arg);
656 }
657 }
658 return buf.toList();
659 }
661 static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
662 public Boolean visitType(Type t, Void s) {
663 return true;
664 }
665 @Override
666 public Boolean visitClassType(ClassType t, Void s) {
667 if (t.isCompound()) {
668 return false;
669 }
670 for (Type targ : t.getTypeArguments()) {
671 if (!visit(targ, s)) {
672 return false;
673 }
674 }
675 return true;
676 }
677 @Override
678 public Boolean visitCapturedType(CapturedType t, Void s) {
679 return false;
680 }
681 }
683 /**
684 * Check that vararg method call is sound
685 * @param pos Position to be used for error reporting.
686 * @param argtypes Actual arguments supplied to vararg method.
687 */
688 void checkVararg(DiagnosticPosition pos, List<Type> argtypes) {
689 Type argtype = argtypes.last();
690 if (!types.isReifiable(argtype))
691 warnUnchecked(pos,
692 "unchecked.generic.array.creation",
693 argtype);
694 }
696 /** Check that given modifiers are legal for given symbol and
697 * return modifiers together with any implicit modififiers for that symbol.
698 * Warning: we can't use flags() here since this method
699 * is called during class enter, when flags() would cause a premature
700 * completion.
701 * @param pos Position to be used for error reporting.
702 * @param flags The set of modifiers given in a definition.
703 * @param sym The defined symbol.
704 */
705 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
706 long mask;
707 long implicit = 0;
708 switch (sym.kind) {
709 case VAR:
710 if (sym.owner.kind != TYP)
711 mask = LocalVarFlags;
712 else if ((sym.owner.flags_field & INTERFACE) != 0)
713 mask = implicit = InterfaceVarFlags;
714 else
715 mask = VarFlags;
716 break;
717 case MTH:
718 if (sym.name == names.init) {
719 if ((sym.owner.flags_field & ENUM) != 0) {
720 // enum constructors cannot be declared public or
721 // protected and must be implicitly or explicitly
722 // private
723 implicit = PRIVATE;
724 mask = PRIVATE;
725 } else
726 mask = ConstructorFlags;
727 } else if ((sym.owner.flags_field & INTERFACE) != 0)
728 mask = implicit = InterfaceMethodFlags;
729 else {
730 mask = MethodFlags;
731 }
732 // Imply STRICTFP if owner has STRICTFP set.
733 if (((flags|implicit) & Flags.ABSTRACT) == 0)
734 implicit |= sym.owner.flags_field & STRICTFP;
735 break;
736 case TYP:
737 if (sym.isLocal()) {
738 mask = LocalClassFlags;
739 if (sym.name.isEmpty()) { // Anonymous class
740 // Anonymous classes in static methods are themselves static;
741 // that's why we admit STATIC here.
742 mask |= STATIC;
743 // JLS: Anonymous classes are final.
744 implicit |= FINAL;
745 }
746 if ((sym.owner.flags_field & STATIC) == 0 &&
747 (flags & ENUM) != 0)
748 log.error(pos, "enums.must.be.static");
749 } else if (sym.owner.kind == TYP) {
750 mask = MemberClassFlags;
751 if (sym.owner.owner.kind == PCK ||
752 (sym.owner.flags_field & STATIC) != 0)
753 mask |= STATIC;
754 else if ((flags & ENUM) != 0)
755 log.error(pos, "enums.must.be.static");
756 // Nested interfaces and enums are always STATIC (Spec ???)
757 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
758 } else {
759 mask = ClassFlags;
760 }
761 // Interfaces are always ABSTRACT
762 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
764 if ((flags & ENUM) != 0) {
765 // enums can't be declared abstract or final
766 mask &= ~(ABSTRACT | FINAL);
767 implicit |= implicitEnumFinalFlag(tree);
768 }
769 // Imply STRICTFP if owner has STRICTFP set.
770 implicit |= sym.owner.flags_field & STRICTFP;
771 break;
772 default:
773 throw new AssertionError();
774 }
775 long illegal = flags & StandardFlags & ~mask;
776 if (illegal != 0) {
777 if ((illegal & INTERFACE) != 0) {
778 log.error(pos, "intf.not.allowed.here");
779 mask |= INTERFACE;
780 }
781 else {
782 log.error(pos,
783 "mod.not.allowed.here", asFlagSet(illegal));
784 }
785 }
786 else if ((sym.kind == TYP ||
787 // ISSUE: Disallowing abstract&private is no longer appropriate
788 // in the presence of inner classes. Should it be deleted here?
789 checkDisjoint(pos, flags,
790 ABSTRACT,
791 PRIVATE | STATIC))
792 &&
793 checkDisjoint(pos, flags,
794 ABSTRACT | INTERFACE,
795 FINAL | NATIVE | SYNCHRONIZED)
796 &&
797 checkDisjoint(pos, flags,
798 PUBLIC,
799 PRIVATE | PROTECTED)
800 &&
801 checkDisjoint(pos, flags,
802 PRIVATE,
803 PUBLIC | PROTECTED)
804 &&
805 checkDisjoint(pos, flags,
806 FINAL,
807 VOLATILE)
808 &&
809 (sym.kind == TYP ||
810 checkDisjoint(pos, flags,
811 ABSTRACT | NATIVE,
812 STRICTFP))) {
813 // skip
814 }
815 return flags & (mask | ~StandardFlags) | implicit;
816 }
819 /** Determine if this enum should be implicitly final.
820 *
821 * If the enum has no specialized enum contants, it is final.
822 *
823 * If the enum does have specialized enum contants, it is
824 * <i>not</i> final.
825 */
826 private long implicitEnumFinalFlag(JCTree tree) {
827 if (tree.getTag() != JCTree.CLASSDEF) return 0;
828 class SpecialTreeVisitor extends JCTree.Visitor {
829 boolean specialized;
830 SpecialTreeVisitor() {
831 this.specialized = false;
832 };
834 @Override
835 public void visitTree(JCTree tree) { /* no-op */ }
837 @Override
838 public void visitVarDef(JCVariableDecl tree) {
839 if ((tree.mods.flags & ENUM) != 0) {
840 if (tree.init instanceof JCNewClass &&
841 ((JCNewClass) tree.init).def != null) {
842 specialized = true;
843 }
844 }
845 }
846 }
848 SpecialTreeVisitor sts = new SpecialTreeVisitor();
849 JCClassDecl cdef = (JCClassDecl) tree;
850 for (JCTree defs: cdef.defs) {
851 defs.accept(sts);
852 if (sts.specialized) return 0;
853 }
854 return FINAL;
855 }
857 /* *************************************************************************
858 * Type Validation
859 **************************************************************************/
861 /** Validate a type expression. That is,
862 * check that all type arguments of a parametric type are within
863 * their bounds. This must be done in a second phase after type attributon
864 * since a class might have a subclass as type parameter bound. E.g:
865 *
866 * class B<A extends C> { ... }
867 * class C extends B<C> { ... }
868 *
869 * and we can't make sure that the bound is already attributed because
870 * of possible cycles.
871 */
872 private Validator validator = new Validator();
874 /** Visitor method: Validate a type expression, if it is not null, catching
875 * and reporting any completion failures.
876 */
877 void validate(JCTree tree, Env<AttrContext> env) {
878 try {
879 if (tree != null) {
880 validator.env = env;
881 tree.accept(validator);
882 checkRaw(tree, env);
883 }
884 } catch (CompletionFailure ex) {
885 completionError(tree.pos(), ex);
886 }
887 }
888 //where
889 void checkRaw(JCTree tree, Env<AttrContext> env) {
890 if (lint.isEnabled(Lint.LintCategory.RAW) &&
891 tree.type.tag == CLASS &&
892 !TreeInfo.isDiamond(tree) &&
893 !env.enclClass.name.isEmpty() && //anonymous or intersection
894 tree.type.isRaw()) {
895 log.warning(tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
896 }
897 }
899 /** Visitor method: Validate a list of type expressions.
900 */
901 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
902 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
903 validate(l.head, env);
904 }
906 /** A visitor class for type validation.
907 */
908 class Validator extends JCTree.Visitor {
910 @Override
911 public void visitTypeArray(JCArrayTypeTree tree) {
912 validate(tree.elemtype, env);
913 }
915 @Override
916 public void visitTypeApply(JCTypeApply tree) {
917 if (tree.type.tag == CLASS) {
918 List<Type> formals = tree.type.tsym.type.allparams();
919 List<Type> actuals = tree.type.allparams();
920 List<JCExpression> args = tree.arguments;
921 List<Type> forms = tree.type.tsym.type.getTypeArguments();
922 ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
924 // For matching pairs of actual argument types `a' and
925 // formal type parameters with declared bound `b' ...
926 while (args.nonEmpty() && forms.nonEmpty()) {
927 validate(args.head, env);
929 // exact type arguments needs to know their
930 // bounds (for upper and lower bound
931 // calculations). So we create new TypeVars with
932 // bounds substed with actuals.
933 tvars_buf.append(types.substBound(((TypeVar)forms.head),
934 formals,
935 actuals));
937 args = args.tail;
938 forms = forms.tail;
939 }
941 args = tree.arguments;
942 List<Type> tvars_cap = types.substBounds(formals,
943 formals,
944 types.capture(tree.type).allparams());
945 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
946 // Let the actual arguments know their bound
947 args.head.type.withTypeVar((TypeVar)tvars_cap.head);
948 args = args.tail;
949 tvars_cap = tvars_cap.tail;
950 }
952 args = tree.arguments;
953 List<Type> tvars = tvars_buf.toList();
955 while (args.nonEmpty() && tvars.nonEmpty()) {
956 Type actual = types.subst(args.head.type,
957 tree.type.tsym.type.getTypeArguments(),
958 tvars_buf.toList());
959 checkExtends(args.head.pos(),
960 actual,
961 (TypeVar)tvars.head);
962 args = args.tail;
963 tvars = tvars.tail;
964 }
966 checkCapture(tree);
968 // Check that this type is either fully parameterized, or
969 // not parameterized at all.
970 if (tree.type.getEnclosingType().isRaw())
971 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
972 if (tree.clazz.getTag() == JCTree.SELECT)
973 visitSelectInternal((JCFieldAccess)tree.clazz);
974 }
975 }
977 @Override
978 public void visitTypeParameter(JCTypeParameter tree) {
979 validate(tree.bounds, env);
980 checkClassBounds(tree.pos(), tree.type);
981 }
983 @Override
984 public void visitWildcard(JCWildcard tree) {
985 if (tree.inner != null)
986 validate(tree.inner, env);
987 }
989 @Override
990 public void visitSelect(JCFieldAccess tree) {
991 if (tree.type.tag == CLASS) {
992 visitSelectInternal(tree);
994 // Check that this type is either fully parameterized, or
995 // not parameterized at all.
996 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
997 log.error(tree.pos(), "improperly.formed.type.param.missing");
998 }
999 }
1000 public void visitSelectInternal(JCFieldAccess tree) {
1001 if (tree.type.tsym.isStatic() &&
1002 tree.selected.type.isParameterized()) {
1003 // The enclosing type is not a class, so we are
1004 // looking at a static member type. However, the
1005 // qualifying expression is parameterized.
1006 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1007 } else {
1008 // otherwise validate the rest of the expression
1009 tree.selected.accept(this);
1010 }
1011 }
1013 @Override
1014 public void visitAnnotatedType(JCAnnotatedType tree) {
1015 tree.underlyingType.accept(this);
1016 }
1018 /** Default visitor method: do nothing.
1019 */
1020 @Override
1021 public void visitTree(JCTree tree) {
1022 }
1024 Env<AttrContext> env;
1025 }
1027 /* *************************************************************************
1028 * Exception checking
1029 **************************************************************************/
1031 /* The following methods treat classes as sets that contain
1032 * the class itself and all their subclasses
1033 */
1035 /** Is given type a subtype of some of the types in given list?
1036 */
1037 boolean subset(Type t, List<Type> ts) {
1038 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1039 if (types.isSubtype(t, l.head)) return true;
1040 return false;
1041 }
1043 /** Is given type a subtype or supertype of
1044 * some of the types in given list?
1045 */
1046 boolean intersects(Type t, List<Type> ts) {
1047 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1048 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1049 return false;
1050 }
1052 /** Add type set to given type list, unless it is a subclass of some class
1053 * in the list.
1054 */
1055 List<Type> incl(Type t, List<Type> ts) {
1056 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1057 }
1059 /** Remove type set from type set list.
1060 */
1061 List<Type> excl(Type t, List<Type> ts) {
1062 if (ts.isEmpty()) {
1063 return ts;
1064 } else {
1065 List<Type> ts1 = excl(t, ts.tail);
1066 if (types.isSubtype(ts.head, t)) return ts1;
1067 else if (ts1 == ts.tail) return ts;
1068 else return ts1.prepend(ts.head);
1069 }
1070 }
1072 /** Form the union of two type set lists.
1073 */
1074 List<Type> union(List<Type> ts1, List<Type> ts2) {
1075 List<Type> ts = ts1;
1076 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1077 ts = incl(l.head, ts);
1078 return ts;
1079 }
1081 /** Form the difference of two type lists.
1082 */
1083 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1084 List<Type> ts = ts1;
1085 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1086 ts = excl(l.head, ts);
1087 return ts;
1088 }
1090 /** Form the intersection of two type lists.
1091 */
1092 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1093 List<Type> ts = List.nil();
1094 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1095 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1096 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1097 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1098 return ts;
1099 }
1101 /** Is exc an exception symbol that need not be declared?
1102 */
1103 boolean isUnchecked(ClassSymbol exc) {
1104 return
1105 exc.kind == ERR ||
1106 exc.isSubClass(syms.errorType.tsym, types) ||
1107 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1108 }
1110 /** Is exc an exception type that need not be declared?
1111 */
1112 boolean isUnchecked(Type exc) {
1113 return
1114 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1115 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1116 exc.tag == BOT;
1117 }
1119 /** Same, but handling completion failures.
1120 */
1121 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1122 try {
1123 return isUnchecked(exc);
1124 } catch (CompletionFailure ex) {
1125 completionError(pos, ex);
1126 return true;
1127 }
1128 }
1130 /** Is exc handled by given exception list?
1131 */
1132 boolean isHandled(Type exc, List<Type> handled) {
1133 return isUnchecked(exc) || subset(exc, handled);
1134 }
1136 /** Return all exceptions in thrown list that are not in handled list.
1137 * @param thrown The list of thrown exceptions.
1138 * @param handled The list of handled exceptions.
1139 */
1140 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1141 List<Type> unhandled = List.nil();
1142 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1143 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1144 return unhandled;
1145 }
1147 /* *************************************************************************
1148 * Overriding/Implementation checking
1149 **************************************************************************/
1151 /** The level of access protection given by a flag set,
1152 * where PRIVATE is highest and PUBLIC is lowest.
1153 */
1154 static int protection(long flags) {
1155 switch ((short)(flags & AccessFlags)) {
1156 case PRIVATE: return 3;
1157 case PROTECTED: return 1;
1158 default:
1159 case PUBLIC: return 0;
1160 case 0: return 2;
1161 }
1162 }
1164 /** A customized "cannot override" error message.
1165 * @param m The overriding method.
1166 * @param other The overridden method.
1167 * @return An internationalized string.
1168 */
1169 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1170 String key;
1171 if ((other.owner.flags() & INTERFACE) == 0)
1172 key = "cant.override";
1173 else if ((m.owner.flags() & INTERFACE) == 0)
1174 key = "cant.implement";
1175 else
1176 key = "clashes.with";
1177 return diags.fragment(key, m, m.location(), other, other.location());
1178 }
1180 /** A customized "override" warning message.
1181 * @param m The overriding method.
1182 * @param other The overridden method.
1183 * @return An internationalized string.
1184 */
1185 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1186 String key;
1187 if ((other.owner.flags() & INTERFACE) == 0)
1188 key = "unchecked.override";
1189 else if ((m.owner.flags() & INTERFACE) == 0)
1190 key = "unchecked.implement";
1191 else
1192 key = "unchecked.clash.with";
1193 return diags.fragment(key, m, m.location(), other, other.location());
1194 }
1196 /** A customized "override" warning message.
1197 * @param m The overriding method.
1198 * @param other The overridden method.
1199 * @return An internationalized string.
1200 */
1201 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1202 String key;
1203 if ((other.owner.flags() & INTERFACE) == 0)
1204 key = "varargs.override";
1205 else if ((m.owner.flags() & INTERFACE) == 0)
1206 key = "varargs.implement";
1207 else
1208 key = "varargs.clash.with";
1209 return diags.fragment(key, m, m.location(), other, other.location());
1210 }
1212 /** Check that this method conforms with overridden method 'other'.
1213 * where `origin' is the class where checking started.
1214 * Complications:
1215 * (1) Do not check overriding of synthetic methods
1216 * (reason: they might be final).
1217 * todo: check whether this is still necessary.
1218 * (2) Admit the case where an interface proxy throws fewer exceptions
1219 * than the method it implements. Augment the proxy methods with the
1220 * undeclared exceptions in this case.
1221 * (3) When generics are enabled, admit the case where an interface proxy
1222 * has a result type
1223 * extended by the result type of the method it implements.
1224 * Change the proxies result type to the smaller type in this case.
1225 *
1226 * @param tree The tree from which positions
1227 * are extracted for errors.
1228 * @param m The overriding method.
1229 * @param other The overridden method.
1230 * @param origin The class of which the overriding method
1231 * is a member.
1232 */
1233 void checkOverride(JCTree tree,
1234 MethodSymbol m,
1235 MethodSymbol other,
1236 ClassSymbol origin) {
1237 // Don't check overriding of synthetic methods or by bridge methods.
1238 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1239 return;
1240 }
1242 // Error if static method overrides instance method (JLS 8.4.6.2).
1243 if ((m.flags() & STATIC) != 0 &&
1244 (other.flags() & STATIC) == 0) {
1245 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1246 cannotOverride(m, other));
1247 return;
1248 }
1250 // Error if instance method overrides static or final
1251 // method (JLS 8.4.6.1).
1252 if ((other.flags() & FINAL) != 0 ||
1253 (m.flags() & STATIC) == 0 &&
1254 (other.flags() & STATIC) != 0) {
1255 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1256 cannotOverride(m, other),
1257 asFlagSet(other.flags() & (FINAL | STATIC)));
1258 return;
1259 }
1261 if ((m.owner.flags() & ANNOTATION) != 0) {
1262 // handled in validateAnnotationMethod
1263 return;
1264 }
1266 // Error if overriding method has weaker access (JLS 8.4.6.3).
1267 if ((origin.flags() & INTERFACE) == 0 &&
1268 protection(m.flags()) > protection(other.flags())) {
1269 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1270 cannotOverride(m, other),
1271 other.flags() == 0 ?
1272 Flag.PACKAGE :
1273 asFlagSet(other.flags() & AccessFlags));
1274 return;
1275 }
1277 Type mt = types.memberType(origin.type, m);
1278 Type ot = types.memberType(origin.type, other);
1279 // Error if overriding result type is different
1280 // (or, in the case of generics mode, not a subtype) of
1281 // overridden result type. We have to rename any type parameters
1282 // before comparing types.
1283 List<Type> mtvars = mt.getTypeArguments();
1284 List<Type> otvars = ot.getTypeArguments();
1285 Type mtres = mt.getReturnType();
1286 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1288 overrideWarner.warned = false;
1289 boolean resultTypesOK =
1290 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1291 if (!resultTypesOK) {
1292 if (!allowCovariantReturns &&
1293 m.owner != origin &&
1294 m.owner.isSubClass(other.owner, types)) {
1295 // allow limited interoperability with covariant returns
1296 } else {
1297 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1298 "override.incompatible.ret",
1299 cannotOverride(m, other),
1300 mtres, otres);
1301 return;
1302 }
1303 } else if (overrideWarner.warned) {
1304 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1305 "override.unchecked.ret",
1306 uncheckedOverrides(m, other),
1307 mtres, otres);
1308 }
1310 // Error if overriding method throws an exception not reported
1311 // by overridden method.
1312 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1313 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1314 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1315 if (unhandledErased.nonEmpty()) {
1316 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1317 "override.meth.doesnt.throw",
1318 cannotOverride(m, other),
1319 unhandledUnerased.head);
1320 return;
1321 }
1322 else if (unhandledUnerased.nonEmpty()) {
1323 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1324 "override.unchecked.thrown",
1325 cannotOverride(m, other),
1326 unhandledUnerased.head);
1327 return;
1328 }
1330 // Optional warning if varargs don't agree
1331 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1332 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
1333 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1334 ((m.flags() & Flags.VARARGS) != 0)
1335 ? "override.varargs.missing"
1336 : "override.varargs.extra",
1337 varargsOverrides(m, other));
1338 }
1340 // Warn if instance method overrides bridge method (compiler spec ??)
1341 if ((other.flags() & BRIDGE) != 0) {
1342 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1343 uncheckedOverrides(m, other));
1344 }
1346 // Warn if a deprecated method overridden by a non-deprecated one.
1347 if ((other.flags() & DEPRECATED) != 0
1348 && (m.flags() & DEPRECATED) == 0
1349 && m.outermostClass() != other.outermostClass()
1350 && !isDeprecatedOverrideIgnorable(other, origin)) {
1351 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1352 }
1353 }
1354 // where
1355 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1356 // If the method, m, is defined in an interface, then ignore the issue if the method
1357 // is only inherited via a supertype and also implemented in the supertype,
1358 // because in that case, we will rediscover the issue when examining the method
1359 // in the supertype.
1360 // If the method, m, is not defined in an interface, then the only time we need to
1361 // address the issue is when the method is the supertype implemementation: any other
1362 // case, we will have dealt with when examining the supertype classes
1363 ClassSymbol mc = m.enclClass();
1364 Type st = types.supertype(origin.type);
1365 if (st.tag != CLASS)
1366 return true;
1367 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1369 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1370 List<Type> intfs = types.interfaces(origin.type);
1371 return (intfs.contains(mc.type) ? false : (stimpl != null));
1372 }
1373 else
1374 return (stimpl != m);
1375 }
1378 // used to check if there were any unchecked conversions
1379 Warner overrideWarner = new Warner();
1381 /** Check that a class does not inherit two concrete methods
1382 * with the same signature.
1383 * @param pos Position to be used for error reporting.
1384 * @param site The class type to be checked.
1385 */
1386 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1387 Type sup = types.supertype(site);
1388 if (sup.tag != CLASS) return;
1390 for (Type t1 = sup;
1391 t1.tsym.type.isParameterized();
1392 t1 = types.supertype(t1)) {
1393 for (Scope.Entry e1 = t1.tsym.members().elems;
1394 e1 != null;
1395 e1 = e1.sibling) {
1396 Symbol s1 = e1.sym;
1397 if (s1.kind != MTH ||
1398 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1399 !s1.isInheritedIn(site.tsym, types) ||
1400 ((MethodSymbol)s1).implementation(site.tsym,
1401 types,
1402 true) != s1)
1403 continue;
1404 Type st1 = types.memberType(t1, s1);
1405 int s1ArgsLength = st1.getParameterTypes().length();
1406 if (st1 == s1.type) continue;
1408 for (Type t2 = sup;
1409 t2.tag == CLASS;
1410 t2 = types.supertype(t2)) {
1411 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1412 e2.scope != null;
1413 e2 = e2.next()) {
1414 Symbol s2 = e2.sym;
1415 if (s2 == s1 ||
1416 s2.kind != MTH ||
1417 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1418 s2.type.getParameterTypes().length() != s1ArgsLength ||
1419 !s2.isInheritedIn(site.tsym, types) ||
1420 ((MethodSymbol)s2).implementation(site.tsym,
1421 types,
1422 true) != s2)
1423 continue;
1424 Type st2 = types.memberType(t2, s2);
1425 if (types.overrideEquivalent(st1, st2))
1426 log.error(pos, "concrete.inheritance.conflict",
1427 s1, t1, s2, t2, sup);
1428 }
1429 }
1430 }
1431 }
1432 }
1434 /** Check that classes (or interfaces) do not each define an abstract
1435 * method with same name and arguments but incompatible return types.
1436 * @param pos Position to be used for error reporting.
1437 * @param t1 The first argument type.
1438 * @param t2 The second argument type.
1439 */
1440 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1441 Type t1,
1442 Type t2) {
1443 return checkCompatibleAbstracts(pos, t1, t2,
1444 types.makeCompoundType(t1, t2));
1445 }
1447 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1448 Type t1,
1449 Type t2,
1450 Type site) {
1451 Symbol sym = firstIncompatibility(t1, t2, site);
1452 if (sym != null) {
1453 log.error(pos, "types.incompatible.diff.ret",
1454 t1, t2, sym.name +
1455 "(" + types.memberType(t2, sym).getParameterTypes() + ")");
1456 return false;
1457 }
1458 return true;
1459 }
1461 /** Return the first method which is defined with same args
1462 * but different return types in two given interfaces, or null if none
1463 * exists.
1464 * @param t1 The first type.
1465 * @param t2 The second type.
1466 * @param site The most derived type.
1467 * @returns symbol from t2 that conflicts with one in t1.
1468 */
1469 private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
1470 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1471 closure(t1, interfaces1);
1472 Map<TypeSymbol,Type> interfaces2;
1473 if (t1 == t2)
1474 interfaces2 = interfaces1;
1475 else
1476 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1478 for (Type t3 : interfaces1.values()) {
1479 for (Type t4 : interfaces2.values()) {
1480 Symbol s = firstDirectIncompatibility(t3, t4, site);
1481 if (s != null) return s;
1482 }
1483 }
1484 return null;
1485 }
1487 /** Compute all the supertypes of t, indexed by type symbol. */
1488 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1489 if (t.tag != CLASS) return;
1490 if (typeMap.put(t.tsym, t) == null) {
1491 closure(types.supertype(t), typeMap);
1492 for (Type i : types.interfaces(t))
1493 closure(i, typeMap);
1494 }
1495 }
1497 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1498 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1499 if (t.tag != CLASS) return;
1500 if (typesSkip.get(t.tsym) != null) return;
1501 if (typeMap.put(t.tsym, t) == null) {
1502 closure(types.supertype(t), typesSkip, typeMap);
1503 for (Type i : types.interfaces(t))
1504 closure(i, typesSkip, typeMap);
1505 }
1506 }
1508 /** Return the first method in t2 that conflicts with a method from t1. */
1509 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
1510 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1511 Symbol s1 = e1.sym;
1512 Type st1 = null;
1513 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1514 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1515 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1516 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1517 Symbol s2 = e2.sym;
1518 if (s1 == s2) continue;
1519 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1520 if (st1 == null) st1 = types.memberType(t1, s1);
1521 Type st2 = types.memberType(t2, s2);
1522 if (types.overrideEquivalent(st1, st2)) {
1523 List<Type> tvars1 = st1.getTypeArguments();
1524 List<Type> tvars2 = st2.getTypeArguments();
1525 Type rt1 = st1.getReturnType();
1526 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1527 boolean compat =
1528 types.isSameType(rt1, rt2) ||
1529 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1530 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1531 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1532 checkCommonOverriderIn(s1,s2,site);
1533 if (!compat) return s2;
1534 }
1535 }
1536 }
1537 return null;
1538 }
1539 //WHERE
1540 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1541 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1542 Type st1 = types.memberType(site, s1);
1543 Type st2 = types.memberType(site, s2);
1544 closure(site, supertypes);
1545 for (Type t : supertypes.values()) {
1546 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1547 Symbol s3 = e.sym;
1548 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1549 Type st3 = types.memberType(site,s3);
1550 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1551 if (s3.owner == site.tsym) {
1552 return true;
1553 }
1554 List<Type> tvars1 = st1.getTypeArguments();
1555 List<Type> tvars2 = st2.getTypeArguments();
1556 List<Type> tvars3 = st3.getTypeArguments();
1557 Type rt1 = st1.getReturnType();
1558 Type rt2 = st2.getReturnType();
1559 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1560 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1561 boolean compat =
1562 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1563 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1564 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1565 if (compat)
1566 return true;
1567 }
1568 }
1569 }
1570 return false;
1571 }
1573 /** Check that a given method conforms with any method it overrides.
1574 * @param tree The tree from which positions are extracted
1575 * for errors.
1576 * @param m The overriding method.
1577 */
1578 void checkOverride(JCTree tree, MethodSymbol m) {
1579 ClassSymbol origin = (ClassSymbol)m.owner;
1580 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1581 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1582 log.error(tree.pos(), "enum.no.finalize");
1583 return;
1584 }
1585 for (Type t = types.supertype(origin.type); t.tag == CLASS;
1586 t = types.supertype(t)) {
1587 TypeSymbol c = t.tsym;
1588 Scope.Entry e = c.members().lookup(m.name);
1589 while (e.scope != null) {
1590 if (m.overrides(e.sym, origin, types, false))
1591 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1592 else if (e.sym.kind == MTH &&
1593 e.sym.isInheritedIn(origin, types) &&
1594 (e.sym.flags() & SYNTHETIC) == 0 &&
1595 !m.isConstructor()) {
1596 Type er1 = m.erasure(types);
1597 Type er2 = e.sym.erasure(types);
1598 if (types.isSameTypes(er1.getParameterTypes(),
1599 er2.getParameterTypes())) {
1600 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1601 "name.clash.same.erasure.no.override",
1602 m, m.location(),
1603 e.sym, e.sym.location());
1604 }
1605 }
1606 e = e.next();
1607 }
1608 }
1609 }
1611 /** Check that all abstract members of given class have definitions.
1612 * @param pos Position to be used for error reporting.
1613 * @param c The class.
1614 */
1615 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1616 try {
1617 MethodSymbol undef = firstUndef(c, c);
1618 if (undef != null) {
1619 if ((c.flags() & ENUM) != 0 &&
1620 types.supertype(c.type).tsym == syms.enumSym &&
1621 (c.flags() & FINAL) == 0) {
1622 // add the ABSTRACT flag to an enum
1623 c.flags_field |= ABSTRACT;
1624 } else {
1625 MethodSymbol undef1 =
1626 new MethodSymbol(undef.flags(), undef.name,
1627 types.memberType(c.type, undef), undef.owner);
1628 log.error(pos, "does.not.override.abstract",
1629 c, undef1, undef1.location());
1630 }
1631 }
1632 } catch (CompletionFailure ex) {
1633 completionError(pos, ex);
1634 }
1635 }
1636 //where
1637 /** Return first abstract member of class `c' that is not defined
1638 * in `impl', null if there is none.
1639 */
1640 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1641 MethodSymbol undef = null;
1642 // Do not bother to search in classes that are not abstract,
1643 // since they cannot have abstract members.
1644 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1645 Scope s = c.members();
1646 for (Scope.Entry e = s.elems;
1647 undef == null && e != null;
1648 e = e.sibling) {
1649 if (e.sym.kind == MTH &&
1650 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1651 MethodSymbol absmeth = (MethodSymbol)e.sym;
1652 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1653 if (implmeth == null || implmeth == absmeth)
1654 undef = absmeth;
1655 }
1656 }
1657 if (undef == null) {
1658 Type st = types.supertype(c.type);
1659 if (st.tag == CLASS)
1660 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1661 }
1662 for (List<Type> l = types.interfaces(c.type);
1663 undef == null && l.nonEmpty();
1664 l = l.tail) {
1665 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1666 }
1667 }
1668 return undef;
1669 }
1671 /** Check for cyclic references. Issue an error if the
1672 * symbol of the type referred to has a LOCKED flag set.
1673 *
1674 * @param pos Position to be used for error reporting.
1675 * @param t The type referred to.
1676 */
1677 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1678 checkNonCyclicInternal(pos, t);
1679 }
1682 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1683 checkNonCyclic1(pos, t, List.<TypeVar>nil());
1684 }
1686 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
1687 final TypeVar tv;
1688 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1689 return;
1690 if (seen.contains(t)) {
1691 tv = (TypeVar)t;
1692 tv.bound = types.createErrorType(t);
1693 log.error(pos, "cyclic.inheritance", t);
1694 } else if (t.tag == TYPEVAR) {
1695 tv = (TypeVar)t;
1696 seen = seen.prepend(tv);
1697 for (Type b : types.getBounds(tv))
1698 checkNonCyclic1(pos, b, seen);
1699 }
1700 }
1702 /** Check for cyclic references. Issue an error if the
1703 * symbol of the type referred to has a LOCKED flag set.
1704 *
1705 * @param pos Position to be used for error reporting.
1706 * @param t The type referred to.
1707 * @returns True if the check completed on all attributed classes
1708 */
1709 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1710 boolean complete = true; // was the check complete?
1711 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1712 Symbol c = t.tsym;
1713 if ((c.flags_field & ACYCLIC) != 0) return true;
1715 if ((c.flags_field & LOCKED) != 0) {
1716 noteCyclic(pos, (ClassSymbol)c);
1717 } else if (!c.type.isErroneous()) {
1718 try {
1719 c.flags_field |= LOCKED;
1720 if (c.type.tag == CLASS) {
1721 ClassType clazz = (ClassType)c.type;
1722 if (clazz.interfaces_field != null)
1723 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1724 complete &= checkNonCyclicInternal(pos, l.head);
1725 if (clazz.supertype_field != null) {
1726 Type st = clazz.supertype_field;
1727 if (st != null && st.tag == CLASS)
1728 complete &= checkNonCyclicInternal(pos, st);
1729 }
1730 if (c.owner.kind == TYP)
1731 complete &= checkNonCyclicInternal(pos, c.owner.type);
1732 }
1733 } finally {
1734 c.flags_field &= ~LOCKED;
1735 }
1736 }
1737 if (complete)
1738 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1739 if (complete) c.flags_field |= ACYCLIC;
1740 return complete;
1741 }
1743 /** Note that we found an inheritance cycle. */
1744 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1745 log.error(pos, "cyclic.inheritance", c);
1746 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1747 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
1748 Type st = types.supertype(c.type);
1749 if (st.tag == CLASS)
1750 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
1751 c.type = types.createErrorType(c, c.type);
1752 c.flags_field |= ACYCLIC;
1753 }
1755 /** Check that all methods which implement some
1756 * method conform to the method they implement.
1757 * @param tree The class definition whose members are checked.
1758 */
1759 void checkImplementations(JCClassDecl tree) {
1760 checkImplementations(tree, tree.sym);
1761 }
1762 //where
1763 /** Check that all methods which implement some
1764 * method in `ic' conform to the method they implement.
1765 */
1766 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
1767 ClassSymbol origin = tree.sym;
1768 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
1769 ClassSymbol lc = (ClassSymbol)l.head.tsym;
1770 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
1771 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
1772 if (e.sym.kind == MTH &&
1773 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
1774 MethodSymbol absmeth = (MethodSymbol)e.sym;
1775 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
1776 if (implmeth != null && implmeth != absmeth &&
1777 (implmeth.owner.flags() & INTERFACE) ==
1778 (origin.flags() & INTERFACE)) {
1779 // don't check if implmeth is in a class, yet
1780 // origin is an interface. This case arises only
1781 // if implmeth is declared in Object. The reason is
1782 // that interfaces really don't inherit from
1783 // Object it's just that the compiler represents
1784 // things that way.
1785 checkOverride(tree, implmeth, absmeth, origin);
1786 }
1787 }
1788 }
1789 }
1790 }
1791 }
1793 /** Check that all abstract methods implemented by a class are
1794 * mutually compatible.
1795 * @param pos Position to be used for error reporting.
1796 * @param c The class whose interfaces are checked.
1797 */
1798 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
1799 List<Type> supertypes = types.interfaces(c);
1800 Type supertype = types.supertype(c);
1801 if (supertype.tag == CLASS &&
1802 (supertype.tsym.flags() & ABSTRACT) != 0)
1803 supertypes = supertypes.prepend(supertype);
1804 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
1805 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
1806 !checkCompatibleAbstracts(pos, l.head, l.head, c))
1807 return;
1808 for (List<Type> m = supertypes; m != l; m = m.tail)
1809 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
1810 return;
1811 }
1812 checkCompatibleConcretes(pos, c);
1813 }
1815 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
1816 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
1817 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
1818 // VM allows methods and variables with differing types
1819 if (sym.kind == e.sym.kind &&
1820 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
1821 sym != e.sym &&
1822 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
1823 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
1824 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
1825 return;
1826 }
1827 }
1828 }
1829 }
1831 /** Report a conflict between a user symbol and a synthetic symbol.
1832 */
1833 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
1834 if (!sym.type.isErroneous()) {
1835 if (warnOnSyntheticConflicts) {
1836 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
1837 }
1838 else {
1839 log.error(pos, "synthetic.name.conflict", sym, sym.location());
1840 }
1841 }
1842 }
1844 /** Check that class c does not implement directly or indirectly
1845 * the same parameterized interface with two different argument lists.
1846 * @param pos Position to be used for error reporting.
1847 * @param type The type whose interfaces are checked.
1848 */
1849 void checkClassBounds(DiagnosticPosition pos, Type type) {
1850 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
1851 }
1852 //where
1853 /** Enter all interfaces of type `type' into the hash table `seensofar'
1854 * with their class symbol as key and their type as value. Make
1855 * sure no class is entered with two different types.
1856 */
1857 void checkClassBounds(DiagnosticPosition pos,
1858 Map<TypeSymbol,Type> seensofar,
1859 Type type) {
1860 if (type.isErroneous()) return;
1861 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
1862 Type it = l.head;
1863 Type oldit = seensofar.put(it.tsym, it);
1864 if (oldit != null) {
1865 List<Type> oldparams = oldit.allparams();
1866 List<Type> newparams = it.allparams();
1867 if (!types.containsTypeEquivalent(oldparams, newparams))
1868 log.error(pos, "cant.inherit.diff.arg",
1869 it.tsym, Type.toString(oldparams),
1870 Type.toString(newparams));
1871 }
1872 checkClassBounds(pos, seensofar, it);
1873 }
1874 Type st = types.supertype(type);
1875 if (st != null) checkClassBounds(pos, seensofar, st);
1876 }
1878 /** Enter interface into into set.
1879 * If it existed already, issue a "repeated interface" error.
1880 */
1881 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
1882 if (its.contains(it))
1883 log.error(pos, "repeated.interface");
1884 else {
1885 its.add(it);
1886 }
1887 }
1889 /* *************************************************************************
1890 * Check annotations
1891 **************************************************************************/
1893 /** Annotation types are restricted to primitives, String, an
1894 * enum, an annotation, Class, Class<?>, Class<? extends
1895 * Anything>, arrays of the preceding.
1896 */
1897 void validateAnnotationType(JCTree restype) {
1898 // restype may be null if an error occurred, so don't bother validating it
1899 if (restype != null) {
1900 validateAnnotationType(restype.pos(), restype.type);
1901 }
1902 }
1904 void validateAnnotationType(DiagnosticPosition pos, Type type) {
1905 if (type.isPrimitive()) return;
1906 if (types.isSameType(type, syms.stringType)) return;
1907 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
1908 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
1909 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
1910 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
1911 validateAnnotationType(pos, types.elemtype(type));
1912 return;
1913 }
1914 log.error(pos, "invalid.annotation.member.type");
1915 }
1917 /**
1918 * "It is also a compile-time error if any method declared in an
1919 * annotation type has a signature that is override-equivalent to
1920 * that of any public or protected method declared in class Object
1921 * or in the interface annotation.Annotation."
1922 *
1923 * @jls3 9.6 Annotation Types
1924 */
1925 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
1926 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
1927 Scope s = sup.tsym.members();
1928 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
1929 if (e.sym.kind == MTH &&
1930 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
1931 types.overrideEquivalent(m.type, e.sym.type))
1932 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
1933 }
1934 }
1935 }
1937 /** Check the annotations of a symbol.
1938 */
1939 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
1940 if (skipAnnotations) return;
1941 for (JCAnnotation a : annotations)
1942 validateAnnotation(a, s);
1943 }
1945 /** Check the type annotations
1946 */
1947 public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
1948 if (skipAnnotations) return;
1949 for (JCTypeAnnotation a : annotations)
1950 validateTypeAnnotation(a, isTypeParameter);
1951 }
1953 /** Check an annotation of a symbol.
1954 */
1955 public void validateAnnotation(JCAnnotation a, Symbol s) {
1956 validateAnnotation(a);
1958 if (!annotationApplicable(a, s))
1959 log.error(a.pos(), "annotation.type.not.applicable");
1961 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
1962 if (!isOverrider(s))
1963 log.error(a.pos(), "method.does.not.override.superclass");
1964 }
1965 }
1967 public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
1968 if (a.type == null)
1969 throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
1970 validateAnnotation(a);
1972 if (!isTypeAnnotation(a, isTypeParameter))
1973 log.error(a.pos(), "annotation.type.not.applicable");
1974 }
1976 /** Is s a method symbol that overrides a method in a superclass? */
1977 boolean isOverrider(Symbol s) {
1978 if (s.kind != MTH || s.isStatic())
1979 return false;
1980 MethodSymbol m = (MethodSymbol)s;
1981 TypeSymbol owner = (TypeSymbol)m.owner;
1982 for (Type sup : types.closure(owner.type)) {
1983 if (sup == owner.type)
1984 continue; // skip "this"
1985 Scope scope = sup.tsym.members();
1986 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
1987 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
1988 return true;
1989 }
1990 }
1991 return false;
1992 }
1994 /** Is the annotation applicable to type annotations */
1995 boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
1996 Attribute.Compound atTarget =
1997 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
1998 if (atTarget == null) return true;
1999 Attribute atValue = atTarget.member(names.value);
2000 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2001 Attribute.Array arr = (Attribute.Array) atValue;
2002 for (Attribute app : arr.values) {
2003 if (!(app instanceof Attribute.Enum)) return true; // recovery
2004 Attribute.Enum e = (Attribute.Enum) app;
2005 if (!isTypeParameter && e.value.name == names.TYPE_USE)
2006 return true;
2007 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2008 return true;
2009 }
2010 return false;
2011 }
2013 /** Is the annotation applicable to the symbol? */
2014 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2015 Attribute.Compound atTarget =
2016 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2017 if (atTarget == null) return true;
2018 Attribute atValue = atTarget.member(names.value);
2019 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2020 Attribute.Array arr = (Attribute.Array) atValue;
2021 for (Attribute app : arr.values) {
2022 if (!(app instanceof Attribute.Enum)) return true; // recovery
2023 Attribute.Enum e = (Attribute.Enum) app;
2024 if (e.value.name == names.TYPE)
2025 { if (s.kind == TYP) return true; }
2026 else if (e.value.name == names.FIELD)
2027 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2028 else if (e.value.name == names.METHOD)
2029 { if (s.kind == MTH && !s.isConstructor()) return true; }
2030 else if (e.value.name == names.PARAMETER)
2031 { if (s.kind == VAR &&
2032 s.owner.kind == MTH &&
2033 (s.flags() & PARAMETER) != 0)
2034 return true;
2035 }
2036 else if (e.value.name == names.CONSTRUCTOR)
2037 { if (s.kind == MTH && s.isConstructor()) return true; }
2038 else if (e.value.name == names.LOCAL_VARIABLE)
2039 { if (s.kind == VAR && s.owner.kind == MTH &&
2040 (s.flags() & PARAMETER) == 0)
2041 return true;
2042 }
2043 else if (e.value.name == names.ANNOTATION_TYPE)
2044 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2045 return true;
2046 }
2047 else if (e.value.name == names.PACKAGE)
2048 { if (s.kind == PCK) return true; }
2049 else if (e.value.name == names.TYPE_USE)
2050 { if (s.kind == TYP ||
2051 s.kind == VAR ||
2052 (s.kind == MTH && !s.isConstructor() &&
2053 s.type.getReturnType().tag != VOID))
2054 return true;
2055 }
2056 else
2057 return true; // recovery
2058 }
2059 return false;
2060 }
2062 /** Check an annotation value.
2063 */
2064 public void validateAnnotation(JCAnnotation a) {
2065 if (a.type.isErroneous()) return;
2067 // collect an inventory of the members
2068 Set<MethodSymbol> members = new HashSet<MethodSymbol>();
2069 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2070 e != null;
2071 e = e.sibling)
2072 if (e.sym.kind == MTH)
2073 members.add((MethodSymbol) e.sym);
2075 // count them off as they're annotated
2076 for (JCTree arg : a.args) {
2077 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
2078 JCAssign assign = (JCAssign) arg;
2079 Symbol m = TreeInfo.symbol(assign.lhs);
2080 if (m == null || m.type.isErroneous()) continue;
2081 if (!members.remove(m))
2082 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2083 m.name, a.type);
2084 if (assign.rhs.getTag() == ANNOTATION)
2085 validateAnnotation((JCAnnotation)assign.rhs);
2086 }
2088 // all the remaining ones better have default values
2089 for (MethodSymbol m : members)
2090 if (m.defaultValue == null && !m.type.isErroneous())
2091 log.error(a.pos(), "annotation.missing.default.value",
2092 a.type, m.name);
2094 // special case: java.lang.annotation.Target must not have
2095 // repeated values in its value member
2096 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2097 a.args.tail == null)
2098 return;
2100 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
2101 JCAssign assign = (JCAssign) a.args.head;
2102 Symbol m = TreeInfo.symbol(assign.lhs);
2103 if (m.name != names.value) return;
2104 JCTree rhs = assign.rhs;
2105 if (rhs.getTag() != JCTree.NEWARRAY) return;
2106 JCNewArray na = (JCNewArray) rhs;
2107 Set<Symbol> targets = new HashSet<Symbol>();
2108 for (JCTree elem : na.elems) {
2109 if (!targets.add(TreeInfo.symbol(elem))) {
2110 log.error(elem.pos(), "repeated.annotation.target");
2111 }
2112 }
2113 }
2115 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2116 if (allowAnnotations &&
2117 lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
2118 (s.flags() & DEPRECATED) != 0 &&
2119 !syms.deprecatedType.isErroneous() &&
2120 s.attribute(syms.deprecatedType.tsym) == null) {
2121 log.warning(pos, "missing.deprecated.annotation");
2122 }
2123 }
2125 /* *************************************************************************
2126 * Check for recursive annotation elements.
2127 **************************************************************************/
2129 /** Check for cycles in the graph of annotation elements.
2130 */
2131 void checkNonCyclicElements(JCClassDecl tree) {
2132 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2133 assert (tree.sym.flags_field & LOCKED) == 0;
2134 try {
2135 tree.sym.flags_field |= LOCKED;
2136 for (JCTree def : tree.defs) {
2137 if (def.getTag() != JCTree.METHODDEF) continue;
2138 JCMethodDecl meth = (JCMethodDecl)def;
2139 checkAnnotationResType(meth.pos(), meth.restype.type);
2140 }
2141 } finally {
2142 tree.sym.flags_field &= ~LOCKED;
2143 tree.sym.flags_field |= ACYCLIC_ANN;
2144 }
2145 }
2147 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2148 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2149 return;
2150 if ((tsym.flags_field & LOCKED) != 0) {
2151 log.error(pos, "cyclic.annotation.element");
2152 return;
2153 }
2154 try {
2155 tsym.flags_field |= LOCKED;
2156 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2157 Symbol s = e.sym;
2158 if (s.kind != Kinds.MTH)
2159 continue;
2160 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2161 }
2162 } finally {
2163 tsym.flags_field &= ~LOCKED;
2164 tsym.flags_field |= ACYCLIC_ANN;
2165 }
2166 }
2168 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2169 switch (type.tag) {
2170 case TypeTags.CLASS:
2171 if ((type.tsym.flags() & ANNOTATION) != 0)
2172 checkNonCyclicElementsInternal(pos, type.tsym);
2173 break;
2174 case TypeTags.ARRAY:
2175 checkAnnotationResType(pos, types.elemtype(type));
2176 break;
2177 default:
2178 break; // int etc
2179 }
2180 }
2182 /* *************************************************************************
2183 * Check for cycles in the constructor call graph.
2184 **************************************************************************/
2186 /** Check for cycles in the graph of constructors calling other
2187 * constructors.
2188 */
2189 void checkCyclicConstructors(JCClassDecl tree) {
2190 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2192 // enter each constructor this-call into the map
2193 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2194 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2195 if (app == null) continue;
2196 JCMethodDecl meth = (JCMethodDecl) l.head;
2197 if (TreeInfo.name(app.meth) == names._this) {
2198 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2199 } else {
2200 meth.sym.flags_field |= ACYCLIC;
2201 }
2202 }
2204 // Check for cycles in the map
2205 Symbol[] ctors = new Symbol[0];
2206 ctors = callMap.keySet().toArray(ctors);
2207 for (Symbol caller : ctors) {
2208 checkCyclicConstructor(tree, caller, callMap);
2209 }
2210 }
2212 /** Look in the map to see if the given constructor is part of a
2213 * call cycle.
2214 */
2215 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2216 Map<Symbol,Symbol> callMap) {
2217 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2218 if ((ctor.flags_field & LOCKED) != 0) {
2219 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2220 "recursive.ctor.invocation");
2221 } else {
2222 ctor.flags_field |= LOCKED;
2223 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2224 ctor.flags_field &= ~LOCKED;
2225 }
2226 ctor.flags_field |= ACYCLIC;
2227 }
2228 }
2230 /* *************************************************************************
2231 * Miscellaneous
2232 **************************************************************************/
2234 /**
2235 * Return the opcode of the operator but emit an error if it is an
2236 * error.
2237 * @param pos position for error reporting.
2238 * @param operator an operator
2239 * @param tag a tree tag
2240 * @param left type of left hand side
2241 * @param right type of right hand side
2242 */
2243 int checkOperator(DiagnosticPosition pos,
2244 OperatorSymbol operator,
2245 int tag,
2246 Type left,
2247 Type right) {
2248 if (operator.opcode == ByteCodes.error) {
2249 log.error(pos,
2250 "operator.cant.be.applied",
2251 treeinfo.operatorName(tag),
2252 List.of(left, right));
2253 }
2254 return operator.opcode;
2255 }
2258 /**
2259 * Check for division by integer constant zero
2260 * @param pos Position for error reporting.
2261 * @param operator The operator for the expression
2262 * @param operand The right hand operand for the expression
2263 */
2264 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2265 if (operand.constValue() != null
2266 && lint.isEnabled(Lint.LintCategory.DIVZERO)
2267 && operand.tag <= LONG
2268 && ((Number) (operand.constValue())).longValue() == 0) {
2269 int opc = ((OperatorSymbol)operator).opcode;
2270 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2271 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2272 log.warning(pos, "div.zero");
2273 }
2274 }
2275 }
2277 /**
2278 * Check for empty statements after if
2279 */
2280 void checkEmptyIf(JCIf tree) {
2281 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
2282 log.warning(tree.thenpart.pos(), "empty.if");
2283 }
2285 /** Check that symbol is unique in given scope.
2286 * @param pos Position for error reporting.
2287 * @param sym The symbol.
2288 * @param s The scope.
2289 */
2290 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2291 if (sym.type.isErroneous())
2292 return true;
2293 if (sym.owner.name == names.any) return false;
2294 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2295 if (sym != e.sym &&
2296 sym.kind == e.sym.kind &&
2297 sym.name != names.error &&
2298 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2299 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
2300 varargsDuplicateError(pos, sym, e.sym);
2301 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
2302 duplicateErasureError(pos, sym, e.sym);
2303 else
2304 duplicateError(pos, e.sym);
2305 return false;
2306 }
2307 }
2308 return true;
2309 }
2310 //where
2311 /** Report duplicate declaration error.
2312 */
2313 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2314 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2315 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2316 }
2317 }
2319 /** Check that single-type import is not already imported or top-level defined,
2320 * but make an exception for two single-type imports which denote the same type.
2321 * @param pos Position for error reporting.
2322 * @param sym The symbol.
2323 * @param s The scope
2324 */
2325 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2326 return checkUniqueImport(pos, sym, s, false);
2327 }
2329 /** Check that static single-type import is not already imported or top-level defined,
2330 * but make an exception for two single-type imports which denote the same type.
2331 * @param pos Position for error reporting.
2332 * @param sym The symbol.
2333 * @param s The scope
2334 * @param staticImport Whether or not this was a static import
2335 */
2336 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2337 return checkUniqueImport(pos, sym, s, true);
2338 }
2340 /** Check that single-type import is not already imported or top-level defined,
2341 * but make an exception for two single-type imports which denote the same type.
2342 * @param pos Position for error reporting.
2343 * @param sym The symbol.
2344 * @param s The scope.
2345 * @param staticImport Whether or not this was a static import
2346 */
2347 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2348 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2349 // is encountered class entered via a class declaration?
2350 boolean isClassDecl = e.scope == s;
2351 if ((isClassDecl || sym != e.sym) &&
2352 sym.kind == e.sym.kind &&
2353 sym.name != names.error) {
2354 if (!e.sym.type.isErroneous()) {
2355 String what = e.sym.toString();
2356 if (!isClassDecl) {
2357 if (staticImport)
2358 log.error(pos, "already.defined.static.single.import", what);
2359 else
2360 log.error(pos, "already.defined.single.import", what);
2361 }
2362 else if (sym != e.sym)
2363 log.error(pos, "already.defined.this.unit", what);
2364 }
2365 return false;
2366 }
2367 }
2368 return true;
2369 }
2371 /** Check that a qualified name is in canonical form (for import decls).
2372 */
2373 public void checkCanonical(JCTree tree) {
2374 if (!isCanonical(tree))
2375 log.error(tree.pos(), "import.requires.canonical",
2376 TreeInfo.symbol(tree));
2377 }
2378 // where
2379 private boolean isCanonical(JCTree tree) {
2380 while (tree.getTag() == JCTree.SELECT) {
2381 JCFieldAccess s = (JCFieldAccess) tree;
2382 if (s.sym.owner != TreeInfo.symbol(s.selected))
2383 return false;
2384 tree = s.selected;
2385 }
2386 return true;
2387 }
2389 private class ConversionWarner extends Warner {
2390 final String key;
2391 final Type found;
2392 final Type expected;
2393 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
2394 super(pos);
2395 this.key = key;
2396 this.found = found;
2397 this.expected = expected;
2398 }
2400 @Override
2401 public void warnUnchecked() {
2402 boolean warned = this.warned;
2403 super.warnUnchecked();
2404 if (warned) return; // suppress redundant diagnostics
2405 Object problem = diags.fragment(key);
2406 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
2407 }
2408 }
2410 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2411 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2412 }
2414 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2415 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2416 }
2417 }