2014-03-31 37 views
0

我有只在一行代码不同的两个规则柔性文件:测试电流启动状态柔性

<STATE1>{SAME_REGEX} { 
    same_code(); 
} 

<STATE2>{SAME_REGEX} { 
    same_code(); 
    one_extra_line(); 
} 

有什么办法,维护的简洁和易用性(即使same_code ()部分发生了变化,他们将始终让这部分相同),通过用if语句测试当前状态来合并这两个部分?例如:

<STATE1,STATE2>{SAME_REGEX} { 
    same_code(); 
    if(STATE2){ 
     one_extra_line(); 
    } 
} 

回答

1

你很近。列出< >之间的几个启动状态是有效的。要获得目前的状态,你可以调用yy_top_state()

<STATE1,STATE2>{SAME_REGEX} { 
    same_code(); 
    if(yy_top_state() == STATE2){ 
     one_extra_line(); 
    } 
} 
1

我不认为接受的答案是正确的。

当您调用yy_push_state(new_state)时,您将当前活动状态推入堆栈并使'new_state'成为当前活动状态。同样,调用yy_pop_state()将删除当前处于状态堆栈顶部的状态并使其成为活动状态。 yy_top_state将返回先前保存到堆栈中的值,而不是当前活动状态,我相信这是OP正在查找的值。

查看flex的信息页面的'第10条开始条件'。

这里有一个小的互动柔性程序来说明这个问题

注:

Exmpale ##说明弯曲状态:下面输入的所有三种状态0,1,2通过切换#

%option stack 

%{ 
#include<stdio.h> 
#define TOP_STATE yy_top_state() 

void pop_state(const char *); 
void push_state(const char *, int); 
%} 


%x STATE1 
%x STATE2 

%% 

<STATE1,STATE2>{ 
#[^#\n]+ { if(YY_START == STATE1) 
      push_state(yytext, STATE2); 
      else 
      pop_state(yytext); 
     } 
.  { pop_state(yytext); } 
\n  { pop_state("NEWLINE"); } 
} 

#  { push_state("#", STATE1); } 
. 

%% 

int 
main(int argv, char ** argc) 
{ 
    yylex(); 
    return 0; 
} 

void 
pop_state(const char * txt) 
{ 
    printf("active state: %d\n", YY_START); 
    printf("\tmatched: %s\n ", txt); 
    printf("\tpopping state (stack top): %d ... ", yy_top_state()); 
    yy_pop_state(); 
    printf("active state: %d\n", YY_START); 
} 

void 
push_state(const char * txt, int new_state) 
{ 
    printf("active state: %d\n", YY_START); 
    printf("\tmatched: '%s'\n ", txt); 
    printf("\tpushing state: %d, switching to state %d ... ", YY_START, new_state); 
    yy_push_state(new_state); 
    printf("stack top: %d, active state: %d\n", yy_top_state(), YY_START); 
}