为什么 yylval 为空?
我正在尝试用 Flex & 编写我的第一个解析器。野牛。解析数字时,我尝试将它们的值保存到 yylval 结构中。问题是,当词法分析器到达数字时,yylval
为 null,这会导致分段错误。
(相关困惑点:为什么在大多数 Flex 示例中(例如 此处),yylval< /code> 是一个结构,而不是指向结构的指针?如果没有
%option bison-bridge
,我无法在 test.l 中识别 yylval
,并且该选项做出yylval
一个指针。另外,我尝试在 test.y 的 main
中初始化 yylval
,但是 yylval = malloc(...)
给出类型不匹配 - 就好像 yylval 不是指针...?)
test.l
%{
#include <stdio.h>
#include <stdlib.h>
#include "svg.tab.h"
%}
%option bison-bridge
%option noyywrap
%%
[0-9]+ { yylval->real = atof(yytext); return REAL; }
. { return *yytext; }
%%
test.y:
%{
#include <stdio.h>
void yyerror(char *);
%}
%union {
double real;
}
%token <real> REAL
%%
...
构建命令:
bison -d test.y && flex test.l && gcc lex.yy.c test.tab.c
I'm trying to write my first parser with Flex & Bison. When parsing numbers, I'm trying to save their values into the yylval
structure. The problem is, yylval
is null when the lexer reaches a number, which causes a segmentation fault.
(Related point of confusion: why is it that in most Flex examples (e.g. here), yylval
is a structure, rather than a pointer to a structure? I couldn't get yylval
to be recognized in test.l without %option bison-bridge
, and that option made yylval
a pointer. Also, I tried initializing yylval
in main
of test.y, but yylval = malloc(...)
gives a type mismatch-- as if yylval
is not a pointer...?)
test.l
%{
#include <stdio.h>
#include <stdlib.h>
#include "svg.tab.h"
%}
%option bison-bridge
%option noyywrap
%%
[0-9]+ { yylval->real = atof(yytext); return REAL; }
. { return *yytext; }
%%
test.y:
%{
#include <stdio.h>
void yyerror(char *);
%}
%union {
double real;
}
%token <real> REAL
%%
...
Build command:
bison -d test.y && flex test.l && gcc lex.yy.c test.tab.c
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,
yylval
是一个全局结构,而不是指针,如果您从 test.l 文件中删除%option bison-bridge
,这就是您得到的(您'您还需要将 yylval->real 更改为 yylval.real 才能使其正常工作)。flex 中的
%option bison-bridge
旨在匹配 bison 中的%define api.pure
,它使用不同的 API 在 yyparse 和 yylex 之间进行通信(yylval 变为yylex 的指针参数而不是全局变量)。所以你的基本问题是 flex 和 bison 之间的 API 不兼容——你需要在两者中指定纯 api/bison-bridge 或两者都不指定——如果你在一个而不是另一个中执行它,事情就会崩溃。
Normally,
yylval
is a global struct and not a pointer, and if you remove the%option bison-bridge
from your test.l file, that's what you get (you'll need to changeyylval->real
toyylval.real
as well to make it work).The
%option bison-bridge
in flex is meant to match up to%define api.pure
in bison, which uses a different API for communicating between yyparse and yylex (yylval becomes a pointer argument to yylex instead of a global var).So your basic problem is an incompatible API between flex and bison -- you need to specify the pure api/bison-bridge in BOTH or NEITHER -- if you do it in one and not the other, things break.