Skip to main content

logicaffeine_language/
ast_depth.rs

1//! The AST depth gate — "parsed ⇒ bounded".
2//!
3//! Every consumer downstream of the parser (optimizer, codegen, tree-walker,
4//! VM compiler, transpiler) walks the AST **recursively**; a tree nested
5//! thousands of levels deep (a 10,000-term `1+1+…` chain, a parenthesis
6//! tower, a generated block pyramid) overflows their stacks and aborts the
7//! process — on every surface at once (CLI, REPL, LSP, web Studio).
8//!
9//! The gate enforces one contract at the single choke point
10//! ([`Parser::parse_program`](crate::Parser)): any program that parses has
11//! nesting depth ≤ the enforced limit ([`max_ast_depth`]), so downstream
12//! recursion is bounded by construction. Programs past the limit get a graceful
13//! [`AstTooDeep`](crate::error::ParseErrorKind::AstTooDeep) diagnostic with
14//! a Socratic fix (split into `Let` bindings).
15//!
16//! The walker itself is **iterative** (an explicit work stack) — measuring
17//! the depth must never be the thing that overflows. Its matches are
18//! **exhaustive with no wildcard**: adding an AST variant with children
19//! fails compilation here, forcing the author to classify the new
20//! children — the ratchet that keeps the gate honest as the language grows.
21//!
22//! Boxed noun-phrase payloads (`Categorical`, `Relation`, `NeoEvent`,
23//! comparatives) carry [`Term`](crate::ast::logic::Term)s whose nesting is
24//! bounded by English sentence structure, not by program size — they count
25//! as one level.
26
27use crate::ast::logic::LogicExpr;
28use crate::ast::stmt::{ClosureBody, Expr, ReadSource, SelectBranch, Stmt, StringPart, TypeExpr};
29use crate::error::{ParseError, ParseErrorKind};
30use crate::token::Span;
31
32/// The DEFAULT maximum AST nesting depth.
33///
34/// The budget, measured: the parser's own descent costs ~7 KiB of stack per
35/// nesting level in debug builds (the fattest case — release and the
36/// downstream walkers are far leaner), and the tightest standard
37/// environments give ~2 MiB (worker threads) or ~1 MiB (browser wasm).
38/// 128 levels keeps the worst case inside the smallest stack with margin,
39/// while being ~3× deeper than any hand-written program observed in the
40/// corpus. Machines with deep stacks raise it via `LOGOS_MAX_AST_DEPTH`
41/// (see [`max_ast_depth`]) — the limit protects the environment, so the
42/// environment gets to size it. Enforced at parse time (recursion guard)
43/// AND on the built tree, covering parenthesis towers, block pyramids, and
44/// iteratively-built operator chains alike.
45pub const DEFAULT_MAX_AST_DEPTH: usize = 128;
46
47/// The smallest limit the override accepts — below this, ordinary programs
48/// stop parsing.
49pub const MIN_AST_DEPTH: usize = 16;
50
51/// The EFFECTIVE depth limit: [`DEFAULT_MAX_AST_DEPTH`] unless the
52/// `LOGOS_MAX_AST_DEPTH` environment variable overrides it.
53///
54/// The default is sized for the tightest standard environment; machines
55/// with deep stacks (a big `ulimit -s` / `RUST_MIN_STACK`) can raise it,
56/// and constrained embedders can lower it — no rebuild required. Read once
57/// per process.
58pub fn max_ast_depth() -> usize {
59    static LIMIT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
60    *LIMIT.get_or_init(|| limit_from(std::env::var("LOGOS_MAX_AST_DEPTH").ok().as_deref()))
61}
62
63/// Pure resolution of the override value (unit-testable without touching
64/// process environment): a parseable value is clamped to at least
65/// [`MIN_AST_DEPTH`]; anything else falls back to the default.
66pub fn limit_from(env_value: Option<&str>) -> usize {
67    match env_value.and_then(|v| v.trim().parse::<usize>().ok()) {
68        Some(n) => n.max(MIN_AST_DEPTH),
69        None => DEFAULT_MAX_AST_DEPTH,
70    }
71}
72
73/// The parse-time recursion budget: an EIGHTH of the AST limit (min the floor).
74///
75/// The parser's own descent is BY FAR the fattest stack consumer — each parenthesis level
76/// re-enters the whole precedence/condition chain — so it gets a much tighter budget than the
77/// built-tree limit. The number that matters is the ratio between one level's frame and the
78/// smallest stack the parser must survive on:
79///
80/// | measured                                    | value       |
81/// |---------------------------------------------|-------------|
82/// | one level of descent, debug build (2026-09) | ~64 KiB     |
83/// | smallest stack the gate is tested on        | 2 MiB       |
84/// | levels before the real stack dies           | 32          |
85/// | this budget at the default limit            | 16          |
86///
87/// The budget must fire BEFORE the stack dies, or the guard is decorative: a `SIGABRT` is
88/// exactly the crash it exists to prevent. It was a QUARTER of the limit, which put it at 32 —
89/// the cliff itself, with no margin — so any growth of the descent's frame turned a graceful
90/// rejection into a stack overflow, and one did. An eighth spends half the stack instead of
91/// all of it, which is room for the parser to keep growing.
92///
93/// Still scales with `LOGOS_MAX_AST_DEPTH`: raising it asserts a deeper stack, and raises both
94/// together as before.
95pub fn max_parse_recursion() -> usize {
96    (max_ast_depth() / 8).max(MIN_AST_DEPTH)
97}
98
99/// A work-stack node: any AST reference that can contain further nesting.
100enum Node<'w, 'a> {
101    S(&'w Stmt<'a>),
102    E(&'w Expr<'a>),
103    T(&'w TypeExpr<'a>),
104    L(&'w LogicExpr<'a>),
105}
106
107/// Measure the maximum nesting depth of a parsed program, iteratively.
108pub fn program_depth(stmts: &[Stmt<'_>]) -> usize {
109    let mut work: Vec<(Node<'_, '_>, usize)> = stmts.iter().map(|s| (Node::S(s), 1)).collect();
110    let mut max_depth = 0usize;
111
112    while let Some((node, depth)) = work.pop() {
113        max_depth = max_depth.max(depth);
114        let d = depth + 1;
115        match node {
116            Node::S(stmt) => push_stmt_children(stmt, d, &mut work),
117            Node::E(expr) => push_expr_children(expr, d, &mut work),
118            Node::T(ty) => push_type_children(ty, d, &mut work),
119            Node::L(logic) => push_logic_children(logic, d, &mut work),
120        }
121    }
122    max_depth
123}
124
125/// A node [`for_each_node`] hands its visitor.
126pub enum Visited<'w, 'a> {
127    Stmt(&'w Stmt<'a>),
128    Expr(&'w Expr<'a>),
129}
130
131/// Visit every statement and expression in `stmts`, each once — the same exhaustive child
132/// enumeration the depth gate walks, so a new variant's children are reached here the moment the
133/// gate reaches them. Iterative, like the gate: visiting must never be what overflows.
134pub fn for_each_node<'w, 'a>(stmts: &'w [Stmt<'a>], mut visit: impl FnMut(Visited<'w, 'a>)) {
135    walk_nodes(stmts, |node| {
136        visit(node);
137        Walk::Into
138    });
139}
140
141/// Whether a [`walk_nodes`] visitor goes on into the children of the node it was handed.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum Walk {
144    /// Visit the node's children too.
145    Into,
146    /// Leave the node's children unvisited — another scope's, say: a function's body is not the
147    /// scope that defines the function.
148    Past,
149}
150
151/// [`for_each_node`], with the visitor answering for each statement and expression whether the walk
152/// goes on into its children. Exhaustive in the same way: a child is left unvisited only because a
153/// visitor said so, never because the walk does not know the kind of node it is in.
154pub fn walk_nodes<'w, 'a>(stmts: &'w [Stmt<'a>], mut visit: impl FnMut(Visited<'w, 'a>) -> Walk) {
155    let mut work: Vec<(Node<'w, 'a>, usize)> = stmts.iter().map(|s| (Node::S(s), 1)).collect();
156    while let Some((node, depth)) = work.pop() {
157        let d = depth + 1;
158        match node {
159            Node::S(stmt) => {
160                if visit(Visited::Stmt(stmt)) == Walk::Into {
161                    push_stmt_children(stmt, d, &mut work);
162                }
163            }
164            Node::E(expr) => {
165                if visit(Visited::Expr(expr)) == Walk::Into {
166                    push_expr_children(expr, d, &mut work);
167                }
168            }
169            Node::T(ty) => push_type_children(ty, d, &mut work),
170            Node::L(logic) => push_logic_children(logic, d, &mut work),
171        }
172    }
173}
174
175/// The expressions an expression evaluates directly — its operands, arguments, elements — in the same
176/// exhaustive enumeration the depth gate walks. A closure's body is not among them: it runs when the
177/// closure is called, not when the closure expression is evaluated.
178pub fn expr_children<'w, 'a>(expr: &'w Expr<'a>) -> Vec<&'w Expr<'a>> {
179    if matches!(expr, Expr::Closure { .. }) {
180        return Vec::new();
181    }
182    let mut work = Vec::new();
183    push_expr_children(expr, 0, &mut work);
184    work.into_iter()
185        .filter_map(|(node, _)| match node {
186            Node::E(e) => Some(e),
187            _ => None,
188        })
189        .collect()
190}
191
192/// The expressions a statement evaluates directly (its value, condition, target, arguments — not the
193/// statements of its nested blocks).
194pub fn stmt_expr_children<'w, 'a>(stmt: &'w Stmt<'a>) -> Vec<&'w Expr<'a>> {
195    let mut work = Vec::new();
196    push_stmt_children(stmt, 0, &mut work);
197    work.into_iter()
198        .filter_map(|(node, _)| match node {
199            Node::E(e) => Some(e),
200            _ => None,
201        })
202        .collect()
203}
204
205/// Validate a parsed program against the effective limit
206/// ([`max_ast_depth`]).
207pub fn validate_program_depth(stmts: &[Stmt<'_>], span: Span) -> Result<(), ParseError> {
208    let limit = max_ast_depth();
209    let depth = program_depth(stmts);
210    if depth > limit {
211        return Err(ParseError {
212            kind: ParseErrorKind::AstTooDeep {
213                depth,
214                max_depth: limit,
215            },
216            span,
217        });
218    }
219    Ok(())
220}
221
222#[cfg(test)]
223#[path = "../../logicaffeine_tests/unit/logicaffeine_language/ast_depth/tests.rs"]
224mod tests;
225
226fn push_stmt_children<'w, 'a>(stmt: &'w Stmt<'a>, d: usize, work: &mut Vec<(Node<'w, 'a>, usize)>) {
227    macro_rules! e {
228        ($x:expr) => {
229            work.push((Node::E($x), d))
230        };
231    }
232    macro_rules! block {
233        ($b:expr) => {
234            for s in $b.iter() {
235                work.push((Node::S(s), d));
236            }
237        };
238    }
239    match stmt {
240        Stmt::Let {
241            ty,
242            value,
243            var: _,
244            mutable: _,
245        } => {
246            if let Some(t) = ty {
247                work.push((Node::T(t), d));
248            }
249            e!(value);
250        }
251        Stmt::Set { value, target: _ } => e!(value),
252        // `Swap a and b` has only two symbol operands — no child expressions to bound.
253        Stmt::Swap { a: _, b: _ } => {}
254        Stmt::Call { args, function: _ } => {
255            for a in args {
256                e!(a);
257            }
258        }
259        Stmt::If {
260            cond,
261            then_block,
262            else_block,
263        } => {
264            e!(cond);
265            block!(then_block);
266            if let Some(b) = else_block {
267                block!(b);
268            }
269        }
270        Stmt::While {
271            cond,
272            body,
273            decreasing,
274        } => {
275            e!(cond);
276            if let Some(x) = decreasing {
277                e!(x);
278            }
279            block!(body);
280        }
281        Stmt::Repeat {
282            iterable,
283            body,
284            pattern: _,
285        } => {
286            e!(iterable);
287            block!(body);
288        }
289        Stmt::Return { value } => {
290            if let Some(x) = value {
291                e!(x);
292            }
293        }
294        Stmt::Break => {}
295        Stmt::Assert { proposition } => work.push((Node::L(proposition), d)),
296        Stmt::Trust {
297            proposition,
298            justification: _,
299        } => work.push((Node::L(proposition), d)),
300        Stmt::RuntimeAssert {
301            condition,
302            hard: _,
303            dim: _,
304            reason,
305        } => {
306            e!(condition);
307            if let Some(r) = reason {
308                e!(r);
309            }
310        }
311        Stmt::Fail { reason } => e!(reason),
312        Stmt::Give { object, recipient } => {
313            e!(object);
314            e!(recipient);
315        }
316        Stmt::Show { object, recipient } => {
317            e!(object);
318            e!(recipient);
319        }
320        Stmt::SetField {
321            object,
322            value,
323            field: _,
324        } => {
325            e!(object);
326            e!(value);
327        }
328        Stmt::StructDef { .. } => {}
329        Stmt::TestDef { cases, body, .. } => {
330            if let Some(table) = cases {
331                for row in &table.rows {
332                    for cell in row {
333                        e!(cell);
334                    }
335                }
336            }
337            block!(body);
338        }
339        Stmt::Expect { condition } => e!(condition),
340        Stmt::ExpectFail { body, message: _ } => block!(body),
341        Stmt::ExpectOutput { .. } => {}
342        Stmt::AdvanceTime { millis } => e!(millis),
343        Stmt::GivenFile { .. } => {}
344        Stmt::Observe { payloads, .. } => {
345            for (_, expr) in payloads {
346                e!(expr);
347            }
348        }
349        Stmt::During { body, .. } => block!(body),
350        Stmt::ForAll {
351            constraint, body, ..
352        } => {
353            if let Some(c) = constraint {
354                e!(c);
355            }
356            block!(body);
357        }
358        Stmt::FunctionDef {
359            params,
360            body,
361            return_type,
362            ..
363        } => {
364            for (_, t) in params {
365                work.push((Node::T(t), d));
366            }
367            if let Some(t) = return_type {
368                work.push((Node::T(t), d));
369            }
370            block!(body);
371        }
372        Stmt::Inspect {
373            target,
374            arms,
375            has_otherwise: _,
376        } => {
377            e!(target);
378            for arm in arms {
379                block!(arm.body);
380            }
381        }
382        Stmt::Push { value, collection } => {
383            e!(value);
384            e!(collection);
385        }
386        Stmt::Pop {
387            collection,
388            into: _,
389        } => e!(collection),
390        Stmt::Add { value, collection } => {
391            e!(value);
392            e!(collection);
393        }
394        Stmt::Remove { value, collection } => {
395            e!(value);
396            e!(collection);
397        }
398        Stmt::SetIndex {
399            collection,
400            index,
401            value,
402        } => {
403            e!(collection);
404            e!(index);
405            e!(value);
406        }
407        Stmt::Splice { body } => block!(body),
408        Stmt::ComponentDef(def) => {
409            for (_, t) in &def.props {
410                work.push((Node::T(t), d));
411            }
412            if let crate::ast::component::ComponentKind::Page { params, .. } = &def.kind {
413                for (_, t) in params {
414                    work.push((Node::T(t), d));
415                }
416            }
417            for f in &def.state {
418                if let Some(t) = f.ty {
419                    work.push((Node::T(t), d));
420                }
421                e!(f.init);
422            }
423            for ev in &def.events {
424                block!(ev.body);
425            }
426            for a in &def.actions {
427                for (_, t) in &a.params {
428                    work.push((Node::T(t), d));
429                }
430                block!(a.body);
431            }
432            if let Some(v) = &def.view {
433                let (es, bs) = v.exprs_and_blocks();
434                for x in es {
435                    e!(x);
436                }
437                for b in bs {
438                    block!(b);
439                }
440            }
441        }
442        Stmt::DirectiveDef {
443            params,
444            body,
445            removed,
446            ..
447        } => {
448            for (_, t) in params {
449                work.push((Node::T(t), d));
450            }
451            block!(body);
452            if let Some(r) = removed {
453                block!(r);
454            }
455        }
456        Stmt::RouteDef {
457            params,
458            return_type,
459            body,
460            ..
461        } => {
462            for (_, t) in params {
463                work.push((Node::T(t), d));
464            }
465            if let Some(t) = return_type {
466                work.push((Node::T(t), d));
467            }
468            match &**body {
469                crate::ast::component::RouteBody::Statements(b) => block!(b),
470                crate::ast::component::RouteBody::View(v) => {
471                    let (es, bs) = v.exprs_and_blocks();
472                    for x in es {
473                        e!(x);
474                    }
475                    for b in bs {
476                        block!(b);
477                    }
478                }
479            }
480        }
481        Stmt::MiddlewareDef { param, body } => {
482            work.push((Node::T(param.1), d));
483            block!(body);
484        }
485        Stmt::RedirectDef { .. } => {}
486        Stmt::Ui(u) => {
487            for x in u.exprs() {
488                e!(x);
489            }
490        }
491        Stmt::ServeFetches | Stmt::Replay { .. } => {}
492        Stmt::GivenFetch {
493            url, status, body, ..
494        } => {
495            e!(url);
496            e!(status);
497            e!(body);
498        }
499        Stmt::Fetch {
500            url, body, as_type, ..
501        } => {
502            e!(url);
503            if let Some(b) = body {
504                e!(b);
505            }
506            work.push((Node::T(as_type), d));
507        }
508        Stmt::Reversibly { body } => block!(body),
509        Stmt::Zone {
510            body,
511            name: _,
512            capacity: _,
513            source_file: _,
514        } => block!(body),
515        Stmt::Concurrent { tasks } => block!(tasks),
516        Stmt::Parallel { tasks } => block!(tasks),
517        Stmt::ReadFrom { source, var: _ } => match source {
518            ReadSource::Console => {}
519            ReadSource::File(path) => e!(path),
520        },
521        Stmt::WriteFile { content, path } => {
522            e!(content);
523            e!(path);
524        }
525        Stmt::Spawn { .. } => {}
526        Stmt::SendMessage {
527            message,
528            destination,
529            ..
530        } => {
531            e!(message);
532            e!(destination);
533        }
534        Stmt::AwaitMessage { source, .. } => e!(source),
535        Stmt::StreamMessage {
536            values,
537            destination,
538        } => {
539            e!(values);
540            e!(destination);
541        }
542        Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
543            e!(source);
544            e!(target);
545        }
546        Stmt::IncreaseCrdt {
547            object,
548            amount,
549            field: _,
550        } => {
551            e!(object);
552            e!(amount);
553        }
554        Stmt::DecreaseCrdt {
555            object,
556            amount,
557            field: _,
558        } => {
559            e!(object);
560            e!(amount);
561        }
562        Stmt::AppendToSequence { sequence, value } => {
563            e!(sequence);
564            e!(value);
565        }
566        Stmt::ResolveConflict {
567            object,
568            value,
569            field: _,
570        } => {
571            e!(object);
572            e!(value);
573        }
574        Stmt::Check { .. } => {}
575        Stmt::Listen { address, secure } => {
576            e!(address);
577            if let Some(pad) = secure {
578                e!(pad.pad);
579            }
580        }
581        Stmt::Serve { port, handler } => {
582            e!(port);
583            e!(handler);
584        }
585        Stmt::ConnectTo { address, secure } => {
586            e!(address);
587            if let Some(pad) = secure {
588                e!(pad.pad);
589            }
590        }
591        Stmt::LetPeerAgent { address, var: _ } => e!(address),
592        Stmt::Sleep { milliseconds } => e!(milliseconds),
593        Stmt::Sync { topic, var: _ } => e!(topic),
594        Stmt::Mount { path, var: _ } => e!(path),
595        Stmt::LaunchTask { args, function: _ } => {
596            for a in args {
597                e!(a);
598            }
599        }
600        Stmt::LaunchTaskWithHandle {
601            args,
602            handle: _,
603            function: _,
604        } => {
605            for a in args {
606                e!(a);
607            }
608        }
609        Stmt::CreatePipe { .. } => {}
610        Stmt::SendPipe { value, pipe } => {
611            e!(value);
612            e!(pipe);
613        }
614        Stmt::ReceivePipe { pipe, var: _ } => e!(pipe),
615        Stmt::TrySendPipe {
616            value,
617            pipe,
618            result: _,
619        } => {
620            e!(value);
621            e!(pipe);
622        }
623        Stmt::TryReceivePipe { pipe, var: _ } => e!(pipe),
624        Stmt::StopTask { handle } => e!(handle),
625        Stmt::CloseChannel { channel } => e!(channel),
626        Stmt::AwaitTask { handle, result: _ } => e!(handle),
627        Stmt::Select { branches } => {
628            for branch in branches {
629                match branch {
630                    SelectBranch::Receive { pipe, body, var: _ } => {
631                        e!(pipe);
632                        block!(body);
633                    }
634                    SelectBranch::Timeout { milliseconds, body } => {
635                        e!(milliseconds);
636                        block!(body);
637                    }
638                }
639            }
640        }
641        // Formal blocks carry owned proof ASTs consumed by the proof layer,
642        // whose own conversion is bounded separately; they count one level.
643        Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {}
644        Stmt::Escape { .. } => {}
645        Stmt::Require { .. } => {}
646        // An opaque failure-site marker: an id, no expression or nested block to bound.
647        Stmt::Site(_) => {}
648    }
649}
650
651fn push_expr_children<'w, 'a>(expr: &'w Expr<'a>, d: usize, work: &mut Vec<(Node<'w, 'a>, usize)>) {
652    macro_rules! e {
653        ($x:expr) => {
654            work.push((Node::E($x), d))
655        };
656    }
657    match expr {
658        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone | Expr::Escape { .. } => {}
659        Expr::Dom(q) => {
660            if let Some(sel) = q.selector() {
661                e!(sel);
662            }
663        }
664        Expr::View(v) => {
665            let (es, bs) = v.exprs_and_blocks();
666            for x in es {
667                e!(x);
668            }
669            for b in bs {
670                for st in b.iter() {
671                    work.push((Node::S(st), d));
672                }
673            }
674        }
675        Expr::BinaryOp { left, right, op: _ } => {
676            e!(left);
677            e!(right);
678        }
679        Expr::Not { operand } => e!(operand),
680        Expr::Call { args, function: _ } => {
681            for a in args {
682                e!(a);
683            }
684        }
685        Expr::Index { collection, index } => {
686            e!(collection);
687            e!(index);
688        }
689        Expr::Slice {
690            collection,
691            start,
692            end,
693        } => {
694            e!(collection);
695            e!(start);
696            e!(end);
697        }
698        Expr::Copy { expr } => e!(expr),
699        Expr::Give { value } => e!(value),
700        Expr::Length { collection } => e!(collection),
701        Expr::Contains { collection, value } => {
702            e!(collection);
703            e!(value);
704        }
705        Expr::Union { left, right } => {
706            e!(left);
707            e!(right);
708        }
709        Expr::Intersection { left, right } => {
710            e!(left);
711            e!(right);
712        }
713        Expr::ManifestOf { zone } => e!(zone),
714        Expr::ChunkAt { index, zone } => {
715            e!(index);
716            e!(zone);
717        }
718        Expr::List(items) => {
719            for x in items {
720                e!(x);
721            }
722        }
723        Expr::Tuple(items) => {
724            for x in items {
725                e!(x);
726            }
727        }
728        Expr::Range { start, end } => {
729            e!(start);
730            e!(end);
731        }
732        Expr::FieldAccess { object, field: _ } => e!(object),
733        Expr::New {
734            type_args,
735            init_fields,
736            type_name: _,
737        } => {
738            for t in type_args {
739                work.push((Node::T(t), d));
740            }
741            for (_, x) in init_fields {
742                e!(x);
743            }
744        }
745        Expr::NewVariant {
746            fields,
747            enum_name: _,
748            variant: _,
749        } => {
750            for (_, x) in fields {
751                e!(x);
752            }
753        }
754        Expr::OptionSome { value } => e!(value),
755        Expr::WithCapacity { value, capacity } => {
756            e!(value);
757            e!(capacity);
758        }
759        Expr::Closure {
760            params,
761            body,
762            return_type,
763        } => {
764            for (_, t) in params {
765                work.push((Node::T(t), d));
766            }
767            if let Some(t) = return_type {
768                work.push((Node::T(t), d));
769            }
770            match body {
771                ClosureBody::Expression(x) => e!(x),
772                ClosureBody::Block(b) => {
773                    for s in *b {
774                        work.push((Node::S(s), d));
775                    }
776                }
777            }
778        }
779        Expr::CallExpr { callee, args } => {
780            e!(callee);
781            for a in args {
782                e!(a);
783            }
784        }
785        Expr::InterpolatedString(parts) => {
786            for part in parts {
787                match part {
788                    StringPart::Literal(_) => {}
789                    StringPart::Expr {
790                        value,
791                        format_spec: _,
792                        debug: _,
793                    } => e!(value),
794                }
795            }
796        }
797    }
798}
799
800fn push_type_children<'w, 'a>(
801    ty: &'w TypeExpr<'a>,
802    d: usize,
803    work: &mut Vec<(Node<'w, 'a>, usize)>,
804) {
805    match ty {
806        TypeExpr::Primitive(_) | TypeExpr::Named(_) => {}
807        TypeExpr::Generic { params, base: _ } => {
808            for t in *params {
809                work.push((Node::T(t), d));
810            }
811        }
812        TypeExpr::Tuple(params) => {
813            for t in *params {
814                work.push((Node::T(t), d));
815            }
816        }
817        TypeExpr::Record { field_types, .. } => {
818            for t in *field_types {
819                work.push((Node::T(t), d));
820            }
821        }
822        TypeExpr::Function { inputs, output } => {
823            for t in *inputs {
824                work.push((Node::T(t), d));
825            }
826            work.push((Node::T(output), d));
827        }
828        TypeExpr::Refinement {
829            base,
830            predicate,
831            var: _,
832        } => {
833            work.push((Node::T(base), d));
834            work.push((Node::L(predicate), d));
835        }
836        TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
837            work.push((Node::T(inner), d));
838        }
839    }
840}
841
842fn push_logic_children<'w, 'a>(
843    logic: &'w LogicExpr<'a>,
844    d: usize,
845    work: &mut Vec<(Node<'w, 'a>, usize)>,
846) {
847    macro_rules! l {
848        ($x:expr) => {
849            work.push((Node::L($x), d))
850        };
851    }
852    match logic {
853        // Terms and noun-phrase payloads nest by English sentence structure,
854        // not program size — leaves for depth purposes.
855        LogicExpr::Predicate { .. }
856        | LogicExpr::Identity { .. }
857        | LogicExpr::Metaphor { .. }
858        | LogicExpr::Atom(_)
859        | LogicExpr::Categorical(_)
860        | LogicExpr::Relation(_)
861        | LogicExpr::NeoEvent(_)
862        | LogicExpr::Comparative { .. }
863        | LogicExpr::Superlative { .. } => {}
864        LogicExpr::Quantifier { body, .. } => l!(body),
865        LogicExpr::Modal { operand, .. } => l!(operand),
866        LogicExpr::Temporal { body, .. } => l!(body),
867        LogicExpr::TemporalBinary { left, right, .. } => {
868            l!(left);
869            l!(right);
870        }
871        LogicExpr::Aspectual { body, .. } => l!(body),
872        LogicExpr::Voice { body, .. } => l!(body),
873        LogicExpr::BinaryOp { left, right, .. } => {
874            l!(left);
875            l!(right);
876        }
877        LogicExpr::UnaryOp { operand, .. } => l!(operand),
878        LogicExpr::Question { body, .. } => l!(body),
879        LogicExpr::YesNoQuestion { body } => l!(body),
880        LogicExpr::Lambda { body, .. } => l!(body),
881        LogicExpr::App { function, argument } => {
882            l!(function);
883            l!(argument);
884        }
885        LogicExpr::Intensional { content, .. } => l!(content),
886        LogicExpr::Event { predicate, .. } => l!(predicate),
887        LogicExpr::Imperative { action } => l!(action),
888        LogicExpr::Exclamative { body, .. } => l!(body),
889        LogicExpr::Optative { wish } => l!(wish),
890        LogicExpr::Implicature {
891            assertion,
892            implicature,
893        } => {
894            l!(assertion);
895            l!(implicature);
896        }
897        LogicExpr::SpeechAct { content, .. } => l!(content),
898        LogicExpr::Counterfactual {
899            antecedent,
900            consequent,
901        } => {
902            l!(antecedent);
903            l!(consequent);
904        }
905        LogicExpr::Causal { effect, cause } => {
906            l!(effect);
907            l!(cause);
908        }
909        LogicExpr::Concessive { main, concession } => {
910            l!(main);
911            l!(concession);
912        }
913        LogicExpr::Scopal { body, .. } => l!(body),
914        LogicExpr::Control { infinitive, .. } => l!(infinitive),
915        LogicExpr::Presupposition {
916            assertion,
917            presupposition,
918        } => {
919            l!(assertion);
920            l!(presupposition);
921        }
922        LogicExpr::Focus { scope, .. } => l!(scope),
923        LogicExpr::TemporalAnchor { body, .. } => l!(body),
924        LogicExpr::Distributive { predicate } => l!(predicate),
925        LogicExpr::GroupQuantifier {
926            restriction, body, ..
927        } => {
928            l!(restriction);
929            l!(body);
930        }
931    }
932}