generate_code.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ///////////////////////////////////////////////////////////////////////////////
  6. //
  7. // Several small snippets generating different C++ code constructs
  8. //
  9. // [ HK October 08, 2009 ] Spirit V2.2
  10. //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include <boost/config/warning_disable.hpp>
  13. #include <boost/spirit/include/karma.hpp>
  14. #include <boost/spirit/include/phoenix.hpp>
  15. #include <iostream>
  16. #include <string>
  17. #include <complex>
  18. namespace client
  19. {
  20. namespace karma = boost::spirit::karma;
  21. namespace phoenix = boost::phoenix;
  22. // create for instance: int name[5] = { 1, 2, 3, 4, 5 };
  23. template <typename Iterator>
  24. struct int_array : karma::grammar<Iterator, std::vector<int>()>
  25. {
  26. int_array(char const* name) : int_array::base_type(start)
  27. {
  28. using karma::int_;
  29. using karma::uint_;
  30. using karma::eol;
  31. using karma::lit;
  32. using karma::_val;
  33. using karma::_r1;
  34. start = array_def(phoenix::size(_val)) << " = " << initializer
  35. << ';' << eol;
  36. array_def = "int " << lit(name) << "[" << uint_(_r1) << "]";
  37. initializer = "{ " << -(int_ % ", ") << " }";
  38. }
  39. karma::rule<Iterator, void(unsigned)> array_def;
  40. karma::rule<Iterator, std::vector<int>()> initializer;
  41. karma::rule<Iterator, std::vector<int>()> start;
  42. };
  43. typedef std::back_insert_iterator<std::string> iterator_type;
  44. bool generate_array(char const* name, std::vector<int> const& v)
  45. {
  46. std::string generated;
  47. iterator_type sink(generated);
  48. int_array<iterator_type> g(name);
  49. if (karma::generate(sink, g, v))
  50. {
  51. std::cout << generated;
  52. return true;
  53. }
  54. return false;
  55. }
  56. }
  57. ///////////////////////////////////////////////////////////////////////////////
  58. // Main program
  59. ///////////////////////////////////////////////////////////////////////////////
  60. int main()
  61. {
  62. // generate an array of integers with initializers
  63. std::vector<int> v;
  64. v.push_back(1);
  65. v.push_back(2);
  66. v.push_back(3);
  67. v.push_back(4);
  68. client::generate_array("array1", v);
  69. return 0;
  70. }