feat: 泛型基础设施 — <T>解析 + 类型推断 (单态化 codegen 待补)

This commit is contained in:
2026-06-06 16:17:15 +08:00
parent fa734b8a23
commit 350eeef3c5
9 changed files with 100 additions and 37 deletions
+20 -2
View File
@@ -907,9 +907,22 @@ static AstNode* parse_function(Parser* p, bool is_pub, ErrorInfo* error) {
const Token* fn_tok = advance(p); // fn
const Token* name = expect(p, TOK_IDENT, error, "fn 后应为函数名");
if (!name) return NULL;
// 泛型类型参数: <T, U, ...>
const char* type_params[8]; int tp_count = 0;
if (peek(p)->kind == TOK_LT) {
advance(p); // 跳过 '<'
while (peek(p)->kind != TOK_GT && !error->message) {
if (tp_count >= 8) { error->message = "类型参数过多 (最多8)"; error->filename = p->filename; error->line = peek(p)->line; error->col = peek(p)->col; return NULL; }
const Token* tp = expect(p, TOK_IDENT, error, "类型参数名");
if (!tp) return NULL;
type_params[tp_count++] = arena_strdup_impl(p->arena, tp->start, tp->length);
if (peek(p)->kind == TOK_COMMA) advance(p); else break;
}
if (!expect(p, TOK_GT, error, "缺少 '>'")) return NULL;
}
if (!expect(p, TOK_LPAREN, error, "缺少 '('")) return NULL;
// 参数列表
// 参数列表(泛型参数可标注为类型参数名)
AstNode* params[64]; int pcount = 0;
while (peek(p)->kind != TOK_RPAREN && !error->message) {
if (pcount >= 64) { error->message = "函数参数过多 (最多64)"; error->filename = p->filename; error->line = peek(p)->line; error->col = peek(p)->col; return NULL; }
@@ -941,9 +954,14 @@ static AstNode* parse_function(Parser* p, bool is_pub, ErrorInfo* error) {
AstNode** parr = arena_alloc_impl(p->arena, pcount * sizeof(AstNode*));
memcpy(parr, params, pcount * sizeof(AstNode*));
const char** tparr = NULL;
if (tp_count > 0) {
tparr = arena_alloc_impl(p->arena, tp_count * sizeof(const char*));
memcpy(tparr, type_params, tp_count * sizeof(const char*));
}
return ast_make_function(p->arena,
arena_strdup_impl(p->arena, name->start, name->length),
parr, pcount, ret, ret_struct_name, body, is_pub, tok_loc(fn_tok));
parr, pcount, ret, ret_struct_name, body, is_pub, tparr, tp_count, tok_loc(fn_tok));
}
// === 模块文件加载辅助 ===