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

What is the proper way to deal with deep recursion in boost::spirit::qi grammar?


I have a working grammar similar to the following:

stock_price = symbol_ >> date_ >> price_;
stock_prices_ = stock_price_ >> stock_prices_ | eps;
grammar_ = lit( "PRICES" ) >> stock_prices_ >> lit( "END" );

The problem is, when the list of stock prices_ gets too high (say around 1000 prices), the the parses seg-faults with a exc_bad_access. I can actually solve this by:

stock_prices_ = stock_price_ >> stock_price_ >> stock_price_ >> stock_price >> stock_prices_ |
                stock_price_ >> stock_prices_ |
                eps;

but I don't see this as an elegant solution. Is there a better solution?


Solution

  • I might be completely missing the problem here, but what wrong with the kleene star, plus parser and or list parser directives?

    stock_prices_ = +stock_price_ | eps; // one or more stock_price_ or nothing
    

    However, this looks to be exactly the semantics of just kleene star:

    stock_price = symbol_ >> date_ >> price_;
    grammar_    = "PRICES" >> *stock_price_ >> "END"; // zero or more stock_price_
    

    Now, if you wanted them line-separated e.g., use1:

    grammar_    = "PRICES" >> -(stock_price_ % eol) >> "END";
    

    1 combine with e.g. the qi::blank skipper, which doesn't eat the newlines