Chapter 15.3.1

This commit is contained in:
Tom Willemse 2021-07-29 23:56:42 -07:00
parent 276debcb35
commit 9b60cf334c
Signed by: ryuslash
GPG key ID: 7D5C407B435025C1
4 changed files with 43 additions and 0 deletions

View file

@ -6,6 +6,10 @@
typedef enum {
OP_CONSTANT,
OP_ADD,
OP_SUBTRACT,
OP_MULTIPLY,
OP_DIVIDE,
OP_NEGATE,
OP_RETURN,
} OpCode;

View file

@ -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:

View file

@ -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);

View file

@ -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) {