stage1 重构代码

This commit is contained in:
zzy
2026-08-01 21:15:47 +08:00
parent a77eade06f
commit b43042c88d
30 changed files with 1211 additions and 6502 deletions

1
stage1/spl_ast.c Normal file
View File

@@ -0,0 +1 @@
#include "spl_ast.h"

305
stage1/spl_ast.h Normal file
View File

@@ -0,0 +1,305 @@
#ifndef __SPL_AST_H__
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "spl_lexer.h"
#include "spl_tok.h"
#include <math.h>
typedef enum {
SPL_AST_CONTAINER_MEMBER,
SPL_AST_FN_DECL,
SPL_AST_TYPE_DECL,
SPL_AST_VAR_DECL,
SPL_AST_CONST_DECL,
SPL_AST_MEMBER_DECL,
SPL_AST__COMPTIME_STMT, /*不实现*/
SPL_AST__DIRECTIVE_BLOCK, /*不实现*/
SPL_AST_BLOCK,
SPL_AST_BLOCK_ITEM,
SPL_AST_EXPR,
SPL_AST_TYPE_EXPR,
SPL_AST_ATTR_LIST,
} spl_ast_node_kind_t;
typedef struct {
const char *fname;
int line;
int col;
} spl_ast_loc_t;
struct spl_ast_node;
typedef struct spl_ast_node spl_ast_node_t;
typedef usize spl_ast_node_ref_t;
typedef VEC(spl_ast_node_ref_t) spl_ast_node_ref_vec_t;
struct spl_ast_node {
spl_ast_node_kind_t kind;
spl_ast_loc_t loc;
union {
spl_ast_node_ref_vec_t container_member;
spl_ast_node_ref_vec_t attr_list;
struct {
spl_ast_node_ref_t attr_list;
const char *name;
spl_ast_node_ref_t param_list;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t block;
} fn_decl;
spl_ast_node_ref_vec_t param_list;
struct {
spl_ast_node_ref_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
} param_decl;
struct {
spl_ast_node_ref_t attr_list;
const char *name;
enum {
SPL_AST_TYPE_STRUCT,
SPL_AST_TYPE_UNION,
SPL_AST_TYPE_ENUM,
SPL_AST_TYPE_TYPE_EXPR,
};
union {
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t aggregate_list;
};
} type_decl;
struct {
spl_ast_node_ref_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
} member_decl;
struct {
spl_ast_node_ref_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t expr;
} var_decl;
struct {
spl_ast_node_ref_t attr_list;
spl_ast_node_ref_t type_expr;
const char *name;
spl_ast_node_ref_t expr;
} const_decl;
spl_ast_node_ref_vec_t block;
struct {
enum {
SPL_AST_IF_STATEMENT,
SPL_AST_IFVAR_STATEMENT,
SPL_AST_WHILE_STATEMENT,
SPL_AST_LOOP_STATEMENT,
SPL_AST_FOR_STATEMENT,
SPL_AST_MATCH_STATEMENT,
SPL_AST_RET_STATEMENT,
SPL_AST_BREAK_STATEMENT,
SPL_AST_CONTINUE_STATEMENT,
SPL_AST_DEFER_STATEMENT,
SPL_AST_VARDECL,
SPL_AST_TYPEDECL,
SPL_AST_EXPR_STATEMENT,
SPL_PACED_EXPR,
} kind;
union {
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_t if_block;
spl_ast_node_ref_t else_block;
} if_statement;
struct {
spl_ast_node_ref_t packed_expr;
spl_ast_node_ref_t if_block;
spl_ast_node_ref_t else_block;
} ifvar_statement;
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_t while_block;
} while_statement;
struct {
spl_ast_node_ref_t loop_block;
} loop_statement;
struct {
spl_ast_node_ref_vec_t expr_vec;
VEC(char *) ident_vec;
spl_ast_node_ref_t block;
} for_statement;
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_vec_t paced_exprs;
spl_ast_node_ref_vec_t statements;
} match_statement;
struct {
spl_ast_node_ref_t expr;
} ret_statement;
struct {
} break_statement;
struct {
} continue_statement;
struct {
spl_ast_node_ref_t block_or_statement;
} defer_statement;
spl_ast_node_ref_t var_decl;
spl_ast_node_ref_t type_decl;
spl_ast_node_ref_t expr_statement;
struct {
const char *ident;
const char *bind_ident;
spl_ast_node_ref_t expr;
} packed_expr;
};
} block_item;
struct {
enum {
SPL_AST_ASSIGN_EXPR,
SPL_AST_BOOLOR_EXPR,
SPL_AST_BOOLAND_EXPR,
SPL_AST_BITOR_EXPR,
SPL_AST_BITXOR_EXPR,
SPL_AST_BITAND_EXPR,
SPL_AST_CMPEQ_EXPR,
SPL_AST_CMP_EXPR,
SPL_AST_RANGE_EXPR,
SPL_AST_SHIFT_EXPR,
SPL_AST_ADD_EXPR,
SPL_AST_MUL_EXPR,
SPL_AST_PREFIX_EXPR,
SPL_AST_POSTFIX_EXPR, /*left ref node*/
SPL_AST_PRIMARY_EXPR, /*left ref node*/
} op;
struct {
spl_ast_node_ref_t left;
spl_ast_node_ref_t right;
} op_expr;
} expr;
struct {
enum {
SPL_AST_CALL_EXPR,
SPL_AST_IDENT_EXPR,
SPL_AST_DEREF_EXPR,
SPL_AST_INDEX_EXPR,
SPL_AST_SLICE_EXPR,
SPL_AST_AS_EXPR,
} kind;
union {
spl_ast_node_ref_vec_t call_expr;
const char *indet_expr;
spl_ast_node_ref_t index_expr;
struct {
spl_ast_node_ref_t begin;
spl_ast_node_ref_t end;
} slice_expr;
spl_ast_node_ref_t type_expr;
};
} postfix_expr;
struct {
enum {
SPL_AST_INTEGER,
SPL_AST_FLOAT,
SPL_AST_CHAR_LIT,
SPL_AST_STRING_LIT,
SPL_AST_TRUE,
SPL_AST_FALSE,
SPL_AST_NULL,
SPL_AST_IDENT,
SPL_AST_ARGGREGATE_INIT,
SPL_AST_EXPR_EXPR,
SPL_AST_ARRAY_LIT,
SPL_AST_BUILTIN_EXPR,
SPL_AST_BLOCK_EXPR,
};
union {
isize integer_expr;
double float_expr;
char char_lit_expr;
const char *string_lit_expr;
const char *ident;
/*aggregate_init_item*/
spl_ast_node_ref_vec_t aggregate_init_expr;
spl_ast_node_ref_t expr;
struct {
isize integer;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_vec_t expr_list;
} array_lit_expr;
struct {
const char *ident;
spl_ast_node_ref_vec_t expr_list;
} builtin_expr;
spl_ast_node_ref_t block_expr;
};
} primary_expr;
struct {
const char *ident;
spl_ast_node_ref_t expr;
} aggregate_init_item;
struct {
/* ASTERISK = 1, [] = 2, else = 0*/
int pointer;
/* if array_size != 0 then pointer == 2 */
int array_size;
enum {
SPL_AST_BASE_TYPE_FN,
SPL_AST_BASE_TYPE_PATH,
} kind;
const char *spl_base_type;
union {
spl_ast_node_ref_vec_t type_path;
struct {
spl_ast_node_ref_t param_list;
spl_ast_node_ref_t type_expr;
} fn_type;
};
} type_expr;
struct {
enum {
SPL_AST_TYPE_VOID,
SPL_AST_TYPE_BOOL,
SPL_AST_TYPE_I8,
SPL_AST_TYPE_U8,
SPL_AST_TYPE_I16,
SPL_AST_TYPE_U16,
SPL_AST_TYPE_I32,
SPL_AST_TYPE_U32,
SPL_AST_TYPE_I64,
SPL_AST_TYPE_U64,
SPL_AST_TYPE_ISIZE,
SPL_AST_TYPE_USIZE,
SPL_AST_TYPE__F32, /*不实现*/
SPL_AST_TYPE__F64, /*不实现*/
SPL_AST_TYPE_PTR,
SPL_AST_TYPE_ANY,
SPL_AST_TYPE_IDENT,
} kind;
const char *ident;
} type_atom;
};
};
typedef VEC(spl_ast_node_t) spl_ast_node_vec_t;
typedef struct {
int parsed;
spl_tok_vec_t input;
spl_ast_node_vec_t buckets;
spl_ast_node_ref_t root;
} spl_ast_t;
void spl_ast_init(spl_ast_t *ast, const spl_tok_vec_t *tok_vec /*move*/);
void spl_ast_drop(spl_ast_t *ast);
void spl_ast_prase(spl_ast_t *ast);
void spl_ast_valid(spl_ast_t *ast);
void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node);
#endif /* __SPL_AST_H__ */

View File

