I'm using Boost Spirit to parse source files in a little compiler project.
If an error arise during the parsing itself, I can print the position of the error, but how do I do in later phase, typically when performing semantic checks ?
My source file is parsed into an Abstract Syntax Tree using auto rules. I want to add line and col informations into the AST nodes. Is there a easy way to achieve that during parsing ?
I'm using boost::spirit::classic::position_iterator2 in my Lexer and then use this lexer in my grammar.
Thank you
EDIT for sehe:
The lexer is defined like that:
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef boost::spirit::lex::lexertl::actor_lexer<Tok> lexer_type;
template<typename L>
class SpiritLexer : public lex::lexer<L> {
//Token definitions
}
typedef lexer_type::iterator_type Iterator;
typedef SpiritLexer<lexer_type> Lexer;
The grammars are defined like that:
struct EddiGrammar : qi::grammar<lexer::Iterator, ast::SourceFile()> {
EddiGrammar(const lexer::Lexer& lexer);
//Token definitions
};
And finally, here is how I parse the source:
ast::SourceFile program
std::ifstream in(file.c_str());
in.unsetf(std::ios::skipws);
in.seekg(0, std::istream::end);
std::size_t size(static_cast<size_t>(in.tellg()));
in.seekg(0, std::istream::beg);
std::string contents(size, 0);
in.read(&contents[0], size);
pos_iterator_type position_begin(contents.begin(), contents.end(), file);
pos_iterator_type position_end;
Lexer lexer;
EddiGrammar grammar(lexer);
bool r = spirit::lex::tokenize_and_parse(position_begin, position_end, lexer, grammar, program);
In my grammar, I use the lexer by referring to some lexer tokens. For example:
else_ %=
lexer.else_
>> lexer.left_brace
>> *(instruction)
>> lexer.right_brace;
All my AST nodes are constructed using auto rules.