summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Li <li.davidm96@gmail.com>2017-11-04 08:34:52 -0400
committerDavid Li <li.davidm96@gmail.com>2017-11-04 08:34:52 -0400
commit35bf004cc923c1bd61a75fa0ff9b336644f0c8b0 (patch)
tree4a06430b9289a03f047a4650c51149078887ec5b
parent8b3f3271be72b89f557d84238f9e3df5c1ea418c (diff)
Add location information to AST
-rw-r--r--src/ast.rs24
-rw-r--r--src/taiga.lalrpop12
2 files changed, 31 insertions, 5 deletions
diff --git a/src/ast.rs b/src/ast.rs
index b5f2049..3863ce9 100644
--- a/src/ast.rs
+++ b/src/ast.rs
@@ -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)
+};