Skip to main content

logicaffeine_compile/analysis/
readonly.rs

1use std::collections::{HashMap, HashSet};
2
3use logicaffeine_base::Symbol;
4use logicaffeine_language::ast::stmt::ClosureBody;
5use logicaffeine_language::ast::{Expr, Stmt};
6
7use super::callgraph::CallGraph;
8use super::types::{LogosType, TypeEnv};
9
10/// Readonly parameter analysis result.
11///
12/// Maps each function to the set of its `Seq<T>` parameters that are never
13/// structurally mutated (no Push, Pop, Add, Remove, SetIndex, or reassignment)
14/// either directly or transitively through callees.
15///
16/// Parameters in this set are eligible for `&[T]` borrow in codegen instead
17/// of requiring ownership or cloning.
18///
19/// # Safety under Rc<RefCell> (reference) semantics
20///
21/// LogosSeq<T> is Rc<RefCell<Vec<T>>>. The analysis is safe because:
22/// - `Let mutable X be param` is caught by `collect_consumed_params`, which
23///   removes the param from the readonly set. This prevents aliasing where
24///   a mutable local could mutate through the shared Rc.
25/// - Interior mutation via Rc clone requires the `mutable` keyword on the
26///   alias, which triggers the consumed-param check.
27/// - Fixed-point propagation through the callgraph catches transitive
28///   mutations: if a callee mutates a param position, all callers passing
29///   a readonly candidate to that position lose their readonly status.
30pub struct ReadonlyParams {
31    /// fn_sym → set of param symbols that are readonly within that function.
32    pub readonly: HashMap<Symbol, HashSet<Symbol>>,
33}
34
35impl ReadonlyParams {
36    /// Analyze the program and compute readonly parameters.
37    ///
38    /// Uses fixed-point iteration: starts optimistically with all `Seq<T>`
39    /// params as readonly candidates, then eliminates those that are directly
40    /// mutated or transitively mutated via callee propagation.
41    ///
42    /// Native functions are trusted: their params remain readonly unless
43    /// the LOGOS body explicitly mutates them (which is impossible since they
44    /// have no body).
45    pub fn analyze(stmts: &[Stmt<'_>], callgraph: &CallGraph, type_env: &TypeEnv) -> Self {
46        // Build fn_params map: fn_sym → ordered list of param symbols
47        let mut fn_params: HashMap<Symbol, Vec<Symbol>> = HashMap::new();
48        for stmt in stmts {
49            if let Stmt::FunctionDef { name, params, .. } = stmt {
50                let syms: Vec<Symbol> = params.iter().map(|(s, _)| *s).collect();
51                fn_params.insert(*name, syms);
52            }
53        }
54
55        // Initialize: all Seq<T> params are readonly candidates
56        let mut readonly: HashMap<Symbol, HashSet<Symbol>> = HashMap::new();
57        for stmt in stmts {
58            if let Stmt::FunctionDef { name, params, .. } = stmt {
59                let mut candidates = HashSet::new();
60                for (sym, _) in params {
61                    if is_seq_type(type_env.lookup(*sym)) {
62                        candidates.insert(*sym);
63                    }
64                }
65                readonly.insert(*name, candidates);
66            }
67        }
68
69        // Remove directly mutated params from non-native functions
70        for stmt in stmts {
71            if let Stmt::FunctionDef {
72                name,
73                params,
74                body,
75                is_native,
76                ..
77            } = stmt
78            {
79                if *is_native {
80                    continue;
81                }
82                let param_set: HashSet<Symbol> = params.iter().map(|(s, _)| *s).collect();
83                let mutated = collect_direct_mutations(body, &param_set);
84                if let Some(candidates) = readonly.get_mut(name) {
85                    for sym in &mutated {
86                        candidates.remove(sym);
87                    }
88                }
89            }
90        }
91
92        // Fixed-point: propagate non-readonly through call sites
93        loop {
94            let mut changed = false;
95
96            for stmt in stmts {
97                if let Stmt::FunctionDef {
98                    name: caller,
99                    body,
100                    is_native,
101                    ..
102                } = stmt
103                {
104                    if *is_native {
105                        continue;
106                    }
107
108                    // Collect all call sites in this function's body (including closures)
109                    let call_sites = collect_call_sites(body);
110
111                    for (callee, arg_syms) in &call_sites {
112                        let callee_params = match fn_params.get(callee) {
113                            Some(p) => p,
114                            None => continue, // unknown function, skip
115                        };
116
117                        for (i, maybe_arg_sym) in arg_syms.iter().enumerate() {
118                            let arg_sym = match maybe_arg_sym {
119                                Some(s) => s,
120                                None => continue, // arg is not a plain identifier
121                            };
122
123                            let callee_param = match callee_params.get(i) {
124                                Some(p) => p,
125                                None => continue,
126                            };
127
128                            // Is callee's param at position i NOT readonly?
129                            let callee_param_readonly = readonly
130                                .get(callee)
131                                .map(|s| s.contains(callee_param))
132                                .unwrap_or(true); // unknown callees are trusted
133
134                            if !callee_param_readonly {
135                                // The caller's arg is passed to a mutating position
136                                if let Some(caller_readonly) = readonly.get_mut(caller) {
137                                    if caller_readonly.remove(arg_sym) {
138                                        changed = true;
139                                    }
140                                }
141                            }
142                        }
143                    }
144                }
145            }
146
147            if !changed {
148                break;
149            }
150        }
151
152        Self { readonly }
153    }
154
155    /// Returns `true` if `param_sym` is readonly within `fn_sym`.
156    pub fn is_readonly(&self, fn_sym: Symbol, param_sym: Symbol) -> bool {
157        self.readonly
158            .get(&fn_sym)
159            .map(|s| s.contains(&param_sym))
160            .unwrap_or(false)
161    }
162}
163
164fn is_seq_type(ty: &LogosType) -> bool {
165    matches!(ty, LogosType::Seq(_))
166}
167
168// =============================================================================
169// Direct mutation detection
170// =============================================================================
171
172/// Collects param symbols that are directly mutated in the body.
173///
174/// Every parameter the body reassigns or changes in place counts (see
175/// [`collect_mutations_from_stmt`]). Also detects "consumed"
176/// parameters: those assigned into a mutable local via `Let mutable X be param`.
177/// A consumed Seq parameter should be taken by value (not borrowed) so the
178/// copy becomes a move instead of a `.to_vec()` clone.
179///
180/// Does NOT recurse into closure bodies (closures in LOGOS capture by clone,
181/// so they don't mutate the original param directly).
182fn collect_direct_mutations(stmts: &[Stmt<'_>], param_set: &HashSet<Symbol>) -> HashSet<Symbol> {
183    let mut mutated = HashSet::new();
184    for stmt in stmts {
185        collect_mutations_from_stmt(stmt, param_set, &mut mutated);
186    }
187    // Detect consumed parameters: `Let mutable X be param` where X is
188    // subsequently mutated. Taking param by value allows a move instead
189    // of a clone. We conservatively mark any param that appears as the
190    // value of a `Let mutable` as consumed.
191    collect_consumed_params(stmts, param_set, &mut mutated);
192    mutated
193}
194
195/// The parameters `stmt` reassigns (`Set`, `Swap`, a lend to a `mutable` parameter) or changes in place, nested
196/// blocks included, from the optimizer's one exhaustive write walk. Closure bodies are not entered: a closure
197/// captures its own copy.
198fn collect_mutations_from_stmt(
199    stmt: &Stmt<'_>,
200    param_set: &HashSet<Symbol>,
201    mutated: &mut HashSet<Symbol>,
202) {
203    let writes = crate::optimize::WriteSet::of_stmt(stmt);
204    mutated.extend(
205        writes
206            .assigned()
207            .iter()
208            .chain(writes.mutated())
209            .copied()
210            .filter(|s| param_set.contains(s)),
211    );
212}
213
214/// Detects consumed parameters: those copied into a mutable local via
215/// `Let mutable X be param`. Recurses into control-flow blocks.
216fn collect_consumed_params(
217    stmts: &[Stmt<'_>],
218    param_set: &HashSet<Symbol>,
219    consumed: &mut HashSet<Symbol>,
220) {
221    for stmt in stmts {
222        match stmt {
223            Stmt::Let {
224                mutable: true,
225                value,
226                ..
227            } => {
228                if let Expr::Identifier(sym) = value {
229                    if param_set.contains(sym) {
230                        consumed.insert(*sym);
231                    }
232                }
233            }
234            Stmt::If {
235                then_block,
236                else_block,
237                ..
238            } => {
239                collect_consumed_params(then_block, param_set, consumed);
240                if let Some(else_b) = else_block {
241                    collect_consumed_params(else_b, param_set, consumed);
242                }
243            }
244            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
245                collect_consumed_params(body, param_set, consumed);
246            }
247            Stmt::Inspect { arms, .. } => {
248                for arm in arms {
249                    collect_consumed_params(arm.body, param_set, consumed);
250                }
251            }
252            _ => {}
253        }
254    }
255}
256
257// =============================================================================
258// Call site collection (for fixed-point propagation)
259// =============================================================================
260
261/// Collects all call sites in a function body, including those inside closures.
262///
263/// Returns `Vec<(callee, [arg0?, arg1?, ...])>` where each arg is `Some(sym)`
264/// if the argument is a plain `Expr::Identifier`, otherwise `None`.
265fn collect_call_sites(stmts: &[Stmt<'_>]) -> Vec<(Symbol, Vec<Option<Symbol>>)> {
266    let mut sites = Vec::new();
267    collect_call_sites_from_stmts(stmts, &mut sites);
268    sites
269}
270
271fn collect_call_sites_from_stmts(
272    stmts: &[Stmt<'_>],
273    sites: &mut Vec<(Symbol, Vec<Option<Symbol>>)>,
274) {
275    for stmt in stmts {
276        collect_call_sites_from_stmt(stmt, sites);
277    }
278}
279
280fn collect_call_sites_from_stmt(stmt: &Stmt<'_>, sites: &mut Vec<(Symbol, Vec<Option<Symbol>>)>) {
281    match stmt {
282        Stmt::Call { function, args } => {
283            let arg_syms = args
284                .iter()
285                .map(|arg| {
286                    if let Expr::Identifier(sym) = *arg {
287                        Some(*sym)
288                    } else {
289                        None
290                    }
291                })
292                .collect();
293            sites.push((*function, arg_syms));
294            for arg in args {
295                collect_call_sites_from_expr(arg, sites);
296            }
297        }
298        Stmt::Let { value, .. } => collect_call_sites_from_expr(value, sites),
299        Stmt::Set { value, .. } => collect_call_sites_from_expr(value, sites),
300        Stmt::Return { value: Some(v) } => collect_call_sites_from_expr(v, sites),
301        Stmt::If {
302            cond,
303            then_block,
304            else_block,
305        } => {
306            collect_call_sites_from_expr(cond, sites);
307            collect_call_sites_from_stmts(then_block, sites);
308            if let Some(else_b) = else_block {
309                collect_call_sites_from_stmts(else_b, sites);
310            }
311        }
312        Stmt::While { cond, body, .. } => {
313            collect_call_sites_from_expr(cond, sites);
314            collect_call_sites_from_stmts(body, sites);
315        }
316        Stmt::Repeat { iterable, body, .. } => {
317            collect_call_sites_from_expr(iterable, sites);
318            collect_call_sites_from_stmts(body, sites);
319        }
320        Stmt::Push { value, collection } => {
321            collect_call_sites_from_expr(value, sites);
322            collect_call_sites_from_expr(collection, sites);
323        }
324        Stmt::Inspect { arms, .. } => {
325            for arm in arms {
326                collect_call_sites_from_stmts(arm.body, sites);
327            }
328        }
329        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
330            collect_call_sites_from_stmts(tasks, sites);
331        }
332        _ => {}
333    }
334}
335
336fn collect_call_sites_from_expr(expr: &Expr<'_>, sites: &mut Vec<(Symbol, Vec<Option<Symbol>>)>) {
337    match expr {
338        Expr::Call { function, args } => {
339            let arg_syms = args
340                .iter()
341                .map(|arg| {
342                    if let Expr::Identifier(sym) = *arg {
343                        Some(*sym)
344                    } else {
345                        None
346                    }
347                })
348                .collect();
349            sites.push((*function, arg_syms));
350            for arg in args {
351                collect_call_sites_from_expr(arg, sites);
352            }
353        }
354        Expr::Closure { body, .. } => match body {
355            ClosureBody::Expression(e) => collect_call_sites_from_expr(e, sites),
356            ClosureBody::Block(stmts) => collect_call_sites_from_stmts(stmts, sites),
357        },
358        Expr::BinaryOp { left, right, .. } => {
359            collect_call_sites_from_expr(left, sites);
360            collect_call_sites_from_expr(right, sites);
361        }
362        Expr::Index { collection, index } => {
363            collect_call_sites_from_expr(collection, sites);
364            collect_call_sites_from_expr(index, sites);
365        }
366        Expr::Length { collection } => collect_call_sites_from_expr(collection, sites),
367        Expr::Contains { collection, value } => {
368            collect_call_sites_from_expr(collection, sites);
369            collect_call_sites_from_expr(value, sites);
370        }
371        Expr::FieldAccess { object, .. } => collect_call_sites_from_expr(object, sites),
372        Expr::Copy { expr } | Expr::Give { value: expr } => {
373            collect_call_sites_from_expr(expr, sites);
374        }
375        Expr::OptionSome { value } => collect_call_sites_from_expr(value, sites),
376        Expr::WithCapacity { value, capacity } => {
377            collect_call_sites_from_expr(value, sites);
378            collect_call_sites_from_expr(capacity, sites);
379        }
380        Expr::CallExpr { callee, args } => {
381            collect_call_sites_from_expr(callee, sites);
382            for arg in args {
383                collect_call_sites_from_expr(arg, sites);
384            }
385        }
386        _ => {}
387    }
388}
389
390// =============================================================================
391// Mutable Borrow Parameter Analysis
392// =============================================================================
393
394/// Mutable borrow parameter analysis result.
395///
396/// Identifies `Seq<T>` parameters that are only mutated via element access
397/// (SetIndex) but never structurally modified (no Push, Pop, Add, Remove,
398/// or reassignment). These parameters can be passed as `&mut [T]` instead
399/// of by value, eliminating the move-in/move-out ownership pattern.
400///
401/// Additional requirement: the function must return the parameter as its
402/// sole return value, so the call site can drop the assignment.
403pub struct MutableBorrowParams {
404    /// fn_sym → set of param symbols eligible for &mut \[T\] borrow.
405    pub mutable_borrow: HashMap<Symbol, HashSet<Symbol>>,
406}
407
408impl MutableBorrowParams {
409    /// Analyze the program and compute mutable borrow parameters.
410    pub fn analyze(stmts: &[Stmt<'_>], callgraph: &CallGraph, type_env: &TypeEnv) -> Self {
411        let mut fn_params: HashMap<Symbol, Vec<Symbol>> = HashMap::new();
412        for stmt in stmts {
413            if let Stmt::FunctionDef { name, params, .. } = stmt {
414                let syms: Vec<Symbol> = params.iter().map(|(s, _)| *s).collect();
415                fn_params.insert(*name, syms);
416            }
417        }
418
419        let mut mutable_borrow: HashMap<Symbol, HashSet<Symbol>> = HashMap::new();
420
421        for stmt in stmts {
422            if let Stmt::FunctionDef {
423                name,
424                params,
425                body,
426                is_native,
427                is_exported,
428                ..
429            } = stmt
430            {
431                if *is_native || *is_exported {
432                    continue;
433                }
434
435                let mut candidates = HashSet::new();
436
437                for (sym, _) in params {
438                    if !is_seq_type(type_env.lookup(*sym)) {
439                        continue;
440                    }
441
442                    let has_set_index = has_set_index_on(body, *sym);
443                    let has_structural = has_structural_mutation_on(body, *sym);
444                    let has_reassign = has_reassignment_on(body, *sym);
445                    let consumed = is_consumed_param(body, *sym);
446                    let returned = is_sole_return_param(body, *sym);
447
448                    if has_set_index && !has_structural && !has_reassign && !consumed && returned {
449                        candidates.insert(*sym);
450                    } else if consumed {
451                        // Consume-alias detection: `Let mutable result be arr`
452                        // where `arr` is never used after the consume and `result`
453                        // satisfies all &mut [T] criteria.
454                        let param_idx = params
455                            .iter()
456                            .position(|(s, _)| *s == *sym)
457                            .unwrap_or(usize::MAX);
458                        if let Some(alias) = detect_consume_alias(body, *sym) {
459                            let alias_has_set_index = has_set_index_on(body, alias);
460                            let alias_has_structural = has_structural_mutation_on(body, alias);
461                            let alias_returned = is_sole_return_param_or_alias(body, *sym, alias);
462                            let alias_reassign_ok =
463                                reassignment_only_self_calls(body, alias, *name, param_idx);
464                            let param_dead = is_param_dead_after_consume(body, *sym, alias);
465
466                            if alias_has_set_index
467                                && !alias_has_structural
468                                && alias_returned
469                                && alias_reassign_ok
470                                && param_dead
471                            {
472                                candidates.insert(*sym);
473                            }
474                        }
475                    }
476                }
477
478                if !candidates.is_empty() {
479                    mutable_borrow.insert(*name, candidates);
480                }
481            }
482        }
483
484        // Fixed-point: propagate through call sites.
485        loop {
486            let mut changed = false;
487            for stmt in stmts {
488                if let Stmt::FunctionDef {
489                    name: caller,
490                    body,
491                    is_native,
492                    ..
493                } = stmt
494                {
495                    if *is_native {
496                        continue;
497                    }
498                    let call_sites = collect_call_sites(body);
499                    for (callee, arg_syms) in &call_sites {
500                        let callee_params = match fn_params.get(callee) {
501                            Some(p) => p,
502                            None => continue,
503                        };
504                        for (i, maybe_arg_sym) in arg_syms.iter().enumerate() {
505                            let arg_sym = match maybe_arg_sym {
506                                Some(s) => s,
507                                None => continue,
508                            };
509                            let callee_param = match callee_params.get(i) {
510                                Some(p) => p,
511                                None => continue,
512                            };
513                            let callee_is_mut_borrow = mutable_borrow
514                                .get(callee)
515                                .map(|s| s.contains(callee_param))
516                                .unwrap_or(false);
517                            if !callee_is_mut_borrow {
518                                if let Some(caller_set) = mutable_borrow.get_mut(caller) {
519                                    if caller_set.remove(arg_sym) {
520                                        changed = true;
521                                    }
522                                }
523                            }
524                        }
525                    }
526                }
527            }
528            if !changed {
529                break;
530            }
531        }
532
533        // Call-site compatibility: &mut [T] suppresses the return type, so the
534        // function can only be called in void context (Stmt::Call) or in
535        // `Set x to f(x, ...)` where x is at a mut_borrow position.
536        // Remove functions from mutable_borrow if any call site uses the return
537        // value in a way that requires it (Let, Show, Return, expression context).
538        let incompatible =
539            collect_incompatible_mut_borrow_callsites(stmts, &mutable_borrow, &fn_params);
540        for fn_sym in incompatible {
541            mutable_borrow.remove(&fn_sym);
542        }
543
544        Self { mutable_borrow }
545    }
546
547    pub fn is_mutable_borrow(&self, fn_sym: Symbol, param_sym: Symbol) -> bool {
548        self.mutable_borrow
549            .get(&fn_sym)
550            .map(|s| s.contains(&param_sym))
551            .unwrap_or(false)
552    }
553}
554
555fn has_set_index_on(stmts: &[Stmt<'_>], sym: Symbol) -> bool {
556    stmts.iter().any(|s| check_set_index_stmt(s, sym))
557}
558
559fn check_set_index_stmt(stmt: &Stmt<'_>, sym: Symbol) -> bool {
560    match stmt {
561        Stmt::SetIndex { collection, .. } => {
562            matches!(**collection, Expr::Identifier(s) if s == sym)
563        }
564        Stmt::If {
565            then_block,
566            else_block,
567            ..
568        } => {
569            has_set_index_on(then_block, sym)
570                || else_block
571                    .as_ref()
572                    .map_or(false, |eb| has_set_index_on(eb, sym))
573        }
574        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => has_set_index_on(body, sym),
575        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| has_set_index_on(arm.body, sym)),
576        _ => false,
577    }
578}
579
580fn has_structural_mutation_on(stmts: &[Stmt<'_>], sym: Symbol) -> bool {
581    stmts.iter().any(|s| check_structural_stmt(s, sym))
582}
583
584fn check_structural_stmt(stmt: &Stmt<'_>, sym: Symbol) -> bool {
585    match stmt {
586        Stmt::Push { collection, .. }
587        | Stmt::Pop { collection, .. }
588        | Stmt::Add { collection, .. }
589        | Stmt::Remove { collection, .. } => {
590            matches!(**collection, Expr::Identifier(s) if s == sym)
591        }
592        Stmt::If {
593            then_block,
594            else_block,
595            ..
596        } => {
597            has_structural_mutation_on(then_block, sym)
598                || else_block
599                    .as_ref()
600                    .map_or(false, |eb| has_structural_mutation_on(eb, sym))
601        }
602        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
603            has_structural_mutation_on(body, sym)
604        }
605        Stmt::Inspect { arms, .. } => arms
606            .iter()
607            .any(|arm| has_structural_mutation_on(arm.body, sym)),
608        _ => false,
609    }
610}
611
612fn has_reassignment_on(stmts: &[Stmt<'_>], sym: Symbol) -> bool {
613    stmts.iter().any(|s| check_reassignment_stmt(s, sym))
614}
615
616fn check_reassignment_stmt(stmt: &Stmt<'_>, sym: Symbol) -> bool {
617    match stmt {
618        Stmt::Set { target, .. } => *target == sym,
619        Stmt::If {
620            then_block,
621            else_block,
622            ..
623        } => {
624            has_reassignment_on(then_block, sym)
625                || else_block
626                    .as_ref()
627                    .map_or(false, |eb| has_reassignment_on(eb, sym))
628        }
629        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => has_reassignment_on(body, sym),
630        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| has_reassignment_on(arm.body, sym)),
631        _ => false,
632    }
633}
634
635fn is_consumed_param(stmts: &[Stmt<'_>], sym: Symbol) -> bool {
636    for stmt in stmts {
637        match stmt {
638            Stmt::Let {
639                mutable: true,
640                value,
641                ..
642            } => {
643                if matches!(value, Expr::Identifier(s) if *s == sym) {
644                    return true;
645                }
646            }
647            Stmt::If {
648                then_block,
649                else_block,
650                ..
651            } => {
652                if is_consumed_param(then_block, sym) {
653                    return true;
654                }
655                if let Some(else_b) = else_block {
656                    if is_consumed_param(else_b, sym) {
657                        return true;
658                    }
659                }
660            }
661            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
662                if is_consumed_param(body, sym) {
663                    return true;
664                }
665            }
666            _ => {}
667        }
668    }
669    false
670}
671
672fn is_sole_return_param(stmts: &[Stmt<'_>], sym: Symbol) -> bool {
673    let mut returns = Vec::new();
674    collect_returns(stmts, &mut returns);
675    !returns.is_empty() && returns.iter().all(|r| *r == sym)
676}
677
678fn collect_returns(stmts: &[Stmt<'_>], returns: &mut Vec<Symbol>) {
679    for stmt in stmts {
680        match stmt {
681            Stmt::Return { value: Some(expr) } => {
682                if let Expr::Identifier(sym) = expr {
683                    returns.push(*sym);
684                } else {
685                    // Non-identifier return — sentinel that won't match
686                    returns.push(Symbol::EMPTY);
687                }
688            }
689            Stmt::If {
690                then_block,
691                else_block,
692                ..
693            } => {
694                collect_returns(then_block, returns);
695                if let Some(else_b) = else_block {
696                    collect_returns(else_b, returns);
697                }
698            }
699            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
700                collect_returns(body, returns);
701            }
702            Stmt::Inspect { arms, .. } => {
703                for arm in arms {
704                    collect_returns(arm.body, returns);
705                }
706            }
707            _ => {}
708        }
709    }
710}
711
712// =============================================================================
713// Call-site compatibility for &mut [T]
714// =============================================================================
715
716/// Collect functions in `mutable_borrow` that have incompatible call sites.
717/// An incompatible call site is one where the function's return value is used
718/// (e.g., in Let, Show, Return, or expression context) because &mut [T]
719/// functions have void return.
720fn collect_incompatible_mut_borrow_callsites(
721    stmts: &[Stmt<'_>],
722    mutable_borrow: &HashMap<Symbol, HashSet<Symbol>>,
723    fn_params: &HashMap<Symbol, Vec<Symbol>>,
724) -> HashSet<Symbol> {
725    let mut incompatible = HashSet::new();
726    for stmt in stmts {
727        if let Stmt::FunctionDef { body, .. } = stmt {
728            check_callsite_compat_stmts(body, mutable_borrow, fn_params, &mut incompatible);
729        }
730    }
731    // Also check main-level statements (not inside function defs)
732    check_callsite_compat_stmts(stmts, mutable_borrow, fn_params, &mut incompatible);
733    incompatible
734}
735
736fn check_callsite_compat_stmts(
737    stmts: &[Stmt<'_>],
738    mutable_borrow: &HashMap<Symbol, HashSet<Symbol>>,
739    fn_params: &HashMap<Symbol, Vec<Symbol>>,
740    incompatible: &mut HashSet<Symbol>,
741) {
742    for stmt in stmts {
743        check_callsite_compat_stmt(stmt, mutable_borrow, fn_params, incompatible);
744    }
745}
746
747fn check_callsite_compat_stmt(
748    stmt: &Stmt<'_>,
749    mutable_borrow: &HashMap<Symbol, HashSet<Symbol>>,
750    fn_params: &HashMap<Symbol, Vec<Symbol>>,
751    incompatible: &mut HashSet<Symbol>,
752) {
753    match stmt {
754        // Stmt::Call → void context, always OK. But check args for nested calls.
755        Stmt::Call { args, .. } => {
756            for arg in args {
757                check_callsite_compat_expr(arg, mutable_borrow, incompatible);
758            }
759        }
760        // Stmt::Set → OK if target == args[mut_borrow_pos], otherwise check expr
761        Stmt::Set { target, value } => {
762            if let Expr::Call { function, args } = value {
763                if mutable_borrow.contains_key(function) {
764                    // Check that target is at a mut_borrow position
765                    let mut_positions: HashSet<usize> = fn_params
766                        .get(function)
767                        .map(|params| {
768                            params
769                                .iter()
770                                .enumerate()
771                                .filter(|(_, sym)| {
772                                    mutable_borrow
773                                        .get(function)
774                                        .map(|s| s.contains(sym))
775                                        .unwrap_or(false)
776                                })
777                                .map(|(i, _)| i)
778                                .collect()
779                        })
780                        .unwrap_or_default();
781
782                    let target_at_mut_pos = args.iter().enumerate().any(|(i, a)| {
783                        mut_positions.contains(&i)
784                            && matches!(a, Expr::Identifier(sym) if *sym == *target)
785                    });
786
787                    if !target_at_mut_pos {
788                        incompatible.insert(*function);
789                    }
790                }
791                // Check args for nested calls
792                for arg in args {
793                    check_callsite_compat_expr(arg, mutable_borrow, incompatible);
794                }
795            } else {
796                check_callsite_compat_expr(value, mutable_borrow, incompatible);
797            }
798        }
799        // Stmt::Let → if value is a call to a mut_borrow function, it's incompatible
800        Stmt::Let { value, .. } => {
801            check_callsite_compat_expr(value, mutable_borrow, incompatible);
802        }
803        Stmt::Return { value: Some(v) } => {
804            check_callsite_compat_expr(v, mutable_borrow, incompatible);
805        }
806        Stmt::Show { object, .. } => {
807            check_callsite_compat_expr(object, mutable_borrow, incompatible);
808        }
809        Stmt::Push { value, collection } => {
810            check_callsite_compat_expr(value, mutable_borrow, incompatible);
811            check_callsite_compat_expr(collection, mutable_borrow, incompatible);
812        }
813        Stmt::SetIndex {
814            collection,
815            index,
816            value,
817        } => {
818            check_callsite_compat_expr(collection, mutable_borrow, incompatible);
819            check_callsite_compat_expr(index, mutable_borrow, incompatible);
820            check_callsite_compat_expr(value, mutable_borrow, incompatible);
821        }
822        Stmt::If {
823            cond,
824            then_block,
825            else_block,
826        } => {
827            check_callsite_compat_expr(cond, mutable_borrow, incompatible);
828            check_callsite_compat_stmts(then_block, mutable_borrow, fn_params, incompatible);
829            if let Some(else_b) = else_block {
830                check_callsite_compat_stmts(else_b, mutable_borrow, fn_params, incompatible);
831            }
832        }
833        Stmt::While { cond, body, .. } => {
834            check_callsite_compat_expr(cond, mutable_borrow, incompatible);
835            check_callsite_compat_stmts(body, mutable_borrow, fn_params, incompatible);
836        }
837        Stmt::Repeat { iterable, body, .. } => {
838            check_callsite_compat_expr(iterable, mutable_borrow, incompatible);
839            check_callsite_compat_stmts(body, mutable_borrow, fn_params, incompatible);
840        }
841        Stmt::Inspect { arms, .. } => {
842            for arm in arms {
843                check_callsite_compat_stmts(arm.body, mutable_borrow, fn_params, incompatible);
844            }
845        }
846        // Skip FunctionDef — handled at top level
847        _ => {}
848    }
849}
850
851/// Check if an expression uses a mut_borrow function in value context (incompatible).
852fn check_callsite_compat_expr(
853    expr: &Expr<'_>,
854    mutable_borrow: &HashMap<Symbol, HashSet<Symbol>>,
855    incompatible: &mut HashSet<Symbol>,
856) {
857    match expr {
858        Expr::Call { function, args } => {
859            if mutable_borrow.contains_key(function) {
860                incompatible.insert(*function);
861            }
862            for arg in args {
863                check_callsite_compat_expr(arg, mutable_borrow, incompatible);
864            }
865        }
866        Expr::BinaryOp { left, right, .. } => {
867            check_callsite_compat_expr(left, mutable_borrow, incompatible);
868            check_callsite_compat_expr(right, mutable_borrow, incompatible);
869        }
870        Expr::Index { collection, index } => {
871            check_callsite_compat_expr(collection, mutable_borrow, incompatible);
872            check_callsite_compat_expr(index, mutable_borrow, incompatible);
873        }
874        Expr::Length { collection } => {
875            check_callsite_compat_expr(collection, mutable_borrow, incompatible);
876        }
877        Expr::Contains { collection, value } => {
878            check_callsite_compat_expr(collection, mutable_borrow, incompatible);
879            check_callsite_compat_expr(value, mutable_borrow, incompatible);
880        }
881        Expr::FieldAccess { object, .. } => {
882            check_callsite_compat_expr(object, mutable_borrow, incompatible);
883        }
884        Expr::Copy { expr: inner }
885        | Expr::Give { value: inner }
886        | Expr::OptionSome { value: inner } => {
887            check_callsite_compat_expr(inner, mutable_borrow, incompatible);
888        }
889        _ => {}
890    }
891}
892
893// =============================================================================
894// Consume-Alias Detection for &mut [T]
895// =============================================================================
896
897/// Detect consume-alias pattern: finds exactly one `Let mutable <alias> be <param>`
898/// at the top level of the function body. Returns the alias symbol if found.
899pub(crate) fn detect_consume_alias(body: &[Stmt<'_>], param_sym: Symbol) -> Option<Symbol> {
900    let mut alias = None;
901    for stmt in body {
902        if let Stmt::Let {
903            var,
904            mutable: true,
905            value,
906            ..
907        } = stmt
908        {
909            if matches!(value, Expr::Identifier(s) if *s == param_sym) {
910                if alias.is_some() {
911                    return None; // Multiple consumes — reject
912                }
913                alias = Some(*var);
914            }
915        }
916    }
917    alias
918}
919
920/// Check that every return in the body returns either `param_sym` or `alias_sym`.
921fn is_sole_return_param_or_alias(stmts: &[Stmt<'_>], param_sym: Symbol, alias_sym: Symbol) -> bool {
922    let mut returns = Vec::new();
923    collect_returns(stmts, &mut returns);
924    !returns.is_empty() && returns.iter().all(|r| *r == param_sym || *r == alias_sym)
925}
926
927/// Check that every `Set <alias> to <expr>` in the body is a call to `func_name`
928/// with `alias` at position `param_position`. No other reassignment patterns allowed.
929fn reassignment_only_self_calls(
930    body: &[Stmt<'_>],
931    alias: Symbol,
932    func_name: Symbol,
933    param_position: usize,
934) -> bool {
935    check_reassignment_self_calls(body, alias, func_name, param_position)
936}
937
938fn check_reassignment_self_calls(
939    stmts: &[Stmt<'_>],
940    alias: Symbol,
941    func_name: Symbol,
942    param_position: usize,
943) -> bool {
944    for stmt in stmts {
945        match stmt {
946            Stmt::Set { target, value } if *target == alias => {
947                // Must be a call to func_name with alias at param_position
948                match value {
949                    Expr::Call { function, args } if *function == func_name => {
950                        let arg_at_pos = args.get(param_position);
951                        let is_alias_at_pos = arg_at_pos
952                            .map(|a| matches!(a, Expr::Identifier(s) if *s == alias))
953                            .unwrap_or(false);
954                        if !is_alias_at_pos {
955                            return false;
956                        }
957                    }
958                    _ => return false, // Non-self-call reassignment
959                }
960            }
961            Stmt::If {
962                then_block,
963                else_block,
964                ..
965            } => {
966                if !check_reassignment_self_calls(then_block, alias, func_name, param_position) {
967                    return false;
968                }
969                if let Some(else_b) = else_block {
970                    if !check_reassignment_self_calls(else_b, alias, func_name, param_position) {
971                        return false;
972                    }
973                }
974            }
975            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
976                if !check_reassignment_self_calls(body, alias, func_name, param_position) {
977                    return false;
978                }
979            }
980            Stmt::Inspect { arms, .. } => {
981                for arm in arms {
982                    if !check_reassignment_self_calls(arm.body, alias, func_name, param_position) {
983                        return false;
984                    }
985                }
986            }
987            _ => {}
988        }
989    }
990    true
991}
992
993/// Check that `param_sym` is dead after the consume statement
994/// (`Let mutable <alias> be <param>`). Scans top-level statements:
995/// before the consume, param can be used freely. After the consume,
996/// param must never appear in any expression.
997fn is_param_dead_after_consume(body: &[Stmt<'_>], param_sym: Symbol, alias: Symbol) -> bool {
998    let mut found_consume = false;
999    for stmt in body {
1000        if !found_consume {
1001            // Check if this is the consume statement
1002            if let Stmt::Let {
1003                var,
1004                mutable: true,
1005                value,
1006                ..
1007            } = stmt
1008            {
1009                if *var == alias && matches!(value, Expr::Identifier(s) if *s == param_sym) {
1010                    found_consume = true;
1011                    continue;
1012                }
1013            }
1014        } else {
1015            // After the consume: param must not appear
1016            if stmt_references_symbol(stmt, param_sym) {
1017                return false;
1018            }
1019        }
1020    }
1021    found_consume // Must have actually found the consume
1022}
1023
1024/// Check if a statement references a given symbol anywhere (expressions, collections, etc.).
1025pub(crate) fn stmt_references_symbol(stmt: &Stmt<'_>, sym: Symbol) -> bool {
1026    match stmt {
1027        Stmt::Let { value, .. } => expr_references_symbol(value, sym),
1028        Stmt::Set { target, value } => *target == sym || expr_references_symbol(value, sym),
1029        Stmt::Call { function, args } => {
1030            *function == sym || args.iter().any(|a| expr_references_symbol(a, sym))
1031        }
1032        Stmt::Push { value, collection } => {
1033            expr_references_symbol(value, sym) || expr_references_symbol(collection, sym)
1034        }
1035        Stmt::Pop { collection, into } => {
1036            expr_references_symbol(collection, sym) || into.map_or(false, |s| s == sym)
1037        }
1038        Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
1039            expr_references_symbol(value, sym) || expr_references_symbol(collection, sym)
1040        }
1041        Stmt::SetIndex {
1042            collection,
1043            index,
1044            value,
1045        } => {
1046            expr_references_symbol(collection, sym)
1047                || expr_references_symbol(index, sym)
1048                || expr_references_symbol(value, sym)
1049        }
1050        Stmt::SetField { object, value, .. } => {
1051            expr_references_symbol(object, sym) || expr_references_symbol(value, sym)
1052        }
1053        Stmt::Return { value: Some(v) } => expr_references_symbol(v, sym),
1054        Stmt::Return { value: None } => false,
1055        Stmt::If {
1056            cond,
1057            then_block,
1058            else_block,
1059        } => {
1060            expr_references_symbol(cond, sym)
1061                || then_block.iter().any(|s| stmt_references_symbol(s, sym))
1062                || else_block.as_ref().map_or(false, |eb| {
1063                    eb.iter().any(|s| stmt_references_symbol(s, sym))
1064                })
1065        }
1066        Stmt::While { cond, body, .. } => {
1067            expr_references_symbol(cond, sym) || body.iter().any(|s| stmt_references_symbol(s, sym))
1068        }
1069        Stmt::Repeat { iterable, body, .. } => {
1070            expr_references_symbol(iterable, sym)
1071                || body.iter().any(|s| stmt_references_symbol(s, sym))
1072        }
1073        Stmt::Inspect { arms, .. } => arms
1074            .iter()
1075            .any(|arm| arm.body.iter().any(|s| stmt_references_symbol(s, sym))),
1076        Stmt::Show { object, .. } => expr_references_symbol(object, sym),
1077        _ => false,
1078    }
1079}
1080
1081fn expr_references_symbol(expr: &Expr<'_>, sym: Symbol) -> bool {
1082    match expr {
1083        Expr::Identifier(s) => *s == sym,
1084        Expr::BinaryOp { left, right, .. } => {
1085            expr_references_symbol(left, sym) || expr_references_symbol(right, sym)
1086        }
1087        Expr::Not { operand } => expr_references_symbol(operand, sym),
1088        Expr::Call { function, args } => {
1089            *function == sym || args.iter().any(|a| expr_references_symbol(a, sym))
1090        }
1091        Expr::Index { collection, index } => {
1092            expr_references_symbol(collection, sym) || expr_references_symbol(index, sym)
1093        }
1094        Expr::Length { collection } => expr_references_symbol(collection, sym),
1095        Expr::Contains { collection, value } => {
1096            expr_references_symbol(collection, sym) || expr_references_symbol(value, sym)
1097        }
1098        Expr::FieldAccess { object, .. } => expr_references_symbol(object, sym),
1099        Expr::Slice {
1100            collection,
1101            start,
1102            end,
1103        } => {
1104            expr_references_symbol(collection, sym)
1105                || expr_references_symbol(start, sym)
1106                || expr_references_symbol(end, sym)
1107        }
1108        Expr::Copy { expr: inner }
1109        | Expr::Give { value: inner }
1110        | Expr::OptionSome { value: inner } => expr_references_symbol(inner, sym),
1111        Expr::CallExpr { callee, args } => {
1112            expr_references_symbol(callee, sym)
1113                || args.iter().any(|a| expr_references_symbol(a, sym))
1114        }
1115        _ => false,
1116    }
1117}