Related articles |
---|
Using Bison parser with C++ code wayne.mitchinson@jennic.com (Wayne Mitchinson) (2001-05-29) |
Re: Using Bison parser with C++ code ifo@xnet.com (Fraser Orr) (2001-05-31) |
From: | "Fraser Orr" <ifo@xnet.com> |
Newsgroups: | comp.compilers |
Date: | 31 May 2001 02:46:45 -0400 |
Organization: | XNet Information Systems (Winstar) |
References: | 01-05-072 |
Keywords: | yacc, C++ |
Posted-Date: | 31 May 2001 02:46:44 EDT |
> Does anyone know of some good online examples for integrating a
> bison/yacc compiler into a C++ program. I'm new at this parser
> writing game and needless to say, the learning curve is steep.
You can simply incorporate C++ code into the bison actions. For example:
%{
// Include definition of the Abstract Syntax Tree class
#include "ASTree.h"
typedef ASTree* ASTreePtr;
#define YYSTYPE ASTreePtr
%}
%left '+' '-'
%token NUM
%%
start: expr {$1->printTree(); }
expr : expr '+' expr {$$ = new ASTree('+', $1, $2); }
| expr '-' expr {$$ = new ASTree('-', $1, $2); }
| NUM {$$ = new ASTree(NUM, atoi(yytext)); }
And so forth. (Note this might not compile exactly as is, I just typed
it out of my head, but I hope you get the general idea.)
Bison will produce a C file containing these C++ statements in the
appropriate places. You must simply tell your compiler to compile it
as a C++ file. For example, in your makefile you might do:
grammar.o : grammar.y
bison -d grammar.y -o grammar.cc
in UNIX, or in Visual C++ you would set the special build instructions
to something like:
bison -d $(InputName).y -o $(ProjDir)\$(InputName).cpp
mv "$(InputName).cpp.h" $(InputName).h
(I use mv, but you can also use ren. For some reason the .h file gets
a screwed up name. This might also be true in unix, I haven't tried.)
The bison parse table processing algorithm is already compatible with
C++.
You can then simply call yyparse as normal. If you want to incorporate
the parsing into a class, most likely you will have to build a pure
parser, as documented in the bison manual.
Note I use an out of date version of bison: 1.24, but I am sure later
versions incorporate these features.
HTH.
Return to the
comp.compilers page.
Search the
comp.compilers archives again.