-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytecode.cpp
More file actions
58 lines (50 loc) · 1.89 KB
/
bytecode.cpp
File metadata and controls
58 lines (50 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "bytecode.h"
int Bytecode::simpleInstruction(std::string opcode, int idx) {
std::cout << "offset " << idx << ", line " << lines[idx] << ": " << opcode << std::endl;
return 1;
}
uint8_t Bytecode::codeAt(size_t idx) {
return code[idx];
}
Value Bytecode::valueAt(size_t idx) {
return constants[idx];
}
int Bytecode::lineAt(size_t idx) {
return lines[idx];
}
void Bytecode::writeByte(uint8_t byte, int line) {
code.push_back(byte);
lines.push_back(line);
}
void Bytecode::writeConstant(Value val, int line) {
constants.push_back(val);
writeByte(Opcode::OP_CONSTANT, line);
writeByte(constants.size() - 1, line);
}
size_t Bytecode::disassembleInstruction(size_t idx) {
switch (code[idx]) {
case Opcode::RETURN: return simpleInstruction("RETURN", idx);
case Opcode::NEGATE: return simpleInstruction("NEGATE", idx);
case Opcode::ADD: return simpleInstruction("ADD", idx);
case Opcode::SUBTRACT: return simpleInstruction("SUBTRACT", idx);
case Opcode::MULTIPLY: return simpleInstruction("MULTIPLY", idx);
case Opcode::DIVIDE: return simpleInstruction("DIVIDE", idx);
case Opcode::TRUE: return simpleInstruction("TRUE", idx);
case Opcode::FALSE: return simpleInstruction("FALSE", idx);
case Opcode::NUL: return simpleInstruction("NUL", idx);
case Opcode::NOT: return simpleInstruction("NOT", idx);
case Opcode::EQUAL: return simpleInstruction("EQUAL", idx);
case Opcode::GREATER: return simpleInstruction("GREATER", idx);
case Opcode::LESSER: return simpleInstruction("LESSER", idx);
case Opcode::OP_CONSTANT:
std::cout << "offset " << idx << ", line " << lines[idx] << ": OP_CONSTANT \'" << constants[code[idx + 1]] << "\'" << std::endl;
return 2;
default:
std::cerr << "offset " << idx << ", line " << lines[idx] << ": Unkown instruction: " << code[idx] << std::endl;
return 1;
}
}
void Bytecode::disassembleCode() {
for (size_t i{ 0 }; i < code.size(); )
i += disassembleInstruction(i);
}