aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--clox/src/chunk.h4
-rw-r--r--clox/src/debug.c8
-rw-r--r--clox/src/main.c12
-rw-r--r--clox/src/vm.c19
4 files changed, 43 insertions, 0 deletions
diff --git a/clox/src/chunk.h b/clox/src/chunk.h
index dcab3df..185f13c 100644
--- a/clox/src/chunk.h
+++ b/clox/src/chunk.h
@@ -6,6 +6,10 @@
typedef enum {
OP_CONSTANT,
+ OP_ADD,
+ OP_SUBTRACT,
+ OP_MULTIPLY,
+ OP_DIVIDE,
OP_NEGATE,
OP_RETURN,
} OpCode;
diff --git a/clox/src/debug.c b/clox/src/debug.c
index 91fe139..570bde9 100644
--- a/clox/src/debug.c
+++ b/clox/src/debug.c
@@ -36,6 +36,14 @@ int disassembleInstruction(Chunk *chunk, int offset) {
switch (instruction) {
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_NEGATE:
return simpleInstruction("OP_NEGATE", offset);
case OP_RETURN:
diff --git a/clox/src/main.c b/clox/src/main.c
index d2cb6bd..d1e747f 100644
--- a/clox/src/main.c
+++ b/clox/src/main.c
@@ -12,6 +12,18 @@ int main(int argc, const char *argv[]) {
int constant = addConstant(&chunk, 1.2);
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, 123);
diff --git a/clox/src/vm.c b/clox/src/vm.c
index e05a0c8..a775acb 100644
--- a/clox/src/vm.c
+++ b/clox/src/vm.c
@@ -25,6 +25,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
@@ -45,6 +51,18 @@ 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;
@@ -58,6 +76,7 @@ static InterpretResult run() {
#undef READ_BYTE
#undef READ_CONSTANT
+#undef BINARY_OP
}
InterpretResult interpret(Chunk *chunk) {