我现在正在尝试使用C语言中的Modern Compiler Implementation(Tiger书籍)构建一个编译器。我现在陷入了解析器阶段。我已经构建了我的语法并试图运行它但仍然会出现一些语法错误。 我尝试了我的词法分析器,似乎有效。
这是我的yacc / bison的代码:
%{
#include <stdio.h>
#include "util.h"
#include "errormsg.h"
#include <stdio.h>
int yylex(void); /* function prototype */
void yyerror(char *s)
{
EM_error(EM_tokPos, "%s", s);
}
%}
%union {
int pos;
int ival;
string sval;
}
%token <sval> ID STRING
%token <ival> INT
%token
COMMA COLON SEMICOLON LPAREN RPAREN LBRACK RBRACK
LBRACE RBRACE DOT
PLUS MINUS TIMES DIVIDE EQ NEQ LT LE GT GE
AND OR ASSIGN
ARRAY IF THEN ELSE WHILE FOR TO DO LET IN END OF
BREAK NIL
FUNCTION VAR TYPE
%start program
%nonassoc DO OF
%nonassoc THEN /* ELSE must come after THEN! */
%nonassoc ELSE
%left SEMICOLON
%left ASSIGN
%left OR
%left AND
%nonassoc EQ NEQ GT LT GE LE
%left PLUS MINUS
%left TIMES DIVIDE
%left UMINUS
%%
program: exp;
dec: tyDec;
dec: varDec;
dec: funDec;
tyDec: TYPE ID EQ ty;
ty: ID;
ty: arrTy;
ty: recTy;
arrTy: ARRAY OF ID;
recTy: LBRACE fieldDecs RBRACE;
fieldDecs: /* empty */ ;
fieldDecs: fieldDec;
fieldDecs: fieldDec COMMA fieldDecs;
fieldDec: ID COLON ID;
funDec: FUNCTION ID LPAREN fieldDecs RPAREN EQ exp;
funDec: FUNCTION ID LPAREN fieldDecs RPAREN COLON ID EQ exp;
varDec: VAR ID ASSIGN exp;
varDec: VAR ID COLON ID ASSIGN exp;
lValue: ID;
lValue: subscript;
lValue: fieldExp;
subscript: lValue LBRACK exp RBRACK;
fieldExp: lValue DOT ID;
exp: lValue;
exp: NIL;
exp: INT;
exp: STRING;
exp: seqExp;
exp: negation;
exp: callExp;
exp: infixExp;
exp: arrCreate;
exp: recCreate;
exp: assignment;
exp: ifThenElse;
exp: ifThen;
exp: whileExp;
exp: forExp;
exp: BREAK;
exp: letExp;
seqExp: LPAREN exps RPAREN;
exps: /* empty */ ;
exps: exp;
exps: exp SEMICOLON exps;
negation: MINUS exp %prec UMINUS ;
callExp: ID LPAREN expsc RPAREN ;
expsc: /* empty */ ;
expsc: exp;
expsc: exp COMMA expsc;
infixExp: arithmExp;
infixExp: boolExp;
infixExp: compExp;
arithmExp: exp PLUS exp;
arithmExp: exp MINUS exp;
arithmExp: exp TIMES exp;
arithmExp: exp DIVIDE exp;
boolExp: exp AND exp;
boolExp: exp OR exp;
compExp: exp EQ exp;
compExp: exp NEQ exp;
compExp: exp GT exp;
compExp: exp LT exp;
compExp: exp GE exp;
compExp: exp LE exp;
arrCreate: ID LBRACK exp RBRACK OF exp;
recCreate: ID LBRACE fieldCreates RBRACE;
fieldCreates: /* empty */ ;
fieldCreates: fieldCreate;
fieldCreates: fieldCreate COMMA fieldCreates;
fieldCreate: ID EQ exp;
assignment: lValue ASSIGN exp;
ifThenElse: IF exp THEN exp ELSE exp;
ifThen: IF exp THEN exp;
whileExp: WHILE exp DO exp;
forExp: FOR ID ASSIGN exp TO exp DO exp;
letExp: LET decs IN exps END;
decs: dec;
decs: dec decs;
/* ERROR RECOVERY */
exp: LPAREN error RPAREN;
seqExp: error SEMICOLON exp;
当我在样本老虎代码上运行我的解析器时,我得到一些语法错误,包括在开头。
你可以帮我解决一下吗?谢谢!