Add vm
This commit is contained in:
66
src/chunk.h
Normal file
66
src/chunk.h
Normal file
@@ -0,0 +1,66 @@
|
||||
#ifndef CAMELLYA_CHUNK_H
|
||||
#define CAMELLYA_CHUNK_H
|
||||
|
||||
#include "opcode.h"
|
||||
#include "value.h"
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace camellya {
|
||||
|
||||
// A chunk represents a sequence of bytecode instructions
|
||||
// along with associated constants and debug information
|
||||
class Chunk {
|
||||
public:
|
||||
Chunk() = default;
|
||||
|
||||
// Write a byte to the chunk
|
||||
void write(uint8_t byte, int line);
|
||||
|
||||
// Write an opcode to the chunk
|
||||
void write_opcode(OpCode op, int line);
|
||||
|
||||
// Add a constant to the constant pool
|
||||
// Returns the index of the constant
|
||||
size_t add_constant(ValuePtr value);
|
||||
|
||||
// Get a constant from the constant pool
|
||||
ValuePtr get_constant(size_t index) const;
|
||||
|
||||
// Get the size of the bytecode
|
||||
size_t size() const { return code.size(); }
|
||||
|
||||
// Get the bytecode at an index
|
||||
uint8_t get_code(size_t index) const { return code[index]; }
|
||||
|
||||
// Get line number for a bytecode offset
|
||||
int get_line(size_t offset) const;
|
||||
|
||||
// Disassemble the chunk for debugging
|
||||
void disassemble(const std::string& name) const;
|
||||
|
||||
// Disassemble a single instruction
|
||||
size_t disassemble_instruction(size_t offset) const;
|
||||
|
||||
// Patch a jump instruction with the correct offset
|
||||
void patch_jump(size_t offset);
|
||||
|
||||
// Get current offset (useful for jump patching)
|
||||
size_t current_offset() const { return code.size(); }
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> code; // Bytecode instructions
|
||||
std::vector<ValuePtr> constants; // Constant pool
|
||||
std::vector<int> lines; // Line information for debugging
|
||||
|
||||
// Helper for disassembly
|
||||
size_t simple_instruction(const std::string& name, size_t offset) const;
|
||||
size_t constant_instruction(const std::string& name, size_t offset) const;
|
||||
size_t byte_instruction(const std::string& name, size_t offset) const;
|
||||
size_t jump_instruction(const std::string& name, int sign, size_t offset) const;
|
||||
};
|
||||
|
||||
} // namespace camellya
|
||||
|
||||
#endif // CAMELLYA_CHUNK_H
|
||||
Reference in New Issue
Block a user