(Array Parser)令牌解析Flex / Bison奇怪的行为

时间:2019-07-18 21:57:30

标签: bison flex-lexer

我目前正在尝试从我用Flex和Bison编写的解析器中解析数组。

例如,如果我输入“ int testarr [90];” Flex解​​析器正确匹配数组标识符“ testarr”,但是当令牌返回给Bison时,相应的令牌(%令牌ID)返回字符串“ testarr [90]”。那怎么可能?

Flex感兴趣的代码部分(正则表达式规则)

%%

letter  [a-z]
digit   [0-9]
char    [_]

%%
    /* rules */
    /* NOTE: If two patterns match the same string the longest match wins. */

[ \t]                                                  ; /* ignore whitespace and tabs */
[-+*=/\n]                                              return *yytext; /* match operators */
int|float|double                                       { yylval.stringValue = yytext; return TYPE; } /* match array types */
{digit}+                                               { yylval.intValue = atoi(yytext); return NUM; } /* match array indexes or integers */
{digit}+(\.?{digit})+                                  { yylval.doubleValue = atof(yytext); return DECIMAL; } /* match any decimal number (double, float) */

// Here the yytext is "testarr"
{letter}({letter}|{digit})*                            { yylval.stringValue = yytext; return ID; } /* match array identifier (name) */


"["                                                    return yytext[0]; /* match [ */
"]"                                                    return yytext[0]; /* match ] */
";"                                                    return yytext[0]; /* match ; */
","                                                    return yytext[0]; /* match , */
.                                                      return yytext[0]; /* match any other character */

%%

在Bison部分,我得到“ testarr [90]”而不是“ testarr”作为令牌ID。

[...other code]

%union
{
    int intValue;
    double doubleValue;
    char *stringValue;
}

%error-verbose
%token TYPE NUM ID DECIMAL

%type <stringValue> TYPE
%type <doubleValue> DECIMAL
%type <intValue>    NUM
%type <stringValue> ID    
%type <doubleValue> E

[...other code and rules]

// here output from printf is "testarr[90]" instead of "testarr"
ARRAY:      ID '[' NUM ']'   { printf("%s", $<stringValue>1); exit(1); };

1 个答案:

答案 0 :(得分:0)

我认为您需要strcpy yytext,因为扫描下一个标记将使旧指针无效(或者更确切地说,它将终止的\0移到下一个标记的末尾)

相关问题