1 // Copyright (c) 2001-2012 Hartmut Kaiser
2 // Copyright (c) 2012 Benjamin Schindler
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6
7 #include <boost/config/warning_disable.hpp>
8 #include <boost/detail/lightweight_test.hpp>
9
10 #include <boost/spirit/include/karma.hpp>
11 #include <boost/spirit/include/phoenix.hpp>
12 #include <boost/fusion/include/adapt_struct.hpp>
13 #include <set>
14
15 namespace generator
16 {
17 struct Enum
18 {
19 std::string enumName;
20 std::vector<std::string> enumEntries;
21 };
22 typedef boost::variant<std::string, Enum> VariantType;
23
24 namespace spirit = boost::spirit;
25 namespace karma = spirit::karma;
26 namespace phoenix = boost::phoenix;
27
28 // Our grammar definition
29 template<typename Iterator>
30 struct SettingsHeaderGenerator: karma::grammar<Iterator, VariantType()>
31 {
SettingsHeaderGeneratorgenerator::SettingsHeaderGenerator32 SettingsHeaderGenerator() : SettingsHeaderGenerator::base_type(baseRule)
33 {
34 using phoenix::insert;
35 using phoenix::at_c;
36 using phoenix::push_back;
37 using phoenix::ref;
38 using karma::lit;
39 using karma::string;
40 using namespace karma::labels;
41
42 enumRule = lit("enum ") << string << lit("\n{\n") << string % ",\n" << "}";
43 declarationRule = lit("class ") << string << ';';
44 baseRule = (declarationRule | enumRule) << lit("\n");
45
46 baseRule.name("base");
47 enumRule.name("enum");
48 declarationRule.name("declaration");
49 }
50
51 karma::rule<Iterator, std::string()> declarationRule;
52 karma::rule<Iterator, Enum()> enumRule;
53 karma::rule<Iterator, VariantType()> baseRule;
54 };
55
56 template <typename OutputIterator>
generate_header(OutputIterator & sink,VariantType & data)57 bool generate_header(OutputIterator& sink, VariantType& data)
58 {
59 SettingsHeaderGenerator<OutputIterator> generator;
60 return karma::generate(sink, generator, data);
61 }
62 }
63
64 BOOST_FUSION_ADAPT_STRUCT(generator::Enum,
65 (std::string, enumName)
66 (std::vector<std::string>, enumEntries)
67 );
68
main()69 int main()
70 {
71 generator::VariantType variant = "bla";
72 std::string generated;
73 std::back_insert_iterator<std::string> sink(generated);
74 BOOST_TEST(generator::generate_header(sink, variant));
75 BOOST_TEST(generated == "class bla;\n");
76
77 return boost::report_errors();
78 }
79
80