Files
camellya/src/vm.h
2026-02-04 19:37:03 +08:00

80 lines
2.1 KiB
C++

#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);
// Register built-in classes for types (like list, map)
void register_builtin_class(const std::string& type_name, std::shared_ptr<ClassValue> klass);
// 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::map<std::string, std::shared_ptr<ClassValue>> builtin_classes;
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