1 /*=============================================================================
2 Copyright (c) 2016 Frank Hein, maxence business consulting gmbh
4 Distributed under the Boost Software License, Version 1.0. (See accompanying
5 file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 ==============================================================================*/
11 #include <boost/spirit/home/qi.hpp>
12 #include <boost/spirit/home/qi/nonterminal/grammar.hpp>
13 #include <boost/spirit/include/phoenix.hpp>
15 namespace qi
= boost::spirit::qi
;
17 typedef std::string::const_iterator iterator_type
;
18 typedef std::string result_type
;
20 template<typename Parser
>
21 void parse(const std::string message
, const std::string
& input
, const std::string
& rule
, const Parser
& parser
) {
22 iterator_type iter
= input
.begin(), end
= input
.end();
24 std::vector
<result_type
> parsed_result
;
26 std::cout
<< "-------------------------\n";
27 std::cout
<< message
<< "\n";
28 std::cout
<< "Rule: " << rule
<< std::endl
;
29 std::cout
<< "Parsing: \"" << input
<< "\"\n";
31 bool result
= qi::phrase_parse(iter
, end
, parser
, qi::space
, parsed_result
);
34 std::cout
<< "Parser succeeded.\n";
35 std::cout
<< "Parsed " << parsed_result
.size() << " elements:";
36 for (const auto& str
: parsed_result
)
37 std::cout
<< "[" << str
<< "]";
38 std::cout
<< std::endl
;
42 std::cout
<< "Parser failed" << std::endl
;
45 std::cout
<< "EOI reached." << std::endl
;
48 std::cout
<< "EOI not reached. Unparsed: \"" << std::string(iter
, end
) << "\"" << std::endl
;
50 std::cout
<< "-------------------------\n";
55 namespace phx
= boost::phoenix
;
57 template <typename Iterator
>
58 struct ident
: qi::grammar
< Iterator
, std::string(), qi::space_type
>
62 qi::rule
<iterator_type
, std::string(), qi::space_type
>
63 id
, id_list
, qualified_id
;
66 template <typename Iterator
>
67 ident
<Iterator
>::ident() : ident::base_type(id_list
) {
73 id
= (qi::alpha
| qi::char_('_')) >> *(qi::alnum
| qi::char_('_'));
75 id_list
= expect
[id
>> qi::lit(';')];
77 on_error
<fail
>(id_list
,
79 << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl
80 << "Error! Expecting "
83 << phx::construct
<std::string
>(qi::_3
, qi::_2
) << std::endl
84 << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl
91 grammars::ident
<iterator_type
> id
;
93 parse("expect directive, fail on first"
95 , "qi::expect[ id >> qi::lit(';') ]"
98 parse("expect directive, fail on second"
100 , "qi::expect[ id >> qi::lit(';') ]"
103 parse("expect directive, success"
105 , "qi::expect[ id >> qi::lit(';') ]"