syntax-lang 1.0.0

Lossless concrete syntax tree (CST) with trivia.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! The tree itself: [`Node`] interior nodes, [`Element`] children, and the
//! iterative traversals over them.

use alloc::vec;
use alloc::vec::Vec;
use core::slice;

use span_lang::Span;
use token_lang::Token;

/// One child of a [`Node`]: either a nested node or a leaf token.
///
/// A concrete syntax tree alternates between the two — a node groups a run of
/// children under a kind, and a [`Token`] is a leaf carrying a classified span of
/// source. Trivia (whitespace, comments) is not special: it rides as an ordinary
/// leaf token, which is what makes the tree lossless.
///
/// # Examples
///
/// ```
/// use syntax_lang::{Element, Node, Span, Token};
///
/// let leaf: Element<&str> = Element::Token(Token::new("ident", Span::new(0, 3)));
/// assert!(leaf.is_token());
/// assert_eq!(leaf.kind(), &"ident");
/// assert_eq!(leaf.span(), Span::new(0, 3));
///
/// let group = Element::Node(Node::new("expr", vec![leaf]));
/// assert!(group.is_node());
/// assert_eq!(group.span(), Span::new(0, 3));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Element<K> {
    /// A nested interior node.
    Node(Node<K>),
    /// A leaf token: a classified span of source.
    Token(Token<K>),
}

impl<K> Element<K> {
    /// The span of source this child covers — the node's covering span or the
    /// token's own span.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Span, Token};
    ///
    /// let e = Element::Token(Token::new('x', Span::new(4, 5)));
    /// assert_eq!(e.span(), Span::new(4, 5));
    /// ```
    #[inline]
    #[must_use]
    pub fn span(&self) -> Span {
        match self {
            Element::Node(node) => node.span(),
            Element::Token(token) => token.span(),
        }
    }

    /// Borrows the kind of this child — the node's kind or the token's kind.
    ///
    /// Node kinds and token kinds share one type `K` (the rowan model), so a
    /// caller can read a child's kind without first knowing whether it is a node
    /// or a leaf.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Span, Token};
    ///
    /// let e = Element::Token(Token::new("plus", Span::new(1, 2)));
    /// assert_eq!(e.kind(), &"plus");
    /// ```
    #[inline]
    #[must_use]
    pub fn kind(&self) -> &K {
        match self {
            Element::Node(node) => node.kind(),
            Element::Token(token) => token.kind(),
        }
    }

    /// Returns the nested node if this child is one, otherwise `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let node = Element::Node(Node::new("n", vec![Element::Token(Token::new("t", Span::new(0, 1)))]));
    /// assert!(node.as_node().is_some());
    /// assert!(node.as_token().is_none());
    /// ```
    #[inline]
    #[must_use]
    pub fn as_node(&self) -> Option<&Node<K>> {
        match self {
            Element::Node(node) => Some(node),
            Element::Token(_) => None,
        }
    }

    /// Returns the leaf token if this child is one, otherwise `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Span, Token};
    ///
    /// let e = Element::Token(Token::new("t", Span::new(0, 1)));
    /// assert_eq!(e.as_token().map(|t| *t.kind()), Some("t"));
    /// ```
    #[inline]
    #[must_use]
    pub fn as_token(&self) -> Option<&Token<K>> {
        match self {
            Element::Token(token) => Some(token),
            Element::Node(_) => None,
        }
    }

    /// Whether this child is a nested node.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Span, Token};
    ///
    /// assert!(!Element::Token(Token::new(0u8, Span::new(0, 1))).is_node());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_node(&self) -> bool {
        matches!(self, Element::Node(_))
    }

    /// Whether this child is a leaf token.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Span, Token};
    ///
    /// assert!(Element::Token(Token::new(0u8, Span::new(0, 1))).is_token());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_token(&self) -> bool {
        matches!(self, Element::Token(_))
    }
}

