actions.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*=============================================================================
  2. Copyright (c) 2001-2015 Joel de Guzman
  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. =============================================================================*/
  6. #include <boost/detail/lightweight_test.hpp>
  7. #include <boost/spirit/home/x3.hpp>
  8. #include <cstring>
  9. #include <functional>
  10. #include "test.hpp"
  11. namespace x3 = boost::spirit::x3;
  12. int x = 0;
  13. auto fun1 =
  14. [](auto& ctx)
  15. {
  16. x += x3::_attr(ctx);
  17. }
  18. ;
  19. struct fun_action
  20. {
  21. template <typename Context>
  22. void operator()(Context const& ctx) const
  23. {
  24. x += x3::_attr(ctx);
  25. }
  26. };
  27. auto fail =
  28. [](auto& ctx)
  29. {
  30. x3::_pass(ctx) = false;
  31. }
  32. ;
  33. struct setnext
  34. {
  35. setnext(char& next) : next(next) {}
  36. template <typename Context>
  37. void operator()(Context const& ctx) const
  38. {
  39. next = x3::_attr(ctx);
  40. }
  41. char& next;
  42. };
  43. struct stationary : boost::noncopyable
  44. {
  45. explicit stationary(int i) : val{i} {}
  46. stationary& operator=(int i) { val = i; return *this; }
  47. int val;
  48. };
  49. int main()
  50. {
  51. using spirit_test::test;
  52. using spirit_test::test_attr;
  53. using x3::int_;
  54. {
  55. char const *s1 = "{42}", *e1 = s1 + std::strlen(s1);
  56. x3::parse(s1, e1, '{' >> int_[fun1] >> '}');
  57. }
  58. {
  59. char const *s1 = "{42}", *e1 = s1 + std::strlen(s1);
  60. x3::parse(s1, e1, '{' >> int_[fun_action()] >> '}');
  61. }
  62. {
  63. using namespace std::placeholders;
  64. char const *s1 = "{42}", *e1 = s1 + std::strlen(s1);
  65. x3::parse(s1, e1, '{' >> int_[std::bind(fun_action(), _1)] >> '}');
  66. }
  67. BOOST_TEST(x == (42*3));
  68. {
  69. std::string input("1234 6543");
  70. char next = '\0';
  71. BOOST_TEST(x3::phrase_parse(input.begin(), input.end(),
  72. x3::int_[fail] | x3::digit[setnext(next)], x3::space));
  73. BOOST_TEST(next == '1');
  74. }
  75. { // ensure no unneded synthesization, copying and moving occured
  76. auto p = '{' >> int_ >> '}';
  77. stationary st { 0 };
  78. BOOST_TEST(test_attr("{42}", p[([]{})], st));
  79. BOOST_TEST_EQ(st.val, 42);
  80. }
  81. return boost::report_errors();
  82. }