-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrenshaw_compiler_port.js
803 lines (697 loc) · 13.9 KB
/
crenshaw_compiler_port.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
(function(console,process,require) {
'use strict';
String.prototype.splice=function(idx,rem,str) {
return this.slice(0,idx)+str+this.slice(idx+Math.abs(rem));
};
var
string=require('fs').readFileSync('test.js','utf8')
,char_i=-1
,look='' //lookahead Character
,token=''
,value=''
,lCount=0
,error_marker='[ERR]'
,kwList=['IF','ELSE','ENDIF','WHILE','ENDWHILE','READ','WRITE','BYTE','WORD','LONG','BEGIN','END','PROGRAM','PROCEDURE']
,kwCode='xiLereRWbwlBepP'
,stdout=process.stdout
,inTable={}
,params={}
,numParams=0
,base=0
;
function getChar() {
++char_i;
//Handle potential comment
if (string[char_i]==='/') {
//single line comment
if (string[char_i+1]==='/') {
char_i+=2;
//Avoid infinite loop by checking against string.length first
while (string.length>char_i&&/[^\r\n]/.test(string[char_i])) {++char_i;}
}
//multiline comment
else if (string[char_i+1]==='*') {
//advance three characters so, by the end, char_i will be at the last
//character ('/') of the comment, then set look to be a space so
//comments don't join statements together
char_i+=3;
while (string.length>char_i&&(string[char_i-1]!=='*'||string[char_i]!=='/')) {++char_i;}
return look=' ';
}
}
return look=string[char_i]||'';
}
function parserDump() {
return 'Parser dump: '+JSON.stringify({look,value,token});
}
function error(s) {
throw new Error(
'error: '+s+'\n'
+parserDump()+'\n'
+'"'
+string
.splice(char_i,0,error_marker)
.slice(Math.max(char_i-10,0),char_i+10+error_marker.length)
+'"'
);
}
function abort(s) {
error(s);
process.exit(-1);
}
function expected(s) {abort(s + ' expected.');}
function undefinedVar(n) {abort('Undefined Identifier '+n);}
function duplicate(n) {
abort('Duplicate Variable Name '+n);
}
function checkIdent() {
if (token!='x') {expected('Identifier');}
}
function matchString(x) {
if (value!==x) {expected('"'+x+'"');}
next();
}
function semi() {
if (token===';') {next();}
}
function isAlpha(c) {return /[a-z]/i.test(c);}
function isDigit(c) {return /[0-9]/.test(c);}
function isAlNum(c) {return /[a-z0-9]/i.test(c);}
function isBoolean(c) {return /[tf]/i.test(c);}
function isOp(c) {return /[+\-*/<>:=]/.test(c);}
function isAddop(c) {return /[+-]/.test(c);}
function isMulop(c) {return /[*/]/.test(c);}
function isOrop(c) {return /[|~]/.test(c);}
function isRelop(c) {return /[=#<>]/.test(c);}
function isWhite(c) {return /[ \t\r\n]/.test(c);}
function isVarType(c) {return /[bwl]/.test(c);}
function skipWhite() {
while (isWhite(look)) {
getChar();
}
}
function getName() {
skipWhite();
value='';
if (!isAlpha(look)) {expected('Identifier');}
do {
value+=look.toUpperCase();
getChar();
} while (isAlNum(look));
token=kwCode[lookup(value)+1];
return value;
}
function getNum() {
skipWhite();
if (!isDigit(look)) {expected('Integer');}
value='';
do {
value+=look;
getChar();
} while (isDigit(look));
//Turn string into number, shouldn't actually change anything...
value=+value;
token='#';
return value;
}
function getOp() {
skipWhite();
token=look;
value=look;
getChar();
}
function next() {
skipWhite();
if (isAlpha(look)) {getName();}
else if (isDigit(look)) {getNum();}
else {getOp();}
//writeLn(parserDump());
return true; //instead of while (cond&&(next()||true)) just while (cond&&next())
}
function lookup(s) {
return kwList.indexOf(s);
}
function newLabel() {return 'L'+(++lCount);}
function postLabel(L) {write(L+':');}
function emit(s) {write('\t'+s);}
function emitLn(s) {emit(s+'\n');}
function write(...s) {
stdout.write(s.join(''));
}
function writeLn(...s) {
write(...s,'\n');
}
//This is different from Crenshaw's impl in that it eliminates the need for
//negFactor, firstFactor, firstTerm, and term1, making the code much less
//windy and confusing.
function factor() {
var neg=false;
let type;
while (/[+-]/.test(token)) {
if (token==='-') {neg=!neg;}
next();
}
if (token === '(') {
next();
type=boolExpression();
matchString(')');
if (neg) {negate();}
}
else {
if (token==='x') {
if (isParam(value)) {type=loadParam(params[value]);}
else {type=loadVar(value);}
if (neg) {negate();}
}
else if (token==='#') {
type=loadConst((neg ? -1 : 1)*value);
}
else {expected('Math factor');}
next();
}
return type;
}
function multiply(t1) {
next();
return popMul(t1,factor());
}
function divide(t1) {
next();
return popDiv(t1,factor());
}
function term() {
let type=factor();
while (isMulop(token)) {
push(type);
switch (token) {
case '*': type=multiply(type); break;
case '/': type=divide(type); break;
}
}
return type;
}
function add(t1) {
next();
return popAdd(t1,term());
}
function subtract(t1) {
next();
return popSub(t1,term());
}
function expression() {
let type=term();
while (isAddop(token)) {
push(type);
switch (token) {
case '+': type=add(type); break;
case '-': type=subtract(type); break;
}
}
return type;
}
function compareExpression() {
boolExpression();
popCompare();
}
function nextExpression() {
next();
compareExpression();
}
function boolTerm() {
let type=notFactor();
while (token === '&') {
push();
next();
notFactor();
popAnd();
}
return type;
}
function notFactor() {
let type;
if (token === '!') {
next();
type=relation();
notIt();
}
else {
type=relation();
}
return type;
}
function boolOr() {
next();
boolTerm();
popOr();
}
function boolXor() {
next();
boolTerm();
popXor();
}
/*
This is an incomplete listing of functions called by boolExpression and its
descendants to make the flow easier to follow.
boolExpression: boolTerm boolOr boolXor
boolTerm: notFactor popAnd
notFactor: relation notIt
relation: expression equals less greater
expression: term add subtract
term: factor multiply divide
factor: boolExpression loadVar loadParam loadConst
*/
function boolExpression() {
let type=boolTerm();
while (isOrop(token)) {
push(type);
switch (token) {
case '|': type=boolOr(type); break;
case '~': type=boolXor(type); break;
}
}
return type;
}
function doProc() {
let name=getName();
next();
checkDup(name);
inTable[name]='p';
formalList();
var k=locDecls();
procProlog(name,k)
matchString('BEGIN');
block();
matchString('END');
procEpilog();
clearParams();
}
function formalList() {
matchString('(');
if (token!==')') {
do {
checkIdent();
addParam(value);
next();
} while (token===','&&next());
}
matchString(')');
base=numParams;
numParams+=4
}
function addParam(name) {
if (isParam(name)) {duplicate(name);}
++numParams;
params[name]=numParams;
}
function isParam(name) {
return params.hasOwnProperty(name);
}
function clearParams() {
params={};
numParams=0;
}
function locDecls() {
var n=0;
while (token==='v') {
do {
addParam(getName());
++n;
next();
} while (token===',');
}
return n;
}
function procProlog(name,k) {
postLabel(name);
emitLn('LINK A6,#'+(-2*k));
}
function procEpilog() {
emitLn('UNLK A6');
emitLn('RTS');
}
function loadParam(n) {
emitLn(`MOVE ${8+2*(base-n)}(A6),D0`);
}
function storeParam(n) {
emitLn(`MOVE D0,${8+2*(base-n)}(A6)`);
}
function doIf() {
var L1, L2;
next();
boolExpression();
L1=newLabel();
L2=L1;
branchFalse(L1);
block();
if (token==='L') {
next();
L2=newLabel();
branch(L2);
postLabel(L1);
block();
}
postLabel(L2);
matchString('ENDIF');
}
function doWhile() {
next();
var L1, L2;
L1=newLabel();
L2=newLabel();
postLabel(L1);
boolExpression();
branchFalse(L2);
block();
matchString('ENDWHILE');
branch(L1);
postLabel(L2);
}
function equals() {
nextExpression();
setEqual();
}
function notEqual() {
nextExpression();
setNEqual();
}
function less() {
next();
switch (token) {
case '=': lessOrEqual(); break;
case '>': notEqual(); break;
default:
compareExpression();
setLess();
}
}
function greater() {
next();
var orEqual=false;
if (token==='=') {next();orEqual=true;}
compareExpression();
if (orEqual) {setGreaterOrEqual();} else {setGreater();}
}
function lessOrEqual() {
nextExpression();
setLessOrEqual();
}
function relation() {
let type=expression();
if (isRelop(token)) {
push();
switch (token) {
case '=': equals(); break;
case '<': less(); break;
case '>': greater(); break;
default: writeLn('Should this happen?');
}
}
return type;
}
function assignOrProc() {
var name=value;
switch (isParam(name) ? 'f' : inTable[name]) {
case 'b':
case 'w':
case 'l':
case 'f': assignment(name); break;
case 'p': callProc(name); break;
default: undefinedVar(name);
}
}
function assignment(name) {
next();
matchString('=');
boolExpression();
if (isParam(name)) {storeParam(params[name]);}
else {store(name);}
}
function callProc(name) {
next();
var n=paramList();
emitLn('BSR '+name);
if (n>0) {
emitLn(`ADD #${n},SP`);
}
}
function paramList() {
var n=0;
matchString('(');
if (token!==')') {
do {
param();
++n;
} while (token===','&&next());
}
matchString(')');
return 2*n;
}
function param() {
boolExpression();
push();
}
function block() {
while (/[^el]/.test(token)) {
switch (token) {
case 'i': doIf(); break;
case 'r': doWhile(); break;
case 'R': doRead(); break;
case 'W': doWrite(); break;
case 'P': doProc(); break;
default: assignOrProc();
}
semi();
}
}
function header() {
writeLn('WARMST', '\t', 'EQU $A01E');
}
function topDecls() {
while (true) { //v or P
if (isVarType(token)) {
let type=token;
do {alloc(type);} while (token===',');
}
else if (token==='P') {doProc();}
else {break;}
semi();
}
}
function varType(n) {
if (!inTable.hasOwnProperty(n)) {undefinedVar(n);}
if (!isVarType(inTable[n])) {abort(`Identifier '${n}' is recorded as a ${inTable[n]}, not a variable`);}
return inTable[n];
}
function checkDup(n) {
if (inTable.hasOwnProperty(n)) {duplicate(n);}
}
function alloc(type) {
next();
if (token!=='x') {expected('Variable Name');}
var name=value;
checkDup(name);
inTable[name]=type;
var val=0;
if (look==='=') {
next();
var isNeg=false;
if (look==='-') {
isNeg=true;
next();
}
val=getNum()*(isNeg ? -1 : 1);
}
allocate(name,val,type);
next();
}
function allocate(name, val, type) {
writeLn(`${name}:\tDC.${type} ${val}`);
}
function prolog() {
postLabel('MAIN');
}
function epilog() {
emitLn('DC WARMST');
emitLn('END MAIN');
}
function init() {
getChar();
next();
}
//Assembly implementations
function clear() {
emitLn('CLR D0');
}
function move(type, src, dest) {
emitLn(`MOVE.${type} ${src},${dest}`);
}
function convert(src, dest, reg) {
if (src!==dest) {
if (src==='b') {emitLn('AND.W #$FF,'+reg);}
if (dest==='l') {emitLn('EXT.L '+reg);}
}
}
function promote(t1, t2, reg) {
let type=t1;
if (t1!==t2&&(t1==='b'||(t1==='w'&&t2==='l'))) {
convert(t1,t2,reg);
type=t2;
}
return type;
}
function sameType(t1,t2) {
t1=promote(t1,t2,'D7');
return promote(t2,t1,'D0');
}
function negate() {
emitLn('NEG D0');
}
function loadConst(n) {
let absN=Math.abs(n);
let type;
if (absN<=127) {type='b'}
else if (absN<=32767) {type='w'}
else {type='l'}
move(type,'#'+n,'D0');
return type;
}
function loadVar(name) {
let type=varType(name);
move(type, name+'(PC)', 'D0');
return type;
}
function push(type) {
move(type, 'D0', '-(SP)');
}
function pop(type) {
move(type, '(SP)+', 'D7');
}
function popAdd(t1,t2) {
pop(t1);
t2=sameType(t1,t2);
emitLn(`ADD.${t2} D7,D0`);
return t2;
}
function popSub(t1,t2) {
pop(t1);
t2=sameType(t1,t2);
emitLn(`SUB.${t2} D7,D0`);
emitLn('NEG D0');
return t2;
}
function popMul(t1,t2) {
pop(t1);
let t=sameType(t1,t2);
convert(t,'w','D7');
convert(t,'w','D0');
if (t==='l') {emitLn('JSR MUL32');}
else {emitLn('MULS D7,D0');}
return (t==='b' ? 'w' : 'l');
}
function popDiv(t1,t2) {
pop(t1);
convert(t1,'l','D7');
if (t1==='l'||t2==='l') {
convert(t2,'l','D0');
emitLn('JSR DIV32');
return 'l';
}
else {
convert(t2,'w','D0');
emitLn('DIVS D0,D7');
move('w','D7','D0');
return t1
}
}
function notIt() {
emitLn('NOT D0');
}
function popAnd() {
emitLn('AND (SP)+,D0');
}
function popOr() {
emitLn('OR (SP)+,D0');
}
function popXor() {
emitLn('EOR (SP)+,D0');
}
function popCompare() {
emitLn('CMP (SP)+,D0');
}
function setEqual() {
emitLn('SEQ D0');
emitLn('EXT D0');
}
function setNEqual() {
emitLn('SNE D0');
emitLn('EXT D0');
}
function setGreater() {
emitLn('SLT D0');
emitLn('EXT D0');
}
function setLess() {
emitLn('SGT D0');
emitLn('EXT D0');
}
function setGreaterOrEqual() {
emitLn('SLE D0');
emitLn('EXT D0');
}
function setLessOrEqual() {
emitLn('SGE D0');
emitLn('EXT D0');
}
function store(name,t1) {
let t2=varType(name);
convert(t1,t2,'D0');
emitLn('LEA '+name+'(PC),A0');
move(t2, 'D0','(A0)');
}
function readVar() {
checkIdent();
varType(value);
readIt(value)
next();
}
function doRead() {
next();
matchString('(');
do {
readVar();
} while (token===','&&next());
matchString(')');
}
function doWrite() {
next();
matchString('(');
do {
expression();
writeIt();
} while (token===','&&next());
matchString(')');
}
function readIt(name) {
emitLn('BSR READ');
store(name);
}
function writeIt() {
emitLn('BSR WRITE');
}
function branch(l) {
emitLn('BRA '+l);
}
function branchFalse(l) {
emitLn('TST D0');
emitLn('BEQ '+l);
}
init();
header();
topDecls();
matchString('PROGRAM');
matchString('BEGIN');
prolog();
block();
matchString('END');
epilog();
}(console,process,require));