Skip to content

Commit 0c8ace9

Browse files
authored
[FixCode] Using coercion (as) instead of forced-coercion (as!) when the former is applicable. rdar://27683732 (#4008)
This fixit is migration-critical to help users call functions now take 'Any' or 'NSHashble' while used to take 'AnyObject'. We insert coercion to the original call sites.
1 parent 9654ebe commit 0c8ace9

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

lib/Sema/CSDiag.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3579,15 +3579,21 @@ static bool tryIntegerCastFixIts(InFlightDiagnostic &diag,
35793579
static bool
35803580
addTypeCoerceFixit(InFlightDiagnostic &diag, ConstraintSystem *CS,
35813581
Type fromType, Type toType, Expr *expr) {
3582-
if (CS->getTypeChecker().typeCheckCheckedCast(fromType, toType, CS->DC,
3583-
SourceLoc(), SourceRange(), SourceRange(), [](Type T) { return false; },
3584-
true) != CheckedCastKind::Unresolved) {
3582+
CheckedCastKind Kind =
3583+
CS->getTypeChecker().typeCheckCheckedCast(fromType, toType, CS->DC,
3584+
SourceLoc(), SourceRange(),
3585+
SourceRange(),
3586+
[](Type T) { return false; },
3587+
/*suppressDiagnostics*/ true);
3588+
if (Kind != CheckedCastKind::Unresolved) {
35853589
SmallString<32> buffer;
35863590
llvm::raw_svector_ostream OS(buffer);
35873591
toType->print(OS);
35883592
diag.fixItInsert(Lexer::getLocForEndOfToken(CS->DC->getASTContext().SourceMgr,
35893593
expr->getEndLoc()),
3590-
(llvm::Twine(" as! ") + OS.str()).str());
3594+
(llvm::Twine(Kind == CheckedCastKind::Coercion ? " as " :
3595+
" as! ") +
3596+
OS.str()).str());
35913597
return true;
35923598
}
35933599
return false;

test/Sema/diag_type_conversion.swift

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
// RUN: %target-parse-verify-swift
1+
// RUN: %target-parse-verify-swift %clang-importer-sdk
2+
3+
// REQUIRES: objc_interop
4+
5+
import Foundation
26

37
func foo1(_ a: [Int]) {}
48
func foo2(_ a : UnsafePointer<Int>) {}
@@ -34,3 +38,13 @@ func foo9(s : S1) {}
3438
func foo10(p : P1) {
3539
foo9(s : p) // expected-error {{cannot convert value of type 'P1' to expected argument type 'S1'}} {{13-13= as! S1}}
3640
}
41+
42+
func foo11(a : [AnyHashable]) {}
43+
func foo12(b : [NSObject]) {
44+
foo11(a : b) // expected-error {{cannot convert value of type '[NSObject]' to expected argument type '[AnyHashable]'}} {{14-14= as [AnyHashable]}}
45+
}
46+
47+
func foo13(a : [AnyHashable : Any]) {}
48+
func foo14(b : [NSObject : AnyObject]) {
49+
foo13(a : b ) // expected-error {{cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[AnyHashable : Any]'}} {{14-14= as [AnyHashable : Any]}}
50+
}

0 commit comments

Comments
 (0)