From 35bf004cc923c1bd61a75fa0ff9b336644f0c8b0 Mon Sep 17 00:00:00 2001
From: David Li
Date: Sat, 4 Nov 2017 08:34:52 -0400
Subject: Add location information to AST
---
src/ast.rs | 24 +++++++++++++++++++++++-
src/taiga.lalrpop | 12 ++++++++----
2 files changed, 31 insertions(+), 5 deletions(-)
(limited to 'src')
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);
+pub struct WithLocation {
+ value: T,
+ location: (usize, usize),
+}
+
+impl WithLocation {
+ pub fn new(value: T, start: usize, end: usize) -> WithLocation {
+ WithLocation {
+ value: value,
+ location: (start, end),
+ }
+ }
+
+ pub fn map U>(self, f: F) -> WithLocation {
+ WithLocation {
+ value: f(self.value),
+ location: self.location,
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Program(pub Box>);
#[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 = {
- Num => Box::new(ast::Expression::Number(<>)),
+Expression: Box> = {
+ Num => Box::new(<>.map(|v| ast::Expression::Number(v))),
};
-Num: u64 = r"[0-9]+" => u64::from_str(<>).unwrap();
+Num: WithLocation = > => e.map(|v| u64::from_str(v).unwrap());
+
+Spanned: WithLocation = {
+ => WithLocation::new(v, l, r)
+};
--
cgit v1.2.3