gpt4 book ai didi

c++ - boost spirit 解析标识符

转载 作者:搜寻专家 更新时间:2023-10-31 00:37:50 24 4
gpt4 key购买 nike

我想创建解析器来解析以 alpha 或 _ 开头的标识符,它的主体可能有 alpha、num 或 _

这是我目前所拥有的:

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/home/support/iterators/line_pos_iterator.hpp>
#include <boost/spirit/repository/include/qi_confix.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>

using namespace boost::spirit;

#include <boost/fusion/include/adapt_struct.hpp>

////////////////////////////////
// extra facilities
struct get_line_f
{
template <typename> struct result { typedef size_t type; };
template <typename It> size_t operator()(It const& pos_iter) const
{
return get_line(pos_iter);
}
};

struct Position
{
Position()
: line(-1)
{
}

size_t line;
};

struct Identifier : public Position
{
Identifier()
: Position()
, name()
{
}

std::string name;
};

BOOST_FUSION_ADAPT_STRUCT(Identifier,
(std::string, name)
(size_t, line)
)

//
////////////////////////////////

template <typename Iterator>
struct source_identifier: qi::grammar<Iterator, Identifier(), qi::space_type>
{
source_identifier() : source_identifier::base_type(start)
{
using qi::alpha;
using qi::alnum;
using qi::raw;
using qi::_val;
using qi::_1;

namespace phx = boost::phoenix;
using phx::at_c;
using phx::begin;

name %= (qi::alpha | "_")
>> *(qi::alnum | "_");

start = raw [ name[at_c<0>(_val) = _1] ]
[
at_c<1>(_val) = get_line_(begin(_1))
]
;
}

boost::phoenix::function<get_line_f> get_line_;
qi::rule<Iterator, Identifier(), qi::space_type> start;
qi::rule<Iterator, std::string()> name;
};

如果标识符中有'_',为什么这会返回一个空名称,如果没有,它会起作用

最佳答案

"_"qi::lit("_") 相同,都匹配字符'_' 但不匹配'合成任何属性。你想要的是 qi::char_('_')。您可以找到更多信息 here .

关于c++ - boost spirit 解析标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19168278/

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