@@ -1,264 +0,0 @@
/* spl_comp.c — SPL compiler main logic and codegen helpers */
#include "spl_comp.h"
#include "spl_lex_util.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
/* ---- Compiler context init/drop ---- */
void spl_comp_init(spl_comp_t *ctx) {
memset(ctx, 0, sizeof(*ctx));
vec_init(ctx->toks);
vec_init(ctx->scopes);
vec_init(ctx->funcs);
map_init(ctx->const_values, MAP_HASH_STR, MAP_CMP_STR);
spl_prog_init(&ctx->prog);
ctx->error_msg[0] = '\0';
ctx->parse_context[0] = '\0';
spl_emit_init(&ctx->emit, &ctx->prog);
spl_type_ctx_init(&ctx->tctx);
ctx->current_ret_type_idx = -1;
}
void spl_comp_drop(spl_comp_t *ctx) {
if (!ctx)
return;
spl_tok_vec_drop(&ctx->toks);
vec_for(ctx->scopes, i) { vec_free(vec_at(ctx->scopes, i).vars); }
vec_free(ctx->scopes);
vec_for(ctx->funcs, i) {
free(ctx->funcs.data[i].name);
free(ctx->funcs.data[i].param_type_indices);
free(ctx->funcs.data[i].param_names);
}
vec_free(ctx->funcs);
map_free(ctx->const_values);
spl_prog_drop(&ctx->prog);
free(ctx->break_patches);
spl_emit_drop(&ctx->emit);
spl_type_ctx_drop(&ctx->tctx);
}
void spl_comp_reset(spl_comp_t *ctx) {
spl_tok_vec_drop(&ctx->toks);
vec_init(ctx->toks);
vec_for(ctx->scopes, i) { vec_free(vec_at(ctx->scopes, i).vars); }
vec_free(ctx->scopes);
vec_init(ctx->scopes);
ctx->scope_depth = 0;
ctx->tok_idx = 0;
ctx->has_error = 0;
ctx->error_msg[0] = '\0';
ctx->current_func_idx = -1;
ctx->current_ret_type_idx = -1;
fa_init(&ctx->emit.frame);
ctx->in_loop = 0;
ctx->break_patch_count = 0;
ctx->break_patch_cap = 0;
ctx->continue_target = 0;
ctx->defer_count = 0;
ctx->next_gdata_idx = 0;
ctx->addr_of_mode = 0;
free(ctx->break_patches);
ctx->break_patches = NULL;
vec_free(ctx->emit.fixups);
vec_init(ctx->emit.fixups);
}
void spl_comp_error(spl_comp_t *ctx, const char *fmt, ...) {
if (ctx->has_error)
return;
char body[COMP_ERROR_MAX - 64];
va_list args;
va_start(args, fmt);
vsnprintf(body, sizeof(body), fmt, args);
va_end(args);
if (ctx->error_line > 0)
snprintf(ctx->error_msg, COMP_ERROR_MAX - 1, "line %zu:%zu: %s", ctx->error_line,
ctx->error_col, body);
else
snprintf(ctx->error_msg, COMP_ERROR_MAX - 1, "%s", body);
ctx->has_error = 1;
}
void spl_comp_err_tok(spl_comp_t *ctx, spl_tok_t *tok, const char *fmt, ...) {
if (ctx->has_error)
return;
char body[COMP_ERROR_MAX - 64];
va_list args;
va_start(args, fmt);
vsnprintf(body, sizeof(body), fmt, args);
va_end(args);
if (tok) {
snprintf(ctx->error_msg, COMP_ERROR_MAX - 1, "line %zu:%zu: %s", tok->line, tok->col, body);
} else {
snprintf(ctx->error_msg, COMP_ERROR_MAX - 1, "%s", body);
}
ctx->has_error = 1;
}
/* ---- Scope management ---- */
void spl_push_scope(spl_comp_t *ctx) {
spl_scope_t scope;
vec_init(scope.vars);
scope.depth = ++ctx->scope_depth;
vec_push(ctx->scopes, scope);
}
void spl_pop_scope(spl_comp_t *ctx) {
if (vec_size(ctx->scopes) > 0) {
spl_scope_t *scope = &vec_at(ctx->scopes, vec_size(ctx->scopes) - 1);
vec_for(scope->vars, i) { free(vec_at(scope->vars, i).name); }
vec_free(scope->vars);
ctx->scope_depth--;
ctx->scopes.size--;
} else {
ctx->scope_depth--;
}
}
/* ---- Variable management ---- */
int spl_declare_var(spl_comp_t *ctx, const char *name, int type_idx, int is_const) {
spl_var_info_t var;
memset(&var, 0, sizeof(var));
var.name = strdup(name);
var.type_idx = type_idx;
var.is_const = is_const;
var.depth = ctx->scope_depth;
var.offset = fa_alloc(&ctx->emit.frame, spl_type_size(&ctx->tctx, type_idx));
if (vec_size(ctx->scopes) > 0) {
spl_scope_t *scope = &vec_at(ctx->scopes, vec_size(ctx->scopes) - 1);
vec_push(scope->vars, var);
}
return var.offset;
}
spl_var_info_t *spl_lookup_var(spl_comp_t *ctx, const char *name) {
for (int i = (int)vec_size(ctx->scopes) - 1; i >= 0; i--) {
spl_scope_t *scope = &vec_at(ctx->scopes, i);
for (int j = (int)vec_size(scope->vars) - 1; j >= 0; j--) {
if (strcmp(vec_at(scope->vars, j).name, name) == 0)
return &vec_at(scope->vars, j);
}
}
return NULL;
}
int spl_get_var_offset(spl_comp_t *ctx, const char *name) {
spl_var_info_t *v = spl_lookup_var(ctx, name);
return v ? v->offset : -1;
}
/* ---- Function management ---- */
int spl_declare_func(spl_comp_t *ctx, const char *name, int ret_type_idx, int nparams,
int is_extern, int is_pub) {
vec_for(ctx->funcs, i) {
spl_func_info_t *existing = &vec_at(ctx->funcs, i);
if (strcmp(existing->name, name) == 0) {
existing->ret_type_idx = ret_type_idx;
existing->nparams = nparams;
existing->is_extern = is_extern;
existing->is_pub = is_pub;
existing->func_idx =
spl_prog_update_func(&ctx->prog, existing->func_idx, name, nparams);
return (int)i;
}
}
spl_func_info_t fi;
memset(&fi, 0, sizeof(fi));
fi.name = strdup(name);
fi.ret_type_idx = ret_type_idx;
fi.nparams = nparams;
fi.is_extern = is_extern;
fi.is_pub = is_pub;
if (is_extern)
fi.func_idx = -1;
else
fi.func_idx = spl_prog_add_func_simple(&ctx->prog, name, nparams);
vec_push(ctx->funcs, fi);
return (int)vec_size(ctx->funcs) - 1;
}
int spl_lookup_func(spl_comp_t *ctx, const char *name) {
{
int current = ctx->tctx.current_type_idx;
while (current >= 0) {
spl_type_item_vec_t *items = spl_type_items(&ctx->tctx, current);
if (items) {
vec_for(*items, j) {
spl_type_item_t *it = &vec_at(*items, j);
if (it->item_kind == ITEM_METHOD && it->name && strcmp(it->name, name) == 0)
return it->method.func_idx;
}
}
current = vec_at(ctx->tctx.types, current).parent_type_idx;
}
}
vec_for(ctx->funcs, j) {
if (strcmp(vec_at(ctx->funcs, j).name, name) == 0)
return (int)j;
}
return -1;
}
int spl_ensure_native(spl_comp_t *ctx, const char *name) {
vec_for(ctx->prog.natives, ni) {
if (strcmp(vec_at(ctx->prog.natives, ni).name, name) == 0)
return (int)ni;
}
spl_native_t nat;
nat.name = strdup(name);
nat.idx_of_strtab = 0;
nat.impl_fn = NULL;
vec_push(ctx->prog.natives, nat);
return (int)vec_size(ctx->prog.natives) - 1;
}
/* ---- String/data management ---- */
int spl_add_string(spl_comp_t *ctx, const char *str) {
return spl_add_global_data(ctx, (void *)str, strlen(str) + 1);
}
int spl_add_global_data(spl_comp_t *ctx, void *data, usize size) {
return spl_prog_add_data(&ctx->prog, data, size);
}
/* ---- Register runtime natives ---- */
void spl_comp_register(spl_prog_t *prog) { (void)prog; }
/* ---- Main compilation ---- */
int spl_compile(spl_comp_t *ctx, const char *source, const char *fname) {
ctx->toks = spl_lex(source, fname);
ctx->tok_idx = 0;
ctx->fname = fname;
ctx->source = source;
while (ctx->tok_idx < vec_size(ctx->toks) &&
vec_at(ctx->toks, ctx->tok_idx).type == TOK_ENDLINE)
ctx->tok_idx++;
spl_parse_prog(ctx);
if (ctx->has_error)
return -1;
emit_patch_call_fixups(&ctx->emit, &ctx->prog);
return 0;
}

View File

@@ -1,206 +0,0 @@
/* spl_comp.h — SPL compiler: type system, parser, codegen */
#ifndef __SPL_COMP_H__
#define __SPL_COMP_H__
#include "../stage0/spl_ir.h"
#include "spl_lexer.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spl_emit.h"
#include "spl_type.h"
/* Forward declarations */
typedef struct spl_comp spl_comp_t;
/* ============================================================
* Scope / symbol table
* ============================================================ */
typedef struct spl_var_info {
char *name;
int type_idx;
int offset;
int is_const;
int depth;
} spl_var_info_t;
typedef VEC(spl_var_info_t) spl_var_vec_t;
typedef struct spl_scope {
spl_var_vec_t vars;
int depth;
} spl_scope_t;
typedef VEC(spl_scope_t) spl_scope_vec_t;
typedef struct spl_func_info {
char *name;
int ret_type_idx;
int *param_type_indices;
char **param_names;
int nparams;
int func_idx;
int is_extern;
int is_pub;
} spl_func_info_t;
typedef VEC(spl_func_info_t) spl_func_info_vec_t;
/* ============================================================
* Compiler context
* ============================================================ */
#define COMP_ERROR_MAX 256
#define DEFER_MAX 64
typedef struct {
usize body_start;
usize jmp_exit;
int depth;
int count_at_decl;
} spl_defer_entry_t;
typedef struct spl_comp {
/* Lexer output */
spl_tok_vec_t toks;
usize tok_idx;
const char *fname;
const char *source;
/* Program output */
spl_prog_t prog;
/* IR emission + frame allocator */
spl_emit_t emit;
/* Error state */
char error_msg[COMP_ERROR_MAX];
int has_error;
usize error_line;
usize error_col;
/* Scopes */
spl_scope_vec_t scopes;
int scope_depth;
/* Function table */
spl_func_info_vec_t funcs;
/* Type context — first-class type arena + namespace */
spl_type_ctx_t tctx;
/* Current function context */
int current_func_idx;
int current_ret_type_idx;
char parse_context[COMP_ERROR_MAX]; /* current parsing context for error messages */
/* Loop context for break/continue */
int in_loop;
usize *break_patches;
usize break_patch_count;
usize break_patch_cap;
usize continue_target;
/* Defer stack */
spl_defer_entry_t defer_stack[DEFER_MAX];
int defer_count;
/* Global data index for string literals */
int next_gdata_idx;
/* Const values */
MAP(const char *, spl_val_t) const_values;
int addr_of_mode;
} spl_comp_t;
/* Initialize/destroy compiler context */
void spl_comp_init(spl_comp_t *ctx);
void spl_comp_drop(spl_comp_t *ctx);
/* Main compilation entry: source → .sir */
int spl_compile(spl_comp_t *ctx, const char *source, const char *fname);
/* Reset for a new compilation */
void spl_comp_reset(spl_comp_t *ctx);
/* Error reporting */
void spl_comp_error(spl_comp_t *ctx, const char *fmt, ...);
void spl_comp_err_tok(spl_comp_t *ctx, spl_tok_t *tok, const char *fmt, ...);
/* ============================================================
* Parser functions (spl_parser.c)
* ============================================================ */
void spl_parse_prog(spl_comp_t *ctx);
void parse_type_decl(spl_comp_t *ctx);
/* ============================================================
* Expression functions (spl_expr.c)
* ============================================================ */
enum {
PREC_MIN = 0,
PREC_ASSIGN = 1,
PREC_LOGOR = 2,
PREC_LOGAND = 3,
PREC_OR = 4,
PREC_XOR = 5,
PREC_AND = 6,
PREC_CMPEQ = 7,
PREC_CMP = 8,
PREC_SHIFT = 9,
PREC_ADD = 10,
PREC_MUL = 11,
PREC_PREFIX = 12,
PREC_POSTFIX = 13
};
typedef struct {
int type_idx;
int is_lvalue;
} spl_expr_result_t;
spl_expr_result_t spl_parse_expr(spl_comp_t *ctx, int min_prec);
spl_expr_result_t spl_parse_struct_literal(spl_comp_t *ctx, int type_idx);
/* Match arm pattern comparison */
int spl_emit_match_enum_cmp(spl_comp_t *ctx, int enum_type_idx, int val_offset, int by_value);
void spl_emit_match_value_cmp(spl_comp_t *ctx, int val_offset);
/* ============================================================
* Statement functions (spl_stmt.c)
* ============================================================ */
void spl_parse_stmt(spl_comp_t *ctx);
void spl_parse_block(spl_comp_t *ctx);
spl_expr_result_t spl_parse_block_expr(spl_comp_t *ctx);
/* ============================================================
* Remaining helpers in spl_comp.c
* ============================================================ */
/* Variable management */
int spl_declare_var(spl_comp_t *ctx, const char *name, int type_idx, int is_const);
spl_var_info_t *spl_lookup_var(spl_comp_t *ctx, const char *name);
int spl_get_var_offset(spl_comp_t *ctx, const char *name);
/* Function management */
int spl_declare_func(spl_comp_t *ctx, const char *name, int ret_type_idx, int nparams,
int is_extern, int is_pub);
int spl_lookup_func(spl_comp_t *ctx, const char *name);
int spl_ensure_native(spl_comp_t *ctx, const char *name);
/* String/data management */
int spl_add_string(spl_comp_t *ctx, const char *str);
int spl_add_global_data(spl_comp_t *ctx, void *data, usize size);
/* Scope management */
void spl_push_scope(spl_comp_t *ctx);
void spl_pop_scope(spl_comp_t *ctx);
/* Register runtime natives (stub) */
void spl_comp_register(spl_prog_t *prog);
#endif /* __SPL_COMP_H__ */

View File