/// An interior node of a concrete syntax tree: a [`kind`](Node::kind), the
/// [`span`](Node::span) of source it covers, and its ordered [`children`](Node::children).
///
/// A node owns its children directly, so a whole tree is a single owned value with
/// no arena or handle bookkeeping. The children are in source order; a node's
/// covering span is the union of its children's spans, computed once when the node
/// is built. Because trivia rides as ordinary leaf tokens, the tree is *lossless*:
/// slicing the original source by a node's span — or concatenating its
/// [`tokens`](Node::tokens) — reproduces exactly the source that node came from.
///
/// The kind type `K` is shared by nodes and tokens alike (an `enum` a language
/// defines with both composite and lexical variants), following the model
/// [`token_lang`](token_lang) establishes. The node type itself is generic over any
/// `K` and needs no trait bound.
///
/// # Stack safety
///
/// Traversal ([`tokens`](Node::tokens), [`descendants`](Node::descendants)) and
/// teardown (`Drop`) are *iterative*: a tree tens of thousands of levels deep is
/// walked and freed without recursing on the call stack. `Clone`, `PartialEq`, and
/// `Debug` recurse with tree depth and so suit trees of realistic source depth.
///
/// # Examples
///
/// ```
/// use syntax_lang::{Element, Node, Span, Token};
///
/// // `1 + 2` as a tiny expression node with three leaf tokens.
/// let node = Node::new(
///     "add",
///     vec![
///         Element::Token(Token::new("num", Span::new(0, 1))),
///         Element::Token(Token::new("plus", Span::new(2, 3))),
///         Element::Token(Token::new("num", Span::new(4, 5))),
///     ],
/// );
///
/// assert_eq!(node.kind(), &"add");
/// assert_eq!(node.span(), Span::new(0, 5));
/// assert_eq!(node.text("1 + 2"), Some("1 + 2"));
/// assert_eq!(node.children().count(), 3);
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Node<K> {
    kind: K,
    span: Span,
    children: Vec<Element<K>>,
}

impl<K> Node<K> {
    /// Builds a node from a kind and its ordered children, computing the covering
    /// span as the union of the children's spans.
    ///
    /// Children are taken in source order. A node with no children reports an empty
    /// span at offset `0`; build such nodes through a [`Builder`](crate::Builder)
    /// instead, which places an empty node at the current stream position.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new(
    ///     "paren",
    ///     vec![
    ///         Element::Token(Token::new("(", Span::new(0, 1))),
    ///         Element::Token(Token::new(")", Span::new(1, 2))),
    ///     ],
    /// );
    /// assert_eq!(n.span(), Span::new(0, 2));
    /// ```
    #[must_use]
    pub fn new(kind: K, children: Vec<Element<K>>) -> Self {
        let span = cover(&children, Span::empty(0));
        Self {
            kind,
            span,
            children,
        }
    }

    /// Builds a node with a caller-supplied span, used by the
    /// [`Builder`](crate::Builder) to place an empty node at the current stream
    /// cursor rather than at offset `0`. For a node with children the span still
    /// equals the union of their spans; this only differs for the childless case.
    #[must_use]
    pub(crate) fn with_span(kind: K, children: Vec<Element<K>>, empty: Span) -> Self {
        let span = cover(&children, empty);
        Self {
            kind,
            span,
            children,
        }
    }

    /// Borrows this node's kind.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::Node;
    ///
    /// let n: Node<&str> = Node::new("root", vec![]);
    /// assert_eq!(n.kind(), &"root");
    /// ```
    #[inline]
    #[must_use]
    pub fn kind(&self) -> &K {
        &self.kind
    }

    /// Returns the span of source this node covers: the union of its children's
    /// spans, or an empty span if it has none.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new("n", vec![Element::Token(Token::new("t", Span::new(3, 8)))]);
    /// assert_eq!(n.span(), Span::new(3, 8));
    /// ```
    #[inline]
    #[must_use]
    pub fn span(&self) -> Span {
        self.span
    }

