Yacc/Bison:伪变量($$,$ 1,$ 2 ..)以及如何使用printf打印它们 [英] Yacc/Bison: The pseudo-variables ($$, $1, $2,..) and how to print them using printf

查看:1334
本文介绍了Yacc/Bison:伪变量($$,$ 1,$ 2 ..)以及如何使用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屋!

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