@@ -1,282 +0,0 @@
/* spl_emit.c — IR emission: frame allocator + Layer 1/2 ops */
#include "spl_emit.h"
#include "spl_comp.h"
#include "spl_type.h"
#include <string.h>
/* ============================================================
* Lifecycle
* ============================================================ */
void spl_emit_init(spl_emit_t *e, spl_prog_t *prog) {
memset(e, 0, sizeof(*e));
e->prog = prog;
vec_init(e->fixups);
}
void spl_emit_drop(spl_emit_t *e) {
if (!e)
return;
vec_free(e->fixups);
}
/* ============================================================
* Frame allocator — non-inline
* ============================================================ */
int fa_alloc_type(spl_frame_alloc_t *fa, spl_type_ctx_t *tctx, int type_idx) {
return fa_alloc(fa, spl_type_size(tctx, type_idx));
}
spl_val_t emit_raw(spl_emit_t *e, uint16_t opcode, uint16_t type, spl_val_t imm) {
return spl_prog_emit(e->prog, opcode, type, imm);
}
/* ============================================================
* Layer 1 — single-instruction semantic wrappers
* ============================================================ */
void emit_drop(spl_emit_t *e) { emit_raw(e, SPL_DROP, SPL_VOID, 0); }
void emit_dup(spl_emit_t *e) { emit_raw(e, SPL_DUP, SPL_VOID, 0); }
void emit_swap(spl_emit_t *e) { emit_raw(e, SPL_SWAP, SPL_VOID, 0); }
void emit_rot(spl_emit_t *e) { emit_raw(e, SPL_ROT, SPL_VOID, 0); }
void emit_pick(spl_emit_t *e, int n) { emit_raw(e, SPL_PICK, SPL_VOID, n); }
void emit_push_i32(spl_emit_t *e, int v) { emit_raw(e, SPL_PUSH, SPL_I32, (spl_val_t)v); }
void emit_push_usize(spl_emit_t *e, usize v) { emit_raw(e, SPL_PUSH, SPL_USIZE, (spl_val_t)v); }
void emit_push_u64(spl_emit_t *e, uint64_t v) { emit_raw(e, SPL_PUSH, SPL_U64, (spl_val_t)v); }
void emit_push_f64(spl_emit_t *e, uint64_t v) { emit_raw(e, SPL_PUSH, SPL_F64, (spl_val_t)v); }
void emit_push_ptr(spl_emit_t *e, spl_val_t v) { emit_raw(e, SPL_PUSH, SPL_PTR, v); }
void emit_push_type(spl_emit_t *e, uint16_t bt, spl_val_t v) { emit_raw(e, SPL_PUSH, bt, v); }
void emit_load_ptr(spl_emit_t *e) { emit_raw(e, SPL_LOAD, SPL_PTR, 0); }
void emit_load_usize(spl_emit_t *e) { emit_raw(e, SPL_LOAD, SPL_USIZE, 0); }
void emit_load_type(spl_emit_t *e, uint16_t bt) { emit_raw(e, SPL_LOAD, bt, 0); }
void emit_store_i32(spl_emit_t *e) { emit_raw(e, SPL_STORE, SPL_I32, 0); }
void emit_store_ptr(spl_emit_t *e) { emit_raw(e, SPL_STORE, SPL_PTR, 0); }
void emit_store_usize(spl_emit_t *e) { emit_raw(e, SPL_STORE, SPL_USIZE, 0); }
void emit_store_type(spl_emit_t *e, uint16_t bt) { emit_raw(e, SPL_STORE, bt, 0); }
void emit_add_usize(spl_emit_t *e) { emit_raw(e, SPL_ADD, SPL_USIZE, 0); }
void emit_add_u64(spl_emit_t *e) { emit_raw(e, SPL_ADD, SPL_U64, 0); }
void emit_mul_u64(spl_emit_t *e) { emit_raw(e, SPL_MUL, SPL_U64, 0); }
void emit_sub_usize(spl_emit_t *e) { emit_raw(e, SPL_SUB, SPL_USIZE, 0); }
void emit_ult_usize(spl_emit_t *e) { emit_raw(e, SPL_ULT, SPL_USIZE, 0); }
void emit_jmp(spl_emit_t *e, spl_val_t offset) { emit_raw(e, SPL_JMP, SPL_VOID, offset); }
spl_val_t emit_jmp_here(spl_emit_t *e) { return emit_raw(e, SPL_JMP, SPL_VOID, 0); }
spl_val_t emit_bz_here(spl_emit_t *e) { return emit_raw(e, SPL_BZ, SPL_VOID, 0); }
spl_val_t emit_bnz_here(spl_emit_t *e) { return emit_raw(e, SPL_BNZ, SPL_VOID, 0); }
void emit_patch(spl_emit_t *e, spl_val_t addr, spl_val_t target) {
if (addr < vec_size(e->prog->insns))
vec_at(e->prog->insns, addr).imm = target;
}
void emit_patch_here(spl_emit_t *e, spl_val_t addr) {
spl_val_t here = vec_size(e->prog->insns);
emit_patch(e, addr, here - addr - 1);
}
void emit_laddr(spl_emit_t *e, int offset) { emit_raw(e, SPL_LADDR, SPL_PTR, offset); }
void emit_gaddr(spl_emit_t *e, int idx) { emit_raw(e, SPL_GADDR, SPL_PTR, idx); }
void emit_call(spl_emit_t *e, int nargs) { emit_raw(e, SPL_CALL, SPL_VOID, nargs); }
void emit_ncall(spl_emit_t *e, int nargs) { emit_raw(e, SPL_NCALL, SPL_VOID, nargs); }
void emit_alloc(spl_emit_t *e, int slots) { emit_raw(e, SPL_ALLOC, SPL_VOID, slots); }
void emit_binop(spl_emit_t *e, uint16_t op, uint16_t bt) { emit_raw(e, op, bt, 0); }
void emit_dbg_void(spl_emit_t *e) { emit_raw(e, SPL_DBG, SPL_VOID, 0); }
void emit_dbg_usize(spl_emit_t *e) { emit_raw(e, SPL_DBG, SPL_USIZE, 0); }
/* ============================================================
* Layer 2 — semantic-level helpers
* ============================================================ */
void emit_frame_copy(spl_emit_t *e, int dest_offset, usize nslots) {
for (usize i = 0; i < nslots; i++) {
if (i < nslots - 1)
emit_dup(e);
if (i > 0) {
emit_push_usize(e, i * sizeof(spl_val_t));
emit_add_usize(e);
}
emit_load_ptr(e);
emit_laddr(e, dest_offset + (int)(i * sizeof(spl_val_t)));
emit_swap(e);
emit_store_ptr(e);
}
}
void emit_copy_addr_to_addr(spl_emit_t *e, usize nslots, int depth) {
for (usize i = 0; i < nslots; i++) {
emit_dup(e);
if (i > 0) {
emit_push_usize(e, i * sizeof(spl_val_t));
emit_add_usize(e);
}
emit_load_ptr(e);
emit_pick(e, 2 + depth);
if (i > 0) {
emit_push_usize(e, i * sizeof(spl_val_t));
emit_add_usize(e);
}
emit_swap(e);
emit_store_ptr(e);
}
emit_drop(e);
emit_drop(e);
}
void emit_load_to_var(spl_emit_t *e, spl_type_ctx_t *tctx, int ptr_slot_offset, usize byte_offset,
int data_type_idx, int var_offset) {
emit_laddr(e, ptr_slot_offset);
emit_load_ptr(e);
emit_ptr_add(e, byte_offset);
if (data_type_idx >= 0 && !spl_type_is_scalar(tctx, data_type_idx) &&
spl_type_size(tctx, data_type_idx) > sizeof(spl_val_t)) {
emit_frame_copy(e, var_offset, spl_type_slot_count(tctx, data_type_idx));
} else {
uint16_t bt = spl_type_emit_type(tctx, data_type_idx);
emit_load_type(e, bt);
emit_laddr(e, var_offset);
emit_swap(e);
emit_store_type(e, bt);
}
}
void emit_store_to_laddr(spl_emit_t *e, int offset, uint16_t type) {
emit_laddr(e, offset);
emit_swap(e);
emit_store_type(e, type);
}
void emit_ptr_add(spl_emit_t *e, usize byte_off) {
if (byte_off > 0) {
emit_push_usize(e, byte_off);
emit_add_usize(e);
}
}
spl_val_t emit_call_with_fixup(spl_emit_t *e, int nargs, int func_idx) {
spl_val_t fixup_addr = emit_raw(e, SPL_PUSH, SPL_PTR, 0);
emit_call(e, nargs);
spl_fixup_entry_t fe = {fixup_addr, func_idx};
vec_push(e->fixups, fe);
return fixup_addr;
}
void emit_return(spl_emit_t *e, spl_type_ctx_t *tctx, int ret_type_idx) {
if (spl_type_needs_multi_slot(tctx, ret_type_idx)) {
emit_laddr(e, (int)sizeof(spl_val_t));
emit_raw(e, SPL_RET, SPL_PTR, 0);
} else {
uint16_t rt = spl_type_emit_type(tctx, ret_type_idx);
emit_raw(e, SPL_RET, rt, 0);
}
}
void emit_patch_call_fixups(spl_emit_t *e, spl_prog_t *prog) {
for (usize i = 0; i < vec_size(e->fixups); i++) {
spl_fixup_entry_t *fe = &vec_at(e->fixups, i);
if (fe->func_idx >= 0 && fe->func_idx < (int)vec_size(prog->funcs)) {
spl_val_t addr = vec_at(prog->funcs, fe->func_idx).address;
vec_at(prog->insns, fe->insn_idx).imm = addr;
} else {
fprintf(stderr, "WARN: fixup func_idx=%d out of bounds [0,%zu), insn_idx=%zu\n",
fe->func_idx, vec_size(prog->funcs), fe->insn_idx);
}
}
}
void spl_emit_ret(spl_comp_t *ctx, int ret_type_idx) {
if (spl_type_needs_multi_slot(&ctx->tctx, ret_type_idx)) {
emit_laddr(&ctx->emit, (int)sizeof(spl_val_t));
emit_swap(&ctx->emit);
emit_copy_addr_to_addr(&ctx->emit, spl_type_slot_count(&ctx->tctx, ret_type_idx), 0);
}
emit_return(&ctx->emit, &ctx->tctx, ret_type_idx);
}
void spl_emit_store_init(spl_comp_t *ctx, int var_offset, int var_type_idx) {
if (var_type_idx >= 0 && (spl_type_kind(&ctx->tctx, var_type_idx) == TYPE_STRUCT ||
spl_type_kind(&ctx->tctx, var_type_idx) == TYPE_ENUM)) {
usize sz = spl_type_size(&ctx->tctx, var_type_idx);
if (sz <= sizeof(spl_val_t)) {
emit_store_to_laddr(&ctx->emit, var_offset,
spl_type_emit_type(&ctx->tctx, var_type_idx));
} else {
usize nslots = (sz + sizeof(spl_val_t) - 1) / sizeof(spl_val_t);
emit_frame_copy(&ctx->emit, var_offset, nslots);
}
} else if (var_type_idx >= 0 && spl_type_kind(&ctx->tctx, var_type_idx) == TYPE_ARRAY) {
int elem_idx = spl_type_elem_type(&ctx->tctx, var_type_idx);
spl_type_t bt = spl_type_emit_type(&ctx->tctx, elem_idx);
usize stride = spl_type_elem_stride(&ctx->tctx, elem_idx);
int arr_len = (int)spl_type_array_len(&ctx->tctx, var_type_idx);
for (int i = arr_len - 1; i >= 0; i--) {
emit_laddr(&ctx->emit, var_offset + (int)(i * stride));
emit_swap(&ctx->emit);
if (elem_idx >= 0 && !spl_type_is_scalar(&ctx->tctx, elem_idx)) {
emit_copy_addr_to_addr(&ctx->emit, spl_type_slot_count(&ctx->tctx, elem_idx), 0);
} else {
emit_store_type(&ctx->emit, bt);
}
}
} else if (var_type_idx >= 0 && spl_type_kind(&ctx->tctx, var_type_idx) == TYPE_SLICE) {
emit_store_to_laddr(&ctx->emit, var_offset + (int)sizeof(spl_val_t), SPL_USIZE);
emit_store_to_laddr(&ctx->emit, var_offset, SPL_PTR);
} else {
spl_type_t bt = spl_type_emit_type(&ctx->tctx, var_type_idx);
emit_store_to_laddr(&ctx->emit, var_offset, bt);
}
}
void spl_emit_defer(spl_comp_t *ctx) {
if (ctx->defer_count >= DEFER_MAX)
return;
spl_val_t jmp_skip = emit_jmp_here(&ctx->emit);
spl_defer_entry_t *e = &ctx->defer_stack[ctx->defer_count];
e->body_start = jmp_skip + 1;
e->jmp_exit = 0;
e->depth = ctx->scope_depth;
e->count_at_decl = ctx->defer_count;
ctx->defer_count++;
}
void spl_emit_defer_epilogue(spl_comp_t *ctx, int depth) {
for (int i = 0; i < ctx->defer_count; i++) {
if (ctx->defer_stack[i].depth != depth)
continue;
spl_defer_entry_t *e = &ctx->defer_stack[i];
spl_val_t skip_addr = e->body_start - 1;
spl_val_t skip_target = e->jmp_exit + 1;
emit_patch(&ctx->emit, skip_addr, skip_target - skip_addr - 1);
}
for (int i = ctx->defer_count - 1; i >= 0; i--) {
if (ctx->defer_stack[i].depth != depth)
continue;
spl_defer_entry_t *e = &ctx->defer_stack[i];
spl_val_t here = vec_size(ctx->prog.insns);
spl_val_t jmp_offset = (spl_val_t)((isize)e->body_start - (isize)here - 1);
emit_jmp(&ctx->emit, jmp_offset);
if (e->jmp_exit > 0)
emit_patch(&ctx->emit, e->jmp_exit, here + 1 - e->jmp_exit - 1);
}
int new_count = 0;
for (int i = 0; i < ctx->defer_count; i++) {
if (ctx->defer_stack[i].depth != depth)
ctx->defer_stack[new_count++] = ctx->defer_stack[i];
}
ctx->defer_count = new_count;
}

