Yacc/Bison:伪变量($$、$1、$2、..)以及如何使用 printf 打印它们
我有一个用 flex 编写的词法分析器,它将标记传递给用 bison 编写的解析器。
以下是我的词法分析器的一小部分:
ID [a-z][a-z0-9]*
%%
rule {
printf("A rule: %s\n", yytext);
return RULE;
}
{ID} {
printf( "An identifier: %s\n", yytext );
return ID;
}
"(" return LEFT;
")" return RIGHT;
还有其他用于解析空格等的位。
然后解析器的一部分如下所示:
%{
#include <stdio.h>
#include <stdlib.h>
#define YYSTYPE char*
%}
%token ID RULE
%token LEFT RIGHT
%%
rule_decl :
RULE LEFT ID RIGHT { printf("Parsing a rule, its identifier is: %s\n", $2); }
;
%%
一切正常,但我只想使用 printf 打印出 ID 令牌 - 仅此而已:)。我不是在写编译器……只是 flex/bison 对于我的软件来说是很好的工具。你打算如何打印代币?当我打印时,我只是得到 (null)
。
谢谢。
I have a lexical analyser written in flex that passes tokens to my parser written in bison.
The following is a small part of my lexer:
ID [a-z][a-z0-9]*
%%
rule {
printf("A rule: %s\n", yytext);
return RULE;
}
{ID} {
printf( "An identifier: %s\n", yytext );
return ID;
}
"(" return LEFT;
")" return RIGHT;
There are other bits for parsing whitespace etc too.
Then part of the parser looks like this:
%{
#include <stdio.h>
#include <stdlib.h>
#define YYSTYPE char*
%}
%token ID RULE
%token LEFT RIGHT
%%
rule_decl :
RULE LEFT ID RIGHT { printf("Parsing a rule, its identifier is: %s\n", $2); }
;
%%
It's all working fine but I just want to print out the ID token using printf - that's all :). I'm not writing a compiler.. it's just that flex/bison are good tools for my software. How are you meant to print tokens? I just get (null)
when I print.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是 yacc 专家,但我处理从词法分析器到解析器的转换的方式如下:对于每个词法分析器标记,您应该有一个单独的规则来“翻译”
yytext< /code> 转换为适合您的解析器的形式。就您而言,您可能只对 yytext 本身感兴趣(如果您正在编写编译器,您会将其包装在 SyntaxNode 对象或类似的对象中)。重点
是,最后一条规则使
yytext
可以作为$
变量使用,可以由涉及id
的规则引用。I'm not an expert at yacc, but the way I've been handling the transition from the lexer to the parser is as follows: for each lexer token, you should have a separate rule to "translate" the
yytext
into a suitable form for your parser. In your case, you are probably just interested inyytext
itself (while if you were writing a compiler, you'd wrap it in aSyntaxNode
object or something like that). TryThe point is that the last rule makes
yytext
available as a$
variable that can be referenced by rules involvingid
.