-
Notifications
You must be signed in to change notification settings - Fork 3
/
lmsm.js
1014 lines (884 loc) · 32.7 KB
/
lmsm.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
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
/**
* This is the main emulator of the LittleManStackMachine.
*/
class LittleManStackMachine {
// The status of the machine, "Ready", "Error", etc.
status = "Ready"
// The memory of the machine, implicitly of size 200
memory = []
// The output buffer of the machine
output = []
// This is the register file for the machine, with a total of five registers
registers = {
program_counter:0, // this register points to the next instruction in memory to execute
current_instruction:0, // this register holds the value of the current instruction
accumulator:0, // this register is the sole general purpose register
stack_pointer:200, // this register points to the memory location of the top of the value stack
return_address_pointer:99 // this register points to the memory location of the top of the return address stack
}
// This holds an error message if the machine is in the error state, reporting what happened
error = null
// This callback is called when input is needed from the user. It should return an integer.
inputCallback = function() {
let returnVal = prompt("Please enter a number");
return parseInt(returnVal);
}
// This callback is called when an output is emitted by the emulator.
outputCallback = (value) => {}
// This callback is called when the emulator is updated.
updateCallback = () => {}
// A helper method to compile Firth source all the way into loaded machine instructions in the emulator
compile(src) {
let compiler = new FirthCompiler();
let compileResult = compiler.compile(src);
if (compileResult.errors.length > 0) {
console.error("Compilation Errors:")
for (const err of compileResult.errors) {
console.error(err)
}
return "";
} else {
return compileResult.assembly;
}
}
// A helper method to assemble LMSM assemebly source into loaded machine instructions in the emulator
assemble(compiledAssembly) {
let assembler = new LMSMAssembler();
let assemblyResult = assembler.assemble(compiledAssembly);
console.log(assemblyResult);
return assemblyResult.machineCode;
}
// Compiles the given Firth source and runs it on the emulator
compileAndRun(src) {
let compiledAssembly = this.compile(src);
let machine_code = this.assemble(compiledAssembly);
this.load(machine_code);
this.run();
}
// Assembles the given LMSM assembly source and runs it on the emulator
assembleAndRun(src) {
let machine_code = this.assemble(src);
this.load(machine_code);
this.run();
}
// Loads the given machine instructions into memory
load(instructions) {
this.memory = instructions;
}
// Executes a single instruction
step() {
this.status = "Running";
this.executeCurrentInstruction();
}
// Executes the current instruction if the machine is runnable
executeCurrentInstruction() {
if (this.status !== "Stopped") {
this.registers.current_instruction = this.memory[this.registers.program_counter];
this.registers.program_counter++;
this.executeInstruction(this.registers.current_instruction);
}
if (this.status === "Error") {
console.error("Error : " + this.error);
}
this.updateCallback()
}
// Runs the machine, executing until an error occurs or the program halts
run() {
this.status = "Running";
while (this.status === "Running") {
this.executeCurrentInstruction();
}
}
/**
* This is the crux of the emulator, which is responsible for interpreting a given instruction and updating
* the state of the machine accordingly. LMSM Machine Code is very simple: it uses decimal values rather than
* binary to make it easier to understand what's going on. But this is the same general algorithm as an emulator
* for a more sophisticated CPU.
*
* @param instruction
*/
executeInstruction(instruction) {
if (instruction === 0) {
this.status = "Stopped";
} else if (100 <= instruction && instruction <= 199) {
this.registers.accumulator += this.memory[instruction - 100];
} else if (200 <= instruction && instruction <= 299) {
this.registers.accumulator -= this.memory[instruction - 200];
} else if (300 <= instruction && instruction <= 399) {
this.memory[instruction - 300] = this.registers.accumulator;
} else if (400 <= instruction && instruction <= 499) {
this.registers.accumulator = instruction - 400;
} else if (500 <= instruction && instruction <= 599) {
this.registers.accumulator = this.memory[instruction - 500];
} else if (600 <= instruction && instruction <= 699) {
this.registers.program_counter = instruction - 600;
} else if (700 <= instruction && instruction <= 799) {
if (this.registers.accumulator === 0) {
this.registers.program_counter = instruction - 700;
}
} else if (800 <= instruction && instruction <= 899) {
if (this.registers.accumulator >= 0) {
this.registers.program_counter = instruction - 800;
}
} else if (instruction === 901) {
let value = this.inputCallback();
this.registers.accumulator = value;
} else if (instruction === 902) {
console.log(this.registers.accumulator + " ");
this.output.push(this.registers.accumulator);
this.outputCallback(this.registers.accumulator);
} else if (instruction === 910) {
this.registers.return_address_pointer++;
this.memory[this.registers.return_address_pointer] = this.registers.program_counter;
this.registers.program_counter = this.memory[this.registers.stack_pointer];
this.registers.stack_pointer++;
} else if (instruction === 911) {
this.registers.program_counter = this.memory[this.registers.return_address_pointer];
this.registers.return_address_pointer--;
} else if (instruction === 920) {
this.registers.stack_pointer--;
this.memory[this.registers.stack_pointer] = this.registers.accumulator;
} else if (instruction === 921) {
this.registers.accumulator = this.memory[this.registers.stack_pointer];
this.registers.stack_pointer++;
} else if (instruction === 922) {
this.registers.stack_pointer--;
this.memory[this.registers.stack_pointer] = this.memory[this.registers.stack_pointer + 1];
} else if (instruction === 923) {
this.registers.stack_pointer++;
} else if (instruction === 924) {
let tmpVal = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer] = this.memory[this.registers.stack_pointer + 1];
this.memory[this.registers.stack_pointer + 1] = tmpVal;
} else if (instruction === 930) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first + second;
this.registers.stack_pointer++;
} else if (instruction === 931) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first - second;
this.registers.stack_pointer++;
} else if (instruction === 932) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first * second;
this.registers.stack_pointer++;
} else if (instruction === 933) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first / second;
this.registers.stack_pointer++;
} else if (instruction === 934) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first > second ? first : second;
this.registers.stack_pointer++;
} else if (instruction === 935) {
let first = this.memory[this.registers.stack_pointer + 1];
let second = this.memory[this.registers.stack_pointer];
this.memory[this.registers.stack_pointer + 1] = first < second ? first : second;
this.registers.stack_pointer++;
} else {
this.status = "Stopped";
}
if (this.registers.stack_pointer < 100) {
this.status = "Error";
this.error = "Value Stack Overflow";
}
if (this.registers.stack_pointer <= this.registers.return_address_pointer) {
this.status = "Error";
this.error = "Stack Collision";
}
if (199 < this.registers.return_address_pointer) {
this.status = "Error";
this.error = "Stack Overflow";
}
if (this.registers.accumulator > 999) {
this.registers.accumulator = 999;
}
if (this.registers.accumulator < -999) {
this.registers.accumulator = -999;
}
}
}
class LMSMTokenizer {
offset = 0
line = 1
lineOffset = 0
tokens = []
constructor(str) {
this.str = str
}
consumeWhitespace() {
while (this.hasMoreChars()) {
if (this.atSpace()) {
this.offset++;
this.lineOffset++;
}else if (this.atNewLine()) {
this.offset++;
this.line++;
this.lineOffset = 0;
} else {
break;
}
}
}
hasMoreChars() {
return this.offset < this.str.length;
}
atNewLine() {
return this.currentChar() === "\n";
}
atSpace() {
return this.currentChar() === " " || this.currentChar() === "\t";
}
currentChar() {
return this.str[this.offset];
}
consumeChar() {
let current = this.currentChar();
this.offset++;
this.lineOffset++;
return current;
}
consumeToken() {
let token = {
offset:this.offset,
line:this.line,
lineOffset: this.lineOffset,
value: this.consumeChar()
}
while (this.hasMoreChars()) {
if (this.atNewLine() || this.atSpace()) {
break;
}
token.value += this.consumeChar()
}
token.lineOffsetEnd = this.lineOffset;
this.tokens.push(token);
}
consumeComment() {
if (this.currentChar() === "#") {
while (this.hasMoreChars()) {
if (this.atNewLine()) {
break;
}
this.consumeChar();
}
return true;
}
}
tokenize() {
this.consumeWhitespace();
while (this.hasMoreChars()) {
if (!this.consumeComment()) {
this.consumeToken();
}
this.consumeWhitespace();
}
return this.tokens;
}
}
class LMSMAssembler {
SYNTHETIC_INSTRUCTION = -1;
INSTRUCTIONS = {
"ADD": 100,
"SUB": 200,
"STA": 300,
"LDI": 400,
"LDA": 500,
"BRA": 600,
"BRZ": 700,
"BRP": 800,
"INP": 901,
"OUT": 902,
"HLT": 0,
"COB": 0,
"DAT": this.SYNTHETIC_INSTRUCTION,
"JAL": 910,
"CALL": this.SYNTHETIC_INSTRUCTION,
"RET": 911,
"SPUSH": 920,
"SPUSHI": this.SYNTHETIC_INSTRUCTION,
"SPOP": 921,
"SDUP": 922,
"SDROP": 923,
"SSWAP": 924,
"SADD": 930,
"SSUB": 931,
"SMUL": 932,
"SDIV": 933,
"SMAX": 934,
"SMIN": 935
}
ARG_INSTRUCTIONS = ["ADD", "SUB", "LDA", "STA", "BRA", "BRZ", "BRP", "DAT", "LDI", "CALL", "SPUSHI"]
assemble(asmSource) {
let lmsmTokenizer = new LMSMTokenizer(asmSource);
let tokens = lmsmTokenizer.tokenize();
let instructions = []
let sourceMap = {}
let labelsToInstructions = {}
let offset = 0;
while (tokens.length > 0) {
let token = tokens.shift();
let instruction = {offset:offset};
// label
if (this.INSTRUCTIONS[token.value] == null) {
instruction.label = token.value;
labelsToInstructions[instruction.label] = instruction;
token = tokens.shift()
}
instruction.token = token;
if (this.ARG_INSTRUCTIONS.includes(token.value)) {
token = tokens.shift()
instruction.arg = token;
}
instructions.push(instruction);
if (instruction.token.value === "CALL") {
offset = offset + 3;
} else if (instruction.token.value === "SPUSHI") {
offset = offset + 2;
} else {
offset++;
}
}
let machineCode = []
for (const instruction of instructions) {
let resolvedArg = null;
if(instruction.arg){
if (isNaN(instruction.arg.value)) {
let targetInstruction = labelsToInstructions[instruction.arg.value];
if (targetInstruction == null) {
throw "Cannot find label " + instruction.arg.value;
}
resolvedArg = targetInstruction.offset;
} else {
resolvedArg = parseInt(instruction.arg.value);
}
}
let baseValue = this.INSTRUCTIONS[instruction.token.value];
sourceMap[instruction.offset] = instruction.token.line;
if (baseValue === this.SYNTHETIC_INSTRUCTION) {
if (instruction.token.value === "DAT") {
machineCode[instruction.offset] = resolvedArg;
} else if (instruction.token.value === "CALL") {
machineCode[instruction.offset] = 400 + resolvedArg;
machineCode[instruction.offset + 1] = 920;
machineCode[instruction.offset + 2] = 910;
sourceMap[instruction.offset + 1] = instruction.token.line;
sourceMap[instruction.offset + 2] = instruction.token.line;
} else if (instruction.token.value === "SPUSHI") {
machineCode[instruction.offset] = 400 + resolvedArg;
machineCode[instruction.offset + 1] = 920;
sourceMap[instruction.offset + 1] = instruction.token.line;
}
} else {
if (this.ARG_INSTRUCTIONS.includes(instruction.token.value)) {
machineCode[instruction.offset] = baseValue + resolvedArg;
} else {
machineCode[instruction.offset] = baseValue;
}
}
}
return {
originalSource: asmSource,
sourceMap : sourceMap,
machineCode : machineCode
};
}
}
class FirthCompiler {
// variables for label generation
conditional = 1;
loop = 1;
variable = 1;
overflow = 1;
// variable names
variables = []
// a loop stack so stop elements can resolve proper jump label
loopStack = [];
// literal number values that require named DAT slots to hold
overflowValues = {};
// statement terminators
KEYWORDS = ["end", "loop", "else"];
// basic operations in Firth
OPS = {"+" : ["SADD"],
"-" : ["SSUB"],
"*" : ["SMUL"],
"/" : ["SDIV"],
"max" : ["SMAX"],
"min" : ["SMIN"],
"dup" : ["SDUP"],
"swap" : ["SSWAP"],
"pop" : ["SPOP"],
"drop" : ["SDROP"],
"return" : ["RET"],
"get" : ["INP", "SPUSH"],
"." : ["SDUP", "SPOP", "OUT"]}
// syntax patterns
FUNCTION_PATTERN = /^[a-zA-Z][a-zA-Z_]*\(\)$/
VARIABLE_PATTERN = /^[a-zA-Z][a-zA-Z_]*$/
VARIABLE_WRITE_PATTERN = /^[a-zA-Z][a-zA-Z_]*!$/
compile(firthSource) {
let lmsmTokenizer = new LMSMTokenizer(firthSource);
this.tokens = lmsmTokenizer.tokenize();
let rootElements = this.parseFirthProgram();
let codeGenResult = this.codeGen(rootElements);
let parseResult = {
parsedElements: rootElements,
sourceMap : codeGenResult.sourceMap,
assembly : codeGenResult.getAssembly(),
errors: this.collectErrors(rootElements),
originalSource: firthSource,
}
console.log(parseResult);
return parseResult
}
collectErrors(elements, errors) {
if (elements) {
errors ||= []
for (const elt of elements) {
if (elt.error) {
errors.push(
{
token: elt.token,
message: elt.error
}
);
}
this.collectErrors(elt.body, errors);
this.collectErrors(elt.trueBranch, errors);
this.collectErrors(elt.falseBranch, errors);
}
return errors;
}
}
currentToken(){
return this.tokens[0];
}
currentTokenValue(){
if (this.tokens[0]) {
return this.tokens[0].value;
}
}
hasMoreTokens(){
return this.tokens.length > 0;
}
takeToken(){
return this.tokens.shift();
}
currentTokenIsANumber() {
return !isNaN(this.tokens[0].value);
}
currentTokenIs(str) {
return this.tokens[0] && this.tokens[0].value === str;
}
currentTokenMatches(regex) {
return this.tokens[0] && this.tokens[0].value.match(regex);
}
currentTokenIsKeyword() {
return this.KEYWORDS.includes(this.tokens[0]);
}
parseFunctionCall() {
if (this.currentTokenMatches(this.FUNCTION_PATTERN)) {
let token = this.takeToken();
return {
type: "FunctionCall",
token:token,
functionName: token.value,
}
}
}
parseInt() {
if (this.currentTokenIsANumber()) {
let token = this.takeToken();
let numberLiteral = {
type: "Number",
token: token,
value: parseInt(token.value),
};
if (numberLiteral.value < -999 || 999 < numberLiteral.value) {
numberLiteral.error = "Numbers in Firth can only only be between -999 and 999";
}
return numberLiteral;
}
}
parseOp() {
if (this.OPS[this.currentTokenValue()]) {
let token = this.takeToken();
return {
type: "Op",
token: token,
op: token.value,
};
}
}
parseFunctionDef() {
if (this.currentTokenMatches("def")) {
let defToken = this.takeToken();
let nameToken = this.takeToken(); // take name as well
let functionDef = {
type: "FunctionDefinition",
token: defToken,
nameToken: nameToken,
name: nameToken.value,
body : [],
};
if (functionDef.name === null || !functionDef.name.match(this.FUNCTION_PATTERN)) {
functionDef.error = "Function names must end with ()"
}
while (this.hasMoreTokens() && !this.currentTokenIs("end")) {
functionDef.body.push(this.parseElement());
}
if (this.currentTokenIs("end")) {
this.takeToken();
} else {
functionDef.error = "Expected 'end' to close function"
}
return functionDef;
}
}
parseConditional() {
if (this.currentTokenIs("zero?") ||
this.currentTokenIs("positive?")) {
let token = this.takeToken();
let conditionalElt = {
type: "Conditional",
token: token,
conditionType: token.value,
conditionCount: this.conditional++,
trueBranch : [],
falseBranch : [],
};
while (this.hasMoreTokens() && !this.currentTokenIs("end") && !this.currentTokenIs("else")) {
conditionalElt.trueBranch.push(this.parseElement());
}
if (this.currentTokenIs("else")) {
this.takeToken(); // consume else
while (this.hasMoreTokens() && !this.currentTokenIs("end")) {
conditionalElt.falseBranch.push(this.parseElement());
}
}
if (this.currentTokenIs("end")) {
this.takeToken();
} else {
conditionalElt.error = "Expected 'end' to close conditional"
}
return conditionalElt;
}
}
parseStop() {
if (this.currentTokenIs("stop")) {
let currentLoop = this.loopStack[this.loopStack.length - 1];
let stopLoop = {
type: "Stop",
token: this.takeToken(),
loop: currentLoop
};
if (currentLoop == null) {
stopLoop.error = "stop must appear inside a loop";
}
return stopLoop;
}
}
parseLoop() {
if (this.currentTokenIs("do")) {
let loopElt = {
loopCount : this.loop++,
type: "Loop",
token: this.takeToken(),
body : [],
};
this.loopStack.push(loopElt);
while (this.hasMoreTokens() && !this.currentTokenIs("loop")) {
loopElt.body.push(this.parseElement());
}
this.loopStack.pop();
if (this.currentTokenIs("loop")) {
loopElt.loopToken = this.takeToken()
} else {
loopElt.error = "Expected 'loop' to close loop"
}
return loopElt;
}
}
parseVariableDeclaration() {
if (this.currentTokenIs("var")) {
let varToken = this.takeToken();
let nameToken = this.takeToken();
let variableElt = {
variableCount : this.variable++,
type: "VariableDeclaration",
token: varToken,
nameToken: nameToken,
name: nameToken ? nameToken.value : null,
};
this.variables.push(variableElt.name)
if (variableElt.name == null || !variableElt.name.match(this.VARIABLE_PATTERN)) {
variableElt.error = "Expected variable to have a name"
}
return variableElt;
}
}
parseVariableRead() {
if (this.currentTokenMatches(this.VARIABLE_PATTERN) && !this.currentTokenIsKeyword()) {
let variableRead = {
type: "VariableRead",
token: this.takeToken(),
};
if (!this.variables.includes(variableRead.token.value)) {
variableRead.error = "No variable named " + variableRead.token.value + " found!";
}
return variableRead;
}
}
parseVariableWrite() {
if (this.currentTokenMatches(this.VARIABLE_WRITE_PATTERN)) {
let token = this.takeToken();
let variableWrite = {
type: "VariableWrite",
token: token,
name: token.value.substring(0, token.value.length - 1)
};
if (!this.variables.includes(variableWrite.name)) {
variableWrite.error = "No variable named " + variableWrite.name + " found!";
}
return variableWrite
}
}
parseAssembly() {
if (this.currentTokenIs("asm")) {
let asmElt = {
type: "Assembly",
token: this.takeToken(),
assembly: []
};
var line = null;
while (this.hasMoreTokens() && !this.currentTokenIs("end")) {
let currentToken = this.takeToken();
if (line === null) {
line = currentToken.line
} else if(line !== currentToken.line) {
line = currentToken.line;
asmElt.assembly.push(""); // pass newline through
}
asmElt.assembly.push(currentToken.value);
}
if (this.currentTokenIs("end")) {
this.takeToken();
} else {
asmElt.error = "Expected 'end' to close asm"
}
return asmElt;
}
}
parseElement() {
let elt = this.parseInt();
if (elt) {
return elt;
}
let op = this.parseOp();
if (op) {
return op;
}
let conditional = this.parseConditional();
if (conditional) {
return conditional;
}
let call = this.parseFunctionCall();
if (call) {
return call;
}
let def = this.parseFunctionDef();
if (def) {
return def;
}
let loop = this.parseLoop();
if (loop) {
return loop;
}
let stop = this.parseStop();
if (stop) {
return stop;
}
let asm = this.parseAssembly();
if (asm) {
return asm;
}
let variableRead = this.parseVariableRead();
if (variableRead) {
return variableRead;
}
let variableWrite = this.parseVariableWrite();
if (variableWrite) {
return variableWrite;
}
let badVariableDeclaration = this.parseVariableDeclaration();
if (badVariableDeclaration) {
badVariableDeclaration.error = "Variables must be declared at the start of a Firth program"
return badVariableDeclaration;
}
let token = this.takeToken();
return {
type: "ERROR",
error: "Unknown token : " + token.value,
token: token
};
}
parseFirthProgram() {
let program = [];
// variables must come first
let varDeclaration = this.parseVariableDeclaration();
while (varDeclaration != null) {
program.push(varDeclaration);
varDeclaration = this.parseVariableDeclaration();
}
let restOfProgram = this.parseElements();
for (const elt of restOfProgram) {
program.push(elt);
}
return program;
}
parseElements() {
let elements = [];
while (this.hasMoreTokens()) {
elements.push(this.parseElement());
}
return elements;
}
codeGenForElement(element, code) {
if (element.type === "Number") {
if (0 <= element.value && element.value <= 99) {
code.add("SPUSHI " + element.value, element.token);
} else {
let overflowSlotLabel = "_OVERFLOW_" + this.overflow++;
this.overflowValues[overflowSlotLabel] = element.value;
code.add("LDA " + overflowSlotLabel, element.token);
code.add("SPUSH", element.token);
}
} else if (element.type === "Op") {
let opAssembly = this.OPS[element.op];
for (const asm of opAssembly) {
code.add(asm, element.token);
}
} else if (element.type === "FunctionCall") {
code.add("CALL " + element.functionName, element.token);
} else if (element.type === "FunctionDefinition") {
code.labelNextInstruction(element.name);
for (const elt of element.body) {
this.codeGenForElement(elt, code);
}
// implicit return is last element of the body, if any
code.add("RET");
} else if (element.type === "Conditional") {
let trueLabel = "COND_" + element.conditionCount;
let endLabel = "END_COND_" + element.conditionCount;
code.add("SPOP", element.token);
if (element.conditionType === "zero?") {
code.add("BRZ " + trueLabel);
} else {
code.add("BRP " + trueLabel);
}
if (element.falseBranch.length > 0) {
for (const elt of element.falseBranch) {
this.codeGenForElement(elt, code);
}
}
code.add("BRA " + endLabel);
code.labelNextInstruction(trueLabel);
if (element.trueBranch.length > 0) {
for (const elt of element.trueBranch) {
this.codeGenForElement(elt, code);
}
} else {
code.add("ADD ZERO");
}
code.labelNextInstruction(endLabel);
code.add("ADD ZERO");
} else if (element.type === "Loop") {
let startLabel = "LOOP_" + element.loopCount;
let endLabel = "END_LOOP_" + element.loopCount;
code.labelNextInstruction(startLabel);
for (const elt of element.body) {
this.codeGenForElement(elt, code);
}
code.add("BRA " + startLabel, element.loopToken);
code.labelNextInstruction(endLabel);
code.add("ADD ZERO");
} else if (element.type === "Stop") {
code.add("BRA END_LOOP_" + element.loop.loopCount, element.token);
} else if (element.type === "VariableRead") {
code.add("LDA " + element.token.value, element.token);
code.add("SPUSH", element.token);
} else if (element.type === "VariableWrite") {
let variableName = element.name;
code.add("SPOP", element.token);
code.add("STA " + variableName, element.token);
} else if (element.type === "VariableDeclaration") {
code.add(element.name + " DAT 0");
} else if (element.type === "Assembly") {
code.add(element.assembly.join(" "), element.token);
}
}
codeGen(elements) {
let code = new FirthCodeGenerator();
// generate non-functions&vars first
for (const element of elements.filter(element => element.type !== "FunctionDefinition" && element.type !== "VariableDeclaration")) {
this.codeGenForElement(element, code);
}
code.add("ZERO HLT"); // End program with a halt, labeled zero to support no-ops
// generate functions second
for (const element of elements.filter(element => element.type === "FunctionDefinition")) {
this.codeGenForElement(element, code);
}
// allocated variable memory third
for (const element of elements.filter(element => element.type === "VariableDeclaration")) {
this.codeGenForElement(element, code);
}
// overflow literal values fourth
for (const label in this.overflowValues) {
code.add(label + " DAT " + this.overflowValues[label]);
}
return code
}
}
/**
* This is a simple class to collect ASM instructions and produce a map of ASM instruction lines to Firth program
* lines.
*/
class FirthCodeGenerator {
// generated assembly
code = [];
// map of source lines to firth program lines
sourceMap = {};
// label for next instruction
label = null;
// last line
currentSourceLine = 0;
labelNextInstruction(str) {
if (this.label) {
throw "Cannot label same instruction twice!";
} else {
this.label = str;
}
}
add(instruction, token) {
// consume the current label, if any
if (this.label) {
instruction = this.label + " " + instruction;
this.label = null;