我正在尝试使用Flex和Bison在C ++中创建解析器。我看到“灵活扫描输入失败”只能在提供解析错误文件的帖子中联机。但是在我正确解析整个文件后,我收到此错误。是否存在flex无法正确检测EOF的错误?这些是相关的定义:
野牛 -
%union {
char node;
char gate;
int index;
}
%token END;
%token <node> NODE;
%token <gate> GATE;
%token <index> INDEX;
%%
atpg:
body END { cout << "Reading last line." << endl; };
body:
assignments;
assignments:
assignments assignment { cout << "Token: assignments - rec." << endl; }
| assignment { cout << "Token: assignments - first." << endl; };
assignment:
outnode gatedec '(' nodelist ')' {
cout << "Token: assignment" << endl;
g_gatelist[last_gate].setOutput(&g_nodelist[out_node]);
for(int i : t_nodelist)
g_gatelist[last_gate].addInput(&g_nodelist[i]);
t_nodelist.clear();
};
outnode:
nodedec '=' {
cout << "Token: outnode" << endl;
out_node = last_node;
};
nodedec:
NODE INDEX {
num_nodes ++;
if ($1 == 'i') input_nodes ++;
if ($1 == 'o') output_nodes ++;
new(&g_nodelist[$2]) Node($1, $2);
last_node = $2;
cout << g_nodelist[$2] << endl;
};
gatedec:
GATE INDEX {
num_gates ++;
createGateFromName(&g_gatelist[$2], $1, $2);
last_gate = $2;
cout << "Gate: " << $1 << "-" << $2 << endl;
};
nodelist:
nodedec nodelist {
cout << "Token: nodelist - rec" << endl;
t_nodelist.push_back(last_node);
}
| nodedec {
cout << "Token: nodelist - first" << endl;
t_nodelist.push_back(last_node);
};
Flex -
%{
#include "gatelist.tab.h"
#define YY_DECL extern "C" int yylex()
%}
INDEX [0-9]+
GATE and|or|not
NODE n|i|o
%%
{GATE} { yylval.gate = yytext[0]; return GATE; }
{NODE} { yylval.node = yytext[0]; return NODE; }
{INDEX} { yylval.index = atoi(yytext); return INDEX; }
[\(\)=] { return yytext[0]; }
end { return END; }
.|\n ;/* ignore */
%%
;
输入 -
n3 = and1 ( i0 i1 i2 )
n4 = or2 ( i1 i2 )
n5 = not3 ( n4 )
n6 = and4 ( n5 n4 )
end
输出 -
Node(n-3 = 0)
Token: outnode
Gate: a-1
Node(i-0 = 0)
Node(i-1 = 0)
Node(i-2 = 0)
Token: nodelist - first
Token: nodelist - rec
Token: nodelist - rec
Token: assignment
Token: assignments - first.
Node(n-4 = 0)
Token: outnode
Gate: o-2
Node(i-1 = 0)
Node(i-2 = 0)
Token: nodelist - first
Token: nodelist - rec
Token: assignment
Token: assignments - rec.
Node(n-5 = 0)
Token: outnode
Gate: n-3
Node(n-4 = 0)
Token: nodelist - first
Token: assignment
Token: assignments - rec.
Node(n-6 = 0)
Token: outnode
Gate: a-4
Node(n-5 = 0)
Node(n-4 = 0)
Token: nodelist - first
Token: nodelist - rec
Token: assignment
Token: assignments - rec.
Reading last line.
input in flex scanner failed
答案 0 :(得分:1)
Bison总是通过添加一个目标规则来增加提供的语法,该目标规则与您提供的开始规则匹配,后跟文件结束指示符(标记号0),以便强制输入匹配完整文件。如果要使用自己的结束标记并在识别时终止解析,则应使用相关操作中的YYACCEPT
操作使解析成功终止而不读取更多标记。
当flex扫描程序在尝试读取数据时收到读取错误时,会出现错误。文件结尾不是一个错误,I / O错误相当罕见。通常,此错误表示在报告文件结束并yyin
关闭(或设置为无效值)后,尝试继续读取输入。一般情况下,在报告文件结束后应避免阅读令牌;虽然它经常有效,但它并不完全支持,并且某些扫描仪选项会产生意想不到的结果。
作为一个副作用,您通常会发现使用bison的内置trace facility比在整个代码中分散printf更容易。你将最终添加和删除printf,这是一个令人讨厌的事情,他们永远不会完整地描述你的野牛踪迹。