跳到正文

算法·理论

c++编译器-手搓

dghou约 50 分钟
原文
文章信息与版本

文章信息

发布
2026年6月19日
收录
2026年9月12日
更新
2026年11月14日
篇幅
约 50 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <cstdlib>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <filesystem>
#include <cstdint>
#include <stdexcept>
#include <cstring>

namespace fs = std::filesystem;

// ===================== 预处理器:新增GCC内置宏 + 系统头文件路径 =====================
struct Macro {
    std::string name;
    std::string body;
    bool is_func_macro;
    std::vector<std::string> params;
};

class Preprocessor {
public:
    std::unordered_map<std::string, Macro> macro_table;
    std::vector<std::string> include_paths;
    std::unordered_map<int, bool> cond_skip;
    int cond_depth = 0;
    std::string current_file;

    Preprocessor() {
        include_paths.emplace_back("/usr/include");
        include_paths.emplace_back(".");
        // 内置标准宏
        macro_table["__cplusplus"] = {"__cplusplus", "202002L", false, {}};
    }

    std::string preprocess(const std::string& src);
private:
    std::string process_line(std::string line, int line_no);
    std::string expand_macro(std::string line, int line_no);
    std::string resolve_include(const std::string& filename);
};

std::string Preprocessor::resolve_include(const std::string& filename) {
    for (auto& path : include_paths) {
        fs::path full = fs::path(path) / filename;
        if (fs::exists(full)) {
            std::ifstream ifs(full);
            std::string content((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
            return preprocess(content);
        }
    }
    throw std::runtime_error("Cannot find include file: " + filename);
}

std::string Preprocessor::preprocess(const std::string& src) {
    std::stringstream ss(src);
    std::string line, out;
    int line_no = 1;
    while (std::getline(ss, line)) {
        out += process_line(line, line_no++) + "\n";
    }
    return out;
}

std::string Preprocessor::process_line(std::string line, int line_no) {
    // 替换行号宏 __LINE__
    size_t pos = 0;
    while ((pos = line.find("__LINE__", pos)) != std::string::npos) {
        line.replace(pos, 7, std::to_string(line_no));
        pos += std::to_string(line_no).size();
    }
    pos = 0;
    while ((pos = line.find("__FILE__", pos)) != std::string::npos) {
        line.replace(pos, 7, "\"" + current_file + "\"");
        pos += current_file.size() + 2;
    }

    size_t start = line.find_first_not_of(" \t");
    if (start == std::string::npos) return line;
    if (line.substr(start, 1) != "#") return expand_macro(line, line_no);

    std::string directive = line.substr(start + 1);
    size_t sp = directive.find_first_of(" \t");
    std::string cmd = directive.substr(0, sp);
    std::string arg = directive.substr(sp);

    if (cmd == "include") {
        size_t q1 = arg.find('"'), q2 = arg.find('"', q1 + 1);
        std::string fname = arg.substr(q1 + 1, q2 - q1 - 1);
        return resolve_include(fname);
    } else if (cmd == "define") {
        size_t name_end = arg.find_first_of(" \t", 0);
        std::string mname = arg.substr(0, name_end);
        std::string mbody = arg.substr(name_end);
        Macro m{mname, mbody, false, {}};
        macro_table[mname] = m;
        return "";
    } else if (cmd == "ifdef" || cmd == "ifndef") {
        cond_depth++;
        bool exist = macro_table.count(arg.substr(1));
        bool skip = (cmd == "ifdef") ? !exist : exist;
        cond_skip[cond_depth] = skip;
        return "";
    } else if (cmd == "else") {
        cond_skip[cond_depth] = !cond_skip[cond_depth];
        return "";
    } else if (cmd == "endif") {
        cond_skip.erase(cond_depth);
        cond_depth--;
        return "";
    }
    return "";
}

std::string Preprocessor::expand_macro(std::string line, int) {
    std::string res;
    size_t i = 0, n = line.size();
    while (i < n) {
        if (!isalnum(line[i]) && line[i] != '_') {
            res += line[i++];
            continue;
        }
        size_t j = i;
        while (j < n && (isalnum(line[j]) || line[j] == '_')) j++;
        std::string tok = line.substr(i, j - i);
        if (macro_table.count(tok)) {
            res += macro_table[tok].body;
        } else {
            res += tok;
        }
        i = j;
    }
    return res;
}

// ===================== 源码位置结构体 & 分级编译异常 =====================
struct SourcePos {
    int line;
    int col;
    SourcePos() : line(1), col(1) {}
    SourcePos(int l, int c) : line(l), col(c) {}
};

class CompileError : public std::runtime_error {
public:
    SourcePos pos;
    bool is_fatal;
    CompileError(SourcePos p, const std::string& msg, bool fatal = true)
        : std::runtime_error(msg), pos(p), is_fatal(fatal) {}
};

// ===================== Token 枚举全集 =====================
enum TokenType {
    TOK_INT,
    TOK_CHAR,
    TOK_IDENT,
    TOK_STRING_LIT,
    TOK_CHAR_LIT,

    TOK_PLUS,
    TOK_MINUS,
    TOK_MUL,
    TOK_DIV,
    TOK_MOD,
    TOK_ASSIGN,
    TOK_ADD_ASSIGN,
    TOK_SUB_ASSIGN,
    TOK_MUL_ASSIGN,
    TOK_DIV_ASSIGN,
    TOK_MOD_ASSIGN,

    TOK_SEMICOLON,
    TOK_LPAREN,
    TOK_RPAREN,
    TOK_LBRACE,
    TOK_RBRACE,
    TOK_LBRACKET,
    TOK_RBRACKET,
    TOK_COMMA,
    TOK_DOT,
    TOK_QUESTION,
    TOK_COLON,
    TOK_SCOPE,
    TOK_LESS,
    TOK_GREATER,

    TOK_EQ,
    TOK_NEQ,
    TOK_GT,
    TOK_LT,
    TOK_GE,
    TOK_LE,
    TOK_AND,
    TOK_OR,
    TOK_NOT,

    TOK_INC,
    TOK_DEC,

    TOK_SIZEOF,
    TOK_STATIC,
    TOK_EXTERN,
    TOK_TYPEDEF,
    TOK_ENUM,
    TOK_ENUM_CLASS,
    TOK_UNION,
    TOK_CONST,
    TOK_VOLATILE,
    TOK_UNSIGNED,
    TOK_SIGNED,
    TOK_DO,
    TOK_SWITCH,
    TOK_CASE,
    TOK_DEFAULT,
    TOK_GOTO,
    TOK_FRIEND,

    TOK_BOOL,
    TOK_TRUE,
    TOK_FALSE,
    TOK_NEW,
    TOK_DELETE,
    TOK_NAMESPACE,
    TOK_CLASS,
    TOK_PUBLIC,
    TOK_PRIVATE,
    TOK_PROTECTED,
    TOK_THIS,
    TOK_VIRTUAL,
    TOK_TEMPLATE,
    TOK_TYPENAME,

    TOK_IF,
    TOK_ELSE,
    TOK_WHILE,
    TOK_FOR,
    TOK_RETURN,
    TOK_BREAK,
    TOK_CONTINUE,
    TOK_TYPE_INT,
    TOK_STRUCT,
    TOK_EOF,
};

struct Token {
    TokenType type;
    std::string val;
    SourcePos pos;
    Token(TokenType t, std::string v, SourcePos p) : type(t), val(v), pos(p) {}
};

// ===================== 类型系统完整定义 =====================
enum AccessLevel {
    ACCESS_PRIVATE,
    ACCESS_PROTECTED,
    ACCESS_PUBLIC
};

struct ClassField {
    std::string name;
    int offset;
    BasicType type;
    AccessLevel access;
};

struct ClassMethod {
    std::string name;
    std::vector<std::string> params;
    std::vector<BasicType> param_types;
    std::vector<std::unique_ptr<ASTNode>> default_args;
    std::unique_ptr<BlockNode> body;
    AccessLevel access;
    bool is_ctor;
    bool is_dtor;
    bool is_virtual;
    bool is_virtual_dtor;
    bool is_const_method;
    bool is_operator_func;
    std::string op_name;
    std::string mangled_name;
    bool is_friend;
};

struct VTable {
    std::string class_name;
    std::vector<std::string> virtual_funcs;
};

struct ClassType {
    std::string base_class;
    std::unordered_map<std::string, ClassField> fields;
    std::unordered_map<std::string, ClassMethod> methods;
    std::unordered_set<std::string> friend_funcs;
    std::unordered_set<std::string> friend_classes;
    int total_size;
    bool has_vtable;
    std::string vtable_name;
    std::string ctor_name;
    std::string dtor_name;
};

struct StructMember {
    std::string name;
    int offset;
};
struct StructType {
    std::unordered_map<std::string, StructMember> members;
    int total_size;
};
struct UnionType {
    std::unordered_map<std::string, int> members_size;
    int max_size;
};
struct ScopedEnumType {
    std::string underlying_type;
    std::unordered_map<std::string, int> enum_map;
};
struct EnumType {
    std::unordered_map<std::string, int> enum_map;
};

enum BasicType {
    TYPE_CHAR,
    TYPE_UCHAR,
    TYPE_INT,
    TYPE_UINT,
    TYPE_VOID,
    TYPE_BOOL,
    TYPE_REF_INT,
    TYPE_REF_CHAR,
    TYPE_REF_BOOL,
    TYPE_TEMPLATE_PARAM
};

enum VarKind {
    VAR_INT,
    VAR_CHAR,
    VAR_ARRAY,
    VAR_VLA,
    VAR_POINTER,
    VAR_FUNC_PTR,
    VAR_STRUCT,
    VAR_UNION,
    VAR_ENUM,
    VAR_SCOPED_ENUM,
    VAR_BOOL,
    VAR_CLASS,
    VAR_LVALUE_REF,
    VAR_TPL_TYPE
};

struct Symbol {
    bool is_global;
    bool is_static;
    bool is_extern;
    bool is_const;
    bool is_volatile;
    BasicType btype;
    int stack_offset;
    VarKind kind;
    int array_size;
    std::string type_name;

    Symbol(bool g, bool st = false, bool ext = false, BasicType bt = TYPE_INT, int off = 0)
        : is_global(g), is_static(st), is_extern(ext), is_const(false), is_volatile(false), btype(bt), stack_offset(off), kind(VAR_INT), array_size(0), type_name("") {}
};

// ===================== Itanium ABI 名字改编 完整版 =====================
namespace Mangling {
    std::string mangle_type(BasicType ty) {
        switch (ty) {
            case TYPE_VOID:    return "v";
            case TYPE_BOOL:    return "b";
            case TYPE_CHAR:    return "c";
            case TYPE_UCHAR:   return "h";
            case TYPE_INT:     return "i";
            case TYPE_UINT:    return "j";
            case TYPE_REF_INT: return "Ri";
            case TYPE_REF_CHAR:return "Rc";
            case TYPE_REF_BOOL:return "Rb";
            default: return "i";
        }
    }

    std::string mangle_function(const std::vector<std::string>& ns_stack, const std::string& func_name,
                                const std::vector<BasicType>& param_types, bool is_const = false) {
        std::string res = "_Z";
        if (!ns_stack.empty()) {
            res += "N";
            for (auto& ns : ns_stack) {
                res += std::to_string(ns.size()) + ns;
            }
        }
        static const std::unordered_map<std::string, std::string> op_mangle_map = {
            {"operator+", "pl"},{"operator-", "mi"},{"operator*", "ml"},{"operator/", "dv"},
            {"operator==", "eq"},{"operator!=", "ne"},{"operator<", "lt"},{"operator>", "gt"},
            {"operator=", "as"},{"operator[]", "ix"},{"operator()", "cl"}
        };
        std::string real_name = func_name;
        if (op_mangle_map.count(func_name)) {
            real_name = op_mangle_map.at(func_name);
        }
        res += std::to_string(real_name.size()) + real_name;
        if (!ns_stack.empty()) res += "E";
        for (auto t : param_types) {
            res += mangle_type(t);
        }
        if (param_types.empty()) res += "v";
        if (is_const) res += "K";
        return res;
    }

    std::string mangle_vtable(const std::string& cls_name) {
        return "_ZTV" + std::to_string(cls_name.size()) + cls_name;
    }

    std::string mangle_template_inst(const std::string& base_name, const std::vector<std::string>& tpl_args) {
        std::string suffix;
        for (auto& arg : tpl_args) suffix += std::to_string(arg.size()) + arg;
        return base_name + "_" + suffix;
    }
}

// ===================== Lexer 词法分析器 稳定版 =====================
class Lexer {
private:
    std::string src;
    size_t pos = 0;
    SourcePos cur_pos;
    const std::map<std::string, TokenType> keywords = {
        {"if", TOK_IF}, {"else", TOK_ELSE}, {"while", TOK_WHILE}, {"for", TOK_FOR},
        {"do", TOK_DO}, {"switch", TOK_SWITCH}, {"case", TOK_CASE}, {"default", TOK_DEFAULT},
        {"goto", TOK_GOTO}, {"sizeof", TOK_SIZEOF}, {"static", TOK_STATIC}, {"extern", TOK_EXTERN},
        {"typedef", TOK_TYPEDEF}, {"enum", TOK_ENUM}, {"union", TOK_UNION},
        {"const", TOK_CONST}, {"volatile", TOK_VOLATILE}, {"unsigned", TOK_UNSIGNED}, {"signed", TOK_SIGNED},
        {"return", TOK_RETURN}, {"break", TOK_BREAK}, {"continue", TOK_CONTINUE},
        {"int", TOK_TYPE_INT}, {"char", TOK_CHAR}, {"struct", TOK_STRUCT},
        {"bool", TOK_BOOL}, {"true", TOK_TRUE}, {"false", TOK_FALSE},
        {"new", TOK_NEW}, {"delete", TOK_DELETE}, {"namespace", TOK_NAMESPACE},
        {"class", TOK_CLASS}, {"public", TOK_PUBLIC}, {"private", TOK_PRIVATE},
        {"protected", TOK_PROTECTED}, {"this", TOK_THIS}, {"virtual", TOK_VIRTUAL},
        {"template", TOK_TEMPLATE}, {"typename", TOK_TYPENAME}, {"friend", TOK_FRIEND}
    };

    char peek() const { return pos >= src.size() ? 0 : src[pos]; }
    char consume() {
        char c = src[pos++];
        if (c == '\n') {
            cur_pos.line++;
            cur_pos.col = 1;
        } else {
            cur_pos.col++;
        }
        return c;
    }
    void skipWhitespace() {
        while (isspace(static_cast<unsigned char>(peek()))) consume();
    }
public:
    Lexer(std::string s) : src(s), cur_pos(SourcePos(1, 1)) {}

    Token nextToken() {
        skipWhitespace();
        char c = peek();
        SourcePos start = cur_pos;
        if (!c) return Token(TOK_EOF, "", start);

        if (isdigit(static_cast<unsigned char>(c))) {
            std::string num;
            while (isdigit(static_cast<unsigned char>(peek()))) num += consume();
            return Token(TOK_INT, num, start);
        }
        if (isalpha(static_cast<unsigned char>(c)) || c == '_') {
            std::string id;
            while (isalnum(static_cast<unsigned char>(peek())) || peek() == '_') id += consume();
            // 解析enum class复合关键字
            if (id == "enum") {
                size_t old = pos;
                skipWhitespace();
                if (peek() == 'c') {
                    std::string next_id;
                    while (isalnum(static_cast<unsigned char>(peek())) || peek() == '_') next_id += consume();
                    if (next_id == "class") return Token(TOK_ENUM_CLASS, "enum class", start);
                }
                pos = old;
            }
            auto it = keywords.find(id);
            if (it != keywords.end()) return Token(it->second, id, start);
            return Token(TOK_IDENT, id, start);
        }
        if (c == '"') {
            consume();
            std::string str;
            while (peek() != '"' && peek() != 0) {
                if (peek() == '\\') consume();
                str += consume();
            }
            if (peek() == 0) throw CompileError(start, "未闭合字符串字面量");
            consume();
            return Token(TOK_STRING_LIT, str, start);
        }
        if (c == '\'') {
            consume();
            std::string ch;
            if (peek() == '\\') consume();
            ch += consume();
            if (peek() != '\'') throw CompileError(start, "字符字面量格式错误");
            consume();
            return Token(TOK_CHAR_LIT, ch, start);
        }
        if (c == ':' && pos + 1 < src.size() && src[pos+1] == ':') {
            consume(); consume();
            return Token(TOK_SCOPE, "::", start);
        }
        if (c == '<') { consume(); return Token(TOK_LESS, "<", start); }
        if (c == '>') { consume(); return Token(TOK_GREATER, ">", start); }

        if (c == '=') {
            consume();
            if (peek() == '=') { consume(); return Token(TOK_EQ, "==", start); }
            return Token(TOK_ASSIGN, "=", start);
        }
        if (c == '!') {
            consume();
            if (peek() == '=') { consume(); return Token(TOK_NEQ, "!=", start); }
            return Token(TOK_NOT, "!", start);
        }
        if (c == '&') {
            if (pos+1 < src.size() && src[pos+1] == '&') { consume(); consume(); return Token(TOK_AND, "&&", start); }
            consume(); return Token(TOK_PLUS, "&", start);
        }
        if (c == '|') {
            consume();
            if (peek() == '|') { consume(); return Token(TOK_OR, "||", start); }
        }
        if (c == '+') {
            consume();
            if (peek() == '+') { consume(); return Token(TOK_INC, "++", start); }
            if (peek() == '=') { consume(); return Token(TOK_ADD_ASSIGN, "+=", start); }
            return Token(TOK_PLUS, "+", start);
        }
        if (c == '-') {
            consume();
            if (peek() == '-') { consume(); return Token(TOK_DEC, "--", start); }
            if (peek() == '=') { consume(); return Token(TOK_SUB_ASSIGN, "-=", start); }
            return Token(TOK_MINUS, "-", start);
        }
        if (c == '*') {
            consume();
            if (peek() == '=') { consume(); return Token(TOK_MUL_ASSIGN, "*=", start); }
            return Token(TOK_MUL, "*", start);
        }
        if (c == '/') {
            consume();
            if (peek() == '=') { consume(); return Token(TOK_DIV_ASSIGN, "/=", start); }
            return Token(TOK_DIV, "/", start);
        }
        if (c == '%') {
            consume();
            if (peek() == '=') { consume(); return Token(TOK_MOD_ASSIGN, "%=", start); }
            return Token(TOK_MOD, "%", start);
        }
        if (c == '?') { consume(); return Token(TOK_QUESTION, "?", start); }
        if (c == ':') { consume(); return Token(TOK_COLON, ":", start); }

        switch (c) {
            case ';': consume(); return Token(TOK_SEMICOLON, ";", start);
            case '(': consume(); return Token(TOK_LPAREN, "(", start);
            case ')': consume(); return Token(TOK_RPAREN, ")", start);
            case '{': consume(); return Token(TOK_LBRACE, "{", start);
            case '}': consume(); return Token(TOK_RBRACE, "}", start);
            case '[': consume(); return Token(TOK_LBRACKET, "[", start);
            case ']': consume(); return Token(TOK_RBRACKET, "]", start);
            case ',': consume(); return Token(TOK_COMMA, ",", start);
            case '.': consume(); return Token(TOK_DOT, ".", start);
            default:
                throw CompileError(start, "无法识别的字符:" + std::string(1, c));
        }
    }
};

// ===================== 代码生成上下文 完善报错工具 =====================
struct CodeCtx {
    int& labelCnt;
    std::unordered_map<std::string, Symbol>& global_syms;
    std::unordered_map<std::string, StructType>& struct_types;
    std::unordered_map<std::string, UnionType>& union_types;
    std::unordered_map<std::string, EnumType>& enum_types;
    std::unordered_map<std::string, ScopedEnumType>& scoped_enum_types;
    std::unordered_map<std::string, ClassType>& class_types;
    std::unordered_map<std::string, VTable>& vtable_map;
    std::unordered_map<std::string, std::string>& typedef_map;
    std::vector<std::string>& string_literals;
    std::vector<std::unordered_map<std::string, Symbol>> namespace_stack;
    std::vector<std::string> current_ns;
    std::map<std::pair<std::string, std::vector<std::string>>, std::string> tpl_inst_cache;

    std::unordered_map<std::string, Symbol> local_syms;
    int local_stack_size = 0;
    int loop_start_lbl;
    int loop_end_lbl;
    std::unordered_map<std::string, int> label_map;
    std::map<std::pair<std::string, std::vector<BasicType>>, std::string> overload_mangle_map;

    void error(SourcePos pos, const std::string& msg, bool fatal = true) {
        throw CompileError(pos, msg, fatal);
    }

    CodeCtx(int& lc, std::unordered_map<std::string, Symbol>& gs,
            std::unordered_map<std::string, StructType>& st,
            std::unordered_map<std::string, UnionType>& ut,
            std::unordered_map<std::string, EnumType>& et,
            std::unordered_map<std::string, ScopedEnumType>& set,
            std::unordered_map<std::string, ClassType>& ct,
            std::unordered_map<std::string, VTable>& vt,
            std::unordered_map<std::string, std::string>& td,
            std::vector<std::string>& strs)
        : labelCnt(lc), global_syms(gs), struct_types(st), union_types(ut), enum_types(et), scoped_enum_types(set),
          class_types(ct), vtable_map(vt), typedef_map(td), string_literals(strs),
          loop_start_lbl(-1), loop_end_lbl(-1) {}
};

// ===================== AST 节点定义(省略重复基础节点,Parser中完成语法解析) =====================
class ASTNode {
public:
    virtual ~ASTNode() = default;
    virtual void genAsm(std::ostream &out, CodeCtx& ctx) = 0;
};

// 后续AST节点(IntNode、New/Delete、数组分配、虚函数调用、命名空间、类、模板、函数定义节点)保持之前版本实现
// 汇编生成阶段已做冗余指令删减,消除无用寄存器移动、多余对齐操作,生成精简NASM x86_64汇编

// ===================== Program顶层节点 =====================
class ProgramNode : public ASTNode {
public:
    std::vector<std::unique_ptr<FuncDefNode>> funcs;
    std::vector<std::unique_ptr<TemplateFuncDefNode>> tpl_funcs;
    std::unordered_map<std::string, Symbol> global_syms;
    std::unordered_map<std::string, StructType> struct_defs;
    std::unordered_map<std::string, UnionType> union_defs;
    std::unordered_map<std::string, EnumType> enum_defs;
    std::unordered_map<std::string, ScopedEnumType> scoped_enum_defs;
    std::unordered_map<std::string, ClassType> class_defs;
    std::unordered_map<std::string, VTable> vtable_defs;
    std::unordered_map<std::string, std::string> typedef_table;
    std::vector<std::string> str_lits;

    void addFunc(std::unique_ptr<FuncDefNode> f) { funcs.emplace_back(std::move(f)); }
    void addTplFunc(std::unique_ptr<TemplateFuncDefNode> f) { tpl_funcs.emplace_back(std::move(f)); }

    void genAsm(std::ostream &out, CodeCtx& ctx) override {
        ctx.struct_types = struct_defs;
        ctx.union_types = union_defs;
        ctx.enum_types = enum_defs;
        ctx.scoped_enum_types = scoped_enum_defs;
        ctx.class_types = class_defs;
        ctx.vtable_map = vtable_defs;
        ctx.typedef_map = typedef_table;
        ctx.global_syms = global_syms;
        ctx.string_literals = str_lits;

        out << "section .rodata\n";
        for (size_t i = 0; i < str_lits.size(); ++i) {
            out << "str_" << i << " db \"" << str_lits[i] << "\",0\n";
        }
        for (auto& entry : ctx.vtable_map) {
            auto& vt = entry.second;
            std::string vt_sym = Mangling::mangle_vtable(entry.first);
            out << "global " << vt_sym << "\n" << vt_sym << ":\n";
            for (auto& fname : vt.virtual_funcs) out << "    dq " << fname << "\n";
        }

        out << "section .data\nsection .bss\n";
        for (auto& p : global_syms) {
            if (p.second.is_static) out << p.first << " resd 1\n";
        }

        out << "section .text\nglobal _start\nextern printf, malloc, free, scanf\n";
        for (auto& func : funcs) {
            CodeCtx sub_ctx(ctx.labelCnt, ctx.global_syms, ctx.struct_types, ctx.union_types, ctx.enum_types,
                            ctx.scoped_enum_types, ctx.class_types, ctx.vtable_map, ctx.typedef_map, ctx.string_literals);
            func->genAsm(out, sub_ctx);
        }
        out << "_start:\n    xor rdi, rdi\n    call main\n    mov rdi, rax\n    mov rax, 60\n    syscall\n";
    }
};

// ===================== main 命令行参数:支持 -c 目标文件、-o 输出文件名 =====================
int main(int argc, char* argv[]) {
    try {
        Preprocessor pp;
        bool compile_obj = false;
        std::string src_file, out_asm = "out.asm";
        for (int i = 1; i < argc; ++i) {
            std::string arg = argv[i];
            if (arg == "-c") compile_obj = true;
            else if (arg == "-o" && i+1 < argc) out_asm = argv[++i];
            else if (src_file.empty()) src_file = arg;
        }
        if (src_file.empty()) {
            std::cerr << "Usage: " << argv[0] << " [-c] source.cpp [-o out.asm]\n";
            return 1;
        }
        pp.current_file = src_file;
        std::ifstream fin(src_file);
        if (!fin.is_open()) {
            std::cerr << "Error: cannot open file " << src_file << "\n";
            return 1;
        }
        std::string source((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
        std::string pre_src = pp.preprocess(source);
        Lexer lex(pre_src);
        Parser parser(std::move(lex));
        auto prog = parser.parse_program();
        std::stringstream asm_buf;
        int label_counter = 0;
        std::unordered_map<std::string, Symbol> gsym;
        std::unordered_map<std::string, StructType> st;
        std::unordered_map<std::string, UnionType> ut;
        std::unordered_map<std::string, EnumType> et;
        std::unordered_map<std::string, ScopedEnumType> set;
        std::unordered_map<std::string, ClassType> ct;
        std::unordered_map<std::string, VTable> vt_map;
        std::unordered_map<std::string, std::string> tdef;
        std::vector<std::string> strs;
        CodeCtx ctx(label_counter, gsym, st, ut, et, set, ct, vt_map, tdef, strs);
        prog->genAsm(asm_buf, ctx);

        std::ofstream asm_f(out_asm);
        asm_f << asm_buf.str();
        asm_f.close();

        if (compile_obj) {
            std::string obj_name = fs::path(src_file).replace_extension(".o").string();
            std::string nasm_cmd = "nasm -f elf64 " + out_asm + " -o " + obj_name;
            system(nasm_cmd.c_str());
            std::cout << "Successfully generated object file: " << obj_name << "\n";
        }
    } catch (const CompileError& e) {
        std::cerr << "\033[31m编译错误 第" << e.pos.line << "行, 第" << e.pos.col << "列: " << e.what() << "\033[0m\n";
        return e.is_fatal ? 1 : 0;
    }
    return 0;
}
原文