Skip to content

[CS] A couple of fixes for implicit callAsFunction #28519

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 5 commits into from
Dec 3, 2019
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
20 changes: 20 additions & 0 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -1910,6 +1910,26 @@ class CallerSideDefaultArgExprRequest
void cacheResult(Expr *expr) const;
};

/// Computes whether this is a type that supports being called through the
/// implementation of a \c callAsFunction method.
class IsCallableNominalTypeRequest
: public SimpleRequest<IsCallableNominalTypeRequest,
bool(CanType, DeclContext *), CacheKind::Cached> {
public:
using SimpleRequest::SimpleRequest;

private:
friend SimpleRequest;

// Evaluation.
llvm::Expected<bool> evaluate(Evaluator &evaluator, CanType ty,
DeclContext *dc) const;

public:
// Cached.
bool isCached() const { return true; }
};

// Allow AnyValue to compare two Type values, even though Type doesn't
// support ==.
template<>
Expand Down
2 changes: 2 additions & 0 deletions include/swift/AST/TypeCheckerTypeIDZone.def
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ SWIFT_REQUEST(TypeChecker, InterfaceTypeRequest,
Type(ValueDecl *), SeparatelyCached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, IsAccessorTransparentRequest, bool(AccessorDecl *),
SeparatelyCached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, IsCallableNominalTypeRequest,
bool(CanType, DeclContext *), Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, IsDynamicRequest, bool(ValueDecl *),
SeparatelyCached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, IsFinalRequest, bool(ValueDecl *), SeparatelyCached,
Expand Down
5 changes: 5 additions & 0 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,11 @@ class alignas(1 << TypeAlignInBits) TypeBase {
getAnyNominal());
}

/// Checks whether this is a type that supports being called through the
/// implementation of a \c callAsFunction method. Note that this does not
/// check access control.
bool isCallableNominalType(DeclContext *dc);

/// Retrieve the superclass of this type.
///
/// \param useArchetypes Whether to use context archetypes for outer generic
Expand Down
15 changes: 15 additions & 0 deletions lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,21 @@ bool TypeBase::satisfiesClassConstraint() {
return mayHaveSuperclass() || isObjCExistentialType();
}

bool TypeBase::isCallableNominalType(DeclContext *dc) {
// Don't allow callAsFunction to be used with dynamic lookup.
if (isAnyObject())
return false;

// If the type cannot have members, we're done.
if (!mayHaveMembers())
return false;

auto canTy = getCanonicalType();
auto &ctx = canTy->getASTContext();
return evaluateOrDefault(ctx.evaluator,
IsCallableNominalTypeRequest{canTy, dc}, false);
}

