#[cfg(test)]
mod tests;
use super::{Failure, system_root};
use crate::effect::PathSegment;
use predicator_rs::{Key, Map, Value};
pub(crate) const MAX_LIST_LENGTH: i64 = 1 << 20;
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum LocationReason {
NotAssignable,
ComputedKey,
UndefinedVariable(String),
InvalidKey(Value),
NotAContainer,
InvalidIndex(i64),
}
impl LocationReason {
pub(crate) fn as_str(&self) -> &'static str {
match self {
LocationReason::NotAssignable => "not_assignable",
LocationReason::ComputedKey => "computed_key",
LocationReason::UndefinedVariable(_) => "undefined_variable",
LocationReason::InvalidKey(_) => "invalid_key",
LocationReason::NotAContainer => "not_a_container",
LocationReason::InvalidIndex(_) => "invalid_index",
}
}
pub(crate) fn message(&self) -> String {
match self {
LocationReason::NotAssignable => String::from("the text is not an assignable location"),
LocationReason::ComputedKey => {
String::from("a computed expression cannot be a location's key")
}
LocationReason::UndefinedVariable(name) => {
format!("the bracket key variable {name} is not defined")
}
LocationReason::InvalidKey(value) => {
format!("a bracket key must be a string or an integer, not {value:?}")
}
LocationReason::NotAContainer => {
String::from("the location runs through a value that is not a container")
}
LocationReason::InvalidIndex(index) => format!("{index} is not a writable list index"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Written {
pub(crate) data: Map,
pub(crate) path: Vec<PathSegment>,
pub(crate) prior_value: Value,
pub(crate) new_value: Value,
}
pub(crate) fn write_location(data: &Map, source: &str, value: Value) -> Result<Written, Failure> {
let failure = |reason| Failure::Location {
source: source.to_owned(),
reason,
};
let path = resolve(source, data).map_err(failure)?;
let Some(PathSegment::Key(root)) = path.first() else {
return Err(failure(LocationReason::NotAssignable));
};
if system_root(root) {
return Err(Failure::SystemVariable(root.clone()));
}
if !data.contains_key(&Key::from(root.as_str())) {
return Err(Failure::UnboundLocation(source.to_owned()));
}
let prior_value = read_path(data, &path);
let mut written = data.clone();
put(&mut written, &path, value.clone()).map_err(failure)?;
Ok(Written {
data: written,
path,
prior_value,
new_value: value,
})
}
#[derive(Debug, Clone, PartialEq)]
enum Bracket {
Text(String),
Integer(i64),
Name(String),
Computed,
}
#[derive(Debug, Clone, PartialEq)]
enum Access {
Property(String),
Bracket(Bracket),
}
pub(crate) fn resolve(source: &str, data: &Map) -> Result<Vec<PathSegment>, LocationReason> {
let (root, accesses) = parse(source).ok_or(LocationReason::NotAssignable)?;
let mut keys = Vec::with_capacity(accesses.len());
for access in accesses.iter().rev() {
keys.push(match access {
Access::Property(name) => PathSegment::Key(name.clone()),
Access::Bracket(bracket) => bracket_key(bracket, data)?,
});
}
let root = root.ok_or(LocationReason::NotAssignable)?;
let mut path = Vec::with_capacity(keys.len() + 1);
path.push(PathSegment::Key(root));
path.extend(keys.into_iter().rev());
Ok(path)
}
fn bracket_key(bracket: &Bracket, data: &Map) -> Result<PathSegment, LocationReason> {
match bracket {
Bracket::Text(text) => Ok(PathSegment::Key(text.clone())),
Bracket::Integer(index) => Ok(PathSegment::Index(*index)),
Bracket::Name(name) => match data.get(&Key::from(name.as_str())) {
Some(Value::String(text)) => Ok(PathSegment::Key(text.clone())),
Some(Value::Integer(index)) => Ok(PathSegment::Index(*index)),
None | Some(Value::Null) => Err(LocationReason::UndefinedVariable(name.clone())),
Some(other) => Err(LocationReason::InvalidKey(other.clone())),
},
Bracket::Computed => Err(LocationReason::ComputedKey),
}
}
const RESERVED: [&str; 22] = [
"true",
"false",
"undefined",
"null",
"AND",
"and",
"OR",
"or",
"NOT",
"not",
"IN",
"in",
"CONTAINS",
"contains",
"if",
"else",
"while",
"ago",
"from",
"now",
"next",
"last",
];
fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
}
fn parse(source: &str) -> Option<(Option<String>, Vec<Access>)> {
let mut cursor = Cursor {
bytes: source.as_bytes(),
at: 0,
};
cursor.skip_space();
let root = match cursor.word() {
Some(word) if !RESERVED.contains(&word) => Some(word.to_owned()),
Some(_) => None,
None => {
cursor.root_literal()?;
None
}
};
let mut accesses = Vec::new();
loop {
cursor.skip_space();
match cursor.peek() {
None => return Some((root, accesses)),
Some(b'.') => {
cursor.at += 1;
cursor.skip_space();
let word = cursor.word()?;
if RESERVED.contains(&word) {
return None;
}
accesses.push(Access::Property(word.to_owned()));
}
Some(b'[') => {
cursor.at += 1;
let inner = cursor.bracket_body()?;
accesses.push(Access::Bracket(bracket(inner)));
}
Some(_) => return None,
}
}
}
fn bracket(inner: &str) -> Bracket {
let text = inner.trim_matches(|c: char| c.is_ascii() && is_space(c as u8));
if let Some(value) = string_literal(text) {
return Bracket::Text(value);
}
if let Some(index) = integer_literal(text) {
return Bracket::Integer(index);
}
let mut cursor = Cursor {
bytes: text.as_bytes(),
at: 0,
};
match cursor.word() {
Some(word) if cursor.at == text.len() && !RESERVED.contains(&word) => {
Bracket::Name(word.to_owned())
}
_ => Bracket::Computed,
}
}
fn string_literal(text: &str) -> Option<String> {
let mut chars = text.chars();
let quote = chars.next().filter(|c| *c == '\'' || *c == '"')?;
let mut value = String::new();
while let Some(c) = chars.next() {
match c {
'\\' => value.push(match chars.next()? {
'n' => '\n',
't' => '\t',
'r' => '\r',
'u' | 'U' => return None,
other => other,
}),
c if c == quote => return chars.next().is_none().then_some(value),
c => value.push(c),
}
}
None
}
fn integer_literal(text: &str) -> Option<i64> {
let (negative, digits) = match text.strip_prefix('-') {
Some(rest) => (true, rest.trim_start_matches([' ', '\t', '\n', '\r'])),
None => (false, text),
};
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
let magnitude: i64 = digits.parse().ok()?;
Some(if negative { -magnitude } else { magnitude })
}
struct Cursor<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Cursor<'a> {
fn peek(&self) -> Option<u8> {
self.bytes.get(self.at).copied()
}
fn skip_space(&mut self) {
while self.peek().is_some_and(is_space) {
self.at += 1;
}
}
fn word(&mut self) -> Option<&'a str> {
let start = self.at;
if !self
.peek()
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
{
return None;
}
while self
.peek()
.is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
{
self.at += 1;
}
std::str::from_utf8(self.bytes.get(start..self.at)?).ok()
}
fn root_literal(&mut self) -> Option<()> {
match self.peek()? {
quote @ (b'\'' | b'"') => {
self.at += 1;
while let Some(byte) = self.peek() {
self.at += 1;
match byte {
b'\\' => self.escape()?,
byte if byte == quote => return Some(()),
_ => {}
}
}
None
}
byte if byte.is_ascii_digit() => {
while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
self.at += 1;
}
Some(())
}
_ => None,
}
}
fn escape(&mut self) -> Option<()> {
if matches!(self.peek(), Some(b'u' | b'U')) {
return None;
}
self.at += 1;
Some(())
}
fn bracket_body(&mut self) -> Option<&'a str> {
let start = self.at;
let mut depth = 0_usize;
let mut quote = None;
while let Some(byte) = self.peek() {
self.at += 1;
match (quote, byte) {
(Some(_), b'\\') => self.escape()?,
(Some(open), byte) if byte == open => quote = None,
(Some(_), _) => {}
(None, b'\'' | b'"') => quote = Some(byte),
(None, b'[') => depth += 1,
(None, b']') if depth == 0 => {
return std::str::from_utf8(self.bytes.get(start..self.at - 1)?).ok();
}
(None, b']') => depth -= 1,
(None, _) => {}
}
}
None
}
}
pub(crate) fn read_path(data: &Map, path: &[PathSegment]) -> Value {
let Some((PathSegment::Key(root), rest)) = path.split_first() else {
return Value::Undefined;
};
let Some(mut value) = data.get(&Key::from(root.as_str())) else {
return Value::Undefined;
};
for segment in rest {
let next = match (value, segment) {
(Value::Map(map), PathSegment::Key(key)) => map.get(&Key::from(key.as_str())),
(Value::List(list), PathSegment::Index(index)) => usize::try_from(*index)
.ok()
.and_then(|index| list.get(index)),
_ => None,
};
match next {
Some(found) => value = found,
None => return Value::Undefined,
}
}
value.clone()
}
fn key(segment: &PathSegment) -> Key {
match segment {
PathSegment::Key(name) => Key::from(name.as_str()),
PathSegment::Index(index) => Key::from(*index),
}
}
fn put(data: &mut Map, path: &[PathSegment], value: Value) -> Result<(), LocationReason> {
let Some((first, rest)) = path.split_first() else {
return Err(LocationReason::NotAssignable);
};
let slot = key(first);
let Some(next) = rest.first() else {
data.insert(slot, value);
return Ok(());
};
let child = data.get(&slot).cloned().unwrap_or(Value::Undefined);
let child = put_in(vivify(child, next)?, rest, value)?;
data.insert(slot, child);
Ok(())
}
fn put_in(
mut container: Value,
path: &[PathSegment],
value: Value,
) -> Result<Value, LocationReason> {
let Some((segment, rest)) = path.split_first() else {
return Ok(value);
};
match &mut container {
Value::Map(map) => {
put(map, path, value)?;
Ok(container)
}
Value::List(list) => {
let PathSegment::Index(index) = segment else {
return Err(LocationReason::NotAContainer);
};
let position = list_position(*index, list.len())?;
let child = match rest.first() {
None => value,
Some(next) => {
let current = list.get(position).cloned().unwrap_or(Value::Undefined);
put_in(vivify(current, next)?, rest, value)?
}
};
if position < list.len() {
if let Some(slot) = list.get_mut(position) {
*slot = child;
}
} else {
list.resize(position, Value::Undefined);
list.push(child);
}
Ok(container)
}
_ => Err(LocationReason::NotAContainer),
}
}
fn list_position(index: i64, length: usize) -> Result<usize, LocationReason> {
let position = usize::try_from(index).map_err(|_| LocationReason::InvalidIndex(index))?;
if position >= length && index >= MAX_LIST_LENGTH {
return Err(LocationReason::InvalidIndex(index));
}
Ok(position)
}
fn vivify(value: Value, next: &PathSegment) -> Result<Value, LocationReason> {
match (value, next) {
(Value::Null | Value::Undefined, PathSegment::Index(_)) => Ok(Value::List(Vec::new())),
(Value::Null | Value::Undefined, PathSegment::Key(_)) => Ok(Value::Map(Map::new())),
(value @ (Value::Map(_) | Value::List(_)), _) => Ok(value),
_ => Err(LocationReason::NotAContainer),
}
}