View File

@@ -1,155 +0,0 @@
#ifndef __SPL_EMIT_H__
#define __SPL_EMIT_H__
#include "../stage0/spl_ir.h"
#include "spl_type.h"
#include <stdint.h>
/* ============================================================
* Frame allocator
* ============================================================ */
typedef struct {
int current_bytes;
int peak_bytes;
} spl_frame_alloc_t;
static inline void fa_init(spl_frame_alloc_t *fa) {
fa->current_bytes = 0;
fa->peak_bytes = 0;
}
static inline int fa_alloc(spl_frame_alloc_t *fa, usize byte_size) {
usize aligned = (byte_size + sizeof(spl_val_t) - 1) & ~(sizeof(spl_val_t) - 1);
if (aligned < sizeof(spl_val_t))
aligned = sizeof(spl_val_t);
int offset = fa->current_bytes;
fa->current_bytes += (int)aligned;
if (fa->current_bytes > fa->peak_bytes)
fa->peak_bytes = fa->current_bytes;
return offset;
}
int fa_alloc_type(spl_frame_alloc_t *fa, spl_type_ctx_t *tctx, int type_idx);
static inline void fa_reset_to(spl_frame_alloc_t *fa, int mark) { fa->current_bytes = mark; }
static inline int fa_alloc_slots(spl_frame_alloc_t *fa, usize nslots) {
return fa_alloc(fa, nslots * sizeof(spl_val_t));
}
static inline int fa_alloc_temp(spl_frame_alloc_t *fa, usize nslots) {
return fa_alloc_slots(fa, nslots);
}
static inline void fa_free(spl_frame_alloc_t *fa, int mark) { fa->current_bytes = mark; }
/* ============================================================
* Emit context
* ============================================================ */
typedef struct {
spl_val_t insn_idx;
int func_idx;
} spl_fixup_entry_t;
typedef struct {
spl_prog_t *prog;
spl_frame_alloc_t frame;
VEC(spl_fixup_entry_t) fixups;
} spl_emit_t;
void spl_emit_init(spl_emit_t *e, spl_prog_t *prog);
void spl_emit_drop(spl_emit_t *e);
/* ============================================================
* Layer 1 — single-instruction semantic wrappers
* ============================================================ */
/* Stack ops */
void emit_drop(spl_emit_t *e);
void emit_dup(spl_emit_t *e);
void emit_swap(spl_emit_t *e);
void emit_rot(spl_emit_t *e);
void emit_pick(spl_emit_t *e, int n);
/* Push */
void emit_push_i32(spl_emit_t *e, int v);
void emit_push_usize(spl_emit_t *e, usize v);
void emit_push_u64(spl_emit_t *e, uint64_t v);
void emit_push_f64(spl_emit_t *e, uint64_t v);
void emit_push_ptr(spl_emit_t *e, spl_val_t v);
void emit_push_type(spl_emit_t *e, uint16_t bt, spl_val_t v);
/* Load */
void emit_load_ptr(spl_emit_t *e);
void emit_load_usize(spl_emit_t *e);
void emit_load_type(spl_emit_t *e, uint16_t bt);
/* Store */
void emit_store_i32(spl_emit_t *e);
void emit_store_ptr(spl_emit_t *e);
void emit_store_usize(spl_emit_t *e);
void emit_store_type(spl_emit_t *e, uint16_t bt);
/* Arithmetic */
void emit_add_usize(spl_emit_t *e);
void emit_add_u64(spl_emit_t *e);
void emit_mul_u64(spl_emit_t *e);
void emit_sub_usize(spl_emit_t *e);
/* Compare */
void emit_ult_usize(spl_emit_t *e);
/* Branch */
void emit_jmp(spl_emit_t *e, spl_val_t offset);
spl_val_t emit_jmp_here(spl_emit_t *e);
spl_val_t emit_bz_here(spl_emit_t *e);
spl_val_t emit_bnz_here(spl_emit_t *e);
void emit_patch(spl_emit_t *e, spl_val_t addr, spl_val_t target);
void emit_patch_here(spl_emit_t *e, spl_val_t addr);
/* Address */
void emit_laddr(spl_emit_t *e, int offset);
void emit_gaddr(spl_emit_t *e, int idx);
/* Call */
void emit_call(spl_emit_t *e, int nargs);
void emit_ncall(spl_emit_t *e, int nargs);
/* Misc */
void emit_alloc(spl_emit_t *e, int slots);
void emit_binop(spl_emit_t *e, uint16_t op, uint16_t bt);
void emit_dbg_void(spl_emit_t *e);
void emit_dbg_usize(spl_emit_t *e);
/* Low-level emit (raw opcode + type + imm) */
spl_val_t emit_raw(spl_emit_t *e, uint16_t opcode, uint16_t type, spl_val_t imm);
/* ============================================================
* Layer 2 — semantic-level helpers
* ============================================================ */
void emit_frame_copy(spl_emit_t *e, int dest_offset, usize nslots);
void emit_copy_addr_to_addr(spl_emit_t *e, usize nslots, int depth);
void emit_load_to_var(spl_emit_t *e, spl_type_ctx_t *tctx, int ptr_slot_offset, usize byte_offset,
int data_type_idx, int var_offset);
void emit_store_to_laddr(spl_emit_t *e, int offset, uint16_t type);
void emit_ptr_add(spl_emit_t *e, usize byte_off);
spl_val_t emit_call_with_fixup(spl_emit_t *e, int nargs, int func_idx);
void emit_return(spl_emit_t *e, spl_type_ctx_t *tctx, int ret_type_idx);
/* Patch all fixups */
void emit_patch_call_fixups(spl_emit_t *e, spl_prog_t *prog);
/* ============================================================
* Layer 3 — compiler-level helpers (need spl_comp_t for tctx)
* ============================================================ */
struct spl_comp;
void spl_emit_ret(struct spl_comp *ctx, int ret_type_idx);
void spl_emit_store_init(struct spl_comp *ctx, int var_offset, int var_type_idx);
void spl_emit_defer(struct spl_comp *ctx);
void spl_emit_defer_epilogue(struct spl_comp *ctx, int depth);
#endif /* __SPL_EMIT_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,142 +0,0 @@
/* spl_lex_util.c — Lexer utility functions */
#include "spl_lex_util.h"
#include <stdio.h>
#include <string.h>
spl_tok_t *peek(spl_comp_t *ctx) { return &vec_at(ctx->toks, ctx->tok_idx); }
spl_tok_t *advance(spl_comp_t *ctx) {
spl_tok_t *t = &vec_at(ctx->toks, ctx->tok_idx);
if (t->type != TOK_EOF)
ctx->tok_idx++;
return t;
}
int expect(spl_comp_t *ctx, spl_tok_type_t type) {
spl_tok_t *tok = peek(ctx);
if (tok->type == type) {
advance(ctx);
return 1;
}
/* Extract token text for display (up to 40 chars) */
char val_buf[64];
usize display_len = tok->len < 40 ? tok->len : 40;
memcpy(val_buf, tok->lexeme, display_len);
val_buf[display_len] = '\0';
/* Replace newlines with \n for display */
for (usize i = 0; i < display_len; i++) {
if (val_buf[i] == '\n')
val_buf[i] = ' ';
}
if (ctx->parse_context[0]) {
spl_comp_err_tok(ctx, tok, "%s: expected %s, got %s '%s'", ctx->parse_context,
spl_tok_type_name(type), spl_tok_type_name(tok->type), val_buf);
} else {
spl_comp_err_tok(ctx, tok, "expected %s, got %s '%s'", spl_tok_type_name(type),
spl_tok_type_name(tok->type), val_buf);
}
return 0;
}
int match(spl_comp_t *ctx, spl_tok_type_t type) {
if (peek(ctx)->type == type) {
advance(ctx);
return 1;
}
return 0;
}
void skip_nl(spl_comp_t *ctx) {
while (peek(ctx)->type == TOK_ENDLINE)
advance(ctx);
}
int spl_parse_int_literal(spl_comp_t *ctx, int *val) {
int negate = 0;
if (peek(ctx)->type == TOK_SUB) {
negate = 1;
advance(ctx);
}
if (peek(ctx)->type != TOK_INT_LITERAL) {
if (negate)
ctx->tok_idx--; /* un-consume the SUB token */
return 0;
}
spl_tok_t *tok = advance(ctx);
long long v = strtoll(tok->lexeme, NULL, 0);
*val = negate ? -(int)v : (int)v;
return 1;
}
const char *spl_tok_type_name(spl_tok_type_t type) {
switch (type) {
#define X(name, enum_name, dummy) \
case enum_name: \
return #name;
KEYWORD_TABLE
TOKEN_TABLE
#undef X
default:
return "???";
}
}
void spl_tok_dump(spl_tok_t *tok) {
if (!tok)
return;
/* Extract token text for display (up to 40 chars) */
char buf[64];
usize display_len = tok->len < 40 ? tok->len : 40;
memcpy(buf, tok->lexeme, display_len);
buf[display_len] = '\0';
/* Replace newlines with \n for display */
for (usize i = 0; i < display_len; i++) {
if (buf[i] == '\n')
buf[i] = ' ';
}
printf("%s:%zu:%zu %-20s '%s'", tok->fname ? tok->fname : "", tok->line, tok->col,
spl_tok_type_name(tok->type), buf);
if (tok->type == TOK_INT_LITERAL) {
printf(" [int]");
} else if (tok->type == TOK_STRING_LITERAL) {
printf(" [string]");
} else if (tok->type == TOK_CHAR_LITERAL) {
printf(" [char]");
} else if (tok->type == TOK_FLOAT_LITERAL) {
printf(" [float]");
}
printf("\n");
}
void spl_tok_vec_dump(spl_tok_vec_t *toks) {
if (!toks)
return;
printf("=== TOKEN DUMP (%zu tokens) ===\n", vec_size(*toks));
vec_for(*toks, i) {
spl_tok_t *tok = &vec_at(*toks, i);
printf("%4zu: ", i);
spl_tok_dump(tok);
}
}
void spl_tok_vec_drop(spl_tok_vec_t *toks) {
if (toks) {
vec_free(*toks);
}
}
usize spl_tok_copy_name(spl_tok_t *tok, char *buf, usize buf_size) {
if (!tok || !buf || buf_size == 0)
return 0;
usize nlen = tok->len < buf_size - 1 ? tok->len : buf_size - 1;
memcpy(buf, tok->lexeme, nlen);
buf[nlen] = '\0';
return nlen;
}

View File

@@ -1,29 +0,0 @@
/* spl_lex_util.h — Shared token helper utilities */
#ifndef __SPL_LEX_UTIL_H__
#define __SPL_LEX_UTIL_H__
#include "spl_comp.h"
/* Token stream access */
spl_tok_t *peek(spl_comp_t *ctx);
spl_tok_t *advance(spl_comp_t *ctx);
/* Token matching helpers */
int expect(spl_comp_t *ctx, spl_tok_type_t type);
int match(spl_comp_t *ctx, spl_tok_type_t type);
void skip_nl(spl_comp_t *ctx);
/* Token introspection */
const char *spl_tok_type_name(spl_tok_type_t type);
void spl_tok_dump(spl_tok_t *tok);
void spl_tok_vec_dump(spl_tok_vec_t *toks);
void spl_tok_vec_drop(spl_tok_vec_t *toks);
usize spl_tok_copy_name(spl_tok_t *tok, char *buf, usize buf_size);
const char *spl_tok_loc_str(spl_comp_t *ctx);
/* Parse an integer literal value, handling optional '-' prefix for negatives.
* Returns 1 on success (value in *val), 0 if current token isn't an integer.
* On success, advances past all consumed tokens. On failure, does not advance. */
int spl_parse_int_literal(spl_comp_t *ctx, int *val);
#endif /* __SPL_LEX_UTIL_H__ */

View File

