首页 > 解决方案 > 在执行 JFlex 中的操作之前检查条件是否满足

问题描述

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

标签: flex-lexerlexerjflex

解决方案


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

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


推荐阅读