From cd4fede07287fe7c153a59e01c8425dea893d6ab Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 23 Jun 2014 08:58:44 -0700 Subject: Add a method for converting to (line, column) --- src/parser.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/parser.rs b/src/parser.rs index 96048b4..04ffaed 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -66,6 +66,20 @@ impl<'a> Parser<'a> { } } + /// Converts a byte offset from an error message to a (line, column) pair + /// + /// All indexes are 0-based. + pub fn to_linecol(&self, offset: uint) -> (uint, uint) { + let mut cur = 0; + for (i, line) in self.input.lines().enumerate() { + if cur + line.len() > offset { + return (i, offset - cur) + } + cur += line.len() + 1; + } + return (self.input.lines().count(), 0) + } + fn next_pos(&self) -> uint { self.cur.clone().next().map(|p| p.val0()).unwrap_or(self.input.len()) } @@ -660,3 +674,19 @@ impl<'a> Parser<'a> { } } } + +#[cfg(test)] +mod tests { + use super::Parser; + + #[test] + fn linecol() { + let p = Parser::new("ab\ncde\nf"); + assert_eq!(p.to_linecol(0), (0, 0)); + assert_eq!(p.to_linecol(1), (0, 1)); + assert_eq!(p.to_linecol(3), (1, 0)); + assert_eq!(p.to_linecol(4), (1, 1)); + assert_eq!(p.to_linecol(7), (2, 0)); + } + +} -- cgit v1.2.3