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