【问题标题】:Boost Spirit (X3) symbol tables resulting in UTF8 stringsBoost Spirit (X3) 符号表产生 UTF8 字符串
【发布时间】:2015-12-18 20:50:32
【问题描述】:

我正在尝试将 LaTeX 转义码(例如 \alpha)解析为 Unicode(数学)字符(例如 U+1D6FC)。

现在这意味着我正在使用这个 symbols 解析器(规则):

struct greek_lower_case_letters_ : x3::symbols<char32_t>
{
  greek_lower_case_letters_::greek_lower_case_letters_()
  {
    add("alpha",   U'\u03B1');
  }
} greek_lower_case_letter;

这很好用,但意味着我得到了一个std::u32string 结果。 我想要一种优雅的方式来将 Unicode 代码点保留在代码中(可能是为了未来的自动化)和维护原因。有没有办法让这种解析器解析成 UTF-8 std::string?

我曾想过将 symbols 结构解析为 std::string,但这会非常低效(我知道,过早的优化等等)。

我希望有一些优雅的方法,而不是通过一堆箍来完成这项工作(symbols 将字符串附加到结果中)。

我确实担心使用代码点值并希望使用 UTF8 会产生转换的运行时成本(或者是否有 constexprUTF32->UTF8 转换可能?)。

【问题讨论】:

    标签: c++ boost c++14 boost-spirit boost-spirit-x3


    【解决方案1】:

    JSON parser example at cierelabs 展示了一种使用语义操作在 utf8 编码中附加代码点的方法:

      auto push_utf8 = [](auto& ctx)
      {
         typedef std::back_insert_iterator<std::string> insert_iter;
         insert_iter out_iter(_val(ctx));
         boost::utf8_output_iterator<insert_iter> utf8_iter(out_iter);
         *utf8_iter++ = _attr(ctx);
      };
    
      // ...
    
      auto const escape =
             ('u' > hex4)           [push_utf8]
         |   char_("\"\\/bfnrt")    [push_esc]
         ;
    

    这用于他们的

    typedef x3::rule<unicode_string_class, std::string> unicode_string_type;
    

    如您所见,它将 utf8 序列构建为 std::string 属性。

    查看完整代码:https://github.com/cierelabs/json_spirit/blob/x3_devel/ciere/json/parser/x3_grammar_def.hpp

    【讨论】:

    • 我决定使用std::string 作为符号键/值,并且我正在尝试使用repeat 指令使char_ 规则作为序列工作。 UTF8 和 UTF32 版本的比较here。我不明白为什么第二个版本在第一个 \alpha 之后失败。
    • @rubenvb 我今晚稍后再看。
    • @rubenvb 有趣的是,在我的测试中,first 版本在第一个 'a' 之后失败了。它与属性传播有关;如果symbols 产生与封闭相同的类型(std::string),它会得到 assigned 而不是 appended (我觉得这是一个错误)。所以,相反,我会使用std::vector&lt;char&gt; 作为属性,它可以正常工作。这是一些清理后的代码:coliru.stacked-crooked.com/a/b9555dfd246b5252(note reinterpret_cast&lt;&gt; 业务看起来不对,我改了)。
    • @rubenvb 也许你应该把它作为一个单独的问题发布。我会尽量记住在邮件列表中询问这种行为。直播在这里:livecoding.tv/video/…(第一部分因技术问题缺失)
    • 我最终选择了创建std::array 的用户定义字符串文字。避免这种可能的错误,是(原则上)编译时代码点-> UTF8 转换,并且可以扩展到组合字符而不用大惊小怪。我最终得到的代码(现在)是here。我将把它解析为一些 AST 表示,从中我将为初学者合成一些有限形式的 Qt 支持的 HTML。不过感谢您的洞察力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多