Skip to content
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

Improve completion behavior for cross references #1004

Merged
merged 3 commits into from
Apr 20, 2023
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
51 changes: 44 additions & 7 deletions packages/langium/src/lsp/completion/completion-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,20 +123,41 @@ export class DefaultCompletionProvider implements CompletionProvider {
}
};

msujew marked this conversation as resolved.
Show resolved Hide resolved
const node = findLeafNodeAtOffset(cst, this.backtrackToAnyToken(text, offset));
const lastTokenOffset = this.backtrackToAnyToken(text, offset);

const astNode = findLeafNodeAtOffset(cst, lastTokenOffset)?.element;

const context: CompletionContext = {
document,
textDocument,
node: node?.element,
node: astNode,
offset,
position: params.position
};

if (!node) {
if (!astNode) {
const parserRule = getEntryRule(this.grammar)!;
await this.completionForRule(context, parserRule, acceptor);
return CompletionList.create(items, true);
return CompletionList.create(this.deduplicateItems(items), true);
}

const contexts: CompletionContext[] = [context];

// In some cases, the completion depends on the concrete AST node at the current position
// Often times, it is not clear whether the completion is related to the ast node at the current cursor position
// (i.e. associated with the character right after the cursor), or the one before the cursor.
// If these are different AST nodes, then we perform the completion twice
if (lastTokenOffset === offset && lastTokenOffset > 0) {
const previousAstNode = findLeafNodeAtOffset(cst, lastTokenOffset - 1)?.element;
if (previousAstNode !== astNode) {
contexts.push({
document,
textDocument,
node: previousAstNode,
offset,
position: params.position
});
}
}

const parserStart = this.backtrackToTokenStart(text, offset);
Expand All @@ -158,19 +179,29 @@ export class DefaultCompletionProvider implements CompletionProvider {
await Promise.all(
stream(beforeFeatures)
.distinct(distinctionFunction)
.map(e => this.completionFor(context, e, acceptor))
.map(e => this.completionForContexts(contexts, e, acceptor))
);

if (reparse) {
await Promise.all(
stream(afterFeatures)
.exclude(beforeFeatures, distinctionFunction)
.distinct(distinctionFunction)
.map(e => this.completionFor(context, e, acceptor))
.map(e => this.completionForContexts(contexts, e, acceptor))
);
}

return CompletionList.create(items, true);
return CompletionList.create(this.deduplicateItems(items), true);
msujew marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* The completion algorithm could yield the same reference/keyword multiple times.
*
* This methods deduplicates these items afterwards before returning to the client.
* Unique items are identified as a combination of `kind`, `label` and `detail`
*/
protected deduplicateItems(items: CompletionItem[]): CompletionItem[] {
return stream(items).distinct(item => `${item.kind}_${item.label}_${item.detail}`).toArray();
}

/**
Expand Down Expand Up @@ -242,6 +273,12 @@ export class DefaultCompletionProvider implements CompletionProvider {
}
}

protected async completionForContexts(contexts: CompletionContext[], next: NextFeature, acceptor: CompletionAcceptor): Promise<void> {
for (const context of contexts) {
await this.completionFor(context, next, acceptor);
}
}

protected completionFor(context: CompletionContext, next: NextFeature, acceptor: CompletionAcceptor): MaybePromise<void> {
if (ast.isKeyword(next.feature)) {
return this.completionForKeyword(context, next.feature, acceptor);
Expand Down
30 changes: 28 additions & 2 deletions packages/langium/test/lsp/completion-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe('Langium completion provider', () => {

describe('Completion within alternatives', () => {

it('Should show correct keywords in completion of entry rule', async () => {
test('Should show correct keywords in completion of entry rule', async () => {

const grammar = `
grammar g
Expand Down Expand Up @@ -106,7 +106,7 @@ describe('Completion within alternatives', () => {
});
});

it('Should show correct cross reference and keyword in completion', async () => {
test('Should show correct cross reference and keyword in completion', async () => {

const grammar = `
grammar g
Expand All @@ -127,4 +127,30 @@ describe('Completion within alternatives', () => {
expectedItems: ['A', 'self']
});
});

test('Should remove duplicated entries', async () => {
const grammar = `
grammar g
entry Model: (elements+=(Person | Greeting))*;
Person: 'person' name=ID;
// The following double 'person' assignment could lead to duplicated completion items
Greeting: 'hello' (person1=[Person:ID] 'x' | person2=[Person:ID] 'y');

terminal ID: /\\^?[_a-zA-Z][\\w_]*/;
hidden terminal WS: /\\s+/;
`;

const services = await createServicesForGrammar({ grammar });
const completion = expectCompletion(services);
const text = `
person A
hello <|>
`;

await completion({
text,
index: 0,
expectedItems: ['A']
});
});
});