diff options
-rw-r--r-- | src/ast.rs | 24 | ||||
-rw-r--r-- | src/taiga.lalrpop | 12 |
2 files changed, 31 insertions, 5 deletions
@@ -1,5 +1,27 @@ #[derive(Debug)] -pub struct Program(pub Box<Expression>); +pub struct WithLocation<T> { + value: T, + location: (usize, usize), +} + +impl<T> WithLocation<T> { + pub fn new(value: T, start: usize, end: usize) -> WithLocation<T> { + WithLocation { + value: value, + location: (start, end), + } + } + + pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> WithLocation<U> { + WithLocation { + value: f(self.value), + location: self.location, + } + } +} + +#[derive(Debug)] +pub struct Program(pub Box<WithLocation<Expression>>); #[derive(Debug)] pub enum Expression { diff --git a/src/taiga.lalrpop b/src/taiga.lalrpop index b60d68f..08c3cd3 100644 --- a/src/taiga.lalrpop +++ b/src/taiga.lalrpop @@ -1,5 +1,5 @@ use std::str::FromStr; -use ast; +use ast::{self, WithLocation}; grammar; @@ -7,8 +7,12 @@ pub Program: ast::Program = { Expression => ast::Program(<>), }; -Expression: Box<ast::Expression> = { - Num => Box::new(ast::Expression::Number(<>)), +Expression: Box<ast::WithLocation<ast::Expression>> = { + Num => Box::new(<>.map(|v| ast::Expression::Number(v))), }; -Num: u64 = r"[0-9]+" => u64::from_str(<>).unwrap(); +Num: WithLocation<u64> = <e: Spanned<r"[0-9]+">> => e.map(|v| u64::from_str(v).unwrap()); + +Spanned<T>: WithLocation<T> = { + <l: @L> <v: T> <r: @R> => WithLocation::new(v, l, r) +}; |