Skip to content

[CodeCompletion] Add keypath apply subscript after open bracket #31980

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
36 changes: 24 additions & 12 deletions lib/IDE/CodeCompletion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2762,23 +2762,32 @@ class CompletionLookup final : public swift::VisibleDeclConsumer {
const AnyFunctionType *AFT, const SubscriptDecl *SD,
const Optional<SemanticContextKind> SemanticContext = None) {
foundFunction(AFT);
auto genericSig =
SD->getInnermostDeclContext()->getGenericSignatureOfContext();
AFT = eraseArchetypes(const_cast<AnyFunctionType *>(AFT), genericSig)
->castTo<AnyFunctionType>();
if (SD) {
auto genericSig =
SD->getInnermostDeclContext()->getGenericSignatureOfContext();
AFT = eraseArchetypes(const_cast<AnyFunctionType *>(AFT), genericSig)
->castTo<AnyFunctionType>();
}

CommandWordsPairs Pairs;
CodeCompletionResultBuilder Builder(
Sink, CodeCompletionResult::ResultKind::Declaration,
Sink,
SD ? CodeCompletionResult::ResultKind::Declaration
: CodeCompletionResult::ResultKind::Pattern,
SemanticContext ? *SemanticContext : getSemanticContextKind(SD),
expectedTypeContext);
Builder.setAssociatedDecl(SD);
setClangDeclKeywords(SD, Pairs, Builder);
if (SD) {
Builder.setAssociatedDecl(SD);
setClangDeclKeywords(SD, Pairs, Builder);
}
if (!HaveLParen)
Builder.addLeftBracket();
else
Builder.addAnnotatedLeftBracket();
addCallArgumentPatterns(Builder, AFT, SD->getIndices());
ArrayRef<const ParamDecl *> declParams;
if (SD)
declParams = SD->getIndices()->getArray();
addCallArgumentPatterns(Builder, AFT->getParams(), declParams);
if (!HaveLParen)
Builder.addRightBracket();
else
Expand Down Expand Up @@ -6063,7 +6072,7 @@ void CodeCompletionCallbacksImpl::doneParsing() {
Lookup.getUnresolvedMemberCompletions(ContextInfo.getPossibleTypes());
break;
}
case CompletionKind::CallArg : {
case CompletionKind::CallArg: {
ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr);

bool shouldPerformGlobalCompletion = true;
Expand All @@ -6072,9 +6081,12 @@ void CodeCompletionCallbacksImpl::doneParsing() {
!ContextInfo.getPossibleCallees().empty()) {
Lookup.setHaveLParen(true);
for (auto &typeAndDecl : ContextInfo.getPossibleCallees()) {
if (auto SD = dyn_cast_or_null<SubscriptDecl>(typeAndDecl.Decl)) {
Lookup.addSubscriptCallPattern(typeAndDecl.Type, SD,
typeAndDecl.SemanticContext);
auto apply = ContextInfo.getAnalyzedExpr();
if (apply && isa<SubscriptExpr>(apply)) {
Lookup.addSubscriptCallPattern(
typeAndDecl.Type,
dyn_cast_or_null<SubscriptDecl>(typeAndDecl.Decl),
typeAndDecl.SemanticContext);
} else {
Lookup.addFunctionCallPattern(
typeAndDecl.Type,
Expand Down
23 changes: 20 additions & 3 deletions lib/IDE/ExprContextAnalysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,11 @@ class ExprParentFinder : public ASTWalker {
static void collectPossibleCalleesByQualifiedLookup(
DeclContext &DC, Type baseTy, DeclNameRef name,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
bool isOnMetaType = baseTy->is<AnyMetatypeType>();
auto baseInstanceTy = baseTy->getMetatypeInstanceType();
if (!baseInstanceTy->mayHaveMembers())
return;

bool isOnMetaType = baseTy->is<AnyMetatypeType>();

SmallVector<ValueDecl *, 2> decls;
if (!DC.lookupQualified(baseInstanceTy,
Expand Down Expand Up @@ -389,15 +392,29 @@ static void collectPossibleCalleesByQualifiedLookup(
baseTy = *baseTyOpt;
}
baseTy = baseTy->getWithoutSpecifierType();
if (!baseTy->getMetatypeInstanceType()->mayHaveMembers())
return;

// Use metatype for lookup 'super.init' if it's inside constructors.
if (isa<SuperRefExpr>(baseExpr) && isa<ConstructorDecl>(DC) &&
name == DeclNameRef::createConstructor())
baseTy = MetatypeType::get(baseTy);

collectPossibleCalleesByQualifiedLookup(DC, baseTy, name, candidates);

// Add virtual 'subscript<Value>(keyPath: KeyPath<Root, Value>) -> Value'.
if (name.getBaseName() == DeclBaseName::createSubscript() &&
(baseTy->getAnyNominal() || baseTy->is<ArchetypeType>() ||
baseTy->is<TupleType>())) {
auto &Ctx = DC.getASTContext();

auto *kpDecl = Ctx.getKeyPathDecl();
Type kpTy = kpDecl->mapTypeIntoContext(kpDecl->getDeclaredInterfaceType());
Type kpValueTy = kpTy->castTo<BoundGenericType>()->getGenericArgs()[1];
kpTy = BoundGenericType::get(kpDecl, Type(), {baseTy, kpValueTy});

Type fnTy = FunctionType::get(
{AnyFunctionType::Param(kpTy, Ctx.Id_keyPath)}, kpValueTy);
candidates.emplace_back(fnTy->castTo<AnyFunctionType>(), nullptr);
}
}

/// For the given \c callExpr, collect possible callee types and declarations.
Expand Down
25 changes: 19 additions & 6 deletions test/IDE/complete_subscript.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUPER_IN_STATICMETHOD | %FileCheck %s -check-prefix=SUPER_IN_STATICMETHOD

// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=LABELED_SUBSCRIPT | %FileCheck %s -check-prefix=LABELED_SUBSCRIPT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TUPLE | %FileCheck %s -check-prefix=TUPLE

struct MyStruct<T> {
static subscript(x: Int, static defValue: T) -> MyStruct<T> {
Expand Down Expand Up @@ -62,6 +63,7 @@ func test1() {
let _ = MyStruct<Int>()[#^INSTANCE_INT_BRACKET^#
// INSTANCE_INT_BRACKET: Begin completions
// INSTANCE_INT_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: Int#}[']'][#Int#];
// INSTANCE_INT_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<Int>, Value>#}[']'][#Value#];
// INSTANCE_INT_BRACKET: End completions
}
func test2<U>(value: MyStruct<U>) {
Expand All @@ -87,6 +89,7 @@ func test2<U>(value: MyStruct<U>) {
let _ = value[#^INSTANCE_ARCHETYPE_BRACKET^#
// INSTANCE_ARCHETYPE_BRACKET: Begin completions
// INSTANCE_ARCHETYPE_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: U#}[']'][#Int#];
// INSTANCE_ARCHETYPE_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<U>, Value>#}[']'][#Value#];
// INSTANCE_ARCHETYPE_BRACKET: End completions

let _ = MyStruct<U>[42, #^METATYPE_LABEL^#
Expand All @@ -110,14 +113,16 @@ class Derived: Base {

func testInstance() {
let _ = self[#^SELF_IN_INSTANCEMETHOD^#]
// SELF_IN_INSTANCEMETHOD: Begin completions, 2 items
// SELF_IN_INSTANCEMETHOD: Begin completions, 3 items
// SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#derivedInstance: Int#}[']'][#Int#];
// SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/Super: ['[']{#instance: Int#}[']'][#Int#];
// SELF_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Derived, Value>#}[']'][#Value#];
// SELF_IN_INSTANCEMETHOD: End completions

let _ = super[#^SUPER_IN_INSTANCEMETHOD^#]
// SUPER_IN_INSTANCEMETHOD: Begin completions, 1 items
// SUPER_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#instance: Int#}[']'][#Int#];
// SUPER_IN_INSTANCEMETHOD: Begin completions, 2 items
// SUPER_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#instance: Int#}[']'][#Int#];
// SUPER_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Base, Value>#}[']'][#Value#];
// SUPER_IN_INSTANCEMETHOD: End completions
}

Expand All @@ -130,7 +135,7 @@ class Derived: Base {

let _ = super[#^SUPER_IN_STATICMETHOD^#]
// SUPER_IN_STATICMETHOD: Begin completions, 1 items
// SUPER_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#static: Int#}[']'][#Int#];
// SUPER_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#static: Int#}[']'][#Int#];
// SUPER_IN_STATICMETHOD: End completions
}
}
Expand All @@ -140,7 +145,15 @@ struct MyStruct1<X: Comparable> {
}
func testSubscriptCallSig<T>(val: MyStruct1<T>) {
val[#^LABELED_SUBSCRIPT^#
// LABELED_SUBSCRIPT: Begin completions, 1 items
// LABELED_SUBSCRIPT: Decl[Subscript]/CurrNominal: ['[']{#idx1: Int#}, {#idx2: Comparable#}[']'][#Int!#];
// LABELED_SUBSCRIPT: Begin completions, 2 items
// LABELED_SUBSCRIPT-DAG: Decl[Subscript]/CurrNominal: ['[']{#idx1: Int#}, {#idx2: Comparable#}[']'][#Int!#];
// LABELED_SUBSCRIPT-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct1<T>, Value>#}[']'][#Value#];
// LABELED_SUBSCRIPT: End completions
}

func testSubcscriptTuple(val: (x: Int, String)) {
val[#^TUPLE^#]
// TUPLE: Begin completions, 1 items
// TUPLE-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<(x: Int, String), Value>#}[']'][#Value#];
// TUPLE: End completions
}