0

I'm trying to write a parser using flex++ and bison. I need the parser to be able to read from a file and write a new file in output.

I have an yyFlexLexer instantiated as follows:

yyFlexLexer lexer;

and I use it:

int main(int argc, char* argv[])
{
    std::istream* in_file = new std::ifstream(argv[1])
    std::ostream* out_file = new std::ofstream(argv[2])
    lexer.switch_streams(in_file, out_file);
    yyparse();
    return 0;
}

If I run:

./executable foo bar

the parser correctly read the file foo (I can see it making some printing in bison rules) but at the end I found only an empty file called "bar" without anything in it.

I have also tried to do this:

int main(int argc, char* argv[])
{
    std::istream* in_file = new std::ifstream(argv[1])
    std::ostream* out_file = new std::ofstream(argv[2])
    lexer.switch_streams(in_file, out_file);
    while(lexer.yylex())
    ;
    return 0;
}

but it does the same thing.

Sebastiano Merlino
  • 1,273
  • 12
  • 23

1 Answers1

2

You need the parser's actions (in your .y file) to build some abstract syntax tree of the parsed input, and you need some routine to pretty print that tree to the output.

flex and bison do only the parsing (which is not much). You should do the rest.

I don't understand what you want to achieve.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I realized all rules for my syntax. I was thinking that the out_file passed to the yyFlexLexer was used by the parser to print the output. If not, I don't understand for what is used the output stream passed to the method switch_streams. – Sebastiano Merlino Nov 06 '11 at 10:58
  • Documentation http://flex.sourceforge.net/manual/Cxx.html says that "virtual void switch_streams(istream* new_in = 0, ostream* new_out = 0) reassigns yyin to new_in (if non-null) and yyout to new_out (if non-null), deleting the previous input buffer if yyin is reassigned.". But I think you don't understand how to use Flex and Bison. Please explain your overall goal. – Basile Starynkevitch Nov 06 '11 at 11:09
  • I explain better the question. I have already realized the parser. It works fine while I print the output to stdout (the complete output obtained at the end of the execution of all rules). I was only supposing that the method switch_stream is used to redirect the output from the stdout to a custom stream. At this moment I'm also able to write to a custom stream writing on it in my terminal rule. Reading the documentaion it seems to me that the function will do what I think but evidently not. – Sebastiano Merlino Nov 06 '11 at 11:20