tabnas-c 0.5.12

C23 concrete-syntax-tree grammar plugin for the tabnas parsing engine, over the jsonic base grammar and the expr operator plugin
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/* Copyright (c) 2026 Richard Rodger and contributors, MIT License */

//! The concrete syntax tree: node and token records, the arena they
//! live in, and the conversion from arena handles to plain engine
//! values.
//!
//! Every node carries `kind`, `span`, `children` and
//! `trivia: {leading, trailing}`, plus per-kind fields, and a token
//! reference is `{kind: "token", tname, src, span}`. That is the
//! cross-runtime shape the shared fixtures pin, so the realized value
//! is byte-comparable with the TypeScript and Go ports.

use std::cell::RefCell;
use std::collections::HashMap;

use indexmap::IndexMap;
use tabnas::{Token, Value};

use crate::state::{handle_node, handle_token, node_handle, token_handle, with_state};

/// The single key a node handle carries. `$` is not a C identifier
/// character and not a key any CST node uses, so a handle cannot be
/// mistaken for a realized node.
pub const NODE_KEY: &str = "$cnode";
/// The single key a token handle carries.
pub const TOKEN_KEY: &str = "$ctoken";

/// A source span, as the CST records it: `start` and `end` are
/// character offsets, `line` is 1-based and `col` is 1-based.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub col: usize,
}

impl Span {
    /// The `{0,0,1,1}` fallback a node with no start token gets.
    pub fn zero() -> Self {
        Span {
            start: 0,
            end: 0,
            line: 1,
            col: 1,
        }
    }

    pub fn to_value(self) -> Value {
        let mut entries = IndexMap::new();
        entries.insert("start".to_string(), Value::Number(self.start as f64));
        entries.insert("end".to_string(), Value::Number(self.end as f64));
        entries.insert("line".to_string(), Value::Number(self.line as f64));
        entries.insert("col".to_string(), Value::Number(self.col as f64));
        Value::object(entries)
    }
}

/// One entry in a node's children, trivia or extra fields: another
/// node, a token, or a plain value.
#[derive(Debug, Clone)]
pub enum Item {
    Node(usize),
    Token(usize),
    Val(Value),
    List(Vec<Item>),
}

impl Item {
    pub fn str(text: impl Into<String>) -> Self {
        Item::Val(Value::String(text.into()))
    }

    pub fn bool(flag: bool) -> Self {
        Item::Val(Value::Bool(flag))
    }

    /// The node this item names, when it names one.
    pub fn as_node(&self) -> Option<usize> {
        match self {
            Item::Node(id) => Some(*id),
            Item::Val(value) => handle_node(value),
            _ => None,
        }
    }

    /// The token this item names, when it names one.
    pub fn as_token(&self) -> Option<usize> {
        match self {
            Item::Token(id) => Some(*id),
            Item::Val(value) => handle_token(value),
            _ => None,
        }
    }

    /// The engine value that stands for this item while a parse runs.
    pub fn to_handle(&self) -> Value {
        match self {
            Item::Node(id) => node_handle(*id),
            Item::Token(id) => token_handle(*id),
            Item::Val(value) => value.clone(),
            Item::List(items) => {
                Value::array(items.iter().map(Item::to_handle).collect::<Vec<_>>())
            }
        }
    }

    /// Read an item back out of a value that travelled through the
    /// engine.
    pub fn from_value(value: &Value) -> Self {
        if let Some(id) = handle_node(value) {
            return Item::Node(id);
        }
        if let Some(id) = handle_token(value) {
            return Item::Token(id);
        }
        Item::Val(value.clone())
    }
}

/// A CST node under construction.
#[derive(Debug, Clone)]
pub struct NodeData {
    pub kind: String,
    pub span: Span,
    pub children: Vec<Item>,
    pub leading: Vec<Item>,
    pub trailing: Vec<Item>,
    /// Per-kind fields, in the order they were first written.
    pub extras: IndexMap<String, Item>,
}

/// A token, as the parse recorded it. Tokens are immutable once
/// emitted, so this is a copy rather than a handle on the engine's.
#[derive(Debug, Clone)]
pub struct TokenData {
    pub name: String,
    pub src: String,
    pub span: Span,
    /// Trivia the lexer attached ahead of this token, as arena ids.
    pub leading: Vec<usize>,
}

