grit_util/
ast_node.rs

1use crate::{error::GritResult, AstCursor, ByteRange, CodeRange};
2use std::borrow::Cow;
3
4/// Represents an AST node and offers convenient AST-specific functionality.
5///
6/// This trait should be free from dependencies on TreeSitter. This also implies
7/// it should not expose details about the node that may make it infeasible to
8/// implement the trait by implementations that use different node
9/// representations internally.
10pub trait AstNode: std::fmt::Debug + Sized {
11    /// Returns an iterator over the node's ancestors, starting with the node
12    /// itself and moving up to the root.
13    fn ancestors(&self) -> impl Iterator<Item = Self>;
14
15    /// Returns an iterator over the node's children.
16    fn children(&self) -> impl Iterator<Item = Self>;
17
18    /// Returns the node's parent.
19    ///
20    /// Returns `None` if this is the root node.
21    fn parent(&self) -> Option<Self>;
22
23    /// Returns the next node in the tree, ignoring trivia such as whitespace.
24    fn next_named_node(&self) -> Option<Self>;
25
26    /// Returns the previous node in the tree, ignoring trivia such as
27    /// whitespace.
28    fn previous_named_node(&self) -> Option<Self>;
29
30    /// Returns the next adjacent node.
31    fn next_sibling(&self) -> Option<Self>;
32
33    /// Returns the previous adjacent node.
34    fn previous_sibling(&self) -> Option<Self>;
35
36    /// Returns the text representation of the node.
37    fn text(&self) -> GritResult<Cow<str>>;
38
39    /// Returns the byte range of the node.
40    fn byte_range(&self) -> ByteRange;
41
42    /// Returns the code range of the node.
43    fn code_range(&self) -> CodeRange;
44
45    /// Returns a cursor for traversing the tree, starting at the current node.
46    fn walk(&self) -> impl AstCursor<Node = Self>;
47}