Add vm
This commit is contained in:
75
src/vm.h
Normal file
75
src/vm.h
Normal file
@@ -0,0 +1,75 @@
|
||||
#ifndef CAMELLYA_VM_H
|
||||
#define CAMELLYA_VM_H
|
||||
|
||||
#include "chunk.h"
|
||||
#include "value.h"
|
||||
#include "exceptions.h"
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
|
||||
namespace camellya {
|
||||
|
||||
// Call frame for function calls
|
||||
struct CallFrame {
|
||||
std::shared_ptr<Chunk> chunk;
|
||||
size_t ip; // Instruction pointer
|
||||
size_t stack_offset; // Where this frame's locals start on the stack
|
||||
|
||||
CallFrame(std::shared_ptr<Chunk> chunk, size_t stack_offset)
|
||||
: chunk(std::move(chunk)), ip(0), stack_offset(stack_offset) {}
|
||||
};
|
||||
|
||||
// Virtual Machine - stack-based bytecode interpreter
|
||||
class VM {
|
||||
public:
|
||||
VM();
|
||||
|
||||
// Execute a chunk of bytecode
|
||||
bool execute(std::shared_ptr<Chunk> chunk);
|
||||
|
||||
// Get the last error message
|
||||
const std::string& get_error() const { return error_message; }
|
||||
|
||||
// Register native functions
|
||||
void register_native_function(const std::string& name, NativeFunction func);
|
||||
|
||||
// Global variable access
|
||||
void set_global(const std::string& name, ValuePtr value);
|
||||
ValuePtr get_global(const std::string& name);
|
||||
|
||||
// Stack operations (for C++ API)
|
||||
void push(ValuePtr value);
|
||||
ValuePtr pop();
|
||||
ValuePtr peek(int distance = 0);
|
||||
|
||||
private:
|
||||
std::vector<ValuePtr> stack;
|
||||
std::vector<CallFrame> frames;
|
||||
CallFrame* current_frame;
|
||||
std::map<std::string, ValuePtr> globals;
|
||||
std::string error_message;
|
||||
|
||||
// Main execution loop
|
||||
bool run();
|
||||
|
||||
// Helper methods
|
||||
uint8_t read_byte();
|
||||
uint16_t read_short();
|
||||
ValuePtr read_constant();
|
||||
std::string read_string();
|
||||
|
||||
// Stack operations
|
||||
void runtime_error(const std::string& message);
|
||||
bool is_falsey(ValuePtr value);
|
||||
|
||||
// Binary operations
|
||||
bool binary_op(OpCode op);
|
||||
|
||||
// Built-in functions
|
||||
void register_builtin_functions();
|
||||
};
|
||||
|
||||
} // namespace camellya
|
||||
|
||||
#endif // CAMELLYA_VM_H
|
||||
Reference in New Issue
Block a user