help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

A simple example of using bison++ and flex++


From: Belaid MOA
Subject: A simple example of using bison++ and flex++
Date: Sun, 27 Mar 2005 20:14:52 +0000

Dear All,

I noticed that there is an interest in having an example of using bison++ and flex++. I also noticed that there is no concrete example in the web (from my search). For this reason, this an example of how to use bison++ and flex++.

I am using bison++ Version 1.21-8 and flex++ version 2.5.4.

The files are:

============================================================
file name: parser.y

%name Parser
%define LSP_NEEDED
%define MEMBERS                 \
    virtual ~Parser()   {} \
    private:                   \
       yyFlexLexer lexer;
%define LEX_BODY {return lexer.yylex();}
%define ERROR_BODY {cerr << "error encountered at line: "<<lexer.lineno()<<" last word parsed:"<<lexer.YYText()<<"\n";}

%header{
#include <iostream>
#include <fstream>
#include <FlexLexer.h>
using namespace std;
%}

%union {
       int i_type;
}

%token UNKNOWN
%token <i_type> NUMBER

%type <i_type> number

%start number

%%
number
: NUMBER { $$ = atoi(lexer.YYText());std::cout << "Parser value "<<$$<<std::endl;}
;

%%
====================================================================
file name: scanner.l
%option c++
%option noyywrap

%{
#include<sstream>
#include "parser.h"
#include <cstdlib>
//YY_CalcParser_STYPE val;
%}

DIGIT   [0-9]
DIGIT1  [1-9]

%%

{DIGIT1}{DIGIT}*  {
                  std::cout <<"Lexer: "<< yytext <<std::endl;
                  return Parser::NUMBER;
                 }
.                 {
                   return Parser::UNKNOWN;
                 }
<<EOF>>           {
                   yyterminate();
                 }

%%
======================================================================
file name: test.cpp
#include "parser.h"
#include <iostream>
using namespace std;
int main(int argc, char ** argv)
{
       Parser parser;
       parser.yyparse();
       return 0;
}
======================================================================

To generate cpp files use:
1. bison++ -d -hparser.h -o parser.cpp parser.y
2. flex++ -d -oscanner.cpp scanner.l

To compile the files user:
1. g++ -c parser.cpp
2. g++ -c scanner.cpp
3. g++ -c test.cpp

To link them all
1. g++ -o test test.o parser.o scanner.o

To test your parser/lexer use
1. echo "12345" | ./test

For more information about options and declarations in flex++ and bison++, the man of flex++ and
bison++ is an excellent source for that.

With best regards.
Belaid Moa.






reply via email to

[Prev in Thread] Current Thread [Next in Thread]