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

fix: Add support of auto suggestion memory variable #1819

Merged
merged 15 commits into from
Jan 13, 2020
Merged
Show file tree
Hide file tree
Changes from 11 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
2 changes: 2 additions & 0 deletions Composer/packages/lib/indexers/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,5 @@ export interface LgFile {
}

export type FileResolver = (id: string) => FileInfo | undefined;

export type MemoryResolver = (id: string) => string[] | undefined;
4 changes: 2 additions & 2 deletions Composer/packages/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,13 @@ const wss: ws.Server = new ws.Server({
perMessageDeflate: false,
});

const { fileResolver } = BotProjectService;
const { fileResolver, staticMemoryResolver } = BotProjectService;

function launchLanguageServer(socket: rpc.IWebSocket) {
const reader = new rpc.WebSocketMessageReader(socket);
const writer = new rpc.WebSocketMessageWriter(socket);
const connection: IConnection = createConnection(reader, writer);
const server = new LGServer(connection, fileResolver);
const server = new LGServer(connection, fileResolver, staticMemoryResolver);
server.start();
}

Expand Down
5 changes: 5 additions & 0 deletions Composer/packages/server/src/services/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export class BotProjectService {
return BotProjectService.currentBotProject?.files.find(file => file.name === name);
}

public static staticMemoryResolver(name: string): string[] | undefined {
BotProjectService.initialize();
cosmicshuai marked this conversation as resolved.
Show resolved Hide resolved
return ['this.value', 'this.turnCount', 'turn.DialogEvent.value', 'intent.score'];
boydc2014 marked this conversation as resolved.
Show resolved Hide resolved
}

