Skip to content

Sema: Fix local property wrappers on constructor [6.1] #78528

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 3 commits into from
Jan 11, 2025
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
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@

## Swift 6.1

* Projected value initializers are now correctly injected into calls when
an argument exactly matches a parameter with an external property wrapper.

For example:

```swift
struct Binding {
...
init(projectedValue: Self) { ... }
}

func checkValue(@Binding value: Int) {}

func use(v: Binding<Int>) {
checkValue($value: v)
// Transformed into: `checkValue(value: Binding(projectedValue: v))`
}
```

Previous versions of the Swift compiler incorrectly omitted projected value
initializer injection in the call to `checkValue` because the argument type
matched the parameter type exactly.

* [SE-0444][]:
When the upcoming feature `MemberImportVisibility` is enabled, Swift will
require that a module be directly imported in a source file when resolving
Expand Down
10 changes: 9 additions & 1 deletion include/swift/Sema/ConstraintSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,13 @@ class Solution {
/// A map from argument expressions to their applied property wrapper expressions.
llvm::DenseMap<ASTNode, SmallVector<AppliedPropertyWrapper, 2>> appliedPropertyWrappers;

ArrayRef<AppliedPropertyWrapper> getAppliedPropertyWrappers(ASTNode anchor) {
auto found = appliedPropertyWrappers.find(anchor);
if (found != appliedPropertyWrappers.end())
return found->second;
return ArrayRef<AppliedPropertyWrapper>();
}

/// A mapping from the constraint locators for references to various
/// names (e.g., member references, normal name references, possible
/// constructions) to the argument lists for the call to that locator.
Expand Down Expand Up @@ -5214,7 +5221,8 @@ class ConstraintSystem {
/// property wrapper type by applying the property wrapper.
TypeMatchResult applyPropertyWrapperToParameter(
Type wrapperType, Type paramType, ParamDecl *param, Identifier argLabel,
ConstraintKind matchKind, ConstraintLocatorBuilder locator);
ConstraintKind matchKind, ConstraintLocator *locator,
ConstraintLocator *calleeLocator);

/// Used by applyPropertyWrapperToParameter() to update appliedPropertyWrappers
/// and record a change in the trail.
Expand Down
28 changes: 20 additions & 8 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1189,8 +1189,8 @@ namespace {
calleeFnTy = calleeFnTy->getResult()->castTo<FunctionType>();
}

const auto &appliedPropertyWrappers =
solution.appliedPropertyWrappers[locator.getAnchor()];
auto appliedPropertyWrappers =
solution.getAppliedPropertyWrappers(locator.getAnchor());
const auto calleeDeclRef = resolveConcreteDeclRef(
dyn_cast<AbstractFunctionDecl>(declOrClosure), locator);

Expand Down Expand Up @@ -2332,8 +2332,8 @@ namespace {
->castTo<FunctionType>();
auto fullSubscriptTy = openedFullFnType->getResult()
->castTo<FunctionType>();
auto &appliedWrappers =
solution.appliedPropertyWrappers[memberLoc->getAnchor()];
auto appliedWrappers =
solution.getAppliedPropertyWrappers(memberLoc->getAnchor());
args = coerceCallArguments(
args, fullSubscriptTy, subscriptRef, nullptr,
locator.withPathElement(ConstraintLocator::ApplyArgument),
Expand Down Expand Up @@ -6297,9 +6297,17 @@ ArgumentList *ExprRewriter::coerceCallArguments(
// `sending` parameter etc.
applyFlagsToArgument(paramIdx, argExpr);

// If the types exactly match, this is easy.
auto canShortcutConversion = [&](Type argType, Type paramType) {
if (shouldInjectWrappedValuePlaceholder ||
paramInfo.hasExternalPropertyWrapper(paramIdx))
return false;

return argType->isEqual(paramType);
};

auto paramType = param.getOldType();
if (argType->isEqual(paramType) && !shouldInjectWrappedValuePlaceholder) {

if (canShortcutConversion(argType, paramType)) {
newArgs.push_back(arg);
continue;
}
Expand Down Expand Up @@ -6328,6 +6336,7 @@ ArgumentList *ExprRewriter::coerceCallArguments(
auto *paramDecl = getParameterAt(callee, paramIdx);
assert(paramDecl);

ASSERT(appliedWrapperIndex < appliedPropertyWrappers.size());
auto appliedWrapper = appliedPropertyWrappers[appliedWrapperIndex++];
auto wrapperType = solution.simplifyType(appliedWrapper.wrapperType);
auto initKind = appliedWrapper.initKind;
Expand Down Expand Up @@ -8230,7 +8239,8 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType,
// Resolve into a DynamicTypeExpr.
auto args = apply->getArgs();

auto &appliedWrappers = solution.appliedPropertyWrappers[calleeLocator.getAnchor()];
auto appliedWrappers = solution.getAppliedPropertyWrappers(
calleeLocator.getAnchor());
auto fnType = cs.getType(fn)->getAs<FunctionType>();
args = coerceCallArguments(
args, fnType, declRef, apply,
Expand Down Expand Up @@ -8426,7 +8436,9 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType,
// For function application, convert the argument to the input type of
// the function.
if (auto fnType = cs.getType(fn)->getAs<FunctionType>()) {
auto &appliedWrappers = solution.appliedPropertyWrappers[calleeLocator.getAnchor()];
auto appliedWrappers = solution.getAppliedPropertyWrappers(
calleeLocator.getAnchor());

args = coerceCallArguments(
args, fnType, callee, apply,
locator.withPathElement(ConstraintLocator::ApplyArgument),
Expand Down
8 changes: 3 additions & 5 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5057,11 +5057,9 @@ void ConstraintSystem::removePropertyWrapper(Expr *anchor) {
ConstraintSystem::TypeMatchResult
ConstraintSystem::applyPropertyWrapperToParameter(
Type wrapperType, Type paramType, ParamDecl *param, Identifier argLabel,
ConstraintKind matchKind, ConstraintLocatorBuilder locator) {
Expr *anchor = getAsExpr(locator.getAnchor());
if (auto *apply = dyn_cast<ApplyExpr>(anchor)) {
anchor = apply->getFn();
}
ConstraintKind matchKind, ConstraintLocator *locator,
ConstraintLocator *calleeLocator) {
Expr *anchor = getAsExpr(calleeLocator->getAnchor());

if (argLabel.hasDollarPrefix() && (!param || !param->hasExternalPropertyWrapper())) {
if (!shouldAttemptFixes())
Expand Down
5 changes: 4 additions & 1 deletion lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1820,7 +1820,9 @@ static ConstraintSystem::TypeMatchResult matchCallArguments(
assert(param);
if (cs.applyPropertyWrapperToParameter(paramTy, argTy,
const_cast<ParamDecl *>(param),
argLabel, subKind, loc)
argLabel, subKind,
cs.getConstraintLocator(loc),
calleeLocator)
.isFailure()) {
return cs.getTypeMatchFailure(loc);
}
Expand Down Expand Up @@ -11920,6 +11922,7 @@ bool ConstraintSystem::resolveClosure(TypeVariableType *typeVar,
auto result = applyPropertyWrapperToParameter(backingType, param.getParameterType(),
paramDecl, paramDecl->getName(),
ConstraintKind::Equal,
getConstraintLocator(closure),
getConstraintLocator(closure));
if (result.isFailure())
return false;
Expand Down
5 changes: 3 additions & 2 deletions lib/Sema/TypeOfReference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -741,14 +741,15 @@ unwrapPropertyWrapperParameterTypes(ConstraintSystem &cs, AbstractFunctionDecl *
continue;
}

auto *wrappedType = cs.createTypeVariable(cs.getConstraintLocator(locator), 0);
auto *loc = cs.getConstraintLocator(locator);
auto *wrappedType = cs.createTypeVariable(loc, 0);
auto paramType = paramTypes[i].getParameterType();
auto paramLabel = paramTypes[i].getLabel();
auto paramInternalLabel = paramTypes[i].getInternalLabel();
adjustedParamTypes.push_back(AnyFunctionType::Param(
wrappedType, paramLabel, ParameterTypeFlags(), paramInternalLabel));
cs.applyPropertyWrapperToParameter(paramType, wrappedType, paramDecl, argLabel,
ConstraintKind::Equal, locator);
ConstraintKind::Equal, loc, loc);
}

return FunctionType::get(adjustedParamTypes, functionType->getResult(),
Expand Down
42 changes: 42 additions & 0 deletions test/SILGen/property_wrapper_parameter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -537,3 +537,45 @@ func testCaptures(@ClassWrapper ref: Int, @Wrapper value: Int) {
// closure #2 in closure #2 in implicit closure #2 in testCaptures(ref:value:)
// CHECK-LABEL: sil private [ossa] @$s26property_wrapper_parameter12testCaptures3ref5valueySi_AA7WrapperVySiGtFyAA010ProjectionH0VySiGcfu0_yAJcfU1_AJycfU0_ : $@convention(thin) (ProjectionWrapper<Int>) -> ProjectionWrapper<Int>
}

do {
@propertyWrapper
struct Binding<Value> {
var wrappedValue: Value {
get { fatalError() }
nonmutating set { }
}

var projectedValue: Self { self }

init(projectedValue: Self) { self = projectedValue }
}

final class Value {
enum Kind {
}

var kind: Binding<Kind> {
fatalError()
}
}

struct Test {
var value: Value

// CHECK-LABEL: sil private [ossa] @$s26property_wrapper_parameter4TestL_V4test5otheryAA7BindingL_VyAA5ValueL_C4KindOG_tF : $@convention(method) (Binding<Value.Kind>, @guaranteed Test) -> ()
// CHECK: [[CHECK_PROJECTED_VALUE_INIT_1:%.*]] = function_ref @$s26property_wrapper_parameter4TestL_V9checkKind4kindyAA7BindingL_VyAA5ValueL_C0F0OG_tFAEL_AKvpfW
// CHECK-NEXT: {{.*}} = apply [[CHECK_PROJECTED_VALUE_INIT_1]]({{.*}}) : $@convention(thin) (Binding<Value.Kind>) -> Binding<Value.Kind>
// CHECK: [[CHECK_PROJECTED_VALUE_INIT_A:%.*]] = function_ref @$s26property_wrapper_parameter4TestL_V15doubleCheckKind1a1byAA7BindingL_VyAA5ValueL_C0G0OG_AMtFAEL_ALvpfW
// CHECK-NEXT: {{.*}} = apply [[CHECK_PROJECTED_VALUE_INIT_A]]({{.*}}) : $@convention(thin) (Binding<Value.Kind>) -> Binding<Value.Kind>
// CHECK: [[CHECK_PROJECTED_VALUE_INIT_B:%.*]] = function_ref @$s26property_wrapper_parameter4TestL_V15doubleCheckKind1a1byAA7BindingL_VyAA5ValueL_C0G0OG_AMtFAFL_ALvpfW
// CHECK-NEXT: {{.*}} = apply [[CHECK_PROJECTED_VALUE_INIT_B]]({{.*}}) : $@convention(thin) (Binding<Value.Kind>) -> Binding<Value.Kind>
func test(other: Binding<Value.Kind>) {
checkKind($kind: value.kind) // Ok
doubleCheckKind($a: value.kind, $b: other) // Ok
}

func checkKind(@Binding kind: Value.Kind) {}
func doubleCheckKind(@Binding a: Value.Kind, @Binding b: Value.Kind) {}
}
}
25 changes: 25 additions & 0 deletions test/Sema/property_wrapper_parameter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,28 @@ func takesWrapperClosure<T>(_: ProjectionWrapper<[S<T>]>, closure: (ProjectionWr
func testGenericPropertyWrapper<U>(@ProjectionWrapper wrappers: [S<U>]) {
takesWrapperClosure($wrappers) { $wrapper in }
}

@propertyWrapper
struct Binding<Value> {
var wrappedValue: Value

init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}

public var projectedValue: Binding<Value> {
return self
}

public init(projectedValue: Binding<Value>) {
self = projectedValue
}
}

struct Widget {
init(@ProjectionWrapper w: Int) {}
}

func buildWidget(_ w: ProjectionWrapper<Int>) -> Widget {
Widget($w: w)
}