use std::collections::HashMap;
use crate::language::{CommentForm, CommentSlot, LanguageError, MentionKind, NodeKind, NodeRow, NodeTable};
use crate::{ExtKind, Span};
use super::rows::{DuplicatePolicy, RowWriter};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comment {
pub text: String,
pub style: CommentForm,
}
#[derive(Clone, Debug)]
pub enum Body {
Leaf,
Mapping {
entries: Vec<Node>,
duplicates: DuplicatePolicy,
by_key: HashMap<String, usize>,
},
Sequence { items: Vec<Node> },
Entry { key: Box<Node>, value: Box<Node> },
}
#[derive(Clone, Debug)]
pub struct Node {
pub row: NodeRow,
pub leading: Vec<Comment>,
pub trailing: Vec<Comment>,
pub dangling: Vec<Comment>,
pub regions: Vec<Span>,
pub mentions: Vec<(Span, MentionKind)>,
pub body: Body,
}
impl Node {
pub fn new(row: NodeRow, body: Body) -> Self {
Node {
row,
leading: Vec::new(),
trailing: Vec::new(),
dangling: Vec::new(),
regions: Vec::new(),
mentions: Vec::new(),
body,
}
}
pub fn scalar(kind: NodeKind, span: Span, text: impl Into<String>) -> Self {
let mut row = NodeRow::new(kind, None, span);
if kind != NodeKind::Null {
row.text = Some(text.into());
}
Node::new(row, Body::Leaf)
}
pub fn extended(ext_kind: ExtKind, kind: NodeKind, span: Span, text: impl Into<String>) -> Self {
let mut n = Node::scalar(kind, span, text);
n.row.ext_kind = Some(ext_kind);
n
}
pub fn null(span: Span) -> Self {
Node::scalar(NodeKind::Null, span, "")
}
pub fn mapping(span: Span, duplicates: DuplicatePolicy) -> Self {
Node::new(
NodeRow::new(NodeKind::Mapping, None, span),
Body::Mapping {
entries: Vec::new(),
duplicates,
by_key: HashMap::new(),
},
)
}
pub fn sequence(span: Span) -> Self {
Node::new(NodeRow::new(NodeKind::Sequence, None, span), Body::Sequence { items: Vec::new() })
}
pub fn entry(key: Node, value: Node, span: Option<Span>) -> Self {
let span = span.unwrap_or_else(|| Span::from(start(&key)..end(&value)));
Node::new(
NodeRow::new(NodeKind::KeyValue, None, span),
Body::Entry {
key: Box::new(key),
value: Box::new(value),
},
)
}
pub fn span(&self) -> Span {
self.row.span.unwrap_or(Span::from(0..0))
}
pub fn comment(&mut self, slot: CommentSlot, text: impl Into<String>) -> &mut Self {
self.comment_as(slot, text, CommentForm::Line)
}
pub fn comment_as(&mut self, slot: CommentSlot, text: impl Into<String>, style: CommentForm) -> &mut Self {
let c = Comment {
text: text.into(),
style,
};
match slot {
CommentSlot::Leading => self.leading.push(c),
CommentSlot::Trailing => self.trailing.push(c),
CommentSlot::Dangling => self.dangling.push(c),
}
self
}
pub fn key(&self) -> Option<&Node> {
match &self.body {
Body::Entry { key, .. } => Some(key),
_ => None,
}
}
pub fn value(&self) -> Option<&Node> {
match &self.body {
Body::Entry { value, .. } => Some(value),
_ => None,
}
}
pub fn put(&mut self, entry: Node) -> Result<usize, LanguageError> {
let Body::Mapping {
entries,
duplicates,
by_key,
} = &mut self.body
else {
panic!("put into a node that is not a mapping");
};
let name = entry.key().expect("put a node that is not an entry").row.text.clone();
let existing = name.as_ref().and_then(|n| by_key.get(n).copied());
if let Some(i) = existing {
match duplicates {
DuplicatePolicy::LastValue => {
let Body::Entry { value, .. } = entry.body else { unreachable!() };
if let Body::Entry { value: old, .. } = &mut entries[i].body {
*old = value;
}
return Ok(i);
}
DuplicatePolicy::FirstValue => return Ok(i),
DuplicatePolicy::Error => {
let message = format!("duplicate key `{}`", name.unwrap_or_default());
return Err(LanguageError::at(message, start(entry.key().unwrap())));
}
_ => {}
}
}
entries.push(entry);
let i = entries.len() - 1;
if let (Some(n), None) = (name, existing) {
by_key.insert(n, i);
}
Ok(i)
}
pub fn add(&mut self, item: Node) -> &mut Node {
let Body::Sequence { items } = &mut self.body else {
panic!("add to a node that is not a sequence");
};
items.push(item);
items.last_mut().unwrap()
}
}
fn start(n: &Node) -> usize {
n.row.span.map_or(0, |s| s.start)
}
fn end(n: &Node) -> usize {
n.row.span.map_or(0, |s| s.end)
}
pub fn rows(root: &Node) -> NodeTable {
let mut w = RowWriter::new();
let id = emit(&mut w, root, None);
w.finish(id)
}
fn emit(w: &mut RowWriter, n: &Node, parent: Option<u32>) -> u32 {
let mut row = n.row.clone();
row.parent = parent;
let id = w.add(row);
for (slot, list) in [
(CommentSlot::Leading, &n.leading),
(CommentSlot::Trailing, &n.trailing),
(CommentSlot::Dangling, &n.dangling),
] {
for c in list {
w.comment(id, slot, c.style, c.text.clone());
}
}
for r in &n.regions {
w.region(id, *r);
}
for (s, k) in &n.mentions {
w.mention(id, *s, *k);
}
match &n.body {
Body::Leaf => {}
Body::Mapping { entries, .. } => {
for e in entries {
emit(w, e, Some(id));
}
}
Body::Sequence { items } => {
for i in items {
emit(w, i, Some(id));
}
}
Body::Entry { key, value } => {
emit(w, key, Some(id));
emit(w, value, Some(id));
}
}
id
}