Skip to main content

ridx_syntax/
tree.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! A lossless syntax tree stored flat: nodes in preorder, each covering a range of lexer tokens. Trivia between
12//! significant tokens belongs to the innermost node covering both neighbours, and the root covers every token, so
13//! the source is recovered from the tokens alone.
14
15use crate::syntax_kind::SyntaxKind;
16use crate::token::Token;
17
18/// Index of a node in [`SyntaxTree::nodes`]; the root is `NodeId(0)`.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct NodeId(pub u32);
21
22/// One node: its kind, the tokens it covers (`first..end`, both significant at the edges unless empty), its parent,
23/// and the index just past its last descendant.
24#[derive(Clone, Copy, Debug)]
25pub struct Node {
26    pub kind: SyntaxKind,
27    pub first: u32,
28    pub end: u32,
29    pub parent: u32,
30    pub subtree_end: u32,
31}
32
33/// The tree of one source text.
34pub struct SyntaxTree<'s> {
35    pub src: &'s str,
36    pub tokens: Vec<Token>,
37    pub nodes: Vec<Node>,
38}
39
40/// Compact 4-byte parser event (`Start`, `Finish`, or `Token`).
41#[derive(Clone, Copy, Debug)]
42pub(crate) struct Event {
43    pub(crate) kind: SyntaxKind,
44    fp_lo: u8,
45    fp_hi: u16,
46}
47
48const _: () = assert!(core::mem::size_of::<Event>() == 4);
49
50impl Event {
51    pub(crate) const FINISH: Self = Self { kind: SyntaxKind::Tombstone, fp_lo: 0, fp_hi: u16::MAX };
52    pub(crate) const TOKEN: Self = Self { kind: SyntaxKind::Tombstone, fp_lo: 1, fp_hi: u16::MAX };
53    pub(crate) const TOMBSTONE: Self = Self { kind: SyntaxKind::Tombstone, fp_lo: 0, fp_hi: 0 };
54
55    #[inline]
56    pub(crate) const fn start(kind: SyntaxKind) -> Self {
57        Self { kind, fp_lo: 0, fp_hi: 0 }
58    }
59
60    #[inline]
61    pub(crate) fn tokens(count: u32) -> Self {
62        let mut ev = Self::TOMBSTONE;
63        ev.set_fp(count);
64        ev
65    }
66
67    #[inline]
68    pub(crate) fn set_fp(&mut self, fp: u32) {
69        debug_assert!(fp < 0xFFFE_FFFF);
70        self.fp_lo = (fp & 0xFF) as u8;
71        self.fp_hi = (fp >> 8) as u16;
72    }
73
74    #[inline]
75    pub(crate) const fn fp(self) -> u32 {
76        (self.fp_lo as u32) | ((self.fp_hi as u32) << 8)
77    }
78
79    #[inline]
80    pub(crate) const fn is_special(self) -> bool {
81        self.fp_hi == u16::MAX
82    }
83
84    #[inline]
85    pub(crate) const fn is_token(self) -> bool {
86        self.fp_lo != 0
87    }
88}
89
90impl<'s> SyntaxTree<'s> {
91    pub(crate) fn build(src: &'s str, mut tokens: Vec<Token>, sig: &[u32], mut events: Vec<Event>, nodes_cap: usize) -> Self {
92        let mut nodes: Vec<Node> = Vec::with_capacity(nodes_cap);
93        let mut stack: Vec<u32> = Vec::with_capacity(64);
94        let mut chain: Vec<SyntaxKind> = Vec::with_capacity(16);
95        Self::build_into(src, &mut tokens, sig, &mut events, &mut nodes, &mut stack, &mut chain)
96    }
97
98    pub(crate) fn build_into(
99        src: &'s str,
100        tokens_slot: &mut Vec<Token>,
101        sig: &[u32],
102        events: &mut [Event],
103        nodes_slot: &mut Vec<Node>,
104        stack: &mut Vec<u32>,
105        chain: &mut Vec<SyntaxKind>,
106    ) -> Self {
107        nodes_slot.clear();
108        stack.clear();
109        chain.clear();
110        let mut unstarted = 0usize;
111        let mut next_sig = 0usize;
112        let mut last_end = 0u32;
113        for i in 0..events.len() {
114            let ev = events[i];
115            if ev.is_special() {
116                if ev.is_token() {
117                    let raw = sig[next_sig];
118                    next_sig += 1;
119                    for &id in &stack[unstarted..] {
120                        nodes_slot[id as usize].first = raw;
121                    }
122                    unstarted = stack.len();
123                    last_end = raw + 1;
124                } else {
125                    let id = stack.pop().expect("balanced events") as usize;
126                    unstarted = unstarted.min(stack.len());
127                    let len = nodes_slot.len() as u32;
128                    let n = &mut nodes_slot[id];
129                    if n.first == u32::MAX {
130                        n.first = last_end;
131                    }
132                    n.end = last_end.max(n.first);
133                    n.subtree_end = len;
134                }
135            } else {
136                let fp0 = ev.fp();
137                if fp0 == 0 {
138                    if ev.kind != SyntaxKind::Tombstone {
139                        let parent = stack.last().copied().unwrap_or(u32::MAX);
140                        stack.push(nodes_slot.len() as u32);
141                        nodes_slot.push(Node { kind: ev.kind, first: u32::MAX, end: 0, parent, subtree_end: 0 });
142                    }
143                } else if ev.kind == SyntaxKind::Tombstone {
144                    let first_raw = sig[next_sig];
145                    next_sig += fp0 as usize;
146                    let last_raw = sig[next_sig - 1];
147                    for &id in &stack[unstarted..] {
148                        nodes_slot[id as usize].first = first_raw;
149                    }
150                    unstarted = stack.len();
151                    last_end = last_raw + 1;
152                } else {
153                    events[i] = Event::TOMBSTONE;
154                    chain.clear();
155                    chain.push(ev.kind);
156                    let mut fp = fp0;
157                    let mut at = i;
158                    while fp != 0 {
159                        at += fp as usize;
160                        let target = events[at];
161                        events[at] = Event::TOMBSTONE;
162                        chain.push(target.kind);
163                        fp = target.fp();
164                    }
165                    for &kind in chain.iter().rev() {
166                        if kind == SyntaxKind::Tombstone {
167                            continue;
168                        }
169                        let parent = stack.last().copied().unwrap_or(u32::MAX);
170                        stack.push(nodes_slot.len() as u32);
171                        nodes_slot.push(Node { kind, first: u32::MAX, end: 0, parent, subtree_end: 0 });
172                    }
173                }
174            }
175        }
176        debug_assert!(stack.is_empty());
177        let tokens = core::mem::take(tokens_slot);
178        let mut nodes = core::mem::take(nodes_slot);
179        if let Some(root) = nodes.first_mut() {
180            root.first = 0;
181            root.end = tokens.len() as u32;
182        }
183        SyntaxTree { src, tokens, nodes }
184    }
185
186    #[inline]
187    pub fn root(&self) -> NodeId {
188        NodeId(0)
189    }
190
191    #[inline]
192    pub fn node(&self, id: NodeId) -> &Node {
193        &self.nodes[id.0 as usize]
194    }
195
196    #[inline]
197    pub fn kind(&self, id: NodeId) -> SyntaxKind {
198        self.node(id).kind
199    }
200
201    #[inline]
202    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
203        let p = self.node(id).parent;
204        (p != u32::MAX).then_some(NodeId(p))
205    }
206
207    /// The direct children of `id`, in source order.
208    #[inline]
209    pub fn children(&self, id: NodeId) -> Children<'_, 's> {
210        let n = self.node(id);
211        Children { tree: self, next: id.0 + 1, end: n.subtree_end }
212    }
213
214    /// The first direct child of `id` of kind `kind`.
215    #[inline]
216    pub fn child(&self, id: NodeId, kind: SyntaxKind) -> Option<NodeId> {
217        self.children(id).find(|&c| self.kind(c) == kind)
218    }
219
220    /// `id` and its descendants, in preorder.
221    #[inline]
222    pub fn descendants(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
223        (id.0..self.node(id).subtree_end).map(NodeId)
224    }
225
226    /// `id`'s ancestors from its parent up to the root.
227    #[inline]
228    pub fn ancestors(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
229        std::iter::successors(self.parent(id), move |&p| self.parent(p))
230    }
231
232    /// The byte range of `id`'s significant tokens.
233    #[inline]
234    pub fn range(&self, id: NodeId) -> std::ops::Range<usize> {
235        let n = self.node(id);
236        if n.first >= n.end {
237            let at = self.tokens.get(n.first as usize).map_or(self.src.len(), |t| t.start as usize);
238            return at..at;
239        }
240        self.tokens[n.first as usize].start as usize..self.tokens[n.end as usize - 1].end as usize
241    }
242
243    #[inline]
244    pub fn text(&self, id: NodeId) -> &'s str {
245        &self.src[self.range(id)]
246    }
247
248    /// The tokens `id` covers, trivia included.
249    #[inline]
250    pub fn tokens_of(&self, id: NodeId) -> &[Token] {
251        let n = self.node(id);
252        &self.tokens[n.first as usize..n.end.max(n.first) as usize]
253    }
254
255    /// The significant tokens directly in `id`, not inside a child node, with their indices.
256    pub fn own_tokens(&self, id: NodeId) -> impl Iterator<Item = (usize, Token)> + '_ {
257        let n = *self.node(id);
258        let mut kids = self.children(id).map(|c| *self.node(c)).peekable();
259        let mut i = n.first as usize;
260        std::iter::from_fn(move || loop {
261            if i >= n.end as usize {
262                return None;
263            }
264            if let Some(k) = kids.peek() {
265                if i >= k.first as usize && k.end > k.first {
266                    i = k.end as usize;
267                    kids.next();
268                    continue;
269                }
270                if k.end <= k.first && i >= k.first as usize {
271                    kids.next();
272                    continue;
273                }
274            }
275            let t = self.tokens[i];
276            i += 1;
277            if !t.is_trivia() {
278                return Some((i - 1, t));
279            }
280        })
281    }
282
283    /// The innermost node whose significant range contains byte `offset`.
284    pub fn covering(&self, offset: usize) -> NodeId {
285        let mut id = self.root();
286        'down: loop {
287            for c in self.children(id) {
288                let r = self.range(c);
289                if r.start <= offset && offset < r.end {
290                    id = c;
291                    continue 'down;
292                }
293            }
294            return id;
295        }
296    }
297
298    /// The innermost node of kind `kind` containing byte `offset`.
299    pub fn covering_of(&self, offset: usize, kind: SyntaxKind) -> Option<NodeId> {
300        let id = self.covering(offset);
301        std::iter::once(id).chain(self.ancestors(id)).find(|&a| self.kind(a) == kind)
302    }
303}
304
305/// Iterator over the direct children of a node.
306pub struct Children<'t, 's> {
307    tree: &'t SyntaxTree<'s>,
308    next: u32,
309    end: u32,
310}
311
312impl Iterator for Children<'_, '_> {
313    type Item = NodeId;
314
315    fn next(&mut self) -> Option<NodeId> {
316        if self.next >= self.end {
317            return None;
318        }
319        let id = self.next;
320        self.next = self.tree.nodes[id as usize].subtree_end;
321        Some(NodeId(id))
322    }
323}