/// The span of a token, in the shape the CST records.
pub fn token_span(token: &Token) -> Span {
    Span {
        start: token.site.pos,
        end: token.site.pos + token.src.as_str().chars().count(),
        line: token.site.ri,
        col: token.site.ci,
    }
}

/// The arena id of the engine's no-token sentinel.
///
/// The canonical `rule.c0` getter answers with a sentinel `Token` when
/// the rule matched no close token, and the C handlers push it as if it
/// were real: `@ppi-pointer` runs in the open state, reads `c0`, and
/// the fixtures record the resulting `pointer` node carrying a token
/// with an empty `tname` and `src` at the zero span. `Rule::c0` here
/// answers `None` instead, so a handler that must reproduce that shape
/// falls back to this. One entry per parse, reused.
pub fn no_token() -> usize {
    with_state(|state| {
        if let Some(id) = state.no_token {
            return id;
        }
        state.tokens.push(TokenData {
            name: String::new(),
            src: String::new(),
            span: Span {
                start: 0,
                end: 0,
                line: 1,
                col: 1,
            },
            leading: Vec::new(),
        });
        let id = state.tokens.len() - 1;
        state.no_token = Some(id);
        id
    })
}

/// Copy a token into the arena and return its id. The leading trivia
/// the lex subscriber attached comes with it.
pub fn intern_token(token: &Token) -> usize {
    let leading = leading_ids(token);
    with_state(|state| {
        state.tokens.push(TokenData {
            name: token.name.as_str().to_string(),
            src: token.src.as_str().to_string(),
            span: token_span(token),
            leading,
        });
        state.tokens.len() - 1
    })
}

/// The arena ids of the trivia tokens the lex subscriber stashed on
/// this token under `use.leading`.
fn leading_ids(token: &Token) -> Vec<usize> {
    let Some(use_data) = token.use_data.as_ref() else {
        return Vec::new();
    };
    let Some(Value::Array(items)) = use_data.get("leading") else {
        return Vec::new();
    };
    items.iter().filter_map(handle_token).collect()
}

/// Make a node and return its arena id.
pub fn new_node(kind: &str, span: Option<Span>) -> usize {
    with_state(|state| {
        state.nodes.push(NodeData {
            kind: kind.to_string(),
            span: span.unwrap_or_else(Span::zero),
            children: Vec::new(),
            leading: Vec::new(),
            trailing: Vec::new(),
            extras: IndexMap::new(),
        });
        state.nodes.len() - 1
    })
}

/// The kind of a node, or the empty string when the id is not a node.
pub fn kind_of(node: usize) -> String {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .map(|data| data.kind.clone())
            .unwrap_or_default()
    })
}

pub fn set_kind(node: usize, kind: &str) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.kind = kind.to_string();
        }
    });
}

pub fn span_of(node: usize) -> Span {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .map(|data| data.span)
            .unwrap_or_else(Span::zero)
    })
}

pub fn set_span(node: usize, span: Span) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.span = span;
        }
    });
}

pub fn push_child(node: usize, item: Item) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.children.push(item);
        }
    });
}

pub fn push_trailing(node: usize, item: Item) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.trailing.push(item);
        }
    });
}

pub fn set_children(node: usize, items: Vec<Item>) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.children = items;
        }
    });
}

pub fn children_of(node: usize) -> Vec<Item> {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .map(|data| data.children.clone())
            .unwrap_or_default()
    })
}

pub fn child_count(node: usize) -> usize {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .map(|data| data.children.len())
            .unwrap_or_default()
    })
}

pub fn set_extra(node: usize, key: &str, item: Item) {
    with_state(|state| {
        if let Some(data) = state.nodes.get_mut(node) {
            data.extras.insert(key.to_string(), item);
        }
    });
}

pub fn extra_of(node: usize, key: &str) -> Option<Item> {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .and_then(|data| data.extras.get(key).cloned())
    })
}

pub fn has_extra(node: usize, key: &str) -> bool {
    with_state(|state| {
        state
            .nodes
            .get(node)
            .is_some_and(|data| data.extras.contains_key(key))
    })
}

