@@ -12364,21 +12364,56 @@ ConstraintSystem::simplifyKeyPathConstraint(
12364
12364
kpDecl = getASTContext().getWritableKeyPathDecl();
12365
12365
}
12366
12366
12367
+ auto formUnsolved = [&]() {
12368
+ addUnsolvedConstraint(Constraint::create(
12369
+ *this, ConstraintKind::KeyPath, keyPathTy, rootTy, valueTy,
12370
+ locator.getBaseLocator(), componentTypeVars));
12371
+ };
12372
+
12367
12373
auto loc = locator.getBaseLocator();
12368
12374
if (definitelyFunctionType) {
12369
12375
increaseScore(SK_FunctionConversion, locator);
12370
12376
return SolutionKind::Solved;
12371
12377
} else if (!anyComponentsUnresolved ||
12372
12378
(definitelyKeyPathType && capability == ReadOnly)) {
12373
- auto resolvedKPTy =
12374
- BoundGenericType::get(kpDecl, nullptr, {rootTy, valueTy});
12375
- return matchTypes(resolvedKPTy, keyPathTy, ConstraintKind::Bind, subflags,
12376
- loc);
12379
+ // If key path is connected to a function application it cannot be
12380
+ // bound until the choice is selected because it's undetermined
12381
+ // until then whether key path is implicitly converted to a function
12382
+ // type or not.
12383
+ //
12384
+ // \code
12385
+ // struct Data {
12386
+ // var value: Int = 42
12387
+ // }
12388
+ //
12389
+ // func test<S: Sequence>(_: S, _: (S.Element) -> Int) {}
12390
+ // func test<C: Collection>(_: C, _: (C.Element) -> Int) {}
12391
+ //
12392
+ // func test(arr: [Data]) {
12393
+ // test(arr, \Data.value)
12394
+ // }
12395
+ // \endcode
12396
+ //
12397
+ // In this example if we did allow to bind the key path before
12398
+ // an overload of `test` is selected, we'd end up with no solutions
12399
+ // because the type of the key path expression is actually: '(Data) -> Int'
12400
+ // and not 'WritableKeyPath<Data, Int>`.
12401
+ auto *typeVar = keyPathTy->getAs<TypeVariableType>();
12402
+ if (typeVar && findConstraintThroughOptionals(
12403
+ typeVar, OptionalWrappingDirection::Unwrap,
12404
+ [&](Constraint *match, TypeVariableType *) {
12405
+ return match->getKind() ==
12406
+ ConstraintKind::ApplicableFunction;
12407
+ })) {
12408
+ formUnsolved();
12409
+ } else {
12410
+ auto resolvedKPTy =
12411
+ BoundGenericType::get(kpDecl, nullptr, {rootTy, valueTy});
12412
+ return matchTypes(resolvedKPTy, keyPathTy, ConstraintKind::Bind, subflags,
12413
+ loc);
12414
+ }
12377
12415
} else {
12378
- addUnsolvedConstraint(Constraint::create(*this, ConstraintKind::KeyPath,
12379
- keyPathTy, rootTy, valueTy,
12380
- locator.getBaseLocator(),
12381
- componentTypeVars));
12416
+ formUnsolved();
12382
12417
}
12383
12418
return SolutionKind::Solved;
12384
12419
}
0 commit comments