BoostSpiritX3中的错误处理和注释

error handling and annotation in Boost.Spirit X3

本文关键字:注释 处理 错误 BoostSpiritX3      更新时间:2023-10-16

使用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"上引发一个错误,作为除法的参数。为此,掌握您所抱怨的元素的位置是很方便的。