use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use tabnas::{ActionError, Context, Rule, RuleSnapshot, Value};
pub(crate) type Cell = Rc<RefCell<Value>>;
pub(crate) const PATH_KEY: &str = "toml_path";
const PATHS_KEY: &str = "toml_paths";
const PARKED_KEY: &str = "toml_parked";
const IMPLICIT_KEY: &str = "toml_implicit";
const ROOT_KEY: &str = "toml_root";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Path {
id: usize,
len: usize,
}
impl Path {
pub(crate) const ROOT: Path = Path { id: 0, len: 0 };
pub(crate) fn len(self) -> usize {
self.len
}
}
#[allow(clippy::cast_precision_loss)]
fn number(count: usize) -> Value {
Value::Number(count as f64)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn count(value: Option<&Value>) -> Option<usize> {
match value {
Some(Value::Number(number)) if *number >= 0.0 && 0.0 == number.fract() => {
Some(*number as usize)
}
_ => None,
}
}
fn path_from(value: Option<&Value>) -> Path {
let Some(Value::Array(parts)) = value else {
return Path::ROOT;
};
match (count(parts.first()), count(parts.get(1))) {
(Some(id), Some(len)) if 0 < len => Path { id, len },
_ => Path::ROOT,
}
}
pub(crate) fn path_of(rule: &Rule) -> Path {
path_from(rule.u.get(PATH_KEY))
}
pub(crate) fn snapshot_path(rule: Option<&Rc<RuleSnapshot>>) -> Path {
rule.map_or(Path::ROOT, |rule| path_from(rule.u.get(PATH_KEY)))
}
pub(crate) fn set_path(rule: &mut Rule, path: Path) {
let value = Value::Array(Arc::new(vec![number(path.id), number(path.len)]));
rule.u_mut().insert(PATH_KEY.to_string(), value);
}
fn buffers_mut(context: &mut Context) -> &mut Vec<Value> {
if !matches!(context.u.get(PATHS_KEY), Some(Value::Array(_))) {
context
.u
.insert(PATHS_KEY.to_string(), Value::Array(Arc::new(Vec::new())));
}
match context.u.get_mut(PATHS_KEY) {
Some(Value::Array(buffers)) => Arc::make_mut(buffers),
_ => unreachable!("the path registry was installed just above"),
}
}
fn segments(context: &Context, path: Path) -> &[Value] {
if 0 == path.len {
return &[];
}
let Some(Value::Array(buffers)) = context.u.get(PATHS_KEY) else {
return &[];
};
match buffers.get(path.id) {
Some(Value::Array(segments)) => segments.get(..path.len).unwrap_or(&[]),
_ => &[],
}
}
fn extend(context: &mut Context, path: Path, segment: Value) -> Path {
let buffers = buffers_mut(context);
let prefix = if 0 == path.len {
Vec::new()
} else {
match buffers.get_mut(path.id) {
Some(Value::Array(segments)) if segments.len() == path.len => {
Arc::make_mut(segments).push(segment);
return Path {
id: path.id,
len: path.len + 1,
};
}
Some(Value::Array(segments)) => segments
.get(..path.len)
.map(<[Value]>::to_vec)
.unwrap_or_default(),
_ => Vec::new(),
}
};
let mut segments = prefix;
segments.push(segment);
let len = segments.len();
buffers.push(Value::Array(Arc::new(segments)));
Path {
id: buffers.len() - 1,
len,
}
}
pub(crate) fn new_map() -> Value {
Value::Object(Arc::new(IndexMap::new()))
}
fn position(segment: &Value) -> Option<usize> {
count(Some(segment))
}
fn at<'v>(mut value: &'v Value, path: &[Value]) -> Option<&'v Value> {
for segment in path {
value = match (value, segment) {
(Value::Object(map), Value::String(key)) => map.get(key)?,
(Value::Array(list), Value::Number(_)) => list.get(position(segment)?)?,
_ => return None,
};
}
Some(value)
}
fn at_mut<'v>(mut value: &'v mut Value, path: &[Value]) -> Option<&'v mut Value> {
for segment in path {
value = match (value, segment) {
(Value::Object(map), Value::String(key)) => Arc::make_mut(map).get_mut(key)?,
(Value::Array(list), Value::Number(_)) => {
Arc::make_mut(list).get_mut(position(segment)?)?
}
_ => return None,
};
}
Some(value)
}
fn write(cell: &Cell, parent: &[Value], last: &Value, value: Value) {
let mut root = cell.borrow_mut();
let Some(container) = at_mut(&mut root, parent) else {
return;
};
match (container, last) {
(Value::Object(map), Value::String(key)) => {
Arc::make_mut(map).insert(key.clone(), value);
}
(Value::Array(list), Value::Number(_)) => {
let Some(index) = position(last) else {
return;
};
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 write_at(context: &mut Context, cell: &Cell, path: Path, key: String, value: Value) {
settle(context, cell);
write(cell, segments(context, path), &Value::String(key), value);
}
pub(crate) fn merge_into(context: &mut Context, cell: &Cell, path: Path, source: &Value) {
settle(context, cell);
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(), segments(context, path)) {
let target = Arc::make_mut(target);
for (key, value) in entries {
target.insert(key, value);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Reach {
Descend,
Define,
Dive,
}
fn conflict(key: &str, why: &str) -> ActionError {
ActionError::new("toml_key_conflict", format!("cannot define {key}, {why}"))
}
pub(crate) const ALREADY_DEFINED: &str = "it is already defined";
pub(crate) fn redefined(key: &str) -> ActionError {
conflict(key, ALREADY_DEFINED)
}
pub(crate) fn existing_at(
context: &mut Context,
cell: &Cell,
path: Path,
key: &str,
) -> Option<Value> {
settle(context, cell);
let root = cell.borrow();
match at(&root, segments(context, path)) {
Some(Value::Object(map)) => match map.get(key) {
None | Some(Value::Undefined | Value::Null) => None,
Some(existing) => Some(existing.clone()),
},
_ => None,
}
}
fn trie_mut(context: &mut Context) -> &mut IndexMap<String, Value> {
if !matches!(context.u.get(IMPLICIT_KEY), Some(Value::Object(_))) {
context.u.insert(
IMPLICIT_KEY.to_string(),
Value::Object(Arc::new(IndexMap::new())),
);
}
match context.u.get_mut(IMPLICIT_KEY) {
Some(Value::Object(trie)) => Arc::make_mut(trie),
_ => unreachable!("the trie was installed just above"),
}
}
fn trie_key(parent: usize, segment: &Value) -> String {
match segment {
Value::String(key) => format!("{parent}:{key}"),
other => format!("{parent}:{}", position(other).unwrap_or(0)),
}
}
fn trie_entry(context: &mut Context, parent: usize, segment: &Value) -> (usize, bool) {
let key = trie_key(parent, segment);
let trie = trie_mut(context);
if let Some(Value::Array(entry)) = trie.get(&key) {
if let Some(id) = count(entry.first()) {
return (id, matches!(entry.get(1), Some(Value::Bool(true))));
}
}
let id = trie.len() + 1;
trie.insert(
key,
Value::Array(Arc::new(vec![number(id), Value::Bool(false)])),
);
(id, false)
}
fn trie_child(context: &mut Context, parent: usize, segment: &Value) -> usize {
trie_entry(context, parent, segment).0
}
pub(crate) fn set_root(context: &mut Context, cell: &Cell) {
let id = cell_id(cell) as u64;
let halves = Value::Array(Arc::new(vec![
number((id >> 32) as usize),
number((id & 0xffff_ffff) as usize),
]));
context.u.insert(ROOT_KEY.to_string(), halves);
}
fn is_root(context: &Context, cell: usize) -> bool {
let Some(Value::Array(halves)) = context.u.get(ROOT_KEY) else {
return false;
};
match (count(halves.first()), count(halves.get(1))) {
#[allow(clippy::cast_possible_truncation)]
(Some(high), Some(low)) => cell == (((high as u64) << 32) | low as u64) as usize,
_ => false,
}
}
fn set_implicit(context: &mut Context, parent: usize, segment: &Value, implicit: bool) -> bool {
let (id, was) = trie_entry(context, parent, segment);
let key = trie_key(parent, segment);
trie_mut(context).insert(
key,
Value::Array(Arc::new(vec![number(id), Value::Bool(implicit)])),
);
was
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fresh {
Table,
Array,
}
impl Fresh {
fn empty(self) -> Value {
match self {
Fresh::Table => new_map(),
Fresh::Array => Value::Array(Arc::new(Vec::new())),
}
}
}
enum Here {
Node(Value),
Fresh(Fresh),
Absent,
}
#[derive(Debug, Clone, Copy)]
struct Pending {
base: usize,
end: usize,
last: Fresh,
}
pub(crate) struct Cursor {
cell: usize,
path: Path,
trie: usize,
here: Here,
pending: Option<Pending>,
}
fn cell_id(cell: &Cell) -> usize {
Rc::as_ptr(cell).addr()
}
impl Cursor {
pub(crate) fn resume(context: &mut Context, cell: &Cell, path: Path) -> Cursor {
if let Some(parked) = take_parked(context) {
if parked.cell != cell_id(cell) {
parked.store(context);
} else if parked.path == path {
return parked;
} else {
parked.finish(context, cell);
}
}
Cursor::find(context, cell, path)
}
fn find(context: &mut Context, cell: &Cell, path: Path) -> Cursor {
let parts = segments(context, path).to_vec();
let here = at(&cell.borrow(), &parts).map_or(Here::Absent, |node| Here::Node(node.clone()));
let trie = parts
.iter()
.fold(0, |trie, segment| trie_child(context, trie, segment));
Cursor {
cell: cell_id(cell),
path,
trie,
here,
pending: None,
}
}
pub(crate) fn path(&self) -> Path {
self.path
}
pub(crate) fn is_list(&self) -> bool {
matches!(
self.here,
Here::Node(Value::Array(_)) | Here::Fresh(Fresh::Array)
)
}
fn child(&self, key: &str) -> Option<&Value> {
match &self.here {
Here::Node(Value::Object(map)) => map.get(key),
_ => None,
}
}
pub(crate) fn has_list(&self, key: &str) -> bool {
matches!(self.child(key), Some(Value::Array(_)))
}
pub(crate) fn enter(&mut self, context: &mut Context, key: &str) {
let here = self
.child(key)
.map_or(Here::Absent, |node| Here::Node(node.clone()));
let segment = Value::String(key.to_string());
self.trie = trie_child(context, self.trie, &segment);
self.path = extend(context, self.path, segment);
self.here = here;
}
fn create(&mut self, context: &mut Context, segment: Value, fresh: Fresh) {
let takes = match (&self.here, &segment) {
(Here::Node(Value::Object(_)) | Here::Fresh(Fresh::Table), Value::String(_)) => true,
(Here::Node(Value::Array(list)), Value::Number(_)) => {
position(&segment).is_some_and(|index| index <= list.len())
}
(Here::Fresh(Fresh::Array), Value::Number(_)) => Some(0) == position(&segment),
_ => false,
};
let from = self.path.len;
self.trie = trie_child(context, self.trie, &segment);
self.path = extend(context, self.path, segment);
if !takes {
self.here = Here::Absent;
return;
}
debug_assert!(self.pending.is_none_or(|pending| pending.end == from));
let base = self.pending.map_or(from, |pending| pending.base);
self.pending = Some(Pending {
base,
end: self.path.len,
last: fresh,
});
self.here = Here::Fresh(fresh);
}
pub(crate) fn table_at(
&mut self,
context: &mut Context,
key: &str,
reach: Reach,
) -> Result<(), ActionError> {
match self.child(key) {
None | Some(Value::Undefined | Value::Null) => {
let segment = Value::String(key.to_string());
if Reach::Descend == reach {
set_implicit(context, self.trie, &segment, true);
}
self.create(context, segment, Fresh::Table);
Ok(())
}
Some(Value::Array(_)) => {
if Reach::Define != reach {
self.enter(context, key);
return Ok(());
}
Err(conflict(key, "it is already an array of tables"))
}
Some(Value::Object(_) | Value::MapRef(_)) => {
let segment = Value::String(key.to_string());
match reach {
Reach::Define => {
if !set_implicit(context, self.trie, &segment, false) {
return Err(conflict(key, "it is already defined"));
}
}
Reach::Dive => {
if is_root(context, self.cell) {
set_implicit(context, self.trie, &segment, false);
}
}
Reach::Descend => {}
}
self.enter(context, key);
Ok(())
}
Some(_) => Err(redefined(key)),
}
}
pub(crate) fn array_at(&mut self, context: &mut Context, key: &str) -> Result<(), ActionError> {
match self.child(key) {
Some(Value::Array(_)) => {
self.enter(context, key);
Ok(())
}
None | Some(Value::Undefined | Value::Null) => {
self.create(context, Value::String(key.to_string()), Fresh::Array);
Ok(())
}
Some(_) => Err(redefined(key)),
}
}
pub(crate) fn last_of_list(&mut self, context: &mut Context) {
let last = match &self.here {
Here::Node(Value::Array(list)) => list
.len()
.checked_sub(1)
.map(|index| (index, list[index].clone())),
_ => None,
};
match last {
Some((index, node)) => {
self.trie = trie_child(context, self.trie, &number(index));
self.path = extend(context, self.path, number(index));
self.here = Here::Node(node);
}
None => self.create(context, number(0), Fresh::Table),
}
}
pub(crate) fn push_table(&mut self, context: &mut Context) {
let index = match &self.here {
Here::Node(Value::Array(list)) => list.len(),
_ => 0,
};
self.create(context, number(index), Fresh::Table);
}
pub(crate) fn finish(self, context: &Context, cell: &Cell) {
let Cursor {
path,
here,
pending,
..
} = self;
drop(here);
let Some(pending) = pending else {
return;
};
let segments = segments(context, path);
let (Some(parent), Some(slot), Some(below)) = (
segments.get(..pending.base),
segments.get(pending.base),
segments.get(pending.base + 1..pending.end),
) else {
return;
};
let mut value = pending.last.empty();
for segment in below.iter().rev() {
value = match segment {
Value::String(key) => {
let mut map = IndexMap::new();
map.insert(key.clone(), value);
Value::Object(Arc::new(map))
}
_ => Value::Array(Arc::new(vec![value])),
};
}
write(cell, parent, slot, value);
}
pub(crate) fn park(self, context: &mut Context, cell: &Cell) {
if context.options.parse.recover.enabled {
self.finish(context, cell);
} else {
self.store(context);
}
}
fn store(self, context: &mut Context) {
let (here, node) = match self.here {
Here::Node(node) => (0, node),
Here::Fresh(Fresh::Table) => (1, Value::Undefined),
Here::Fresh(Fresh::Array) => (2, Value::Undefined),
Here::Absent => (3, Value::Undefined),
};
let (base, end, last) = self.pending.map_or((0, 0, 0), |pending| {
let last = if Fresh::Array == pending.last { 2 } else { 1 };
(pending.base + 1, pending.end, last)
});
let cell = self.cell as u64;
let parked = Value::Array(Arc::new(vec![
number((cell >> 32) as usize),
number((cell & 0xffff_ffff) as usize),
number(self.path.id),
number(self.path.len),
number(here),
node,
number(base),
number(end),
number(last),
number(self.trie),
]));
match context.u.get_mut(PARKED_KEY) {
Some(Value::Array(stack)) => Arc::make_mut(stack).push(parked),
_ => {
context
.u
.insert(PARKED_KEY.to_string(), Value::Array(Arc::new(vec![parked])));
}
}
}
}
fn take_parked(context: &mut Context) -> Option<Cursor> {
let Some(Value::Array(stack)) = context.u.get_mut(PARKED_KEY) else {
return None;
};
let Value::Array(parts) = Arc::make_mut(stack).pop()? else {
return None;
};
let mut parts = Arc::try_unwrap(parts).unwrap_or_else(|shared| (*shared).clone());
let field = |index: usize| count(parts.get(index));
let (
Some(high),
Some(low),
Some(id),
Some(len),
Some(here),
Some(base),
Some(end),
Some(last),
Some(trie),
) = (
field(0),
field(1),
field(2),
field(3),
field(4),
field(6),
field(7),
field(8),
field(9),
)
else {
return None;
};
let node = std::mem::replace(parts.get_mut(5)?, Value::Undefined);
let fresh = |tag: usize| if 2 == tag { Fresh::Array } else { Fresh::Table };
#[allow(clippy::cast_possible_truncation)]
let cell = (((high as u64) << 32) | low as u64) as usize;
Some(Cursor {
cell,
path: if 0 == len {
Path::ROOT
} else {
Path { id, len }
},
trie,
here: match here {
0 => Here::Node(node),
1 | 2 => Here::Fresh(fresh(here)),
_ => Here::Absent,
},
pending: (0 < base).then(|| Pending {
base: base - 1,
end,
last: fresh(last),
}),
})
}
pub(crate) fn settle(context: &mut Context, cell: &Cell) {
if let Some(parked) = take_parked(context) {
if parked.cell == cell_id(cell) {
parked.finish(context, cell);
} else {
parked.store(context);
}
}
}