word_count_lexer_tokens.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2001-2010 Hartmut Kaiser
  2. //
  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. #if !defined(SPIRIT_LEXER_EXAMPLE_WORD_COUNT_LEXER_TOKENS_FEB_10_2008_0739PM)
  6. #define SPIRIT_LEXER_EXAMPLE_WORD_COUNT_LEXER_TOKENS_FEB_10_2008_0739PM
  7. #include <boost/spirit/include/phoenix_operator.hpp>
  8. #include <boost/spirit/include/phoenix_statement.hpp>
  9. #include <boost/spirit/include/phoenix_core.hpp>
  10. #include <boost/iterator/iterator_traits.hpp>
  11. ///////////////////////////////////////////////////////////////////////////////
  12. // Token definition: We use the lexertl based lexer engine as the underlying
  13. // lexer type.
  14. //
  15. // Note, the token definition type is derived from the 'lexertl_actor_lexer'
  16. // template, which is a necessary to being able to use lexer semantic actions.
  17. ///////////////////////////////////////////////////////////////////////////////
  18. struct distance_func
  19. {
  20. template <typename Iterator1, typename Iterator2>
  21. struct result : boost::iterator_difference<Iterator1> {};
  22. template <typename Iterator1, typename Iterator2>
  23. typename result<Iterator1, Iterator2>::type
  24. operator()(Iterator1& begin, Iterator2& end) const
  25. {
  26. return std::distance(begin, end);
  27. }
  28. };
  29. boost::phoenix::function<distance_func> const distance = distance_func();
  30. //[wcl_static_token_definition
  31. template <typename Lexer>
  32. struct word_count_lexer_tokens : boost::spirit::lex::lexer<Lexer>
  33. {
  34. word_count_lexer_tokens()
  35. : c(0), w(0), l(0)
  36. , word("[^ \t\n]+") // define tokens
  37. , eol("\n")
  38. , any(".")
  39. {
  40. using boost::spirit::lex::_start;
  41. using boost::spirit::lex::_end;
  42. using boost::phoenix::ref;
  43. // associate tokens with the lexer
  44. this->self
  45. = word [++ref(w), ref(c) += distance(_start, _end)]
  46. | eol [++ref(c), ++ref(l)]
  47. | any [++ref(c)]
  48. ;
  49. }
  50. std::size_t c, w, l;
  51. boost::spirit::lex::token_def<> word, eol, any;
  52. };
  53. //]
  54. #endif