declare为必须写的

This commit is contained in:
Luke 2025-04-25 09:40:35 +08:00
parent 95ac9d4177
commit 9662e722a4
2 changed files with 27 additions and 8 deletions

View File

@ -146,11 +146,21 @@ public class FunctionParser implements TopLevelParser {
/** /**
* 解析参数定义区块 * 解析参数定义区块
* <p>
* 语法格式示例
* <pre>
* parameter:
* declare param1: int
* declare param2: string
* </pre>
* 每一行参数定义都必须以 <code>declare</code> 开头
* 方法将跳过空行并在遇到下一个语句区块 return_typebodyend时终止
* *
* @param ts Token * @param ts Token 用于逐个读取语法标记
* @return 参数节点列表 * @return 参数节点列表每个 {@link ParameterNode} 包含参数名和类型
*/ */
private List<ParameterNode> parseParameters(TokenStream ts) { private List<ParameterNode> parseParameters(TokenStream ts) {
// 开始匹配 "parameter:"
ts.expect("parameter"); ts.expect("parameter");
ts.expect(":"); ts.expect(":");
ts.expectType(TokenType.NEWLINE); ts.expectType(TokenType.NEWLINE);
@ -158,33 +168,42 @@ public class FunctionParser implements TopLevelParser {
List<ParameterNode> params = new ArrayList<>(); List<ParameterNode> params = new ArrayList<>();
while (true) { while (true) {
// 跳过空行
if (ts.peek().getType() == TokenType.NEWLINE) { if (ts.peek().getType() == TokenType.NEWLINE) {
ts.next(); // 跳过空行 ts.next();
continue; continue;
} }
String lexeme = ts.peek().getLexeme(); String lexeme = ts.peek().getLexeme();
// 如果是下一个区块的起始关键字则退出当前 parameter 区块 // 遇到新语句区块的开始结束当前参数解析块
if ("return_type".equals(lexeme) || "body".equals(lexeme) || "end".equals(lexeme)) { if ("return_type".equals(lexeme) || "body".equals(lexeme) || "end".equals(lexeme)) {
break; break;
} }
if ("declare".equals(lexeme)) { // 参数定义必须以 "declare" 开头
ts.next(); // 可选 "declare" ts.expect("declare");
}
// 获取参数名称
String paramName = ts.expectType(TokenType.IDENTIFIER).getLexeme(); String paramName = ts.expectType(TokenType.IDENTIFIER).getLexeme();
// 冒号分隔符
ts.expect(":"); ts.expect(":");
// 参数类型
String paramType = ts.expectType(TokenType.TYPE).getLexeme(); String paramType = ts.expectType(TokenType.TYPE).getLexeme();
// 每行结束必须是 NEWLINE
ts.expectType(TokenType.NEWLINE); ts.expectType(TokenType.NEWLINE);
// 加入参数列表
params.add(new ParameterNode(paramName, paramType)); params.add(new ParameterNode(paramName, paramType));
} }
return params; return params;
} }
/** /**
* 解析返回类型区块 * 解析返回类型区块
* *

2
test
View File

@ -51,7 +51,7 @@ module: MainModule
function: main function: main
parameter: parameter:
args: string declare args: string
return_type: void return_type: void
body: body:
loop: loop: