use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Range;
use crate::source::{Source, SourceSpan, Span, TextContent};
use crate::state::{Lang, ParsingState};
use crate::node::{
copy_subtree_into, BuildId, NodeBuildError, NodeId, NodeKind, NodeRef, NodeSlice,
NodeTree, NodeTreeBuilder,
};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExtractError {
NonCharsContent {
node: NodeId,
},
EmptySeparator,
UnexpectedContent {
node: NodeId,
},
Build(NodeBuildError),
}
impl From<NodeBuildError> for ExtractError {
fn from(error: NodeBuildError) -> ExtractError {
ExtractError::Build(error)
}
}
impl fmt::Display for ExtractError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExtractError::NonCharsContent { node } => write!(
f,
"Invalid node {} in text content: the content may consist only of \
characters, comments, groups and lists",
node.index()
),
ExtractError::EmptySeparator => write!(f, "Split separator may not be empty"),
ExtractError::UnexpectedContent { node } => write!(
f,
"Unexpected node {}: the content may consist only of whitespace, comments \
and entries of the expected form",
node.index()
),
ExtractError::Build(error) => {
write!(f, "Failed to build the result tree: {}", error)
}
}
}
}
impl core::error::Error for ExtractError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
ExtractError::Build(error) => Some(error),
_ => None,
}
}
}
struct Piece<'t, L: Lang, A> {
node: NodeRef<'t, L, A>,
part: Option<Range<usize>>,
}
impl<L: Lang, A> Clone for Piece<'_, L, A> {
fn clone(&self) -> Self {
Piece { node: self.node, part: self.part.clone() }
}
}
fn whole<L: Lang, A>(node: NodeRef<'_, L, A>) -> Piece<'_, L, A> {
Piece { node, part: None }
}
fn piece_text<'t, L: Lang, A>(piece: &Piece<'t, L, A>) -> Option<&'t str> {
let text = piece.node.chars()?;
Some(match &piece.part {
None => text,
Some(sub) => text
.get(sub.clone())
.expect("piece sub-ranges lie on char boundaries of their node's content by construction"),
})
}
fn piece_span<L: Lang, A>(piece: &Piece<'_, L, A>) -> SourceSpan<L::SourceOrigin> {
if let Some(sub) = &piece.part {
if let NodeKind::Chars { content: TextContent::Spanned(span), .. } = piece.node.kind() {
return SourceSpan::new(
piece.node.span().source(),
span.start() + sub.start..span.start() + sub.end,
);
}
}
piece.node.span().clone()
}
pub fn content_as_chars<'t, L: Lang, A: 't>(
nodes: impl IntoIterator<Item = NodeRef<'t, L, A>>,
) -> Result<Cow<'t, str>, ExtractError> {
let mut acc = Acc::Empty;
for node in nodes {
collect_chars(node, None, &mut acc)?;
}
Ok(acc.finish())
}
fn pieces_as_chars<'t, L: Lang, A>(
pieces: &[Piece<'t, L, A>],
) -> Result<Cow<'t, str>, ExtractError> {
let mut acc = Acc::Empty;
for piece in pieces {
collect_chars(piece.node, piece.part.clone(), &mut acc)?;
}
Ok(acc.finish())
}
fn collect_chars<'t, L: Lang, A>(
node: NodeRef<'t, L, A>,
part: Option<Range<usize>>,
acc: &mut Acc<'t>,
) -> Result<(), ExtractError> {
match node.kind() {
NodeKind::Chars { .. } => {
let piece = Piece { node, part };
acc.push(piece_text(&piece).expect("chars kind resolves text"));
Ok(())
}
NodeKind::Comment { .. } => Ok(()),
NodeKind::Group(_) | NodeKind::List => {
for child in node.children() {
collect_chars(child, None, acc)?;
}
Ok(())
}
NodeKind::Callable(_) => Err(ExtractError::NonCharsContent { node: node.id() }),
}
}
enum Acc<'t> {
Empty,
One(&'t str),
Many(String),
}
impl<'t> Acc<'t> {
fn push(&mut self, text: &'t str) {
if text.is_empty() {
return;
}
match self {
Acc::Empty => *self = Acc::One(text),
Acc::One(first) => {
let mut owned = String::with_capacity(first.len() + text.len());
owned.push_str(first);
owned.push_str(text);
*self = Acc::Many(owned);
}
Acc::Many(owned) => owned.push_str(text),
}
}
fn finish(self) -> Cow<'t, str> {
match self {
Acc::Empty => Cow::Borrowed(""),
Acc::One(text) => Cow::Borrowed(text),
Acc::Many(owned) => Cow::Owned(owned),
}
}
}
fn split_pieces<'t, L: Lang, A>(
input: impl IntoIterator<Item = Piece<'t, L, A>>,
sep: &str,
max_split: Option<usize>,
keep_empty: bool,
) -> Vec<Vec<Piece<'t, L, A>>> {
let mut segments: Vec<Vec<Piece<'t, L, A>>> = Vec::new();
let mut current: Vec<Piece<'t, L, A>> = Vec::new();
let mut splits = 0usize;
fn flush<'t, L: Lang, A>(
current: &mut Vec<Piece<'t, L, A>>,
segments: &mut Vec<Vec<Piece<'t, L, A>>>,
keep_empty: bool,
) {
if keep_empty || !current.is_empty() {
segments.push(core::mem::take(current));
}
}
for piece in input {
let splittable = max_split.is_none_or(|max| splits < max);
let Some(text) = splittable.then(|| piece_text(&piece)).flatten() else {
current.push(piece);
continue;
};
let base = piece.part.as_ref().map_or(0, |sub| sub.start);
let mut pos = 0;
while max_split.is_none_or(|max| splits < max) {
let Some(found) = text[pos..].find(sep) else { break };
let at = pos + found;
if at > pos {
current.push(Piece { node: piece.node, part: Some(base + pos..base + at) });
}
flush(&mut current, &mut segments, keep_empty);
splits += 1;
pos = at + sep.len();
}
if pos == 0 {
current.push(piece); } else if pos < text.len() {
current.push(Piece { node: piece.node, part: Some(base + pos..base + text.len()) });
}
}
flush(&mut current, &mut segments, keep_empty);
segments
}
fn anchor<L: Lang, A>(
slice: &NodeSlice<'_, L, A>,
) -> (SourceSpan<L::SourceOrigin>, Arc<ParsingState<L>>) {
match slice.first() {
Some(first) => (
slice.span().unwrap_or_else(|| first.span().clone()),
first.parsing_state().clone(),
),
None => {
let root = slice.tree().root();
let start = root.span().start();
(
SourceSpan::new(root.span().source(), start..start),
root.parsing_state().clone(),
)
}
}
}
fn covering<O: crate::source::SourceOrigin>(
first: &SourceSpan<O>,
last: &SourceSpan<O>,
) -> SourceSpan<O> {
if first.same_source(last) && first.start() <= last.end() {
SourceSpan::new(first.source(), first.start()..last.end())
} else {
first.clone()
}
}
struct PartFacts<'t, L: Lang, A> {
original: Option<NodeRef<'t, L, A>>,
partial: Option<&'t str>,
index: Option<usize>,
}
pub struct SplitAtCharsPart<'t, L: Lang, A = ()> {
facts: PartFacts<'t, L, A>,
}
impl<'t, L: Lang, A> SplitAtCharsPart<'t, L, A> {
pub fn original(&self) -> Option<NodeRef<'t, L, A>> {
self.facts.original
}
pub fn is_partial(&self) -> bool {
self.facts.partial.is_some()
}
pub fn partial_text(&self) -> Option<&'t str> {
self.facts.partial
}
pub fn segment_index(&self) -> Option<usize> {
self.facts.index
}
}
impl<L: Lang, A> fmt::Debug for SplitAtCharsPart<'_, L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SplitAtCharsPart")
.field("original", &self.facts.original.map(|node| node.id()))
.field("partial", &self.facts.partial)
.field("segment_index", &self.facts.index)
.finish()
}
}
pub struct KeyValsPart<'t, L: Lang, A = ()> {
facts: PartFacts<'t, L, A>,
}
impl<'t, L: Lang, A> KeyValsPart<'t, L, A> {
pub fn original(&self) -> Option<NodeRef<'t, L, A>> {
self.facts.original
}
pub fn is_partial(&self) -> bool {
self.facts.partial.is_some()
}
pub fn partial_text(&self) -> Option<&'t str> {
self.facts.partial
}
pub fn entry_index(&self) -> Option<usize> {
self.facts.index
}
}
impl<L: Lang, A> fmt::Debug for KeyValsPart<'_, L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyValsPart")
.field("original", &self.facts.original.map(|node| node.id()))
.field("partial", &self.facts.partial)
.field("entry_index", &self.facts.index)
.finish()
}
}
type Mint<'m, 't, L, A, B> = &'m mut dyn FnMut(PartFacts<'t, L, A>) -> B;
fn stage_piece<'t, L: Lang, A, B>(
builder: &mut NodeTreeBuilder<L, B>,
piece: &Piece<'t, L, A>,
index: Option<usize>,
mint: Mint<'_, 't, L, A, B>,
) -> Result<BuildId, NodeBuildError> {
let Some(sub) = &piece.part else {
return copy_subtree_into(builder, piece.node, &mut |original| {
mint(PartFacts { original: Some(original), partial: None, index })
});
};
let NodeKind::Chars { content, .. } = piece.node.kind() else {
unreachable!("parts are only minted for Chars nodes (split_pieces)")
};
let (content, span) = match content {
TextContent::Spanned(span) => (
TextContent::Spanned(Span::new(span.start() + sub.start, span.start() + sub.end)),
SourceSpan::new(
piece.node.span().source(),
span.start() + sub.start..span.start() + sub.end,
),
),
TextContent::Owned(text) => (
TextContent::Owned(Box::from(
text.get(sub.clone())
.expect("piece sub-ranges lie on char boundaries by construction"),
)),
piece.node.span().clone(),
),
};
let partial = piece_text(piece).expect("chars kind resolves text");
let annotation =
mint(PartFacts { original: Some(piece.node), partial: Some(partial), index });
let kind = NodeKind::chars(content);
let state = piece.node.parsing_state().clone();
let ext = L::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))?;
builder.add(kind, span, state, Vec::new(), ext, annotation)
}
fn stage_segment_list<'t, L: Lang, A, B>(
builder: &mut NodeTreeBuilder<L, B>,
pieces: &[Piece<'t, L, A>],
fallback_span: &SourceSpan<L::SourceOrigin>,
fallback_state: &Arc<ParsingState<L>>,
index: usize,
mint: Mint<'_, 't, L, A, B>,
) -> Result<BuildId, NodeBuildError> {
let mut children = Vec::with_capacity(pieces.len());
for piece in pieces {
children.push(stage_piece(builder, piece, Some(index), mint)?);
}
let (span, state) = match (pieces.first(), pieces.last()) {
(Some(first), Some(last)) => (
covering(&piece_span(first), &piece_span(last)),
first.node.parsing_state().clone(),
),
_ => (fallback_span.clone(), fallback_state.clone()),
};
let annotation = mint(PartFacts { original: None, partial: None, index: Some(index) });
let kind = NodeKind::list();
let ext = L::make_node_ext(&kind, &span, &state, builder.staged_children(&children))?;
builder.add(kind, span, state, children, ext, annotation)
}
pub fn split_at_chars<'t, L: Lang, A, B>(
nodes: NodeSlice<'t, L, A>,
sep: &str,
mut annotate: impl FnMut(&SplitAtCharsPart<'t, L, A>) -> B,
) -> Result<SplitAtChars<L, B>, ExtractError> {
let mut mint = |facts: PartFacts<'t, L, A>| annotate(&SplitAtCharsPart { facts });
if sep.is_empty() {
return Err(ExtractError::EmptySeparator);
}
let segments = split_pieces(nodes.iter().map(whole), sep, None, false);
let (anchor_span, anchor_state) = anchor(&nodes);
let mut builder = NodeTreeBuilder::new();
let mut lists = Vec::with_capacity(segments.len());
for (i, segment) in segments.iter().enumerate() {
lists.push(stage_segment_list(
&mut builder,
segment,
&anchor_span,
&anchor_state,
i,
&mut mint,
)?);
}
let span = match (segments.first().and_then(|s| s.first()), segments.last().and_then(|s| s.last()))
{
(Some(first), Some(last)) => covering(&piece_span(first), &piece_span(last)),
_ => anchor_span,
};
let annotation = mint(PartFacts { original: None, partial: None, index: None });
let kind = NodeKind::list();
let ext = L::make_node_ext(&kind, &span, &anchor_state, builder.staged_children(&lists))?;
let root = builder.add(kind, span, anchor_state, lists, ext, annotation)?;
Ok(SplitAtChars { tree: builder.finish(root)? })
}
pub fn split_at_chars_drop_annotations<L: Lang, A>(
nodes: NodeSlice<'_, L, A>,
sep: &str,
) -> Result<SplitAtChars<L>, ExtractError> {
split_at_chars(nodes, sep, |_| ())
}
pub fn split_at_chars_keep_annotations<L: Lang, A: Clone + Default>(
nodes: NodeSlice<'_, L, A>,
sep: &str,
) -> Result<SplitAtChars<L, A>, ExtractError> {
split_at_chars(nodes, sep, keep_annotation)
}
fn keep_annotation<'t, L: Lang, A: Clone + Default>(part: &SplitAtCharsPart<'t, L, A>) -> A {
part.original().map(|node| node.annotation().clone()).unwrap_or_default()
}
pub struct SplitAtChars<L: Lang, B = ()> {
tree: NodeTree<L, B>,
}
impl<L: Lang, B> SplitAtChars<L, B> {
pub fn len(&self) -> usize {
self.tree.root().child_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn segment(&self, i: usize) -> Option<NodeSlice<'_, L, B>> {
Some(self.tree.root().child(i)?.children())
}
pub fn segments(&self) -> impl Iterator<Item = NodeSlice<'_, L, B>> {
self.tree.root().children().iter().map(|list| list.children())
}
pub fn tree(&self) -> &NodeTree<L, B> {
&self.tree
}
pub fn into_tree(self) -> NodeTree<L, B> {
self.tree
}
}
impl<L: Lang, B> fmt::Debug for SplitAtChars<L, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SplitAtChars").field("segments", &self.len()).finish()
}
}
pub fn parse_keyval<'t, L: Lang, A, B>(
nodes: NodeSlice<'t, L, A>,
mut annotate: impl FnMut(&KeyValsPart<'t, L, A>) -> B,
) -> Result<KeyVals<L, B>, ExtractError> {
let mut mint = |facts: PartFacts<'t, L, A>| annotate(&KeyValsPart { facts });
let (anchor_span, anchor_state) = anchor(&nodes);
let comma_parts = split_pieces(nodes.iter().map(whole), ",", None, false);
let mut builder = NodeTreeBuilder::new();
let mut value_lists: Vec<BuildId> = Vec::new();
let mut entries: Vec<(Box<str>, Option<usize>)> = Vec::new();
for part in &comma_parts {
let mut eq_parts = split_pieces(part.iter().cloned(), "=", Some(1), true);
debug_assert!((1..=2).contains(&eq_parts.len()), "max_split=1 on nonempty input");
let value_pieces = if eq_parts.len() == 2 { eq_parts.pop() } else { None };
let key = pieces_as_chars(&eq_parts[0])?;
let value = match value_pieces {
Some(pieces) => {
value_lists.push(stage_segment_list(
&mut builder,
&pieces,
&anchor_span,
&anchor_state,
entries.len(),
&mut mint,
)?);
Some(value_lists.len() - 1)
}
None => None,
};
entries.push((key.trim().into(), value));
}
finish_keyvals(builder, value_lists, entries, anchor_span, anchor_state, &mut mint)
}
pub fn parse_keyval_drop_annotations<L: Lang, A>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L>, ExtractError> {
parse_keyval(nodes, |_| ())
}
pub fn parse_keyval_keep_annotations<L: Lang, A: Clone + Default>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L, A>, ExtractError> {
parse_keyval(nodes, keep_keyval_annotation)
}
fn keep_keyval_annotation<'t, L: Lang, A: Clone + Default>(part: &KeyValsPart<'t, L, A>) -> A {
part.original().map(|node| node.annotation().clone()).unwrap_or_default()
}
fn finish_keyvals<'t, L: Lang, A, B>(
mut builder: NodeTreeBuilder<L, B>,
value_lists: Vec<BuildId>,
entries: Vec<(Box<str>, Option<usize>)>,
anchor_span: SourceSpan<L::SourceOrigin>,
anchor_state: Arc<ParsingState<L>>,
mint: Mint<'_, 't, L, A, B>,
) -> Result<KeyVals<L, B>, ExtractError> {
let annotation = mint(PartFacts { original: None, partial: None, index: None });
let kind = NodeKind::list();
let ext =
L::make_node_ext(&kind, &anchor_span, &anchor_state, builder.staged_children(&value_lists))?;
let root = builder.add(kind, anchor_span, anchor_state, value_lists, ext, annotation)?;
let tree = builder.finish(root)?;
let value_ids: Vec<NodeId> = tree.root().children().iter().map(|list| list.id()).collect();
let entries = entries
.into_iter()
.map(|(key, value)| KeyValEntryData { key, value: value.map(|i| value_ids[i]) })
.collect();
Ok(KeyVals { tree, entries })
}
fn is_run_noise<L: Lang, A>(node: &NodeRef<'_, L, A>) -> bool {
match node.kind() {
NodeKind::Comment { .. } => true,
NodeKind::Chars { .. } => node
.chars()
.is_some_and(|text| text.chars().all(char::is_whitespace)),
_ => false,
}
}
pub fn split_embellishments<'t, L: Lang, A, B>(
nodes: NodeSlice<'t, L, A>,
mut annotate: impl FnMut(&KeyValsPart<'t, L, A>) -> B,
) -> Result<KeyVals<L, B>, ExtractError> {
let mut mint = |facts: PartFacts<'t, L, A>| annotate(&KeyValsPart { facts });
let (anchor_span, anchor_state) = anchor(&nodes);
let mut builder = NodeTreeBuilder::new();
let mut value_lists: Vec<BuildId> = Vec::new();
let mut entries: Vec<(Box<str>, Option<usize>)> = Vec::new();
for node in nodes.iter() {
if is_run_noise(&node) {
continue;
}
let Some((marker, _close)) = node.group_delimiters() else {
return Err(ExtractError::UnexpectedContent { node: node.id() });
};
let pieces: Vec<Piece<'_, L, A>> = node
.children()
.iter()
.filter(|child| !is_run_noise(child))
.map(whole)
.collect();
value_lists.push(stage_segment_list(
&mut builder,
&pieces,
&anchor_span,
&anchor_state,
entries.len(),
&mut mint,
)?);
entries.push((Box::from(marker), Some(value_lists.len() - 1)));
}
finish_keyvals(builder, value_lists, entries, anchor_span, anchor_state, &mut mint)
}
pub fn split_embellishments_drop_annotations<L: Lang, A>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L>, ExtractError> {
split_embellishments(nodes, |_| ())
}
pub fn split_embellishments_keep_annotations<L: Lang, A: Clone + Default>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L, A>, ExtractError> {
split_embellishments(nodes, keep_keyval_annotation)
}
pub fn split_tack_on_fields<'t, L: Lang, A, B>(
nodes: NodeSlice<'t, L, A>,
mut annotate: impl FnMut(&KeyValsPart<'t, L, A>) -> B,
) -> Result<KeyVals<L, B>, ExtractError> {
let mut mint = |facts: PartFacts<'t, L, A>| annotate(&KeyValsPart { facts });
let (anchor_span, anchor_state) = anchor(&nodes);
let mut builder = NodeTreeBuilder::new();
let mut value_lists: Vec<BuildId> = Vec::new();
let mut entries: Vec<(Box<str>, Option<usize>)> = Vec::new();
for node in nodes.iter() {
if is_run_noise(&node) {
continue;
}
let (Some(name), Some(arguments)) = (node.name(), node.arguments()) else {
return Err(ExtractError::UnexpectedContent { node: node.id() });
};
let mut pieces: Option<Vec<Piece<'_, L, A>>> = None;
for i in 0..arguments.len() {
if let Some(content) = node.argument_content_nodes(i) {
pieces.get_or_insert_with(Vec::new).extend(content.iter().map(whole));
}
}
let value = match pieces {
Some(pieces) => {
value_lists.push(stage_segment_list(
&mut builder,
&pieces,
&anchor_span,
&anchor_state,
entries.len(),
&mut mint,
)?);
Some(value_lists.len() - 1)
}
None => None,
};
entries.push((Box::from(name), value));
}
finish_keyvals(builder, value_lists, entries, anchor_span, anchor_state, &mut mint)
}
pub fn split_tack_on_fields_drop_annotations<L: Lang, A>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L>, ExtractError> {
split_tack_on_fields(nodes, |_| ())
}
pub fn split_tack_on_fields_keep_annotations<L: Lang, A: Clone + Default>(
nodes: NodeSlice<'_, L, A>,
) -> Result<KeyVals<L, A>, ExtractError> {
split_tack_on_fields(nodes, keep_keyval_annotation)
}
struct KeyValEntryData {
key: Box<str>,
value: Option<NodeId>,
}
pub struct KeyVals<L: Lang, B = ()> {
tree: NodeTree<L, B>,
entries: Vec<KeyValEntryData>,
}
impl<L: Lang, B> KeyVals<L, B> {
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn keyval(&self, i: usize) -> Option<KeyValEntry<'_, L, B>> {
self.entries.get(i).map(|entry| self.view(entry))
}
pub fn get(&self, key: &str) -> Option<KeyValEntry<'_, L, B>> {
self.entries.iter().rev().find(|entry| &*entry.key == key).map(|entry| self.view(entry))
}
pub fn iter(&self) -> impl Iterator<Item = KeyValEntry<'_, L, B>> {
self.entries.iter().map(|entry| self.view(entry))
}
pub fn get_combined_with(
&self,
key: &str,
sep: &str,
) -> Result<Option<NodeTree<L>>, ExtractError> {
let values: Vec<NodeSlice<'_, L, B>> = self
.entries
.iter()
.filter(|entry| &*entry.key == key)
.filter_map(|entry| entry.value)
.map(|id| self.tree.node(id).children())
.collect();
if !self.entries.iter().any(|entry| &*entry.key == key) {
return Ok(None);
}
let root_span = self.tree.root().span().clone();
let state = self.tree.root().parsing_state().clone();
let sep_source: Option<Arc<Source<L::SourceOrigin>>> = (!sep.is_empty()).then(|| {
Arc::new(Source::synthesized(sep, "keyval combined-value separator", root_span.clone()))
});
let mut builder = NodeTreeBuilder::new();
let mut children = Vec::new();
for (i, value) in values.iter().enumerate() {
if i > 0 {
if let Some(sep_source) = &sep_source {
let kind = NodeKind::chars(TextContent::Owned(Box::from(sep)));
let span = SourceSpan::entire(sep_source);
let ext =
L::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))?;
children.push(builder.add(kind, span, state.clone(), Vec::new(), ext, ())?);
}
}
for node in value.iter() {
children.push(copy_subtree_into(&mut builder, node, &mut |_| ())?);
}
}
let kind = NodeKind::list();
let ext =
L::make_node_ext(&kind, &root_span, &state, builder.staged_children(&children))?;
let root = builder.add(kind, root_span, state, children, ext, ())?;
Ok(Some(builder.finish(root)?))
}
pub fn tree(&self) -> &NodeTree<L, B> {
&self.tree
}
pub fn into_tree(self) -> NodeTree<L, B> {
self.tree
}
fn view<'k>(&'k self, entry: &'k KeyValEntryData) -> KeyValEntry<'k, L, B> {
KeyValEntry {
key: &entry.key,
value: entry.value.map(|id| self.tree.node(id).children()),
}
}
}
impl<L: Lang, B> fmt::Debug for KeyVals<L, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut map = f.debug_map();
for entry in &self.entries {
map.entry(&&*entry.key, &entry.value);
}
map.finish()
}
}
pub struct KeyValEntry<'k, L: Lang, B = ()> {
key: &'k str,
value: Option<NodeSlice<'k, L, B>>,
}
impl<'k, L: Lang, B> KeyValEntry<'k, L, B> {
pub fn key(&self) -> &'k str {
self.key
}
pub fn value(&self) -> Option<NodeSlice<'k, L, B>> {
self.value
}
pub fn value_content(&self) -> Option<NodeSlice<'k, L, B>> {
let value = self.value?;
if value.len() == 1 {
let node = value.first().expect("len 1");
if node.is_group() {
return Some(node.children());
}
}
Some(value)
}
}
impl<L: Lang, B> Clone for KeyValEntry<'_, L, B> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang, B> Copy for KeyValEntry<'_, L, B> {}
impl<L: Lang, B> fmt::Debug for KeyValEntry<'_, L, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyValEntry")
.field("key", &self.key)
.field("value", &self.value)
.finish()
}
}
#[cfg(test)]
#[allow(clippy::let_unit_value)]
mod tests {
use super::*;
use crate::engine::Language;
use crate::latexlike::Latexlike;
use crate::node::NodeTree;
fn parse(input: &str) -> NodeTree<Latexlike> {
use crate::error::Recovery;
use crate::latexlike::minidefs::minilatex_package;
use crate::latexlike::LatexlikeDriver;
use crate::state::ParsingState;
let language: Language<Latexlike> = Language::new(
LatexlikeDriver::new(Recovery::Strict),
ParsingState::lang_initial_with_packages([minilatex_package()]).expect("seed state"),
);
let result = language.parse(input).expect("test inputs parse cleanly");
assert!(result.diagnostics.is_empty(), "unexpected diagnostics: {:?}", result.diagnostics);
result.tree
}
fn texts(slice: NodeSlice<'_, Latexlike>) -> Vec<String> {
slice.iter().map(|node| node.span_content().into()).collect()
}
enum Part<'t> {
Owned(&'t str),
Copied(NodeRef<'t, Latexlike>),
}
fn owned_tree(parts: &[Part<'_>]) -> NodeTree<Latexlike> {
use crate::state::ParsingState;
let source: Arc<Source> = Arc::new(Source::new("<generated>"));
let span = SourceSpan::new(&source, 0..source.content().len());
let state = Arc::new(ParsingState::<Latexlike>::lang_initial().expect("seed state"));
let mut builder: NodeTreeBuilder<Latexlike> = NodeTreeBuilder::new();
let mut children = Vec::new();
for part in parts {
children.push(match part {
Part::Owned(text) => {
let kind = NodeKind::chars(TextContent::Owned((*text).into()));
let ext = <Latexlike as Lang>::make_node_ext(
&kind,
&span,
&state,
builder.staged_children(&[]),
)
.expect("mint node ext");
builder
.add(kind, span.clone(), state.clone(), Vec::new(), ext, ())
.expect("stage an owned chars node")
}
Part::Copied(node) => copy_subtree_into(&mut builder, *node, &mut |_| ())
.expect("copy a parsed subtree"),
});
}
let kind = NodeKind::list();
let ext =
<Latexlike as Lang>::make_node_ext(&kind, &span, &state, builder.staged_children(&children))
.expect("mint node ext");
let root = builder.add(kind, span, state, children, ext, ()).expect("stage the root");
builder.finish(root).expect("the fixture satisfies the all-trees law")
}
#[test]
fn content_as_chars_single_chars_node_is_borrowed() {
let tree = parse("my-label");
let content = content_as_chars(tree.root().children()).unwrap();
assert_eq!(content, "my-label");
assert!(matches!(content, Cow::Borrowed(_)));
}
#[test]
fn content_as_chars_recurses_groups_and_skips_comments() {
let tree = parse("ab{cd{e}}f");
assert_eq!(content_as_chars(tree.root().children()).unwrap(), "abcdef");
let tree = parse("ab%c\ncd");
let content = content_as_chars(tree.root().children()).unwrap();
assert_eq!(content, "abcd");
assert!(matches!(content, Cow::Owned(_)));
let tree = parse("");
assert_eq!(content_as_chars(tree.root().children()).unwrap(), "");
}
#[test]
fn content_as_chars_reads_owned_chars_content() {
let tree = owned_tree(&[Part::Owned("my-label")]);
let content = content_as_chars(tree.root().children()).unwrap();
assert_eq!(content, "my-label");
assert!(matches!(content, Cow::Borrowed(_)));
assert_eq!(tree.root().child(0).unwrap().span_content(), "<generated>");
let parsed = parse("{x,y}");
let tree = owned_tree(&[
Part::Owned("a"),
Part::Copied(parsed.root().child(0).unwrap()),
Part::Owned("b"),
]);
assert_eq!(content_as_chars(tree.root().children()).unwrap(), "ax,yb");
}
#[test]
fn content_as_chars_rejects_callables() {
let tree = parse("a--b");
let error = content_as_chars(tree.root().children()).unwrap_err();
let ExtractError::NonCharsContent { node } = error else {
panic!("expected NonCharsContent, got {error:?}");
};
assert!(tree.node(node).is_callable());
}
#[test]
fn split_at_chars_groups_protect_their_interior() {
let tree = parse("key1,key2,my{special,key},keyN");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert_eq!(split.len(), 4);
assert_eq!(texts(split.segment(0).unwrap()), ["key1"]);
assert_eq!(texts(split.segment(1).unwrap()), ["key2"]);
assert_eq!(texts(split.segment(2).unwrap()), ["my", "{special,key}"]);
assert_eq!(texts(split.segment(3).unwrap()), ["keyN"]);
let group = split.segment(2).unwrap().get(1).unwrap();
assert!(group.is_group());
assert_eq!(content_as_chars(group.children()).unwrap(), "special,key");
assert_eq!(split.segments().count(), 4);
}
#[test]
fn split_segments_carry_exact_spans() {
let tree = parse("key1,my{a,b}tail");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert_eq!(split.len(), 2);
let seg0 = split.segment(0).unwrap();
assert_eq!(seg0.span().unwrap().range(), 0..4);
assert_eq!(seg0.source_text(), Some("key1"));
let seg1 = split.segment(1).unwrap();
assert_eq!(seg1.span().unwrap().range(), 5..16);
assert_eq!(seg1.source_text(), Some("my{a,b}tail"));
assert!(Arc::ptr_eq(
seg1.span().unwrap().source(),
tree.root().span().source()
));
}
#[test]
fn split_at_chars_drops_empty_segments() {
let tree = parse("a,,b");
assert_eq!(split_at_chars_drop_annotations(tree.root().children(), ",").unwrap().len(), 2);
let tree = parse(",a,");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert_eq!(split.len(), 1);
assert_eq!(texts(split.segment(0).unwrap()), ["a"]);
let tree = parse(",,");
assert!(split_at_chars_drop_annotations(tree.root().children(), ",").unwrap().is_empty());
}
#[test]
fn split_at_chars_multi_char_separator_and_errors() {
let tree = parse("a::b::c");
let split = split_at_chars_drop_annotations(tree.root().children(), "::").unwrap();
assert_eq!(split.len(), 3);
assert_eq!(
split.segments().map(|s| s.source_text().unwrap().to_string()).collect::<Vec<_>>(),
["a", "b", "c"]
);
assert_eq!(
split_at_chars_drop_annotations(tree.root().children(), "").unwrap_err(),
ExtractError::EmptySeparator
);
}
#[test]
fn split_of_empty_or_separator_free_input() {
let tree = parse("");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert!(split.is_empty());
assert!(split.segment(0).is_none());
let tree = parse("a{b}c");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert_eq!(split.len(), 1);
assert_eq!(split.segment(0).unwrap().source_text(), Some("a{b}c"));
}
#[test]
fn split_segments_are_ordinary_node_lists() {
let tree = parse("a=1,b={x,y}");
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
let resplit = split_at_chars_drop_annotations(split.segment(0).unwrap(), "=").unwrap();
assert_eq!(resplit.len(), 2);
assert_eq!(content_as_chars(resplit.segment(1).unwrap()).unwrap(), "1");
assert!(split.tree().descendants().count() >= 4);
let owned: NodeTree<Latexlike> = split.into_tree();
assert_eq!(owned.root().child(1).unwrap().children().source_text(), Some("b={x,y}"));
}
#[test]
fn split_partials_of_owned_content_keep_whole_node_provenance() {
let tree = parse("ab,cd").materialize();
let split = split_at_chars_drop_annotations(tree.root().children(), ",").unwrap();
assert_eq!(split.len(), 2);
let seg0 = split.segment(0).unwrap();
assert_eq!(seg0.first().unwrap().chars(), Some("ab"));
assert_eq!(seg0.span().unwrap().range(), 0..5); }
#[test]
fn split_at_chars_cuts_owned_content_and_keeps_node_provenance() {
let parsed = parse("{x,y}").materialize();
let group = parsed.root().child(0).unwrap();
let tree =
owned_tree(&[Part::Owned("k1,my"), Part::Copied(group), Part::Owned("tail,k3")]);
let split = split_at_chars(tree.root().children(), ",", |part| {
part.partial_text().map(String::from)
})
.unwrap();
assert_eq!(split.len(), 3);
assert_eq!(content_as_chars(split.segment(0).unwrap()).unwrap(), "k1");
assert_eq!(content_as_chars(split.segment(1).unwrap()).unwrap(), "myx,ytail");
assert_eq!(content_as_chars(split.segment(2).unwrap()).unwrap(), "k3");
assert_eq!(
*split.segment(0).unwrap().first().unwrap().annotation(),
Some("k1".to_string())
);
let seg0 = split.segment(0).unwrap();
assert_eq!(seg0.first().unwrap().chars(), Some("k1"));
assert_eq!(seg0.span().unwrap().range(), 0..11);
assert_eq!(seg0.source_text(), Some("<generated>"));
assert_eq!(split.segment(1).unwrap().span(), None);
assert_eq!(split.segment(1).unwrap().source_text(), None);
}
#[test]
fn parse_keyval_entries_in_source_order() {
let tree = parse("width=2cm,legend={a,b},draft,label=");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
assert_eq!(keyvals.len(), 4);
let width = keyvals.keyval(0).unwrap();
assert_eq!(width.key(), "width");
assert_eq!(content_as_chars(width.value().unwrap()).unwrap(), "2cm");
let legend = keyvals.get("legend").unwrap();
assert_eq!(texts(legend.value().unwrap()), ["{a,b}"]);
assert_eq!(content_as_chars(legend.value_content().unwrap()).unwrap(), "a,b");
assert_eq!(legend.value_content().unwrap().len(), 1);
assert!(keyvals.get("draft").unwrap().value().is_none());
let label = keyvals.get("label").unwrap();
assert!(label.value().unwrap().is_empty());
assert!(keyvals.get("nonsense").is_none());
assert_eq!(keyvals.keyval(4).map(|_| ()), None);
}
#[test]
fn parse_keyval_trims_keys_and_flattens_grouped_keys() {
let tree = parse(" spaced key = v ,{grouped}=w");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
assert_eq!(keyvals.keyval(0).unwrap().key(), "spaced key");
assert_eq!(content_as_chars(keyvals.keyval(0).unwrap().value().unwrap()).unwrap(), " v ");
assert_eq!(keyvals.keyval(1).unwrap().key(), "grouped");
let tree = parse("a=b=c");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
assert_eq!(content_as_chars(keyvals.get("a").unwrap().value().unwrap()).unwrap(), "b=c");
}
#[test]
fn parse_keyval_duplicates_last_wins_via_get() {
let tree = parse("a=1,b=9,a=2");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
assert_eq!(keyvals.len(), 3); assert_eq!(content_as_chars(keyvals.get("a").unwrap().value().unwrap()).unwrap(), "2");
assert_eq!(content_as_chars(keyvals.keyval(0).unwrap().value().unwrap()).unwrap(), "1");
let keys: Vec<_> = keyvals.iter().map(|entry| entry.key().to_string()).collect();
assert_eq!(keys, ["a", "b", "a"]);
}
#[test]
fn parse_keyval_rejects_non_chars_keys() {
let tree = parse("a--b=1");
assert!(matches!(
parse_keyval_drop_annotations(tree.root().children()),
Err(ExtractError::NonCharsContent { .. })
));
}
#[test]
fn get_combined_with_joins_all_occurrences() {
let tree = parse("a=1,b=x,a={2,3}");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
let combined = keyvals.get_combined_with("a", ";").unwrap().unwrap();
let run = combined.root().children();
assert_eq!(run.len(), 3);
assert_eq!(run.get(0).unwrap().chars(), Some("1"));
assert_eq!(run.get(1).unwrap().chars(), Some(";")); assert!(run.get(2).unwrap().is_group());
assert_eq!(content_as_chars(run.get(2).unwrap().children()).unwrap(), "2,3");
assert_eq!(run.get(1).unwrap().span_content(), ";");
assert!(keyvals.get_combined_with("zzz", ";").unwrap().is_none());
let tree = parse("a,a=1");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
let combined = keyvals.get_combined_with("a", ";").unwrap().unwrap();
assert_eq!(combined.root().children().len(), 1);
let tree = parse("a=1,a=2");
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
let combined = keyvals.get_combined_with("a", "").unwrap().unwrap();
assert_eq!(texts(combined.root().children()), ["1", "2"]);
}
#[test]
fn keyval_reads_owned_content() {
let parsed = parse("{a,b}").materialize();
let group = parsed.root().child(0).unwrap();
let tree = owned_tree(&[
Part::Owned("width=2cm, legend ="),
Part::Copied(group),
Part::Owned(",draft"),
]);
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
let keys: Vec<_> = keyvals.iter().map(|entry| entry.key().to_string()).collect();
assert_eq!(keys, ["width", "legend", "draft"]);
assert_eq!(
content_as_chars(keyvals.get("width").unwrap().value().unwrap()).unwrap(),
"2cm"
);
assert_eq!(
content_as_chars(keyvals.get("legend").unwrap().value_content().unwrap()).unwrap(),
"a,b"
);
assert!(keyvals.get("draft").unwrap().value().is_none());
let tree = owned_tree(&[Part::Owned("a=1,a=2")]);
let keyvals = parse_keyval_drop_annotations(tree.root().children()).unwrap();
let combined = keyvals.get_combined_with("a", ";").unwrap().unwrap();
assert_eq!(content_as_chars(combined.root().children()).unwrap(), "1;2");
}
#[test]
fn run_readers_skip_noise_and_reject_unexpected_content() {
let tree = parse("a{b}");
assert!(matches!(
split_embellishments_drop_annotations(tree.root().children()),
Err(ExtractError::UnexpectedContent { .. })
));
assert!(matches!(
split_tack_on_fields_drop_annotations(tree.root().children()),
Err(ExtractError::UnexpectedContent { .. })
));
let tree = parse("");
assert!(split_embellishments_drop_annotations(tree.root().children()).unwrap().is_empty());
assert!(split_tack_on_fields_drop_annotations(tree.root().children()).unwrap().is_empty());
let tree = parse(" %c\n ");
assert!(split_embellishments_drop_annotations(tree.root().children()).unwrap().is_empty());
assert!(split_tack_on_fields_drop_annotations(tree.root().children()).unwrap().is_empty());
}
#[test]
fn run_readers_read_owned_content() {
let parsed = parse("{p}").materialize();
let group = parsed.root().child(0).unwrap();
let tree = owned_tree(&[Part::Owned(" "), Part::Copied(group)]);
let fields = split_embellishments_drop_annotations(tree.root().children()).unwrap();
assert_eq!(fields.len(), 1);
assert_eq!(fields.keyval(0).unwrap().key(), "{");
assert_eq!(
content_as_chars(fields.keyval(0).unwrap().value().unwrap()).unwrap(),
"p"
);
let parsed = parse("\\emph{x}").materialize();
let emph = parsed.root().child(0).unwrap();
let tree = owned_tree(&[Part::Owned(" "), Part::Copied(emph)]);
let fields = split_tack_on_fields_drop_annotations(tree.root().children()).unwrap();
assert_eq!(fields.len(), 1);
assert_eq!(fields.keyval(0).unwrap().key(), "emph");
assert_eq!(
content_as_chars(fields.keyval(0).unwrap().value().unwrap()).unwrap(),
"x"
);
}
#[test]
fn split_at_chars_general_form_mints_from_part_facts() {
let tree = parse("ab,{c}d");
let chars_id = tree.root().child(0).unwrap().id();
let group_id = tree.root().child(1).unwrap().id();
#[derive(Clone, Debug, PartialEq, Eq)]
struct Mint {
original: Option<crate::node::NodeId>,
partial: Option<String>,
segment: Option<usize>,
}
let split = split_at_chars(tree.root().children(), ",", |part| Mint {
original: part.original().map(|node| node.id()),
partial: part.partial_text().map(String::from),
segment: part.segment_index(),
})
.unwrap();
let root = split.tree().root();
assert_eq!(
*root.annotation(),
Mint { original: None, partial: None, segment: None }
);
assert_eq!(
*root.child(0).unwrap().annotation(),
Mint { original: None, partial: None, segment: Some(0) }
);
let ab = split.segment(0).unwrap().first().unwrap();
assert_eq!(
*ab.annotation(),
Mint {
original: Some(chars_id),
partial: Some("ab".into()),
segment: Some(0)
}
);
let seg1 = split.segment(1).unwrap();
let group = seg1.get(0).unwrap();
assert_eq!(
*group.annotation(),
Mint { original: Some(group_id), partial: None, segment: Some(1) }
);
assert!(group.annotation().partial.is_none());
let inner = group.child(0).unwrap();
assert_eq!(
inner.annotation().original,
Some(tree.root().child(1).unwrap().child(0).unwrap().id())
);
let d = seg1.get(1).unwrap();
assert_eq!(d.annotation().partial, None);
assert_eq!(d.annotation().original, Some(tree.root().child(2).unwrap().id()));
}
#[test]
fn split_at_chars_keep_annotations_clones_through() {
let tree = parse("x,{y}").annotate(|node| node.id().index() as u32 + 100);
let split = split_at_chars_keep_annotations(tree.root().children(), ",").unwrap();
let x = split.segment(0).unwrap().first().unwrap();
assert_eq!(*x.annotation(), *tree.root().child(0).unwrap().annotation());
let group = split.segment(1).unwrap().first().unwrap();
assert_eq!(*group.annotation(), *tree.root().child(1).unwrap().annotation());
assert_eq!(*split.tree().root().annotation(), 0);
assert_eq!(*split.tree().root().child(0).unwrap().annotation(), 0);
}
#[test]
fn producers_accept_any_input_annotation_type() {
#[derive(Clone, Debug, PartialEq, Eq)]
struct Stage(&'static str);
let tree = parse("a=1,b={x,y}").annotate(|_| Stage("analysis"));
let keyvals = parse_keyval(tree.root().children(), |part| {
(part.entry_index(), part.original().is_some())
})
.unwrap();
assert_eq!(keyvals.len(), 2);
let value = keyvals.keyval(0).unwrap().value().unwrap();
assert_eq!(*value.first().unwrap().annotation(), (Some(0), true));
let wrapper = value.first().unwrap().parent().unwrap();
assert_eq!(*wrapper.annotation(), (Some(0), false));
let value1 = keyvals.get("b").unwrap().value().unwrap();
assert_eq!(value1.first().unwrap().annotation().0, Some(1));
let resplit =
split_at_chars(value1.first().unwrap().children(), ",", |part| {
part.original().map(|n| *n.annotation())
})
.unwrap();
assert_eq!(resplit.len(), 2);
assert_eq!(
*resplit.segment(0).unwrap().first().unwrap().annotation(),
Some((Some(1), true))
);
}
#[test]
fn keyval_partials_report_their_cut_text() {
let tree = parse("k=start,rest");
let keyvals = parse_keyval(tree.root().children(), |part| {
(part.is_partial(), part.partial_text().map(String::from))
})
.unwrap();
let value = keyvals.get("k").unwrap().value().unwrap();
assert_eq!(
*value.first().unwrap().annotation(),
(true, Some("start".to_string()))
);
}
#[test]
fn run_reader_triples_mint_annotations() {
let tree = parse("{p}{q}");
let fields = split_embellishments(tree.root().children(), |part| {
(part.entry_index(), part.original().is_some())
})
.unwrap();
assert_eq!(fields.len(), 2);
let q = fields.keyval(1).unwrap().value().unwrap();
assert_eq!(*q.first().unwrap().annotation(), (Some(1), true));
assert_eq!(*fields.tree().root().annotation(), (None, false));
let kept = split_embellishments_keep_annotations(
parse("{p}").annotate(|_| 7u32).root().children(),
)
.unwrap();
assert_eq!(*kept.keyval(0).unwrap().value().unwrap().first().unwrap().annotation(), 7);
let tree = parse(" -- ");
let mut calls = 0usize;
let fields = split_tack_on_fields(tree.root().children(), |part| {
calls += 1;
part.entry_index()
})
.unwrap();
assert_eq!(fields.len(), 1);
assert_eq!(fields.keyval(0).unwrap().key(), "--");
assert!(fields.keyval(0).unwrap().value().is_none());
assert_eq!(calls, 1); assert_eq!(*fields.tree().root().annotation(), None);
let kept =
split_tack_on_fields_keep_annotations(tree.annotate(|_| 3u8).root().children())
.unwrap();
assert_eq!(*kept.tree().root().annotation(), 0); }
#[test]
fn helpers_compose_over_argument_content() {
let tree = parse("{k1,k2{x,y},k3}");
let group = tree.root().child(0).unwrap();
let split = split_at_chars_drop_annotations(group.children(), ",").unwrap();
assert_eq!(split.len(), 3);
let keys: Vec<_> = split
.segments()
.map(|segment| content_as_chars(segment).map(|k| k.into_owned()))
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(keys, ["k1", "k2x,y", "k3"]);
}
}