use alloc::vec::Vec;
use hashbrown::HashMap;
use crate::state::Lang;
use super::arguments::{ChildRegion, ContentNodes};
use super::builder::{BuildId, NodeTreeBuilder, StagedNodeView, StagedNodes};
use super::kind::NodeKind;
use super::node_ref::NodeRef;
use super::tree::NodeId;
use super::NodeBuildError;
impl<L: Lang, A> NodeTreeBuilder<L, A> {
pub fn restage_node<AOld>(
&mut self,
node: NodeRef<'_, L, AOld>,
replacements: &[Vec<BuildId>],
content_parents: impl Fn(NodeId) -> Option<BuildId>,
annotation: A,
) -> Result<BuildId, NodeBuildError> {
self.restage_node_with_content_mapping(
node,
replacements,
|old| content_parents(old).map(ContentParentMapping::Verbatim),
annotation,
)
}
pub(crate) fn restage_node_with_content_mapping<'a, AOld>(
&mut self,
node: NodeRef<'_, L, AOld>,
replacements: &[Vec<BuildId>],
content_parents: impl Fn(NodeId) -> Option<ContentParentMapping<'a>>,
annotation: A,
) -> Result<BuildId, NodeBuildError> {
let n_children = node.child_count();
if replacements.len() != n_children {
return Err(NodeBuildError::ReplacementsLengthMismatch {
children: n_children,
replacements: replacements.len(),
});
}
let prefix = replacement_prefix_sums(replacements)?;
let kind = match node.kind() {
NodeKind::Callable(data) => {
let mut data = (**data).clone();
let base = node.children().range().start;
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 {
*region = restage_region(region, base, node, &prefix, &content_parents)?;
}
NodeKind::Callable(alloc::boxed::Box::new(data))
}
other => other.clone(),
};
let children: Vec<BuildId> =
replacements.iter().flat_map(|entry| entry.iter().copied()).collect();
self.add(
kind,
node.span().clone(),
node.parsing_state().clone(),
children,
node.ext().clone(),
annotation,
)
}
pub fn restage_staged_node(
&mut self,
node: StagedNodeView<'_, L>,
replacements: &[Vec<BuildId>],
content_parents: impl Fn(BuildId) -> Option<BuildId>,
annotation: A,
) -> Result<BuildId, NodeBuildError> {
let n_children = node.children().len();
if replacements.len() != n_children {
return Err(NodeBuildError::ReplacementsLengthMismatch {
children: n_children,
replacements: replacements.len(),
});
}
let prefix = replacement_prefix_sums(replacements)?;
let kind = match node.kind() {
NodeKind::Callable(data) => {
let mut data = (**data).clone();
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 {
*region = restage_staged_region(region, &prefix, &content_parents)?;
}
NodeKind::Callable(alloc::boxed::Box::new(data))
}
other => other.clone(),
};
let children: Vec<BuildId> =
replacements.iter().flat_map(|entry| entry.iter().copied()).collect();
self.add(
kind,
node.span().clone(),
node.parsing_state().clone(),
children,
node.ext().clone(),
annotation,
)
}
}
fn replacement_prefix_sums(replacements: &[Vec<BuildId>]) -> Result<Vec<u32>, NodeBuildError> {
let mut prefix: Vec<u32> = Vec::with_capacity(replacements.len() + 1);
let mut total: usize = 0;
prefix.push(0);
for entry in replacements {
total += entry.len();
let Ok(offset) = u32::try_from(total) else {
return Err(NodeBuildError::TooManyNodes);
};
prefix.push(offset);
}
Ok(prefix)
}
fn restage_staged_region(
region: &ChildRegion,
prefix: &[u32],
content_parents: &impl Fn(BuildId) -> Option<BuildId>,
) -> Result<ChildRegion, NodeBuildError> {
let (children, content) = region
.staged()
.expect("a staged callable's regions are staged (add() rejects resolved ones)");
let new_children = prefix[children.start as usize]..prefix[children.end as usize];
let designation = match content {
ContentNodes::InRegion(r) => ContentNodes::InRegion(
prefix[(children.start + r.start) as usize] - new_children.start
..prefix[(children.start + r.end) as usize] - new_children.start,
),
ContentNodes::InChildrenOf(parent, r) => ContentNodes::InChildrenOf(
content_parents(*parent)
.ok_or(NodeBuildError::StagedContentParentUnmapped { parent: *parent })?,
r.clone(),
),
};
Ok(ChildRegion::new(new_children, designation))
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum ContentParentMapping<'a> {
Verbatim(BuildId),
Translate(BuildId, &'a [u32]),
}
fn restage_region<'a, L: Lang, AOld>(
region: &ChildRegion,
base: u32,
callable: NodeRef<'_, L, AOld>,
prefix: &[u32],
content_parents: &impl Fn(NodeId) -> Option<ContentParentMapping<'a>>,
) -> Result<ChildRegion, NodeBuildError> {
let children = region.children();
let content = region.content_range();
let parent = region.content_parent();
let new_children =
prefix[(children.start - base) as usize]..prefix[(children.end - base) as usize];
let designation = if parent == callable.id() {
let content_start = prefix[(content.start - base) as usize];
let content_end = prefix[(content.end - base) as usize];
ContentNodes::InRegion(
content_start - new_children.start..content_end - new_children.start,
)
} else {
let parent_node = callable.tree().node(parent);
let parent_base = parent_node.children().range().start;
let child_range = content.start - parent_base..content.end - parent_base;
match content_parents(parent)
.ok_or(NodeBuildError::ContentParentUnmapped { parent })?
{
ContentParentMapping::Verbatim(new_parent) => {
ContentNodes::InChildrenOf(new_parent, child_range)
}
ContentParentMapping::Translate(new_parent, parent_prefix) => {
ContentNodes::InChildrenOf(
new_parent,
parent_prefix[child_range.start as usize]
..parent_prefix[child_range.end as usize],
)
}
}
};
Ok(ChildRegion::new(new_children, designation))
}
pub(crate) fn copy_subtree_into<'t, L: Lang, AOld, B>(
builder: &mut NodeTreeBuilder<L, B>,
node: NodeRef<'t, L, AOld>,
annotate: &mut impl FnMut(NodeRef<'t, L, AOld>) -> B,
) -> Result<BuildId, NodeBuildError> {
let mut ids: HashMap<NodeId, BuildId> = HashMap::new();
copy_node(builder, node, annotate, &mut ids)
}
fn copy_node<'t, L: Lang, AOld, B>(
builder: &mut NodeTreeBuilder<L, B>,
node: NodeRef<'t, L, AOld>,
annotate: &mut impl FnMut(NodeRef<'t, L, AOld>) -> B,
ids: &mut HashMap<NodeId, BuildId>,
) -> Result<BuildId, NodeBuildError> {
let mut replacements = Vec::with_capacity(node.child_count());
for child in node.children() {
replacements.push(alloc::vec![copy_node(builder, child, annotate, ids)?]);
}
let annotation = annotate(node);
let id = builder.restage_node(node, &replacements, |old| ids.get(&old).copied(), annotation)?;
ids.insert(node.id(), id);
Ok(id)
}
impl<'b, L: Lang> StagedNodes<'b, L> {
pub fn copy_subtree_into<B>(
&self,
id: BuildId,
builder: &mut NodeTreeBuilder<L, B>,
annotate: &mut impl FnMut(StagedNodeView<'b, L>) -> B,
) -> Result<BuildId, NodeBuildError> {
let mut ids: HashMap<BuildId, BuildId> = HashMap::new();
self.copy_staged_node(id, builder, annotate, &mut ids)
}
fn copy_staged_node<B>(
&self,
id: BuildId,
builder: &mut NodeTreeBuilder<L, B>,
annotate: &mut impl FnMut(StagedNodeView<'b, L>) -> B,
ids: &mut HashMap<BuildId, BuildId>,
) -> Result<BuildId, NodeBuildError> {
let node = self.get(id).ok_or(NodeBuildError::ChildNotStaged { child: id })?;
let mut replacements = Vec::with_capacity(node.children().len());
for child in node.children() {
replacements
.push(alloc::vec![self.copy_staged_node(*child, builder, annotate, ids)?]);
}
let annotation = annotate(node);
let new =
builder.restage_staged_node(node, &replacements, |old| ids.get(&old).copied(), annotation)?;
ids.insert(id, new);
Ok(new)
}
}