feat: 增加常量声明支持并优化声明语句解析
- 增加对常量声明的支持,通过匹配 "const" 关键字 -优化代码结构,使用 var tokens变量引用词法 token 流 - 简化代码逻辑,提高可读性和可维护性
This commit is contained in:
parent
d0c34ce1c2
commit
da7d7bbcaa
@ -34,45 +34,51 @@ public class DeclarationStatementParser implements StatementParser {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public DeclarationNode parse(ParserContext ctx) {
|
public DeclarationNode parse(ParserContext ctx) {
|
||||||
|
// 便捷引用词法 token 流
|
||||||
|
var tokens = ctx.getTokens();
|
||||||
|
|
||||||
// 获取当前 token 的行号、列号和文件名
|
// 获取当前 token 的行号、列号和文件名
|
||||||
int line = ctx.getTokens().peek().getLine();
|
int line = tokens.peek().getLine();
|
||||||
int column = ctx.getTokens().peek().getCol();
|
int column = tokens.peek().getCol();
|
||||||
String file = ctx.getSourceName();
|
String file = ctx.getSourceName();
|
||||||
|
|
||||||
// 声明语句必须以 "declare" 开头
|
// 声明语句必须以 "declare" 开头
|
||||||
ctx.getTokens().expect("declare");
|
tokens.expect("declare");
|
||||||
|
|
||||||
|
// 是否声明为常量
|
||||||
|
boolean isConst = tokens.match("const");
|
||||||
|
|
||||||
// 获取变量名称(标识符)
|
// 获取变量名称(标识符)
|
||||||
String name = ctx.getTokens()
|
String name = tokens
|
||||||
.expectType(TokenType.IDENTIFIER)
|
.expectType(TokenType.IDENTIFIER)
|
||||||
.getLexeme();
|
.getLexeme();
|
||||||
|
|
||||||
// 类型标注的冒号分隔符
|
// 类型标注的冒号分隔符
|
||||||
ctx.getTokens().expect(":");
|
tokens.expect(":");
|
||||||
|
|
||||||
// 获取变量类型(类型标识符)
|
// 获取变量类型(类型标识符)
|
||||||
StringBuilder type = new StringBuilder(
|
StringBuilder type = new StringBuilder(
|
||||||
ctx.getTokens()
|
tokens
|
||||||
.expectType(TokenType.TYPE)
|
.expectType(TokenType.TYPE)
|
||||||
.getLexeme()
|
.getLexeme()
|
||||||
);
|
);
|
||||||
|
|
||||||
// 消费多维数组类型后缀 "[]"
|
// 消费多维数组类型后缀 "[]"
|
||||||
while (ctx.getTokens().match("[")) {
|
while (tokens.match("[")) {
|
||||||
ctx.getTokens().expectType(TokenType.RBRACKET); // 必须配对
|
tokens.expectType(TokenType.RBRACKET); // 必须配对
|
||||||
type.append("[]"); // 类型名称拼接 [],如 int[][] 等
|
type.append("[]"); // 类型名称拼接 [],如 int[][] 等
|
||||||
}
|
}
|
||||||
|
|
||||||
// 可选初始化表达式(=号右侧)
|
// 可选初始化表达式(=号右侧)
|
||||||
ExpressionNode init = null;
|
ExpressionNode init = null;
|
||||||
if (ctx.getTokens().match("=")) {
|
if (tokens.match("=")) {
|
||||||
init = new PrattExpressionParser().parse(ctx);
|
init = new PrattExpressionParser().parse(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 声明语句必须以换行符结尾
|
// 声明语句必须以换行符结尾
|
||||||
ctx.getTokens().expectType(TokenType.NEWLINE);
|
tokens.expectType(TokenType.NEWLINE);
|
||||||
|
|
||||||
// 返回构建好的声明语法树节点
|
// 返回构建好的声明语法树节点
|
||||||
return new DeclarationNode(name, type.toString(), init, new NodeContext(line, column, file));
|
return new DeclarationNode(name, type.toString(), isConst, init, new NodeContext(line, column, file));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user