feat: 实现控制流语句并优化类型解析

- 新增了 ReturnStmt、BreakStmt 和 ContinueStmt 结构,以支持 AST 中的控制流。
- 引入了 TypeInfo 和 TypeContext 以实现更好的类型管理和解析。
- 对分析器进行了增强,能够处理函数定义和返回语句,包括类型检查和错误处理。
- 更新了编译器和解析器以适应新的控制流语句和类型解析逻辑。
- 重构了现有代码以提高清晰度和可维护性,包括对表达式和语句中的类型处理的更改。
- 删除了过时的 String 和 Struct 定义,代之以 StringObject 和 StructObject 以实现更好的对象表示。
This commit is contained in:
2026-02-28 20:42:15 +08:00
parent bb23ddf9fa
commit 1fe9ccf7ea
18 changed files with 642 additions and 137 deletions

View File

@@ -166,6 +166,9 @@ namespace Fig
ParsingIf,
ParsingWhile,
ParsingFnDefStmt,
ParsingReturn,
ParsingBreak,
ParsingContinue,
ParsingNamedTypeExpr,
@@ -305,6 +308,9 @@ namespace Fig
Result<DynArray<Param *>, Error> parseFnParams(); // 由 parseFnDefStmt或lambda调用
Result<FnDefStmt *, Error> parseFnDefStmt(bool); // 由 parseStatement调用, 当前token为 func
Result<ReturnStmt *, Error> parseReturnStmt(); // 由 parseStatement调用, 当前token为 return
// continue break直接由parseStatement一步解析
Result<Stmt *, Error> parseStatement();
public:

View File

@@ -357,7 +357,8 @@ namespace Fig
{
if (!currentToken().isIdentifier())
{
return std::unexpected(makeUnexpectTokenError("fn params", "param name", currentToken()));
return std::unexpected(
makeUnexpectTokenError("fn params", "param name", currentToken()));
}
}
}
@@ -418,13 +419,36 @@ namespace Fig
{
delete returnType;
}
body = *bodyResult;
return std::unexpected(bodyResult.error());
}
body = *bodyResult;
FnDefStmt *fnDef = new FnDefStmt(isPublic, name, params, returnType, body, location);
return fnDef;
}
Result<ReturnStmt *, Error>
Parser::parseReturnStmt() // 由 parseStatement调用, 当前token为 return
{
StateProtector p(this, {State::ParsingReturn});
SourceLocation location = makeSourceLocation(consumeToken()); // consume `return`
auto result = parseExpression();
if (!result)
{
return std::unexpected(result.error());
}
Expr *value = *result;
ReturnStmt *returnStmt = new ReturnStmt(value, location);
if (!match(TokenType::Semicolon))
{
return std::unexpected(makeExpectSemicolonError());
}
return returnStmt;
}
Result<Stmt *, Error> Parser::parseStatement()
{
StateProtector p(this, {State::Standby});
@@ -471,6 +495,33 @@ namespace Fig
return parseFnDefStmt(false);
}
if (currentToken().type == TokenType::Return)
{
return parseReturnStmt();
}
if (match(TokenType::Break))
{
SourceLocation location = makeSourceLocation(prevToken());
if (!match(TokenType::Semicolon))
{
return std::unexpected(makeExpectSemicolonError());
}
BreakStmt *breakStmt = new BreakStmt(location);
return breakStmt;
}
if (match(TokenType::Continue))
{
SourceLocation location = makeSourceLocation(prevToken());
if (!match(TokenType::Semicolon))
{
return std::unexpected(makeExpectSemicolonError());
}
ContinueStmt *continueStmt = new ContinueStmt(location);
return continueStmt;
}
if (isEOF)
{
return nullptr;