• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*=============================================================================
2     Copyright (c) 2001-2014 Joel de Guzman
3     Copyright (c) 2013-2014 Agustin Berge
4 
5     Distributed under the Boost Software License, Version 1.0. (See accompanying
6     file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 =============================================================================*/
8 ///////////////////////////////////////////////////////////////////////////////
9 //
10 //  A Calculator example demonstrating generation of AST. The AST,
11 //  once created, is traversed, 1) To print its contents and
12 //  2) To evaluate the result.
13 //
14 //  [ JDG April 28, 2008 ]      For BoostCon 2008
15 //  [ JDG February 18, 2011 ]   Pure attributes. No semantic actions.
16 //  [ JDG January 9, 2013 ]     Spirit X3
17 //
18 ///////////////////////////////////////////////////////////////////////////////
19 
20 #include "grammar.hpp"
21 
22 namespace client
23 {
24     ///////////////////////////////////////////////////////////////////////////////
25     //  The calculator grammar
26     ///////////////////////////////////////////////////////////////////////////////
27     namespace calculator_grammar
28     {
29         using x3::uint_;
30         using x3::char_;
31 
32         x3::rule<class expression, ast::program> const expression("expression");
33         x3::rule<class term, ast::program> const term("term");
34         x3::rule<class factor, ast::operand> const factor("factor");
35 
36         auto const expression_def =
37             term
38             >> *(   (char_('+') >> term)
39                 |   (char_('-') >> term)
40                 )
41             ;
42 
43         auto const term_def =
44             factor
45             >> *(   (char_('*') >> factor)
46                 |   (char_('/') >> factor)
47                 )
48             ;
49 
50         auto const factor_def =
51                 uint_
52             |   '(' >> expression >> ')'
53             |   (char_('-') >> factor)
54             |   (char_('+') >> factor)
55             ;
56 
57         BOOST_SPIRIT_DEFINE(
58             expression
59           , term
60           , factor
61         );
62 
calculator()63         parser_type calculator()
64         {
65             return expression;
66         }
67     }
68 }