Chapter 15.3

This commit is contained in:
Tom Willemse 2021-07-29 23:38:20 -07:00
parent 73dfe7efa5
commit 2adc0cc33a
Signed by: ryuslash
GPG key ID: 7D5C407B435025C1
4 changed files with 20 additions and 18 deletions

View file

@ -6,6 +6,7 @@
typedef enum {
OP_CONSTANT,
OP_NEGATE,
OP_RETURN,
} OpCode;

View file

@ -26,8 +26,7 @@ static int simpleInstruction(const char* name, int offset) {
int disassembleInstruction(Chunk *chunk, int offset) {
printf("%04d ", offset);
if (offset > 0 &&
chunk->lines[offset] == chunk->lines[offset - 1]) {
if (offset > 0 && chunk->lines[offset] == chunk->lines[offset - 1]) {
printf(" | ");
} else {
printf("%4d ", chunk->lines[offset]);
@ -37,6 +36,8 @@ int disassembleInstruction(Chunk* chunk, int offset) {
switch (instruction) {
case OP_CONSTANT:
return constantInstruction("OP_CONSTANT", chunk, offset);
case OP_NEGATE:
return simpleInstruction("OP_NEGATE", offset);
case OP_RETURN:
return simpleInstruction("OP_RETURN", offset);
default:

View file

@ -12,6 +12,7 @@ int main(int argc, const char *argv[]) {
int constant = addConstant(&chunk, 1.2);
writeChunk(&chunk, OP_CONSTANT, 123);
writeChunk(&chunk, constant, 123);
writeChunk(&chunk, OP_NEGATE, 123);
writeChunk(&chunk, OP_RETURN, 123);

View file

@ -6,13 +6,9 @@
VM vm;
static void resetStack() {
vm.stackTop = vm.stack;
}
static void resetStack() { vm.stackTop = vm.stack; }
void initVM() {
resetStack();
}
void initVM() { resetStack(); }
void freeVM() {}
@ -49,6 +45,9 @@ static InterpretResult run() {
push(constant);
break;
}
case OP_NEGATE:
push(-pop());
break;
case OP_RETURN: {
printValue(pop());
printf("\n");