@@ -2,130 +2,7 @@
#ifndef __SPL_LEXER_H__
#define __SPL_LEXER_H__
#include "../stage0/spl_ir.h"
/* clang-format off */
#define KEYWORD_TABLE \
X(as , KW_AS , SPL_V0) \
X(asm , KW_ASM , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(catch , KW_CATCH , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(extern , KW_EXTERN , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
X(match , KW_MATCH , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(pub , KW_PUB , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(struct , KW_STRUCT , SPL_V0) \
X(test , KW_TEST , SPL_V0) \
X(true , KW_TRUE , SPL_V0) \
X(try , KW_TRY , SPL_V0) \
X(type , KW_TYPE , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
X(var , KW_VAR , SPL_V0) \
X(void , KW_VOID , SPL_V0) \
X(while , KW_WHILE , SPL_V0) \
X(_ , KW_ANY , SPL_V0) \
// KEYWORD_TABLE
#define TOKEN_TABLE \
X(unknown , TOK_UNKNOWN , SPL_V0 ) \
X(EOF , TOK_EOF , SPL_V0 ) \
X(blank , TOK_BLANK , SPL_V0 ) \
X(endline , TOK_ENDLINE , SPL_V0 ) \
X("#" , TOK_SHARP , SPL_V0 ) \
X("@" , TOK_AT , SPL_V0 ) \
X("==" , TOK_EQ , SPL_V0 ) \
X("=" , TOK_ASSIGN , SPL_V0 ) \
X("+=" , TOK_ASSIGN_ADD , SPL_V0 ) \
X("+" , TOK_ADD , SPL_V0 ) \
X("-=" , TOK_ASSIGN_SUB , SPL_V0 ) \
X("->" , TOK_RIGHT_ARRAY , SPL_V0 ) \
X("<-" , TOK_LEFT_ARRAY , SPL_V0 ) \
X("-" , TOK_SUB , SPL_V0 ) \
X("*=" , TOK_ASSIGN_MUL , SPL_V0 ) \
X("*" , TOK_MUL , SPL_V0 ) \
X("/=" , TOK_ASSIGN_DIV , SPL_V0 ) \
X("/" , TOK_DIV , SPL_V0 ) \
X("//" , TOK_LINE_COMMENT , SPL_V0 ) \
X("/* */" , TOK_BLOCK_COMMENT , SPL_V0 ) \
X("%=" , TOK_ASSIGN_MOD , SPL_V0 ) \
X("%" , TOK_MOD , SPL_V0 ) \
X("&&" , TOK_AND_AND , SPL_V0 ) \
X("&=" , TOK_ASSIGN_AND , SPL_V0 ) \
X("&" , TOK_AND , SPL_V0 ) \
X("||" , TOK_OR_OR , SPL_V0 ) \
X("|=" , TOK_ASSIGN_OR , SPL_V0 ) \
X("|" , TOK_OR , SPL_V0 ) \
X("^=" , TOK_ASSIGN_XOR , SPL_V0 ) \
X("^" , TOK_XOR , SPL_V0 ) \
X("<<=" , TOK_ASSIGN_L_SH , SPL_V0 ) \
X("<<" , TOK_L_SH , SPL_V0 ) \
X("<=" , TOK_LE , SPL_V0 ) \
X("<" , TOK_LT , SPL_V0 ) \
X(">>=" , TOK_ASSIGN_R_SH , SPL_V0 ) \
X(">>" , TOK_R_SH , SPL_V0 ) \
X(">=" , TOK_GE , SPL_V0 ) \
X(">" , TOK_GT , SPL_V0 ) \
X("!" , TOK_NOT , SPL_V0 ) \
X("!=" , TOK_NEQ , SPL_V0 ) \
X("~" , TOK_BIT_NOT , SPL_V0 ) \
X("[" , TOK_L_BRACKET , SPL_V0 ) \
X("]" , TOK_R_BRACKET , SPL_V0 ) \
X("(" , TOK_L_PAREN , SPL_V0 ) \
X(")" , TOK_R_PAREN , SPL_V0 ) \
X("{" , TOK_L_BRACE , SPL_V0 ) \
X("}" , TOK_R_BRACE , SPL_V0 ) \
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
X(char , TOK_CHAR_LITERAL , SPL_V0 ) \
X(string , TOK_STRING_LITERAL , SPL_V0 ) \
// TOKEN_TABLE
/* clang-format on */
/* spl_tok_type_t — KEYWORD_TABLE + TOKEN_TABLE 展开 */
/* clang-format off */
typedef enum {
#define X(name, enum_name, dummy) enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) enum_name,
TOKEN_TABLE
#undef X
} spl_tok_type_t;
/* clang-format on */
typedef struct {
spl_tok_type_t type;
const char *lexeme;
usize len; /* token length in bytes */
const char *fname;
usize offset;
usize line;
usize col;
} spl_tok_t;
typedef VEC(spl_tok_t) spl_tok_vec_t;
#include "spl_tok.h"
/* Lexer entry point */
spl_tok_vec_t spl_lex(const char *source, const char *fname);

View File

@@ -1,753 +0,0 @@
/* spl_parser.c — Top-level parser: function declarations, type declarations, etc. */
#include "spl_comp.h"
#include "spl_lex_util.h"
#include <string.h>
/* ============================================================
* Parse function definition
* ============================================================ */
enum { MAX_PARAMS = 64 };
static int parse_params_decl(spl_comp_t *ctx, char pnames[][256], int ptypes[]) {
int nparams = 0;
skip_nl(ctx);
if (peek(ctx)->type != TOK_R_PAREN) {
{
usize saved = ctx->tok_idx;
spl_tok_t *ptok = advance(ctx);
skip_nl(ctx);
if (ptok->type == KW_VOID && peek(ctx)->type == TOK_R_PAREN) {
expect(ctx, TOK_R_PAREN);
return 0;
}
ctx->tok_idx = saved;
}
while (1) {
if (peek(ctx)->type == TOK_ELLIPSIS) {
advance(ctx);
break;
}
spl_tok_t *pname = advance(ctx);
spl_tok_copy_name(pname, pnames[nparams], 256);
skip_nl(ctx);
if (peek(ctx)->type == TOK_COLON) {
advance(ctx);
skip_nl(ctx);
ptypes[nparams] = spl_type_parse(&ctx->tctx, ctx);
} else {
ptypes[nparams] = spl_type_basic(&ctx->tctx, SPL_I32);
}
nparams++;
skip_nl(ctx);
if (peek(ctx)->type == TOK_COMMA) {
advance(ctx);
skip_nl(ctx);
continue;
}
break;
}
}
expect(ctx, TOK_R_PAREN);
return nparams;
}
static int parse_fn_body(spl_comp_t *ctx, const char *fn_name, int ret_type_idx, int nparams,
char pnames[][256], int ptypes[], int is_pub) {
snprintf(ctx->parse_context, sizeof(ctx->parse_context), "function '%s'", fn_name);
int fi = spl_declare_func(ctx, fn_name, ret_type_idx, nparams, 0, is_pub);
{
spl_func_info_t *f = &vec_at(ctx->funcs, fi);
f->param_type_indices = calloc(nparams, sizeof(int));
f->param_names = calloc(nparams, sizeof(char *));
for (int i = 0; i < nparams; i++) {
f->param_type_indices[i] = ptypes[i];
f->param_names[i] = strdup(pnames[i]);
}
}
ctx->current_func_idx = fi;
ctx->current_ret_type_idx = ret_type_idx;
fa_init(&ctx->emit.frame);
spl_push_scope(ctx);
for (int i = 0; i < nparams; i++) {
spl_declare_var(ctx, pnames[i], ptypes[i], 0);
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_L_BRACE) {
advance(ctx);
skip_nl(ctx);
spl_val_t alloc_addr = vec_size(ctx->prog.insns);
emit_alloc(&ctx->emit, 0);
while (!ctx->has_error && peek(ctx)->type != TOK_R_BRACE && peek(ctx)->type != TOK_EOF) {
spl_parse_stmt(ctx);
skip_nl(ctx);
}
/* Error recovery: skip to matching } if has_error caused early exit */
if (ctx->has_error) {
int depth = 1;
while (depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE)
depth++;
else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0)
break;
} else if (tt == TOK_EOF)
break;
advance(ctx);
}
if (peek(ctx)->type == TOK_R_BRACE)
advance(ctx);
else
return 0;
} else {
if (!expect(ctx, TOK_R_BRACE))
return 0;
}
int total_phys_slots = 0;
for (int i = 0; i < nparams; i++) {
usize psz = spl_type_size(&ctx->tctx, ptypes[i]);
total_phys_slots += (int)((psz + sizeof(spl_val_t) - 1) / sizeof(spl_val_t));
}
if (spl_type_needs_multi_slot(&ctx->tctx, ret_type_idx)) {
usize min_bytes = spl_type_slot_count(&ctx->tctx, ret_type_idx) * sizeof(spl_val_t);
if ((usize)ctx->emit.frame.peak_bytes < min_bytes)
ctx->emit.frame.peak_bytes = (int)min_bytes;
}
int alloc_slots = ctx->emit.frame.peak_bytes / (int)sizeof(spl_val_t) - total_phys_slots;
if (alloc_slots < 0 || alloc_slots > 65536) {
fprintf(
stderr,
"WARN: parse_fn_body: suspicious alloc_slots=%d (peak_bytes=%d, phys_slots=%d)\n",
alloc_slots, ctx->emit.frame.peak_bytes, total_phys_slots);
}
emit_patch(&ctx->emit, alloc_addr, alloc_slots);
}
spl_emit_defer_epilogue(ctx, ctx->scope_depth);
spl_pop_scope(ctx);
emit_return(&ctx->emit, &ctx->tctx, ctx->current_ret_type_idx);
{
spl_func_info_t *f = &vec_at(ctx->funcs, fi);
spl_prog_end_func(&ctx->prog, f->func_idx);
}
ctx->current_func_idx = -1;
ctx->current_ret_type_idx = -1;
return fi;
}
static void parse_fn_decl(spl_comp_t *ctx, int is_extern, int is_pub) {
advance(ctx); /* fn */
skip_nl(ctx);
spl_tok_t *fname_tok = advance(ctx);
char fn_name[256];
spl_tok_copy_name(fname_tok, fn_name, sizeof(fn_name));
skip_nl(ctx);
if (!expect(ctx, TOK_L_PAREN))
return;
char pnames[MAX_PARAMS][256];
int ptypes[MAX_PARAMS];
int nparams = parse_params_decl(ctx, pnames, ptypes);
skip_nl(ctx);
int ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
if (peek(ctx)->type != TOK_SEMICOLON && peek(ctx)->type != TOK_L_BRACE) {
ret_type_idx = spl_type_parse(&ctx->tctx, ctx);
if (ret_type_idx < 0)
ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
skip_nl(ctx);
}
int fi;
if (is_extern) {
fi = spl_declare_func(ctx, fn_name, ret_type_idx, nparams, 1, is_pub);
spl_ensure_native(ctx, fn_name);
if (ctx->tctx.current_type_idx == 0)
spl_type_add_method(&ctx->tctx, 0, fn_name, fi);
if (peek(ctx)->type == TOK_SEMICOLON)
advance(ctx);
return;
}
if (peek(ctx)->type == TOK_SEMICOLON) {
advance(ctx);
return;
}
skip_nl(ctx);
fi = parse_fn_body(ctx, fn_name, ret_type_idx, nparams, pnames, ptypes, is_pub);
if (ctx->tctx.current_type_idx == 0)
spl_type_add_method(&ctx->tctx, 0, fn_name, fi);
}
/* ============================================================
* Parse method declaration inside a type body
* ============================================================ */
static void parse_method_decl(spl_comp_t *ctx, int container_type_idx) {
advance(ctx); /* fn */
skip_nl(ctx);
spl_tok_t *mname_tok = advance(ctx);
char mname[256];
spl_tok_copy_name(mname_tok, mname, sizeof(mname));
const char *cname = spl_type_name(&ctx->tctx, container_type_idx);
char qualified[512];
snprintf(qualified, sizeof(qualified), "%s.%s", cname ? cname : "anon", mname);
skip_nl(ctx);
if (!expect(ctx, TOK_L_PAREN))
return;
char pnames[MAX_PARAMS][256];
int ptypes[MAX_PARAMS];
int nparams = parse_params_decl(ctx, pnames, ptypes);
skip_nl(ctx);
int ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
if (peek(ctx)->type != TOK_SEMICOLON && peek(ctx)->type != TOK_L_BRACE) {
ret_type_idx = spl_type_parse(&ctx->tctx, ctx);
if (ret_type_idx < 0)
ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
skip_nl(ctx);
}
int fi = parse_fn_body(ctx, qualified, ret_type_idx, nparams, pnames, ptypes, 0);
spl_type_add_method(&ctx->tctx, container_type_idx, mname, fi);
}
/* ============================================================
* Parse type container body (shared for struct, union, enum)
* ============================================================ */
static void parse_type_body(spl_comp_t *ctx, int container_type_idx, int is_enum) {
if (peek(ctx)->type != TOK_L_BRACE)
return;
advance(ctx); /* { */
int saved_current = ctx->tctx.current_type_idx;
ctx->tctx.current_type_idx = container_type_idx;
/* === Pass 1: Parse all nested type declarations first === */
{
usize saved = ctx->tok_idx;
int depth = 1;
while (!ctx->has_error && depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE) {
depth++;
advance(ctx);
} else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0)
break;
advance(ctx);
} else if (tt == KW_TYPE && depth == 1) {
parse_type_decl(ctx);
} else if (tt == TOK_EOF) {
break;
} else {
advance(ctx);
}
}
ctx->tok_idx = saved;
}
/* === Pre-register method names for forward references === */
{
const char *cname = spl_type_name(&ctx->tctx, container_type_idx);
if (cname) {
usize saved = ctx->tok_idx;
int depth = 1;
while (!ctx->has_error && depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE) {
depth++;
advance(ctx);
} else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0)
break;
advance(ctx);
} else if (tt == KW_FN && depth == 1) {
advance(ctx); /* fn */
skip_nl(ctx);
spl_tok_t *name_tok = advance(ctx);
char mname[256];
spl_tok_copy_name(name_tok, mname, sizeof(mname));
/* Count parameters for forward reference */
int pcount = 0;
if (peek(ctx)->type == TOK_L_PAREN) {
advance(ctx); /* ( */
skip_nl(ctx);
if (peek(ctx)->type != TOK_R_PAREN) {
pcount = 1;
for (;;) {
advance(ctx); /* skip param name or type token */
skip_nl(ctx);
if (peek(ctx)->type == TOK_R_PAREN)
break;
if (peek(ctx)->type == TOK_COMMA) {
advance(ctx); /* , */
skip_nl(ctx);
pcount++;
}
}
}
advance(ctx); /* ) */
}
char qualified[512];
snprintf(qualified, sizeof(qualified), "%s.%s", cname, mname);
int fi = spl_declare_func(ctx, qualified, -1, pcount, 0, 0);
spl_type_add_method(&ctx->tctx, container_type_idx, mname, fi);
} else if (tt == TOK_EOF) {
break;
} else {
advance(ctx);
}
}
ctx->tok_idx = saved;
}
}
/* === Pass 2: Parse fields/variants and methods === */
{
int depth = 1;
while (!ctx->has_error && depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
skip_nl(ctx);
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE) {
depth++;
advance(ctx);
} else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0) {
advance(ctx);
break;
}
advance(ctx);
} else if (tt == KW_TYPE && depth == 1) {
parse_type_decl(ctx);
} else if (tt == KW_VAR && depth == 1 && !is_enum) {
advance(ctx); /* var */
skip_nl(ctx);
spl_tok_t *ftok = advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == TOK_COLON) {
advance(ctx); /* : */
skip_nl(ctx);
int ftype = spl_type_parse(&ctx->tctx, ctx);
char fname[256];
spl_tok_copy_name(ftok, fname, sizeof(fname));
if (ftype >= 0)
spl_type_add_var(&ctx->tctx, container_type_idx, fname, ftype);
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_SEMICOLON || peek(ctx)->type == TOK_COMMA)
advance(ctx);
} else if (tt == TOK_IDENT && depth == 1) {
if (is_enum) {
spl_tok_t *vtok = advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == TOK_COLON) {
advance(ctx); /* : */
skip_nl(ctx);
int dtype = spl_type_parse(&ctx->tctx, ctx);
char vname[256];
spl_tok_copy_name(vtok, vname, sizeof(vname));
spl_type_add_variant(&ctx->tctx, container_type_idx, vname,
dtype >= 0 ? dtype : -1);
} else if (tt == TOK_EOF) {
break;
} else {
char vname[256];
spl_tok_copy_name(vtok, vname, sizeof(vname));
spl_type_add_variant(&ctx->tctx, container_type_idx, vname, -1);
}
} else {
spl_tok_t *ftok = advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == TOK_COLON) {
advance(ctx); /* : */
skip_nl(ctx);
int ftype = spl_type_parse(&ctx->tctx, ctx);
char fname[256];
spl_tok_copy_name(ftok, fname, sizeof(fname));
if (ftype >= 0)
spl_type_add_field(&ctx->tctx, container_type_idx, fname, ftype);
}
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_SEMICOLON || peek(ctx)->type == TOK_COMMA)
advance(ctx);
} else if (tt == KW_FN && depth == 1) {
spl_type_compute_layout(&ctx->tctx, container_type_idx);
parse_method_decl(ctx, container_type_idx);
} else {
advance(ctx);
}
}
}
ctx->tctx.current_type_idx = saved_current;
}
/* ============================================================
* Parse type declaration
* ============================================================ */
void parse_type_decl(spl_comp_t *ctx) {
advance(ctx); /* type */
spl_tok_t *name_tok = advance(ctx);
char tname[256];
spl_tok_copy_name(name_tok, tname, sizeof(tname));
snprintf(ctx->parse_context, sizeof(ctx->parse_context), "type '%s'", tname);
skip_nl(ctx);
if (!expect(ctx, TOK_ASSIGN))
return;
skip_nl(ctx);
int parent_type_idx = ctx->tctx.current_type_idx;
/* Check if already pre-registered in Pass 0 */
int existing = spl_type_resolve(&ctx->tctx, tname);
if (peek(ctx)->type == KW_STRUCT) {
advance(ctx);
int ti;
if (existing >= 0)
ti = existing;
else
ti = spl_type_struct(&ctx->tctx, tname);
if (parent_type_idx >= 0 && existing < 0)
spl_type_add_nested(&ctx->tctx, parent_type_idx, tname, ti);
skip_nl(ctx);
parse_type_body(ctx, ti, 0);
} else if (peek(ctx)->type == KW_UNION) {
advance(ctx);
int ti;
if (existing >= 0)
ti = existing;
else
ti = spl_type_union(&ctx->tctx, tname);
if (parent_type_idx >= 0 && existing < 0)
spl_type_add_nested(&ctx->tctx, parent_type_idx, tname, ti);
skip_nl(ctx);
parse_type_body(ctx, ti, 1);
} else if (peek(ctx)->type == KW_ENUM) {
advance(ctx);
int ti;
if (existing >= 0)
ti = existing;
else
ti = spl_type_enum(&ctx->tctx, tname);
if (parent_type_idx >= 0 && existing < 0)
spl_type_add_nested(&ctx->tctx, parent_type_idx, tname, ti);
skip_nl(ctx);
parse_type_body(ctx, ti, 1);
} else if (peek(ctx)->type == TOK_IDENT ||
(peek(ctx)->type >= KW_AS && peek(ctx)->type <= KW_ANY)) {
int base = spl_type_parse(&ctx->tctx, ctx);
if (base >= 0) {
spl_type_alias(&ctx->tctx, tname, base);
}
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_SEMICOLON)
advance(ctx);
}
/* ============================================================
* Pre-registration pass: register all names before filling bodies
* ============================================================ */
/* Skip a { ... } function body */
static void skip_fn_body(spl_comp_t *ctx) {
int depth = 1;
while (depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE)
depth++;
else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0)
break;
} else if (tt == TOK_EOF)
break;
advance(ctx);
}
if (peek(ctx)->type == TOK_R_BRACE)
advance(ctx);
}
/* Pre-register a type name (and nested type names), skip the body */
static void pre_register_type_decl(spl_comp_t *ctx) {
advance(ctx); /* type */
spl_tok_t *name_tok = advance(ctx);
char tname[256];
spl_tok_copy_name(name_tok, tname, sizeof(tname));
skip_nl(ctx);
if (!expect(ctx, TOK_ASSIGN))
return;
skip_nl(ctx);
int parent_type_idx = ctx->tctx.current_type_idx;
int ti = -1;
if (peek(ctx)->type == KW_STRUCT) {
advance(ctx);
ti = spl_type_struct(&ctx->tctx, tname);
} else if (peek(ctx)->type == KW_ENUM) {
advance(ctx);
ti = spl_type_enum(&ctx->tctx, tname);
} else if (peek(ctx)->type == KW_UNION) {
advance(ctx);
ti = spl_type_union(&ctx->tctx, tname);
}
if (ti >= 0) {
if (parent_type_idx >= 0)
spl_type_add_nested(&ctx->tctx, parent_type_idx, tname, ti);
/* Register nested type names inside the body */
if (peek(ctx)->type == TOK_L_BRACE) {
int saved_current = ctx->tctx.current_type_idx;
ctx->tctx.current_type_idx = ti;
int depth = 1;
advance(ctx); /* { */
while (depth > 0 && ctx->tok_idx < vec_size(ctx->toks)) {
spl_tok_type_t tt = peek(ctx)->type;
if (tt == TOK_L_BRACE) {
depth++;
advance(ctx);
} else if (tt == TOK_R_BRACE) {
depth--;
if (depth == 0)
break;
advance(ctx);
} else if (tt == KW_TYPE && depth == 1) {
pre_register_type_decl(ctx);
} else if (tt == TOK_EOF) {
break;
} else {
advance(ctx);
}
}
if (peek(ctx)->type == TOK_R_BRACE)
advance(ctx);
ctx->tctx.current_type_idx = saved_current;
}
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_SEMICOLON)
advance(ctx);
}
/* Pre-register a function name and signature, skip the body */
static void pre_register_fn_decl(spl_comp_t *ctx, int is_extern) {
advance(ctx);
skip_nl(ctx);
spl_tok_t *fname_tok = advance(ctx);
char fn_name[256];
spl_tok_copy_name(fname_tok, fn_name, sizeof(fn_name));
skip_nl(ctx);
if (!expect(ctx, TOK_L_PAREN))
return;
char pnames[MAX_PARAMS][256];
int ptypes[MAX_PARAMS];
int nparams = parse_params_decl(ctx, pnames, ptypes);
skip_nl(ctx);
int ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
if (peek(ctx)->type != TOK_SEMICOLON && peek(ctx)->type != TOK_L_BRACE) {
ret_type_idx = spl_type_parse(&ctx->tctx, ctx);
if (ret_type_idx < 0)
ret_type_idx = spl_type_basic(&ctx->tctx, SPL_VOID);
skip_nl(ctx);
}
if (is_extern) {
spl_declare_func(ctx, fn_name, ret_type_idx, nparams, 1, 0);
spl_ensure_native(ctx, fn_name);
if (peek(ctx)->type == TOK_SEMICOLON)
advance(ctx);
return;
}
if (peek(ctx)->type == TOK_SEMICOLON) {
advance(ctx);
return;
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_L_BRACE) {
skip_fn_body(ctx);
}
skip_nl(ctx);
if (peek(ctx)->type == TOK_SEMICOLON)
advance(ctx);
}
/* ============================================================
* Parse top-level program
* ============================================================ */
void spl_parse_prog(spl_comp_t *ctx) {
/* Pass 0: Pre-register all type names, function signatures, and variables */
{
usize saved = ctx->tok_idx;
while (!ctx->has_error && peek(ctx)->type != TOK_EOF) {
skip_nl(ctx);
if (peek(ctx)->type == TOK_EOF)
break;
switch (peek(ctx)->type) {
case KW_TYPE:
pre_register_type_decl(ctx);
break;
case KW_FN:
pre_register_fn_decl(ctx, 0);
break;
case KW_PUB: {
advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == KW_FN)
pre_register_fn_decl(ctx, 0);
else if (peek(ctx)->type == KW_TYPE)
pre_register_type_decl(ctx);
break;
}
case TOK_AT:
case TOK_SHARP: {
int tt = peek(ctx)->type;
advance(ctx);
skip_nl(ctx);
if (tt == TOK_AT) {
if (peek(ctx)->type == KW_EXTERN) {
advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == TOK_L_PAREN) {
advance(ctx);
skip_nl(ctx);
advance(ctx);
skip_nl(ctx);
if (peek(ctx)->type == TOK_R_PAREN)
advance(ctx);
}
}
} else {
if (peek(ctx)->type == TOK_L_BRACKET) {
advance(ctx);
while (peek(ctx)->type != TOK_R_BRACKET && peek(ctx)->type != TOK_EOF)
advance(ctx);
if (peek(ctx)->type == TOK_R_BRACKET)
advance(ctx);
}
}
skip_nl(ctx);
if (peek(ctx)->type == KW_FN)
pre_register_fn_decl(ctx, 1);
break;
}
default:
/* Skip unrecognized tokens (stmts, etc.) */
advance(ctx);
break;
}
}
ctx->tok_idx = saved;
}
/* Pass 1: Fill all bodies */
while (!ctx->has_error && peek(ctx)->type != TOK_EOF) {
skip_nl(ctx);
if (peek(ctx)->type == TOK_EOF)
break;
switch (peek(ctx)->type) {
case KW_FN:
parse_fn_decl(ctx, 0, 0);
break;
case KW_TYPE:
parse_type_decl(ctx);
break;
case KW_PUB: {
advance(ctx); /* skip pub */
skip_nl(ctx);
if (peek(ctx)->type == KW_FN)
parse_fn_decl(ctx, 0, 1);
else if (peek(ctx)->type == KW_TYPE)
parse_type_decl(ctx);
break;
}
case TOK_AT:
case TOK_SHARP: {
int tt = peek(ctx)->type;
advance(ctx); /* @ or # */
skip_nl(ctx);
if (tt == TOK_AT) {
if (peek(ctx)->type == KW_EXTERN) {
advance(ctx); /* extern */
skip_nl(ctx);
if (peek(ctx)->type == TOK_L_PAREN) {
advance(ctx); /* ( */
skip_nl(ctx);
advance(ctx); /* target name (e.g. "vm") */
skip_nl(ctx);
if (peek(ctx)->type == TOK_R_PAREN)
advance(ctx);
}
}
} else {
if (peek(ctx)->type == TOK_L_BRACKET) {
advance(ctx);
while (peek(ctx)->type != TOK_R_BRACKET && peek(ctx)->type != TOK_EOF)
advance(ctx);
if (peek(ctx)->type == TOK_R_BRACKET)
advance(ctx);
}
}
skip_nl(ctx);
if (peek(ctx)->type == KW_FN)
parse_fn_decl(ctx, 1, 0);
break;
}
default: {
usize prev = ctx->tok_idx;
spl_parse_stmt(ctx);
if (ctx->tok_idx == prev)
advance(ctx);
break;
}
}
}
/* Recompute all type layouts now that forward references are resolved */
for (int i = 0; i < (int)vec_size(ctx->tctx.types); i++) {
spl_type_compute_layout(&ctx->tctx, i);
}
}

