Where can I find standard BNF or YACC grammar for C++ language?

Kevin Yu picture Kevin Yu · Mar 5, 2009 · Viewed 16.4k times · Source

I'm trying to work on a kind of code generator to help unit-testing an legacy C/C++ blended project. I don't find any kind of independent tool can generate stub code from declaration. So I decide to build one, it shouldn't be that hard.

Please, anybody can point me a standard grammar link, better described by yacc language.

Hope I'm not reinventing wheel, please help me out in that case.

Best Regards, Kevin

Answer

Jared Oberhaus picture Jared Oberhaus · Mar 5, 2009

From the C++ FAQ Lite:

38.11 Is there a yacc-able C++ grammar?

The primary yacc grammar you'll want is from Ed Willink. Ed believes his grammar is fully compliant with the ISO/ANSI C++ standard, however he doesn't warrant it: "the grammar has not," he says, "been used in anger." You can get the grammar without action routines or the grammar with dummy action routines. You can also get the corresponding lexer. For those who are interested in how he achieves a context-free parser (by pushing all the ambiguities plus a small number of repairs to be done later after parsing is complete), you might want to read chapter 4 of his thesis.

There is also a very old yacc grammar that doesn't support templates, exceptions, nor namespaces; plus it deviates from the core language in some subtle ways. You can get that grammar here or here.