Yacc/Bison:伪变量($$,$ 1,$ 2 ..)以及如何使用printf打印它们 [英] Yacc/Bison: The pseudo-variables ($$, $1, $2,..) and how to print them using printf
问题描述
我有一个用flex编写的词法分析器,它将令牌传递给用bison编写的解析器.
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.
解析器的一部分如下:
%{
#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)
.
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.
谢谢.
推荐答案
我不是yacc的专家,但是我处理从词法分析器到解析器的过渡的方式如下:对于每个词法分析器标记,您应该有一条单独的规则来将yytext
翻译"成适合您的解析器的形式.在您的情况下,您可能只对yytext
本身感兴趣(如果您正在编写编译器,则将其包装在SyntaxNode
对象或类似的对象中).试试
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 in yytext
itself (while if you were writing a compiler, you'd wrap it in a SyntaxNode
object or something like that). Try
%token ID RULE
%token LEFT RIGHT
%%
rule_decl:
RULE LEFT id RIGHT { printf("%s\n", $3); }
id:
ID { $$ = strdup(yytext); }
关键是最后一条规则将yytext
用作$
变量,可以由涉及id
的规则引用.
The point is that the last rule makes yytext
available as a $
variable that can be referenced by rules involving id
.
这篇关于Yacc/Bison:伪变量($$,$ 1,$ 2 ..)以及如何使用printf打印它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!