File diff suppressed because it is too large Load Diff

122
stage1/spl_tok.h Normal file
View File

@@ -0,0 +1,122 @@
/* spl_tok.h — Token type definitions (extracted from spl_lexer.h) */
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
#include "../stage0/include/utils.h"
/* clang-format off */
#define KEYWORD_TABLE \
X(as , KW_AS , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
X(match , KW_MATCH , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(struct , KW_STRUCT , SPL_V0) \
X(true , KW_TRUE , SPL_V0) \
X(type , KW_TYPE , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
X(var , KW_VAR , SPL_V0) \
X(void , KW_VOID , SPL_V0) \
X(while , KW_WHILE , SPL_V0) \
X(_ , KW_ANY , SPL_V0) \
// KEYWORD_TABLE
#define TOKEN_TABLE \
X(unknown , TOK_UNKNOWN , SPL_V0 ) \
X(EOF , TOK_EOF , SPL_V0 ) \
X(blank , TOK_BLANK , SPL_V0 ) \
X(endline , TOK_ENDLINE , SPL_V0 ) \
X("#" , TOK_SHARP , SPL_V0 ) \
X("@" , TOK_AT , SPL_V0 ) \
X("==" , TOK_EQ , SPL_V0 ) \
X("=" , TOK_ASSIGN , SPL_V0 ) \
X("+=" , TOK_ASSIGN_ADD , SPL_V0 ) \
X("+" , TOK_ADD , SPL_V0 ) \
X("-=" , TOK_ASSIGN_SUB , SPL_V0 ) \
X("->" , TOK_RIGHT_ARRAY , SPL_V0 ) \
X("<-" , TOK_LEFT_ARRAY , SPL_V0 ) \
X("-" , TOK_SUB , SPL_V0 ) \
X("*=" , TOK_ASSIGN_MUL , SPL_V0 ) \
X("*" , TOK_MUL , SPL_V0 ) \
X("/=" , TOK_ASSIGN_DIV , SPL_V0 ) \
X("/" , TOK_DIV , SPL_V0 ) \
X("//" , TOK_LINE_COMMENT , SPL_V0 ) \
X("/* */" , TOK_BLOCK_COMMENT , SPL_V0 ) \
X("%=" , TOK_ASSIGN_MOD , SPL_V0 ) \
X("%" , TOK_MOD , SPL_V0 ) \
X("&&" , TOK_AND_AND , SPL_V0 ) \
X("&=" , TOK_ASSIGN_AND , SPL_V0 ) \
X("&" , TOK_AND , SPL_V0 ) \
X("||" , TOK_OR_OR , SPL_V0 ) \
X("|=" , TOK_ASSIGN_OR , SPL_V0 ) \
X("|" , TOK_OR , SPL_V0 ) \
X("^=" , TOK_ASSIGN_XOR , SPL_V0 ) \
X("^" , TOK_XOR , SPL_V0 ) \
X("<<=" , TOK_ASSIGN_L_SH , SPL_V0 ) \
X("<<" , TOK_L_SH , SPL_V0 ) \
X("<=" , TOK_LE , SPL_V0 ) \
X("<" , TOK_LT , SPL_V0 ) \
X(">>=" , TOK_ASSIGN_R_SH , SPL_V0 ) \
X(">>" , TOK_R_SH , SPL_V0 ) \
X(">=" , TOK_GE , SPL_V0 ) \
X(">" , TOK_GT , SPL_V0 ) \
X("!" , TOK_NOT , SPL_V0 ) \
X("!=" , TOK_NEQ , SPL_V0 ) \
X("~" , TOK_BIT_NOT , SPL_V0 ) \
X("[" , TOK_L_BRACKET , SPL_V0 ) \
X("]" , TOK_R_BRACKET , SPL_V0 ) \
X("(" , TOK_L_PAREN , SPL_V0 ) \
X(")" , TOK_R_PAREN , SPL_V0 ) \
X("{" , TOK_L_BRACE , SPL_V0 ) \
X("}" , TOK_R_BRACE , SPL_V0 ) \
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("=>" , TOK_FAT_ARROW , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
X(char , TOK_CHAR_LITERAL , SPL_V0 ) \
X(string , TOK_STRING_LITERAL , SPL_V0 ) \
// TOKEN_TABLE
/* clang-format on */
typedef enum {
#define X(name, enum_name, dummy) enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) enum_name,
TOKEN_TABLE
#undef X
} spl_tok_type_t;
typedef struct {
spl_tok_type_t type;
const char *lexeme;
usize len;
const char *fname;
usize offset;
usize line;
usize col;
} spl_tok_t;
typedef VEC(spl_tok_t) spl_tok_vec_t;
#endif /* __SPL_TOK_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,213 +0,0 @@
#ifndef __SPL_TYPE_H__
#define __SPL_TYPE_H__
#include "../stage0/spl_ir.h"
#include "spl_lexer.h"
/* ============================================================
* Type kinds
* ============================================================ */
typedef enum {
TYPE_VOID,
TYPE_BASIC,
TYPE_PTR,
TYPE_ARRAY,
TYPE_SLICE,
TYPE_STRUCT,
TYPE_UNION,
TYPE_ENUM,
TYPE_NAME,
TYPE_FN,
TYPE_COUNT,
} spl_type_kind_t;
#define ENUM_TAG_SIZE 4 /* discriminator tag byte size */
/* ============================================================
* Item kinds — unified member storage
* ============================================================ */
typedef enum {
ITEM_FIELD, /* aggregate_field : struct/union field */
ITEM_VARIANT, /* enum_field : enum variant */
ITEM_METHOD, /* method : type method */
ITEM_NESTED_TYPE, /* nested_type : child type decl */
ITEM_VAR, /* aggregate_field : type-level var */
} spl_type_item_kind_t;
/* ============================================================
* Type item — one member/variant/method/nested-type
* ============================================================ */
typedef struct {
const char *name;
spl_type_item_kind_t item_kind;
union {
struct {
int type_idx; /* field type */
usize offset; /* byte offset (for array: array_len) */
} aggregate_field;
struct {
int type_idx; /* data type, -1 if none */
isize value; /* discriminator value */
} enum_field;
struct {
int func_idx; /* index in spl_comp_t.funcs */
} method;
struct {
int type_idx; /* child type index */
} nested_type;
};
} spl_type_item_t;
typedef VEC(spl_type_item_t) spl_type_item_vec_t;
/* ============================================================
* Type info — one type definition
*
* PTR : items[0].aggregate_field.type_idx = elem
* ARRAY : items[0].aggregate_field.type_idx = elem,
* items[0].aggregate_field.offset = len
* SLICE : same as PTR
* STRUCT : items = ITEM_FIELD for each field
* UNION : items = ITEM_FIELD for each field
* ENUM : items = ITEM_VARIANT for each variant
* NAME : items[0].aggregate_field.type_idx = alias target
* ============================================================ */
typedef struct spl_type_info {
char *name;
spl_type_kind_t kind;
spl_type_t basic_type; /* for TYPE_BASIC */
spl_type_item_vec_t items;
usize byte_size; /* total byte size (cached) */
usize slot_count; /* stack slot count (cached) */
int resolved; /* layout computed */
int parent_type_idx; /* enclosing type, -1 for root */
} spl_type_info_t;
typedef VEC(spl_type_info_t) spl_type_info_vec_t;
/* ============================================================
* Type context — type arena + namespace
*
* types[0] = root (compilation unit type)
* Types form a tree via parent_type_idx on each type info.
* current_type_idx tracks the innermost type being parsed.
* ============================================================ */
typedef struct {
spl_type_info_vec_t types;
MAP(const char *, int) type_map; /* name → type_idx 加速查找 */
int root_type_idx; /* 编译单元自身 = 0 */
int current_type_idx; /* 当前作用域类型 */
int basic_cache[SPL_TYPE_COUNT]; /* memoized basic-type → type_idx */
} spl_type_ctx_t;
/* ============================================================
* Lifecycle
* ============================================================ */
void spl_type_ctx_init(spl_type_ctx_t *tctx);
void spl_type_ctx_drop(spl_type_ctx_t *tctx);
/* ============================================================
* Constructors — all return type_idx (index into tctx->types)
* ============================================================ */
int spl_type_basic(spl_type_ctx_t *tctx, spl_type_t bt);
int spl_type_ptr(spl_type_ctx_t *tctx, int elem_type_idx);
int spl_type_array(spl_type_ctx_t *tctx, int elem_type_idx, usize len);
int spl_type_slice(spl_type_ctx_t *tctx, int elem_type_idx);
int spl_type_struct(spl_type_ctx_t *tctx, const char *name);
int spl_type_union(spl_type_ctx_t *tctx, const char *name);
int spl_type_enum(spl_type_ctx_t *tctx, const char *name);
int spl_type_alias(spl_type_ctx_t *tctx, const char *name, int target_type_idx);
int spl_type_fn(spl_type_ctx_t *tctx, int params_type_idx, int ret_type_idx);
/* ============================================================
* Item management — add members to aggregate types
* ============================================================ */
void spl_type_add_field(spl_type_ctx_t *tctx, int type_idx, const char *name, int field_type_idx);
void spl_type_add_var(spl_type_ctx_t *tctx, int type_idx, const char *name, int var_type_idx);
void spl_type_add_variant(spl_type_ctx_t *tctx, int type_idx, const char *name, int data_type_idx);
void spl_type_add_method(spl_type_ctx_t *tctx, int type_idx, const char *name, int func_idx);
void spl_type_add_nested(spl_type_ctx_t *tctx, int parent_idx, const char *name,
int child_type_idx);
/* ============================================================
* Layout — compute byte_size / slot_count, set resolved
* ============================================================ */
void spl_type_compute_layout(spl_type_ctx_t *tctx, int type_idx);
/* ============================================================
* Accessors — get info from type_idx
* ============================================================ */
spl_type_kind_t spl_type_kind(spl_type_ctx_t *tctx, int type_idx);
spl_type_t spl_type_basic_type(spl_type_ctx_t *tctx, int type_idx);
const char *spl_type_name(spl_type_ctx_t *tctx, int type_idx);
usize spl_type_size(spl_type_ctx_t *tctx, int type_idx);
usize spl_type_slot_count(spl_type_ctx_t *tctx, int type_idx);
usize spl_type_elem_stride(spl_type_ctx_t *tctx, int elem_type_idx);
/* Element type for PTR / ARRAY / SLICE / NAME (reads items[0]) */
int spl_type_elem_type(spl_type_ctx_t *tctx, int type_idx);
usize spl_type_array_len(spl_type_ctx_t *tctx, int type_idx);
/* Scalar: fits in one slot, supports ==/!= directly */
int spl_type_is_scalar(spl_type_ctx_t *tctx, int type_idx);
/* Integer type check */
int spl_type_is_integer(spl_type_t bt);
/* True for types that support inline literal {} syntax */
int spl_type_has_inline_literal(spl_type_ctx_t *tctx, int type_idx);
/* True for multi-slot type — alias for needs_multi_slot for semantic clarity */
int spl_type_is_aggregate(spl_type_ctx_t *tctx, int type_idx);
/* Multi-slot: aggregate type needing >1 stack slots */
int spl_type_needs_multi_slot(spl_type_ctx_t *tctx, int type_idx);
/* Follow alias chain to underlying type */
int spl_type_resolve_underlying(spl_type_ctx_t *tctx, int type_idx);
/* SPL_IR opcode type tag for LOAD/STORE */
spl_type_t spl_type_emit_type(spl_type_ctx_t *tctx, int type_idx);
/* Debug string */
const char *spl_type_str(spl_type_ctx_t *tctx, int type_idx);
/* ============================================================
* Item iteration — filter by item_kind
* ============================================================ */
int spl_type_item_count(spl_type_ctx_t *tctx, int type_idx, spl_type_item_kind_t kind);
spl_type_item_t *spl_type_item_at(spl_type_ctx_t *tctx, int type_idx, int item_index);
/* Returns pointer to first item of given kind, with *count set */
spl_type_item_t *spl_type_first_of_kind(spl_type_ctx_t *tctx, int type_idx,
spl_type_item_kind_t kind, int *count);
/* Get raw items vec for direct iteration (avoids double-lookup) */
spl_type_item_vec_t *spl_type_items(spl_type_ctx_t *tctx, int type_idx);
/* ============================================================
* Type resolution — name → type_idx
* ============================================================ */
/* Walk current → parent chain, then type_map */
int spl_type_resolve(spl_type_ctx_t *tctx, const char *name);
/* Resolve within a specific parent type's ITEM_NESTED_TYPE items */
int spl_type_resolve_in(spl_type_ctx_t *tctx, int parent_idx, const char *name);
/* ============================================================
* Forward declaration for spl_parse_type
* ============================================================ */
struct spl_comp;
int spl_type_parse(spl_type_ctx_t *tctx, struct spl_comp *ctx);
#endif /* __SPL_TYPE_H__ */

View File

@@ -1,13 +1,4 @@
/* splc0.c — Stage 1 SPL compiler (bootstrap)
* Usage:
* splc0 <input.spl> <output.sir> — compile
* splc0 --dump-tokens <input.spl> — dump tokens
* splc0 --help — help
*/
#include "../stage0/spl_ir.h"
#include "spl_comp.h"
#include "spl_lex_util.h"
/* splc0.c — SPL compiler CLI */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -33,75 +24,19 @@ static char *read_file(const char *path, long *out_len) {
return buf;
}
static int cmd_dump_tokens(int argc, char **argv) {
if (argc < 1) {
fprintf(stderr, "Usage: splc0 --dump-tokens <file.spl>\n");
return 1;
}
long len;
char *src = read_file(argv[0], &len);
if (!src)
return 1;
spl_tok_vec_t toks = spl_lex(src, argv[0]);
spl_tok_vec_dump(&toks);
spl_tok_vec_drop(&toks);
free(src);
return 0;
}
static int cmd_compile(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "Usage: splc0 <input.spl> <output.sir>\n");
return 1;
}
const char *inpath = argv[0];
const char *outpath = argv[1];
long len;
char *src = read_file(inpath, &len);
if (!src)
return 1;
spl_comp_t ctx;
spl_comp_init(&ctx);
int ret = 0;
if (spl_compile(&ctx, src, inpath) != 0) {
fprintf(stderr, "compilation failed: %s\n", ctx.error_msg);
ret = 1;
goto cleanup;
}
if (spl_prog_store_to_file(outpath, &ctx.prog) != 0) {
fprintf(stderr, "failed to write '%s'\n", outpath);
ret = 1;
goto cleanup;
}
printf("compiled %s -> %s\n", inpath, outpath);
cleanup:
spl_comp_drop(&ctx);
free(src);
return ret;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "Usage: splc0 [--dump-tokens|--help] <input.spl> [output.sir]\n");
fprintf(stderr, "Usage: splc0 [--dump <flags>] <in> [out]\n");
return 1;
}
if (strcmp(argv[1], "--dump-tokens") == 0) {
return cmd_dump_tokens(argc - 2, argv + 2);
}
if (strcmp(argv[1], "--dump") == 0)
// return cmd_dump(argc - 2, argv + 2);
return 0;
if (strcmp(argv[1], "--help") == 0) {
printf("SPL Compiler (stage1 bootstrap)\n");
printf(" splc0 <input.spl> <output.sir> - compile\n");
printf(" splc0 --dump-tokens <file.spl> - dump token stream\n");
printf("splc0 <in> <out> compile\n");
printf("splc0 --dump <f> <file> dump: tokens,cst,ast,ir,mcode,all\n");
return 0;
}
return cmd_compile(argc - 1, argv + 1);
// return cmd_compile(argc - 1, argv + 1);
return 0;
}

