use core::marker::PhantomData;
use alloc::vec::Vec;
use hashbrown::HashMap;
use alloc::string::String;
use alloc::sync::Arc;
use crate::engine::{DescentGuard, StdDescentGuard, StdDescentGuardInit};
use crate::node::{
BuildId, CallableData, ChildRegion, ContentNodes, ContentParentMapping, NodeBuildError,
NodeId, NodeKind, NodeRef, NodeTree, NodeTreeBuilder, ParsedArgument, ParsedArguments,
ParsedSlot, ParsedSlots,
};
use crate::state::Lang;
use super::bundles::ProvidedRegion;
use super::{Restage, RestageError, RestageVisitor, RestagedArgument, RestagedSlot};
pub struct TreeRestager<'v, V: ?Sized> {
visitor: &'v mut V,
descent_guard_init: StdDescentGuardInit,
}
impl<'v, V: ?Sized> TreeRestager<'v, V> {
pub fn new(visitor: &'v mut V) -> TreeRestager<'v, V> {
TreeRestager { visitor, descent_guard_init: StdDescentGuardInit::default() }
}
pub fn with_descent_guard_init(mut self, init: StdDescentGuardInit) -> TreeRestager<'v, V> {
self.descent_guard_init = init;
self
}
pub fn restage<L, A, B>(
self,
tree: &NodeTree<L, A>,
) -> Result<NodeTree<L, B>, RestageError<V::Error>>
where
L: Lang,
V: RestageVisitor<L, A, B>,
{
let mut cx = RestageContext {
builder: NodeTreeBuilder::new(),
replaced: HashMap::new(),
descent_guard: StdDescentGuard::init(&self.descent_guard_init),
_input: PhantomData,
};
let ids = drive(&mut cx, tree.root(), self.visitor)?;
if ids.len() != 1 {
return Err(RestageError::RootNotSingular { count: ids.len() });
}
cx.builder.finish(ids[0]).map_err(RestageError::Build)
}
}
impl<V: ?Sized> core::fmt::Debug for TreeRestager<'_, V> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("TreeRestager")
.field("descent_guard_init", &self.descent_guard_init)
.finish_non_exhaustive()
}
}
pub(super) fn drive<L, A, B, V>(
cx: &mut RestageContext<'_, L, A, B>,
node: NodeRef<'_, L, A>,
visitor: &mut V,
) -> Result<Vec<BuildId>, RestageError<V::Error>>
where
L: Lang,
V: RestageVisitor<L, A, B> + ?Sized,
{
match cx.descent_guard.try_enter() {
Err(refusal) => {
return Err(RestageError::DescentLimitExceeded {
detail: refusal.detail,
limit: refusal.limit,
})
}
Ok(Some(warning)) => visitor.observe_descent_warning(warning),
Ok(None) => {}
}
let result = drive_entered(cx, node, visitor);
cx.descent_guard.exit();
result
}
fn drive_entered<L, A, B, V>(
cx: &mut RestageContext<'_, L, A, B>,
node: NodeRef<'_, L, A>,
visitor: &mut V,
) -> Result<Vec<BuildId>, RestageError<V::Error>>
where
L: Lang,
V: RestageVisitor<L, A, B> + ?Sized,
{
match visitor.restage(node, cx).map_err(RestageError::Visitor)? {
Restage::Emit(ids) => {
cx.record_emit(node.id(), &ids);
Ok(ids)
}
Restage::Descend(annotation) => {
let mut replacements = Vec::with_capacity(node.child_count());
for child in node.children() {
replacements.push(drive(cx, child, visitor)?);
}
let id = cx.restage_over(node, &replacements, annotation)?;
Ok(alloc::vec![id])
}
}
}
#[derive(Clone, Debug)]
enum Replaced {
Restaged { id: BuildId, prefix: Vec<u32> },
One(BuildId),
Count(usize),
}
fn dropped_replaced_by(record: Option<&Replaced>) -> Option<usize> {
match record {
Some(Replaced::Count(count)) => Some(*count),
_ => None,
}
}
pub struct RestageContext<'t, L: Lang, A, B> {
builder: NodeTreeBuilder<L, B>,
replaced: HashMap<NodeId, Replaced>,
descent_guard: StdDescentGuard,
_input: PhantomData<&'t NodeTree<L, A>>,
}
impl<'t, L: Lang, A, B> RestageContext<'t, L, A, B> {
pub fn builder(&mut self) -> &mut NodeTreeBuilder<L, B> {
&mut self.builder
}
pub fn restage_subtree<V>(
&mut self,
node: NodeRef<'_, L, A>,
visitor: &mut V,
) -> Result<Vec<BuildId>, RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
drive(self, node, visitor)
}
pub fn restage_children<V>(
&mut self,
node: NodeRef<'_, L, A>,
visitor: &mut V,
) -> Result<Vec<BuildId>, RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
let mut ids = Vec::new();
for child in node.children() {
ids.extend(drive(self, child, visitor)?);
}
Ok(ids)
}
pub fn restage_argument<V>(
&mut self,
node: NodeRef<'_, L, A>,
index: usize,
visitor: &mut V,
) -> Result<RestagedArgument<L>, RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
let data = callable_data(node)?;
let count = data.arguments.len();
let argument = data
.arguments
.get(index)
.ok_or(RestageError::ArgumentIndexOutOfRange { node: node.id(), index, count })?;
let spec = Arc::clone(&argument.spec);
match &argument.region {
None => Ok(RestagedArgument::absent(spec)),
Some(region) => {
let ext = argument.ext.clone();
let (nodes, content) = self.restage_region(node, region, visitor)?;
Ok(RestagedArgument {
spec,
provided: Some(ProvidedRegion { nodes, content, ext }),
})
}
}
}
pub fn restage_argument_named<V>(
&mut self,
node: NodeRef<'_, L, A>,
name: &str,
visitor: &mut V,
) -> Result<RestagedArgument<L>, RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
let data = callable_data(node)?;
let index = data
.arguments
.iter()
.position(|argument| argument.name() == Some(name))
.ok_or_else(|| RestageError::UnknownArgumentName {
node: node.id(),
name: String::from(name),
})?;
self.restage_argument(node, index, visitor)
}
pub fn restage_slot<V>(
&mut self,
node: NodeRef<'_, L, A>,
index: usize,
visitor: &mut V,
) -> Result<RestagedSlot<L>, RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
let data = callable_data(node)?;
let count = data.slots.len();
let slot = data
.slots
.get(index)
.ok_or(RestageError::SlotIndexOutOfRange { node: node.id(), index, count })?;
let (name, role, ext) = (slot.name.clone(), slot.role, slot.ext.clone());
let (nodes, content) = self.restage_region(node, &slot.region, visitor)?;
Ok(RestagedSlot { name, role, nodes, content, ext })
}
pub fn restage_invocation<E>(
&mut self,
node: NodeRef<'_, L, A>,
arguments: Vec<RestagedArgument<L>>,
slots: Vec<RestagedSlot<L>>,
annotation: B,
) -> Result<BuildId, RestageError<E>> {
let data = callable_data(node)?;
let mut children: Vec<BuildId> = Vec::new();
let mut offset = |added: &[BuildId]| -> Result<core::ops::Range<u32>, RestageError<E>> {
let start = u32::try_from(children.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
let end = start
.checked_add(
u32::try_from(added.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?,
)
.ok_or(RestageError::Build(NodeBuildError::TooManyNodes))?;
children.extend_from_slice(added);
Ok(start..end)
};
let mut parsed_arguments = Vec::with_capacity(arguments.len());
for bundle in arguments {
let RestagedArgument { spec, provided } = bundle;
let (region, ext) = match provided {
None => (None, None),
Some(ProvidedRegion { nodes, content, ext }) => {
let range = offset(&nodes)?;
(Some(ChildRegion::new(range, content)), ext)
}
};
parsed_arguments.push(ParsedArgument { spec, region, ext });
}
let mut parsed_slots = Vec::with_capacity(slots.len());
for bundle in slots {
let RestagedSlot { name, role, nodes, content, ext } = bundle;
let range = offset(&nodes)?;
parsed_slots.push(ParsedSlot {
name,
region: ChildRegion::new(range, content),
role,
ext,
});
}
let kind = NodeKind::callable(CallableData {
callable_type: data.callable_type,
name: data.name.clone(),
spec: Arc::clone(&data.spec),
arguments: ParsedArguments::new(parsed_arguments),
slots: ParsedSlots::new(parsed_slots),
invocation_syntax: data.invocation_syntax.clone(),
});
self.builder
.add(
kind,
node.span().clone(),
node.parsing_state().clone(),
children,
node.ext().clone(),
annotation,
)
.map_err(RestageError::Build)
}
pub fn restage_argument_with_content<E>(
&mut self,
node: NodeRef<'_, L, A>,
index: usize,
content: Vec<BuildId>,
annotation: B,
) -> Result<RestagedArgument<L>, RestageError<E>>
where
B: Clone,
{
let data = callable_data(node)?;
let count = data.arguments.len();
let argument = data
.arguments
.get(index)
.ok_or(RestageError::ArgumentIndexOutOfRange { node: node.id(), index, count })?;
let region = argument
.region
.as_ref()
.ok_or(RestageError::ArgumentAbsent { node: node.id(), index })?;
let spec = Arc::clone(&argument.spec);
let ext = argument.ext.clone();
let (nodes, content) =
self.copy_region_with_swapped_content(node, region, content, &annotation)?;
Ok(RestagedArgument { spec, provided: Some(ProvidedRegion { nodes, content, ext }) })
}
pub fn restage_slot_with_content<E>(
&mut self,
node: NodeRef<'_, L, A>,
index: usize,
content: Vec<BuildId>,
annotation: B,
) -> Result<RestagedSlot<L>, RestageError<E>>
where
B: Clone,
{
let data = callable_data(node)?;
let count = data.slots.len();
let slot = data
.slots
.get(index)
.ok_or(RestageError::SlotIndexOutOfRange { node: node.id(), index, count })?;
let (name, role, ext) = (slot.name.clone(), slot.role, slot.ext.clone());
let (nodes, content) =
self.copy_region_with_swapped_content(node, &slot.region, content, &annotation)?;
Ok(RestagedSlot { name, role, nodes, content, ext })
}
fn copy_region_with_swapped_content<E>(
&mut self,
callable: NodeRef<'_, L, A>,
region: &ChildRegion,
new_content: Vec<BuildId>,
annotation: &B,
) -> Result<(Vec<BuildId>, ContentNodes), RestageError<E>>
where
B: Clone,
{
let children = region.children();
let content = region.content_range();
let parent = region.content_parent();
let tree = callable.tree();
if parent == callable.id() {
let cstart = (content.start - children.start) as usize;
let cend = (content.end - children.start) as usize;
let mut nodes: Vec<BuildId> = Vec::new();
let mut new_range = 0u32..0u32;
let splice =
|nodes: &mut Vec<BuildId>| -> Result<core::ops::Range<u32>, RestageError<E>> {
let start = u32::try_from(nodes.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
nodes.extend_from_slice(&new_content);
let end = u32::try_from(nodes.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
Ok(start..end)
};
for (i, region_node) in tree.nodes_in(children.clone()).enumerate() {
if i == cstart {
new_range = splice(&mut nodes)?;
}
if (cstart..cend).contains(&i) {
continue; }
nodes.push(self.copy_verbatim(region_node, annotation)?);
}
if cstart == children.len() {
new_range = splice(&mut nodes)?;
}
Ok((nodes, ContentNodes::InRegion(new_range)))
} else {
let mut path: Vec<NodeId> = alloc::vec![parent];
let mut cursor = tree.node(parent);
loop {
let up = cursor
.parent()
.expect("resolved content parents lie inside their region's subtree");
if up.id() == callable.id() {
break;
}
path.push(up.id());
cursor = up;
}
let anchor = *path.last().expect("path holds at least the parent");
let parent_node = tree.node(parent);
let parent_base = parent_node.children().range().start;
let rel = (content.start - parent_base) as usize..(content.end - parent_base) as usize;
let mut nodes: Vec<BuildId> = Vec::new();
let mut swapped: Option<(BuildId, core::ops::Range<u32>)> = None;
for region_node in tree.nodes_in(children.clone()) {
if region_node.id() == anchor {
let id = self.copy_swapping_at(
region_node,
&path,
rel.clone(),
&new_content,
annotation,
&mut swapped,
)?;
nodes.push(id);
} else {
nodes.push(self.copy_verbatim(region_node, annotation)?);
}
}
let (new_parent, new_range) =
swapped.expect("the path's anchor lies among the region's nodes");
Ok((nodes, ContentNodes::InChildrenOf(new_parent, new_range)))
}
}
fn copy_swapping_at<E>(
&mut self,
node: NodeRef<'_, L, A>,
path: &[NodeId],
rel: core::ops::Range<usize>,
new_content: &[BuildId],
annotation: &B,
swapped: &mut Option<(BuildId, core::ops::Range<u32>)>,
) -> Result<BuildId, RestageError<E>>
where
B: Clone,
{
let at_target = node.id() == path[0];
let mut children: Vec<BuildId> = Vec::new();
let mut new_range = 0u32..0u32;
let splice =
|children: &mut Vec<BuildId>| -> Result<core::ops::Range<u32>, RestageError<E>> {
let start = u32::try_from(children.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
children.extend_from_slice(new_content);
let end = u32::try_from(children.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
Ok(start..end)
};
for (i, child) in node.children().iter().enumerate() {
if at_target {
if i == rel.start {
new_range = splice(&mut children)?;
}
if rel.contains(&i) {
continue; }
children.push(self.copy_verbatim(child, annotation)?);
} else if path[..path.len() - 1].last() == Some(&child.id()) {
let id = self.copy_swapping_at(
child,
&path[..path.len() - 1],
rel.clone(),
new_content,
annotation,
swapped,
)?;
children.push(id);
} else {
children.push(self.copy_verbatim(child, annotation)?);
}
}
if at_target && rel.start == node.child_count() {
new_range = splice(&mut children)?;
}
let id = self
.builder
.add(
node.kind().clone(),
node.span().clone(),
node.parsing_state().clone(),
children,
node.ext().clone(),
annotation.clone(),
)
.map_err(RestageError::Build)?;
if at_target {
*swapped = Some((id, new_range));
}
Ok(id)
}
fn copy_verbatim<E>(
&mut self,
node: NodeRef<'_, L, A>,
annotation: &B,
) -> Result<BuildId, RestageError<E>>
where
B: Clone,
{
crate::node::copy_subtree_into(&mut self.builder, node, &mut |_| annotation.clone())
.map_err(RestageError::Build)
}
fn restage_region<V>(
&mut self,
callable: NodeRef<'_, L, A>,
region: &ChildRegion,
visitor: &mut V,
) -> Result<(Vec<BuildId>, ContentNodes), RestageError<V::Error>>
where
V: RestageVisitor<L, A, B> + ?Sized,
{
let children = region.children();
let content = region.content_range();
let parent = region.content_parent();
let mut nodes: Vec<BuildId> = Vec::new();
let mut prefix: Vec<u32> = Vec::with_capacity(children.len() + 1);
prefix.push(0);
for region_node in callable.tree().nodes_in(children.clone()) {
nodes.extend(drive(self, region_node, visitor)?);
let offset = u32::try_from(nodes.len())
.map_err(|_| RestageError::Build(NodeBuildError::TooManyNodes))?;
prefix.push(offset);
}
let designation = if parent == callable.id() {
let start = (content.start - children.start) as usize;
let end = (content.end - children.start) as usize;
ContentNodes::InRegion(prefix[start]..prefix[end])
} else {
let parent_node = callable.tree().node(parent);
let parent_base = parent_node.children().range().start;
let child_range =
(content.start - parent_base) as usize..(content.end - parent_base) as usize;
match self.replaced.get(&parent) {
Some(Replaced::Restaged { id, prefix }) => ContentNodes::InChildrenOf(
*id,
prefix[child_range.start]..prefix[child_range.end],
),
Some(Replaced::One(id)) => ContentNodes::InChildrenOf(
*id,
child_range.start as u32..child_range.end as u32,
),
other => {
return Err(RestageError::ContentParentDropped {
callable: callable.id(),
parent,
replaced_by: dropped_replaced_by(other),
})
}
}
};
Ok((nodes, designation))
}
pub(super) fn record_emit(&mut self, old: NodeId, ids: &[BuildId]) {
let entry = match ids {
[one] => Replaced::One(*one),
_ => Replaced::Count(ids.len()),
};
self.replaced.insert(old, entry);
}
pub(super) fn restage_over<AOld, E>(
&mut self,
node: NodeRef<'_, L, AOld>,
replacements: &[Vec<BuildId>],
annotation: B,
) -> Result<BuildId, RestageError<E>> {
let replaced = &self.replaced;
let result = self
.builder
.restage_node_with_content_mapping(
node,
replacements,
|old| match replaced.get(&old) {
Some(Replaced::Restaged { id, prefix }) => {
Some(ContentParentMapping::Translate(*id, prefix))
}
Some(Replaced::One(id)) => Some(ContentParentMapping::Verbatim(*id)),
_ => None,
},
annotation,
)
.map_err(|error| match error {
NodeBuildError::ContentParentUnmapped { parent } => {
RestageError::ContentParentDropped {
callable: node.id(),
parent,
replaced_by: dropped_replaced_by(replaced.get(&parent)),
}
}
other => RestageError::Build(other),
})?;
let mut prefix: Vec<u32> = Vec::with_capacity(replacements.len() + 1);
let mut total: u32 = 0;
prefix.push(0);
for entry in replacements {
total += entry.len() as u32;
prefix.push(total);
}
self.replaced.insert(node.id(), Replaced::Restaged { id: result, prefix });
Ok(result)
}
}
fn callable_data<'n, L: Lang, A, E>(
node: NodeRef<'n, L, A>,
) -> Result<&'n CallableData<L>, RestageError<E>> {
node.callable().ok_or(RestageError::NotACallable { node: node.id() })
}
impl<L: Lang, A, B> core::fmt::Debug for RestageContext<'_, L, A, B> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RestageContext")
.field("builder", &self.builder)
.field("replaced", &self.replaced.len())
.finish()
}
}