/// The `src` of a token, or the empty string.
pub fn token_src(token: usize) -> String {
    with_state(|state| {
        state
            .tokens
            .get(token)
            .map(|data| data.src.clone())
            .unwrap_or_default()
    })
}

/// The `tname` of a token, or the empty string.
pub fn token_name(token: usize) -> String {
    with_state(|state| {
        state
            .tokens
            .get(token)
            .map(|data| data.name.clone())
            .unwrap_or_default()
    })
}

pub fn token_data(token: usize) -> Option<TokenData> {
    with_state(|state| state.tokens.get(token).cloned())
}

/// Token-reference items for the trivia attached ahead of a token, as
/// `leadingTriviaRefs` in the canonical port.
pub fn leading_trivia_items(token: usize) -> Vec<Item> {
    with_state(|state| {
        state
            .tokens
            .get(token)
            .map(|data| data.leading.iter().map(|id| Item::Token(*id)).collect())
            .unwrap_or_default()
    })
}

/// Push a token onto a node, leading trivia first, as
/// `pushTokenWithTrivia` does.
pub fn push_token_with_trivia(node: usize, token: usize) {
    for item in leading_trivia_items(token) {
        push_child(node, item);
    }
    push_child(node, Item::Token(token));
}

/// How deep [`realize`] will descend before it gives up.
///
/// The walk is recursive, as the value it builds is, and a Rust stack
/// overflow aborts the process rather than unwinding. Two inputs reach
/// that: source nested deeply enough that its tree is, and a tree that
/// is not a tree at all. `int a = b ? c : d;` builds a
/// `conditional_expression` holding ITSELF among its descendants, in
/// all three ports, so a walk over it never ends. The realized value's
/// own `to_json` and `Drop` recurse over the same shape afterwards, so
/// the bound has to hold for them too.
///
/// The number is MEASURED rather than copied. A translation unit of N
/// nested compound statements realizes at depth `N + 2`, and an
/// unoptimized build costs a little under 1 KiB of stack per level:
///
/// | thread stack | deepest that survived | first that aborted |
/// |---|---|---|
/// | 1 MiB (small) | 302 | 402 |
/// | 2 MiB (a spawned thread's default) | 402 | 802 |
/// | 8 MiB (the main thread's default) | 1202 | past the cap |
///
/// The cap sits below the smallest of those with room to spare, so the
/// bound holds wherever the parse runs rather than only on the main
/// thread. It is still far past any C anyone writes: no fixture in
/// `test/spec` and no program in the 100-program Csmith corpus reaches
/// a tenth of it.
pub const REALIZE_DEPTH_CAP: usize = 256;

thread_local! {
    // Set when a realize walk reached the cap, cleared when one starts.
    // `crate::parse_with` reads it and fails the parse rather than
    // handing back a tree with a hole in it, and the walk itself stops
    // the moment it is set: see `past_the_cap`.
    static REALIZE_TRUNCATED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };

    // What each node realized to, for the length of one walk.
    //
    // The tree can be a DAG: a conditional expression sits in its
    // parent's `children` AND under `cond`, `then` or `else`, which is how the canonical hands
    // callers both views of the same object. JavaScript shares the
    // reference, so building the value costs nothing extra there. A
    // straight port re-walks the node once per path, which is
    // EXPONENTIAL in expression depth: a Csmith translation unit, whose
    // expressions nest dozens deep, never finished. Realizing each node
    // once and handing out the same value restores the sharing, and an
    // engine container is behind an `Arc`, so the copy is a refcount.
    static REALIZED: RefCell<HashMap<usize, Value>> = RefCell::new(HashMap::new());
}

/// True when the last [`realize`] walk on this thread stopped at
/// [`REALIZE_DEPTH_CAP`], so the value it returned is incomplete.
pub fn realize_truncated() -> bool {
    REALIZE_TRUNCATED.with(|cell| cell.get())
}

