167
168 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
169 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
170 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
171 boolean enforceMandatoryWarnings = true;
172
173 deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
174 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
175 removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
176 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
177 uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
178 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
179 sunApiHandler = new MandatoryWarningHandler(log, null, false,
180 enforceMandatoryWarnings, "sunapi", null);
181
182 deferredLintHandler = DeferredLintHandler.instance(context);
183
184 allowModules = Feature.MODULES.allowedInSource(source);
185 allowRecords = Feature.RECORDS.allowedInSource(source);
186 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
187 }
188
189 /** Character for synthetic names
190 */
191 char syntheticNameChar;
192
193 /** A table mapping flat names of all compiled classes for each module in this run
194 * to their symbols; maintained from outside.
195 */
196 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
197
198 /** A handler for messages about deprecated usage.
199 */
200 private MandatoryWarningHandler deprecationHandler;
201
202 /** A handler for messages about deprecated-for-removal usage.
203 */
204 private MandatoryWarningHandler removalHandler;
205
206 /** A handler for messages about unchecked or unsafe usage.
210 /** A handler for messages about using proprietary API.
211 */
212 private MandatoryWarningHandler sunApiHandler;
213
214 /** A handler for deferred lint warnings.
215 */
216 private DeferredLintHandler deferredLintHandler;
217
218 /** Are modules allowed
219 */
220 private final boolean allowModules;
221
222 /** Are records allowed
223 */
224 private final boolean allowRecords;
225
226 /** Are sealed classes allowed
227 */
228 private final boolean allowSealed;
229
230 /* *************************************************************************
231 * Errors and Warnings
232 **************************************************************************/
233
234 Lint setLint(Lint newLint) {
235 Lint prev = lint;
236 lint = newLint;
237 return prev;
238 }
239
240 MethodSymbol setMethod(MethodSymbol newMethod) {
241 MethodSymbol prev = method;
242 method = newMethod;
243 return prev;
244 }
245
246 /** Warn about deprecated symbol.
247 * @param pos Position to be used for error reporting.
248 * @param sym The deprecated symbol.
249 */
612 public String toString() {
613 return "CheckContext: basicHandler";
614 }
615 };
616
617 /** Check that a given type is assignable to a given proto-type.
618 * If it is, return the type, otherwise return errType.
619 * @param pos Position to be used for error reporting.
620 * @param found The type that was found.
621 * @param req The type that was required.
622 */
623 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
624 return checkType(pos, found, req, basicHandler);
625 }
626
627 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
628 final InferenceContext inferenceContext = checkContext.inferenceContext();
629 if (inferenceContext.free(req) || inferenceContext.free(found)) {
630 inferenceContext.addFreeTypeListener(List.of(req, found),
631 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
632 }
633 if (req.hasTag(ERROR))
634 return req;
635 if (req.hasTag(NONE))
636 return found;
637 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
638 return found;
639 } else {
640 if (found.isNumeric() && req.isNumeric()) {
641 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
642 return types.createErrorType(found);
643 }
644 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
645 return types.createErrorType(found);
646 }
647 }
648
649 /** Check that a given type can be cast to a given target type.
650 * Return the result of the cast.
651 * @param pos Position to be used for error reporting.
742 /** Check that type is a class or interface type.
743 * @param pos Position to be used for error reporting.
744 * @param t The type to be checked.
745 */
746 Type checkClassType(DiagnosticPosition pos, Type t) {
747 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
748 return typeTagError(pos,
749 diags.fragment(Fragments.TypeReqClass),
750 asTypeParam(t));
751 } else {
752 return t;
753 }
754 }
755 //where
756 private Object asTypeParam(Type t) {
757 return (t.hasTag(TYPEVAR))
758 ? diags.fragment(Fragments.TypeParameter(t))
759 : t;
760 }
761
762 /** Check that type is a valid qualifier for a constructor reference expression
763 */
764 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
765 t = checkClassOrArrayType(pos, t);
766 if (t.hasTag(CLASS)) {
767 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
768 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
769 t = types.createErrorType(t);
770 } else if ((t.tsym.flags() & ENUM) != 0) {
771 log.error(pos, Errors.EnumCantBeInstantiated);
772 t = types.createErrorType(t);
773 } else {
774 t = checkClassType(pos, t, true);
775 }
776 } else if (t.hasTag(ARRAY)) {
777 if (!types.isReifiable(((ArrayType)t).elemtype)) {
778 log.error(pos, Errors.GenericArrayCreation);
779 t = types.createErrorType(t);
780 }
781 }
782 return t;
783 }
784
785 /** Check that type is a class or interface type.
786 * @param pos Position to be used for error reporting.
787 * @param t The type to be checked.
788 * @param noBounds True if type bounds are illegal here.
789 */
790 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
791 t = checkClassType(pos, t);
792 if (noBounds && t.isParameterized()) {
793 List<Type> args = t.getTypeArguments();
794 while (args.nonEmpty()) {
795 if (args.head.hasTag(WILDCARD))
796 return typeTagError(pos,
797 diags.fragment(Fragments.TypeReqExact),
798 args.head);
799 args = args.tail;
800 }
801 }
802 return t;
803 }
804
805 /** Check that type is a reference type, i.e. a class, interface or array type
806 * or a type variable.
807 * @param pos Position to be used for error reporting.
808 * @param t The type to be checked.
809 */
810 Type checkRefType(DiagnosticPosition pos, Type t) {
811 if (t.isReference())
812 return t;
813 else
814 return typeTagError(pos,
815 diags.fragment(Fragments.TypeReqRef),
816 t);
817 }
818
819 /** Check that each type is a reference type, i.e. a class, interface or array type
820 * or a type variable.
821 * @param trees Original trees, used for error reporting.
822 * @param types The types to be checked.
823 */
824 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
825 List<JCExpression> tl = trees;
826 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
827 l.head = checkRefType(tl.head.pos(), l.head);
828 tl = tl.tail;
829 }
830 return types;
831 }
832
833 /** Check that type is a null or reference type.
834 * @param pos Position to be used for error reporting.
835 * @param t The type to be checked.
836 */
837 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
838 if (t.isReference() || t.hasTag(BOT))
839 return t;
840 else
841 return typeTagError(pos,
842 diags.fragment(Fragments.TypeReqRef),
843 t);
844 }
845
846 /** Check that flag set does not contain elements of two conflicting sets. s
847 * Return true if it doesn't.
848 * @param pos Position to be used for error reporting.
849 * @param flags The set of flags to be checked.
850 * @param set1 Conflicting flags set #1.
851 * @param set2 Conflicting flags set #2.
852 */
853 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
854 if ((flags & set1) != 0 && (flags & set2) != 0) {
855 log.error(pos,
856 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
857 asFlagSet(TreeInfo.firstFlag(flags & set2))));
858 return false;
859 } else
860 return true;
861 }
862
863 /** Check that usage of diamond operator is correct (i.e. diamond should not
864 * be used with non-generic classes or in anonymous class creation expressions)
865 */
866 Type checkDiamond(JCNewClass tree, Type t) {
867 if (!TreeInfo.isDiamond(tree) ||
868 t.isErroneous()) {
869 return checkClassType(tree.clazz.pos(), t, true);
870 } else {
871 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
872 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
873 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
874 }
875 if (t.tsym.type.getTypeArguments().isEmpty()) {
876 log.error(tree.clazz.pos(),
877 Errors.CantApplyDiamond1(t,
878 Fragments.DiamondNonGeneric(t)));
879 return types.createErrorType(t);
880 } else if (tree.typeargs != null &&
881 tree.typeargs.nonEmpty()) {
882 log.error(tree.clazz.pos(),
975 msg));
976 } else {
977 log.error(tree,
978 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
979 Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
980 }
981 } else if (hasTrustMeAnno && varargElemType != null &&
982 types.isReifiable(varargElemType)) {
983 warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
984 syms.trustMeType.tsym,
985 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
986 }
987 else if (!hasTrustMeAnno && varargElemType != null &&
988 !types.isReifiable(varargElemType)) {
989 warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
990 }
991 }
992 //where
993 private boolean isTrustMeAllowedOnMethod(Symbol s) {
994 return (s.flags() & VARARGS) != 0 &&
995 (s.isConstructor() ||
996 (s.flags() & (STATIC | FINAL |
997 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
998 }
999
1000 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
1001 //check that resulting type is not the null type
1002 if (t.hasTag(BOT)) {
1003 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
1004 return types.createErrorType(t);
1005 } else if (t.hasTag(VOID)) {
1006 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
1007 return types.createErrorType(t);
1008 }
1009
1010 //upward project the initializer type
1011 return types.upward(t, types.captures(t)).baseType();
1012 }
1013
1014 Type checkMethod(final Type mtype,
1015 final Symbol sym,
1016 final Env<AttrContext> env,
1017 final List<JCExpression> argtrees,
1018 final List<Type> argtypes,
1019 final boolean useVarargs,
1020 InferenceContext inferenceContext) {
1021 // System.out.println("call : " + env.tree);
1022 // System.out.println("method : " + owntype);
1023 // System.out.println("actuals: " + argtypes);
1024 if (inferenceContext.free(mtype)) {
1025 inferenceContext.addFreeTypeListener(List.of(mtype),
1026 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1027 return mtype;
1028 }
1029 Type owntype = mtype;
1030 List<Type> formals = owntype.getParameterTypes();
1031 List<Type> nonInferred = sym.type.getParameterTypes();
1032 if (nonInferred.length() != formals.length()) nonInferred = formals;
1033 Type last = useVarargs ? formals.last() : null;
1034 if (sym.name == names.init && sym.owner == syms.enumSym) {
1035 formals = formals.tail.tail;
1036 nonInferred = nonInferred.tail.tail;
1037 }
1038 if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1039 formals = formals.tail;
1040 nonInferred = nonInferred.tail;
1041 }
1042 List<JCExpression> args = argtrees;
1043 if (args != null) {
1044 //this is null when type-checking a method reference
1045 while (formals.head != last) {
1046 JCTree arg = args.head;
1047 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1048 assertConvertible(arg, arg.type, formals.head, warn);
1049 args = args.tail;
1050 formals = formals.tail;
1051 nonInferred = nonInferred.tail;
1052 }
1053 if (useVarargs) {
1189 * return modifiers together with any implicit modifiers for that symbol.
1190 * Warning: we can't use flags() here since this method
1191 * is called during class enter, when flags() would cause a premature
1192 * completion.
1193 * @param pos Position to be used for error reporting.
1194 * @param flags The set of modifiers given in a definition.
1195 * @param sym The defined symbol.
1196 */
1197 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1198 long mask;
1199 long implicit = 0;
1200
1201 switch (sym.kind) {
1202 case VAR:
1203 if (TreeInfo.isReceiverParam(tree))
1204 mask = ReceiverParamFlags;
1205 else if (sym.owner.kind != TYP)
1206 mask = LocalVarFlags;
1207 else if ((sym.owner.flags_field & INTERFACE) != 0)
1208 mask = implicit = InterfaceVarFlags;
1209 else
1210 mask = VarFlags;
1211 break;
1212 case MTH:
1213 if (sym.name == names.init) {
1214 if ((sym.owner.flags_field & ENUM) != 0) {
1215 // enum constructors cannot be declared public or
1216 // protected and must be implicitly or explicitly
1217 // private
1218 implicit = PRIVATE;
1219 mask = PRIVATE;
1220 } else
1221 mask = ConstructorFlags;
1222 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1223 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1224 mask = AnnotationTypeElementMask;
1225 implicit = PUBLIC | ABSTRACT;
1226 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1227 mask = InterfaceMethodMask;
1228 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1229 if ((flags & DEFAULT) != 0) {
1230 implicit |= ABSTRACT;
1231 }
1232 } else {
1233 mask = implicit = InterfaceMethodFlags;
1234 }
1235 } else if ((sym.owner.flags_field & RECORD) != 0) {
1236 mask = RecordMethodFlags;
1237 } else {
1238 mask = MethodFlags;
1239 }
1240 if ((flags & STRICTFP) != 0) {
1241 warnOnExplicitStrictfp(pos);
1242 }
1243 // Imply STRICTFP if owner has STRICTFP set.
1244 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1245 ((flags) & Flags.DEFAULT) != 0)
1246 implicit |= sym.owner.flags_field & STRICTFP;
1247 break;
1248 case TYP:
1249 if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1250 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1251 boolean implicitlyStatic = !sym.isAnonymous() &&
1252 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1253 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1254 // local statics are allowed only if records are allowed too
1255 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1256 implicit = implicitlyStatic ? STATIC : implicit;
1257 } else if (sym.owner.kind == TYP) {
1258 // statics in inner classes are allowed only if records are allowed too
1259 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1260 if (sym.owner.owner.kind == PCK ||
1261 (sym.owner.flags_field & STATIC) != 0) {
1262 mask |= STATIC;
1263 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1264 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1265 }
1266 // Nested interfaces and enums are always STATIC (Spec ???)
1267 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1268 } else {
1269 mask = ExtendedClassFlags;
1270 }
1271 // Interfaces are always ABSTRACT
1272 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1273
1274 if ((flags & ENUM) != 0) {
1275 // enums can't be declared abstract, final, sealed or non-sealed
1276 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1277 implicit |= implicitEnumFinalFlag(tree);
1278 }
1279 if ((flags & RECORD) != 0) {
1280 // records can't be declared abstract
1281 mask &= ~ABSTRACT;
1282 implicit |= FINAL;
1283 }
1284 if ((flags & STRICTFP) != 0) {
1285 warnOnExplicitStrictfp(pos);
1286 }
1287 // Imply STRICTFP if owner has STRICTFP set.
1288 implicit |= sym.owner.flags_field & STRICTFP;
1289 break;
1290 default:
1291 throw new AssertionError();
1292 }
1293 long illegal = flags & ExtendedStandardFlags & ~mask;
1294 if (illegal != 0) {
1295 if ((illegal & INTERFACE) != 0) {
1296 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1297 mask |= INTERFACE;
1298 }
1299 else {
1300 log.error(pos,
1301 Errors.ModNotAllowedHere(asFlagSet(illegal)));
1302 }
1303 }
1304 else if ((sym.kind == TYP ||
1305 // ISSUE: Disallowing abstract&private is no longer appropriate
1306 // in the presence of inner classes. Should it be deleted here?
1307 checkDisjoint(pos, flags,
1308 ABSTRACT,
1309 PRIVATE | STATIC | DEFAULT))
1310 &&
1311 checkDisjoint(pos, flags,
1312 STATIC | PRIVATE,
1313 DEFAULT)
1314 &&
1315 checkDisjoint(pos, flags,
1316 ABSTRACT | INTERFACE,
1317 FINAL | NATIVE | SYNCHRONIZED)
1318 &&
1319 checkDisjoint(pos, flags,
1320 PUBLIC,
1321 PRIVATE | PROTECTED)
1322 &&
1323 checkDisjoint(pos, flags,
1324 PRIVATE,
1325 PUBLIC | PROTECTED)
1326 &&
1327 checkDisjoint(pos, flags,
1328 FINAL,
1329 VOLATILE)
1330 &&
1331 (sym.kind == TYP ||
1332 checkDisjoint(pos, flags,
1333 ABSTRACT | NATIVE,
1334 STRICTFP))
1335 && checkDisjoint(pos, flags,
1336 FINAL,
1337 SEALED | NON_SEALED)
1338 && checkDisjoint(pos, flags,
1339 SEALED,
1340 FINAL | NON_SEALED)
1341 && checkDisjoint(pos, flags,
1342 SEALED,
1343 ANNOTATION)) {
1344 // skip
1345 }
1346 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1347 }
1348
1349 private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1350 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1351 try {
1352 deferredLintHandler.report(() -> {
1353 if (lint.isEnabled(LintCategory.STRICTFP)) {
1354 log.warning(LintCategory.STRICTFP,
1355 pos, Warnings.Strictfp); }
1356 });
1357 } finally {
1358 deferredLintHandler.setPos(prevLintPos);
1359 }
1360 }
1361
1362
1363 /** Determine if this enum should be implicitly final.
1496 @Override
1497 public void visitWildcard(JCWildcard tree) {
1498 if (tree.inner != null)
1499 validateTree(tree.inner, true, isOuter);
1500 }
1501
1502 @Override
1503 public void visitSelect(JCFieldAccess tree) {
1504 if (tree.type.hasTag(CLASS)) {
1505 visitSelectInternal(tree);
1506
1507 // Check that this type is either fully parameterized, or
1508 // not parameterized at all.
1509 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1510 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1511 }
1512 }
1513
1514 public void visitSelectInternal(JCFieldAccess tree) {
1515 if (tree.type.tsym.isStatic() &&
1516 tree.selected.type.isParameterized()) {
1517 // The enclosing type is not a class, so we are
1518 // looking at a static member type. However, the
1519 // qualifying expression is parameterized.
1520 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1521 } else {
1522 // otherwise validate the rest of the expression
1523 tree.selected.accept(this);
1524 }
1525 }
1526
1527 @Override
1528 public void visitAnnotatedType(JCAnnotatedType tree) {
1529 tree.underlyingType.accept(this);
1530 }
1531
1532 @Override
1533 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1534 if (that.type.hasTag(TypeTag.VOID)) {
1535 log.error(that.pos(), Errors.VoidNotAllowedHere);
1536 }
1537 super.visitTypeIdent(that);
1538 }
1539
1563
1564 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1565 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1566 validateTree(l.head, checkRaw, isOuter);
1567 }
1568 }
1569
1570 void checkRaw(JCTree tree, Env<AttrContext> env) {
1571 if (lint.isEnabled(LintCategory.RAW) &&
1572 tree.type.hasTag(CLASS) &&
1573 !TreeInfo.isDiamond(tree) &&
1574 !withinAnonConstr(env) &&
1575 tree.type.isRaw()) {
1576 log.warning(LintCategory.RAW,
1577 tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1578 }
1579 }
1580 //where
1581 private boolean withinAnonConstr(Env<AttrContext> env) {
1582 return env.enclClass.name.isEmpty() &&
1583 env.enclMethod != null && env.enclMethod.name == names.init;
1584 }
1585
1586 /* *************************************************************************
1587 * Exception checking
1588 **************************************************************************/
1589
1590 /* The following methods treat classes as sets that contain
1591 * the class itself and all their subclasses
1592 */
1593
1594 /** Is given type a subtype of some of the types in given list?
1595 */
1596 boolean subset(Type t, List<Type> ts) {
1597 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1598 if (types.isSubtype(t, l.head)) return true;
1599 return false;
1600 }
1601
1602 /** Is given type a subtype or supertype of
1603 * some of the types in given list?
2164 if (recordComponent.isPresent()) {
2165 return;
2166 }
2167 }
2168
2169 for (Type t = origin.type; t.hasTag(CLASS);
2170 t = types.supertype(t)) {
2171 if (t != origin.type) {
2172 checkOverride(tree, t, origin, m);
2173 }
2174 for (Type t2 : types.interfaces(t)) {
2175 checkOverride(tree, t2, origin, m);
2176 }
2177 }
2178
2179 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2180 // Check if this method must override a super method due to being annotated with @Override
2181 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2182 // be treated "as if as they were annotated" with @Override.
2183 boolean mustOverride = explicitOverride ||
2184 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2185 if (mustOverride && !isOverrider(m)) {
2186 DiagnosticPosition pos = tree.pos();
2187 for (JCAnnotation a : tree.getModifiers().annotations) {
2188 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2189 pos = a.pos();
2190 break;
2191 }
2192 }
2193 log.error(pos,
2194 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2195 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2196 }
2197 }
2198
2199 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2200 TypeSymbol c = site.tsym;
2201 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2202 if (m.overrides(sym, origin, types, false)) {
2203 if ((sym.flags() & ABSTRACT) == 0) {
2204 checkOverride(tree, m, (MethodSymbol)sym, origin);
2320 cf.test(s2) &&
2321 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2322 }
2323
2324
2325 /** Check that all abstract members of given class have definitions.
2326 * @param pos Position to be used for error reporting.
2327 * @param c The class.
2328 */
2329 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2330 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2331 if (undef != null) {
2332 MethodSymbol undef1 =
2333 new MethodSymbol(undef.flags(), undef.name,
2334 types.memberType(c.type, undef), undef.owner);
2335 log.error(pos,
2336 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2337 }
2338 }
2339
2340 void checkNonCyclicDecl(JCClassDecl tree) {
2341 CycleChecker cc = new CycleChecker();
2342 cc.scan(tree);
2343 if (!cc.errorFound && !cc.partialCheck) {
2344 tree.sym.flags_field |= ACYCLIC;
2345 }
2346 }
2347
2348 class CycleChecker extends TreeScanner {
2349
2350 Set<Symbol> seenClasses = new HashSet<>();
2351 boolean errorFound = false;
2352 boolean partialCheck = false;
2353
2354 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2355 if (sym != null && sym.kind == TYP) {
2356 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2357 if (classEnv != null) {
2358 DiagnosticSource prevSource = log.currentSource();
2359 try {
2568 /** Check that all abstract methods implemented by a class are
2569 * mutually compatible.
2570 * @param pos Position to be used for error reporting.
2571 * @param c The class whose interfaces are checked.
2572 */
2573 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2574 List<Type> supertypes = types.interfaces(c);
2575 Type supertype = types.supertype(c);
2576 if (supertype.hasTag(CLASS) &&
2577 (supertype.tsym.flags() & ABSTRACT) != 0)
2578 supertypes = supertypes.prepend(supertype);
2579 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2580 if (!l.head.getTypeArguments().isEmpty() &&
2581 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2582 return;
2583 for (List<Type> m = supertypes; m != l; m = m.tail)
2584 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2585 return;
2586 }
2587 checkCompatibleConcretes(pos, c);
2588 }
2589
2590 /** Check that all non-override equivalent methods accessible from 'site'
2591 * are mutually compatible (JLS 8.4.8/9.4.1).
2592 *
2593 * @param pos Position to be used for error reporting.
2594 * @param site The class whose methods are checked.
2595 * @param sym The method symbol to be checked.
2596 */
2597 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2598 ClashFilter cf = new ClashFilter(site);
2599 //for each method m1 that is overridden (directly or indirectly)
2600 //by method 'sym' in 'site'...
2601
2602 ArrayList<Symbol> symbolsByName = new ArrayList<>();
2603 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2604 for (Symbol m1 : symbolsByName) {
2605 if (!sym.overrides(m1, site.tsym, types, false)) {
2606 continue;
2607 }
2663 //where
2664 private class ClashFilter implements Predicate<Symbol> {
2665
2666 Type site;
2667
2668 ClashFilter(Type site) {
2669 this.site = site;
2670 }
2671
2672 boolean shouldSkip(Symbol s) {
2673 return (s.flags() & CLASH) != 0 &&
2674 s.owner == site.tsym;
2675 }
2676
2677 @Override
2678 public boolean test(Symbol s) {
2679 return s.kind == MTH &&
2680 (s.flags() & SYNTHETIC) == 0 &&
2681 !shouldSkip(s) &&
2682 s.isInheritedIn(site.tsym, types) &&
2683 !s.isConstructor();
2684 }
2685 }
2686
2687 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2688 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2689 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2690 Assert.check(m.kind == MTH);
2691 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2692 if (prov.size() > 1) {
2693 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2694 ListBuffer<Symbol> defaults = new ListBuffer<>();
2695 for (MethodSymbol provSym : prov) {
2696 if ((provSym.flags() & DEFAULT) != 0) {
2697 defaults = defaults.append(provSym);
2698 } else if ((provSym.flags() & ABSTRACT) != 0) {
2699 abstracts = abstracts.append(provSym);
2700 }
2701 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2702 //strong semantics - issue an error if two sibling interfaces
2703 //have two override-equivalent defaults - or if one is abstract
2722 }
2723 }
2724 }
2725 }
2726 }
2727
2728 //where
2729 private class DefaultMethodClashFilter implements Predicate<Symbol> {
2730
2731 Type site;
2732
2733 DefaultMethodClashFilter(Type site) {
2734 this.site = site;
2735 }
2736
2737 @Override
2738 public boolean test(Symbol s) {
2739 return s.kind == MTH &&
2740 (s.flags() & DEFAULT) != 0 &&
2741 s.isInheritedIn(site.tsym, types) &&
2742 !s.isConstructor();
2743 }
2744 }
2745
2746 /** Report warnings for potentially ambiguous method declarations in the given site. */
2747 void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) {
2748
2749 // Skip if warning not enabled
2750 if (!lint.isEnabled(LintCategory.OVERLOADS))
2751 return;
2752
2753 // Gather all of site's methods, including overridden methods, grouped by name (except Object methods)
2754 List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site,
2755 new PotentiallyAmbiguousFilter(site), ArrayList::new);
2756
2757 // Build the predicate that determines if site is responsible for an ambiguity
2758 BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups);
2759
2760 // Now remove overridden methods from each group, leaving only site's actual members
2761 methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false)));
2762
3605 Attribute app = arr.values[i];
3606 if (!(app instanceof Attribute.Enum attributeEnum)) {
3607 // recovery
3608 return Optional.empty();
3609 }
3610 targets[i] = attributeEnum.value.name;
3611 }
3612 }
3613 for (Name target : targets) {
3614 if (target == names.TYPE) {
3615 if (s.kind == TYP)
3616 applicableTargets.add(names.TYPE);
3617 } else if (target == names.FIELD) {
3618 if (s.kind == VAR && s.owner.kind != MTH)
3619 applicableTargets.add(names.FIELD);
3620 } else if (target == names.RECORD_COMPONENT) {
3621 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3622 applicableTargets.add(names.RECORD_COMPONENT);
3623 }
3624 } else if (target == names.METHOD) {
3625 if (s.kind == MTH && !s.isConstructor())
3626 applicableTargets.add(names.METHOD);
3627 } else if (target == names.PARAMETER) {
3628 if (s.kind == VAR &&
3629 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3630 applicableTargets.add(names.PARAMETER);
3631 }
3632 } else if (target == names.CONSTRUCTOR) {
3633 if (s.kind == MTH && s.isConstructor())
3634 applicableTargets.add(names.CONSTRUCTOR);
3635 } else if (target == names.LOCAL_VARIABLE) {
3636 if (s.kind == VAR && s.owner.kind == MTH &&
3637 (s.flags() & PARAMETER) == 0) {
3638 applicableTargets.add(names.LOCAL_VARIABLE);
3639 }
3640 } else if (target == names.ANNOTATION_TYPE) {
3641 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3642 applicableTargets.add(names.ANNOTATION_TYPE);
3643 }
3644 } else if (target == names.PACKAGE) {
3645 if (s.kind == PCK)
3646 applicableTargets.add(names.PACKAGE);
3647 } else if (target == names.TYPE_USE) {
3648 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3649 //cannot type annotate implicitly typed locals
3650 continue;
3651 } else if (s.kind == TYP || s.kind == VAR ||
3652 (s.kind == MTH && !s.isConstructor() &&
3653 !s.type.getReturnType().hasTag(VOID)) ||
3654 (s.kind == MTH && s.isConstructor())) {
3655 applicableTargets.add(names.TYPE_USE);
3656 }
3657 } else if (target == names.TYPE_PARAMETER) {
3658 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3659 applicableTargets.add(names.TYPE_PARAMETER);
3660 } else if (target == names.MODULE) {
3661 if (s.kind == MDL)
3662 applicableTargets.add(names.MODULE);
3663 } else {
3664 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3665 return Optional.empty(); // Unknown ElementType
3666 }
3667 }
3668 return Optional.of(applicableTargets);
3669 }
3670
3671 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3672 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3673 if (atTarget == null) return null; // ok, is applicable
3674 Attribute atValue = atTarget.member(names.value);
4956 });
4957 }
4958
4959 return null;
4960 }
4961
4962 boolean canBeSerialized(Type type) {
4963 return type.isPrimitive() || rs.isSerializable(type);
4964 }
4965
4966 /**
4967 * Check that Externalizable class needs a public no-arg
4968 * constructor.
4969 *
4970 * Check that a Serializable class has access to the no-arg
4971 * constructor of its first nonserializable superclass.
4972 */
4973 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
4974 if (isExternalizable(c.type)) {
4975 for(var sym : c.getEnclosedElements()) {
4976 if (sym.isConstructor() &&
4977 ((sym.flags() & PUBLIC) == PUBLIC)) {
4978 if (((MethodSymbol)sym).getParameters().isEmpty()) {
4979 return;
4980 }
4981 }
4982 }
4983 log.warning(LintCategory.SERIAL, tree.pos(),
4984 Warnings.ExternalizableMissingPublicNoArgCtor);
4985 } else {
4986 // Approximate access to the no-arg constructor up in
4987 // the superclass chain by checking that the
4988 // constructor is not private. This may not handle
4989 // some cross-package situations correctly.
4990 Type superClass = c.getSuperclass();
4991 // java.lang.Object is *not* Serializable so this loop
4992 // should terminate.
4993 while (rs.isSerializable(superClass) ) {
4994 try {
4995 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
4996 } catch(ClassCastException cce) {
4997 return ; // Don't try to recover
4998 }
4999 }
5000 // Non-Serializable superclass
5001 try {
5002 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5003 for(var sym : supertype.getEnclosedElements()) {
5004 if (sym.isConstructor()) {
5005 MethodSymbol ctor = (MethodSymbol)sym;
5006 if (ctor.getParameters().isEmpty()) {
5007 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5008 // Handle nested classes and implicit this$0
5009 (supertype.getNestingKind() == NestingKind.MEMBER &&
5010 ((supertype.flags() & STATIC) == 0)))
5011 log.warning(LintCategory.SERIAL, tree.pos(),
5012 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5013 }
5014 }
5015 }
5016 } catch (ClassCastException cce) {
5017 return ; // Don't try to recover
5018 }
5019 return;
5020 }
5021 }
5022
5023 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5024 // To be effective, serialVersionUID must be marked static
|
167
168 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
169 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
170 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
171 boolean enforceMandatoryWarnings = true;
172
173 deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
174 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
175 removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
176 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
177 uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
178 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
179 sunApiHandler = new MandatoryWarningHandler(log, null, false,
180 enforceMandatoryWarnings, "sunapi", null);
181
182 deferredLintHandler = DeferredLintHandler.instance(context);
183
184 allowModules = Feature.MODULES.allowedInSource(source);
185 allowRecords = Feature.RECORDS.allowedInSource(source);
186 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
187 allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
188 }
189
190 /** Character for synthetic names
191 */
192 char syntheticNameChar;
193
194 /** A table mapping flat names of all compiled classes for each module in this run
195 * to their symbols; maintained from outside.
196 */
197 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
198
199 /** A handler for messages about deprecated usage.
200 */
201 private MandatoryWarningHandler deprecationHandler;
202
203 /** A handler for messages about deprecated-for-removal usage.
204 */
205 private MandatoryWarningHandler removalHandler;
206
207 /** A handler for messages about unchecked or unsafe usage.
211 /** A handler for messages about using proprietary API.
212 */
213 private MandatoryWarningHandler sunApiHandler;
214
215 /** A handler for deferred lint warnings.
216 */
217 private DeferredLintHandler deferredLintHandler;
218
219 /** Are modules allowed
220 */
221 private final boolean allowModules;
222
223 /** Are records allowed
224 */
225 private final boolean allowRecords;
226
227 /** Are sealed classes allowed
228 */
229 private final boolean allowSealed;
230
231 /** Are primitive classes allowed
232 */
233 private final boolean allowPrimitiveClasses;
234
235 /* *************************************************************************
236 * Errors and Warnings
237 **************************************************************************/
238
239 Lint setLint(Lint newLint) {
240 Lint prev = lint;
241 lint = newLint;
242 return prev;
243 }
244
245 MethodSymbol setMethod(MethodSymbol newMethod) {
246 MethodSymbol prev = method;
247 method = newMethod;
248 return prev;
249 }
250
251 /** Warn about deprecated symbol.
252 * @param pos Position to be used for error reporting.
253 * @param sym The deprecated symbol.
254 */
617 public String toString() {
618 return "CheckContext: basicHandler";
619 }
620 };
621
622 /** Check that a given type is assignable to a given proto-type.
623 * If it is, return the type, otherwise return errType.
624 * @param pos Position to be used for error reporting.
625 * @param found The type that was found.
626 * @param req The type that was required.
627 */
628 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
629 return checkType(pos, found, req, basicHandler);
630 }
631
632 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
633 final InferenceContext inferenceContext = checkContext.inferenceContext();
634 if (inferenceContext.free(req) || inferenceContext.free(found)) {
635 inferenceContext.addFreeTypeListener(List.of(req, found),
636 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
637 } else {
638 if (allowPrimitiveClasses && found.hasTag(CLASS)) {
639 if (inferenceContext != infer.emptyContext)
640 checkParameterizationByPrimitiveClass(pos, found);
641 }
642 }
643 if (req.hasTag(ERROR))
644 return req;
645 if (req.hasTag(NONE))
646 return found;
647 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
648 return found;
649 } else {
650 if (found.isNumeric() && req.isNumeric()) {
651 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
652 return types.createErrorType(found);
653 }
654 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
655 return types.createErrorType(found);
656 }
657 }
658
659 /** Check that a given type can be cast to a given target type.
660 * Return the result of the cast.
661 * @param pos Position to be used for error reporting.
752 /** Check that type is a class or interface type.
753 * @param pos Position to be used for error reporting.
754 * @param t The type to be checked.
755 */
756 Type checkClassType(DiagnosticPosition pos, Type t) {
757 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
758 return typeTagError(pos,
759 diags.fragment(Fragments.TypeReqClass),
760 asTypeParam(t));
761 } else {
762 return t;
763 }
764 }
765 //where
766 private Object asTypeParam(Type t) {
767 return (t.hasTag(TYPEVAR))
768 ? diags.fragment(Fragments.TypeParameter(t))
769 : t;
770 }
771
772 void checkConstraintsOfValueClass(DiagnosticPosition pos, ClassSymbol c) {
773 for (Type st : types.closure(c.type)) {
774 if (st == null || st.tsym == null || st.tsym.kind == ERR)
775 continue;
776 if (st.tsym == syms.objectType.tsym || st.tsym == syms.recordType.tsym || st.isInterface())
777 continue;
778 if (!st.tsym.isAbstract()) {
779 if (c != st.tsym) {
780 log.error(pos, Errors.ConcreteSupertypeForValueClass(c, st));
781 }
782 continue;
783 }
784 // dealing with an abstract value or value super class below.
785 Fragment fragment = c.isAbstract() && c.isValueClass() && c == st.tsym ? Fragments.AbstractValueClass(c) : Fragments.SuperclassOfValueClass(c, st);
786 if ((st.tsym.flags() & HASINITBLOCK) != 0) {
787 log.error(pos, Errors.AbstractValueClassDeclaresInitBlock(fragment));
788 }
789 Type encl = st.getEnclosingType();
790 if (encl != null && encl.hasTag(CLASS)) {
791 log.error(pos, Errors.AbstractValueClassCannotBeInner(fragment));
792 }
793 for (Symbol s : st.tsym.members().getSymbols(NON_RECURSIVE)) {
794 switch (s.kind) {
795 case VAR:
796 if ((s.flags() & STATIC) == 0) {
797 log.error(pos, Errors.InstanceFieldNotAllowed(s, fragment));
798 }
799 break;
800 case MTH:
801 if ((s.flags() & (SYNCHRONIZED | STATIC)) == SYNCHRONIZED) {
802 log.error(pos, Errors.SuperClassMethodCannotBeSynchronized(s, c, st));
803 } else if (s.isInitOrVNew()) {
804 MethodSymbol m = (MethodSymbol)s;
805 if (m.getParameters().size() > 0) {
806 log.error(pos, Errors.AbstractValueClassConstructorCannotTakeArguments(m, fragment));
807 } else if (m.getTypeParameters().size() > 0) {
808 log.error(pos, Errors.AbstractValueClassConstructorCannotBeGeneric(m, fragment));
809 } else if (m.type.getThrownTypes().size() > 0) {
810 log.error(pos, Errors.AbstractValueClassConstructorCannotThrow(m, fragment));
811 } else if (protection(m.flags()) > protection(m.owner.flags())) {
812 log.error(pos, Errors.AbstractValueClassConstructorHasWeakerAccess(m, fragment));
813 } else if ((m.flags() & EMPTYNOARGCONSTR) == 0) {
814 log.error(pos, Errors.AbstractValueClassNoArgConstructorMustBeEmpty(m, fragment));
815 }
816 }
817 break;
818 }
819 }
820 }
821 }
822
823 /** Check that type is a valid qualifier for a constructor reference expression
824 */
825 Type checkConstructorRefType(JCExpression expr, Type t) {
826 t = checkClassOrArrayType(expr, t);
827 if (t.hasTag(CLASS)) {
828 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
829 log.error(expr, Errors.AbstractCantBeInstantiated(t.tsym));
830 t = types.createErrorType(t);
831 } else if ((t.tsym.flags() & ENUM) != 0) {
832 log.error(expr, Errors.EnumCantBeInstantiated);
833 t = types.createErrorType(t);
834 } else {
835 // Projection types may not be mentioned in constructor references
836 if (expr.hasTag(SELECT)) {
837 JCFieldAccess fieldAccess = (JCFieldAccess) expr;
838 if (allowPrimitiveClasses && fieldAccess.selected.type.isPrimitiveClass() &&
839 (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
840 log.error(expr, Errors.ProjectionCantBeInstantiated);
841 t = types.createErrorType(t);
842 }
843 }
844 t = checkClassType(expr, t, true);
845 }
846 } else if (t.hasTag(ARRAY)) {
847 if (!types.isReifiable(((ArrayType)t).elemtype)) {
848 log.error(expr, Errors.GenericArrayCreation);
849 t = types.createErrorType(t);
850 }
851 }
852 return t;
853 }
854
855 /** Check that type is a class or interface type.
856 * @param pos Position to be used for error reporting.
857 * @param t The type to be checked.
858 * @param noBounds True if type bounds are illegal here.
859 */
860 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
861 t = checkClassType(pos, t);
862 if (noBounds && t.isParameterized()) {
863 List<Type> args = t.getTypeArguments();
864 while (args.nonEmpty()) {
865 if (args.head.hasTag(WILDCARD))
866 return typeTagError(pos,
867 diags.fragment(Fragments.TypeReqExact),
868 args.head);
869 args = args.tail;
870 }
871 }
872 return t;
873 }
874
875 /** Check that type is a reference type, i.e. a class, interface or array type
876 * or a type variable.
877 * @param pos Position to be used for error reporting.
878 * @param t The type to be checked.
879 * @param primitiveClassOK If false, a primitive class does not qualify
880 */
881 Type checkRefType(DiagnosticPosition pos, Type t, boolean primitiveClassOK) {
882 if (t.isReference() && (!allowPrimitiveClasses || primitiveClassOK || !t.isPrimitiveClass()))
883 return t;
884 else
885 return typeTagError(pos,
886 diags.fragment(Fragments.TypeReqRef),
887 t);
888 }
889
890 /** Check that type is an identity type, i.e. not a primitive/value type
891 * nor its reference projection. When not discernible statically,
892 * give it the benefit of doubt and defer to runtime.
893 *
894 * @param pos Position to be used for error reporting.
895 * @param t The type to be checked.
896 */
897 void checkIdentityType(DiagnosticPosition pos, Type t) {
898 if (t.hasTag(TYPEVAR)) {
899 t = types.skipTypeVars(t, false);
900 }
901 if (t.isIntersection()) {
902 IntersectionClassType ict = (IntersectionClassType)t;
903 for (Type component : ict.getExplicitComponents()) {
904 checkIdentityType(pos, component);
905 }
906 return;
907 }
908 if (t.isPrimitive() || t.isValueClass() || t.isValueInterface() || t.isReferenceProjection())
909 typeTagError(pos, diags.fragment(Fragments.TypeReqIdentity), t);
910 }
911
912 /** Check that type is a reference type, i.e. a class, interface or array type
913 * or a type variable.
914 * @param pos Position to be used for error reporting.
915 * @param t The type to be checked.
916 */
917 Type checkRefType(DiagnosticPosition pos, Type t) {
918 return checkRefType(pos, t, true);
919 }
920
921 /** Check that each type is a reference type, i.e. a class, interface or array type
922 * or a type variable.
923 * @param trees Original trees, used for error reporting.
924 * @param types The types to be checked.
925 */
926 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
927 List<JCExpression> tl = trees;
928 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
929 l.head = checkRefType(tl.head.pos(), l.head, false);
930 tl = tl.tail;
931 }
932 return types;
933 }
934
935 /** Check that type is a null or reference type.
936 * @param pos Position to be used for error reporting.
937 * @param t The type to be checked.
938 */
939 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
940 if (t.isReference() || t.hasTag(BOT))
941 return t;
942 else
943 return typeTagError(pos,
944 diags.fragment(Fragments.TypeReqRef),
945 t);
946 }
947
948 /** Check that flag set does not contain elements of two conflicting sets. s
949 * Return true if it doesn't.
950 * @param pos Position to be used for error reporting.
951 * @param flags The set of flags to be checked.
952 * @param set1 Conflicting flags set #1.
953 * @param set2 Conflicting flags set #2.
954 */
955 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
956 if ((flags & set1) != 0 && (flags & set2) != 0) {
957 log.error(pos,
958 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
959 asFlagSet(TreeInfo.firstFlag(flags & set2))));
960 return false;
961 } else
962 return true;
963 }
964
965 void checkParameterizationByPrimitiveClass(DiagnosticPosition pos, Type t) {
966 parameterizationByPrimitiveClassChecker.visit(t, pos);
967 }
968
969 /** parameterizationByPrimitiveClassChecker: A type visitor that descends down the given type looking for instances of primitive classes
970 * being used as type arguments and issues error against those usages.
971 */
972 private final Types.SimpleVisitor<Void, DiagnosticPosition> parameterizationByPrimitiveClassChecker =
973 new Types.SimpleVisitor<Void, DiagnosticPosition>() {
974
975 @Override
976 public Void visitType(Type t, DiagnosticPosition pos) {
977 return null;
978 }
979
980 @Override
981 public Void visitClassType(ClassType t, DiagnosticPosition pos) {
982 for (Type targ : t.allparams()) {
983 if (allowPrimitiveClasses && targ.isPrimitiveClass()) {
984 log.error(pos, Errors.GenericParameterizationWithPrimitiveClass(t));
985 }
986 visit(targ, pos);
987 }
988 return null;
989 }
990
991 @Override
992 public Void visitTypeVar(TypeVar t, DiagnosticPosition pos) {
993 return null;
994 }
995
996 @Override
997 public Void visitCapturedType(CapturedType t, DiagnosticPosition pos) {
998 return null;
999 }
1000
1001 @Override
1002 public Void visitArrayType(ArrayType t, DiagnosticPosition pos) {
1003 return visit(t.elemtype, pos);
1004 }
1005
1006 @Override
1007 public Void visitWildcardType(WildcardType t, DiagnosticPosition pos) {
1008 return visit(t.type, pos);
1009 }
1010 };
1011
1012
1013
1014 /** Check that usage of diamond operator is correct (i.e. diamond should not
1015 * be used with non-generic classes or in anonymous class creation expressions)
1016 */
1017 Type checkDiamond(JCNewClass tree, Type t) {
1018 if (!TreeInfo.isDiamond(tree) ||
1019 t.isErroneous()) {
1020 return checkClassType(tree.clazz.pos(), t, true);
1021 } else {
1022 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
1023 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
1024 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
1025 }
1026 if (t.tsym.type.getTypeArguments().isEmpty()) {
1027 log.error(tree.clazz.pos(),
1028 Errors.CantApplyDiamond1(t,
1029 Fragments.DiamondNonGeneric(t)));
1030 return types.createErrorType(t);
1031 } else if (tree.typeargs != null &&
1032 tree.typeargs.nonEmpty()) {
1033 log.error(tree.clazz.pos(),
1126 msg));
1127 } else {
1128 log.error(tree,
1129 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
1130 Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
1131 }
1132 } else if (hasTrustMeAnno && varargElemType != null &&
1133 types.isReifiable(varargElemType)) {
1134 warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
1135 syms.trustMeType.tsym,
1136 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
1137 }
1138 else if (!hasTrustMeAnno && varargElemType != null &&
1139 !types.isReifiable(varargElemType)) {
1140 warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
1141 }
1142 }
1143 //where
1144 private boolean isTrustMeAllowedOnMethod(Symbol s) {
1145 return (s.flags() & VARARGS) != 0 &&
1146 (s.isInitOrVNew() ||
1147 (s.flags() & (STATIC | FINAL |
1148 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
1149 }
1150
1151 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
1152 //check that resulting type is not the null type
1153 if (t.hasTag(BOT)) {
1154 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
1155 return types.createErrorType(t);
1156 } else if (t.hasTag(VOID)) {
1157 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
1158 return types.createErrorType(t);
1159 }
1160
1161 //upward project the initializer type
1162 Type varType = types.upward(t, types.captures(t)).baseType();
1163 if (allowPrimitiveClasses && varType.hasTag(CLASS)) {
1164 checkParameterizationByPrimitiveClass(pos, varType);
1165 }
1166 return varType;
1167 }
1168
1169 Type checkMethod(final Type mtype,
1170 final Symbol sym,
1171 final Env<AttrContext> env,
1172 final List<JCExpression> argtrees,
1173 final List<Type> argtypes,
1174 final boolean useVarargs,
1175 InferenceContext inferenceContext) {
1176 // System.out.println("call : " + env.tree);
1177 // System.out.println("method : " + owntype);
1178 // System.out.println("actuals: " + argtypes);
1179 if (inferenceContext.free(mtype)) {
1180 inferenceContext.addFreeTypeListener(List.of(mtype),
1181 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1182 return mtype;
1183 }
1184 Type owntype = mtype;
1185 List<Type> formals = owntype.getParameterTypes();
1186 List<Type> nonInferred = sym.type.getParameterTypes();
1187 if (nonInferred.length() != formals.length()) nonInferred = formals;
1188 Type last = useVarargs ? formals.last() : null;
1189 // TODO - is enum so <init>
1190 if (sym.name == names.init && sym.owner == syms.enumSym) {
1191 formals = formals.tail.tail;
1192 nonInferred = nonInferred.tail.tail;
1193 }
1194 if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1195 formals = formals.tail;
1196 nonInferred = nonInferred.tail;
1197 }
1198 List<JCExpression> args = argtrees;
1199 if (args != null) {
1200 //this is null when type-checking a method reference
1201 while (formals.head != last) {
1202 JCTree arg = args.head;
1203 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1204 assertConvertible(arg, arg.type, formals.head, warn);
1205 args = args.tail;
1206 formals = formals.tail;
1207 nonInferred = nonInferred.tail;
1208 }
1209 if (useVarargs) {
1345 * return modifiers together with any implicit modifiers for that symbol.
1346 * Warning: we can't use flags() here since this method
1347 * is called during class enter, when flags() would cause a premature
1348 * completion.
1349 * @param pos Position to be used for error reporting.
1350 * @param flags The set of modifiers given in a definition.
1351 * @param sym The defined symbol.
1352 */
1353 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1354 long mask;
1355 long implicit = 0;
1356
1357 switch (sym.kind) {
1358 case VAR:
1359 if (TreeInfo.isReceiverParam(tree))
1360 mask = ReceiverParamFlags;
1361 else if (sym.owner.kind != TYP)
1362 mask = LocalVarFlags;
1363 else if ((sym.owner.flags_field & INTERFACE) != 0)
1364 mask = implicit = InterfaceVarFlags;
1365 else {
1366 mask = VarFlags;
1367 if (sym.owner.type.isValueClass() && (flags & STATIC) == 0) {
1368 implicit |= FINAL;
1369 }
1370 }
1371 break;
1372 case MTH:
1373 if (names.isInitOrVNew(sym.name)) {
1374 if ((sym.owner.flags_field & ENUM) != 0) {
1375 // enum constructors cannot be declared public or
1376 // protected and must be implicitly or explicitly
1377 // private
1378 implicit = PRIVATE;
1379 mask = PRIVATE;
1380 } else
1381 mask = ConstructorFlags;
1382 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1383 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1384 mask = AnnotationTypeElementMask;
1385 implicit = PUBLIC | ABSTRACT;
1386 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1387 mask = InterfaceMethodMask;
1388 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1389 if ((flags & DEFAULT) != 0) {
1390 implicit |= ABSTRACT;
1391 }
1392 } else {
1393 mask = implicit = InterfaceMethodFlags;
1394 }
1395 } else if ((sym.owner.flags_field & RECORD) != 0) {
1396 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1397 RecordMethodFlags & ~SYNCHRONIZED : RecordMethodFlags;
1398 } else {
1399 // value objects do not have an associated monitor/lock
1400 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1401 MethodFlags & ~SYNCHRONIZED : MethodFlags;
1402 }
1403 if ((flags & STRICTFP) != 0) {
1404 warnOnExplicitStrictfp(pos);
1405 }
1406 // Imply STRICTFP if owner has STRICTFP set.
1407 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1408 ((flags) & Flags.DEFAULT) != 0)
1409 implicit |= sym.owner.flags_field & STRICTFP;
1410 break;
1411 case TYP:
1412 if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1413 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1414 boolean implicitlyStatic = !sym.isAnonymous() &&
1415 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1416 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1417 // local statics are allowed only if records are allowed too
1418 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedStaticLocalClassFlags : ExtendedLocalClassFlags;
1419 implicit = implicitlyStatic ? STATIC : implicit;
1420 } else if (sym.owner.kind == TYP) {
1421 // statics in inner classes are allowed only if records are allowed too
1422 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1423 if (sym.owner.owner.kind == PCK ||
1424 (sym.owner.flags_field & STATIC) != 0) {
1425 mask |= STATIC;
1426 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1427 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1428 }
1429 // Nested interfaces and enums are always STATIC (Spec ???)
1430 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1431 } else {
1432 mask = ExtendedClassFlags;
1433 }
1434 // Interfaces are always ABSTRACT
1435 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1436
1437 if ((flags & ENUM) != 0) {
1438 // enums can't be declared abstract, final, sealed or non-sealed or primitive/value
1439 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED | PRIMITIVE_CLASS | VALUE_CLASS);
1440 implicit |= implicitEnumFinalFlag(tree);
1441 }
1442 if ((flags & RECORD) != 0) {
1443 // records can't be declared abstract
1444 mask &= ~ABSTRACT;
1445 implicit |= FINAL;
1446 }
1447 if ((flags & STRICTFP) != 0) {
1448 warnOnExplicitStrictfp(pos);
1449 }
1450 // Imply STRICTFP if owner has STRICTFP set.
1451 implicit |= sym.owner.flags_field & STRICTFP;
1452
1453 // primitive classes are implicitly final value classes.
1454 if ((flags & PRIMITIVE_CLASS) != 0)
1455 implicit |= VALUE_CLASS | FINAL;
1456
1457 // concrete value classes are implicitly final
1458 if ((flags & (ABSTRACT | INTERFACE | VALUE_CLASS)) == VALUE_CLASS) {
1459 implicit |= FINAL;
1460 if ((flags & NON_SEALED) != 0) {
1461 // cant declare a final value class non-sealed
1462 log.error(pos,
1463 Errors.ModNotAllowedHere(asFlagSet(NON_SEALED)));
1464 }
1465 }
1466
1467 // TYPs can't be declared synchronized
1468 mask &= ~SYNCHRONIZED;
1469 break;
1470 default:
1471 throw new AssertionError();
1472 }
1473 long illegal = flags & ExtendedStandardFlags & ~mask;
1474 if (illegal != 0) {
1475 if ((illegal & INTERFACE) != 0) {
1476 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1477 mask |= INTERFACE;
1478 }
1479 else {
1480 log.error(pos,
1481 Errors.ModNotAllowedHere(asFlagSet(illegal)));
1482 }
1483 }
1484 else if ((sym.kind == TYP ||
1485 // ISSUE: Disallowing abstract&private is no longer appropriate
1486 // in the presence of inner classes. Should it be deleted here?
1487 checkDisjoint(pos, flags,
1488 ABSTRACT,
1489 PRIVATE | STATIC | DEFAULT))
1490 &&
1491 checkDisjoint(pos, flags,
1492 STATIC | PRIVATE,
1493 DEFAULT)
1494 &&
1495 checkDisjoint(pos, flags,
1496 ABSTRACT | INTERFACE,
1497 FINAL | NATIVE | SYNCHRONIZED | PRIMITIVE_CLASS)
1498 &&
1499 checkDisjoint(pos, flags,
1500 IDENTITY_TYPE,
1501 PRIMITIVE_CLASS | VALUE_CLASS)
1502 &&
1503 checkDisjoint(pos, flags,
1504 PUBLIC,
1505 PRIVATE | PROTECTED)
1506 &&
1507 checkDisjoint(pos, flags,
1508 PRIVATE,
1509 PUBLIC | PROTECTED)
1510 &&
1511 checkDisjoint(pos, (flags | implicit), // complain against volatile & implcitly final entities too.
1512 FINAL,
1513 VOLATILE)
1514 &&
1515 (sym.kind == TYP ||
1516 checkDisjoint(pos, flags,
1517 ABSTRACT | NATIVE,
1518 STRICTFP))
1519 && checkDisjoint(pos, flags,
1520 FINAL,
1521 SEALED | NON_SEALED)
1522 && checkDisjoint(pos, flags,
1523 SEALED,
1524 FINAL | NON_SEALED)
1525 && checkDisjoint(pos, flags,
1526 SEALED,
1527 ANNOTATION)
1528 && checkDisjoint(pos, flags,
1529 IDENTITY_TYPE,
1530 ANNOTATION)
1531 && checkDisjoint(pos, flags,
1532 VALUE_CLASS,
1533 ANNOTATION) ) {
1534 // skip
1535 }
1536 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1537 }
1538
1539 private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1540 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1541 try {
1542 deferredLintHandler.report(() -> {
1543 if (lint.isEnabled(LintCategory.STRICTFP)) {
1544 log.warning(LintCategory.STRICTFP,
1545 pos, Warnings.Strictfp); }
1546 });
1547 } finally {
1548 deferredLintHandler.setPos(prevLintPos);
1549 }
1550 }
1551
1552
1553 /** Determine if this enum should be implicitly final.
1686 @Override
1687 public void visitWildcard(JCWildcard tree) {
1688 if (tree.inner != null)
1689 validateTree(tree.inner, true, isOuter);
1690 }
1691
1692 @Override
1693 public void visitSelect(JCFieldAccess tree) {
1694 if (tree.type.hasTag(CLASS)) {
1695 visitSelectInternal(tree);
1696
1697 // Check that this type is either fully parameterized, or
1698 // not parameterized at all.
1699 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1700 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1701 }
1702 }
1703
1704 public void visitSelectInternal(JCFieldAccess tree) {
1705 if (tree.type.tsym.isStatic() &&
1706 tree.selected.type.isParameterized() &&
1707 (tree.name != names.ref || !tree.type.isReferenceProjection())) {
1708 // The enclosing type is not a class, so we are
1709 // looking at a static member type. However, the
1710 // qualifying expression is parameterized.
1711 // Tolerate the pseudo-select V.ref: V<T>.ref will be static if V<T> is and
1712 // should not be confused as selecting a static member of a parameterized type.
1713 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1714 } else {
1715 // otherwise validate the rest of the expression
1716 tree.selected.accept(this);
1717 }
1718 }
1719
1720 @Override
1721 public void visitAnnotatedType(JCAnnotatedType tree) {
1722 tree.underlyingType.accept(this);
1723 }
1724
1725 @Override
1726 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1727 if (that.type.hasTag(TypeTag.VOID)) {
1728 log.error(that.pos(), Errors.VoidNotAllowedHere);
1729 }
1730 super.visitTypeIdent(that);
1731 }
1732
1756
1757 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1758 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1759 validateTree(l.head, checkRaw, isOuter);
1760 }
1761 }
1762
1763 void checkRaw(JCTree tree, Env<AttrContext> env) {
1764 if (lint.isEnabled(LintCategory.RAW) &&
1765 tree.type.hasTag(CLASS) &&
1766 !TreeInfo.isDiamond(tree) &&
1767 !withinAnonConstr(env) &&
1768 tree.type.isRaw()) {
1769 log.warning(LintCategory.RAW,
1770 tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1771 }
1772 }
1773 //where
1774 private boolean withinAnonConstr(Env<AttrContext> env) {
1775 return env.enclClass.name.isEmpty() &&
1776 env.enclMethod != null && names.isInitOrVNew(env.enclMethod.name);
1777 }
1778
1779 /* *************************************************************************
1780 * Exception checking
1781 **************************************************************************/
1782
1783 /* The following methods treat classes as sets that contain
1784 * the class itself and all their subclasses
1785 */
1786
1787 /** Is given type a subtype of some of the types in given list?
1788 */
1789 boolean subset(Type t, List<Type> ts) {
1790 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1791 if (types.isSubtype(t, l.head)) return true;
1792 return false;
1793 }
1794
1795 /** Is given type a subtype or supertype of
1796 * some of the types in given list?
2357 if (recordComponent.isPresent()) {
2358 return;
2359 }
2360 }
2361
2362 for (Type t = origin.type; t.hasTag(CLASS);
2363 t = types.supertype(t)) {
2364 if (t != origin.type) {
2365 checkOverride(tree, t, origin, m);
2366 }
2367 for (Type t2 : types.interfaces(t)) {
2368 checkOverride(tree, t2, origin, m);
2369 }
2370 }
2371
2372 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2373 // Check if this method must override a super method due to being annotated with @Override
2374 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2375 // be treated "as if as they were annotated" with @Override.
2376 boolean mustOverride = explicitOverride ||
2377 (env.info.isAnonymousDiamond && !m.isInitOrVNew() && !m.isPrivate());
2378 if (mustOverride && !isOverrider(m)) {
2379 DiagnosticPosition pos = tree.pos();
2380 for (JCAnnotation a : tree.getModifiers().annotations) {
2381 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2382 pos = a.pos();
2383 break;
2384 }
2385 }
2386 log.error(pos,
2387 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2388 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2389 }
2390 }
2391
2392 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2393 TypeSymbol c = site.tsym;
2394 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2395 if (m.overrides(sym, origin, types, false)) {
2396 if ((sym.flags() & ABSTRACT) == 0) {
2397 checkOverride(tree, m, (MethodSymbol)sym, origin);
2513 cf.test(s2) &&
2514 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2515 }
2516
2517
2518 /** Check that all abstract members of given class have definitions.
2519 * @param pos Position to be used for error reporting.
2520 * @param c The class.
2521 */
2522 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2523 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2524 if (undef != null) {
2525 MethodSymbol undef1 =
2526 new MethodSymbol(undef.flags(), undef.name,
2527 types.memberType(c.type, undef), undef.owner);
2528 log.error(pos,
2529 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2530 }
2531 }
2532
2533 // A primitive class cannot contain a field of its own type either or indirectly.
2534 void checkNonCyclicMembership(JCClassDecl tree) {
2535 if (allowPrimitiveClasses) {
2536 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2537 try {
2538 tree.sym.flags_field |= LOCKED;
2539 for (List<? extends JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2540 if (l.head.hasTag(VARDEF)) {
2541 JCVariableDecl field = (JCVariableDecl) l.head;
2542 if (cyclePossible(field.sym)) {
2543 checkNonCyclicMembership((ClassSymbol) field.type.tsym, field.pos());
2544 }
2545 }
2546 }
2547 } finally {
2548 tree.sym.flags_field &= ~LOCKED;
2549 }
2550 }
2551 }
2552 // where
2553 private void checkNonCyclicMembership(ClassSymbol c, DiagnosticPosition pos) {
2554 if ((c.flags_field & LOCKED) != 0) {
2555 log.error(pos, Errors.CyclicPrimitiveClassMembership(c));
2556 return;
2557 }
2558 try {
2559 c.flags_field |= LOCKED;
2560 for (Symbol fld : c.members().getSymbols(s -> s.kind == VAR && cyclePossible((VarSymbol) s), NON_RECURSIVE)) {
2561 checkNonCyclicMembership((ClassSymbol) fld.type.tsym, pos);
2562 }
2563 } finally {
2564 c.flags_field &= ~LOCKED;
2565 }
2566 }
2567 // where
2568 private boolean cyclePossible(VarSymbol symbol) {
2569 return (symbol.flags() & STATIC) == 0 && allowPrimitiveClasses && symbol.type.isPrimitiveClass();
2570 }
2571
2572 void checkNonCyclicDecl(JCClassDecl tree) {
2573 CycleChecker cc = new CycleChecker();
2574 cc.scan(tree);
2575 if (!cc.errorFound && !cc.partialCheck) {
2576 tree.sym.flags_field |= ACYCLIC;
2577 }
2578 }
2579
2580 class CycleChecker extends TreeScanner {
2581
2582 Set<Symbol> seenClasses = new HashSet<>();
2583 boolean errorFound = false;
2584 boolean partialCheck = false;
2585
2586 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2587 if (sym != null && sym.kind == TYP) {
2588 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2589 if (classEnv != null) {
2590 DiagnosticSource prevSource = log.currentSource();
2591 try {
2800 /** Check that all abstract methods implemented by a class are
2801 * mutually compatible.
2802 * @param pos Position to be used for error reporting.
2803 * @param c The class whose interfaces are checked.
2804 */
2805 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2806 List<Type> supertypes = types.interfaces(c);
2807 Type supertype = types.supertype(c);
2808 if (supertype.hasTag(CLASS) &&
2809 (supertype.tsym.flags() & ABSTRACT) != 0)
2810 supertypes = supertypes.prepend(supertype);
2811 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2812 if (!l.head.getTypeArguments().isEmpty() &&
2813 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2814 return;
2815 for (List<Type> m = supertypes; m != l; m = m.tail)
2816 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2817 return;
2818 }
2819 checkCompatibleConcretes(pos, c);
2820
2821 boolean cIsValue = (c.tsym.flags() & VALUE_CLASS) != 0;
2822 boolean cHasIdentity = (c.tsym.flags() & IDENTITY_TYPE) != 0;
2823 Type identitySuper = null, valueSuper = null;
2824 for (Type t : types.closure(c)) {
2825 if (t != c) {
2826 if ((t.tsym.flags() & IDENTITY_TYPE) != 0)
2827 identitySuper = t;
2828 else if ((t.tsym.flags() & VALUE_CLASS) != 0)
2829 valueSuper = t;
2830 if (cIsValue && identitySuper != null) {
2831 log.error(pos, Errors.ValueTypeHasIdentitySuperType(c, identitySuper));
2832 break;
2833 } else if (cHasIdentity && valueSuper != null) {
2834 log.error(pos, Errors.IdentityTypeHasValueSuperType(c, valueSuper));
2835 break;
2836 } else if (identitySuper != null && valueSuper != null) {
2837 log.error(pos, Errors.MutuallyIncompatibleSupers(c, identitySuper, valueSuper));
2838 break;
2839 }
2840 }
2841 }
2842 }
2843
2844 /** Check that all non-override equivalent methods accessible from 'site'
2845 * are mutually compatible (JLS 8.4.8/9.4.1).
2846 *
2847 * @param pos Position to be used for error reporting.
2848 * @param site The class whose methods are checked.
2849 * @param sym The method symbol to be checked.
2850 */
2851 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2852 ClashFilter cf = new ClashFilter(site);
2853 //for each method m1 that is overridden (directly or indirectly)
2854 //by method 'sym' in 'site'...
2855
2856 ArrayList<Symbol> symbolsByName = new ArrayList<>();
2857 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2858 for (Symbol m1 : symbolsByName) {
2859 if (!sym.overrides(m1, site.tsym, types, false)) {
2860 continue;
2861 }
2917 //where
2918 private class ClashFilter implements Predicate<Symbol> {
2919
2920 Type site;
2921
2922 ClashFilter(Type site) {
2923 this.site = site;
2924 }
2925
2926 boolean shouldSkip(Symbol s) {
2927 return (s.flags() & CLASH) != 0 &&
2928 s.owner == site.tsym;
2929 }
2930
2931 @Override
2932 public boolean test(Symbol s) {
2933 return s.kind == MTH &&
2934 (s.flags() & SYNTHETIC) == 0 &&
2935 !shouldSkip(s) &&
2936 s.isInheritedIn(site.tsym, types) &&
2937 !s.isInitOrVNew();
2938 }
2939 }
2940
2941 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2942 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2943 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2944 Assert.check(m.kind == MTH);
2945 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2946 if (prov.size() > 1) {
2947 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2948 ListBuffer<Symbol> defaults = new ListBuffer<>();
2949 for (MethodSymbol provSym : prov) {
2950 if ((provSym.flags() & DEFAULT) != 0) {
2951 defaults = defaults.append(provSym);
2952 } else if ((provSym.flags() & ABSTRACT) != 0) {
2953 abstracts = abstracts.append(provSym);
2954 }
2955 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2956 //strong semantics - issue an error if two sibling interfaces
2957 //have two override-equivalent defaults - or if one is abstract
2976 }
2977 }
2978 }
2979 }
2980 }
2981
2982 //where
2983 private class DefaultMethodClashFilter implements Predicate<Symbol> {
2984
2985 Type site;
2986
2987 DefaultMethodClashFilter(Type site) {
2988 this.site = site;
2989 }
2990
2991 @Override
2992 public boolean test(Symbol s) {
2993 return s.kind == MTH &&
2994 (s.flags() & DEFAULT) != 0 &&
2995 s.isInheritedIn(site.tsym, types) &&
2996 !s.isInitOrVNew();
2997 }
2998 }
2999
3000 /** Report warnings for potentially ambiguous method declarations in the given site. */
3001 void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) {
3002
3003 // Skip if warning not enabled
3004 if (!lint.isEnabled(LintCategory.OVERLOADS))
3005 return;
3006
3007 // Gather all of site's methods, including overridden methods, grouped by name (except Object methods)
3008 List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site,
3009 new PotentiallyAmbiguousFilter(site), ArrayList::new);
3010
3011 // Build the predicate that determines if site is responsible for an ambiguity
3012 BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups);
3013
3014 // Now remove overridden methods from each group, leaving only site's actual members
3015 methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false)));
3016
3859 Attribute app = arr.values[i];
3860 if (!(app instanceof Attribute.Enum attributeEnum)) {
3861 // recovery
3862 return Optional.empty();
3863 }
3864 targets[i] = attributeEnum.value.name;
3865 }
3866 }
3867 for (Name target : targets) {
3868 if (target == names.TYPE) {
3869 if (s.kind == TYP)
3870 applicableTargets.add(names.TYPE);
3871 } else if (target == names.FIELD) {
3872 if (s.kind == VAR && s.owner.kind != MTH)
3873 applicableTargets.add(names.FIELD);
3874 } else if (target == names.RECORD_COMPONENT) {
3875 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3876 applicableTargets.add(names.RECORD_COMPONENT);
3877 }
3878 } else if (target == names.METHOD) {
3879 if (s.kind == MTH && !s.isInitOrVNew())
3880 applicableTargets.add(names.METHOD);
3881 } else if (target == names.PARAMETER) {
3882 if (s.kind == VAR &&
3883 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3884 applicableTargets.add(names.PARAMETER);
3885 }
3886 } else if (target == names.CONSTRUCTOR) {
3887 if (s.kind == MTH && s.isInitOrVNew())
3888 applicableTargets.add(names.CONSTRUCTOR);
3889 } else if (target == names.LOCAL_VARIABLE) {
3890 if (s.kind == VAR && s.owner.kind == MTH &&
3891 (s.flags() & PARAMETER) == 0) {
3892 applicableTargets.add(names.LOCAL_VARIABLE);
3893 }
3894 } else if (target == names.ANNOTATION_TYPE) {
3895 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3896 applicableTargets.add(names.ANNOTATION_TYPE);
3897 }
3898 } else if (target == names.PACKAGE) {
3899 if (s.kind == PCK)
3900 applicableTargets.add(names.PACKAGE);
3901 } else if (target == names.TYPE_USE) {
3902 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3903 //cannot type annotate implicitly typed locals
3904 continue;
3905 } else if (s.kind == TYP || s.kind == VAR ||
3906 (s.kind == MTH && !s.isInitOrVNew() &&
3907 !s.type.getReturnType().hasTag(VOID)) ||
3908 (s.kind == MTH && s.isInitOrVNew())) {
3909 applicableTargets.add(names.TYPE_USE);
3910 }
3911 } else if (target == names.TYPE_PARAMETER) {
3912 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3913 applicableTargets.add(names.TYPE_PARAMETER);
3914 } else if (target == names.MODULE) {
3915 if (s.kind == MDL)
3916 applicableTargets.add(names.MODULE);
3917 } else {
3918 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3919 return Optional.empty(); // Unknown ElementType
3920 }
3921 }
3922 return Optional.of(applicableTargets);
3923 }
3924
3925 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3926 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3927 if (atTarget == null) return null; // ok, is applicable
3928 Attribute atValue = atTarget.member(names.value);
5210 });
5211 }
5212
5213 return null;
5214 }
5215
5216 boolean canBeSerialized(Type type) {
5217 return type.isPrimitive() || rs.isSerializable(type);
5218 }
5219
5220 /**
5221 * Check that Externalizable class needs a public no-arg
5222 * constructor.
5223 *
5224 * Check that a Serializable class has access to the no-arg
5225 * constructor of its first nonserializable superclass.
5226 */
5227 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5228 if (isExternalizable(c.type)) {
5229 for(var sym : c.getEnclosedElements()) {
5230 if (sym.isInitOrVNew() &&
5231 ((sym.flags() & PUBLIC) == PUBLIC)) {
5232 if (((MethodSymbol)sym).getParameters().isEmpty()) {
5233 return;
5234 }
5235 }
5236 }
5237 log.warning(LintCategory.SERIAL, tree.pos(),
5238 Warnings.ExternalizableMissingPublicNoArgCtor);
5239 } else {
5240 // Approximate access to the no-arg constructor up in
5241 // the superclass chain by checking that the
5242 // constructor is not private. This may not handle
5243 // some cross-package situations correctly.
5244 Type superClass = c.getSuperclass();
5245 // java.lang.Object is *not* Serializable so this loop
5246 // should terminate.
5247 while (rs.isSerializable(superClass) ) {
5248 try {
5249 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5250 } catch(ClassCastException cce) {
5251 return ; // Don't try to recover
5252 }
5253 }
5254 // Non-Serializable superclass
5255 try {
5256 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5257 for(var sym : supertype.getEnclosedElements()) {
5258 if (sym.isInitOrVNew()) {
5259 MethodSymbol ctor = (MethodSymbol)sym;
5260 if (ctor.getParameters().isEmpty()) {
5261 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5262 // Handle nested classes and implicit this$0
5263 (supertype.getNestingKind() == NestingKind.MEMBER &&
5264 ((supertype.flags() & STATIC) == 0)))
5265 log.warning(LintCategory.SERIAL, tree.pos(),
5266 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5267 }
5268 }
5269 }
5270 } catch (ClassCastException cce) {
5271 return ; // Don't try to recover
5272 }
5273 return;
5274 }
5275 }
5276
5277 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5278 // To be effective, serialVersionUID must be marked static
|