我正在尝试使用flex和yacc识别整数 token 。这是我的整数的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($2); freeNode($2);}
|
;
stmt :
| PORT location { printf("Port taken"); }
;
location : INTEGER { printf("Number is %d",$1); }
;
但是当我执行程序时,它无法识别数字,
输入为
pin 4
输出量
4
输出应为
Port taken Number is 4
我在这里想念什么?
所有其他 token 工作正常。
提前致谢。
最佳答案
您获得的输出是yyerror
函数的输出,默认情况下,该函数仅将无效标记输出到stderr。
发生的情况是正确识别了“pin”,但没有识别出“4”。因此,语句规则不会产生任何输出,因为它仍在等待整数。因此,唯一的输出是yyerror
的输出。
无法识别4的原因是您用数字引号的正则表达式作为字符串文字。因此,它正在寻找文字字符串“[0-9] +”。删除引号以将其解释为正则表达式。
PS:您还需要添加跳过空格的规则,否则必须输入不带空格的pin4
。
关于compiler-errors - 使用flex和yacc的整数 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46755790/