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