diff --git a/src/path/mod.rs b/src/path/mod.rs index f96abb4f..333a4d57 100644 --- a/src/path/mod.rs +++ b/src/path/mod.rs @@ -7,10 +7,18 @@ use crate::value::{Value, ValueKind}; mod parser; #[derive(Debug, Eq, PartialEq, Clone, Hash)] -pub(crate) enum Expression { - Identifier(String), - Child(Box, String), - Subscript(Box, isize), +pub(crate) struct Expression { + root: String, + postfix: Vec, +} + +impl Expression { + pub(crate) fn root(root: String) -> Self { + Self { + root, + postfix: Vec::new(), + } + } } impl FromStr for Expression { @@ -23,6 +31,12 @@ impl FromStr for Expression { } } +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +enum Postfix { + Key(String), + Index(isize), +} + #[derive(Debug)] struct ParseError(String); @@ -53,186 +67,97 @@ fn abs_index(index: isize, len: usize) -> Result { impl Expression { pub(crate) fn get(self, root: &Value) -> Option<&Value> { - match self { - Self::Identifier(id) => { - match root.kind { - // `x` access on a table is equivalent to: map[x] - ValueKind::Table(ref map) => map.get(&id), - - // all other variants return None - _ => None, + let ValueKind::Table(map) = &root.kind else { + return None; + }; + let mut child = map.get(&self.root)?; + for postfix in &self.postfix { + match postfix { + Postfix::Key(key) => { + let ValueKind::Table(map) = &child.kind else { + return None; + }; + child = map.get(key)?; } - } - - Self::Child(expr, key) => { - match expr.get(root) { - Some(value) => { - match value.kind { - // Access on a table is identical to Identifier, it just forwards - ValueKind::Table(ref map) => map.get(&key), - - // all other variants return None - _ => None, - } - } - - _ => None, + Postfix::Index(rel_index) => { + let ValueKind::Array(array) = &child.kind else { + return None; + }; + let index = abs_index(*rel_index, array.len()).ok()?; + child = array.get(index)?; } } - - Self::Subscript(expr, index) => match expr.get(root) { - Some(value) => match value.kind { - ValueKind::Array(ref array) => { - let index = abs_index(index, array.len()).ok()?; - array.get(index) - } - - _ => None, - }, - - _ => None, - }, } + Some(child) } - pub(crate) fn get_mut_forcibly<'a>(&self, root: &'a mut Value) -> Option<&'a mut Value> { - match *self { - Self::Identifier(ref id) => match root.kind { - ValueKind::Table(ref mut map) => Some( - map.entry(id.clone()) - .or_insert_with(|| Value::new(None, ValueKind::Nil)), - ), - - _ => None, - }, - - Self::Child(ref expr, ref key) => match expr.get_mut_forcibly(root) { - Some(value) => { - if let ValueKind::Table(ref mut map) = value.kind { - Some( - map.entry(key.clone()) - .or_insert_with(|| Value::new(None, ValueKind::Nil)), - ) - } else { - *value = Map::::new().into(); - - if let ValueKind::Table(ref mut map) = value.kind { - Some( - map.entry(key.clone()) - .or_insert_with(|| Value::new(None, ValueKind::Nil)), - ) - } else { - unreachable!(); - } + pub(crate) fn get_mut_forcibly<'a>(&self, root: &'a mut Value) -> &'a mut Value { + if !matches!(root.kind, ValueKind::Table(_)) { + *root = Map::::new().into(); + } + let ValueKind::Table(map) = &mut root.kind else { + unreachable!() + }; + let mut child = map + .entry(self.root.clone()) + .or_insert_with(|| Value::new(None, ValueKind::Nil)); + for postfix in &self.postfix { + match postfix { + Postfix::Key(key) => { + if !matches!(child.kind, ValueKind::Table(_)) { + *child = Map::::new().into(); } - } - - _ => None, - }, + let ValueKind::Table(ref mut map) = child.kind else { + unreachable!() + }; - Self::Subscript(ref expr, index) => match expr.get_mut_forcibly(root) { - Some(value) => { - match value.kind { - ValueKind::Array(_) => (), - _ => *value = Vec::::new().into(), + child = map + .entry(key.clone()) + .or_insert_with(|| Value::new(None, ValueKind::Nil)); + } + Postfix::Index(rel_index) => { + if !matches!(child.kind, ValueKind::Array(_)) { + *child = Vec::::new().into(); } - - match value.kind { - ValueKind::Array(ref mut array) => { - let index = abs_index(index, array.len()).ok()?; - - if index >= array.len() { - array.resize(index + 1, Value::new(None, ValueKind::Nil)); + let ValueKind::Array(ref mut array) = child.kind else { + unreachable!() + }; + + let uindex = match abs_index(*rel_index, array.len()) { + Ok(uindex) => { + if uindex >= array.len() { + array.resize(uindex + 1, Value::new(None, ValueKind::Nil)); } - - Some(&mut array[index]) + uindex + } + Err(insertion) => { + array.splice( + 0..0, + (0..insertion).map(|_| Value::new(None, ValueKind::Nil)), + ); + 0 } + }; - _ => None, - } + child = &mut array[uindex]; } - _ => None, - }, + } } + child } pub(crate) fn set(&self, root: &mut Value, value: Value) { - match *self { - Self::Identifier(ref id) => { - // Ensure that root is a table - match root.kind { - ValueKind::Table(_) => {} - - _ => { - *root = Map::::new().into(); - } - } - - match value.kind { - ValueKind::Table(ref incoming_map) => { - // Pull out another table - let target = if let ValueKind::Table(ref mut map) = root.kind { - map.entry(id.clone()) - .or_insert_with(|| Map::::new().into()) - } else { - unreachable!(); - }; - - // Continue the deep merge - for (key, val) in incoming_map { - Self::Identifier(key.clone()).set(target, val.clone()); - } - } - - _ => { - if let ValueKind::Table(ref mut map) = root.kind { - // Just do a simple set - if let Some(existing) = map.get_mut(id) { - *existing = value; - } else { - map.insert(id.clone(), value); - } - } - } - } - } - - Self::Child(ref expr, ref key) => { - if let Some(parent) = expr.get_mut_forcibly(root) { - if !matches!(parent.kind, ValueKind::Table(_)) { - // Didn't find a table. Oh well. Make a table and do this anyway - *parent = Map::::new().into(); - } - Self::Identifier(key.clone()).set(parent, value); + let parent = self.get_mut_forcibly(root); + match value.kind { + ValueKind::Table(ref incoming_map) => { + // Continue the deep merge + for (key, val) in incoming_map { + Self::root(key.clone()).set(parent, val.clone()); } } - Self::Subscript(ref expr, index) => { - if let Some(parent) = expr.get_mut_forcibly(root) { - if !matches!(parent.kind, ValueKind::Array(_)) { - *parent = Vec::::new().into(); - } - - if let ValueKind::Array(ref mut array) = parent.kind { - let uindex = match abs_index(index, array.len()) { - Ok(uindex) => { - if uindex >= array.len() { - array.resize(uindex + 1, Value::new(None, ValueKind::Nil)); - } - uindex - } - Err(insertion) => { - array.splice( - 0..0, - (0..insertion).map(|_| Value::new(None, ValueKind::Nil)), - ); - 0 - } - }; - - array[uindex] = value; - } - } + _ => { + *parent = value; } } } diff --git a/src/path/parser.rs b/src/path/parser.rs index dcd0f284..3b45fb77 100644 --- a/src/path/parser.rs +++ b/src/path/parser.rs @@ -17,6 +17,7 @@ use winnow::token::any; use winnow::token::take_while; use crate::path::Expression; +use crate::path::Postfix; pub(crate) fn from_str(input: &str) -> Result> { path.parse(input) @@ -24,33 +25,22 @@ pub(crate) fn from_str(input: &str) -> Result PResult { let root = ident.parse_next(i)?; - let expr = repeat(0.., postfix) - .fold( - || root.clone(), - |prev, cur| match cur { - Child::Key(k) => Expression::Child(Box::new(prev), k), - Child::Index(k) => Expression::Subscript(Box::new(prev), k), - }, - ) - .parse_next(i)?; + let postfix = repeat(0.., postfix).parse_next(i)?; + let expr = Expression { root, postfix }; Ok(expr) } -fn ident(i: &mut &str) -> PResult { - raw_ident.map(Expression::Identifier).parse_next(i) -} - -fn postfix(i: &mut &str) -> PResult { +fn postfix(i: &mut &str) -> PResult { dispatch! {any; '[' => cut_err( seq!( - integer.map(Child::Index), + integer.map(Postfix::Index), _: ']'.context(StrContext::Expected(StrContextValue::CharLiteral(']'))), ) .map(|(i,)| i) .context(StrContext::Label("subscript")) ), - '.' => cut_err(raw_ident.map(Child::Key)), + '.' => cut_err(ident.map(Postfix::Key)), _ => cut_err( fail .context(StrContext::Label("postfix")) @@ -61,14 +51,9 @@ fn postfix(i: &mut &str) -> PResult { .parse_next(i) } -enum Child { - Key(String), - Index(isize), -} - -fn raw_ident(i: &mut &str) -> PResult { +fn ident(i: &mut &str) -> PResult { take_while(1.., ('a'..='z', 'A'..='Z', '0'..='9', '_', '-')) - .map(ToString::to_string) + .map(ToOwned::to_owned) .context(StrContext::Label("identifier")) .context(StrContext::Expected(StrContextValue::Description( "ASCII alphanumeric", @@ -93,53 +78,115 @@ fn integer(i: &mut &str) -> PResult { #[cfg(test)] mod test { + use snapbox::prelude::*; use snapbox::{assert_data_eq, str}; - use super::Expression::*; use super::*; #[test] fn test_id() { let parsed: Expression = from_str("abcd").unwrap(); - assert_eq!(parsed, Identifier("abcd".into())); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd", + postfix: [], +} + +"#]] + ); } #[test] fn test_id_dash() { let parsed: Expression = from_str("abcd-efgh").unwrap(); - assert_eq!(parsed, Identifier("abcd-efgh".into())); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd-efgh", + postfix: [], +} + +"#]] + ); } #[test] fn test_child() { let parsed: Expression = from_str("abcd.efgh").unwrap(); - let expected = Child(Box::new(Identifier("abcd".into())), "efgh".into()); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd", + postfix: [ + Key( + "efgh", + ), + ], +} - assert_eq!(parsed, expected); +"#]] + ); let parsed: Expression = from_str("abcd.efgh.ijkl").unwrap(); - let expected = Child( - Box::new(Child(Box::new(Identifier("abcd".into())), "efgh".into())), - "ijkl".into(), - ); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd", + postfix: [ + Key( + "efgh", + ), + Key( + "ijkl", + ), + ], +} - assert_eq!(parsed, expected); +"#]] + ); } #[test] fn test_subscript() { let parsed: Expression = from_str("abcd[12]").unwrap(); - let expected = Subscript(Box::new(Identifier("abcd".into())), 12); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd", + postfix: [ + Index( + 12, + ), + ], +} - assert_eq!(parsed, expected); +"#]] + ); } #[test] fn test_subscript_neg() { let parsed: Expression = from_str("abcd[-1]").unwrap(); - let expected = Subscript(Box::new(Identifier("abcd".into())), -1); + assert_data_eq!( + parsed.to_debug(), + str![[r#" +Expression { + root: "abcd", + postfix: [ + Index( + -1, + ), + ], +} - assert_eq!(parsed, expected); +"#]] + ); } #[test] diff --git a/src/source.rs b/src/source.rs index b68e3950..c11bae5e 100644 --- a/src/source.rs +++ b/src/source.rs @@ -33,7 +33,7 @@ fn set_value(cache: &mut Value, key: &str, value: &Value) { Ok(expr) => expr.set(cache, value.clone()), // Set directly anyway - _ => path::Expression::Identifier(key.to_owned()).set(cache, value.clone()), + _ => path::Expression::root(key.to_owned()).set(cache, value.clone()), } }