bison

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

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

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

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

结尾部分能够包含你但愿使用的任何的代码。一般在序言部分声明的函数就在此处定义。在简单程序中全部其他部分均可以在此处定义。spa

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

%{token

#define YYSTYPE doubleip

#include <stdio.h>rpc

#include <stdlib.h>get

#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 */

相关文章
相关标签/搜索