In Boost :: Spirit, come è possibile attivare uno expectation_failure
da una funzione associata a Boost::Bind
?Come lanciare un expectation_failure da una funzione in Boost Spirit?
Sfondo: analizzo un file di grandi dimensioni che contiene voci complesse. Quando una voce è incoerente con una voce precedente, voglio fallire e lanciare un expectation_failure
(contenente informazioni sulla posizione di analisi corretta). Quando analizzo una voce lego una funzione che decide se la voce è incoerente con qualcosa vista prima.
Ho inventato un piccolo esempio di giocattolo che mostra il punto. Qui voglio semplicemente gettare un expectation_failure
quando il int
non è divisibile per 10:
#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;
}
Lanciare un expectation_failure
significherebbe che ricevo un messaggio di errore come questo su un int che non è divisibile per 10:
parse error at file <string> line 1 column 2
'11'
^- here
È possibile creare un'altra regola anziché int_, che corrisponderebbe a un numero intero solo quando la condizione è soddisfatta? Non conosco bene lo spirito, ma suppongo che ci sia una regola simile a r_bool in AX che avvolge un predicato, è una situazione abbastanza comune. –
Penso che avrò bisogno di qualcosa del genere, sfortunatamente: http://boost-spirit.com/home/articles/qi-example/creating-your-own-parser-component-for-spirit-qi/ – Frank
Siamo spiacenti vedete, è molto ostile all'utente. Ecco perché hai bisogno di AXE :-) –