From a14070b05476495cdf5ff555b94fdb2f98506d32 Mon Sep 17 00:00:00 2001 From: ConnorSkees <39542938+ConnorSkees@users.noreply.github.com> Date: Sun, 5 Jan 2020 19:47:50 -0500 Subject: [PATCH] Refactor style parsing --- src/main.rs | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index 32f7f4c..78a262f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,29 +135,53 @@ impl Display for Style { } } +impl Style { + pub fn from_tokens(tokens: &[Token], vars: &HashMap>) -> Result { + StyleParser::new(tokens, vars).parse() + } +} + struct StyleParser<'a> { tokens: &'a [Token], vars: &'a HashMap>, } -impl Style { - fn deref_variable(variable: &TokenKind, vars: &HashMap>) -> String { - let mut val = String::with_capacity(15); - let v = match variable { - TokenKind::Variable(ref v) => vars.get(v).expect("todo! expected variable to exist"), +impl<'a> StyleParser<'a> { + const fn new(tokens: &'a [Token], vars: &'a HashMap>) -> Self { + StyleParser { tokens, vars } + } + + fn deref_variable(&mut self, variable: &TokenKind) -> String { + let mut val = String::with_capacity(25); + let mut v = match variable { + TokenKind::Variable(ref v) => { + self.vars.get(v).expect("todo! expected variable to exist") + } _ => panic!("expected variable"), - }; - for tok in v { + } + .iter() + .peekable(); + while let Some(tok) = v.next() { match &tok.kind { - TokenKind::Variable(_) => val.push_str(&Self::deref_variable(&tok.kind, vars)), + TokenKind::Variable(_) => val.push_str(&self.deref_variable(&tok.kind)), + TokenKind::Whitespace(_) => { + while let Some(w) = v.peek() { + if let TokenKind::Whitespace(_) = w.kind { + v.next(); + } else { + val.push(' '); + break; + } + } + } _ => val.push_str(&tok.kind.to_string()), }; } val } - fn from_tokens(raw: &[Token], vars: &HashMap>) -> Result { - let mut iter = raw.iter(); + fn parse(&mut self) -> Result { + let mut iter = self.tokens.iter(); let property: String; loop { if let Some(tok) = iter.next() { @@ -193,7 +217,7 @@ impl Style { TokenKind::Symbol(s) => value.push(StyleToken::Symbol(s)), TokenKind::Unit(u) => value.push(StyleToken::Ident(u.into())), TokenKind::Variable(_) => { - value.push(StyleToken::Ident(Self::deref_variable(&tok.kind, vars))) + value.push(StyleToken::Ident(self.deref_variable(&tok.kind))) } TokenKind::Number(ref num) => { if let Some(t) = iter.next() { @@ -346,7 +370,6 @@ impl<'a> StyleSheetParser<'a> { fn eat_expr(&mut self, vars: &HashMap>) -> Result { let mut values = Vec::with_capacity(5); while let Some(tok) = self.lexer.next() { - dbg!(&tok.kind); match tok.kind { TokenKind::Symbol(Symbol::SemiColon) | TokenKind::Symbol(Symbol::CloseBrace) => { self.devour_whitespace();