use scrusted_feel::Value;
use std::sync::Arc;
use crate::problem::Place;
pub type NodeId = usize;
pub type EntryId = usize;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pos {
pub file: Arc<str>,
pub line: u32,
pub column: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Key {
pub raw: Arc<str>,
pub name: Arc<str>,
pub marker: Option<Arc<str>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyKind {
Plain,
Formula,
Marked,
}
impl Key {
pub fn new(raw: &str) -> Key {
match raw.rfind('!') {
Some(at) => Key { raw: raw.into(), name: raw[..at].into(), marker: Some(raw[at + 1..].into()) },
None => Key { raw: raw.into(), name: raw.into(), marker: None },
}
}
pub fn kind(&self) -> KeyKind {
match self.marker.as_deref() {
None => KeyKind::Plain,
Some("") => KeyKind::Formula,
Some(_) => KeyKind::Marked,
}
}
pub fn keyword(&self) -> bool {
self.name.starts_with('$')
}
pub fn marker_name(&self) -> &str {
self.marker.as_deref().unwrap_or("")
}
}
#[derive(Debug, Clone)]
pub struct Scalar {
pub value: Value,
pub source: Arc<str>,
}
#[derive(Debug, Clone)]
pub enum NodeKind {
Scalar(Scalar),
Map(Vec<EntryId>),
List(Vec<NodeId>),
}
#[derive(Debug, Clone)]
pub struct Node {
pub kind: NodeKind,
pub pos: Pos,
pub parent: Option<NodeId>,
pub entry: Option<EntryId>,
pub key_field: Arc<str>,
}
#[derive(Debug, Clone)]
pub struct Entry {
pub key: Key,
pub value: NodeId,
pub map: NodeId,
pub pos: Pos,
pub base: Option<EntryId>,
pub listed: bool,
}
#[derive(Debug, Clone, Default)]
pub struct Tree {
pub nodes: Vec<Node>,
pub entries: Vec<Entry>,
}
pub fn js_string(v: &Value) -> String {
match v {
Value::Null => "null".into(),
other => other.to_feel_string(),
}
}
impl Tree {
pub fn add(&mut self, kind: NodeKind, pos: Pos) -> NodeId {
self.nodes.push(Node { kind, pos, parent: None, entry: None, key_field: "id".into() });
self.nodes.len() - 1
}
pub fn scalar(&mut self, value: Value, source: impl Into<Arc<str>>, pos: Pos) -> NodeId {
self.add(NodeKind::Scalar(Scalar { value, source: source.into() }), pos)
}
pub fn map(&mut self, pos: Pos) -> NodeId {
self.add(NodeKind::Map(Vec::new()), pos)
}
pub fn list(&mut self, pos: Pos) -> NodeId {
self.add(NodeKind::List(Vec::new()), pos)
}
pub fn node(&self, id: NodeId) -> &Node {
&self.nodes[id]
}
pub fn entry(&self, id: EntryId) -> &Entry {
&self.entries[id]
}
pub fn entries_of(&self, map: NodeId) -> &[EntryId] {
match &self.nodes[map].kind {
NodeKind::Map(e) => e,
_ => &[],
}
}
pub fn items(&self, list: NodeId) -> &[NodeId] {
match &self.nodes[list].kind {
NodeKind::List(i) => i,
_ => &[],
}
}
pub fn is_map(&self, id: NodeId) -> bool {
matches!(self.nodes[id].kind, NodeKind::Map(_))
}
pub fn is_list(&self, id: NodeId) -> bool {
matches!(self.nodes[id].kind, NodeKind::List(_))
}
pub fn scalar_of(&self, id: NodeId) -> Option<&Scalar> {
match &self.nodes[id].kind {
NodeKind::Scalar(s) => Some(s),
_ => None,
}
}
pub fn get(&self, map: NodeId, name: &str) -> Option<EntryId> {
self.entries_of(map).iter().copied().find(|e| &*self.entries[*e].key.name == name)
}
pub fn cases(&self, map: NodeId) -> Vec<NodeId> {
match self.get(map, "$when") {
Some(when) => self.items(self.entries[when].value).iter().copied().filter(|i| self.is_map(*i)).collect(),
None => Vec::new(),
}
}
pub fn find(&self, map: NodeId, name: &str) -> Option<EntryId> {
if let Some(own) = self.get(map, name) {
return Some(own);
}
self.cases(map).into_iter().find_map(|case| self.get(case, name))
}
pub fn scalar_field(&self, map: NodeId, name: &str) -> Option<&Value> {
let e = self.get(map, name)?;
let entry = &self.entries[e];
if entry.key.kind() != KeyKind::Plain {
return None;
}
self.scalar_of(entry.value).map(|s| &s.value)
}
pub fn set(&mut self, map: NodeId, raw: &str, value: NodeId, pos: Pos, at: Option<usize>) -> EntryId {
let entry = Entry { key: Key::new(raw), value, map, pos, base: None, listed: true };
self.entries.push(entry);
let id = self.entries.len() - 1;
self.nodes[value].entry = Some(id);
self.nodes[value].parent = Some(map);
if let NodeKind::Map(list) = &mut self.nodes[map].kind {
match at {
Some(i) if i <= list.len() => list.insert(i, id),
_ => list.push(id),
}
}
id
}
pub fn detached(&mut self, map: NodeId, raw: &str, value: NodeId, pos: Pos) -> EntryId {
self.entries.push(Entry { key: Key::new(raw), value, map, pos, base: None, listed: false });
let id = self.entries.len() - 1;
self.nodes[value].entry = Some(id);
self.nodes[value].parent = Some(map);
id
}
pub fn remove(&mut self, entry: EntryId) {
let map = self.entries[entry].map;
if let NodeKind::Map(list) = &mut self.nodes[map].kind {
list.retain(|e| *e != entry);
}
self.entries[entry].listed = false;
}
pub fn push_item(&mut self, list: NodeId, item: NodeId, at: Option<usize>) {
self.nodes[item].parent = Some(list);
self.nodes[item].entry = None;
if let NodeKind::List(items) = &mut self.nodes[list].kind {
match at {
Some(i) if i <= items.len() => items.insert(i, item),
_ => items.push(item),
}
}
}
pub fn by_id(&self, list: NodeId, id: &str) -> Option<NodeId> {
let field = self.nodes[list].key_field.clone();
self.items(list)
.iter()
.copied()
.find(|item| self.is_map(*item) && self.scalar_field(*item, &field).is_some_and(|v| js_string(v) == id))
}
pub fn label(&self, list: NodeId, item: NodeId) -> String {
let field = self.nodes[list].key_field.clone();
match self.is_map(item).then(|| self.scalar_field(item, &field)).flatten() {
Some(v) => format!(".{}", js_string(v)),
None => format!("[{}]", self.items(list).iter().position(|i| *i == item).map(|i| i + 1).unwrap_or(0)),
}
}
pub fn path(&self, id: NodeId) -> String {
let node = &self.nodes[id];
if let Some(e) = node.entry {
return self.entry_path(e);
}
if let Some(parent) = node.parent
&& self.is_list(parent)
{
return format!("{}{}", self.path(parent), self.label(parent, id));
}
String::new()
}
pub fn entry_path(&self, e: EntryId) -> String {
let entry = &self.entries[e];
let before = self.path(entry.map);
if before.is_empty() { entry.key.raw.to_string() } else { format!("{before}.{}", entry.key.raw) }
}
pub fn place(&self, id: NodeId) -> Place {
let pos = &self.nodes[id].pos;
Place { file: pos.file.to_string(), line: pos.line, column: pos.column, key: self.path(id) }
}
pub fn at(&self, id: NodeId) -> Place {
match self.nodes[id].entry {
Some(e) => self.entry_place(e),
None => self.place(id),
}
}
pub fn entry_place(&self, e: EntryId) -> Place {
let pos = &self.entries[e].pos;
Place { file: pos.file.to_string(), line: pos.line, column: pos.column, key: self.entry_path(e) }
}
pub fn ancestors(&self, id: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
let mut at = self.nodes[id].parent;
while let Some(p) = at {
out.push(p);
at = self.nodes[p].parent;
}
out
}
pub fn within(&self, id: NodeId, ancestor: NodeId) -> bool {
let mut at = Some(id);
while let Some(n) = at {
if n == ancestor {
return true;
}
at = self.nodes[n].parent;
}
false
}
pub fn to_data(&self, id: NodeId) -> Value {
match &self.nodes[id].kind {
NodeKind::Scalar(s) => s.value.clone(),
NodeKind::List(items) => Value::List(items.iter().map(|i| self.to_data(*i)).collect::<Vec<_>>().into()),
NodeKind::Map(entries) => {
let mut map = scrusted_feel::Map::new();
for e in entries {
let entry = &self.entries[*e];
map.insert(entry.key.raw.clone(), self.to_data(entry.value));
}
Value::from(map)
}
}
}
pub fn clone_node(&mut self, id: NodeId) -> NodeId {
let node = self.nodes[id].clone();
match node.kind {
NodeKind::Scalar(s) => self.add(NodeKind::Scalar(s), node.pos),
NodeKind::List(items) => {
let copy = self.add(NodeKind::List(Vec::new()), node.pos);
self.nodes[copy].key_field = node.key_field;
for item in items {
let c = self.clone_node(item);
self.push_item(copy, c, None);
}
copy
}
NodeKind::Map(entries) => {
let copy = self.add(NodeKind::Map(Vec::new()), node.pos);
for e in entries {
let entry = self.entries[e].clone();
let c = self.clone_node(entry.value);
self.set(copy, &entry.key.raw, c, entry.pos, None);
}
copy
}
}
}
}