仅在找到EOF时,使野牛减少以开始符号 [英] Make bison reduce to start symbol only if EOF is found

查看:60
本文介绍了仅在找到EOF时,使野牛减少以开始符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Bison与Flex一起使用. 我的Yacc输入文件中有以下规则:

I am using Bison with Flex. I have the following rule in my Yacc input file:

program     : PROGRAM m2 declarations m0 block {cout << "Success\n"} ;

问题是,如果我有一个部分正确的程序,但是在EOF之前有一些垃圾",它将根据先前的规则减少,报告成功",然后才报告错误.

The problem is that if I have a program that is partially correct, but then there is some "garbage" before EOF, it will reduce according to the previous rule, report "success" and only then report an error.

我想在上述规则的末尾包含EOF,但是Flex读取<<EOF>>时必须返回EOF,而Bison怎么知道何时终止程序? 现在,我在Flex中有了这个

I want to include EOF at the end of the rule above, but then, Flex would have to return EOF when it read <<EOF>>, and how would Bison know when to end the program? Now, I have this in Flex:

<<EOF>>    {return 0;}

推荐答案

以下是可以做到这一点的示例:

Here is an example that would do that:

首先是lex文件:

%{
#include "grammar.tab.h"
%}
%x REALLYEND
%option noinput nounput
%%
"END"                   { return END; }
.                       { return TOK; }
<INITIAL><<EOF>>        { BEGIN(REALLYEND); return EOP; }
<REALLYEND><<EOF>>      { return 0; }
%%

int yywrap(void)
{
        return 1;
}

<INITIAL>条件下,文件结束会生成令牌EOP.请注意明确使用<INITIAL>,因为<<EOF>>否则将用于所有开始条件.然后切换到<REALLYEND>为野牛生成内部文件结尾令牌".

In the <INITIAL> condition the end-of-file generates a token EOP. Note the explicit use of <INITIAL>, because otherwise the <<EOF>> will be used for all begin conditions. Then it switches to <REALLYEND> to generate the internal end-of-file "token" for bison.

野牛文件看起来像这样:

The bison file could look like this:

%token END EOP TOK
%{
#include <stdio.h>
void yyerror(char * msg)
{
        fprintf(stderr, "%s\n", msg);
}
extern int yylex(void);
%}
%%
prog : END EOP { printf ("ok\n"); };
%%

int main(void)
{
        return yyparse();
}

标题中的问题有点误导,因为如果找到了EOFbison总是只会减少 internal 的起始符号,即内部文件结尾标记为了.不同之处在于,您希望仅在找到EOF之后而不是在发现之前执行语法中打印success的操作.也就是说,减少您的起始符号.

The question in your title is a bit misleading as bison will always only reduce the internal start symbol if EOF is found, that is what the internal end-of-file token is for. The difference is that you wanted the action, printing success, in the grammar only to be executed after the EOF has been found and not before. That is, reduction of your start symbol.

这篇关于仅在找到EOF时,使野牛减少以开始符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