Skip to content

Commit 97609dd

Browse files
Merge pull request #33623 from LucianoPAlmeida/SR-13442-key-path-unwrap-crash
[CSApply] Handle OptionalForce component when is initial component on key path expr
2 parents 79b0a7e + 7815ecf commit 97609dd

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/Sema/CSApply.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4732,9 +4732,21 @@ namespace {
47324732
KeyPathExpr::Component::forOptionalChain(objectTy, loc));
47334733
break;
47344734
}
4735-
case KeyPathExpr::Component::Kind::OptionalForce:
4736-
buildKeyPathOptionalForceComponent(resolvedComponents);
4735+
case KeyPathExpr::Component::Kind::OptionalForce: {
4736+
// Handle force optional when it is the first component e.g.
4737+
// \String?.!.count
4738+
if (resolvedComponents.empty()) {
4739+
auto loc = origComponent.getLoc();
4740+
auto objectTy = componentTy->getOptionalObjectType();
4741+
assert(objectTy);
4742+
4743+
resolvedComponents.push_back(
4744+
KeyPathExpr::Component::forOptionalForce(objectTy, loc));
4745+
} else {
4746+
buildKeyPathOptionalForceComponent(resolvedComponents);
4747+
}
47374748
break;
4749+
}
47384750
case KeyPathExpr::Component::Kind::Invalid: {
47394751
auto component = origComponent;
47404752
component.setComponentType(leafTy);

test/Constraints/keypath.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,11 @@ func key_path_root_mismatch<T>(_ base: KeyPathBase?, subBase: KeyPathBaseSubtype
179179
let _ : T = subBase[keyPath: kpa] // expected-error {{key path with root type 'AnotherBase' cannot be applied to a base of type 'KeyPathBaseSubtype?'}}
180180

181181
}
182+
183+
// SR-13442
184+
func SR13442<T>(_ x: KeyPath<String?, T>) -> T { "1"[keyPath: x] }
185+
186+
func testSR13442() {
187+
_ = SR13442(\.!.count) // OK
188+
_ = SR13442(\String?.!.count) // OK
189+
}

0 commit comments

Comments
 (0)