c++ - Boost.Spirit X3 中的错误处理和注释

标签 c++ boost-spirit-qi boost-spirit-x3

使用 boost::spirit::x3::position_tagged 作为一些 AST 节点的基类的逻辑是什么(如何选择哪些应该被标记,例如对于类 C 语言?)和其他结构,用于规则 ID 定义,例如:

struct error_handler_tag;

struct error_handler_base
{

    template< typename Iterator, typename Exception, typename Context >
    x3::error_handler_result
    on_error(Iterator & /*first*/, Iterator const & /*last*/,
             Exception const & x, Context const & context)
    {
        std::string message_ = "Error! Expecting: " + x.which() + " here:";
        auto & error_handler = x3::get< error_handler_tag >(context).get();
        error_handler(x.where(), message_);
        return x3::error_handler_result::fail;
    }

};

struct annotation_base
{

    template< typename T, typename Iterator, typename Context >
    void
    on_success(Iterator const & first, Iterator const & last,
               T & ast, Context const & context)
    {
        auto & error_handler = x3::get< error_handler_tag >(context).get();
        error_handler.tag(ast, first, last);
    }

};
// ...
error_handler_type error_handler(beg, end, std::cerr);
auto const parser_ = x3::with< error_handler_tag >(std::ref(error_handler))[grammar];
// ...

?

如果输入错误(语法不匹配),这部分代码什么都不做(即使是最简单的语法,它应该识别标识符)——不打印错误消息。

最佳答案

语法正确的解析并不意味着 AST 也可以成功求值。想一想定义一些可以评估数学表达式(如“3+4/(5-5)”)的评估器的语法。它会很好地解析,但在 AST 评估期间,您可能希望在“5-5”上引发错误作为除法的参数。为此,拥有您提示的元素的位置很方便。

关于c++ - Boost.Spirit X3 中的错误处理和注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25778915/

相关文章:

c++ - SensorTest.exe 中 0x76F8277C 处的第一次机会异常:Microsoft C++ 异常:Platform::COMException ^ 在内存位置

c++ - 使用 Boost.spirit 解析一个简单的重复文本宏

c++ - 使用 Spirit::Qi 进行语法解析失败

c++ - 模棱两可的变种和提升精神x3

c++ - 可能会失败的 "post-initialization"的 eps 解析器

c++ - 编译错误 C++ Spirit X3 没有可行的重载=,没有调用 move_to 的匹配函数

c++ - 使用计数器模式用 SHA256 加密数据是否聪明?

c++ - 两个 SSE2 打包 double 的最优无分支条件选择

c++ - 带字符串文字的自动

c++ - 为什么 boost::recursive_wrapper 在这种情况下不起作用