-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathparser.ts
1790 lines (1642 loc) · 62.4 KB
/
parser.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
//-----------------------------------------------------------
// Parser
//-----------------------------------------------------------
import * as commonmark from "commonmark";
import * as chev from "chevrotain";
import {parserErrors, EveError} from "./errors";
var {Lexer, tokenMatcher} = chev;
export var Token = chev.Token;
import * as uuid from "uuid";
//-----------------------------------------------------------
// Utils
//-----------------------------------------------------------
function cleanString(str:string) {
let cleaned = str
.replace(/\\n/g, "\n")
.replace(/\\t/g, "\t")
.replace(/\\r/g, "\r")
.replace(/\\"/g, "\"")
.replace(/\\{/g, "{")
.replace(/\\}/g, "}");
return cleaned;
}
function toEnd(node:any) {
if(node && node.tokenType !== undefined) {
return node.endOffset! + 1;
}
return node.endOffset;
}
//-----------------------------------------------------------
// Markdown
//-----------------------------------------------------------
let markdownParser = new commonmark.Parser();
function parseMarkdown(markdown: string, docId: string) {
let parsed = markdownParser.parse(markdown);
let walker = parsed.walker();
var cur;
let tokenId = 0;
var text = [];
var extraInfo:any = {};
var pos = 0;
var lastLine = 1;
var spans = [];
var context = [];
var blocks = [];
while(cur = walker.next()) {
let node = cur.node as any;
if(cur.entering) {
while(node.sourcepos && node.sourcepos[0][0] > lastLine) {
lastLine++;
pos++;
text.push("\n");
}
if(node.type !== "text") {
context.push({node, start: pos});
}
if(node.type == "text" || node.type === "code_block" || node.type == "code") {
text.push(node.literal);
pos += node.literal.length;
}
if(node.type == "softbreak") {
text.push("\n");
pos += 1;
lastLine++;
context.pop();
}
if(node.type == "code_block") {
let spanId = `${docId}|block|${tokenId++}`;
let start = context.pop()!.start;
node.id = spanId;
node.startOffset = start;
let type = node.type;
if(!(node as any)._isFenced) {
type = "indented_code_block";
} else {
blocks.push(node);
}
spans.push(start, pos, node.type, spanId);
lastLine = node.sourcepos[1][0] + 1;
}
if(node.type == "code") {
let spanId = `${docId}|${tokenId++}`;
let start = context.pop()!.start;
spans.push(start, pos, node.type, spanId);
}
} else {
let info = context.pop()!;
if(node !== info.node) {
throw new Error("Common mark is exiting a node that doesn't agree with the context stack");
}
if(node.type == "emph" || node.type == "strong" || node.type == "link") {
let spanId = `${docId}|${tokenId++}`;
spans.push(info.start, pos, node.type, spanId);
if(node.type === "link") {
extraInfo[spanId] = {destination: node._destination};
}
} else if(node.type == "heading" || node.type == "item") {
let spanId = `${docId}|${tokenId++}`;
spans.push(info.start, info.start, node.type, spanId);
extraInfo[spanId] = {level: node._level, listData: node._listData};
}
}
}
return {text: text.join(""), spans, blocks, extraInfo};
}
//-----------------------------------------------------------
// Tokens
//-----------------------------------------------------------
const breakChars = "@#\\.,\\(\\)\\[\\]\\{\\}⦑⦒:\\\"";
// Markdown
export class DocContent extends Token { static PATTERN = /[^\n]+/; }
export class Fence extends Token {
static PATTERN = /```|~~~/;
static PUSH_MODE = "code";
}
export class CloseFence extends Token {
static PATTERN = /```|~~~/;
static POP_MODE = true;
}
// Comments
export class CommentLine extends Token { static PATTERN = /\/\/.*\n/; label = "comment"; static GROUP = "comments"; }
// Operators
export class Equality extends Token { static PATTERN = /:|=/; label = "equality"; }
export class Comparison extends Token { static PATTERN = />=|<=|!=|>|</; label = "comparison"; }
export class AddInfix extends Token { static PATTERN = /\+|-/; label = "infix"; }
export class MultInfix extends Token { static PATTERN = /\*|\//; label = "infix"; }
export class Merge extends Token { static PATTERN = /<-/; label = "merge"; }
export class Set extends Token { static PATTERN = /:=/; label = "set"; }
export class Mutate extends Token { static PATTERN = /\+=|-=/; label = "mutate"; }
export class Dot extends Token { static PATTERN = /\./; label = "dot"; }
export class Pipe extends Token { static PATTERN = /\|/; label = "pipe"; }
// Identifier
export class Identifier extends Token { static PATTERN = new RegExp(`([\\+-/\\*][^\\s${breakChars}]+|[^\\d${breakChars}\\+-/\\*][^\\s${breakChars}]*)(?=[^\\[])`); label = "identifier"; }
export class FunctionIdentifier extends Token { static PATTERN = new RegExp(`([\\+-/\\*][^\\s${breakChars}]+|[^\\d${breakChars}\\+-/\\*][^\\s${breakChars}]*)(?=\\[)`); label = "functionIdentifier"; }
// Keywords
export class Keyword extends Token {
static PATTERN = Lexer.NA;
static LONGER_ALT = Identifier;
}
export class Lookup extends Keyword { static PATTERN = /lookup(?=\[)/; label = "lookup"; }
export class Action extends Keyword { static PATTERN = /bind|commit/; label = "action"; }
export class Search extends Keyword { static PATTERN = /search/; label = "search"; }
export class If extends Keyword { static PATTERN = /if/; label = "if"; }
export class Else extends Keyword { static PATTERN = /else/; label = "else"; }
export class Then extends Keyword { static PATTERN = /then/; label = "then"; }
export class Not extends Keyword { static PATTERN = /not/; label = "not"; }
// Values
export class Bool extends Keyword { static PATTERN = /true|false/; label = "bool"; }
export class Num extends Token { static PATTERN = /-?\d+(\.\d+)?/; label = "num"; }
export class None extends Keyword { static PATTERN = /none/; label = "none"; }
export class Name extends Token { static PATTERN = /@/; label = "name"; }
export class Tag extends Token { static PATTERN = /#/; label = "tag"; }
// Delimiters
export class OpenBracket extends Token { static PATTERN = /\[/; label = "open-bracket"; }
export class CloseBracket extends Token { static PATTERN = /\]/; label = "close-bracket"; }
export class OpenParen extends Token { static PATTERN = /\(/; label = "open-paren"; }
export class CloseParen extends Token { static PATTERN = /\)/; label = "close-paren"; }
// Strings
export class StringChars extends Token { static PATTERN = /(\\.|{(?=[^{])|[^"\\{])+/; label = "string"; }
export class OpenString extends Token {
static PATTERN = /"/;
static PUSH_MODE = "string";
label = "quote";
}
export class CloseString extends Token {
static PATTERN = /"/;
static POP_MODE = true;
label = "quote";
}
// String Embeds
export class StringEmbedOpen extends Token {
static PATTERN = /{{/;
static PUSH_MODE = "code";
label = "string-embed-open";
}
export class StringEmbedClose extends Token {
static PATTERN = /}}/;
static POP_MODE = true;
label = "string-embed-close";
}
// Whitespace
export class WhiteSpace extends Token {
static PATTERN = /\s+|,/;
static GROUP = Lexer.SKIPPED;
}
//-----------------------------------------------------------
// Lexers
//-----------------------------------------------------------
let codeTokens: any[] = [
CloseFence, WhiteSpace, CommentLine, OpenBracket, CloseBracket, OpenParen,
CloseParen, StringEmbedClose, OpenString, Bool, Action, Set, Equality, Dot, Pipe, Merge,
Mutate, Comparison, Num, Search, Lookup, If, Else, Then,
Not, None, Name, Tag, FunctionIdentifier, Identifier, AddInfix, MultInfix
];
let stringEmbedTokens: any[] = [StringEmbedClose].concat(codeTokens);
let LexerModes:any = {
"doc": [WhiteSpace, Fence, DocContent],
"code": codeTokens,
"string": [CloseString, StringEmbedOpen, StringChars],
// "stringEmbed": stringEmbedTokens,
};
let allTokens: any[] = codeTokens.concat([Fence, DocContent, CloseString, StringEmbedOpen, StringEmbedClose, StringChars]);
let EveDocLexer = new Lexer({modes: LexerModes, defaultMode: "doc"});
let EveBlockLexer = new Lexer({modes: LexerModes, defaultMode: "code"});
//-----------------------------------------------------------
// Parse Nodes
//-----------------------------------------------------------
export type NodeDependent = chev.IToken | ParseNode;
export interface ParseNode {
type?: string
id?: string
startOffset?: number,
endOffset?: number,
from: NodeDependent[]
[property: string]: any
}
export class ParseBlock {
id: string;
start: number;
nodeId = 0;
variables: {[name: string]: ParseNode} = {};
equalities: any[] = [];
scanLike: ParseNode[] = [];
expressions: ParseNode[] = [];
binds: ParseNode[] = [];
commits: ParseNode[] = [];
variableLookup: {[name: string]: ParseNode};
links: string[] = [];
tokens: chev.Token[];
searchScopes: string[] = [];
parent: ParseBlock | undefined;
constructor(id:string, variableLookup?:any) {
this.id = id;
this.variableLookup = variableLookup || {};
}
toVariable(name:string, generated = false) {
let variable = this.variableLookup[name];
if(!variable) {
this.variableLookup[name] = this.makeNode("variable", {name, from: [], generated});
}
variable = this.variables[name] = this.variableLookup[name];
return {id: variable.id, type: "variable", name, from: [], generated};
}
addUsage(variable:any, usage:any) {
let global = this.variableLookup[variable.name];
global.from.push(usage)
if(global.from.length === 1) {
global.startOffset = usage.startOffset;
global.endOffset = toEnd(usage);
}
variable.from.push(usage);
variable.startOffset = usage.startOffset;
variable.endOffset = toEnd(usage);
this.links.push(variable.id, usage.id);
}
equality(a:any, b:any) {
this.equalities.push([a, b]);
}
commit(node: ParseNode) {
this.commits.push(node);
}
bind(node: ParseNode) {
this.binds.push(node);
}
expression(node: ParseNode) {
this.expressions.push(node);
}
scan(node: ParseNode) {
this.scanLike.push(node);
}
makeNode(type:any, node: ParseNode) {
if(!node.id) {
node.id = `${this.id}|node|${this.nodeId++}`;
}
for(let from of node.from as any[]) {
this.links.push(node.id, from.id);
}
if(node.from.length) {
node.startOffset = node.from[0].startOffset;
node.endOffset = toEnd(node.from[node.from.length - 1]);
}
node.type = type;
return node;
}
addSearchScopes(scopes: string[]) {
for(let scope of scopes) {
if(this.searchScopes.indexOf(scope) === -1) {
this.searchScopes.push(scope);
}
}
}
subBlock() {
let neue = new ParseBlock(`${this.id}|sub${this.nodeId++}`, this.variableLookup);
neue.parent = this;
return neue;
}
}
//-----------------------------------------------------------
// Parser
//-----------------------------------------------------------
export class Parser extends chev.Parser {
customErrors: any[];
block: ParseBlock;
activeScopes: string[];
currentAction: string;
// Parser patterns
doc: any;
codeBlock: any;
fencedBlock: any;
section: any;
searchSection: any;
actionSection: any;
value: any;
bool: any;
num: any;
scopeDeclaration: any;
name: any;
statement: any;
expression: any;
attribute: any;
attributeEquality: any;
attributeComparison: any;
attributeNot: any;
attributeOperation: any;
record: any;
tag: any;
functionRecord: any;
notStatement: any;
comparison: any;
infix: any;
attributeAccess: any;
actionStatement: any;
actionEqualityRecord: any;
actionAttributeExpression: any;
actionOperation: any;
actionLookup: any;
variable: any;
recordOperation: any;
ifExpression: any;
ifBranch: any;
elseIfBranch: any;
elseBranch: any;
multiplication: any;
addition: any;
infixValue: any;
parenthesis: any;
attributeMutator: any;
singularAttribute: any;
stringInterpolation: any;
constructor(input:any) {
super(input, allTokens, {});
let self = this;
let asValue = (node:any) => {
if(node.type === "constant" || node.type === "variable" || node.type === "parenthesis") {
return node;
} else if(node.variable) {
return node.variable;
}
throw new Error("Tried to get value of a node that is neither a constant nor a variable.\n\n" + JSON.stringify(node));
}
let ifOutputs = (expression:any) => {
let outputs = [];
if(expression.type === "parenthesis") {
for(let item of expression.items) {
outputs.push(asValue(item));
}
} else {
outputs.push(asValue(expression));
}
return outputs;
}
let makeNode = (type:string, node:any) => {
return self.block.makeNode(type, node);
}
let blockStack:any[] = [];
let pushBlock = (blockId?:string) => {
let block;
let prev = blockStack[blockStack.length - 1];
if(prev) {
block = prev.subBlock();
} else {
block = new ParseBlock(blockId || "block");
}
blockStack.push(block);
self.block = block;
return block;
}
let popBlock = () => {
let popped = blockStack.pop();
self.block = blockStack[blockStack.length - 1];
return popped;
}
//-----------------------------------------------------------
// Doc rules
//-----------------------------------------------------------
self.RULE("doc", () => {
let doc = {
full: [] as any[],
content: [] as any[],
blocks: [] as any[],
}
self.MANY(() => {
self.OR([
{ALT: () => {
let content = self.CONSUME(DocContent);
doc.full.push(content);
doc.content.push(content);
}},
{ALT: () => {
let block : any = self.SUBRULE(self.fencedBlock);
if(doc.content.length) {
block.name = doc.content[doc.content.length - 1].image;
} else {
block.name = "Unnamed block";
}
doc.full.push(block);
doc.blocks.push(block);
}},
])
});
return doc;
});
self.RULE("fencedBlock", () => {
self.CONSUME(Fence);
let block = self.SUBRULE(self.codeBlock);
let fence = self.CONSUME(CloseFence);
return block;
});
//-----------------------------------------------------------
// Blocks
//-----------------------------------------------------------
self.RULE("codeBlock", (blockId = "block") => {
blockStack = [];
let block = pushBlock(blockId);
self.MANY(() => { self.SUBRULE(self.section) })
return popBlock();
})
self.RULE("section", () => {
return self.OR([
{ALT: () => { return self.SUBRULE(self.searchSection) }},
{ALT: () => { return self.SUBRULE(self.actionSection) }},
{ALT: () => { return self.CONSUME(CommentLine); }},
]);
});
//-----------------------------------------------------------
// Scope declaration
//-----------------------------------------------------------
self.RULE("scopeDeclaration", () => {
let scopes:any[] = [];
self.OR([
{ALT: () => {
self.CONSUME(OpenParen);
self.AT_LEAST_ONE(() => {
let name: any = self.SUBRULE(self.name);
scopes.push(name.name);
})
self.CONSUME(CloseParen);
}},
{ALT: () => {
self.AT_LEAST_ONE2(() => {
let name: any = self.SUBRULE2(self.name);
scopes.push(name.name);
})
}},
]);
return scopes;
});
//-----------------------------------------------------------
// Search section
//-----------------------------------------------------------
self.RULE("searchSection", () => {
// @TODO fill in from
let from:any[] = [];
self.CONSUME(Search);
let scopes:any = ["session"];
self.OPTION(() => { scopes = self.SUBRULE(self.scopeDeclaration) })
self.activeScopes = scopes;
self.currentAction = "match";
self.block.addSearchScopes(scopes);
let statements:any[] = [];
self.MANY(() => {
let statement: any = self.SUBRULE(self.statement);
if(statement) {
statements.push(statement);
statement.scopes = scopes;
}
});
return makeNode("searchSection", {statements, scopes, from});
});
self.RULE("statement", () => {
return self.OR([
{ALT: () => { return self.SUBRULE(self.comparison); }},
{ALT: () => { return self.SUBRULE(self.notStatement); }},
])
});
//-----------------------------------------------------------
// Action section
//-----------------------------------------------------------
self.RULE("actionSection", () => {
// @TODO fill in from
let from:any[] = [];
let action = self.CONSUME(Action).image;
let actionKey = action;
let scopes:any = ["session"];
self.OPTION(() => { scopes = self.SUBRULE(self.scopeDeclaration) })
self.activeScopes = scopes;
self.currentAction = action!;
let statements:any[] = [];
self.MANY(() => {
let statement = self.SUBRULE(self.actionStatement, [actionKey]) as any;
if(statement) {
statements.push(statement);
statement.scopes = scopes;
}
});
return makeNode("actionSection", {statements, scopes, from});
});
self.RULE("actionStatement", (actionKey) => {
return self.OR([
{ALT: () => {
let record = self.SUBRULE(self.record, [false, actionKey, "+="]);
return record;
}},
{ALT: () => { return self.SUBRULE(self.actionEqualityRecord, [actionKey]); }},
{ALT: () => {
let record = self.SUBRULE(self.actionOperation, [actionKey]);
(self.block as any)[actionKey](record);
return record;
}},
{ALT: () => { return self.SUBRULE(self.actionLookup, [actionKey]); }},
])
});
//-----------------------------------------------------------
// Action operations
//-----------------------------------------------------------
self.RULE("actionOperation", (actionKey) => {
return self.OR([
{ALT: () => { return self.SUBRULE(self.recordOperation, [actionKey]) }},
{ALT: () => { return self.SUBRULE(self.attributeOperation, [actionKey]) }},
]);
});
self.RULE("attributeOperation", (actionKey) => {
let mutator = self.SUBRULE(self.attributeMutator) as any;
let {attribute, parent} = mutator;
return self.OR([
{ALT: () => {
let variable = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true);
let scan = makeNode("scan", {entity: parent, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value: variable, scopes: self.activeScopes, from: [mutator]});
self.block.addUsage(variable, scan);
self.block.scan(scan);
self.CONSUME(Merge);
let record = self.SUBRULE(self.record, [true, actionKey, "+=", undefined, variable]) as any;
record.variable = variable;
record.action = "<-";
return record;
}},
{ALT: () => {
let op = self.CONSUME(Set);
let none = self.CONSUME(None);
return makeNode("action", {action: "erase", entity: asValue(parent), attribute: attribute.image, from: [mutator, op, none]});
}},
{ALT: () => {
let op = self.CONSUME2(Set);
let value = self.SUBRULE(self.infix);
return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]});
}},
{ALT: () => {
let op = self.CONSUME3(Set);
let value = self.SUBRULE2(self.record, [false, actionKey, "+=", parent]);
return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]});
}},
{ALT: () => {
let variable = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true);
let scan = makeNode("scan", {entity: parent, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value: variable, scopes: self.activeScopes, from: [mutator]});
self.block.addUsage(variable, scan);
self.block.scan(scan);
let op = self.CONSUME(Mutate);
let tag : any = self.SUBRULE(self.tag);
return makeNode("action", {action: op.image, entity: variable, attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [mutator, op, tag]});
}},
{ALT: () => {
let op = self.CONSUME2(Mutate);
let value: any = self.SUBRULE2(self.actionAttributeExpression, [actionKey, op.image, parent]);
if(value.type === "record" && !value.extraProjection) {
value.extraProjection = [parent];
}
if(value.type === "parenthesis") {
let autoIndex = 0;
for(let item of value.items) {
if(item.type === "record" && !value.extraProjection) {
item.extraProjection = [parent];
}
if(item.from[0] && item.from[0].type === "record") {
let record = item.from[0];
record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]}));
autoIndex++;
}
}
}
return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]});
}},
])
});
self.RULE("recordOperation", (actionKey) => {
let variable = self.SUBRULE(self.variable) as any;
return self.OR([
{ALT: () => {
let set = self.CONSUME(Set);
let none = self.CONSUME(None);
return makeNode("action", {action: "erase", entity: asValue(variable), from: [variable, set, none]});
}},
{ALT: () => {
self.CONSUME(Merge);
let record = self.SUBRULE(self.record, [true, actionKey, "+=", undefined, variable]) as any;
record.needsEntity = true;
record.action = "<-";
return record;
}},
{ALT: () => {
let op = self.CONSUME(Mutate);
let tag : any = self.SUBRULE(self.tag);
return makeNode("action", {action: op.image, entity: asValue(variable), attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [variable, op, tag]});
}},
])
});
self.RULE("actionLookup", (actionKey) => {
let lookup = self.CONSUME(Lookup);
let record: any = self.SUBRULE(self.record, [true]);
let info: any = {};
for(let attribute of record.attributes) {
info[attribute.attribute] = attribute.value;
}
let actionType = "+=";
self.OPTION(() => {
self.CONSUME(Set);
self.CONSUME(None);
if(info["value"] !== undefined) {
actionType = "-=";
} else {
actionType = "erase";
}
})
let action = makeNode("action", {action: actionType, entity: info.record, attribute: info.attribute, value: info.value, node: info.node, scopes: self.activeScopes, from: [lookup, record]});
(self.block as any)[actionKey](action);
return action;
});
self.RULE("actionAttributeExpression", (actionKey, action, parent) => {
return self.OR([
{ALT: () => { return self.SUBRULE(self.record, [false, actionKey, action, parent]); }},
{ALT: () => { return self.SUBRULE(self.infix); }},
])
})
self.RULE("actionEqualityRecord", (actionKey) => {
let variable = self.SUBRULE(self.variable);
self.CONSUME(Equality);
let record : any = self.SUBRULE(self.record, [true, actionKey, "+="]);
record.variable = variable;
(self.block as any)[actionKey](record);
return record;
});
//-----------------------------------------------------------
// Record + attribute
//-----------------------------------------------------------
self.RULE("record", (noVar = false, blockKey = "scan", action = false, parent?, passedVariable?) => {
let attributes:any[] = [];
let start = self.CONSUME(OpenBracket);
let from: NodeDependent[] = [start];
let info: any = {attributes, action, scopes: self.activeScopes, from};
if(parent) {
info.extraProjection = [parent];
}
if(passedVariable) {
info.variable = passedVariable;
info.variable.nonProjecting = true;
} else if(!noVar) {
info.variable = self.block.toVariable(`record|${start.startLine}|${start.startColumn}`, true);
info.variable.nonProjecting = true;
}
let nonProjecting = false;
self.MANY(() => {
self.OR([
{ALT: () => {
let attribute: any = self.SUBRULE(self.attribute, [false, blockKey, action, info.variable]);
// Inline handles attributes itself and so won't return any attribute for us to add
// to this object
if(!attribute) return;
if(attribute.constructor === Array) {
for(let attr of attribute as any[]) {
attr.nonProjecting = nonProjecting;
attributes.push(attr);
from.push(attr);
}
} else {
attribute.nonProjecting = nonProjecting;
attributes.push(attribute);
from.push(attribute);
}
}},
{ALT: () => {
nonProjecting = true;
let pipe = self.CONSUME(Pipe);
from.push(pipe);
return pipe;
}},
]);
})
from.push(self.CONSUME(CloseBracket));
let record : any = makeNode("record", info);
if(!noVar) {
self.block.addUsage(info.variable, record);
(self.block as any)[blockKey](record);
}
return record;
});
self.RULE("attribute", (noVar, blockKey, action, recordVariable) => {
return self.OR([
{ALT: () => { return self.SUBRULE(self.attributeEquality, [noVar, blockKey, action, recordVariable]); }},
{ALT: () => { return self.SUBRULE(self.attributeComparison); }},
{ALT: () => { return self.SUBRULE(self.attributeNot, [recordVariable]); }},
{ALT: () => { return self.SUBRULE(self.singularAttribute); }},
{ALT: () => {
let value: any = self.SUBRULE(self.value);
let token = value.from[0];
let message = "Value missing attribute";
if (value.hasOwnProperty("value")) {
message = `"${value.value}" needs to be labeled with an attribute`;
}
self.customErrors.push({
message,
name: "Unlabeled value",
resyncedTokens: [],
context: {
ruleOccurrenceStack: [],
ruleStack: []
},
token
});
}},
]);
});
self.RULE("singularAttribute", (forceGenerate) => {
return self.OR([
{ALT: () => {
let tag : any = self.SUBRULE(self.tag);
return makeNode("attribute", {attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [tag]});
}},
{ALT: () => {
let variable : any = self.SUBRULE(self.variable, [forceGenerate]);
return makeNode("attribute", {attribute: variable.from[0].image, value: variable, from: [variable]});
}},
]);
});
self.RULE("attributeMutator", () => {
let scans:any[] = [];
let entity:any, attribute:any, value:any;
let needsEntity = true;
let from:any[] = [];
entity = self.SUBRULE(self.variable);
let dot = self.CONSUME(Dot);
from.push(entity, dot);
self.MANY(() => {
attribute = self.CONSUME(Identifier);
from.push(attribute);
from.push(self.CONSUME2(Dot));
value = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true);
self.block.addUsage(value, attribute);
let scopes = self.activeScopes;
if(self.currentAction !== "match") {
scopes = self.block.searchScopes;
}
let scan = makeNode("scan", {entity, attribute: makeNode("constant", {value: attribute.image, from: [value]}), value, needsEntity, scopes, from: [entity, dot, attribute]});
self.block.scan(scan);
needsEntity = false;
entity = value;
});
attribute = self.CONSUME2(Identifier);
from.push(attribute);
return makeNode("attributeMutator", {attribute: attribute, parent: entity, from});
});
self.RULE("attributeAccess", () => {
let scans:any[] = [];
let entity:any, attribute:any, value:any;
let needsEntity = true;
entity = self.SUBRULE(self.variable);
let parentId = entity.name;
self.AT_LEAST_ONE(() => {
let dot = self.CONSUME(Dot);
attribute = self.CONSUME(Identifier);
parentId = `${parentId}|${attribute.image}`;
value = self.block.toVariable(parentId, true);
self.block.addUsage(value, attribute);
let scopes = self.activeScopes;
if(self.currentAction !== "match") {
scopes = self.block.searchScopes;
}
let scan = makeNode("scan", {entity, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value, needsEntity, scopes, from: [entity, dot, attribute]});
self.block.scan(scan);
needsEntity = false;
entity = value;
});
return value;
});
self.RULE("attributeEquality", (noVar, blockKey, action, parent) => {
let attributes:any[] = [];
let autoIndex = 1;
let attributeNode:any;
let attribute: any = self.OR([
{ALT: () => {
attributeNode = self.CONSUME(Identifier);
return attributeNode.image;
}},
{ALT: () => {
attributeNode = self.CONSUME(Num);
return parseFloat(attributeNode.image) as any;
}}
]);
let equality = self.CONSUME(Equality);
let result : any;
self.OR2([
{ALT: () => {
result = self.SUBRULE(self.infix);
// if the result is a parenthesis, we have to make sure that if there are sub-records
// inside that they get eve-auto-index set on them and they also have the parent transfered
// down to them. If we don't do this, we'll end up with children that are shared between
// the parents instead of one child per parent.
if(result.type === "parenthesis") {
for(let item of result.items) {
// this is a bit sad, but by the time we see the parenthesis, the records have been replaced
// with their variables. Those variables are created from the record object though, so we can
// check the from of the variable for a reference to the record.
if(item.type === "variable" && item.from[0] && item.from[0].type === "record") {
let record = item.from[0];
// if we have a parent, we need to make sure it ends up part of our extraProjection set
if(parent && !item.extraProjection) {
record.extraProjection = [parent];
} else if(parent) {
record.extraProjection.push(parent);
}
// Lastly we need to add the eve-auto-index attribute to make sure this is consistent with the case
// where we leave the parenthesis off and just put records one after another.
record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]}));
autoIndex++;
}
}
}
}},
{ALT: () => {
result = self.SUBRULE(self.record, [noVar, blockKey, action, parent]);
self.MANY(() => {
autoIndex++;
let record : any = self.SUBRULE2(self.record, [noVar, blockKey, action, parent]);
record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]}));
attributes.push(makeNode("attribute", {attribute, value: asValue(record), from: [attributeNode, equality, record]}));
})
if(autoIndex > 1) {
result.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: 1, from: [result]}), from: [result]}));
}
}},
]);
attributes.push(makeNode("attribute", {attribute, value: asValue(result), from: [attributeNode, equality, result]}))
return attributes;
});
self.RULE("attributeComparison", () => {
let attribute = self.CONSUME(Identifier);
let comparator = self.CONSUME(Comparison);
let result = self.SUBRULE(self.expression);
let variable = self.block.toVariable(`attribute|${attribute.startLine}|${attribute.startColumn}`, true);
let expression = makeNode("expression", {op: `compare/${comparator.image}`, args: [asValue(variable), asValue(result)], from: [attribute, comparator, result]})
self.block.addUsage(variable, expression);
self.block.expression(expression);
return makeNode("attribute", {attribute: attribute.image, value: variable, from: [attribute, comparator, expression]});
});
self.RULE("attributeNot", (recordVariable) => {
let block = pushBlock();
block.type = "not";
let not = self.CONSUME(Not);
let start = self.CONSUME(OpenParen);
let attribute: any = self.OR([
{ALT: () => { return self.SUBRULE(self.attributeComparison); }},
{ALT: () => { return self.SUBRULE(self.singularAttribute, [true]); }},
]);
let end = self.CONSUME(CloseParen);
// we have to add a record for this guy
let scan : any = makeNode("scan", {entity: recordVariable, attribute: makeNode("constant", {value: attribute.attribute, from: [attribute]}), value: attribute.value, needsEntity: true, scopes: self.activeScopes, from: [attribute]});
block.variables[recordVariable.name] = recordVariable;
block.scan(scan);
block.from = [not, start, attribute, end];
block.startOffset = not.startOffset;
block.endOffset = toEnd(end);
popBlock();
self.block.scan(block);
return;
});
//-----------------------------------------------------------
// Name and tag
//-----------------------------------------------------------
self.RULE("name", () => {
let at = self.CONSUME(Name);
let name = self.CONSUME(Identifier);
self.customErrors.push({message: `Databases have been deprecated, so @${name.image} has no meaning here`, name: "Database deprecation", resyncedTokens: [], context:{ruleOccurrenceStack: [], ruleStack: []}, token:name})
return makeNode("name", {name: name.image, from: [at, name]});
});
self.RULE("tag", () => {
let hash = self.CONSUME(Tag);
let tag = self.CONSUME(Identifier);
return makeNode("tag", {tag: tag.image, from: [hash, tag]});
});
//-----------------------------------------------------------
// Function
//-----------------------------------------------------------