简体   繁体   English

提升精神分析标识符

[英]boost spirit parsing identifier

I would like to create parser that will parse identifiers that start with alpha or _ and it might have alpha, num or _ in the body 我想创建一个解析器,该解析器将解析以alpha或_开头的标识符,并且主体中可能包含alpha,num或_

This is what I have so far: 这是我到目前为止的内容:

#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;
};

why this returns an empty name if there is '_' in the identifier, it works in case there isn't 为什么如果标识符中有“ _”,则返回一个空名称,如果没有

"_" is the same as qi::lit("_") , both match the character '_' but don't synthesize any attribute. "_"qi::lit("_") ,都与字符'_'匹配,但不合成任何属性。 What you want is qi::char_('_') . 您想要的是qi::char_('_') You can find more info here . 您可以在此处找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM