Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost::Spirit result of phrase_parse

Hello everybody I am new to boost and boost::spirit, so I am sorry for noob question.

When I use qi::phrase_parsefunction, the function returns only bool variable which indicates whether parsing has been successful or not, but I don't know where I can find the result of parsing ...some sort of syntax tree etc.

If I use macro #define BOOST_SPIRIT_DEBUG XML representation of tree is printed on standard output, but these nodes has to be stored somewhere. Can you help me please?

like image 817
Michal Avatar asked Jul 19 '12 07:07

Michal


1 Answers

You can 'bind' attribute references. qi::parse, qi::phrase_parse (and related) accept variadic arguments that will be used to receive the exposed attributes.

A simplistic example is: (EDIT included a utree example too)

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_utree.hpp>

namespace qi = boost::spirit::qi;

int main()
{
    using namespace qi;

    std::string input("1 2 3 4 5");
    std::string::const_iterator F(input.begin()), f(F), l(input.end());

    std::vector<int> ints;
    if (qi::phrase_parse(f = F, l, *qi::int_, qi::space, ints))
        std::cout << ints.size() << " ints parsed\n";

    int i;
    std::string s;
    // it is variadic:
    if (qi::parse(f = F, l, "1 2 " >> qi::int_ >> +qi::char_, i, s))
        std::cout << "i: " << i << ", s: " << s << '\n';

    std::pair<int, std::string> data;
    // any compatible sequence can be used:
    if (qi::parse(f = F, l, "1 2 " >> qi::int_ >> +qi::char_, data))
        std::cout << "first: " << data.first << ", second: " << data.second << '\n';

    // using utree:
    boost::spirit::utree tree;
    if (qi::parse(f = F, l, "1 2 " >> qi::int_ >> qi::as_string [ +qi::char_ ], tree))
        std::cout << "tree: " << tree << '\n';

}

Outputs:

5 ints parsed
i: 3, s:  4 5
first: 3, second:  4 5
tree: ( 3 " 4 5" )

A few samples of parsers with 'AST' like data structures:

  • Boolean expression (grammar) parser in c++
  • Boost::Spirit Expression Parser

If you want to have a very generic AST structure, look at utree: http://www.boost.org/doc/libs/1_50_0/libs/spirit/doc/html/spirit/support/utree.html

like image 129
sehe Avatar answered Sep 21 '22 06:09

sehe