1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <iostream>
#include <fstream>
#include <string>
struct Result
{
enum Type { PERE, MERE };
Type type;
std::string nom1;
std::string nom2;
};
template <typename Iterator>
bool do_parse(Iterator first, Iterator last, Result& res)
{
using boost::spirit::qi::eps;
using boost::spirit::qi::char_;
using boost::spirit::qi::_1;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
using boost::phoenix::ref;
using boost::phoenix::push_back;
Result::Type type;
std::string nom1;
std::string nom2;
bool parsed = phrase_parse(first, last,
// Begin grammar
(
"pere(" >> +(char_ - ',')[push_back(ref(nom1), _1)] >> ','
>> +(char_ - ')')[push_back(ref(nom2), _1)] >> ")."
>> eps[ref(type) = Result::PERE]
|
"mere(" >> +(char_ - ',')[push_back(ref(nom1), _1)] >> ','
>> +(char_ - ')')[push_back(ref(nom2), _1)] >> ")."
>> eps[ref(type) = Result::MERE]
),
// End grammar
space);
if (!parsed || first != last) // fail if we did not get a full match
return false;
res.type = type;
res.nom1 = nom1;
res.nom2 = nom2;
return parsed;
}
/**
* Main program
*/
int main()
{
std::ifstream ifile("test.txt");
if (!ifile) {
return EXIT_FAILURE;
}
bool ok = true;
std::string line;
while (ok && std::getline(ifile, line)) {
boost::trim(line);
if (line.empty()) {
continue;
}
std::cout << "Parsing '" << line << "' : ";
Result res;
if (do_parse(line.begin(), line.end(), res)) {
std::cout << "Succeeded" << std::endl;
std::cout << " -> " << res.type << " : " << res.nom1 << ", " << res.nom2 << std::endl;
std::cout << std::endl;
}
else {
std::cout << "Failed !" << std::endl;
}
}
return 0;
} |
Partager