Skip to content

Commit 47c7b9b

Browse files
committed
[Diagnostics] Upon keypath result contextual mismatch try to match object types
If there was a mismatch between last component type and contextual key path result type, let's try to re-match the types with all optionals stripped off. In cases where the problem is optionality difference e.g. `[Int] vs. [Int]?` that propagates contextual information to the last component which facilitates better diagnostics. Resolves: rdar://problem/57843297
1 parent 9cbc761 commit 47c7b9b

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/Sema/CSSimplify.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2842,6 +2842,13 @@ bool ConstraintSystem::repairFailures(
28422842
if (fnType && fnType->getResult()->isEqual(rhs))
28432843
return true;
28442844

2845+
auto lastComponentType = lhs->lookThroughAllOptionalTypes();
2846+
auto keyPathResultType = rhs->lookThroughAllOptionalTypes();
2847+
2848+
// Propagate contextual information from/to keypath result type.
2849+
(void)matchTypes(lastComponentType, keyPathResultType, matchKind,
2850+
TMF_ApplyingFix, getConstraintLocator(locator));
2851+
28452852
conversionsOrFixes.push_back(IgnoreContextualType::create(
28462853
*this, lhs, rhs, getConstraintLocator(locator)));
28472854
return true;

test/Constraints/keypath.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,16 @@ func rdar56131416() {
102102
// This type should be selected correctly.
103103
Rdar56131416.takesCorrectType(result)
104104
}
105+
106+
func test_mismatch_with_contextual_optional_result() {
107+
struct A<T> {
108+
init<U: Collection>(_ data: T, keyPath: KeyPath<T, U?>) {}
109+
}
110+
111+
struct B {
112+
var arr: [Int] = []
113+
}
114+
115+
let _ = A(B(), keyPath: \.arr)
116+
// expected-error@-1 {{key path value type '[Int]' cannot be converted to contextual type '[Int]?'}}
117+
}

0 commit comments

Comments
 (0)