Overload the spirit grammar to use lexer or qi parsers

I am trying to write a spirit grammar component that works with a lexer (when it is part of a larger project) or simply with qi :: parsers (like int_) for testing.

Below is an example of a parser (a very detailed way to parse an int). The problem is in the function lex_int. I would like to use the second overload if the token is qi::unused_type(without the lexer) and the first for the lexer. I suggest that I should use some MPL template or technique, as it tok.integer_is a compilation error for qi::unused_type.

In addition, even with a specific USE_LEXER, it now discards the core. Embedding code with a preprocessor definition works fine, but it seems to be in the last century.

namespace qi    = boost::spirit::qi;
namespace lex   = boost::spirit::lex;

#define USE_MYINT
#define USE_LEXER

// my grammar replacing int_
template<typename Iterator, typename Skipper=qi::space_type>
struct my_int : qi::grammar<Iterator, int(), Skipper>
{
    qi::rule<Iterator, int(), Skipper> start;

    template<typename TokenDef>
    my_int(TokenDef &tok): my_int::base_type(start)
    {
        start %= lex_int(tok);
        BOOST_SPIRIT_DEBUG_NODE(start);
    }

    // overload for lexer
    template<typename TokenDef>
    decltype(start) lex_int(TokenDef &tok)
    {
        return tok.integer_;
    }

    // overload for no lexer
    // template<typename TokenDef>
    decltype(start) lex_int(qi::unused_type)
    {
        return qi::int_;
    }
};

A complete (compiled) example is given at dual_grammar.cc. This example works with USE_MYINTboth USE_LEXERdefined and undefined. The goal is automatic selection using a symbol USE_AUTO_SELECT.

+4
source share
1 answer

Just do what works, not what you like. Believe me, this will hurt you more than you can expect (including this terrifying class of errors that do not occur until your application crashes).

1: ,

, Proto , . , , ( : , , , parser::compile()).

(, lex_int) .

:)

, ( , , , , Spirit V2 , constexpr . Proto-0x, , ).

, , , Iterator - -.

, , , qi::space_type .

, . , . Qi, .

2: , [] Spirit?

, , ANTLR CoCo/R, .

+2

Source: https://habr.com/ru/post/1540285/


All Articles