-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
contextkey.ts
2160 lines (1783 loc) · 58.1 KB
/
contextkey.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CharCode } from 'vs/base/common/charCode';
import { Event } from 'vs/base/common/event';
import { isChrome, isEdge, isFirefox, isLinux, isMacintosh, isSafari, isWeb, isWindows } from 'vs/base/common/platform';
import { isFalsyOrWhitespace } from 'vs/base/common/strings';
import { Scanner, LexingError, Token, TokenType } from 'vs/platform/contextkey/common/scanner';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { localize } from 'vs/nls';
import { IDisposable } from 'vs/base/common/lifecycle';
import { illegalArgument } from 'vs/base/common/errors';
const CONSTANT_VALUES = new Map<string, boolean>();
CONSTANT_VALUES.set('false', false);
CONSTANT_VALUES.set('true', true);
CONSTANT_VALUES.set('isMac', isMacintosh);
CONSTANT_VALUES.set('isLinux', isLinux);
CONSTANT_VALUES.set('isWindows', isWindows);
CONSTANT_VALUES.set('isWeb', isWeb);
CONSTANT_VALUES.set('isMacNative', isMacintosh && !isWeb);
CONSTANT_VALUES.set('isEdge', isEdge);
CONSTANT_VALUES.set('isFirefox', isFirefox);
CONSTANT_VALUES.set('isChrome', isChrome);
CONSTANT_VALUES.set('isSafari', isSafari);
/** allow register constant context keys that are known only after startup; requires running `substituteConstants` on the context key - https://github.com/microsoft/vscode/issues/174218#issuecomment-1437972127 */
export function setConstant(key: string, value: boolean) {
if (CONSTANT_VALUES.get(key) !== undefined) { throw illegalArgument('contextkey.setConstant(k, v) invoked with already set constant `k`'); }
CONSTANT_VALUES.set(key, value);
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
export const enum ContextKeyExprType {
False = 0,
True = 1,
Defined = 2,
Not = 3,
Equals = 4,
NotEquals = 5,
And = 6,
Regex = 7,
NotRegex = 8,
Or = 9,
In = 10,
NotIn = 11,
Greater = 12,
GreaterEquals = 13,
Smaller = 14,
SmallerEquals = 15,
}
export interface IContextKeyExprMapper {
mapDefined(key: string): ContextKeyExpression;
mapNot(key: string): ContextKeyExpression;
mapEquals(key: string, value: any): ContextKeyExpression;
mapNotEquals(key: string, value: any): ContextKeyExpression;
mapGreater(key: string, value: any): ContextKeyExpression;
mapGreaterEquals(key: string, value: any): ContextKeyExpression;
mapSmaller(key: string, value: any): ContextKeyExpression;
mapSmallerEquals(key: string, value: any): ContextKeyExpression;
mapRegex(key: string, regexp: RegExp | null): ContextKeyRegexExpr;
mapIn(key: string, valueKey: string): ContextKeyInExpr;
mapNotIn(key: string, valueKey: string): ContextKeyNotInExpr;
}
export interface IContextKeyExpression {
cmp(other: ContextKeyExpression): number;
equals(other: ContextKeyExpression): boolean;
substituteConstants(): ContextKeyExpression | undefined;
evaluate(context: IContext): boolean;
serialize(): string;
keys(): string[];
map(mapFnc: IContextKeyExprMapper): ContextKeyExpression;
negate(): ContextKeyExpression;
}
export type ContextKeyExpression = (
ContextKeyFalseExpr | ContextKeyTrueExpr | ContextKeyDefinedExpr | ContextKeyNotExpr
| ContextKeyEqualsExpr | ContextKeyNotEqualsExpr | ContextKeyRegexExpr
| ContextKeyNotRegexExpr | ContextKeyAndExpr | ContextKeyOrExpr | ContextKeyInExpr
| ContextKeyNotInExpr | ContextKeyGreaterExpr | ContextKeyGreaterEqualsExpr
| ContextKeySmallerExpr | ContextKeySmallerEqualsExpr
);
/*
Syntax grammar:
```ebnf
expression ::= or
or ::= and { '||' and }*
and ::= term { '&&' term }*
term ::=
| '!' (KEY | true | false | parenthesized)
| primary
primary ::=
| 'true'
| 'false'
| parenthesized
| KEY '=~' REGEX
| KEY [ ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'not' 'in' | 'in') value ]
parenthesized ::=
| '(' expression ')'
value ::=
| 'true'
| 'false'
| 'in' // we support `in` as a value because there's an extension that uses it, ie "when": "languageId == in"
| VALUE // matched by the same regex as KEY; consider putting the value in single quotes if it's a string (e.g., with spaces)
| SINGLE_QUOTED_STR
| EMPTY_STR // this allows "when": "foo == " which's used by existing extensions
```
*/
export type ParserConfig = {
/**
* with this option enabled, the parser can recover from regex parsing errors, e.g., unescaped slashes: `/src//` is accepted as `/src\//` would be
*/
regexParsingWithErrorRecovery: boolean;
};
const defaultConfig: ParserConfig = {
regexParsingWithErrorRecovery: true
};
export type ParsingError = {
message: string;
offset: number;
lexeme: string;
additionalInfo?: string;
};
const errorEmptyString = localize('contextkey.parser.error.emptyString', "Empty context key expression");
const hintEmptyString = localize('contextkey.parser.error.emptyString.hint', "Did you forget to write an expression? You can also put 'false' or 'true' to always evaluate to false or true, respectively.");
const errorNoInAfterNot = localize('contextkey.parser.error.noInAfterNot', "'in' after 'not'.");
const errorClosingParenthesis = localize('contextkey.parser.error.closingParenthesis', "closing parenthesis ')'");
const errorUnexpectedToken = localize('contextkey.parser.error.unexpectedToken', "Unexpected token");
const hintUnexpectedToken = localize('contextkey.parser.error.unexpectedToken.hint', "Did you forget to put && or || before the token?");
const errorUnexpectedEOF = localize('contextkey.parser.error.unexpectedEOF', "Unexpected end of expression");
const hintUnexpectedEOF = localize('contextkey.parser.error.unexpectedEOF.hint', "Did you forget to put a context key?");
/**
* A parser for context key expressions.
*
* Example:
* ```ts
* const parser = new Parser();
* const expr = parser.parse('foo == "bar" && baz == true');
*
* if (expr === undefined) {
* // there were lexing or parsing errors
* // process lexing errors with `parser.lexingErrors`
* // process parsing errors with `parser.parsingErrors`
* } else {
* // expr is a valid expression
* }
* ```
*/
export class Parser {
// Note: this doesn't produce an exact syntax tree but a normalized one
// ContextKeyExpression's that we use as AST nodes do not expose constructors that do not normalize
private static _parseError = new Error();
// lifetime note: `_scanner` lives as long as the parser does, i.e., is not reset between calls to `parse`
private readonly _scanner = new Scanner();
// lifetime note: `_tokens`, `_current`, and `_parsingErrors` must be reset between calls to `parse`
private _tokens: Token[] = [];
private _current = 0; // invariant: 0 <= this._current < this._tokens.length ; any incrementation of this value must first call `_isAtEnd`
private _parsingErrors: ParsingError[] = [];
get lexingErrors(): Readonly<LexingError[]> {
return this._scanner.errors;
}
get parsingErrors(): Readonly<ParsingError[]> {
return this._parsingErrors;
}
constructor(private readonly _config: ParserConfig = defaultConfig) {
}
/**
* Parse a context key expression.
*
* @param input the expression to parse
* @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors
*/
parse(input: string): ContextKeyExpression | undefined {
if (input === '') {
this._parsingErrors.push({ message: errorEmptyString, offset: 0, lexeme: '', additionalInfo: hintEmptyString });
return undefined;
}
this._tokens = this._scanner.reset(input).scan();
// @ulugbekna: we do not stop parsing if there are lexing errors to be able to reconstruct regexes with unescaped slashes; TODO@ulugbekna: make this respect config option for recovery
this._current = 0;
this._parsingErrors = [];
try {
const expr = this._expr();
if (!this._isAtEnd()) {
const peek = this._peek();
const additionalInfo = peek.type === TokenType.Str ? hintUnexpectedToken : undefined;
this._parsingErrors.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: Scanner.getLexeme(peek), additionalInfo });
throw Parser._parseError;
}
return expr;
} catch (e) {
if (!(e === Parser._parseError)) {
throw e;
}
return undefined;
}
}
private _expr(): ContextKeyExpression | undefined {
return this._or();
}
private _or(): ContextKeyExpression | undefined {
const expr = [this._and()];
while (this._matchOne(TokenType.Or)) {
const right = this._and();
expr.push(right);
}
return expr.length === 1 ? expr[0] : ContextKeyExpr.or(...expr);
}
private _and(): ContextKeyExpression | undefined {
const expr = [this._term()];
while (this._matchOne(TokenType.And)) {
const right = this._term();
expr.push(right);
}
return expr.length === 1 ? expr[0] : ContextKeyExpr.and(...expr);
}
private _term(): ContextKeyExpression | undefined {
if (this._matchOne(TokenType.Neg)) {
const peek = this._peek();
switch (peek.type) {
case TokenType.True:
this._advance();
return ContextKeyFalseExpr.INSTANCE;
case TokenType.False:
this._advance();
return ContextKeyTrueExpr.INSTANCE;
case TokenType.LParen: {
this._advance();
const expr = this._expr();
this._consume(TokenType.RParen, errorClosingParenthesis);
return expr?.negate();
}
case TokenType.Str:
this._advance();
return ContextKeyNotExpr.create(peek.lexeme);
default:
throw this._errExpectedButGot(`KEY | true | false | '(' expression ')'`, peek);
}
}
return this._primary();
}
private _primary(): ContextKeyExpression | undefined {
const peek = this._peek();
switch (peek.type) {
case TokenType.True:
this._advance();
return ContextKeyExpr.true();
case TokenType.False:
this._advance();
return ContextKeyExpr.false();
case TokenType.LParen: {
this._advance();
const expr = this._expr();
this._consume(TokenType.RParen, errorClosingParenthesis);
return expr;
}
case TokenType.Str: {
// KEY
const key = peek.lexeme;
this._advance();
// =~ regex
if (this._matchOne(TokenType.RegexOp)) {
// @ulugbekna: we need to reconstruct the regex from the tokens because some extensions use unescaped slashes in regexes
const expr = this._peek();
if (!this._config.regexParsingWithErrorRecovery) {
this._advance();
if (expr.type !== TokenType.RegexStr) {
throw this._errExpectedButGot(`REGEX`, expr);
}
const regexLexeme = expr.lexeme;
const closingSlashIndex = regexLexeme.lastIndexOf('/');
const flags = closingSlashIndex === regexLexeme.length - 1 ? undefined : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
let regexp: RegExp | null;
try {
regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
} catch (e) {
throw this._errExpectedButGot(`REGEX`, expr);
}
return ContextKeyRegexExpr.create(key, regexp);
}
switch (expr.type) {
case TokenType.RegexStr:
case TokenType.Error: { // also handle an ErrorToken in case of smth such as /(/file)/
const lexemeReconstruction = [expr.lexeme]; // /REGEX/ or /REGEX/FLAGS
this._advance();
let followingToken = this._peek();
let parenBalance = 0;
for (let i = 0; i < expr.lexeme.length; i++) {
if (expr.lexeme.charCodeAt(i) === CharCode.OpenParen) {
parenBalance++;
} else if (expr.lexeme.charCodeAt(i) === CharCode.CloseParen) {
parenBalance--;
}
}
while (!this._isAtEnd() && followingToken.type !== TokenType.And && followingToken.type !== TokenType.Or) {
switch (followingToken.type) {
case TokenType.LParen:
parenBalance++;
break;
case TokenType.RParen:
parenBalance--;
break;
case TokenType.RegexStr:
case TokenType.QuotedStr:
for (let i = 0; i < followingToken.lexeme.length; i++) {
if (followingToken.lexeme.charCodeAt(i) === CharCode.OpenParen) {
parenBalance++;
} else if (expr.lexeme.charCodeAt(i) === CharCode.CloseParen) {
parenBalance--;
}
}
}
if (parenBalance < 0) {
break;
}
lexemeReconstruction.push(Scanner.getLexeme(followingToken));
this._advance();
followingToken = this._peek();
}
const regexLexeme = lexemeReconstruction.join('');
const closingSlashIndex = regexLexeme.lastIndexOf('/');
const flags = closingSlashIndex === regexLexeme.length - 1 ? undefined : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
let regexp: RegExp | null;
try {
regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
} catch (e) {
throw this._errExpectedButGot(`REGEX`, expr);
}
return ContextKeyExpr.regex(key, regexp);
}
case TokenType.QuotedStr: {
const serializedValue = expr.lexeme;
this._advance();
// replicate old regex parsing behavior
let regex: RegExp | null = null;
if (!isFalsyOrWhitespace(serializedValue)) {
const start = serializedValue.indexOf('/');
const end = serializedValue.lastIndexOf('/');
if (start !== end && start >= 0) {
const value = serializedValue.slice(start + 1, end);
const caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : '';
try {
regex = new RegExp(value, caseIgnoreFlag);
} catch (_e) {
throw this._errExpectedButGot(`REGEX`, expr);
}
}
}
if (regex === null) {
throw this._errExpectedButGot('REGEX', expr);
}
return ContextKeyRegexExpr.create(key, regex);
}
default:
throw this._errExpectedButGot('REGEX', this._peek());
}
}
// [ 'not' 'in' value ]
if (this._matchOne(TokenType.Not)) {
this._consume(TokenType.In, errorNoInAfterNot);
const right = this._value();
return ContextKeyExpr.notIn(key, right);
}
// [ ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in') value ]
const maybeOp = this._peek().type;
switch (maybeOp) {
case TokenType.Eq: {
this._advance();
const right = this._value();
if (this._previous().type === TokenType.QuotedStr) { // to preserve old parser behavior: "foo == 'true'" is preserved as "foo == 'true'", but "foo == true" is optimized as "foo"
return ContextKeyExpr.equals(key, right);
}
switch (right) {
case 'true':
return ContextKeyExpr.has(key);
case 'false':
return ContextKeyExpr.not(key);
default:
return ContextKeyExpr.equals(key, right);
}
}
case TokenType.NotEq: {
this._advance();
const right = this._value();
if (this._previous().type === TokenType.QuotedStr) { // same as above with "foo != 'true'"
return ContextKeyExpr.notEquals(key, right);
}
switch (right) {
case 'true':
return ContextKeyExpr.not(key);
case 'false':
return ContextKeyExpr.has(key);
default:
return ContextKeyExpr.notEquals(key, right);
}
}
// TODO: ContextKeyExpr.smaller(key, right) accepts only `number` as `right` AND during eval of this node, we just eval to `false` if `right` is not a number
// consequently, package.json linter should _warn_ the user if they're passing undesired things to ops
case TokenType.Lt:
this._advance();
return ContextKeySmallerExpr.create(key, this._value());
case TokenType.LtEq:
this._advance();
return ContextKeySmallerEqualsExpr.create(key, this._value());
case TokenType.Gt:
this._advance();
return ContextKeyGreaterExpr.create(key, this._value());
case TokenType.GtEq:
this._advance();
return ContextKeyGreaterEqualsExpr.create(key, this._value());
case TokenType.In:
this._advance();
return ContextKeyExpr.in(key, this._value());
default:
return ContextKeyExpr.has(key);
}
}
case TokenType.EOF:
this._parsingErrors.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: '', additionalInfo: hintUnexpectedEOF });
throw Parser._parseError;
default:
throw this._errExpectedButGot(`true | false | KEY \n\t| KEY '=~' REGEX \n\t| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this._peek());
}
}
private _value(): string {
const token = this._peek();
switch (token.type) {
case TokenType.Str:
case TokenType.QuotedStr:
this._advance();
return token.lexeme;
case TokenType.True:
this._advance();
return 'true';
case TokenType.False:
this._advance();
return 'false';
case TokenType.In: // we support `in` as a value, e.g., "when": "languageId == in" - exists in existing extensions
this._advance();
return 'in';
default:
// this allows "when": "foo == " which's used by existing extensions
// we do not call `_advance` on purpose - we don't want to eat unintended tokens
return '';
}
}
private _flagsGYRe = /g|y/g;
private _removeFlagsGY(flags: string): string {
return flags.replaceAll(this._flagsGYRe, '');
}
// careful: this can throw if current token is the initial one (ie index = 0)
private _previous() {
return this._tokens[this._current - 1];
}
private _matchOne(token: TokenType) {
if (this._check(token)) {
this._advance();
return true;
}
return false;
}
private _advance() {
if (!this._isAtEnd()) {
this._current++;
}
return this._previous();
}
private _consume(type: TokenType, message: string) {
if (this._check(type)) {
return this._advance();
}
throw this._errExpectedButGot(message, this._peek());
}
private _errExpectedButGot(expected: string, got: Token, additionalInfo?: string) {
const message = localize('contextkey.parser.error.expectedButGot', "Expected: {0}\nReceived: '{1}'.", expected, Scanner.getLexeme(got));
const offset = got.offset;
const lexeme = Scanner.getLexeme(got);
this._parsingErrors.push({ message, offset, lexeme, additionalInfo });
return Parser._parseError;
}
private _check(type: TokenType) {
return this._peek().type === type;
}
private _peek() {
return this._tokens[this._current];
}
private _isAtEnd() {
return this._peek().type === TokenType.EOF;
}
}
export abstract class ContextKeyExpr {
public static false(): ContextKeyExpression {
return ContextKeyFalseExpr.INSTANCE;
}
public static true(): ContextKeyExpression {
return ContextKeyTrueExpr.INSTANCE;
}
public static has(key: string): ContextKeyExpression {
return ContextKeyDefinedExpr.create(key);
}
public static equals(key: string, value: any): ContextKeyExpression {
return ContextKeyEqualsExpr.create(key, value);
}
public static notEquals(key: string, value: any): ContextKeyExpression {
return ContextKeyNotEqualsExpr.create(key, value);
}
public static regex(key: string, value: RegExp): ContextKeyExpression {
return ContextKeyRegexExpr.create(key, value);
}
public static in(key: string, value: string): ContextKeyExpression {
return ContextKeyInExpr.create(key, value);
}
public static notIn(key: string, value: string): ContextKeyExpression {
return ContextKeyNotInExpr.create(key, value);
}
public static not(key: string): ContextKeyExpression {
return ContextKeyNotExpr.create(key);
}
public static and(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined {
return ContextKeyAndExpr.create(expr, null, true);
}
public static or(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined {
return ContextKeyOrExpr.create(expr, null, true);
}
public static greater(key: string, value: number): ContextKeyExpression {
return ContextKeyGreaterExpr.create(key, value);
}
public static greaterEquals(key: string, value: number): ContextKeyExpression {
return ContextKeyGreaterEqualsExpr.create(key, value);
}
public static smaller(key: string, value: number): ContextKeyExpression {
return ContextKeySmallerExpr.create(key, value);
}
public static smallerEquals(key: string, value: number): ContextKeyExpression {
return ContextKeySmallerEqualsExpr.create(key, value);
}
private static _parser = new Parser({ regexParsingWithErrorRecovery: false });
public static deserialize(serialized: string | null | undefined): ContextKeyExpression | undefined {
if (serialized === undefined || serialized === null) { // an empty string needs to be handled by the parser to get a corresponding parsing error reported
return undefined;
}
const expr = this._parser.parse(serialized);
return expr;
}
}
export function validateWhenClauses(whenClauses: string[]): any {
const parser = new Parser({ regexParsingWithErrorRecovery: false }); // we run with no recovery to guide users to use correct regexes
return whenClauses.map(whenClause => {
parser.parse(whenClause);
if (parser.lexingErrors.length > 0) {
return parser.lexingErrors.map((se: LexingError) => ({
errorMessage: se.additionalInfo ?
localize('contextkey.scanner.errorForLinterWithHint', "Unexpected token. Hint: {0}", se.additionalInfo) :
localize('contextkey.scanner.errorForLinter', "Unexpected token."),
offset: se.offset,
length: se.lexeme.length,
}));
} else if (parser.parsingErrors.length > 0) {
return parser.parsingErrors.map((pe: ParsingError) => ({
errorMessage: pe.additionalInfo ? `${pe.message}. ${pe.additionalInfo}` : pe.message,
offset: pe.offset,
length: pe.lexeme.length,
}));
} else {
return [];
}
});
}
export function expressionsAreEqualWithConstantSubstitution(a: ContextKeyExpression | null | undefined, b: ContextKeyExpression | null | undefined): boolean {
const aExpr = a ? a.substituteConstants() : undefined;
const bExpr = b ? b.substituteConstants() : undefined;
if (!aExpr && !bExpr) {
return true;
}
if (!aExpr || !bExpr) {
return false;
}
return aExpr.equals(bExpr);
}
function cmp(a: ContextKeyExpression, b: ContextKeyExpression): number {
return a.cmp(b);
}
export class ContextKeyFalseExpr implements IContextKeyExpression {
public static INSTANCE = new ContextKeyFalseExpr();
public readonly type = ContextKeyExprType.False;
protected constructor() {
}
public cmp(other: ContextKeyExpression): number {
return this.type - other.type;
}
public equals(other: ContextKeyExpression): boolean {
return (other.type === this.type);
}
public substituteConstants(): ContextKeyExpression | undefined {
return this;
}
public evaluate(context: IContext): boolean {
return false;
}
public serialize(): string {
return 'false';
}
public keys(): string[] {
return [];
}
public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
return this;
}
public negate(): ContextKeyExpression {
return ContextKeyTrueExpr.INSTANCE;
}
}
export class ContextKeyTrueExpr implements IContextKeyExpression {
public static INSTANCE = new ContextKeyTrueExpr();
public readonly type = ContextKeyExprType.True;
protected constructor() {
}
public cmp(other: ContextKeyExpression): number {
return this.type - other.type;
}
public equals(other: ContextKeyExpression): boolean {
return (other.type === this.type);
}
public substituteConstants(): ContextKeyExpression | undefined {
return this;
}
public evaluate(context: IContext): boolean {
return true;
}
public serialize(): string {
return 'true';
}
public keys(): string[] {
return [];
}
public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
return this;
}
public negate(): ContextKeyExpression {
return ContextKeyFalseExpr.INSTANCE;
}
}
export class ContextKeyDefinedExpr implements IContextKeyExpression {
public static create(key: string, negated: ContextKeyExpression | null = null): ContextKeyExpression {
const constantValue = CONSTANT_VALUES.get(key);
if (typeof constantValue === 'boolean') {
return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
}
return new ContextKeyDefinedExpr(key, negated);
}
public readonly type = ContextKeyExprType.Defined;
protected constructor(
readonly key: string,
private negated: ContextKeyExpression | null
) {
}
public cmp(other: ContextKeyExpression): number {
if (other.type !== this.type) {
return this.type - other.type;
}
return cmp1(this.key, other.key);
}
public equals(other: ContextKeyExpression): boolean {
if (other.type === this.type) {
return (this.key === other.key);
}
return false;
}
public substituteConstants(): ContextKeyExpression | undefined {
const constantValue = CONSTANT_VALUES.get(this.key);
if (typeof constantValue === 'boolean') {
return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
}
return this;
}
public evaluate(context: IContext): boolean {
return (!!context.getValue(this.key));
}
public serialize(): string {
return this.key;
}
public keys(): string[] {
return [this.key];
}
public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
return mapFnc.mapDefined(this.key);
}
public negate(): ContextKeyExpression {
if (!this.negated) {
this.negated = ContextKeyNotExpr.create(this.key, this);
}
return this.negated;
}
}
export class ContextKeyEqualsExpr implements IContextKeyExpression {
public static create(key: string, value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
if (typeof value === 'boolean') {
return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated));
}
const constantValue = CONSTANT_VALUES.get(key);
if (typeof constantValue === 'boolean') {
const trueValue = constantValue ? 'true' : 'false';
return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
}
return new ContextKeyEqualsExpr(key, value, negated);
}
public readonly type = ContextKeyExprType.Equals;
private constructor(
private readonly key: string,
private readonly value: any,
private negated: ContextKeyExpression | null
) {
}
public cmp(other: ContextKeyExpression): number {
if (other.type !== this.type) {
return this.type - other.type;
}
return cmp2(this.key, this.value, other.key, other.value);
}
public equals(other: ContextKeyExpression): boolean {
if (other.type === this.type) {
return (this.key === other.key && this.value === other.value);
}
return false;
}
public substituteConstants(): ContextKeyExpression | undefined {
const constantValue = CONSTANT_VALUES.get(this.key);
if (typeof constantValue === 'boolean') {
const trueValue = constantValue ? 'true' : 'false';
return (this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
}
return this;
}
public evaluate(context: IContext): boolean {
// Intentional ==
// eslint-disable-next-line eqeqeq
return (context.getValue(this.key) == this.value);
}
public serialize(): string {
return `${this.key} == '${this.value}'`;
}
public keys(): string[] {
return [this.key];
}
public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
return mapFnc.mapEquals(this.key, this.value);
}
public negate(): ContextKeyExpression {
if (!this.negated) {
this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this);
}
return this.negated;
}
}
export class ContextKeyInExpr implements IContextKeyExpression {
public static create(key: string, valueKey: string): ContextKeyInExpr {
return new ContextKeyInExpr(key, valueKey);
}
public readonly type = ContextKeyExprType.In;
private negated: ContextKeyExpression | null = null;
private constructor(
private readonly key: string,
private readonly valueKey: string,
) {
}
public cmp(other: ContextKeyExpression): number {
if (other.type !== this.type) {
return this.type - other.type;
}
return cmp2(this.key, this.valueKey, other.key, other.valueKey);
}
public equals(other: ContextKeyExpression): boolean {
if (other.type === this.type) {
return (this.key === other.key && this.valueKey === other.valueKey);
}
return false;
}
public substituteConstants(): ContextKeyExpression | undefined {
return this;
}
public evaluate(context: IContext): boolean {
const source = context.getValue(this.valueKey);
const item = context.getValue(this.key);
if (Array.isArray(source)) {
return source.includes(item as any);
}
if (typeof item === 'string' && typeof source === 'object' && source !== null) {
return hasOwnProperty.call(source, item);
}
return false;
}
public serialize(): string {
return `${this.key} in '${this.valueKey}'`;
}
public keys(): string[] {
return [this.key, this.valueKey];
}
public map(mapFnc: IContextKeyExprMapper): ContextKeyInExpr {
return mapFnc.mapIn(this.key, this.valueKey);
}
public negate(): ContextKeyExpression {
if (!this.negated) {
this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey);
}
return this.negated;
}
}
export class ContextKeyNotInExpr implements IContextKeyExpression {
public static create(key: string, valueKey: string): ContextKeyNotInExpr {
return new ContextKeyNotInExpr(key, valueKey);
}
public readonly type = ContextKeyExprType.NotIn;
private readonly _negated: ContextKeyInExpr;
private constructor(
private readonly key: string,
private readonly valueKey: string,
) {
this._negated = ContextKeyInExpr.create(key, valueKey);
}
public cmp(other: ContextKeyExpression): number {
if (other.type !== this.type) {
return this.type - other.type;
}
return this._negated.cmp(other._negated);
}
public equals(other: ContextKeyExpression): boolean {
if (other.type === this.type) {
return this._negated.equals(other._negated);
}
return false;
}
public substituteConstants(): ContextKeyExpression | undefined {
return this;