tree_calc_grammar.hpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*=============================================================================
  2. Copyright (c) 2001-2003 Daniel Nuffer
  3. http://spirit.sourceforge.net/
  4. Use, modification and distribution is subject to the Boost Software
  5. License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. http://www.boost.org/LICENSE_1_0.txt)
  7. =============================================================================*/
  8. #ifndef BOOST_SPIRIT_TREE_CALC_GRAMMAR_HPP_
  9. #define BOOST_SPIRIT_TREE_CALC_GRAMMAR_HPP_
  10. using namespace BOOST_SPIRIT_CLASSIC_NS;
  11. ///////////////////////////////////////////////////////////////////////////////
  12. //
  13. // Demonstrates the AST and parse trees. This is discussed in the
  14. // "Trees" chapter in the Spirit User's Guide.
  15. //
  16. ///////////////////////////////////////////////////////////////////////////////
  17. ////////////////////////////////////////////////////////////////////////////
  18. //
  19. // Our calculator grammar
  20. //
  21. ////////////////////////////////////////////////////////////////////////////
  22. struct calculator : public grammar<calculator>
  23. {
  24. static const int integerID = 1;
  25. static const int factorID = 2;
  26. static const int termID = 3;
  27. static const int expressionID = 4;
  28. template <typename ScannerT>
  29. struct definition
  30. {
  31. definition(calculator const& /*self*/)
  32. {
  33. // Start grammar definition
  34. integer = leaf_node_d[ lexeme_d[
  35. (!ch_p('-') >> +digit_p)
  36. ] ];
  37. factor = integer
  38. | inner_node_d[ch_p('(') >> expression >> ch_p(')')]
  39. | (root_node_d[ch_p('-')] >> factor);
  40. term = factor >>
  41. *( (root_node_d[ch_p('*')] >> factor)
  42. | (root_node_d[ch_p('/')] >> factor)
  43. );
  44. expression = term >>
  45. *( (root_node_d[ch_p('+')] >> term)
  46. | (root_node_d[ch_p('-')] >> term)
  47. );
  48. // End grammar definition
  49. // turn on the debugging info.
  50. BOOST_SPIRIT_DEBUG_RULE(integer);
  51. BOOST_SPIRIT_DEBUG_RULE(factor);
  52. BOOST_SPIRIT_DEBUG_RULE(term);
  53. BOOST_SPIRIT_DEBUG_RULE(expression);
  54. }
  55. rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression;
  56. rule<ScannerT, parser_context<>, parser_tag<termID> > term;
  57. rule<ScannerT, parser_context<>, parser_tag<factorID> > factor;
  58. rule<ScannerT, parser_context<>, parser_tag<integerID> > integer;
  59. rule<ScannerT, parser_context<>, parser_tag<expressionID> > const&
  60. start() const { return expression; }
  61. };
  62. };
  63. #endif