-
Notifications
You must be signed in to change notification settings - Fork 6
/
compile.js
807 lines (707 loc) · 20.7 KB
/
compile.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
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
'use strict';
///////////////////////////////////////////////////////// PARSING
var charIsInRange = function (arg) {
var lower = arg[0];
var c = arg[1]; // falsy if eof
var upper = arg[2];
return c &&
lower.charCodeAt(0) <= c.charCodeAt(0) &&
c.charCodeAt(0) <= upper.charCodeAt(0);
};
var isDigit = function (c) {
return charIsInRange(['0', c, '9']);
};
var isLowercaseLetter = function (c) {
return charIsInRange(['a', c, 'z']);
};
var isUppercaseLetter = function (c) {
return charIsInRange(['A', c, 'Z']);
};
var isLetter = function (c) {
return isLowercaseLetter(c) || isUppercaseLetter(c);
};
var whitespaces = [' ', '\n', '\r', '\t'];
var isWhitespace = function (c) {
return whitespaces.indexOf(c) !== -1;
};
var keywords = [
'else', 'false', 'function', 'if', 'in', 'null', 'return', 'true',
'typeof', 'var', 'while'
];
var getLineNumberAtIndex = function (arg) {
var lines = 1;
var i = 0;
while (i < arg.source.length && i < arg.index) {
if (arg.source[i] === '\n') {
lines = lines + 1;
}
i = i + 1;
}
return lines;
};
// Returns a list of statements (they are AST nodes).
var parse = function (source) {
var index = 0; // Don't set directly. Use setIndex().
var farthestIndex = 0; // Only used for error management.
// Most of the following parsing functions return a falsy value on
// failure, or the read substring on success.
var setIndex = function (newIndex) {
index = newIndex;
if (index > farthestIndex) {
farthestIndex = index;
}
};
// Tries to read the given string.
var read = function (expected) {
// TODO: String#slice() is slow and performance matters here.
if (source.slice(index).indexOf(expected) === 0) {
setIndex(index + expected.length);
return expected;
}
};
// Tries to read one character that matches the given predicate.
var readCharIf = function (predicate) {
var c = source[index];
if (predicate(c)) {
setIndex(index + 1);
return c;
}
};
// Pretty obvious. See how it is used below.
var backtrack = function (func) {
return function (arg) {
var begin = index;
var result = func(arg);
if (result) {
return result;
}
index = begin;
};
};
var createToken = function (token) {
token.index = index;
return token;
};
var digit = function () {
return readCharIf(isDigit);
};
var letter = function () {
return readCharIf(isLetter);
};
var whitespace = function () {
// That's bit hackish for performance reasons.
while (1) {
if (source[index] === '/' && source[index + 1] === '/') {
setIndex(index + 2);
while (readCharIf(function (c) {return c !== '\n';})) {}
}
if (!readCharIf(isWhitespace)) {
return 1;
}
}
};
var stringEscapeTable = {
n: '\n', t: '\t', r: '\r', '\'': '\'', '\\': '\\',
};
var string = backtrack(function () {
whitespace();
var quote = read('\'');
if (!quote) {
return;
}
var value = '';
while (1) {
var c = source[index];
setIndex(index + 1);
if (!c) {
return;
}
if (c === '\'') {
return createToken({type: 'string', value});
}
if (c === '\\') {
var d = source[index];
setIndex(index + 1);
if (!(d in stringEscapeTable)) {
return;
}
value = value + stringEscapeTable[d];
}
if (c !== '\\') {
value = value + c;
}
}
});
var identifierish = backtrack(function () {
whitespace();
var string = letter() || read('_');
if (!string) {
return;
}
while (1) {
var c = digit() || letter() || read('_');
if (!c) {
return string;
}
string = string + c;
}
});
var identifier = backtrack(function () {
var string = identifierish();
if (string && keywords.indexOf(string) === -1) {
return createToken({type: 'identifier', string});
}
});
var number = backtrack(function () {
whitespace();
var string = digit();
if (!string) {
return;
}
while (1) {
var c = digit();
if (!c) {
return createToken({
type: 'number',
value: parseInt(string)
});
}
string = string + c;
}
});
var keyword = backtrack(function () {
var string = identifierish();
if (string && keywords.indexOf(string) !== -1) {
return string;
}
});
var thisKeyword = backtrack(function (expected) {
var string = keyword();
if (string === expected) {
return string;
}
});
var nullExpr = function () {
return thisKeyword('null') && {type: 'null'};
};
var literal = function () {
return nullExpr() || identifier() || number() || string();
};
// Used to parse parentheses, braces or square brackets.
var wrapped = backtrack(function (arg) {
whitespace();
if (!read(arg.left)) {
return;
}
var e = arg.body();
whitespace();
if (read(arg.right)) {
return e;
}
});
// Used to parse lists delimited by commas or semicolons.
var sequence = backtrack(function (arg) {
var items = [];
while (1) {
if (items.length && !arg.sep()) {
return items;
}
var item = arg.item();
if (!item) {
return items;
}
items.push(item);
}
});
var paren = function () {
var body = function () {
return expr() || {type: 'null'};
};
return wrapped({left: '(', body, right: ')'});
};
var statements = function () {
return sequence({item: statement, sep: whitespace});
};
var block = function () {
return wrapped({left: '{', body: statements, right: '}'});
};
var commaSeparated = function (item) {
return sequence({
item,
sep: function () {return read(',');}
});
};
var list = function () {
var children = wrapped({
left: '[',
body: function () {return commaSeparated(expr);},
right: ']'
});
if (children) {
return {type: 'list', children};
}
};
var dictEntry = backtrack(function () {
var left = identifier() || string();
if (!left) {
return;
}
left.type = 'string';
left.value = left.string || left.value;
whitespace();
if (!read(':')) {
var right = {
type: 'identifier',
string: left.value
};
return {type: 'dictEntry', left, right};
}
var right = expr();
if (right) {
return {type: 'dictEntry', left, right};
}
});
var dict = function () {
var children = wrapped({
left: '{',
body: function () {return commaSeparated(dictEntry);},
right: '}'
});
if (children) {
return {type: 'dict', children};
}
};
var atom = function () {
return literal() || list() || dict() || paren();
};
var postfixDot = backtrack(function () {
whitespace();
return read('.') && identifier();
});
var postfixRight = function (left) {
var right = paren();
if (right) {
return {type: 'binaryOp', left, op: 'call', right};
}
if (right = wrapped({left: '[', body: expr, right: ']'})) {
return {type: 'subscript', left, right};
}
if (right = postfixDot()) {
return {
type: 'subscript',
left,
right: {type: 'string', value: right.string},
};
}
return;
};
var postfix = function () {
var left = atom();
while (left) {
var n = postfixRight(left);
if (!n) {
return left;
}
left = n;
}
return left;
};
var whileStatement = backtrack(function () {
if (!thisKeyword('while')) {
return;
}
var cond = paren();
var b = block();
if (cond && b) {
return {type: 'while', cond, children: b};
}
});
var ifStatement = backtrack(function () {
if (!thisKeyword('if')) {
return;
}
var cond = paren();
var b = block();
if (cond && b) {
return {type: 'if', cond, children: b};
}
});
var varExpr = backtrack(function () {
if (!thisKeyword('var')) {
return;
}
var name = identifier();
whitespace();
var eq = read('=');
var value = expr();
if (name && eq && value) {
return {type: 'var', name, value};
}
});
var returnExpr = backtrack(function () {
if (!thisKeyword('return')) {
return;
}
return {
type: 'return',
value: expr() || {type: 'null'}
};
});
var func = backtrack(function () {
if (!thisKeyword('function')) {
return;
}
var optionalId = function () {
return identifier() || {type: 'null'};
};
var param = wrapped({left: '(', body: optionalId, right: ')'});
var b = block();
if (param && b) {
return {type: 'function', param, children: b};
}
});
var binaryOp = function (arg) {
return backtrack(function () {
var left = arg.next();
if (!left) {
return;
}
while (1) {
var op = arg.parseOp();
if (!op) {
return left;
}
var right = arg.next();
left = {type: 'binaryOp', left, op, right};
}
return left;
});
};
var binaryOp2 = function (opStrings) {
return function (next) {
var parseOp = function () {
var i = 0;
whitespace();
while (i < opStrings.length) {
var op = read(opStrings[i]);
if (op) {
return op;
}
i = i + 1;
}
};
return binaryOp({next, parseOp});
};
};
var unary = backtrack(function () {
whitespace();
var op = read('-') || read('!') || thisKeyword('typeof');
var right = postfix();
if (op && right) {
return {type: 'unaryOp', op, right};
}
return right;
});
var multiplication = binaryOp2(['*', '/', '%'])(unary);
var addition = binaryOp2(['+', '-'])(multiplication);
var relation = binaryOp2(['<=', '>=', '<', '>', 'in'])(addition);
var equality = binaryOp2(['===', '!=='])(relation);
var andExpr = binaryOp2(['&&'])(equality);
var orExpr = binaryOp2(['||'])(andExpr);
var assignment_ = backtrack(function () {
var left = postfix();
whitespace();
if (!left || !read('=')) {
return;
}
var right = assignment();
if (right) {
return {type: 'assignment', left, right};
}
});
var assignment = function () {
return assignment_() || orExpr() || func();
};
var expr = function () {
return func() || varExpr() || returnExpr() || assignment();
};
var exprStatement = backtrack(function () {
var e = expr();
whitespace();
if (read(';')) {
return e;
}
});
var statement = function () {
return whileStatement() || ifStatement() || exprStatement();
};
var result = statements();
whitespace();
if (!result || index < source.length) {
if (index > farthestIndex) {
farthestIndex = index;
}
var line = getLineNumberAtIndex({source, index: farthestIndex});
die('syntax error (line ' + line + ')');
}
return result;
};
//////////////////////////////////////////////////// BYTECODE GENERATION
var opSignsToNames = {
'+': 'add', '-': 'sub', '*': 'mul', '/': 'div', '%': 'mod',
'===': 'eq', '!==': 'neq',
'<': 'lt', '>': 'gt', '<=': 'lte', '>=': 'gte',
'in': 'in', call: 'call',
};
var unarySignsToNames = {
'-': 'unary_minus',
'!': 'not',
'typeof': 'typeof'
};
var compileFunctionBody = function (statements) {
var code = [];
var consts = [];
var toUint16 = function (n) {
return [Math.floor(n / 256), n % 256]; // big endian
};
var genUint16 = function (n) {
code = code.concat(toUint16(n));
};
var setUint16At = function (arg) {
var number = arg[0];
var index = arg[1];
code[index] = toUint16(number)[0];
code[index + 1] = toUint16(number)[1];
};
var genLoadConst = function (c) {
code.push('load_const');
genUint16(consts.length);
consts.push(c);
};
var compileAssign = function (expr) {
if (expr.left.type === 'identifier') {
compileExpr(expr.right);
code.push('dup');
genLoadConst(expr.left.string);
code.push('rot');
code.push('store_var');
return;
}
if (expr.left.type === 'subscript') {
compileExpr(expr.right);
code.push('dup');
compileExpr(expr.left.left);
compileExpr(expr.left.right);
code.push('set');
return;
}
die('unknown lvalue type');
};
var compileAndOr = function (expr) {
// Shortcuts right operand. We need a `goto`. A plain old binary
// operator is not suitable.
compileExpr(expr.left);
code.push('dup');
if (expr.op === '&&') {
code.push('not');
}
code.push('goto_if');
var breakLabel = code.length;
genUint16(0);
code.push('pop');
compileExpr(expr.right);
setUint16At([code.length, breakLabel]);
};
var compileExpr = function (expr) {
if (expr.type === 'string' || expr.type === 'number') {
return genLoadConst(expr.value);
}
if (expr.type === 'null') {
return code.push('load_null');
}
if (expr.type === 'assignment') {
return compileAssign(expr);
}
if (expr.type === 'binaryOp') {
if (expr.op === '&&' || expr.op === '||') {
return compileAndOr(expr);
}
compileExpr(expr.left);
compileExpr(expr.right);
if (!opSignsToNames[expr.op]) {
die('unknown op ' + expr.op);
}
code.push(opSignsToNames[expr.op]);
return;
}
if (expr.type === 'unaryOp') {
compileExpr(expr.right);
code.push(unarySignsToNames[expr.op]);
return;
}
if (expr.type === 'identifier') {
genLoadConst(expr.string);
code.push('load_var');
return;
}
if (expr.type === 'function') {
code.push('load_func');
genUint16(expr._id);
return;
}
if (expr.type === 'subscript') {
compileExpr(expr.left);
compileExpr(expr.right);
code.push('get');
return;
}
if (expr.type === 'list') {
code.push('load_empty_list');
var i = 0;
while (i < expr.children.length) {
compileExpr(expr.children[i]);
code.push('list_push');
i = i + 1;
}
return;
}
if (expr.type === 'dict') {
code.push('load_empty_dict');
var i = 0;
while (i < expr.children.length) {
var entry = expr.children[i];
compileExpr(entry.left);
compileExpr(entry.right);
code.push('dict_push');
i = i + 1;
}
return;
}
die('unknown expr type');
};
var compileStatement = function (expr) {
if (expr.type === 'var') {
genLoadConst(expr.name.string);
code.push('dup');
code.push('decl_var');
compileExpr(expr.value);
code.push('store_var');
return;
}
if (expr.type === 'return') {
compileExpr(expr.value);
code.push('return');
return;
}
if (expr.type === 'while') {
// This is what people call "spaghetty code".
var beginLabel = code.length;
compileExpr(expr.cond);
code.push('not');
code.push('goto_if');
var breakLabel = code.length;
genUint16(0);
compileStatements(expr.children);
code.push('goto');
genUint16(beginLabel);
setUint16At([code.length, breakLabel]);
return;
}
if (expr.type === 'if') {
compileExpr(expr.cond);
code.push('not');
code.push('goto_if');
var breakLabel = code.length;
genUint16(0);
compileStatements(expr.children);
setUint16At([code.length, breakLabel]);
return;
}
compileExpr(expr);
code.push('pop'); // In statements like `print("hello");`, we
// don't care about the value returned by `print`.
};
var compileStatements = function (statements) {
var i = 0;
while (i < statements.length) {
compileStatement(statements[i]);
i = i + 1;
}
};
compileStatements(statements);
code.push('load_null');
code.push('return');
return {consts, code};
};
// Returns a list of the functions present in the given AST node.
// Performs a depth-first search.
var getFunctions = function (node) {
if (node.type === 'var') {
return getFunctions(node.value);
}
if (node.type === 'function') {
return [node].concat(getFunctionsInList(node.children));
}
if (node.type === 'while' || node.type === 'if') {
return getFunctionsInList(node.children)
.concat(getFunctions(node.cond));
}
if (['binaryOp', 'assignment', 'subscript'].indexOf(node.type) !== -1) {
return getFunctions(node.left)
.concat(getFunctions(node.right));
}
if (node.type === 'unaryOp') {
return getFunctions(node.right);
}
if (node.type === 'return') {
return getFunctions(node.value);
}
if (node.type === 'list' || node.type === 'dict') {
return getFunctionsInList(node.children);
}
if (node.type === 'dictEntry') {
return getFunctions(node.right);
}
return [];
};
// Exactly like `getFunctions` but works on a list of AST nodes.
var getFunctionsInList = function (list) {
var funcs = [];
var i = 0;
while (i < list.length) {
funcs = funcs.concat(getFunctions(list[i]));
i = i + 1;
}
return funcs;
};
// Returns a list of compiled functions.
var codegen = function (statements) {
var root = {
type: 'function',
children: statements,
param: {type: 'null'}
};
// Assign an unique `_id` property to each function. The first function
// must be the entrypoint.
var functions = getFunctions(root);
var i = 0;
while (i < functions.length) {
functions[i]._id = i;
i = i + 1;
}
var compiledFuncs = [];
i = 0;
while (i < functions.length) {
var func = functions[i];
var compiled = compileFunctionBody(func.children);
if (func.param.type !== 'null') {
compiled.paramName = func.param.string;
}
compiledFuncs.push(compiled);
i = i + 1;
}
return compiledFuncs;
};
module.exports = function (source) {
return codegen(parse(source));
};