Skip to content

[CSSimplify] Propagate contextual result type into result builder tra… #64192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3532,11 +3532,29 @@ ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
}
}

auto resultMatchKind = subKind;
// Performance optimization: Propagate fully or partially resolved contextual
// type down into the body of result builder transformed closure by eagerly
// binding intermediate body result type to the contextual one. This helps to
// determine when closure body could be solved early.
//
// TODO: This could be extended to cover all multi-statement closures.
//
// See \c BindingSet::favoredOverConjunction for more details.
if (resultMatchKind >= ConstraintKind::Subtype &&
!func2->getResult()->isTypeVariableOrMember()) {
if (auto *closure = getAsExpr<ClosureExpr>(locator.trySimplifyToExpr())) {
if (!closure->hasExplicitResultType() &&
getAppliedResultBuilderTransform(closure)) {
resultMatchKind = ConstraintKind::Equal;
}
}
}

// Result type can be covariant (or equal).
return matchTypes(func1->getResult(), func2->getResult(), subKind,
subflags,
locator.withPathElement(
ConstraintLocator::FunctionResult));
return matchTypes(func1->getResult(), func2->getResult(), resultMatchKind,
subflags,
locator.withPathElement(ConstraintLocator::FunctionResult));
}

ConstraintSystem::TypeMatchResult
Expand Down
19 changes: 19 additions & 0 deletions test/Constraints/result_builder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1383,3 +1383,22 @@ testOptionalIfElseSequences()
// CHECK-NEXT: second(Optional(main.B()), nil)
// CHECK-NEXT: second(nil, Optional(main.Either<main.C, main.D>.first(main.C())))
// CHECK-NEXT: second(nil, Optional(main.Either<main.C, main.D>.second(main.D())))

// rdar://106364495 - ambiguous use of `buildFinalResult`
func testBuildFinalResultDependentOnContextualType() {
@resultBuilder
struct MyBuilder {
static func buildBlock(_ v: Int) -> Int { v }
static func buildFinalResult(_ v: Int) -> Int { v }
static func buildFinalResult(_ v: Int) -> String { "" }
}

func test(@MyBuilder _ fn: () -> Int?) { print(fn()) }

test {
42
}
}

testBuildFinalResultDependentOnContextualType()
// CHECK: Optional(42)