-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodel-service.ts
248 lines (229 loc) · 10.5 KB
/
model-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/********************************************************************************
* Copyright (c) 2023 CrossBreeze.
********************************************************************************/
import {
CloseModelArgs,
CrossReference,
CrossReferenceContext,
ModelSavedEvent,
ModelUpdatedEvent,
OpenModelArgs,
ReferenceableElement,
SaveModelArgs,
SystemInfo,
SystemInfoArgs,
SystemUpdatedEvent,
UpdateModelArgs
} from '@crossbreeze/protocol';
import { AstNode, Deferred, DocumentState, isAstNode } from 'langium';
import { Disposable, OptionalVersionedTextDocumentIdentifier, Range, TextDocumentEdit, TextEdit, uinteger } from 'vscode-languageserver';
import { URI, Utils as UriUtils } from 'vscode-uri';
import { CrossModelServices, CrossModelSharedServices } from '../language-server/cross-model-module.js';
import { PACKAGE_JSON } from '../language-server/cross-model-package-manager.js';
import { CrossModelRoot, isCrossModelRoot } from '../language-server/generated/ast.js';
import { findDocument } from '../language-server/util/ast-util.js';
import { AstCrossModelDocument } from './open-text-document-manager.js';
import { LANGUAGE_CLIENT_ID } from './openable-text-documents.js';
/**
* The model service serves as a facade to access and update semantic models from the language server as a non-LSP client.
* It provides a simple open-request-update-save/close lifecycle for documents and their semantic model.
*/
export class ModelService {
constructor(
protected shared: CrossModelSharedServices,
protected documentManager = shared.workspace.TextDocumentManager,
protected documents = shared.workspace.LangiumDocuments,
protected documentBuilder = shared.workspace.DocumentBuilder,
protected fileSystemProvider = shared.workspace.FileSystemProvider
) {
// sync updates with language client
this.documentBuilder.onBuildPhase(DocumentState.Validated, (allChangedDocuments, _token) => {
for (const changedDocument of allChangedDocuments) {
const sourceClientId = this.documentManager.getSourceClientId(changedDocument, allChangedDocuments);
if (sourceClientId === LANGUAGE_CLIENT_ID) {
continue;
}
const textDocument = changedDocument.textDocument;
if (this.documentManager.isOpenInLanguageClient(textDocument.uri)) {
// we only want to apply a text edit if the editor is already open
// because opening and updating at the same time might cause problems as the open call resets the document to filesystem
this.shared.lsp.Connection?.workspace.applyEdit({
label: 'Update Model',
documentChanges: [
// we use a null version to indicate that the version is known
// eslint-disable-next-line no-null/no-null
TextDocumentEdit.create(OptionalVersionedTextDocumentIdentifier.create(textDocument.uri, null), [
TextEdit.replace(Range.create(0, 0, uinteger.MAX_VALUE, uinteger.MAX_VALUE), textDocument.getText())
])
]
});
}
}
});
}
/**
* Opens the document with the given URI for modification.
*
* @param uri document URI
*/
async open(args: OpenModelArgs): Promise<Disposable> {
return this.documentManager.open(args);
}
isOpen(uri: string): boolean {
return this.documentManager.isOpen(uri);
}
/**
* Closes the document with the given URI for modification.
*
* @param uri document URI
*/
async close(args: CloseModelArgs): Promise<void> {
if (this.documentManager.isOnlyOpenInClient(args.uri, args.clientId)) {
// we need to restore the original state without any unsaved changes
await this.update({ ...args, model: await this.documentManager.readFile(args.uri) });
}
return this.documentManager.close(args);
}
/**
* Waits until the document with the given URI has reached the given state.
* @param state minimum state the document should have before returning
* @param uri document URI
*/
async ready(state = DocumentState.Validated, uri?: string): Promise<void> {
await this.documentBuilder.waitUntil(state, uri ? URI.parse(uri) : undefined);
}
/**
* Requests the semantic model stored in the document with the given URI.
* If the document was not already open for modification, it will be opened automatically.
*
* @param uri document URI
* @param state minimum state the document should have before returning
*/
async request(uri: string, state = DocumentState.Validated): Promise<AstCrossModelDocument | undefined> {
const documentUri = URI.parse(uri);
await this.documentBuilder.waitUntil(state, documentUri);
const document = await this.documents.getOrCreateDocument(documentUri);
const root = document.parseResult.value;
return isCrossModelRoot(root) ? { root, diagnostics: document.diagnostics ?? [], uri } : undefined;
}
/**
* Updates the semantic model stored in the document with the given model or textual representation of a model.
* Any previous content will be overridden.
* If the document was not already open for modification, it will be opened automatically.
*
* @param uri document URI
* @param model semantic model or textual representation of it
* @returns the stored semantic model
*/
async update(args: UpdateModelArgs<CrossModelRoot>): Promise<AstCrossModelDocument> {
await this.open(args);
const documentUri = URI.parse(args.uri);
const document = await this.documents.getOrCreateDocument(documentUri);
const root = document.parseResult.value;
if (!isAstNode(root)) {
throw new Error(`No AST node to update exists in '${args.uri}'`);
}
const textDocument = document.textDocument;
const text = typeof args.model === 'string' ? args.model : this.serialize(documentUri, args.model);
if (text === textDocument.getText()) {
return {
diagnostics: document.diagnostics ?? [],
root: document.parseResult.value as CrossModelRoot,
uri: args.uri
};
}
const newVersion = textDocument.version + 1;
const pendingUpdate = new Deferred<AstCrossModelDocument>();
const listener = this.documentBuilder.onBuildPhase(DocumentState.Validated, (allChangedDocuments, _token) => {
const updatedDocument = allChangedDocuments.find(
doc => doc.uri.toString() === documentUri.toString() && doc.textDocument.version === newVersion
);
if (updatedDocument) {
pendingUpdate.resolve({
diagnostics: updatedDocument.diagnostics ?? [],
root: updatedDocument.parseResult.value as CrossModelRoot,
uri: args.uri
});
listener.dispose();
}
});
const timeout = new Promise<AstCrossModelDocument>((_, reject) =>
setTimeout(() => {
listener.dispose();
reject('Update timed out.');
}, 5000)
);
this.documentManager.update(args.uri, newVersion, text, args.clientId);
return Promise.race([pendingUpdate.promise, timeout]);
}
onModelUpdated(uri: string, listener: (model: ModelUpdatedEvent<AstCrossModelDocument>) => void): Disposable {
return this.documentManager.onUpdate(uri, listener);
}
onModelSaved(uri: string, listener: (model: ModelSavedEvent<AstCrossModelDocument>) => void): Disposable {
return this.documentManager.onSave(uri, listener);
}
/**
* Overrides the document with the given URI with the given semantic model or text.
*
* @param uri document uri
* @param model semantic model or text
*/
async save(args: SaveModelArgs<CrossModelRoot>): Promise<void> {
// sync: implicit update of internal data structure to match file system (similar to workspace initialization)
const text = typeof args.model === 'string' ? args.model : this.serialize(URI.parse(args.uri), args.model);
if (this.documents.hasDocument(URI.parse(args.uri))) {
await this.update(args);
} else {
this.documents.createDocument(URI.parse(args.uri), text);
}
return this.documentManager.save(args.uri, text, args.clientId);
}
/**
* Serializes the given semantic model by using the serializer service for the corresponding language.
*
* @param uri document uri
* @param model semantic model
*/
protected serialize(uri: URI, model: AstNode): string {
const serializer = this.shared.ServiceRegistry.getServices(uri).serializer.Serializer;
return serializer.serialize(model);
}
getId(node: AstNode, uri = findDocument(node)?.uri): string | undefined {
if (uri) {
const services = this.shared.ServiceRegistry.getServices(uri) as CrossModelServices;
return services.references.IdProvider.getLocalId(node);
}
return undefined;
}
getGlobalId(node: AstNode, uri = findDocument(node)?.uri): string | undefined {
if (uri) {
const services = this.shared.ServiceRegistry.getServices(uri) as CrossModelServices;
return services.references.IdProvider.getGlobalId(node);
}
return undefined;
}
async findReferenceableElements(args: CrossReferenceContext): Promise<ReferenceableElement[]> {
return this.shared.ServiceRegistry.CrossModel.references.ScopeProvider.complete(args);
}
async resolveCrossReference(args: CrossReference): Promise<AstNode | undefined> {
return this.shared.ServiceRegistry.CrossModel.references.ScopeProvider.resolveCrossReference(args);
}
async getSystemInfos(): Promise<SystemInfo[]> {
return this.shared.workspace.PackageManager.getPackageInfos().map(info =>
this.shared.workspace.PackageManager.convertPackageInfoToSystemInfo(info)
);
}
async getSystemInfo(args: SystemInfoArgs): Promise<SystemInfo | undefined> {
const contextUri = URI.parse(args.contextUri);
const packageInfo =
this.shared.workspace.PackageManager.getPackageInfoByURI(contextUri) ??
this.shared.workspace.PackageManager.getPackageInfoByURI(UriUtils.joinPath(contextUri, PACKAGE_JSON));
if (!packageInfo) {
return undefined;
}
return this.shared.workspace.PackageManager.convertPackageInfoToSystemInfo(packageInfo);
}
onSystemUpdated(listener: (event: SystemUpdatedEvent) => void): Disposable {
return this.shared.workspace.PackageManager.onUpdate(listener);
}
}