Search code examples
c++boost-spirit

boost::spirit optional parsing into a fusion adapted structure


If there's a structure

struct price
{
   int chicken;
   int cow;
   bool in_stock;
   std::string place;
};

which is adapted using boost::fusion. If there's a need to parse it, but optionally for in_stock and place. e.g.

template <typename it, typename skipper = qi::space_type>
struct p : qi::grammar<it, price(), skipper>
{
    p() : p::base_type(p_instance)
    {
        using namespace qi;
        psr %= int_ > int_ > -bool_ > -('"' > char_ % ',' > '"');
    }
  private:
      qi::rule<it,price(),skipper> limit;
};

However, this does not work. There's an exception thrown, if an input is "2 3 \"Chili\"". What is a solution?


Solution

  • Firstly

    I guess you're having a few too many > expectation points, which could/should be >> sequence operators.

    I'd say, make your grammar more explicit, e.g. by saying

    bool_ | attr(false)
    

    to ensure that if bool_ fails, there will be a resulting attribute value of false exposed. This way, the exposed attribute is bool, instead of boost::optional<bool>, which is more compatible with the target struct (price).

    Demo:

    template <typename It, typename Skipper = qi::space_type>
        struct parser : qi::grammar<It, price(), Skipper>
    {
        parser() : parser::base_type(start)
        {
            using namespace qi;
    
            in_stock = bool_ | attr(false);
            start    = int_ > int_ > in_stock > -('"' >> char_ % ',' > '"');
        }
    
      private:
        qi::rule<It, price(), Skipper> start;
        qi::rule<It, bool()> in_stock;
    };
    

    Secondly

    Then,

    ('"' > char_ % ',' > '"')
    

    will only ever match string like "a", "b,c,d" etc. If you wanted "Chili" to parse, you should probably change it to something like:

        place    = '"' >> *~char_('"') > '"';
        start    = int_ > int_ > in_stock > (place | attr(""));
    

    Which means parse any string delimited by '"' (~char_("abc) means: any char except [abc]).

    Sample solution

    Here's a full demonstration showing:

    • Fusion adaptation of the struct
    • the above adjusted grammar
    • using BOOST_SPIRIT_DEBUG to debug
    • catching qi::expectation_failure to print diagnostics on parse failure
    • using Spirit Karma to print the result of parsing in human readable form

    Output of test program listed below:

    Code

    #define BOOST_SPIRIT_DEBUG
    #include <boost/fusion/adapted/struct.hpp>
    #include <boost/spirit/include/qi.hpp>
    #include <boost/spirit/include/karma.hpp>
    
    namespace qi    = boost::spirit::qi;
    namespace karma = boost::spirit::karma;
    namespace phx   = boost::phoenix;
    
    struct price
    {
        int chicken;
        int cow;
        bool in_stock;
        std::string place;
    };
    
    BOOST_FUSION_ADAPT_STRUCT(price, 
            (int, chicken)
            (int, cow)
            (bool, in_stock)
            (std::string, place))
    
    template <typename It, typename Skipper = qi::space_type>
        struct parser : qi::grammar<It, price(), Skipper>
    {
        parser() : parser::base_type(start)
        {
            using namespace qi;
    
            in_stock = bool_ | attr(false);
    #if 0
            start    = int_ > int_ > in_stock > -('"' >> char_ % ',' > '"');
    #else
            place    = '"' >> *~char_('"') > '"';
            start    = int_ > int_ > in_stock > (place | attr(""));
    #endif
    
            BOOST_SPIRIT_DEBUG_NODE(start);
            BOOST_SPIRIT_DEBUG_NODE(place);
            BOOST_SPIRIT_DEBUG_NODE(in_stock);
        }
    
      private:
        qi::rule<It, price(), Skipper> start;
        //
        qi::rule<It, bool()>            in_stock;
        qi::rule<It, std::string()>     place; // no skipper
    };
    
    bool doParse(const std::string& input)
    {
        typedef std::string::const_iterator It;
        auto f(begin(input)), l(end(input));
    
        parser<It, qi::space_type> p;
        price data;
    
        try
        {
            bool ok = qi::phrase_parse(f,l,p,qi::space,data);
            if (ok)   
            {
                std::cout << "parse success: '" << input << "'\n";
                std::cout << "data: " << karma::format_delimited(karma::eps <<
                        "chicken:"  << karma::int_  << 
                        "cow:"      << karma::int_  << 
                        "in_stock:" << karma::bool_ << 
                        "place:"    << karma::auto_,
                        " ", data) << "\n";
            }
            else      std::cerr << "parse failed: '" << std::string(f,l) << "'\n";
    
            if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
            return ok;
        } catch(const qi::expectation_failure<It>& e)
        {
            std::string frag(e.first, e.last);
            std::cerr << e.what() << "'" << frag << "'\n";
        }
    
        return false;
    }
    
    int main()
    {
        doParse("1 2 true \"a,b,c,d,e,f\"");
        doParse("3 4 \"a,b,c,d,e,f\"");
        doParse("5 6");
        doParse("7 8 false");
    }
    

    Output

    <start>
      <try>1 2 true "a,b,c,d,e,</try>
      <in_stock>
        <try>true "a,b,c,d,e,f"</try>
        <success> "a,b,c,d,e,f"</success>
        <attributes>[1]</attributes>
      </in_stock>
      <place>
        <try>"a,b,c,d,e,f"</try>
        <success></success>
        <attributes>[[a, ,, b, ,, c, ,, d, ,, e, ,, f]]</attributes>
      </place>
      <success></success>
      <attributes>[[1, 2, 1, [a, ,, b, ,, c, ,, d, ,, e, ,, f]]]</attributes>
    </start>
    parse success: '1 2 true "a,b,c,d,e,f"'
    data:  chicken: 1 cow: 2 in_stock: true place: a,b,c,d,e,f 
    <start>
      <try>3 4 "a,b,c,d,e,f"</try>
      <in_stock>
        <try>"a,b,c,d,e,f"</try>
        <success>"a,b,c,d,e,f"</success>
        <attributes>[0]</attributes>
      </in_stock>
      <place>
        <try>"a,b,c,d,e,f"</try>
        <success></success>
        <attributes>[[a, ,, b, ,, c, ,, d, ,, e, ,, f]]</attributes>
      </place>
      <success></success>
      <attributes>[[3, 4, 0, [a, ,, b, ,, c, ,, d, ,, e, ,, f]]]</attributes>
    </start>
    parse success: '3 4 "a,b,c,d,e,f"'
    data:  chicken: 3 cow: 4 in_stock: false place: a,b,c,d,e,f 
    <start>
      <try>5 6</try>
      <in_stock>
        <try></try>
        <success></success>
        <attributes>[0]</attributes>
      </in_stock>
      <place>
        <try></try>
        <fail/>
      </place>
      <success></success>
      <attributes>[[5, 6, 0, []]]</attributes>
    </start>
    parse success: '5 6'
    data:  chicken: 5 cow: 6 in_stock: false place:  
    <start>
      <try>7 8 false</try>
      <in_stock>
        <try>false</try>
        <success></success>
        <attributes>[0]</attributes>
      </in_stock>
      <place>
        <try></try>
        <fail/>
      </place>
      <success></success>
      <attributes>[[7, 8, 0, []]]</attributes>
    </start>
    parse success: '7 8 false'
    data:  chicken: 7 cow: 8 in_stock: false place: