5

我正在寻找实现可变参数函数的最简单方法,该函数采用 boost::spirit::qi 规则列表并将列表扩展为格式的表达式:rule1 | 规则2 | rule3 |.... 假设规则不合成任何属性。非常感谢您的帮助。

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iostream>
#include <boost/spirit/include/phoenix_operator.hpp>

namespace qi    = boost::spirit::qi;
namespace ph    = boost::phoenix;
namespace ascii = boost::spirit::ascii;
using boost::spirit::qi::phrase_parse;
using boost::spirit::qi::ascii::space;
using boost::spirit::iso8859_1::char_;

typedef qi::rule<std::string::const_iterator,ascii::space_type> mrule_t;
typedef qi::rule< std::string::const_iterator,std::string() >   wrule_t;

//How to deduce expandBitwise() return type ?

template<typename T>
T expandBitwise(T& t)
{
    return t.rule_;
}

template<typename T,typename ...Tail>
T expandBitwise(T& t,Tail& ...tail)
{
    return t.rule_ | expandBitwise(tail...);
}

struct TStruct
{
    mrule_t     rule_;
    template<typename T,typename R>
    TStruct( T& rVar,const std::string&name, R& rule ) :
        rule_( qi::lit( name ) >> rule[ ph::ref( rVar )=qi::_1 ] )
        {}
};

template<typename T,typename ...Tail>
void mparse(const std::string& line,T& t,Tail& ...tail)
{
    std::string::const_iterator f,l;

    f=line.begin();
    l=line.end();

    // I would like to expand the rules here ...
    //if(phrase_parse(f,l,expandBitwise(t,tail...),space ) && f==l)

    if( phrase_parse(f, l, t.rule_, space ) && f==l )
        std::cout<<"Parsed:"<<line<<std::endl;
    else
        std::cout<<"Syntax error:"<<line<<std::endl;
}

int main()
{
    wrule_t rword=+~space;

    std::string par1,par2,par3,par4;

    TStruct r1( par1,"-a", rword );
    TStruct r2( par2,"-b", rword );
    TStruct r3( par3,"-c", rword );
    TStruct r4( par4,"-d", rword );

    mparse("abc 8.81"   ,r1,r2,r3,r4);
    mparse("-a atoken"  ,r1,r2,r3,r4);
    mparse("-b btoken"  ,r1,r2,r3,r4);
    mparse("-c ctoken"  ,r1,r2,r3,r4);
    mparse("-d dtoken"  ,r1,r2,r3,r4);

    return 0;
}
4

2 回答 2

5

感谢您的快速提示!我刚刚尝试了你的代码,除非我做错了什么......我得到这个输出:Syntax error:abc 8.81 Parsed:-a atoken Syntax error:-b btoken Syntax error:-c ctoken Syntax error:-d dtoken - G. Civardi 2 小时前

好的,所以,我不能不管它:/

原来涉及到未定义的行为,因为解析器表达式被传递expandBitwise和被复制的方式:Boost Proto 表达式模板不是被设计为被复制的,因为它们可能包含对临时对象的引用,其生命周期在结束时结束它们包含完整的表达。

有关更多背景信息,请参阅2 秒内零到 60 MPH 的讨论!

经过长时间(长时间)的调整,rule_.alias()boost::proto::deepcopy已经达到了以下解决方案(顺便说一下,它不再需要辅助函数了):

