-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathgrammar.ts
More file actions
1218 lines (1060 loc) · 31.5 KB
/
grammar.ts
File metadata and controls
1218 lines (1060 loc) · 31.5 KB
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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { DebugFlags } from '../debug';
import { EncodedTokenAttributes, OptionalStandardTokenType, StandardTokenType, toOptionalTokenType } from '../encodedTokenAttributes';
import { IEmbeddedLanguagesMap, IGrammar, IToken, ITokenizeLineResult, ITokenizeLineResult2, ITokenTypeMap, StateStack, IFontInfo } from '../main';
import { createMatchers, Matcher } from '../matcher';
import { disposeOnigString, IOnigLib, OnigScanner, OnigString } from '../onigLib';
import { IRawGrammar, IRawRepository, IRawRule } from '../rawGrammar';
import { ruleIdFromNumber, IRuleFactoryHelper, IRuleRegistry, Rule, RuleFactory, RuleId, ruleIdToNumber } from '../rule';
import { FontStyle, ScopeName, ScopePath, ScopeStack, StyleAttributes } from '../theme';
import { clone, containsRTL } from '../utils';
import { BasicScopeAttributes, BasicScopeAttributesProvider } from './basicScopesAttributeProvider';
import { _tokenizeString } from './tokenizeString';
export function createGrammar(
scopeName: ScopeName,
grammar: IRawGrammar,
initialLanguage: number,
embeddedLanguages: IEmbeddedLanguagesMap | null,
tokenTypes: ITokenTypeMap | null,
balancedBracketSelectors: BalancedBracketSelectors | null,
grammarRepository: IGrammarRepository & IThemeProvider,
onigLib: IOnigLib
): Grammar {
return new Grammar(
scopeName,
grammar,
initialLanguage,
embeddedLanguages,
tokenTypes,
balancedBracketSelectors,
grammarRepository,
onigLib
); //TODO
}
export interface IThemeProvider {
themeMatch(scopePath: ScopeStack): StyleAttributes | null;
getDefaults(): StyleAttributes;
}
export interface IGrammarRepository {
lookup(scopeName: ScopeName): IRawGrammar | undefined;
injections(scopeName: ScopeName): ScopeName[];
}
export interface Injection {
readonly debugSelector: string;
readonly matcher: Matcher<string[]>;
readonly priority: -1 | 0 | 1; // 0 is the default. -1 for 'L' and 1 for 'R'
readonly ruleId: RuleId;
readonly grammar: IRawGrammar;
}
function collectInjections(result: Injection[], selector: string, rule: IRawRule, ruleFactoryHelper: IRuleFactoryHelper, grammar: IRawGrammar): void {
const matchers = createMatchers(selector, nameMatcher);
const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);
for (const matcher of matchers) {
result.push({
debugSelector: selector,
matcher: matcher.matcher,
ruleId: ruleId,
grammar: grammar,
priority: matcher.priority
});
}
}
function nameMatcher(identifers: ScopeName[], scopes: ScopeName[]): boolean {
if (scopes.length < identifers.length) {
return false;
}
let lastIndex = 0;
return identifers.every(identifier => {
for (let i = lastIndex; i < scopes.length; i++) {
if (scopesAreMatching(scopes[i], identifier)) {
lastIndex = i + 1;
return true;
}
}
return false;
});
}
function scopesAreMatching(thisScopeName: string, scopeName: string): boolean {
if (!thisScopeName) {
return false;
}
if (thisScopeName === scopeName) {
return true;
}
const len = scopeName.length;
return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === '.';
}
export class Grammar implements IGrammar, IRuleFactoryHelper, IOnigLib {
private _rootId: RuleId | -1;
private _lastRuleId: number;
private readonly _ruleId2desc: Rule[];
private readonly _includedGrammars: { [scopeName: string]: IRawGrammar };
private readonly _grammarRepository: IGrammarRepository & IThemeProvider;
private readonly _grammar: IRawGrammar;
private _injections: Injection[] | null;
private readonly _basicScopeAttributesProvider: BasicScopeAttributesProvider;
private readonly _tokenTypeMatchers: TokenTypeMatcher[];
public get themeProvider(): IThemeProvider { return this._grammarRepository; }
constructor(
private readonly _rootScopeName: ScopeName,
grammar: IRawGrammar,
initialLanguage: number,
embeddedLanguages: IEmbeddedLanguagesMap | null,
tokenTypes: ITokenTypeMap | null,
private readonly balancedBracketSelectors: BalancedBracketSelectors | null,
grammarRepository: IGrammarRepository & IThemeProvider,
private readonly _onigLib: IOnigLib
) {
this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(
initialLanguage,
embeddedLanguages
);
this._rootId = -1;
this._lastRuleId = 0;
this._ruleId2desc = [null!];
this._includedGrammars = {};
this._grammarRepository = grammarRepository;
this._grammar = initGrammar(grammar, null);
this._injections = null;
this._tokenTypeMatchers = [];
if (tokenTypes) {
for (const selector of Object.keys(tokenTypes)) {
const matchers = createMatchers(selector, nameMatcher);
for (const matcher of matchers) {
this._tokenTypeMatchers.push({
matcher: matcher.matcher,
type: tokenTypes[selector],
});
}
}
}
}
public dispose(): void {
for (const rule of this._ruleId2desc) {
if (rule) {
rule.dispose();
}
}
}
public createOnigScanner(sources: string[]): OnigScanner {
return this._onigLib.createOnigScanner(sources);
}
public createOnigString(sources: string): OnigString {
return this._onigLib.createOnigString(sources);
}
public getMetadataForScope(scope: string): BasicScopeAttributes {
return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);
}
private _collectInjections(): Injection[] {
const grammarRepository: IGrammarRepository = {
lookup: (scopeName: string): IRawGrammar | undefined => {
if (scopeName === this._rootScopeName) {
return this._grammar;
}
return this.getExternalGrammar(scopeName);
},
injections: (scopeName: string): string[] => {
return this._grammarRepository.injections(scopeName);
},
};
const result: Injection[] = [];
const scopeName = this._rootScopeName;
const grammar = grammarRepository.lookup(scopeName);
if (grammar) {
// add injections from the current grammar
const rawInjections = grammar.injections;
if (rawInjections) {
for (let expression in rawInjections) {
collectInjections(
result,
expression,
rawInjections[expression],
this,
grammar
);
}
}
// add injection grammars contributed for the current scope
const injectionScopeNames = this._grammarRepository.injections(scopeName);
if (injectionScopeNames) {
injectionScopeNames.forEach((injectionScopeName) => {
const injectionGrammar =
this.getExternalGrammar(injectionScopeName);
if (injectionGrammar) {
const selector = injectionGrammar.injectionSelector;
if (selector) {
collectInjections(
result,
selector,
injectionGrammar,
this,
injectionGrammar
);
}
}
});
}
}
result.sort((i1, i2) => i1.priority - i2.priority); // sort by priority
return result;
}
public getInjections(): Injection[] {
if (this._injections === null) {
this._injections = this._collectInjections();
if (DebugFlags.InDebugMode && this._injections.length > 0) {
console.log(
`Grammar ${this._rootScopeName} contains the following injections:`
);
for (const injection of this._injections) {
console.log(` - ${injection.debugSelector}`);
}
}
}
return this._injections;
}
public registerRule<T extends Rule>(factory: (id: RuleId) => T): T {
const id = ++this._lastRuleId;
const result = factory(ruleIdFromNumber(id));
this._ruleId2desc[id] = result;
return result;
}
public getRule(ruleId: RuleId): Rule {
return this._ruleId2desc[ruleIdToNumber(ruleId)];
}
public getExternalGrammar(
scopeName: string,
repository?: IRawRepository
): IRawGrammar | undefined {
if (this._includedGrammars[scopeName]) {
return this._includedGrammars[scopeName];
} else if (this._grammarRepository) {
const rawIncludedGrammar =
this._grammarRepository.lookup(scopeName);
if (rawIncludedGrammar) {
// console.log('LOADED GRAMMAR ' + pattern.include);
this._includedGrammars[scopeName] = initGrammar(
rawIncludedGrammar,
repository && repository.$base
);
return this._includedGrammars[scopeName];
}
}
return undefined;
}
public tokenizeLine(
lineText: string,
prevState: StateStackImpl | null,
timeLimit: number = 0
): ITokenizeLineResult {
const r = this._tokenize(lineText, prevState, false, timeLimit);
return {
tokens: r.tokenHandler.getTokenResult(r.ruleStack, r.lineLength),
ruleStack: r.ruleStack,
stoppedEarly: r.stoppedEarly,
fonts: r.tokenHandler.getFontResult()
};
}
public tokenizeLine2(
lineText: string,
prevState: StateStackImpl | null,
timeLimit: number = 0
): ITokenizeLineResult2 {
const r = this._tokenize(lineText, prevState, true, timeLimit);
return {
tokens: r.tokenHandler.getBinaryTokenResult(r.ruleStack, r.lineLength),
ruleStack: r.ruleStack,
stoppedEarly: r.stoppedEarly,
fonts: r.tokenHandler.getFontResult()
};
}
private _tokenize(
lineText: string,
prevState: StateStackImpl | null,
emitBinaryTokens: boolean,
timeLimit: number
): {
lineLength: number;
tokenHandler: ITokenHandler;
ruleStack: StateStackImpl;
stoppedEarly: boolean;
} {
if (this._rootId === -1) {
this._rootId = RuleFactory.getCompiledRuleId(
this._grammar.repository.$self,
this,
this._grammar.repository
);
// This ensures ids are deterministic, and thus equal in renderer and webworker.
this.getInjections();
}
let isFirstLine: boolean;
if (!prevState || prevState === StateStackImpl.NULL) {
isFirstLine = true;
const rawDefaultMetadata =
this._basicScopeAttributesProvider.getDefaultAttributes();
const defaultStyle = this.themeProvider.getDefaults();
const defaultMetadata = EncodedTokenAttributes.set(
0,
rawDefaultMetadata.languageId,
rawDefaultMetadata.tokenType,
null,
defaultStyle.fontStyle,
defaultStyle.foregroundId,
defaultStyle.backgroundId
);
const rootScopeName = this.getRule(this._rootId).getName(
null,
null
);
let scopeList: AttributedScopeStack;
if (rootScopeName) {
scopeList = AttributedScopeStack.createRootAndLookUpScopeName(
rootScopeName,
defaultMetadata,
this
);
} else {
scopeList = AttributedScopeStack.createRoot(
"unknown",
defaultMetadata
);
}
prevState = new StateStackImpl(
null,
this._rootId,
-1,
-1,
false,
null,
scopeList,
scopeList
);
} else {
isFirstLine = false;
prevState.reset();
}
lineText = lineText + "\n";
const onigLineText = this.createOnigString(lineText);
const lineLength = onigLineText.content.length;
const tokenHandler = new TokenHandler(
emitBinaryTokens,
lineText,
this._tokenTypeMatchers,
this.balancedBracketSelectors
);
const r = _tokenizeString(
this,
onigLineText,
isFirstLine,
0,
prevState,
tokenHandler,
true,
timeLimit
);
disposeOnigString(onigLineText);
return {
lineLength: lineLength,
tokenHandler: tokenHandler,
ruleStack: r.stack,
stoppedEarly: r.stoppedEarly,
};
}
}
function initGrammar(grammar: IRawGrammar, base: IRawRule | null | undefined): IRawGrammar {
grammar = clone(grammar);
grammar.repository = grammar.repository || <any>{};
grammar.repository.$self = {
$vscodeTextmateLocation: grammar.$vscodeTextmateLocation,
patterns: grammar.patterns,
name: grammar.scopeName
};
grammar.repository.$base = base || grammar.repository.$self;
return grammar;
}
export class AttributedScopeStack {
static fromExtension(namesScopeList: AttributedScopeStack | null, contentNameScopesList: AttributedScopeStackFrame[]): AttributedScopeStack | null {
let current = namesScopeList;
let scopeNames = namesScopeList?.scopePath ?? null;
for (const frame of contentNameScopesList) {
scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);
current = new AttributedScopeStack(current, scopeNames!, frame.encodedTokenAttributes, null);
}
return current;
}
public static createRoot(scopeName: ScopeName, tokenAttributes: EncodedTokenAttributes): AttributedScopeStack {
return new AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes, null);
}
public static createRootAndLookUpScopeName(scopeName: ScopeName, tokenAttributes: EncodedTokenAttributes, grammar: Grammar): AttributedScopeStack {
const rawRootMetadata = grammar.getMetadataForScope(scopeName);
const scopePath = new ScopeStack(null, scopeName);
const rootStyle = grammar.themeProvider.themeMatch(scopePath);
const resolvedTokenAttributes = AttributedScopeStack.mergeAttributes(
tokenAttributes,
rawRootMetadata,
rootStyle
);
return new AttributedScopeStack(null, scopePath, resolvedTokenAttributes, rootStyle);
}
public get scopeName(): ScopeName { return this.scopePath.scopeName; }
/**
* Invariant:
* ```
* if (parent && !scopePath.extends(parent.scopePath)) {
* throw new Error();
* }
* ```
*/
private constructor(
public readonly parent: AttributedScopeStack | null,
public readonly scopePath: ScopeStack,
public readonly tokenAttributes: EncodedTokenAttributes,
public readonly styleAttributes: StyleAttributes | null
) {
}
public toString() {
return this.getScopeNames().join(' ');
}
public equals(other: AttributedScopeStack): boolean {
return AttributedScopeStack.equals(this, other);
}
public static equals(
a: AttributedScopeStack | null,
b: AttributedScopeStack | null
): boolean {
do {
if (a === b) {
return true;
}
if (!a && !b) {
// End of list reached for both
return true;
}
if (!a || !b) {
// End of list reached only for one
return false;
}
if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {
return false;
}
// Go to previous pair
a = a.parent;
b = b.parent;
} while (true);
}
private static mergeAttributes(
existingTokenAttributes: EncodedTokenAttributes,
basicScopeAttributes: BasicScopeAttributes,
styleAttributes: StyleAttributes | null
): EncodedTokenAttributes {
let fontStyle = FontStyle.NotSet;
let foreground = 0;
let background = 0;
if (styleAttributes !== null) {
fontStyle = styleAttributes.fontStyle;
foreground = styleAttributes.foregroundId;
background = styleAttributes.backgroundId;
}
return EncodedTokenAttributes.set(
existingTokenAttributes,
basicScopeAttributes.languageId,
basicScopeAttributes.tokenType,
null,
fontStyle,
foreground,
background
);
}
public pushAttributed(scopePath: ScopePath | null, grammar: Grammar): AttributedScopeStack {
if (scopePath === null) {
return this;
}
if (scopePath.indexOf(' ') === -1) {
// This is the common case and much faster
return AttributedScopeStack._pushAttributed(this, scopePath, grammar);
}
const scopes = scopePath.split(/ /g);
let result: AttributedScopeStack = this;
for (const scope of scopes) {
result = AttributedScopeStack._pushAttributed(result, scope, grammar);
}
return result;
}
private static _pushAttributed(
target: AttributedScopeStack,
scopeName: ScopeName,
grammar: Grammar,
): AttributedScopeStack {
const rawMetadata = grammar.getMetadataForScope(scopeName);
const newPath = target.scopePath.push(scopeName);
const scopeThemeMatchResult =
grammar.themeProvider.themeMatch(newPath);
const metadata = AttributedScopeStack.mergeAttributes(
target.tokenAttributes,
rawMetadata,
scopeThemeMatchResult
);
return new AttributedScopeStack(target, newPath, metadata, scopeThemeMatchResult);
}
public getScopeNames(): string[] {
return this.scopePath.getSegments();
}
public getExtensionIfDefined(base: AttributedScopeStack | null): AttributedScopeStackFrame[] | undefined {
const result: AttributedScopeStackFrame[] = [];
let self: AttributedScopeStack | null = this;
while (self && self !== base) {
result.push({
encodedTokenAttributes: self.tokenAttributes,
scopeNames: self.scopePath.getExtensionIfDefined(self.parent?.scopePath ?? null)!,
});
self = self.parent;
}
return self === base ? result.reverse() : undefined;
}
}
interface AttributedScopeStackFrame {
encodedTokenAttributes: number;
scopeNames: string[];
}
/**
* Represents a "pushed" state on the stack (as a linked list element).
*/
export class StateStackImpl implements StateStack {
_stackElementBrand: void = undefined;
// TODO remove me
public static NULL = new StateStackImpl(
null,
0 as any,
0,
0,
false,
null,
null,
null
);
/**
* The position on the current line where this state was pushed.
* This is relevant only while tokenizing a line, to detect endless loops.
* Its value is meaningless across lines.
*/
private _enterPos: number;
/**
* The captured anchor position when this stack element was pushed.
* This is relevant only while tokenizing a line, to restore the anchor position when popping.
* Its value is meaningless across lines.
*/
private _anchorPos: number;
/**
* The depth of the stack.
*/
public readonly depth: number;
/**
* Invariant:
* ```
* if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {
* throw new Error();
* }
* if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {
* throw new Error();
* }
* ```
*/
constructor(
/**
* The previous state on the stack (or null for the root state).
*/
public readonly parent: StateStackImpl | null,
/**
* The state (rule) that this element represents.
*/
private readonly ruleId: RuleId,
enterPos: number,
anchorPos: number,
/**
* The state has entered and captured \n. This means that the next line should have an anchorPosition of 0.
*/
public readonly beginRuleCapturedEOL: boolean,
/**
* The "pop" (end) condition for this state in case that it was dynamically generated through captured text.
*/
public readonly endRule: string | null,
/**
* The list of scopes containing the "name" for this state.
*/
public readonly nameScopesList: AttributedScopeStack | null,
/**
* The list of scopes containing the "contentName" (besides "name") for this state.
* This list **must** contain as an element `scopeName`.
*/
public readonly contentNameScopesList: AttributedScopeStack | null,
) {
this.depth = this.parent ? this.parent.depth + 1 : 1;
this._enterPos = enterPos;
this._anchorPos = anchorPos;
}
public equals(other: StateStackImpl): boolean {
if (other === null) {
return false;
}
return StateStackImpl._equals(this, other);
}
private static _equals(a: StateStackImpl, b: StateStackImpl): boolean {
if (a === b) {
return true;
}
if (!this._structuralEquals(a, b)) {
return false;
}
return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);
}
/**
* A structural equals check. Does not take into account `scopes`.
*/
private static _structuralEquals(
a: StateStackImpl | null,
b: StateStackImpl | null
): boolean {
do {
if (a === b) {
return true;
}
if (!a && !b) {
// End of list reached for both
return true;
}
if (!a || !b) {
// End of list reached only for one
return false;
}
if (
a.depth !== b.depth ||
a.ruleId !== b.ruleId ||
a.endRule !== b.endRule
) {
return false;
}
// Go to previous pair
a = a.parent;
b = b.parent;
} while (true);
}
public clone(): StateStackImpl {
return this;
}
private static _reset(el: StateStackImpl | null): void {
while (el) {
el._enterPos = -1;
el._anchorPos = -1;
el = el.parent;
}
}
public reset(): void {
StateStackImpl._reset(this);
}
public pop(): StateStackImpl | null {
return this.parent;
}
public safePop(): StateStackImpl {
if (this.parent) {
return this.parent;
}
return this;
}
public push(
ruleId: RuleId,
enterPos: number,
anchorPos: number,
beginRuleCapturedEOL: boolean,
endRule: string | null,
nameScopesList: AttributedScopeStack | null,
contentNameScopesList: AttributedScopeStack | null,
): StateStackImpl {
return new StateStackImpl(
this,
ruleId,
enterPos,
anchorPos,
beginRuleCapturedEOL,
endRule,
nameScopesList,
contentNameScopesList
);
}
public getEnterPos(): number {
return this._enterPos;
}
public getAnchorPos(): number {
return this._anchorPos;
}
public getRule(grammar: IRuleRegistry): Rule {
return grammar.getRule(this.ruleId);
}
public toString(): string {
const r: string[] = [];
this._writeString(r, 0);
return "[" + r.join(",") + "]";
}
private _writeString(res: string[], outIndex: number): number {
if (this.parent) {
outIndex = this.parent._writeString(res, outIndex);
}
res[
outIndex++
] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`;
return outIndex;
}
public withContentNameScopesList(
contentNameScopeStack: AttributedScopeStack
): StateStackImpl {
if (this.contentNameScopesList === contentNameScopeStack) {
return this;
}
return this.parent!.push(
this.ruleId,
this._enterPos,
this._anchorPos,
this.beginRuleCapturedEOL,
this.endRule,
this.nameScopesList,
contentNameScopeStack
);
}
public withEndRule(endRule: string): StateStackImpl {
if (this.endRule === endRule) {
return this;
}
return new StateStackImpl(
this.parent,
this.ruleId,
this._enterPos,
this._anchorPos,
this.beginRuleCapturedEOL,
endRule,
this.nameScopesList,
this.contentNameScopesList
);
}
// Used to warn of endless loops
public hasSameRuleAs(other: StateStackImpl): boolean {
let el: StateStackImpl | null = this;
while (el && el._enterPos === other._enterPos) {
if (el.ruleId === other.ruleId) {
return true;
}
el = el.parent;
}
return false;
}
public toStateStackFrame(): StateStackFrame {
return {
ruleId: ruleIdToNumber(this.ruleId),
beginRuleCapturedEOL: this.beginRuleCapturedEOL,
endRule: this.endRule,
nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null)! ?? [],
contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)! ?? [],
};
}
public static pushFrame(self: StateStackImpl | null, frame: StateStackFrame): StateStackImpl {
const namesScopeList = AttributedScopeStack.fromExtension(self?.nameScopesList ?? null, frame.nameScopesList)!;
return new StateStackImpl(
self,
ruleIdFromNumber(frame.ruleId),
frame.enterPos ?? -1,
frame.anchorPos ?? -1,
frame.beginRuleCapturedEOL,
frame.endRule,
namesScopeList,
AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)!
);
}
}
export interface StateStackFrame {
ruleId: number;
enterPos?: number;
anchorPos?: number;
beginRuleCapturedEOL: boolean;
endRule: string | null;
nameScopesList: AttributedScopeStackFrame[];
/**
* on top of nameScopesList
*/
contentNameScopesList: AttributedScopeStackFrame[];
}
interface TokenTypeMatcher {
readonly matcher: Matcher<string[]>;
readonly type: StandardTokenType;
}
export class BalancedBracketSelectors {
private readonly balancedBracketScopes: Matcher<string[]>[];
private readonly unbalancedBracketScopes: Matcher<string[]>[];
private allowAny = false;
constructor(
balancedBracketScopes: string[],
unbalancedBracketScopes: string[],
) {
this.balancedBracketScopes = balancedBracketScopes.flatMap((selector) => {
if (selector === '*') {
this.allowAny = true;
return [];
}
return createMatchers(selector, nameMatcher).map((m) => m.matcher);
}
);
this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap((selector) =>
createMatchers(selector, nameMatcher).map((m) => m.matcher)
);
}
public get matchesAlways(): boolean {
return this.allowAny && this.unbalancedBracketScopes.length === 0;
}
public get matchesNever(): boolean {
return this.balancedBracketScopes.length === 0 && !this.allowAny;
}
public match(scopes: string[]): boolean {
for (const excluder of this.unbalancedBracketScopes) {
if (excluder(scopes)) {
return false;
}
}
for (const includer of this.balancedBracketScopes) {
if (includer(scopes)) {
return true;
}
}
return this.allowAny;
}
}
export class LineTokens {
private readonly _emitBinaryTokens: boolean;
/**
* defined only if `DebugFlags.InDebugMode`.
*/
private readonly _lineText: string | null;
/**
* used only if `_emitBinaryTokens` is false.
*/
private readonly _tokens: IToken[];
/**
* used only if `_emitBinaryTokens` is true.
*/
private readonly _binaryTokens: number[];
private _lastTokenEndIndex: number;
private readonly _tokenTypeOverrides: TokenTypeMatcher[];
private readonly _mergeConsecutiveTokensWithEqualMetadata: boolean;
constructor(
emitBinaryTokens: boolean,
lineText: string,
tokenTypeOverrides: TokenTypeMatcher[],
private readonly balancedBracketSelectors: BalancedBracketSelectors | null,
) {
this._emitBinaryTokens = emitBinaryTokens;
this._tokenTypeOverrides = tokenTypeOverrides;
if (DebugFlags.InDebugMode) {
this._lineText = lineText;
} else {
this._lineText = null;
}
// Don't merge tokens if the line contains RTL characters
this._mergeConsecutiveTokensWithEqualMetadata = !containsRTL(lineText);
this._tokens = [];
this._binaryTokens = [];
this._lastTokenEndIndex = 0;
}
public produceFromScopes(
scopesList: AttributedScopeStack | null,
endIndex: number
): void {
if (this._lastTokenEndIndex >= endIndex) {
return;
}
if (this._emitBinaryTokens) {
let metadata = scopesList?.tokenAttributes ?? 0;
let containsBalancedBrackets = false;
if (this.balancedBracketSelectors?.matchesAlways) {
containsBalancedBrackets = true;