How to use Boost Spirit auto rules with AST?

我们两清 提交于 2021-01-27 07:53:17

问题


EDIT: I expanded sehe's example to show the problem when I want to use it on another rule: http://liveworkspace.org/code/22lxL7$17

I'm trying to improve the performances of my Boost Spirit parser and I saw that since C++11, it was possible to use auto-rules like that:

auto comment = "/*" >> *(char_ - "*/") >> "*/"; 

(or with BOOST_AUTO or BOOST_SPIRIT_AUTO).

I have a rule declarer like that:

qi::rule<lexer::Iterator, ast::SimpleType()> simple_type;

and defined like that:

simple_type %=
        const_
    >>  lexer.identifier;

If I declare it with auto, it compiles, but it cannot be used as AST in other rules.

Is it possible to define rules creating AST with auto rules ? I'm also interested in other ways to speedup AST creation in Boost Spirit.


回答1:


First of all, I tried a simple example and "it works for me" with a simple adapted struct:

struct fixed
{
    int integral;
    unsigned fractional;
};

BOOST_FUSION_ADAPT_STRUCT(fixed, (int, integral)(unsigned, fractional));

template <typename It, typename Skipper = qi::space_type>
    struct parser : qi::grammar<It, std::vector<fixed>(), Skipper>
{
    parser() : parser::base_type(start)
    {
        using namespace qi;

        BOOST_SPIRIT_AUTO(qi, fixed_rule, lexeme [ int_ >> -('.' >> uint_ | attr(0u)) ]);
        start = *fixed_rule;

        BOOST_SPIRIT_DEBUG_NODE(start);
    }

  private:
    qi::rule<It, std::vector<fixed>(), Skipper> start;
};

This happily parses the inputs: http://liveworkspace.org/code/22lxL7$1

I think you might mean where attribute compatibility is required, and

  • attr_cast (doc)
  • as<T>(parse_expr) (doc)

should be able to help out just fine in those cases.

See this answer for more details on attr_cast (and attribute compatibility in general): String parser with boost variant recursive wrapper




回答2:


There's no such thing as an "auto rule". When you auto-capture an expression like that, you're using all of the defaults to create a rule. So the attribute of this "auto rule" will be exactly and only the attribute of the expression, with no attribute conversion.

If you need to create special attribute data (ie: you need to convert the incoming attribute type to your own data), you must either use a rule or a semantic action.



来源:https://stackoverflow.com/questions/15316848/how-to-use-boost-spirit-auto-rules-with-ast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!