5

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?

Michal
  • 1,955
  • 5
  • 33
  • 56

1 Answers1

9

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:

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

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633