From 852543212ba5c68b3428a80187087cc641de612c Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 4 Feb 2018 14:35:59 +0300 Subject: Extract parser input into a separate struct --- src/parser/input.rs | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/parser/input.rs (limited to 'src/parser/input.rs') diff --git a/src/parser/input.rs b/src/parser/input.rs new file mode 100644 index 000000000..162b9ef5f --- /dev/null +++ b/src/parser/input.rs @@ -0,0 +1,77 @@ +use {SyntaxKind, TextRange, TextUnit, Token}; +use syntax_kinds::EOF; +use super::is_insignificant; + +use std::ops::{Add, AddAssign}; + +pub(crate) struct ParserInput<'t> { + #[allow(unused)] + text: &'t str, + #[allow(unused)] + start_offsets: Vec, + tokens: Vec, // non-whitespace tokens +} + +impl<'t> ParserInput<'t> { + pub fn new(text: &'t str, raw_tokens: &'t [Token]) -> ParserInput<'t> { + let mut tokens = Vec::new(); + let mut start_offsets = Vec::new(); + let mut len = TextUnit::new(0); + for &token in raw_tokens.iter() { + if !is_insignificant(token.kind) { + tokens.push(token); + start_offsets.push(len); + } + len += token.len; + } + + ParserInput { + text, + start_offsets, + tokens, + } + } + + pub fn kind(&self, pos: InputPosition) -> SyntaxKind { + let idx = pos.0 as usize; + if !(idx < self.tokens.len()) { + return EOF; + } + self.tokens[idx].kind + } + + #[allow(unused)] + pub fn text(&self, pos: InputPosition) -> &'t str { + let idx = pos.0 as usize; + if !(idx < self.tokens.len()) { + return ""; + } + let start_offset = self.start_offsets[idx]; + let end_offset = self.tokens[idx].len; + let range = TextRange::from_to(start_offset, end_offset); + &self.text[range] + } +} + +#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] +pub(crate) struct InputPosition(u32); + +impl InputPosition { + pub fn new() -> Self { + InputPosition(0) + } +} + +impl Add for InputPosition { + type Output = InputPosition; + + fn add(self, rhs: u32) -> InputPosition { + InputPosition(self.0 + rhs) + } +} + +impl AddAssign for InputPosition { + fn add_assign(&mut self, rhs: u32) { + self.0 += rhs + } +} -- cgit v1.2.3