如何从yacc文件中创建解析器?

时间:2009-11-15 23:56:09

标签: parsing yacc

我得到了以下yacc文件。如何从中解析出来?我是否必须先制作扫描仪?

/* C-Minus BNF Grammar */

%token ELSE
%token IF
%token INT
%token RETURN
%token VOID
%token WHILE

%token ID
%token NUM

%token LTE
%token GTE
%token EQUAL
%token NOTEQUAL
%%

program : declaration_list ;

declaration_list : declaration_list declaration | declaration ;

declaration : var_declaration | fun_declaration ;

var_declaration : type_specifier ID ';'
                | type_specifier ID '[' NUM ']' ';' ;

type_specifier : INT | VOID ;

fun_declaration : type_specifier ID '(' params ')' compound_stmt ;

params : param_list | VOID ;

param_list : param_list ',' param
           | param ;

param : type_specifier ID | type_specifier ID '[' ']' ;

compound_stmt : '{' local_declarations statement_list '}' ;

local_declarations : local_declarations var_declaration
                   | /* empty */ ;

statement_list : statement_list statement
               | /* empty */ ;

statement : expression_stmt
          | compound_stmt
          | selection_stmt
          | iteration_stmt
          | return_stmt ;

expression_stmt : expression ';'
                | ';' ;

selection_stmt : IF '(' expression ')' statement
               | IF '(' expression ')' statement ELSE statement ;

iteration_stmt : WHILE '(' expression ')' statement ;

return_stmt : RETURN ';' | RETURN expression ';' ;

expression : var '=' expression | simple_expression ;

var : ID | ID '[' expression ']' ;

simple_expression : additive_expression relop additive_expression
                  | additive_expression ;

relop : LTE | '<' | '>' | GTE | EQUAL | NOTEQUAL ;

additive_expression : additive_expression addop term | term ;

addop : '+' | '-' ;

term : term mulop factor | factor ;

mulop : '*' | '/' ;

factor : '(' expression ')' | var | call | NUM ;

call : ID '(' args ')' ;

args : arg_list | /* empty */ ;

arg_list : arg_list ',' expression | expression ;

1 个答案:

答案 0 :(得分:2)

你确实需要一台扫描仪(有些人也称为漫射器或词法分析器)。如果您使用yacc,则通常使用lex;如果使用bison(对于.y文件),则通常使用flex(对于.l文件)。

扫描程序需要输出yacc文件中定义的所有不同标记(%token指令以及单引号中的内容)。

为了帮助您入门,您需要将以下内容添加到.l文件并在其上运行flex,然后查看标题和诸如此类的信息,然后编译.c输出。

%{
#include "y.tab.h"
// other stuff for your program
%}

%%

else return ELSE;  // correspond to the %token's in your yacc file
if   return IF;
int  return INT;
// other ones at the top of your yacc file

%%

// any c-code helper functions to do fancy scanning.

这是一个非常简单的例子,它总是变得更复杂,但应该让你开始。

有关教程,请参阅http://dinosaur.compilertools.net/

玩得开心!