Skip to content

[SE-0258] Improve implementation of property wrapper composition #25457

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
112 changes: 73 additions & 39 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5489,12 +5489,13 @@ VarDecl *VarDecl::getPropertyWrapperBackingProperty() const {
return getPropertyWrapperBackingPropertyInfo().backingVar;
}

bool VarDecl::isPropertyWrapperInitializedWithInitialValue() const {
auto customAttrs = getAttachedPropertyWrappers();
static bool propertyWrapperInitializedViaInitialValue(
const VarDecl *var, bool checkDefaultInit) {
auto customAttrs = var->getAttachedPropertyWrappers();
if (customAttrs.empty())
return false;

auto *PBD = getParentPatternBinding();
auto *PBD = var->getParentPatternBinding();
if (!PBD)
return false;

Expand All @@ -5509,36 +5510,23 @@ bool VarDecl::isPropertyWrapperInitializedWithInitialValue() const {
return false;

// Default initialization does not use a value.
if (getAttachedPropertyWrapperTypeInfo(0).defaultInit)
if (checkDefaultInit &&
var->getAttachedPropertyWrapperTypeInfo(0).defaultInit)
return false;

// If all property wrappers have an initialValue initializer, the property
// wrapper will be initialized that way.
return allAttachedPropertyWrappersHaveInitialValueInit();
return var->allAttachedPropertyWrappersHaveInitialValueInit();
}

bool VarDecl::isPropertyMemberwiseInitializedWithWrappedType() const {
auto customAttrs = getAttachedPropertyWrappers();
if (customAttrs.empty())
return false;

auto *PBD = getParentPatternBinding();
if (!PBD)
return false;

// If there was an initializer on the original property, initialize
// via the initial value.
if (PBD->getPatternList()[0].getEqualLoc().isValid())
return true;

// If there was an initializer on the outermost wrapper, initialize
// via the full wrapper.
if (customAttrs[0]->getArg() != nullptr)
return false;
bool VarDecl::isPropertyWrapperInitializedWithInitialValue() const {
return propertyWrapperInitializedViaInitialValue(
this, /*checkDefaultInit=*/true);
}

// If all property wrappers have an initialValue initializer, the property
// wrapper will be initialized that way.
return allAttachedPropertyWrappersHaveInitialValueInit();
bool VarDecl::isPropertyMemberwiseInitializedWithWrappedType() const {
return propertyWrapperInitializedViaInitialValue(
this, /*checkDefaultInit=*/false);
}

Identifier VarDecl::getObjCPropertyName() const {
Expand Down Expand Up @@ -5806,25 +5794,71 @@ void ParamDecl::setDefaultArgumentInitContext(Initializer *initContext) {

Expr *swift::findOriginalPropertyWrapperInitialValue(VarDecl *var,
Expr *init) {
auto attr = var->getAttachedPropertyWrappers().front();
auto *PBD = var->getParentPatternBinding();
if (!PBD)
return nullptr;

// Direct initialization implies no original initial value.
if (attr->getArg())
// If there is no '=' on the pattern, there was no initial value.
if (PBD->getPatternList()[0].getEqualLoc().isInvalid())
return nullptr;

// Look through any expressions wrapping the initializer.
init = init->getSemanticsProvidingExpr();
auto initCall = dyn_cast<CallExpr>(init);
if (!initCall)
ASTContext &ctx = var->getASTContext();
auto dc = var->getInnermostDeclContext();
auto innermostAttr = var->getAttachedPropertyWrappers().back();
auto innermostNominal = evaluateOrDefault(
ctx.evaluator, CustomAttrNominalRequest{innermostAttr, dc}, nullptr);
if (!innermostNominal)
return nullptr;

auto initArg = cast<TupleExpr>(initCall->getArg())->getElement(0);
initArg = initArg->getSemanticsProvidingExpr();
if (auto autoclosure = dyn_cast<AutoClosureExpr>(initArg)) {
initArg =
autoclosure->getSingleExpressionBody()->getSemanticsProvidingExpr();
}
// Walker
class Walker : public ASTWalker {
public:
NominalTypeDecl *innermostNominal;
Expr *initArg = nullptr;

Walker(NominalTypeDecl *innermostNominal)
: innermostNominal(innermostNominal) { }

virtual std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (initArg)
return { false, E };

if (auto call = dyn_cast<CallExpr>(E)) {
// We're looking for an implicit call.
if (!call->isImplicit())
return { true, E };

// ... producing a value of the same nominal type as the innermost
// property wrapper.
if (call->getType()->getAnyNominal() != innermostNominal)
return { true, E };

// Find the implicit initialValue argument.
if (auto tuple = dyn_cast<TupleExpr>(call->getArg())) {
ASTContext &ctx = innermostNominal->getASTContext();
for (unsigned i : range(tuple->getNumElements())) {
if (tuple->getElementName(i) == ctx.Id_initialValue &&
tuple->getElementNameLoc(i).isInvalid()) {
initArg = tuple->getElement(i);
return { false, E };
}
}
}
}

return { true, E };
}
} walker(innermostNominal);
init->walk(walker);

Expr *initArg = walker.initArg;
if (initArg) {
initArg = initArg->getSemanticsProvidingExpr();
if (auto autoclosure = dyn_cast<AutoClosureExpr>(initArg)) {
initArg =
autoclosure->getSingleExpressionBody()->getSemanticsProvidingExpr();
}
}
return initArg;
}

Expand Down
6 changes: 3 additions & 3 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4662,7 +4662,8 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyMemberConstraint(

// If the base type is optional because we haven't chosen to force an
// implicit optional, don't try to fix it. The IUO will be forced instead.
if (auto dotExpr = dyn_cast<UnresolvedDotExpr>(locator->getAnchor())) {
if (auto dotExpr =
dyn_cast_or_null<UnresolvedDotExpr>(locator->getAnchor())) {
auto baseExpr = dotExpr->getBase();
auto resolvedOverload = getResolvedOverloadSets();
while (resolvedOverload) {
Expand All @@ -4682,8 +4683,7 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyMemberConstraint(
auto innerTV = createTypeVariable(locator,
TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
Type optTy = getTypeChecker().getOptionalType(
locator->getAnchor()->getSourceRange().Start, innerTV);
Type optTy = getTypeChecker().getOptionalType(SourceLoc(), innerTV);
SmallVector<Constraint *, 2> optionalities;
auto nonoptionalResult = Constraint::createFixed(
*this, ConstraintKind::Bind,
Expand Down
54 changes: 54 additions & 0 deletions test/SILGen/property_wrappers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,60 @@ class UseWrapperWithDefaultInit {
// CHECK: function_ref @$s17property_wrappers22WrapperWithDefaultInitVACyxGycfC
// CHECK: return {{%.*}} : $WrapperWithDefaultInit<String>

// Property wrapper composition.
@propertyWrapper
struct WrapperA<Value> {
var value: Value

init(initialValue: Value) {
value = initialValue
}
}

@propertyWrapper
struct WrapperB<Value> {
var value: Value

init(initialValue: Value) {
value = initialValue
}
}

@propertyWrapper
struct WrapperC<Value> {
var value: Value?

init(initialValue: Value?) {
value = initialValue
}
}

struct CompositionMembers {
// CompositionMembers.p1.getter
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p1SiSgvg : $@convention(method) (@guaranteed CompositionMembers) -> Optional<Int>
// CHECK: bb0([[SELF:%.*]] : @guaranteed $CompositionMembers):
// CHECK: [[P1:%.*]] = struct_extract [[SELF]] : $CompositionMembers, #CompositionMembers.$p1
// CHECK: [[P1_VALUE:%.*]] = struct_extract [[P1]] : $WrapperA<WrapperB<WrapperC<Int>>>, #WrapperA.value
// CHECK: [[P1_VALUE2:%.*]] = struct_extract [[P1_VALUE]] : $WrapperB<WrapperC<Int>>, #WrapperB.value
// CHECK: [[P1_VALUE3:%.*]] = struct_extract [[P1_VALUE2]] : $WrapperC<Int>, #WrapperC.value
// CHECK: return [[P1_VALUE3]] : $Optional<Int>
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"

// variable initialization expression of CompositionMembers.$p2
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers18CompositionMembersV3$p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi : $@convention(thin) () -> @owned Optional<String> {
// CHECK: %0 = string_literal utf8 "Hello"

// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p12p2ACSiSg_SSSgtcfC : $@convention(method) (Optional<Int>, @owned Optional<String>, @thin CompositionMembers.Type) -> @owned CompositionMembers
// CHECK: function_ref @$s17property_wrappers8WrapperCV12initialValueACyxGxSg_tcfC
// CHECK: function_ref @$s17property_wrappers8WrapperBV12initialValueACyxGx_tcfC
// CHECK: function_ref @$s17property_wrappers8WrapperAV12initialValueACyxGx_tcfC
}

func testComposition() {
_ = CompositionMembers(p1: nil)
}


// CHECK-LABEL: sil_vtable ClassUsingWrapper {
// CHECK-NEXT: #ClassUsingWrapper.x!getter.1: (ClassUsingWrapper) -> () -> Int : @$s17property_wrappers17ClassUsingWrapperC1xSivg // ClassUsingWrapper.x.getter
Expand Down
15 changes: 15 additions & 0 deletions test/decl/var/property_wrappers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -799,15 +799,30 @@ struct WrapperC<Value> {
}
}

@propertyWrapper
struct WrapperD<Value, X, Y> { // expected-note{{property wrapper type 'WrapperD' declared here}}
var value: Value
}

@propertyWrapper
struct WrapperE<Value> {
var value: Value
}

struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{property type 'Int' does not match that of the 'value' property of its wrapper type 'WrapperD<WrapperC, Int, String>'}}

func triggerErrors(d: Double) {
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}

$p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
$p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
$p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
}
}