如何从提升精神中的函数中投掷expectation_failure

How to throw an expectation_failure from a function in Boost Spirit?

本文关键字:函数 expectation failure      更新时间:2023-10-16

在 Boost::Spirit 中,如何从绑定Boost::Bind的函数触发expectation_failure

背景:我解析了一个包含复杂条目的大文件。当一个条目与上一个条目不一致时,我想失败并抛出一个expectation_failure(包含正确的解析位置信息(。当我解析一个条目时,我绑定了一个函数,该函数决定该条目是否与之前看到的内容不一致。

我编了一个小玩具例子来说明这一点。在这里,我只想在int不能被 10 整除时抛出一个expectation_failure

#include <iostream>
#include <iomanip>
#include <boost/spirit/include/qi.hpp>
#include <boost/bind.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
namespace qi = boost::spirit::qi;
namespace classic = boost::spirit::classic;
void checkNum(int const& i) {
  if (i % 10 != 0) // >> How to throw proper expectation_failure? <<
    std::cerr << "ERROR: Number check failed" << std::endl;
}
template <typename Iterator, typename Skipper>
struct MyGrammar : qi::grammar<Iterator, int(), Skipper> {
  MyGrammar() : MyGrammar::base_type(start) {
    start %= qi::eps > qi::int_[boost::bind(&checkNum, _1)];
  }
  qi::rule<Iterator, int(), Skipper> start;
};
template<class PosIter>
std::string errorMsg(PosIter const& iter) {
  const classic::file_position_base<std::string>& pos = iter.get_position();
  std::stringstream msg;
  msg << "parse error at file " << pos.file
      << " line " << pos.line << " column " << pos.column << std::endl
      << "'" << iter.get_currentline() << "'" << std::endl
      << std::setw(pos.column) << " " << "^- here";
  return msg.str();
}
int main() {
  std::string in = "11";
  typedef std::string::const_iterator Iter;
  typedef classic::position_iterator2<Iter> PosIter;
  MyGrammar<PosIter, qi::space_type> grm;
  int i;
  PosIter it(in.begin(), in.end(), "<string>");
  PosIter end;
  try {
    qi::phrase_parse(it, end, grm, qi::space, i);
    if (it != end)
      throw std::runtime_error(errorMsg(it));
  } catch(const qi::expectation_failure<PosIter>& e) {
    throw std::runtime_error(errorMsg(e.first));
  }
  return 0;
}

抛出expectation_failure意味着我在不能被 10 整除的 int 上收到这样的错误消息:

parse error at file <string> line 1 column 2
'11'
  ^- here

您可以使用 phoenix 中的 _pass 占位符来强制分析失败。这样的事情应该有效。

bool myfunc(int i) {return i%10 == 0;}
...
_int [ _pass = phoenix::bind(myfunc,_1)] 

晚了几年,但无论如何:

如果绝对希望引发异常并希望on_error捕获它,则必须从 qi 命名空间中抛出expectation_exception,因为错误处理程序on_error不会捕获任何其他内容。

这可能适用于语义操作或自定义分析器实现。

看起来像:

boost::throw_exception(Exception(first, last, component.what(context)));

其中Exceptionqi::expactation_exception,仅此而已。

如果您手头没有像语义操作那样的组件,则必须提供自己的qi::info对象而不是component.what(..)

您可以在由 on_error 保护的上下文中从任何地方投掷。