Skip to content

[BuilderTransform] AST Transform: Inject buildOptional to top-level… #60912

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
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
20 changes: 18 additions & 2 deletions lib/Sema/BuilderTransform.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1245,10 +1245,26 @@ class ResultBuilderTransform
auto *builderCall =
buildWrappedChainPayload(branchVarRef, i, numPayloads, isOptional);

auto isTopLevel = [&](Stmt *anchor) {
if (ifStmt->getThenStmt() == anchor)
return true;

// The situation is this:
//
// if <cond> {
// ...
// } else if <other-cond> {
// ...
// }
if (auto *innerIf = getAsStmt<IfStmt>(ifStmt->getElseStmt()))
return innerIf->getThenStmt() == anchor;

return ifStmt->getElseStmt() == anchor;
};

// The operand should have optional type if we had optional results,
// so we just need to call `buildIf` now, since we're at the top level.
if (isOptional && (ifStmt->getThenStmt() == anchor ||
ifStmt->getElseStmt() == anchor)) {
if (isOptional && isTopLevel(anchor)) {
builderCall = buildCallIfWanted(ifStmt->getEndLoc(),
builder.getBuildOptionalId(),
builderCall, /*argLabels=*/{});
Expand Down
36 changes: 36 additions & 0 deletions test/Constraints/result_builder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1216,3 +1216,39 @@ do {
}
// CHECK: (42, "", [true])
}

do {
@resultBuilder
struct MyBuilder {
static func buildBlock<T1: ExpressibleByStringLiteral>(_ t1: T1) -> (T1) {
return (t1)
}

static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}

static func buildOptional<T>(_ value: T?) -> T { return value! }

static func buildEither<T>(first value: T) -> T {
return value
}

static func buildEither<U>(second value: U) -> U {
return value
}
}

func test<T>(@MyBuilder _ builder: (Int) -> T) {
print(builder(42))
}

test {
if $0 < 0 {
"\($0)"
} else if $0 == 42 {
"the answer"
}
}
// CHECK: the answer
}