1/*=============================================================================
2 Copyright (c) 2001-2014 Joel de Guzman
3
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///////////////////////////////////////////////////////////////////////////////
8//
9// Same as Calc4, this time, we'll incorporate debugging support,
10// plus error handling and reporting.
11//
12// [ JDG April 28, 2008 ] For BoostCon 2008
13// [ JDG February 18, 2011 ] Pure attributes. No semantic actions.
14// [ JDG April 9, 2014 ] Spirit X3
15//
16///////////////////////////////////////////////////////////////////////////////
17
18///////////////////////////////////////////////////////////////////////////////
19// Uncomment this if you want to enable debugging
20//#define BOOST_SPIRIT_X3_DEBUG
21
22#include <boost/spirit/home/x3.hpp>
23#include <boost/spirit/home/x3/support/ast/variant.hpp>
24#include <boost/fusion/include/adapt_struct.hpp>
25
26#include <iostream>
27#include <string>
28#include <list>
29#include <numeric>
30
31namespace x3 = boost::spirit::x3;
32
33namespace client { namespace ast
34{
35 ///////////////////////////////////////////////////////////////////////////
36 // The AST
37 ///////////////////////////////////////////////////////////////////////////
38 struct nil {};
39 struct signed_;
40 struct program;
41
42 struct operand : x3::variant<
43 nil
44 , unsigned int
45 , x3::forward_ast<signed_>
46 , x3::forward_ast<program>
47 >
48 {
49 using base_type::base_type;
50 using base_type::operator=;
51 };
52
53 struct signed_
54 {
55 char sign;
56 operand operand_;
57 };
58
59 struct operation
60 {
61 char operator_;
62 operand operand_;
63 };
64
65 struct program
66 {
67 operand first;
68 std::list<operation> rest;
69 };
70
71 // print function for debugging
72 inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
73}}
74
75BOOST_FUSION_ADAPT_STRUCT(client::ast::signed_,
76 sign, operand_
77)
78
79BOOST_FUSION_ADAPT_STRUCT(client::ast::operation,
80 operator_, operand_
81)
82
83BOOST_FUSION_ADAPT_STRUCT(client::ast::program,
84 first, rest
85)
86
87namespace client { namespace ast
88{
89 ///////////////////////////////////////////////////////////////////////////
90 // The AST Printer
91 ///////////////////////////////////////////////////////////////////////////
92 struct printer
93 {
94 typedef void result_type;
95
96 void operator()(nil) const {}
97 void operator()(unsigned int n) const { std::cout << n; }
98
99 void operator()(operation const& x) const
100 {
101 boost::apply_visitor(visitor: *this, visitable: x.operand_);
102 switch (x.operator_)
103 {
104 case '+': std::cout << " add"; break;
105 case '-': std::cout << " subt"; break;
106 case '*': std::cout << " mult"; break;
107 case '/': std::cout << " div"; break;
108 }
109 }
110
111 void operator()(signed_ const& x) const
112 {
113 boost::apply_visitor(visitor: *this, visitable: x.operand_);
114 switch (x.sign)
115 {
116 case '-': std::cout << " neg"; break;
117 case '+': std::cout << " pos"; break;
118 }
119 }
120
121 void operator()(program const& x) const
122 {
123 boost::apply_visitor(visitor: *this, visitable: x.first);
124 for (operation const& oper : x.rest)
125 {
126 std::cout << ' ';
127 (*this)(oper);
128 }
129 }
130 };
131
132 ///////////////////////////////////////////////////////////////////////////
133 // The AST evaluator
134 ///////////////////////////////////////////////////////////////////////////
135 struct eval
136 {
137 typedef int result_type;
138
139 int operator()(nil) const { BOOST_ASSERT(0); return 0; }
140 int operator()(unsigned int n) const { return n; }
141
142 int operator()(operation const& x, int lhs) const
143 {
144 int rhs = boost::apply_visitor(visitor: *this, visitable: x.operand_);
145 switch (x.operator_)
146 {
147 case '+': return lhs + rhs;
148 case '-': return lhs - rhs;
149 case '*': return lhs * rhs;
150 case '/': return lhs / rhs;
151 }
152 BOOST_ASSERT(0);
153 return 0;
154 }
155
156 int operator()(signed_ const& x) const
157 {
158 int rhs = boost::apply_visitor(visitor: *this, visitable: x.operand_);
159 switch (x.sign)
160 {
161 case '-': return -rhs;
162 case '+': return +rhs;
163 }
164 BOOST_ASSERT(0);
165 return 0;
166 }
167
168 int operator()(program const& x) const
169 {
170 int state = boost::apply_visitor(visitor: *this, visitable: x.first);
171 for (operation const& oper : x.rest)
172 {
173 state = (*this)(oper, state);
174 }
175 return state;
176 }
177 };
178}}
179
180namespace client
181{
182 ///////////////////////////////////////////////////////////////////////////////
183 // The calculator grammar
184 ///////////////////////////////////////////////////////////////////////////////
185 namespace calculator_grammar
186 {
187 using x3::uint_;
188 using x3::char_;
189
190 struct expression_class;
191 struct term_class;
192 struct factor_class;
193
194 x3::rule<expression_class, ast::program> const expression("expression");
195 x3::rule<term_class, ast::program> const term("term");
196 x3::rule<factor_class, ast::operand> const factor("factor");
197
198 auto const expression_def =
199 term
200 >> *( (char_('+') > term)
201 | (char_('-') > term)
202 )
203 ;
204
205 auto const term_def =
206 factor
207 >> *( (char_('*') > factor)
208 | (char_('/') > factor)
209 )
210 ;
211
212 auto const factor_def =
213 uint_
214 | '(' > expression > ')'
215 | (char_('-') > factor)
216 | (char_('+') > factor)
217 ;
218
219 BOOST_SPIRIT_DEFINE(
220 expression
221 , term
222 , factor
223 );
224
225 struct expression_class
226 {
227 // Our error handler
228 template <typename Iterator, typename Exception, typename Context>
229 x3::error_handler_result
230 on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context)
231 {
232 std::cout
233 << "Error! Expecting: "
234 << x.which()
235 << " here: \""
236 << std::string(x.where(), last)
237 << "\""
238 << std::endl
239 ;
240 return x3::error_handler_result::fail;
241 }
242 };
243
244 auto calculator = expression;
245 }
246
247 using calculator_grammar::calculator;
248}
249
250///////////////////////////////////////////////////////////////////////////////
251// Main program
252///////////////////////////////////////////////////////////////////////////////
253int
254main()
255{
256 std::cout << "/////////////////////////////////////////////////////////\n\n";
257 std::cout << "Expression parser...\n\n";
258 std::cout << "/////////////////////////////////////////////////////////\n\n";
259 std::cout << "Type an expression...or [q or Q] to quit\n\n";
260
261 typedef std::string::const_iterator iterator_type;
262 typedef client::ast::program ast_program;
263 typedef client::ast::printer ast_print;
264 typedef client::ast::eval ast_eval;
265
266 std::string str;
267 while (std::getline(is&: std::cin, str&: str))
268 {
269 if (str.empty() || str[0] == 'q' || str[0] == 'Q')
270 break;
271
272 auto& calc = client::calculator; // Our grammar
273 ast_program program; // Our program (AST)
274 ast_print print; // Prints the program
275 ast_eval eval; // Evaluates the program
276
277 iterator_type iter = str.begin();
278 iterator_type end = str.end();
279 boost::spirit::x3::ascii::space_type space;
280 bool r = phrase_parse(first&: iter, last: end, p: calc, s: space, attr&: program);
281
282 if (r && iter == end)
283 {
284 std::cout << "-------------------------\n";
285 std::cout << "Parsing succeeded\n";
286 print(program);
287 std::cout << "\nResult: " << eval(program) << std::endl;
288 std::cout << "-------------------------\n";
289 }
290 else
291 {
292 std::cout << "-------------------------\n";
293 std::cout << "Parsing failed\n";
294 std::cout << "-------------------------\n";
295 }
296 }
297
298 std::cout << "Bye... :-) \n\n";
299 return 0;
300}
301

source code of boost/libs/spirit/example/x3/calc/calc5.cpp