plain_token.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright (c) 2001-2010 Hartmut Kaiser
  2. // Copyright (c) 2016 Jeffrey E. Trull
  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. #include <boost/detail/lightweight_test.hpp>
  6. #include <boost/config/warning_disable.hpp>
  7. #include <boost/spirit/include/lex_lexertl.hpp>
  8. #include <boost/spirit/include/qi_parse.hpp>
  9. #include <boost/spirit/include/qi_operator.hpp>
  10. #include <string>
  11. namespace qi = boost::spirit::qi;
  12. namespace lex = boost::spirit::lex;
  13. enum tokenids
  14. {
  15. // left tokens
  16. IDLPAREN = lex::min_token_id,
  17. IDLANGLE,
  18. IDLBRACE,
  19. IDLSQUARE,
  20. // right tokens
  21. IDRPAREN,
  22. IDRANGLE,
  23. IDRBRACE,
  24. IDRSQUARE,
  25. IDANY
  26. };
  27. template <typename Lexer>
  28. struct delimiter_tokens : lex::lexer<Lexer>
  29. {
  30. delimiter_tokens()
  31. {
  32. this->self =
  33. lex::char_('(', IDLPAREN)
  34. | lex::char_(')', IDRPAREN)
  35. | lex::char_('<', IDLANGLE)
  36. | lex::char_('>', IDRANGLE)
  37. | lex::char_('{', IDLBRACE)
  38. | lex::char_('}', IDRBRACE)
  39. | lex::char_('[', IDLSQUARE)
  40. | lex::char_(']', IDRSQUARE)
  41. | lex::string(".", IDANY)
  42. ;
  43. }
  44. };
  45. int main()
  46. {
  47. typedef lex::lexertl::token<
  48. std::string::iterator, boost::mpl::vector<std::string>
  49. > token_type;
  50. typedef lex::lexertl::lexer<token_type> lexer_type;
  51. delimiter_tokens<lexer_type> delims;
  52. // two test cases for the token range
  53. std::string angled_delimiter_str("<canvas>");
  54. using qi::token;
  55. // angle brackets
  56. std::string::iterator beg = angled_delimiter_str.begin();
  57. BOOST_TEST(lex::tokenize_and_parse(
  58. beg, angled_delimiter_str.end(),
  59. delims,
  60. token(IDLPAREN, IDLSQUARE)
  61. >> +token(IDANY)
  62. >> token(IDRPAREN, IDRSQUARE)));
  63. std::string paren_delimiter_str("(setq foo nil)");
  64. beg = paren_delimiter_str.begin();
  65. BOOST_TEST(lex::tokenize_and_parse(
  66. beg, paren_delimiter_str.end(),
  67. delims,
  68. token(IDLPAREN, IDLSQUARE)
  69. >> +token(IDANY)
  70. >> token(IDRPAREN, IDRSQUARE)));
  71. // reset and use a regular plain token
  72. beg = paren_delimiter_str.begin();
  73. BOOST_TEST(lex::tokenize_and_parse(
  74. beg, paren_delimiter_str.end(),
  75. delims,
  76. token(IDLPAREN) >> +token(IDANY) >> token(IDRPAREN)));
  77. return boost::report_errors();
  78. }