View File

@@ -1,9 +1,8 @@
/* spc_vm.c VM launcher for stage 1 */
/* spc_vm.c 鈥?VM launcher for stage 1 */
#include "../stage0/spl_ir.h"
#include "../stage0/spl_mcode.h"
#include "../stage0/spl_syscall.h"
#include "../stage0/spl_vm.h"
#include "spl_comp.h"
#include <stdio.h>
#include <string.h>
@@ -11,28 +10,31 @@
int main(int argc, const char **argv) {
int argi = 1;
if (argi >= argc) {
fprintf(stderr, "Usage: spc_vm <file.sir> [entry] [--trace]\n");
return 1;
}
const char *path = argv[argi++];
/* Parse flags: --entry <name>, --trace */
/* Parse flags: --entry <name>, --trace, -d */
const char *entry = "main";
int trace = 0;
int debug_addr = 0;
for (int i = argi; i < argc; i += 1) {
if (strcmp(argv[i], "--entry") == 0 && i + 1 < argc) {
entry = argv[++i];
} else if (strcmp(argv[i], "--trace") == 0) {
trace = 1;
} else if (strcmp(argv[i], "-d") == 0) {
debug_addr = 1;
} else if (argv[i][0] != '-') {
argi = i;
break;
}
}
/* Adjust argv so the SPL program sees path as argv[0] and
* remaining positional args as argv[1..], just like a native exe. */
int spl_argc = argc - (argi - 1);
if (argi >= argc) {
fprintf(stderr, "Usage: spc_vm [-d] [--trace] <file.sir> [args...]\n");
return 1;
}
const char *path = argv[argi++];
const char **spl_argv = argv + (argi - 1);
int spl_argc = (int)(argc - (argi - 1));
spl_prog_t prog;
if (spl_prog_load_from_file(path, &prog) != 0) {
@@ -41,7 +43,6 @@ int main(int argc, const char **argv) {
}
spl_syscall_register(&prog);
spl_comp_register(&prog);
spl_vm_t vm;
spl_vm_init(&vm);
@@ -56,6 +57,7 @@ int main(int argc, const char **argv) {
return 1;
}
spl_vm_set_trace(&vm, trace);
if (debug_addr) spl_vm_set_debug(&vm, 1);
int ret = spl_vm_run_until(&vm, 0);
spl_vm_drop(&vm);

View File

@@ -24,8 +24,8 @@ type Expr = enum {
fn eval(self: *Expr) i32 {
match self {
.Int(val) => ret val,
.Add(left, right) => ret eval(left) + eval(right),
.Int[val] => ret val,
.Add[.left = left, .right = right] => ret eval(left) + eval(right),
}
ret 0;
}

View File

@@ -79,7 +79,7 @@ fn test_optional_match() i32 {
var o: Optional = Optional { .Some = 42 };
match o {
.Some(val) => {
.Some[val] => {
if val != 42 { ret 1; }
},
.None => {
@@ -90,7 +90,7 @@ fn test_optional_match() i32 {
o = Optional { .None };
var is_none: i32 = 0;
match o {
.Some(val) => {},
.Some[val] => {},
.None => { is_none = 1; }
}
if is_none != 1 { ret 3; }
@@ -98,7 +98,7 @@ fn test_optional_match() i32 {
/* 多次提取不同值 */
o = Optional { .Some = 99 };
match o {
.Some(val) => {
.Some[val] => {
if val != 99 { ret 4; }
},
.None => { ret 5; }
@@ -115,10 +115,10 @@ fn test_shape_match() i32 {
/* Circle: 单数据 */
var s: Shape = Shape { .Circle = 10 };
match s {
.Circle(r) => {
.Circle[r] => {
if r != 10 { ret 1; }
},
.Rect(w, h) => {
.Rect[.x = w, .y = h] => {
ret 2;
}
}
@@ -126,8 +126,8 @@ fn test_shape_match() i32 {
/* Rect: 结构体数据,绑定为 (x, y) 对应 Point 的字段 */
s = Shape { .Rect = Point { .x = 3, .y = 4 } };
match s {
.Circle(r) => { ret 3; },
.Rect(w, h) => {
.Circle[r] => { ret 3; },
.Rect[.x = w, .y = h] => {
if w != 3 { ret 4; }
if h != 4 { ret 5; }
}
@@ -143,16 +143,16 @@ fn test_shape_match() i32 {
fn test_action_result_match() i32 {
var r: ActionResult = ActionResult { .Success = 200 };
match r {
.Success(code) => {
.Success[code] => {
if code != 200 { ret 1; }
},
.NotFound => {
ret 2;
},
.Timeout(ms) => {
.Timeout[ms] => {
ret 3;
},
.Error(msg) => {
.Error[msg] => {
ret 4;
}
}
@@ -160,21 +160,21 @@ fn test_action_result_match() i32 {
r = ActionResult { .NotFound };
var found: i32 = 1;
match r {
.Success(code) => { found = 0; },
.Success[code] => { found = 0; },
.NotFound => { },
.Timeout(ms) => { found = 0; },
.Error(msg) => { found = 0; }
.Timeout[ms] => { found = 0; },
.Error[msg] => { found = 0; }
}
if found != 1 { ret 5; }
r = ActionResult { .Timeout = 5000 };
match r {
.Success(code) => { ret 6; },
.Success[code] => { ret 6; },
.NotFound => { ret 7; },
.Timeout(ms) => {
.Timeout[ms] => {
if ms != 5000 { ret 8; }
},
.Error(msg) => { ret 9; }
.Error[msg] => { ret 9; }
}
ret 0;
@@ -252,7 +252,7 @@ fn test_match_in_loop() i32 {
}
match o {
.Some(val) => {
.Some[val] => {
sum = sum + val;
},
.None => { }

View File

@@ -253,13 +253,13 @@ fn test_enum_complex() i32 {
/* Verify active variant */
match s {
.Active(val) => {
.Active[val] => {
if val != 42 { ret 1; }
},
.Inactive => {
ret 2;
},
.Pending(px, py) => {
.Pending[.x = px, .y = py] => {
ret 3;
}
}
@@ -268,18 +268,18 @@ fn test_enum_complex() i32 {
var s2: Status = Status { .Inactive };
var is_inactive: i32 = 0;
match s2 {
.Active(val) => {},
.Active[val] => {},
.Inactive => { is_inactive = 1; },
.Pending(px, py) => {}
.Pending[.x = px, .y = py] => {}
}
if is_inactive != 1 { ret 4; }
/* Test Pending variant with struct data */
var s3: Status = Status { .Pending = Point { .x = 7, .y = 8 } };
match s3 {
.Active(val) => { ret 5; },
.Active[val] => { ret 5; },
.Inactive => { ret 6; },
.Pending(px, py) => {
.Pending[.x = px, .y = py] => {
if px != 7 { ret 7; }
if py != 8 { ret 8; }
}