Poppy
Poppy

Reputation: 59

Why can't LEX/YACC be used to parse C++ for a compiler?

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.

Upvotes: 5

Views: 2775

Answers (1)

rici
rici

Reputation: 241671

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).

Upvotes: 2

Related Questions