Skip to content

[5.1][CSApply] Restructure the implicit AST when applying @dynamicCallable #26004

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

Closed
Closed
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
64 changes: 45 additions & 19 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,10 @@ namespace {
Expr *finishApply(ApplyExpr *apply, Type openedType,
ConstraintLocatorBuilder locator);

// Resolve @dynamicCallable applications.
Expr *finishApplyDynamicCallable(const Solution &solution, ApplyExpr *apply,
ConstraintLocatorBuilder locator);

private:
/// Simplify the given type by substituting all occurrences of
/// type variables for their fixed types.
Expand Down Expand Up @@ -2041,9 +2045,6 @@ namespace {
}

Expr *handleStringLiteralExpr(LiteralExpr *expr) {
if (cs.getType(expr) && !cs.getType(expr)->hasTypeVariable())
return expr;

auto stringLiteral = dyn_cast<StringLiteralExpr>(expr);
auto magicLiteral = dyn_cast<MagicIdentifierLiteralExpr>(expr);
assert(bool(stringLiteral) != bool(magicLiteral) &&
Expand Down Expand Up @@ -7004,10 +7005,10 @@ Expr *ExprRewriter::convertLiteralInPlace(Expr *literal,
}

// Resolve @dynamicCallable applications.
static Expr *finishApplyDynamicCallable(ConstraintSystem &cs,
const Solution &solution,
ApplyExpr *apply,
ConstraintLocatorBuilder locator) {
Expr *
ExprRewriter::finishApplyDynamicCallable(const Solution &solution,
ApplyExpr *apply,
ConstraintLocatorBuilder locator) {
auto &ctx = cs.getASTContext();
auto *fn = apply->getFn();

Expand All @@ -7019,12 +7020,14 @@ static Expr *finishApplyDynamicCallable(ConstraintSystem &cs,
auto loc = locator.withPathElement(ConstraintLocator::ApplyFunction);
auto selected = solution.getOverloadChoice(cs.getConstraintLocator(loc));
auto *method = dyn_cast<FuncDecl>(selected.choice.getDecl());
auto methodType = selected.openedType->castTo<AnyFunctionType>();
auto methodType = simplifyType(selected.openedType)->castTo<AnyFunctionType>();
assert(method->getName() == ctx.Id_dynamicallyCall &&
"Expected 'dynamicallyCall' method");
assert(methodType->getParams().size() == 1 &&
auto params = methodType->getParams();
assert(params.size() == 1 &&
"Expected 'dynamicallyCall' method with one parameter");
auto argumentLabel = methodType->getParams()[0].getLabel();
auto argumentType = params[0].getParameterType();
auto argumentLabel = params[0].getLabel();
assert((argumentLabel == ctx.Id_withArguments ||
argumentLabel == ctx.Id_withKeywordArguments) &&
"Expected 'dynamicallyCall' method argument label 'withArguments' or "
Expand All @@ -7034,39 +7037,62 @@ static Expr *finishApplyDynamicCallable(ConstraintSystem &cs,
// `withKeywordArguments` method.
bool useKwargsMethod = argumentLabel == ctx.Id_withKeywordArguments;

// Construct expression referencing the `dynamicallyCall` method.
Expr *member =
new (ctx) MemberRefExpr(fn, fn->getEndLoc(), ConcreteDeclRef(method),
DeclNameLoc(method->getNameLoc()),
/*Implicit*/ true);
// Construct expression referencing the `dynamicallyCall` method.
bool isDynamic =
selected.choice.getKind() == OverloadChoiceKind::DeclViaDynamic;
auto member = buildMemberRef(fn, selected.openedFullType,
SourceLoc(), selected.choice,
DeclNameLoc(method->getNameLoc()),
selected.openedType, loc, loc, /*implicit*/ true,
selected.choice.getFunctionRefKind(),
AccessSemantics::Ordinary, isDynamic);

// Construct argument to the method (either an array or dictionary
// expression).
Expr *argument = nullptr;
if (!useKwargsMethod) {
argument = ArrayExpr::create(ctx, SourceLoc(), arg->getElements(),
{}, SourceLoc());
cs.setType(argument, argumentType);
finishArrayExpr(cast<ArrayExpr>(argument));
} else {
auto dictLitProto =
ctx.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral);
auto conformance =
cs.TC.conformsToProtocol(argumentType, dictLitProto, cs.DC,
ConformanceCheckFlags::InExpression);
auto keyType = conformance->getTypeWitnessByName(argumentType, ctx.Id_Key);
auto valueType = conformance->getTypeWitnessByName(argumentType,
ctx.Id_Value);
SmallVector<Identifier, 4> names;
SmallVector<Expr *, 4> dictElements;
for (unsigned i = 0, n = arg->getNumElements(); i < n; i++) {
Expr *labelExpr =
new (ctx) StringLiteralExpr(arg->getElementName(i).get(),
arg->getElementNameLoc(i),
/*Implicit*/ true);
cs.setType(labelExpr, keyType);
handleStringLiteralExpr(cast<LiteralExpr>(labelExpr));

Expr *pair =
TupleExpr::createImplicit(ctx, { labelExpr, arg->getElement(i) }, {});
auto eltTypes = { TupleTypeElt(keyType), TupleTypeElt(valueType) };
cs.setType(pair, TupleType::get(eltTypes, ctx));
dictElements.push_back(pair);
}
argument = DictionaryExpr::create(ctx, SourceLoc(), dictElements, {},
SourceLoc());
cs.setType(argument, argumentType);
finishDictionaryExpr(cast<DictionaryExpr>(argument));
}
argument->setImplicit();

// Construct call to the `dynamicallyCall` method.
Expr *result = CallExpr::createImplicit(ctx, member, argument,
{ argumentLabel });
cs.TC.typeCheckExpression(result, cs.DC);
auto result = CallExpr::createImplicit(ctx, member, argument,
{ argumentLabel });
cs.setType(result->getArg(), AnyFunctionType::composeInput(ctx, params,
false));
cs.setType(result, methodType->getResult());
cs.cacheExprTypes(result);
return result;
}
Expand Down Expand Up @@ -7367,7 +7393,7 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType,

// Handle @dynamicCallable applications.
// At this point, all other ApplyExpr cases have been handled.
return finishApplyDynamicCallable(cs, solution, apply, locator);
return finishApplyDynamicCallable(solution, apply, locator);
}


Expand Down
46 changes: 46 additions & 0 deletions test/attr/attr_dynamic_callable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,49 @@ func testGenericType5<T>(a: CallableGeneric5<T>) -> Double {
func testArchetypeType5<T, C : CallableGeneric5<T>>(a: C) -> Double {
return a(1, 2, 3) + a(x1: 1, 2, x3: 3)
}

// SR-9239 Default argument in initializer

@dynamicCallable
struct A {
init(_ x: Int = 0) {}
func dynamicallyCall(withArguments args: [Int]) {}
}

func test9239() {
_ = A()() // ok
}

// SR-10313
//
// Modified version of the code snippet in the SR to not crash.

struct MissingKeyError: Error {}

@dynamicCallable
class DictionaryBox {
var dictionary: [String: Any] = [:]

func dynamicallyCall<T>(withArguments args: [String]) throws -> T {
guard let value = dictionary[args[0]] as? T else {
throw MissingKeyError()
}
return value
}
}

func test10313() {
let box = DictionaryBox()
box.dictionary["bool"] = false
let _: Bool = try! box("bool") // ok
}

// SR-10753

@dynamicCallable
struct B {
public func dynamicallyCall(withArguments arguments: [String]) {}
}

B()("hello") // ok
B()("\(1)") // ok