2017-10-15 132 views
0

我想使用flex和yacc来识别整数令牌。这是我用于整数的flex文件语法。使用flex和yacc的整数令牌

%{ 
#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); } 

       ; 

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

输入是

销4

输出

输出应该是

端口取号是4

缺少什么我在这里? 所有其他令牌工作正常。

在此先感谢。

+0

请发布足够的代码来运行代码并重现问题。对输入量,实际产量和预期产出也要更加清楚。输入“引脚4”和输出“4”?预期的产出将是“数量”,没有别的? – sepp2k

+0

@ sepp2k我已添加完整的代码。 实际上,我需要确定的是我的代码获取“引脚4”并确定引脚和编号。然后我可以使用该数字在我的C代码中进一步处理。 – Sachith

+0

我还不清楚你的输入,实际输出和预期输出是什么。我没有看到输出结果如何只能是'4',你的代码中没有任何东西只是打印一个没有附加文本的数字。 – sepp2k

回答

1

您得到的输出是yyerror函数的输出,默认情况下,该函数会将无效令牌打印到stderr。

会发生什么是“引脚”被正确识别,但“4”不是。所以语句规则不会产生任何输出,因为它仍在等待一个整数。所以唯一的输出是yyerror

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

PS:您还需要添加跳过空格的规则,否则您将不得不输入pin4而不能有空格。

+0

是的,那是我的错误。非常感谢@ sepp2k – Sachith