I'm aware there's a reason but I haven't found a good, concise explanation as to why LEX/YACC cannot be used for C++. I am also interested to know whether LEX/YACC could be used to parse Objective C, or whether that language suffers from the same problem. (Mind you I mean ObjC, not Obj-C++.) Thanks.
-
http://stackoverflow.com/q/1961604/139010 – Matt Ball May 07 '13 at 03:04
-
3It's just the wrong tool for the job. YACC is an [LALR parser](http://en.wikipedia.org/wiki/LALR_parser) and C++ really needs a [recursive descent parser](http://en.wikipedia.org/wiki/Recursive_descent_parser). You can probably put a screw in with a hammer, but the result won't be pretty and it will take a lot of extra work. – David Schwartz May 07 '13 at 03:14
-
1@DavidSchwartz: C++ does not *need* a recursive descent parser. It can be implemented with almost any parser technology. The question is, "how much hacking?". – Ira Baxter May 07 '13 at 07:08
-
1@DavidSchwartz: You're the one making the (incorrect) assertion that C++ *needs* recursive descent. Doing it with recursive descent isn't exactly pretty. A GLR solution is much prettier and easier, and has zero hacking. – Ira Baxter May 07 '13 at 07:33
1 Answers
It is certainly possible to use lex and yacc to parse c++, but you need a lot of other machinery as well. At one time, gcc used a yacc-based parser, but it was replaced with a hand-built recursive descent parser which is believed to be easier to maintain, and which makes generating meaningful syntax errors simpler. clang uses a hand-built recursive descent parser for much the same reason.
Bison can build GLR parsers, which makes it a lot easier to explore alternative parses (necessary for disambiguation rules). See Ira Baxter's answer to Are GCC and Clang parsers really handwritten? for some testimony about GLR parsing of C++.
Also see the links in Matthew Slattery's answer to the same question for some background on gcc and clang; in particular, a summary of costs and benefits perceived in 2008 for replacing the old yacc parser in gcc is found on the gcc wiki (link copied from Matthew Slattery).
-
1When gcc people say something is easier to maintain, that should be taken with a large sodium pellet. – Kaz Jun 09 '13 at 05:07