[英]How do you make a parser from a yacc file?
我得到了以下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 ;
實際上,您將需要一台掃描儀(有時也稱為令牌生成器或詞法分析器)。 如果您使用的是yacc,則通常使用lex來完成;如果您使用的是bison的(.y文件),則通常使用flex(用於.l文件)完成。
掃描程序需要輸出yacc文件中定義的所有不同標記(%token指令以及單引號中的內容)。
首先,將d添加到.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/
玩得開心!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.