template<typename ...Tail>
void mparse(const std::string& line,Tail& ...tail)
{
    auto parser = boost::fusion::fold(
                boost::tie(ph::bind(&TStruct::rule_, arg1)(tail)...),
                qi::eps(false),
                deepcopy_(arg2 | arg1)
            );

    auto f=begin(line), l=end(line);

    if( qi::phrase_parse(f, l, parser, ascii::space ) )
        std::cout << "Parsed:" << line << std::endl;
    else
        std::cout << "Syntax error:" << line << std::endl;

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

针对 UB 的保护是deepcopy_()调用,它是一个简单的多态可调用适配器boost::proto::deepcopy

struct DeepCopy
{
    template<typename E> struct result { typedef typename boost::proto::result_of::deep_copy<E>::type type; };

    template<typename E>
        typename result<E>::type
        operator()(E const& expr) const {
            return boost::proto::deep_copy(expr);
        }
};

static const ph::function<DeepCopy> deepcopy_;

使用此代码,你瞧,输出变为:

Syntax error:abc 8.81
Remaining unparsed: 'abc 8.81'
Parsed:-a atoken
Parsed:-b btoken
Parsed:-c ctoken
Parsed:-d dtoken
Bye

作为奖励,代码现在允许您使用 Spirit 的内置 debug() 功能(取消注释该行):

<-d>
  <try>abc 8.81</try>
  <fail/>
</-d>
<-c>
  <try>abc 8.81</try>
  <fail/>
</-c>
<-b>
  <try>abc 8.81</try>
  <fail/>
</-b>
<-a>
  <try>abc 8.81</try>
  <fail/>
</-a>
Syntax error:abc 8.81
Remaining unparsed: 'abc 8.81'

经测试

  • 升压 1_54_0
  • GCC 4.7.2、4.8.x、Clang 3.2
  • 注意#define重要的 s。

完整代码

#define BOOST_RESULT_OF_USE_DECLTYPE
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/fusion/adapted/boost_tuple.hpp>
#include <boost/fusion/include/fold.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace qi    = boost::spirit::qi;
namespace ph    = boost::phoenix;
namespace ascii = boost::spirit::ascii;
using namespace ph::arg_names;

typedef qi::rule<std::string::const_iterator,ascii::space_type> mrule_t;
typedef qi::rule<std::string::const_iterator,std::string() >    wrule_t;

struct TStruct
{
    mrule_t     rule_;
    template<typename T,typename R>
    TStruct( T& rVar,const std::string&name, R& rule ) :
        rule_( qi::lit(name) >> rule[ ph::ref(rVar) = qi::_1 ] )
    { 
        rule_.name(name);
        // debug(rule_);
    }
};

struct DeepCopy
{
    template<typename E> struct result { typedef typename boost::proto::result_of::deep_copy<E>::type type; };

    template<typename E>
        typename result<E>::type
        operator()(E const& expr) const {
            return boost::proto::deep_copy(expr);
        }
};

static const ph::function<DeepCopy> deepcopy_;

template<typename ...Tail>
void mparse(const std::string& line,Tail& ...tail)
{
    auto parser = boost::fusion::fold(
                boost::tie(ph::bind(&TStruct::rule_, arg1)(tail)...),
                qi::eps(false),
                deepcopy_(arg2 | arg1)
            );

    auto f=begin(line), l=end(line);

    if( qi::phrase_parse(f, l, parser, ascii::space ) )
        std::cout << "Parsed:" << line << std::endl;
    else
        std::cout << "Syntax error:" << line << std::endl;

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

int main()
{
    wrule_t rword=+~ascii::space;

    std::string par1,par2,par3,par4;

    TStruct r1( par1, "-a", rword );
    TStruct r2( par2, "-b", rword );
    TStruct r3( par3, "-c", rword );
    TStruct r4( par4, "-d", rword );

    mparse("abc 8.81"   ,r1,r2,r3,r4);
    mparse("-a atoken"  ,r1,r2,r3,r4);
    mparse("-b btoken"  ,r1,r2,r3,r4);
    mparse("-c ctoken"  ,r1,r2,r3,r4);
    mparse("-d dtoken"  ,r1,r2,r3,r4);

    std::cout << "Bye\n";
}
于 2013-04-24T00:44:23.823 回答
2

您不小心从帮助程序返回了 TStruct 类型expandBitwise。像这样修复它:

template<typename T>
auto expandBitwise(T const& t) -> decltype(t.rule_)
{
    return t.rule_;
}

template<typename T,typename ...Tail>
auto expandBitwise(T const& t,Tail const&... tail) -> decltype(t.rule_)
{
    return t.rule_ | expandBitwise(tail...);
}

如果要公开属性,则返回类型推导规则变得更加复杂。基本上,您所做的是复制 Spirit 的 EDSL 部分。


让我们交换故事...

Clippy: 看起来您正在尝试编写命令行参数解析器。你需要帮助吗?

通过创建一个新的 Proto Domain 并实际创建终端,可以更系统地为您的选项解析器实现 DSL 机制。现在这会以某种方式吸引我。

或者,您可以使用Nabialek Trick完全从另一个角度看待这个问题。这恰好是我几周前使用的一种方法,我将与您分享我提出的设计: https ://gist.github.com/sehe/2a556a8231606406fe36#file-test-cpp

重要的部分是,语法是“固定的”:

start    = -argument % '\0';
unparsed = as_string  [ +~nul ] [ std::cerr << phx::val("ignoring unparsed argument: '") << _1 << "'\n" ];
argument = ('-' >> +shortopt) | ("--" >> longopt) >> -unparsed | unparsed;

诀窍在于:

shortopt = shortNames [_a = _1] >> lazy(_a);
longopt  = longNames  [_a = _1] >> lazy(_a);

WhereshortNameslongNamesqi::symbols解析器表,动态构建,基于和的可变参数列表CliOptionsCliFlags我将它们作为元组传递,因为我也想将结果存储在CliOption结构中)。

qi::lazy(_a)调用存储在符号表中的解析器。

作为奖励,我的 CliOptions 解析器还具有生成“使用”信息的功能。解析表达式的构建器以及使用信息是可扩展的。

int main(int argc, char* argv[])
{
    using CliParsing::make_option;

    typedef std::string::const_iterator It;

    auto config = std::make_tuple(
        make_option('a', "absolutely", "absolutely"),
        make_option('b', "borked"    , "borked")    ,
        make_option('c', "completion", "completion"),
        make_option('d', "debug",      "turn on debugging"),
        make_option('e', "",           "no long name")  ,
        //make_option('f', "flungeons" , "flungeons") ,
        //make_option('g', "goofing"   , "")   ,
        //make_option('m', "monitor",    "monitoring level"),
        make_option('t', "testing"   , "testing flags"),
        make_option('\0',"file"      , "with a filename (no short name)"),

        make_option('y', "assume-yes", "always assume yes"),
        make_option('v', "verbose",    "increase verbosity level"),
        make_option('i', "increment",  "stepsize to increment with", 5)
        );

    CliParsing::OptionGrammar<It> parser(config);

    using namespace phx::arg_names;
    const auto cmdline = std::accumulate(argv+1, argv+argc, std::string(), arg1 + arg2 + '\0');

    bool ok = qi::parse(begin(cmdline), end(cmdline), parser);

    std::cout << "Parse success " << std::boolalpha << ok << "\n";
    std::cout << parser.getUsage();

    return ok? 0 : 255;
}

当使用一些随机参数调用时-i 3 --completion -t --file=SOME.TXT -b huh?,打印:

short form option --increment parsed
ignoring unparsed argument: '3'
long form switch --completion parsed
short form switch --testing parsed
long form switch --file parsed
ignoring unparsed argument: '=SOME.TXT'
short form switch --borked parsed
ignoring unparsed argument: 'huh?'

Parse success true
 --absolutely (-a)
    absolutely (flag)
 --borked (-b)
    borked (flag)
 --completion (-c)
    completion (flag)
 --debug (-d)
    turn on debugging (flag)
 -e
    no long name (flag)
 --testing (-t)
    testing flags (flag)
 --file
    with a filename (no short name) (flag)
 --assume-yes (-y)
    always assume yes (flag)
 --verbose (-v)
    increase verbosity level (flag)
 --increment (-i)
    stepsize to increment with (option with value; default '5')

如您所见,并非所有选项都已实现(特别是--标记选项列表的末尾)。

于 2013-04-23T21:33:07.440 回答