use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use core::fmt;
use crate::source::{Source, SourceSpan};
use crate::spec::CallableSpec;
use crate::state::{Lang, ParsingState};
use alloc::vec::Vec;
use super::arguments::{BodySlotExt, ChildRegion, ParsedArguments, ParsedSlots};
use super::kind::{CallableData, CommentData, GroupData, NodeKind};
use super::slice::NodeSlice;
use super::tree::{NodeData, NodeId, NodeTree, NO_PARENT};
use super::{NodeExt, SlotExt};
pub struct NodeRef<'t, L: Lang, A = ()> {
tree: &'t NodeTree<L, A>,
id: NodeId,
}
impl<'t, L: Lang, A> NodeRef<'t, L, A> {
pub(crate) fn new(tree: &'t NodeTree<L, A>, id: NodeId) -> NodeRef<'t, L, A> {
debug_assert_eq!(
id.tree_tag(),
tree.tree_tag(),
"NodeId used with a tree that did not mint it \
(ids are only meaningful for their own tree)"
);
NodeRef { tree, id }
}
fn data(&self) -> &'t NodeData<L> {
&self.tree.nodes()[self.id.index()]
}
pub fn tree(&self) -> &'t NodeTree<L, A> {
self.tree
}
pub fn parent(&self) -> Option<NodeRef<'t, L, A>> {
let parent = self.tree.parent_table()[self.id.index()];
(parent != NO_PARENT).then(|| NodeRef::new(self.tree, self.tree.make_id(parent)))
}
pub fn index_in_parent(&self) -> Option<usize> {
let parent = self.parent()?;
Some(self.id.index() - parent.data().children.start as usize)
}
pub fn annotation(&self) -> &'t A {
&self.tree.annotations[self.id.index()]
}
pub fn id(&self) -> NodeId {
self.id
}
pub fn kind(&self) -> &'t NodeKind<L> {
&self.data().kind
}
pub fn ext(&self) -> &'t NodeExt<L> {
&self.data().ext
}
pub fn span(&self) -> &'t SourceSpan<L::SourceOrigin> {
&self.data().span
}
pub fn span_content(&self) -> &'t str {
self.data().span.content()
}
pub fn parsing_state(&self) -> &'t Arc<ParsingState<L>> {
&self.data().parsing_state
}
pub fn summary(&self) -> String {
if let Some(text) = self.chars() {
format!("chars({text})")
} else if self.is_group() {
let class = self
.group_type()
.map_or_else(|| "?".to_string(), |group_type| format!("{group_type:?}"));
let (open, close) = self.group_delimiters().unwrap_or(("", ""));
format!("group({class} {open} {close})")
} else if let Some(data) = self.callable() {
format!("{:?}({})", data.callable_type, data.name)
} else if let Some(data) = self.comment() {
format!("comment({})", data.content.resolve(self.source()))
} else {
format!("list({})", self.child_count())
}
}
pub(crate) fn source(&self) -> &'t Source<L::SourceOrigin> {
self.data().span.source()
}
pub fn child_count(&self) -> usize {
self.data().children.len()
}
pub fn child(&self, i: usize) -> Option<NodeRef<'t, L, A>> {
let children = &self.data().children;
let id = children.start.checked_add(u32::try_from(i).ok()?)?;
(id < children.end).then(|| NodeRef::new(self.tree, self.tree.make_id(id)))
}
pub fn children(&self) -> NodeSlice<'t, L, A> {
NodeSlice::new(self.tree, self.data().children.clone())
}
pub fn descendants(&self) -> Descendants<'t, L, A> {
let mut stack = Vec::new();
push_children_reversed(&mut stack, self.data());
Descendants { tree: self.tree, stack }
}
pub fn is_chars(&self) -> bool {
matches!(self.kind(), NodeKind::Chars { .. })
}
pub fn is_group(&self) -> bool {
matches!(self.kind(), NodeKind::Group { .. })
}
pub fn is_callable(&self) -> bool {
matches!(self.kind(), NodeKind::Callable(_))
}
pub fn is_comment(&self) -> bool {
matches!(self.kind(), NodeKind::Comment { .. })
}
pub fn is_list(&self) -> bool {
matches!(self.kind(), NodeKind::List)
}
pub fn chars(&self) -> Option<&'t str> {
match self.kind() {
NodeKind::Chars { content, .. } => Some(content.resolve(self.source())),
_ => None,
}
}
pub fn comment(&self) -> Option<&'t CommentData> {
match self.kind() {
NodeKind::Comment(data) => Some(data),
_ => None,
}
}
pub fn group(&self) -> Option<&'t GroupData<L>> {
match self.kind() {
NodeKind::Group(data) => Some(data),
_ => None,
}
}
pub fn group_type(&self) -> Option<L::GroupTypeId> {
self.group().and_then(|data| data.group_type)
}
pub fn group_delimiters(&self) -> Option<(&'t str, &'t str)> {
self.group().map(|data| {
(data.open.resolve(self.source()), data.close.resolve(self.source()))
})
}
pub fn callable(&self) -> Option<&'t CallableData<L>> {
match self.kind() {
NodeKind::Callable(data) => Some(data),
_ => None,
}
}
pub fn callable_type(&self) -> Option<L::CallableTypeId> {
self.callable().map(|data| data.callable_type)
}
pub fn name(&self) -> Option<&'t str> {
self.callable().map(|data| &*data.name)
}
pub fn spec(&self) -> Option<&'t Arc<dyn CallableSpec<L>>> {
self.callable().map(|data| &data.spec)
}
pub fn invocation_syntax(&self) -> Option<&'t L::InvocationSyntax> {
self.callable().map(|data| &data.invocation_syntax)
}
pub fn arguments(&self) -> Option<&'t ParsedArguments<L>> {
self.callable().map(|data| &data.arguments)
}
pub fn slots(&self) -> Option<&'t ParsedSlots<L>> {
self.callable().map(|data| &data.slots)
}
pub fn argument_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
self.region_nodes(self.callable()?.arguments.get(i)?.region.as_ref()?)
}
pub fn argument_nodes_named(
&self,
name: &str,
) -> Result<Option<NodeSlice<'t, L, A>>, NamedAccessError> {
let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
let argument = callable.arguments.get_named(name).ok_or_else(|| {
NamedAccessError::UnknownArgumentName { name: name.into() }
})?;
Ok(argument.region.as_ref().and_then(|region| self.region_nodes(region)))
}
pub fn argument_content_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
self.region_content(self.callable()?.arguments.get(i)?.region.as_ref()?)
}
pub fn argument_content_nodes_named(
&self,
name: &str,
) -> Result<Option<NodeSlice<'t, L, A>>, NamedAccessError> {
let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
let argument = callable.arguments.get_named(name).ok_or_else(|| {
NamedAccessError::UnknownArgumentName { name: name.into() }
})?;
Ok(argument.region.as_ref().and_then(|region| self.region_content(region)))
}
fn region_nodes(&self, region: &ChildRegion) -> Option<NodeSlice<'t, L, A>> {
Some(NodeSlice::new(self.tree, region.children()))
}
fn region_content(&self, region: &ChildRegion) -> Option<NodeSlice<'t, L, A>> {
Some(NodeSlice::new(self.tree, region.content_range()))
}
pub fn slot_content_parent(&self, i: usize) -> Option<NodeRef<'t, L, A>> {
let region = &self.callable()?.slots.get(i)?.region;
let parent = region.content_parent();
(parent != self.id).then(|| NodeRef::new(self.tree, parent))
}
pub fn slot_content_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
self.region_content(&self.callable()?.slots.get(i)?.region)
}
pub fn slot_content_nodes_named(
&self,
name: &str,
) -> Result<NodeSlice<'t, L, A>, NamedAccessError> {
let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
let slot = callable
.slots
.get_named(name)
.ok_or_else(|| NamedAccessError::UnknownSlotName { name: name.into() })?;
Ok(NodeSlice::new(self.tree, slot.region.content_range()))
}
pub fn body(&self) -> Option<NodeSlice<'t, L, A>>
where
SlotExt<L>: BodySlotExt,
{
let slot = self.callable()?.slots.iter().find(|slot| slot.ext.is_body())?;
self.region_content(&slot.region)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NamedAccessError {
NotACallable,
UnknownArgumentName {
name: Box<str>,
},
UnknownSlotName {
name: Box<str>,
},
}
impl fmt::Display for NamedAccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NamedAccessError::NotACallable => {
write!(f, "the node is not a callable (no arguments or slots)")
}
NamedAccessError::UnknownArgumentName { name } => {
write!(f, "no argument named ‘{name}’ among the declared arguments")
}
NamedAccessError::UnknownSlotName { name } => {
write!(f, "no slot named ‘{name}’ on the callable")
}
}
}
}
impl core::error::Error for NamedAccessError {}
pub struct Descendants<'t, L: Lang, A = ()> {
tree: &'t NodeTree<L, A>,
stack: Vec<u32>,
}
fn push_children_reversed<L: Lang>(stack: &mut Vec<u32>, data: &NodeData<L>) {
for i in data.children.clone().rev() {
stack.push(i);
}
}
impl<'t, L: Lang, A> Iterator for Descendants<'t, L, A> {
type Item = NodeRef<'t, L, A>;
fn next(&mut self) -> Option<NodeRef<'t, L, A>> {
let index = self.stack.pop()?;
let node = self.tree.node(self.tree.make_id(index));
push_children_reversed(&mut self.stack, &self.tree.nodes()[index as usize]);
Some(node)
}
}
impl<L: Lang, A> fmt::Debug for Descendants<'_, L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Descendants").field("pending", &self.stack.len()).finish()
}
}
impl<L: Lang, A> Clone for NodeRef<'_, L, A> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang, A> Copy for NodeRef<'_, L, A> {}
impl<L: Lang, A> fmt::Debug for NodeRef<'_, L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodeRef")
.field("id", &self.id)
.field("kind", self.kind())
.field("span", self.span())
.field("children", &self.data().children)
.finish()
}
}