1 /*=============================================================================
2 Copyright (c) 2001-2014 Joel de Guzman
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 =============================================================================*/
7 ///////////////////////////////////////////////////////////////////////////////
9 // Plain calculator example demonstrating the grammar. The parser is a
10 // syntax checker only and does not do any semantic evaluation.
12 // [ JDG May 10, 2002 ] spirit 1
13 // [ JDG March 4, 2007 ] spirit 2
14 // [ JDG February 21, 2011 ] spirit 2.5
15 // [ JDG June 6, 2014 ] spirit x3
17 ///////////////////////////////////////////////////////////////////////////////
19 #include <boost/spirit/home/x3.hpp>
20 #include <boost/spirit/home/x3/support/ast/variant.hpp>
21 #include <boost/fusion/include/adapt_struct.hpp>
28 namespace x3
= boost::spirit::x3
;
32 ///////////////////////////////////////////////////////////////////////////////
33 // The calculator grammar
34 ///////////////////////////////////////////////////////////////////////////////
35 namespace calculator_grammar
40 x3::rule
<class expression
> const expression("expression");
41 x3::rule
<class term
> const term("term");
42 x3::rule
<class factor
> const factor("factor");
44 auto const expression_def
=
58 auto const factor_def
=
60 | '(' >> expression
>> ')'
71 auto calculator
= expression
;
74 using calculator_grammar::calculator
;
78 ///////////////////////////////////////////////////////////////////////////////
80 ///////////////////////////////////////////////////////////////////////////////
84 std::cout
<< "/////////////////////////////////////////////////////////\n\n";
85 std::cout
<< "Expression parser...\n\n";
86 std::cout
<< "/////////////////////////////////////////////////////////\n\n";
87 std::cout
<< "Type an expression...or [q or Q] to quit\n\n";
89 typedef std::string::const_iterator iterator_type
;
92 while (std::getline(std::cin
, str
))
94 if (str
.empty() || str
[0] == 'q' || str
[0] == 'Q')
97 auto& calc
= client::calculator
; // Our grammar
99 iterator_type iter
= str
.begin();
100 iterator_type end
= str
.end();
101 boost::spirit::x3::ascii::space_type space
;
102 bool r
= phrase_parse(iter
, end
, calc
, space
);
104 if (r
&& iter
== end
)
106 std::cout
<< "-------------------------\n";
107 std::cout
<< "Parsing succeeded\n";
108 std::cout
<< "-------------------------\n";
112 std::string
rest(iter
, end
);
113 std::cout
<< "-------------------------\n";
114 std::cout
<< "Parsing failed\n";
115 std::cout
<< "stopped at: \"" << rest
<< "\"\n";
116 std::cout
<< "-------------------------\n";
120 std::cout
<< "Bye... :-) \n\n";