/// Realize an arena handle into the plain engine value the caller sees.
/// Values that are not handles pass through unchanged, so a tree that
/// mixes CST nodes with engine values realizes correctly.
///
/// A walk that runs out of depth answers with a value that stops short
/// of the whole tree. [`crate::parse_with`] and [`crate::parse_with_meta`]
/// check for that and report the engine's `cancel` code rather than hand
/// back a tree with a hole in it; a caller driving a `tabnas` instance
/// itself gets the same answer from `realize_truncated` in this module.
pub fn realize(value: &Value) -> Value {
    REALIZE_TRUNCATED.with(|cell| cell.set(false));
    REALIZED.with(|memo| memo.borrow_mut().clear());
    let out = realize_at(value, 0);
    // The memo names arena ids, and the next parse reuses them, so it
    // cannot outlive this walk.
    REALIZED.with(|memo| memo.borrow_mut().clear());
    out
}

/// True when the walk must not go on from here: this level is at the
/// cap, or some earlier part of the walk already reached it.
///
/// Stopping the WHOLE walk at the first truncation, not only the branch
/// that reached the cap, is what keeps a truncated walk linear. The value
/// it would go on to build is thrown away, since a truncation anywhere
/// fails the parse, so nothing is lost. What the walk would cost is
/// exponential: a subtree with a hole in it cannot be memoized, and the
/// tree is a DAG (see `REALIZED`), so every node above the hole would be
/// walked once per path that reaches it. An expression chain two hundred
/// levels past the cap, each level reachable through `children` and a
/// semantic alias such as `operand`, is two to the two hundred paths.
fn past_the_cap(depth: usize) -> bool {
    REALIZE_TRUNCATED.with(|cell| {
        if !cell.get() && depth >= REALIZE_DEPTH_CAP {
            cell.set(true);
        }
        cell.get()
    })
}

