Skip to content

[Function builders] Add support for function builders on stored struct properties #34097

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
19 changes: 18 additions & 1 deletion lib/SILGen/SILGenConstructor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "SILGenFunctionBuilder.h"
#include "Scope.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
Expand Down Expand Up @@ -211,8 +212,24 @@ static void emitImplicitValueConstructor(SILGenFunction &SGF,
"number of args does not match number of fields");
(void)eltEnd;
FullExpr scope(SGF.Cleanups, field->getParentPatternBinding());

RValue arg = std::move(*elti);

// If the stored property has an attached function builder and its
// type is not a function type, the argument is a noescape closure
// that needs to be called.
if (field->getFunctionBuilderType()) {
if (!field->getValueInterfaceType()
->lookThroughAllOptionalTypes()->is<AnyFunctionType>()) {
auto resultTy = cast<FunctionType>(arg.getType()).getResult();
arg = SGF.emitMonomorphicApply(
Loc, std::move(arg).getAsSingleValue(SGF, Loc), { }, resultTy,
resultTy, ApplyOptions::None, None, None);
}
}

maybeEmitPropertyWrapperInitFromValue(SGF, Loc, field, subs,
std::move(*elti))
std::move(arg))
.forwardInto(SGF, Loc, init.get());
++elti;
} else {
Expand Down
22 changes: 22 additions & 0 deletions lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,20 @@ static ConstructorDecl *createImplicitConstructor(NominalTypeDecl *decl,
}
}

Type functionBuilderType= var->getFunctionBuilderType();
if (functionBuilderType) {
// If the variable's type is structurally a function type, use that
// type. Otherwise, form a non-escaping function type for the function
// parameter.
bool isStructuralFunctionType =
varInterfaceType->lookThroughAllOptionalTypes()
->is<AnyFunctionType>();
if (!isStructuralFunctionType) {
auto extInfo = ASTExtInfoBuilder().withNoEscape().build();
varInterfaceType = FunctionType::get({ }, varInterfaceType, extInfo);
}
}

// Create the parameter.
auto *arg = new (ctx)
ParamDecl(SourceLoc(), Loc,
Expand All @@ -273,6 +287,14 @@ static ConstructorDecl *createImplicitConstructor(NominalTypeDecl *decl,
// Don't allow the parameter to accept temporary pointer conversions.
arg->setNonEphemeralIfPossible();

// Attach a function builder attribute if needed.
if (functionBuilderType) {
auto typeExpr = TypeExpr::createImplicit(functionBuilderType, ctx);
auto attr = CustomAttr::create(
ctx, SourceLoc(), typeExpr, /*implicit=*/true);
arg->getAttrs().add(attr);
}

maybeAddMemberwiseDefaultArg(arg, var, params.size(), ctx);

params.push_back(arg);
Expand Down
13 changes: 12 additions & 1 deletion lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2987,8 +2987,19 @@ void AttributeChecker::visitCustomAttr(CustomAttr *attr) {
} else if (auto storage = dyn_cast<AbstractStorageDecl>(D)) {
decl = storage;

// Check whether this is a property without an explicit getter.
// Check whether this is a storage declaration that is not permitted
// to have a function builder attached.
auto shouldDiagnose = [&]() -> bool {
// An uninitialized stored property in a struct can have a function
// builder attached.
if (auto var = dyn_cast<VarDecl>(decl)) {
if (var->isInstanceMember() &&
isa<StructDecl>(var->getDeclContext()) &&
!var->getParentInitializer()) {
return false;
}
}

auto getter = storage->getParsedAccessor(AccessorKind::Get);
if (!getter)
return true;
Expand Down
21 changes: 21 additions & 0 deletions test/Constraints/function_builder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -767,3 +767,24 @@ do {
} catch {
fatalError("Threw something else?")
}

// CHECK: testStoredProperties
struct MyTupleStruct<T, U> {
@TupleBuilder let first: () -> T
@TupleBuilder let second: U
}

print("testStoredProperties")
let ts1 = MyTupleStruct {
1
"hello"
if true {
"conditional"
}
} second: {
3.14159
"blah"
}

// CHECK: MyTupleStruct<(Int, String, Optional<String>), (Double, String)>(first: (Function), second: (3.14159, "blah"))
print(ts1)
57 changes: 57 additions & 0 deletions test/SILGen/function_builder_memberwise.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// RUN: %target-swift-emit-silgen %s | %FileCheck %s

@_functionBuilder
struct TupleBuilder {
static func buildBlock<T1>(_ t1: T1) -> (T1) {
return (t1)
}

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

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

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

static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}

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

struct MyTupleStruct<T, U> {
@TupleBuilder let first: () -> T
@TupleBuilder let second: U
// CHECK: init(@TupleBuilder first: @escaping () -> T, @TupleBuilder second: () -> U)
}

// CHECK-LABEL: sil hidden [ossa] @$s27function_builder_memberwise13MyTupleStructV5first6secondACyxq_Gxyc_q_yXEtcfC : $@convention(method) <T, U> (@owned @callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <T>, @noescape @callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <U>, @thin MyTupleStruct<T, U>.Type) -> @out MyTupleStruct<T, U> {
// CHECK: bb0([[SELF:%.*]] : $*MyTupleStruct<T, U>, [[FIRST:%.*]] : @owned $@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <T>, [[SECOND:%.*]] : $@noescape @callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <U>, [[META:%.*]] : $@thin MyTupleStruct<T, U>.Type):
// CHECK-NEXT: [[FIRST_ADDR:%.*]] = struct_element_addr [[SELF]] : $*MyTupleStruct<T, U>, #MyTupleStruct.first
// CHECK-NEXT: store [[FIRST]] to [init] [[FIRST_ADDR]] : $*@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <T>
// CHECK-NEXT: [[SECOND_ADDR:%.*]] = struct_element_addr [[SELF]] : $*MyTupleStruct<T, U>, #MyTupleStruct.second
// CHECK-NEXT: [[CALL_RESULT:%.*]] = alloc_stack $U
// CHECK-NEXT: apply [[SECOND]]([[CALL_RESULT]]) : $@noescape @callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <U>
// CHECK-NEXT: copy_addr [take] [[CALL_RESULT]] to [initialization] [[SECOND_ADDR]] : $*U
func trigger(cond: Bool) {
_ = MyTupleStruct {
1
"hello"
if cond {
"conditional"
}
} second: {
3.14159
"blah"
}
}