gpt4 book ai didi

c++ - 当某些结构字段被省略或顺序与结构声明中的顺序不同时,如何实现正确的解析?

转载 作者:太空狗 更新时间:2023-10-29 20:42:11 28 4
gpt4 key购买 nike

所以我有一个解析器,可以将 7.5*[someAlphanumStr]7.5[someAlphanumStr] 之类的字符串解析到这个结构中:

struct summand {
float factor;
std::string name;
summand(const float & f):factor(f), name(""){}
summand(const std::string & n):factor(1.0f), name(n){}
summand(const float & f, const std::string & n):factor(f), name(n){}
summand():factor(0.0f), name(""){}
};

但除此之外,我还需要能够解析像 [someAlphanumStr]*7.4[someAlphanumStr]57.4 这样的字符串>[someAlphanumStr]。在最后两种情况下(7.4[someAlphanumStr])我想为省略的字段设置默认值,为此我为我的结构编写了 summand 具有一个参数的构造函数。

下面是我的代码和它产生的结果:

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

#include <iostream>
#include <string>
#include <vector>

namespace client
{
namespace spirit = boost::spirit;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

struct summand {
float factor;
std::string name;
summand(const float & f):factor(f), name(""){}
summand(const std::string & n):factor(1.0f), name(n){}
summand(const float & f, const std::string & n):factor(f), name(n){}
summand():factor(0.0f), name(""){}
};
}

BOOST_FUSION_ADAPT_STRUCT(client::summand,
(float, factor)
(std::string, name)
)

namespace client {

template <typename Iterator>
struct summand_parser : qi::grammar<Iterator, summand(), ascii::space_type>
{
summand_parser() : summand_parser::base_type(summand_rule)
{
using namespace ascii;

summand_rule %= (qi::float_ >> -qi::lit('*') >> '[' >> qi::lexeme[alpha >> *alnum] >> ']')|('[' >> qi::lexeme[alpha >> *alnum] >> ']' >> -qi::lit('*') >> qi::float_)|(qi::float_)|('[' >> qi::lexeme[alpha >> *alnum] >> ']');

}

qi::rule<Iterator, summand(), ascii::space_type> summand_rule;
};
}

void parseSummandsInto(std::string const& str, client::summand& summands)
{
typedef std::string::const_iterator It;
static const client::summand_parser<It> g;

It iter = str.begin(),
end = str.end();

bool r = phrase_parse(iter, end, g, boost::spirit::ascii::space, summands);

if (r && iter == end)
return;
else
throw "Parse failed";
}

int main()
{
std::vector<std::string> inputStrings = {"7.5*[someAlphanumStr]", "7.5[someAlphanumStr]", "[someAlphanumStr]*7.4", "[someAlphanumStr]5", "7.4", "[someAlphanumStr]"};

std::for_each(inputStrings.begin(), inputStrings.end(), [&inputStrings](std::string & inputStr) {
client::summand parsed;
parseSummandsInto(inputStr, parsed);
std::cout << inputStr << " -> " << boost::fusion::as_vector(parsed) << std::endl;
});
}

结果(Coliru):

+ clang++ -std=c++11 -O0 -Wall -pedantic main.cpp
+ ./a.out
+ c++filt -t
7.5*[someAlphanumStr] -> (7.5 someAlphanumStr)
7.5[someAlphanumStr] -> (7.5 someAlphanumStr)
[someAlphanumStr]*7.4 -> (115 )
[someAlphanumStr]5 -> (115 )
7.4 -> (7.4 )
[someAlphanumStr] -> (115 omeAlphanumStr)

感谢所有明确的答案和建议,尤其感谢@sehe。

最佳答案

使用 Spirit[1] 完成任何的方法是使用小步骤,并在整个过程中严格简化。

不要忍受“垃圾”(例如,随机重复的子表达式)。另外,明确是好的。在这种情况下,我将从提取重复的子表达式并重新格式化以提高易读性开始:

    name_rule   = '[' >> qi::lexeme[alpha >> *alnum] >> ']';
factor_rule = qi::float_;

summand_rule %=
(factor_rule >> -qi::lit('*') >> name_rule)
| (name_rule >> -qi::lit('*') >> factor_rule)
| (factor_rule)
| (name_rule)
;

那里,好多了,而且我没有改变任何事情。可是等等!它不再编译

    qi::rule<Iterator, std::string(), ascii::space_type> name_rule;
qi::rule<Iterator, float(), ascii::space_type> factor_rule;

