flex-lexer - 在执行 JFlex 中的操作之前检查条件是否满足
问题描述
我正在使用 JFlex 编写一个词法分析器。当单词co
匹配时,我们必须忽略后面的内容,直到行尾(因为它是注释)。目前,我有一个布尔变量,true
只要匹配这个词,如果标识符或运算符匹配co
到行尾,我就会忽略它,因为我的和令牌标识if
中有一个条件。
我想知道是否有更好的方法来做到这一点并摆脱无处不在的这种说法?Identifier
Operator
if
这是代码:
%% // Options of the scanner
%class Lexer
%unicode
%line
%column
%standalone
%{
private boolean isCommentOpen = false;
private void toggleIsCommentOpen() {
this.isCommentOpen = ! this.isCommentOpen;
}
private boolean getIsCommentOpen() {
return this.isCommentOpen;
}
%}
Operators = [\+\-]
Identifier = [A-Z]*
EndOfLine = \r|\n|\r\n
%%
{Operators} {
if (! getIsBlockCommentOpen() && ! getIsCommentOpen()) {
// Do Code
}
}
{Identifier} {
if (! getIsBlockCommentOpen() && ! getIsCommentOpen()) {
// Do Code
}
}
"co" {
toggleIsCommentOpen();
}
. {}
{EndOfLine} {
if (getIsCommentOpen()) {
toggleIsCommentOpen();
}
}
解决方案
一种方法是在 JFlex 中使用状态。我们说每次co
匹配单词时,我们进入一个名为的状态COMMENT_STATE
,直到行尾我们什么都不做。行结束后,我们退出COMMENT_STATE
状态。所以这里是代码:
%% // Options of the scanner
%class Lexer
%unicode
%line
%column
%standalone
Operators = [\+\-]
Identifier = [A-Z]*
EndOfLine = \r|\n|\r\n
%xstate YYINITIAL, COMMENT_STATE
%%
<YYINITIAL> {
"co" {yybegin(COMMENT_STATE);}
}
<COMMENT_STATE> {
{EndOfLine} {yybegin(YYINITIAL);}
. {}
}
{Operators} {// Do Code}
{Identifier} {// Do Code}
. {}
{EndOfLine} {}
使用这种新方法,词法分析器更简单,也更具可读性。
推荐阅读
- javascript - 在重复的选项卡上自动更新 DOM 通过 chrome 扩展
- c++ - 在析构函数 C++ 中删除指针
- c# - 卷积算法逻辑
- css - 是否可以在 WKWebview 中更新 CSS?
- python - 使用sklearn在python中的时空克里金?
- c# - vs buildtools 容器 'dotnet test' 无法找到 Dotnet Core 测试项目的测试
- symfony - Symfony4 DateTimeType 显示无效日期
- amazon-s3 - 在 EC2 中运行时,Flink 未从 S3 读取文件
- c# - 确保在 UI 线程上创建新表单
- video - 什么是 I 帧,它们会影响视频大小吗?