Skip to main content

logicaffeine_compile/codegen/
detection.rs

1use std::collections::{HashMap, HashSet};
2
3use crate::analysis::registry::{FieldType, TypeDef, TypeRegistry};
4use crate::ast::stmt::{Expr, Literal, ReadSource, Stmt, TypeExpr};
5use crate::intern::{Interner, Symbol};
6
7use super::field_is_boxed;
8use super::types::codegen_type_expr;
9
10pub(super) fn is_result_type(ty: &TypeExpr, interner: &Interner) -> bool {
11    if let TypeExpr::Generic { base, .. } = ty {
12        interner.resolve(*base) == "Result"
13    } else {
14        false
15    }
16}
17
18/// Whether the program serves HTTP requests: a `Serve` anywhere in it, at the top level or in a function.
19pub(super) fn serves(stmts: &[Stmt]) -> bool {
20    let mut found = false;
21    logicaffeine_language::ast_depth::for_each_node(stmts, |node| {
22        if let logicaffeine_language::ast_depth::Visited::Stmt(Stmt::Serve { .. }) = node {
23            found = true;
24        }
25    });
26    found
27}
28
29/// Phase 51: Detect if any statements require async execution.
30/// Returns true if the program needs #[tokio::main] async fn main().
31pub(super) fn requires_async(stmts: &[Stmt]) -> bool {
32    stmts.iter().any(|s| requires_async_stmt(s))
33}
34
35pub(super) fn requires_async_stmt(stmt: &Stmt) -> bool {
36    match stmt {
37        // Phase 9: Concurrent blocks use tokio::join!
38        Stmt::Concurrent { tasks: _ } => true,
39        // Phase 51: Network operations and Sleep are async
40        Stmt::Listen { .. } => true,
41        Stmt::ConnectTo { .. } => true,
42        // HTTP server binds a tokio listener and awaits per-request handling.
43        Stmt::Serve { .. } => true,
44        Stmt::Sleep { .. } => true,
45        // Phase 52: Sync is async (GossipSub subscription)
46        Stmt::Sync { .. } => true,
47        // Phase 53: Mount is async (VFS file operations)
48        Stmt::Mount { .. } => true,
49        // Phase 53: File I/O is async (VFS operations)
50        Stmt::ReadFrom {
51            source: ReadSource::File(_),
52            ..
53        } => true,
54        Stmt::WriteFile { .. } => true,
55        // Phase 54: Go-like concurrency is async
56        Stmt::LaunchTask { .. } => true,
57        Stmt::LaunchTaskWithHandle { .. } => true,
58        Stmt::SendPipe { .. } => true,
59        Stmt::ReceivePipe { .. } => true,
60        Stmt::Select { .. } => true,
61        Stmt::AwaitTask { .. } => true,
62        // Mode B: every scheduler operation is an awaited step on the replay executor.
63        Stmt::CreatePipe { .. }
64        | Stmt::TrySendPipe { .. }
65        | Stmt::TryReceivePipe { .. }
66        | Stmt::StopTask { .. }
67        | Stmt::CloseChannel { .. } => super::deterministic_replay_enabled(),
68        // While and Repeat are now always async due to check_preemption()
69        // (handled below in recursive check)
70        // Recursively check nested blocks
71        Stmt::If {
72            then_block,
73            else_block,
74            ..
75        } => {
76            then_block.iter().any(|s| requires_async_stmt(s))
77                || else_block.map_or(false, |b| b.iter().any(|s| requires_async_stmt(s)))
78        }
79        Stmt::While { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
80        Stmt::Repeat { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
81        Stmt::Zone { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
82        Stmt::Parallel { tasks } => tasks.iter().any(|s| requires_async_stmt(s)),
83        Stmt::FunctionDef { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
84        // Check Inspect arms for async operations
85        Stmt::Inspect { arms, .. } => arms
86            .iter()
87            .any(|arm| arm.body.iter().any(|s| requires_async_stmt(s))),
88        _ => false,
89    }
90}
91
92/// Phase 53: Detect if any statements require VFS (Virtual File System).
93/// Returns true if the program uses file operations or persistent storage.
94pub(super) fn requires_vfs(stmts: &[Stmt]) -> bool {
95    stmts.iter().any(|s| requires_vfs_stmt(s))
96}
97
98pub(super) fn requires_vfs_stmt(stmt: &Stmt) -> bool {
99    match stmt {
100        // Phase 53: Mount uses VFS for persistent storage
101        Stmt::Mount { .. } => true,
102        // Phase 53: File I/O uses VFS
103        Stmt::ReadFrom {
104            source: ReadSource::File(_),
105            ..
106        } => true,
107        Stmt::WriteFile { .. } => true,
108        // Recursively check nested blocks
109        Stmt::If {
110            then_block,
111            else_block,
112            ..
113        } => {
114            then_block.iter().any(|s| requires_vfs_stmt(s))
115                || else_block.map_or(false, |b| b.iter().any(|s| requires_vfs_stmt(s)))
116        }
117        Stmt::While { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
118        Stmt::Repeat { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
119        Stmt::Zone { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
120        Stmt::Concurrent { tasks } => tasks.iter().any(|s| requires_vfs_stmt(s)),
121        Stmt::Parallel { tasks } => tasks.iter().any(|s| requires_vfs_stmt(s)),
122        Stmt::FunctionDef { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
123        _ => false,
124    }
125}
126
127/// Every variable that needs `let mut` in Rust: each name the block reassigns (`Set`, `Swap`) or changes in place
128/// (`Push`, `Pop`, `SetIndex`, …), and each binding lent to a `mutable` parameter (the callee writes it in place).
129pub(super) fn collect_mutable_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
130    let mut targets = HashSet::new();
131    for stmt in stmts {
132        collect_mutable_vars_stmt(stmt, &mut targets);
133    }
134    targets
135}
136
137pub(super) fn collect_mutable_vars_stmt(stmt: &Stmt, targets: &mut HashSet<Symbol>) {
138    collect_written_vars_stmt(stmt, targets);
139    collect_lent_vars(std::slice::from_ref(stmt), targets);
140}
141
142/// Every binding `stmts` passes to a `mutable` parameter, wherever the call sits
143/// ([`crate::analysis::callgraph::lent_positions`]). The callee writes a lent binding, and a lend
144/// copies the binding on write first, so the binding is written like any `Push` target.
145fn collect_lent_vars(stmts: &[Stmt], targets: &mut HashSet<Symbol>) {
146    crate::analysis::callgraph::for_each_call_site(stmts, &mut |function, args| {
147        for at in crate::analysis::callgraph::lent_positions(function) {
148            if let Some(Expr::Identifier(sym)) = args.get(at) {
149                targets.insert(*sym);
150            }
151        }
152    });
153}
154
155/// Every name `stmt` reassigns (`Set`, `Swap`, a lend to a `mutable` parameter) or changes in place (the root of a
156/// `Push`, `SetIndex`, `SetField`, CRDT update, …), nested blocks included: the optimizer's one exhaustive write walk,
157/// so a statement kind cannot write a name here and not in the passes that ask the same question.
158fn collect_written_vars_stmt(stmt: &Stmt, targets: &mut HashSet<Symbol>) {
159    let writes = crate::optimize::WriteSet::of_stmt(stmt);
160    targets.extend(writes.assigned().iter().copied());
161    targets.extend(writes.mutated().iter().copied());
162}
163
164/// Detect mutable Text variables that are only ever assigned single-character
165/// string literals. These can be emitted as `u8` (byte) instead of `String`,
166/// eliminating heap allocations for temporary character variables.
167///
168/// Returns a set of symbols that qualify for the u8 optimization.
169///
170/// A variable qualifies if:
171/// 1. It is declared with `Let mutable ch be "x"` (single-char text literal)
172/// 2. Every `Set ch to "y"` assigns a single-char text literal
173/// 3. It is never used in a context that requires String (e.g., function call args,
174///    Return, field access) — only push_str (→ push), Show, or comparison
175pub(super) fn collect_single_char_text_vars(
176    stmts: &[Stmt],
177    interner: &Interner,
178) -> HashSet<Symbol> {
179    let mut candidates: HashSet<Symbol> = HashSet::new();
180    let mut disqualified: HashSet<Symbol> = HashSet::new();
181
182    // Pass 1: Find candidates (Let mutable with single-char text literal)
183    // and check all Set assignments are also single-char.
184    scan_single_char_candidates(stmts, interner, &mut candidates, &mut disqualified);
185
186    // Remove disqualified
187    for sym in &disqualified {
188        candidates.remove(sym);
189    }
190
191    // Pass 2: Check usage contexts. If any use requires a String, disqualify.
192    let mut usage_disqualified: HashSet<Symbol> = HashSet::new();
193    check_single_char_usage(stmts, &candidates, &mut usage_disqualified);
194
195    for sym in &usage_disqualified {
196        candidates.remove(sym);
197    }
198
199    // A swap exchanges the two texts whole: both are one byte, or neither is.
200    crate::optimize::SwapClasses::of(stmts, interner).close_set(&mut candidates, interner);
201    candidates
202}
203
204fn is_single_char_text_literal<'a>(expr: &Expr<'a>, interner: &Interner) -> bool {
205    if let Expr::Literal(crate::ast::stmt::Literal::Text(sym)) = expr {
206        let text = interner.resolve(*sym);
207        text.len() == 1 && text.is_ascii()
208    } else {
209        false
210    }
211}
212
213fn scan_single_char_candidates(
214    stmts: &[Stmt],
215    interner: &Interner,
216    candidates: &mut HashSet<Symbol>,
217    disqualified: &mut HashSet<Symbol>,
218) {
219    for stmt in stmts {
220        match stmt {
221            Stmt::Let {
222                var,
223                value,
224                mutable,
225                ..
226            } => {
227                if *mutable && is_single_char_text_literal(value, interner) {
228                    candidates.insert(*var);
229                }
230                // Recurse into nested blocks in any case
231            }
232            Stmt::Set { target, value } => {
233                if candidates.contains(target) || !disqualified.contains(target) {
234                    if !is_single_char_text_literal(value, interner) {
235                        // Non-single-char assignment disqualifies
236                        disqualified.insert(*target);
237                    }
238                }
239            }
240            Stmt::If {
241                then_block,
242                else_block,
243                ..
244            } => {
245                scan_single_char_candidates(then_block, interner, candidates, disqualified);
246                if let Some(eb) = else_block {
247                    scan_single_char_candidates(eb, interner, candidates, disqualified);
248                }
249            }
250            Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
251                scan_single_char_candidates(body, interner, candidates, disqualified);
252            }
253            Stmt::FunctionDef { body, .. } => {
254                scan_single_char_candidates(body, interner, candidates, disqualified);
255            }
256            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
257                scan_single_char_candidates(tasks, interner, candidates, disqualified);
258            }
259            _ => {}
260        }
261    }
262}
263
264/// Check that a candidate variable is only used in contexts compatible with u8:
265/// - `Set text to text + ch` (self-append → push)
266/// - `Show ch`
267/// - Comparison (`ch equals "x"`)
268///
269/// Disqualify if used in:
270/// - Function call arguments
271/// - Return value
272/// - Assignment to another variable (`Let y be ch`)
273/// - Any other expression context that expects String
274fn check_single_char_usage(
275    stmts: &[Stmt],
276    candidates: &HashSet<Symbol>,
277    disqualified: &mut HashSet<Symbol>,
278) {
279    for stmt in stmts {
280        match stmt {
281            Stmt::Set { target, value } => {
282                // `Set ch to "x"` is fine (already validated in pass 1).
283                // `Set text to text + ch` is fine (self-append).
284                // But if ch appears in a non-append context in value, disqualify.
285                if !candidates.contains(target) {
286                    // target is not a candidate, check if value uses a candidate
287                    // in a non-append-compatible way
288                    check_expr_usage(value, candidates, disqualified, true);
289                }
290            }
291            Stmt::Show { object, .. } => {
292                // A BARE candidate is fine — Show emits `println!("{}", ch as char)`.
293                // Any deeper appearance (an interpolated string, arithmetic, a
294                // call) would format the raw u8 as its byte code, so it
295                // disqualifies.
296                if !matches!(object, Expr::Identifier(_)) {
297                    check_expr_usage_strict(object, candidates, disqualified);
298                }
299            }
300            Stmt::Let { value, .. } => {
301                // `Let y be ch` would assign a u8 to y, which may not work.
302                // Disqualify if a candidate appears directly as the value.
303                check_expr_usage_strict(value, candidates, disqualified);
304            }
305            Stmt::Return { value: Some(v) } => {
306                check_expr_usage_strict(v, candidates, disqualified);
307            }
308            Stmt::Call { args, .. } => {
309                for a in args.iter() {
310                    check_expr_usage_strict(a, candidates, disqualified);
311                }
312            }
313            Stmt::Push { value, .. } => {
314                // `Push ch to list` — disqualify since list expects String
315                check_expr_usage_strict(value, candidates, disqualified);
316            }
317            Stmt::If {
318                cond: _,
319                then_block,
320                else_block,
321            } => {
322                // Comparisons in conditions are fine for u8
323                check_single_char_usage(then_block, candidates, disqualified);
324                if let Some(eb) = else_block {
325                    check_single_char_usage(eb, candidates, disqualified);
326                }
327            }
328            Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
329                check_single_char_usage(body, candidates, disqualified);
330            }
331            Stmt::FunctionDef { body, .. } => {
332                check_single_char_usage(body, candidates, disqualified);
333            }
334            _ => {}
335        }
336    }
337}
338
339/// Check an expression for usage of candidates in self-append context.
340/// `is_self_append` indicates the expression is the RHS of `Set text to <expr>`
341/// where text is a string (not a candidate). In that context, `text + ch` is fine.
342fn check_expr_usage(
343    expr: &Expr,
344    candidates: &HashSet<Symbol>,
345    disqualified: &mut HashSet<Symbol>,
346    is_self_append: bool,
347) {
348    match expr {
349        Expr::BinaryOp {
350            op: crate::ast::stmt::BinaryOpKind::Add,
351            left,
352            right,
353        } if is_self_append => {
354            // In self-append: `text + ch` — ch as a direct identifier is fine
355            check_expr_usage(left, candidates, disqualified, true);
356            // right side: if it's a bare candidate identifier, that's fine (push)
357            if !matches!(right, Expr::Identifier(sym) if candidates.contains(sym)) {
358                check_expr_usage(right, candidates, disqualified, false);
359            }
360        }
361        Expr::Identifier(sym) if !is_self_append => {
362            // Bare candidate in non-append context — disqualify
363            if candidates.contains(sym) {
364                disqualified.insert(*sym);
365            }
366        }
367        // A candidate inside an interpolation would format as its byte code.
368        Expr::InterpolatedString(parts) => {
369            for part in parts {
370                if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
371                    check_expr_usage_strict(value, candidates, disqualified);
372                }
373            }
374        }
375        _ => {}
376    }
377}
378
379/// Strictly disqualify any candidate that appears anywhere in this expression.
380fn check_expr_usage_strict(
381    expr: &Expr,
382    candidates: &HashSet<Symbol>,
383    disqualified: &mut HashSet<Symbol>,
384) {
385    match expr {
386        Expr::Identifier(sym) => {
387            if candidates.contains(sym) {
388                disqualified.insert(*sym);
389            }
390        }
391        Expr::BinaryOp { left, right, .. } => {
392            check_expr_usage_strict(left, candidates, disqualified);
393            check_expr_usage_strict(right, candidates, disqualified);
394        }
395        Expr::Call { args, .. } => {
396            for a in args.iter() {
397                check_expr_usage_strict(a, candidates, disqualified);
398            }
399        }
400        Expr::Not { operand } => check_expr_usage_strict(operand, candidates, disqualified),
401        Expr::Index { collection, index } => {
402            check_expr_usage_strict(collection, candidates, disqualified);
403            check_expr_usage_strict(index, candidates, disqualified);
404        }
405        Expr::Length { collection } => {
406            check_expr_usage_strict(collection, candidates, disqualified)
407        }
408        Expr::List(items) => {
409            for item in items.iter() {
410                check_expr_usage_strict(item, candidates, disqualified);
411            }
412        }
413        // A candidate inside an interpolation would format as its byte code.
414        Expr::InterpolatedString(parts) => {
415            for part in parts {
416                if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
417                    check_expr_usage_strict(value, candidates, disqualified);
418                }
419            }
420        }
421        _ => {}
422    }
423}
424
425pub(super) fn collect_crdt_register_fields(
426    registry: &TypeRegistry,
427    interner: &Interner,
428) -> (HashSet<(String, String)>, HashSet<(String, String)>) {
429    let mut lww_fields = HashSet::new();
430    let mut mv_fields = HashSet::new();
431    for (type_sym, def) in registry.iter_types() {
432        if let TypeDef::Struct { fields, .. } = def {
433            let type_name = interner.resolve(*type_sym).to_string();
434            for field in fields {
435                if let FieldType::Generic { base, .. } = &field.ty {
436                    let base_name = interner.resolve(*base);
437                    let field_name = interner.resolve(field.name).to_string();
438                    if base_name == "LastWriteWins" {
439                        lww_fields.insert((type_name.clone(), field_name));
440                    } else if base_name == "Divergent" || base_name == "MVRegister" {
441                        mv_fields.insert((type_name.clone(), field_name));
442                    }
443                }
444            }
445        }
446    }
447    (lww_fields, mv_fields)
448}
449
450/// The enum fields stored in a box of their own ([`field_is_boxed`]), as (EnumName, VariantName, FieldName).
451pub(super) fn collect_boxed_fields(
452    registry: &TypeRegistry,
453    interner: &Interner,
454) -> HashSet<(String, String, String)> {
455    let mut boxed_fields = HashSet::new();
456    for (type_sym, def) in registry.iter_types() {
457        if let TypeDef::Enum { variants, .. } = def {
458            let enum_name = interner.resolve(*type_sym);
459            for variant in variants {
460                let variant_name = interner.resolve(variant.name);
461                for field in &variant.fields {
462                    if field_is_boxed(&field.ty, enum_name, interner) {
463                        let field_name = interner.resolve(field.name).to_string();
464                        boxed_fields.insert((
465                            enum_name.to_string(),
466                            variant_name.to_string(),
467                            field_name,
468                        ));
469                    }
470                }
471            }
472        }
473    }
474    boxed_fields
475}
476
477/// Phase 54: Collect function names that are async.
478/// Used by LaunchTask codegen to determine if .await is needed.
479///
480/// Two-pass analysis:
481/// 1. First pass: Collect directly async functions (have Sleep, LaunchTask, etc.)
482/// 2. Second pass: Iterate until fixed point - if function calls an async function, mark it async
483pub fn collect_async_functions(stmts: &[Stmt]) -> HashSet<Symbol> {
484    // First, collect all function definitions
485    let mut func_bodies: HashMap<Symbol, &[Stmt]> = HashMap::new();
486    for stmt in stmts {
487        if let Stmt::FunctionDef { name, body, .. } = stmt {
488            func_bodies.insert(*name, *body);
489        }
490    }
491
492    // Pass 1: Collect directly async functions
493    let mut async_fns = HashSet::new();
494    for stmt in stmts {
495        if let Stmt::FunctionDef { name, body, .. } = stmt {
496            if body.iter().any(|s| requires_async_stmt(s)) {
497                async_fns.insert(*name);
498            }
499        }
500    }
501
502    // Pass 2: Propagate async-ness through call graph until fixed point
503    loop {
504        let mut changed = false;
505        for (func_name, body) in &func_bodies {
506            if async_fns.contains(func_name) {
507                continue; // Already marked async
508            }
509            // Check if this function calls any async function
510            if body.iter().any(|s| calls_async_function(s, &async_fns)) {
511                async_fns.insert(*func_name);
512                changed = true;
513            }
514        }
515        if !changed {
516            break;
517        }
518    }
519
520    async_fns
521}
522
523/// Helper: Check if a statement calls any function in the async_fns set
524pub(super) fn calls_async_function(stmt: &Stmt, async_fns: &HashSet<Symbol>) -> bool {
525    match stmt {
526        Stmt::Call { function, args } => {
527            // Check if the called function is async OR if any argument expression calls an async function
528            async_fns.contains(function)
529                || args
530                    .iter()
531                    .any(|a| calls_async_function_in_expr(a, async_fns))
532        }
533        Stmt::If {
534            cond,
535            then_block,
536            else_block,
537        } => {
538            calls_async_function_in_expr(cond, async_fns)
539                || then_block
540                    .iter()
541                    .any(|s| calls_async_function(s, async_fns))
542                || else_block.map_or(false, |b| {
543                    b.iter().any(|s| calls_async_function(s, async_fns))
544                })
545        }
546        Stmt::While { cond, body, .. } => {
547            calls_async_function_in_expr(cond, async_fns)
548                || body.iter().any(|s| calls_async_function(s, async_fns))
549        }
550        Stmt::Repeat { iterable, body, .. } => {
551            calls_async_function_in_expr(iterable, async_fns)
552                || body.iter().any(|s| calls_async_function(s, async_fns))
553        }
554        Stmt::Zone { body, .. } => body.iter().any(|s| calls_async_function(s, async_fns)),
555        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
556            tasks.iter().any(|s| calls_async_function(s, async_fns))
557        }
558        Stmt::FunctionDef { body, .. } => body.iter().any(|s| calls_async_function(s, async_fns)),
559        // Check Let statements for async function calls in the value expression
560        Stmt::Let { value, .. } => calls_async_function_in_expr(value, async_fns),
561        // Check Set statements for async function calls in the value expression
562        Stmt::Set { value, .. } => calls_async_function_in_expr(value, async_fns),
563        // Check Return statements for async function calls in the return value
564        Stmt::Return { value } => value
565            .as_ref()
566            .map_or(false, |v| calls_async_function_in_expr(v, async_fns)),
567        // Check RuntimeAssert condition for async calls
568        Stmt::RuntimeAssert { condition, .. } => calls_async_function_in_expr(condition, async_fns),
569        // Check Show for async calls
570        Stmt::Show { object, .. } => calls_async_function_in_expr(object, async_fns),
571        // Check Push for async calls
572        Stmt::Push { collection, value } => {
573            calls_async_function_in_expr(collection, async_fns)
574                || calls_async_function_in_expr(value, async_fns)
575        }
576        // Check SetIndex for async calls
577        Stmt::SetIndex {
578            collection,
579            index,
580            value,
581        } => {
582            calls_async_function_in_expr(collection, async_fns)
583                || calls_async_function_in_expr(index, async_fns)
584                || calls_async_function_in_expr(value, async_fns)
585        }
586        // Check SendPipe for async calls
587        Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
588            calls_async_function_in_expr(value, async_fns)
589                || calls_async_function_in_expr(pipe, async_fns)
590        }
591        // Check Inspect arms for async function calls
592        Stmt::Inspect { target, arms, .. } => {
593            calls_async_function_in_expr(target, async_fns)
594                || arms
595                    .iter()
596                    .any(|arm| arm.body.iter().any(|s| calls_async_function(s, async_fns)))
597        }
598        _ => false,
599    }
600}
601
602/// Helper: Check if an expression calls any function in the async_fns set
603fn calls_async_function_in_expr(expr: &Expr, async_fns: &HashSet<Symbol>) -> bool {
604    match expr {
605        Expr::Call { function, args } => {
606            async_fns.contains(function)
607                || args
608                    .iter()
609                    .any(|a| calls_async_function_in_expr(a, async_fns))
610        }
611        Expr::BinaryOp { left, right, .. } => {
612            calls_async_function_in_expr(left, async_fns)
613                || calls_async_function_in_expr(right, async_fns)
614        }
615        Expr::Index { collection, index } => {
616            calls_async_function_in_expr(collection, async_fns)
617                || calls_async_function_in_expr(index, async_fns)
618        }
619        Expr::FieldAccess { object, .. } => calls_async_function_in_expr(object, async_fns),
620        Expr::List(items) | Expr::Tuple(items) => items
621            .iter()
622            .any(|i| calls_async_function_in_expr(i, async_fns)),
623        Expr::Closure { body, .. } => match body {
624            crate::ast::stmt::ClosureBody::Expression(expr) => {
625                calls_async_function_in_expr(expr, async_fns)
626            }
627            crate::ast::stmt::ClosureBody::Block(_) => false,
628        },
629        Expr::CallExpr { callee, args } => {
630            calls_async_function_in_expr(callee, async_fns)
631                || args
632                    .iter()
633                    .any(|a| calls_async_function_in_expr(a, async_fns))
634        }
635        Expr::InterpolatedString(parts) => parts.iter().any(|p| {
636            if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
637                calls_async_function_in_expr(value, async_fns)
638            } else {
639                false
640            }
641        }),
642        _ => false,
643    }
644}
645
646// =============================================================================
647// Purity Analysis
648// =============================================================================
649
650/// The program's pure functions: the shared optimizer's one definition ([`crate::optimize::purity::Purity`]), which
651/// memoization asks of a recursion before it caches one.
652pub(crate) fn collect_pure_functions(stmts: &[Stmt], interner: &Interner) -> HashSet<Symbol> {
653    crate::optimize::purity::Purity::of_program(stmts, interner).into_set()
654}
655
656// =============================================================================
657// Memoization Detection
658// =============================================================================
659
660pub(super) fn count_self_calls(func_name: Symbol, body: &[Stmt]) -> usize {
661    let mut count = 0;
662    for stmt in body {
663        count += count_self_calls_in_stmt(func_name, stmt);
664    }
665    count
666}
667
668fn count_self_calls_in_stmt(func_name: Symbol, stmt: &Stmt) -> usize {
669    match stmt {
670        Stmt::Return { value: Some(expr) } => count_self_calls_in_expr(func_name, expr),
671        Stmt::Let { value, .. } => count_self_calls_in_expr(func_name, value),
672        Stmt::Set { value, .. } => count_self_calls_in_expr(func_name, value),
673        Stmt::Call { function, args } => {
674            let mut c = if *function == func_name { 1 } else { 0 };
675            c += args
676                .iter()
677                .map(|a| count_self_calls_in_expr(func_name, a))
678                .sum::<usize>();
679            c
680        }
681        Stmt::If {
682            cond,
683            then_block,
684            else_block,
685        } => {
686            let mut c = count_self_calls_in_expr(func_name, cond);
687            c += count_self_calls(func_name, then_block);
688            if let Some(else_stmts) = else_block {
689                c += count_self_calls(func_name, else_stmts);
690            }
691            c
692        }
693        Stmt::While { cond, body, .. } => {
694            count_self_calls_in_expr(func_name, cond) + count_self_calls(func_name, body)
695        }
696        Stmt::Repeat { body, .. } => count_self_calls(func_name, body),
697        Stmt::Show { object, .. } => count_self_calls_in_expr(func_name, object),
698        _ => 0,
699    }
700}
701
702fn count_self_calls_in_expr(func_name: Symbol, expr: &Expr) -> usize {
703    match expr {
704        Expr::Call { function, args } => {
705            let mut c = if *function == func_name { 1 } else { 0 };
706            c += args
707                .iter()
708                .map(|a| count_self_calls_in_expr(func_name, a))
709                .sum::<usize>();
710            c
711        }
712        Expr::BinaryOp { left, right, .. } => {
713            count_self_calls_in_expr(func_name, left) + count_self_calls_in_expr(func_name, right)
714        }
715        Expr::Index { collection, index } => {
716            count_self_calls_in_expr(func_name, collection)
717                + count_self_calls_in_expr(func_name, index)
718        }
719        Expr::FieldAccess { object, .. } => count_self_calls_in_expr(func_name, object),
720        Expr::List(items) | Expr::Tuple(items) => items
721            .iter()
722            .map(|i| count_self_calls_in_expr(func_name, i))
723            .sum(),
724        Expr::InterpolatedString(parts) => parts
725            .iter()
726            .map(|p| {
727                if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
728                    count_self_calls_in_expr(func_name, value)
729                } else {
730                    0
731                }
732            })
733            .sum(),
734        _ => 0,
735    }
736}
737
738pub(super) fn is_hashable_type(ty: &TypeExpr, interner: &Interner) -> bool {
739    match ty {
740        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
741            let name = interner.resolve(*sym);
742            matches!(
743                name,
744                "Int"
745                    | "Nat"
746                    | "Bool"
747                    | "Char"
748                    | "Byte"
749                    | "Text"
750                    | "i64"
751                    | "u64"
752                    | "bool"
753                    | "char"
754                    | "u8"
755                    | "String"
756            )
757        }
758        TypeExpr::Refinement { base, .. } => is_hashable_type(base, interner),
759        _ => false,
760    }
761}
762
763pub(super) fn is_copy_type_expr(ty: &TypeExpr, interner: &Interner) -> bool {
764    match ty {
765        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
766            let name = interner.resolve(*sym);
767            matches!(
768                name,
769                "Int" | "Nat" | "Bool" | "Char" | "Byte" | "i64" | "u64" | "bool" | "char" | "u8"
770            )
771        }
772        TypeExpr::Refinement { base, .. } => is_copy_type_expr(base, interner),
773        _ => false,
774    }
775}
776
777pub(super) fn should_memoize(
778    name: Symbol,
779    body: &[Stmt],
780    params: &[(Symbol, &TypeExpr)],
781    return_type: Option<&TypeExpr>,
782    is_pure: bool,
783    interner: &Interner,
784) -> bool {
785    if !is_pure {
786        return false;
787    }
788    if !body_contains_self_call(name, body) {
789        return false;
790    }
791    if count_self_calls(name, body) < 2 {
792        return false;
793    }
794    if params.is_empty() {
795        return false;
796    }
797    if !params.iter().all(|(_, ty)| is_hashable_type(ty, interner)) {
798        return false;
799    }
800    if return_type.is_none() {
801        return false;
802    }
803    true
804}
805
806pub(super) fn body_contains_self_call(func_name: Symbol, body: &[Stmt]) -> bool {
807    body.iter().any(|s| stmt_contains_self_call(func_name, s))
808}
809
810fn stmt_contains_self_call(func_name: Symbol, stmt: &Stmt) -> bool {
811    match stmt {
812        Stmt::Return { value: Some(expr) } => expr_contains_self_call(func_name, expr),
813        Stmt::Return { value: None } => false,
814        Stmt::Let { value, .. } => expr_contains_self_call(func_name, value),
815        Stmt::Set { value, .. } => expr_contains_self_call(func_name, value),
816        Stmt::Call { function, args } => {
817            *function == func_name || args.iter().any(|a| expr_contains_self_call(func_name, a))
818        }
819        Stmt::If {
820            cond,
821            then_block,
822            else_block,
823        } => {
824            expr_contains_self_call(func_name, cond)
825                || then_block
826                    .iter()
827                    .any(|s| stmt_contains_self_call(func_name, s))
828                || else_block.map_or(false, |b| {
829                    b.iter().any(|s| stmt_contains_self_call(func_name, s))
830                })
831        }
832        Stmt::While { cond, body, .. } => {
833            expr_contains_self_call(func_name, cond)
834                || body.iter().any(|s| stmt_contains_self_call(func_name, s))
835        }
836        Stmt::Repeat { body, .. } => body.iter().any(|s| stmt_contains_self_call(func_name, s)),
837        Stmt::Show { object, .. } => expr_contains_self_call(func_name, object),
838        _ => false,
839    }
840}
841
842pub(super) fn expr_contains_self_call(func_name: Symbol, expr: &Expr) -> bool {
843    match expr {
844        Expr::Call { function, args } => {
845            *function == func_name || args.iter().any(|a| expr_contains_self_call(func_name, a))
846        }
847        Expr::BinaryOp { left, right, .. } => {
848            expr_contains_self_call(func_name, left) || expr_contains_self_call(func_name, right)
849        }
850        Expr::Index { collection, index } => {
851            expr_contains_self_call(func_name, collection)
852                || expr_contains_self_call(func_name, index)
853        }
854        Expr::FieldAccess { object, .. } => expr_contains_self_call(func_name, object),
855        Expr::List(items) | Expr::Tuple(items) => {
856            items.iter().any(|i| expr_contains_self_call(func_name, i))
857        }
858        Expr::InterpolatedString(parts) => parts.iter().any(|p| {
859            if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
860                expr_contains_self_call(func_name, value)
861            } else {
862                false
863            }
864        }),
865        _ => false,
866    }
867}
868
869/// True if `expr` borrows ANY collection at runtime — an index (`item i of C`),
870/// slice, or length read. Under LOGOS reference semantics any such collection
871/// may alias the target of a `SetIndex`, so the RHS must be evaluated into a
872/// temp BEFORE the target's `borrow_mut()` is taken; otherwise the live
873/// `borrow()` and the `borrow_mut()` can land on the same `RefCell` and panic
874/// ("already borrowed"). `expr_indexes_collection` only catches same-symbol
875/// aliasing; this catches the cross-variable case (e.g. `prev` aliasing `curr`
876/// after `Set prev to curr`).
877pub(super) fn expr_reads_any_collection(expr: &Expr) -> bool {
878    match expr {
879        Expr::Index { .. } | Expr::Slice { .. } | Expr::Length { .. } => true,
880        Expr::BinaryOp { left, right, .. } => {
881            expr_reads_any_collection(left) || expr_reads_any_collection(right)
882        }
883        Expr::Call { args, .. } => args.iter().any(|a| expr_reads_any_collection(a)),
884        Expr::FieldAccess { object, .. } => expr_reads_any_collection(object),
885        Expr::Not { operand } => expr_reads_any_collection(operand),
886        Expr::List(items) | Expr::Tuple(items) => {
887            items.iter().any(|i| expr_reads_any_collection(i))
888        }
889        _ => false,
890    }
891}
892
893// =============================================================================
894// Inline Annotation Detection
895// =============================================================================
896
897pub(super) fn should_inline(
898    name: Symbol,
899    body: &[Stmt],
900    is_native: bool,
901    is_exported: bool,
902    is_async: bool,
903) -> bool {
904    !is_native
905        && !is_exported
906        && !is_async
907        && body.len() <= 10
908        && !body_contains_self_call(name, body)
909}
910
911// =============================================================================
912// Pipe Detection
913// =============================================================================
914
915pub fn collect_pipe_sender_params(body: &[Stmt]) -> HashSet<Symbol> {
916    let mut senders = HashSet::new();
917    for stmt in body {
918        collect_pipe_sender_params_stmt(stmt, &mut senders);
919    }
920    senders
921}
922
923fn collect_pipe_sender_params_stmt(stmt: &Stmt, senders: &mut HashSet<Symbol>) {
924    match stmt {
925        Stmt::SendPipe { pipe, .. } | Stmt::TrySendPipe { pipe, .. } => {
926            if let Expr::Identifier(sym) = pipe {
927                senders.insert(*sym);
928            }
929        }
930        Stmt::If {
931            then_block,
932            else_block,
933            ..
934        } => {
935            for s in *then_block {
936                collect_pipe_sender_params_stmt(s, senders);
937            }
938            if let Some(else_stmts) = else_block {
939                for s in *else_stmts {
940                    collect_pipe_sender_params_stmt(s, senders);
941                }
942            }
943        }
944        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
945            for s in *body {
946                collect_pipe_sender_params_stmt(s, senders);
947            }
948        }
949        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
950            for s in *tasks {
951                collect_pipe_sender_params_stmt(s, senders);
952            }
953        }
954        _ => {}
955    }
956}
957
958/// Phase 54: Collect variables that are pipe declarations (created with CreatePipe).
959/// These have _tx/_rx suffixes, while pipe parameters don't.
960pub fn collect_pipe_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
961    let mut pipe_vars = HashSet::new();
962    for stmt in stmts {
963        collect_pipe_vars_stmt(stmt, &mut pipe_vars);
964    }
965    pipe_vars
966}
967
968fn collect_pipe_vars_stmt(stmt: &Stmt, pipe_vars: &mut HashSet<Symbol>) {
969    match stmt {
970        Stmt::CreatePipe { var, .. } => {
971            pipe_vars.insert(*var);
972        }
973        Stmt::If {
974            then_block,
975            else_block,
976            ..
977        } => {
978            for s in *then_block {
979                collect_pipe_vars_stmt(s, pipe_vars);
980            }
981            if let Some(else_stmts) = else_block {
982                for s in *else_stmts {
983                    collect_pipe_vars_stmt(s, pipe_vars);
984                }
985            }
986        }
987        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
988            for s in *body {
989                collect_pipe_vars_stmt(s, pipe_vars);
990            }
991        }
992        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
993            for s in *tasks {
994                collect_pipe_vars_stmt(s, pipe_vars);
995            }
996        }
997        _ => {}
998    }
999}
1000
1001/// Collect all identifier symbols from an expression recursively.
1002/// Used by Concurrent/Parallel codegen to find variables that need cloning.
1003pub(super) fn collect_expr_identifiers(expr: &Expr, identifiers: &mut HashSet<Symbol>) {
1004    match expr {
1005        Expr::Dom(q) => {
1006            if let Some(sel) = q.selector() {
1007                collect_expr_identifiers(sel, identifiers);
1008            }
1009        }
1010        Expr::View(v) => {
1011            for e in v.exprs_and_blocks().0 {
1012                collect_expr_identifiers(e, identifiers);
1013            }
1014        }
1015        Expr::Identifier(sym) => {
1016            identifiers.insert(*sym);
1017        }
1018        Expr::BinaryOp { left, right, .. } => {
1019            collect_expr_identifiers(left, identifiers);
1020            collect_expr_identifiers(right, identifiers);
1021        }
1022        Expr::Call { args, .. } => {
1023            for arg in args {
1024                collect_expr_identifiers(arg, identifiers);
1025            }
1026        }
1027        Expr::Index { collection, index } => {
1028            collect_expr_identifiers(collection, identifiers);
1029            collect_expr_identifiers(index, identifiers);
1030        }
1031        Expr::Slice {
1032            collection,
1033            start,
1034            end,
1035        } => {
1036            collect_expr_identifiers(collection, identifiers);
1037            collect_expr_identifiers(start, identifiers);
1038            collect_expr_identifiers(end, identifiers);
1039        }
1040        Expr::Copy { expr: inner }
1041        | Expr::Give { value: inner }
1042        | Expr::Length { collection: inner }
1043        | Expr::Not { operand: inner } => {
1044            collect_expr_identifiers(inner, identifiers);
1045        }
1046        Expr::Contains { collection, value }
1047        | Expr::Union {
1048            left: collection,
1049            right: value,
1050        }
1051        | Expr::Intersection {
1052            left: collection,
1053            right: value,
1054        } => {
1055            collect_expr_identifiers(collection, identifiers);
1056            collect_expr_identifiers(value, identifiers);
1057        }
1058        Expr::ManifestOf { zone } | Expr::ChunkAt { zone, .. } => {
1059            collect_expr_identifiers(zone, identifiers);
1060        }
1061        Expr::List(items) | Expr::Tuple(items) => {
1062            for item in items {
1063                collect_expr_identifiers(item, identifiers);
1064            }
1065        }
1066        Expr::Range { start, end } => {
1067            collect_expr_identifiers(start, identifiers);
1068            collect_expr_identifiers(end, identifiers);
1069        }
1070        Expr::FieldAccess { object, .. } => {
1071            collect_expr_identifiers(object, identifiers);
1072        }
1073        Expr::New { init_fields, .. } => {
1074            for (_, value) in init_fields {
1075                collect_expr_identifiers(value, identifiers);
1076            }
1077        }
1078        Expr::NewVariant { fields, .. } => {
1079            for (_, value) in fields {
1080                collect_expr_identifiers(value, identifiers);
1081            }
1082        }
1083        Expr::OptionSome { value } => {
1084            collect_expr_identifiers(value, identifiers);
1085        }
1086        Expr::WithCapacity { value, capacity } => {
1087            collect_expr_identifiers(value, identifiers);
1088            collect_expr_identifiers(capacity, identifiers);
1089        }
1090        Expr::Closure { body, .. } => match body {
1091            crate::ast::stmt::ClosureBody::Expression(expr) => {
1092                collect_expr_identifiers(expr, identifiers)
1093            }
1094            crate::ast::stmt::ClosureBody::Block(_) => {}
1095        },
1096        Expr::CallExpr { callee, args } => {
1097            collect_expr_identifiers(callee, identifiers);
1098            for arg in args {
1099                collect_expr_identifiers(arg, identifiers);
1100            }
1101        }
1102        Expr::InterpolatedString(parts) => {
1103            for part in parts {
1104                if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
1105                    collect_expr_identifiers(value, identifiers);
1106                }
1107            }
1108        }
1109        Expr::OptionNone => {}
1110        Expr::Escape { .. } => {}
1111        Expr::Literal(_) => {}
1112    }
1113}
1114
1115/// Check if a symbol appears anywhere in a slice of statements (expressions or targets).
1116/// Used by dead-counter elimination to decide if a post-loop counter binding is needed.
1117pub(crate) fn symbol_appears_in_stmts(sym: Symbol, stmts: &[&Stmt]) -> bool {
1118    stmts.iter().any(|s| symbol_appears_in_stmt(sym, s))
1119}
1120
1121/// Whether the value `sym` holds once `block[..at]` has run can still be read. A variable a `Let` in `block[..at]`
1122/// declares lives only in the block, so only a later statement of the block reads it; any other variable belongs to
1123/// an enclosing scope, whose code past this block (after an enclosing loop, or on its next pass) can read it.
1124pub(crate) fn value_read_after(sym: Symbol, block: &[&Stmt], at: usize) -> bool {
1125    let declared_here = block[..at]
1126        .iter()
1127        .any(|s| matches!(s, Stmt::Let { var, .. } if *var == sym));
1128    !declared_here || symbol_appears_in_stmts(sym, &block[at..])
1129}
1130
1131/// Whether `sym` appears anywhere in `stmt` — read, written, declared, captured — from the optimizer's one exhaustive
1132/// walk. A nested function body is searched too: callers ask whether a NAME is still spoken of.
1133pub(super) fn symbol_appears_in_stmt(sym: Symbol, stmt: &Stmt) -> bool {
1134    match stmt {
1135        Stmt::FunctionDef { body, .. } => body.iter().any(|s| symbol_appears_in_stmt(sym, s)),
1136        other => crate::optimize::stmt_touches(other, sym),
1137    }
1138}
1139
1140/// Whether `sym` appears anywhere in `expr`, closures included.
1141pub(super) fn symbol_appears_in_expr(sym: Symbol, expr: &Expr) -> bool {
1142    crate::optimize::expr_touches(expr, sym)
1143}
1144
1145/// Check if a TypeExpr is a Vec/Seq/List type (collection that could be borrowed as &[T]).
1146pub(crate) fn is_vec_type_expr(ty: &TypeExpr, interner: &Interner) -> bool {
1147    match ty {
1148        TypeExpr::Generic { base, .. } => {
1149            let name = interner.resolve(*base);
1150            matches!(name, "Seq" | "List" | "Vec")
1151        }
1152        _ => false,
1153    }
1154}
1155
1156/// Convert a Vec<T> or LogosSeq<T> type string to a slice &[T] type string.
1157/// E.g., "Vec<i64>" → "&[i64]", "LogosSeq<i64>" → "&[i64]"
1158pub(super) fn vec_to_slice_type(vec_type: &str) -> String {
1159    if let Some(inner) = vec_type
1160        .strip_prefix("Vec<")
1161        .and_then(|s| s.strip_suffix('>'))
1162    {
1163        format!("&[{}]", inner)
1164    } else if let Some(inner) = vec_type
1165        .strip_prefix("LogosSeq<")
1166        .and_then(|s| s.strip_suffix('>'))
1167    {
1168        format!("&[{}]", inner)
1169    } else if vec_type == "String" {
1170        // A readonly Text param borrows as `&str` — the caller passes `&s` (no clone), matching
1171        // Rust's string ops which take `&str`. `text_bytes`/reads work through deref.
1172        "&str".to_string()
1173    } else {
1174        vec_type.to_string()
1175    }
1176}
1177
1178/// Convert `Vec<T>` or `LogosSeq<T>` to `&mut [T]` for mutable borrow parameters.
1179pub(super) fn vec_to_mut_slice_type(vec_type: &str) -> String {
1180    if let Some(inner) = vec_type
1181        .strip_prefix("Vec<")
1182        .and_then(|s| s.strip_suffix('>'))
1183    {
1184        format!("&mut [{}]", inner)
1185    } else if let Some(inner) = vec_type
1186        .strip_prefix("LogosSeq<")
1187        .and_then(|s| s.strip_suffix('>'))
1188    {
1189        format!("&mut [{}]", inner)
1190    } else {
1191        vec_type.to_string()
1192    }
1193}
1194
1195/// O2 de-Rc eligibility: Seq variables that provably never need reference
1196/// semantics, so codegen can emit a plain `Vec<T>` (no Rc/RefCell) instead of
1197/// `LogosSeq<T> = Rc<RefCell<Vec<T>>>`.
1198///
1199/// A variable qualifies when it is declared with a FRESH allocation of a Seq
1200/// whose element type is a scalar (Int/Float/Bool/Char/Text — reading an
1201/// element copies, never shares a handle) and, across the whole scope, it is
1202/// never aliased by a second live handle (`Let b be a`, `Set b to a`, stored
1203/// as an element) and never escapes (call arg, return, given away).
1204///
1205/// Conservative by construction: anything uncertain stays `LogosSeq`. An
1206/// unsound de-Rc would make the generated Rust fail to compile (two owners /
1207/// moved-from use), a loud failure the tests catch — never silent corruption.
1208pub(crate) fn collect_de_rc_seqs(
1209    stmts: &[Stmt],
1210    interner: &Interner,
1211    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1212    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1213    vec_return_fns: &HashSet<Symbol>,
1214    returns_vec: bool,
1215) -> HashSet<Symbol> {
1216    // Kill switch (benchmark A/B): `LOGOS_DERC=0` keeps every Seq as `LogosSeq`.
1217    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Unbox) {
1218        return HashSet::new();
1219    }
1220    // Phase 3a/3b: a candidate passed at EITHER a readonly-borrow (`&[T]`) or a
1221    // mutable-borrow (`&mut [T]`) param slot is only borrowed for the call, not
1222    // retained — that is not an escape. Both call conventions pass a reference
1223    // to the de-Rc'd `Vec`, so the use-scan treats both as safe slots. (Codegen
1224    // distinguishes `&x` vs `&mut x` via its own borrow maps.)
1225    let borrow_slots: HashMap<Symbol, HashSet<usize>> = if mut_borrow_params.is_empty() {
1226        borrow_params.clone()
1227    } else {
1228        let mut m = borrow_params.clone();
1229        for (f, idx) in mut_borrow_params {
1230            m.entry(*f).or_default().extend(idx.iter().copied());
1231        }
1232        m
1233    };
1234    let borrow_params = &borrow_slots;
1235    let mut candidates = HashSet::new();
1236    collect_de_rc_candidates_block(stmts, interner, vec_return_fns, &mut candidates);
1237    if candidates.is_empty() {
1238        return candidates;
1239    }
1240    // A candidate survives ONLY if every one of its occurrences is in a
1241    // Vec-safe slot (the collection of push/pop/add/remove/setindex/index/
1242    // length, or a fresh-Seq decl/reassign). Any other occurrence — call arg,
1243    // return, given/shown whole, sliced, copied, stored as an element,
1244    // aliased, or inside any statement/expression kind not explicitly
1245    // permitted — disqualifies it. Conservative by construction: the worst
1246    // outcome of the catch-alls is a missed optimization, never an unsound
1247    // `Vec` used where a `LogosSeq` is required.
1248    // Phase 2: buffer-reuse swap pairs. `Set outer to inner`, where `inner` is
1249    // a fresh-per-iteration buffer, is lowered by codegen to `std::mem::swap`
1250    // (a content exchange, NOT a shared handle), so it must not be treated as
1251    // aliasing. Collect those (outer, inner) pairs so the use-scan exempts them.
1252    let mut swaps = HashSet::new();
1253    collect_buffer_swap_pairs(stmts, interner, &mut swaps);
1254
1255    let mut disqualified = HashSet::new();
1256    derc_scan_uses(
1257        stmts,
1258        &candidates,
1259        &swaps,
1260        borrow_params,
1261        mut_borrow_params,
1262        vec_return_fns,
1263        returns_vec,
1264        interner,
1265        &mut disqualified,
1266    );
1267    candidates.retain(|c| !disqualified.contains(c));
1268
1269    // A swap pair must de-Rc together — `std::mem::swap` needs both partners to
1270    // be the same type. If either is disqualified, drop both; the same holds for
1271    // the names a `Swap` statement exchanges. Iterate to a fixpoint so chained
1272    // pairs settle.
1273    let classes = crate::optimize::SwapClasses::of(stmts, interner);
1274    loop {
1275        let before = candidates.len();
1276        for (outer, inner) in &swaps {
1277            if candidates.contains(outer) != candidates.contains(inner) {
1278                candidates.remove(outer);
1279                candidates.remove(inner);
1280            }
1281        }
1282        classes.close_set(&mut candidates, interner);
1283        if candidates.len() == before {
1284            break;
1285        }
1286    }
1287    if !candidates.is_empty() {
1288        crate::optimize::mark_fired(crate::optimization::Opt::Unbox);
1289    }
1290    candidates
1291}
1292
1293/// Phase 4 — return-type de-Rc. A function declared to return `Seq of T` can
1294/// instead return `Vec<T>` when EVERY `Return` yields a uniquely-owned value:
1295/// a freshly-built local Seq (moved out), a readonly-BORROW param (copied via
1296/// `.to_vec()` — a borrow can't alias), a fresh-Seq expression, or a call to
1297/// another such function. Returning `Vec` removes the per-call Rc clone +
1298/// RefCell borrow and the Rc box, and — crucially — makes `Set x to f(...)` at
1299/// every call site a uniquely-owned fresh value, unblocking de-Rc on `x` (the
1300/// mergesort `left`/`right`/`result` chain, currently disqualified because the
1301/// callee returns `LogosSeq`). Fixpoint over the callgraph so a function that
1302/// returns a call to a not-yet-confirmed peer settles.
1303pub(super) fn collect_vec_return_fns(
1304    stmts: &[Stmt],
1305    interner: &Interner,
1306    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1307    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1308) -> HashSet<Symbol> {
1309    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Unbox) {
1310        return HashSet::new();
1311    }
1312    // Every non-native function declared to return a Seq/List/Vec, with its
1313    // body + params. Each is a CANDIDATE to instead return an owned `Vec<T>`.
1314    let mut seq_fns: Vec<(Symbol, &[Stmt], &[(Symbol, &TypeExpr)])> = Vec::new();
1315    for s in stmts {
1316        if let Stmt::FunctionDef {
1317            name,
1318            body,
1319            params,
1320            return_type: Some(rt),
1321            is_native: false,
1322            ..
1323        } = s
1324        {
1325            if is_vec_type_expr(rt, interner) {
1326                seq_fns.push((*name, body, params));
1327            }
1328        }
1329    }
1330    if seq_fns.is_empty() {
1331        return HashSet::new();
1332    }
1333
1334    // GREATEST FIXPOINT — return-type de-Rc is an interprocedural aliasing
1335    // problem co-dependent with each scope's local de-Rc set: a function `f`
1336    // returns `Vec` only if every return site AND every call site is owned-Vec
1337    // compatible, while a call site's result de-Rc's only if `f` returns `Vec`.
1338    // Start OPTIMISTIC (every candidate returns `Vec`), then SHRINK on any
1339    // soundness violation until stable. Monotone (removals only) ⇒ converges.
1340    //
1341    // `f` is removed when ANY holds (each would emit ill-typed `Vec`/`LogosSeq`
1342    // code, never silent corruption — the violations are type errors):
1343    //   (a) a `Return` in `f` yields a value that is not an owned Vec — i.e. NOT
1344    //       a readonly-borrow param (returns `.to_vec()`) and NOT a local that
1345    //       itself de-Rc's (returns the moved `Vec`). A LogosSeq local return
1346    //       would be `return os;` into a `-> Vec` signature.
1347    //   (b) a call site `Let/Set x to f(...)` whose result `x` does not de-Rc —
1348    //       a `Vec` assigned into a `LogosSeq` variable.
1349    //   (c) `f(...)` used in ANY inline / non-binding position (struct field,
1350    //       owned arg, `Return f(x)`, `Show f(x)`, nested expression) — a `Vec`
1351    //       where a `LogosSeq` is expected. Conservative: only a top-level
1352    //       `Let/Set x to f(...)` binding consumes the owned `Vec` cleanly.
1353    let mut vec_fns: HashSet<Symbol> = seq_fns.iter().map(|(n, _, _)| *n).collect();
1354    loop {
1355        let mut remove = HashSet::new();
1356
1357        // (c) any inline use anywhere in the program (recurses into fn bodies).
1358        flag_inline_vec_calls(stmts, &vec_fns, &mut remove);
1359
1360        // (a)+(b), per scope, with that scope's de-Rc set computed under the
1361        // CURRENT candidate set. Main's scope is the whole program slice
1362        // (`collect_de_rc_seqs` skips nested fn defs); each function's scope is
1363        // its own body with `returns_vec` = whether it is still a candidate.
1364        let main_de_rc = collect_de_rc_seqs(
1365            stmts,
1366            interner,
1367            borrow_params,
1368            mut_borrow_params,
1369            &vec_fns,
1370            false,
1371        );
1372        collect_unsound_vec_returns(stmts, &vec_fns, &main_de_rc, &mut remove);
1373        for (name, body, params) in &seq_fns {
1374            let rv = vec_fns.contains(name);
1375            let de_rc = collect_de_rc_seqs(
1376                body,
1377                interner,
1378                borrow_params,
1379                mut_borrow_params,
1380                &vec_fns,
1381                rv,
1382            );
1383            collect_unsound_vec_returns(body, &vec_fns, &de_rc, &mut remove);
1384            if rv && !all_returns_vec_ownable(body, params, borrow_params.get(name), &de_rc) {
1385                remove.insert(*name);
1386            }
1387        }
1388
1389        if remove.is_empty() {
1390            break;
1391        }
1392        vec_fns.retain(|f| !remove.contains(f));
1393    }
1394    if !vec_fns.is_empty() {
1395        crate::optimize::mark_fired(crate::optimization::Opt::Unbox);
1396    }
1397    vec_fns
1398}
1399
1400/// Record any `f ∈ vec_fns` that has a call site `Let/Set x to f(...)` whose
1401/// result variable `x` is NOT de-Rc'd in this scope — returning `Vec` there
1402/// would assign a `Vec` into a `LogosSeq` variable.
1403fn collect_unsound_vec_returns(
1404    stmts: &[Stmt],
1405    vec_fns: &HashSet<Symbol>,
1406    de_rc: &HashSet<Symbol>,
1407    remove: &mut HashSet<Symbol>,
1408) {
1409    for stmt in stmts {
1410        let binding = match stmt {
1411            Stmt::Let { var, value, .. } => Some((*var, value)),
1412            Stmt::Set { target, value } => Some((*target, value)),
1413            _ => None,
1414        };
1415        if let Some((x, Expr::Call { function, .. })) = binding {
1416            if vec_fns.contains(function) && !de_rc.contains(&x) {
1417                remove.insert(*function);
1418            }
1419        }
1420        match stmt {
1421            Stmt::If {
1422                then_block,
1423                else_block,
1424                ..
1425            } => {
1426                collect_unsound_vec_returns(then_block, vec_fns, de_rc, remove);
1427                if let Some(eb) = else_block {
1428                    collect_unsound_vec_returns(eb, vec_fns, de_rc, remove);
1429                }
1430            }
1431            Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
1432                collect_unsound_vec_returns(body, vec_fns, de_rc, remove)
1433            }
1434            _ => {}
1435        }
1436    }
1437}
1438
1439/// Condition (a): every `Return` in `body` yields a value the codegen can hand
1440/// back as an owned `Vec<T>`. Only two return shapes are owned-Vec compatible:
1441///   - a readonly-BORROW param (idx ∈ `borrow_idx`) → `return p.to_vec();` (a
1442///     copy — a borrow can never alias the caller's value), or
1443///   - a LOCAL that itself de-Rc's (`x ∈ de_rc`) → `return x;` (the moved Vec).
1444/// Anything else — a LogosSeq local, a bare fresh/slice/copy expression, an
1445/// owned param, a valueless `Return` — would emit a value of the wrong type
1446/// into the `-> Vec<T>` signature, so it disqualifies the function. (Inline
1447/// peer-call returns like `Return g(x)` are handled by the inline-use check.)
1448fn all_returns_vec_ownable(
1449    body: &[Stmt],
1450    params: &[(Symbol, &TypeExpr)],
1451    borrow_idx: Option<&HashSet<usize>>,
1452    de_rc: &HashSet<Symbol>,
1453) -> bool {
1454    fn walk(
1455        stmts: &[Stmt],
1456        params: &[(Symbol, &TypeExpr)],
1457        borrow_idx: Option<&HashSet<usize>>,
1458        de_rc: &HashSet<Symbol>,
1459        ok: &mut bool,
1460    ) {
1461        for s in stmts {
1462            match s {
1463                Stmt::Return { value: Some(e) } => {
1464                    if !is_vec_ownable_return(e, params, borrow_idx, de_rc) {
1465                        *ok = false;
1466                    }
1467                }
1468                Stmt::Return { value: None } => *ok = false,
1469                Stmt::If {
1470                    then_block,
1471                    else_block,
1472                    ..
1473                } => {
1474                    walk(then_block, params, borrow_idx, de_rc, ok);
1475                    if let Some(eb) = else_block {
1476                        walk(eb, params, borrow_idx, de_rc, ok);
1477                    }
1478                }
1479                Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
1480                    walk(body, params, borrow_idx, de_rc, ok)
1481                }
1482                _ => {}
1483            }
1484        }
1485    }
1486    let mut ok = true;
1487    walk(body, params, borrow_idx, de_rc, &mut ok);
1488    ok
1489}
1490
1491fn is_vec_ownable_return(
1492    e: &Expr,
1493    params: &[(Symbol, &TypeExpr)],
1494    borrow_idx: Option<&HashSet<usize>>,
1495    de_rc: &HashSet<Symbol>,
1496) -> bool {
1497    match e {
1498        Expr::Identifier(x) => match params.iter().position(|(p, _)| p == x) {
1499            // A readonly-BORROW param: `return p.to_vec();` — a copy, cannot alias.
1500            Some(idx) => borrow_idx.map_or(false, |b| b.contains(&idx)),
1501            // A LOCAL that de-Rc's: it is already a `Vec<T>` → `return x;`.
1502            None => de_rc.contains(x),
1503        },
1504        _ => false,
1505    }
1506}
1507
1508/// Condition (c): flag every `f ∈ vec_fns` whose call result is consumed in an
1509/// inline / non-binding position — anywhere other than the outermost RHS of a
1510/// top-level `Let/Set x to f(...)`. Such a position (struct field, owned arg,
1511/// `Return f(x)`, `Show f(x)`, a nested sub-expression, a control condition)
1512/// expects a `LogosSeq`, so an owned `Vec` return would not type-check.
1513/// Recurses into nested function bodies. Uses `symbol_appears_in_*` (the same
1514/// complete walker the de-Rc disqualification rests on) so its coverage matches.
1515fn flag_inline_vec_calls(stmts: &[Stmt], vec_fns: &HashSet<Symbol>, remove: &mut HashSet<Symbol>) {
1516    let flag_in_expr = |e: &Expr, remove: &mut HashSet<Symbol>| {
1517        for &f in vec_fns {
1518            if symbol_appears_in_expr(f, e) {
1519                remove.insert(f);
1520            }
1521        }
1522    };
1523    for stmt in stmts {
1524        match stmt {
1525            Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
1526                // The outermost call of a binding RHS is the one SAFE consuming
1527                // position (its result is named; `collect_unsound_vec_returns`
1528                // separately requires that name to de-Rc). Only the call's ARGS
1529                // are inline positions here.
1530                if let Expr::Call { args, .. } = value {
1531                    for a in args.iter() {
1532                        flag_in_expr(a, remove);
1533                    }
1534                } else {
1535                    flag_in_expr(value, remove);
1536                }
1537            }
1538            Stmt::If {
1539                cond,
1540                then_block,
1541                else_block,
1542            } => {
1543                flag_in_expr(cond, remove);
1544                flag_inline_vec_calls(then_block, vec_fns, remove);
1545                if let Some(eb) = else_block {
1546                    flag_inline_vec_calls(eb, vec_fns, remove);
1547                }
1548            }
1549            Stmt::While { cond, body, .. } => {
1550                flag_in_expr(cond, remove);
1551                flag_inline_vec_calls(body, vec_fns, remove);
1552            }
1553            Stmt::Repeat { iterable, body, .. } => {
1554                flag_in_expr(iterable, remove);
1555                flag_inline_vec_calls(body, vec_fns, remove);
1556            }
1557            Stmt::Zone { body, .. } | Stmt::FunctionDef { body, .. } => {
1558                flag_inline_vec_calls(body, vec_fns, remove)
1559            }
1560            // Every other statement kind (Return, Show, Give, Push, Add, Remove,
1561            // SetIndex, Call, Inspect, …): a vec-fn call anywhere inside is an
1562            // inline use. `symbol_appears_in_stmt` is the complete walker.
1563            other => {
1564                for &f in vec_fns {
1565                    if symbol_appears_in_stmt(f, other) {
1566                        remove.insert(f);
1567                    }
1568                }
1569            }
1570        }
1571    }
1572}
1573
1574/// `value` is a call to a function that returns an owned `Vec` (Phase 4) — so
1575/// `Set x to value` binds `x` to a uniquely-owned fresh value, not a shared
1576/// callee handle.
1577fn is_vec_return_call(value: &Expr, vec_return_fns: &HashSet<Symbol>) -> bool {
1578    matches!(value, Expr::Call { function, .. } if vec_return_fns.contains(function))
1579}
1580
1581/// Phase 3b: `value` is a call `f(..., target, ...)` where `f` mutably borrows
1582/// `target` at the position `target` appears. Codegen lowers `Set target to
1583/// f(...)` to the in-place call `f(&mut target, ...)`, so it is a mutation of
1584/// `target`, not a rebinding — `target` keeps its identity and de-Rc eligibility.
1585fn is_mut_borrow_inplace_call(
1586    target: Symbol,
1587    value: &Expr,
1588    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1589) -> bool {
1590    if let Expr::Call { function, args } = value {
1591        if let Some(slots) = mut_borrow_params.get(function) {
1592            return args.iter().enumerate().any(|(i, a)| {
1593                slots.contains(&i) && matches!(a, Expr::Identifier(s) if *s == target)
1594            });
1595        }
1596    }
1597    false
1598}
1599
1600/// Collect `(outer, inner)` pairs where `Set outer to inner` is a buffer-reuse
1601/// swap: `inner` is declared `Let mutable inner = <fresh Seq>` earlier in the
1602/// same loop body and is not referenced after the `Set`. These exactly mirror
1603/// `detect_buffer_reuse_in_body`'s shape, so codegen lowers each to
1604/// `std::mem::swap` — content exchange, not aliasing.
1605fn collect_buffer_swap_pairs(
1606    stmts: &[Stmt],
1607    interner: &Interner,
1608    out: &mut HashSet<(Symbol, Symbol)>,
1609) {
1610    for stmt in stmts {
1611        match stmt {
1612            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
1613                detect_swap_in_body(body, interner, out);
1614                collect_buffer_swap_pairs(body, interner, out);
1615            }
1616            Stmt::If {
1617                then_block,
1618                else_block,
1619                ..
1620            } => {
1621                collect_buffer_swap_pairs(then_block, interner, out);
1622                if let Some(eb) = else_block {
1623                    collect_buffer_swap_pairs(eb, interner, out);
1624                }
1625            }
1626            Stmt::Zone { body, .. } => collect_buffer_swap_pairs(body, interner, out),
1627            _ => {}
1628        }
1629    }
1630}
1631
1632fn detect_swap_in_body(body: &[Stmt], interner: &Interner, out: &mut HashSet<(Symbol, Symbol)>) {
1633    let mut fresh_inner: HashSet<Symbol> = HashSet::new();
1634    for stmt in body {
1635        if let Stmt::Let {
1636            var,
1637            value,
1638            mutable: true,
1639            ..
1640        } = stmt
1641        {
1642            if is_fresh_seq_value(value, interner) {
1643                fresh_inner.insert(*var);
1644            }
1645        }
1646    }
1647    if fresh_inner.is_empty() {
1648        return;
1649    }
1650    for (idx, stmt) in body.iter().enumerate() {
1651        if let Stmt::Set {
1652            target,
1653            value: Expr::Identifier(src),
1654        } = stmt
1655        {
1656            if *target != *src && fresh_inner.contains(src) {
1657                let used_after = body[idx + 1..]
1658                    .iter()
1659                    .any(|s| symbol_appears_in_stmt(*src, s));
1660                if !used_after {
1661                    out.insert((*target, *src));
1662                }
1663            }
1664        }
1665    }
1666}
1667
1668/// Walk every statement, disqualifying any candidate that appears outside a
1669/// Vec-safe slot. Buffer-reuse swap pairs are exempt from the alias rule.
1670fn derc_scan_uses(
1671    stmts: &[Stmt],
1672    cands: &HashSet<Symbol>,
1673    swaps: &HashSet<(Symbol, Symbol)>,
1674    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1675    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1676    vec_return_fns: &HashSet<Symbol>,
1677    returns_vec: bool,
1678    interner: &Interner,
1679    dq: &mut HashSet<Symbol>,
1680) {
1681    for stmt in stmts {
1682        derc_scan_stmt(
1683            stmt,
1684            cands,
1685            swaps,
1686            borrow_params,
1687            mut_borrow_params,
1688            vec_return_fns,
1689            returns_vec,
1690            interner,
1691            dq,
1692        );
1693    }
1694}
1695
1696/// Phase 3: a candidate passed at a READONLY-borrow-param position (`&[T]`) is
1697/// only borrowed, never retained — that is NOT an escape, so it stays eligible
1698/// and the call site passes `&vec`. A candidate at any other arg position
1699/// (owned param, or a callee with no borrow info) escapes and is disqualified.
1700fn derc_scan_call_args(
1701    function: Symbol,
1702    args: &[&Expr],
1703    cands: &HashSet<Symbol>,
1704    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1705    dq: &mut HashSet<Symbol>,
1706) {
1707    let slots = borrow_params.get(&function);
1708    for (i, a) in args.iter().enumerate() {
1709        match a {
1710            Expr::Identifier(s) if cands.contains(s) => {
1711                let is_borrow_slot = slots.map_or(false, |set| set.contains(&i));
1712                if !is_borrow_slot {
1713                    dq.insert(*s);
1714                }
1715            }
1716            _ => derc_scan_expr(a, cands, borrow_params, dq),
1717        }
1718    }
1719}
1720
1721/// True if `value` is a fresh Seq/List allocation (a safe decl/reassign source).
1722fn is_fresh_seq_value(value: &Expr, interner: &Interner) -> bool {
1723    match value {
1724        Expr::New {
1725            type_name,
1726            init_fields,
1727            ..
1728        } if init_fields.is_empty() => {
1729            matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec")
1730        }
1731        Expr::WithCapacity { value: inner, .. } => is_fresh_seq_value(inner, interner),
1732        Expr::List(_) => true,
1733        _ => false,
1734    }
1735}
1736
1737fn derc_scan_stmt(
1738    stmt: &Stmt,
1739    cands: &HashSet<Symbol>,
1740    swaps: &HashSet<(Symbol, Symbol)>,
1741    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1742    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1743    vec_return_fns: &HashSet<Symbol>,
1744    returns_vec: bool,
1745    interner: &Interner,
1746    dq: &mut HashSet<Symbol>,
1747) {
1748    match stmt {
1749        // A fresh-Seq decl is the safe origin; otherwise the initializer is a
1750        // general use of whatever it references.
1751        Stmt::Let { value, .. } => {
1752            if is_vec_return_call(value, vec_return_fns) {
1753                // Phase 4: `Let r be f(...)` with f returning an OWNED Vec — r
1754                // captures a uniquely-owned fresh value, not a shared handle.
1755                // Still scan the call's args.
1756                if let Expr::Call { function, args } = value {
1757                    derc_scan_call_args(*function, args, cands, borrow_params, dq);
1758                }
1759            } else if !is_fresh_seq_value(value, interner) {
1760                derc_scan_expr(value, cands, borrow_params, dq);
1761            }
1762        }
1763        Stmt::Set { target, value } => {
1764            if let Expr::Identifier(src) = value {
1765                if swaps.contains(&(*target, *src)) {
1766                    // Buffer-reuse swap → content exchange (`std::mem::swap`),
1767                    // not aliasing. Both partners stay eligible.
1768                } else if target != src {
1769                    // `Set x to y` rebinds x onto y's allocation — both lose
1770                    // unique ownership.
1771                    dq.insert(*src);
1772                    dq.insert(*target);
1773                }
1774            } else if is_vec_return_call(value, vec_return_fns) {
1775                // Phase 4: `Set x to f(...)` where f returns an OWNED Vec — x
1776                // captures a uniquely-owned fresh value, not a shared callee
1777                // handle, so x stays eligible. Still scan the call's args (a
1778                // candidate passed to a NON-borrow param would escape).
1779                if let Expr::Call { function, args } = value {
1780                    derc_scan_call_args(*function, args, cands, borrow_params, dq);
1781                }
1782            } else if is_mut_borrow_inplace_call(*target, value, mut_borrow_params) {
1783                // Phase 3b: `Set x to f(..., x, ...)` where `f` mut-borrows `x`
1784                // at x's position is lowered to an IN-PLACE call `f(&mut x, ...)`
1785                // — the "result" is x itself, not a reassignment, so x keeps its
1786                // unique ownership and stays eligible. Scan the OTHER args (a
1787                // candidate passed to a non-borrow slot still escapes).
1788                if let Expr::Call { function, args } = value {
1789                    derc_scan_call_args(*function, args, cands, borrow_params, dq);
1790                }
1791            } else if !is_fresh_seq_value(value, interner) {
1792                // `Set x to <non-fresh value>` (a call result, slice, copy, …)
1793                // rebinds x to a value that is NOT a uniquely-owned fresh Vec —
1794                // e.g. `Set right to mergeSort(right)` binds right to a callee's
1795                // returned `LogosSeq`. Disqualify the target.
1796                dq.insert(*target);
1797                derc_scan_expr(value, cands, borrow_params, dq);
1798            }
1799        }
1800        // Collection slots are safe for a bare candidate; the value/index are
1801        // general uses.
1802        Stmt::Push { value, collection } | Stmt::Add { value, collection } => {
1803            derc_scan_collection_slot(collection, cands, borrow_params, dq);
1804            derc_scan_expr(value, cands, borrow_params, dq);
1805        }
1806        Stmt::Pop { collection, .. } => {
1807            derc_scan_collection_slot(collection, cands, borrow_params, dq)
1808        }
1809        Stmt::Remove { value, collection } => {
1810            derc_scan_collection_slot(collection, cands, borrow_params, dq);
1811            derc_scan_expr(value, cands, borrow_params, dq);
1812        }
1813        Stmt::SetIndex {
1814            collection,
1815            index,
1816            value,
1817        } => {
1818            derc_scan_collection_slot(collection, cands, borrow_params, dq);
1819            derc_scan_expr(index, cands, borrow_params, dq);
1820            derc_scan_expr(value, cands, borrow_params, dq);
1821        }
1822        Stmt::If {
1823            cond,
1824            then_block,
1825            else_block,
1826        } => {
1827            derc_scan_expr(cond, cands, borrow_params, dq);
1828            derc_scan_uses(
1829                then_block,
1830                cands,
1831                swaps,
1832                borrow_params,
1833                mut_borrow_params,
1834                vec_return_fns,
1835                returns_vec,
1836                interner,
1837                dq,
1838            );
1839            if let Some(eb) = else_block {
1840                derc_scan_uses(
1841                    eb,
1842                    cands,
1843                    swaps,
1844                    borrow_params,
1845                    mut_borrow_params,
1846                    vec_return_fns,
1847                    returns_vec,
1848                    interner,
1849                    dq,
1850                );
1851            }
1852        }
1853        Stmt::While { cond, body, .. } => {
1854            derc_scan_expr(cond, cands, borrow_params, dq);
1855            derc_scan_uses(
1856                body,
1857                cands,
1858                swaps,
1859                borrow_params,
1860                mut_borrow_params,
1861                vec_return_fns,
1862                returns_vec,
1863                interner,
1864                dq,
1865            );
1866        }
1867        Stmt::Repeat { iterable, body, .. } => {
1868            // Iterating a de-Rc'd Vec is not lowered in v1 → treat as a use.
1869            derc_scan_expr(iterable, cands, borrow_params, dq);
1870            derc_scan_uses(
1871                body,
1872                cands,
1873                swaps,
1874                borrow_params,
1875                mut_borrow_params,
1876                vec_return_fns,
1877                returns_vec,
1878                interner,
1879                dq,
1880            );
1881        }
1882        Stmt::Zone { body, .. } => derc_scan_uses(
1883            body,
1884            cands,
1885            swaps,
1886            borrow_params,
1887            mut_borrow_params,
1888            vec_return_fns,
1889            returns_vec,
1890            interner,
1891            dq,
1892        ),
1893        // Statements that carry expressions which may legitimately pass a
1894        // candidate to a borrow-param: scan position-aware.
1895        Stmt::Call { function, args } => {
1896            derc_scan_call_args(*function, args, cands, borrow_params, dq);
1897        }
1898        // Phase 4: in a Vec-returning function, returning a candidate LOCAL
1899        // moves it out as the owned Vec result — not a disqualifying escape.
1900        Stmt::Return { value: Some(e) } => {
1901            if !(returns_vec && matches!(e, Expr::Identifier(x) if cands.contains(x))) {
1902                derc_scan_expr(e, cands, borrow_params, dq);
1903            }
1904        }
1905        Stmt::Return { value: None } => {}
1906        Stmt::Show { object, recipient } | Stmt::Give { object, recipient } => {
1907            derc_scan_expr(object, cands, borrow_params, dq);
1908            derc_scan_expr(recipient, cands, borrow_params, dq);
1909        }
1910        // A nested function is a SEPARATE scope with its own de-Rc analysis. Its
1911        // parameter/local symbols are distinct bindings even when they reuse an
1912        // outer name (the interner gives `arr` one Symbol, but main's `arr` and a
1913        // function's `arr` param are different variables). The outer scan must
1914        // NOT descend — a candidate can only reach a function through explicit
1915        // call args, which are checked at the call site. Skipping keeps a
1916        // name-collision from spuriously disqualifying an outer candidate.
1917        Stmt::FunctionDef { .. } => {}
1918        // A swap exchanges two uniquely-owned buffers whole (`std::mem::swap`);
1919        // `SwapClasses` keeps the two the same type.
1920        Stmt::Swap { .. } => {}
1921        // Every other statement kind (SetField, Concurrent, …): any candidate
1922        // that appears anywhere in it is an unsafe use. `symbol_appears_in_stmt`
1923        // is a complete walker.
1924        other => {
1925            for &c in cands {
1926                if symbol_appears_in_stmt(c, other) {
1927                    dq.insert(c);
1928                }
1929            }
1930        }
1931    }
1932}
1933
1934/// The collection position of an indexing/mutation op: a bare candidate
1935/// identifier here is the SAFE Vec target; a nested expression is scanned.
1936fn derc_scan_collection_slot(
1937    collection: &Expr,
1938    cands: &HashSet<Symbol>,
1939    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1940    dq: &mut HashSet<Symbol>,
1941) {
1942    match collection {
1943        Expr::Identifier(_) => {}
1944        other => derc_scan_expr(other, cands, borrow_params, dq),
1945    }
1946}
1947
1948/// Disqualify any candidate that appears in `expr` outside an index/length
1949/// collection slot. Expression kinds that may legitimately read a candidate by
1950/// index (BinaryOp, Not, Call args) are recursed position-aware; every other
1951/// kind is treated conservatively — any candidate inside is an unsafe use.
1952fn derc_scan_expr(
1953    expr: &Expr,
1954    cands: &HashSet<Symbol>,
1955    borrow_params: &HashMap<Symbol, HashSet<usize>>,
1956    dq: &mut HashSet<Symbol>,
1957) {
1958    match expr {
1959        Expr::Identifier(s) => {
1960            if cands.contains(s) {
1961                dq.insert(*s);
1962            }
1963        }
1964        Expr::Index { collection, index } => {
1965            derc_scan_collection_slot(collection, cands, borrow_params, dq);
1966            derc_scan_expr(index, cands, borrow_params, dq);
1967        }
1968        Expr::Length { collection } => {
1969            derc_scan_collection_slot(collection, cands, borrow_params, dq)
1970        }
1971        Expr::BinaryOp { left, right, .. } => {
1972            derc_scan_expr(left, cands, borrow_params, dq);
1973            derc_scan_expr(right, cands, borrow_params, dq);
1974        }
1975        Expr::Not { operand } => derc_scan_expr(operand, cands, borrow_params, dq),
1976        Expr::Call { function, args } => {
1977            derc_scan_call_args(*function, args, cands, borrow_params, dq);
1978        }
1979        // Slice, Copy, FieldAccess, interpolation, New init-fields, and any
1980        // other kind: a candidate appearing inside is an unsafe use.
1981        // `symbol_appears_in_expr` is a complete walker.
1982        other => {
1983            for &c in cands {
1984                if symbol_appears_in_expr(c, other) {
1985                    dq.insert(c);
1986                }
1987            }
1988        }
1989    }
1990}
1991
1992/// Rust element type of a homogeneous **scalar-literal** list, or `None` when the list is
1993/// empty, mixed-kind, or has any non-scalar-literal element. `[1,2,3]`→`i64`, `[1.0,…]`→`f64`,
1994/// `[true,…]`→`bool`, `['a',…]`→`char`. Such a list is a uniquely-owned fresh value with no
1995/// borrowed handle inside it, so it de-Rc's from `LogosSeq<T>` to a plain `Vec<T>`. Detection
1996/// (`fresh_scalar_seq_elem`) and codegen (`derc_vec_decl`) BOTH route through this one helper
1997/// so their eligibility can never drift.
1998pub(crate) fn homogeneous_scalar_literal_elem(items: &[&Expr]) -> Option<String> {
1999    fn elem_ty(e: &Expr) -> Option<&'static str> {
2000        match e {
2001            Expr::Literal(Literal::Number(_)) => Some("i64"),
2002            Expr::Literal(Literal::Float(_)) => Some("f64"),
2003            Expr::Literal(Literal::Boolean(_)) => Some("bool"),
2004            Expr::Literal(Literal::Char(_)) => Some("char"),
2005            _ => None,
2006        }
2007    }
2008    let first = elem_ty(items.first()?)?;
2009    if items.iter().all(|i| elem_ty(i) == Some(first)) {
2010        Some(first.to_string())
2011    } else {
2012        None
2013    }
2014}
2015
2016/// The Rust element type string if `value` freshly allocates a Seq of scalars.
2017fn fresh_scalar_seq_elem(value: &Expr, interner: &Interner) -> Option<String> {
2018    match value {
2019        Expr::New {
2020            type_name,
2021            type_args,
2022            init_fields,
2023        } if init_fields.is_empty() => match interner.resolve(*type_name) {
2024            "Seq" | "List" | "Vec" => {
2025                let elem = type_args.first()?;
2026                let ty = codegen_type_expr(elem, interner);
2027                if is_scalar_elem_type(&ty) {
2028                    Some(ty)
2029                } else {
2030                    None
2031                }
2032            }
2033            _ => None,
2034        },
2035        Expr::WithCapacity { value: inner, .. } => fresh_scalar_seq_elem(inner, interner),
2036        // A homogeneous SCALAR-literal list (`[1,2,3]`, `[1.0,…]`, `[true,…]`, `['a',…]`) is a
2037        // uniquely-owned fresh Seq — de-Rc it to a plain `Vec<T>` so indexed access skips the
2038        // RefCell borrow + the Rc box. The use-scan still disqualifies any occurrence that
2039        // escapes a Vec-safe slot.
2040        Expr::List(items) => homogeneous_scalar_literal_elem(items),
2041        _ => None,
2042    }
2043}
2044
2045/// Scalar element types whose reads copy (no shared handle): safe to de-Rc.
2046fn is_scalar_elem_type(ty: &str) -> bool {
2047    matches!(
2048        ty,
2049        "i64" | "i32" | "i16" | "i8" | "u64" | "u32" | "u16" | "u8" | "usize" | "isize"
2050            | "f64" | "f32" | "bool" | "char" | "String"
2051            // Fixed-width word newtypes are Copy scalars (repr(transparent)) → de-Rc to `Vec<WordN>`.
2052            | "Word8" | "Word16" | "Word32" | "Word64"
2053    )
2054}
2055
2056fn collect_de_rc_candidates_block(
2057    stmts: &[Stmt],
2058    interner: &Interner,
2059    vec_return_fns: &HashSet<Symbol>,
2060    out: &mut HashSet<Symbol>,
2061) {
2062    for stmt in stmts {
2063        match stmt {
2064            Stmt::Let { var, value, .. } => {
2065                // A fresh-Seq decl, or a binding to a Phase-4 Vec-returning call
2066                // (`Let r be buildSeq(4)`) — both capture a uniquely-owned value.
2067                if fresh_scalar_seq_elem(value, interner).is_some()
2068                    || is_vec_return_call(value, vec_return_fns)
2069                {
2070                    out.insert(*var);
2071                }
2072            }
2073            Stmt::If {
2074                then_block,
2075                else_block,
2076                ..
2077            } => {
2078                collect_de_rc_candidates_block(then_block, interner, vec_return_fns, out);
2079                if let Some(eb) = else_block {
2080                    collect_de_rc_candidates_block(eb, interner, vec_return_fns, out);
2081                }
2082            }
2083            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
2084                collect_de_rc_candidates_block(body, interner, vec_return_fns, out);
2085            }
2086            Stmt::Zone { body, .. } => {
2087                collect_de_rc_candidates_block(body, interner, vec_return_fns, out);
2088            }
2089            _ => {}
2090        }
2091    }
2092}
2093
2094/// Collect locally-created Seq/List variables that escape the function body.
2095/// A variable "escapes" if it is:
2096/// - Passed to a function call (without `copy of` wrapper)
2097/// - Returned from the function
2098/// Variables NOT in the returned set can safely use `Vec<T>` instead of `LogosSeq<T>`.
2099pub(super) fn collect_escaping_collection_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
2100    let mut escaped = HashSet::new();
2101    collect_escaping_vars_block(stmts, &mut escaped);
2102    escaped
2103}
2104
2105fn collect_escaping_vars_block(stmts: &[Stmt], escaped: &mut HashSet<Symbol>) {
2106    for stmt in stmts {
2107        collect_escaping_vars_stmt(stmt, escaped);
2108    }
2109}
2110
2111fn collect_escaping_vars_stmt(stmt: &Stmt, escaped: &mut HashSet<Symbol>) {
2112    match stmt {
2113        Stmt::Call { args, .. } => {
2114            for arg in args.iter() {
2115                collect_escaping_vars_from_call_arg(arg, escaped);
2116            }
2117        }
2118        Stmt::Return { value: Some(expr) } => {
2119            if let Expr::Identifier(sym) = expr {
2120                escaped.insert(*sym);
2121            }
2122        }
2123        Stmt::If {
2124            then_block,
2125            else_block,
2126            ..
2127        } => {
2128            collect_escaping_vars_block(then_block, escaped);
2129            if let Some(else_stmts) = else_block {
2130                collect_escaping_vars_block(else_stmts, escaped);
2131            }
2132        }
2133        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
2134            collect_escaping_vars_block(body, escaped);
2135        }
2136        Stmt::Let { value, .. } => {
2137            collect_escaping_vars_from_expr_calls(value, escaped);
2138        }
2139        Stmt::Set { value, .. } => {
2140            collect_escaping_vars_from_expr_calls(value, escaped);
2141        }
2142        _ => {}
2143    }
2144}
2145
2146/// Check if an expression is a direct call arg (not wrapped in Copy).
2147fn collect_escaping_vars_from_call_arg(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2148    match expr {
2149        Expr::Identifier(sym) => {
2150            escaped.insert(*sym);
2151        }
2152        Expr::Copy { .. } => { /* copy of X does not cause X to escape */ }
2153        _ => {
2154            // For complex expressions, check nested identifiers
2155            collect_escaping_vars_from_expr_ids(expr, escaped);
2156        }
2157    }
2158}
2159
2160/// Collect identifiers that appear as direct args in Call expressions within an expression.
2161fn collect_escaping_vars_from_expr_calls(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2162    match expr {
2163        Expr::Call { args, .. } => {
2164            for arg in args.iter() {
2165                collect_escaping_vars_from_call_arg(arg, escaped);
2166            }
2167        }
2168        Expr::BinaryOp { left, right, .. } => {
2169            collect_escaping_vars_from_expr_calls(left, escaped);
2170            collect_escaping_vars_from_expr_calls(right, escaped);
2171        }
2172        _ => {}
2173    }
2174}
2175
2176/// Collect direct identifier references from a non-Copy expression used as a call arg.
2177fn collect_escaping_vars_from_expr_ids(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2178    match expr {
2179        Expr::Identifier(sym) => {
2180            escaped.insert(*sym);
2181        }
2182        Expr::BinaryOp { left, right, .. } => {
2183            collect_escaping_vars_from_expr_ids(left, escaped);
2184            collect_escaping_vars_from_expr_ids(right, escaped);
2185        }
2186        _ => {}
2187    }
2188}
2189
2190/// Extract a debug prefix string from an expression for `{var=}` format.
2191pub(super) fn expr_debug_prefix(expr: &Expr, interner: &Interner) -> String {
2192    match expr {
2193        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
2194        _ => "expr".to_string(),
2195    }
2196}
2197
2198/// Collect identifiers from a statement's expressions (for Concurrent/Parallel variable capture).
2199pub(super) fn collect_stmt_identifiers(stmt: &Stmt, identifiers: &mut HashSet<Symbol>) {
2200    match stmt {
2201        Stmt::Let { value, .. } => {
2202            collect_expr_identifiers(value, identifiers);
2203        }
2204        Stmt::Call { args, .. } => {
2205            for arg in args {
2206                collect_expr_identifiers(arg, identifiers);
2207            }
2208        }
2209        _ => {}
2210    }
2211}
2212
2213/// Collect parameter indices where any call site passes `Give` as the argument.
2214/// If a caller writes `Call f with Give x`, index 0 must not be borrowed as &[T].
2215pub(super) fn collect_give_arg_indices(fn_sym: Symbol, stmts: &[Stmt]) -> HashSet<usize> {
2216    let mut result = HashSet::new();
2217    for stmt in stmts {
2218        scan_give_args_stmt(fn_sym, stmt, &mut result);
2219    }
2220    result
2221}
2222
2223fn scan_give_args_stmt(fn_sym: Symbol, stmt: &Stmt, result: &mut HashSet<usize>) {
2224    match stmt {
2225        Stmt::Call { function, args } => {
2226            if *function == fn_sym {
2227                for (i, arg) in args.iter().enumerate() {
2228                    if matches!(arg, Expr::Give { .. }) {
2229                        result.insert(i);
2230                    }
2231                }
2232            }
2233            for arg in args {
2234                scan_give_args_expr(fn_sym, arg, result);
2235            }
2236        }
2237        Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
2238            scan_give_args_expr(fn_sym, value, result);
2239        }
2240        Stmt::Return { value: Some(v) } => scan_give_args_expr(fn_sym, v, result),
2241        Stmt::FunctionDef { body, .. } => {
2242            for s in *body {
2243                scan_give_args_stmt(fn_sym, s, result);
2244            }
2245        }
2246        Stmt::If {
2247            then_block,
2248            else_block,
2249            ..
2250        } => {
2251            for s in *then_block {
2252                scan_give_args_stmt(fn_sym, s, result);
2253            }
2254            if let Some(b) = else_block {
2255                for s in *b {
2256                    scan_give_args_stmt(fn_sym, s, result);
2257                }
2258            }
2259        }
2260        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
2261            for s in *body {
2262                scan_give_args_stmt(fn_sym, s, result);
2263            }
2264        }
2265        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
2266            for s in *tasks {
2267                scan_give_args_stmt(fn_sym, s, result);
2268            }
2269        }
2270        Stmt::Inspect { arms, .. } => {
2271            for arm in arms.iter() {
2272                for s in arm.body.iter() {
2273                    scan_give_args_stmt(fn_sym, s, result);
2274                }
2275            }
2276        }
2277        _ => {}
2278    }
2279}
2280
2281fn scan_give_args_expr(fn_sym: Symbol, expr: &Expr, result: &mut HashSet<usize>) {
2282    match expr {
2283        Expr::Call { function, args } => {
2284            if *function == fn_sym {
2285                for (i, arg) in args.iter().enumerate() {
2286                    if matches!(arg, Expr::Give { .. }) {
2287                        result.insert(i);
2288                    }
2289                }
2290            }
2291            for arg in args {
2292                scan_give_args_expr(fn_sym, arg, result);
2293            }
2294        }
2295        Expr::BinaryOp { left, right, .. } => {
2296            scan_give_args_expr(fn_sym, left, result);
2297            scan_give_args_expr(fn_sym, right, result);
2298        }
2299        Expr::FieldAccess { object, .. }
2300        | Expr::Give { value: object }
2301        | Expr::Copy { expr: object }
2302        | Expr::Length { collection: object } => {
2303            scan_give_args_expr(fn_sym, object, result);
2304        }
2305        Expr::Index { collection, index } => {
2306            scan_give_args_expr(fn_sym, collection, result);
2307            scan_give_args_expr(fn_sym, index, result);
2308        }
2309        Expr::List(items) | Expr::Tuple(items) => {
2310            for item in items {
2311                scan_give_args_expr(fn_sym, item, result);
2312            }
2313        }
2314        _ => {}
2315    }
2316}
2317
2318// =============================================================================
2319// Closed-Form Double Recursion Detection
2320// =============================================================================
2321
2322/// Result of detecting a closed-form double recursion pattern.
2323/// For f(0) = base, f(d) = k + f(d-1) + f(d-1), the closed form is:
2324/// f(d) = ((base + k) << d) - k
2325pub(super) struct ClosedFormInfo {
2326    pub base: i64,
2327    pub k: i64,
2328}
2329
2330/// Detect "double recursion with constant addend" pattern:
2331///   f(0) = base
2332///   f(d) = k + f(d-1) + f(d-1)
2333/// where base and k are integer constants. Returns the closed-form parameters.
2334///
2335/// GCC/LLVM recognize this pattern and replace it with bit shifts at -O2.
2336/// This detection lets Logos emit the same closed form.
2337pub(super) fn detect_double_recursion_closed_form<'a>(
2338    func_name: Symbol,
2339    params: &[(Symbol, &'a TypeExpr<'a>)],
2340    body: &'a [Stmt<'a>],
2341    interner: &Interner,
2342) -> Option<ClosedFormInfo> {
2343    use crate::ast::stmt::BinaryOpKind;
2344
2345    if params.len() != 1 {
2346        return None;
2347    }
2348    let param_sym = params[0].0;
2349
2350    // The closed form emits `((base + k) << d) - k`, which requires the parameter
2351    // `d` to be an integer (a `<<` on a float operand does not type-check). A bare
2352    // `0`/`1` base literal parses as an integer regardless of the declared
2353    // parameter type, so a Float-typed double recursion would otherwise still
2354    // match and emit `i64 << f64`. Decline anything but an integer parameter.
2355    let is_integer_param = matches!(
2356        params[0].1,
2357        TypeExpr::Primitive(sym) | TypeExpr::Named(sym)
2358            if matches!(interner.resolve(*sym), "Int" | "Nat" | "Byte")
2359    );
2360    if !is_integer_param {
2361        return None;
2362    }
2363
2364    // Body must be exactly: If { param == 0 → Return base }, Return(recursive_expr)
2365    if body.len() != 2 {
2366        return None;
2367    }
2368
2369    // First statement: base case check
2370    let base_value = match &body[0] {
2371        Stmt::If {
2372            cond,
2373            then_block,
2374            else_block,
2375        } => {
2376            if else_block.is_some() {
2377                return None;
2378            }
2379            if then_block.len() != 1 {
2380                return None;
2381            }
2382            let base = match &then_block[0] {
2383                Stmt::Return { value: Some(expr) } => cf_extract_literal_int(expr)?,
2384                _ => return None,
2385            };
2386            match cond {
2387                Expr::BinaryOp {
2388                    op: BinaryOpKind::Eq,
2389                    left,
2390                    right,
2391                } => {
2392                    let ok = (cf_is_identifier(left, param_sym) && cf_is_literal_int(right, 0))
2393                        || (cf_is_literal_int(left, 0) && cf_is_identifier(right, param_sym));
2394                    if !ok {
2395                        return None;
2396                    }
2397                }
2398                _ => return None,
2399            }
2400            base
2401        }
2402        _ => return None,
2403    };
2404
2405    // Second statement: recursive case Return
2406    let recursive_expr = match &body[1] {
2407        Stmt::Return { value: Some(expr) } => *expr,
2408        _ => return None,
2409    };
2410
2411    // Flatten the Add tree and analyze: must have exactly 2 self-calls with
2412    // arg (param - 1), and any number of integer literal addends.
2413    let mut self_call_count = 0usize;
2414    let mut constant_sum = 0i64;
2415    if !cf_analyze_add_tree(
2416        recursive_expr,
2417        func_name,
2418        param_sym,
2419        &mut self_call_count,
2420        &mut constant_sum,
2421    ) {
2422        return None;
2423    }
2424
2425    if self_call_count != 2 {
2426        return None;
2427    }
2428
2429    Some(ClosedFormInfo {
2430        base: base_value,
2431        k: constant_sum,
2432    })
2433}
2434
2435fn cf_extract_literal_int(expr: &Expr) -> Option<i64> {
2436    if let Expr::Literal(crate::ast::stmt::Literal::Number(n)) = expr {
2437        Some(*n)
2438    } else {
2439        None
2440    }
2441}
2442
2443fn cf_is_identifier(expr: &Expr, sym: Symbol) -> bool {
2444    matches!(expr, Expr::Identifier(s) if *s == sym)
2445}
2446
2447fn cf_is_literal_int(expr: &Expr, val: i64) -> bool {
2448    matches!(expr, Expr::Literal(crate::ast::stmt::Literal::Number(n)) if *n == val)
2449}
2450
2451fn cf_is_self_call_with_decrement(expr: &Expr, func_name: Symbol, param_sym: Symbol) -> bool {
2452    use crate::ast::stmt::BinaryOpKind;
2453    if let Expr::Call { function, args } = expr {
2454        if *function != func_name || args.len() != 1 {
2455            return false;
2456        }
2457        if let Expr::BinaryOp {
2458            op: BinaryOpKind::Subtract,
2459            left,
2460            right,
2461        } = args[0]
2462        {
2463            cf_is_identifier(left, param_sym) && cf_is_literal_int(right, 1)
2464        } else {
2465            false
2466        }
2467    } else {
2468        false
2469    }
2470}
2471
2472/// Walk an Add-tree, counting self-calls and summing literal constants.
2473/// Returns false if any leaf is neither a self-call(param-1) nor an integer literal.
2474fn cf_analyze_add_tree(
2475    expr: &Expr,
2476    func_name: Symbol,
2477    param_sym: Symbol,
2478    self_calls: &mut usize,
2479    constant_sum: &mut i64,
2480) -> bool {
2481    use crate::ast::stmt::BinaryOpKind;
2482    match expr {
2483        Expr::BinaryOp {
2484            op: BinaryOpKind::Add,
2485            left,
2486            right,
2487        } => {
2488            cf_analyze_add_tree(left, func_name, param_sym, self_calls, constant_sum)
2489                && cf_analyze_add_tree(right, func_name, param_sym, self_calls, constant_sum)
2490        }
2491        _ if cf_is_self_call_with_decrement(expr, func_name, param_sym) => {
2492            *self_calls += 1;
2493            true
2494        }
2495        _ => {
2496            if let Some(n) = cf_extract_literal_int(expr) {
2497                *constant_sum += n;
2498                true
2499            } else {
2500                false
2501            }
2502        }
2503    }
2504}
2505
2506// =============================================================================
2507// O3: small fixed-size Seq scalarization (`Seq` → `[T; N]`).
2508// =============================================================================
2509
2510/// A `Seq` local proven to have a compile-time-constant size, built by
2511/// straight-line pushes and thereafter only indexed/length-queried, never
2512/// resized, aliased, or escaped. Codegen emits it as a Rust `[T; N]` array —
2513/// C's representation for nbody's bodies: stack-allocated, statically bounded.
2514pub(crate) struct ScalarizableSeq {
2515    pub elem_ty: String,
2516    pub len: usize,
2517}
2518
2519struct ScalarCand {
2520    elem_ty: String,
2521    len: usize,
2522    /// A non-push use of the handle has been seen — later pushes disqualify.
2523    seen_use: bool,
2524    disqualified: bool,
2525}
2526
2527/// `a new Seq of {Int|Nat|Float|Bool}` → the Rust element type, else None.
2528fn scalar_seq_elem_ty(value: &Expr, interner: &Interner) -> Option<String> {
2529    if let Expr::New {
2530        type_name,
2531        type_args,
2532        ..
2533    } = value
2534    {
2535        if matches!(interner.resolve(*type_name), "Seq" | "List") && type_args.len() == 1 {
2536            if let TypeExpr::Primitive(t) | TypeExpr::Named(t) = &type_args[0] {
2537                return match interner.resolve(*t) {
2538                    "Int" | "Nat" => Some("i64".to_string()),
2539                    "Float" => Some("f64".to_string()),
2540                    "Bool" => Some("bool".to_string()),
2541                    _ => None,
2542                };
2543            }
2544        }
2545    }
2546    None
2547}
2548
2549/// Maximum scalarized array length (keeps generated arrays small).
2550const MAX_SCALARIZE_LEN: usize = 64;
2551
2552/// Find scalarizable Seqs among the given block's locals (v1: the block
2553/// passed is Main; function bodies are not scanned). Conservative: any
2554/// appearance of a candidate outside an allowed position disqualifies it.
2555pub(crate) fn collect_scalarizable_seqs(
2556    stmts: &[Stmt],
2557    interner: &Interner,
2558) -> HashMap<Symbol, ScalarizableSeq> {
2559    // Kill switch for A/B measurement (`LOGOS_SCALARIZE=0`).
2560    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Scalarize) {
2561        return HashMap::new();
2562    }
2563    let mut cand: HashMap<Symbol, ScalarCand> = HashMap::new();
2564    scalar_walk_block(stmts, true, &mut cand, interner);
2565    let mut result: HashMap<Symbol, ScalarizableSeq> = cand
2566        .into_iter()
2567        .filter_map(|(sym, c)| {
2568            if c.disqualified || c.len == 0 || c.len > MAX_SCALARIZE_LEN {
2569                None
2570            } else {
2571                Some((
2572                    sym,
2573                    ScalarizableSeq {
2574                        elem_ty: c.elem_ty,
2575                        len: c.len,
2576                    },
2577                ))
2578            }
2579        })
2580        .collect();
2581    // A swap exchanges two arrays whole: both stay `[T; N]` only as the same `[T; N]`.
2582    crate::optimize::SwapClasses::of(stmts, interner).close_by(&mut result, interner, |x, y| {
2583        x.elem_ty == y.elem_ty && x.len == y.len
2584    });
2585    if !result.is_empty() {
2586        crate::optimize::mark_fired(crate::optimization::Opt::Scalarize);
2587    }
2588    result
2589}
2590
2591/// The set of Seq variables that qualify for fixed-size scalarization (`[T; N]`).
2592///
2593/// Exposed to the AOT loop-unroller (`optimize::unroll`): it only unrolls a loop
2594/// when every collection the loop indexes is one of these. Unrolling a loop over
2595/// a reference-semantics `LogosSeq` (a push-grown buffer or DP row) would destroy
2596/// the loop shapes the de-Rc buffer-reuse and borrow-hoist passes pattern-match
2597/// on — and yields no SROA benefit there anyway, since only scalarized arrays
2598/// promote to registers.
2599pub(crate) fn scalarizable_seq_symbols(
2600    stmts: &[Stmt],
2601    interner: &Interner,
2602) -> std::collections::HashSet<Symbol> {
2603    collect_scalarizable_seqs(stmts, interner)
2604        .into_keys()
2605        .collect()
2606}
2607
2608fn scalar_disq(cand: &mut HashMap<Symbol, ScalarCand>, sym: Symbol) {
2609    if let Some(c) = cand.get_mut(&sym) {
2610        c.disqualified = true;
2611    }
2612}
2613
2614// =============================================================================
2615// Co-indexed array interleaving (struct-of-arrays → array-of-structs).
2616// =============================================================================
2617
2618/// A group of same-type, same-length scalarizable Seqs built by an interleaved
2619/// (round-robin) push pattern — the columns of an array-of-structs. Codegen
2620/// fuses them into one `[[T; W]; N]` backing so per-entity fields are adjacent
2621/// (C's `struct Body[N]` layout), letting LLVM pack them with `movupd` instead
2622/// of gathering separate arrays with shuffles.
2623pub(super) struct InterleaveGroup {
2624    /// Members in column order: column `c` is `members[c]`.
2625    pub members: Vec<Symbol>,
2626    /// `N` — the common length (number of round-robin rounds).
2627    pub len: usize,
2628    /// The common Rust element type ("f64" / "i64" / "bool").
2629    pub elem_ty: String,
2630}
2631
2632/// Detect co-indexed array groups for AoS interleaving. GENERAL over W (number
2633/// of co-indexed arrays) and N (length). v1 recognizes a single round-robin
2634/// cycle that covers all scalarizable pushes, with W >= 2 distinct members of
2635/// equal element type and length — the canonical AoS-init pattern
2636/// (`Push x to ax; Push y to ay; …` repeated per entity).
2637pub(super) fn collect_interleaved_groups(
2638    stmts: &[Stmt],
2639    scalarizable: &HashMap<Symbol, ScalarizableSeq>,
2640    interner: &Interner,
2641) -> Vec<InterleaveGroup> {
2642    // Kill switch for A/B measurement (`LOGOS_AOS=0`).
2643    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Interleave) {
2644        return Vec::new();
2645    }
2646    if scalarizable.len() < 2 {
2647        return Vec::new();
2648    }
2649    // Ordered sequence of top-level pushes targeting scalarizable Seqs (their
2650    // pushes are straight-line top-level by the scalarization rule).
2651    let mut push_seq: Vec<Symbol> = Vec::new();
2652    for s in stmts {
2653        if let Stmt::Push { collection, .. } = s {
2654            if let Expr::Identifier(sym) = collection {
2655                if scalarizable.contains_key(sym) {
2656                    push_seq.push(*sym);
2657                }
2658            }
2659        }
2660    }
2661    if push_seq.len() < 2 {
2662        return Vec::new();
2663    }
2664    // Period W = index of the first repeat of the first pushed array.
2665    let first = push_seq[0];
2666    let w = match push_seq.iter().skip(1).position(|&s| s == first) {
2667        Some(p) => p + 1,
2668        None => return Vec::new(),
2669    };
2670    if w < 2 || push_seq.len() % w != 0 {
2671        return Vec::new();
2672    }
2673    let group: Vec<Symbol> = push_seq[..w].to_vec();
2674    // The W columns must be distinct symbols.
2675    let mut seen = std::collections::HashSet::new();
2676    if !group.iter().all(|s| seen.insert(*s)) {
2677        return Vec::new();
2678    }
2679    // A column of a fused backing is not a variable a swap can exchange.
2680    let swaps = crate::optimize::SwapClasses::of(stmts, interner);
2681    if group.iter().any(|m| swaps.is_swapped(interner.resolve(*m))) {
2682        return Vec::new();
2683    }
2684    // Every round must repeat the same column order exactly.
2685    let rounds = push_seq.len() / w;
2686    for r in 0..rounds {
2687        for c in 0..w {
2688            if push_seq[r * w + c] != group[c] {
2689                return Vec::new();
2690            }
2691        }
2692    }
2693    // The group must cover the whole scalarizable set (no stragglers), and all
2694    // members must share element type and length (== rounds).
2695    if group.len() != scalarizable.len() {
2696        return Vec::new();
2697    }
2698    let elem_ty = scalarizable[&group[0]].elem_ty.clone();
2699    for m in &group {
2700        let info = &scalarizable[m];
2701        if info.elem_ty != elem_ty || info.len != rounds {
2702            return Vec::new();
2703        }
2704    }
2705    // Regime gate: AoS pays off only while the group stays MEMORY-RESIDENT —
2706    // accessed by variable indices in rolled loops, where adjacent fields load
2707    // packed (C's `movupd`) and beat SoA's gather. If ANY member is read/written
2708    // at a CONSTANT literal index, the kernel has been unrolled (or will SROA
2709    // into registers), where the layout is moot and SoA+unroll wins outright —
2710    // AoS there only perturbs LLVM's SLP for the worse (measured: nbody
2711    // 1.12×→1.19×). Leave those to the unroller.
2712    // `LOGOS_AOS_FORCE=1` bypasses the regime gate for A/B measurement.
2713    let force = std::env::var("LOGOS_AOS_FORCE")
2714        .map(|v| v == "1")
2715        .unwrap_or(false);
2716    let members: std::collections::HashSet<Symbol> = group.iter().copied().collect();
2717    if !force && block_has_const_member_index(stmts, &members) {
2718        // A const-index access means the kernel has been unrolled / will SROA into
2719        // registers — Unroll/Scalarize claim it, preempting AoS interleaving.
2720        crate::optimize::mark_preempted(
2721            crate::optimization::Opt::Scalarize,
2722            crate::optimization::Opt::Interleave,
2723        );
2724        crate::optimize::mark_preempted(
2725            crate::optimization::Opt::Unroll,
2726            crate::optimization::Opt::Interleave,
2727        );
2728        return Vec::new();
2729    }
2730    crate::optimize::mark_fired(crate::optimization::Opt::Interleave);
2731    vec![InterleaveGroup {
2732        members: group,
2733        len: rounds,
2734        elem_ty,
2735    }]
2736}
2737
2738/// True if any member of `members` is indexed by a constant literal anywhere in
2739/// `stmts` (evidence the kernel unrolled / will SROA — the register regime).
2740fn block_has_const_member_index(
2741    stmts: &[Stmt],
2742    members: &std::collections::HashSet<Symbol>,
2743) -> bool {
2744    stmts
2745        .iter()
2746        .any(|s| stmt_has_const_member_index(s, members))
2747}
2748
2749fn is_member_const_index(
2750    collection: &Expr,
2751    index: &Expr,
2752    members: &std::collections::HashSet<Symbol>,
2753) -> bool {
2754    matches!(collection, Expr::Identifier(s) if members.contains(s))
2755        && matches!(index, Expr::Literal(Literal::Number(_)))
2756}
2757
2758fn stmt_has_const_member_index(s: &Stmt, members: &std::collections::HashSet<Symbol>) -> bool {
2759    match s {
2760        Stmt::SetIndex {
2761            collection,
2762            index,
2763            value,
2764        } => {
2765            is_member_const_index(collection, index, members)
2766                || expr_has_const_member_index(collection, members)
2767                || expr_has_const_member_index(index, members)
2768                || expr_has_const_member_index(value, members)
2769        }
2770        Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
2771            expr_has_const_member_index(value, members)
2772        }
2773        Stmt::Push { value, collection } => {
2774            expr_has_const_member_index(value, members)
2775                || expr_has_const_member_index(collection, members)
2776        }
2777        Stmt::Show { object, .. } => expr_has_const_member_index(object, members),
2778        Stmt::SetField { object, value, .. } => {
2779            expr_has_const_member_index(object, members)
2780                || expr_has_const_member_index(value, members)
2781        }
2782        Stmt::Give { object, recipient } => {
2783            expr_has_const_member_index(object, members)
2784                || expr_has_const_member_index(recipient, members)
2785        }
2786        Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
2787            expr_has_const_member_index(value, members)
2788                || expr_has_const_member_index(collection, members)
2789        }
2790        Stmt::RuntimeAssert { condition, .. } => expr_has_const_member_index(condition, members),
2791        Stmt::Return { value } => {
2792            matches!(value, Some(v) if expr_has_const_member_index(v, members))
2793        }
2794        Stmt::Call { args, .. } => args.iter().any(|a| expr_has_const_member_index(a, members)),
2795        Stmt::If {
2796            cond,
2797            then_block,
2798            else_block,
2799        } => {
2800            expr_has_const_member_index(cond, members)
2801                || block_has_const_member_index(then_block, members)
2802                || matches!(else_block, Some(eb) if block_has_const_member_index(eb, members))
2803        }
2804        Stmt::While { cond, body, .. } => {
2805            expr_has_const_member_index(cond, members)
2806                || block_has_const_member_index(body, members)
2807        }
2808        Stmt::Repeat { iterable, body, .. } => {
2809            expr_has_const_member_index(iterable, members)
2810                || block_has_const_member_index(body, members)
2811        }
2812        Stmt::Inspect { target, arms, .. } => {
2813            expr_has_const_member_index(target, members)
2814                || arms
2815                    .iter()
2816                    .any(|a| block_has_const_member_index(a.body, members))
2817        }
2818        _ => false,
2819    }
2820}
2821
2822fn expr_has_const_member_index(e: &Expr, members: &std::collections::HashSet<Symbol>) -> bool {
2823    match e {
2824        Expr::Index { collection, index } => {
2825            is_member_const_index(collection, index, members)
2826                || expr_has_const_member_index(collection, members)
2827                || expr_has_const_member_index(index, members)
2828        }
2829        Expr::Slice {
2830            collection,
2831            start,
2832            end,
2833        } => {
2834            expr_has_const_member_index(collection, members)
2835                || expr_has_const_member_index(start, members)
2836                || expr_has_const_member_index(end, members)
2837        }
2838        Expr::BinaryOp { left, right, .. } => {
2839            expr_has_const_member_index(left, members)
2840                || expr_has_const_member_index(right, members)
2841        }
2842        Expr::Not { operand } => expr_has_const_member_index(operand, members),
2843        Expr::Length { collection } => expr_has_const_member_index(collection, members),
2844        Expr::Contains { collection, value } => {
2845            expr_has_const_member_index(collection, members)
2846                || expr_has_const_member_index(value, members)
2847        }
2848        Expr::Union { left, right } | Expr::Intersection { left, right } => {
2849            expr_has_const_member_index(left, members)
2850                || expr_has_const_member_index(right, members)
2851        }
2852        Expr::Call { args, .. } | Expr::CallExpr { args, .. } => {
2853            args.iter().any(|a| expr_has_const_member_index(a, members))
2854        }
2855        Expr::FieldAccess { object, .. } => expr_has_const_member_index(object, members),
2856        Expr::Copy { expr } => expr_has_const_member_index(expr, members),
2857        Expr::Give { value } | Expr::OptionSome { value } => {
2858            expr_has_const_member_index(value, members)
2859        }
2860        Expr::WithCapacity { value, capacity } => {
2861            expr_has_const_member_index(value, members)
2862                || expr_has_const_member_index(capacity, members)
2863        }
2864        Expr::Range { start, end } => {
2865            expr_has_const_member_index(start, members) || expr_has_const_member_index(end, members)
2866        }
2867        Expr::List(items) | Expr::Tuple(items) => items
2868            .iter()
2869            .any(|i| expr_has_const_member_index(i, members)),
2870        Expr::InterpolatedString(parts) => parts.iter().any(|p| match p {
2871            crate::ast::stmt::StringPart::Expr { value, .. } => {
2872                expr_has_const_member_index(value, members)
2873            }
2874            _ => false,
2875        }),
2876        _ => false,
2877    }
2878}
2879
2880/// A parsed `__aos:<backing>:<col>:<width>:<len>:<elem>` member type tag — one
2881/// column of a fused array-of-structs. `item i of member` lowers to
2882/// `backing[(i-1)][col]`; column 0 emits the `[[elem; width]; len]` backing.
2883pub(super) struct AosTag {
2884    pub backing: String,
2885    pub col: usize,
2886    pub width: usize,
2887    pub len: usize,
2888    pub elem: String,
2889}
2890
2891/// Parse an AoS member type tag (registered in `codegen_program`). The backing
2892/// name is the first member's emitted identifier; it contains no `:`, and the
2893/// element type (`f64`/`i64`/`bool`) contains none either, so `:`-splitting is
2894/// unambiguous.
2895pub(super) fn parse_aos_tag(ty: Option<&String>) -> Option<AosTag> {
2896    let rest = ty?.strip_prefix("__aos:")?;
2897    let mut parts = rest.split(':');
2898    let backing = parts.next()?.to_string();
2899    let col = parts.next()?.parse().ok()?;
2900    let width = parts.next()?.parse().ok()?;
2901    let len = parts.next()?.parse().ok()?;
2902    let elem = parts.next()?.to_string();
2903    Some(AosTag {
2904        backing,
2905        col,
2906        width,
2907        len,
2908        elem,
2909    })
2910}
2911
2912fn scalar_mark_use(cand: &mut HashMap<Symbol, ScalarCand>, sym: Symbol) {
2913    if let Some(c) = cand.get_mut(&sym) {
2914        c.seen_use = true;
2915    }
2916}
2917
2918/// A collection-position expression: a bare candidate handle is an ALLOWED
2919/// access (read/length); anything else is a value.
2920fn scalar_note_access(e: &Expr, cand: &mut HashMap<Symbol, ScalarCand>) {
2921    if let Expr::Identifier(s) = e {
2922        scalar_mark_use(cand, *s);
2923    } else {
2924        scalar_note_value(e, cand);
2925    }
2926}
2927
2928/// A value-position expression: a bare candidate handle DISQUALIFIES (the
2929/// handle itself flows somewhere). `item i of x` and `length of x` remain
2930/// allowed accesses — their results are scalars.
2931fn scalar_note_value(e: &Expr, cand: &mut HashMap<Symbol, ScalarCand>) {
2932    match e {
2933        Expr::Identifier(s) => scalar_disq(cand, *s),
2934        Expr::Literal(_) | Expr::OptionNone => {}
2935        Expr::Index { collection, index } => {
2936            scalar_note_access(collection, cand);
2937            scalar_note_value(index, cand);
2938        }
2939        Expr::Length { collection } => scalar_note_access(collection, cand),
2940        Expr::Slice {
2941            collection,
2942            start,
2943            end,
2944        } => {
2945            // A slice yields a new Seq — the handle escapes into it.
2946            if let Expr::Identifier(s) = collection {
2947                scalar_disq(cand, *s);
2948            } else {
2949                scalar_note_value(collection, cand);
2950            }
2951            scalar_note_value(start, cand);
2952            scalar_note_value(end, cand);
2953        }
2954        Expr::Contains { collection, value } => {
2955            if let Expr::Identifier(s) = collection {
2956                scalar_disq(cand, *s);
2957            } else {
2958                scalar_note_value(collection, cand);
2959            }
2960            scalar_note_value(value, cand);
2961        }
2962        Expr::Copy { expr } => {
2963            if let Expr::Identifier(s) = expr {
2964                scalar_disq(cand, *s);
2965            } else {
2966                scalar_note_value(expr, cand);
2967            }
2968        }
2969        Expr::BinaryOp { left, right, .. }
2970        | Expr::Union { left, right }
2971        | Expr::Intersection { left, right }
2972        | Expr::Range {
2973            start: left,
2974            end: right,
2975        } => {
2976            scalar_note_value(left, cand);
2977            scalar_note_value(right, cand);
2978        }
2979        Expr::Not { operand } => scalar_note_value(operand, cand),
2980        Expr::FieldAccess { object, .. } => scalar_note_value(object, cand),
2981        Expr::OptionSome { value } | Expr::Give { value } => scalar_note_value(value, cand),
2982        Expr::WithCapacity { value, capacity } => {
2983            scalar_note_value(value, cand);
2984            scalar_note_value(capacity, cand);
2985        }
2986        Expr::List(items) | Expr::Tuple(items) => {
2987            for it in items {
2988                scalar_note_value(it, cand);
2989            }
2990        }
2991        Expr::New { init_fields, .. } => {
2992            for (_, v) in init_fields {
2993                scalar_note_value(v, cand);
2994            }
2995        }
2996        Expr::NewVariant { fields, .. } => {
2997            for (_, v) in fields {
2998                scalar_note_value(v, cand);
2999            }
3000        }
3001        Expr::Call { args, .. } => {
3002            for a in args {
3003                scalar_note_value(a, cand);
3004            }
3005        }
3006        Expr::CallExpr { callee, args } => {
3007            scalar_note_value(callee, cand);
3008            for a in args {
3009                scalar_note_value(a, cand);
3010            }
3011        }
3012        Expr::InterpolatedString(parts) => {
3013            for p in parts {
3014                if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
3015                    scalar_note_value(value, cand);
3016                }
3017            }
3018        }
3019        Expr::ManifestOf { zone } => scalar_note_value(zone, cand),
3020        Expr::ChunkAt { index, zone } => {
3021            scalar_note_value(index, cand);
3022            scalar_note_value(zone, cand);
3023        }
3024        // Closures and escape hatches are opaque — they may capture or
3025        // reference any handle in scope — and so is any form this walk has no
3026        // case for. Conservatively disqualify every candidate rather than risk
3027        // scalarizing a Seq it holds.
3028        _ => {
3029            for c in cand.values_mut() {
3030                c.disqualified = true;
3031            }
3032        }
3033    }
3034}
3035
3036fn scalar_walk_block(
3037    stmts: &[Stmt],
3038    top_level: bool,
3039    cand: &mut HashMap<Symbol, ScalarCand>,
3040    interner: &Interner,
3041) {
3042    for stmt in stmts {
3043        match stmt {
3044            Stmt::Let {
3045                var,
3046                value,
3047                mutable,
3048                ..
3049            } => {
3050                if top_level && *mutable {
3051                    if let Some(elem) = scalar_seq_elem_ty(value, interner) {
3052                        cand.insert(
3053                            *var,
3054                            ScalarCand {
3055                                elem_ty: elem,
3056                                len: 0,
3057                                seen_use: false,
3058                                disqualified: false,
3059                            },
3060                        );
3061                        continue;
3062                    }
3063                }
3064                // `Let y be x` aliases x; any candidate in the value escapes.
3065                if let Expr::Identifier(s) = value {
3066                    scalar_disq(cand, *s);
3067                } else {
3068                    scalar_note_value(value, cand);
3069                }
3070            }
3071            Stmt::Push { value, collection } => {
3072                // The pushed value may carry a candidate handle (it escapes).
3073                if let Expr::Identifier(s) = value {
3074                    scalar_disq(cand, *s);
3075                } else {
3076                    scalar_note_value(value, cand);
3077                }
3078                if let Expr::Identifier(x) = collection {
3079                    let nested_or_used = {
3080                        match cand.get(x) {
3081                            Some(c) => !top_level || c.seen_use || c.disqualified,
3082                            None => false,
3083                        }
3084                    };
3085                    if cand.contains_key(x) {
3086                        if nested_or_used {
3087                            scalar_disq(cand, *x);
3088                        } else if let Some(c) = cand.get_mut(x) {
3089                            c.len += 1;
3090                        }
3091                    }
3092                } else {
3093                    scalar_note_value(collection, cand);
3094                }
3095            }
3096            Stmt::SetIndex {
3097                collection,
3098                index,
3099                value,
3100            } => {
3101                if let Expr::Identifier(x) = collection {
3102                    scalar_mark_use(cand, *x);
3103                } else {
3104                    scalar_note_value(collection, cand);
3105                }
3106                scalar_note_value(index, cand);
3107                scalar_note_value(value, cand);
3108            }
3109            Stmt::Set { target, value } => {
3110                // Rebinding a candidate disqualifies it; aliasing escapes the RHS.
3111                scalar_disq(cand, *target);
3112                if let Expr::Identifier(s) = value {
3113                    scalar_disq(cand, *s);
3114                } else {
3115                    scalar_note_value(value, cand);
3116                }
3117            }
3118            Stmt::Pop { collection, .. } => {
3119                if let Expr::Identifier(x) = collection {
3120                    scalar_disq(cand, *x);
3121                } else {
3122                    scalar_note_value(collection, cand);
3123                }
3124            }
3125            Stmt::Add { collection, value } | Stmt::Remove { collection, value } => {
3126                if let Expr::Identifier(x) = collection {
3127                    scalar_disq(cand, *x);
3128                } else {
3129                    scalar_note_value(collection, cand);
3130                }
3131                scalar_note_value(value, cand);
3132            }
3133            Stmt::Show { object, recipient } => {
3134                scalar_note_value(object, cand);
3135                scalar_note_value(recipient, cand);
3136            }
3137            Stmt::Give { object, recipient } => {
3138                if let Expr::Identifier(s) = object {
3139                    scalar_disq(cand, *s);
3140                } else {
3141                    scalar_note_value(object, cand);
3142                }
3143                scalar_note_value(recipient, cand);
3144            }
3145            Stmt::Return { value: Some(v) } => {
3146                if let Expr::Identifier(s) = v {
3147                    scalar_disq(cand, *s);
3148                } else {
3149                    scalar_note_value(v, cand);
3150                }
3151            }
3152            Stmt::SetField { object, value, .. } => {
3153                scalar_note_value(object, cand);
3154                scalar_note_value(value, cand);
3155            }
3156            Stmt::If {
3157                cond,
3158                then_block,
3159                else_block,
3160            } => {
3161                scalar_note_value(cond, cand);
3162                scalar_walk_block(then_block, false, cand, interner);
3163                if let Some(eb) = else_block {
3164                    scalar_walk_block(eb, false, cand, interner);
3165                }
3166            }
3167            Stmt::While { cond, body, .. } => {
3168                scalar_note_value(cond, cand);
3169                scalar_walk_block(body, false, cand, interner);
3170            }
3171            Stmt::Repeat { iterable, body, .. } => {
3172                if let Expr::Identifier(x) = iterable {
3173                    scalar_disq(cand, *x);
3174                } else {
3175                    scalar_note_value(iterable, cand);
3176                }
3177                scalar_walk_block(body, false, cand, interner);
3178            }
3179            Stmt::Inspect { target, arms, .. } => {
3180                scalar_note_value(target, cand);
3181                for arm in arms {
3182                    scalar_walk_block(&arm.body, false, cand, interner);
3183                }
3184            }
3185            Stmt::RuntimeAssert { condition, .. } => scalar_note_value(condition, cand),
3186            Stmt::Call { args, .. } => {
3187                for a in args {
3188                    if let Expr::Identifier(s) = a {
3189                        scalar_disq(cand, *s);
3190                    } else {
3191                        scalar_note_value(a, cand);
3192                    }
3193                }
3194            }
3195            Stmt::Zone { body, .. } => scalar_walk_block(body, false, cand, interner),
3196            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
3197                scalar_walk_block(tasks, false, cand, interner)
3198            }
3199            // Scope-transparent desugar output (`Push a, b to xs`): its statements
3200            // are the enclosing block's.
3201            Stmt::Splice { body } => scalar_walk_block(body, top_level, cand, interner),
3202            // A swap exchanges the two handles whole; neither may grow after it,
3203            // and `SwapClasses` keeps the pair alike.
3204            Stmt::Swap { a, b } => {
3205                scalar_mark_use(cand, *a);
3206                scalar_mark_use(cand, *b);
3207            }
3208            // Candidates are Main-locals; a function body cannot reference them.
3209            Stmt::FunctionDef { .. } => {}
3210            // Any other form hands what it touches somewhere this walk does not
3211            // model, so every candidate it touches is disqualified.
3212            other => {
3213                let touched = crate::optimize::Mentions::of_stmt(other);
3214                for (sym, c) in cand.iter_mut() {
3215                    if touched.touches(interner.resolve(*sym), interner) {
3216                        c.disqualified = true;
3217                    }
3218                }
3219            }
3220        }
3221    }
3222}