This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
parser.js
765 lines (692 loc) · 16 KB
/
parser.js
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
/*
* Copyright (c) 2015-2016, Salesforce.com, Inc.
* All rights reserved.
* Licensed under the MIT license.
* For full license text, see LICENSE.md file in the repo root or
* https://opensource.org/licenses/MIT
*/
'use strict';
let errors = require('./errors.js');
let Source = require('./source.js');
let Parsimmon = require('parsimmon');
////////// Helpers //////////
// Calls anonymous function immediatey. Used to make clear when anonymous
// functions are used only for scoping, as in the following example:
// let x = call(function() {
// let tmp = 3;
// return tmp * tmp;
// });
let call = function(fn) {
return fn();
};
// Like .mark() except puts start and end in a 'source' attribute hanging off value.
// The 'input' attribute of the Source values is set later in parse().
Parsimmon.Parser.prototype.source = function() {
return Parsimmon.Parser.prototype.mark.call(this).map((marked) => {
marked.value.source = new Source(marked.start, marked.end);
return marked.value;
});
};
// Case-insensitive string match that's not followed by a word character. The
// latter check is what prevents two keywords from slamming into each other with
// no intervening spaces or things like ifFalse (see issue #16: "Whitespace is
// incorrectly ignored by the parser for lexemes").
let istring = function(str) {
let len = str.length;
let expected = "'" + str + "'";
str = str.toLowerCase();
return Parsimmon.custom(function(success, failure) {
return function(stream, i) {
let head = stream.slice(i, i + len);
let next = stream.charAt(i + len);
if (head.toLowerCase() === str && next.match(/\w/) === null) {
return success(i + len, head);
} else {
return failure(i, expected);
}
};
});
};
let alt = Parsimmon.alt;
let lazy = Parsimmon.lazy;
let regex = Parsimmon.regex;
let sepBy = Parsimmon.sepBy;
let sepBy1 = Parsimmon.sepBy1;
let seqMap = Parsimmon.seqMap;
let string = Parsimmon.string;
let whitespace = Parsimmon.whitespace;
let sepByOptTrail = function(content, separator) {
return sepBy(content, separator)
.skip(separator.or(Parsimmon.succeed()));
};
let sepBy1OptTrail = function(content, separator) {
return sepBy1(content, separator)
.skip(separator.or(Parsimmon.succeed()));
};
let comment = call(function() {
let eolComment = regex(/\/\/[^\n]*/); // this kind
let multilineComment = Parsimmon.custom(function(success, failure) {
return function(stream, i) {
if (stream.slice(i, i + 2) === '/*') {
for (let j = i + 2; j + 2 <= stream.length; ++j) {
if (stream.slice(j, j + 2) === '*/') {
return success(j + 2, 'multi-line comment');
}
}
return failure(i, "'*/'");
} else {
return failure(i, "'/*'");
}
};
});
return eolComment
.or(multilineComment)
.desc('comment');
});
let lexeme = function(p) {
return p.skip(whitespace.or(comment).many());
};
let arrow = lexeme(string('->'));
let bang = lexeme(string('!'));
let colon = lexeme(string(':'));
let comma = lexeme(string(','));
let dot = lexeme(string('.'));
let dots = lexeme(string('..'));
let doubleAnd = lexeme(string('&&'));
let doubleArrow = lexeme(string('=>'));
let doubleEquals = lexeme(string('=='));
let doublePipe = lexeme(string('||'));
let equals = lexeme(string('='));
let langle = lexeme(string('<'));
let lbrace = lexeme(string('{'));
let lbracket = lexeme(string('['));
let leq = lexeme(string('<='));
let lparen = lexeme(string('('));
let minus = lexeme(string('-'));
let minusEquals = lexeme(string('-='));
let percent = lexeme(string('%'));
let percentEquals = lexeme(string('%='));
let neq = lexeme(string('!='));
let plus = lexeme(string('+'));
let plusEquals = lexeme(string('+='));
let rangle = lexeme(string('>'));
let rbrace = lexeme(string('}'));
let rbracket = lexeme(string(']'));
let req = lexeme(string('>='));
let rparen = lexeme(string(')'));
let semicolon = lexeme(string(';'));
let slash = lexeme(string('/'));
let slashEquals = lexeme(string('/='));
let star = lexeme(string('*'));
let starEquals = lexeme(string('*='));
let keywordList = [
'as',
'assert',
'break',
'continue',
'either',
'else',
'external',
'for',
'function',
'if',
'in',
'invariant',
'match',
'node',
'param',
'print',
'record',
'reset',
'return',
'rule',
'type',
'var',
'while',
];
let keywords = {};
keywordList.forEach((keyword) => {
keywords[keyword] = lexeme(istring(keyword));
});
let numberWithUnit = call(function() {
let re = /([0-9]+)([a-z]+)/i;
return lexeme(regex(re))
.map((s) => {
let result = re.exec(s);
return {
kind: 'numberWithUnit',
number: result[1],
unit: result[2],
};
})
.source()
.desc('number with unit');
});
let number = lexeme(regex(/[0-9]+/).map(parseInt)).desc('number').map((v) => ({
kind: 'number',
value: v,
})).source();
let id = lexeme(regex(/[a-z_]\w*/i)).desc('identifier').map((v) => ({
kind: 'id',
value: v,
})).source();
////////// Expressions //////////
let lhs = call(function() {
let lhsmore = lazy(() => alt(
seqMap(lbracket,
expr,
rbracket,
(_, expr, _2) => ({
kind: 'index',
by: expr,
})),
seqMap(dot,
id,
(_, id) => ({
kind: 'lookup',
child: id,
}))));
let lhshelper = function(lhsparent, more) {
if (more.length == 0) {
return lhsparent;
}
let ret = more.shift(0);
ret.parent = lhsparent;
return lhshelper(ret, more);
};
return seqMap(id,
lhsmore.many(),
lhshelper);
});
let expr = call(function() {
let group = lazy(() => {
return lparen.then(expr).skip(rparen);
});
let expr0 = lazy(() => alt(
numberWithUnit,
number,
recordvalue,
group,
seqMap(id,
lparen,
sepBy(expr, comma),
rparen,
(func, _, args, _2) => ({
kind: 'apply',
func: func,
args: args,
})),
seqMap(generic,
lparen,
sepBy(expr, comma),
rparen,
(generic, _, args, _2) => ({
kind: 'apply',
func: generic.base,
genericargs: generic.args,
args: args,
})),
lhs));
let expr1 = lazy(() => alt(
seqMap(bang.mark(),
expr0,
(bang, v) => ({
kind: 'apply',
func: bang,
args: [v]
})).source(),
expr0));
// Order of parsers in this table defines precedence.
let binop = [
alt(star, slash, percent),
alt(plus, minus),
alt(leq, req, langle, rangle),
alt(neq, doubleEquals),
doubleAnd,
doublePipe,
];
// This parser is "(exprprev op exprcurr) | (exprprev)", just rewritten as
// "exprprev [op exprcurr]" to be more efficient.
let makeBinopParser = (exprprev, ops, exprcurr) => seqMap(
exprprev,
seqMap(
ops.mark(),
exprcurr,
(op, right) => ((left) => ({
kind: 'apply',
func: op,
args: [left, right]
}))).times(0, 1),
(left, rest) => {
if (rest.length == 0) {
return left;
} else {
return rest[0](left);
}
}).source();
let expr3 = binop.reduce((exprprev, ops) => {
let exprcurr = lazy(() => makeBinopParser(exprprev, ops, exprcurr));
return exprcurr;
}, expr1);
return expr3.desc('expression');
});
////////// Types //////////
let range = seqMap(expr, dots, expr,
(low, _, high) => ({
kind: 'range',
low: low,
high: high
})).source();
let fieldlist = call(function() {
let field = lazy(() => seqMap(
id,
colon,
complexType.or(type),
(id, _, type) => ({
id: id,
type: type
})));
return sepByOptTrail(field, comma).map((fields) => ({
kind: 'record',
fields: fields
}));
});
let recordvalue = call(function() {
let fieldvalue = lazy(() => seqMap(
id,
colon,
expr,
(id, _, expr) => ({
id: id,
expr: expr,
})));
return seqMap(id,
lbrace,
sepByOptTrail(fieldvalue, comma),
rbrace,
(id, _, fields, _2) => ({
kind: 'recordvalue',
type: id,
fields: fields,
}));
});
let record = alt(keywords.node, keywords.record)
.skip(lbrace)
.then(fieldlist)
.skip(rbrace);
let either = call(function() {
let eitherfield = seqMap(id,
lbrace,
fieldlist,
rbrace,
(id, _, fields, _2) => ({
id: id,
type: fields,
})).or(id.map((id) => ({
id: id,
kind: 'enumvariant',
})));
let eitherfieldlist = sepBy1OptTrail(eitherfield, comma);
return keywords.either
.skip(lbrace)
.then(eitherfieldlist.map((fields) => ({
kind: 'either',
fields: fields
})))
.skip(rbrace).source();
});
let generic = lazy(() => seqMap(id,
langle,
type,
rangle,
(base, _, arg, _2) => ({
kind: 'generic',
base: base,
args: [arg],
})));
let genericIndexable = lazy(() => seqMap(generic,
lbracket,
type,
rbracket,
(generic, _, indexBy, _2) => {
generic.indexBy = indexBy;
return generic;
}));
let type = alt(range,
genericIndexable,
generic,
id.map((id) => {
id.kind = 'alias';
return id;
}));
let complexType = Parsimmon.alt(
record,
either);
////////// Statements //////////
let typedecl = seqMap(keywords.type,
id,
colon,
alt(complexType.skip(semicolon.times(0, 1)),
type.skip(semicolon)),
(_, id, _2, type) => ({
kind: 'typedecl',
id: id,
type: type,
}));
let vardecl = seqMap(keywords.var,
id,
colon,
type,
equals.then(expr).times(0, 1),
semicolon,
(_, id, _2, type, value, _3) => {
let o = {
'kind': 'vardecl',
id: id,
type: type,
};
if (value.length > 0) {
o.default = value[0];
}
return o;
});
let param = seqMap(keywords.param,
id,
colon,
type,
equals.then(expr).times(0, 1),
semicolon,
(_, id, _2, type, value, _3) => {
let o = {
'kind': 'paramdecl',
id: id,
type: type,
};
if (value.length > 0) {
o.default = value[0];
}
return o;
});
let block = lazy(() => {
return lbrace
.then(statement.many()).map((statements) => ({
kind: 'block',
code: {
kind: 'sequence',
statements: statements,
},
}))
.skip(rbrace);
});
let functionDecl = call(function() {
let param = seqMap(id,
colon,
type,
(id, _, type) => ({
id: id,
type: type,
})).source();
let paramlist = lparen
.then(sepBy(param, comma))
.skip(rparen);
return seqMap(keywords['function'],
id,
paramlist,
arrow,
type,
block,
(subkind, id, params, _2, returntype, block) => ({
kind: 'function',
id: id,
params: params,
returntype: returntype,
code: block
})).or(seqMap(keywords['function'],
id,
paramlist,
block,
(subkind, id, params, block) => ({
kind: 'function',
id: id,
params: params,
returntype: null,
code: block
})));
});
let returnStmt = keywords.return
.then(expr).map((expr) => ({
kind: 'returnstmt',
expr: expr,
}))
.skip(semicolon);
let match = call(function() {
let asClause = seqMap(keywords.as,
id,
(_1, id) => id).or(seqMap(lparen,
id,
rparen,
(_1, id, _2) => id));
let matchvariant = seqMap(id,
asClause.times(0, 1),
doubleArrow.times(0, 1),
block,
(type, as, _2, block) => ({
kind: 'matchvariant',
type: type,
id: as.length > 0 ? as[0] : undefined,
code: block,
}));
return seqMap(keywords.match,
expr,
lbrace,
sepBy1OptTrail(matchvariant, comma.times(0, 1)),
rbrace,
(_, expr, _2, variants, _3) => ({
kind: 'match',
expr: expr,
variants: variants,
}));
});
let assignment = seqMap(
lhs,
equals,
expr,
semicolon,
(lhs, _, rhs, _2) => ({
kind: 'assign',
lhs: lhs,
rhs: rhs,
})).or(seqMap(
lhs,
alt(plusEquals, minusEquals, starEquals, slashEquals, percentEquals).mark(),
expr,
semicolon,
(lhs, op, rhs, _) => {
op.value = op.value[0];
return {
kind: 'assign',
lhs: lhs,
rhs: {
kind: 'apply',
func: op,
args: [lhs, rhs],
},
};
}));
let print = seqMap(
keywords.print,
expr,
semicolon,
(_, expr, _2) => ({
kind: 'print',
expr: expr,
}));
let assert = seqMap(
keywords.assert,
expr.source(),
semicolon,
(_, expr, _2) => ({
kind: 'assert',
expr: expr,
})).source();
let foreachLoop = seqMap(keywords.for,
id.skip(comma).times(0, 1),
id,
keywords.in,
expr,
block,
(_, index, value, _2, expr, block) => ({
kind: 'foreach',
index: index.length == 1 ? index[0] : undefined,
value: value,
expr: expr,
code: block,
}));
let whileLoop = seqMap(keywords.while,
expr,
block,
(_, expr, block) => ({
kind: 'while',
expr: expr,
code: block,
}));
let ifElse = lazy(() => {
return seqMap(keywords.if,
expr,
block,
(keywords.else).then(alt(block, ifElse.source().map((elseIf) =>({
kind: 'block',
code: {
kind: 'sequence',
statements: [elseIf],
},
})))).times(0, 1).map((elses) => {
if (elses.length == 0) {
return {
kind: 'sequence',
statements: [],
};
} else {
return elses[0];
}
}),
(_, condition, thenblock, elseblock) => ({
kind: 'ifelse',
condition: condition,
thenblock: thenblock,
elseblock: elseblock,
})
);
});
let invariant = seqMap(keywords.invariant,
id,
block,
(_, id, block) => ({
kind: 'invariant',
id: id,
code: block,
}));
let rulefor = seqMap(keywords.for,
id.skip(comma).times(0, 1),
id,
keywords.in,
expr,
(_1, index, value, _2, expr) => ({
index: index.length == 1 ? index[0] : undefined,
value: value,
expr: expr,
}));
let rule = seqMap(alt(keywords.rule, keywords.external),
id,
rulefor.many(),
block,
(subkind, id, loops, block) => ({
kind: loops.length > 0 ? 'rulefor' : 'rule',
subkind: subkind,
id: id,
loops: loops.length > 0 ? loops : undefined,
code: block,
}));
let breakStmt = seqMap(keywords.break,
semicolon,
() => ({
kind: 'break',
})).source();
let continueStmt = seqMap(keywords.continue,
semicolon,
() => ({
kind: 'continue',
})).source();
let resetStmt = seqMap(keywords.reset,
semicolon,
() => ({
kind: 'reset',
})).source();
let statement = Parsimmon.alt(
param,
typedecl,
functionDecl,
ifElse,
invariant,
foreachLoop,
match,
assignment,
print,
assert,
rule,
returnStmt,
vardecl,
breakStmt,
continueStmt,
resetStmt,
whileLoop,
expr.skip(semicolon).map(v => ({
kind: 'do',
expr: v,
}))).source();
////////// Main parser (entry point) //////////
let file = lazy(() => {
return lexeme(string('')).then(statement.many()).map((statements) => ({
kind: 'sequence',
statements: statements,
}));
});
// Given an instance of Input, attempt to parse it.
// Either returns an AST or throws an Error.
let parse = function(input) {
let r = file.parse(input.getText());
if (r.status) {
let setInputAll = (obj) => {
for (var property in obj) {
var value = obj[property];
if (value instanceof Source) {
value.setInput(input);
} else if (typeof value == 'object') {
setInputAll(value);
}
}
};
setInputAll(r.value);
return r.value;
} else {
let at = input.lookup(r.index.offset);
let expected = [];
r.expected.forEach((v) => {
if (expected.indexOf(v) == -1) {
expected.push(v);
}
});
expected = expected.sort();
let error = new errors.Parse(`Parsing failed in ${input.filename} at line ${at.line}, col ${at.col}:
${input.highlight(at)}
Expected one of: ${expected.join(', ')}`);
error.input = input;
error.failAt = r.at;
error.expected = expected;
throw error;
}
};
module.exports = {
parse: parse,
keywords: keywordList,
};