6

我正在尝试将 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结构解析为 a std::string,但这将非常低效(我知道,过早的优化 bla bla)。

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

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

4

1 回答 1

7

cierelabs上的JSON 解析器示例展示了一种使用语义操作以 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

于 2015-12-18T20:54:35.403 回答