【问题标题】:check if condition is met before executing the action in JFlex在执行 JFlex 中的操作之前检查条件是否满足
【发布时间】:2021-12-04 17:44:11
【问题描述】:

我正在使用 JFlex 编写一个词法分析器。当单词co 匹配时,我们必须忽略后面的内容,直到行尾(因为它是注释)。目前,我有一个布尔变量,只要匹配这个词,它就会更改为true,并且如果在co 之后匹配标识符或运算符直到行尾,我只是忽略它,因为我有一个@987654324我的IdentifierOperator 令牌标识中的@ 条件。
我想知道是否有更好的方法来做到这一点并摆脱这个无处不在的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();
                        }
                    }

【问题讨论】:

  • 为什么不将co 中的单个评论匹配到行尾?

标签: flex-lexer lexer jflex


【解决方案1】:

一种方法是在 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} {}

使用这种新方法,词法分析器更简单,也更具可读性。

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 2021-04-25
    • 2022-11-15
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多