use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::{Any, TypeId};
use core::fmt::{self, Debug};
use hashbrown::HashMap;
use crate::node::{
validate_tree, ArgumentExt, BuildId, CallableData, ChildRegion, CommentData, ContentNodes,
GroupData, NodeBuildError, NodeExt, NodeKind, NodeTree, NodeTreeBuilder, ParsedArgument,
ParsedArguments, ParsedSlot, ParsedSlots, SlotExt, SlotRole,
};
use crate::source::TextContent;
use crate::spec::CallableSpec;
use crate::state::{InvocationSyntax, Lang};
use crate::token::GroupRule;
use super::super::engine::{
DeserializeContext, ObjectSerdeDriver, SerdeSession, SerializeContext, TableHandle, TableRegistry,
};
use super::super::error::{DeserializeError, RegistrationError, SerializeError};
use super::super::object::{DeserializableValue, SerializableLang, SerializableValue};
use super::super::value::{SerialEntry, SerialValue};
use super::super::wire::state::WireGroupRule;
use super::super::wire::tree::{
WireArgument, WireContent, WireNode, WireNodeKind, WireRange, WireRegion, WireSlot, WireTree,
};
use super::super::wire::{FromSerialValue, ToSerialValue};
use super::source::{deserialize_span, serialize_span};
use super::standard::{StandardTableInterning, StandardTableReading};
use super::{CORE_TREE_IDENTIFIER, TREES_TABLE};
crate::serial_index! {
pub struct TreeIndex;
}
pub struct TreeSerdeDriver<L: SerializableLang> {
lang: core::marker::PhantomData<fn() -> L>,
}
impl<L: SerializableLang> TreeSerdeDriver<L> {
pub fn new() -> TreeSerdeDriver<L> {
TreeSerdeDriver { lang: core::marker::PhantomData }
}
}
impl<L: SerializableLang> Default for TreeSerdeDriver<L> {
fn default() -> Self {
TreeSerdeDriver::new()
}
}
impl<L: SerializableLang> fmt::Debug for TreeSerdeDriver<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TreeSerdeDriver").finish()
}
}
impl<L: SerializableLang> ObjectSerdeDriver<L> for TreeSerdeDriver<L> {
type Object = dyn Any + Send + Sync;
type Index = TreeIndex;
fn table_name(&self) -> &'static str {
TREES_TABLE
}
fn homogeneous_identifier(&self) -> Option<&'static str> {
None
}
fn serialize_object(
&self,
object: &Arc<dyn Any + Send + Sync>,
cx: &mut SerializeContext<'_, L>,
) -> Result<SerialEntry, SerializeError> {
let type_id = (**object).type_id();
let codec = codec_by_type::<L>(cx, type_id)?;
let data = (codec.serialize)(object, cx)?;
Ok(SerialEntry { identifier: codec.identifier.clone(), data })
}
fn deserialize_object(
&self,
entry: &SerialEntry,
cx: &mut DeserializeContext<'_, L>,
) -> Result<Arc<dyn Any + Send + Sync>, DeserializeError> {
let codec = codec_by_identifier::<L>(cx, &entry.identifier)?;
(codec.deserialize)(&entry.data, cx)
}
}
struct TreeCodec<L: SerializableLang> {
identifier: Cow<'static, str>,
serialize: Arc<SerializeTreeFn<L>>,
deserialize: Arc<DeserializeTreeFn<L>>,
}
type SerializeTreeFn<L> = dyn Fn(&Arc<dyn Any + Send + Sync>, &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
+ Send
+ Sync;
type DeserializeTreeFn<L> = dyn Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<Arc<dyn Any + Send + Sync>, DeserializeError>
+ Send
+ Sync;
impl<L: SerializableLang> Clone for TreeCodec<L> {
fn clone(&self) -> Self {
TreeCodec {
identifier: self.identifier.clone(),
serialize: Arc::clone(&self.serialize),
deserialize: Arc::clone(&self.deserialize),
}
}
}
struct TreeRegistry<L: SerializableLang> {
by_type: HashMap<TypeId, TreeCodec<L>>,
by_identifier: HashMap<String, TreeCodec<L>>,
}
impl<L: SerializableLang> Default for TreeRegistry<L> {
fn default() -> Self {
let mut registry = TreeRegistry { by_type: HashMap::new(), by_identifier: HashMap::new() };
let unit = unit_tree_codec::<L>();
registry.by_type.insert(TypeId::of::<NodeTree<L, ()>>(), unit.clone());
registry.by_identifier.insert(unit.identifier.to_string(), unit);
registry
}
}
impl<L: SerializableLang> TableRegistry for TreeRegistry<L> {
fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync) {
self
}
fn forget_memo(&mut self, _identifier: &str) {
}
}
fn codec_by_type<L: SerializableLang>(
cx: &mut SerializeContext<'_, L>,
type_id: TypeId,
) -> Result<TreeCodec<L>, SerializeError> {
let ordinal = cx
.session_mut()
.table_ordinal_by_name(TREES_TABLE)
.ok_or_else(|| SerializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
let registry = cx
.session_mut()
.registry_mut::<TreeRegistry<L>>(ordinal)
.ok_or_else(|| {
SerializeError::failed(alloc::format!(
"Misconfigured table ‘{TREES_TABLE}’: the table is not registered with the tree driver"
))
})?;
registry.by_type.get(&type_id).cloned().ok_or_else(|| {
SerializeError::failed(alloc::format!(
"Unsupported object for table ‘{TREES_TABLE}’: the table accepts only node trees \
of an annotation type registered with ‘TableHandle::register_annotation’"
))
})
}
fn codec_by_identifier<L: SerializableLang>(
cx: &mut DeserializeContext<'_, L>,
identifier: &str,
) -> Result<TreeCodec<L>, DeserializeError> {
let ordinal = cx.session_mut().table_ordinal_by_name(TREES_TABLE).ok_or_else(|| {
DeserializeError::failed(alloc::format!(
"Missing table ‘{TREES_TABLE}’: no table of this name is registered in the \
session of the context"
))
})?;
let registry = cx
.session_mut()
.registry_mut::<TreeRegistry<L>>(ordinal)
.ok_or_else(|| {
DeserializeError::failed(alloc::format!(
"Misconfigured table ‘{TREES_TABLE}’: the table is not registered with the tree driver"
))
})?;
registry.by_identifier.get(identifier).cloned().ok_or_else(|| DeserializeError::UnknownIdentifier {
table: TREES_TABLE,
identifier: identifier.to_string(),
})
}
fn unit_tree_codec<L: SerializableLang>() -> TreeCodec<L> {
TreeCodec {
identifier: Cow::Borrowed(CORE_TREE_IDENTIFIER),
serialize: Arc::new(|object, cx| {
let tree = downcast_tree::<L, ()>(object)?;
let nodes = serialize_nodes(tree, cx)?;
Ok(WireTree { nodes, annotations: None }.to_serial_value()?)
}),
deserialize: Arc::new(|data, cx| {
let wire = WireTree::from_serial_value(data)?;
let annotations = alloc::vec![(); wire.nodes.len()];
let tree = rebuild_tree::<L, ()>(wire.nodes, annotations, cx)?;
Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
}),
}
}
fn value_tree_codec<L, A>(identifier: Cow<'static, str>) -> TreeCodec<L>
where
L: SerializableLang,
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
{
TreeCodec {
identifier,
serialize: Arc::new(|object, cx| {
let tree = downcast_tree::<L, A>(object)?;
let nodes = serialize_nodes(tree, cx)?;
let annotations = serialize_annotations(tree, |annotation, cx| annotation.serialize_value(cx), cx)?;
Ok(WireTree { nodes, annotations: Some(annotations) }.to_serial_value()?)
}),
deserialize: Arc::new(|data, cx| {
let wire = WireTree::from_serial_value(data)?;
let (nodes, annotations) = deserialize_annotations(
wire,
|value, cx| <A as DeserializableValue<L>>::deserialize_value(value, cx),
cx,
)?;
let tree = rebuild_tree::<L, A>(nodes, annotations, cx)?;
Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
}),
}
}
fn serialize_annotations<L: SerializableLang, A>(
tree: &NodeTree<L, A>,
serialize: impl Fn(&A, &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>,
cx: &mut SerializeContext<'_, L>,
) -> Result<Vec<SerialValue>, SerializeError> {
tree.annotations()
.iter()
.zip(tree.nodes())
.enumerate()
.map(|(index, (annotation, node))| {
serialize(annotation, cx).map_err(|error| error.in_node(index as u32, callable_name(&node.kind)))
})
.collect()
}
fn deserialize_annotations<L: SerializableLang, A>(
mut wire: WireTree,
deserialize: impl Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<A, DeserializeError>,
cx: &mut DeserializeContext<'_, L>,
) -> Result<(Vec<WireNode>, Vec<A>), DeserializeError> {
let node_count = wire.nodes.len();
let list = wire.annotations.take().ok_or_else(|| {
DeserializeError::failed(
"Missing annotations in a tree entry (only trees with the unit annotation type have no \
annotations)",
)
})?;
if list.len() != node_count {
return Err(DeserializeError::failed(alloc::format!(
"Wrong number of annotations in a tree entry ({} annotations for {node_count} nodes)",
list.len()
)));
}
let annotations = list
.iter()
.zip(&wire.nodes)
.enumerate()
.map(|(index, (value, node))| {
deserialize(value, cx).map_err(|error| error.in_node(index as u32, wire_callable_name(node)))
})
.collect::<Result<Vec<A>, _>>()?;
Ok((wire.nodes, annotations))
}
fn downcast_tree<L: SerializableLang, A: 'static>(
object: &Arc<dyn Any + Send + Sync>,
) -> Result<&NodeTree<L, A>, SerializeError> {
(**object)
.downcast_ref::<NodeTree<L, A>>()
.ok_or_else(|| {
SerializeError::failed(
"Annotation type mismatch: the tree codec was called on a tree of another \
annotation type",
)
})
}
impl<L: SerializableLang> TableHandle<TreeSerdeDriver<L>> {
pub fn register_annotation<A>(
self,
session: &mut SerdeSession<L>,
identifier: impl Into<Cow<'static, str>>,
) -> Result<(), RegistrationError>
where
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
{
register_codec::<L>(self, session, TypeId::of::<NodeTree<L, A>>(), value_tree_codec::<L, A>(identifier.into()))
}
#[cfg(feature = "serde")]
pub fn register_serde_annotation<A>(
self,
session: &mut SerdeSession<L>,
identifier: impl Into<Cow<'static, str>>,
) -> Result<(), RegistrationError>
where
A: serde::Serialize + serde::de::DeserializeOwned + Clone + Debug + Send + Sync + 'static,
{
register_codec::<L>(self, session, TypeId::of::<NodeTree<L, A>>(), serde_tree_codec::<L, A>(identifier.into()))
}
}
#[cfg(feature = "serde")]
fn serde_tree_codec<L, A>(identifier: Cow<'static, str>) -> TreeCodec<L>
where
L: SerializableLang,
A: serde::Serialize + serde::de::DeserializeOwned + Clone + Debug + Send + Sync + 'static,
{
TreeCodec {
identifier,
serialize: Arc::new(|object, cx| {
let tree = downcast_tree::<L, A>(object)?;
let nodes = serialize_nodes(tree, cx)?;
let annotations = serialize_annotations(
tree,
|annotation, _cx| super::super::bridge::to_value(annotation).map_err(SerializeError::from),
cx,
)?;
Ok(WireTree { nodes, annotations: Some(annotations) }.to_serial_value()?)
}),
deserialize: Arc::new(|data, cx| {
let wire = WireTree::from_serial_value(data)?;
let (nodes, annotations) = deserialize_annotations(
wire,
|value, _cx| super::super::bridge::from_value::<A>(value).map_err(DeserializeError::from),
cx,
)?;
let tree = rebuild_tree::<L, A>(nodes, annotations, cx)?;
Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
}),
}
}
fn register_codec<L: SerializableLang>(
handle: TableHandle<TreeSerdeDriver<L>>,
session: &mut SerdeSession<L>,
type_id: TypeId,
codec: TreeCodec<L>,
) -> Result<(), RegistrationError> {
let ordinal = session.table_index(handle).map_err(|table| RegistrationError::UnknownTable { table })?;
let table = session.table_name(ordinal);
let registry = session
.registry_mut::<TreeRegistry<L>>(ordinal)
.ok_or(RegistrationError::UnknownTable { table: handle.id() })?;
if registry.by_identifier.contains_key(&*codec.identifier) {
return Err(RegistrationError::DuplicateIdentifier { table, identifier: codec.identifier.to_string() });
}
if registry.by_type.contains_key(&type_id) {
return Err(RegistrationError::DuplicateAnnotationType { table });
}
registry.by_type.insert(type_id, codec.clone());
registry.by_identifier.insert(codec.identifier.to_string(), codec);
Ok(())
}
pub trait TreeSerialization<L: SerializableLang> {
fn serialize_tree<A>(&mut self, tree: &NodeTree<L, A>) -> Result<TreeIndex, SerializeError>
where
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static;
fn tree<A>(&mut self, position: TreeIndex) -> Result<NodeTree<L, A>, DeserializeError>
where
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static;
}
fn registered_identifier<L: SerializableLang>(session: &mut SerdeSession<L>, tree_type: TypeId) -> Option<String> {
let ordinal = session.table_ordinal_by_name(TREES_TABLE)?;
let registry = session.registry_mut::<TreeRegistry<L>>(ordinal)?;
registry.by_type.get(&tree_type).map(|codec| codec.identifier.to_string())
}
impl<L: SerializableLang> TreeSerialization<L> for SerdeSession<L> {
fn serialize_tree<A>(&mut self, tree: &NodeTree<L, A>) -> Result<TreeIndex, SerializeError>
where
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
{
let handle = self
.table_handle::<TreeSerdeDriver<L>>(TREES_TABLE)
.ok_or_else(|| SerializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
let object: Arc<dyn Any + Send + Sync> = Arc::new(tree.clone());
self.intern(handle, &object)
}
fn tree<A>(&mut self, position: TreeIndex) -> Result<NodeTree<L, A>, DeserializeError>
where
A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
{
let handle = self
.table_handle::<TreeSerdeDriver<L>>(TREES_TABLE)
.ok_or_else(|| DeserializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
let object = self.object(handle, position)?;
tree_of_object(self, object)
}
}
pub(crate) fn tree_of_object<L: SerializableLang, A: Clone + Send + Sync + 'static>(
session: &mut SerdeSession<L>,
object: Arc<dyn Any + Send + Sync>,
) -> Result<NodeTree<L, A>, DeserializeError> {
match object.downcast::<NodeTree<L, A>>() {
Ok(tree) => Ok((*tree).clone()),
Err(object) => {
let stored = registered_identifier(session, (*object).type_id());
let requested = core::any::type_name::<A>();
let requested_identifier = registered_identifier(session, TypeId::of::<NodeTree<L, A>>());
Err(DeserializeError::AnnotationTypeMismatch { stored, requested, requested_identifier })
}
}
}
fn serialize_nodes<L: SerializableLang, A>(
tree: &NodeTree<L, A>,
cx: &mut SerializeContext<'_, L>,
) -> Result<Vec<WireNode>, SerializeError> {
let nodes = tree.nodes();
nodes
.iter()
.enumerate()
.map(|(index, data)| {
serialize_node(index as u32, data, nodes, cx)
.map_err(|error| error.in_node(index as u32, callable_name(&data.kind)))
})
.collect()
}
fn callable_name<L: Lang>(kind: &NodeKind<L>) -> Option<String> {
match kind {
NodeKind::Callable(data) => Some(data.name.to_string()),
_ => None,
}
}
fn serialize_node<L: SerializableLang>(
index: u32,
data: &crate::node::NodeData<L>,
nodes: &[crate::node::NodeData<L>],
cx: &mut SerializeContext<'_, L>,
) -> Result<WireNode, SerializeError> {
let kind = serialize_kind(index, data, nodes, cx)?;
let span = serialize_span(&data.span, cx)?;
let state = cx.intern_state(&data.parsing_state)?;
let ext = data.ext.serialize_value(cx)?;
let children = WireRange { start: data.children.start, end: data.children.end };
Ok(WireNode { kind, span, state, ext, children })
}
fn serialize_kind<L: SerializableLang>(
index: u32,
data: &crate::node::NodeData<L>,
nodes: &[crate::node::NodeData<L>],
cx: &mut SerializeContext<'_, L>,
) -> Result<WireNodeKind, SerializeError> {
match &data.kind {
NodeKind::Chars { content } => Ok(WireNodeKind::Chars { content: content.clone() }),
NodeKind::Group(group) => Ok(WireNodeKind::Group {
group_type: group.group_type.serialize_value(cx)?,
open: group.open.clone(),
close: group.close.clone(),
}),
NodeKind::Comment(comment) => Ok(WireNodeKind::Comment {
start: comment.start.clone(),
content: comment.content.clone(),
post_space: comment.post_space.clone(),
}),
NodeKind::List => Ok(WireNodeKind::List),
NodeKind::Callable(callable) => {
let children_start = data.children.start;
let arguments = callable
.arguments
.iter()
.enumerate()
.map(|(arg_index, argument)| {
serialize_argument(arg_index, argument, &callable.spec, index, children_start, nodes, cx)
})
.collect::<Result<Vec<_>, _>>()?;
let slots = callable
.slots
.iter()
.map(|slot| serialize_slot(slot, index, children_start, nodes, cx))
.collect::<Result<Vec<_>, _>>()?;
let invocation_syntax = callable.invocation_syntax.materialized(data.span.source()).serialize_value(cx)?;
Ok(WireNodeKind::Callable {
callable_type: callable.callable_type.serialize_value(cx)?,
name: callable.name.to_string(),
spec: cx.intern_spec(&callable.spec)?,
arguments,
slots,
invocation_syntax,
})
}
}
}
fn serialize_argument<L: SerializableLang>(
arg_index: usize,
argument: &ParsedArgument<L>,
callable_spec: &Arc<dyn CallableSpec<L>>,
callable_index: u32,
children_start: u32,
nodes: &[crate::node::NodeData<L>],
cx: &mut SerializeContext<'_, L>,
) -> Result<WireArgument, SerializeError> {
let spec_payload = callable_spec.serialize_argument_spec(arg_index, &argument.spec, cx)?;
let region = argument.region.as_ref().map(|region| serialize_region(region, callable_index, children_start, nodes));
let ext = argument.ext.as_ref().map(|ext| ext.serialize_value(cx)).transpose()?;
Ok(WireArgument { region, ext, spec_payload })
}
fn serialize_slot<L: SerializableLang>(
slot: &ParsedSlot<L>,
callable_index: u32,
children_start: u32,
nodes: &[crate::node::NodeData<L>],
cx: &mut SerializeContext<'_, L>,
) -> Result<WireSlot, SerializeError> {
Ok(WireSlot {
name: slot.name().map(String::from),
region: serialize_region(&slot.region, callable_index, children_start, nodes),
role: slot.role,
ext: slot.ext.serialize_value(cx)?,
})
}
fn serialize_region<L: Lang>(
region: &ChildRegion,
callable_index: u32,
children_start: u32,
nodes: &[crate::node::NodeData<L>],
) -> WireRegion {
let region_children = region.children();
let region_start = region_children.start;
let children = WireRange { start: region_start - children_start, end: region_children.end - children_start };
let content_parent = region.content_parent().index() as u32;
let content_range = region.content_range();
let content = if content_parent == callable_index {
WireContent::InRegion { start: content_range.start - region_start, end: content_range.end - region_start }
} else {
let parent_start = nodes[content_parent as usize].children.start;
WireContent::InChildrenOf {
node: content_parent,
start: content_range.start - parent_start,
end: content_range.end - parent_start,
}
};
WireRegion { children, content }
}
fn rebuild_tree<L: SerializableLang, A>(
wire_nodes: Vec<WireNode>,
annotations: Vec<A>,
cx: &mut DeserializeContext<'_, L>,
) -> Result<NodeTree<L, A>, DeserializeError> {
let node_count = wire_nodes.len();
if node_count == 0 {
return Err(DeserializeError::failed("Missing root node: a node tree must have at least one node"));
}
if u32::try_from(node_count).is_err() {
return Err(DeserializeError::failed("Too many nodes in a node tree (at most u32::MAX nodes)"));
}
if annotations.len() != node_count {
return Err(DeserializeError::failed(alloc::format!(
"Wrong number of annotations in a tree entry ({} annotations for {node_count} nodes)",
annotations.len()
)));
}
let mut builder = NodeTreeBuilder::<L, A>::new();
let mut build_id_of: Vec<Option<BuildId>> = alloc::vec![None; node_count];
let mut claimed_by: Vec<Option<u32>> = alloc::vec![None; node_count];
for (index, annotation) in annotations.into_iter().enumerate().rev() {
let wire = &wire_nodes[index];
let build_id =
stage_node(index as u32, wire, &build_id_of, &mut claimed_by, &mut builder, annotation, cx)
.map_err(|error| error.in_node(index as u32, wire_callable_name(wire)))?;
build_id_of[index] = Some(build_id);
}
if let Some(unclaimed) = (1..node_count).find(|&index| claimed_by[index].is_none()) {
return Err(DeserializeError::failed(
"Unreachable node: no node lists this node among its children",
)
.in_node(unclaimed as u32, wire_callable_name(&wire_nodes[unclaimed])));
}
let root = build_id_of[0].expect("the root node was staged");
let tree = builder.finish(root).map_err(|error| builder_failure(error, &build_id_of))?;
validate_tree(&tree).map_err(|violation| {
DeserializeError::failed(violation.to_string()).with_cause(violation)
})?;
if tree.node_count() != node_count {
return Err(DeserializeError::Internal {
detail: alloc::format!(
"Wrong number of nodes in a rebuilt tree: {} nodes (expected {node_count})",
tree.node_count()
),
});
}
Ok(tree)
}
fn stage_node<L: SerializableLang, A>(
index: u32,
wire: &WireNode,
build_id_of: &[Option<BuildId>],
claimed_by: &mut [Option<u32>],
builder: &mut NodeTreeBuilder<L, A>,
annotation: A,
cx: &mut DeserializeContext<'_, L>,
) -> Result<BuildId, DeserializeError> {
let node_count = build_id_of.len();
let (child_start, child_end) = (wire.children.start, wire.children.end);
if child_start > child_end || child_end as usize > node_count {
return Err(DeserializeError::failed(alloc::format!(
"Invalid children range {child_start}..{child_end} ({node_count} nodes in the tree)"
)));
}
if child_start != child_end && child_start <= index {
return Err(DeserializeError::failed(alloc::format!(
"Invalid children range {child_start}..{child_end}: the children of a node must be \
stored after the node"
)));
}
let mut children = Vec::with_capacity((child_end - child_start) as usize);
for child in child_start..child_end {
if let Some(other) = claimed_by[child as usize] {
return Err(DeserializeError::failed(alloc::format!(
"Node #{child} has two parents (node #{other} and node #{index})"
)));
}
claimed_by[child as usize] = Some(index);
let build_id = build_id_of[child as usize].ok_or_else(|| DeserializeError::Internal {
detail: alloc::format!("Child node #{child} of node #{index} was not staged before its parent"),
})?;
children.push(build_id);
}
let kind = rebuild_kind(wire, build_id_of, cx)?;
let span = deserialize_span(wire.span, cx)?;
let state = cx.state(wire.state)?;
let ext = <NodeExt<L> as DeserializableValue<L>>::deserialize_value(&wire.ext, cx)?;
builder.add(kind, span, state, children, ext, annotation).map_err(|error| builder_failure(error, build_id_of))
}
fn wire_callable_name(wire: &WireNode) -> Option<String> {
match &wire.kind {
WireNodeKind::Callable { name, .. } => Some(name.clone()),
_ => None,
}
}
fn wire_position_of(build_id_of: &[Option<BuildId>], id: BuildId) -> Option<usize> {
build_id_of.iter().position(|staged| *staged == Some(id))
}
fn builder_failure(error: NodeBuildError, build_id_of: &[Option<BuildId>]) -> DeserializeError {
let node = |id: BuildId| match wire_position_of(build_id_of, id) {
Some(position) => alloc::format!("node #{position}"),
None => alloc::format!("node {}", id.number()),
};
let detail = match &error {
NodeBuildError::ChildNotStaged { child } => {
alloc::format!("Invalid child {}: the node was not staged before its parent", node(*child))
}
NodeBuildError::ChildAlreadyClaimed { child } => {
alloc::format!("Invalid child {}: the node is already the child of another node", node(*child))
}
NodeBuildError::ContentParentNotStaged { parent } => {
alloc::format!("Invalid content parent {}: the node was not staged before its callable", node(*parent))
}
NodeBuildError::RootNotStaged { root } => {
alloc::format!("Invalid root {}: the node was not staged", node(*root))
}
NodeBuildError::RootClaimed { root } => {
alloc::format!("Invalid root {}: the node is the child of another node", node(*root))
}
NodeBuildError::ContentParentUnreachable { parent } => {
alloc::format!("Invalid content parent {}: the node is not reachable from the root", node(*parent))
}
NodeBuildError::ContentParentOutsideSubtree { parent } => alloc::format!(
"Invalid content parent {}: the node is not inside the subtree of its callable",
node(*parent)
),
NodeBuildError::ContentParentOutsideRegion { parent } => alloc::format!(
"Invalid content parent {}: the node is not inside its argument or slot region",
node(*parent)
),
other => other.to_string(),
};
DeserializeError::failed(detail).with_cause(error)
}
fn rebuild_kind<L: SerializableLang>(
wire: &WireNode,
build_id_of: &[Option<BuildId>],
cx: &mut DeserializeContext<'_, L>,
) -> Result<NodeKind<L>, DeserializeError> {
match &wire.kind {
WireNodeKind::Chars { content } => Ok(NodeKind::Chars { content: content.clone() }),
WireNodeKind::Group { group_type, open, close } => {
let group_type = <Option<L::GroupTypeId> as DeserializableValue<L>>::deserialize_value(group_type, cx)?;
Ok(NodeKind::Group(Box::new(GroupData { group_type, open: open.clone(), close: close.clone() })))
}
WireNodeKind::Comment { start, content, post_space } => Ok(NodeKind::Comment(Box::new(CommentData {
start: start.clone(),
content: content.clone(),
post_space: post_space.clone(),
}))),
WireNodeKind::List => Ok(NodeKind::List),
WireNodeKind::Callable { callable_type, name, spec, arguments, slots, invocation_syntax } => {
let callable_type = <L::CallableTypeId as DeserializableValue<L>>::deserialize_value(callable_type, cx)?;
let spec = cx.spec(*spec)?;
let arguments = arguments
.iter()
.enumerate()
.map(|(arg_index, wire)| rebuild_argument(arg_index, wire, &spec, build_id_of, cx))
.collect::<Result<Vec<_>, _>>()?;
let slots = slots
.iter()
.map(|wire| rebuild_slot(wire, build_id_of, cx))
.collect::<Result<Vec<_>, _>>()?;
let invocation_syntax =
<L::InvocationSyntax as DeserializableValue<L>>::deserialize_value(invocation_syntax, cx)?;
Ok(NodeKind::Callable(Box::new(CallableData {
callable_type,
name: name.as_str().into(),
spec,
arguments: ParsedArguments::new(arguments),
slots: ParsedSlots::new(slots),
invocation_syntax,
})))
}
}
}
fn rebuild_argument<L: SerializableLang>(
arg_index: usize,
wire: &WireArgument,
callable_spec: &Arc<dyn CallableSpec<L>>,
build_id_of: &[Option<BuildId>],
cx: &mut DeserializeContext<'_, L>,
) -> Result<ParsedArgument<L>, DeserializeError> {
let spec = callable_spec.deserialize_argument_spec(arg_index, wire.spec_payload.as_ref(), cx)?;
match &wire.region {
Some(region) => {
let region = staged_region(region, build_id_of)?;
let null = SerialValue::Null;
let ext_value = wire.ext.as_ref().unwrap_or(&null);
let ext = <ArgumentExt<L> as DeserializableValue<L>>::deserialize_value(ext_value, cx)?;
Ok(ParsedArgument::provided(spec, region, ext))
}
None => {
if wire.ext.is_some() {
return Err(DeserializeError::failed(alloc::format!(
"Unexpected ext on absent argument #{} (an absent argument has no ext)",
arg_index.saturating_add(1)
)));
}
Ok(ParsedArgument::absent(spec))
}
}
}
fn rebuild_slot<L: SerializableLang>(
wire: &WireSlot,
build_id_of: &[Option<BuildId>],
cx: &mut DeserializeContext<'_, L>,
) -> Result<ParsedSlot<L>, DeserializeError> {
let region = staged_region(&wire.region, build_id_of)?;
let ext = <SlotExt<L> as DeserializableValue<L>>::deserialize_value(&wire.ext, cx)?;
match &wire.name {
Some(name) => Ok(ParsedSlot::new(region, name.as_str(), wire.role, ext)),
None => Ok(ParsedSlot::new_unnamed(region, wire.role, ext)),
}
}
fn staged_region(wire: &WireRegion, build_id_of: &[Option<BuildId>]) -> Result<ChildRegion, DeserializeError> {
let children = wire.children.start..wire.children.end;
let content = match wire.content {
WireContent::InRegion { start, end } => ContentNodes::InRegion(start..end),
WireContent::InChildrenOf { node: parent, start, end } => {
let build_id = match build_id_of.get(parent as usize) {
None => {
return Err(DeserializeError::failed(alloc::format!(
"Content parent node #{parent} of a region is out of range ({} nodes in the tree)",
build_id_of.len()
)))
}
Some(None) => {
return Err(DeserializeError::failed(alloc::format!(
"Invalid content parent node #{parent} of a region: the content parent must be a \
node inside the region, stored after its callable"
)))
}
Some(Some(build_id)) => *build_id,
};
ContentNodes::InChildrenOf(build_id, start..end)
}
};
Ok(ChildRegion::new(children, content))
}
impl<L: Lang> SerializableValue<L> for TextContent {
fn serialize_value(&self, _cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
where
L: SerializableLang,
{
match self {
TextContent::Owned(_) => Ok(self.to_serial_value()?),
TextContent::Spanned(span) => Err(SerializeError::failed(alloc::format!(
"Unsupported span-backed text ({span:?}) in a language payload: convert the text \
with ‘TextContent::materialized’ before serializing the payload"
))),
}
}
}
impl<L: Lang> DeserializableValue<L> for TextContent {
fn deserialize_value(value: &SerialValue, _cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
where
L: SerializableLang,
{
match TextContent::from_serial_value(value)? {
owned @ TextContent::Owned(_) => Ok(owned),
TextContent::Spanned(span) => Err(DeserializeError::failed(alloc::format!(
"Invalid span-backed text ({span:?}) in a language payload: text in a language \
payload must be owned text"
))),
}
}
}
impl<L: Lang> SerializableValue<L> for SlotRole {
fn serialize_value(&self, _cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
where
L: SerializableLang,
{
Ok(self.to_serial_value()?)
}
}
impl<L: Lang> DeserializableValue<L> for SlotRole {
fn deserialize_value(value: &SerialValue, _cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
where
L: SerializableLang,
{
Ok(SlotRole::from_serial_value(value)?)
}
}
impl<L: Lang> SerializableValue<L> for GroupRule<L> {
fn serialize_value(&self, cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
where
L: SerializableLang,
{
let wire = WireGroupRule {
group_type: self.group_type.serialize_value(cx)?,
open: self.open.clone(),
close: self.close.clone(),
};
Ok(wire.to_serial_value()?)
}
}
impl<L: Lang> DeserializableValue<L> for GroupRule<L> {
fn deserialize_value(value: &SerialValue, cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
where
L: SerializableLang,
{
let wire = WireGroupRule::from_serial_value(value)?;
Ok(GroupRule {
group_type: <L::GroupTypeId as DeserializableValue<L>>::deserialize_value(&wire.group_type, cx)?,
open: wire.open,
close: wire.close,
})
}
}