I created a simple parser in Rust and defined the AST like this:
enum Expression {
Number(i32),
BinaryOperator(Box<Expression>, Operator, Box<Expression>),
Identifier(String),
}
enum ProgramLine {
SetIdentifier(String, Expression),
Print(Expression),
}
struct Program {
lines: Vec<ProgramLine>,
}
I would like to keep information about where these nodes come from, so when there is an error, I can also report the line number.
How is it solved in parsers? My first idea is to add something line linenumber to each type, like this:
enum Expression {
Number(i32, i32),
BinaryOperator(Box<Expression>, Operator, Box<Expression>, i32),
Identifier(String, i32),
}
But it does not seem right, because the AST should only represent the syntax tree of the language. But where should I store a context like this?
rustc
does it or talk to its developers?&str
). You can recalculate the line + column number from that later. If you have multiple source files, the span must contain a reference/name/ID for the file.