Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <string>
- #include <boost/spirit/include/lex_lexertl.hpp>
- #include <boost/spirit/include/qi.hpp>
- #include <boost/spirit/include/support_utree.hpp>
- #include <boost/spirit/include/phoenix_function.hpp>
- #include <boost/spirit/include/phoenix_object.hpp>
- #include <boost/spirit/include/phoenix_stl.hpp>
- namespace lex = boost::spirit::lex;
- namespace qi = boost::spirit::qi;
- namespace spirit = boost::spirit;
- namespace phx = boost::phoenix;
- using lex::token_def;
- using qi::rule;
- using qi::_1;
- using qi::_2;
- using qi::_val;
- using spirit::utree;
- using phx::construct;
- // base iterator type
- typedef std::string::iterator BaseIteratorT;
- // token type
- typedef lex::lexertl::token<BaseIteratorT, boost::mpl::vector<double, int, std::string> > TokenT;
- // lexer type
- typedef lex::lexertl::actor_lexer<TokenT> LexerT;
- template <typename LexerT>
- struct Tokens: public lex::lexer<LexerT>
- {
- Tokens()
- {
- using lex::_pass;
- using lex::pass_flags;
- // literals
- symbol = "[a-zA-Z_?](\\w|\\?)*|@(\\w|\\?)+";
- arrow = "->";
- dot = '.';
- assign = "=";
- // literal rules
- this->self += symbol;
- this->self += arrow;
- this->self += dot;
- this->self += assign;
- }
- ~Tokens() {}
- // literal tokens
- token_def<std::string> symbol;
- token_def<> arrow, dot;
- token_def<lex::omit> assign;
- };
- struct ternaryImpl
- {
- template <typename Expr1Type, typename Expr2Type>
- struct result { typedef utree type; };
- template <typename Expr1Type, typename Expr2Type>
- utree operator()(Expr1Type &vec, Expr2Type &operand) const {
- utree ret;
- for (typename Expr1Type::iterator it = vec.begin(); it != vec.end(); ++it) {
- // some code
- ret = *it;
- // more code
- }
- // some code here
- return ret;
- }
- };
- phx::function<ternaryImpl> ternary = ternaryImpl();
- template <typename Iterator>
- struct Parser: public qi::grammar<Iterator, utree()>
- {
- template <typename Tokens>
- Parser(const Tokens &toks):
- Parser::base_type(expression)
- {
- expression =
- factor
- | (
- +(
- (
- toks.symbol
- [
- _val = construct<utree::list_type>()
- // some code here
- ]
- | (
- factor >>
- +(
- toks.arrow >> factor
- | toks.dot >> factor
- )
- )
- [
- _val = construct<utree::list_type>()
- // some code here
- ]
- ) >> toks.assign
- ) >> factor
- ) [ _val = ternary(_1, _2) ]
- ;
- }
- rule<Iterator, utree()> expression, factor;
- };
- int main()
- {
- typedef Tokens<LexerT>::iterator_type IteratorT;
- Tokens<LexerT> l;
- Parser<IteratorT> p(l);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement