use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Range;
use crate::source::{SourceSpan, Span, TextContent};
use crate::state::{Lang, ParsingState};
use super::arguments::ContentNodes;
use super::kind::{CallableData, NodeKind};
use super::tree::{NodeData, NodeTree, TreeCore, TreeTag, NO_PARENT};
use super::NodeExt;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct BuildId(u32);
impl BuildId {
pub(crate) const fn number(self) -> u32 {
self.0
}
}
impl fmt::Debug for BuildId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BuildId({})", self.0)
}
}
struct Staged<L: Lang> {
kind: NodeKind<L>,
ext: NodeExt<L>,
span: SourceSpan<L::SourceOrigin>,
parsing_state: Arc<ParsingState<L>>,
children: Vec<BuildId>,
claimed: bool,
}
pub struct NodeTreeBuilder<L: Lang, A = ()> {
staged: Vec<Staged<L>>,
annotations: Vec<A>,
}
impl<L: Lang, A> NodeTreeBuilder<L, A> {
pub fn new() -> NodeTreeBuilder<L, A> {
NodeTreeBuilder { staged: Vec::new(), annotations: Vec::new() }
}
}
impl<L: Lang, A> NodeTreeBuilder<L, A> {
pub fn add(
&mut self,
kind: NodeKind<L>,
span: SourceSpan<L::SourceOrigin>,
parsing_state: Arc<ParsingState<L>>,
children: Vec<BuildId>,
ext: NodeExt<L>,
annotation: A,
) -> Result<BuildId, NodeBuildError> {
if self.staged.len() >= u32::MAX as usize {
return Err(NodeBuildError::TooManyNodes);
}
for child in &children {
let staged = self
.staged
.get_mut(child.0 as usize)
.ok_or(NodeBuildError::ChildNotStaged { child: *child })?;
if staged.claimed {
return Err(NodeBuildError::ChildAlreadyClaimed { child: *child });
}
staged.claimed = true;
}
if let NodeKind::Callable(data) = &kind {
let n_children = children.len() as u32;
let mut next: u32 = 0;
let regions = data
.arguments
.iter()
.filter_map(|arg| arg.region.as_ref())
.chain(data.slots.iter().map(|slot| &slot.region));
for region in regions {
let Some((child_range, content)) = region.staged() else {
return Err(NodeBuildError::RegionAlreadyResolved);
};
if child_range.start > child_range.end || child_range.end > n_children {
return Err(NodeBuildError::RegionOutOfBounds {
region: child_range.clone(),
n_children,
});
}
if child_range.start != next {
return Err(NodeBuildError::RegionNotTiling {
region: child_range.clone(),
expected_start: next,
});
}
next = child_range.end;
match content {
ContentNodes::InRegion(r) => {
let region_len = child_range.end - child_range.start;
if r.start > r.end || r.end > region_len {
return Err(NodeBuildError::ContentOutOfBounds {
content: r.clone(),
available: region_len,
});
}
}
ContentNodes::InChildrenOf(b, r) => {
let content_parent = self
.staged
.get(b.0 as usize)
.ok_or(NodeBuildError::ContentParentNotStaged { parent: *b })?;
if r.start > r.end || r.end as usize > content_parent.children.len() {
return Err(NodeBuildError::ContentOutOfBounds {
content: r.clone(),
available: content_parent.children.len() as u32,
});
}
}
}
}
if next != n_children {
return Err(NodeBuildError::ChildrenNotInRegions { unassigned: next..n_children });
}
}
check_spanned_contents(&kind, &span)?;
let id = BuildId(self.staged.len() as u32);
self.staged.push(Staged { kind, ext, span, parsing_state, children, claimed: false });
self.annotations.push(annotation);
Ok(id)
}
pub fn staged_nodes(&self) -> StagedNodes<'_, L> {
StagedNodes { staged: &self.staged }
}
pub fn staged_children<'b>(
&'b self,
children: &'b [BuildId],
) -> StagedChildren<'b, L> {
StagedChildren { arena: &self.staged, children }
}
pub fn finish(self, root: BuildId) -> Result<NodeTree<L, A>, NodeBuildError> {
const NONE: u32 = NO_PARENT; let tree_tag = super::tree::next_tree_tag();
match self.staged.get(root.0 as usize) {
None => return Err(NodeBuildError::RootNotStaged { root }),
Some(entry) if entry.claimed => return Err(NodeBuildError::RootClaimed { root }),
Some(_) => {}
}
let mut staged: Vec<Option<Staged<L>>> = self.staged.into_iter().map(Some).collect();
let mut staged_annotations: Vec<Option<A>> =
self.annotations.into_iter().map(Some).collect();
let mut order: Vec<u32> = Vec::with_capacity(staged.len());
let mut ranges: Vec<Range<u32>> = Vec::with_capacity(staged.len());
let mut parent: Vec<u32> = Vec::with_capacity(staged.len()); let mut final_of: Vec<u32> = alloc::vec![NONE; staged.len()]; order.push(root.0);
parent.push(NONE);
final_of[root.0 as usize] = 0;
let mut pos = 0;
while pos < order.len() {
let sid = order[pos] as usize;
let start = order.len() as u32;
for child in &staged[sid].as_ref().unwrap().children {
final_of[child.0 as usize] = order.len() as u32;
parent.push(pos as u32);
order.push(child.0);
}
let end = order.len() as u32;
ranges.push(start..end);
pos += 1;
}
let mut nodes = Vec::with_capacity(order.len());
let mut annotations = Vec::with_capacity(order.len());
for (f, &sid) in order.iter().enumerate() {
let children = ranges[f].clone();
let mut staged = staged[sid as usize].take().expect("staged node used twice");
annotations
.push(staged_annotations[sid as usize].take().expect("staged node used twice"));
if let NodeKind::Callable(data) = &mut staged.kind {
resolve_regions(data, f as u32, &children, &ranges, &parent, &final_of, tree_tag)?;
}
nodes.push(NodeData {
kind: staged.kind,
ext: staged.ext,
span: staged.span,
parsing_state: staged.parsing_state,
children,
});
}
let single_source = match nodes.split_first() {
Some((first, rest)) => {
let source = first.span.source();
rest.iter().all(|data| Arc::ptr_eq(data.span.source(), source))
}
None => true,
};
Ok(NodeTree {
core: Arc::new(TreeCore { nodes, parent, tree_tag, single_source }),
annotations,
})
}
}
fn resolve_regions<L: Lang>(
data: &mut CallableData<L>,
callable: u32,
callable_children: &Range<u32>,
ranges: &[Range<u32>],
parent: &[u32],
final_of: &[u32],
tree_tag: TreeTag,
) -> Result<(), NodeBuildError> {
const NONE: u32 = NO_PARENT;
let regions = data
.arguments
.arguments
.iter_mut()
.filter_map(|arg| arg.region.as_mut())
.chain(data.slots.slots.iter_mut().map(|slot| &mut slot.region));
for region in regions {
let (child_range, content) = {
let (c, k) = region.staged().expect("staged regions were checked in add()");
(c.clone(), k.clone())
};
let children =
callable_children.start + child_range.start..callable_children.start + child_range.end;
let (content_range, content_parent) = match content {
ContentNodes::InRegion(r) => {
(children.start + r.start..children.start + r.end, callable)
}
ContentNodes::InChildrenOf(b, r) => {
let bf = final_of[b.0 as usize];
if bf == NONE {
return Err(NodeBuildError::ContentParentUnreachable { parent: b });
}
let mut a = bf;
loop {
let p = parent[a as usize];
if p == NONE {
return Err(NodeBuildError::ContentParentOutsideSubtree { parent: b });
}
if p == callable {
break;
}
a = p;
}
if !children.contains(&a) {
return Err(NodeBuildError::ContentParentOutsideRegion { parent: b });
}
let block = &ranges[bf as usize];
(block.start + r.start..block.start + r.end, bf)
}
};
region.resolve(children, content_range, content_parent, tree_tag);
}
Ok(())
}
pub struct StagedNodes<'b, L: Lang> {
staged: &'b [Staged<L>],
}
impl<'b, L: Lang> StagedNodes<'b, L> {
pub fn get(&self, id: BuildId) -> Option<StagedNodeView<'b, L>> {
self.staged.get(id.0 as usize).map(|staged| StagedNodeView { id, staged })
}
pub fn len(&self) -> usize {
self.staged.len()
}
pub fn is_empty(&self) -> bool {
self.staged.is_empty()
}
}
pub struct StagedNodeView<'b, L: Lang> {
id: BuildId,
staged: &'b Staged<L>,
}
impl<'b, L: Lang> StagedNodeView<'b, L> {
pub fn id(&self) -> BuildId {
self.id
}
pub fn kind(&self) -> &'b NodeKind<L> {
&self.staged.kind
}
pub fn ext(&self) -> &'b NodeExt<L> {
&self.staged.ext
}
pub fn span(&self) -> &'b SourceSpan<L::SourceOrigin> {
&self.staged.span
}
pub fn parsing_state(&self) -> &'b Arc<ParsingState<L>> {
&self.staged.parsing_state
}
pub fn children(&self) -> &'b [BuildId] {
&self.staged.children
}
}
pub struct StagedChildren<'b, L: Lang> {
arena: &'b [Staged<L>],
children: &'b [BuildId],
}
impl<'b, L: Lang> StagedChildren<'b, L> {
pub fn len(&self) -> usize {
self.children.len()
}
pub fn is_empty(&self) -> bool {
self.children.is_empty()
}
pub fn get(&self, i: usize) -> Option<StagedChildView<'b, L>> {
let id = *self.children.get(i)?;
let staged = self.arena.get(id.0 as usize)?;
Some(StagedChildView { arena: self.arena, staged })
}
pub fn iter(&self) -> impl Iterator<Item = StagedChildView<'b, L>> + use<'b, L> {
let arena = self.arena;
self.children
.iter()
.filter_map(move |id| arena.get(id.0 as usize))
.map(move |staged| StagedChildView { arena, staged })
}
}
pub struct StagedChildView<'b, L: Lang> {
arena: &'b [Staged<L>],
staged: &'b Staged<L>,
}
impl<'b, L: Lang> StagedChildView<'b, L> {
pub fn kind(&self) -> &'b NodeKind<L> {
&self.staged.kind
}
pub fn ext(&self) -> &'b NodeExt<L> {
&self.staged.ext
}
pub fn span(&self) -> &'b SourceSpan<L::SourceOrigin> {
&self.staged.span
}
pub fn parsing_state(&self) -> &'b Arc<ParsingState<L>> {
&self.staged.parsing_state
}
pub fn children(&self) -> StagedChildren<'b, L> {
StagedChildren { arena: self.arena, children: &self.staged.children }
}
}
impl<L: Lang> Clone for StagedNodes<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for StagedNodes<'_, L> {}
impl<L: Lang> fmt::Debug for StagedNodes<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StagedNodes").field("len", &self.staged.len()).finish()
}
}
impl<L: Lang> Clone for StagedNodeView<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for StagedNodeView<'_, L> {}
impl<L: Lang> fmt::Debug for StagedNodeView<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StagedNodeView")
.field("id", &self.id)
.field("kind", &self.staged.kind)
.field("span", &self.staged.span)
.field("children", &self.staged.children)
.finish()
}
}
impl<L: Lang> Clone for StagedChildren<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for StagedChildren<'_, L> {}
impl<L: Lang> fmt::Debug for StagedChildren<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StagedChildren").field("children", &self.children).finish()
}
}
impl<L: Lang> Clone for StagedChildView<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for StagedChildView<'_, L> {}
impl<L: Lang> fmt::Debug for StagedChildView<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StagedChildView")
.field("kind", &self.staged.kind)
.field("span", &self.staged.span)
.field("children", &self.staged.children)
.finish()
}
}
impl<L: Lang, A> Default for NodeTreeBuilder<L, A> {
fn default() -> Self {
NodeTreeBuilder::new()
}
}
impl<L: Lang, A> fmt::Debug for NodeTreeBuilder<L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodeTreeBuilder").field("staged", &self.staged.len()).finish()
}
}
fn check_spanned_contents<L: Lang>(
kind: &NodeKind<L>,
span: &SourceSpan<L::SourceOrigin>,
) -> Result<(), NodeBuildError> {
let content = span.source().content();
let check = |text: &TextContent, what: &'static str| match text {
TextContent::Spanned(s) if s.get(content).is_none() => {
Err(NodeBuildError::SpannedContentInvalid {
what,
span: *s,
content_len: content.len(),
})
}
_ => Ok(()),
};
match kind {
NodeKind::Chars { content: text, .. } => check(text, "chars content"),
NodeKind::Comment(data) => {
check(&data.content, "comment content")?;
check(&data.start, "comment start delimiter")?;
check(&data.post_space, "comment post-space")
}
NodeKind::Callable(_) => Ok(()),
NodeKind::Group(data) => {
check(&data.open, "group open delimiter")?;
check(&data.close, "group close delimiter")
}
NodeKind::List => Ok(()),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NodeBuildError {
TooManyNodes,
ExtMintFailed {
detail: String,
},
ChildNotStaged {
child: BuildId,
},
ChildAlreadyClaimed {
child: BuildId,
},
RegionAlreadyResolved,
RegionOutOfBounds {
region: Range<u32>,
n_children: u32,
},
RegionNotTiling {
region: Range<u32>,
expected_start: u32,
},
ChildrenNotInRegions {
unassigned: Range<u32>,
},
ContentOutOfBounds {
content: Range<u32>,
available: u32,
},
ContentParentNotStaged {
parent: BuildId,
},
SpannedContentInvalid {
what: &'static str,
span: Span,
content_len: usize,
},
RootNotStaged {
root: BuildId,
},
RootClaimed {
root: BuildId,
},
ContentParentUnreachable {
parent: BuildId,
},
ContentParentOutsideSubtree {
parent: BuildId,
},
ContentParentOutsideRegion {
parent: BuildId,
},
ReplacementsLengthMismatch {
children: usize,
replacements: usize,
},
ContentParentUnmapped {
parent: super::NodeId,
},
StagedContentParentUnmapped {
parent: BuildId,
},
}
impl fmt::Display for NodeBuildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NodeBuildError::TooManyNodes => {
write!(f, "Node tree too large (node and child counts must fit in 32 bits)")
}
NodeBuildError::ExtMintFailed { detail } => {
write!(f, "‘Lang::make_node_ext’ failed: {}", detail)
}
NodeBuildError::ChildNotStaged { child } => {
write!(f, "Invalid child node {}: the node is not staged in this builder", child.0)
}
NodeBuildError::ChildAlreadyClaimed { child } => write!(
f,
"Invalid child node {}: the node is already the child of another node",
child.0
),
NodeBuildError::RegionAlreadyResolved => write!(
f,
"Invalid argument or slot records: records read back from a finished \
tree may not be staged again"
),
NodeBuildError::RegionOutOfBounds { region, n_children } => write!(
f,
"Invalid argument or slot region {:?} (the callable has {} \
children)",
region, n_children
),
NodeBuildError::RegionNotTiling { region, expected_start } => write!(
f,
"Argument or slot region {:?} must start at child offset {} (the \
regions must cover the children in order, without gaps)",
region, expected_start
),
NodeBuildError::ChildrenNotInRegions { unassigned } => write!(
f,
"Children {:?} are not in any argument or slot region (the regions must \
cover all children of the callable)",
unassigned
),
NodeBuildError::ContentOutOfBounds { content, available } => write!(
f,
"Invalid content range {:?} (the node list has {} nodes)",
content, available
),
NodeBuildError::ContentParentNotStaged { parent } => write!(
f,
"Invalid content parent node {}: the node is not staged in this builder",
parent.0
),
NodeBuildError::SpannedContentInvalid { what, span, content_len } => write!(
f,
"Invalid span {:?} of the {}: the span must lie within the source of \
the node ({} bytes) on character boundaries",
span, what, content_len
),
NodeBuildError::RootNotStaged { root } => {
write!(f, "Invalid root node {}: the node is not staged in this builder", root.0)
}
NodeBuildError::RootClaimed { root } => {
write!(f, "Invalid root node {}: the node is the child of another node", root.0)
}
NodeBuildError::ContentParentUnreachable { parent } => write!(
f,
"Invalid content parent node {}: the node is not reachable from the root",
parent.0
),
NodeBuildError::ContentParentOutsideSubtree { parent } => write!(
f,
"Invalid content parent node {}: the node is not inside the subtree of \
its callable",
parent.0
),
NodeBuildError::ContentParentOutsideRegion { parent } => write!(
f,
"Invalid content parent node {}: the node is not inside its argument or \
slot region",
parent.0
),
NodeBuildError::ReplacementsLengthMismatch { children, replacements } => write!(
f,
"Wrong number of replacements: one replacement per child is required \
({} children, {} replacements)",
children, replacements
),
NodeBuildError::ContentParentUnmapped { parent } => write!(
f,
"Missing mapping for content parent node {}: the content-parent mapping \
of ‘restage_node’ returned ‘None’",
parent.index()
),
NodeBuildError::StagedContentParentUnmapped { parent } => write!(
f,
"Missing mapping for content parent node {}: the content-parent mapping \
of ‘restage_staged_node’ returned ‘None’",
parent.0
),
}
}
}
impl core::error::Error for NodeBuildError {}