    /// Whether this node has no children.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::Node;
    ///
    /// let n: Node<&str> = Node::new("empty", vec![]);
    /// assert!(n.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }

    /// The number of direct children (nodes and tokens) this node has.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new("n", vec![Element::Token(Token::new("t", Span::new(0, 1)))]);
    /// assert_eq!(n.len(), 1);
    /// ```
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Iterates this node's direct children — nodes and tokens interleaved in
    /// source order.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new(
    ///     "n",
    ///     vec![
    ///         Element::Token(Token::new("a", Span::new(0, 1))),
    ///         Element::Node(Node::new("inner", vec![Element::Token(Token::new("b", Span::new(1, 2)))])),
    ///     ],
    /// );
    /// let kinds: Vec<_> = n.children().map(Element::kind).copied().collect();
    /// assert_eq!(kinds, ["a", "inner"]);
    /// ```
    #[inline]
    pub fn children(&self) -> impl Iterator<Item = &Element<K>> {
        self.children.iter()
    }

    /// Iterates only the direct children that are nested nodes, skipping leaf
    /// tokens.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new(
    ///     "n",
    ///     vec![
    ///         Element::Token(Token::new("a", Span::new(0, 1))),
    ///         Element::Node(Node::new("inner", vec![Element::Token(Token::new("b", Span::new(1, 2)))])),
    ///     ],
    /// );
    /// assert_eq!(n.child_nodes().count(), 1);
    /// ```
    #[inline]
    pub fn child_nodes(&self) -> impl Iterator<Item = &Node<K>> {
        self.children.iter().filter_map(Element::as_node)
    }

    /// Iterates only the direct children that are leaf tokens, skipping nested
    /// nodes.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new(
    ///     "n",
    ///     vec![
    ///         Element::Token(Token::new("a", Span::new(0, 1))),
    ///         Element::Node(Node::new("inner", vec![Element::Token(Token::new("b", Span::new(1, 2)))])),
    ///     ],
    /// );
    /// let direct: Vec<_> = n.child_tokens().map(|t| *t.kind()).collect();
    /// assert_eq!(direct, ["a"]);
    /// ```
    #[inline]
    pub fn child_tokens(&self) -> impl Iterator<Item = &Token<K>> {
        self.children.iter().filter_map(Element::as_token)
    }

    /// Iterates this node and every node beneath it in pre-order (a parent before
    /// its descendants, children in source order).
    ///
    /// The walk is iterative — its work stack lives on the heap — so a tree of any
    /// depth is traversed without overflowing the call stack.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let tree = Node::new(
    ///     "root",
    ///     vec![Element::Node(Node::new(
    ///         "inner",
    ///         vec![Element::Token(Token::new("t", Span::new(0, 1)))],
    ///     ))],
    /// );
    /// let kinds: Vec<_> = tree.descendants().map(Node::kind).copied().collect();
    /// assert_eq!(kinds, ["root", "inner"]);
    /// ```
    #[inline]
    pub fn descendants(&self) -> impl Iterator<Item = &Node<K>> {
        Descendants {
            root: Some(self),
            stack: Vec::new(),
        }
    }

    /// Iterates every leaf token in the tree in source order — the lossless token
    /// stream, trivia included.
    ///
    /// Concatenating these tokens' source slices reproduces the node's source
    /// exactly; the walk is iterative and safe on any depth.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let tree = Node::new(
    ///     "root",
    ///     vec![Element::Node(Node::new(
    ///         "inner",
    ///         vec![
    ///             Element::Token(Token::new("a", Span::new(0, 1))),
    ///             Element::Token(Token::new("b", Span::new(1, 2))),
    ///         ],
    ///     ))],
    /// );
    /// let leaves: Vec<_> = tree.tokens().map(|t| *t.kind()).collect();
    /// assert_eq!(leaves, ["a", "b"]);
    /// ```
    #[inline]
    pub fn tokens(&self) -> impl Iterator<Item = &Token<K>> {
        Tokens {
            stack: vec![self.children.iter()],
        }
    }

