Fri, 16 Jul 2010 19:35:24 -0700
6911256: Project Coin: Support Automatic Resource Management (ARM) blocks in the compiler
6964740: Project Coin: More tests for ARM compiler changes
6965277: Project Coin: Correctness issues in ARM implementation
6967065: add -Xlint warning category for Automatic Resource Management (ARM)
Reviewed-by: jjb, darcy, mcimadamore, jjg, briangoetz
Contributed-by: tball@google.com
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");
115 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
116 enforceMandatoryWarnings, "unchecked");
117 unsafeVarargsHandler = new MandatoryWarningHandler(log, verboseVarargs,
118 enforceMandatoryWarnings, "varargs");
119 sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
120 enforceMandatoryWarnings, "sunapi");
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(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(tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
933 }
934 }
936 /** Visitor method: Validate a list of type expressions.
937 */
938 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
939 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
940 validate(l.head, env);
941 }
943 /** A visitor class for type validation.
944 */
945 class Validator extends JCTree.Visitor {
947 @Override
948 public void visitTypeArray(JCArrayTypeTree tree) {
949 validate(tree.elemtype, env);
950 }
952 @Override
953 public void visitTypeApply(JCTypeApply tree) {
954 if (tree.type.tag == CLASS) {
955 List<Type> formals = tree.type.tsym.type.allparams();
956 List<Type> actuals = tree.type.allparams();
957 List<JCExpression> args = tree.arguments;
958 List<Type> forms = tree.type.tsym.type.getTypeArguments();
959 ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
961 // For matching pairs of actual argument types `a' and
962 // formal type parameters with declared bound `b' ...
963 while (args.nonEmpty() && forms.nonEmpty()) {
964 validate(args.head, env);
966 // exact type arguments needs to know their
967 // bounds (for upper and lower bound
968 // calculations). So we create new TypeVars with
969 // bounds substed with actuals.
970 tvars_buf.append(types.substBound(((TypeVar)forms.head),
971 formals,
972 actuals));
974 args = args.tail;
975 forms = forms.tail;
976 }
978 args = tree.arguments;
979 List<Type> tvars_cap = types.substBounds(formals,
980 formals,
981 types.capture(tree.type).allparams());
982 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
983 // Let the actual arguments know their bound
984 args.head.type.withTypeVar((TypeVar)tvars_cap.head);
985 args = args.tail;
986 tvars_cap = tvars_cap.tail;
987 }
989 args = tree.arguments;
990 List<Type> tvars = tvars_buf.toList();
992 while (args.nonEmpty() && tvars.nonEmpty()) {
993 Type actual = types.subst(args.head.type,
994 tree.type.tsym.type.getTypeArguments(),
995 tvars_buf.toList());
996 checkExtends(args.head.pos(),
997 actual,
998 (TypeVar)tvars.head);
999 args = args.tail;
1000 tvars = tvars.tail;
1001 }
1003 checkCapture(tree);
1005 // Check that this type is either fully parameterized, or
1006 // not parameterized at all.
1007 if (tree.type.getEnclosingType().isRaw())
1008 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1009 if (tree.clazz.getTag() == JCTree.SELECT)
1010 visitSelectInternal((JCFieldAccess)tree.clazz);
1011 }
1012 }
1014 @Override
1015 public void visitTypeParameter(JCTypeParameter tree) {
1016 validate(tree.bounds, env);
1017 checkClassBounds(tree.pos(), tree.type);
1018 }
1020 @Override
1021 public void visitWildcard(JCWildcard tree) {
1022 if (tree.inner != null)
1023 validate(tree.inner, env);
1024 }
1026 @Override
1027 public void visitSelect(JCFieldAccess tree) {
1028 if (tree.type.tag == CLASS) {
1029 visitSelectInternal(tree);
1031 // Check that this type is either fully parameterized, or
1032 // not parameterized at all.
1033 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1034 log.error(tree.pos(), "improperly.formed.type.param.missing");
1035 }
1036 }
1037 public void visitSelectInternal(JCFieldAccess tree) {
1038 if (tree.type.tsym.isStatic() &&
1039 tree.selected.type.isParameterized()) {
1040 // The enclosing type is not a class, so we are
1041 // looking at a static member type. However, the
1042 // qualifying expression is parameterized.
1043 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1044 } else {
1045 // otherwise validate the rest of the expression
1046 tree.selected.accept(this);
1047 }
1048 }
1050 @Override
1051 public void visitAnnotatedType(JCAnnotatedType tree) {
1052 tree.underlyingType.accept(this);
1053 }
1055 /** Default visitor method: do nothing.
1056 */
1057 @Override
1058 public void visitTree(JCTree tree) {
1059 }
1061 Env<AttrContext> env;
1062 }
1064 /* *************************************************************************
1065 * Exception checking
1066 **************************************************************************/
1068 /* The following methods treat classes as sets that contain
1069 * the class itself and all their subclasses
1070 */
1072 /** Is given type a subtype of some of the types in given list?
1073 */
1074 boolean subset(Type t, List<Type> ts) {
1075 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1076 if (types.isSubtype(t, l.head)) return true;
1077 return false;
1078 }
1080 /** Is given type a subtype or supertype of
1081 * some of the types in given list?
1082 */
1083 boolean intersects(Type t, List<Type> ts) {
1084 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1085 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1086 return false;
1087 }
1089 /** Add type set to given type list, unless it is a subclass of some class
1090 * in the list.
1091 */
1092 List<Type> incl(Type t, List<Type> ts) {
1093 return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1094 }
1096 /** Remove type set from type set list.
1097 */
1098 List<Type> excl(Type t, List<Type> ts) {
1099 if (ts.isEmpty()) {
1100 return ts;
1101 } else {
1102 List<Type> ts1 = excl(t, ts.tail);
1103 if (types.isSubtype(ts.head, t)) return ts1;
1104 else if (ts1 == ts.tail) return ts;
1105 else return ts1.prepend(ts.head);
1106 }
1107 }
1109 /** Form the union of two type set lists.
1110 */
1111 List<Type> union(List<Type> ts1, List<Type> ts2) {
1112 List<Type> ts = ts1;
1113 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1114 ts = incl(l.head, ts);
1115 return ts;
1116 }
1118 /** Form the difference of two type lists.
1119 */
1120 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1121 List<Type> ts = ts1;
1122 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1123 ts = excl(l.head, ts);
1124 return ts;
1125 }
1127 /** Form the intersection of two type lists.
1128 */
1129 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1130 List<Type> ts = List.nil();
1131 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1132 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1133 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1134 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1135 return ts;
1136 }
1138 /** Is exc an exception symbol that need not be declared?
1139 */
1140 boolean isUnchecked(ClassSymbol exc) {
1141 return
1142 exc.kind == ERR ||
1143 exc.isSubClass(syms.errorType.tsym, types) ||
1144 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1145 }
1147 /** Is exc an exception type that need not be declared?
1148 */
1149 boolean isUnchecked(Type exc) {
1150 return
1151 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
1152 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
1153 exc.tag == BOT;
1154 }
1156 /** Same, but handling completion failures.
1157 */
1158 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1159 try {
1160 return isUnchecked(exc);
1161 } catch (CompletionFailure ex) {
1162 completionError(pos, ex);
1163 return true;
1164 }
1165 }
1167 /** Is exc handled by given exception list?
1168 */
1169 boolean isHandled(Type exc, List<Type> handled) {
1170 return isUnchecked(exc) || subset(exc, handled);
1171 }
1173 /** Return all exceptions in thrown list that are not in handled list.
1174 * @param thrown The list of thrown exceptions.
1175 * @param handled The list of handled exceptions.
1176 */
1177 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1178 List<Type> unhandled = List.nil();
1179 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1180 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1181 return unhandled;
1182 }
1184 /* *************************************************************************
1185 * Overriding/Implementation checking
1186 **************************************************************************/
1188 /** The level of access protection given by a flag set,
1189 * where PRIVATE is highest and PUBLIC is lowest.
1190 */
1191 static int protection(long flags) {
1192 switch ((short)(flags & AccessFlags)) {
1193 case PRIVATE: return 3;
1194 case PROTECTED: return 1;
1195 default:
1196 case PUBLIC: return 0;
1197 case 0: return 2;
1198 }
1199 }
1201 /** A customized "cannot override" error message.
1202 * @param m The overriding method.
1203 * @param other The overridden method.
1204 * @return An internationalized string.
1205 */
1206 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1207 String key;
1208 if ((other.owner.flags() & INTERFACE) == 0)
1209 key = "cant.override";
1210 else if ((m.owner.flags() & INTERFACE) == 0)
1211 key = "cant.implement";
1212 else
1213 key = "clashes.with";
1214 return diags.fragment(key, m, m.location(), other, other.location());
1215 }
1217 /** A customized "override" warning message.
1218 * @param m The overriding method.
1219 * @param other The overridden method.
1220 * @return An internationalized string.
1221 */
1222 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1223 String key;
1224 if ((other.owner.flags() & INTERFACE) == 0)
1225 key = "unchecked.override";
1226 else if ((m.owner.flags() & INTERFACE) == 0)
1227 key = "unchecked.implement";
1228 else
1229 key = "unchecked.clash.with";
1230 return diags.fragment(key, m, m.location(), other, other.location());
1231 }
1233 /** A customized "override" warning message.
1234 * @param m The overriding method.
1235 * @param other The overridden method.
1236 * @return An internationalized string.
1237 */
1238 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1239 String key;
1240 if ((other.owner.flags() & INTERFACE) == 0)
1241 key = "varargs.override";
1242 else if ((m.owner.flags() & INTERFACE) == 0)
1243 key = "varargs.implement";
1244 else
1245 key = "varargs.clash.with";
1246 return diags.fragment(key, m, m.location(), other, other.location());
1247 }
1249 /** Check that this method conforms with overridden method 'other'.
1250 * where `origin' is the class where checking started.
1251 * Complications:
1252 * (1) Do not check overriding of synthetic methods
1253 * (reason: they might be final).
1254 * todo: check whether this is still necessary.
1255 * (2) Admit the case where an interface proxy throws fewer exceptions
1256 * than the method it implements. Augment the proxy methods with the
1257 * undeclared exceptions in this case.
1258 * (3) When generics are enabled, admit the case where an interface proxy
1259 * has a result type
1260 * extended by the result type of the method it implements.
1261 * Change the proxies result type to the smaller type in this case.
1262 *
1263 * @param tree The tree from which positions
1264 * are extracted for errors.
1265 * @param m The overriding method.
1266 * @param other The overridden method.
1267 * @param origin The class of which the overriding method
1268 * is a member.
1269 */
1270 void checkOverride(JCTree tree,
1271 MethodSymbol m,
1272 MethodSymbol other,
1273 ClassSymbol origin) {
1274 // Don't check overriding of synthetic methods or by bridge methods.
1275 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1276 return;
1277 }
1279 // Error if static method overrides instance method (JLS 8.4.6.2).
1280 if ((m.flags() & STATIC) != 0 &&
1281 (other.flags() & STATIC) == 0) {
1282 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1283 cannotOverride(m, other));
1284 return;
1285 }
1287 // Error if instance method overrides static or final
1288 // method (JLS 8.4.6.1).
1289 if ((other.flags() & FINAL) != 0 ||
1290 (m.flags() & STATIC) == 0 &&
1291 (other.flags() & STATIC) != 0) {
1292 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1293 cannotOverride(m, other),
1294 asFlagSet(other.flags() & (FINAL | STATIC)));
1295 return;
1296 }
1298 if ((m.owner.flags() & ANNOTATION) != 0) {
1299 // handled in validateAnnotationMethod
1300 return;
1301 }
1303 // Error if overriding method has weaker access (JLS 8.4.6.3).
1304 if ((origin.flags() & INTERFACE) == 0 &&
1305 protection(m.flags()) > protection(other.flags())) {
1306 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1307 cannotOverride(m, other),
1308 other.flags() == 0 ?
1309 Flag.PACKAGE :
1310 asFlagSet(other.flags() & AccessFlags));
1311 return;
1312 }
1314 Type mt = types.memberType(origin.type, m);
1315 Type ot = types.memberType(origin.type, other);
1316 // Error if overriding result type is different
1317 // (or, in the case of generics mode, not a subtype) of
1318 // overridden result type. We have to rename any type parameters
1319 // before comparing types.
1320 List<Type> mtvars = mt.getTypeArguments();
1321 List<Type> otvars = ot.getTypeArguments();
1322 Type mtres = mt.getReturnType();
1323 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1325 overrideWarner.warned = false;
1326 boolean resultTypesOK =
1327 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1328 if (!resultTypesOK) {
1329 if (!allowCovariantReturns &&
1330 m.owner != origin &&
1331 m.owner.isSubClass(other.owner, types)) {
1332 // allow limited interoperability with covariant returns
1333 } else {
1334 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1335 "override.incompatible.ret",
1336 cannotOverride(m, other),
1337 mtres, otres);
1338 return;
1339 }
1340 } else if (overrideWarner.warned) {
1341 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1342 "override.unchecked.ret",
1343 uncheckedOverrides(m, other),
1344 mtres, otres);
1345 }
1347 // Error if overriding method throws an exception not reported
1348 // by overridden method.
1349 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1350 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1351 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1352 if (unhandledErased.nonEmpty()) {
1353 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1354 "override.meth.doesnt.throw",
1355 cannotOverride(m, other),
1356 unhandledUnerased.head);
1357 return;
1358 }
1359 else if (unhandledUnerased.nonEmpty()) {
1360 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1361 "override.unchecked.thrown",
1362 cannotOverride(m, other),
1363 unhandledUnerased.head);
1364 return;
1365 }
1367 // Optional warning if varargs don't agree
1368 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1369 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
1370 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1371 ((m.flags() & Flags.VARARGS) != 0)
1372 ? "override.varargs.missing"
1373 : "override.varargs.extra",
1374 varargsOverrides(m, other));
1375 }
1377 // Warn if instance method overrides bridge method (compiler spec ??)
1378 if ((other.flags() & BRIDGE) != 0) {
1379 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1380 uncheckedOverrides(m, other));
1381 }
1383 // Warn if a deprecated method overridden by a non-deprecated one.
1384 if ((other.flags() & DEPRECATED) != 0
1385 && (m.flags() & DEPRECATED) == 0
1386 && m.outermostClass() != other.outermostClass()
1387 && !isDeprecatedOverrideIgnorable(other, origin)) {
1388 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
1389 }
1390 }
1391 // where
1392 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1393 // If the method, m, is defined in an interface, then ignore the issue if the method
1394 // is only inherited via a supertype and also implemented in the supertype,
1395 // because in that case, we will rediscover the issue when examining the method
1396 // in the supertype.
1397 // If the method, m, is not defined in an interface, then the only time we need to
1398 // address the issue is when the method is the supertype implemementation: any other
1399 // case, we will have dealt with when examining the supertype classes
1400 ClassSymbol mc = m.enclClass();
1401 Type st = types.supertype(origin.type);
1402 if (st.tag != CLASS)
1403 return true;
1404 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1406 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1407 List<Type> intfs = types.interfaces(origin.type);
1408 return (intfs.contains(mc.type) ? false : (stimpl != null));
1409 }
1410 else
1411 return (stimpl != m);
1412 }
1415 // used to check if there were any unchecked conversions
1416 Warner overrideWarner = new Warner();
1418 /** Check that a class does not inherit two concrete methods
1419 * with the same signature.
1420 * @param pos Position to be used for error reporting.
1421 * @param site The class type to be checked.
1422 */
1423 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1424 Type sup = types.supertype(site);
1425 if (sup.tag != CLASS) return;
1427 for (Type t1 = sup;
1428 t1.tsym.type.isParameterized();
1429 t1 = types.supertype(t1)) {
1430 for (Scope.Entry e1 = t1.tsym.members().elems;
1431 e1 != null;
1432 e1 = e1.sibling) {
1433 Symbol s1 = e1.sym;
1434 if (s1.kind != MTH ||
1435 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1436 !s1.isInheritedIn(site.tsym, types) ||
1437 ((MethodSymbol)s1).implementation(site.tsym,
1438 types,
1439 true) != s1)
1440 continue;
1441 Type st1 = types.memberType(t1, s1);
1442 int s1ArgsLength = st1.getParameterTypes().length();
1443 if (st1 == s1.type) continue;
1445 for (Type t2 = sup;
1446 t2.tag == CLASS;
1447 t2 = types.supertype(t2)) {
1448 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
1449 e2.scope != null;
1450 e2 = e2.next()) {
1451 Symbol s2 = e2.sym;
1452 if (s2 == s1 ||
1453 s2.kind != MTH ||
1454 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1455 s2.type.getParameterTypes().length() != s1ArgsLength ||
1456 !s2.isInheritedIn(site.tsym, types) ||
1457 ((MethodSymbol)s2).implementation(site.tsym,
1458 types,
1459 true) != s2)
1460 continue;
1461 Type st2 = types.memberType(t2, s2);
1462 if (types.overrideEquivalent(st1, st2))
1463 log.error(pos, "concrete.inheritance.conflict",
1464 s1, t1, s2, t2, sup);
1465 }
1466 }
1467 }
1468 }
1469 }
1471 /** Check that classes (or interfaces) do not each define an abstract
1472 * method with same name and arguments but incompatible return types.
1473 * @param pos Position to be used for error reporting.
1474 * @param t1 The first argument type.
1475 * @param t2 The second argument type.
1476 */
1477 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1478 Type t1,
1479 Type t2) {
1480 return checkCompatibleAbstracts(pos, t1, t2,
1481 types.makeCompoundType(t1, t2));
1482 }
1484 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1485 Type t1,
1486 Type t2,
1487 Type site) {
1488 Symbol sym = firstIncompatibility(t1, t2, site);
1489 if (sym != null) {
1490 log.error(pos, "types.incompatible.diff.ret",
1491 t1, t2, sym.name +
1492 "(" + types.memberType(t2, sym).getParameterTypes() + ")");
1493 return false;
1494 }
1495 return true;
1496 }
1498 /** Return the first method which is defined with same args
1499 * but different return types in two given interfaces, or null if none
1500 * exists.
1501 * @param t1 The first type.
1502 * @param t2 The second type.
1503 * @param site The most derived type.
1504 * @returns symbol from t2 that conflicts with one in t1.
1505 */
1506 private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
1507 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
1508 closure(t1, interfaces1);
1509 Map<TypeSymbol,Type> interfaces2;
1510 if (t1 == t2)
1511 interfaces2 = interfaces1;
1512 else
1513 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
1515 for (Type t3 : interfaces1.values()) {
1516 for (Type t4 : interfaces2.values()) {
1517 Symbol s = firstDirectIncompatibility(t3, t4, site);
1518 if (s != null) return s;
1519 }
1520 }
1521 return null;
1522 }
1524 /** Compute all the supertypes of t, indexed by type symbol. */
1525 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1526 if (t.tag != CLASS) return;
1527 if (typeMap.put(t.tsym, t) == null) {
1528 closure(types.supertype(t), typeMap);
1529 for (Type i : types.interfaces(t))
1530 closure(i, typeMap);
1531 }
1532 }
1534 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1535 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1536 if (t.tag != CLASS) return;
1537 if (typesSkip.get(t.tsym) != null) return;
1538 if (typeMap.put(t.tsym, t) == null) {
1539 closure(types.supertype(t), typesSkip, typeMap);
1540 for (Type i : types.interfaces(t))
1541 closure(i, typesSkip, typeMap);
1542 }
1543 }
1545 /** Return the first method in t2 that conflicts with a method from t1. */
1546 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
1547 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
1548 Symbol s1 = e1.sym;
1549 Type st1 = null;
1550 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
1551 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1552 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
1553 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
1554 Symbol s2 = e2.sym;
1555 if (s1 == s2) continue;
1556 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
1557 if (st1 == null) st1 = types.memberType(t1, s1);
1558 Type st2 = types.memberType(t2, s2);
1559 if (types.overrideEquivalent(st1, st2)) {
1560 List<Type> tvars1 = st1.getTypeArguments();
1561 List<Type> tvars2 = st2.getTypeArguments();
1562 Type rt1 = st1.getReturnType();
1563 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
1564 boolean compat =
1565 types.isSameType(rt1, rt2) ||
1566 rt1.tag >= CLASS && rt2.tag >= CLASS &&
1567 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
1568 types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
1569 checkCommonOverriderIn(s1,s2,site);
1570 if (!compat) return s2;
1571 }
1572 }
1573 }
1574 return null;
1575 }
1576 //WHERE
1577 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
1578 Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
1579 Type st1 = types.memberType(site, s1);
1580 Type st2 = types.memberType(site, s2);
1581 closure(site, supertypes);
1582 for (Type t : supertypes.values()) {
1583 for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
1584 Symbol s3 = e.sym;
1585 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
1586 Type st3 = types.memberType(site,s3);
1587 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
1588 if (s3.owner == site.tsym) {
1589 return true;
1590 }
1591 List<Type> tvars1 = st1.getTypeArguments();
1592 List<Type> tvars2 = st2.getTypeArguments();
1593 List<Type> tvars3 = st3.getTypeArguments();
1594 Type rt1 = st1.getReturnType();
1595 Type rt2 = st2.getReturnType();
1596 Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
1597 Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
1598 boolean compat =
1599 rt13.tag >= CLASS && rt23.tag >= CLASS &&
1600 (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
1601 types.covariantReturnType(rt23, rt2, Warner.noWarnings));
1602 if (compat)
1603 return true;
1604 }
1605 }
1606 }
1607 return false;
1608 }
1610 /** Check that a given method conforms with any method it overrides.
1611 * @param tree The tree from which positions are extracted
1612 * for errors.
1613 * @param m The overriding method.
1614 */
1615 void checkOverride(JCTree tree, MethodSymbol m) {
1616 ClassSymbol origin = (ClassSymbol)m.owner;
1617 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
1618 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
1619 log.error(tree.pos(), "enum.no.finalize");
1620 return;
1621 }
1622 for (Type t = types.supertype(origin.type); t.tag == CLASS;
1623 t = types.supertype(t)) {
1624 TypeSymbol c = t.tsym;
1625 Scope.Entry e = c.members().lookup(m.name);
1626 while (e.scope != null) {
1627 if (m.overrides(e.sym, origin, types, false))
1628 checkOverride(tree, m, (MethodSymbol)e.sym, origin);
1629 else if (e.sym.kind == MTH &&
1630 e.sym.isInheritedIn(origin, types) &&
1631 (e.sym.flags() & SYNTHETIC) == 0 &&
1632 !m.isConstructor()) {
1633 Type er1 = m.erasure(types);
1634 Type er2 = e.sym.erasure(types);
1635 if (types.isSameTypes(er1.getParameterTypes(),
1636 er2.getParameterTypes())) {
1637 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1638 "name.clash.same.erasure.no.override",
1639 m, m.location(),
1640 e.sym, e.sym.location());
1641 }
1642 }
1643 e = e.next();
1644 }
1645 }
1646 }
1648 /** Check that all abstract members of given class have definitions.
1649 * @param pos Position to be used for error reporting.
1650 * @param c The class.
1651 */
1652 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
1653 try {
1654 MethodSymbol undef = firstUndef(c, c);
1655 if (undef != null) {
1656 if ((c.flags() & ENUM) != 0 &&
1657 types.supertype(c.type).tsym == syms.enumSym &&
1658 (c.flags() & FINAL) == 0) {
1659 // add the ABSTRACT flag to an enum
1660 c.flags_field |= ABSTRACT;
1661 } else {
1662 MethodSymbol undef1 =
1663 new MethodSymbol(undef.flags(), undef.name,
1664 types.memberType(c.type, undef), undef.owner);
1665 log.error(pos, "does.not.override.abstract",
1666 c, undef1, undef1.location());
1667 }
1668 }
1669 } catch (CompletionFailure ex) {
1670 completionError(pos, ex);
1671 }
1672 }
1673 //where
1674 /** Return first abstract member of class `c' that is not defined
1675 * in `impl', null if there is none.
1676 */
1677 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
1678 MethodSymbol undef = null;
1679 // Do not bother to search in classes that are not abstract,
1680 // since they cannot have abstract members.
1681 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
1682 Scope s = c.members();
1683 for (Scope.Entry e = s.elems;
1684 undef == null && e != null;
1685 e = e.sibling) {
1686 if (e.sym.kind == MTH &&
1687 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
1688 MethodSymbol absmeth = (MethodSymbol)e.sym;
1689 MethodSymbol implmeth = absmeth.implementation(impl, types, true);
1690 if (implmeth == null || implmeth == absmeth)
1691 undef = absmeth;
1692 }
1693 }
1694 if (undef == null) {
1695 Type st = types.supertype(c.type);
1696 if (st.tag == CLASS)
1697 undef = firstUndef(impl, (ClassSymbol)st.tsym);
1698 }
1699 for (List<Type> l = types.interfaces(c.type);
1700 undef == null && l.nonEmpty();
1701 l = l.tail) {
1702 undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
1703 }
1704 }
1705 return undef;
1706 }
1708 /** Check for cyclic references. Issue an error if the
1709 * symbol of the type referred to has a LOCKED flag set.
1710 *
1711 * @param pos Position to be used for error reporting.
1712 * @param t The type referred to.
1713 */
1714 void checkNonCyclic(DiagnosticPosition pos, Type t) {
1715 checkNonCyclicInternal(pos, t);
1716 }
1719 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
1720 checkNonCyclic1(pos, t, List.<TypeVar>nil());
1721 }
1723 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
1724 final TypeVar tv;
1725 if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
1726 return;
1727 if (seen.contains(t)) {
1728 tv = (TypeVar)t;
1729 tv.bound = types.createErrorType(t);
1730 log.error(pos, "cyclic.inheritance", t);
1731 } else if (t.tag == TYPEVAR) {
1732 tv = (TypeVar)t;
1733 seen = seen.prepend(tv);
1734 for (Type b : types.getBounds(tv))
1735 checkNonCyclic1(pos, b, seen);
1736 }
1737 }
1739 /** Check for cyclic references. Issue an error if the
1740 * symbol of the type referred to has a LOCKED flag set.
1741 *
1742 * @param pos Position to be used for error reporting.
1743 * @param t The type referred to.
1744 * @returns True if the check completed on all attributed classes
1745 */
1746 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
1747 boolean complete = true; // was the check complete?
1748 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
1749 Symbol c = t.tsym;
1750 if ((c.flags_field & ACYCLIC) != 0) return true;
1752 if ((c.flags_field & LOCKED) != 0) {
1753 noteCyclic(pos, (ClassSymbol)c);
1754 } else if (!c.type.isErroneous()) {
1755 try {
1756 c.flags_field |= LOCKED;
1757 if (c.type.tag == CLASS) {
1758 ClassType clazz = (ClassType)c.type;
1759 if (clazz.interfaces_field != null)
1760 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
1761 complete &= checkNonCyclicInternal(pos, l.head);
1762 if (clazz.supertype_field != null) {
1763 Type st = clazz.supertype_field;
1764 if (st != null && st.tag == CLASS)
1765 complete &= checkNonCyclicInternal(pos, st);
1766 }
1767 if (c.owner.kind == TYP)
1768 complete &= checkNonCyclicInternal(pos, c.owner.type);
1769 }
1770 } finally {
1771 c.flags_field &= ~LOCKED;
1772 }
1773 }
1774 if (complete)
1775 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
1776 if (complete) c.flags_field |= ACYCLIC;
1777 return complete;
1778 }
1780 /** Note that we found an inheritance cycle. */
1781 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
1782 log.error(pos, "cyclic.inheritance", c);
1783 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
1784 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
1785 Type st = types.supertype(c.type);
1786 if (st.tag == CLASS)
1787 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
1788 c.type = types.createErrorType(c, c.type);
1789 c.flags_field |= ACYCLIC;
1790 }
1792 /** Check that all methods which implement some
1793 * method conform to the method they implement.
1794 * @param tree The class definition whose members are checked.
1795 */
1796 void checkImplementations(JCClassDecl tree) {
1797 checkImplementations(tree, tree.sym);
1798 }
1799 //where
1800 /** Check that all methods which implement some
1801 * method in `ic' conform to the method they implement.
1802 */
1803 void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
1804 ClassSymbol origin = tree.sym;
1805 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
1806 ClassSymbol lc = (ClassSymbol)l.head.tsym;
1807 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
1808 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
1809 if (e.sym.kind == MTH &&
1810 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
1811 MethodSymbol absmeth = (MethodSymbol)e.sym;
1812 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
1813 if (implmeth != null && implmeth != absmeth &&
1814 (implmeth.owner.flags() & INTERFACE) ==
1815 (origin.flags() & INTERFACE)) {
1816 // don't check if implmeth is in a class, yet
1817 // origin is an interface. This case arises only
1818 // if implmeth is declared in Object. The reason is
1819 // that interfaces really don't inherit from
1820 // Object it's just that the compiler represents
1821 // things that way.
1822 checkOverride(tree, implmeth, absmeth, origin);
1823 }
1824 }
1825 }
1826 }
1827 }
1828 }
1830 /** Check that all abstract methods implemented by a class are
1831 * mutually compatible.
1832 * @param pos Position to be used for error reporting.
1833 * @param c The class whose interfaces are checked.
1834 */
1835 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
1836 List<Type> supertypes = types.interfaces(c);
1837 Type supertype = types.supertype(c);
1838 if (supertype.tag == CLASS &&
1839 (supertype.tsym.flags() & ABSTRACT) != 0)
1840 supertypes = supertypes.prepend(supertype);
1841 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
1842 if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
1843 !checkCompatibleAbstracts(pos, l.head, l.head, c))
1844 return;
1845 for (List<Type> m = supertypes; m != l; m = m.tail)
1846 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
1847 return;
1848 }
1849 checkCompatibleConcretes(pos, c);
1850 }
1852 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
1853 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
1854 for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
1855 // VM allows methods and variables with differing types
1856 if (sym.kind == e.sym.kind &&
1857 types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
1858 sym != e.sym &&
1859 (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
1860 (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
1861 (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
1862 syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
1863 return;
1864 }
1865 }
1866 }
1867 }
1869 /** Report a conflict between a user symbol and a synthetic symbol.
1870 */
1871 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
1872 if (!sym.type.isErroneous()) {
1873 if (warnOnSyntheticConflicts) {
1874 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
1875 }
1876 else {
1877 log.error(pos, "synthetic.name.conflict", sym, sym.location());
1878 }
1879 }
1880 }
1882 /** Check that class c does not implement directly or indirectly
1883 * the same parameterized interface with two different argument lists.
1884 * @param pos Position to be used for error reporting.
1885 * @param type The type whose interfaces are checked.
1886 */
1887 void checkClassBounds(DiagnosticPosition pos, Type type) {
1888 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
1889 }
1890 //where
1891 /** Enter all interfaces of type `type' into the hash table `seensofar'
1892 * with their class symbol as key and their type as value. Make
1893 * sure no class is entered with two different types.
1894 */
1895 void checkClassBounds(DiagnosticPosition pos,
1896 Map<TypeSymbol,Type> seensofar,
1897 Type type) {
1898 if (type.isErroneous()) return;
1899 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
1900 Type it = l.head;
1901 Type oldit = seensofar.put(it.tsym, it);
1902 if (oldit != null) {
1903 List<Type> oldparams = oldit.allparams();
1904 List<Type> newparams = it.allparams();
1905 if (!types.containsTypeEquivalent(oldparams, newparams))
1906 log.error(pos, "cant.inherit.diff.arg",
1907 it.tsym, Type.toString(oldparams),
1908 Type.toString(newparams));
1909 }
1910 checkClassBounds(pos, seensofar, it);
1911 }
1912 Type st = types.supertype(type);
1913 if (st != null) checkClassBounds(pos, seensofar, st);
1914 }
1916 /** Enter interface into into set.
1917 * If it existed already, issue a "repeated interface" error.
1918 */
1919 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
1920 if (its.contains(it))
1921 log.error(pos, "repeated.interface");
1922 else {
1923 its.add(it);
1924 }
1925 }
1927 /* *************************************************************************
1928 * Check annotations
1929 **************************************************************************/
1931 /** Annotation types are restricted to primitives, String, an
1932 * enum, an annotation, Class, Class<?>, Class<? extends
1933 * Anything>, arrays of the preceding.
1934 */
1935 void validateAnnotationType(JCTree restype) {
1936 // restype may be null if an error occurred, so don't bother validating it
1937 if (restype != null) {
1938 validateAnnotationType(restype.pos(), restype.type);
1939 }
1940 }
1942 void validateAnnotationType(DiagnosticPosition pos, Type type) {
1943 if (type.isPrimitive()) return;
1944 if (types.isSameType(type, syms.stringType)) return;
1945 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
1946 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
1947 if (types.lowerBound(type).tsym == syms.classType.tsym) return;
1948 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
1949 validateAnnotationType(pos, types.elemtype(type));
1950 return;
1951 }
1952 log.error(pos, "invalid.annotation.member.type");
1953 }
1955 /**
1956 * "It is also a compile-time error if any method declared in an
1957 * annotation type has a signature that is override-equivalent to
1958 * that of any public or protected method declared in class Object
1959 * or in the interface annotation.Annotation."
1960 *
1961 * @jls3 9.6 Annotation Types
1962 */
1963 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
1964 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
1965 Scope s = sup.tsym.members();
1966 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
1967 if (e.sym.kind == MTH &&
1968 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
1969 types.overrideEquivalent(m.type, e.sym.type))
1970 log.error(pos, "intf.annotation.member.clash", e.sym, sup);
1971 }
1972 }
1973 }
1975 /** Check the annotations of a symbol.
1976 */
1977 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
1978 if (skipAnnotations) return;
1979 for (JCAnnotation a : annotations)
1980 validateAnnotation(a, s);
1981 }
1983 /** Check the type annotations
1984 */
1985 public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
1986 if (skipAnnotations) return;
1987 for (JCTypeAnnotation a : annotations)
1988 validateTypeAnnotation(a, isTypeParameter);
1989 }
1991 /** Check an annotation of a symbol.
1992 */
1993 public void validateAnnotation(JCAnnotation a, Symbol s) {
1994 validateAnnotation(a);
1996 if (!annotationApplicable(a, s))
1997 log.error(a.pos(), "annotation.type.not.applicable");
1999 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2000 if (!isOverrider(s))
2001 log.error(a.pos(), "method.does.not.override.superclass");
2002 }
2003 }
2005 public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
2006 if (a.type == null)
2007 throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
2008 validateAnnotation(a);
2010 if (!isTypeAnnotation(a, isTypeParameter))
2011 log.error(a.pos(), "annotation.type.not.applicable");
2012 }
2014 /** Is s a method symbol that overrides a method in a superclass? */
2015 boolean isOverrider(Symbol s) {
2016 if (s.kind != MTH || s.isStatic())
2017 return false;
2018 MethodSymbol m = (MethodSymbol)s;
2019 TypeSymbol owner = (TypeSymbol)m.owner;
2020 for (Type sup : types.closure(owner.type)) {
2021 if (sup == owner.type)
2022 continue; // skip "this"
2023 Scope scope = sup.tsym.members();
2024 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
2025 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
2026 return true;
2027 }
2028 }
2029 return false;
2030 }
2032 /** Is the annotation applicable to type annotations */
2033 boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
2034 Attribute.Compound atTarget =
2035 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2036 if (atTarget == null) return true;
2037 Attribute atValue = atTarget.member(names.value);
2038 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2039 Attribute.Array arr = (Attribute.Array) atValue;
2040 for (Attribute app : arr.values) {
2041 if (!(app instanceof Attribute.Enum)) return true; // recovery
2042 Attribute.Enum e = (Attribute.Enum) app;
2043 if (!isTypeParameter && e.value.name == names.TYPE_USE)
2044 return true;
2045 else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
2046 return true;
2047 }
2048 return false;
2049 }
2051 /** Is the annotation applicable to the symbol? */
2052 boolean annotationApplicable(JCAnnotation a, Symbol s) {
2053 Attribute.Compound atTarget =
2054 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
2055 if (atTarget == null) return true;
2056 Attribute atValue = atTarget.member(names.value);
2057 if (!(atValue instanceof Attribute.Array)) return true; // error recovery
2058 Attribute.Array arr = (Attribute.Array) atValue;
2059 for (Attribute app : arr.values) {
2060 if (!(app instanceof Attribute.Enum)) return true; // recovery
2061 Attribute.Enum e = (Attribute.Enum) app;
2062 if (e.value.name == names.TYPE)
2063 { if (s.kind == TYP) return true; }
2064 else if (e.value.name == names.FIELD)
2065 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
2066 else if (e.value.name == names.METHOD)
2067 { if (s.kind == MTH && !s.isConstructor()) return true; }
2068 else if (e.value.name == names.PARAMETER)
2069 { if (s.kind == VAR &&
2070 s.owner.kind == MTH &&
2071 (s.flags() & PARAMETER) != 0)
2072 return true;
2073 }
2074 else if (e.value.name == names.CONSTRUCTOR)
2075 { if (s.kind == MTH && s.isConstructor()) return true; }
2076 else if (e.value.name == names.LOCAL_VARIABLE)
2077 { if (s.kind == VAR && s.owner.kind == MTH &&
2078 (s.flags() & PARAMETER) == 0)
2079 return true;
2080 }
2081 else if (e.value.name == names.ANNOTATION_TYPE)
2082 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
2083 return true;
2084 }
2085 else if (e.value.name == names.PACKAGE)
2086 { if (s.kind == PCK) return true; }
2087 else if (e.value.name == names.TYPE_USE)
2088 { if (s.kind == TYP ||
2089 s.kind == VAR ||
2090 (s.kind == MTH && !s.isConstructor() &&
2091 s.type.getReturnType().tag != VOID))
2092 return true;
2093 }
2094 else
2095 return true; // recovery
2096 }
2097 return false;
2098 }
2100 /** Check an annotation value.
2101 */
2102 public void validateAnnotation(JCAnnotation a) {
2103 if (a.type.isErroneous()) return;
2105 // collect an inventory of the members
2106 Set<MethodSymbol> members = new HashSet<MethodSymbol>();
2107 for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
2108 e != null;
2109 e = e.sibling)
2110 if (e.sym.kind == MTH)
2111 members.add((MethodSymbol) e.sym);
2113 // count them off as they're annotated
2114 for (JCTree arg : a.args) {
2115 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
2116 JCAssign assign = (JCAssign) arg;
2117 Symbol m = TreeInfo.symbol(assign.lhs);
2118 if (m == null || m.type.isErroneous()) continue;
2119 if (!members.remove(m))
2120 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
2121 m.name, a.type);
2122 if (assign.rhs.getTag() == ANNOTATION)
2123 validateAnnotation((JCAnnotation)assign.rhs);
2124 }
2126 // all the remaining ones better have default values
2127 for (MethodSymbol m : members)
2128 if (m.defaultValue == null && !m.type.isErroneous())
2129 log.error(a.pos(), "annotation.missing.default.value",
2130 a.type, m.name);
2132 // special case: java.lang.annotation.Target must not have
2133 // repeated values in its value member
2134 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
2135 a.args.tail == null)
2136 return;
2138 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
2139 JCAssign assign = (JCAssign) a.args.head;
2140 Symbol m = TreeInfo.symbol(assign.lhs);
2141 if (m.name != names.value) return;
2142 JCTree rhs = assign.rhs;
2143 if (rhs.getTag() != JCTree.NEWARRAY) return;
2144 JCNewArray na = (JCNewArray) rhs;
2145 Set<Symbol> targets = new HashSet<Symbol>();
2146 for (JCTree elem : na.elems) {
2147 if (!targets.add(TreeInfo.symbol(elem))) {
2148 log.error(elem.pos(), "repeated.annotation.target");
2149 }
2150 }
2151 }
2153 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
2154 if (allowAnnotations &&
2155 lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
2156 (s.flags() & DEPRECATED) != 0 &&
2157 !syms.deprecatedType.isErroneous() &&
2158 s.attribute(syms.deprecatedType.tsym) == null) {
2159 log.warning(pos, "missing.deprecated.annotation");
2160 }
2161 }
2163 /* *************************************************************************
2164 * Check for recursive annotation elements.
2165 **************************************************************************/
2167 /** Check for cycles in the graph of annotation elements.
2168 */
2169 void checkNonCyclicElements(JCClassDecl tree) {
2170 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
2171 assert (tree.sym.flags_field & LOCKED) == 0;
2172 try {
2173 tree.sym.flags_field |= LOCKED;
2174 for (JCTree def : tree.defs) {
2175 if (def.getTag() != JCTree.METHODDEF) continue;
2176 JCMethodDecl meth = (JCMethodDecl)def;
2177 checkAnnotationResType(meth.pos(), meth.restype.type);
2178 }
2179 } finally {
2180 tree.sym.flags_field &= ~LOCKED;
2181 tree.sym.flags_field |= ACYCLIC_ANN;
2182 }
2183 }
2185 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
2186 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
2187 return;
2188 if ((tsym.flags_field & LOCKED) != 0) {
2189 log.error(pos, "cyclic.annotation.element");
2190 return;
2191 }
2192 try {
2193 tsym.flags_field |= LOCKED;
2194 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
2195 Symbol s = e.sym;
2196 if (s.kind != Kinds.MTH)
2197 continue;
2198 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
2199 }
2200 } finally {
2201 tsym.flags_field &= ~LOCKED;
2202 tsym.flags_field |= ACYCLIC_ANN;
2203 }
2204 }
2206 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
2207 switch (type.tag) {
2208 case TypeTags.CLASS:
2209 if ((type.tsym.flags() & ANNOTATION) != 0)
2210 checkNonCyclicElementsInternal(pos, type.tsym);
2211 break;
2212 case TypeTags.ARRAY:
2213 checkAnnotationResType(pos, types.elemtype(type));
2214 break;
2215 default:
2216 break; // int etc
2217 }
2218 }
2220 /* *************************************************************************
2221 * Check for cycles in the constructor call graph.
2222 **************************************************************************/
2224 /** Check for cycles in the graph of constructors calling other
2225 * constructors.
2226 */
2227 void checkCyclicConstructors(JCClassDecl tree) {
2228 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
2230 // enter each constructor this-call into the map
2231 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2232 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
2233 if (app == null) continue;
2234 JCMethodDecl meth = (JCMethodDecl) l.head;
2235 if (TreeInfo.name(app.meth) == names._this) {
2236 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
2237 } else {
2238 meth.sym.flags_field |= ACYCLIC;
2239 }
2240 }
2242 // Check for cycles in the map
2243 Symbol[] ctors = new Symbol[0];
2244 ctors = callMap.keySet().toArray(ctors);
2245 for (Symbol caller : ctors) {
2246 checkCyclicConstructor(tree, caller, callMap);
2247 }
2248 }
2250 /** Look in the map to see if the given constructor is part of a
2251 * call cycle.
2252 */
2253 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
2254 Map<Symbol,Symbol> callMap) {
2255 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
2256 if ((ctor.flags_field & LOCKED) != 0) {
2257 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
2258 "recursive.ctor.invocation");
2259 } else {
2260 ctor.flags_field |= LOCKED;
2261 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
2262 ctor.flags_field &= ~LOCKED;
2263 }
2264 ctor.flags_field |= ACYCLIC;
2265 }
2266 }
2268 /* *************************************************************************
2269 * Miscellaneous
2270 **************************************************************************/
2272 /**
2273 * Return the opcode of the operator but emit an error if it is an
2274 * error.
2275 * @param pos position for error reporting.
2276 * @param operator an operator
2277 * @param tag a tree tag
2278 * @param left type of left hand side
2279 * @param right type of right hand side
2280 */
2281 int checkOperator(DiagnosticPosition pos,
2282 OperatorSymbol operator,
2283 int tag,
2284 Type left,
2285 Type right) {
2286 if (operator.opcode == ByteCodes.error) {
2287 log.error(pos,
2288 "operator.cant.be.applied",
2289 treeinfo.operatorName(tag),
2290 List.of(left, right));
2291 }
2292 return operator.opcode;
2293 }
2296 /**
2297 * Check for division by integer constant zero
2298 * @param pos Position for error reporting.
2299 * @param operator The operator for the expression
2300 * @param operand The right hand operand for the expression
2301 */
2302 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
2303 if (operand.constValue() != null
2304 && lint.isEnabled(Lint.LintCategory.DIVZERO)
2305 && operand.tag <= LONG
2306 && ((Number) (operand.constValue())).longValue() == 0) {
2307 int opc = ((OperatorSymbol)operator).opcode;
2308 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
2309 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
2310 log.warning(pos, "div.zero");
2311 }
2312 }
2313 }
2315 /**
2316 * Check for empty statements after if
2317 */
2318 void checkEmptyIf(JCIf tree) {
2319 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
2320 log.warning(tree.thenpart.pos(), "empty.if");
2321 }
2323 /** Check that symbol is unique in given scope.
2324 * @param pos Position for error reporting.
2325 * @param sym The symbol.
2326 * @param s The scope.
2327 */
2328 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
2329 if (sym.type.isErroneous())
2330 return true;
2331 if (sym.owner.name == names.any) return false;
2332 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
2333 if (sym != e.sym &&
2334 sym.kind == e.sym.kind &&
2335 sym.name != names.error &&
2336 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
2337 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
2338 varargsDuplicateError(pos, sym, e.sym);
2339 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
2340 duplicateErasureError(pos, sym, e.sym);
2341 else
2342 duplicateError(pos, e.sym);
2343 return false;
2344 }
2345 }
2346 return true;
2347 }
2348 //where
2349 /** Report duplicate declaration error.
2350 */
2351 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
2352 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
2353 log.error(pos, "name.clash.same.erasure", sym1, sym2);
2354 }
2355 }
2357 /** Check that single-type import is not already imported or top-level defined,
2358 * but make an exception for two single-type imports which denote the same type.
2359 * @param pos Position for error reporting.
2360 * @param sym The symbol.
2361 * @param s The scope
2362 */
2363 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2364 return checkUniqueImport(pos, sym, s, false);
2365 }
2367 /** Check that static single-type import is not already imported or top-level defined,
2368 * but make an exception for two single-type imports which denote the same type.
2369 * @param pos Position for error reporting.
2370 * @param sym The symbol.
2371 * @param s The scope
2372 * @param staticImport Whether or not this was a static import
2373 */
2374 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
2375 return checkUniqueImport(pos, sym, s, true);
2376 }
2378 /** Check that single-type import is not already imported or top-level defined,
2379 * but make an exception for two single-type imports which denote the same type.
2380 * @param pos Position for error reporting.
2381 * @param sym The symbol.
2382 * @param s The scope.
2383 * @param staticImport Whether or not this was a static import
2384 */
2385 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
2386 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
2387 // is encountered class entered via a class declaration?
2388 boolean isClassDecl = e.scope == s;
2389 if ((isClassDecl || sym != e.sym) &&
2390 sym.kind == e.sym.kind &&
2391 sym.name != names.error) {
2392 if (!e.sym.type.isErroneous()) {
2393 String what = e.sym.toString();
2394 if (!isClassDecl) {
2395 if (staticImport)
2396 log.error(pos, "already.defined.static.single.import", what);
2397 else
2398 log.error(pos, "already.defined.single.import", what);
2399 }
2400 else if (sym != e.sym)
2401 log.error(pos, "already.defined.this.unit", what);
2402 }
2403 return false;
2404 }
2405 }
2406 return true;
2407 }
2409 /** Check that a qualified name is in canonical form (for import decls).
2410 */
2411 public void checkCanonical(JCTree tree) {
2412 if (!isCanonical(tree))
2413 log.error(tree.pos(), "import.requires.canonical",
2414 TreeInfo.symbol(tree));
2415 }
2416 // where
2417 private boolean isCanonical(JCTree tree) {
2418 while (tree.getTag() == JCTree.SELECT) {
2419 JCFieldAccess s = (JCFieldAccess) tree;
2420 if (s.sym.owner != TreeInfo.symbol(s.selected))
2421 return false;
2422 tree = s.selected;
2423 }
2424 return true;
2425 }
2427 private class ConversionWarner extends Warner {
2428 final String key;
2429 final Type found;
2430 final Type expected;
2431 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
2432 super(pos);
2433 this.key = key;
2434 this.found = found;
2435 this.expected = expected;
2436 }
2438 @Override
2439 public void warnUnchecked() {
2440 boolean warned = this.warned;
2441 super.warnUnchecked();
2442 if (warned) return; // suppress redundant diagnostics
2443 Object problem = diags.fragment(key);
2444 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
2445 }
2446 }
2448 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
2449 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
2450 }
2452 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
2453 return new ConversionWarner(pos, "unchecked.assign", found, expected);
2454 }
2455 }