feat: 支持结构体多个 init 构造函数
- 修改 StructParser 类,支持解析多个 init 构造函数 - 使用列表 inits 替代单个 init 函数节点 - 增加按参数个数去重的逻辑,避免重复定义 init构造函数 - 更新 StructNode 构造方法,接收 inits 列表作为参数
This commit is contained in:
parent
94b4bf94cf
commit
ba436cb91c
@ -65,7 +65,7 @@ public class StructParser implements TopLevelParser {
|
|||||||
|
|
||||||
/* -------- 初始化容器 -------- */
|
/* -------- 初始化容器 -------- */
|
||||||
List<DeclarationNode> fields = new ArrayList<>();
|
List<DeclarationNode> fields = new ArrayList<>();
|
||||||
FunctionNode init = null;
|
List<FunctionNode> inits = new ArrayList<>();
|
||||||
List<FunctionNode> methods = new ArrayList<>();
|
List<FunctionNode> methods = new ArrayList<>();
|
||||||
|
|
||||||
DeclarationStatementParser declParser = new DeclarationStatementParser();
|
DeclarationStatementParser declParser = new DeclarationStatementParser();
|
||||||
@ -104,12 +104,17 @@ public class StructParser implements TopLevelParser {
|
|||||||
|
|
||||||
/* ---------- 构造函数 init ---------- */
|
/* ---------- 构造函数 init ---------- */
|
||||||
case "init" -> {
|
case "init" -> {
|
||||||
if (init != null) {
|
FunctionNode ctor = parseInit(ctx, structName);
|
||||||
|
|
||||||
|
// 按参数个数去重
|
||||||
|
for (FunctionNode ex : inits) {
|
||||||
|
if (ex.parameters().size() == ctor.parameters().size()) {
|
||||||
throw new UnexpectedToken(
|
throw new UnexpectedToken(
|
||||||
"重复定义 init 构造函数",
|
"重复定义 init 构造函数 (参数数量冲突)",
|
||||||
ts.peek().getLine(), ts.peek().getCol());
|
ts.peek().getLine(), ts.peek().getCol());
|
||||||
}
|
}
|
||||||
init = parseInit(ctx, structName);
|
}
|
||||||
|
inits.add(ctor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- 普通方法 function ---------- */
|
/* ---------- 普通方法 function ---------- */
|
||||||
@ -119,8 +124,8 @@ public class StructParser implements TopLevelParser {
|
|||||||
case "end" -> {
|
case "end" -> {
|
||||||
ts.expect("end");
|
ts.expect("end");
|
||||||
ts.expect("struct");
|
ts.expect("struct");
|
||||||
// 返回完整结构体 AST 节点
|
return new StructNode(structName, parentName,
|
||||||
return new StructNode(structName, parentName, fields, init, methods,
|
fields, inits, methods,
|
||||||
new NodeContext(line, col, file));
|
new NodeContext(line, col, file));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user