-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmpCompiler.java
More file actions
786 lines (679 loc) · 25.4 KB
/
Copy pathSmpCompiler.java
File metadata and controls
786 lines (679 loc) · 25.4 KB
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
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
enum Status {
CONTINUE, BREAK, DONE
}
/**
* A variable class with address
*/
class SmpVariable {
public int address;
public String name;
public String value;
public SmpVariable(int address, String name, String value) {
this.address = address;
this.name = name;
this.value = value;
}
}
/**
* ------------------------------------
* High-level Simpletron Instructions Compiler
*
* @author Maverick G. Fabroa
* Date: October 11, 2022
* ------------ Features: -------------
* 1. Compile high-level simpletron instruction into low-level.
* 2. Dynamic branching with `@branch_name` anywhere in the program.
* 3. Evaluate arithmetic expressions.
* 4. Declare variables anywhere.
* 5. Include only used variables to improve memory efficiency.
* 6. Show error if variable declared but doesn't have a value.
* 7. Detect whether the variable already exist.
* 8. Detect whether the variable doesn't exist.
* 9. Detect whether the command is valid or not.
* 10. Single line comment with ">"
* 11. Append HALT instruction at the end of the program if not explicitly added.
* ------------------------------------
*/
public class SmpCompiler {
// Simpletron high-level commands
private final HashMap<String, Integer> commands = createCommands();
// Simpletron branch storage
private final HashMap<String, Integer> branches = new HashMap<String, Integer>();
// Variable storage
private final List<SmpVariable> variables = new ArrayList<SmpVariable>();
// Initialize the program storage
private final List<String> program = new ArrayList<String>();
// List of operands
private final List<Integer> operands = new ArrayList<Integer>();
// Initialize output
private final List<String> output = new ArrayList<String>();
// Input extension name
private final String INPUT_FILE_EXT = "smp";
// Output extension name
private final String OUTPUT_FILE_EXT = "sml";
// Branch keyword identifier
private final String BRANCH_IDENTIFIER = "@";
// Initialize input file name
private String inputFilename = "";
// Compilation time
private long compilationTime = 0;
// Flag if the input program has a halt instruction
private boolean hasHalt = false;
/**
* Initialize compiler with file name
*
* @param filename Input filename
* @throws FileNotFoundException If file doesn't exist
*/
public SmpCompiler(String filename) throws FileNotFoundException {
// Get the file
File file = new File(filename);
// Check if the file doesn't exist
if (!file.exists()) {
error("file not found " + filename);
}
// Check input filename
if (!isSmpFile(filename)) {
error("must be a ." + INPUT_FILE_EXT + " file.");
}
// Reset simpletron properties
reset();
// Otherwise, read the file
Scanner sc = new Scanner(file);
// Read the file line by line
while (sc.hasNextLine()) {
// Get the line, and trim
String line = sc.nextLine().trim();
// add to program
program.add(line);
// If the line is not empty, increment
if (line.equals("HALT")) {
// Set the flag to true
hasHalt = true;
}
}
// Set input filename
inputFilename = filename;
// Close the scanner
sc.close();
}
/**
* Compiles the program
*/
public void compile() throws Exception {
// If the program is empty, return
if (isProgramEmpty()) {
error("no instructions written (" + inputFilename + ")");
return;
}
// Set initial compilation time
compilationTime = System.currentTimeMillis();
// Loop through the program
for (int i = 0; i < program.size(); i++) {
// Remove trailing and leading whitespace
String line = program.get(i).trim();
// Check if the line is a comment, or
// Check if the line is empty
if (line.startsWith(">") || line.isEmpty()) {
// Proceed to next line
continue;
}
// Check if the line is a variable declaration
if (line.contains("=")) {
// If it has plus or minus sign
if (line.contains("+") || line.contains("-")) {
// Check if it's an arithmetic expression
// Split by operators
String[] split = line.split("=")[1].split("[+-]");
// If expression
boolean isExpression = true;
// Loop through the split
for (String s : split) {
// If s is blank
if (s.trim().isEmpty()) {
// Proceed to next line
isExpression = false;
break;
}
}
// If it's an expression
if (isExpression) {
// Process expression declaration
processExpression(i, line);
// Proceed to next line
continue;
}
}
// Process variable declaration
processVariable(i, line);
// Proceed to next line
continue;
}
// If current line is a branch declaration
if (line.startsWith(BRANCH_IDENTIFIER)) {
// Process branch declaration
processBranch(i, line);
// Proceed to next line
continue;
}
// Using other commands
// Split the line by space
String[] commandTokens = line.split(" ", 2);
// Get command (e.g READ, STORE, LOAD, ...)
// If tokens length is only 1 and is not HALT
if (commandTokens.length == 1 && !commandTokens[0].equals("HALT")) {
// Check if command is exist
if (commands.containsKey(commandTokens[0])) {
// Incomplete command
error("incomplete command '" + line + "' in " + getFilenameWithLine(i));
}
// Otherwise, throw error
error("unknown command '" + commandTokens[0] + "' in " + getFilenameWithLine(i));
}
// Check if the command exist
if (commands.containsKey(commandTokens[0])) {
// Process command
Status status = processCommand(i, commandTokens);
// Check if the status is done
if (status == Status.BREAK) {
// Break the loop
break;
} else if (status == Status.CONTINUE) {
// Proceed to next line
continue;
}
// Proceed to next line
continue;
}
// Otherwise, throw error
error("unknown command '" + commandTokens[0] + "' in " + getFilenameWithLine(i));
}
// If the instruction doesn't have a halt instruction
// Automatically add a HALT instruction
if (!hasHalt) {
// Add a HALT
output.add(commands.get("HALT") + "00");
}
// Process operands
processOperands();
// Calculate compilation time
compilationTime = System.currentTimeMillis() - compilationTime;
// Output file
if (generateOutput(output)) {
// Print output statistics
printOutputStats(output, true);
}
}
// ===================== Utility methods ===================== //
/**
* Process expression
*/
private void processExpression(int i, String line) {
// Remove all spaces
line = line.replaceAll(" ", "");
// Split by equal sign
String[] splits = line.split("=", 2);
// Get variable name
String varName = splits[0];
// Get expression
String varExpression = splits[1];
// Split expression by plus sign and minus sign
String[] expressionSplits = varExpression.split("");
// Current variable
String currentVar = "";
// Parsed expression
List<String> expression = new ArrayList<String>();
// Loop through the expression splits
for (String ch : expressionSplits) {
// Check if the split is a plus or minus sign
if (ch.equals("+") || ch.equals("-")) {
// Add variable to the list
expression.add(currentVar);
expression.add(ch);
// Reset current variable
currentVar = "";
// Proceed to next split
continue;
}
// Otherwise, add to current variable
currentVar += ch;
}
// Add the last variable
expression.add(currentVar);
// Add variable if not exist
if (getVariableAddress(varName) == -1) {
// Add var name to the list
variables.add(new SmpVariable(i, varName, "0"));
}
// Process expression
// Start at 2
for (int j = 2; j < expression.size(); j++) {
// Get expression component
String component = expression.get(j);
// Check if the component is not an operator
// Then it's a variable
if (!component.equals("+") && !component.equals("-")) {
// Get both components
String v1 = expression.get(j - 2); // (e.g, 5)
String op = expression.get(j - 1); // (e.g, +)
String v2 = expression.get(j); // (e.g, 10)
// Find and get the first variable's address
int v1Address = getVariableAddress(v1);
int v2Address = getVariableAddress(v2);
// Check if the variable is not found
if (v1Address == -1) {
// Throw error
error("variable '" + v1 + "' not found in " + getFilenameWithLine(i));
}
// Check if the variable is not found
if (v2Address == -1) {
// Throw error
error("variable '" + v2 + "' not found in " + getFilenameWithLine(i));
}
// Add opcodes to the output
output.add(commands.get("LOAD").toString());
output.add(commands.get(op.equals("+") ? "ADD" : "SUBTRACT").toString());
output.add(commands.get("STORE").toString());
// Add operands to operands
operands.add(j > 2 ? getVariableAddress(varName) : v1Address);
operands.add(v2Address);
operands.add(getVariableAddress(varName));
}
}
}
/**
* Post process variables and operands
*/
private void processOperands() {
// Added variables in the output
List<Integer> addedVariables = new ArrayList<Integer>();
// For every variable in the program
for (SmpVariable v : variables) {
// Loop every operands
for (int i = 0; i < operands.size(); i++) {
// If the current operand is same as the current variable address
if (operands.get(i) == v.address) {
// If the variable isn't in the output yet
if (!addedVariables.contains(v.address)) {
// Then add the variable to the output
output.add(v.value);
// Added variables
addedVariables.add(v.address);
}
// New address
int newAddress = output.size() - 1;
// Set new address
operands.set(i, newAddress);
}
}
}
// Loop every operands
for (int i = 0; i < operands.size(); i++) {
// Get opcode
String opcode = output.get(i);
// Get operand
int operand = operands.get(i);
// If opcode number is a branch instruction
if (opcode.startsWith("40") || opcode.startsWith("41") || opcode.startsWith("42")) {
continue;
}
// Set output
output.set(i, String.valueOf(opcode) + (operand < 10 ? "0" + operand : operand));
}
}
/**
* Process command
*
* @param i line index
* @param commandTokens line chunks
* @return Status
*/
private Status processCommand(int i, String[] commandTokens) {
// Get command
String command = commandTokens[0];
// Get operand
String operand = "";
// If has operand
if (commandTokens.length > 1) {
operand = commandTokens[1];
}
// Get opcode
final String OPCODE = commands.get(command).toString();
// If command is HALT
if (command.equals("HALT")) {
// Add its opcode and exit the loop
output.add(OPCODE + "00");
// return break
return Status.BREAK;
}
// Otherwise, get value or variable name
String OPERAND = operand.replaceAll(" ", "");
// If command is a branch
if (command.contains("BRANCH")) {
// Get branch name
String branchName = OPERAND.substring(1, OPERAND.length());
// If branch has no identifier name
if (branchName.length() == 0) {
// Show error
error("branch name is missing " + getFilenameWithLine(i));
}
// Find branch name
if (branches.containsKey(branchName)) {
// Get address
int addr = branches.get(branchName);
// Add to output
output.add(OPCODE + (addr < 10 ? "0" + addr : addr));
// Add to operand
operands.add(-1);
// Proceed to next line
return Status.CONTINUE;
}
// Flag if branch declaration is after the branch callee
boolean isFound = false;
// Loop through the file next to the error
for (int j = i + 1, k = 0; j < program.size(); j++, k++) {
// Get current line
String line = program.get(j);
// Get branch name
String name = line.replaceAll(" ", "");
// If branch name exist after the branch line
if (name.startsWith(BRANCH_IDENTIFIER) && name.contains(branchName)) {
// Adjust address
int addr = output.size() + k;
// Add to output
output.add(OPCODE + (addr < 10 ? "0" + addr : addr));
// Add to operand
operands.add(-1);
// Set found to true
isFound = true;
// Break the loop
break;
}
}
// If branch declaration not found
if (!isFound) {
// Show error
error("branch name '" + BRANCH_IDENTIFIER + branchName + "' doesn't exist in " + getFilenameWithLine(i));
}
// Process to next line
return Status.CONTINUE;
}
// Loop through the variable
for (SmpVariable v : variables) {
// If variable name is not null and is same with the current variable
if (v.name != null && v.name.equals(OPERAND)) {
// Set vName to the address of that variable
OPERAND = (v.address < 10 ? "0" + v.address : v.address).toString();
}
}
// Variable not found
if (operand.equals(OPERAND)) {
error("variable '" + OPERAND + "' not found in " + getFilenameWithLine(i));
}
// Add opcode to output
output.add(OPCODE);
// Add operand to operands (to be incremented based on how many lines does the output sml have)
operands.add(Integer.parseInt(OPERAND));
// Return success
return Status.DONE;
}
/**
* Process branch
*
* @param i line index
* @param line current line
*/
private void processBranch(int i, String line) {
// Remove all whitespace
line = line.replaceAll(" ", "");
// Get name
String name = line.substring(1, line.length());
// Check if branch name already exist
if (branches.containsKey(name)) {
// Show error
error("branch '" + BRANCH_IDENTIFIER + name + "' already exist " + getFilenameWithLine(i));
}
// Add branch to branches
branches.put(name, output.size());
}
/**
* Process variable
*
* @param i line index
* @param line current line
*/
private void processVariable(int i, String line) {
// Remove all whitespaces
line = line.replaceAll(" ", "");
// Split line by equal (=) sign
String[] tokens = line.split("=");
// Get variable name
String vName = tokens[0];
// Check if tokens has only 1 value
if (tokens.length == 1) {
// Show error
error("variable '" + vName + "' doesn't have a value " + getFilenameWithLine(i));
}
// Get variable value
String vValue = tokens[1];
// Check if variable has been declared
// Loop through declared variables
for (SmpVariable v : variables) {
// Check if variable name already exist
if (v.name.equals(vName)) {
error("variable '" + vName + "' already exist " + getFilenameWithLine(i));
}
}
// If not exist, then store it in the variables list
variables.add(new SmpVariable(i, vName, vValue));
}
// =========================================================== //
/**
* Get variable's address
*
* @param varName variable name
* @return address
*/
private int getVariableAddress(String varName) {
// Loop through the variables
for (SmpVariable v : variables) {
// If variable name is not null and is same with the current variable
if (v.name != null && v.name.equals(varName)) {
// Return the address of that variable
return v.address;
}
}
// Variable not found
return -1;
}
/**
* Generate low-level simpletron instructions
*
* @param program List of instructions
* @return boolean
* @throws Exception If errors occurred when closing the file
*/
private boolean generateOutput(List<String> program) throws Exception {
// Initialize file output name
String outputFilename = getOutputFilename();
// Create file
File file = new File(outputFilename);
// Create file if not exist or file already exist
if (file.createNewFile() || file.exists()) {
// Initialize FileWriter with file
FileWriter io = new FileWriter(file);
// For every line in program
for (String line : program) {
// Write the output to the file
io.write(line + "\n");
}
// Close file writer
io.close();
// Return success
return true;
}
return false;
}
/**
* Get output filename based on the input file name
*
* @return file name
*/
private String getOutputFilename() {
// Set default output name
String name = inputFilename;
// Get period last index
int index = inputFilename.lastIndexOf(".");
// If found
if (index > 0) {
// Get filename without extension
name = name.substring(0, index) + "." + OUTPUT_FILE_EXT;
}
// return name
return name;
}
/**
* Check whether the input file name have .smp extension
*
* @param filename Input file name
* @return boolean
*/
private boolean isSmpFile(String filename) {
return filename != null && filename.trim().endsWith("." + INPUT_FILE_EXT);
}
/**
* Get filename with line number based on the program execution index
*
* @param index line index
* @return filename with line
*/
private String getFilenameWithLine(int index) {
return "(" + inputFilename + ":" + (index + 1) + ")";
}
/**
* Check if program is empty
*/
private boolean isProgramEmpty() {
if (program.size() == 0) {
return true;
}
for (String line : program) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
return true;
}
/**
* Print compilation output statistics
*
* @param output List of instructions
* @param showOutput Whether to show output when compiling
*/
private void printOutputStats(List<String> output, boolean showOutput) {
// Get file size
final long SIZE = new File(getOutputFilename()).length();
// Print info
line();
System.out.println("Compiled to : " + getOutputFilename() + " (" + SIZE + " bytes)");
System.out.println("Compilation time : " + compilationTime + " ms");
System.out.println("Number of lines : " + output.size());
line();
// If showOutput
if (showOutput) {
// For every line in the output
for (int i = 0; i < output.size(); i++) {
// Print current line
System.out.println((i < 10 ? "0" + i : i) + " " + output.get(i));
}
line();
}
}
/**
* Get low-level simpletron instructions
*
* @return key-value pair of the instructions
*/
private HashMap<String, Integer> createCommands() {
HashMap<String, Integer> commands = new HashMap<String, Integer>();
commands.put("READ", 10);
commands.put("WRITE", 11);
commands.put("LOAD", 20);
commands.put("STORE", 21);
commands.put("ADD", 30);
commands.put("SUBTRACT", 31);
commands.put("BRANCH", 40);
commands.put("BRANCHNEG", 41);
commands.put("BRANCHZERO", 42);
commands.put("HALT", 43);
return commands;
}
/**
* Reset simpletron properties
*/
private void reset() {
// Reset list
variables.clear();
program.clear();
operands.clear();
branches.clear();
// Reset properties
inputFilename = "";
compilationTime = 0;
}
/**
* Print a line
*/
private static void line() {
System.out.println("------------------------------------------");
}
/**
* Generate a compilation error message and exit the program
*
* @param message The message
*/
private static void error(String message) {
line();
System.err.println("Error: " + message);
line();
System.exit(1);
}
/**
* Run output with Simpletron Interpreter
*/
public void run() throws Exception {
// Initialize simpleton
SmpSimpletron simpletron = new SmpSimpletron(getOutputFilename());
// Execute low-level simpletron code
simpletron.execute();
}
/**
* Main program
*
* @param args Name of the input
* @throws Exception If an error occurred
*/
public static void main(String[] args) throws Exception {
// Check if args have values
if (args.length > 0) {
// Instantiate the high-level simpletron compiler with the first value
// which is assuming an input high-level simpletron instructions
SmpCompiler compiler = new SmpCompiler(args[0]);
compiler.compile();
// Run simpletron if no "-" after input filename when running
if (!(args.length > 1 && args[1].equals("-"))) {
compiler.run();
}
return;
}
// Otherwise, show no input specified
SmpCompiler.error("no input file specified.");
}
}