• flex & bison学习(三)


    GNU bison是一个自由软件,用于自动生成语法分析器程序,实际上可用于所有常见的操作系统。Bison把LALR形式的上下文无关文法描述转换为可做语法分析的CC++程序。在新近版本中,Bison增加了对GLR语法分析算法的支持。

    GNU bison基本兼容Yacc,并做了一些改进。它一般与flex一起使用。

    下面是一个简单的计算器的文法描述Bison程序

    /* simplest version of calculator */

    %{
    #  include <stdio.h>
    %}

    /* declare tokens */
    %token NUMBER
    %token ADD SUB MUL DIV ABS
    %token OP CP
    %token EOL


    %%

    calclist: /* nothing */
     | calclist exp EOL { printf("= %d\n> ", $2); }
     | calclist EOL { printf("> "); } /* blank line or a comment */
     ;

    exp: factor
     | exp ADD exp { $$ = $1 + $3; }
     | exp SUB factor { $$ = $1 - $3; }
     | exp ABS factor { $$ = $1 | $3; }
     ;

    factor: term
     | factor MUL term { $$ = $1 * $3; }
     | factor DIV term { $$ = $1 / $3; }
     ;

    term: NUMBER
     | ABS term { $$ = $2 >= 0? $2 : - $2; }
     | OP exp CP { $$ = $2; }
     ;
    %%

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

    int yyerror(char *s)
    {
      fprintf(stderr, "error: %s\n", s);
    }

    对应的flex词法分析器为


    /* recognize tokens for the calculator and print them out */

    %{
    # include "fb1-5.tab.h"
    %}
    %option noyywrap

    %%
    "+"    { return ADD; }
    "-"    { return SUB; }
    "*"    { return MUL; }
    "/"    { return DIV; }
    "|"     { return ABS; }
    "("     { return OP; }
    ")"     { return CP; }
    [0-9]+    { yylval = atoi(yytext); return NUMBER; }

    \n      { return EOL; }
    "//".*  
    [ \t]   { /* ignore white space */ }
    .    { yyerror("Mystery character %c\n", *yytext); }
    %%


    按照如下顺序编译出fb1-5即可
    bison -d fb1-5.y
    flex fb1-5.l
    cc -o fb1-5 fb1-5.tab.c lex.yy.c -lfl


  • 相关阅读:
    方法名的string类型应用(补)
    unity3D里面的点乘和叉乘
    C# 计算时间日期
    iOS设备屏幕分辨率分布
    免证书发布ipa文件真机测试
    unity3D +php +数据库
    windows下mysql5.1忘记root密码解决方法[win7]
    springboot配置多数据源(JdbcTemplate方式)
    【转】Google Chrome中顺时针/逆时针滚动圆的含义
    Redis内存模型(2):存储细节
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2251670.html
Copyright © 2020-2023  润新知