Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package ru.jengine.virtualmachine;

import ru.jengine.virtualmachine.commands.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

public static void main(String[] args) {
List<Object> firstStorage = new ArrayList<>(Arrays.asList(5, 7, 2));
byte[] firstCode = {
0b00,
0,
0b00,
1,
0b100,
0b00,
2,
0b01
};
VirtualMachine virtualMachine = new VirtualMachine(List.of(new Add(), new Const(), new Sub(), new Div(), new Mul(), new Jump()));
virtualMachine.registerScript(firstStorage, firstCode);
virtualMachine.executeRegisteredContexts();

// TODO: Handle errors?
}
}
28 changes: 28 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/VMStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ru.jengine.virtualmachine;

import java.util.ArrayDeque;

public class VMStack {
private final int stackSize;
private final ArrayDeque<Object> stack;

public VMStack(int capacity) {
stackSize = capacity;
stack = new ArrayDeque<>(capacity);
}

public Object pop() {
return stack.pop();
}

public void push(Object element) {
if (stack.size() == stackSize) {
throw new StackOverflowError("VM's stack has overflowed.");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут давай кидать тоже VirtualMachineException. throw new VirtualMachineException(VM's stack has overflowed! Command push is unavailable);

}
stack.push(element);
}

public Object peek() {
return stack.peek();
}
}
53 changes: 53 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/VirtualMachine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package ru.jengine.virtualmachine;

import ru.jengine.virtualmachine.commands.*;
import ru.jengine.virtualmachine.context.ScriptContext;
import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class VirtualMachine {

private final Map<Byte, Command> commandsMap;

private final List<ScriptContext> contexts = new ArrayList<>();

public VirtualMachine(List<Command> commands) {
commandsMap = commands.stream().collect(Collectors.toMap(Command::getOpCode, Function.identity()));
}

public void executeRegisteredContexts() {
for (ScriptContext context : this.contexts) {
execute(context);
}
}

private Command extractNextCommand(ScriptContext context, byte[] code) {
byte opCode = code[context.getInstructionPointer()];
return commandsMap.get(opCode);
}

public void registerScript(List<Object> initialStorage, byte[] bytecode) {
ScriptContext scriptContext = new ScriptContext(initialStorage, bytecode);
contexts.add(scriptContext);
}

private void execute(ScriptContext context) {
byte[] code = context.getCode();
while (context.getInstructionPointer() < code.length) {
Command command = extractNextCommand(context, code);
try {
int offset = command.execute(context);
context.moveInstructionPointer(offset);
} catch (VirtualMachineException e) {
throw e; // TODO: ???
}
}

}

}
27 changes: 27 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Add.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ru.jengine.virtualmachine.commands;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Предлагаю начать писать тесты :) По сути весь данный пакет должен перекочевать в тестовую структуру, за исключением интерфейса Command

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Context (Script)
  • VM (+ перенести имеющиеся команды в тесты)


import ru.jengine.virtualmachine.context.CommandContext;
import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

