【问题标题】:Integer token using flex and yacc使用 flex 和 yacc 的整数令牌
【发布时间】:2023-03-22 22:51:01
【问题描述】:

我正在尝试使用 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

输出应该是

端口号是4

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

提前致谢。

【问题讨论】:

  • 请发布足够的代码来运行代码并重现问题。还要更清楚输入、实际输出和预期输出是什么。输入“pin 4”和输出“4”?预期的输出将是“取数”而不是别的?
  • @sepp2k 我已经添加了完整的代码。实际上我需要识别的是我的代码获取pin 4 并识别引脚和编号。然后我可以在我的 C 代码中使用该数字进行进一步处理。
  • 我仍然不清楚您的输入、实际输出和预期输出是什么。我看不出输出怎么可能只是4,您的代码中没有任何内容只打印一个没有附加文本的数字。
  • @sepp2k 这里我想做的是,当输入为pin 4 时,我的语法应该识别它和Port taken Number is 4。这只是一个大代码的片段,我正在尝试将伪代码制作成 arduino 代码。
  • 好的,会发生什么?因为查看代码,这正是我所期望的。

标签: compiler-errors bison flex-lexer yacc


【解决方案1】:

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

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

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

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

【讨论】:

  • 是的,那是我的错误。非常感谢@sepp2k
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多