| 1 | #include <boost/spirit/include/qi.hpp>
|
|---|
| 2 |
|
|---|
| 3 | #include <string>
|
|---|
| 4 | #include <sstream>
|
|---|
| 5 | #include <iostream>
|
|---|
| 6 |
|
|---|
| 7 | using namespace boost::spirit;
|
|---|
| 8 |
|
|---|
| 9 | template<typename Iterator>
|
|---|
| 10 | class grammar
|
|---|
| 11 | : public qi::grammar<Iterator, std::string()>
|
|---|
| 12 | {
|
|---|
| 13 | public:
|
|---|
| 14 | grammar();
|
|---|
| 15 | ~grammar();
|
|---|
| 16 |
|
|---|
| 17 | qi::rule<Iterator, std::string()> tok;
|
|---|
| 18 | };
|
|---|
| 19 |
|
|---|
| 20 | void
|
|---|
| 21 | parse(std::string const& str)
|
|---|
| 22 | {
|
|---|
| 23 | static grammar<std::string::const_iterator> gram;
|
|---|
| 24 |
|
|---|
| 25 | std::string::const_iterator i = str.begin();
|
|---|
| 26 | std::string::const_iterator const i_end = str.end();
|
|---|
| 27 |
|
|---|
| 28 | std::string token;
|
|---|
| 29 |
|
|---|
| 30 | std::cerr << "Parsing: " << str << std::endl;
|
|---|
| 31 |
|
|---|
| 32 | try
|
|---|
| 33 | {
|
|---|
| 34 | qi::parse(i, i_end, gram, token);
|
|---|
| 35 | }
|
|---|
| 36 | catch (qi::expectation_failure<std::string::const_iterator>& e)
|
|---|
| 37 | {
|
|---|
| 38 | std::cerr << "Oops: parse" << std::endl;
|
|---|
| 39 | return;
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | if (i != i_end)
|
|---|
| 43 | {
|
|---|
| 44 | std::cerr << "Oops: not all" << std::endl;
|
|---|
| 45 | return;
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | std::cerr << "Parsed: " << token << std::endl;
|
|---|
| 49 |
|
|---|
| 50 | std::cerr << "Length: " << token.size() << std::endl;
|
|---|
| 51 | if (token == "abc")
|
|---|
| 52 | {
|
|---|
| 53 | std::cerr << "Whee!" << std::endl;
|
|---|
| 54 | }
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | int
|
|---|
| 58 | main(int argc, char* argv[])
|
|---|
| 59 | {
|
|---|
| 60 | std::cerr << BOOST_LIB_VERSION << std::endl;
|
|---|
| 61 |
|
|---|
| 62 | parse("asdf");
|
|---|
| 63 | parse("a b c");
|
|---|
| 64 | parse("a-b-c");
|
|---|
| 65 | parse("a_b_c");
|
|---|
| 66 |
|
|---|
| 67 | return 0;
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | template<typename Iterator>
|
|---|
| 71 | grammar<Iterator>
|
|---|
| 72 | ::grammar()
|
|---|
| 73 | : grammar::base_type(tok, "token")
|
|---|
| 74 | {
|
|---|
| 75 | using namespace boost::phoenix;
|
|---|
| 76 |
|
|---|
| 77 | tok %=
|
|---|
| 78 | +( qi::alnum
|
|---|
| 79 | | qi::lit('-')
|
|---|
| 80 | | qi::lit('_')
|
|---|
| 81 | );
|
|---|
| 82 | }
|
|---|
| 83 |
|
|---|
| 84 | template<typename Iterator>
|
|---|
| 85 | grammar<Iterator>
|
|---|
| 86 | ::~grammar()
|
|---|
| 87 | {
|
|---|
| 88 | }
|
|---|