    /// Slices `source` by this node's covering span, returning the exact text the
    /// node came from, or `None` if the span lies outside `source`.
    ///
    /// This is zero-copy: it borrows a sub-slice of `source` rather than allocating.
    /// Pass the same source the tree was built from; the `None` case guards against
    /// a mismatched or truncated string rather than panicking.
    ///
    /// # Examples
    ///
    /// ```
    /// use syntax_lang::{Element, Node, Span, Token};
    ///
    /// let n = Node::new(
    ///     "call",
    ///     vec![
    ///         Element::Token(Token::new("id", Span::new(0, 1))),
    ///         Element::Token(Token::new("(", Span::new(1, 2))),
    ///         Element::Token(Token::new(")", Span::new(2, 3))),
    ///     ],
    /// );
    /// assert_eq!(n.text("f()"), Some("f()"));
    /// assert_eq!(n.text("f"), None); // span runs past the string
    /// ```
    #[inline]
    #[must_use]
    pub fn text<'s>(&self, source: &'s str) -> Option<&'s str> {
        let start = self.span.start().to_usize();
        let end = self.span.end().to_usize();
        source.get(start..end)
    }
}

impl<K> Drop for Node<K> {
    /// Frees the tree without recursion.
    ///
    /// The default drop glue would recurse once per level of nesting, overflowing
    /// the stack on a pathologically deep tree (a long chain of single-child
    /// nodes). This moves every descendant node onto an explicit heap worklist and
    /// drops them there, so teardown depth is bounded by heap, not stack.
    fn drop(&mut self) {
        // Fast path: a leaf-only node (or already-drained node) has no nested nodes
        // to recurse into, so the default glue is already non-recursive.
        if self.children.iter().all(Element::is_token) {
            return;
        }
        let mut stack: Vec<Node<K>> = Vec::new();
        drain_nodes(&mut self.children, &mut stack);
        while let Some(mut node) = stack.pop() {
            // Detaching `node`'s children before it drops means its own drop glue
            // runs against an empty vector — no further recursion.
            drain_nodes(&mut node.children, &mut stack);
        }
    }
}

/// Moves every nested node out of `children` onto `stack`; leaf tokens drop in
/// place as the source vector is cleared.
fn drain_nodes<K>(children: &mut Vec<Element<K>>, stack: &mut Vec<Node<K>>) {
    for element in children.drain(..) {
        if let Element::Node(node) = element {
            stack.push(node);
        }
    }
}

/// Folds the children's spans into their covering span, falling back to `empty`
/// for a childless node.
fn cover<K>(children: &[Element<K>], empty: Span) -> Span {
    let mut iter = children.iter();
    match iter.next() {
        None => empty,
        Some(first) => iter.fold(first.span(), |acc, child| acc.merge(child.span())),
    }
}

/// Pre-order iterator over a node and its descendants. Returned by
/// [`Node::descendants`]; iterative, so it never recurses on the call stack.
struct Descendants<'a, K> {
    root: Option<&'a Node<K>>,
    stack: Vec<slice::Iter<'a, Element<K>>>,
}

impl<'a, K> Iterator for Descendants<'a, K> {
    type Item = &'a Node<K>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(root) = self.root.take() {
            self.stack.push(root.children.iter());
            return Some(root);
        }
        loop {
            let top = self.stack.last_mut()?;
            match top.next() {
                None => {
                    let _ = self.stack.pop();
                }
                Some(Element::Node(node)) => {
                    self.stack.push(node.children.iter());
                    return Some(node);
                }
                Some(Element::Token(_)) => {}
            }
        }
    }
}

/// Source-order iterator over every leaf token in a tree. Returned by
/// [`Node::tokens`]; iterative, so it never recurses on the call stack.
struct Tokens<'a, K> {
    stack: Vec<slice::Iter<'a, Element<K>>>,
}