Type TypeBase::getSuperclass(bool useArchetypes) {
auto *nominalDecl = getAnyNominal();
auto *classDecl = dyn_cast_or_null<ClassDecl>(nominalDecl);
Expand Down
37 changes: 14 additions & 23 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6495,12 +6495,10 @@ static bool isValidDynamicCallableMethod(FuncDecl *method,
return true;
}

// Resolve `callAsFunction` method applications.
static Expr *finishApplyCallAsFunctionMethod(
// Build a reference to a `callAsFunction` method.
static Expr *buildCallAsFunctionMethodRef(
ExprRewriter &rewriter, ApplyExpr *apply, SelectedOverload selected,
AnyFunctionType *openedMethodType,
ConstraintLocatorBuilder applyFunctionLoc) {
auto &cs = rewriter.cs;
auto *fn = apply->getFn();
auto choice = selected.choice;
// Create direct reference to `callAsFunction` method.
Expand All @@ -6512,21 +6510,7 @@ static Expr *finishApplyCallAsFunctionMethod(
if (!declRef)
return nullptr;
declRef->setImplicit(apply->isImplicit());
apply->setFn(declRef);
// Coerce argument to input type of the `callAsFunction` method.
auto callee = rewriter.resolveConcreteDeclRef(choice.getDecl(),
applyFunctionLoc);
SmallVector<Identifier, 2> argLabelsScratch;
auto *arg = rewriter.coerceCallArguments(
apply->getArg(), openedMethodType, callee, apply,
apply->getArgumentLabels(argLabelsScratch), apply->hasTrailingClosure(),
applyFunctionLoc);
if (!arg)
return nullptr;
apply->setArg(arg);
cs.setType(apply, openedMethodType->getResult());
cs.cacheExprTypes(apply);
return apply;
return declRef;
}

// Resolve `@dynamicCallable` applications.
Expand Down Expand Up @@ -6768,12 +6752,19 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, ConcreteDeclRef callee,
auto methodType =
simplifyType(selected->openedType)->getAs<AnyFunctionType>();
if (method && methodType) {
if (method->isCallAsFunctionMethod())
return finishApplyCallAsFunctionMethod(
*this, apply, *selected, methodType, applyFunctionLoc);
if (methodType && isValidDynamicCallableMethod(method, methodType))
// Handle a call to a @dynamicCallable method.
if (isValidDynamicCallableMethod(method, methodType))
return finishApplyDynamicCallable(
apply, *selected, method, methodType, applyFunctionLoc);

// If this is an implicit call to a callAsFunction method, build the
// appropriate member reference.
if (method->isCallAsFunctionMethod()) {
fn = buildCallAsFunctionMethodRef(*this, apply, *selected,
applyFunctionLoc);
if (!fn)
return nullptr;
}
}
}

Expand Down
8 changes: 1 addition & 7 deletions lib/Sema/CSDiag.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2616,13 +2616,7 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) {
auto isDynamicCallable =
CS.DynamicCallableCache[fnType->getCanonicalType()].isValid();

// Note: Consider caching `hasCallAsFunctionMethods` in `NominalTypeDecl`.
auto *nominal = fnType->getAnyNominal();
auto hasCallAsFunctionMethods = nominal &&
llvm::any_of(nominal->getMembers(), [](Decl *member) {
auto funcDecl = dyn_cast<FuncDecl>(member);
return funcDecl && funcDecl->isCallAsFunctionMethod();
});
auto hasCallAsFunctionMethods = fnType->isCallableNominalType(CS.DC);

// Diagnose specific @dynamicCallable errors.
if (isDynamicCallable) {
Expand Down
10 changes: 3 additions & 7 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7334,20 +7334,16 @@ ConstraintSystem::simplifyApplicableFnConstraint(
// Handle applications of types with `callAsFunction` methods.
// Do this before stripping optional types below, when `shouldAttemptFixes()`
// is true.
auto hasCallAsFunctionMethods =
desugar2->mayHaveMembers() &&
llvm::any_of(lookupMember(desugar2, DeclName(ctx.Id_callAsFunction)),
[](LookupResultEntry entry) {
return isa<FuncDecl>(entry.getValueDecl());
});
if (hasCallAsFunctionMethods) {
if (desugar2->isCallableNominalType(DC)) {
auto memberLoc = getConstraintLocator(
outerLocator.withPathElement(ConstraintLocator::Member));
// Add a `callAsFunction` member constraint, binding the member type to a
// type variable.
auto memberTy = createTypeVariable(memberLoc, /*options=*/0);
// TODO: Revisit this if `static func callAsFunction` is to be supported.
// Static member constraint requires `FunctionRefKind::DoubleApply`.
// TODO: Use a custom locator element to identify this member constraint
// instead of just pointing to the function expr.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this, something that I mentioned in the original PR for this feature as would be useful.

addValueMemberConstraint(origLValueType2, DeclName(ctx.Id_callAsFunction),
memberTy, DC, FunctionRefKind::SingleApply,
/*outerAlternatives*/ {}, locator);
Expand Down
14 changes: 13 additions & 1 deletion lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -478,17 +478,29 @@ ConstraintSystem::getCalleeLocator(ConstraintLocator *locator,
if (lookThroughApply) {
if (auto *applyExpr = dyn_cast<ApplyExpr>(anchor)) {
auto *fnExpr = applyExpr->getFn();

// FIXME: We should probably assert that we don't get a type variable
// here to make sure we only retrieve callee locators for resolved calls,
// ensuring that callee locators don't change after binding a type.
// Unfortunately CSDiag currently calls into getCalleeLocator, so all bets
// are off. Once we remove that legacy diagnostic logic, we should be able
// to assert here.
auto fnTy = getFixedTypeRecursive(getType(fnExpr), /*wantRValue*/ true);

// For an apply of a metatype, we have a short-form constructor. Unlike
// other locators to callees, these are anchored on the apply expression
// rather than the function expr.
auto fnTy = getFixedTypeRecursive(getType(fnExpr), /*wantRValue*/ true);
if (fnTy->is<AnyMetatypeType>()) {
auto *fnLocator =
getConstraintLocator(applyExpr, ConstraintLocator::ApplyFunction);
return getConstraintLocator(fnLocator,
ConstraintLocator::ConstructorMember);
}

// Handle an apply of a nominal type which supports callAsFunction.
if (fnTy->isCallableNominalType(DC))
return getConstraintLocator(anchor, ConstraintLocator::ApplyFunction);

// Otherwise fall through and look for locators anchored on the function
// expr. For CallExprs, this can look through things like parens and
// optional chaining.
Expand Down
20 changes: 20 additions & 0 deletions lib/Sema/TypeCheckConstraints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckerDebugConsumer.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
#include "swift/Parse/Confusables.h"
#include "swift/Parse/Lexer.h"
Expand Down Expand Up @@ -4569,3 +4570,22 @@ ForcedCheckedCastExpr *swift::findForcedDowncast(ASTContext &ctx, Expr *expr) {

return nullptr;
}

llvm::Expected<bool>
IsCallableNominalTypeRequest::evaluate(Evaluator &evaluator, CanType ty,
DeclContext *dc) const {
auto options = defaultMemberLookupOptions;
options |= NameLookupFlags::IgnoreAccessControl;
if (isa<AbstractFunctionDecl>(dc))
options |= NameLookupFlags::KnownPrivate;

// Look for a callAsFunction method.
auto &ctx = ty->getASTContext();
auto results =
TypeChecker::lookupMember(dc, ty, ctx.Id_callAsFunction, options);
return llvm::any_of(results, [](LookupResultEntry entry) -> bool {
if (auto *fd = dyn_cast<FuncDecl>(entry.getValueDecl()))
return fd->isCallAsFunctionMethod();
return false;
});
}
10 changes: 10 additions & 0 deletions test/Constraints/dynamic_lookup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,13 @@ class HasMethodWithDefault {
func testAnyObjectWithDefault(_ x: AnyObject) {
x.hasDefaultParam()
}

// SR-11829: Don't perform dynamic lookup for callAsFunction.
class ClassWithObjcCallAsFunction {
@objc func callAsFunction() {}
}

func testCallAsFunctionAnyObject(_ x: AnyObject) {
x() // expected-error {{cannot call value of non-function type 'AnyObject'}}
x.callAsFunction() // Okay.
}
23 changes: 23 additions & 0 deletions test/SILGen/default_arguments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -408,3 +408,26 @@ func genericMagic<T : ExpressibleByStringLiteral>(x: T = #file) -> T {
}

let _: String = genericMagic()

// SR-11778
struct CallableWithDefault {
func callAsFunction(x: Int = 4) {}
func callAsFunction(y: Int, z: String = #function) {}
}

// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments23testCallableWithDefaultyyAA0deF0VF : $@convention(thin) (CallableWithDefault) -> ()
func testCallableWithDefault(_ x: CallableWithDefault) {
// CHECK: [[DEF_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1xySi_tFfA_ : $@convention(thin) () -> Int
// CHECK: [[DEF:%[0-9]+]] = apply [[DEF_FN]]() : $@convention(thin) () -> Int
// CHECK: [[CALL_AS_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1xySi_tF : $@convention(method) (Int, CallableWithDefault) -> ()
// CHECK: apply [[CALL_AS_FN]]([[DEF]], {{%[0-9]+}})
x()

// CHECK: [[RAW_I:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 5
// CHECK: [[I:%[0-9]+]] = apply {{%[0-9]+}}([[RAW_I]], {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[RAW_STR:%[0-9]+]] = string_literal utf8 "testCallableWithDefault(_:)"
// CHECK: [[STR:%[0-9]+]] = apply {{%[0-9]+}}([[RAW_STR]], {{%[0-9]+}}, {{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
// CHECK: [[CALL_AS_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1y1zySi_SStF : $@convention(method) (Int, @guaranteed String, CallableWithDefault) -> ()
// CHECK: apply [[CALL_AS_FN]]([[I]], [[STR]], {{%[0-9]+}})
x(y: 5)
}
16 changes: 16 additions & 0 deletions test/Sema/call_as_function_generic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,19 @@ let genericString = GenericType<[String]>(collection: ["Hello", "world", "!"])
_ = genericString("Hello")
let genericInt = GenericType<Set<Int>>(collection: [1, 2, 3])
_ = genericInt(initialValue: 1)

// SR-11386
class C<T> {}
protocol P1 {}
extension C where T : P1 { // expected-note {{where 'T' = 'Int'}}
func callAsFunction(t: T) {}
}

struct S0 : P1 {}

func testCallAsFunctionWithWhereClause(_ c1: C<Int>, _ c2: C<S0>, _ s0: S0) {
c1(42) // expected-error {{referencing instance method 'callAsFunction(t:)' on 'C' requires that 'Int' conform to 'P1'}}
// expected-error@-1 {{missing argument label 't:' in call}}

c2(t: s0) // Okay.
}
36 changes: 36 additions & 0 deletions test/Sema/call_as_function_simple.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,39 @@ func testIUO(a: SimpleCallable!, b: MultipleArgsCallable!, c: Extended!,
_ = try? h()
_ = try? h { throw DummyError() }
}

// SR-11778
struct DoubleANumber {
func callAsFunction(_ x: Int, completion: (Int) -> Void = { _ in }) {
completion(x + x)
}
}

func testDefaults(_ x: DoubleANumber) {
x(5)
x(5, completion: { _ in })
}

// SR-11881
struct IUOCallable {
static var callable: IUOCallable { IUOCallable() }
func callAsFunction(_ x: Int) -> IUOCallable! { nil }
}

func testIUOCallAsFunction(_ x: IUOCallable) {
let _: IUOCallable = x(5)
let _: IUOCallable? = x(5)
let _ = x(5)

let _: IUOCallable = .callable(5)
let _: IUOCallable? = .callable(5)
}

// Test access control.
struct PrivateCallable {
private func callAsFunction(_ x: Int) {} // expected-note {{'callAsFunction' declared here}}
}

func testAccessControl(_ x: PrivateCallable) {
x(5) // expected-error {{'callAsFunction' is inaccessible due to 'private' protection level}}
}