public static getCurrentBotProject(): BotProject | undefined {
BotProjectService.initialize();
return BotProjectService.currentBotProject;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from 'vscode-languageserver-types';
import { TextDocumentPositionParams } from 'vscode-languageserver-protocol';
import get from 'lodash/get';
import { lgIndexer, filterTemplateDiagnostics, isValid, FileResolver, FileInfo } from '@bfc/indexers';
import { lgIndexer, filterTemplateDiagnostics, isValid, FileResolver, FileInfo, MemoryResolver } from '@bfc/indexers';

import { buildInfunctionsMap } from './builtinFunctionsMap';
import {
Expand All @@ -29,6 +29,7 @@ import {
generageDiagnostic,
LGOption,
LGCursorState,
MemoryVaribleCompletionResult,
} from './utils';

const { check, indexOne } = lgIndexer;
Expand All @@ -43,8 +44,13 @@ export class LGServer {
protected readonly documents = new TextDocuments();
protected readonly pendingValidationRequests = new Map<string, number>();
protected LGDocuments: LGDocument[] = [];
private memoryVariables: Record<string, any> = {};

constructor(protected readonly connection: IConnection, protected readonly resolver?: FileResolver) {
constructor(
protected readonly connection: IConnection,
protected readonly resolver?: FileResolver,
protected readonly memoryResolver?: MemoryResolver
) {
this.documents.listen(this.connection);
this.documents.onDidChangeContent(change => this.validate(change.document));
this.documents.onDidClose(event => {
Expand All @@ -65,6 +71,7 @@ export class LGServer {
codeActionProvider: false,
completionProvider: {
resolveProvider: true,
triggerCharacters: ['.'],
},
hoverProvider: true,
foldingRangeProvider: false,
Expand All @@ -91,6 +98,36 @@ export class LGServer {
this.connection.listen();
}

protected updateObject(propertyList: string[]): void {
let tempVariable: Record<string, any> = this.memoryVariables;
for (const property of propertyList) {
if (property in tempVariable) {
tempVariable = tempVariable[property];
} else {
tempVariable[property] = {};
tempVariable = tempVariable[property];
}
}
}

protected updateMemoryVariables(uri: string): void {
if (!this.memoryResolver) {
return;
}

const memoryFileInfo: string[] | undefined = this.memoryResolver(uri);
if (!memoryFileInfo || memoryFileInfo.length === 0) {
return;
}

memoryFileInfo.forEach(variable => {
const propertyList = variable.split('.');
if (propertyList.length >= 1) {
this.updateObject(propertyList);
}
});
}

protected validateLgOption(document: TextDocument, lgOption?: LGOption) {
if (!lgOption) return;

Expand Down Expand Up @@ -281,6 +318,81 @@ export class LGServer {
return state.pop();
}

protected matchingCompletionProperty(propertyList: string[], ...objects: object[]): CompletionItem[] {
const completionList: CompletionItem[] = [];
for (const obj of objects) {
let tempVariable = obj;
for (const property of propertyList) {
if (property in obj) {
tempVariable = tempVariable[property];
} else {
tempVariable = {};
}
}

if (!tempVariable || Object.keys(tempVariable).length === 0) {
continue;
}

if (tempVariable instanceof Object) {
Object.keys(tempVariable).forEach(e => {
const item = {
label: e.toString(),
kind: CompletionItemKind.Property,
insertText: e.toString(),
documentation: '',
};
if (!completionList.includes(item)) {
completionList.push(item);
}
});
} else if (typeof tempVariable === 'string') {
const item = {
label: tempVariable,
kind: CompletionItemKind.Property,
insertText: tempVariable,
documentation: '',
};

if (!completionList.includes(item)) {
completionList.push(item);
}
}
}

return completionList;
}

protected findValidMemoryVariables(params: TextDocumentPositionParams): MemoryVaribleCompletionResult {
const document = this.documents.get(params.textDocument.uri);
if (!document) return { endWithDotFlag: false, completionList: [] };
const position = params.position;
const range = getRangeAtPosition(document, position);
const wordAtCurRange = document.getText(range);
const flag = wordAtCurRange.endsWith('.');

this.updateMemoryVariables(params.textDocument.uri);
const memoryVariblesRootCompletionList = Object.keys(this.memoryVariables).map(e => {
return {
label: e.toString(),
kind: CompletionItemKind.Property,
insertText: e.toString(),
documentation: '',
};
});

if (!wordAtCurRange || !flag) {
return { endWithDotFlag: flag, completionList: memoryVariblesRootCompletionList };
}

let propertyList = wordAtCurRange.split('.');
propertyList = propertyList.slice(0, propertyList.length - 1);

const completionList = this.matchingCompletionProperty(propertyList, this.memoryVariables);

return { endWithDotFlag: true, completionList: completionList };
}

protected completion(params: TextDocumentPositionParams): Thenable<CompletionList | null> {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
Expand Down Expand Up @@ -312,9 +424,21 @@ export class LGServer {
};
});

const completionPropertyResult = this.findValidMemoryVariables(params);

const matchedState = this.matchState(params);
if (matchedState === EXPRESSION) {
return Promise.resolve({ isIncomplete: true, items: completionTemplateList.concat(completionFunctionList) });
if (completionPropertyResult.endWithDotFlag) {
return Promise.resolve({
isIncomplete: true,
items: completionPropertyResult.completionList,
});
} else {
return Promise.resolve({
isIncomplete: true,
items: completionTemplateList.concat(completionFunctionList.concat(completionPropertyResult.completionList)),
});
}
} else {
return Promise.resolve(null);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { TextDocument, Range, Position, DiagnosticSeverity, Diagnostic } from 'vscode-languageserver-types';
import {
TextDocument,
Range,
Position,
DiagnosticSeverity,
Diagnostic,
CompletionItem,
} from 'vscode-languageserver-types';
import {
DiagnosticSeverity as LGDiagnosticSeverity,
ImportResolver,
Expand Down Expand Up @@ -125,3 +132,8 @@ export function checkTemplate(template: Template): LGDiagnostic[] {
return diagnostic.message.includes('does not have an evaluator') === false;
});
}

export type MemoryVaribleCompletionResult = {
endWithDotFlag: boolean;
cosmicshuai marked this conversation as resolved.
Show resolved Hide resolved
completionList: CompletionItem[];
};