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