Search code examples
c++boostboost-spiritboost-spirit-qi

qi::rule<It, std::string ()> doesn't parse input string


I have a strange trouble:

qi::rule <Iterator, std::string ()> str = +alnum;
// will not parse given input
//param = "WELL" >> space >> str >> ((space >> no_case[control]) || (space >> no_case[limit])) >> space >> qi::eol; 

// will parse given input ok
param = "WELL" >> space >> +alnum >> ((space >> no_case[control]) || (space >> no_case[limit])) >> space >> qi::eol; 

expression = qi::no_skip[param];

Input is "WELL name3 PROD OIL \n". control and limit are symbol tables.

What I'm doing wrong?

upd:

With BOOST_SPIRIT_QI_DEBUG defined and with BOOST_SPIRIT_DEBUG_NODE (param) before expression I got following output if str used:

<param>
  <try>WELL name3 PROD OIL </try>
Segmentation fault

In +alnum case I got:

<param>
  <try>WELL name3 PROD OIL </try>
  <success></success>
  <attributes>[]</attributes>
</param>

Backtrace:

<param>
  <try>WELL name3 PROD OIL </try>

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff64db290 in boost::function4<bool, char*&, char* const&, boost::spirit::context<boost::fusion::cons<std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, boost::fusion::nil>, boost::fusion::vector0<void> >&, boost::spirit::unused_type const&>::operator() (this=
    0x7fffffffd700, a0=@0x7fffffffd2d0, a1=@0x7fffffffda20, a2=..., a3=...)
    at /opt/libs/boost/boost/function/function_template.hpp:1013
1013                 (this->functor BOOST_FUNCTION_COMMA BOOST_FUNCTION_ARGS);

Solution

  • The problem is that you defined the rule str on the stack (as a local variable inside the constructor). This variable goes out of scope when the constructor of your grammar is exited, leaving the param rule with a dangling reference to it. If you move str to be a member variable of the grammar everything works as expected.

    Moreover, you seem to want to skip spaces in between your input elements. I'd suggest to look at the phrase_parse API and at how to use skippers.