Spirit: Parser Combinators for C++

I was thinking of writing a parser combinator library for C++ today so that I could write a C++ parser in a style similar to using Daan Leijen’s awesome Parsec Haskell library. Then, I came across Spirit, part of the excellent C++ Boost libraries. Of course, they’re advertised as template-based parsers rather than parser combinator-based parsers, since C++ programmers will go blank in the face when you say ‘parser combinators’. If you’re not familiar with parser combinators, here should be all the motivation you need for using Spirit, from its introduction page:

A simple EBNF grammar snippet:

    group       ::= '(' expression ')'
    factor      ::= integer | group
    term        ::= factor (('*' factor) | ('/' factor))*
    expression  ::= term (('+' term) | ('-' term))*

is approximated using Spirit's facilities as seen in this code snippet:

    group       = '(' >> expression >> ')';
    factor      = integer | group;
    term        = factor >> *(('*' >> factor) | ('/' >> factor));
    expression  = term >> *(('+' >> term) | ('-' >> term));

Mapping an EBNF directly on to the language syntax: ahh, so good. If only more people realised that the whole embedded domain-specific language approach is so nice!

blog comments powered by Disqus