feat: NewlineTokenScanner 重构为状态机

This commit is contained in:
Luke 2025-07-01 17:10:11 +08:00
parent 51f5ba9884
commit dbc3ea0a33

View File

@ -7,10 +7,19 @@ import org.jcnc.snow.compiler.lexer.token.TokenType;
/**
* 换行符扫描器将源代码中的换行符\n识别为 {@code NEWLINE} 类型的 Token
* <p>
* 通常用于记录行的分界辅助语法分析阶段进行行敏感的判断或保持结构清晰
* 用于记录行的分界辅助语法分析阶段进行行敏感的判断或保持结构清晰
*/
public class NewlineTokenScanner extends AbstractTokenScanner {
// 定义状态枚举
private enum State {
INITIAL,
NEWLINE
}
// 当前状态
private State currentState = State.INITIAL;
/**
* 判断是否可以处理当前位置的字符
* <p>当字符为换行符\n时返回 true</p>
@ -21,7 +30,8 @@ public class NewlineTokenScanner extends AbstractTokenScanner {
*/
@Override
public boolean canHandle(char c, LexerContext ctx) {
return c == '\n';
// 只有当处于 INITIAL 状态并且遇到换行符时才可以处理
return currentState == State.INITIAL && c == '\n';
}
/**
@ -35,7 +45,16 @@ public class NewlineTokenScanner extends AbstractTokenScanner {
*/
@Override
protected Token scanToken(LexerContext ctx, int line, int col) {
// 状态转换为 NEWLINE
currentState = State.NEWLINE;
// 执行换行符扫描生成 token
ctx.advance();
return new Token(TokenType.NEWLINE, "\n", line, col);
Token newlineToken = new Token(TokenType.NEWLINE, "\n", line, col);
// 扫描完成后恢复状态为 INITIAL
currentState = State.INITIAL;
return newlineToken;
}
}
}