This commit is contained in:
2026-01-19 23:10:09 +08:00
parent 1a66d45204
commit 2839c0daff
17 changed files with 2274 additions and 46 deletions

101
src/compiler.h Normal file
View File

@@ -0,0 +1,101 @@
#ifndef CAMELLYA_COMPILER_H
#define CAMELLYA_COMPILER_H
#include "ast.h"
#include "chunk.h"
#include "value.h"
#include "exceptions.h"
#include <memory>
#include <map>
#include <vector>
namespace camellya {
// Local variable information
struct Local {
std::string name;
int depth;
bool is_captured;
};
// Loop information for break/continue
struct LoopInfo {
size_t start; // Loop start position (for continue)
std::vector<size_t> breaks; // Break jump positions to patch
int scope_depth; // Scope depth at loop start
};
// Compiler class for converting AST to bytecode
class Compiler {
public:
Compiler();
// Compile a program into a chunk
std::shared_ptr<Chunk> compile(const Program& program);
// Get the last error message
const std::string& get_error() const { return error_message; }
private:
std::shared_ptr<Chunk> current_chunk;
std::vector<Local> locals;
std::vector<LoopInfo> loops; // Stack of loop information
int scope_depth;
std::string error_message;
bool had_error;
// Compilation methods for expressions
void compile_expr(const Expr& expr);
void compile_binary(const BinaryExpr& expr);
void compile_unary(const UnaryExpr& expr);
void compile_literal(const LiteralExpr& expr);
void compile_variable(const VariableExpr& expr);
void compile_assign(const AssignExpr& expr);
void compile_call(const CallExpr& expr);
void compile_get(const GetExpr& expr);
void compile_set(const SetExpr& expr);
void compile_index(const IndexExpr& expr);
void compile_index_set(const IndexSetExpr& expr);
void compile_list(const ListExpr& expr);
void compile_map(const MapExpr& expr);
// Compilation methods for statements
void compile_stmt(const Stmt& stmt);
void compile_expr_stmt(const ExprStmt& stmt);
void compile_var_decl(const VarDecl& stmt);
void compile_block(const BlockStmt& stmt);
void compile_if(const IfStmt& stmt);
void compile_while(const WhileStmt& stmt);
void compile_for(const ForStmt& stmt);
void compile_return(const ReturnStmt& stmt);
void compile_break(const BreakStmt& stmt);
void compile_continue(const ContinueStmt& stmt);
void compile_function_decl(const FunctionDecl& stmt);
void compile_class_decl(const ClassDecl& stmt);
// Helper methods
void emit_byte(uint8_t byte);
void emit_opcode(OpCode op);
void emit_bytes(uint8_t byte1, uint8_t byte2);
void emit_constant(ValuePtr value);
size_t emit_jump(OpCode op);
void patch_jump(size_t offset);
void emit_loop(size_t loop_start);
// Variable management
void begin_scope();
void end_scope();
void add_local(const std::string& name);
int resolve_local(const std::string& name);
// Constant pool
uint8_t make_constant(ValuePtr value);
uint8_t identifier_constant(const std::string& name);
// Error handling
void report_error(const std::string& message);
};
} // namespace camellya
#endif // CAMELLYA_COMPILER_H