Parse File using flex and bison -
i need parse following file using flex , bison:
new file
begin block blk_rowdec name cell_rowdec size uni_rowdecsize iterate itr_rows direction lgdir_rowdec strap strd1,strd3,strd2 wrap wrd1 via viab,viac,viad ends blk_rowdec
i want read above file , write code
lex.l
%{ #include <iostream> #include <stdio.h> #include "yacc.tab.h" #define yy_decl extern "c" int yylex() using namespace std; %} dot "." colon ":" semicolon ";" comma "," angle_left "<" angle_right ">" @ "@" equal "=" square_open "[" square_close [^\\]"]" openbrace "\(" closebrace "\)" quote "\"" quote_open "\"" quote_close [^\\]"\"" space " " tab "\t" crlf "\r\n" quoted_pair "\\"[^\r\n] digit [0-9] alpha [a-za-z] qtext [0-9a-za-z!#$%&'()*+,\-.\/:;<=>?@\[\]^_`{|}~] %% [a-za-z0-9]+ { yylval.sval = strdup(yytext); return tok_string; } {space}* {return tok_space; } ^{space}*name {return tok_name; } {space}*size.* {return tok_size; } {space}*iterate.* {return tok_iterate; } {space}*direction.* {return tok_direction; } ^{crlf} { return tok_empty_line; } {crlf} {} . {}/* ignore unknown chars */
yacc.y
%{ #include <cstdio> #include <cstring> #include <iostream> #include <stdio.h> using namespace std; extern "c" int yylex(); extern "c" file *yyin; void yyerror(const char* s); %} // symbols. %union { char* sval; }; %token <sval> tok_name %token <sval> tok_size %token <sval> tok_string %token <sval> tok_iterate %token <sval> tok_direction %token <sval> tok_empty_line %token tok_space %% str: tok_space tok_name tok_space tok_string { cout << "value:" << $2 << "->" << $4; } ; %% int main(void) { file * pt = fopen("new file ", "r" ); if(!pt) { cout << "bad input.noexistant file" << endl; return -1; } yyin = pt; { yyparse(); }while (!feof(yyin)); } void yyerror(const char *s) { cout << "error. " << s << endl; exit(-1); } #include "lex.yy.c"
first, try print second line of file not able print anything. please me do??
compilation done by:
flex lex.l bison -d yacc.y g++ yacc.tab.c -lfl -o scanner.exe
it important knowing how debug parser. in first part of file, #define yydebug 1
, , in main set yydebug = 1
. allow see exact steps when run parser ant you'll know error is. knowing extrimely important, because mistakes hard find. debug program!
%{ #include <cstdio> #include <cstring> #include <iostream> #include <stdio.h> #define yydebug 1 // new using namespace std; extern "c" int yylex(); extern "c" file *yyin; void yyerror(const char* s); %} int main(){ yydebug = 1; // new yyparse(); }
also yylval.sval = strdup(yytext);
after need check whether yylval.sval null, because strdup(yytext)
first allocating memory, , after function copying string, strdup(yytext)
return null if memory allocation fails.
Comments
Post a Comment