Example using bison and flex with cygwin on Windows
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2007/02/example-using-bison-and-flex-with/
You should be redirected in 2 seconds.
Here is an example of how to use bison and flex (yacc and lex) with cygwin on windows xp.
- Go to http://www.cygwin.com/, install Cygwin including bison 2.3-1, flex 2.5.4a-3, gcc-core 3.4.4-1, and make 3.81-1.
- Create a file called "simple.flex" in "c:\temp":
%{
#include "simple.tab.h"
extern int line_number;
%}
%option noyywrap
%%
"float" { printf("FROM FLEX FLOAT %s\n", yytext); return FLOAT; }
"int" { printf("FROM FLEX INT %s\n", yytext); return INT; }
[;] { return *yytext; }
[_a-zA-Z][_a-zA-Z0-9]* { printf("FROM FLEX IDENTIFIER: %s\n", yytext); return IDENTIFIER; }
[ \t\r]+ /* eat up whitespace */
[\n] { line_number++; }
%%
- Create a file called "simple.y" in "c:\temp":
%{
#include
#include "simple_shared.h"
#define YYSTYPE char *
int yydebug=1;
int indent=0;
char *iden_dum;
%}
%token FLOAT
%token INT
%token IDENTIFIER
%% /* Grammar rules and actions follow */
declaration:
type_specifier identifier_dum ';'
{ printf("%3d: FROM BISON declaration\n", line_number); }
;
type_specifier:
FLOAT
{ printf("%3d: FROM BISON FLOAT\n", line_number); }
| INT
{ printf("%3d: FROM BISON INT\n", line_number); }
;
identifier_dum:
IDENTIFIER
{ iden_dum = $1; printf("%3d: IDENTIFIER: %s\n", line_number, &iden_dum); }
;
%%
main ()
{
yyparse ();
}
- Create a file called "simple_shared.h" in "c:\temp":
int line_number=1;
- Create a file called "Makefile" in "c:\temp":
simple: lex.yy.o simple.tab.o
gcc -o simple $^
simple.tab.h: simple.y
bison --debug --verbose -d simple.y
simple.tab.c: simple.y
bison -d simple.y
lex.yy.c: simple.flex simple.tab.h
flex simple.flex - Create a file called "input.c" in "c:\temp":
- Open a Cygwin bash shell.
- "cd /cygdrive/c/temp"
- "make"
- "./simple.exe < input.c"
float variable;
You should get some output like this:
$ ./simple.exe < input.c
Starting parse
Entering state 0
Reading a token: FROM FLEX FLOAT float
Next token is token FLOAT ()
Shifting token FLOAT ()
Entering state 1
Reducing stack by rule 2 (line 21):
$1 = token FLOAT ()
1: FROM BISON FLOAT
-> $$ = nterm type_specifier ()
Stack now 0
Entering state 4
Reading a token: FROM FLEX IDENTIFIER: variable
Next token is token IDENTIFIER ()
Shifting token IDENTIFIER ()
Entering state 6
Reducing stack by rule 4 (line 27):
$1 = token IDENTIFIER ()
1: IDENTIFIER:
-> $$ = nterm identifier_dum ()
Stack now 0 4
Entering state 7
Reading a token: Next token is token ';' ()
Shifting token ';' ()
Entering state 8
Reducing stack by rule 1 (line 17):
$1 = nterm type_specifier ()
$2 = nterm identifier_dum ()
$3 = token ';' ()
1: FROM BISON declaration
-> $$ = nterm declaration ()
Stack now 0
Entering state 3
Reading a token: Now at end of input.
Stack now 0 3
Cleanup: popping nterm declaration ()
No comments:
Post a Comment