-
Notifications
You must be signed in to change notification settings - Fork 61
/
SourceContext.ts
1744 lines (1480 loc) · 65.8 KB
/
SourceContext.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is released under the MIT license.
* Copyright (c) 2016, 2022, Mike Lischke
*
* See LICENSE file for more info.
*/
// This file contains the handling for a single source file. It provides syntactic and semantic
// information, symbol lookups and more.
import * as child_process from "child_process";
import * as path from "path";
import * as fs from "fs";
import * as vm from "vm";
import {
CharStreams, CommonTokenStream, BailErrorStrategy, DefaultErrorStrategy, Token, RuleContext, ParserRuleContext,
Vocabulary,
} from "antlr4ts";
import {
PredictionMode, ATNState, RuleTransition, TransitionType, ATNStateType, RuleStartState, ActionTransition,
PredicateTransition, PrecedencePredicateTransition,
} from "antlr4ts/atn";
import { ParseCancellationException, IntervalSet, Interval } from "antlr4ts/misc";
import { ParseTreeWalker, TerminalNode, ParseTree } from "antlr4ts/tree";
import { CodeCompletionCore, Symbol, LiteralSymbol } from "antlr4-c3";
import {
ANTLRv4Parser, ParserRuleSpecContext, LexerRuleSpecContext, GrammarSpecContext, OptionsSpecContext, ModeSpecContext,
} from "../parser/ANTLRv4Parser";
import { ANTLRv4Lexer } from "../parser/ANTLRv4Lexer";
import {
ISymbolInfo, IDiagnosticEntry, DiagnosticType, IReferenceNode, IGenerationOptions,
ISentenceGenerationOptions, IFormattingOptions, IDefinition, IContextDetails, PredicateFunction,
CodeActionType, SymbolKind, GrammarType,
} from "./types";
import { ContextErrorListener } from "./ContextErrorListener";
import { ContextLexerErrorListener } from "./ContextLexerErrorListener";
import { DetailsListener } from "./DetailsListener";
import { SemanticListener } from "./SemanticListener";
import { RuleVisitor } from "./RuleVisitor";
import { InterpreterDataReader, IInterpreterData } from "./InterpreterDataReader";
import { ErrorParser } from "./ErrorParser";
import {
ContextSymbolTable, BuiltInChannelSymbol, BuiltInTokenSymbol, BuiltInModeSymbol, RuleSymbol,
VirtualTokenSymbol, FragmentTokenSymbol, TokenSymbol, RuleReferenceSymbol, TokenReferenceSymbol, ImportSymbol,
LexerModeSymbol, TokenChannelSymbol, OperatorSymbol, ArgumentsSymbol, ExceptionActionSymbol,
FinallyActionSymbol, LexerActionSymbol, LexerPredicateSymbol, ParserActionSymbol, ParserPredicateSymbol,
LexerCommandSymbol, TerminalSymbol, GlobalNamedActionSymbol, LocalNamedActionSymbol,
} from "./ContextSymbolTable";
import { SentenceGenerator } from "./SentenceGenerator";
import { GrammarFormatter } from "./Formatter";
import {
GrammarLexerInterpreter, InterpreterLexerErrorListener, GrammarParserInterpreter, InterpreterParserErrorListener,
} from "./GrammarInterpreters";
import { printableUnicodePoints } from "./Unicode";
import { BackendUtils } from "./BackendUtils";
import { IATNGraphData, IATNLink, IATNNode } from "../webview-scripts/types";
// One source context per file. Source contexts can reference each other (e.g. for symbol lookups).
export class SourceContext {
private static globalSymbols = new ContextSymbolTable("Global Symbols", { allowDuplicateSymbols: false });
private static symbolToKindMap: Map<new () => Symbol, SymbolKind> = new Map([
[GlobalNamedActionSymbol, SymbolKind.GlobalNamedAction],
[LocalNamedActionSymbol, SymbolKind.LocalNamedAction],
[ImportSymbol, SymbolKind.Import],
[BuiltInTokenSymbol, SymbolKind.BuiltInLexerToken],
[VirtualTokenSymbol, SymbolKind.VirtualLexerToken],
[FragmentTokenSymbol, SymbolKind.FragmentLexerToken],
[TokenSymbol, SymbolKind.LexerRule],
[BuiltInModeSymbol, SymbolKind.BuiltInMode],
[LexerModeSymbol, SymbolKind.LexerMode],
[BuiltInChannelSymbol, SymbolKind.BuiltInChannel],
[TokenChannelSymbol, SymbolKind.TokenChannel],
[RuleSymbol, SymbolKind.ParserRule],
[OperatorSymbol, SymbolKind.Operator],
[TerminalSymbol, SymbolKind.Terminal],
[TokenReferenceSymbol, SymbolKind.TokenReference],
[RuleReferenceSymbol, SymbolKind.RuleReference],
[LexerCommandSymbol, SymbolKind.LexerCommand],
[ExceptionActionSymbol, SymbolKind.ExceptionAction],
[FinallyActionSymbol, SymbolKind.FinallyAction],
[ParserActionSymbol, SymbolKind.ParserAction],
[LexerActionSymbol, SymbolKind.LexerAction],
[ParserPredicateSymbol, SymbolKind.ParserPredicate],
[LexerPredicateSymbol, SymbolKind.LexerPredicate],
[ArgumentsSymbol, SymbolKind.Arguments],
]);
private static printableChars = printableUnicodePoints({});
public symbolTable: ContextSymbolTable;
public sourceId: string;
public info: IContextDetails = {
type: GrammarType.Unknown,
unreferencedRules: [],
imports: [],
};
/* @internal */
public diagnostics: IDiagnosticEntry[] = [];
// eslint-disable-next-line no-use-before-define
private references: SourceContext[] = []; // Contexts referencing us.
// Result related fields.
//private diagnostics: DiagnosticEntry[] = [];
private rrdScripts: Map<string, string>;
private semanticAnalysisDone = false; // Includes determining reference counts.
// Grammar parsing infrastructure.
private tokenStream: CommonTokenStream;
private parser: ANTLRv4Parser | undefined;
private errorListener: ContextErrorListener = new ContextErrorListener(this.diagnostics);
private lexerErrorListener: ContextLexerErrorListener = new ContextLexerErrorListener(this.diagnostics);
// Grammar data.
private grammarLexerData: IInterpreterData | undefined;
private grammarLexerRuleMap = new Map<string, number>(); // A mapping from lexer rule names to their index.
private grammarParserData: IInterpreterData | undefined;
private grammarParserRuleMap = new Map<string, number>(); // A mapping from parser rule names to their index.
private tree: GrammarSpecContext | undefined; // The root context from the last parse run.
public constructor(public fileName: string, private extensionDir: string) {
this.sourceId = path.basename(fileName, path.extname(fileName));
this.symbolTable = new ContextSymbolTable(this.sourceId, { allowDuplicateSymbols: true }, this);
// Initialize static global symbol table, if not yet done.
const eof = SourceContext.globalSymbols.resolve("EOF");
eof.then((value) => {
if (!value) {
SourceContext.globalSymbols.addNewSymbolOfType(BuiltInChannelSymbol, undefined,
"DEFAULT_TOKEN_CHANNEL");
SourceContext.globalSymbols.addNewSymbolOfType(BuiltInChannelSymbol, undefined, "HIDDEN");
SourceContext.globalSymbols.addNewSymbolOfType(BuiltInTokenSymbol, undefined, "EOF");
SourceContext.globalSymbols.addNewSymbolOfType(BuiltInModeSymbol, undefined, "DEFAULT_MODE");
}
}).catch(() => {
// ignore
});
}
public get isInterpreterDataLoaded(): boolean {
return this.grammarLexerData !== undefined || this.grammarParserData !== undefined;
}
/**
* Internal function to provide interpreter data to certain internal classes (e.g. the debugger).
*
* @returns Lexer and parser interpreter data for use outside of this context.
*/
public get interpreterData(): [IInterpreterData | undefined, IInterpreterData | undefined] {
return [this.grammarLexerData, this.grammarParserData];
}
public get hasErrors(): boolean {
for (const diagnostic of this.diagnostics) {
if (diagnostic.type === DiagnosticType.Error) {
return true;
}
}
return false;
}
public static getKindFromSymbol(symbol: Symbol): SymbolKind {
if (symbol.name === "tokenVocab") {
return SymbolKind.TokenVocab;
}
return this.symbolToKindMap.get(symbol.constructor as typeof Symbol) || SymbolKind.Unknown;
}
/**
* @param ctx The context to get info for.
* @param keepQuotes A flag indicating if quotes should be kept if there are any around the context's text.
*
* @returns The definition info for the given rule context.
*/
public static definitionForContext(ctx: ParseTree | undefined, keepQuotes: boolean): IDefinition | undefined {
if (!ctx) {
return undefined;
}
const result: IDefinition = {
text: "",
range: {
start: { column: 0, row: 0 },
end: { column: 0, row: 0 },
},
};
if (ctx instanceof ParserRuleContext) {
const range = <Interval>{ a: ctx.start.startIndex, b: ctx.stop!.stopIndex };
result.range.start.column = ctx.start.charPositionInLine;
result.range.start.row = ctx.start.line;
result.range.end.column = ctx.stop!.charPositionInLine;
result.range.end.row = ctx.stop!.line;
// For mode definitions we only need the init line, not all the lexer rules following it.
if (ctx.ruleIndex === ANTLRv4Parser.RULE_modeSpec) {
const modeSpec = ctx as ModeSpecContext;
range.b = modeSpec.SEMI().symbol.stopIndex;
result.range.end.column = modeSpec.SEMI().symbol.charPositionInLine;
result.range.end.row = modeSpec.SEMI().symbol.line;
} else if (ctx.ruleIndex === ANTLRv4Parser.RULE_grammarSpec) {
// Similar for entire grammars. We only need the introducer line here.
const grammarSpec: GrammarSpecContext = <GrammarSpecContext>ctx;
range.b = grammarSpec.SEMI().symbol.stopIndex;
result.range.end.column = grammarSpec.SEMI().symbol.charPositionInLine;
result.range.end.row = grammarSpec.SEMI().symbol.line;
range.a = grammarSpec.grammarType().start.startIndex;
result.range.start.column = grammarSpec.grammarType().start.charPositionInLine;
result.range.start.row = grammarSpec.grammarType().start.line;
}
if (ctx.start.tokenSource?.inputStream) {
const stream = ctx.start.tokenSource.inputStream;
try {
result.text = stream.getText(range);
} catch (e) {
// The method getText uses an unreliable JS String API which can throw on larger texts.
// In this case we cannot return the text of the given context.
// A context with such a large size is probably an error case anyway (unfinished multi line comment
// or unfinished action).
}
}
} else if (ctx instanceof TerminalNode) {
result.text = ctx.text;
result.range.start.column = ctx.symbol.charPositionInLine;
result.range.start.row = ctx.symbol.line;
result.range.end.column = ctx.symbol.charPositionInLine + result.text.length;
result.range.end.row = ctx.symbol.line;
}
if (keepQuotes || result.text.length < 2) {
return result;
}
const quoteChar = result.text[0];
if ((quoteChar === '"' || quoteChar === "`" || quoteChar === "'")
&& quoteChar === result.text[result.text.length - 1]) {
result.text = result.text.substr(1, result.text.length - 2);
}
return result;
}
public symbolAtPosition(column: number, row: number, limitToChildren: boolean): ISymbolInfo | undefined {
const terminal = BackendUtils.parseTreeFromPosition(this.tree!, column, row);
if (!terminal || !(terminal instanceof TerminalNode)) {
return undefined;
}
// If limitToChildren is set we only want to show info for symbols in specific contexts.
// These are contexts which are used as subrules in rule definitions.
if (!limitToChildren) {
return this.getSymbolInfo(terminal.text);
}
let parent = (terminal.parent as RuleContext);
if (parent.ruleIndex === ANTLRv4Parser.RULE_identifier) {
parent = (parent.parent as RuleContext);
}
switch (parent.ruleIndex) {
case ANTLRv4Parser.RULE_ruleref:
case ANTLRv4Parser.RULE_terminalRule: {
let symbol = this.symbolTable.symbolContainingContext(terminal);
if (symbol) {
// This is only the reference to a symbol. See if that symbol exists actually.
symbol = this.resolveSymbol(symbol.name);
if (symbol) {
return this.getSymbolInfo(symbol);
}
}
break;
}
case ANTLRv4Parser.RULE_actionBlock:
case ANTLRv4Parser.RULE_ruleAction:
case ANTLRv4Parser.RULE_lexerCommandExpr:
case ANTLRv4Parser.RULE_optionValue:
case ANTLRv4Parser.RULE_delegateGrammar:
case ANTLRv4Parser.RULE_modeSpec:
case ANTLRv4Parser.RULE_setElement: {
const symbol = this.symbolTable.symbolContainingContext(terminal);
if (symbol) {
return this.getSymbolInfo(symbol);
}
break;
}
case ANTLRv4Parser.RULE_lexerCommand:
case ANTLRv4Parser.RULE_lexerCommandName: {
const symbol = this.symbolTable.symbolContainingContext(terminal);
if (symbol) {
return this.getSymbolInfo(symbol);
}
break;
}
default: {
break;
}
}
return undefined;
}
/**
* Returns the symbol at the given position or one of its outer scopes.
*
* @param column The position within a source line.
* @param row The source line index.
* @param ruleScope If true find the enclosing rule (if any) and return it's range, instead of the directly
* enclosing scope.
*
* @returns The symbol at the given position (if there's any).
*/
public enclosingSymbolAtPosition(column: number, row: number, ruleScope: boolean): ISymbolInfo | undefined {
let context = BackendUtils.parseTreeFromPosition(this.tree!, column, row);
if (!context) {
return undefined;
}
if (context instanceof TerminalNode) {
context = context.parent;
}
if (ruleScope) {
let run = context;
while (run
&& !(run instanceof ParserRuleSpecContext)
&& !(run instanceof OptionsSpecContext)
&& !(run instanceof LexerRuleSpecContext)) {
run = run.parent;
}
if (run) {
context = run;
}
}
if (context) {
const symbol = this.symbolTable.symbolWithContextSync(context);
if (symbol) {
return this.symbolTable.getSymbolInfo(symbol);
}
}
}
public listTopLevelSymbols(includeDependencies: boolean): ISymbolInfo[] {
return this.symbolTable.listTopLevelSymbols(includeDependencies);
}
public getVocabulary(): Vocabulary | undefined {
if (this.grammarLexerData) {
return this.grammarLexerData.vocabulary;
}
}
public getRuleList(): string[] | undefined {
if (this.grammarParserData) {
return this.grammarParserData.ruleNames;
}
}
public getChannels(): string[] | undefined {
if (this.grammarLexerData) {
return this.grammarLexerData.channels;
}
}
public getModes(): string[] | undefined {
if (this.grammarLexerData) {
return this.grammarLexerData.modes;
}
}
/**
* Returns a list of actions of a specific kind from the context's symbol table.
*
* @param type The type of list to return.
*
* @returns The list of actions.
*/
public listActions(type: CodeActionType): ISymbolInfo[] {
return this.symbolTable.listActions(type);
}
/**
* Returns numbers of registered actions of each kind.
*
* @returns An object containing the individual action counts.
*/
public getActionCounts(): Map<CodeActionType, number> {
return this.symbolTable.getActionCounts();
}
public async getCodeCompletionCandidates(column: number, row: number): Promise<ISymbolInfo[]> {
if (!this.parser) {
return [];
}
const core = new CodeCompletionCore(this.parser);
core.showResult = false;
core.ignoredTokens = new Set([
ANTLRv4Lexer.TOKEN_REF,
ANTLRv4Lexer.RULE_REF,
ANTLRv4Lexer.LEXER_CHAR_SET,
ANTLRv4Lexer.DOC_COMMENT,
ANTLRv4Lexer.BLOCK_COMMENT,
ANTLRv4Lexer.LINE_COMMENT,
ANTLRv4Lexer.INT,
ANTLRv4Lexer.STRING_LITERAL,
ANTLRv4Lexer.UNTERMINATED_STRING_LITERAL,
ANTLRv4Lexer.MODE,
ANTLRv4Lexer.COLON,
ANTLRv4Lexer.COLONCOLON,
ANTLRv4Lexer.COMMA,
ANTLRv4Lexer.SEMI,
ANTLRv4Lexer.LPAREN,
ANTLRv4Lexer.RPAREN,
ANTLRv4Lexer.LBRACE,
ANTLRv4Lexer.RBRACE,
//ANTLRv4Lexer.RARROW,
//ANTLRv4Lexer.LT,
ANTLRv4Lexer.GT,
//ANTLRv4Lexer.ASSIGN,
//ANTLRv4Lexer.QUESTION,
//ANTLRv4Lexer.STAR,
//ANTLRv4Lexer.PLUS_ASSIGN,
//ANTLRv4Lexer.PLUS,
//ANTLRv4Lexer.OR,
ANTLRv4Lexer.DOLLAR,
ANTLRv4Lexer.RANGE,
ANTLRv4Lexer.DOT,
ANTLRv4Lexer.AT,
ANTLRv4Lexer.POUND,
ANTLRv4Lexer.NOT,
ANTLRv4Lexer.ID,
ANTLRv4Lexer.WS,
ANTLRv4Lexer.END_ARGUMENT,
ANTLRv4Lexer.UNTERMINATED_ARGUMENT,
ANTLRv4Lexer.ARGUMENT_CONTENT,
ANTLRv4Lexer.END_ACTION,
ANTLRv4Lexer.UNTERMINATED_ACTION,
ANTLRv4Lexer.ACTION_CONTENT,
ANTLRv4Lexer.UNTERMINATED_CHAR_SET,
ANTLRv4Lexer.EOF,
-2, // TODO: Erroneously inserted. Needs fix in antlr4-c3.
]);
core.preferredRules = new Set([
ANTLRv4Parser.RULE_argActionBlock,
ANTLRv4Parser.RULE_actionBlock,
ANTLRv4Parser.RULE_terminalRule,
ANTLRv4Parser.RULE_lexerCommandName,
ANTLRv4Parser.RULE_identifier,
ANTLRv4Parser.RULE_ruleref,
]);
// Search the token index which covers our caret position.
let index: number;
this.tokenStream.fill();
for (index = 0; ; ++index) {
const token = this.tokenStream.get(index);
//console.log(token.toString());
if (token.type === Token.EOF || token.line > row) {
break;
}
if (token.line < row) {
continue;
}
const length = token.text ? token.text.length : 0;
if ((token.charPositionInLine + length) >= column) {
break;
}
}
const candidates = core.collectCandidates(index);
const result: ISymbolInfo[] = [];
candidates.tokens.forEach((following: number[], type: number) => {
switch (type) {
case ANTLRv4Lexer.RARROW: {
result.push({
kind: SymbolKind.Operator,
name: "->",
description: "Lexer action introducer",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.LT: {
result.push({
kind: SymbolKind.Operator,
name: "< key = value >",
description: "Rule element option",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.ASSIGN: {
result.push({
kind: SymbolKind.Operator,
name: "=",
description: "Variable assignment",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.QUESTION: {
result.push({
kind: SymbolKind.Operator,
name: "?",
description: "Zero or one repetition operator",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.STAR: {
result.push({
kind: SymbolKind.Operator,
name: "*",
description: "Zero or more repetition operator",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.PLUS_ASSIGN: {
result.push({
kind: SymbolKind.Operator,
name: "+=",
description: "Variable list addition",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.PLUS: {
result.push({
kind: SymbolKind.Operator,
name: "+",
description: "One or more repetition operator",
source: this.fileName,
});
break;
}
case ANTLRv4Lexer.OR: {
result.push({
kind: SymbolKind.Operator,
name: "|",
description: "Rule alt separator",
source: this.fileName,
});
break;
}
default: {
const value = this.parser!.vocabulary.getDisplayName(type);
result.push({
kind: SymbolKind.Keyword,
name: value[0] === "'" ? value.substr(1, value.length - 2) : value, // Remove quotes.
source: this.fileName,
});
break;
}
}
});
const promises: Array<Promise<Symbol[] | undefined>> = [];
candidates.rules.forEach((candidateRule, key) => {
switch (key) {
case ANTLRv4Parser.RULE_argActionBlock: {
result.push({
kind: SymbolKind.Arguments,
name: "[ argument action code ]",
source: this.fileName,
definition: undefined,
description: undefined,
});
break;
}
case ANTLRv4Parser.RULE_actionBlock: {
result.push({
kind: SymbolKind.ParserAction,
name: "{ action code }",
source: this.fileName,
definition: undefined,
description: undefined,
});
// Include predicates only when we are in a lexer or parser element.
const list = candidateRule.ruleList;
if (list[list.length - 1] === ANTLRv4Parser.RULE_lexerElement) {
result.push({
kind: SymbolKind.LexerPredicate,
name: "{ predicate }?",
source: this.fileName,
definition: undefined,
description: undefined,
});
} else if (list[list.length - 1] === ANTLRv4Parser.RULE_element) {
result.push({
kind: SymbolKind.ParserPredicate,
name: "{ predicate }?",
source: this.fileName,
definition: undefined,
description: undefined,
});
}
break;
}
case ANTLRv4Parser.RULE_terminalRule: { // Lexer rules.
promises.push(this.symbolTable.getAllSymbols(BuiltInTokenSymbol));
promises.push(this.symbolTable.getAllSymbols(VirtualTokenSymbol));
promises.push(this.symbolTable.getAllSymbols(TokenSymbol));
// Include fragment rules only when referenced from a lexer rule.
const list = candidateRule.ruleList;
if (list[list.length - 1] === ANTLRv4Parser.RULE_lexerAtom) {
promises.push(this.symbolTable.getAllSymbols(FragmentTokenSymbol));
}
break;
}
case ANTLRv4Parser.RULE_lexerCommandName: {
["channel", "skip", "more", "mode", "push", "pop"].forEach((symbol) => {
result.push({
kind: SymbolKind.Keyword,
name: symbol,
source: this.fileName,
definition: undefined,
description: undefined,
});
});
break;
}
case ANTLRv4Parser.RULE_ruleref: {
promises.push(this.symbolTable.getAllSymbols(RuleSymbol));
break;
}
case ANTLRv4Parser.RULE_identifier: {
// Identifiers can be a lot of things. We only handle special cases here.
// More concrete identifiers should be captured by rules further up in the call chain.
const list = candidateRule.ruleList;
switch (list[list.length - 1]) {
case ANTLRv4Parser.RULE_option: {
["superClass", "tokenVocab", "TokenLabelType", "contextSuperClass", "exportMacro"]
.forEach((symbol) => {
result.push({
kind: SymbolKind.Option,
name: symbol,
source: this.fileName,
definition: undefined,
description: undefined,
});
});
break;
}
case ANTLRv4Parser.RULE_namedAction: {
["header", "members", "preinclude", "postinclude", "context", "declarations", "definitions",
"listenerpreinclude", "listenerpostinclude", "listenerdeclarations", "listenermembers",
"listenerdefinitions", "baselistenerpreinclude", "baselistenerpostinclude",
"baselistenerdeclarations", "baselistenermembers", "baselistenerdefinitions",
"visitorpreinclude", "visitorpostinclude", "visitordeclarations", "visitormembers",
"visitordefinitions", "basevisitorpreinclude", "basevisitorpostinclude",
"basevisitordeclarations", "basevisitormembers", "basevisitordefinitions"]
.forEach((symbol) => {
result.push({
kind: SymbolKind.Keyword,
name: symbol,
source: this.fileName,
definition: undefined,
description: undefined,
});
});
break;
}
default: {
break;
}
}
break;
}
default: {
break;
}
}
});
const symbolLists = await Promise.all(promises);
symbolLists.forEach((symbols) => {
if (symbols) {
symbols.forEach((symbol) => {
if (symbol.name !== "EOF") {
result.push({
kind: SourceContext.getKindFromSymbol(symbol),
name: symbol.name,
source: this.fileName,
definition: undefined,
description: undefined,
});
}
});
}
});
return result;
}
/**
* Should be called on every change to keep the input stream up to date, particularly for code completion.
* This call doesn't do any expensive processing (parse() does).
*
* @param source The new content of the editor.
*/
public setText(source: string): void {
const input = CharStreams.fromString(source);
const lexer = new ANTLRv4Lexer(input);
// There won't be lexer errors actually. They are silently bubbled up and will cause parser errors.
lexer.removeErrorListeners();
lexer.addErrorListener(this.lexerErrorListener);
this.tokenStream = new CommonTokenStream(lexer);
// Keep the old parser around until the next parse run. Code completion could kick in before that.
// this.parser = undefined;
}
public parse(): string[] {
// Rewind the input stream for a new parse run.
// Might be unnecessary when we just created that via setText.
this.tokenStream.seek(0);
this.parser = new ANTLRv4Parser(this.tokenStream);
this.parser.removeErrorListeners();
this.parser.addErrorListener(this.errorListener);
this.parser.errorHandler = new BailErrorStrategy();
this.parser.interpreter.setPredictionMode(PredictionMode.SLL);
this.tree = undefined;
this.info.type = GrammarType.Unknown;
this.info.imports.length = 0;
this.grammarLexerData = undefined;
this.grammarLexerRuleMap.clear();
this.grammarParserData = undefined;
this.grammarLexerRuleMap.clear();
this.semanticAnalysisDone = false;
this.diagnostics.length = 0;
this.symbolTable.clear();
this.symbolTable.addDependencies(SourceContext.globalSymbols);
try {
this.tree = this.parser.grammarSpec();
} catch (e) {
if (e instanceof ParseCancellationException) {
this.tokenStream.seek(0);
this.parser.reset();
this.parser.errorHandler = new DefaultErrorStrategy();
this.parser.interpreter.setPredictionMode(PredictionMode.LL);
this.tree = this.parser.grammarSpec();
} else {
throw e;
}
}
if (this.tree && this.tree.childCount > 0) {
try {
const typeContext = this.tree.grammarType();
if (typeContext.LEXER()) {
this.info.type = GrammarType.Lexer;
} else if (typeContext.PARSER()) {
this.info.type = GrammarType.Parser;
} else {
this.info.type = GrammarType.Combined;
}
} catch (e) {
// ignored
}
}
this.symbolTable.tree = this.tree;
const listener = new DetailsListener(this.symbolTable, this.info.imports);
ParseTreeWalker.DEFAULT.walk(listener, this.tree);
this.info.unreferencedRules = this.symbolTable.getUnreferencedSymbols();
return this.info.imports;
}
public getDiagnostics(): IDiagnosticEntry[] {
this.runSemanticAnalysisIfNeeded();
return this.diagnostics;
}
public getReferenceGraph(): Map<string, IReferenceNode> {
this.runSemanticAnalysisIfNeeded();
const result = new Map<string, IReferenceNode>();
for (const symbol of this.symbolTable.getAllSymbolsSync(Symbol, false)) {
if (symbol instanceof RuleSymbol
|| symbol instanceof TokenSymbol
|| symbol instanceof FragmentTokenSymbol) {
const entry: IReferenceNode = {
kind: symbol instanceof RuleSymbol ? SymbolKind.ParserRule : SymbolKind.LexerRule,
rules: new Set<string>(),
tokens: new Set<string>(),
literals: new Set<string>(),
};
for (const child of symbol.getNestedSymbolsOfTypeSync(RuleReferenceSymbol)) {
const resolved = this.symbolTable.resolveSync(child.name, false);
if (resolved) {
entry.rules.add(resolved.qualifiedName());
} else {
entry.rules.add(child.name);
}
}
for (const child of symbol.getNestedSymbolsOfTypeSync(TokenReferenceSymbol)) {
const resolved = this.symbolTable.resolveSync(child.name, false);
if (resolved) {
entry.tokens.add(resolved.qualifiedName());
} else {
entry.tokens.add(child.name);
}
}
for (const child of symbol.getNestedSymbolsOfTypeSync(LiteralSymbol)) {
const resolved = this.symbolTable.resolveSync(child.name, false);
if (resolved) {
entry.literals.add(resolved.qualifiedName());
} else {
entry.literals.add(child.name);
}
}
result.set(symbol.qualifiedName(), entry);
} else if (symbol instanceof BuiltInTokenSymbol) {
result.set(symbol.qualifiedName(), {
kind: SymbolKind.BuiltInLexerToken,
rules: new Set<string>(),
tokens: new Set<string>(),
literals: new Set<string>(),
});
} else if (symbol instanceof VirtualTokenSymbol) {
result.set(symbol.qualifiedName(), {
kind: SymbolKind.VirtualLexerToken,
rules: new Set<string>(),
tokens: new Set<string>(),
literals: new Set<string>(),
});
}
}
return result;
}
public getRRDScript(ruleName: string): string | undefined {
this.runSemanticAnalysisIfNeeded();
return this.rrdScripts.get(ruleName);
}
/**
* Add this context to the list of referencing contexts in the given context.
*
* @param context The context to add.
*/
public addAsReferenceTo(context: SourceContext): void {
// Check for mutual inclusion. References are organized like a mesh.
const pipeline: SourceContext[] = [context];
while (pipeline.length > 0) {
const current = pipeline.shift();
if (!current) {
continue;
}
if (current.references.indexOf(this) > -1) {
return; // Already in the list.
}
pipeline.push(...current.references);
}
context.references.push(this);
this.symbolTable.addDependencies(context.symbolTable);
}
/**
* Remove the given context from our list of dependencies.
*
* @param context The context to remove.
*/
public removeDependency(context: SourceContext): void {
const index = context.references.indexOf(this);
if (index > -1) {
context.references.splice(index, 1);
}
this.symbolTable.removeDependency(context.symbolTable);
}
public getReferenceCount(symbol: string): number {
this.runSemanticAnalysisIfNeeded();
let result = this.symbolTable.getReferenceCount(symbol);
for (const reference of this.references) {
result += reference.getReferenceCount(symbol);
}
return result;
}
public async getAllSymbols(recursive: boolean): Promise<Symbol[]> {
// The symbol table returns symbols of itself and those it depends on (if recursive is true).
const result = await this.symbolTable.getAllSymbols(Symbol, !recursive);
// Add also symbols from contexts referencing us, this time not recursive
// as we have added our content already.
for (const reference of this.references) {
const symbols = await reference.symbolTable.getAllSymbols(Symbol, true);
symbols.forEach((value) => {
result.push(value);
});
}
return result;
}
/**
* Similar like `enclosingRangeForSymbol` but returns the rule's name and index, if found.
*
* @param column The position within a line.
* @param row The line index.
*
* @returns A rule name and its index if found.
*/
public ruleFromPosition(column: number, row: number): [string | undefined, number | undefined] {
const tree = BackendUtils.parseTreeFromPosition(this.tree!, column, row);
if (!tree) {
return [undefined, undefined];
}
let context: RuleContext | undefined = (tree as RuleContext);
while (context && context.ruleIndex !== ANTLRv4Parser.RULE_parserRuleSpec
&& context.ruleIndex !== ANTLRv4Parser.RULE_lexerRuleSpec) {
context = context.parent;
}
if (context) {
if (context.ruleIndex === ANTLRv4Parser.RULE_parserRuleSpec) {
const ruleName = (context as ParserRuleSpecContext).RULE_REF().text;
let ruleIndex;