Skip to content

Commit f822361

Browse files
CodaFijrose-apple
authored andcommitted
Check value casts are to non-foreign types (#2754)
Per the discussion in SR-1612, we don’t have a robust mechanism for checking this and should warn about it. Signed-off-by: Robert Widmann <[email protected]>
1 parent 9c37b30 commit f822361

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -665,8 +665,12 @@ ERROR(init_not_instance_member,none,
665665
"a new object of the same dynamic type", ())
666666
ERROR(super_initializer_not_in_initializer,none,
667667
"'super.init' cannot be called outside of an initializer", ())
668+
668669
WARNING(isa_is_always_true,none, "'%0' test is always true",
669670
(StringRef))
671+
WARNING(isa_is_foreign_check,none,
672+
"'is' test is always true because %0 is a Core Foundation type",
673+
(Type))
670674
WARNING(conditional_downcast_coercion,none,
671675
"conditional cast from %0 to %1 always succeeds",
672676
(Type, Type))

lib/Sema/CSApply.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2857,12 +2857,20 @@ namespace {
28572857
tc.diagnose(expr->getLoc(), diag::isa_is_always_true, "is");
28582858
expr->setCastKind(castKind);
28592859
break;
2860+
case CheckedCastKind::ValueCast:
2861+
// Check the cast target is a non-foreign type
2862+
if (auto cls = toType->getAs<ClassType>()) {
2863+
if (cls->getDecl()->isForeign()) {
2864+
tc.diagnose(expr->getLoc(), diag::isa_is_foreign_check, toType);
2865+
}
2866+
}
2867+
expr->setCastKind(castKind);
2868+
break;
28602869
case CheckedCastKind::ArrayDowncast:
28612870
case CheckedCastKind::DictionaryDowncast:
28622871
case CheckedCastKind::DictionaryDowncastBridged:
28632872
case CheckedCastKind::SetDowncast:
28642873
case CheckedCastKind::SetDowncastBridged:
2865-
case CheckedCastKind::ValueCast:
28662874
case CheckedCastKind::BridgeFromObjectiveC:
28672875
// Valid checks.
28682876
expr->setCastKind(castKind);

test/Misc/misc_diagnostics.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,8 @@ func tuple_splat2(_ q : (a : Int, b : Int)) {
148148
tuple_splat2(1, b: 2) // expected-error {{extra argument 'b' in call}}
149149
}
150150

151+
// SR-1612: Type comparison of foreign types is always true.
152+
func is_foreign(a: AnyObject) -> Bool {
153+
return a is CGColor // expected-warning {{'is' test is always true because 'CGColor' is a Core Foundation type}}
154+
}
151155

0 commit comments

Comments
 (0)