152
153 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
154 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
155 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
156 boolean enforceMandatoryWarnings = true;
157
158 deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
159 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
160 removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
161 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
162 uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
163 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
164 sunApiHandler = new MandatoryWarningHandler(log, null, false,
165 enforceMandatoryWarnings, "sunapi", null);
166
167 deferredLintHandler = DeferredLintHandler.instance(context);
168
169 allowModules = Feature.MODULES.allowedInSource(source);
170 allowRecords = Feature.RECORDS.allowedInSource(source);
171 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
172 }
173
174 /** Character for synthetic names
175 */
176 char syntheticNameChar;
177
178 /** A table mapping flat names of all compiled classes for each module in this run
179 * to their symbols; maintained from outside.
180 */
181 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
182
183 /** A handler for messages about deprecated usage.
184 */
185 private MandatoryWarningHandler deprecationHandler;
186
187 /** A handler for messages about deprecated-for-removal usage.
188 */
189 private MandatoryWarningHandler removalHandler;
190
191 /** A handler for messages about unchecked or unsafe usage.
195 /** A handler for messages about using proprietary API.
196 */
197 private MandatoryWarningHandler sunApiHandler;
198
199 /** A handler for deferred lint warnings.
200 */
201 private DeferredLintHandler deferredLintHandler;
202
203 /** Are modules allowed
204 */
205 private final boolean allowModules;
206
207 /** Are records allowed
208 */
209 private final boolean allowRecords;
210
211 /** Are sealed classes allowed
212 */
213 private final boolean allowSealed;
214
215 /* *************************************************************************
216 * Errors and Warnings
217 **************************************************************************/
218
219 Lint setLint(Lint newLint) {
220 Lint prev = lint;
221 lint = newLint;
222 return prev;
223 }
224
225 MethodSymbol setMethod(MethodSymbol newMethod) {
226 MethodSymbol prev = method;
227 method = newMethod;
228 return prev;
229 }
230
231 /** Warn about deprecated symbol.
232 * @param pos Position to be used for error reporting.
233 * @param sym The deprecated symbol.
234 */
597 public String toString() {
598 return "CheckContext: basicHandler";
599 }
600 };
601
602 /** Check that a given type is assignable to a given proto-type.
603 * If it is, return the type, otherwise return errType.
604 * @param pos Position to be used for error reporting.
605 * @param found The type that was found.
606 * @param req The type that was required.
607 */
608 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
609 return checkType(pos, found, req, basicHandler);
610 }
611
612 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
613 final InferenceContext inferenceContext = checkContext.inferenceContext();
614 if (inferenceContext.free(req) || inferenceContext.free(found)) {
615 inferenceContext.addFreeTypeListener(List.of(req, found),
616 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
617 }
618 if (req.hasTag(ERROR))
619 return req;
620 if (req.hasTag(NONE))
621 return found;
622 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
623 return found;
624 } else {
625 if (found.isNumeric() && req.isNumeric()) {
626 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
627 return types.createErrorType(found);
628 }
629 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
630 return types.createErrorType(found);
631 }
632 }
633
634 /** Check that a given type can be cast to a given target type.
635 * Return the result of the cast.
636 * @param pos Position to be used for error reporting.
727 /** Check that type is a class or interface type.
728 * @param pos Position to be used for error reporting.
729 * @param t The type to be checked.
730 */
731 Type checkClassType(DiagnosticPosition pos, Type t) {
732 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
733 return typeTagError(pos,
734 diags.fragment(Fragments.TypeReqClass),
735 asTypeParam(t));
736 } else {
737 return t;
738 }
739 }
740 //where
741 private Object asTypeParam(Type t) {
742 return (t.hasTag(TYPEVAR))
743 ? diags.fragment(Fragments.TypeParameter(t))
744 : t;
745 }
746
747 /** Check that type is a valid qualifier for a constructor reference expression
748 */
749 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
750 t = checkClassOrArrayType(pos, t);
751 if (t.hasTag(CLASS)) {
752 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
753 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
754 t = types.createErrorType(t);
755 } else if ((t.tsym.flags() & ENUM) != 0) {
756 log.error(pos, Errors.EnumCantBeInstantiated);
757 t = types.createErrorType(t);
758 } else {
759 t = checkClassType(pos, t, true);
760 }
761 } else if (t.hasTag(ARRAY)) {
762 if (!types.isReifiable(((ArrayType)t).elemtype)) {
763 log.error(pos, Errors.GenericArrayCreation);
764 t = types.createErrorType(t);
765 }
766 }
767 return t;
768 }
769
770 /** Check that type is a class or interface type.
771 * @param pos Position to be used for error reporting.
772 * @param t The type to be checked.
773 * @param noBounds True if type bounds are illegal here.
774 */
775 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
776 t = checkClassType(pos, t);
777 if (noBounds && t.isParameterized()) {
778 List<Type> args = t.getTypeArguments();
779 while (args.nonEmpty()) {
780 if (args.head.hasTag(WILDCARD))
781 return typeTagError(pos,
782 diags.fragment(Fragments.TypeReqExact),
783 args.head);
784 args = args.tail;
785 }
786 }
787 return t;
788 }
789
790 /** Check that type is a reference type, i.e. a class, interface or array type
791 * or a type variable.
792 * @param pos Position to be used for error reporting.
793 * @param t The type to be checked.
794 */
795 Type checkRefType(DiagnosticPosition pos, Type t) {
796 if (t.isReference())
797 return t;
798 else
799 return typeTagError(pos,
800 diags.fragment(Fragments.TypeReqRef),
801 t);
802 }
803
804 /** Check that each type is a reference type, i.e. a class, interface or array type
805 * or a type variable.
806 * @param trees Original trees, used for error reporting.
807 * @param types The types to be checked.
808 */
809 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
810 List<JCExpression> tl = trees;
811 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
812 l.head = checkRefType(tl.head.pos(), l.head);
813 tl = tl.tail;
814 }
815 return types;
816 }
817
818 /** Check that type is a null or reference type.
819 * @param pos Position to be used for error reporting.
820 * @param t The type to be checked.
821 */
822 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
823 if (t.isReference() || t.hasTag(BOT))
824 return t;
825 else
826 return typeTagError(pos,
827 diags.fragment(Fragments.TypeReqRef),
828 t);
829 }
830
831 /** Check that flag set does not contain elements of two conflicting sets. s
832 * Return true if it doesn't.
833 * @param pos Position to be used for error reporting.
834 * @param flags The set of flags to be checked.
835 * @param set1 Conflicting flags set #1.
836 * @param set2 Conflicting flags set #2.
837 */
838 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
839 if ((flags & set1) != 0 && (flags & set2) != 0) {
840 log.error(pos,
841 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
842 asFlagSet(TreeInfo.firstFlag(flags & set2))));
843 return false;
844 } else
845 return true;
846 }
847
848 /** Check that usage of diamond operator is correct (i.e. diamond should not
849 * be used with non-generic classes or in anonymous class creation expressions)
850 */
851 Type checkDiamond(JCNewClass tree, Type t) {
852 if (!TreeInfo.isDiamond(tree) ||
853 t.isErroneous()) {
854 return checkClassType(tree.clazz.pos(), t, true);
855 } else {
856 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
857 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
858 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
859 }
860 if (t.tsym.type.getTypeArguments().isEmpty()) {
861 log.error(tree.clazz.pos(),
862 Errors.CantApplyDiamond1(t,
863 Fragments.DiamondNonGeneric(t)));
864 return types.createErrorType(t);
865 } else if (tree.typeargs != null &&
866 tree.typeargs.nonEmpty()) {
867 log.error(tree.clazz.pos(),
960 msg));
961 } else {
962 log.error(tree,
963 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
964 Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
965 }
966 } else if (hasTrustMeAnno && varargElemType != null &&
967 types.isReifiable(varargElemType)) {
968 warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
969 syms.trustMeType.tsym,
970 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
971 }
972 else if (!hasTrustMeAnno && varargElemType != null &&
973 !types.isReifiable(varargElemType)) {
974 warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
975 }
976 }
977 //where
978 private boolean isTrustMeAllowedOnMethod(Symbol s) {
979 return (s.flags() & VARARGS) != 0 &&
980 (s.isConstructor() ||
981 (s.flags() & (STATIC | FINAL |
982 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
983 }
984
985 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
986 //check that resulting type is not the null type
987 if (t.hasTag(BOT)) {
988 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
989 return types.createErrorType(t);
990 } else if (t.hasTag(VOID)) {
991 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
992 return types.createErrorType(t);
993 }
994
995 //upward project the initializer type
996 return types.upward(t, types.captures(t)).baseType();
997 }
998
999 Type checkMethod(final Type mtype,
1000 final Symbol sym,
1001 final Env<AttrContext> env,
1002 final List<JCExpression> argtrees,
1003 final List<Type> argtypes,
1004 final boolean useVarargs,
1005 InferenceContext inferenceContext) {
1006 // System.out.println("call : " + env.tree);
1007 // System.out.println("method : " + owntype);
1008 // System.out.println("actuals: " + argtypes);
1009 if (inferenceContext.free(mtype)) {
1010 inferenceContext.addFreeTypeListener(List.of(mtype),
1011 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1012 return mtype;
1013 }
1014 Type owntype = mtype;
1015 List<Type> formals = owntype.getParameterTypes();
1016 List<Type> nonInferred = sym.type.getParameterTypes();
1017 if (nonInferred.length() != formals.length()) nonInferred = formals;
1018 Type last = useVarargs ? formals.last() : null;
1019 if (sym.name == names.init && sym.owner == syms.enumSym) {
1020 formals = formals.tail.tail;
1021 nonInferred = nonInferred.tail.tail;
1022 }
1023 if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1024 formals = formals.tail;
1025 nonInferred = nonInferred.tail;
1026 }
1027 List<JCExpression> args = argtrees;
1028 if (args != null) {
1029 //this is null when type-checking a method reference
1030 while (formals.head != last) {
1031 JCTree arg = args.head;
1032 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1033 assertConvertible(arg, arg.type, formals.head, warn);
1034 args = args.tail;
1035 formals = formals.tail;
1036 nonInferred = nonInferred.tail;
1037 }
1038 if (useVarargs) {
1174 * return modifiers together with any implicit modifiers for that symbol.
1175 * Warning: we can't use flags() here since this method
1176 * is called during class enter, when flags() would cause a premature
1177 * completion.
1178 * @param pos Position to be used for error reporting.
1179 * @param flags The set of modifiers given in a definition.
1180 * @param sym The defined symbol.
1181 */
1182 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1183 long mask;
1184 long implicit = 0;
1185
1186 switch (sym.kind) {
1187 case VAR:
1188 if (TreeInfo.isReceiverParam(tree))
1189 mask = ReceiverParamFlags;
1190 else if (sym.owner.kind != TYP)
1191 mask = LocalVarFlags;
1192 else if ((sym.owner.flags_field & INTERFACE) != 0)
1193 mask = implicit = InterfaceVarFlags;
1194 else
1195 mask = VarFlags;
1196 break;
1197 case MTH:
1198 if (sym.name == names.init) {
1199 if ((sym.owner.flags_field & ENUM) != 0) {
1200 // enum constructors cannot be declared public or
1201 // protected and must be implicitly or explicitly
1202 // private
1203 implicit = PRIVATE;
1204 mask = PRIVATE;
1205 } else
1206 mask = ConstructorFlags;
1207 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1208 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1209 mask = AnnotationTypeElementMask;
1210 implicit = PUBLIC | ABSTRACT;
1211 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1212 mask = InterfaceMethodMask;
1213 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1214 if ((flags & DEFAULT) != 0) {
1215 implicit |= ABSTRACT;
1216 }
1217 } else {
1218 mask = implicit = InterfaceMethodFlags;
1219 }
1220 } else if ((sym.owner.flags_field & RECORD) != 0) {
1221 mask = RecordMethodFlags;
1222 } else {
1223 mask = MethodFlags;
1224 }
1225 if ((flags & STRICTFP) != 0) {
1226 warnOnExplicitStrictfp(pos);
1227 }
1228 // Imply STRICTFP if owner has STRICTFP set.
1229 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1230 ((flags) & Flags.DEFAULT) != 0)
1231 implicit |= sym.owner.flags_field & STRICTFP;
1232 break;
1233 case TYP:
1234 if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1235 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1236 boolean implicitlyStatic = !sym.isAnonymous() &&
1237 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1238 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1239 // local statics are allowed only if records are allowed too
1240 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1241 implicit = implicitlyStatic ? STATIC : implicit;
1242 } else if (sym.owner.kind == TYP) {
1243 // statics in inner classes are allowed only if records are allowed too
1244 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1245 if (sym.owner.owner.kind == PCK ||
1246 (sym.owner.flags_field & STATIC) != 0) {
1247 mask |= STATIC;
1248 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1249 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1250 }
1251 // Nested interfaces and enums are always STATIC (Spec ???)
1252 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1253 } else {
1254 mask = ExtendedClassFlags;
1255 }
1256 // Interfaces are always ABSTRACT
1257 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1258
1259 if ((flags & ENUM) != 0) {
1260 // enums can't be declared abstract, final, sealed or non-sealed
1261 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1262 implicit |= implicitEnumFinalFlag(tree);
1263 }
1264 if ((flags & RECORD) != 0) {
1265 // records can't be declared abstract
1266 mask &= ~ABSTRACT;
1267 implicit |= FINAL;
1268 }
1269 if ((flags & STRICTFP) != 0) {
1270 warnOnExplicitStrictfp(pos);
1271 }
1272 // Imply STRICTFP if owner has STRICTFP set.
1273 implicit |= sym.owner.flags_field & STRICTFP;
1274 break;
1275 default:
1276 throw new AssertionError();
1277 }
1278 long illegal = flags & ExtendedStandardFlags & ~mask;
1279 if (illegal != 0) {
1280 if ((illegal & INTERFACE) != 0) {
1281 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1282 mask |= INTERFACE;
1283 }
1284 else {
1285 log.error(pos,
1286 Errors.ModNotAllowedHere(asFlagSet(illegal)));
1287 }
1288 }
1289 else if ((sym.kind == TYP ||
1290 // ISSUE: Disallowing abstract&private is no longer appropriate
1291 // in the presence of inner classes. Should it be deleted here?
1292 checkDisjoint(pos, flags,
1293 ABSTRACT,
1294 PRIVATE | STATIC | DEFAULT))
1295 &&
1296 checkDisjoint(pos, flags,
1297 STATIC | PRIVATE,
1298 DEFAULT)
1299 &&
1300 checkDisjoint(pos, flags,
1301 ABSTRACT | INTERFACE,
1302 FINAL | NATIVE | SYNCHRONIZED)
1303 &&
1304 checkDisjoint(pos, flags,
1305 PUBLIC,
1306 PRIVATE | PROTECTED)
1307 &&
1308 checkDisjoint(pos, flags,
1309 PRIVATE,
1310 PUBLIC | PROTECTED)
1311 &&
1312 checkDisjoint(pos, flags,
1313 FINAL,
1314 VOLATILE)
1315 &&
1316 (sym.kind == TYP ||
1317 checkDisjoint(pos, flags,
1318 ABSTRACT | NATIVE,
1319 STRICTFP))
1320 && checkDisjoint(pos, flags,
1321 FINAL,
1322 SEALED | NON_SEALED)
1323 && checkDisjoint(pos, flags,
1324 SEALED,
1325 FINAL | NON_SEALED)
1326 && checkDisjoint(pos, flags,
1327 SEALED,
1328 ANNOTATION)) {
1329 // skip
1330 }
1331 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1332 }
1333
1334 private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1335 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1336 try {
1337 deferredLintHandler.report(() -> {
1338 if (lint.isEnabled(LintCategory.STRICTFP)) {
1339 log.warning(LintCategory.STRICTFP,
1340 pos, Warnings.Strictfp); }
1341 });
1342 } finally {
1343 deferredLintHandler.setPos(prevLintPos);
1344 }
1345 }
1346
1347
1348 /** Determine if this enum should be implicitly final.
1481 @Override
1482 public void visitWildcard(JCWildcard tree) {
1483 if (tree.inner != null)
1484 validateTree(tree.inner, true, isOuter);
1485 }
1486
1487 @Override
1488 public void visitSelect(JCFieldAccess tree) {
1489 if (tree.type.hasTag(CLASS)) {
1490 visitSelectInternal(tree);
1491
1492 // Check that this type is either fully parameterized, or
1493 // not parameterized at all.
1494 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1495 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1496 }
1497 }
1498
1499 public void visitSelectInternal(JCFieldAccess tree) {
1500 if (tree.type.tsym.isStatic() &&
1501 tree.selected.type.isParameterized()) {
1502 // The enclosing type is not a class, so we are
1503 // looking at a static member type. However, the
1504 // qualifying expression is parameterized.
1505 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1506 } else {
1507 // otherwise validate the rest of the expression
1508 tree.selected.accept(this);
1509 }
1510 }
1511
1512 @Override
1513 public void visitAnnotatedType(JCAnnotatedType tree) {
1514 tree.underlyingType.accept(this);
1515 }
1516
1517 @Override
1518 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1519 if (that.type.hasTag(TypeTag.VOID)) {
1520 log.error(that.pos(), Errors.VoidNotAllowedHere);
1521 }
1522 super.visitTypeIdent(that);
1523 }
1524
1548
1549 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1550 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1551 validateTree(l.head, checkRaw, isOuter);
1552 }
1553 }
1554
1555 void checkRaw(JCTree tree, Env<AttrContext> env) {
1556 if (lint.isEnabled(LintCategory.RAW) &&
1557 tree.type.hasTag(CLASS) &&
1558 !TreeInfo.isDiamond(tree) &&
1559 !withinAnonConstr(env) &&
1560 tree.type.isRaw()) {
1561 log.warning(LintCategory.RAW,
1562 tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1563 }
1564 }
1565 //where
1566 private boolean withinAnonConstr(Env<AttrContext> env) {
1567 return env.enclClass.name.isEmpty() &&
1568 env.enclMethod != null && env.enclMethod.name == names.init;
1569 }
1570
1571 /* *************************************************************************
1572 * Exception checking
1573 **************************************************************************/
1574
1575 /* The following methods treat classes as sets that contain
1576 * the class itself and all their subclasses
1577 */
1578
1579 /** Is given type a subtype of some of the types in given list?
1580 */
1581 boolean subset(Type t, List<Type> ts) {
1582 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1583 if (types.isSubtype(t, l.head)) return true;
1584 return false;
1585 }
1586
1587 /** Is given type a subtype or supertype of
1588 * some of the types in given list?
2149 if (recordComponent.isPresent()) {
2150 return;
2151 }
2152 }
2153
2154 for (Type t = origin.type; t.hasTag(CLASS);
2155 t = types.supertype(t)) {
2156 if (t != origin.type) {
2157 checkOverride(tree, t, origin, m);
2158 }
2159 for (Type t2 : types.interfaces(t)) {
2160 checkOverride(tree, t2, origin, m);
2161 }
2162 }
2163
2164 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2165 // Check if this method must override a super method due to being annotated with @Override
2166 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2167 // be treated "as if as they were annotated" with @Override.
2168 boolean mustOverride = explicitOverride ||
2169 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2170 if (mustOverride && !isOverrider(m)) {
2171 DiagnosticPosition pos = tree.pos();
2172 for (JCAnnotation a : tree.getModifiers().annotations) {
2173 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2174 pos = a.pos();
2175 break;
2176 }
2177 }
2178 log.error(pos,
2179 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2180 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2181 }
2182 }
2183
2184 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2185 TypeSymbol c = site.tsym;
2186 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2187 if (m.overrides(sym, origin, types, false)) {
2188 if ((sym.flags() & ABSTRACT) == 0) {
2189 checkOverride(tree, m, (MethodSymbol)sym, origin);
2275 cf.test(s2) &&
2276 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2277 }
2278
2279
2280 /** Check that all abstract members of given class have definitions.
2281 * @param pos Position to be used for error reporting.
2282 * @param c The class.
2283 */
2284 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2285 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2286 if (undef != null) {
2287 MethodSymbol undef1 =
2288 new MethodSymbol(undef.flags(), undef.name,
2289 types.memberType(c.type, undef), undef.owner);
2290 log.error(pos,
2291 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2292 }
2293 }
2294
2295 void checkNonCyclicDecl(JCClassDecl tree) {
2296 CycleChecker cc = new CycleChecker();
2297 cc.scan(tree);
2298 if (!cc.errorFound && !cc.partialCheck) {
2299 tree.sym.flags_field |= ACYCLIC;
2300 }
2301 }
2302
2303 class CycleChecker extends TreeScanner {
2304
2305 Set<Symbol> seenClasses = new HashSet<>();
2306 boolean errorFound = false;
2307 boolean partialCheck = false;
2308
2309 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2310 if (sym != null && sym.kind == TYP) {
2311 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2312 if (classEnv != null) {
2313 DiagnosticSource prevSource = log.currentSource();
2314 try {
2523 /** Check that all abstract methods implemented by a class are
2524 * mutually compatible.
2525 * @param pos Position to be used for error reporting.
2526 * @param c The class whose interfaces are checked.
2527 */
2528 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2529 List<Type> supertypes = types.interfaces(c);
2530 Type supertype = types.supertype(c);
2531 if (supertype.hasTag(CLASS) &&
2532 (supertype.tsym.flags() & ABSTRACT) != 0)
2533 supertypes = supertypes.prepend(supertype);
2534 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2535 if (!l.head.getTypeArguments().isEmpty() &&
2536 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2537 return;
2538 for (List<Type> m = supertypes; m != l; m = m.tail)
2539 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2540 return;
2541 }
2542 checkCompatibleConcretes(pos, c);
2543 }
2544
2545 /** Check that all non-override equivalent methods accessible from 'site'
2546 * are mutually compatible (JLS 8.4.8/9.4.1).
2547 *
2548 * @param pos Position to be used for error reporting.
2549 * @param site The class whose methods are checked.
2550 * @param sym The method symbol to be checked.
2551 */
2552 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2553 ClashFilter cf = new ClashFilter(site);
2554 //for each method m1 that is overridden (directly or indirectly)
2555 //by method 'sym' in 'site'...
2556
2557 List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2558 boolean overridesAny = false;
2559 ArrayList<Symbol> symbolsByName = new ArrayList<>();
2560 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2561 for (Symbol m1 : symbolsByName) {
2562 if (!sym.overrides(m1, site.tsym, types, false)) {
2640 //where
2641 private class ClashFilter implements Predicate<Symbol> {
2642
2643 Type site;
2644
2645 ClashFilter(Type site) {
2646 this.site = site;
2647 }
2648
2649 boolean shouldSkip(Symbol s) {
2650 return (s.flags() & CLASH) != 0 &&
2651 s.owner == site.tsym;
2652 }
2653
2654 @Override
2655 public boolean test(Symbol s) {
2656 return s.kind == MTH &&
2657 (s.flags() & SYNTHETIC) == 0 &&
2658 !shouldSkip(s) &&
2659 s.isInheritedIn(site.tsym, types) &&
2660 !s.isConstructor();
2661 }
2662 }
2663
2664 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2665 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2666 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2667 Assert.check(m.kind == MTH);
2668 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2669 if (prov.size() > 1) {
2670 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2671 ListBuffer<Symbol> defaults = new ListBuffer<>();
2672 for (MethodSymbol provSym : prov) {
2673 if ((provSym.flags() & DEFAULT) != 0) {
2674 defaults = defaults.append(provSym);
2675 } else if ((provSym.flags() & ABSTRACT) != 0) {
2676 abstracts = abstracts.append(provSym);
2677 }
2678 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2679 //strong semantics - issue an error if two sibling interfaces
2680 //have two override-equivalent defaults - or if one is abstract
2699 }
2700 }
2701 }
2702 }
2703 }
2704
2705 //where
2706 private class DefaultMethodClashFilter implements Predicate<Symbol> {
2707
2708 Type site;
2709
2710 DefaultMethodClashFilter(Type site) {
2711 this.site = site;
2712 }
2713
2714 @Override
2715 public boolean test(Symbol s) {
2716 return s.kind == MTH &&
2717 (s.flags() & DEFAULT) != 0 &&
2718 s.isInheritedIn(site.tsym, types) &&
2719 !s.isConstructor();
2720 }
2721 }
2722
2723 /**
2724 * Report warnings for potentially ambiguous method declarations. Two declarations
2725 * are potentially ambiguous if they feature two unrelated functional interface
2726 * in same argument position (in which case, a call site passing an implicit
2727 * lambda would be ambiguous).
2728 */
2729 void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2730 MethodSymbol msym1, MethodSymbol msym2) {
2731 if (msym1 != msym2 &&
2732 lint.isEnabled(LintCategory.OVERLOADS) &&
2733 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2734 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2735 Type mt1 = types.memberType(site, msym1);
2736 Type mt2 = types.memberType(site, msym2);
2737 //if both generic methods, adjust type variables
2738 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2739 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
3402 Attribute app = arr.values[i];
3403 if (!(app instanceof Attribute.Enum attributeEnum)) {
3404 // recovery
3405 return Optional.empty();
3406 }
3407 targets[i] = attributeEnum.value.name;
3408 }
3409 }
3410 for (Name target : targets) {
3411 if (target == names.TYPE) {
3412 if (s.kind == TYP)
3413 applicableTargets.add(names.TYPE);
3414 } else if (target == names.FIELD) {
3415 if (s.kind == VAR && s.owner.kind != MTH)
3416 applicableTargets.add(names.FIELD);
3417 } else if (target == names.RECORD_COMPONENT) {
3418 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3419 applicableTargets.add(names.RECORD_COMPONENT);
3420 }
3421 } else if (target == names.METHOD) {
3422 if (s.kind == MTH && !s.isConstructor())
3423 applicableTargets.add(names.METHOD);
3424 } else if (target == names.PARAMETER) {
3425 if (s.kind == VAR &&
3426 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3427 applicableTargets.add(names.PARAMETER);
3428 }
3429 } else if (target == names.CONSTRUCTOR) {
3430 if (s.kind == MTH && s.isConstructor())
3431 applicableTargets.add(names.CONSTRUCTOR);
3432 } else if (target == names.LOCAL_VARIABLE) {
3433 if (s.kind == VAR && s.owner.kind == MTH &&
3434 (s.flags() & PARAMETER) == 0) {
3435 applicableTargets.add(names.LOCAL_VARIABLE);
3436 }
3437 } else if (target == names.ANNOTATION_TYPE) {
3438 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3439 applicableTargets.add(names.ANNOTATION_TYPE);
3440 }
3441 } else if (target == names.PACKAGE) {
3442 if (s.kind == PCK)
3443 applicableTargets.add(names.PACKAGE);
3444 } else if (target == names.TYPE_USE) {
3445 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3446 //cannot type annotate implicitly typed locals
3447 continue;
3448 } else if (s.kind == TYP || s.kind == VAR ||
3449 (s.kind == MTH && !s.isConstructor() &&
3450 !s.type.getReturnType().hasTag(VOID)) ||
3451 (s.kind == MTH && s.isConstructor())) {
3452 applicableTargets.add(names.TYPE_USE);
3453 }
3454 } else if (target == names.TYPE_PARAMETER) {
3455 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3456 applicableTargets.add(names.TYPE_PARAMETER);
3457 } else if (target == names.MODULE) {
3458 if (s.kind == MDL)
3459 applicableTargets.add(names.MODULE);
3460 } else
3461 return Optional.empty(); // Unknown ElementType. This should be an error at declaration site,
3462 // assume applicable.
3463 }
3464 return Optional.of(applicableTargets);
3465 }
3466
3467 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3468 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3469 if (atTarget == null) return null; // ok, is applicable
3470 Attribute atValue = atTarget.member(names.value);
3471 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
4729 });
4730 }
4731
4732 return null;
4733 }
4734
4735 boolean canBeSerialized(Type type) {
4736 return type.isPrimitive() || rs.isSerializable(type);
4737 }
4738
4739 /**
4740 * Check that Externalizable class needs a public no-arg
4741 * constructor.
4742 *
4743 * Check that a Serializable class has access to the no-arg
4744 * constructor of its first nonserializable superclass.
4745 */
4746 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
4747 if (isExternalizable(c.type)) {
4748 for(var sym : c.getEnclosedElements()) {
4749 if (sym.isConstructor() &&
4750 ((sym.flags() & PUBLIC) == PUBLIC)) {
4751 if (((MethodSymbol)sym).getParameters().isEmpty()) {
4752 return;
4753 }
4754 }
4755 }
4756 log.warning(LintCategory.SERIAL, tree.pos(),
4757 Warnings.ExternalizableMissingPublicNoArgCtor);
4758 } else {
4759 // Approximate access to the no-arg constructor up in
4760 // the superclass chain by checking that the
4761 // constructor is not private. This may not handle
4762 // some cross-package situations correctly.
4763 Type superClass = c.getSuperclass();
4764 // java.lang.Object is *not* Serializable so this loop
4765 // should terminate.
4766 while (rs.isSerializable(superClass) ) {
4767 try {
4768 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
4769 } catch(ClassCastException cce) {
4770 return ; // Don't try to recover
4771 }
4772 }
4773 // Non-Serializable superclass
4774 try {
4775 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
4776 for(var sym : supertype.getEnclosedElements()) {
4777 if (sym.isConstructor()) {
4778 MethodSymbol ctor = (MethodSymbol)sym;
4779 if (ctor.getParameters().isEmpty()) {
4780 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
4781 // Handle nested classes and implicit this$0
4782 (supertype.getNestingKind() == NestingKind.MEMBER &&
4783 ((supertype.flags() & STATIC) == 0)))
4784 log.warning(LintCategory.SERIAL, tree.pos(),
4785 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
4786 }
4787 }
4788 }
4789 } catch (ClassCastException cce) {
4790 return ; // Don't try to recover
4791 }
4792 return;
4793 }
4794 }
4795
4796 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
4797 // To be effective, serialVersionUID must be marked static
|
152
153 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
154 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
155 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
156 boolean enforceMandatoryWarnings = true;
157
158 deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
159 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
160 removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
161 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
162 uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
163 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
164 sunApiHandler = new MandatoryWarningHandler(log, null, false,
165 enforceMandatoryWarnings, "sunapi", null);
166
167 deferredLintHandler = DeferredLintHandler.instance(context);
168
169 allowModules = Feature.MODULES.allowedInSource(source);
170 allowRecords = Feature.RECORDS.allowedInSource(source);
171 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
172 allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
173 }
174
175 /** Character for synthetic names
176 */
177 char syntheticNameChar;
178
179 /** A table mapping flat names of all compiled classes for each module in this run
180 * to their symbols; maintained from outside.
181 */
182 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
183
184 /** A handler for messages about deprecated usage.
185 */
186 private MandatoryWarningHandler deprecationHandler;
187
188 /** A handler for messages about deprecated-for-removal usage.
189 */
190 private MandatoryWarningHandler removalHandler;
191
192 /** A handler for messages about unchecked or unsafe usage.
196 /** A handler for messages about using proprietary API.
197 */
198 private MandatoryWarningHandler sunApiHandler;
199
200 /** A handler for deferred lint warnings.
201 */
202 private DeferredLintHandler deferredLintHandler;
203
204 /** Are modules allowed
205 */
206 private final boolean allowModules;
207
208 /** Are records allowed
209 */
210 private final boolean allowRecords;
211
212 /** Are sealed classes allowed
213 */
214 private final boolean allowSealed;
215
216 /** Are primitive classes allowed
217 */
218 private final boolean allowPrimitiveClasses;
219
220 /* *************************************************************************
221 * Errors and Warnings
222 **************************************************************************/
223
224 Lint setLint(Lint newLint) {
225 Lint prev = lint;
226 lint = newLint;
227 return prev;
228 }
229
230 MethodSymbol setMethod(MethodSymbol newMethod) {
231 MethodSymbol prev = method;
232 method = newMethod;
233 return prev;
234 }
235
236 /** Warn about deprecated symbol.
237 * @param pos Position to be used for error reporting.
238 * @param sym The deprecated symbol.
239 */
602 public String toString() {
603 return "CheckContext: basicHandler";
604 }
605 };
606
607 /** Check that a given type is assignable to a given proto-type.
608 * If it is, return the type, otherwise return errType.
609 * @param pos Position to be used for error reporting.
610 * @param found The type that was found.
611 * @param req The type that was required.
612 */
613 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
614 return checkType(pos, found, req, basicHandler);
615 }
616
617 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
618 final InferenceContext inferenceContext = checkContext.inferenceContext();
619 if (inferenceContext.free(req) || inferenceContext.free(found)) {
620 inferenceContext.addFreeTypeListener(List.of(req, found),
621 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
622 } else {
623 if (allowPrimitiveClasses && found.hasTag(CLASS)) {
624 if (inferenceContext != infer.emptyContext)
625 checkParameterizationByPrimitiveClass(pos, found);
626 }
627 }
628 if (req.hasTag(ERROR))
629 return req;
630 if (req.hasTag(NONE))
631 return found;
632 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
633 return found;
634 } else {
635 if (found.isNumeric() && req.isNumeric()) {
636 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
637 return types.createErrorType(found);
638 }
639 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
640 return types.createErrorType(found);
641 }
642 }
643
644 /** Check that a given type can be cast to a given target type.
645 * Return the result of the cast.
646 * @param pos Position to be used for error reporting.
737 /** Check that type is a class or interface type.
738 * @param pos Position to be used for error reporting.
739 * @param t The type to be checked.
740 */
741 Type checkClassType(DiagnosticPosition pos, Type t) {
742 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
743 return typeTagError(pos,
744 diags.fragment(Fragments.TypeReqClass),
745 asTypeParam(t));
746 } else {
747 return t;
748 }
749 }
750 //where
751 private Object asTypeParam(Type t) {
752 return (t.hasTag(TYPEVAR))
753 ? diags.fragment(Fragments.TypeParameter(t))
754 : t;
755 }
756
757 void checkConstraintsOfValueClass(DiagnosticPosition pos, ClassSymbol c) {
758 for (Type st : types.closure(c.type)) {
759 if (st == null || st.tsym == null || st.tsym.kind == ERR)
760 continue;
761 if (st.tsym == syms.objectType.tsym || st.tsym == syms.recordType.tsym || st.isInterface())
762 continue;
763 if (!st.tsym.isAbstract()) {
764 if (c != st.tsym) {
765 log.error(pos, Errors.ConcreteSupertypeForValueClass(c, st));
766 }
767 continue;
768 }
769 // dealing with an abstract value or value super class below.
770 Fragment fragment = c.isAbstract() && c.isValueClass() && c == st.tsym ? Fragments.AbstractValueClass(c) : Fragments.SuperclassOfValueClass(c, st);
771 if ((st.tsym.flags() & HASINITBLOCK) != 0) {
772 log.error(pos, Errors.AbstractValueClassDeclaresInitBlock(fragment));
773 }
774 Type encl = st.getEnclosingType();
775 if (encl != null && encl.hasTag(CLASS)) {
776 log.error(pos, Errors.AbstractValueClassCannotBeInner(fragment));
777 }
778 for (Symbol s : st.tsym.members().getSymbols(NON_RECURSIVE)) {
779 switch (s.kind) {
780 case VAR:
781 if ((s.flags() & STATIC) == 0) {
782 log.error(pos, Errors.InstanceFieldNotAllowed(s, fragment));
783 }
784 break;
785 case MTH:
786 if ((s.flags() & (SYNCHRONIZED | STATIC)) == SYNCHRONIZED) {
787 log.error(pos, Errors.SuperClassMethodCannotBeSynchronized(s, c, st));
788 } else if (s.isInitOrVNew()) {
789 MethodSymbol m = (MethodSymbol)s;
790 if (m.getParameters().size() > 0) {
791 log.error(pos, Errors.AbstractValueClassConstructorCannotTakeArguments(m, fragment));
792 } else if (m.getTypeParameters().size() > 0) {
793 log.error(pos, Errors.AbstractValueClassConstructorCannotBeGeneric(m, fragment));
794 } else if (m.type.getThrownTypes().size() > 0) {
795 log.error(pos, Errors.AbstractValueClassConstructorCannotThrow(m, fragment));
796 } else if (protection(m.flags()) > protection(m.owner.flags())) {
797 log.error(pos, Errors.AbstractValueClassConstructorHasWeakerAccess(m, fragment));
798 } else if ((m.flags() & EMPTYNOARGCONSTR) == 0) {
799 log.error(pos, Errors.AbstractValueClassNoArgConstructorMustBeEmpty(m, fragment));
800 }
801 }
802 break;
803 }
804 }
805 }
806 }
807
808 /** Check that type is a valid qualifier for a constructor reference expression
809 */
810 Type checkConstructorRefType(JCExpression expr, Type t) {
811 t = checkClassOrArrayType(expr, t);
812 if (t.hasTag(CLASS)) {
813 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
814 log.error(expr, Errors.AbstractCantBeInstantiated(t.tsym));
815 t = types.createErrorType(t);
816 } else if ((t.tsym.flags() & ENUM) != 0) {
817 log.error(expr, Errors.EnumCantBeInstantiated);
818 t = types.createErrorType(t);
819 } else {
820 // Projection types may not be mentioned in constructor references
821 if (expr.hasTag(SELECT)) {
822 JCFieldAccess fieldAccess = (JCFieldAccess) expr;
823 if (allowPrimitiveClasses && fieldAccess.selected.type.isPrimitiveClass() &&
824 (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
825 log.error(expr, Errors.ProjectionCantBeInstantiated);
826 t = types.createErrorType(t);
827 }
828 }
829 t = checkClassType(expr, t, true);
830 }
831 } else if (t.hasTag(ARRAY)) {
832 if (!types.isReifiable(((ArrayType)t).elemtype)) {
833 log.error(expr, Errors.GenericArrayCreation);
834 t = types.createErrorType(t);
835 }
836 }
837 return t;
838 }
839
840 /** Check that type is a class or interface type.
841 * @param pos Position to be used for error reporting.
842 * @param t The type to be checked.
843 * @param noBounds True if type bounds are illegal here.
844 */
845 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
846 t = checkClassType(pos, t);
847 if (noBounds && t.isParameterized()) {
848 List<Type> args = t.getTypeArguments();
849 while (args.nonEmpty()) {
850 if (args.head.hasTag(WILDCARD))
851 return typeTagError(pos,
852 diags.fragment(Fragments.TypeReqExact),
853 args.head);
854 args = args.tail;
855 }
856 }
857 return t;
858 }
859
860 /** Check that type is a reference type, i.e. a class, interface or array type
861 * or a type variable.
862 * @param pos Position to be used for error reporting.
863 * @param t The type to be checked.
864 * @param primitiveClassOK If false, a primitive class does not qualify
865 */
866 Type checkRefType(DiagnosticPosition pos, Type t, boolean primitiveClassOK) {
867 if (t.isReference() && (!allowPrimitiveClasses || primitiveClassOK || !t.isPrimitiveClass()))
868 return t;
869 else
870 return typeTagError(pos,
871 diags.fragment(Fragments.TypeReqRef),
872 t);
873 }
874
875 /** Check that type is an identity type, i.e. not a primitive/value type
876 * nor its reference projection. When not discernible statically,
877 * give it the benefit of doubt and defer to runtime.
878 *
879 * @param pos Position to be used for error reporting.
880 * @param t The type to be checked.
881 */
882 void checkIdentityType(DiagnosticPosition pos, Type t) {
883 if (t.hasTag(TYPEVAR)) {
884 t = types.skipTypeVars(t, false);
885 }
886 if (t.isIntersection()) {
887 IntersectionClassType ict = (IntersectionClassType)t;
888 for (Type component : ict.getExplicitComponents()) {
889 checkIdentityType(pos, component);
890 }
891 return;
892 }
893 if (t.isPrimitive() || t.isValueClass() || t.isValueInterface() || t.isReferenceProjection())
894 typeTagError(pos, diags.fragment(Fragments.TypeReqIdentity), t);
895 }
896
897 /** Check that type is a reference type, i.e. a class, interface or array type
898 * or a type variable.
899 * @param pos Position to be used for error reporting.
900 * @param t The type to be checked.
901 */
902 Type checkRefType(DiagnosticPosition pos, Type t) {
903 return checkRefType(pos, t, true);
904 }
905
906 /** Check that each type is a reference type, i.e. a class, interface or array type
907 * or a type variable.
908 * @param trees Original trees, used for error reporting.
909 * @param types The types to be checked.
910 */
911 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
912 List<JCExpression> tl = trees;
913 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
914 l.head = checkRefType(tl.head.pos(), l.head, false);
915 tl = tl.tail;
916 }
917 return types;
918 }
919
920 /** Check that type is a null or reference type.
921 * @param pos Position to be used for error reporting.
922 * @param t The type to be checked.
923 */
924 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
925 if (t.isReference() || t.hasTag(BOT))
926 return t;
927 else
928 return typeTagError(pos,
929 diags.fragment(Fragments.TypeReqRef),
930 t);
931 }
932
933 /** Check that flag set does not contain elements of two conflicting sets. s
934 * Return true if it doesn't.
935 * @param pos Position to be used for error reporting.
936 * @param flags The set of flags to be checked.
937 * @param set1 Conflicting flags set #1.
938 * @param set2 Conflicting flags set #2.
939 */
940 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
941 if ((flags & set1) != 0 && (flags & set2) != 0) {
942 log.error(pos,
943 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
944 asFlagSet(TreeInfo.firstFlag(flags & set2))));
945 return false;
946 } else
947 return true;
948 }
949
950 void checkParameterizationByPrimitiveClass(DiagnosticPosition pos, Type t) {
951 parameterizationByPrimitiveClassChecker.visit(t, pos);
952 }
953
954 /** parameterizationByPrimitiveClassChecker: A type visitor that descends down the given type looking for instances of primitive classes
955 * being used as type arguments and issues error against those usages.
956 */
957 private final Types.SimpleVisitor<Void, DiagnosticPosition> parameterizationByPrimitiveClassChecker =
958 new Types.SimpleVisitor<Void, DiagnosticPosition>() {
959
960 @Override
961 public Void visitType(Type t, DiagnosticPosition pos) {
962 return null;
963 }
964
965 @Override
966 public Void visitClassType(ClassType t, DiagnosticPosition pos) {
967 for (Type targ : t.allparams()) {
968 if (allowPrimitiveClasses && targ.isPrimitiveClass()) {
969 log.error(pos, Errors.GenericParameterizationWithPrimitiveClass(t));
970 }
971 visit(targ, pos);
972 }
973 return null;
974 }
975
976 @Override
977 public Void visitTypeVar(TypeVar t, DiagnosticPosition pos) {
978 return null;
979 }
980
981 @Override
982 public Void visitCapturedType(CapturedType t, DiagnosticPosition pos) {
983 return null;
984 }
985
986 @Override
987 public Void visitArrayType(ArrayType t, DiagnosticPosition pos) {
988 return visit(t.elemtype, pos);
989 }
990
991 @Override
992 public Void visitWildcardType(WildcardType t, DiagnosticPosition pos) {
993 return visit(t.type, pos);
994 }
995 };
996
997
998
999 /** Check that usage of diamond operator is correct (i.e. diamond should not
1000 * be used with non-generic classes or in anonymous class creation expressions)
1001 */
1002 Type checkDiamond(JCNewClass tree, Type t) {
1003 if (!TreeInfo.isDiamond(tree) ||
1004 t.isErroneous()) {
1005 return checkClassType(tree.clazz.pos(), t, true);
1006 } else {
1007 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
1008 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
1009 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
1010 }
1011 if (t.tsym.type.getTypeArguments().isEmpty()) {
1012 log.error(tree.clazz.pos(),
1013 Errors.CantApplyDiamond1(t,
1014 Fragments.DiamondNonGeneric(t)));
1015 return types.createErrorType(t);
1016 } else if (tree.typeargs != null &&
1017 tree.typeargs.nonEmpty()) {
1018 log.error(tree.clazz.pos(),
1111 msg));
1112 } else {
1113 log.error(tree,
1114 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
1115 Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
1116 }
1117 } else if (hasTrustMeAnno && varargElemType != null &&
1118 types.isReifiable(varargElemType)) {
1119 warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
1120 syms.trustMeType.tsym,
1121 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
1122 }
1123 else if (!hasTrustMeAnno && varargElemType != null &&
1124 !types.isReifiable(varargElemType)) {
1125 warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
1126 }
1127 }
1128 //where
1129 private boolean isTrustMeAllowedOnMethod(Symbol s) {
1130 return (s.flags() & VARARGS) != 0 &&
1131 (s.isInitOrVNew() ||
1132 (s.flags() & (STATIC | FINAL |
1133 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
1134 }
1135
1136 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
1137 //check that resulting type is not the null type
1138 if (t.hasTag(BOT)) {
1139 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
1140 return types.createErrorType(t);
1141 } else if (t.hasTag(VOID)) {
1142 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
1143 return types.createErrorType(t);
1144 }
1145
1146 //upward project the initializer type
1147 Type varType = types.upward(t, types.captures(t)).baseType();
1148 if (allowPrimitiveClasses && varType.hasTag(CLASS)) {
1149 checkParameterizationByPrimitiveClass(pos, varType);
1150 }
1151 return varType;
1152 }
1153
1154 Type checkMethod(final Type mtype,
1155 final Symbol sym,
1156 final Env<AttrContext> env,
1157 final List<JCExpression> argtrees,
1158 final List<Type> argtypes,
1159 final boolean useVarargs,
1160 InferenceContext inferenceContext) {
1161 // System.out.println("call : " + env.tree);
1162 // System.out.println("method : " + owntype);
1163 // System.out.println("actuals: " + argtypes);
1164 if (inferenceContext.free(mtype)) {
1165 inferenceContext.addFreeTypeListener(List.of(mtype),
1166 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1167 return mtype;
1168 }
1169 Type owntype = mtype;
1170 List<Type> formals = owntype.getParameterTypes();
1171 List<Type> nonInferred = sym.type.getParameterTypes();
1172 if (nonInferred.length() != formals.length()) nonInferred = formals;
1173 Type last = useVarargs ? formals.last() : null;
1174 // TODO - is enum so <init>
1175 if (sym.name == names.init && sym.owner == syms.enumSym) {
1176 formals = formals.tail.tail;
1177 nonInferred = nonInferred.tail.tail;
1178 }
1179 if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1180 formals = formals.tail;
1181 nonInferred = nonInferred.tail;
1182 }
1183 List<JCExpression> args = argtrees;
1184 if (args != null) {
1185 //this is null when type-checking a method reference
1186 while (formals.head != last) {
1187 JCTree arg = args.head;
1188 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1189 assertConvertible(arg, arg.type, formals.head, warn);
1190 args = args.tail;
1191 formals = formals.tail;
1192 nonInferred = nonInferred.tail;
1193 }
1194 if (useVarargs) {
1330 * return modifiers together with any implicit modifiers for that symbol.
1331 * Warning: we can't use flags() here since this method
1332 * is called during class enter, when flags() would cause a premature
1333 * completion.
1334 * @param pos Position to be used for error reporting.
1335 * @param flags The set of modifiers given in a definition.
1336 * @param sym The defined symbol.
1337 */
1338 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1339 long mask;
1340 long implicit = 0;
1341
1342 switch (sym.kind) {
1343 case VAR:
1344 if (TreeInfo.isReceiverParam(tree))
1345 mask = ReceiverParamFlags;
1346 else if (sym.owner.kind != TYP)
1347 mask = LocalVarFlags;
1348 else if ((sym.owner.flags_field & INTERFACE) != 0)
1349 mask = implicit = InterfaceVarFlags;
1350 else {
1351 mask = VarFlags;
1352 if (sym.owner.type.isValueClass() && (flags & STATIC) == 0) {
1353 implicit |= FINAL;
1354 }
1355 }
1356 break;
1357 case MTH:
1358 if (names.isInitOrVNew(sym.name)) {
1359 if ((sym.owner.flags_field & ENUM) != 0) {
1360 // enum constructors cannot be declared public or
1361 // protected and must be implicitly or explicitly
1362 // private
1363 implicit = PRIVATE;
1364 mask = PRIVATE;
1365 } else
1366 mask = ConstructorFlags;
1367 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1368 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1369 mask = AnnotationTypeElementMask;
1370 implicit = PUBLIC | ABSTRACT;
1371 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1372 mask = InterfaceMethodMask;
1373 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1374 if ((flags & DEFAULT) != 0) {
1375 implicit |= ABSTRACT;
1376 }
1377 } else {
1378 mask = implicit = InterfaceMethodFlags;
1379 }
1380 } else if ((sym.owner.flags_field & RECORD) != 0) {
1381 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1382 RecordMethodFlags & ~SYNCHRONIZED : RecordMethodFlags;
1383 } else {
1384 // value objects do not have an associated monitor/lock
1385 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1386 MethodFlags & ~SYNCHRONIZED : MethodFlags;
1387 }
1388 if ((flags & STRICTFP) != 0) {
1389 warnOnExplicitStrictfp(pos);
1390 }
1391 // Imply STRICTFP if owner has STRICTFP set.
1392 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1393 ((flags) & Flags.DEFAULT) != 0)
1394 implicit |= sym.owner.flags_field & STRICTFP;
1395 break;
1396 case TYP:
1397 if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1398 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1399 boolean implicitlyStatic = !sym.isAnonymous() &&
1400 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1401 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1402 // local statics are allowed only if records are allowed too
1403 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedStaticLocalClassFlags : ExtendedLocalClassFlags;
1404 implicit = implicitlyStatic ? STATIC : implicit;
1405 } else if (sym.owner.kind == TYP) {
1406 // statics in inner classes are allowed only if records are allowed too
1407 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1408 if (sym.owner.owner.kind == PCK ||
1409 (sym.owner.flags_field & STATIC) != 0) {
1410 mask |= STATIC;
1411 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1412 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1413 }
1414 // Nested interfaces and enums are always STATIC (Spec ???)
1415 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1416 } else {
1417 mask = ExtendedClassFlags;
1418 }
1419 // Interfaces are always ABSTRACT
1420 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1421
1422 if ((flags & ENUM) != 0) {
1423 // enums can't be declared abstract, final, sealed or non-sealed or primitive/value
1424 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED | PRIMITIVE_CLASS | VALUE_CLASS);
1425 implicit |= implicitEnumFinalFlag(tree);
1426 }
1427 if ((flags & RECORD) != 0) {
1428 // records can't be declared abstract
1429 mask &= ~ABSTRACT;
1430 implicit |= FINAL;
1431 }
1432 if ((flags & STRICTFP) != 0) {
1433 warnOnExplicitStrictfp(pos);
1434 }
1435 // Imply STRICTFP if owner has STRICTFP set.
1436 implicit |= sym.owner.flags_field & STRICTFP;
1437
1438 // primitive classes are implicitly final value classes.
1439 if ((flags & PRIMITIVE_CLASS) != 0)
1440 implicit |= VALUE_CLASS | FINAL;
1441
1442 // concrete value classes are implicitly final
1443 if ((flags & (ABSTRACT | INTERFACE | VALUE_CLASS)) == VALUE_CLASS) {
1444 implicit |= FINAL;
1445 if ((flags & NON_SEALED) != 0) {
1446 // cant declare a final value class non-sealed
1447 log.error(pos,
1448 Errors.ModNotAllowedHere(asFlagSet(NON_SEALED)));
1449 }
1450 }
1451
1452 // TYPs can't be declared synchronized
1453 mask &= ~SYNCHRONIZED;
1454 break;
1455 default:
1456 throw new AssertionError();
1457 }
1458 long illegal = flags & ExtendedStandardFlags & ~mask;
1459 if (illegal != 0) {
1460 if ((illegal & INTERFACE) != 0) {
1461 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1462 mask |= INTERFACE;
1463 }
1464 else {
1465 log.error(pos,
1466 Errors.ModNotAllowedHere(asFlagSet(illegal)));
1467 }
1468 }
1469 else if ((sym.kind == TYP ||
1470 // ISSUE: Disallowing abstract&private is no longer appropriate
1471 // in the presence of inner classes. Should it be deleted here?
1472 checkDisjoint(pos, flags,
1473 ABSTRACT,
1474 PRIVATE | STATIC | DEFAULT))
1475 &&
1476 checkDisjoint(pos, flags,
1477 STATIC | PRIVATE,
1478 DEFAULT)
1479 &&
1480 checkDisjoint(pos, flags,
1481 ABSTRACT | INTERFACE,
1482 FINAL | NATIVE | SYNCHRONIZED | PRIMITIVE_CLASS)
1483 &&
1484 checkDisjoint(pos, flags,
1485 IDENTITY_TYPE,
1486 PRIMITIVE_CLASS | VALUE_CLASS)
1487 &&
1488 checkDisjoint(pos, flags,
1489 PUBLIC,
1490 PRIVATE | PROTECTED)
1491 &&
1492 checkDisjoint(pos, flags,
1493 PRIVATE,
1494 PUBLIC | PROTECTED)
1495 &&
1496 checkDisjoint(pos, (flags | implicit), // complain against volatile & implcitly final entities too.
1497 FINAL,
1498 VOLATILE)
1499 &&
1500 (sym.kind == TYP ||
1501 checkDisjoint(pos, flags,
1502 ABSTRACT | NATIVE,
1503 STRICTFP))
1504 && checkDisjoint(pos, flags,
1505 FINAL,
1506 SEALED | NON_SEALED)
1507 && checkDisjoint(pos, flags,
1508 SEALED,
1509 FINAL | NON_SEALED)
1510 && checkDisjoint(pos, flags,
1511 SEALED,
1512 ANNOTATION)
1513 && checkDisjoint(pos, flags,
1514 IDENTITY_TYPE,
1515 ANNOTATION)
1516 && checkDisjoint(pos, flags,
1517 VALUE_CLASS,
1518 ANNOTATION) ) {
1519 // skip
1520 }
1521 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1522 }
1523
1524 private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1525 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1526 try {
1527 deferredLintHandler.report(() -> {
1528 if (lint.isEnabled(LintCategory.STRICTFP)) {
1529 log.warning(LintCategory.STRICTFP,
1530 pos, Warnings.Strictfp); }
1531 });
1532 } finally {
1533 deferredLintHandler.setPos(prevLintPos);
1534 }
1535 }
1536
1537
1538 /** Determine if this enum should be implicitly final.
1671 @Override
1672 public void visitWildcard(JCWildcard tree) {
1673 if (tree.inner != null)
1674 validateTree(tree.inner, true, isOuter);
1675 }
1676
1677 @Override
1678 public void visitSelect(JCFieldAccess tree) {
1679 if (tree.type.hasTag(CLASS)) {
1680 visitSelectInternal(tree);
1681
1682 // Check that this type is either fully parameterized, or
1683 // not parameterized at all.
1684 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1685 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1686 }
1687 }
1688
1689 public void visitSelectInternal(JCFieldAccess tree) {
1690 if (tree.type.tsym.isStatic() &&
1691 tree.selected.type.isParameterized() &&
1692 (tree.name != names.ref || !tree.type.isReferenceProjection())) {
1693 // The enclosing type is not a class, so we are
1694 // looking at a static member type. However, the
1695 // qualifying expression is parameterized.
1696 // Tolerate the pseudo-select V.ref: V<T>.ref will be static if V<T> is and
1697 // should not be confused as selecting a static member of a parameterized type.
1698 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1699 } else {
1700 // otherwise validate the rest of the expression
1701 tree.selected.accept(this);
1702 }
1703 }
1704
1705 @Override
1706 public void visitAnnotatedType(JCAnnotatedType tree) {
1707 tree.underlyingType.accept(this);
1708 }
1709
1710 @Override
1711 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1712 if (that.type.hasTag(TypeTag.VOID)) {
1713 log.error(that.pos(), Errors.VoidNotAllowedHere);
1714 }
1715 super.visitTypeIdent(that);
1716 }
1717
1741
1742 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1743 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1744 validateTree(l.head, checkRaw, isOuter);
1745 }
1746 }
1747
1748 void checkRaw(JCTree tree, Env<AttrContext> env) {
1749 if (lint.isEnabled(LintCategory.RAW) &&
1750 tree.type.hasTag(CLASS) &&
1751 !TreeInfo.isDiamond(tree) &&
1752 !withinAnonConstr(env) &&
1753 tree.type.isRaw()) {
1754 log.warning(LintCategory.RAW,
1755 tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1756 }
1757 }
1758 //where
1759 private boolean withinAnonConstr(Env<AttrContext> env) {
1760 return env.enclClass.name.isEmpty() &&
1761 env.enclMethod != null && names.isInitOrVNew(env.enclMethod.name);
1762 }
1763
1764 /* *************************************************************************
1765 * Exception checking
1766 **************************************************************************/
1767
1768 /* The following methods treat classes as sets that contain
1769 * the class itself and all their subclasses
1770 */
1771
1772 /** Is given type a subtype of some of the types in given list?
1773 */
1774 boolean subset(Type t, List<Type> ts) {
1775 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1776 if (types.isSubtype(t, l.head)) return true;
1777 return false;
1778 }
1779
1780 /** Is given type a subtype or supertype of
1781 * some of the types in given list?
2342 if (recordComponent.isPresent()) {
2343 return;
2344 }
2345 }
2346
2347 for (Type t = origin.type; t.hasTag(CLASS);
2348 t = types.supertype(t)) {
2349 if (t != origin.type) {
2350 checkOverride(tree, t, origin, m);
2351 }
2352 for (Type t2 : types.interfaces(t)) {
2353 checkOverride(tree, t2, origin, m);
2354 }
2355 }
2356
2357 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2358 // Check if this method must override a super method due to being annotated with @Override
2359 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2360 // be treated "as if as they were annotated" with @Override.
2361 boolean mustOverride = explicitOverride ||
2362 (env.info.isAnonymousDiamond && !m.isInitOrVNew() && !m.isPrivate());
2363 if (mustOverride && !isOverrider(m)) {
2364 DiagnosticPosition pos = tree.pos();
2365 for (JCAnnotation a : tree.getModifiers().annotations) {
2366 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2367 pos = a.pos();
2368 break;
2369 }
2370 }
2371 log.error(pos,
2372 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2373 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2374 }
2375 }
2376
2377 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2378 TypeSymbol c = site.tsym;
2379 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2380 if (m.overrides(sym, origin, types, false)) {
2381 if ((sym.flags() & ABSTRACT) == 0) {
2382 checkOverride(tree, m, (MethodSymbol)sym, origin);
2468 cf.test(s2) &&
2469 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2470 }
2471
2472
2473 /** Check that all abstract members of given class have definitions.
2474 * @param pos Position to be used for error reporting.
2475 * @param c The class.
2476 */
2477 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2478 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2479 if (undef != null) {
2480 MethodSymbol undef1 =
2481 new MethodSymbol(undef.flags(), undef.name,
2482 types.memberType(c.type, undef), undef.owner);
2483 log.error(pos,
2484 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2485 }
2486 }
2487
2488 // A primitive class cannot contain a field of its own type either or indirectly.
2489 void checkNonCyclicMembership(JCClassDecl tree) {
2490 if (allowPrimitiveClasses) {
2491 Assert.check((tree.sym.flags_field & LOCKED) == 0);
2492 try {
2493 tree.sym.flags_field |= LOCKED;
2494 for (List<? extends JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2495 if (l.head.hasTag(VARDEF)) {
2496 JCVariableDecl field = (JCVariableDecl) l.head;
2497 if (cyclePossible(field.sym)) {
2498 checkNonCyclicMembership((ClassSymbol) field.type.tsym, field.pos());
2499 }
2500 }
2501 }
2502 } finally {
2503 tree.sym.flags_field &= ~LOCKED;
2504 }
2505 }
2506 }
2507 // where
2508 private void checkNonCyclicMembership(ClassSymbol c, DiagnosticPosition pos) {
2509 if ((c.flags_field & LOCKED) != 0) {
2510 log.error(pos, Errors.CyclicPrimitiveClassMembership(c));
2511 return;
2512 }
2513 try {
2514 c.flags_field |= LOCKED;
2515 for (Symbol fld : c.members().getSymbols(s -> s.kind == VAR && cyclePossible((VarSymbol) s), NON_RECURSIVE)) {
2516 checkNonCyclicMembership((ClassSymbol) fld.type.tsym, pos);
2517 }
2518 } finally {
2519 c.flags_field &= ~LOCKED;
2520 }
2521 }
2522 // where
2523 private boolean cyclePossible(VarSymbol symbol) {
2524 return (symbol.flags() & STATIC) == 0 && allowPrimitiveClasses && symbol.type.isPrimitiveClass();
2525 }
2526
2527 void checkNonCyclicDecl(JCClassDecl tree) {
2528 CycleChecker cc = new CycleChecker();
2529 cc.scan(tree);
2530 if (!cc.errorFound && !cc.partialCheck) {
2531 tree.sym.flags_field |= ACYCLIC;
2532 }
2533 }
2534
2535 class CycleChecker extends TreeScanner {
2536
2537 Set<Symbol> seenClasses = new HashSet<>();
2538 boolean errorFound = false;
2539 boolean partialCheck = false;
2540
2541 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2542 if (sym != null && sym.kind == TYP) {
2543 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2544 if (classEnv != null) {
2545 DiagnosticSource prevSource = log.currentSource();
2546 try {
2755 /** Check that all abstract methods implemented by a class are
2756 * mutually compatible.
2757 * @param pos Position to be used for error reporting.
2758 * @param c The class whose interfaces are checked.
2759 */
2760 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2761 List<Type> supertypes = types.interfaces(c);
2762 Type supertype = types.supertype(c);
2763 if (supertype.hasTag(CLASS) &&
2764 (supertype.tsym.flags() & ABSTRACT) != 0)
2765 supertypes = supertypes.prepend(supertype);
2766 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2767 if (!l.head.getTypeArguments().isEmpty() &&
2768 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2769 return;
2770 for (List<Type> m = supertypes; m != l; m = m.tail)
2771 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2772 return;
2773 }
2774 checkCompatibleConcretes(pos, c);
2775
2776 boolean cIsValue = (c.tsym.flags() & VALUE_CLASS) != 0;
2777 boolean cHasIdentity = (c.tsym.flags() & IDENTITY_TYPE) != 0;
2778 Type identitySuper = null, valueSuper = null;
2779 for (Type t : types.closure(c)) {
2780 if (t != c) {
2781 if ((t.tsym.flags() & IDENTITY_TYPE) != 0)
2782 identitySuper = t;
2783 else if ((t.tsym.flags() & VALUE_CLASS) != 0)
2784 valueSuper = t;
2785 if (cIsValue && identitySuper != null) {
2786 log.error(pos, Errors.ValueTypeHasIdentitySuperType(c, identitySuper));
2787 break;
2788 } else if (cHasIdentity && valueSuper != null) {
2789 log.error(pos, Errors.IdentityTypeHasValueSuperType(c, valueSuper));
2790 break;
2791 } else if (identitySuper != null && valueSuper != null) {
2792 log.error(pos, Errors.MutuallyIncompatibleSupers(c, identitySuper, valueSuper));
2793 break;
2794 }
2795 }
2796 }
2797 }
2798
2799 /** Check that all non-override equivalent methods accessible from 'site'
2800 * are mutually compatible (JLS 8.4.8/9.4.1).
2801 *
2802 * @param pos Position to be used for error reporting.
2803 * @param site The class whose methods are checked.
2804 * @param sym The method symbol to be checked.
2805 */
2806 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2807 ClashFilter cf = new ClashFilter(site);
2808 //for each method m1 that is overridden (directly or indirectly)
2809 //by method 'sym' in 'site'...
2810
2811 List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2812 boolean overridesAny = false;
2813 ArrayList<Symbol> symbolsByName = new ArrayList<>();
2814 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2815 for (Symbol m1 : symbolsByName) {
2816 if (!sym.overrides(m1, site.tsym, types, false)) {
2894 //where
2895 private class ClashFilter implements Predicate<Symbol> {
2896
2897 Type site;
2898
2899 ClashFilter(Type site) {
2900 this.site = site;
2901 }
2902
2903 boolean shouldSkip(Symbol s) {
2904 return (s.flags() & CLASH) != 0 &&
2905 s.owner == site.tsym;
2906 }
2907
2908 @Override
2909 public boolean test(Symbol s) {
2910 return s.kind == MTH &&
2911 (s.flags() & SYNTHETIC) == 0 &&
2912 !shouldSkip(s) &&
2913 s.isInheritedIn(site.tsym, types) &&
2914 !s.isInitOrVNew();
2915 }
2916 }
2917
2918 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2919 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2920 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2921 Assert.check(m.kind == MTH);
2922 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2923 if (prov.size() > 1) {
2924 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2925 ListBuffer<Symbol> defaults = new ListBuffer<>();
2926 for (MethodSymbol provSym : prov) {
2927 if ((provSym.flags() & DEFAULT) != 0) {
2928 defaults = defaults.append(provSym);
2929 } else if ((provSym.flags() & ABSTRACT) != 0) {
2930 abstracts = abstracts.append(provSym);
2931 }
2932 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2933 //strong semantics - issue an error if two sibling interfaces
2934 //have two override-equivalent defaults - or if one is abstract
2953 }
2954 }
2955 }
2956 }
2957 }
2958
2959 //where
2960 private class DefaultMethodClashFilter implements Predicate<Symbol> {
2961
2962 Type site;
2963
2964 DefaultMethodClashFilter(Type site) {
2965 this.site = site;
2966 }
2967
2968 @Override
2969 public boolean test(Symbol s) {
2970 return s.kind == MTH &&
2971 (s.flags() & DEFAULT) != 0 &&
2972 s.isInheritedIn(site.tsym, types) &&
2973 !s.isInitOrVNew();
2974 }
2975 }
2976
2977 /**
2978 * Report warnings for potentially ambiguous method declarations. Two declarations
2979 * are potentially ambiguous if they feature two unrelated functional interface
2980 * in same argument position (in which case, a call site passing an implicit
2981 * lambda would be ambiguous).
2982 */
2983 void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2984 MethodSymbol msym1, MethodSymbol msym2) {
2985 if (msym1 != msym2 &&
2986 lint.isEnabled(LintCategory.OVERLOADS) &&
2987 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2988 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2989 Type mt1 = types.memberType(site, msym1);
2990 Type mt2 = types.memberType(site, msym2);
2991 //if both generic methods, adjust type variables
2992 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2993 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
3656 Attribute app = arr.values[i];
3657 if (!(app instanceof Attribute.Enum attributeEnum)) {
3658 // recovery
3659 return Optional.empty();
3660 }
3661 targets[i] = attributeEnum.value.name;
3662 }
3663 }
3664 for (Name target : targets) {
3665 if (target == names.TYPE) {
3666 if (s.kind == TYP)
3667 applicableTargets.add(names.TYPE);
3668 } else if (target == names.FIELD) {
3669 if (s.kind == VAR && s.owner.kind != MTH)
3670 applicableTargets.add(names.FIELD);
3671 } else if (target == names.RECORD_COMPONENT) {
3672 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3673 applicableTargets.add(names.RECORD_COMPONENT);
3674 }
3675 } else if (target == names.METHOD) {
3676 if (s.kind == MTH && !s.isInitOrVNew())
3677 applicableTargets.add(names.METHOD);
3678 } else if (target == names.PARAMETER) {
3679 if (s.kind == VAR &&
3680 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3681 applicableTargets.add(names.PARAMETER);
3682 }
3683 } else if (target == names.CONSTRUCTOR) {
3684 if (s.kind == MTH && s.isInitOrVNew())
3685 applicableTargets.add(names.CONSTRUCTOR);
3686 } else if (target == names.LOCAL_VARIABLE) {
3687 if (s.kind == VAR && s.owner.kind == MTH &&
3688 (s.flags() & PARAMETER) == 0) {
3689 applicableTargets.add(names.LOCAL_VARIABLE);
3690 }
3691 } else if (target == names.ANNOTATION_TYPE) {
3692 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3693 applicableTargets.add(names.ANNOTATION_TYPE);
3694 }
3695 } else if (target == names.PACKAGE) {
3696 if (s.kind == PCK)
3697 applicableTargets.add(names.PACKAGE);
3698 } else if (target == names.TYPE_USE) {
3699 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3700 //cannot type annotate implicitly typed locals
3701 continue;
3702 } else if (s.kind == TYP || s.kind == VAR ||
3703 (s.kind == MTH && !s.isInitOrVNew() &&
3704 !s.type.getReturnType().hasTag(VOID)) ||
3705 (s.kind == MTH && s.isInitOrVNew())) {
3706 applicableTargets.add(names.TYPE_USE);
3707 }
3708 } else if (target == names.TYPE_PARAMETER) {
3709 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3710 applicableTargets.add(names.TYPE_PARAMETER);
3711 } else if (target == names.MODULE) {
3712 if (s.kind == MDL)
3713 applicableTargets.add(names.MODULE);
3714 } else
3715 return Optional.empty(); // Unknown ElementType. This should be an error at declaration site,
3716 // assume applicable.
3717 }
3718 return Optional.of(applicableTargets);
3719 }
3720
3721 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3722 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3723 if (atTarget == null) return null; // ok, is applicable
3724 Attribute atValue = atTarget.member(names.value);
3725 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
4983 });
4984 }
4985
4986 return null;
4987 }
4988
4989 boolean canBeSerialized(Type type) {
4990 return type.isPrimitive() || rs.isSerializable(type);
4991 }
4992
4993 /**
4994 * Check that Externalizable class needs a public no-arg
4995 * constructor.
4996 *
4997 * Check that a Serializable class has access to the no-arg
4998 * constructor of its first nonserializable superclass.
4999 */
5000 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5001 if (isExternalizable(c.type)) {
5002 for(var sym : c.getEnclosedElements()) {
5003 if (sym.isInitOrVNew() &&
5004 ((sym.flags() & PUBLIC) == PUBLIC)) {
5005 if (((MethodSymbol)sym).getParameters().isEmpty()) {
5006 return;
5007 }
5008 }
5009 }
5010 log.warning(LintCategory.SERIAL, tree.pos(),
5011 Warnings.ExternalizableMissingPublicNoArgCtor);
5012 } else {
5013 // Approximate access to the no-arg constructor up in
5014 // the superclass chain by checking that the
5015 // constructor is not private. This may not handle
5016 // some cross-package situations correctly.
5017 Type superClass = c.getSuperclass();
5018 // java.lang.Object is *not* Serializable so this loop
5019 // should terminate.
5020 while (rs.isSerializable(superClass) ) {
5021 try {
5022 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5023 } catch(ClassCastException cce) {
5024 return ; // Don't try to recover
5025 }
5026 }
5027 // Non-Serializable superclass
5028 try {
5029 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5030 for(var sym : supertype.getEnclosedElements()) {
5031 if (sym.isInitOrVNew()) {
5032 MethodSymbol ctor = (MethodSymbol)sym;
5033 if (ctor.getParameters().isEmpty()) {
5034 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5035 // Handle nested classes and implicit this$0
5036 (supertype.getNestingKind() == NestingKind.MEMBER &&
5037 ((supertype.flags() & STATIC) == 0)))
5038 log.warning(LintCategory.SERIAL, tree.pos(),
5039 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5040 }
5041 }
5042 }
5043 } catch (ClassCastException cce) {
5044 return ; // Don't try to recover
5045 }
5046 return;
5047 }
5048 }
5049
5050 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5051 // To be effective, serialVersionUID must be marked static
|