bison

BSION
==Bison 语法文件内容的布局==

Bison 工具将把 Bison 语法文件作为输入。语法文件的扩展名为.y。Bison 语法文件内容的分布如下(四个部分):
%{
序言
%}
Bison 声明
%%
语法规则
%%
结尾
序言部分可定义 actions 中的C代码要用到的类型和变量,定义宏,用 #include 包含头文件等等。要在此处声明词法分析器 yylex 和错误输出器 yyerror 。还在此处定义其他 actions 中使用到的全局标识符。

Bison声明部分可以声明终结符和非终结符的名字,也可以描述操作符的优先级,以及各种符号的值语义的数据类型。各种非单个字符的记号(节点)都必须在此声明。

语法规则部分描述了如何用组件构造出一个非终结符。(这里我们用术语组件来表示一条规则中的各个组成部分。)

结尾部分可以包含你希望使用的任何的代码。通常在序言部分声明的函数就在此处定义。在简单程序中所有其余部分都可以在此处定义。

一个逆波兰计算器的例子:                                                                                                                                                                                     
/* Reverse polish notation calculator. */

%{

#define YYSTYPE double

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

int yylex (void);

void yyerror (char const *);

%}

%token NUM

%% /* Grammar rules and actions follow. */

input: /* empty */

| input line

;

line: '\n'

| exp '\n' { printf ("\t%.10g\n", $1); }

;

exp: NUM { $$ = $1; }

| exp exp '+' { $$ = $1 + $2; }

| exp exp '-' { $$ = $1 - $2; }

| exp exp '*' { $$ = $1 * $2; }

| exp exp '/' { $$ = $1 / $2; }

/* Exponentiation */

| exp exp '^' { $$ = pow($1, $2); }

/* Unary minus */

| exp 'n' { $$ = -$1; }

;

%%

/* The lexical analyzer returns a double floating point

number on the stack and the token NUM, or the numeric code

of the character read if not a number. It skips all blanks

and tabs, and returns 0 for end-of-input. */

#include <ctype.h>

int yylex (void)
{

    int c;

    /* Skip white space. */

    while ((c = getchar ()) == ' ' || c == '\t');

    /* Process numbers. */

    if (c == '.' || isdigit (c))
    {
    ungetc (c, stdin);
    scanf ("%lf", &yylval);
    return NUM;
    }

    /* Return end-of-input. */

    if (c == EOF)
        return 0;

    /* Return a single char. */

    return c;

}

int main (void)
{
    return yyparse ();
}


/* Called by yyparse on error. */

void yyerror(char const *s)
{
    fprintf (stderr, "%s\n", s);
}
/*
编译方法
bison rpcalc.y
cc -o rpcalc rpcalc.tab.c -lm
*/

转载于:https://my.oschina.net/u/2358894/blog/1600222

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值