c++ - 使用 Boost::Spirit::X3 解析复数

标签 c++ boost-spirit complex-numbers boost-spirit-x3

我想编写一个 Boost::Spirit::X3 解析器来解析具有以下可能输入格式的复数:

  • “(X+Yi)”
  • “Yj”
  • “X”

迄今为止我最好的尝试如下( Open on Coliru ):

#include <complex>
#include <iostream>

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>

namespace x3 = boost::spirit::x3;

struct error_handler {
    template <typename iterator_t, typename error_t, typename context_t>
    auto on_error(iterator_t& /* iter */, const iterator_t& /* end */, const error_t& error,
                  const context_t& context) {
        namespace x3 = boost::spirit::x3;
        const auto& handler = x3::get<x3::error_handler_tag>(context).get();
        handler(error.where(), "error: expecting: " + error.which());
        return x3::error_handler_result::fail;
    }
};

// -----------------------------------------------------------------------------

namespace ast {
template <typename T>
struct complex_number {
    T real;
    T imag;
    operator std::complex<T>() {
        return {real, imag};
    }
};
}  // namespace ast
BOOST_FUSION_ADAPT_STRUCT(ast::complex_number<double>, real, imag);

// -----------------------------------------------------------------------------

namespace parser {
const auto pure_imag_number = x3::attr(0.) > x3::double_ > x3::omit[x3::char_("ij")];
const auto pure_real_number = x3::double_ > x3::attr(0.);

struct complex_class : error_handler {};
const x3::rule<complex_class, ast::complex_number<double>> complex = "Complex number";
static const auto complex_def = ('(' > (x3::double_ > -(x3::double_ > x3::omit[x3::char_("ij")])) >> ')')
                                | pure_imag_number 
                                | pure_real_number;

BOOST_SPIRIT_DEFINE(complex);
}  // namespace parser

// =============================================================================

void parse(const std::string& str) {
    using iterator_t = std::string::const_iterator;

    auto iter = std::begin(str);
    auto end = std::end(str);

    boost::spirit::x3::error_handler<iterator_t> handler(iter, end, std::cerr);
    const auto parser = boost::spirit::x3::with<boost::spirit::x3::error_handler_tag>(
        std::ref(handler))[parser::complex];

    std::complex<double> result{};
    if (boost::spirit::x3::phrase_parse(iter, end, parser, x3::space, result) && iter == end) {
        std::cout << "Parsing successful for:' " << str << "'\n";
    } else {
        std::cout << "Parsing failed for:' " << str << "'\n";
    }
}

int main() {
    for (const auto& str : {
             "(1+2j)",
             "(3+4.5j)",
             "1.23j",
             "42",
         }) {
        parse(str);
    }
    return 0;
}

运行编译后的代码时会给出以下结果(使用 GCC 12.1.1 和 Boost 1.79.0):

Parsing successful for:' (1+2j)'
Parsing successful for:' (3+4.5j)'
Parsing successful for:' 1.23j'
In line 1:
error: expecting: N5boost6spirit2x314omit_directiveINS1_8char_setINS0_13char_encoding8standardEcEEEE
42
__^_
Parsing failed for:' 42'

令我困惑的是,为什么在解析仅包含实数的字符串时,最后一个替代方案被认为无效。

最佳答案

您已经发现,如果您需要允许回溯,则期望点过于强制。

但是请注意,你的语法有点有趣。仅使用 double_ 解析器中包含的一元符号分隔值。

这是一个简化的测试,突出显示了一些边缘情况:

static const auto ij      = x3::omit[x3::char_("ij")];
static const auto implied = x3::attr(0.);

static const auto complex =
    x3::rule<struct complex_, ast::complex_number<double>>{"complex"} //
= ('(' >> x3::double_ >> ((x3::double_ >> ij) | implied) >> ')')      //
    | implied >> x3::double_ >> ij                                    //
    | x3::double_ >> implied;

经过完整测试Live On Coliru打印

Parsing successful for: '(1+2j)' -> (1,2)
Parsing successful for: '(1 2j)' -> (1,2)
Parsing successful for: '(+1+2j)' -> (1,2)
Parsing successful for: '(+1-2j)' -> (1,-2)
Parsing successful for: '(-1-2j)' -> (-1,-2)
Parsing successful for: '(3+4.5j)' -> (3,4.5)
Parsing successful for: '1.23j' -> (0,1.23)
Parsing successful for: '42' -> (42,0)
Parsing successful for: 'inf' -> (inf,0)
Parsing successful for: '-infj' -> (0,-inf)
Parsing successful for: 'NaNj' -> (0,nan)
Parsing successful for: '(.0e9)' -> (0,0)
Parsing successful for: '(.0e-4)' -> (0,0)
Parsing successful for: '.0e-4i' -> (0,0)
Parsing successful for: '.0e-4j' -> (0,0)
Parsing successful for: '(3-0.e-4j)' -> (3,-0)
Parsing successful for: '(3-.0e-4j)' -> (3,-0)

请注意,在非括号版本中允许空格很容易导致问题(不明确的输入/令人惊讶的错误解析)。我建议您可能只想跳过括号内的空格:

static const auto complex =
    x3::rule<struct complex_, ast::complex_number<double>>{"complex"} //
= x3::skip(x3::blank)['(' >> x3::double_ >>
                      ((x3::double_ >> ij) | implied) >> ')'] //
    | x3::lexeme[implied >> x3::double_ >> ij                 //
                 | x3::double_ >> implied];

关于c++ - 使用 Boost::Spirit::X3 解析复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73322232/

相关文章:

c++ - 访问 union 中相同类型的非事件成员

c++ - 为什么在调用 GetThreadTimes 时出现错误 "The handle is invalid"?

C++11 原子 : does it make sense, 或者甚至可以将它们与内存映射 I/O 一起使用?

c++ - boost spirit - 无法获得属性

c++ - Boost::spirit::karma:复制在 repeat 或 kleene star 中不起作用?

python - 如何在Python中构建复数类?

c++ - 链接错误 : undefined reference for architecture x86_64 for Xcode 5

c++ - 如何在不提供有效生成器的情况下告诉 boost::karma::rule 不消耗其属性?

c++ - C99 中的 _Complex 类型的行为与 C++ 中的 std::complex<> 类似吗?

c++ - 通过引用传递 Complex real 和 imag