calc5.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*=============================================================================
  2. Copyright (c) 2001-2011 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. //
  14. ///////////////////////////////////////////////////////////////////////////////
  15. ///////////////////////////////////////////////////////////////////////////////
  16. // Spirit v2.5 allows you to suppress automatic generation
  17. // of predefined terminals to speed up complation. With
  18. // BOOST_SPIRIT_NO_PREDEFINED_TERMINALS defined, you are
  19. // responsible in creating instances of the terminals that
  20. // you need (e.g. see qi::uint_type uint_ below).
  21. #define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
  22. ///////////////////////////////////////////////////////////////////////////////
  23. ///////////////////////////////////////////////////////////////////////////////
  24. // Define this to enable debugging
  25. #define BOOST_SPIRIT_QI_DEBUG
  26. ///////////////////////////////////////////////////////////////////////////////
  27. // Uncomment this if you want to enable debugging
  28. //#define BOOST_SPIRIT_QI_DEBUG
  29. ///////////////////////////////////////////////////////////////////////////////
  30. #if defined(_MSC_VER)
  31. # pragma warning(disable: 4345)
  32. #endif
  33. #include <boost/config/warning_disable.hpp>
  34. #include <boost/spirit/include/qi.hpp>
  35. #include <boost/variant/recursive_variant.hpp>
  36. #include <boost/variant/apply_visitor.hpp>
  37. #include <boost/fusion/include/adapt_struct.hpp>
  38. #include <boost/spirit/include/phoenix_function.hpp>
  39. #include <boost/foreach.hpp>
  40. #include <iostream>
  41. #include <string>
  42. namespace client { namespace ast
  43. {
  44. ///////////////////////////////////////////////////////////////////////////
  45. // The AST
  46. ///////////////////////////////////////////////////////////////////////////
  47. struct nil {};
  48. struct signed_;
  49. struct program;
  50. typedef boost::variant<
  51. nil
  52. , unsigned int
  53. , boost::recursive_wrapper<signed_>
  54. , boost::recursive_wrapper<program>
  55. >
  56. operand;
  57. struct signed_
  58. {
  59. char sign;
  60. operand operand_;
  61. };
  62. struct operation
  63. {
  64. char operator_;
  65. operand operand_;
  66. };
  67. struct program
  68. {
  69. operand first;
  70. std::list<operation> rest;
  71. };
  72. // print function for debugging
  73. inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
  74. }}
  75. BOOST_FUSION_ADAPT_STRUCT(
  76. client::ast::signed_,
  77. (char, sign)
  78. (client::ast::operand, operand_)
  79. )
  80. BOOST_FUSION_ADAPT_STRUCT(
  81. client::ast::operation,
  82. (char, operator_)
  83. (client::ast::operand, operand_)
  84. )
  85. BOOST_FUSION_ADAPT_STRUCT(
  86. client::ast::program,
  87. (client::ast::operand, first)
  88. (std::list<client::ast::operation>, rest)
  89. )
  90. namespace client { namespace ast
  91. {
  92. ///////////////////////////////////////////////////////////////////////////
  93. // The AST Printer
  94. ///////////////////////////////////////////////////////////////////////////
  95. struct printer
  96. {
  97. typedef void result_type;
  98. void operator()(nil) const {}
  99. void operator()(unsigned int n) const { std::cout << n; }
  100. void operator()(operation const& x) const
  101. {
  102. boost::apply_visitor(*this, x.operand_);
  103. switch (x.operator_)
  104. {
  105. case '+': std::cout << " add"; break;
  106. case '-': std::cout << " subt"; break;
  107. case '*': std::cout << " mult"; break;
  108. case '/': std::cout << " div"; break;
  109. }
  110. }
  111. void operator()(signed_ const& x) const
  112. {
  113. boost::apply_visitor(*this, x.operand_);
  114. switch (x.sign)
  115. {
  116. case '-': std::cout << " neg"; break;
  117. case '+': std::cout << " pos"; break;
  118. }
  119. }
  120. void operator()(program const& x) const
  121. {
  122. boost::apply_visitor(*this, x.first);
  123. BOOST_FOREACH(operation const& oper, x.rest)
  124. {
  125. std::cout << ' ';
  126. (*this)(oper);
  127. }
  128. }
  129. };
  130. ///////////////////////////////////////////////////////////////////////////
  131. // The AST evaluator
  132. ///////////////////////////////////////////////////////////////////////////
  133. struct eval
  134. {
  135. typedef int result_type;
  136. int operator()(nil) const { BOOST_ASSERT(0); return 0; }
  137. int operator()(unsigned int n) const { return n; }
  138. int operator()(operation const& x, int lhs) const
  139. {
  140. int rhs = boost::apply_visitor(*this, x.operand_);
  141. switch (x.operator_)
  142. {
  143. case '+': return lhs + rhs;
  144. case '-': return lhs - rhs;
  145. case '*': return lhs * rhs;
  146. case '/': return lhs / rhs;
  147. }
  148. BOOST_ASSERT(0);
  149. return 0;
  150. }
  151. int operator()(signed_ const& x) const
  152. {
  153. int rhs = boost::apply_visitor(*this, x.operand_);
  154. switch (x.sign)
  155. {
  156. case '-': return -rhs;
  157. case '+': return +rhs;
  158. }
  159. BOOST_ASSERT(0);
  160. return 0;
  161. }
  162. int operator()(program const& x) const
  163. {
  164. int state = boost::apply_visitor(*this, x.first);
  165. BOOST_FOREACH(operation const& oper, x.rest)
  166. {
  167. state = (*this)(oper, state);
  168. }
  169. return state;
  170. }
  171. };
  172. }}
  173. namespace client
  174. {
  175. namespace qi = boost::spirit::qi;
  176. namespace ascii = boost::spirit::ascii;
  177. using boost::phoenix::function;
  178. ///////////////////////////////////////////////////////////////////////////////
  179. // Our error handler
  180. ///////////////////////////////////////////////////////////////////////////////
  181. struct error_handler_
  182. {
  183. template <typename, typename, typename>
  184. struct result { typedef void type; };
  185. template <typename Iterator>
  186. void operator()(
  187. qi::info const& what
  188. , Iterator err_pos, Iterator last) const
  189. {
  190. std::cout
  191. << "Error! Expecting "
  192. << what // what failed?
  193. << " here: \""
  194. << std::string(err_pos, last) // iterators to error-pos, end
  195. << "\""
  196. << std::endl
  197. ;
  198. }
  199. };
  200. function<error_handler_> const error_handler = error_handler_();
  201. ///////////////////////////////////////////////////////////////////////////////
  202. // Our calculator grammar
  203. ///////////////////////////////////////////////////////////////////////////////
  204. template <typename Iterator>
  205. struct calculator : qi::grammar<Iterator, ast::program(), ascii::space_type>
  206. {
  207. calculator() : calculator::base_type(expression)
  208. {
  209. qi::char_type char_;
  210. qi::uint_type uint_;
  211. qi::_2_type _2;
  212. qi::_3_type _3;
  213. qi::_4_type _4;
  214. using qi::on_error;
  215. using qi::fail;
  216. expression =
  217. term
  218. >> *( (char_('+') > term)
  219. | (char_('-') > term)
  220. )
  221. ;
  222. term =
  223. factor
  224. >> *( (char_('*') > factor)
  225. | (char_('/') > factor)
  226. )
  227. ;
  228. factor =
  229. uint_
  230. | '(' > expression > ')'
  231. | (char_('-') > factor)
  232. | (char_('+') > factor)
  233. ;
  234. // Debugging and error handling and reporting support.
  235. BOOST_SPIRIT_DEBUG_NODE(expression);
  236. BOOST_SPIRIT_DEBUG_NODE(term);
  237. BOOST_SPIRIT_DEBUG_NODE(factor);
  238. // Error handling
  239. on_error<fail>(expression, error_handler(_4, _3, _2));
  240. }
  241. qi::rule<Iterator, ast::program(), ascii::space_type> expression;
  242. qi::rule<Iterator, ast::program(), ascii::space_type> term;
  243. qi::rule<Iterator, ast::operand(), ascii::space_type> factor;
  244. };
  245. }
  246. ///////////////////////////////////////////////////////////////////////////////
  247. // Main program
  248. ///////////////////////////////////////////////////////////////////////////////
  249. int
  250. main()
  251. {
  252. std::cout << "/////////////////////////////////////////////////////////\n\n";
  253. std::cout << "Expression parser...\n\n";
  254. std::cout << "/////////////////////////////////////////////////////////\n\n";
  255. std::cout << "Type an expression...or [q or Q] to quit\n\n";
  256. typedef std::string::const_iterator iterator_type;
  257. typedef client::calculator<iterator_type> calculator;
  258. typedef client::ast::program ast_program;
  259. typedef client::ast::printer ast_print;
  260. typedef client::ast::eval ast_eval;
  261. std::string str;
  262. while (std::getline(std::cin, str))
  263. {
  264. if (str.empty() || str[0] == 'q' || str[0] == 'Q')
  265. break;
  266. calculator calc; // Our grammar
  267. ast_program program; // Our program (AST)
  268. ast_print print; // Prints the program
  269. ast_eval eval; // Evaluates the program
  270. std::string::const_iterator iter = str.begin();
  271. std::string::const_iterator end = str.end();
  272. boost::spirit::ascii::space_type space;
  273. bool r = phrase_parse(iter, end, calc, space, program);
  274. if (r && iter == end)
  275. {
  276. std::cout << "-------------------------\n";
  277. std::cout << "Parsing succeeded\n";
  278. print(program);
  279. std::cout << "\nResult: " << eval(program) << std::endl;
  280. std::cout << "-------------------------\n";
  281. }
  282. else
  283. {
  284. std::string rest(iter, end);
  285. std::cout << "-------------------------\n";
  286. std::cout << "Parsing failed\n";
  287. std::cout << "-------------------------\n";
  288. }
  289. }
  290. std::cout << "Bye... :-) \n\n";
  291. return 0;
  292. }