Skip to content

Commit

Permalink
Implemented RamCode object for future compiler use
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicola Pfister committed Oct 4, 2016
1 parent 94aca76 commit c1280c1
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/JohnnyScript.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import java.nio.file.Path;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* Compiles JohnnyScript (.jns) files to ram files for the Johnny Simulator
Expand Down Expand Up @@ -158,6 +160,68 @@ public String getCode() {

}

class RamCode {

private static final int MAX_LINES = 999;

private static int writeIndex;

private ArrayList<String> code;
private Map<String, Integer> variables;

RamCode() {
code = new ArrayList<>();
variables = new LinkedHashMap<>();
}

public void addCode(String input) {
code.add(input);
}

public void addVar(String name, int value) throws DuplicateVariableException {
if (variables.containsKey(name)) {
throw new DuplicateVariableException("Variable cannot be defined twice: " + name);
} else variables.put(name, value);
}

private List<String> initializeZeros(List<String> code) {
for (int i = 0; i <= MAX_LINES; i++) {
code.add("000");
}
return code;
}

List getCode() {
List<String> output = new ArrayList<>();
initializeZeros(output);

writeIndex = 0;

output.set(writeIndex, generateLineZero());
writeIndex++;

variables.forEach((k,v) -> {
output.set(writeIndex, String.format("%03d",v));
writeIndex++;
});

for (String loc: code
) {
output.add(writeIndex, loc);
writeIndex++;
}

assert writeIndex == 1 + variables.size() + code.size();

return output;
}

private String generateLineZero() {
String firstLocAdress = String.format("%03d",variables.size()+1);
return JohnnyScript.Codes.JMP.codeOrdinal + firstLocAdress;
}
}

class InvalidScriptException extends Exception {

InvalidScriptException(String message) {
Expand All @@ -171,3 +235,8 @@ class CompilerHaltException extends RuntimeException {
super(message, cause);
}
}

class DuplicateVariableException extends Exception {

DuplicateVariableException(String message) {super(message);}
}
23 changes: 23 additions & 0 deletions test/RamCodeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.*;

/**
* Test class for RamCode object
*/
public class RamCodeTest {

@Test
public void testInitialize() throws Exception {
RamCode code = new RamCode();
List codeList = code.getCode();

assertEquals(JohnnyScript.Codes.JMP.codeOrdinal + "001",codeList.get(0));

for (int i = 1; i < 1000; i++) {
assertEquals("000",codeList.get(i));
}
}
}

0 comments on commit c1280c1

Please sign in to comment.