-
Notifications
You must be signed in to change notification settings - Fork 65
/
semantic-token-provider.ts
465 lines (426 loc) · 17.1 KB
/
semantic-token-provider.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/******************************************************************************
* Copyright 2022 TypeFox GmbH
* This program and the accompanying materials are made available under the
* terms of the MIT License, which is available in the project root.
******************************************************************************/
/* eslint-disable no-bitwise */
import type { Range, SemanticTokens, SemanticTokensClientCapabilities, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensOptions, SemanticTokensParams, SemanticTokensRangeParams } from 'vscode-languageserver';
import { SemanticTokensBuilder as BaseSemanticTokensBuilder, SemanticTokenModifiers, SemanticTokenTypes } from 'vscode-languageserver';
import { CancellationToken } from '../utils/cancellation.js';
import type { AstNode, CstNode, Properties } from '../syntax-tree.js';
import { streamAst } from '../utils/ast-utils.js';
import { inRange } from '../utils/cst-utils.js';
import { findNodeForKeyword, findNodeForProperty, findNodesForKeyword, findNodesForProperty } from '../utils/grammar-utils.js';
import type { MaybePromise } from '../utils/promise-utils.js';
import { interruptAndCheck } from '../utils/promise-utils.js';
import type { LangiumDocument } from '../workspace/documents.js';
import type { LangiumServices } from './lsp-services.js';
export const AllSemanticTokenTypes: Record<string, number> = {
[SemanticTokenTypes.class]: 0,
[SemanticTokenTypes.comment]: 1,
[SemanticTokenTypes.enum]: 2,
[SemanticTokenTypes.enumMember]: 3,
[SemanticTokenTypes.event]: 4,
[SemanticTokenTypes.function]: 5,
[SemanticTokenTypes.interface]: 6,
[SemanticTokenTypes.keyword]: 7,
[SemanticTokenTypes.macro]: 8,
[SemanticTokenTypes.method]: 9,
[SemanticTokenTypes.modifier]: 10,
[SemanticTokenTypes.namespace]: 11,
[SemanticTokenTypes.number]: 12,
[SemanticTokenTypes.operator]: 13,
[SemanticTokenTypes.parameter]: 14,
[SemanticTokenTypes.property]: 15,
[SemanticTokenTypes.regexp]: 16,
[SemanticTokenTypes.string]: 17,
[SemanticTokenTypes.struct]: 18,
[SemanticTokenTypes.type]: 19,
[SemanticTokenTypes.typeParameter]: 20,
[SemanticTokenTypes.variable]: 21,
[SemanticTokenTypes.decorator]: 22
};
export const AllSemanticTokenModifiers: Record<string, number> = {
[SemanticTokenModifiers.abstract]: 1 << 0,
[SemanticTokenModifiers.async]: 1 << 1,
[SemanticTokenModifiers.declaration]: 1 << 2,
[SemanticTokenModifiers.defaultLibrary]: 1 << 3,
[SemanticTokenModifiers.definition]: 1 << 4,
[SemanticTokenModifiers.deprecated]: 1 << 5,
[SemanticTokenModifiers.documentation]: 1 << 6,
[SemanticTokenModifiers.modification]: 1 << 7,
[SemanticTokenModifiers.readonly]: 1 << 8,
[SemanticTokenModifiers.static]: 1 << 9
};
export const DefaultSemanticTokenOptions: SemanticTokensOptions = {
legend: {
tokenTypes: Object.keys(AllSemanticTokenTypes),
tokenModifiers: Object.keys(AllSemanticTokenModifiers)
},
full: {
delta: true
},
range: true
};
export interface SemanticTokenProvider {
semanticHighlight(document: LangiumDocument, params: SemanticTokensParams, cancelToken?: CancellationToken): MaybePromise<SemanticTokens>
semanticHighlightRange(document: LangiumDocument, params: SemanticTokensRangeParams, cancelToken?: CancellationToken): MaybePromise<SemanticTokens>
semanticHighlightDelta(document: LangiumDocument, params: SemanticTokensDeltaParams, cancelToken?: CancellationToken): MaybePromise<SemanticTokens | SemanticTokensDelta>
}
export interface SemanticToken {
line: number
char: number
length: number
tokenType: number
tokenModifiers: number
}
export type SemanticTokenAcceptorOptions<N extends AstNode = AstNode> = ({
line: number;
char: number;
length: number;
} | {
node: N;
property: Properties<N>;
index?: number;
} | {
node: N;
keyword: string;
index?: number;
} | {
cst: CstNode;
} | {
range: Range;
}) & {
type: string;
modifier?: string | string[];
}
export interface SemanticTokenPropertyOptions<T extends AstNode> {
node: T;
property: Properties<T>;
index?: number;
type: string;
modifier?: string | string[];
}
export interface SemanticTokenKeywordOptions {
node: AstNode;
keyword: string;
index?: number;
type: string;
modifier?: string | string[];
}
export interface SemanticTokenNodeOptions {
node: CstNode;
type: string;
modifier?: string | string[];
}
export interface SemanticTokenRangeOptions {
range: Range
type: string
modifier?: string | string[]
}
export class SemanticTokensBuilder extends BaseSemanticTokensBuilder {
private _tokens: SemanticToken[] = [];
override push(line: number, char: number, length: number, tokenType: number, tokenModifiers: number): void {
this._tokens.push({
line,
char,
length,
tokenType,
tokenModifiers
});
}
override build(): SemanticTokens {
this.applyTokens();
return super.build();
}
override buildEdits(): SemanticTokens | SemanticTokensDelta {
this.applyTokens();
return super.buildEdits();
}
/**
* Flushes the cached delta token values
*/
flush(): void {
this.previousResult(this.id);
}
private applyTokens(): void {
for (const token of this._tokens.sort(this.compareTokens)) {
super.push(token.line, token.char, token.length, token.tokenType, token.tokenModifiers);
}
this._tokens = [];
}
private compareTokens(a: SemanticToken, b: SemanticToken): number {
if (a.line === b.line) {
return a.char - b.char;
}
return a.line - b.line;
}
}
export type SemanticTokenAcceptor = <N extends AstNode = AstNode>(options: SemanticTokenAcceptorOptions<N>) => void;
/**
* A basic super class for providing semantic token data.
* Users of Langium should extend this class to create their own `SemanticTokenProvider`.
*
* The entry method for generating semantic tokens based on an `AstNode` is the `highlightElement` method.
*/
export abstract class AbstractSemanticTokenProvider implements SemanticTokenProvider {
/**
* Store a token builder for each open document.
*/
protected tokensBuilders = new Map<string, SemanticTokensBuilder>();
protected currentDocument?: LangiumDocument;
protected currentTokensBuilder?: SemanticTokensBuilder;
protected currentRange?: Range;
protected clientCapabilities?: SemanticTokensClientCapabilities;
constructor(services: LangiumServices) {
// Delete the token builder once the text document has been closed
services.shared.workspace.TextDocuments.onDidClose(e => {
this.tokensBuilders.delete(e.document.uri);
});
services.shared.lsp.LanguageServer.onInitialize(params => {
this.initialize(params.capabilities.textDocument?.semanticTokens);
});
}
initialize(clientCapabilities?: SemanticTokensClientCapabilities): void {
this.clientCapabilities = clientCapabilities;
}
async semanticHighlight(document: LangiumDocument, _params: SemanticTokensParams, cancelToken = CancellationToken.None): Promise<SemanticTokens> {
this.currentRange = undefined;
this.currentDocument = document;
this.currentTokensBuilder = this.getDocumentTokensBuilder(document);
this.currentTokensBuilder.flush();
await this.computeHighlighting(document, this.createAcceptor(), cancelToken);
return this.currentTokensBuilder.build();
}
async semanticHighlightRange(document: LangiumDocument, params: SemanticTokensRangeParams, cancelToken = CancellationToken.None): Promise<SemanticTokens> {
this.currentRange = params.range;
this.currentDocument = document;
this.currentTokensBuilder = this.getDocumentTokensBuilder(document);
this.currentTokensBuilder.flush();
await this.computeHighlighting(document, this.createAcceptor(), cancelToken);
return this.currentTokensBuilder.build();
}
async semanticHighlightDelta(document: LangiumDocument, params: SemanticTokensDeltaParams, cancelToken = CancellationToken.None): Promise<SemanticTokens | SemanticTokensDelta> {
this.currentRange = undefined;
this.currentDocument = document;
this.currentTokensBuilder = this.getDocumentTokensBuilder(document);
this.currentTokensBuilder.previousResult(params.previousResultId);
await this.computeHighlighting(document, this.createAcceptor(), cancelToken);
return this.currentTokensBuilder.buildEdits();
}
protected createAcceptor(): SemanticTokenAcceptor {
const acceptor: SemanticTokenAcceptor = options => {
if ('line' in options) {
this.highlightToken({
range: {
start: {
line: options.line,
character: options.char
},
end: {
line: options.line,
character: options.char + options.length
}
},
type: options.type,
modifier: options.modifier
});
} else if ('range' in options) {
this.highlightToken(options);
} else if ('keyword' in options) {
this.highlightKeyword(options);
} else if ('property' in options) {
this.highlightProperty(options);
} else {
this.highlightNode({
node: options.cst,
type: options.type,
modifier: options.modifier
});
}
};
return acceptor;
}
protected getDocumentTokensBuilder(document: LangiumDocument): SemanticTokensBuilder {
const existing = this.tokensBuilders.get(document.uri.toString());
if (existing) {
return existing;
}
const builder = new SemanticTokensBuilder();
this.tokensBuilders.set(document.uri.toString(), builder);
return builder;
}
protected async computeHighlighting(document: LangiumDocument, acceptor: SemanticTokenAcceptor, cancelToken: CancellationToken): Promise<void> {
const root = document.parseResult.value;
const treeIterator = streamAst(root, { range: this.currentRange }).iterator();
let result: IteratorResult<AstNode>;
do {
result = treeIterator.next();
if (!result.done) {
await interruptAndCheck(cancelToken);
const node = result.value;
if (this.highlightElement(node, acceptor) === 'prune') {
treeIterator.prune();
}
}
} while (!result.done);
}
/**
* @return `'prune'` to skip the children of this element, nothing otherwise.
*/
protected abstract highlightElement(node: AstNode, acceptor: SemanticTokenAcceptor): void | undefined | 'prune';
protected highlightToken(options: SemanticTokenRangeOptions): void {
const { range, type } = options;
let modifiers = options.modifier;
if ((this.currentRange && !inRange(range, this.currentRange)) || !this.currentDocument || !this.currentTokensBuilder) {
return;
}
const intType = AllSemanticTokenTypes[type];
let totalModifier = 0;
if (modifiers !== undefined) {
if (typeof modifiers === 'string') {
modifiers = [modifiers];
}
for (const modifier of modifiers) {
const intModifier = AllSemanticTokenModifiers[modifier];
totalModifier |= intModifier;
}
}
const startLine = range.start.line;
const endLine = range.end.line;
if (startLine === endLine) {
// Token only spans a single line
const char = range.start.character;
const length = range.end.character - char;
this.currentTokensBuilder.push(startLine, char, length, intType, totalModifier);
} else if (this.clientCapabilities?.multilineTokenSupport) {
// Let token span multiple lines
const startChar = range.start.character;
const startOffset = this.currentDocument.textDocument.offsetAt(range.start);
const endOffset = this.currentDocument.textDocument.offsetAt(range.end);
this.currentTokensBuilder.push(startLine, startChar, endOffset - startOffset, intType, totalModifier);
} else {
// Token spans multiple lines, but the client doesn't support it
// Split the range into multiple semantic tokens
const firstLineStart = range.start;
let nextLineOffset = this.currentDocument.textDocument.offsetAt({
line: startLine + 1,
character: 0
});
// Build first line
this.currentTokensBuilder.push(
firstLineStart.line,
firstLineStart.character,
nextLineOffset - firstLineStart.character - 1,
intType,
totalModifier
);
// Build all lines in between first and last
for (let i = startLine + 1; i < endLine; i++) {
const currentLineOffset = nextLineOffset;
nextLineOffset = this.currentDocument.textDocument.offsetAt({
line: i + 1,
character: 0
});
this.currentTokensBuilder.push(
i,
0,
nextLineOffset - currentLineOffset - 1,
intType, totalModifier
);
}
// Build last line
this.currentTokensBuilder.push(
endLine,
0,
range.end.character,
intType,
totalModifier
);
}
}
protected highlightProperty<N extends AstNode>(options: SemanticTokenPropertyOptions<N>): void {
const nodes: CstNode[] = [];
if (typeof options.index === 'number') {
const node = findNodeForProperty(options.node.$cstNode, options.property, options.index);
if (node) {
nodes.push(node);
}
} else {
nodes.push(...findNodesForProperty(options.node.$cstNode, options.property));
}
const { type, modifier } = options;
for (const node of nodes) {
this.highlightNode({
node,
type,
modifier
});
}
}
protected highlightKeyword(options: SemanticTokenKeywordOptions): void {
const { node, keyword, type, index, modifier } = options;
const nodes: CstNode[] = [];
if (typeof index === 'number') {
const keywordNode = findNodeForKeyword(node.$cstNode, keyword, index);
if (keywordNode) {
nodes.push(keywordNode);
}
} else {
nodes.push(...findNodesForKeyword(node.$cstNode, keyword));
}
for (const keywordNode of nodes) {
this.highlightNode({
node: keywordNode,
type,
modifier
});
}
}
protected highlightNode(options: SemanticTokenNodeOptions): void {
const { node, type, modifier } = options;
const range = node.range;
this.highlightToken({
range,
type,
modifier
});
}
}
export namespace SemanticTokensDecoder {
export interface DecodedSemanticToken {
offset: number;
tokenType: SemanticTokenTypes;
tokenModifiers: number;
text: string;
}
export function decode<T extends AstNode = AstNode>(tokens: SemanticTokens, document: LangiumDocument<T>): DecodedSemanticToken[] {
const typeMap = new Map<number, SemanticTokenTypes>();
Object.entries(AllSemanticTokenTypes).forEach(([type, index]) => typeMap.set(index, type as SemanticTokenTypes));
let line = 0;
let character = 0;
return sliceIntoChunks(tokens.data, 5).map(t => {
line += t[0];
if (t[0] !== 0) {
character = 0;
}
character += t[1];
const length = t[2];
const offset = document.textDocument.offsetAt({ line, character });
return {
offset,
tokenType: typeMap.get(t[3])!,
tokenModifiers: t[4],
text: document.textDocument.getText({ start: { line, character }, end: { line, character: character + length } })
} as DecodedSemanticToken;
});
}
function sliceIntoChunks<T>(arr: T[], chunkSize: number) {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
}