[英]check if condition is met before executing the action in JFlex
I am writing a lexical analyzer using JFlex.我正在使用 JFlex 编写词法分析器。 When the word
co
is matched, we have to ignore what comes after until the end of the line (because it's a comment).当单词
co
匹配时,我们必须忽略行尾之前的内容(因为它是注释)。 For the moment, I have a boolean variable that changes to true
whenever this word is matched and if an identifier or an operator is matched after co
until the end of the line, I simply ignore it because I have an if
condition in my Identifier
and Operator
token identification.目前,我有一个布尔变量,只要匹配这个词,它就会变为
true
并且如果标识符或运算符在co
之后匹配到行尾,我只是忽略它,因为我的Identifier
有一个if
条件,并且Operator
令牌识别。
I am wondering if there is better way to do this and get rid of this if
statement that appears everywhere?我想知道是否有更好的方法来做到这一点并摆脱这种随处可见的
if
语句?
Here is the code:这是代码:
%% // 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();
}
}
One way to do this is to use states in JFlex.一种方法是在 JFlex 中使用状态。 We say that every time the word
co
is matched, we enter in a state named COMMENT_STATE
and we do nothing until the end of the line.我们说每次匹配单词
co
,我们都会进入一个名为COMMENT_STATE
的状态,并且直到行尾我们什么都不做。 After the end of the line, we exit the COMMENT_STATE
state.行结束后,我们退出
COMMENT_STATE
状态。 So here is the code:所以这里是代码:
%% // 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} {}
With this new approach, the lexer is more simpler and it's also more readable.使用这种新方法,词法分析器更简单,也更易读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.