use rustc_hash::FxHashMap;
use tree_sitter::Node;
const NONE: u32 = u32::MAX;
pub trait Nav<'tree>: Copy {
fn kind(self, node: Node<'tree>) -> &'static str;
fn parent(self, node: Node<'tree>) -> Option<Node<'tree>>;
fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
fn walk(self, root: Node<'tree>, visit: impl FnMut(Node<'tree>, &'static str) -> bool);
fn walk_with_parent_kind(
self,
root: Node<'tree>,
visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
);
fn walk_named(self, root: Node<'tree>, visit: impl FnMut(Node<'tree>, &'static str) -> bool);
fn for_each_child(self, node: Node<'tree>, visit: impl FnMut(Node<'tree>));
fn for_each_named_child(self, node: Node<'tree>, visit: impl FnMut(Node<'tree>));
fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>>;
fn enclosing(self, mut node: Node<'tree>, kinds: &[&str]) -> Option<Node<'tree>> {
loop {
if kinds.contains(&self.kind(node)) {
return Some(node);
}
node = self.parent(node)?;
}
}
}
#[derive(Clone, Copy)]
pub struct Direct;
impl<'tree> Nav<'tree> for Direct {
fn kind(self, node: Node<'tree>) -> &'static str {
node.kind()
}
fn parent(self, node: Node<'tree>) -> Option<Node<'tree>> {
node.parent()
}
fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
node.prev_sibling()
}
fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
node.prev_named_sibling()
}
fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
node.next_named_sibling()
}
fn walk(self, root: Node<'tree>, mut visit: impl FnMut(Node<'tree>, &'static str) -> bool) {
let mut cursor = root.walk();
loop {
let node = cursor.node();
if visit(node, node.kind()) && cursor.goto_first_child() {
continue;
}
while !cursor.goto_next_sibling() {
if !cursor.goto_parent() {
return;
}
}
}
}
fn walk_with_parent_kind(
self,
root: Node<'tree>,
mut visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
) {
let mut cursor = root.walk();
let mut parents: Vec<&'static str> = Vec::new();
'walk: loop {
let node = cursor.node();
let kind = node.kind();
visit(node, kind, parents.last().copied());
if cursor.goto_first_child() {
parents.push(kind);
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
break 'walk;
}
parents.pop();
}
}
}
fn walk_named(
self,
root: Node<'tree>,
mut visit: impl FnMut(Node<'tree>, &'static str) -> bool,
) {
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if visit(node, node.kind()) {
stack.extend(node.named_children(&mut node.walk()));
}
}
}
fn for_each_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
visit(child);
}
}
fn for_each_named_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
visit(child);
}
}
fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>> {
let mut result = Vec::new();
let mut cursor = root.walk();
let mut depth = 0;
loop {
result.push(cursor.node());
if cursor.goto_last_child() {
while !cursor.node().is_named() && cursor.goto_previous_sibling() {}
if cursor.node().is_named() {
depth += 1;
continue;
}
cursor.goto_parent();
}
loop {
if depth == 0 {
return result;
}
let mut previous = cursor.goto_previous_sibling();
while previous && !cursor.node().is_named() {
previous = cursor.goto_previous_sibling();
}
if previous {
break;
}
cursor.goto_parent();
depth -= 1;
}
}
}
}
pub struct SyntaxIndex<'tree> {
nodes: Vec<Node<'tree>>,
kinds: Vec<&'static str>,
named: Vec<bool>,
parents: Vec<u32>,
previous_siblings: Vec<u32>,
next_siblings: Vec<u32>,
subtree_ends: Vec<u32>,
positions: std::cell::OnceCell<FxHashMap<usize, u32>>,
reverse_named: Vec<Node<'tree>>,
kind_names: Vec<Option<&'static str>>,
}
impl<'tree> SyntaxIndex<'tree> {
pub fn new(root: Node<'tree>) -> Self {
let language = root.language();
let kind_names = (0..language.node_kind_count())
.map(|id| {
u16::try_from(id)
.ok()
.and_then(|id| language.node_kind_for_id(id))
})
.collect();
let mut index = Self {
nodes: Vec::new(),
kinds: Vec::new(),
named: Vec::new(),
parents: Vec::new(),
previous_siblings: Vec::new(),
next_siblings: Vec::new(),
subtree_ends: Vec::new(),
positions: std::cell::OnceCell::new(),
reverse_named: Vec::new(),
kind_names,
};
let mut cursor = root.walk();
let mut ancestors: Vec<(u32, u32)> = Vec::new();
'walk: loop {
let node = cursor.node();
let position = index.nodes.len() as u32;
let (parent, previous) = match ancestors.last_mut() {
Some((parent, last_child)) => {
let previous = std::mem::replace(last_child, position);
(*parent, previous)
}
None => (NONE, NONE),
};
if previous != NONE {
index.next_siblings[previous as usize] = position;
}
index.nodes.push(node);
index.kinds.push(index.kind_name(node));
index.named.push(node.is_named());
index.parents.push(parent);
index.previous_siblings.push(previous);
index.next_siblings.push(NONE);
index.subtree_ends.push(position + 1);
if cursor.goto_first_child() {
ancestors.push((position, NONE));
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
break 'walk;
}
let (closed, _) = ancestors.pop().expect("every parent was entered");
index.subtree_ends[closed as usize] = index.nodes.len() as u32;
}
}
index.reverse_named = index.reverse_named_from(0);
index
}
pub fn preorder_kinds(&self) -> impl Iterator<Item = (Node<'tree>, &'static str)> + '_ {
self.nodes.iter().copied().zip(self.kinds.iter().copied())
}
fn kind_name(&self, node: Node<'tree>) -> &'static str {
match self.kind_names.get(usize::from(node.kind_id())) {
Some(Some(name)) => name,
_ => node.kind(),
}
}
fn position(&self, node: Node<'tree>) -> Option<u32> {
if self.nodes.first() == Some(&node) {
return Some(0);
}
self.positions
.get_or_init(|| {
self.nodes
.iter()
.enumerate()
.map(|(position, node)| (node.id(), position as u32))
.collect()
})
.get(&node.id())
.copied()
}
fn reverse_named_from(&self, root: u32) -> Vec<Node<'tree>> {
let mut order = Vec::new();
let mut stack = vec![root];
while let Some(position) = stack.pop() {
order.push(self.nodes[position as usize]);
let end = self.subtree_ends[position as usize];
let mut child = position + 1;
while child < end {
if self.named[child as usize] {
stack.push(child);
}
child = self.subtree_ends[child as usize];
}
}
order
}
fn neighbour(&self, position: u32) -> Result<Option<Node<'tree>>, ()> {
if position == NONE {
return Ok(None);
}
let node = self.nodes[position as usize];
if node.start_byte() == node.end_byte() {
return Err(());
}
Ok(Some(node))
}
fn step(&self, node: Node<'tree>, links: &[u32]) -> Option<Option<Node<'tree>>> {
if node.start_byte() == node.end_byte() {
return None;
}
let position = self.position(node)?;
self.neighbour(links[position as usize]).ok()
}
fn named_step(&self, node: Node<'tree>, links: &[u32]) -> Option<Option<Node<'tree>>> {
if node.start_byte() == node.end_byte() {
return None;
}
let mut position = links[self.position(node)? as usize];
loop {
let sibling = self.neighbour(position).ok()?;
match sibling {
None => return Some(None),
Some(sibling) if self.named[position as usize] => return Some(Some(sibling)),
Some(_) => position = links[position as usize],
}
}
}
}
impl<'tree> Nav<'tree> for &SyntaxIndex<'tree> {
fn kind(self, node: Node<'tree>) -> &'static str {
self.kind_name(node)
}
fn parent(self, node: Node<'tree>) -> Option<Node<'tree>> {
if node.start_byte() == node.end_byte() {
return node.parent();
}
match self.position(node) {
Some(position) => {
let parent = self.parents[position as usize];
(parent != NONE).then(|| self.nodes[parent as usize])
}
None => node.parent(),
}
}
fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
self.step(node, &self.previous_siblings)
.unwrap_or_else(|| node.prev_sibling())
}
fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
self.named_step(node, &self.previous_siblings)
.unwrap_or_else(|| node.prev_named_sibling())
}
fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
self.named_step(node, &self.next_siblings)
.unwrap_or_else(|| node.next_named_sibling())
}
fn walk(self, root: Node<'tree>, mut visit: impl FnMut(Node<'tree>, &'static str) -> bool) {
let Some(start) = self.position(root) else {
return Direct.walk(root, visit);
};
let end = self.subtree_ends[start as usize];
let mut position = start;
while position < end {
let index = position as usize;
position = if visit(self.nodes[index], self.kinds[index]) {
position + 1
} else {
self.subtree_ends[index]
};
}
}
fn walk_with_parent_kind(
self,
root: Node<'tree>,
mut visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
) {
let Some(start) = self.position(root) else {
return Direct.walk_with_parent_kind(root, visit);
};
visit(root, self.kinds[start as usize], None);
for position in start + 1..self.subtree_ends[start as usize] {
let index = position as usize;
let parent = self.parents[index] as usize;
visit(
self.nodes[index],
self.kinds[index],
Some(self.kinds[parent]),
);
}
}
fn walk_named(
self,
root: Node<'tree>,
mut visit: impl FnMut(Node<'tree>, &'static str) -> bool,
) {
let Some(start) = self.position(root) else {
return Direct.walk_named(root, visit);
};
let mut stack = vec![start];
while let Some(position) = stack.pop() {
let index = position as usize;
if visit(self.nodes[index], self.kinds[index]) {
let end = self.subtree_ends[index];
let mut child = position + 1;
while child < end {
if self.named[child as usize] {
stack.push(child);
}
child = self.subtree_ends[child as usize];
}
}
}
}
fn for_each_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
let Some(position) = self.position(node) else {
return Direct.for_each_child(node, visit);
};
let end = self.subtree_ends[position as usize];
let mut child = position + 1;
while child < end {
visit(self.nodes[child as usize]);
child = self.subtree_ends[child as usize];
}
}
fn for_each_named_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
let Some(position) = self.position(node) else {
return Direct.for_each_named_child(node, visit);
};
let end = self.subtree_ends[position as usize];
let mut child = position + 1;
while child < end {
if self.named[child as usize] {
visit(self.nodes[child as usize]);
}
child = self.subtree_ends[child as usize];
}
}
fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>> {
match self.position(root) {
Some(0) => self.reverse_named.clone(),
Some(position) => self.reverse_named_from(position),
None => Direct.reverse_named_preorder(root),
}
}
}