Skip to main content

logicaffeine_compile/analysis/
callgraph.rs

1use std::collections::{HashMap, HashSet};
2
3use logicaffeine_base::{Interner, Symbol};
4use logicaffeine_language::ast::stmt::{ClosureBody, ReadSource, SelectBranch, StringPart};
5use logicaffeine_language::ast::{Expr, Stmt};
6
7/// Whole-program call graph for the LOGOS compilation pipeline.
8///
9/// Captures all direct and closure-embedded call edges between user-defined
10/// functions. Used by `ReadonlyParams` for transitive mutation detection and
11/// by liveness analysis for inter-procedural precision.
12pub struct CallGraph {
13    /// Direct call edges: fn_sym → set of directly called function symbols.
14    pub edges: HashMap<Symbol, HashSet<Symbol>>,
15    /// Set of native (extern) function symbols.
16    pub native_fns: HashSet<Symbol>,
17    /// Strongly connected components (Kosaraju's algorithm).
18    pub sccs: Vec<Vec<Symbol>>,
19}
20
21impl CallGraph {
22    /// Build the call graph from a program's top-level statements.
23    ///
24    /// Walks all `FunctionDef` bodies, collecting `Stmt::Call` and
25    /// `Expr::Call` targets, including calls inside closure bodies.
26    pub fn build(stmts: &[Stmt<'_>], _interner: &Interner) -> Self {
27        let mut edges: HashMap<Symbol, HashSet<Symbol>> = HashMap::new();
28        let mut native_fns: HashSet<Symbol> = HashSet::new();
29
30        for stmt in stmts {
31            if let Stmt::FunctionDef {
32                name,
33                body,
34                is_native,
35                ..
36            } = stmt
37            {
38                edges.entry(*name).or_default();
39                if *is_native {
40                    native_fns.insert(*name);
41                } else {
42                    let callees = edges.entry(*name).or_default();
43                    collect_calls_from_stmts(body, callees);
44                }
45            }
46        }
47
48        let sccs = compute_sccs(&edges);
49
50        Self {
51            edges,
52            native_fns,
53            sccs,
54        }
55    }
56
57    /// Returns all functions reachable from `fn_sym` via the call graph.
58    ///
59    /// Does not include `fn_sym` itself unless it is part of a cycle.
60    pub fn reachable_from(&self, fn_sym: Symbol) -> HashSet<Symbol> {
61        let mut visited = HashSet::new();
62        let mut stack = Vec::new();
63
64        if let Some(callees) = self.edges.get(&fn_sym) {
65            for &c in callees {
66                if c != fn_sym {
67                    stack.push(c);
68                }
69            }
70        }
71
72        while let Some(f) = stack.pop() {
73            if visited.insert(f) {
74                if let Some(callees) = self.edges.get(&f) {
75                    for &c in callees {
76                        if !visited.contains(&c) {
77                            stack.push(c);
78                        }
79                    }
80                }
81            }
82        }
83
84        visited
85    }
86
87    /// Returns `true` if `fn_sym` participates in a recursive cycle
88    /// (direct self-call or mutual recursion via SCC membership).
89    pub fn is_recursive(&self, fn_sym: Symbol) -> bool {
90        // Direct self-edge
91        if self
92            .edges
93            .get(&fn_sym)
94            .map(|s| s.contains(&fn_sym))
95            .unwrap_or(false)
96        {
97            return true;
98        }
99        // Mutual recursion: fn_sym is in an SCC with more than one member
100        for scc in &self.sccs {
101            if scc.len() > 1 && scc.contains(&fn_sym) {
102                return true;
103            }
104        }
105        false
106    }
107}
108
109// =============================================================================
110// Call collection from AST
111// =============================================================================
112
113/// The set of functions a block of statements calls *synchronously* (`Stmt::Call`
114/// / `Expr::Call` / closures), NOT including spawned (`LaunchTask`) targets — a
115/// spawn is a distinct concurrent thread, not a same-thread call. Used by the
116/// determinacy classifier to attribute a thread's reachable print sites.
117pub(crate) fn calls_in_stmts(stmts: &[Stmt<'_>]) -> HashSet<Symbol> {
118    let mut calls = HashSet::new();
119    collect_calls_from_stmts(stmts, &mut calls);
120    calls
121}
122
123pub(crate) fn collect_calls_from_stmts(stmts: &[Stmt<'_>], calls: &mut HashSet<Symbol>) {
124    for_each_call_site(stmts, &mut |function, _| {
125        calls.insert(function);
126    });
127}
128
129/// Every call site `stmts` holds, wherever a call can sit — statement and expression calls,
130/// closure bodies, view holes, component and route bodies — as `visit(function, arguments)`. A
131/// fetch's completion action and a store call are calls by name and carry no arguments here; a
132/// spawn's target is not a call, though its arguments are walked. The one traversal the call graph
133/// is built from.
134pub(crate) fn for_each_call_site<'a>(
135    stmts: &[Stmt<'a>],
136    visit: &mut dyn FnMut(Symbol, &[&'a Expr<'a>]),
137) {
138    for stmt in stmts {
139        walk_call_sites_stmt(stmt, visit);
140    }
141}
142
143thread_local! {
144    /// The program's functions that take `mutable` parameters, by those parameters' positions.
145    /// Installed per program by [`install_lending_parameters`].
146    static LENDING_PARAMETERS: std::cell::RefCell<HashMap<Symbol, Vec<usize>>> =
147        std::cell::RefCell::new(HashMap::new());
148}
149
150/// The functions a program built ahead of time compiles: every function that does not need a
151/// document. A function needs one when it is the browser half of a page's lowering (`__render_`,
152/// `__act_`, …, `lgx_lower::is_browser_only_lowering`), when it calls a builtin only a browser has
153/// (`BuiltinId::is_browser_only` — the DOM, a page's patch stream, storage, signals, WebRTC), or
154/// when it calls or names a function that needs one. A binary has no document, so it carries none of
155/// them: not a page's dispatcher, not vdom.lg's patch application; every other function — the
156/// author's own, the server renders, the library code they run — compiles as it always did.
157pub(crate) fn aot_compiled_functions(stmts: &[Stmt<'_>], interner: &Interner) -> HashSet<Symbol> {
158    use logicaffeine_language::ast_depth::{for_each_node, Visited};
159    let functions: HashMap<Symbol, &[Stmt<'_>]> = stmts
160        .iter()
161        .filter_map(|s| match s {
162            Stmt::FunctionDef { name, body, .. } => Some((*name, *body)),
163            _ => None,
164        })
165        .collect();
166    let browser_builtin = |f: Symbol| {
167        crate::semantics::builtins::builtin_from_name(interner.resolve(f))
168            .is_some_and(|b| b.is_browser_only())
169    };
170    let mut needs_a_document: HashSet<Symbol> = HashSet::new();
171    let mut callers: HashMap<Symbol, Vec<Symbol>> = HashMap::new();
172    for (&function, body) in &functions {
173        let mut direct = logicaffeine_language::parser::lgx_lower::is_browser_only_lowering(
174            interner.resolve(function),
175        );
176        for_each_node(body, |node| {
177            let (named, called) = match node {
178                Visited::Expr(Expr::Call { function, .. })
179                | Visited::Stmt(Stmt::Call { function, .. }) => (*function, true),
180                Visited::Expr(Expr::Identifier(sym)) => (*sym, false),
181                _ => return,
182            };
183            if functions.contains_key(&named) {
184                callers.entry(named).or_default().push(function);
185            } else if called && browser_builtin(named) {
186                direct = true;
187            }
188        });
189        if direct {
190            needs_a_document.insert(function);
191        }
192    }
193    let mut pending: Vec<Symbol> = needs_a_document.iter().copied().collect();
194    while let Some(f) = pending.pop() {
195        for caller in callers.get(&f).into_iter().flatten() {
196            if needs_a_document.insert(*caller) {
197                pending.push(*caller);
198            }
199        }
200    }
201    functions
202        .into_keys()
203        .filter(|f| !needs_a_document.contains(f))
204        .collect()
205}
206
207/// Install which positions of which of `stmts`' functions take a `mutable` parameter. A call lends
208/// the binding it passes at such a position: the callee writes it, so the call is a write of that
209/// binding — for the optimizer's write analysis and codegen's `let mut` alike, both of which ask
210/// [`lent_positions`] of the program installed here.
211pub(crate) fn install_lending_parameters(stmts: &[Stmt<'_>]) {
212    let mut lending = HashMap::new();
213    for stmt in stmts {
214        if let Stmt::FunctionDef {
215            name,
216            params,
217            is_native: false,
218            ..
219        } = stmt
220        {
221            let at: Vec<usize> = params
222                .iter()
223                .enumerate()
224                .filter(|(_, (_, ty))| {
225                    matches!(
226                        ty,
227                        logicaffeine_language::ast::stmt::TypeExpr::Mutable { .. }
228                    )
229                })
230                .map(|(i, _)| i)
231                .collect();
232            if !at.is_empty() {
233                lending.insert(*name, at);
234            }
235        }
236    }
237    LENDING_PARAMETERS.with(|l| *l.borrow_mut() = lending);
238}
239
240/// The positions of `function`'s `mutable` parameters, in the program last installed.
241pub(crate) fn lent_positions(function: Symbol) -> Vec<usize> {
242    LENDING_PARAMETERS.with(|l| l.borrow().get(&function).cloned().unwrap_or_default())
243}
244
245/// Every call site inside `expr`, itself included, as [`for_each_call_site`] visits them.
246pub(crate) fn for_each_call_site_in_expr<'a>(
247    expr: &Expr<'a>,
248    visit: &mut dyn FnMut(Symbol, &[&'a Expr<'a>]),
249) {
250    walk_call_sites_expr(expr, visit);
251}
252
253fn walk_call_sites_stmt<'a>(stmt: &Stmt<'a>, visit: &mut dyn FnMut(Symbol, &[&'a Expr<'a>])) {
254    match stmt {
255        Stmt::ComponentDef(def) => {
256            for f in &def.state {
257                walk_call_sites_expr(f.init, visit);
258            }
259            for ev in &def.events {
260                for_each_call_site(ev.body, visit);
261            }
262            for a in &def.actions {
263                for_each_call_site(a.body, visit);
264            }
265            if let Some(view) = &def.view {
266                let (view_exprs, view_blocks) = view.exprs_and_blocks();
267                for e in view_exprs {
268                    walk_call_sites_expr(e, visit);
269                }
270                for b in view_blocks {
271                    for_each_call_site(b, visit);
272                }
273            }
274        }
275        Stmt::DirectiveDef { body, removed, .. } => {
276            for_each_call_site(body, visit);
277            if let Some(r) = removed {
278                for_each_call_site(r, visit);
279            }
280        }
281        Stmt::RouteDef { body, .. } => match &**body {
282            logicaffeine_language::ast::component::RouteBody::Statements(b) => {
283                for_each_call_site(b, visit)
284            }
285            logicaffeine_language::ast::component::RouteBody::View(view) => {
286                let (view_exprs, view_blocks) = view.exprs_and_blocks();
287                for e in view_exprs {
288                    walk_call_sites_expr(e, visit);
289                }
290                for b in view_blocks {
291                    for_each_call_site(b, visit);
292                }
293            }
294        },
295        Stmt::MiddlewareDef { body, .. } => for_each_call_site(body, visit),
296        Stmt::RedirectDef { .. } => {}
297        // A fetch's completion action and a store call are CALLS by name.
298        Stmt::Fetch {
299            url, body, then, ..
300        } => {
301            visit(*then, &[]);
302            walk_call_sites_expr(url, visit);
303            if let Some(b) = body {
304                walk_call_sites_expr(b, visit);
305            }
306        }
307        Stmt::Ui(u) => {
308            if let logicaffeine_language::ast::stmt::UiStmt::CallStore { action, .. } = u {
309                visit(*action, &[]);
310            }
311            for x in u.exprs() {
312                walk_call_sites_expr(x, visit);
313            }
314        }
315        Stmt::Call { function, args } => {
316            visit(*function, args);
317            for arg in args {
318                walk_call_sites_expr(arg, visit);
319            }
320        }
321        Stmt::Let { value, .. } => walk_call_sites_expr(value, visit),
322        Stmt::Set { value, .. } => walk_call_sites_expr(value, visit),
323        Stmt::Return { value: Some(v) } => walk_call_sites_expr(v, visit),
324        Stmt::If {
325            cond,
326            then_block,
327            else_block,
328        } => {
329            walk_call_sites_expr(cond, visit);
330            for_each_call_site(then_block, visit);
331            if let Some(else_b) = else_block {
332                for_each_call_site(else_b, visit);
333            }
334        }
335        Stmt::While {
336            cond,
337            body,
338            decreasing,
339        } => {
340            walk_call_sites_expr(cond, visit);
341            for_each_call_site(body, visit);
342            if let Some(d) = decreasing {
343                walk_call_sites_expr(d, visit);
344            }
345        }
346        Stmt::Repeat { iterable, body, .. } => {
347            walk_call_sites_expr(iterable, visit);
348            for_each_call_site(body, visit);
349        }
350        Stmt::Push { value, collection } => {
351            walk_call_sites_expr(value, visit);
352            walk_call_sites_expr(collection, visit);
353        }
354        Stmt::Pop { collection, .. } => walk_call_sites_expr(collection, visit),
355        Stmt::Add { value, collection } => {
356            walk_call_sites_expr(value, visit);
357            walk_call_sites_expr(collection, visit);
358        }
359        Stmt::Remove { value, collection } => {
360            walk_call_sites_expr(value, visit);
361            walk_call_sites_expr(collection, visit);
362        }
363        Stmt::SetIndex {
364            collection,
365            index,
366            value,
367        } => {
368            walk_call_sites_expr(collection, visit);
369            walk_call_sites_expr(index, visit);
370            walk_call_sites_expr(value, visit);
371        }
372        Stmt::SetField { object, value, .. } => {
373            walk_call_sites_expr(object, visit);
374            walk_call_sites_expr(value, visit);
375        }
376        Stmt::Inspect { target, arms, .. } => {
377            walk_call_sites_expr(target, visit);
378            for arm in arms {
379                for_each_call_site(arm.body, visit);
380            }
381        }
382        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
383            for_each_call_site(tasks, visit);
384        }
385        Stmt::Zone { body, .. } => for_each_call_site(body, visit),
386        // Expression-bearing statements whose operands can contain calls. Notably
387        // `Show` (the primary Main-body output form) — omitting these left calls
388        // there invisible to callers of this walk (e.g. per-file scope checking).
389        Stmt::Show { object, recipient } | Stmt::Give { object, recipient } => {
390            walk_call_sites_expr(object, visit);
391            walk_call_sites_expr(recipient, visit);
392        }
393        Stmt::RuntimeAssert { condition, .. } => walk_call_sites_expr(condition, visit),
394        // A scope-transparent desugar sequence: its body runs in the enclosing
395        // scope, so its calls are this statement's calls.
396        Stmt::Splice { body } | Stmt::Reversibly { body } => for_each_call_site(body, visit),
397        // Test-family statements — their operands and bodies bear calls that a
398        // per-file scope check must see (a leaked reference is just as invalid
399        // inside a `## Test` as in Main).
400        Stmt::TestDef { body, cases, .. } => {
401            for_each_call_site(body, visit);
402            if let Some(table) = cases {
403                for row in &table.rows {
404                    for cell in row {
405                        walk_call_sites_expr(cell, visit);
406                    }
407                }
408            }
409        }
410        Stmt::Expect { condition } => walk_call_sites_expr(condition, visit),
411        Stmt::ExpectFail { body, .. } => for_each_call_site(body, visit),
412        Stmt::AdvanceTime { millis } => walk_call_sites_expr(millis, visit),
413        Stmt::Observe { payloads, .. } => {
414            for (_, value) in payloads {
415                walk_call_sites_expr(value, visit);
416            }
417        }
418        Stmt::During { body, .. } => for_each_call_site(body, visit),
419        Stmt::ForAll {
420            constraint, body, ..
421        } => {
422            if let Some(c) = constraint {
423                walk_call_sites_expr(c, visit);
424            }
425            for_each_call_site(body, visit);
426        }
427        // I/O and networking — every operand is evaluated same-thread.
428        Stmt::ReadFrom { source, .. } => {
429            if let ReadSource::File(path) = source {
430                walk_call_sites_expr(path, visit);
431            }
432        }
433        Stmt::WriteFile { content, path } => {
434            walk_call_sites_expr(content, visit);
435            walk_call_sites_expr(path, visit);
436        }
437        Stmt::SendMessage {
438            message,
439            destination,
440            ..
441        } => {
442            walk_call_sites_expr(message, visit);
443            walk_call_sites_expr(destination, visit);
444        }
445        Stmt::AwaitMessage { source, .. } => walk_call_sites_expr(source, visit),
446        Stmt::StreamMessage {
447            values,
448            destination,
449        } => {
450            walk_call_sites_expr(values, visit);
451            walk_call_sites_expr(destination, visit);
452        }
453        Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
454            walk_call_sites_expr(source, visit);
455            walk_call_sites_expr(target, visit);
456        }
457        Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
458            walk_call_sites_expr(object, visit);
459            walk_call_sites_expr(amount, visit);
460        }
461        Stmt::AppendToSequence { sequence, value } => {
462            walk_call_sites_expr(sequence, visit);
463            walk_call_sites_expr(value, visit);
464        }
465        Stmt::ResolveConflict { object, value, .. } => {
466            walk_call_sites_expr(object, visit);
467            walk_call_sites_expr(value, visit);
468        }
469        Stmt::Listen { address, .. } | Stmt::ConnectTo { address, .. } => {
470            walk_call_sites_expr(address, visit);
471        }
472        Stmt::Serve { port, handler } => {
473            walk_call_sites_expr(port, visit);
474            walk_call_sites_expr(handler, visit);
475        }
476        Stmt::LetPeerAgent { address, .. } => walk_call_sites_expr(address, visit),
477        Stmt::Sleep { milliseconds } => walk_call_sites_expr(milliseconds, visit),
478        Stmt::Sync { topic, .. } => walk_call_sites_expr(topic, visit),
479        Stmt::Mount { path, .. } => walk_call_sites_expr(path, visit),
480        // Green-thread pipes: operands are same-thread; the SPAWN targets of
481        // `LaunchTask`/`LaunchTaskWithHandle` are deliberately NOT treated as
482        // call edges (a spawn is a distinct thread, per `calls_in_stmts`), but
483        // their arguments ARE evaluated here and must be walked.
484        Stmt::LaunchTask { args, .. } | Stmt::LaunchTaskWithHandle { args, .. } => {
485            for arg in args {
486                walk_call_sites_expr(arg, visit);
487            }
488        }
489        Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
490            walk_call_sites_expr(value, visit);
491            walk_call_sites_expr(pipe, visit);
492        }
493        Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
494            walk_call_sites_expr(pipe, visit);
495        }
496        Stmt::StopTask { handle } => walk_call_sites_expr(handle, visit),
497        Stmt::Select { branches } => {
498            for branch in branches {
499                match branch {
500                    SelectBranch::Receive { pipe, body, .. } => {
501                        walk_call_sites_expr(pipe, visit);
502                        for_each_call_site(body, visit);
503                    }
504                    SelectBranch::Timeout { milliseconds, body } => {
505                        walk_call_sites_expr(milliseconds, visit);
506                        for_each_call_site(body, visit);
507                    }
508                }
509            }
510        }
511        _ => {}
512    }
513}
514
515fn walk_call_sites_expr<'a>(expr: &Expr<'a>, visit: &mut dyn FnMut(Symbol, &[&'a Expr<'a>])) {
516    match expr {
517        Expr::Dom(q) => {
518            if let Some(sel) = q.selector() {
519                walk_call_sites_expr(sel, visit);
520            }
521        }
522        Expr::View(v) => {
523            let (view_exprs, view_blocks) = v.exprs_and_blocks();
524            for e in view_exprs {
525                walk_call_sites_expr(e, visit);
526            }
527            for b in view_blocks {
528                for_each_call_site(b, visit);
529            }
530        }
531        Expr::Call { function, args } => {
532            visit(*function, args);
533            for arg in args {
534                walk_call_sites_expr(arg, visit);
535            }
536        }
537        Expr::Closure { body, .. } => match body {
538            ClosureBody::Expression(e) => walk_call_sites_expr(e, visit),
539            ClosureBody::Block(stmts) => for_each_call_site(stmts, visit),
540        },
541        Expr::BinaryOp { left, right, .. } => {
542            walk_call_sites_expr(left, visit);
543            walk_call_sites_expr(right, visit);
544        }
545        Expr::Index { collection, index } => {
546            walk_call_sites_expr(collection, visit);
547            walk_call_sites_expr(index, visit);
548        }
549        Expr::Slice {
550            collection,
551            start,
552            end,
553        } => {
554            walk_call_sites_expr(collection, visit);
555            walk_call_sites_expr(start, visit);
556            walk_call_sites_expr(end, visit);
557        }
558        Expr::Length { collection } => walk_call_sites_expr(collection, visit),
559        Expr::Contains { collection, value } => {
560            walk_call_sites_expr(collection, visit);
561            walk_call_sites_expr(value, visit);
562        }
563        Expr::Union { left, right } | Expr::Intersection { left, right } => {
564            walk_call_sites_expr(left, visit);
565            walk_call_sites_expr(right, visit);
566        }
567        Expr::FieldAccess { object, .. } => walk_call_sites_expr(object, visit),
568        Expr::List(items) | Expr::Tuple(items) => {
569            for item in items {
570                walk_call_sites_expr(item, visit);
571            }
572        }
573        Expr::Range { start, end } => {
574            walk_call_sites_expr(start, visit);
575            walk_call_sites_expr(end, visit);
576        }
577        Expr::Copy { expr } | Expr::Give { value: expr } => {
578            walk_call_sites_expr(expr, visit);
579        }
580        Expr::OptionSome { value } => walk_call_sites_expr(value, visit),
581        Expr::WithCapacity { value, capacity } => {
582            walk_call_sites_expr(value, visit);
583            walk_call_sites_expr(capacity, visit);
584        }
585        Expr::CallExpr { callee, args } => {
586            walk_call_sites_expr(callee, visit);
587            for arg in args {
588                walk_call_sites_expr(arg, visit);
589            }
590        }
591        Expr::Not { operand } => walk_call_sites_expr(operand, visit),
592        Expr::ManifestOf { zone } => walk_call_sites_expr(zone, visit),
593        Expr::ChunkAt { index, zone } => {
594            walk_call_sites_expr(index, visit);
595            walk_call_sites_expr(zone, visit);
596        }
597        // A `{f(x)}` hole is a real call — one that carries the component View's
598        // policy calls — and was previously dropped by the wildcard arm, so the
599        // per-file scope check never saw it. The `New`/`NewVariant` field values
600        // are ordinary expressions too and can hold calls.
601        Expr::InterpolatedString(parts) => {
602            for part in parts {
603                if let StringPart::Expr { value, .. } = part {
604                    walk_call_sites_expr(value, visit);
605                }
606            }
607        }
608        Expr::New { init_fields, .. } => {
609            for (_, value) in init_fields {
610                walk_call_sites_expr(value, visit);
611            }
612        }
613        Expr::NewVariant { fields, .. } => {
614            for (_, value) in fields {
615                walk_call_sites_expr(value, visit);
616            }
617        }
618        // Leaves and non-expression-bearing forms carry no call site. Kept
619        // EXHAUSTIVE (no wildcard) so a new `Expr` variant with an embedded
620        // expression fails this build until its call positions are wired.
621        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone | Expr::Escape { .. } => {}
622    }
623}
624
625// =============================================================================
626// Type-reference collection (for per-file privacy of TYPES)
627// =============================================================================
628
629/// Every user-type name a block of statements REFERENCES — constructions
630/// (`a new Point`), enum constructions, and type annotations. Used by the per-file
631/// scope check to gate a `private` type: a reference to it from any file other
632/// than its owner is rejected, exactly like a private function call. The traversal
633/// mirrors the call walk so no reference position is missed.
634pub(crate) fn collect_type_refs_from_stmts(stmts: &[Stmt<'_>], types: &mut HashSet<Symbol>) {
635    for stmt in stmts {
636        collect_type_refs_from_stmt(stmt, types);
637    }
638}
639
640pub(crate) fn type_names_in_type_expr(
641    ty: &logicaffeine_language::ast::stmt::TypeExpr<'_>,
642    types: &mut HashSet<Symbol>,
643) {
644    use logicaffeine_language::ast::stmt::TypeExpr;
645    match ty {
646        // `Named` is a user-defined type; `Primitive` (Int/Text/…) never is.
647        TypeExpr::Named(sym) => {
648            types.insert(*sym);
649        }
650        TypeExpr::Generic { base, params } => {
651            types.insert(*base);
652            for p in params.iter() {
653                type_names_in_type_expr(p, types);
654            }
655        }
656        TypeExpr::Tuple(params) => {
657            for p in params.iter() {
658                type_names_in_type_expr(p, types);
659            }
660        }
661        TypeExpr::Record { field_types, .. } => {
662            for p in field_types.iter() {
663                type_names_in_type_expr(p, types);
664            }
665        }
666        TypeExpr::Function { inputs, output } => {
667            for i in inputs.iter() {
668                type_names_in_type_expr(i, types);
669            }
670            type_names_in_type_expr(output, types);
671        }
672        TypeExpr::Refinement { base, .. } => type_names_in_type_expr(base, types),
673        TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
674            type_names_in_type_expr(inner, types)
675        }
676        TypeExpr::Primitive(_) => {}
677    }
678}
679
680fn collect_type_refs_from_stmt(stmt: &Stmt<'_>, types: &mut HashSet<Symbol>) {
681    match stmt {
682        Stmt::ComponentDef(def) => {
683            for (_, t) in &def.props {
684                type_names_in_type_expr(t, types);
685            }
686            for f in &def.state {
687                if let Some(t) = f.ty {
688                    type_names_in_type_expr(t, types);
689                }
690                collect_type_refs_from_expr(f.init, types);
691            }
692            for ev in &def.events {
693                for s in ev.body.iter() {
694                    collect_type_refs_from_stmt(s, types);
695                }
696            }
697            for a in &def.actions {
698                for (_, t) in &a.params {
699                    type_names_in_type_expr(t, types);
700                }
701                for s in a.body.iter() {
702                    collect_type_refs_from_stmt(s, types);
703                }
704            }
705            if let Some(view) = &def.view {
706                let (view_exprs, view_blocks) = view.exprs_and_blocks();
707                for e in view_exprs {
708                    collect_type_refs_from_expr(e, types);
709                }
710                for b in view_blocks {
711                    for s in b.iter() {
712                        collect_type_refs_from_stmt(s, types);
713                    }
714                }
715            }
716        }
717        Stmt::DirectiveDef {
718            params,
719            body,
720            removed,
721            ..
722        } => {
723            for (_, t) in params {
724                type_names_in_type_expr(t, types);
725            }
726            for s in body.iter() {
727                collect_type_refs_from_stmt(s, types);
728            }
729            if let Some(r) = removed {
730                for s in r.iter() {
731                    collect_type_refs_from_stmt(s, types);
732                }
733            }
734        }
735        Stmt::RouteDef {
736            params,
737            return_type,
738            body,
739            ..
740        } => {
741            for (_, t) in params {
742                type_names_in_type_expr(t, types);
743            }
744            if let Some(t) = return_type {
745                type_names_in_type_expr(t, types);
746            }
747            match &**body {
748                logicaffeine_language::ast::component::RouteBody::Statements(b) => {
749                    for s in b.iter() {
750                        collect_type_refs_from_stmt(s, types);
751                    }
752                }
753                logicaffeine_language::ast::component::RouteBody::View(view) => {
754                    let (view_exprs, view_blocks) = view.exprs_and_blocks();
755                    for e in view_exprs {
756                        collect_type_refs_from_expr(e, types);
757                    }
758                    for b in view_blocks {
759                        for s in b.iter() {
760                            collect_type_refs_from_stmt(s, types);
761                        }
762                    }
763                }
764            }
765        }
766        Stmt::MiddlewareDef { param, body } => {
767            type_names_in_type_expr(param.1, types);
768            for s in body.iter() {
769                collect_type_refs_from_stmt(s, types);
770            }
771        }
772        Stmt::RedirectDef { .. } => {}
773        Stmt::Fetch {
774            url, body, as_type, ..
775        } => {
776            type_names_in_type_expr(as_type, types);
777            collect_type_refs_from_expr(url, types);
778            if let Some(b) = body {
779                collect_type_refs_from_expr(b, types);
780            }
781        }
782        Stmt::Ui(u) => {
783            for x in u.exprs() {
784                collect_type_refs_from_expr(x, types);
785            }
786        }
787        Stmt::Call { args, .. } => {
788            for arg in args {
789                collect_type_refs_from_expr(arg, types);
790            }
791        }
792        Stmt::Let { value, ty, .. } => {
793            collect_type_refs_from_expr(value, types);
794            if let Some(t) = ty {
795                type_names_in_type_expr(t, types);
796            }
797        }
798        Stmt::Set { value, .. } => collect_type_refs_from_expr(value, types),
799        Stmt::Return { value: Some(v) } => collect_type_refs_from_expr(v, types),
800        Stmt::If {
801            cond,
802            then_block,
803            else_block,
804        } => {
805            collect_type_refs_from_expr(cond, types);
806            collect_type_refs_from_stmts(then_block, types);
807            if let Some(else_b) = else_block {
808                collect_type_refs_from_stmts(else_b, types);
809            }
810        }
811        Stmt::While {
812            cond,
813            body,
814            decreasing,
815        } => {
816            collect_type_refs_from_expr(cond, types);
817            collect_type_refs_from_stmts(body, types);
818            if let Some(d) = decreasing {
819                collect_type_refs_from_expr(d, types);
820            }
821        }
822        Stmt::Repeat { iterable, body, .. } => {
823            collect_type_refs_from_expr(iterable, types);
824            collect_type_refs_from_stmts(body, types);
825        }
826        Stmt::Push { value, collection }
827        | Stmt::Add { value, collection }
828        | Stmt::Remove { value, collection } => {
829            collect_type_refs_from_expr(value, types);
830            collect_type_refs_from_expr(collection, types);
831        }
832        Stmt::Pop { collection, .. } => collect_type_refs_from_expr(collection, types),
833        Stmt::SetIndex {
834            collection,
835            index,
836            value,
837        } => {
838            collect_type_refs_from_expr(collection, types);
839            collect_type_refs_from_expr(index, types);
840            collect_type_refs_from_expr(value, types);
841        }
842        Stmt::SetField { object, value, .. } => {
843            collect_type_refs_from_expr(object, types);
844            collect_type_refs_from_expr(value, types);
845        }
846        Stmt::Inspect { target, arms, .. } => {
847            collect_type_refs_from_expr(target, types);
848            for arm in arms {
849                collect_type_refs_from_stmts(arm.body, types);
850            }
851        }
852        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
853            collect_type_refs_from_stmts(tasks, types)
854        }
855        Stmt::Zone { body, .. }
856        | Stmt::Splice { body }
857        | Stmt::During { body, .. }
858        | Stmt::Reversibly { body } => collect_type_refs_from_stmts(body, types),
859        Stmt::Show { object, recipient } | Stmt::Give { object, recipient } => {
860            collect_type_refs_from_expr(object, types);
861            collect_type_refs_from_expr(recipient, types);
862        }
863        Stmt::RuntimeAssert { condition, .. } | Stmt::Expect { condition } => {
864            collect_type_refs_from_expr(condition, types)
865        }
866        Stmt::TestDef { body, cases, .. } => {
867            collect_type_refs_from_stmts(body, types);
868            if let Some(table) = cases {
869                for row in &table.rows {
870                    for cell in row {
871                        collect_type_refs_from_expr(cell, types);
872                    }
873                }
874            }
875        }
876        Stmt::ExpectFail { body, .. } => collect_type_refs_from_stmts(body, types),
877        Stmt::AdvanceTime { millis } => collect_type_refs_from_expr(millis, types),
878        Stmt::Observe { payloads, .. } => {
879            for (_, value) in payloads {
880                collect_type_refs_from_expr(value, types);
881            }
882        }
883        Stmt::ForAll {
884            constraint, body, ..
885        } => {
886            if let Some(c) = constraint {
887                collect_type_refs_from_expr(c, types);
888            }
889            collect_type_refs_from_stmts(body, types);
890        }
891        Stmt::ReadFrom { source, .. } => {
892            if let ReadSource::File(path) = source {
893                collect_type_refs_from_expr(path, types);
894            }
895        }
896        Stmt::WriteFile { content, path } => {
897            collect_type_refs_from_expr(content, types);
898            collect_type_refs_from_expr(path, types);
899        }
900        Stmt::SendMessage {
901            message,
902            destination,
903            ..
904        } => {
905            collect_type_refs_from_expr(message, types);
906            collect_type_refs_from_expr(destination, types);
907        }
908        Stmt::AwaitMessage { source, .. } => collect_type_refs_from_expr(source, types),
909        Stmt::StreamMessage {
910            values,
911            destination,
912        } => {
913            collect_type_refs_from_expr(values, types);
914            collect_type_refs_from_expr(destination, types);
915        }
916        Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
917            collect_type_refs_from_expr(source, types);
918            collect_type_refs_from_expr(target, types);
919        }
920        Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
921            collect_type_refs_from_expr(object, types);
922            collect_type_refs_from_expr(amount, types);
923        }
924        Stmt::AppendToSequence { sequence, value } => {
925            collect_type_refs_from_expr(sequence, types);
926            collect_type_refs_from_expr(value, types);
927        }
928        Stmt::ResolveConflict { object, value, .. } => {
929            collect_type_refs_from_expr(object, types);
930            collect_type_refs_from_expr(value, types);
931        }
932        Stmt::Listen { address, .. }
933        | Stmt::ConnectTo { address, .. }
934        | Stmt::LetPeerAgent { address, .. } => collect_type_refs_from_expr(address, types),
935        Stmt::Serve { port, handler } => {
936            collect_type_refs_from_expr(port, types);
937            collect_type_refs_from_expr(handler, types);
938        }
939        Stmt::Sleep { milliseconds } => collect_type_refs_from_expr(milliseconds, types),
940        Stmt::Sync { topic, .. } => collect_type_refs_from_expr(topic, types),
941        Stmt::Mount { path, .. } => collect_type_refs_from_expr(path, types),
942        Stmt::LaunchTask { args, .. } | Stmt::LaunchTaskWithHandle { args, .. } => {
943            for arg in args {
944                collect_type_refs_from_expr(arg, types);
945            }
946        }
947        Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
948            collect_type_refs_from_expr(value, types);
949            collect_type_refs_from_expr(pipe, types);
950        }
951        Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
952            collect_type_refs_from_expr(pipe, types)
953        }
954        Stmt::StopTask { handle } => collect_type_refs_from_expr(handle, types),
955        Stmt::Select { branches } => {
956            for branch in branches {
957                match branch {
958                    SelectBranch::Receive { pipe, body, .. } => {
959                        collect_type_refs_from_expr(pipe, types);
960                        collect_type_refs_from_stmts(body, types);
961                    }
962                    SelectBranch::Timeout { milliseconds, body } => {
963                        collect_type_refs_from_expr(milliseconds, types);
964                        collect_type_refs_from_stmts(body, types);
965                    }
966                }
967            }
968        }
969        _ => {}
970    }
971}
972
973fn collect_type_refs_from_expr(expr: &Expr<'_>, types: &mut HashSet<Symbol>) {
974    match expr {
975        Expr::Dom(q) => {
976            if let Some(sel) = q.selector() {
977                collect_type_refs_from_expr(sel, types);
978            }
979        }
980        Expr::View(v) => {
981            let (view_exprs, view_blocks) = v.exprs_and_blocks();
982            for e in view_exprs {
983                collect_type_refs_from_expr(e, types);
984            }
985            for b in view_blocks {
986                for s in b.iter() {
987                    collect_type_refs_from_stmt(s, types);
988                }
989            }
990        }
991        Expr::New {
992            type_name,
993            type_args,
994            init_fields,
995        } => {
996            types.insert(*type_name);
997            for t in type_args.iter() {
998                type_names_in_type_expr(t, types);
999            }
1000            for (_, value) in init_fields {
1001                collect_type_refs_from_expr(value, types);
1002            }
1003        }
1004        Expr::NewVariant {
1005            enum_name, fields, ..
1006        } => {
1007            types.insert(*enum_name);
1008            for (_, value) in fields {
1009                collect_type_refs_from_expr(value, types);
1010            }
1011        }
1012        Expr::Call { args, .. } => {
1013            for arg in args {
1014                collect_type_refs_from_expr(arg, types);
1015            }
1016        }
1017        Expr::Closure { body, .. } => match body {
1018            ClosureBody::Expression(e) => collect_type_refs_from_expr(e, types),
1019            ClosureBody::Block(stmts) => collect_type_refs_from_stmts(stmts, types),
1020        },
1021        Expr::BinaryOp { left, right, .. } => {
1022            collect_type_refs_from_expr(left, types);
1023            collect_type_refs_from_expr(right, types);
1024        }
1025        Expr::Index { collection, index } => {
1026            collect_type_refs_from_expr(collection, types);
1027            collect_type_refs_from_expr(index, types);
1028        }
1029        Expr::Slice {
1030            collection,
1031            start,
1032            end,
1033        } => {
1034            collect_type_refs_from_expr(collection, types);
1035            collect_type_refs_from_expr(start, types);
1036            collect_type_refs_from_expr(end, types);
1037        }
1038        Expr::Length { collection } => collect_type_refs_from_expr(collection, types),
1039        Expr::Contains { collection, value } => {
1040            collect_type_refs_from_expr(collection, types);
1041            collect_type_refs_from_expr(value, types);
1042        }
1043        Expr::Union { left, right } | Expr::Intersection { left, right } => {
1044            collect_type_refs_from_expr(left, types);
1045            collect_type_refs_from_expr(right, types);
1046        }
1047        Expr::FieldAccess { object, .. } => collect_type_refs_from_expr(object, types),
1048        Expr::List(items) | Expr::Tuple(items) => {
1049            for item in items {
1050                collect_type_refs_from_expr(item, types);
1051            }
1052        }
1053        Expr::Range { start, end } => {
1054            collect_type_refs_from_expr(start, types);
1055            collect_type_refs_from_expr(end, types);
1056        }
1057        Expr::Copy { expr } | Expr::Give { value: expr } => {
1058            collect_type_refs_from_expr(expr, types)
1059        }
1060        Expr::OptionSome { value } => collect_type_refs_from_expr(value, types),
1061        Expr::WithCapacity { value, capacity } => {
1062            collect_type_refs_from_expr(value, types);
1063            collect_type_refs_from_expr(capacity, types);
1064        }
1065        Expr::CallExpr { callee, args } => {
1066            collect_type_refs_from_expr(callee, types);
1067            for arg in args {
1068                collect_type_refs_from_expr(arg, types);
1069            }
1070        }
1071        Expr::Not { operand } => collect_type_refs_from_expr(operand, types),
1072        Expr::ManifestOf { zone } => collect_type_refs_from_expr(zone, types),
1073        Expr::ChunkAt { index, zone } => {
1074            collect_type_refs_from_expr(index, types);
1075            collect_type_refs_from_expr(zone, types);
1076        }
1077        // A `{a new Point}` hole references a type just like a bare construction;
1078        // the wildcard arm used to drop it, leaking a private type used only in a
1079        // component's interpolated view. Kept EXHAUSTIVE (no wildcard) so a new
1080        // expression variant fails this build until its type positions are wired.
1081        Expr::InterpolatedString(parts) => {
1082            for part in parts {
1083                if let StringPart::Expr { value, .. } = part {
1084                    collect_type_refs_from_expr(value, types);
1085                }
1086            }
1087        }
1088        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone | Expr::Escape { .. } => {}
1089    }
1090}
1091
1092/// The records and enums the program's generated code defines: every one its registry holds except
1093/// a compiler-provided struct (`TypeRegistry::is_builtin_struct`, `HttpError`/`File`) the program
1094/// never names — in its own type references (a construction, an annotation), or in a field of a type
1095/// it defines. The one answer the AOT-Rust and C emitters share, so a program pays for a builtin
1096/// struct only when it uses one.
1097pub(crate) fn program_type_defs(
1098    stmts: &[Stmt<'_>],
1099    registry: &crate::analysis::TypeRegistry,
1100) -> HashSet<Symbol> {
1101    use crate::analysis::TypeDef;
1102    let mut named = HashSet::new();
1103    collect_type_refs_from_stmts(stmts, &mut named);
1104    let mut defined: HashSet<Symbol> = registry
1105        .iter_types()
1106        .filter(|(sym, def)| {
1107            matches!(def, TypeDef::Struct { .. } | TypeDef::Enum { .. })
1108                && (!registry.is_builtin_struct(**sym) || named.contains(*sym))
1109        })
1110        .map(|(sym, _)| *sym)
1111        .collect();
1112    loop {
1113        let mut reached = HashSet::new();
1114        for sym in &defined {
1115            let fields: Vec<&crate::analysis::FieldType> = match registry.get(*sym) {
1116                Some(TypeDef::Struct { fields, .. }) => fields.iter().map(|f| &f.ty).collect(),
1117                Some(TypeDef::Enum { variants, .. }) => variants
1118                    .iter()
1119                    .flat_map(|v| v.fields.iter().map(|f| &f.ty))
1120                    .collect(),
1121                _ => Vec::new(),
1122            };
1123            for ty in fields {
1124                field_type_names(ty, &mut reached);
1125            }
1126        }
1127        let before = defined.len();
1128        defined.extend(
1129            reached
1130                .into_iter()
1131                .filter(|sym| registry.is_builtin_struct(*sym)),
1132        );
1133        if defined.len() == before {
1134            return defined;
1135        }
1136    }
1137}
1138
1139/// Every type name a registry field type mentions.
1140fn field_type_names(ty: &crate::analysis::FieldType, names: &mut HashSet<Symbol>) {
1141    use crate::analysis::FieldType;
1142    match ty {
1143        FieldType::Primitive(sym) | FieldType::Named(sym) | FieldType::TypeParam(sym) => {
1144            names.insert(*sym);
1145        }
1146        FieldType::Generic { base, params } => {
1147            names.insert(*base);
1148            for p in params {
1149                field_type_names(p, names);
1150            }
1151        }
1152        FieldType::Tuple(items) => {
1153            for t in items {
1154                field_type_names(t, names);
1155            }
1156        }
1157        FieldType::Record(fields) => {
1158            for (_, t) in fields {
1159                field_type_names(t, names);
1160            }
1161        }
1162    }
1163}
1164
1165// =============================================================================
1166// Kosaraju's SCC algorithm
1167// =============================================================================
1168
1169fn compute_sccs(edges: &HashMap<Symbol, HashSet<Symbol>>) -> Vec<Vec<Symbol>> {
1170    let nodes: Vec<Symbol> = edges.keys().copied().collect();
1171
1172    // Step 1: DFS on forward graph to compute finish order
1173    let mut visited: HashSet<Symbol> = HashSet::new();
1174    let mut finish_order: Vec<Symbol> = Vec::new();
1175
1176    for &v in &nodes {
1177        if !visited.contains(&v) {
1178            dfs_finish(v, edges, &mut visited, &mut finish_order);
1179        }
1180    }
1181
1182    // Step 2: Build reversed graph
1183    let mut rev_edges: HashMap<Symbol, HashSet<Symbol>> = HashMap::new();
1184    for (&src, callees) in edges {
1185        for &dst in callees {
1186            rev_edges.entry(dst).or_default().insert(src);
1187        }
1188    }
1189
1190    // Step 3: DFS on reversed graph in reverse finish order to collect SCCs
1191    let mut visited2: HashSet<Symbol> = HashSet::new();
1192    let mut sccs: Vec<Vec<Symbol>> = Vec::new();
1193
1194    for &v in finish_order.iter().rev() {
1195        if !visited2.contains(&v) {
1196            let mut scc = Vec::new();
1197            dfs_collect(v, &rev_edges, &mut visited2, &mut scc);
1198            sccs.push(scc);
1199        }
1200    }
1201
1202    sccs
1203}
1204
1205fn dfs_finish(
1206    v: Symbol,
1207    edges: &HashMap<Symbol, HashSet<Symbol>>,
1208    visited: &mut HashSet<Symbol>,
1209    finish_order: &mut Vec<Symbol>,
1210) {
1211    if !visited.insert(v) {
1212        return;
1213    }
1214    if let Some(callees) = edges.get(&v) {
1215        for &callee in callees {
1216            dfs_finish(callee, edges, visited, finish_order);
1217        }
1218    }
1219    finish_order.push(v);
1220}
1221
1222fn dfs_collect(
1223    v: Symbol,
1224    edges: &HashMap<Symbol, HashSet<Symbol>>,
1225    visited: &mut HashSet<Symbol>,
1226    scc: &mut Vec<Symbol>,
1227) {
1228    if !visited.insert(v) {
1229        return;
1230    }
1231    scc.push(v);
1232    if let Some(callees) = edges.get(&v) {
1233        for &callee in callees {
1234            dfs_collect(callee, edges, visited, scc);
1235        }
1236    }
1237}