From a45f7d8e2fb61f0384fd7d48ee7bf3b85a2bfab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E8=88=AA=E5=AE=87?= <3364451258@qq.com> Date: Fri, 5 Jun 2026 19:38:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=95=B0=E7=BB=84=E6=94=AF=E6=8C=81=20?= =?UTF-8?q?struct=20=E5=85=83=E7=B4=A0=E7=B1=BB=E5=9E=8B=20[Point;=20N]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/sema/sema.c | 11 ++++++++++- test/programs/24_array_struct.l | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 test/programs/24_array_struct.l diff --git a/src/sema/sema.c b/src/sema/sema.c index 2639ce5..43beee9 100644 --- a/src/sema/sema.c +++ b/src/sema/sema.c @@ -719,12 +719,21 @@ static void analyze_node(AstNode* node, Scope* scope, ErrorList* errors, Arena* error_add(errors, "", node->loc.line, node->loc.col, "数组索引必须是 i64 类型, 得到 '%s'", type_name(idx->type.kind)); } - TypeKind elem_kind = sym->type == TYPE_ARRAY ? TYPE_I64 : sym->type; + TypeKind elem_kind = (sym->type == TYPE_ARRAY) ? sym->array_element_type : sym->type; if (val->type.kind != TYPE_ERROR && val->type.kind != elem_kind) { error_add(errors, "", node->loc.line, node->loc.col, "数组元素类型不匹配: 期望 '%s',得到 '%s'", type_name(elem_kind), type_name(val->type.kind)); } + // struct 元素类型时还需检查结构体名是否匹配 + if (val->type.kind != TYPE_ERROR && elem_kind == TYPE_STRUCT + && sym->array_element_struct_name && val->type.struct_name) { + if (strcmp(sym->array_element_struct_name, val->type.struct_name) != 0) { + error_add(errors, "", node->loc.line, node->loc.col, + "数组元素类型不匹配: 期望 '%s',得到 '%s'", + sym->array_element_struct_name, val->type.struct_name); + } + } node->type.kind = TYPE_VOID; break; } diff --git a/test/programs/24_array_struct.l b/test/programs/24_array_struct.l new file mode 100644 index 0000000..39a402c --- /dev/null +++ b/test/programs/24_array_struct.l @@ -0,0 +1,12 @@ +struct Point { x: i64, y: i64 } + +fn main() -> i64 { + let arr: [Point; 2] = arr; + arr[0] = Point { x: 10, y: 20 }; + arr[1] = Point { x: 30, y: 40 }; + print_i64(arr[0].x); + print_i64(arr[0].y); + print_i64(arr[1].x); + print_i64(arr[1].y); + return 0; +}