首页 > 解决方案 > 使用转义序列处理为带引号的字符串创建 boost::spirit::x3 解析器

问题描述

我需要为我的自定义语言创建一个带引号的字符串的解析器,该解析器还将正确处理转义序列,其中包括允许字符串中的转义引号。这是我当前的字符串解析器:

x3::lexeme[quote > *(x3::char_ - quote) > quote]

wherequote只是 的常量表达式'"'。它不进行任何转义序列处理。我知道boost::spirit::classic::lex_escape_ch_p,但我不知道如何在boost::spirit::x3工具(或一般情况下)使用它。我怎么能创建一个解析器呢?解析器必须识别大多数转义序列,例如常见的转义序列,如'\n', '\t',以及更复杂的东西,如 hex、oct 和 ansi 转义序列。

如果这篇文章有问题,我深表歉意,这是我第一次在 SO 上发帖。

编辑:

以下是我最终实现解析器的方式:

x3::lexeme[quote > *(
    ("\\\"" >> &x3::char_) >> x3::attr(quote) | ~x3::char_(quote)
    ) > quote]
[handle_escape_sequences];

哪里handle_escape_sequences是 lambda:

auto handle_escape_sequences = [&](auto&& context) -> void {
    std::string& str = x3::_val(context);

    uint32_t i{};

    static auto replace = [&](const char replacement) -> void {
        str[i++] = replacement;
    };

    if (!classic::parse(std::begin(str), std::end(str), *classic::lex_escape_ch_p[replace]).full)
        throw Error{ "invalid literal" }; // invalid escape sequence most likely

    str.resize(i);
};

它进行完整的 ANSI 转义序列解析,这意味着您可以使用它进行各种花哨的终端操作,例如设置文本颜色、光标位置等。

这是规则的完整定义以及它所依赖的所有内容(我只是从我的代码中挑选了与之相关的所有内容,这就是为什么结果看起来像意大利面条)以防有人碰巧需要它:

#include <boost\spirit\home\x3.hpp>
#include <boost\spirit\include\classic_utility.hpp>

using namespace boost::spirit;

#define RULE_DECLARATION(rule_name, attribute_type)                            \
inline namespace Tag { class rule_name ## _tag; }                              \
x3::rule<Tag::rule_name ## _tag, attribute_type, true> rule_name = #rule_name; \

#define SIMPLE_RULE_DEFINITION(rule_name, attribute_type, definition) \
RULE_DECLARATION(rule_name, attribute_type)                           \
auto rule_name ## _def = definition;                                  \
BOOST_SPIRIT_DEFINE(rule_name);

constexpr char quote = '"';


template <class Base, class>
struct Access_base_s : Base {
    using Base::Base, Base::operator=;
};

template <class Base, class Tag>
using Unique_alias_for = Access_base_s<Base, Tag>;


using String_literal = Unique_alias_for<std::string, class String_literal_tag>;

SIMPLE_RULE_DEFINITION(string_literal, String_literal,
    x3::lexeme[quote > *(
        ("\\\"" >> &x3::char_) >> x3::attr(quote) | ~x3::char_(quote)
        ) > quote]
    [handle_escape_sequences];
);

标签: c++parsingboostboost-spiritboost-spirit-x3

解决方案


我在这个网站上有很多这样的例子¹

让我们从简化您的表达式开始(~charset可能比 更有效charset - exceptions):

x3::lexeme['"' > *~x3::char_('"')) > '"']

现在,为了允许转义,我们可以对它们进行临时解码:

auto qstring = x3::lexeme['"' > *(
         "\\n" >> x3::attr('\n')
       | "\\b" >> x3::attr('\b')
       | "\\f" >> x3::attr('\f')
       | "\\t" >> x3::attr('\t')
       | "\\v" >> x3::attr('\v')
       | "\\0" >> x3::attr('\0')
       | "\\r" >> x3::attr('\r')
       | "\\n" >> x3::attr('\n')
       | "\\"  >> x3::char_("\"\\")
       | ~x3::char_('"')
   ) > '"'];

或者,您可以使用符号方法,包括或不包括斜杠:

x3::symbols<char> escapes;
escapes.add
    ( "\\n", '\n')
    ( "\\b", '\b')
    ( "\\f", '\f')
    ( "\\t", '\t')
    ( "\\v", '\v')
    ( "\\0", '\0')
    ( "\\r", '\r')
    ( "\\n", '\n')
    ( "\\\\", '\\')
    ( "\\\"", '"');

auto qstring = x3::lexeme['"' > *(escapes | ~x3::char_('"')) > '"'];

也可以在 Coliru上看到它。

我想我更喜欢手卷分支,因为它们让你可以灵活地进行例如他/八进制转义(\0尽管注意冲突):

       | "\\" >> x3::int_parser<char, 8, 1, 3>()
       | "\\x" >> x3::int_parser<char, 16, 2, 2>()

这也可以正常工作:

住在科利鲁

#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <iomanip>

int main() {
    namespace x3 = boost::spirit::x3;

    auto qstring = x3::lexeme['"' > *(
             "\\n" >> x3::attr('\n')
           | "\\b" >> x3::attr('\b')
           | "\\f" >> x3::attr('\f')
           | "\\t" >> x3::attr('\t')
           | "\\v" >> x3::attr('\v')
           | "\\r" >> x3::attr('\r')
           | "\\n" >> x3::attr('\n')
           | "\\"  >> x3::char_("\"\\")
           | "\\" >> x3::int_parser<char, 8, 1, 3>()
           | "\\x" >> x3::int_parser<char, 16, 2, 2>()
           | ~x3::char_('"')
       ) > '"'];

    for (std::string const input : { R"("\ttest\x41\x42\x43 \x031\x032\x033 \"hello\"\r\n")" }) {
        std::string output;
        auto f = begin(input), l = end(input);
        if (x3::phrase_parse(f, l, qstring, x3::blank, output)) {
            std::cout << "[" << output << "]\n";
        } else {
            std::cout << "Failed\n";
        }
        if (f != l) {
            std::cout << "Remaining unparsed: " << std::quoted(std::string(f,l)) << "\n";
        }
    }
}

印刷

[   testABC 123 "hello"
]

¹ 看看这些


推荐阅读