Update Span to include line and col information

pest::Span and pest::Position both carry a ref to the input text, while
we carry an Rc<String> so we don't have to supply the lifetime
everywhere we use Spans (which is everywhere). They also calculate line
information on-the-fly, while we cache it.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2022-02-16 15:39:05 -08:00
parent d77bf48fe9
commit 8c0e1a02f5
2 changed files with 24 additions and 8 deletions

View File

@@ -66,8 +66,8 @@ fn parse_atom(source: &Rc<String>, pair: Pair<Rule>) -> Result<SpAtom> {
}; };
let span = Span { let span = Span {
source: Rc::clone(source), source: Rc::clone(source),
start: pair_span.start(), start: pair_span.start_pos().into(),
end: pair_span.end(), end: pair_span.end_pos().into(),
}; };
Ok(SpAtom::new(span, atom)) Ok(SpAtom::new(span, atom))
} }
@@ -85,8 +85,8 @@ fn parse_expr(source: &Rc<String>, pair: Pair<Rule>) -> Result<SpExpr> {
}; };
let span = Span { let span = Span {
source: Rc::clone(source), source: Rc::clone(source),
start: pair_span.start(), start: pair_span.start_pos().into(),
end: pair_span.end(), end: pair_span.end_pos().into(),
}; };
Ok(SpExpr::new(span, expr)) Ok(SpExpr::new(span, expr))
} }
@@ -100,8 +100,8 @@ fn parse_stmt(source: &Rc<String>, pair: Pair<Rule>) -> Result<SpStmt> {
}; };
let span = Span { let span = Span {
source: Rc::clone(&source), source: Rc::clone(&source),
start: pair_span.start(), start: pair_span.start_pos().into(),
end: pair_span.end(), end: pair_span.end_pos().into(),
}; };
Ok(SpStmt::new(span, stmt)) Ok(SpStmt::new(span, stmt))
} }

View File

@@ -3,12 +3,28 @@
use std::fmt::{self, Debug}; use std::fmt::{self, Debug};
use std::rc::Rc; use std::rc::Rc;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Pos {
/// The byte index of this position.
pub source: usize,
pub line: usize,
pub col: usize,
}
impl From<pest::Position<'_>> for Pos {
fn from(other: pest::Position) -> Self {
let (line, col) = other.line_col();
let source = other.pos();
Pos { source, line, col }
}
}
#[cfg_attr(not(test), derive(PartialEq))] #[cfg_attr(not(test), derive(PartialEq))]
#[derive(Debug, Default, Clone, Eq)] #[derive(Debug, Default, Clone, Eq)]
pub struct Span { pub struct Span {
pub source: Rc<String>, pub source: Rc<String>,
pub start: usize, pub start: Pos,
pub end: usize, pub end: Pos,
} }
#[cfg(test)] #[cfg(test)]