0

我得到了以下 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 ;
4

1 回答 1

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/

玩得开心!

于 2009-11-16T00:08:32.693 回答