我尝试使用flex和bison创建一个简单的解析器。它编译好并生成输出文件,但问题是它没有产生预期的结果:例如输入"整数X:= 13"产生语法错误和" 13"在下一行不应该的时候。这是我的标记器。
%{
#include <stdio.h>
#include <stdlib.h>
#include "y.tab.h"
int yyerror(char *errormsg);
%}
number [0-9]
digit {number}+
letter [a-zA-Z]
bigletter [A-Z]
any [a-zA-Z0-9]
identifier {bigletter}({any))*
comm "--"
%%
"IO.read" {return READ;}
"IO.write" {return WRITE;}
"if" {return IF;}
"loop" {return LOOP;}
"until" {return UNTIL;}
"from" {return FROM;}
"finish if" {return FINISHIF;}
"finish from" {return FINISHFROM;}
"then" {return THEN;}
"start if" {return STARTIF;}
"but if" {return BUTIF;}
"start from" {return STARTFROM;}
digit {return DIGIT;}
"=" {return EQUAL;}
":=" {return ASSIGNMENT;}
"/=" {return NE;}
"<" {return LT;}
"<=" {return LE;}
">" {return GT;}
">=" {return GE;}
"+" {return PLUS;}
"-" {return MINUS;}
"*" {return MULT;}
"/" {return DIVIDE;}
"--" {return COMM;}
";" {return SEMICOLON;}
\"(([^\"]|\\\")*[^\\])?\" {return STRING;}
{comm}({any})*{comm} {return COMMENT;}
identifier {return IDENTIFIER;}
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 0;
}
int yyerror(char *errormsg)
{
fprintf(stderr, "%s\n", errormsg);
exit(1);
}
这是我的解析器:
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);
%}
%token TOK_EMPTY_LINE READ WRITE IF LOOP UNTIL FROM FINISHIF ENDIF FINISHFROM THEN
%token STARTIF BUTIF STARTFROM BIGLETTER DIGIT NUMBER
%token EQUAL ASSIGNMENT NE LT LE GT GE PLUS MINUS MULT DIVIDE COMM STRING
%token COMMENT LETTER IDENTIFIER SEMICOLON
%left PLUS MINUS
%left MULT DIVIDE
%%
stmts : stmt
| stmt SEMICOLON stmts
;
stmt : if_stmt
| from_stmt
| assign_stmt
| print_stmt
| decl_stmt
;
if_stmt : STARTIF IF cond THEN stmts FINISHIF
| STARTIF IF cond THEN stmts BUTIF cond THEN stmts FINISHIF
;
from_stmt : STARTFROM FROM decl_stmt UNTIL boolean_stmt LOOP stmt FINISHFROM
;
boolean_stmt : expr EQUAL expr
| expr NE expr
| expr GT expr
| expr LE expr
| expr GE expr
;
print_stmt : WRITE expr
;
cond : expr relop cond
| expr
;
relop : NE
| LE
| LT
| GT
| GE
| EQUAL
;
decl_stmt : DIGIT IDENTIFIER
| DIGIT assign_stmt
;
assign_stmt : IDENTIFIER IDENTIFIER ASSIGNMENT expr
;
expr : expr PLUS term
| expr MINUS term
| term
;
term : term MULT factor
| term DIVIDE factor
| factor
;
factor : DIGIT
| IDENTIFIER
;
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 0;
}
int yyerror(char *errormsg)
{
fprintf(stderr, "%s\n", errormsg);
exit(1);
}
非常感谢你花时间检查我的代码!