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