calc5.cpp 8.7 KB

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