Spirit Parser Framework

The Spirit Parser Framework is an object oriented recursive descent parser generator framework implemented using template metaprogramming techniques. Expression templates allow users to approximate the syntax of extended Backus–Naur form (EBNF) completely in C++. Parser objects are composed through operator overloading and the result is a backtracking LL(∞) parser that is capable of parsing rather ambiguous grammars.

Spirit can be used for both lexing and parsing, together or separately.

This framework is part of the  Boost libraries.

Operators 

Because of limitations of the C++ language, the syntax of Spirit has been designed around the operator precedences of C++, while bearing resemblance to both EBNF and regular expressions.

Example 
This example shows how to use an inline parser expression with a semantic action.

#include <string>
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
 
int main()
{
  namespace qi = boost::spirit::qi;

  std::string input;
 
  std::cout << "Input a line: \n";
  getline(std::cin, input);
  std::cout << "Got '" << input << "'.\n";
 
  unsigned count = 0;
  /*  
      Next, parse the input (input.c_str()),
      using a parser constructed with the following semantics:
 
      Zero or more occurrences of (
          literal string "cat" (when matched, increment the counter "count")
      or  any character (which will be skipped)
      )

     The parser is constructed by the compiler using operator overloading and
     template matching, so the actual work is done within qi::parse(), and the
     expression starting with * only initializes the rule object that the parse
     function uses.

  */
  auto rule = *(qi::lit("cat") [ ++qi::_val ] | qi::omit[qi::char_]);
  qi::parse(input.begin(), input.end(), rule, count);
  

  // Finally, show results.
  std::cout << "The input contained " << count << " occurrences of 'cat'\n";
}

External links
Spirit parser framework SourceForge page
Documentation in the Boost project
Article on Spirit by designer Joel de Guzman in Dr. Dobb's Journal

Category:Parser generators