使用 flex 和 yacc 的整数令牌

Integer token using flex and yacc

我正在尝试使用 flex 和 yacc 识别整数标记。这是我的整数 flex 文件语法。

%{
#include "main.h"
#include "y.tab.h"
#include <stdlib.h>
#include <string.h>
#define YYSTYPE char *
void yyerror(char *);
%}

code            "code"
special         ":"
turn            "turn"
send            "send"
on              "on"
pin             "pin"
for             "for"
num             "[0-9]+"

%%
{code}          {return CODE;}
{special}       {return SPECIAL; }
{turn}          {return OPRTURN;}
{send}          {return OPRSEND;}
{on}            {return OPRON;}
{pin}           {return PORT;}
{for}           {return FOR;}
{num}           { yylval.iValue = atoi(yytext); return INTEGER;}
%%

int yywrap(void) {
return 1;
}

在 yacc 文件中..

%{
    #include "main.h"
    #include <stdio.h>
    #include <stdarg.h>
    #include <stdlib.h>
//    char *name[10];

void  startCompiler();

/* prototypes */
nodeType *enm(char* c);
nodeType *opr(int oper,int nops,...);
nodeType *id(int i);
nodeType *con(int value);
nodeType *cmd(char *c);

void freeNode(nodeType *p);
int ex(nodeType *p);
int yylex(void);

void yyerror(char *s);
//int sym[26];                    /* symbol table */
%}

%union {
    int iValue;                 /* integer value */
    char sIndex;                /* symbol table index */
    char *str;                /* symbol table index */
    nodeType *nPtr;             /* node pointer */
};

%token <iValue> INTEGER

%token CODE SPECIAL OPRTURN OPRSEND OPRON PORT FOR
%type <nPtr> stmt stmt_list oper operation duration pin location



%%

input   : function { exit(0);}
        ;

input   : function { exit(0);}
        ;

function : function stmt  { ex(); freeNode();}
        |
        ;

stmt    : 

        | PORT location          { printf("Port taken"); }
        ;


location : INTEGER  { printf("Number is %d",); }

                ;

但是当我执行程序时,它不识别数字,

输入是

pin 4

输出

4

输出应该是

Port taken Number is 4

我在这里错过了什么? 所有其他令牌都工作正常。

提前致谢。

您得到的输出是 yyerror 函数的输出,默认情况下它只将无效标记打印到 stderr。

发生的情况是 "pin" 被正确识别,但“4”不是。所以语句规则没有产生任何输出,因为它仍在等待一个整数。所以唯一的输出是 yyerror.

它无法识别 4 的原因是您将数字的正则表达式作为字符串文字引用。所以它正在寻找文字字符串“[0-9]+”。删除引号以将其解释为正则表达式。

PS:您还需要添加一个跳过空格的规则,否则您将不得不输入不带空格的 pin4