diff --git a/src/chunk.h b/src/chunk.h index 894ebe3..f02ad14 100644 --- a/src/chunk.h +++ b/src/chunk.h @@ -8,6 +8,11 @@ typedef enum { OP_NOOP, OP_CONSTANT, + OP_ADD, + OP_SUBTRACT, + OP_MULTIPLY, + OP_DIVIDE, + OP_NEGATE, OP_RETURN, } OpCode; diff --git a/src/debug.c b/src/debug.c index 7b59fb0..0f9a408 100644 --- a/src/debug.c +++ b/src/debug.c @@ -38,8 +38,18 @@ int disassembleInstruction(Chunk* chunk, int offset) { switch (instruction) { case OP_NOOP: return simpleInstruction("OP_NOOP", offset); + case OP_NEGATE: + return simpleInstruction("OP_NEGATE", offset); case OP_CONSTANT: return constantInstruction("OP_CONSTANT", chunk, offset); + case OP_ADD: + return simpleInstruction("OP_ADD", offset); + case OP_SUBTRACT: + return simpleInstruction("OP_SUBTRACT", offset); + case OP_MULTIPLY: + return simpleInstruction("OP_MULTIPLY", offset); + case OP_DIVIDE: + return simpleInstruction("OP_DIVIDE", offset); case OP_RETURN: return simpleInstruction("OP_RETURN", offset); default: diff --git a/src/main.c b/src/main.c index 5a93d46..ec32b79 100644 --- a/src/main.c +++ b/src/main.c @@ -10,8 +10,21 @@ int main(int argc, const char** argv) { newChunk(&chunk); int constant = addConstant(&chunk, 1.2); - writeChunk(&chunk, OP_CONSTANT, 1); - writeChunk(&chunk, constant, 1); + writeChunk(&chunk, OP_CONSTANT, 123); + writeChunk(&chunk, constant, 123); + + constant = addConstant(&chunk, 3.4); + writeChunk(&chunk, OP_CONSTANT, 123); + writeChunk(&chunk, constant, 123); + + writeChunk(&chunk, OP_ADD, 123); + + constant = addConstant(&chunk, 5.6); + writeChunk(&chunk, OP_CONSTANT, 123); + writeChunk(&chunk, constant, 123); + + writeChunk(&chunk, OP_DIVIDE, 123); + writeChunk(&chunk, OP_NEGATE, 123); writeChunk(&chunk, OP_RETURN, 1); diff --git a/src/vm.c b/src/vm.c index 235e8c6..715446c 100644 --- a/src/vm.c +++ b/src/vm.c @@ -31,6 +31,12 @@ Value pop() { static InterpretResult run() { #define READ_BYTE() (*vm.ip++) #define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()]) +#define BINARY_OP(op) \ + do { \ + double b = pop(); \ + double a = pop(); \ + push(a op b); \ + } while (false) for (;;) { #ifdef DEBUG_TRACE_EXECUTION @@ -52,6 +58,11 @@ static InterpretResult run() { push(constant); break; } + case OP_ADD: BINARY_OP(+); break; + case OP_SUBTRACT: BINARY_OP(-); break; + case OP_MULTIPLY: BINARY_OP(*); break; + case OP_DIVIDE: BINARY_OP(/); break; + case OP_NEGATE: push(-pop()); break; case OP_RETURN: { printValue(pop()); printf("\n"); @@ -62,6 +73,7 @@ static InterpretResult run() { #undef READ_BYTE #undef READ_CONSTANT +#undef BINARY_OP } InterpretResult interpret(Chunk* chunk) {