Flex is a lexical parsing program, and Bison is a syntax parsing open source program. Together, they can parse the language of some computer scripting language, such as SQL. This time I mainly introduce the build of flex and Bison under Unix system.
Look at the Flex code first:
%{#include"Fb1-5.tab.h"//the file is generated by the bison behind Bison. The value of the token is defined primarily. and Yylval variables%}%%"+"{returnADD; }//match on "+", return token add,yylval at this time the value is 259"-"{returnSUB;}"*"{returnMUL;}"/"{returnDIV;}"|"{returnABS;}"("{returnOP;}")"{returnCP;} [0-9]+ {yylval = Atoi (Yytext);returnNumber ;} \ n {returnEOL;}"//".*[\ t] {/*Ignore white space*/ }. {Yyerror ("Mystery character%c\n", *yytext); }%%
Bison Code:
%{# include<stdio.h>%}/*Declare tokens*/%token number//Declare token%token ADD SUB MUL DIV ABS%token OP CP%token EOL%%calclist:/* Nothing*/| Calclist exp EOL {printf ("=%d\n>", $2); } | Calclist EOL {printf (">"); }/*Blank line or a comment*/; Exp:factor| Exp ADD Exp {$$ = $1+ $3; } | Exp SUB Factor {$$ = $1- $3; } | Exp ABS Factor {$$ = $1| $3; } ; Factor:term| Factor MUL Term {$$ = $1* $3; } | Factor DIV Term {$$ = $1/ $3; } ; Term:number| ABS term {$$ = $2>=0? $2: - $2; } | OP exp CP {$$ = $2; } ;%%Main () {printf (">"); Yyparse ();} Yyerror (Char*s) {fprintf (stderr,"Error:%s\n", s);}
Run the command at the terminal:
directory where Cd/flex and bison files are located
Bison-d Fb.y (FB is a bison file, after the command executes successfully, Fb.tab.h and FB.TAB.C two files are generated)
Flex FB.L (FB.L is a flex file and generates FLEX.YY.C files. But the above code is wrong in my system because there is no FL library in my system, so there is no yywrap () function
The solution is as follows: In the original FB.L file, the last line, add a yywrap () function. See Code)
%{#include"Fb1-5.tab.h"%}%%"+"{returnADD;}"-"{returnSUB;}"*"{returnMUL;}"/"{returnDIV;}"|"{returnABS;}"("{returnOP;}")"{returnCP;} [0-9]+ {yylval = Atoi (Yytext);returnNumber ;} \ n {returnEOL;}"//".*[\ t] {/*Ignore white space*/ }. {Yyerror ("Mystery character%c\n", *yytext); }%%Yywrap () {return 1; }
CC FB.TAB.C LEX.YY.C (the a.out executable will be generated in the current directory if it runs successfully)
./a.out (Running the executable file)
Co-compiling flex and Bison programs under UNIX systems