事实证明,语法只是“碰巧”编译,因为 Spirit 的属性兼容性规则非常宽松/宽松,以至于与名称匹配的字符只是被分配给因子部分(这就是 115 的来源:0x73是来自 ssomeAlphanumStr 的 ASCII。


OOPS/TL;DW 有一次我在这里写了相当长的分析,但我通过关闭浏览器破坏了它,所以只有一个旧的草稿缓存服务器端:(我'现在将其归结为底线:

Guideline Use either constructor overloads to assign to your exposed attribute type, or use Fusion Sequence adaptation, but don't mix the two: they will interfere in surprising/annoying ways.

放心,我当然不会让你空手而归。我只是“手动”指示 factorname各自“插槽”(成员)中的组件[2]

继承属性是保持其清晰易读的好方法:

// assuming the above rules redefined to take ("inherit") a summand& attribute:
qi::rule<Iterator, void(summand&), ascii::space_type> name_rule, factor_rule;

只需在语义 Action 中添加一个简单的赋值即可:

name_rule   = as_string [ '[' >> lexeme[alpha >> *alnum] >> ']' ] 
[ _name = _1 ];
factor_rule = double_ [ _factor = _1 ];

现在,'魔尘'当然是如何_name_factor Actor 被定义。我更喜欢为此使用绑定(bind),而不是 phx::at_c<N>由于维护成本:

static const auto _factor = phx::bind(&summand::factor, qi::_r1);
static const auto _name = phx::bind(&summand::name, qi::_r1);

看到了吗?这非常简洁,清楚地显示了正在发生的事情。此外,实际上不需要为 summand 进行 Fusion 适配。在这里。

现在,我们终于可以简化主要规则了:

    summand_rule = 
factor_rule (_val) >> - ( -lit('*') >> name_rule (_val) )
| name_rule (_val) >> - ( -lit('*') >> factor_rule (_val) )
;

它的作用是通过使尾随部分成为可选来简单地将单组件分支合并到双组件分支中。

请注意 summand默认构造函数负责处理默认值:

struct summand {
float factor;
std::string name;

summand() : factor(1.f), name("") {}
};

注意这如何消除了相当多的复杂性。

查看完全改编的示例运行 Live on Coliru 打印:

7.5*[someAlphanumStr] -> (7.5 someAlphanumStr)
7.5[someAlphanumStr] -> (7.5 someAlphanumStr)
[someAlphanumStr]*7.4 -> (7.4 someAlphanumStr)
[someAlphanumStr]5 -> (5 someAlphanumStr)
7.4 -> (7.4 )
[someAlphanumStr] -> (1 someAlphanumStr)

完整代码 list

#define BOOST_SPIRIT_USE_PHOENIX_V3
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace client {
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
namespace ascii = boost::spirit::ascii;

struct summand {
float factor;
std::string name;

summand() : factor(1.f), name("") {}
};
}

namespace client {

template <typename Iterator>
struct summand_parser : qi::grammar<Iterator, summand(), ascii::space_type>
{
summand_parser() : summand_parser::base_type(summand_rule)
{
using namespace ascii;

static const auto _factor = phx::bind(&summand::factor, qi::_r1);
static const auto _name = phx::bind(&summand::name, qi::_r1);

name_rule = qi::as_string [ '[' >> qi::lexeme[alpha >> *alnum] >> ']' ]
[ _name = qi::_1 ] ;
factor_rule = qi::double_ [ _factor = qi::_1 ] ;

summand_rule =
factor_rule (qi::_val) >> - ( -qi::lit('*') >> name_rule (qi::_val) )
| name_rule (qi::_val) >> - ( -qi::lit('*') >> factor_rule (qi::_val) )
;

BOOST_SPIRIT_DEBUG_NODES((summand_rule)(name_rule)(factor_rule))
}

qi::rule<Iterator, void(summand&), ascii::space_type> name_rule, factor_rule;
qi::rule<Iterator, summand(), ascii::space_type> summand_rule;
};
}

bool parseSummandsInto(std::string const& str, client::summand& summand)
{
typedef std::string::const_iterator It;
static const client::summand_parser<It> g;

It iter(str.begin()), end(str.end());
bool r = phrase_parse(iter, end, g, boost::spirit::ascii::space, summand);

return (r && iter == end);
}

int main()
{
std::vector<std::string> inputStrings = {
"7.5*[someAlphanumStr]",
"7.5[someAlphanumStr]",
"[someAlphanumStr]*7.4",
"[someAlphanumStr]5",
"7.4",
"[someAlphanumStr]",
};

std::for_each(inputStrings.begin(), inputStrings.end(), [&inputStrings](std::string const& inputStr) {
client::summand parsed;
if (parseSummandsInto(inputStr, parsed))
std::cout << inputStr << " -> (" << parsed.factor << " " << parsed.name << ")\n";
else
std::cout << inputStr << " -> FAILED\n";
});
}

[1] 可以说,技术中的任何其他内容

[2] 您可以保留 FUSION_ADAPT_STRUCT,但如您所见,它不再是必需的

关于c++ - 当某些结构字段被省略或顺序与结构声明中的顺序不同时,如何实现正确的解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663539/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com