我已经实现了一个解析器,但它不打印任何东西。yyerror()
如果给定的输入在语法上是错误的,尽管我将它包含在例程中,但它不会打印“错误” 。此外,如果输入正确,它不会打印 Parse 树。这可能是什么原因?我已将我main()
的文件放入.lex
文件而不是.y
文件中。这是可能的原因吗?这是主要方法:
int main( argc, argv )
int argc;
char **argv;
{
++argv, --argc;
if ( argc > 0 )
yyin = fopen( argv[0], "r" );
else
yyin = stdin;
yyparse();
}
语法文件是:
%{
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%union {
char* a_variable;
tree* a_tree;
}
%start file
%token <a_variable> TOKID TOKSEMICOLON TOLCOLON TOKCOMMA TOKUNRECOG TOKDOT TOKMINUS TOKCOLON
%type <a_tree> field file obj ID
%right TOKMINUS
%%
file : /*empty*/ { return NULL; }
| field file { printtree($1, 1); }
;
field : ID TOKCOLON field {$$ = make_op($1, ':', $3); }
| ID TOKCOMMA field {$$ = make_op($1, ',', $3); }
| obj { $$ = $1; }
;
obj : ID TOKSEMICOLON { $$ = make_op($1, ';', NULL); }
;
ID : TOKID { $$ = $1; }
%%
#include <stdio.h>
yyerror(char *str)
{
fprintf(stderr,"error FAIL: %s\n",str);
}
int yywrap()
{
return 1;
}
这是我的.lex
文件的外观:
%{
/* need this for the call to atof() below */
#include <math.h>
#include "parser.h"
#include "idf.tab.h"
%}
DIGIT [0-9]
ID [a-zA-Z]*
%option noyywrap
%%
{ID} |
-?{DIGIT}+"."{DIGIT}* |
-?{DIGIT}+ { yylval.a_variable = findname(yytext); return TOKID; }
";" return TOKSEMICOLON;
":" return TOKCOLON;
"," return TOKCOMMA;
"." return TOKDOT;
"-" return TOKMINUS;
. return TOKUNRECOG;
%%
int main( int argc, char** argv )
{
++argv, --argc;
if ( argc > 0 )
yyin = fopen( argv[0], "r" );
else
yyin = stdin;
yyparse();
}