public class Add implements Command {
private static final byte[] opCode = {0b0000_0001};
private static final int offset = 1;

@Override
public Byte getOpCode() {
return opCode[0];
}

@Override
public int execute(CommandContext context) {
Object firstOp = context.popFromStack();
Object secondOp = context.popFromStack();

if (firstOp instanceof Number && secondOp instanceof Number) {
Number result = BinaryHandler.sumTwoNumbers((Number) firstOp, (Number) secondOp);
context.pushToStack(result);
} else throw new VirtualMachineException("Add operation uses two instances of Number.");

return offset;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package ru.jengine.virtualmachine.commands;


import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

public class BinaryHandler {
public static Number sumTwoNumbers(Number firstOp, Number secondOp) {
if (firstOp instanceof Double || secondOp instanceof Double) {
return firstOp.doubleValue() + secondOp.doubleValue();
} else if (firstOp instanceof Float || secondOp instanceof Float) {
return firstOp.floatValue() + secondOp.floatValue();
} else if (firstOp instanceof Long || secondOp instanceof Long) {
return firstOp.longValue() + secondOp.longValue();
} else {
return firstOp.intValue() + secondOp.intValue();
}
}

public static Number mulTwoNumbers(Number firstOp, Number secondOp) {
if (firstOp instanceof Double || secondOp instanceof Double) {
return firstOp.doubleValue() * secondOp.doubleValue();
} else if (firstOp instanceof Float || secondOp instanceof Float) {
return firstOp.floatValue() * secondOp.floatValue();
} else if (firstOp instanceof Long || secondOp instanceof Long) {
return firstOp.longValue() * secondOp.longValue();
} else {
return firstOp.intValue() * secondOp.intValue();
}
}

public static Number subTwoNumbers(Number firstOp, Number secondOp) {
if (firstOp instanceof Double || secondOp instanceof Double) {
return firstOp.doubleValue() - secondOp.doubleValue();
} else if (firstOp instanceof Float || secondOp instanceof Float) {
return firstOp.floatValue() - secondOp.floatValue();
} else if (firstOp instanceof Long || secondOp instanceof Long) {
return firstOp.longValue() - secondOp.longValue();
} else {
return firstOp.intValue() - secondOp.intValue();
}
}

public static Number divTwoNumbers(Number firstOp, Number secondOp) {
if (secondOp.doubleValue() < 1.0E-10) {
throw new VirtualMachineException("Division by zero is restricted.");
}

if (firstOp instanceof Double || secondOp instanceof Double) {
return firstOp.doubleValue() / secondOp.doubleValue();
} else if (firstOp instanceof Float || secondOp instanceof Float) {
return firstOp.floatValue() / secondOp.floatValue();
} else if (firstOp instanceof Long || secondOp instanceof Long) {
return firstOp.doubleValue() / secondOp.longValue();
} else {
return firstOp.floatValue() / secondOp.intValue();
}
}
}
10 changes: 10 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Command.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;

public interface Command {
Byte getOpCode();

int execute(CommandContext context);

}
22 changes: 22 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Const.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;

public class Const implements Command {
private static final byte[] opCode = {0b0000_0000};
private static final int offset = 2;

@Override
public Byte getOpCode() {
return opCode[0]; // TODO: Byte[] opcode
}

@Override
public int execute(CommandContext context) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай, наверное, унаследуем VirtualMachineException от Exception и тут сделаем throws VirtualMachineException.
Соответственно во всех метода контекста, где может упасть ошибка виртуальной машины - тоже добавим throws

byte storageIndex = context.readBytes(1)[0];
Object constValue = context.getElementByIndex(storageIndex);
context.pushToStack(constValue);
return offset;
}

}
30 changes: 30 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Div.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;
import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

public class Div implements Command {
private static final byte[] opCode = {0b0000_0100};
private static final int offset = 1;

@Override
public Byte getOpCode() {
return opCode[0];
}

@Override
public int execute(CommandContext context) {
Object firstOp = context.popFromStack();
Object secondOp = context.popFromStack();
if (firstOp instanceof Number && secondOp instanceof Number) {
try {
Number result = BinaryHandler.divTwoNumbers((Number) firstOp, (Number) secondOp);
context.pushToStack(result);
} catch (VirtualMachineException e) {
throw e; // TODO: ???
}
} else throw new VirtualMachineException("Divide operation uses two instances of Number.");
return offset;
}

}
21 changes: 21 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Jump.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;

public class Jump implements Command {

private static final byte[] opCode = {0b0111_1111};
private static final int offset = 1;

@Override
public Byte getOpCode() {
return opCode[0];
}

@Override
public int execute(CommandContext context) {
byte storageIndex = context.readBytes(1)[0];
Integer offsetValue = (Integer) context.getElementByIndex(storageIndex);
return offsetValue;
}
}
25 changes: 25 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Mul.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;
import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

public class Mul implements Command {
private static final byte[] opCode = {0b0000_0011};
private static final int offset = 1;

@Override
public Byte getOpCode() {
return opCode[0];
}

@Override
public int execute(CommandContext context) {
Object firstOp = context.popFromStack();
Object secondOp = context.popFromStack();
if (firstOp instanceof Number && secondOp instanceof Number) {
Number result = BinaryHandler.mulTwoNumbers((Number) firstOp, (Number) secondOp);
context.pushToStack(result);
} else throw new VirtualMachineException("Multiply operation uses two instances of Number.");
return offset;
}
}
26 changes: 26 additions & 0 deletions src/main/java/ru/jengine/virtualmachine/commands/Sub.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ru.jengine.virtualmachine.commands;

import ru.jengine.virtualmachine.context.CommandContext;
import ru.jengine.virtualmachine.exceptions.VirtualMachineException;

public class Sub implements Command {
private static final byte[] opCode = {0b0000_0010};
private static final int offset = 1;

@Override
public Byte getOpCode() {
return opCode[0];
}

@Override
public int execute(CommandContext context) {
Object firstOp = context.popFromStack();
Object secondOp = context.popFromStack();
if (firstOp instanceof Number && secondOp instanceof Number) {
Number result = BinaryHandler.subTwoNumbers((Number) firstOp, (Number) secondOp);
context.pushToStack(result);
} else throw new VirtualMachineException("Sub operation uses two instances of Number.");
return offset;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package ru.jengine.virtualmachine.context;

public interface CommandContext {

Object popFromStack();

Object peekFromStack();

void pushToStack(Object element);

Object getElementByIndex(Byte index);

byte[] readBytes(int n);
}
Loading