use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use tabnas::{ActionError, Rule, RuleSnapshot, Value};
pub(crate) const PATH_KEY: &str = "toml_path";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Seg {
Key(String),
Index(usize),
}
fn path_to_value(path: &[Seg]) -> Value {
Value::Array(Arc::new(
path.iter()
.map(|seg| match seg {
Seg::Key(key) => Value::String(key.clone()),
#[allow(clippy::cast_precision_loss)]
Seg::Index(index) => Value::Number(*index as f64),
})
.collect(),
))
}
fn value_to_path(value: Option<&Value>) -> Vec<Seg> {
let Some(Value::Array(items)) = value else {
return Vec::new();
};
items
.iter()
.filter_map(|item| match item {
Value::String(key) => Some(Seg::Key(key.clone())),
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Value::Number(index) if *index >= 0.0 => Some(Seg::Index(*index as usize)),
_ => None,
})
.collect()
}
pub(crate) fn path_of(rule: &Rule) -> Vec<Seg> {
value_to_path(rule.u.get(PATH_KEY))
}
pub(crate) fn snapshot_path(rule: Option<&Rc<RuleSnapshot>>) -> Vec<Seg> {
rule.map_or_else(Vec::new, |rule| value_to_path(rule.u.get(PATH_KEY)))
}
pub(crate) fn set_path(rule: &mut Rule, path: &[Seg]) {
let value = path_to_value(path);
rule.u_mut().insert(PATH_KEY.to_string(), value);
}
pub(crate) fn new_map() -> Value {
Value::Object(Arc::new(IndexMap::new()))
}
fn at<'v>(value: &'v Value, path: &[Seg]) -> Option<&'v Value> {
match path.split_first() {
None => Some(value),
Some((seg, rest)) => {
let child = match (value, seg) {
(Value::Object(map), Seg::Key(key)) => map.get(key)?,
(Value::Array(list), Seg::Index(index)) => list.get(*index)?,
_ => return None,
};
at(child, rest)
}
}
}
fn at_mut<'v>(value: &'v mut Value, path: &[Seg]) -> Option<&'v mut Value> {
match path.split_first() {
None => Some(value),
Some((seg, rest)) => {
let child = match (value, seg) {
(Value::Object(map), Seg::Key(key)) => Arc::make_mut(map).get_mut(key)?,
(Value::Array(list), Seg::Index(index)) => Arc::make_mut(list).get_mut(*index)?,
_ => return None,
};
at_mut(child, rest)
}
}
}
pub(crate) fn read(cell: &Rc<RefCell<Value>>, path: &[Seg]) -> Option<Value> {
at(&cell.borrow(), path).cloned()
}
pub(crate) fn is_list(cell: &Rc<RefCell<Value>>, path: &[Seg]) -> bool {
matches!(read(cell, path), Some(Value::Array(_)))
}
pub(crate) fn list_len(cell: &Rc<RefCell<Value>>, path: &[Seg]) -> usize {
match at(&cell.borrow(), path) {
Some(Value::Array(list)) => list.len(),
_ => 0,
}
}
pub(crate) fn write(cell: &Rc<RefCell<Value>>, path: &[Seg], value: Value) {
let Some((last, parent)) = path.split_last() else {
*cell.borrow_mut() = value;
return;
};
let mut root = cell.borrow_mut();
let Some(container) = at_mut(&mut root, parent) else {
return;
};
match (container, last) {
(Value::Object(map), Seg::Key(key)) => {
Arc::make_mut(map).insert(key.clone(), value);
}
(Value::Array(list), Seg::Index(index)) => {
let list = Arc::make_mut(list);
match (*index).cmp(&list.len()) {
Ordering::Less => list[*index] = value,
Ordering::Equal => list.push(value),
Ordering::Greater => {}
}
}
_ => {}
}
}
pub(crate) fn push(cell: &Rc<RefCell<Value>>, path: &[Seg], value: Value) -> Option<usize> {
match at_mut(&mut cell.borrow_mut(), path) {
Some(Value::Array(list)) => {
let list = Arc::make_mut(list);
list.push(value);
Some(list.len() - 1)
}
_ => None,
}
}
pub(crate) fn merge_into(cell: &Rc<RefCell<Value>>, path: &[Seg], source: &Value) {
let Value::Object(entries) = source else {
return;
};
let entries: Vec<(String, Value)> = entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
if let Some(Value::Object(target)) = at_mut(&mut cell.borrow_mut(), path) {
let target = Arc::make_mut(target);
for (key, value) in entries {
target.insert(key, value);
}
}
}
pub(crate) const DESCEND: bool = true;
pub(crate) const DEFINE: bool = false;
fn conflict(key: &str, why: &str) -> ActionError {
ActionError::new("toml_key_conflict", format!("cannot define {key}, {why}"))
}
fn describe(value: &Value) -> String {
format!("it already has the value {}", value.to_json())
}
pub(crate) fn table_at(
cell: &Rc<RefCell<Value>>,
parent: &[Seg],
key: &str,
descend: bool,
) -> Result<Vec<Seg>, ActionError> {
let mut path = parent.to_vec();
path.push(Seg::Key(key.to_string()));
match read(cell, &path) {
None | Some(Value::Undefined) | Some(Value::Null) => {
write(cell, &path, new_map());
Ok(path)
}
Some(Value::Array(_)) => {
if descend {
return Ok(path);
}
Err(conflict(key, "it is already an array of tables"))
}
Some(Value::Object(_)) | Some(Value::MapRef(_)) => Ok(path),
Some(other) => Err(conflict(key, &describe(&other))),
}
}
pub(crate) fn array_at(
cell: &Rc<RefCell<Value>>,
parent: &[Seg],
key: &str,
) -> Result<Vec<Seg>, ActionError> {
let mut path = parent.to_vec();
path.push(Seg::Key(key.to_string()));
match read(cell, &path) {
Some(Value::Array(_)) => Ok(path),
None | Some(Value::Undefined) | Some(Value::Null) => {
write(cell, &path, Value::Array(Arc::new(Vec::new())));
Ok(path)
}
Some(other) => Err(conflict(key, &describe(&other))),
}
}
pub(crate) fn last_of_list(cell: &Rc<RefCell<Value>>, path: &[Seg]) -> Vec<Seg> {
let mut length = list_len(cell, path);
if 0 == length {
push(cell, path, new_map());
length = list_len(cell, path);
}
let mut last = path.to_vec();
last.push(Seg::Index(length.saturating_sub(1)));
last
}