Why does this nabialek trick not work in my simple grammar with boost::spirit::qi

38 views Asked by At

I want to parse command line arguments with boost::spirit. Instead of listing all possible commands in an or combination it seems more elegant to use a symbol table.

Now I started very simple (lets assume I only have 2 possible commands that do not consume any arguments) and I am already stuck.

I read about the nabialek trick that is also listed in the boost examples and I tried:

#include <boost/spirit/home/qi/nonterminal/rule.hpp>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

template <typename Tag>
struct GenericCommand
{};

namespace tag {
    struct none
    {};
    struct stop
    {};
    struct limit
    {};
} // namespace tag

using None = GenericCommand<tag::none>;
using Stop = GenericCommand<tag::stop>;
using Limit = GenericCommand<tag::limit>;

using Command = std::variant<None, Stop, Limit>;

struct Grammar :
  qi::grammar<std::string::const_iterator, Command (), qi::ascii::space_type>
{
    using Iterator = std::string::const_iterator;
    using Skipper = qi::ascii::space_type;

    Grammar ();

    using Rule = qi::rule<Iterator, Command (), Skipper>;

    qi::symbols<char, const Rule*> commands;
    qi::rule<Iterator, Command (), Skipper> command;
    qi::rule<Iterator, Stop (), Skipper> stop_;
    qi::rule<Iterator, Limit (), Skipper> limit_;

    Rule parse, stop, limit, rest;

    struct SetRest
    {
        explicit SetRest (Rule& rule) : rule {rule} {}

        void operator() (Rule* real_rule) const { rule = *real_rule; }

        Rule& rule;
    };
};

Grammar::Grammar () : Grammar::base_type {parse}
{
    using namespace qi;

    parse = command;
    commands.add ("stop", &stop) ("limit", &limit);

    command = no_case[commands[SetRest {rest}]] >> rest;

    stop_ = eps;
    limit_ = eps;

    stop = stop_;
    limit = limit_;
}

This code gives me compile errors («no matching function for call to 'do_call'») I have no clue how to interpret. Why does this not work? I don't see a conceptual difference between the example and my code. Or is it that this stopped working? The example is from an older version.

1

There are 1 answers

1
David On

Thanks to Marek I found out that I can follow the symbols with the lazy parser that uses the attribute of the symbol. And I missed to include boost/phoenix/operator.hpp. So my command rule now looks like this:

command = no_case[commands[_a = _1]] >> lazy(*_a)[_val = _1];

This works as expected.

The example showing this can be found on the boost.org Website.