Skip to content

[Property delegates] Implicit initialization for properties with delegates #24430

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
6 changes: 4 additions & 2 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -4332,10 +4332,12 @@ ERROR(property_delegate_ambiguous_value_property, none,
ERROR(property_delegate_wrong_initial_value_init, none,
"'init(initialValue:)' parameter type (%0) must be the same as its "
"'value' property type (%1) or an @autoclosure thereof", (Type, Type))
ERROR(property_delegate_failable_initial_value_init, none,
"'init(initialValue:)' cannot be failable", ())
ERROR(property_delegate_failable_init, none,
"%0 cannot be failable", (DeclName))
ERROR(property_delegate_ambiguous_initial_value_init, none,
"property delegate type %0 has multiple initial-value initializers", (Type))
ERROR(property_delegate_ambiguous_default_value_init, none,
"property delegate type %0 has multiple default-value initializers", (Type))
ERROR(property_delegate_type_requirement_not_accessible,none,
"%select{private|fileprivate|internal|public|open}0 %1 %2 cannot have "
"more restrictive access than its enclosing property delegate type %3 "
Expand Down
6 changes: 5 additions & 1 deletion include/swift/AST/PropertyDelegates.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,16 @@ struct PropertyDelegateTypeInfo {
VarDecl *valueVar = nullptr;

/// The initializer init(initialValue:) that will be called when the
/// initiqlizing the property delegate type from a value of the property type.
/// initializing the property delegate type from a value of the property type.
///
/// This initializer is optional, but if present will be used for the `=`
/// initialization syntax.
ConstructorDecl *initialValueInit = nullptr;

/// The initializer `init()` that will be called to default-initialize a
/// value with an attached property delegate.
ConstructorDecl *defaultInit = nullptr;

/// The property through which the delegate value ($foo) will be accessed,
/// hiding the underlying storage completely.
///
Expand Down
34 changes: 31 additions & 3 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1580,6 +1580,15 @@ bool PatternBindingDecl::isDefaultInitializable(unsigned i) const {
if (entry.isInitialized())
return true;

// If it has an attached property delegate that vends an `init()`, use that
// for default initialization.
if (auto singleVar = getSingleVar()) {
if (auto delegateInfo = singleVar->getAttachedPropertyDelegateTypeInfo()) {
if (delegateInfo.defaultInit)
return true;
}
}

if (entry.getPattern()->isNeverDefaultInitializable())
return false;

Expand Down Expand Up @@ -5325,7 +5334,9 @@ bool VarDecl::isMemberwiseInitialized(bool preferDeclaredProperties) const {
origVar = origDelegate;
if (origVar->getFormalAccess() < AccessLevel::Internal &&
origVar->getAttachedPropertyDelegate() &&
origVar->isParentInitialized())
(origVar->isParentInitialized() ||
(origVar->getParentPatternBinding() &&
origVar->getParentPatternBinding()->isDefaultInitializable())))
return false;

return true;
Expand Down Expand Up @@ -5736,8 +5747,25 @@ ParamDecl::getDefaultValueStringRepresentation(
return getASTContext().SourceMgr.extractText(charRange);
}

auto init = findOriginalPropertyDelegateInitialValue(
original, original->getParentInitializer());
// If there is no parent initializer, we used the default initializer.
auto parentInit = original->getParentInitializer();
if (!parentInit) {
if (auto type = original->getPropertyDelegateBackingPropertyType()) {
if (auto nominal = type->getAnyNominal()) {
scratch.clear();
auto typeName = nominal->getName().str();
scratch.append(typeName.begin(), typeName.end());
scratch.push_back('(');
scratch.push_back(')');
return {scratch.data(), scratch.size()};
}
}

return ".init()";
}

auto init =
findOriginalPropertyDelegateInitialValue(original, parentInit);
return extractInlinableText(getASTContext().SourceMgr, init, scratch);
}
}
Expand Down
53 changes: 36 additions & 17 deletions lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1520,6 +1520,23 @@ static VarDecl *synthesizePropertyDelegateStorageDelegateProperty(
return property;
}

static void typeCheckSynthesizedDelegateInitializer(
PatternBindingDecl *pbd, VarDecl *backingVar, PatternBindingDecl *parentPBD,
Expr *&initializer) {
DeclContext *dc = pbd->getDeclContext();
ASTContext &ctx = dc->getASTContext();

// Type-check the initialization.
auto &tc = *static_cast<TypeChecker *>(ctx.getLazyResolver());
tc.typeCheckExpression(initializer, dc);
if (auto initializerContext =
dyn_cast_or_null<Initializer>(
pbd->getPatternEntryForVarDecl(backingVar).getInitContext())) {
tc.contextualizeInitializer(initializerContext, initializer);
}
tc.checkPropertyDelegateErrorHandling(pbd, initializer);
}

llvm::Expected<PropertyDelegateBackingPropertyInfo>
PropertyDelegateBackingPropertyInfoRequest::evaluate(Evaluator &evaluator,
VarDecl *var) const {
Expand Down Expand Up @@ -1589,14 +1606,6 @@ PropertyDelegateBackingPropertyInfoRequest::evaluate(Evaluator &evaluator,

tc.typeCheckPatternBinding(parentPBD, patternNumber);
}

Expr *originalInitialValue = nullptr;
if (Expr *init = parentPBD->getInit(patternNumber)) {
pbd->setInit(0, init);
pbd->setInitializerChecked(0);
originalInitialValue = findOriginalPropertyDelegateInitialValue(var, init);
}

// Mark the backing property as 'final'. There's no sensible way to override.
if (dc->getSelfClassDecl())
makeFinal(ctx, backingVar);
Expand All @@ -1616,6 +1625,23 @@ PropertyDelegateBackingPropertyInfoRequest::evaluate(Evaluator &evaluator,
std::min(defaultAccess, var->getSetterFormalAccess());
backingVar->overwriteSetterAccess(setterAccess);

Expr *originalInitialValue = nullptr;
if (Expr *init = parentPBD->getInit(patternNumber)) {
pbd->setInit(0, init);
pbd->setInitializerChecked(0);
originalInitialValue = findOriginalPropertyDelegateInitialValue(var, init);
} else if (!parentPBD->isInitialized(patternNumber) &&
delegateInfo.defaultInit) {
// FIXME: Record this expression somewhere so that DI can perform the
// initialization itself.
auto typeExpr = TypeExpr::createImplicit(storageType, ctx);
Expr *initializer = CallExpr::createImplicit(ctx, typeExpr, {}, { });
typeCheckSynthesizedDelegateInitializer(pbd, backingVar, parentPBD,
initializer);
pbd->setInit(0, initializer);
pbd->setInitializerChecked(0);
}

// If there is a storage delegate property (delegateVar) in the delegate,
// synthesize a computed property for '$foo'.
VarDecl *storageVar = nullptr;
Expand All @@ -1640,16 +1666,9 @@ PropertyDelegateBackingPropertyInfoRequest::evaluate(Evaluator &evaluator,
Expr *initializer =
CallExpr::createImplicit(ctx, typeExpr, {origValue},
{ctx.Id_initialValue});
typeCheckSynthesizedDelegateInitializer(pbd, backingVar, parentPBD,
initializer);

// Type-check the initialization.
auto &tc = *static_cast<TypeChecker *>(ctx.getLazyResolver());
tc.typeCheckExpression(initializer, dc);
if (auto initializerContext =
dyn_cast_or_null<Initializer>(
pbd->getPatternEntryForVarDecl(backingVar).getInitContext())) {
tc.contextualizeInitializer(initializerContext, initializer);
}
tc.checkPropertyDelegateErrorHandling(parentPBD, initializer);
return PropertyDelegateBackingPropertyInfo(
backingVar, storageVar, originalInitialValue, initializer, origValue);
}
Expand Down
57 changes: 56 additions & 1 deletion lib/Sema/TypeCheckPropertyDelegate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,61 @@ static ConstructorDecl *findInitialValueInit(ASTContext &ctx,

// The initializer must not be failable.
if (init->getFailability() != OTK_None) {
init->diagnose(diag::property_delegate_failable_initial_value_init);
init->diagnose(diag::property_delegate_failable_init, initName);
return nullptr;
}

return init;
}

/// Determine whether we have a suitable init() within a property
/// delegate type.
static ConstructorDecl *findDefaultInit(ASTContext &ctx,
NominalTypeDecl *nominal) {
SmallVector<ConstructorDecl *, 2> defaultValueInitializers;
DeclName initName(ctx, DeclBaseName::createConstructor(),
ArrayRef<Identifier>());
SmallVector<ValueDecl *, 2> decls;
nominal->lookupQualified(nominal, initName, NL_QualifiedDefault, decls);
for (const auto &decl : decls) {
auto init = dyn_cast<ConstructorDecl>(decl);
if (!init || init->getDeclContext() != nominal)
continue;

defaultValueInitializers.push_back(init);
}

switch (defaultValueInitializers.size()) {
case 0:
return nullptr;

case 1:
break;

default:
// Diagnose ambiguous init() initializers.
nominal->diagnose(diag::property_delegate_ambiguous_default_value_init,
nominal->getDeclaredType());
for (auto init : defaultValueInitializers) {
init->diagnose(diag::kind_declname_declared_here,
init->getDescriptiveKind(), init->getFullName());
}
return nullptr;
}

// 'init()' must be as accessible as the nominal type.
auto init = defaultValueInitializers.front();
if (init->getFormalAccess() < nominal->getFormalAccess()) {
init->diagnose(diag::property_delegate_type_requirement_not_accessible,
init->getFormalAccess(), init->getDescriptiveKind(),
init->getFullName(), nominal->getDeclaredType(),
nominal->getFormalAccess());
return nullptr;
}

// The initializer must not be failable.
if (init->getFailability() != OTK_None) {
init->diagnose(diag::property_delegate_failable_init, initName);
return nullptr;
}

Expand All @@ -186,6 +240,7 @@ PropertyDelegateTypeInfoRequest::evaluate(
PropertyDelegateTypeInfo result;
result.valueVar = valueVar;
result.initialValueInit = findInitialValueInit(ctx, nominal, valueVar);
result.defaultInit = findDefaultInit(ctx, nominal);
result.delegateValueVar =
findValueProperty(ctx, nominal, ctx.Id_delegateValue, /*allowMissing=*/true);

Expand Down
25 changes: 21 additions & 4 deletions test/IDE/print_property_delegates.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,28 @@

@_propertyDelegate
struct Delegate<Value> {
var value: Value
var _stored: Value?

var value: Value {
get {
return _stored!
}

set {
_stored = newValue
}
}

init() {
self._stored = nil
}

init(initialValue: Value) {
self.value = initialValue
self._stored = initialValue
}

init(closure: () -> Value) {
self.value = closure()
self._stored = closure()
}
}

Expand All @@ -29,8 +43,11 @@ struct HasDelegates {
@Delegate
var y = true

@Delegate
var z: String

// Memberwise initializer.
// CHECK: init(x: Delegate<Int> = Delegate(closure: foo), y: Bool = true)
// CHECK: init(x: Delegate<Int> = Delegate(closure: foo), y: Bool = true, z: String = Delegate())
}

func trigger() {
Expand Down
43 changes: 42 additions & 1 deletion test/SILOptimizer/di-property-delegates.swift
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,50 @@ func testGenericClass() {
}
}

@_propertyDelegate
struct WrapperWithDefaultInit<Value> {
private var _value: Value? = nil

init() {
print("default init called on \(Value.self)")
}

var value: Value {
get {
return _value!
} set {
print("set value \(newValue)")
_value = newValue
}
}
}

struct UseWrapperWithDefaultInit {
@WrapperWithDefaultInit<Int>
var x: Int

@WrapperWithDefaultInit<String>
var y: String

init(y: String) {
self.y = y
}
}

func testDefaultInit() {
// CHECK: ## DefaultInit
print("\n## DefaultInit")

let use = UseWrapperWithDefaultInit(y: "hello")
// CHECK: default init called on Int

// FIXME: DI should eliminate the following call
// CHECK: default init called on String
// CHECK: set value hello
}

testIntStruct()
testIntClass()
testRefStruct()
testGenericClass()

testDefaultInit()