fn realize_at(value: &Value, depth: usize) -> Value {
    if past_the_cap(depth) {
        return Value::Null;
    }
    if let Some(node) = handle_node(value) {
        return realize_node(node, depth);
    }
    if let Some(token) = handle_token(value) {
        return realize_token(token);
    }
    match value {
        Value::Array(items) => Value::array(
            items
                .iter()
                .map(|item| realize_at(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
        Value::ListRef(list) => Value::array(
            list.value
                .iter()
                .map(|item| realize_at(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
        Value::Object(entries) => Value::object(
            entries
                .iter()
                .map(|(key, entry)| (key.clone(), realize_at(entry, depth + 1)))
                .collect::<IndexMap<_, _>>(),
        ),
        Value::MapRef(map) => Value::object(
            map.value
                .iter()
                .map(|(key, entry)| (key.clone(), realize_at(entry, depth + 1)))
                .collect::<IndexMap<_, _>>(),
        ),
        other => other.clone(),
    }
}

fn realize_item(item: &Item, depth: usize) -> Value {
    if past_the_cap(depth) {
        return Value::Null;
    }
    match item {
        Item::Node(id) => realize_node(*id, depth),
        Item::Token(id) => realize_token(*id),
        Item::Val(value) => realize_at(value, depth),
        Item::List(items) => Value::array(
            items
                .iter()
                .map(|item| realize_item(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
    }
}

fn realize_token(token: usize) -> Value {
    let Some(data) = token_data(token) else {
        return Value::Null;
    };
    let mut entries = IndexMap::new();
    entries.insert("kind".to_string(), Value::String("token".to_string()));
    entries.insert("tname".to_string(), Value::String(data.name));
    entries.insert("src".to_string(), Value::String(data.src));
    entries.insert("span".to_string(), data.span.to_value());
    Value::object(entries)
}

fn realize_node(node: usize, depth: usize) -> Value {
    if past_the_cap(depth) {
        return Value::Null;
    }
    if let Some(done) = REALIZED.with(|memo| memo.borrow().get(&node).cloned()) {
        return done;
    }
    let Some(data) = with_state(|state| state.nodes.get(node).cloned()) else {
        return Value::Null;
    };
    let mut entries = IndexMap::new();
    entries.insert("kind".to_string(), Value::String(data.kind));
    entries.insert("span".to_string(), data.span.to_value());
    entries.insert(
        "children".to_string(),
        Value::array(
            data.children
                .iter()
                .map(|item| realize_item(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
    );
    let mut trivia = IndexMap::new();
    trivia.insert(
        "leading".to_string(),
        Value::array(
            data.leading
                .iter()
                .map(|item| realize_item(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
    );
    trivia.insert(
        "trailing".to_string(),
        Value::array(
            data.trailing
                .iter()
                .map(|item| realize_item(item, depth + 1))
                .collect::<Vec<_>>(),
        ),
    );
    entries.insert("trivia".to_string(), Value::object(trivia));
    for (key, item) in data.extras.iter() {
        entries.insert(key.clone(), realize_item(item, depth + 1));
    }
    let out = Value::object(entries);
    // Only a subtree that finished is worth keeping. The flag was clear
    // when this node started, or the walk would have stopped above, so
    // a flag set now means this subtree is the one with the hole in it.
    if !REALIZE_TRUNCATED.with(|cell| cell.get()) {
        REALIZED.with(|memo| memo.borrow_mut().insert(node, out.clone()));
    }
    out
}

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

    /// The id of a node reachable from itself, with the path that got
    /// there, or `None` when the arena is a directed ACYCLIC graph.
    ///
    /// A node that holds itself is invisible to the fixtures until the
    /// walk over it reaches [`REALIZE_DEPTH_CAP`], and then the parse
    /// reports `cancel` rather than naming the shape that did it. The
    /// two constructs below both built one: a cast as the whole of a
    /// declaration initializer, and a compound literal in the same
    /// position.
    fn first_cycle() -> Option<(usize, Vec<usize>)> {
        fn children_of(node: usize) -> Vec<usize> {
            with_state(|state| {
                let Some(data) = state.nodes.get(node) else {
                    return Vec::new();
                };
                let mut out = Vec::new();
                let mut push = |item: &Item| {
                    let mut stack = vec![item.clone()];
                    while let Some(item) = stack.pop() {
                        match item {
                            Item::Node(id) => out.push(id),
                            Item::List(items) => stack.extend(items),
                            _ => {}
                        }
                    }
                };
                for item in data
                    .children
                    .iter()
                    .chain(data.leading.iter())
                    .chain(data.trailing.iter())
                    .chain(data.extras.values())
                {
                    push(item);
                }
                out
            })
        }

        let count = with_state(|state| state.nodes.len());
        // Depth-first from every node, carrying the path, so the report
        // names the loop rather than only the node it closes on.
        for root in 0..count {
            let mut stack = vec![(root, vec![root])];
            let mut seen = std::collections::HashSet::new();
            while let Some((node, path)) = stack.pop() {
                for child in children_of(node) {
                    if path.contains(&child) {
                        let mut loop_path = path.clone();
                        loop_path.push(child);
                        return Some((child, loop_path));
                    }
                    if seen.insert(child) {
                        let mut next = path.clone();
                        next.push(child);
                        stack.push((child, next));
                    }
                }
            }
        }
        None
    }

    /// Every shape below parses into a tree, not into a graph that
    /// holds itself.
    ///
    /// The one input that does build a cycle, a ternary as the whole of
    /// a declaration initializer, is not here: the canonical builds it
    /// too, and `DIVERGENCE.md` section 1 records it.
    #[test]
    fn no_ordinary_source_builds_a_node_that_holds_itself() {
        let parser = crate::make_with(&crate::COptions::new().with_extended(true));
        for source in [
            "int g = (int)0;",
            "int *p = (int[2]){1,2};",
            "int g = (int)0 + 1;",
            "void f(void) { int y = (int)x + 1; }",
            "int g = sizeof(int);",
            "int g[2] = {1,2};",
            "int g[2][2] = {{1,2},{3,4}};",
            "struct S { int x; }; struct S s = { .x = 1 };",
            "int g = _Generic(x, int: 1, default: 0);",
            "int g = ({ 1; });",
            "const char *s = \"a\" \"b\";",
            "void f(void) { for (int i = 0; i < 2; i++) { g(i); } }",
            "typedef int T; T f(T a) { return a; }",
            "#define M(a) (a)\nint g = M(1);",
            "void f(void) { switch (x) { case 1: break; default: break; } }",
            "int f(int (*p)(void)) { return p(); }",
            "enum E { A = 1, B };",
            "union U { int a; char b; };",
            "static const volatile int *const p = 0;",
            "void f(void) { while (x) { y = a ? b : c; } }",
        ] {
            let _ = crate::parse_with(&parser, source);
            assert_eq!(
                first_cycle(),
                None,
                "{source:?} built a node that is its own descendant"
            );
        }
    }
}