I saw some projects require BISON to generate C++ code. What is the advantage of having BISON/Yacc etc. generate C/C++ code instead of writing it yourself?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
The most important thing about BISON and YACC is that they generate a state machine which would parse exactly your grammar. This is for speed reason, since complexity of generated code is not O(n) with n = number of rules as it would be in most first-attempt implementations.
The state machine approach causes the number of states spawned to be very high and thus it would be very error prone to write that code. Manteinance of that code would also be an hell (where hell = I would quit the job if someone suggested me to do that).
Bison and Yacc make you concentrate on the grammar instead of its implementation.
The same reason that you don't write your own hashmap, or smart pointer, or threading library. Its much better use of your time to use something that is already written and debugged that do it yourself. There will always be certain people and certain situations where the best option is to roll your own, but these are rare. Probably more rare than most people accept.
For parsers in particular, it is fairly easy to write a parser that works most of the time. It is tricky to write one that work correctly for all input, including malformed input, and is easy to modify. Its also tempting to impose some strange syntax on the input to make it east to parse, at the expense of making it harder to create input files.
For C++, I've had good results with Boost::spirit. Its a parser framework that, through the use of lots of template magic, lets you embed BNF directly into your C++ code. It has a bit of a learning curve, but once you wrap your mind around it, it make it easy to construct parsers for complex languages.
Clarity: A parser generator can use a language (say, ABNF) that is geared towards the problem, that of describing a grammar. (Some languages arguably can get away with not needing a separate language: just build a DSL in the host language.)
Ease of use: You don't have to know how to write a parser yourself. Would you use a recursive descent parser? a pack-rat parser? etc. And do you care, if you just want to parse a SIP message?
If you know the grammar you need to parse, it's much faster to get working code by simply feeding that grammar to a parser generator and use suitable call-outs from that than to hand-code a parser.
If, however, you have a poorly-described file format you need to parse, it may be about as much work to hand-roll a parser as it would be to figure out the grammar, describe it to the parser generator and then get a parser.
Hopefully, you're closer to the first paragraph than the second.