提升精神(X3)符号表,产生UTF8字符串

时间:2015-12-18 20:50:32

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

我正在尝试将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,但这样效率非常低(我知道,过早优化bla bla)。

我希望有一些优雅的方式,而不是通过一堆箍来使这个工作(symbols附加结果的字符串)。

我确实担心使用代码点值并想要UTF8会产生转换的运行时成本(或者是constexpr UTF32-> UTF8转换可能吗?)。

1 个答案:

答案 0 :(得分:7)

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

相关问题