-
Notifications
You must be signed in to change notification settings - Fork 11
/
extension.ts
490 lines (426 loc) · 15.9 KB
/
extension.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import * as vscode from 'vscode';
const tokenTypes = new Map<string, number>();
const tokenModifiers = new Map<string, number>();
const legend = (function () {
const tokenTypesLegend = [
'comment', 'string', 'keyword', 'number', 'regexp', 'operator', 'namespace',
'type', 'struct', 'class', 'interface', 'enum', 'typeParameter', 'function',
'member', 'macro', 'variable', 'parameter', 'property', 'label'
];
tokenTypesLegend.forEach((tokenType, index) => tokenTypes.set(tokenType, index));
const tokenModifiersLegend = [
'declaration', 'documentation', 'readonly', 'static', 'abstract', 'deprecated',
'modification', 'async'
];
tokenModifiersLegend.forEach((tokenModifier, index) => tokenModifiers.set(tokenModifier, index));
return new vscode.SemanticTokensLegend(tokenTypesLegend, tokenModifiersLegend);
})();
export function activate(context: vscode.ExtensionContext) {
const yacc = new YaccSemanticProvider();
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('yacc', yacc, '%', '<'));
context.subscriptions.push(vscode.languages.registerDocumentSemanticTokensProvider('yacc', yacc, legend));
context.subscriptions.push(vscode.languages.registerHoverProvider('yacc', yacc));
context.subscriptions.push(vscode.languages.registerDefinitionProvider('yacc', yacc));
const lex = new LexSemanticProvider();
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('lex', lex, '%', '{', '<'));
context.subscriptions.push(vscode.languages.registerDocumentSemanticTokensProvider('lex', lex, legend));
context.subscriptions.push(vscode.languages.registerHoverProvider('lex', lex));
context.subscriptions.push(vscode.languages.registerDefinitionProvider('lex', lex));
}
interface IParsedToken {
line: number;
startCharacter: number;
length: number;
tokenType: string;
tokenModifiers: string[];
}
abstract class SemanticAnalyzer implements vscode.DocumentSemanticTokensProvider, vscode.CompletionItemProvider, vscode.HoverProvider, vscode.DefinitionProvider {
protected keywords: string[];
protected invalidRegions: vscode.Range[] = [];
protected startingLine = -1;
protected endingLine = -1;
constructor(keywords: string[]) {
this.keywords = keywords;
}
async provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Location | vscode.Location[] | vscode.LocationLink[]> {
for (let i = 0; i < this.invalidRegions.length; i++) {
const range = this.invalidRegions[i];
if (range.contains(position)) {
return [];
}
}
return this._provideDefinition(document, position);
}
async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Hover> {
for (let i = 0; i < this.invalidRegions.length; i++) {
const range = this.invalidRegions[i];
if (range.contains(position)) {
return { contents: [] };
}
}
return this._provideHover(document, position);
}
async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext): Promise<vscode.CompletionItem[] | vscode.CompletionList> {
for (let i = 0; i < this.invalidRegions.length; i++) {
const range = this.invalidRegions[i];
if (range.contains(position)) {
return [];
}
}
if (context.triggerKind === vscode.CompletionTriggerKind.TriggerCharacter) {
return this._handleTrigger(document, position, context.triggerCharacter);
}
return this._rulesCompletion(document, position);
}
async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken): Promise<vscode.SemanticTokens> {
const allTokens = this._parseText(document);
const builder = new vscode.SemanticTokensBuilder();
allTokens.forEach((token) => {
builder.push(token.line, token.startCharacter, token.length, this._encodeTokenType(token.tokenType), this._encodeTokenModifiers(token.tokenModifiers));
});
return builder.build()
}
private _encodeTokenType(tokenType: string): number {
if (!tokenTypes.has(tokenType)) {
return 0;
}
return tokenTypes.get(tokenType)!;
}
private _encodeTokenModifiers(strTokenModifiers: string[]): number {
let result = 0;
for (let i = 0; i < strTokenModifiers.length; i++) {
const tokenModifier = strTokenModifiers[i];
if (tokenModifiers.has(tokenModifier)) {
result = result | (1 << tokenModifiers.get(tokenModifier)!);
}
}
return result;
}
protected _keywordCompletions(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem[] | vscode.CompletionList {
if (position.line >= this.startingLine) {
return [];
}
return this.keywords.map((keyword) => {
const completion = new vscode.CompletionItem(keyword, vscode.CompletionItemKind.Constructor);
completion.detail = "keyword";
return completion;
});
}
protected abstract _provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location | vscode.Location[] | vscode.LocationLink[];
protected abstract _provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover;
protected abstract _handleTrigger(document: vscode.TextDocument, position: vscode.Position, character: string | undefined): vscode.CompletionItem[] | vscode.CompletionList;
protected abstract _rulesCompletion(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem[] | vscode.CompletionList;
protected abstract _parseText(document: vscode.TextDocument): IParsedToken[];
}
class YaccSemanticProvider extends SemanticAnalyzer {
private symbols: Map<string, vscode.Position> = new Map();
private tokens: Map<string, vscode.Position> = new Map();
private types: Map<string, vscode.Position> = new Map();
constructor() {
super(['type', 'option', 'token', 'left', 'right', 'define', 'output', 'precedence', 'nterm', 'destructor', 'union', 'code', 'printer', 'parse-param', 'lex-param']);
}
protected _provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location | vscode.Location[] | vscode.LocationLink[] {
const word = document.getText(document.getWordRangeAtPosition(position));
if (this.symbols.has(word)) {
const pos = this.symbols.get(word)!;
return new vscode.Location(document.uri, pos);
}
if (this.tokens.has(word)) {
const pos = this.tokens.get(word)!;
return new vscode.Location(document.uri, pos);
}
if (this.types.has(word)) {
const pos = this.types.get(word)!;
return new vscode.Location(document.uri, pos);
}
return [];
}
protected _provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover {
const word = document.getText(document.getWordRangeAtPosition(position));
if (this.symbols.has(word)) {
return { contents: ['symbol'] }
}
if (this.tokens.has(word)) {
return { contents: ['token'] }
}
if (this.types.has(word)) {
return { contents: ['type'] }
}
return { contents: [] };
}
protected _handleTrigger(document: vscode.TextDocument, position: vscode.Position, character: string | undefined): vscode.CompletionItem[] | vscode.CompletionList {
let line = document.lineAt(position).text.substr(0, position.character);
if (character === '%') {
if (line.startsWith('%'))
return this._keywordCompletions(document, position);
} else if (character === '<') {
if (line.match(/^%(?:type|token)\s*<.*/)) {
return this._typeParamCompletions(document, position);
}
}
return [];
}
protected _rulesCompletion(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem[] | vscode.CompletionList {
let line = document.lineAt(position).text.substr(0, position.character);
/**
* Result suggestion on defining type
*/
if (line.match(/^%type\s*<.*>.*$/)) {
var completions: vscode.CompletionItem[] = [];
this.symbols.forEach((value, key) => {
const completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.Class);
completion.detail = "symbol"
completions.push(completion);
})
return completions;
}
if (line.match(/^%(?:type|token)\s*<[^>\n]+$/)) {
return this._typeParamCompletions(document, position);
}
/**
* Token and result suggestion only inside the rules section
*/
if (position.line >= this.startingLine && position.line <= this.endingLine) {
if (line.indexOf('|') !== -1 || line.indexOf(':') !== -1) {
var completions: vscode.CompletionItem[] = [];
var completion: vscode.CompletionItem;
this.symbols.forEach((value, key) => {
completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.Class)
completion.detail = "symbol";
completions.push(completion);
})
this.tokens.forEach((value, key) => {
completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.Field)
completion.detail = "token";
completions.push(completion);
})
return completions;
}
}
return [];
}
private _typeParamCompletions(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem[] | vscode.CompletionList {
if (position.line >= this.startingLine) {
return [];
}
var completion: vscode.CompletionItem;
var completions: vscode.CompletionItem[] = [];
this.types.forEach((value, key) => {
completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.TypeParameter)
completion.detail = "type"
completions.push(completion);
})
return completions;
}
protected _parseText(document: vscode.TextDocument): IParsedToken[] {
let text = document.getText();
this.tokens.clear();
this.symbols.clear();
this.invalidRegions = [];
let r: IParsedToken[] = [];
let lines = text.split(/\r\n|\r|\n/);
let rules: string[] = [];
/**
* Find all invalid regions
*/
const codeMatcher = /%(?=top)?{[\s\S]*?%}|{[\s\S]*?}/g;
var cpp;
while ((cpp = codeMatcher.exec(text)) !== null) {
let start = document.positionAt(cpp.index);
let end = document.positionAt(cpp.index + cpp[0].length);
this.invalidRegions.push(new vscode.Range(start, end));
}
const yyType = /%union\s*{([\s\S]*?)}/.exec(text);
if (yyType !== null) {
const typeMatcher = /([a-zA-Z0-9_]*)\s*;/g
var res;
while ((res = typeMatcher.exec(yyType[1])) !== null) {
const position = document.positionAt(yyType.index + res.index);
this.types.set(res[1], position);
}
}
/**
* Find rule section
*/
this.startingLine = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.startsWith('%%')) {
if (this.startingLine !== -1) {
/**
* If we are inside of rules section
*/
const filtered = line.replace(/{[\s\S]*}/, "").replace(/\/\*.*?\*\//, "");
rules.push(filtered);
} else {
if (line.startsWith('%token')) {
const tokenSymbols = line.slice(6).replace(/<.*>/, "").trim().split(" ");
tokenSymbols.forEach(token => {
if (token.length > 0) {
this.tokens.set(token, new vscode.Position(i, 1));
}
});
}
}
continue;
} else {
if (this.startingLine === -1) {
this.startingLine = i + 1;
} else {
this.endingLine = i + 1;
}
}
}
/**
* Find all symbols
*/
for (let i = 0; i < rules.length; i++) {
const ruleMatcher = /^[a-zA-Z0-9_]+/;
const rule = ruleMatcher.exec(rules[i]);
if (rule !== null) {
this.symbols.set(rule[0], new vscode.Position(this.startingLine + i, 1));
}
}
/**
* Highlight symbols in rules section
*/
const matcher = /[a-zA-Z0-9_]+/g;
for (let i = 0; i < rules.length; i++) {
const line = rules[i];
var match;
while ((match = matcher.exec(line)) != null) {
const word = match[0];
if (this.symbols.has(word)) {
r.push({
line: this.startingLine + i,
startCharacter: match.index,
length: word.length,
tokenType: "class",
tokenModifiers: []
});
}
}
}
return r;
}
}
class LexSemanticProvider extends SemanticAnalyzer {
private defines: Map<string, vscode.Position> = new Map();
private states: Map<string, vscode.Position> = new Map();
constructor() {
super(['array', 'pointer', 'option', 's', 'x']);
}
protected _provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location | vscode.Location[] | vscode.LocationLink[] {
const word = document.getText(document.getWordRangeAtPosition(position));
if (this.defines.has(word)) {
const pos = this.defines.get(word)!;
return new vscode.Location(document.uri, pos);
}
if (this.states.has(word)) {
const pos = this.states.get(word)!;
return new vscode.Location(document.uri, pos);
}
return [];
}
protected _provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover {
const word = document.getText(document.getWordRangeAtPosition(position));
if (this.defines.has(word)) {
return { contents: ['symbol'] };
}
if (this.defines.has(word)) {
return { contents: ['definition'] };
}
if (this.states.has(word)) {
return { contents: ['initial state'] };
}
return { contents: [] };
}
protected _handleTrigger(document: vscode.TextDocument, position: vscode.Position, character: string | undefined): vscode.CompletionItem[] | vscode.CompletionList {
var completion: vscode.CompletionItem;
const completions: vscode.CompletionItem[] = [];
let line = document.lineAt(position).text.substr(0, position.character);
if (character === '%') {
if (line.startsWith('%'))
return this._keywordCompletions(document, position);
} else if (character === '{') {
if (position.line < this.startingLine || line.charAt(position.character - 2) !== ' ')
this.defines.forEach((value, key) => {
completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.Class);
completion.detail = "definition";
completions.push(completion);
})
} else if (character === '<' && position.line >= this.startingLine && position.line <= this.endingLine) {
if (line.match(/^</)) {
this.states.forEach((value, key) => {
completion = new vscode.CompletionItem(key, vscode.CompletionItemKind.Class);
completion.detail = "initial state";
completions.push(completion);
})
}
}
return completions;
}
protected _rulesCompletion(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem[] | vscode.CompletionList {
return [];
}
protected _parseText(document: vscode.TextDocument): IParsedToken[] {
this.invalidRegions = [];
this.defines.clear();
let text = document.getText();
let r: IParsedToken[] = [];
let lines = text.split(/\r\n|\r|\n/);
/**
* Find all invalid regions
*/
const codeMatcher = /%(?=top)?{[\s\S]*?%}/g;
var cpp;
while ((cpp = codeMatcher.exec(text)) !== null) {
let start = document.positionAt(cpp.index);
let end = document.positionAt(cpp.index + cpp[0].length);
this.invalidRegions.push(new vscode.Range(start, end));
}
/**
* Find rule section
*/
this.startingLine = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.startsWith('%%')) {
if (this.startingLine !== -1) {
/**
* If we are inside of rules section
*/
cpp = /(?<=[\t\v\f ]){[\s\S]*?}/.exec(line);
if (cpp !== null) {
let start = new vscode.Position(i, cpp.index);
let end = new vscode.Position(i, cpp.index + cpp[0].length);
this.invalidRegions.push(new vscode.Range(start, end));
}
} else {
/**
* If we are inside of definition section
*/
if (line.startsWith('%s') || line.startsWith('%x')) {
const tokenSymbols = line.slice(2).trim().split(" ");
tokenSymbols.forEach(token => {
if (token.length > 0) {
this.states.set(token, new vscode.Position(i, 0));
}
});
}
const defined = line.match(/^[a-zA-Z0-9_]+/);
if (defined !== null) {
this.defines.set(defined[0], new vscode.Position(i, 0));
}
}
} else {
if (this.startingLine === -1) {
this.startingLine = i + 1;
} else {
this.endingLine = i + 1;
}
}
}
return r;
}
}