use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Range;
use crate::source::{Source, SourcePos, SourceSpan};
use crate::state::{Lang, ParsingState};
use super::kind::NodeKind;
use super::node_ref::NodeRef;
use super::slice::NodeSlice;
use super::NodeExt;
static NEXT_TREE_TAG: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
pub(crate) fn next_tree_tag() -> TreeTag {
TreeTag(NEXT_TREE_TAG.fetch_add(1, core::sync::atomic::Ordering::Relaxed))
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TreeTag(u32);
impl fmt::Debug for TreeTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TreeTag({})", self.0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId {
pub(crate) index: u32,
pub(crate) tree_tag: TreeTag,
}
impl NodeId {
pub(crate) fn new(index: u32, tree_tag: TreeTag) -> NodeId {
NodeId { index, tree_tag }
}
pub const fn index(&self) -> usize {
self.index as usize
}
pub const fn tree_tag(&self) -> TreeTag {
self.tree_tag
}
}
impl fmt::Debug for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "NodeId({}@{})", self.index, self.tree_tag.0)
}
}
pub struct NodeData<L: Lang> {
pub(crate) kind: NodeKind<L>,
pub(crate) ext: NodeExt<L>,
pub(crate) span: SourceSpan<L::SourceOrigin>,
pub(crate) parsing_state: Arc<ParsingState<L>>,
pub(crate) children: Range<u32>,
}
pub(crate) struct TreeCore<L: Lang> {
pub(crate) nodes: Vec<NodeData<L>>,
pub(crate) parent: Vec<u32>,
pub(crate) tree_tag: TreeTag,
pub(crate) single_source: bool,
}
pub(crate) const NO_PARENT: u32 = u32::MAX;
pub struct NodeTree<L: Lang, A = ()> {
pub(crate) core: Arc<TreeCore<L>>,
pub(crate) annotations: Vec<A>,
}
impl<L: Lang, A> NodeTree<L, A> {
#[inline]
pub(crate) fn nodes(&self) -> &[NodeData<L>] {
&self.core.nodes
}
#[inline]
pub(crate) fn parent_table(&self) -> &[u32] {
&self.core.parent
}
#[inline]
pub(crate) fn is_single_source(&self) -> bool {
self.core.single_source
}
pub fn root(&self) -> NodeRef<'_, L, A> {
self.node(self.make_id(0))
}
pub fn node(&self, id: NodeId) -> NodeRef<'_, L, A> {
assert!(
id.tree_tag == self.core.tree_tag,
"node id {:?} used with a tree it does not belong to (this tree is {:?})",
id,
self.core.tree_tag
);
assert!(id.index() < self.core.nodes.len(), "node id {:?} out of range", id);
NodeRef::new(self, id)
}
pub fn get(&self, id: NodeId) -> Option<NodeRef<'_, L, A>> {
if id.index() >= self.core.nodes.len() || id.tree_tag != self.core.tree_tag {
return None;
}
Some(NodeRef::new(self, id))
}
pub fn tree_tag(&self) -> TreeTag {
self.core.tree_tag
}
pub(crate) fn make_id(&self, index: u32) -> NodeId {
NodeId::new(index, self.core.tree_tag)
}
pub fn descendants(&self) -> super::Descendants<'_, L, A> {
self.root().descendants()
}
pub fn node_count(&self) -> usize {
self.core.nodes.len()
}
pub fn iter_storage_order(&self) -> impl Iterator<Item = NodeRef<'_, L, A>> {
(0..self.core.nodes.len() as u32).map(move |i| NodeRef::new(self, self.make_id(i)))
}
pub fn nodes_in(&self, range: Range<u32>) -> impl Iterator<Item = NodeRef<'_, L, A>> {
assert!(
range.start <= range.end && range.end as usize <= self.core.nodes.len(),
"node range {:?} out of range",
range
);
range.map(move |i| NodeRef::new(self, self.make_id(i)))
}
pub fn annotations(&self) -> &[A] {
&self.annotations
}
pub fn annotate<B>(&self, mut f: impl FnMut(NodeRef<'_, L, A>) -> B) -> NodeTree<L, B> {
let annotations =
(0..self.core.nodes.len() as u32).map(|i| f(self.node(self.make_id(i)))).collect();
NodeTree { core: Arc::clone(&self.core), annotations }
}
pub fn node_at(&self, pos: &SourcePos<L::SourceOrigin>) -> Option<NodeRef<'_, L, A>> {
deepest_containing(self.root(), pos.source(), &|span: &SourceSpan<
L::SourceOrigin,
>| span.span().contains(pos.pos()))
}
pub fn covering_slice(
&self,
span: &SourceSpan<L::SourceOrigin>,
) -> Option<NodeSlice<'_, L, A>> {
let node = deepest_containing(self.root(), span.source(), &|node_span: &SourceSpan<
L::SourceOrigin,
>| {
if span.is_empty() {
node_span.span().contains(span.start())
} else {
node_span.start() <= span.start() && span.end() <= node_span.end()
}
})?;
if let Some(run) = covering_child_run(node, span) {
return Some(NodeSlice::new(self, run));
}
let index = node.id().index() as u32;
Some(NodeSlice::new(self, index..index + 1))
}
pub fn slice(&self, range: Range<u32>) -> Option<NodeSlice<'_, L, A>> {
let node_count = self.core.nodes.len() as u32;
if range.start > range.end || range.end > node_count {
return None;
}
if range.is_empty() {
return Some(NodeSlice::new(self, range));
}
if range.start == 0 {
return (range.end == 1).then(|| NodeSlice::new(self, range));
}
let parent = self.core.parent[range.start as usize];
debug_assert_ne!(parent, NO_PARENT, "non-root node without a parent");
let children = &self.core.nodes[parent as usize].children;
(range.end <= children.end).then(|| NodeSlice::new(self, range))
}
pub fn materialize(&self) -> NodeTree<L, A>
where
A: Clone,
{
let nodes = self
.core
.nodes
.iter()
.map(|data| {
NodeData {
kind: data.kind.materialized(data.span.source()),
ext: data.ext.clone(),
span: data.span.clone(),
parsing_state: Arc::clone(&data.parsing_state),
children: data.children.clone(),
}
})
.collect();
NodeTree {
core: Arc::new(TreeCore {
nodes,
parent: self.core.parent.clone(),
tree_tag: self.core.tree_tag,
single_source: self.core.single_source,
}),
annotations: self.annotations.clone(),
}
}
}
fn deepest_containing<'t, L: Lang, A>(
node: NodeRef<'t, L, A>,
source: &Arc<Source<L::SourceOrigin>>,
contains: &impl Fn(&SourceSpan<L::SourceOrigin>) -> bool,
) -> Option<NodeRef<'t, L, A>> {
if Arc::ptr_eq(node.span().source(), source) {
if !contains(node.span()) {
return None;
}
for child in node.children() {
if Arc::ptr_eq(child.span().source(), source) {
if let Some(deeper) = deepest_containing(child, source, contains) {
return Some(deeper);
}
}
}
Some(node)
} else {
for child in node.children() {
if let Some(found) = deepest_containing(child, source, contains) {
return Some(found);
}
}
None
}
}
fn covering_child_run<L: Lang, A>(
node: NodeRef<'_, L, A>,
query: &SourceSpan<L::SourceOrigin>,
) -> Option<Range<u32>> {
if query.is_empty() || node.child_count() == 0 {
return None;
}
let tree = node.tree();
let block = node.children().range();
if let Some(run) = binary_candidate_run(tree, &block, query) {
if verify_covering_run(tree, &block, &run, query) {
return Some(run);
}
}
let overlaps = |i: u32| {
let span = &tree.nodes()[i as usize].span;
Arc::ptr_eq(span.source(), query.source())
&& span.start() < query.end()
&& span.end() > query.start()
};
let first = block.clone().find(|&i| overlaps(i))?;
let last = block.clone().rev().find(|&i| overlaps(i))?;
let run = first..last + 1;
verify_covering_run(tree, &block, &run, query).then_some(run)
}
fn binary_candidate_run<L: Lang, A>(
tree: &NodeTree<L, A>,
block: &Range<u32>,
query: &SourceSpan<L::SourceOrigin>,
) -> Option<Range<u32>> {
let len = (block.end - block.start) as usize;
let span_at = |k: usize| &tree.nodes()[block.start as usize + k].span;
let first = partition_point(len, |k| span_at(k).end() <= query.start());
let one_past_last = partition_point(len, |k| span_at(k).start() < query.end());
(first < one_past_last)
.then(|| block.start + first as u32..block.start + one_past_last as u32)
}
fn partition_point(len: usize, pred: impl Fn(usize) -> bool) -> usize {
let (mut lo, mut hi) = (0, len);
while lo < hi {
let mid = lo + (hi - lo) / 2;
if pred(mid) {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
fn verify_covering_run<L: Lang, A>(
tree: &NodeTree<L, A>,
block: &Range<u32>,
run: &Range<u32>,
query: &SourceSpan<L::SourceOrigin>,
) -> bool {
if run.start < block.start || run.end > block.end || run.start >= run.end {
return false;
}
let span_at = |i: u32| &tree.nodes()[i as usize].span;
let same_source = |i: u32| Arc::ptr_eq(span_at(i).source(), query.source());
let overlaps = |i: u32| {
same_source(i) && span_at(i).start() < query.end() && span_at(i).end() > query.start()
};
if !run.clone().all(same_source) {
return false;
}
if !overlaps(run.start) || !overlaps(run.end - 1) {
return false;
}
if span_at(run.start).start() > query.start() || span_at(run.end - 1).end() < query.end() {
return false;
}
if !(run.start..run.end - 1).all(|i| span_at(i).end() == span_at(i + 1).start()) {
return false;
}
if run.start > block.start && overlaps(run.start - 1) {
return false;
}
if run.end < block.end && overlaps(run.end) {
return false;
}
true
}
impl<L: Lang> Clone for NodeData<L> {
fn clone(&self) -> Self {
NodeData {
kind: self.kind.clone(),
ext: self.ext.clone(),
span: self.span.clone(),
parsing_state: Arc::clone(&self.parsing_state),
children: self.children.clone(),
}
}
}
impl<L: Lang> fmt::Debug for NodeData<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodeData")
.field("kind", &self.kind)
.field("ext", &self.ext)
.field("span", &self.span)
.field("children", &self.children)
.finish_non_exhaustive()
}
}
impl<L: Lang, A: Clone> Clone for NodeTree<L, A> {
fn clone(&self) -> Self {
NodeTree { core: Arc::clone(&self.core), annotations: self.annotations.clone() }
}
}
impl<L: Lang, A: fmt::Debug> fmt::Debug for NodeTree<L, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodeTree")
.field("nodes", &self.core.nodes)
.field("annotations", &self.annotations)
.finish()
}
}