#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/phoenix/statement.hpp>
#include <boost/phoenix/core.hpp>
#include <iostream>
#include <string>
#include "example.hpp"
using namespace boost::spirit;
enum tokenids
{
IDANY = lex::min_token_id + 10,
IDEOL = lex::min_token_id + 11
};
template <typename Char, typename Traits>
struct echo_input_functor
{
echo_input_functor (std::basic_ostream<Char, Traits>& os_)
: os(os_) {}
template <typename Iterator, typename Context>
void operator()(Iterator const& b, Iterator const& e
, BOOST_SCOPED_ENUM(boost::spirit::lex::pass_flags)&
, std::size_t&, Context&) const
{
os << std::string(b, e);
}
std::basic_ostream<Char, Traits>& os;
};
template <typename Char, typename Traits>
inline echo_input_functor<Char, Traits>
echo_input(std::basic_ostream<Char, Traits>& os)
{
return echo_input_functor<Char, Traits>(os);
}
struct set_lexer_state
{
set_lexer_state(char const* state_)
: state(state_) {}
template <typename Iterator, typename Context>
void operator()(Iterator const&, Iterator const&
, BOOST_SCOPED_ENUM(boost::spirit::lex::pass_flags)&
, std::size_t&, Context& ctx) const
{
ctx.set_state_name(state.c_str());
}
std::string state;
};
template <typename Lexer>
struct strip_comments_tokens : lex::lexer<Lexer>
{
strip_comments_tokens()
: strip_comments_tokens::base_type(lex::match_flags::match_default)
{
cppcomment = "\"//\"[^\n]*"; ccomment = "\"/*\""; endcomment = "\"*/\""; any = std::string(".");
eol = "\n";
this->self
= cppcomment
| ccomment [ set_lexer_state("COMMENT") ]
| eol [ echo_input(std::cout) ]
| any [ echo_input(std::cout) ]
;
this->self("COMMENT")
= endcomment [ set_lexer_state("INITIAL") ]
| "\n"
| std::string(".")
;
}
lex::token_def<> cppcomment, ccomment, endcomment, any, eol;
};
int main(int argc, char* argv[])
{
typedef std::string::iterator base_iterator_type;
typedef
lex::lexertl::actor_lexer<lex::lexertl::token<base_iterator_type> >
lexer_type;
strip_comments_tokens<lexer_type> strip_comments;
std::string str (read_from_file(1 == argc ? "strip_comments.input" : argv[1]));
base_iterator_type first = str.begin();
bool r = lex::tokenize(first, str.end(), strip_comments);
if (!r) {
std::string rest(first, str.end());
std::cerr << "Lexical analysis failed\n" << "stopped at: \""
<< rest << "\"\n";
}
return 0;
}