Jump to content

Compiler/virtual machine interpreter: Difference between revisions

m
Minor improvement to coding.
(New post.)
m (Minor improvement to coding.)
Line 8,426:
 
public static void main(String[] args) throws IOException {
Path pathfilePath = Path.of("Compiler Test Cases/AsciiMandlebrot.txt");
VirtualMachineInfo info = loadCode(pathfilePath);
runVirtualMachine(info.dataSize, info.vmStrings, info.codes());
}
Line 8,439:
int index = 0;
OP_CODEOpCode opCode = null;
while ( opCode != OP_CODEOpCode.HALT ) {
opCode = OP_CODEOpCode.havingCode(codes.get(index));
index += 1;
Line 8,458:
case NE -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) != stack.pop() ) ? 1 : 0);
case AND -> { final int value = ( stack.get(stack.size() - 2) != 0 && stack.pop() != 0 ) ? 1 : 0;
stack.set(stack.size() - 1, value);
}
case OR -> { final int value = ( stack.get(stack.size() - 2) != 0 || stack.pop() != 0 ) ? 1 : 0;
Line 8,478:
}
private static VirtualMachineInfo loadCode(Path pathfilePath) throws IOException {
List<String> lines = Files.readAllLines(pathfilePath, StandardCharsets.UTF_8);
String line = lines.getFirst();
Line 8,502:
sections = lines.get(i).trim().split("\\s+");
offset = Integer.parseInt(sections[0]);
OP_CODEOpCode opCode = OP_CODEOpCode.valueOf(sections[1].toUpperCase());
codes.addLast(opCode.byteCode());
Line 8,518:
private static int operand(int index, List<Byte> codes) {
bufferbyteBuffer.clear();
for ( int i = index; i < index + 4; i++ ) {
bufferbyteBuffer.put((byte) codes.get(i));
}
bufferbyteBuffer.flip();
return bufferbyteBuffer.getInt();
}
private static void addToCodes(int number, List<Byte> codes) {
bufferbyteBuffer.clear();
bufferbyteBuffer.putInt(number);
bufferbyteBuffer.flip();
for ( byte bb : bufferbyteBuffer.array() ) {
codes.addLast(bb);
}
Line 8,557:
}
private static ByteBuffer bufferbyteBuffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
private static enum OP_CODEOpCode {
HALT(0), ADD(1), SUB(2), MUL(3), DIV(4), MOD(5), LT(6), GT(7), LE(8), GE(9), EQ(10), NE(11),
Line 8,569:
}
public static OP_CODEOpCode havingCode(Byte byteCode) {
return op_codes[(int) byteCode];
}
private OP_CODEOpCode(int aByteCode) {
byteCode = aByteCode;
}
Line 8,579:
private int byteCode;
private static OP_CODEOpCode[] op_codes = values();
}
907

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.