impl<'a, K> Iterator for Tokens<'a, K> {
    type Item = &'a Token<K>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let top = self.stack.last_mut()?;
            match top.next() {
                None => {
                    let _ = self.stack.pop();
                }
                Some(Element::Node(node)) => {
                    self.stack.push(node.children.iter());
                }
                Some(Element::Token(token)) => return Some(token),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    fn tok(kind: &'static str, lo: u32, hi: u32) -> Element<&'static str> {
        Element::Token(Token::new(kind, Span::new(lo, hi)))
    }

    #[test]
    fn test_new_covers_children_span() {
        let n = Node::new("n", vec![tok("a", 2, 4), tok("b", 4, 9)]);
        assert_eq!(n.span(), Span::new(2, 9));
    }

    #[test]
    fn test_new_empty_node_has_empty_span() {
        let n: Node<&str> = Node::new("n", vec![]);
        assert_eq!(n.span(), Span::empty(0));
        assert!(n.is_empty());
        assert_eq!(n.len(), 0);
    }

    #[test]
    fn test_children_iterators_split_nodes_and_tokens() {
        let inner = Element::Node(Node::new("inner", vec![tok("x", 1, 2)]));
        let n = Node::new("n", vec![tok("a", 0, 1), inner]);
        assert_eq!(n.children().count(), 2);
        assert_eq!(n.child_nodes().count(), 1);
        assert_eq!(
            n.child_tokens().map(|t| *t.kind()).collect::<Vec<_>>(),
            ["a"]
        );
    }

    #[test]
    fn test_descendants_preorder() {
        let tree = Node::new(
            "root",
            vec![
                Element::Node(Node::new("l", vec![tok("a", 0, 1)])),
                Element::Node(Node::new("r", vec![tok("b", 1, 2)])),
            ],
        );
        let kinds: Vec<_> = tree.descendants().map(Node::kind).copied().collect();
        assert_eq!(kinds, ["root", "l", "r"]);
    }

    #[test]
    fn test_tokens_source_order_includes_all_leaves() {
        let tree = Node::new(
            "root",
            vec![
                tok("a", 0, 1),
                Element::Node(Node::new("inner", vec![tok("b", 1, 2), tok("c", 2, 3)])),
                tok("d", 3, 4),
            ],
        );
        let leaves: Vec<_> = tree.tokens().map(|t| *t.kind()).collect();
        assert_eq!(leaves, ["a", "b", "c", "d"]);
    }

    #[test]
    fn test_text_slices_source_and_rejects_out_of_bounds() {
        let n = Node::new("n", vec![tok("a", 0, 2), tok("b", 2, 5)]);
        assert_eq!(n.text("hello"), Some("hello"));
        assert_eq!(n.text("hi"), None);
    }

    #[test]
    fn test_element_accessors() {
        let e = tok("a", 0, 1);
        assert!(e.is_token());
        assert!(!e.is_node());
        assert_eq!(e.kind(), &"a");
        assert_eq!(e.span(), Span::new(0, 1));
        assert!(e.as_token().is_some());
        assert!(e.as_node().is_none());
    }

    #[test]
    fn test_deep_tree_drops_without_stack_overflow() {
        // A 200_000-level left chain: recursive drop glue would overflow here.
        let mut node = Node::new("leaf", vec![tok("t", 0, 1)]);
        for _ in 0..200_000 {
            node = Node::new("link", vec![Element::Node(node)]);
        }
        drop(node);
    }

    #[test]
    fn test_deep_tree_tokens_and_descendants_are_iterative() {
        let mut node = Node::new("leaf", vec![tok("t", 0, 1)]);
        for _ in 0..100_000 {
            node = Node::new("link", vec![Element::Node(node)]);
        }
        assert_eq!(node.tokens().count(), 1);
        assert_eq!(node.descendants().count(), 100_001);
    }
}