Skip to main content

logicaffeine_compile/optimize/
partial_eval.rs

1use std::collections::HashMap;
2
3use crate::arena::Arena;
4use crate::ast::stmt::{Block, Expr, Literal, Stmt, StringPart, TypeExpr};
5use crate::intern::{Interner, Symbol};
6
7use super::bta::{self, BindingTime, Division};
8use super::effects::EffectEnv;
9
10type SpecKey = (Symbol, Vec<Option<Literal>>);
11
12struct FuncInfo<'a> {
13    name: Symbol,
14    params: Vec<(Symbol, &'a TypeExpr<'a>)>,
15    body: Block<'a>,
16    generics: Vec<Symbol>,
17    return_type: Option<&'a TypeExpr<'a>>,
18    opt_flags: crate::optimization::OptimizationConfig,
19}
20
21struct SpecRegistry<'a> {
22    cache: HashMap<SpecKey, Symbol>,
23    new_funcs: Vec<Stmt<'a>>,
24    variant_count: HashMap<Symbol, usize>,
25    history: Vec<SpecKey>,
26    bta_cache: Option<super::bta::BtaCache>,
27}
28
29impl<'a> SpecRegistry<'a> {
30    fn new() -> Self {
31        SpecRegistry {
32            cache: HashMap::new(),
33            new_funcs: Vec::new(),
34            variant_count: HashMap::new(),
35            history: Vec::new(),
36            bta_cache: None,
37        }
38    }
39}
40
41fn spec_key_embeds(earlier: &SpecKey, later: &SpecKey) -> bool {
42    if earlier.0 != later.0 {
43        return false;
44    }
45    let ea = &earlier.1;
46    let la = &later.1;
47    if ea.len() != la.len() {
48        return false;
49    }
50    if ea == la {
51        return false; // reflexive — not a proper embedding
52    }
53    let mut strict = false;
54    for (e, l) in ea.iter().zip(la.iter()) {
55        match (e, l) {
56            (None, _) => {}                  // dynamic embeds in anything
57            (Some(_), None) => return false, // static does not embed in dynamic
58            (Some(e_lit), Some(l_lit)) => {
59                if !literal_embeds(e_lit, l_lit) {
60                    return false;
61                }
62                if e_lit != l_lit {
63                    strict = true;
64                }
65            }
66        }
67    }
68    strict
69}
70
71fn literal_embeds(a: &Literal, b: &Literal) -> bool {
72    match (a, b) {
73        (Literal::Number(x), Literal::Number(y)) => x.abs() <= y.abs(),
74        (Literal::Float(x), Literal::Float(y)) => x.abs() <= y.abs(),
75        (Literal::Boolean(_), Literal::Boolean(_)) => true,
76        (Literal::Text(x), Literal::Text(y)) => x.index() <= y.index(),
77        (Literal::Nothing, Literal::Nothing) => true,
78        _ => a == b,
79    }
80}
81
82fn collect_func_defs<'a>(stmts: &[Stmt<'a>]) -> HashMap<Symbol, FuncInfo<'a>> {
83    let mut defs = HashMap::new();
84    for stmt in stmts {
85        if let Stmt::FunctionDef {
86            name,
87            params,
88            body,
89            generics,
90            return_type,
91            is_native,
92            opt_flags,
93            ..
94        } = stmt
95        {
96            if !is_native {
97                defs.insert(
98                    *name,
99                    FuncInfo {
100                        name: *name,
101                        params: params.clone(),
102                        body,
103                        generics: generics.clone(),
104                        return_type: *return_type,
105                        opt_flags: opt_flags.clone(),
106                    },
107                );
108            }
109        }
110    }
111    defs
112}
113
114fn body_has_io(stmts: &[Stmt]) -> bool {
115    for stmt in stmts {
116        if stmt_has_io(stmt) {
117            return true;
118        }
119    }
120    false
121}
122
123/// Whether a statement carries an opaque effectful boundary that disqualifies its
124/// enclosing function from specialization. This is the fallback for the no-`effect_env`
125/// path; the production path uses `EffectEnv::function_is_specialization_safe`, which is
126/// strictly more precise. The name is kept for continuity, but it now covers IO *and* the
127/// concurrency / networking constructs the substitution cannot enter.
128fn stmt_has_io(stmt: &Stmt) -> bool {
129    match stmt {
130        Stmt::Show { .. }
131        | Stmt::WriteFile { .. }
132        | Stmt::SendMessage { .. }
133        | Stmt::StreamMessage { .. }
134        | Stmt::Sleep { .. }
135        | Stmt::SendPipe { .. }
136        | Stmt::TrySendPipe { .. }
137        | Stmt::ReceivePipe { .. }
138        | Stmt::TryReceivePipe { .. }
139        | Stmt::ReadFrom { .. }
140        | Stmt::Check { .. } => true,
141        // Concurrency / spawn / networking — opaque boundaries, never specialize across.
142        Stmt::LaunchTask { .. }
143        | Stmt::LaunchTaskWithHandle { .. }
144        | Stmt::CreatePipe { .. }
145        | Stmt::StopTask { .. }
146        | Stmt::Spawn { .. }
147        | Stmt::Listen { .. }
148        | Stmt::ConnectTo { .. }
149        | Stmt::LetPeerAgent { .. }
150        | Stmt::AwaitMessage { .. }
151        | Stmt::Sync { .. }
152        | Stmt::Mount { .. } => true,
153        Stmt::IncreaseCrdt { .. }
154        | Stmt::DecreaseCrdt { .. }
155        | Stmt::MergeCrdt { .. }
156        | Stmt::JoinCrdt { .. }
157        | Stmt::AppendToSequence { .. }
158        | Stmt::ResolveConflict { .. } => true,
159        // A Select is nondeterministic and a Concurrent/Parallel block is a concurrency
160        // boundary — disqualifying regardless of their body contents.
161        Stmt::Select { .. } | Stmt::Concurrent { .. } | Stmt::Parallel { .. } => true,
162        Stmt::If {
163            then_block,
164            else_block,
165            ..
166        } => body_has_io(then_block) || else_block.map_or(false, |eb| body_has_io(eb)),
167        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => body_has_io(body),
168        Stmt::Zone { body, .. } | Stmt::Reversibly { body } => body_has_io(body),
169        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| body_has_io(arm.body)),
170        _ => false,
171    }
172}
173
174fn body_has_escape(stmts: &[Stmt]) -> bool {
175    for stmt in stmts {
176        match stmt {
177            Stmt::Escape { .. } => return true,
178            Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
179                if expr_has_escape(value) {
180                    return true;
181                }
182            }
183            Stmt::If {
184                then_block,
185                else_block,
186                ..
187            } => {
188                if body_has_escape(then_block) {
189                    return true;
190                }
191                if let Some(eb) = else_block {
192                    if body_has_escape(eb) {
193                        return true;
194                    }
195                }
196            }
197            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
198                if body_has_escape(body) {
199                    return true;
200                }
201            }
202            Stmt::Return { value } => {
203                if let Some(v) = value {
204                    if expr_has_escape(v) {
205                        return true;
206                    }
207                }
208            }
209            _ => {}
210        }
211    }
212    false
213}
214
215fn expr_has_escape(expr: &Expr) -> bool {
216    match expr {
217        Expr::Escape { .. } => true,
218        _ => false,
219    }
220}
221
222fn classify_arg<'a>(arg: &Expr<'a>, division: Option<&Division>) -> Option<Literal> {
223    match arg {
224        Expr::Literal(lit) => Some(lit.clone()),
225        _ => {
226            if let Some(div) = division {
227                match bta::analyze_expr(arg, div) {
228                    BindingTime::Static(lit) => Some(lit),
229                    BindingTime::Dynamic => None,
230                }
231            } else {
232                None
233            }
234        }
235    }
236}
237
238fn compute_spec_key<'a>(
239    function: Symbol,
240    args: &[&'a Expr<'a>],
241    division: Option<&Division>,
242) -> (SpecKey, Vec<Option<Literal>>) {
243    let arg_classifications: Vec<Option<Literal>> =
244        args.iter().map(|a| classify_arg(a, division)).collect();
245    let key = (function, arg_classifications.clone());
246    (key, arg_classifications)
247}
248
249fn is_mixed(classifications: &[Option<Literal>]) -> bool {
250    let has_static = classifications.iter().any(|c| c.is_some());
251    let has_dynamic = classifications.iter().any(|c| c.is_none());
252    has_static && has_dynamic
253}
254
255/// The name of `func_name` specialized to the static arguments in `classifications`: the function's name,
256/// then each static argument's position and value. A name `taken` already (a function of the program, or
257/// another specialization) gets a trailing `_` until it is not, since two functions under one name would be
258/// one function.
259fn make_spec_name(
260    interner: &mut Interner,
261    func_name: Symbol,
262    classifications: &[Option<Literal>],
263    taken: &dyn Fn(Symbol) -> bool,
264) -> Symbol {
265    let mut name = interner.resolve(func_name).to_string();
266    for (i, c) in classifications.iter().enumerate() {
267        if let Some(lit) = c {
268            name.push_str(&format!("_s{}_{}", i, literal_to_name_part(lit)));
269        }
270    }
271    let mut sym = interner.intern(&name);
272    while taken(sym) {
273        name.push('_');
274        sym = interner.intern(&name);
275    }
276    sym
277}
278
279/// A literal's part of a specialization's name: an identifier fragment, and a different one for every
280/// literal. A float is named by its bits, so `15.0` is not `15` and `-0.0` is not `0.0`.
281fn literal_to_name_part(lit: &Literal) -> String {
282    fn signed(n: i64) -> String {
283        if n < 0 {
284            format!("m{}", n.unsigned_abs())
285        } else {
286            n.to_string()
287        }
288    }
289    match lit {
290        Literal::Number(n) => signed(*n),
291        Literal::Float(f) => format!("f{:x}", f.to_bits()),
292        Literal::Boolean(b) => b.to_string(),
293        Literal::Text(s) => format!("t{:x}", s.index()),
294        Literal::Nothing => "nothing".to_string(),
295        Literal::Char(c) => format!("c{:x}", *c as u32),
296        Literal::Duration(n) => format!("du{}", signed(*n)),
297        Literal::Date(n) => format!("da{}", signed(*n as i64)),
298        Literal::Moment(n) => format!("mo{}", signed(*n)),
299        Literal::Span { months, days } => {
300            format!("sp{}_{}", signed(*months as i64), signed(*days as i64))
301        }
302        Literal::Time(n) => format!("ti{}", signed(*n)),
303    }
304}
305
306fn substitute_expr<'a>(
307    expr: &'a Expr<'a>,
308    substitutions: &HashMap<Symbol, &'a Expr<'a>>,
309    expr_arena: &'a Arena<Expr<'a>>,
310) -> &'a Expr<'a> {
311    match expr {
312        Expr::Identifier(sym) => {
313            if let Some(replacement) = substitutions.get(sym) {
314                replacement
315            } else {
316                expr
317            }
318        }
319        Expr::BinaryOp { op, left, right } => {
320            let new_left = substitute_expr(left, substitutions, expr_arena);
321            let new_right = substitute_expr(right, substitutions, expr_arena);
322            if std::ptr::eq(new_left as *const _, *left as *const _)
323                && std::ptr::eq(new_right as *const _, *right as *const _)
324            {
325                expr
326            } else {
327                expr_arena.alloc(Expr::BinaryOp {
328                    op: *op,
329                    left: new_left,
330                    right: new_right,
331                })
332            }
333        }
334        Expr::Not { operand } => {
335            let new_operand = substitute_expr(operand, substitutions, expr_arena);
336            if std::ptr::eq(new_operand as *const _, *operand as *const _) {
337                expr
338            } else {
339                expr_arena.alloc(Expr::Not {
340                    operand: new_operand,
341                })
342            }
343        }
344        Expr::Call { function, args } => {
345            let new_args: Vec<&'a Expr<'a>> = args
346                .iter()
347                .map(|a| substitute_expr(a, substitutions, expr_arena))
348                .collect();
349            let changed = new_args
350                .iter()
351                .zip(args.iter())
352                .any(|(new, old)| !std::ptr::eq(*new as *const _, *old as *const _));
353            if changed {
354                expr_arena.alloc(Expr::Call {
355                    function: *function,
356                    args: new_args,
357                })
358            } else {
359                expr
360            }
361        }
362        Expr::Index { collection, index } => {
363            let new_coll = substitute_expr(collection, substitutions, expr_arena);
364            let new_idx = substitute_expr(index, substitutions, expr_arena);
365            if std::ptr::eq(new_coll as *const _, *collection as *const _)
366                && std::ptr::eq(new_idx as *const _, *index as *const _)
367            {
368                expr
369            } else {
370                expr_arena.alloc(Expr::Index {
371                    collection: new_coll,
372                    index: new_idx,
373                })
374            }
375        }
376        Expr::Length { collection } => {
377            let new_coll = substitute_expr(collection, substitutions, expr_arena);
378            if std::ptr::eq(new_coll as *const _, *collection as *const _) {
379                expr
380            } else {
381                expr_arena.alloc(Expr::Length {
382                    collection: new_coll,
383                })
384            }
385        }
386        Expr::Slice {
387            collection,
388            start,
389            end,
390        } => {
391            let new_coll = substitute_expr(collection, substitutions, expr_arena);
392            let new_start = substitute_expr(start, substitutions, expr_arena);
393            let new_end = substitute_expr(end, substitutions, expr_arena);
394            if std::ptr::eq(new_coll as *const _, *collection as *const _)
395                && std::ptr::eq(new_start as *const _, *start as *const _)
396                && std::ptr::eq(new_end as *const _, *end as *const _)
397            {
398                expr
399            } else {
400                expr_arena.alloc(Expr::Slice {
401                    collection: new_coll,
402                    start: new_start,
403                    end: new_end,
404                })
405            }
406        }
407        Expr::FieldAccess { object, field } => {
408            let new_obj = substitute_expr(object, substitutions, expr_arena);
409            if std::ptr::eq(new_obj as *const _, *object as *const _) {
410                expr
411            } else {
412                expr_arena.alloc(Expr::FieldAccess {
413                    object: new_obj,
414                    field: *field,
415                })
416            }
417        }
418        Expr::Contains { collection, value } => {
419            let new_coll = substitute_expr(collection, substitutions, expr_arena);
420            let new_val = substitute_expr(value, substitutions, expr_arena);
421            if std::ptr::eq(new_coll as *const _, *collection as *const _)
422                && std::ptr::eq(new_val as *const _, *value as *const _)
423            {
424                expr
425            } else {
426                expr_arena.alloc(Expr::Contains {
427                    collection: new_coll,
428                    value: new_val,
429                })
430            }
431        }
432        Expr::NewVariant {
433            enum_name,
434            variant,
435            fields,
436        } => {
437            let new_fields: Vec<(Symbol, &'a Expr<'a>)> = fields
438                .iter()
439                .map(|(name, val)| (*name, substitute_expr(val, substitutions, expr_arena)))
440                .collect();
441            let changed = new_fields
442                .iter()
443                .zip(fields.iter())
444                .any(|((_, new_v), (_, old_v))| {
445                    !std::ptr::eq(*new_v as *const _, *old_v as *const _)
446                });
447            if changed {
448                expr_arena.alloc(Expr::NewVariant {
449                    enum_name: *enum_name,
450                    variant: *variant,
451                    fields: new_fields,
452                })
453            } else {
454                expr
455            }
456        }
457        Expr::New {
458            type_name,
459            type_args,
460            init_fields,
461        } => {
462            let new_fields: Vec<(Symbol, &'a Expr<'a>)> = init_fields
463                .iter()
464                .map(|(name, val)| (*name, substitute_expr(val, substitutions, expr_arena)))
465                .collect();
466            let changed =
467                new_fields
468                    .iter()
469                    .zip(init_fields.iter())
470                    .any(|((_, new_v), (_, old_v))| {
471                        !std::ptr::eq(*new_v as *const _, *old_v as *const _)
472                    });
473            if changed {
474                expr_arena.alloc(Expr::New {
475                    type_name: *type_name,
476                    type_args: type_args.clone(),
477                    init_fields: new_fields,
478                })
479            } else {
480                expr
481            }
482        }
483        Expr::OptionSome { value } => {
484            let new_val = substitute_expr(value, substitutions, expr_arena);
485            if std::ptr::eq(new_val as *const _, *value as *const _) {
486                expr
487            } else {
488                expr_arena.alloc(Expr::OptionSome { value: new_val })
489            }
490        }
491        Expr::Copy { expr: inner } => {
492            let new_inner = substitute_expr(inner, substitutions, expr_arena);
493            if std::ptr::eq(new_inner as *const _, *inner as *const _) {
494                expr
495            } else {
496                expr_arena.alloc(Expr::Copy { expr: new_inner })
497            }
498        }
499        Expr::Give { value } => {
500            let new_val = substitute_expr(value, substitutions, expr_arena);
501            if std::ptr::eq(new_val as *const _, *value as *const _) {
502                expr
503            } else {
504                expr_arena.alloc(Expr::Give { value: new_val })
505            }
506        }
507        Expr::List(items) => {
508            let new_items: Vec<&'a Expr<'a>> = items
509                .iter()
510                .map(|item| substitute_expr(item, substitutions, expr_arena))
511                .collect();
512            let changed = new_items
513                .iter()
514                .zip(items.iter())
515                .any(|(new, old)| !std::ptr::eq(*new as *const _, *old as *const _));
516            if changed {
517                expr_arena.alloc(Expr::List(new_items))
518            } else {
519                expr
520            }
521        }
522        Expr::Tuple(items) => {
523            let new_items: Vec<&'a Expr<'a>> = items
524                .iter()
525                .map(|item| substitute_expr(item, substitutions, expr_arena))
526                .collect();
527            let changed = new_items
528                .iter()
529                .zip(items.iter())
530                .any(|(new, old)| !std::ptr::eq(*new as *const _, *old as *const _));
531            if changed {
532                expr_arena.alloc(Expr::Tuple(new_items))
533            } else {
534                expr
535            }
536        }
537        Expr::Range { start, end } => {
538            let new_start = substitute_expr(start, substitutions, expr_arena);
539            let new_end = substitute_expr(end, substitutions, expr_arena);
540            if std::ptr::eq(new_start as *const _, *start as *const _)
541                && std::ptr::eq(new_end as *const _, *end as *const _)
542            {
543                expr
544            } else {
545                expr_arena.alloc(Expr::Range {
546                    start: new_start,
547                    end: new_end,
548                })
549            }
550        }
551        Expr::Union { left, right } => {
552            let new_left = substitute_expr(left, substitutions, expr_arena);
553            let new_right = substitute_expr(right, substitutions, expr_arena);
554            if std::ptr::eq(new_left as *const _, *left as *const _)
555                && std::ptr::eq(new_right as *const _, *right as *const _)
556            {
557                expr
558            } else {
559                expr_arena.alloc(Expr::Union {
560                    left: new_left,
561                    right: new_right,
562                })
563            }
564        }
565        Expr::Intersection { left, right } => {
566            let new_left = substitute_expr(left, substitutions, expr_arena);
567            let new_right = substitute_expr(right, substitutions, expr_arena);
568            if std::ptr::eq(new_left as *const _, *left as *const _)
569                && std::ptr::eq(new_right as *const _, *right as *const _)
570            {
571                expr
572            } else {
573                expr_arena.alloc(Expr::Intersection {
574                    left: new_left,
575                    right: new_right,
576                })
577            }
578        }
579        Expr::CallExpr { callee, args } => {
580            let new_callee = substitute_expr(callee, substitutions, expr_arena);
581            let new_args: Vec<&'a Expr<'a>> = args
582                .iter()
583                .map(|a| substitute_expr(a, substitutions, expr_arena))
584                .collect();
585            let changed = !std::ptr::eq(new_callee as *const _, *callee as *const _)
586                || new_args
587                    .iter()
588                    .zip(args.iter())
589                    .any(|(new, old)| !std::ptr::eq(*new as *const _, *old as *const _));
590            if changed {
591                expr_arena.alloc(Expr::CallExpr {
592                    callee: new_callee,
593                    args: new_args,
594                })
595            } else {
596                expr
597            }
598        }
599        Expr::WithCapacity { value, capacity } => {
600            let new_val = substitute_expr(value, substitutions, expr_arena);
601            let new_cap = substitute_expr(capacity, substitutions, expr_arena);
602            if std::ptr::eq(new_val as *const _, *value as *const _)
603                && std::ptr::eq(new_cap as *const _, *capacity as *const _)
604            {
605                expr
606            } else {
607                expr_arena.alloc(Expr::WithCapacity {
608                    value: new_val,
609                    capacity: new_cap,
610                })
611            }
612        }
613        Expr::InterpolatedString(parts) => {
614            let new_parts: Vec<StringPart<'a>> = parts
615                .iter()
616                .map(|part| match part {
617                    StringPart::Literal(_) => part.clone(),
618                    StringPart::Expr {
619                        value,
620                        format_spec,
621                        debug,
622                    } => {
623                        let new_val = substitute_expr(value, substitutions, expr_arena);
624                        if std::ptr::eq(new_val as *const _, *value as *const _) {
625                            part.clone()
626                        } else {
627                            StringPart::Expr {
628                                value: new_val,
629                                format_spec: *format_spec,
630                                debug: *debug,
631                            }
632                        }
633                    }
634                })
635                .collect();
636            expr_arena.alloc(Expr::InterpolatedString(new_parts))
637        }
638        _ => expr,
639    }
640}
641
642fn substitute_stmt<'a>(
643    stmt: &Stmt<'a>,
644    substitutions: &HashMap<Symbol, &'a Expr<'a>>,
645    expr_arena: &'a Arena<Expr<'a>>,
646    stmt_arena: &'a Arena<Stmt<'a>>,
647) -> Stmt<'a> {
648    match stmt {
649        Stmt::Let {
650            var,
651            value,
652            mutable,
653            ty,
654        } => Stmt::Let {
655            var: *var,
656            value: substitute_expr(value, substitutions, expr_arena),
657            mutable: *mutable,
658            ty: *ty,
659        },
660        Stmt::Set { target, value } => Stmt::Set {
661            target: *target,
662            value: substitute_expr(value, substitutions, expr_arena),
663        },
664        Stmt::Return { value } => Stmt::Return {
665            value: value.map(|v| substitute_expr(v, substitutions, expr_arena)),
666        },
667        Stmt::Show { object, recipient } => Stmt::Show {
668            object: substitute_expr(object, substitutions, expr_arena),
669            recipient: *recipient,
670        },
671        Stmt::Call { function, args } => Stmt::Call {
672            function: *function,
673            args: args
674                .iter()
675                .map(|a| substitute_expr(a, substitutions, expr_arena))
676                .collect(),
677        },
678        Stmt::If {
679            cond,
680            then_block,
681            else_block,
682        } => {
683            let new_then: Vec<Stmt<'a>> = then_block
684                .iter()
685                .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
686                .collect();
687            let new_else = else_block.map(|eb| {
688                let stmts: Vec<Stmt<'a>> = eb
689                    .iter()
690                    .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
691                    .collect();
692                stmt_arena.alloc_slice(stmts) as &[Stmt<'a>]
693            });
694            Stmt::If {
695                cond: substitute_expr(cond, substitutions, expr_arena),
696                then_block: stmt_arena.alloc_slice(new_then),
697                else_block: new_else,
698            }
699        }
700        Stmt::While {
701            cond,
702            body,
703            decreasing,
704        } => {
705            let new_body: Vec<Stmt<'a>> = body
706                .iter()
707                .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
708                .collect();
709            Stmt::While {
710                cond: substitute_expr(cond, substitutions, expr_arena),
711                body: stmt_arena.alloc_slice(new_body),
712                decreasing: *decreasing,
713            }
714        }
715        Stmt::Repeat {
716            pattern,
717            iterable,
718            body,
719        } => {
720            let new_body: Vec<Stmt<'a>> = body
721                .iter()
722                .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
723                .collect();
724            Stmt::Repeat {
725                pattern: pattern.clone(),
726                iterable: substitute_expr(iterable, substitutions, expr_arena),
727                body: stmt_arena.alloc_slice(new_body),
728            }
729        }
730        Stmt::SetIndex {
731            collection,
732            index,
733            value,
734        } => Stmt::SetIndex {
735            collection: substitute_expr(collection, substitutions, expr_arena),
736            index: substitute_expr(index, substitutions, expr_arena),
737            value: substitute_expr(value, substitutions, expr_arena),
738        },
739        Stmt::Push { value, collection } => Stmt::Push {
740            value: substitute_expr(value, substitutions, expr_arena),
741            collection: substitute_expr(collection, substitutions, expr_arena),
742        },
743        Stmt::SetField {
744            object,
745            field,
746            value,
747        } => Stmt::SetField {
748            object: substitute_expr(object, substitutions, expr_arena),
749            field: *field,
750            value: substitute_expr(value, substitutions, expr_arena),
751        },
752        Stmt::Give { object, recipient } => Stmt::Give {
753            object: substitute_expr(object, substitutions, expr_arena),
754            recipient: substitute_expr(recipient, substitutions, expr_arena),
755        },
756        Stmt::Add { value, collection } => Stmt::Add {
757            value: substitute_expr(value, substitutions, expr_arena),
758            collection: substitute_expr(collection, substitutions, expr_arena),
759        },
760        Stmt::Remove { value, collection } => Stmt::Remove {
761            value: substitute_expr(value, substitutions, expr_arena),
762            collection: substitute_expr(collection, substitutions, expr_arena),
763        },
764        Stmt::Inspect {
765            target,
766            arms,
767            has_otherwise,
768        } => {
769            let new_arms: Vec<_> = arms
770                .iter()
771                .map(|arm| {
772                    let new_body: Vec<Stmt<'a>> = arm
773                        .body
774                        .iter()
775                        .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
776                        .collect();
777                    crate::ast::stmt::MatchArm {
778                        enum_name: arm.enum_name,
779                        variant: arm.variant,
780                        bindings: arm.bindings.clone(),
781                        body: stmt_arena.alloc_slice(new_body),
782                    }
783                })
784                .collect();
785            Stmt::Inspect {
786                target: substitute_expr(target, substitutions, expr_arena),
787                arms: new_arms,
788                has_otherwise: *has_otherwise,
789            }
790        }
791        Stmt::RuntimeAssert {
792            condition,
793            hard,
794            dim,
795            reason,
796        } => Stmt::RuntimeAssert {
797            condition: substitute_expr(condition, substitutions, expr_arena),
798            hard: *hard,
799            dim: *dim,
800            reason: reason.map(|r| substitute_expr(r, substitutions, expr_arena)),
801        },
802        Stmt::Splice { body } => {
803            let new_body: Vec<Stmt<'a>> = body
804                .iter()
805                .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
806                .collect();
807            Stmt::Splice {
808                body: stmt_arena.alloc_slice(new_body),
809            }
810        }
811        other => other.clone(),
812    }
813}
814
815/// `block` with every read of a name in `substitutions` replaced by its expression, or `None` when a
816/// read is left: one inside a form the substitution carries through unchanged, or a name the block
817/// binds again. A value folded into a block reaches every place it is read there, or the block is not
818/// rewritten — the check is the exhaustive effect walk's (`mentions::stmt_touches`), so a form the
819/// substitution has no case for can only stop a fold, never leave a name dangling.
820pub(crate) fn substitute_block<'a>(
821    block: Block<'a>,
822    substitutions: &HashMap<Symbol, &'a Expr<'a>>,
823    expr_arena: &'a Arena<Expr<'a>>,
824    stmt_arena: &'a Arena<Stmt<'a>>,
825) -> Option<Vec<Stmt<'a>>> {
826    let out: Vec<Stmt<'a>> = block
827        .iter()
828        .map(|s| substitute_stmt(s, substitutions, expr_arena, stmt_arena))
829        .collect();
830    let left = out
831        .iter()
832        .any(|s| substitutions.keys().any(|name| super::mentions::stmt_touches(s, *name)));
833    (!left).then_some(out)
834}
835
836fn count_stmts(stmts: &[Stmt]) -> usize {
837    let mut count = 0;
838    for stmt in stmts {
839        count += 1;
840        match stmt {
841            Stmt::If {
842                then_block,
843                else_block,
844                ..
845            } => {
846                count += count_stmts(then_block);
847                if let Some(eb) = else_block {
848                    count += count_stmts(eb);
849                }
850            }
851            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
852                count += count_stmts(body);
853            }
854            Stmt::FunctionDef { body, .. } => {
855                count += count_stmts(body);
856            }
857            _ => {}
858        }
859    }
860    count
861}
862
863/// Whether a written type names any of `names` (a function's type parameters) anywhere inside it.
864fn type_mentions_any(t: &TypeExpr, names: &[Symbol]) -> bool {
865    match t {
866        TypeExpr::Primitive(s) | TypeExpr::Named(s) => names.contains(s),
867        TypeExpr::Generic { base, params } => {
868            names.contains(base) || params.iter().any(|p| type_mentions_any(p, names))
869        }
870        TypeExpr::Tuple(items) => items.iter().any(|p| type_mentions_any(p, names)),
871        TypeExpr::Record { field_types, .. } => {
872            field_types.iter().any(|p| type_mentions_any(p, names))
873        }
874        TypeExpr::Function { inputs, output } => {
875            inputs.iter().any(|p| type_mentions_any(p, names)) || type_mentions_any(output, names)
876        }
877        TypeExpr::Refinement { base: inner, .. }
878        | TypeExpr::Persistent { inner }
879        | TypeExpr::Mutable { inner } => type_mentions_any(inner, names),
880    }
881}
882
883fn try_specialize_call<'a>(
884    function: Symbol,
885    args: &[&'a Expr<'a>],
886    func_defs: &HashMap<Symbol, FuncInfo<'a>>,
887    registry: &mut SpecRegistry<'a>,
888    expr_arena: &'a Arena<Expr<'a>>,
889    stmt_arena: &'a Arena<Stmt<'a>>,
890    interner: &mut Interner,
891    effect_env: Option<&EffectEnv>,
892) -> Option<(Symbol, Vec<&'a Expr<'a>>)> {
893    // Each argument is an expression of the CALLER, so it is classified with nothing bound: a literal
894    // or a closed constant expression is static, an identifier is dynamic. The caller's known constants
895    // are already literals here (every specialization round runs after fold and propagation). The
896    // callee's parameter bindings are not a scope an argument can be read in: there a caller's `beta`
897    // would be taken for the callee's own `beta`.
898    let (_, mut classifications) = compute_spec_key(function, args, Some(&Division::new()));
899    // A parameter typed by the callee's own type parameters is never folded: the constant would
900    // fix `T` in a clone whose signature is still generic over it (`applyTwice_s1_1<T>` returning
901    // the literal `1` as a `T`).
902    if let Some(func_info) = func_defs.get(&function) {
903        for (i, (_, param_type)) in func_info.params.iter().enumerate() {
904            // A mutable argument denotes storage even when its current value is constant.
905            if matches!(param_type, TypeExpr::Mutable { .. })
906                || type_mentions_any(param_type, &func_info.generics)
907            {
908                if let Some(c) = classifications.get_mut(i) {
909                    *c = None;
910                }
911            }
912        }
913    }
914    let key = (function, classifications.clone());
915
916    if !is_mixed(&classifications) {
917        return None;
918    }
919
920    if let Some(&cached_name) = registry.cache.get(&key) {
921        let dynamic_args: Vec<&'a Expr<'a>> = args
922            .iter()
923            .zip(classifications.iter())
924            .filter(|(_, c)| c.is_none())
925            .map(|(a, _)| *a)
926            .collect();
927        return Some((cached_name, dynamic_args));
928    }
929
930    // Check if this specialization embeds in a previous one (termination guard)
931    if registry
932        .history
933        .iter()
934        .any(|prev| spec_key_embeds(prev, &key))
935    {
936        return None;
937    }
938
939    let count = registry.variant_count.get(&function).copied().unwrap_or(0);
940    if count >= 8 {
941        return None;
942    }
943
944    let func_info = func_defs.get(&function)?;
945
946    // The specialization folds a static argument into the body and drops the parameter.
947    // That is only sound when the callee has no opaque effectful boundary: IO, escape,
948    // a security check, nondeterminism, or concurrency.
949    let safe_to_specialize = if let Some(env) = effect_env {
950        let fn_name = interner.resolve(function);
951        env.function_is_specialization_safe(fn_name)
952    } else {
953        !body_has_io(func_info.body)
954    };
955    if !safe_to_specialize {
956        return None;
957    }
958
959    if body_has_escape(func_info.body) {
960        return None;
961    }
962
963    let spec_name = make_spec_name(interner, func_info.name, &classifications, &|sym| {
964        func_defs.contains_key(&sym) || registry.cache.values().any(|name| *name == sym)
965    });
966
967    let mut substitutions: HashMap<Symbol, &'a Expr<'a>> = HashMap::new();
968    let mut new_params: Vec<(Symbol, &'a TypeExpr<'a>)> = Vec::new();
969
970    for (i, (param_sym, param_type)) in func_info.params.iter().enumerate() {
971        if let Some(Some(lit)) = classifications.get(i) {
972            let lit_expr = expr_arena.alloc(Expr::Literal(lit.clone()));
973            substitutions.insert(*param_sym, lit_expr);
974        } else {
975            new_params.push((*param_sym, *param_type));
976        }
977    }
978
979    let specialized_body = substitute_block(func_info.body, &substitutions, expr_arena, stmt_arena)?;
980
981    let folded = super::fold::fold_stmts(specialized_body, expr_arena, stmt_arena, interner);
982    let optimized = super::dce::eliminate_dead_code(folded, stmt_arena, expr_arena);
983
984    let original_cost = count_stmts(func_info.body) + func_info.params.len();
985    let specialized_cost = count_stmts(&optimized) + new_params.len();
986
987    if specialized_cost as f64 > original_cost as f64 * 0.8 {
988        return None;
989    }
990
991    // Register the specialized function in cache BEFORE cascading to prevent infinite loops
992    registry.history.push(key.clone());
993    registry.cache.insert(key, spec_name);
994    *registry.variant_count.entry(function).or_insert(0) += 1;
995
996    // Cascade: walk specialized body for further specialization candidates
997    let cascaded: Vec<Stmt<'a>> = optimized
998        .into_iter()
999        .map(|s| {
1000            specialize_in_stmt(
1001                s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1002            )
1003        })
1004        .collect();
1005
1006    let new_body = stmt_arena.alloc_slice(cascaded);
1007
1008    let new_func = Stmt::FunctionDef {
1009        name: spec_name,
1010        generics: func_info.generics.clone(),
1011        params: new_params,
1012        body: new_body,
1013        return_type: func_info.return_type,
1014        is_native: false,
1015        native_path: None,
1016        is_exported: false,
1017        export_target: None,
1018        opt_flags: func_info.opt_flags.clone(),
1019    };
1020
1021    registry.new_funcs.push(new_func);
1022
1023    let dynamic_args: Vec<&'a Expr<'a>> = args
1024        .iter()
1025        .zip(classifications.iter())
1026        .filter(|(_, c)| c.is_none())
1027        .map(|(a, _)| *a)
1028        .collect();
1029
1030    Some((spec_name, dynamic_args))
1031}
1032
1033fn specialize_in_expr<'a>(
1034    expr: &'a Expr<'a>,
1035    func_defs: &HashMap<Symbol, FuncInfo<'a>>,
1036    registry: &mut SpecRegistry<'a>,
1037    expr_arena: &'a Arena<Expr<'a>>,
1038    stmt_arena: &'a Arena<Stmt<'a>>,
1039    interner: &mut Interner,
1040    effect_env: Option<&EffectEnv>,
1041) -> &'a Expr<'a> {
1042    match expr {
1043        Expr::Call { function, args } => {
1044            let new_args: Vec<&'a Expr<'a>> = args
1045                .iter()
1046                .map(|a| {
1047                    specialize_in_expr(
1048                        a, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1049                    )
1050                })
1051                .collect();
1052
1053            if let Some((spec_name, dynamic_args)) = try_specialize_call(
1054                *function, &new_args, func_defs, registry, expr_arena, stmt_arena, interner,
1055                effect_env,
1056            ) {
1057                expr_arena.alloc(Expr::Call {
1058                    function: spec_name,
1059                    args: dynamic_args,
1060                })
1061            } else {
1062                let changed = new_args
1063                    .iter()
1064                    .zip(args.iter())
1065                    .any(|(new, old)| !std::ptr::eq(*new as *const _, *old as *const _));
1066                if changed {
1067                    expr_arena.alloc(Expr::Call {
1068                        function: *function,
1069                        args: new_args,
1070                    })
1071                } else {
1072                    expr
1073                }
1074            }
1075        }
1076        Expr::BinaryOp { op, left, right } => {
1077            let new_left = specialize_in_expr(
1078                left, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1079            );
1080            let new_right = specialize_in_expr(
1081                right, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1082            );
1083            if std::ptr::eq(new_left as *const _, *left as *const _)
1084                && std::ptr::eq(new_right as *const _, *right as *const _)
1085            {
1086                expr
1087            } else {
1088                expr_arena.alloc(Expr::BinaryOp {
1089                    op: *op,
1090                    left: new_left,
1091                    right: new_right,
1092                })
1093            }
1094        }
1095        Expr::Not { operand } => {
1096            let new_op = specialize_in_expr(
1097                operand, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1098            );
1099            if std::ptr::eq(new_op as *const _, *operand as *const _) {
1100                expr
1101            } else {
1102                expr_arena.alloc(Expr::Not { operand: new_op })
1103            }
1104        }
1105        _ => expr,
1106    }
1107}
1108
1109fn specialize_in_stmt<'a>(
1110    stmt: Stmt<'a>,
1111    func_defs: &HashMap<Symbol, FuncInfo<'a>>,
1112    registry: &mut SpecRegistry<'a>,
1113    expr_arena: &'a Arena<Expr<'a>>,
1114    stmt_arena: &'a Arena<Stmt<'a>>,
1115    interner: &mut Interner,
1116    effect_env: Option<&EffectEnv>,
1117) -> Stmt<'a> {
1118    match stmt {
1119        Stmt::Let {
1120            var,
1121            value,
1122            mutable,
1123            ty,
1124        } => Stmt::Let {
1125            var,
1126            value: specialize_in_expr(
1127                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1128            ),
1129            mutable,
1130            ty,
1131        },
1132        Stmt::Set { target, value } => Stmt::Set {
1133            target,
1134            value: specialize_in_expr(
1135                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1136            ),
1137        },
1138        Stmt::Return { value } => Stmt::Return {
1139            value: value.map(|v| {
1140                specialize_in_expr(
1141                    v, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1142                )
1143            }),
1144        },
1145        Stmt::Show { object, recipient } => Stmt::Show {
1146            object: specialize_in_expr(
1147                object, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1148            ),
1149            recipient,
1150        },
1151        Stmt::Call { function, args } => {
1152            let new_args: Vec<&'a Expr<'a>> = args
1153                .iter()
1154                .map(|a| {
1155                    specialize_in_expr(
1156                        a, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1157                    )
1158                })
1159                .collect();
1160
1161            if let Some((spec_name, dynamic_args)) = try_specialize_call(
1162                function, &new_args, func_defs, registry, expr_arena, stmt_arena, interner,
1163                effect_env,
1164            ) {
1165                Stmt::Call {
1166                    function: spec_name,
1167                    args: dynamic_args,
1168                }
1169            } else {
1170                Stmt::Call {
1171                    function,
1172                    args: new_args,
1173                }
1174            }
1175        }
1176        Stmt::If {
1177            cond,
1178            then_block,
1179            else_block,
1180        } => {
1181            let new_cond = specialize_in_expr(
1182                cond, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1183            );
1184            let new_then: Vec<Stmt<'a>> = then_block
1185                .iter()
1186                .cloned()
1187                .map(|s| {
1188                    specialize_in_stmt(
1189                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1190                    )
1191                })
1192                .collect();
1193            let new_else = else_block.map(|eb| {
1194                let stmts: Vec<Stmt<'a>> = eb
1195                    .iter()
1196                    .cloned()
1197                    .map(|s| {
1198                        specialize_in_stmt(
1199                            s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1200                        )
1201                    })
1202                    .collect();
1203                stmt_arena.alloc_slice(stmts) as &[Stmt<'a>]
1204            });
1205            Stmt::If {
1206                cond: new_cond,
1207                then_block: stmt_arena.alloc_slice(new_then),
1208                else_block: new_else,
1209            }
1210        }
1211        Stmt::While {
1212            cond,
1213            body,
1214            decreasing,
1215        } => {
1216            let new_cond = specialize_in_expr(
1217                cond, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1218            );
1219            let new_body: Vec<Stmt<'a>> = body
1220                .iter()
1221                .cloned()
1222                .map(|s| {
1223                    specialize_in_stmt(
1224                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1225                    )
1226                })
1227                .collect();
1228            Stmt::While {
1229                cond: new_cond,
1230                body: stmt_arena.alloc_slice(new_body),
1231                decreasing,
1232            }
1233        }
1234        Stmt::Repeat {
1235            pattern,
1236            iterable,
1237            body,
1238        } => {
1239            let new_iter = specialize_in_expr(
1240                iterable, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1241            );
1242            let new_body: Vec<Stmt<'a>> = body
1243                .iter()
1244                .cloned()
1245                .map(|s| {
1246                    specialize_in_stmt(
1247                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1248                    )
1249                })
1250                .collect();
1251            Stmt::Repeat {
1252                pattern,
1253                iterable: new_iter,
1254                body: stmt_arena.alloc_slice(new_body),
1255            }
1256        }
1257        Stmt::SetIndex {
1258            collection,
1259            index,
1260            value,
1261        } => Stmt::SetIndex {
1262            collection: specialize_in_expr(
1263                collection, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1264            ),
1265            index: specialize_in_expr(
1266                index, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1267            ),
1268            value: specialize_in_expr(
1269                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1270            ),
1271        },
1272        Stmt::Push { value, collection } => Stmt::Push {
1273            value: specialize_in_expr(
1274                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1275            ),
1276            collection: specialize_in_expr(
1277                collection, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1278            ),
1279        },
1280        Stmt::SetField {
1281            object,
1282            field,
1283            value,
1284        } => Stmt::SetField {
1285            object: specialize_in_expr(
1286                object, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1287            ),
1288            field,
1289            value: specialize_in_expr(
1290                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1291            ),
1292        },
1293        Stmt::Give { object, recipient } => Stmt::Give {
1294            object: specialize_in_expr(
1295                object, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1296            ),
1297            recipient: specialize_in_expr(
1298                recipient, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1299            ),
1300        },
1301        Stmt::Add { value, collection } => Stmt::Add {
1302            value: specialize_in_expr(
1303                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1304            ),
1305            collection: specialize_in_expr(
1306                collection, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1307            ),
1308        },
1309        Stmt::Remove { value, collection } => Stmt::Remove {
1310            value: specialize_in_expr(
1311                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1312            ),
1313            collection: specialize_in_expr(
1314                collection, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1315            ),
1316        },
1317        Stmt::Inspect {
1318            target,
1319            arms,
1320            has_otherwise,
1321        } => {
1322            let new_target = specialize_in_expr(
1323                target, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1324            );
1325            let new_arms: Vec<_> = arms
1326                .into_iter()
1327                .map(|arm| {
1328                    let new_body: Vec<Stmt<'a>> = arm
1329                        .body
1330                        .iter()
1331                        .cloned()
1332                        .map(|s| {
1333                            specialize_in_stmt(
1334                                s, func_defs, registry, expr_arena, stmt_arena, interner,
1335                                effect_env,
1336                            )
1337                        })
1338                        .collect();
1339                    crate::ast::stmt::MatchArm {
1340                        enum_name: arm.enum_name,
1341                        variant: arm.variant,
1342                        bindings: arm.bindings,
1343                        body: stmt_arena.alloc_slice(new_body),
1344                    }
1345                })
1346                .collect();
1347            Stmt::Inspect {
1348                target: new_target,
1349                arms: new_arms,
1350                has_otherwise,
1351            }
1352        }
1353        Stmt::RuntimeAssert {
1354            condition,
1355            hard,
1356            dim,
1357            reason,
1358        } => Stmt::RuntimeAssert {
1359            condition: specialize_in_expr(
1360                condition, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1361            ),
1362            hard,
1363            dim,
1364            reason: reason.map(|r| {
1365                specialize_in_expr(
1366                    r, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1367                )
1368            }),
1369        },
1370        Stmt::FunctionDef {
1371            name,
1372            params,
1373            generics,
1374            body,
1375            return_type,
1376            is_native,
1377            native_path,
1378            is_exported,
1379            export_target,
1380            opt_flags,
1381        } => {
1382            if is_native {
1383                return Stmt::FunctionDef {
1384                    name,
1385                    params,
1386                    generics,
1387                    body,
1388                    return_type,
1389                    is_native,
1390                    native_path,
1391                    is_exported,
1392                    export_target,
1393                    opt_flags,
1394                };
1395            }
1396            let new_body: Vec<Stmt<'a>> = body
1397                .iter()
1398                .cloned()
1399                .map(|s| {
1400                    specialize_in_stmt(
1401                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1402                    )
1403                })
1404                .collect();
1405            Stmt::FunctionDef {
1406                name,
1407                params,
1408                generics,
1409                body: stmt_arena.alloc_slice(new_body),
1410                return_type,
1411                is_native,
1412                native_path,
1413                is_exported,
1414                export_target,
1415                opt_flags,
1416            }
1417        }
1418        // ---- Deep specialization across concurrency boundaries ----
1419        // Descend into Concurrent/Parallel/Zone/Select bodies and the expression
1420        // arguments of the Go-like concurrency statements to specialize the pure calls
1421        // within. Each statement is rebuilt as the SAME variant in the SAME order — the
1422        // boundary is never folded across, and no effect is reordered or duplicated.
1423        Stmt::Concurrent { tasks } => {
1424            let new_tasks: Vec<Stmt<'a>> = tasks
1425                .iter()
1426                .cloned()
1427                .map(|s| {
1428                    specialize_in_stmt(
1429                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1430                    )
1431                })
1432                .collect();
1433            Stmt::Concurrent {
1434                tasks: stmt_arena.alloc_slice(new_tasks),
1435            }
1436        }
1437        Stmt::Parallel { tasks } => {
1438            let new_tasks: Vec<Stmt<'a>> = tasks
1439                .iter()
1440                .cloned()
1441                .map(|s| {
1442                    specialize_in_stmt(
1443                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1444                    )
1445                })
1446                .collect();
1447            Stmt::Parallel {
1448                tasks: stmt_arena.alloc_slice(new_tasks),
1449            }
1450        }
1451        Stmt::Zone {
1452            name,
1453            capacity,
1454            source_file,
1455            body,
1456        } => {
1457            let new_body: Vec<Stmt<'a>> = body
1458                .iter()
1459                .cloned()
1460                .map(|s| {
1461                    specialize_in_stmt(
1462                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1463                    )
1464                })
1465                .collect();
1466            Stmt::Zone {
1467                name,
1468                capacity,
1469                source_file,
1470                body: stmt_arena.alloc_slice(new_body),
1471            }
1472        }
1473        Stmt::Reversibly { body } => {
1474            let new_body: Vec<Stmt<'a>> = body
1475                .iter()
1476                .cloned()
1477                .map(|s| {
1478                    specialize_in_stmt(
1479                        s, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1480                    )
1481                })
1482                .collect();
1483            Stmt::Reversibly {
1484                body: stmt_arena.alloc_slice(new_body),
1485            }
1486        }
1487        Stmt::Select { branches } => {
1488            let new_branches: Vec<crate::ast::stmt::SelectBranch<'a>> = branches
1489                .into_iter()
1490                .map(|b| match b {
1491                    crate::ast::stmt::SelectBranch::Receive { var, pipe, body } => {
1492                        let new_body: Vec<Stmt<'a>> = body
1493                            .iter()
1494                            .cloned()
1495                            .map(|s| {
1496                                specialize_in_stmt(
1497                                    s, func_defs, registry, expr_arena, stmt_arena, interner,
1498                                    effect_env,
1499                                )
1500                            })
1501                            .collect();
1502                        crate::ast::stmt::SelectBranch::Receive {
1503                            var,
1504                            pipe: specialize_in_expr(
1505                                pipe, func_defs, registry, expr_arena, stmt_arena, interner,
1506                                effect_env,
1507                            ),
1508                            body: stmt_arena.alloc_slice(new_body),
1509                        }
1510                    }
1511                    crate::ast::stmt::SelectBranch::Timeout { milliseconds, body } => {
1512                        let new_body: Vec<Stmt<'a>> = body
1513                            .iter()
1514                            .cloned()
1515                            .map(|s| {
1516                                specialize_in_stmt(
1517                                    s, func_defs, registry, expr_arena, stmt_arena, interner,
1518                                    effect_env,
1519                                )
1520                            })
1521                            .collect();
1522                        crate::ast::stmt::SelectBranch::Timeout {
1523                            milliseconds: specialize_in_expr(
1524                                milliseconds,
1525                                func_defs,
1526                                registry,
1527                                expr_arena,
1528                                stmt_arena,
1529                                interner,
1530                                effect_env,
1531                            ),
1532                            body: stmt_arena.alloc_slice(new_body),
1533                        }
1534                    }
1535                })
1536                .collect();
1537            Stmt::Select {
1538                branches: new_branches,
1539            }
1540        }
1541        Stmt::SendPipe { value, pipe } => Stmt::SendPipe {
1542            value: specialize_in_expr(
1543                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1544            ),
1545            pipe: specialize_in_expr(
1546                pipe, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1547            ),
1548        },
1549        Stmt::TrySendPipe {
1550            value,
1551            pipe,
1552            result,
1553        } => Stmt::TrySendPipe {
1554            value: specialize_in_expr(
1555                value, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1556            ),
1557            pipe: specialize_in_expr(
1558                pipe, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1559            ),
1560            result,
1561        },
1562        Stmt::ReceivePipe { var, pipe } => Stmt::ReceivePipe {
1563            var,
1564            pipe: specialize_in_expr(
1565                pipe, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1566            ),
1567        },
1568        Stmt::TryReceivePipe { var, pipe } => Stmt::TryReceivePipe {
1569            var,
1570            pipe: specialize_in_expr(
1571                pipe, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1572            ),
1573        },
1574        Stmt::LaunchTask { function, args } => Stmt::LaunchTask {
1575            function,
1576            args: args
1577                .iter()
1578                .map(|a| {
1579                    specialize_in_expr(
1580                        a, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1581                    )
1582                })
1583                .collect(),
1584        },
1585        Stmt::LaunchTaskWithHandle {
1586            handle,
1587            function,
1588            args,
1589        } => Stmt::LaunchTaskWithHandle {
1590            handle,
1591            function,
1592            args: args
1593                .iter()
1594                .map(|a| {
1595                    specialize_in_expr(
1596                        a, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1597                    )
1598                })
1599                .collect(),
1600        },
1601        Stmt::StopTask { handle } => Stmt::StopTask {
1602            handle: specialize_in_expr(
1603                handle, func_defs, registry, expr_arena, stmt_arena, interner, effect_env,
1604            ),
1605        },
1606        other => other,
1607    }
1608}
1609
1610pub fn specialize_stmts<'a>(
1611    stmts: Vec<Stmt<'a>>,
1612    expr_arena: &'a Arena<Expr<'a>>,
1613    stmt_arena: &'a Arena<Stmt<'a>>,
1614    interner: &mut Interner,
1615) -> (Vec<Stmt<'a>>, usize) {
1616    let mut variant_count = HashMap::new();
1617    specialize_stmts_with_state(
1618        stmts,
1619        expr_arena,
1620        stmt_arena,
1621        interner,
1622        &mut variant_count,
1623        None,
1624    )
1625}
1626
1627pub fn specialize_stmts_with_state<'a>(
1628    stmts: Vec<Stmt<'a>>,
1629    expr_arena: &'a Arena<Expr<'a>>,
1630    stmt_arena: &'a Arena<Stmt<'a>>,
1631    interner: &mut Interner,
1632    persistent_variant_count: &mut HashMap<Symbol, usize>,
1633    bta_cache: Option<&super::bta::BtaCache>,
1634) -> (Vec<Stmt<'a>>, usize) {
1635    let effect_env = EffectEnv::from_stmts(&stmts, interner);
1636    let func_defs = collect_func_defs(&stmts);
1637    let mut registry = SpecRegistry::new();
1638    registry.variant_count = persistent_variant_count.clone();
1639    if let Some(cache) = bta_cache {
1640        registry.bta_cache = Some(cache.clone());
1641    }
1642
1643    let specialized: Vec<Stmt<'a>> = stmts
1644        .into_iter()
1645        .map(|stmt| {
1646            specialize_in_stmt(
1647                stmt,
1648                &func_defs,
1649                &mut registry,
1650                expr_arena,
1651                stmt_arena,
1652                interner,
1653                Some(&effect_env),
1654            )
1655        })
1656        .collect();
1657
1658    let changes = registry.new_funcs.len();
1659    *persistent_variant_count = registry.variant_count;
1660    let mut result = registry.new_funcs;
1661    result.extend(specialized);
1662    // The next propagation round must recognize loans to newly created callees.
1663    crate::analysis::callgraph::install_lending_parameters(&result);
1664    (result, changes)
1665}
1666
1667/// Remove identity bindings and trivial patterns from residual code.
1668///
1669/// - `Let x = x` → removed
1670/// - `Let x = lit; Return x` → `Return lit`
1671/// - Single-arm `Inspect` with Otherwise only → inline the body
1672/// - Iterates to fixpoint (max 4 passes)
1673pub fn cleanup_identities<'a>(
1674    stmts: Vec<Stmt<'a>>,
1675    expr_arena: &'a Arena<Expr<'a>>,
1676    stmt_arena: &'a Arena<Stmt<'a>>,
1677) -> Vec<Stmt<'a>> {
1678    let mut current = stmts;
1679    for _ in 0..4 {
1680        let next = cleanup_pass(&current, expr_arena, stmt_arena);
1681        if next.len() == current.len() {
1682            // Quick structural check for fixpoint
1683            let mut same = true;
1684            for (a, b) in next.iter().zip(current.iter()) {
1685                if !stmt_structurally_equal(a, b) {
1686                    same = false;
1687                    break;
1688                }
1689            }
1690            if same {
1691                return next;
1692            }
1693        }
1694        current = next;
1695    }
1696    current
1697}
1698
1699fn cleanup_pass<'a>(
1700    stmts: &[Stmt<'a>],
1701    expr_arena: &'a Arena<Expr<'a>>,
1702    stmt_arena: &'a Arena<Stmt<'a>>,
1703) -> Vec<Stmt<'a>> {
1704    let mut result = Vec::with_capacity(stmts.len());
1705
1706    for (i, stmt) in stmts.iter().enumerate() {
1707        match stmt {
1708            // Remove Let x = x (identity binding)
1709            Stmt::Let {
1710                var,
1711                value: Expr::Identifier(src),
1712                ..
1713            } if var == src => {
1714                continue;
1715            }
1716            // Collapse Let x = lit; Return x → Return lit
1717            Stmt::Let {
1718                var,
1719                value,
1720                mutable: false,
1721                ..
1722            } => {
1723                if let Some(Stmt::Return {
1724                    value: Some(Expr::Identifier(ret_var)),
1725                }) = stmts.get(i + 1)
1726                {
1727                    if var == ret_var {
1728                        if let Expr::Literal(_) = value {
1729                            result.push(Stmt::Return { value: Some(value) });
1730                            // Skip the next Return statement too — handled below
1731                            continue;
1732                        }
1733                    }
1734                }
1735                // Recurse into sub-blocks
1736                result.push(cleanup_stmt(stmt, expr_arena, stmt_arena));
1737            }
1738            // Skip Return that was already folded into a Let
1739            Stmt::Return {
1740                value: Some(Expr::Identifier(ret_var)),
1741            } => {
1742                if i > 0 {
1743                    if let Stmt::Let {
1744                        var,
1745                        value: Expr::Literal(_),
1746                        mutable: false,
1747                        ..
1748                    } = &stmts[i - 1]
1749                    {
1750                        if var == ret_var {
1751                            continue;
1752                        }
1753                    }
1754                }
1755                result.push(cleanup_stmt(stmt, expr_arena, stmt_arena));
1756            }
1757            // Single-arm Inspect with only Otherwise → inline body
1758            Stmt::Inspect {
1759                arms,
1760                has_otherwise: true,
1761                ..
1762            } if arms.len() == 1 => {
1763                let arm = &arms[0];
1764                if arm.variant.is_none() {
1765                    // Otherwise-only: inline body
1766                    for s in arm.body {
1767                        result.push(cleanup_stmt(s, expr_arena, stmt_arena));
1768                    }
1769                    continue;
1770                }
1771                result.push(cleanup_stmt(stmt, expr_arena, stmt_arena));
1772            }
1773            _ => {
1774                result.push(cleanup_stmt(stmt, expr_arena, stmt_arena));
1775            }
1776        }
1777    }
1778
1779    result
1780}
1781
1782fn cleanup_stmt<'a>(
1783    stmt: &Stmt<'a>,
1784    expr_arena: &'a Arena<Expr<'a>>,
1785    stmt_arena: &'a Arena<Stmt<'a>>,
1786) -> Stmt<'a> {
1787    match stmt {
1788        Stmt::If {
1789            cond,
1790            then_block,
1791            else_block,
1792        } => {
1793            let new_then = cleanup_pass(then_block, expr_arena, stmt_arena);
1794            let new_else = else_block.map(|eb| {
1795                let cleaned = cleanup_pass(eb, expr_arena, stmt_arena);
1796                stmt_arena.alloc_slice(cleaned) as &[Stmt<'a>]
1797            });
1798            Stmt::If {
1799                cond,
1800                then_block: stmt_arena.alloc_slice(new_then),
1801                else_block: new_else,
1802            }
1803        }
1804        Stmt::While {
1805            cond,
1806            body,
1807            decreasing,
1808        } => {
1809            let new_body = cleanup_pass(body, expr_arena, stmt_arena);
1810            Stmt::While {
1811                cond,
1812                body: stmt_arena.alloc_slice(new_body),
1813                decreasing: *decreasing,
1814            }
1815        }
1816        Stmt::FunctionDef {
1817            name,
1818            params,
1819            generics,
1820            body,
1821            return_type,
1822            is_native,
1823            native_path,
1824            is_exported,
1825            export_target,
1826            opt_flags,
1827        } => {
1828            if *is_native {
1829                return stmt.clone();
1830            }
1831            let new_body = cleanup_pass(body, expr_arena, stmt_arena);
1832            Stmt::FunctionDef {
1833                name: *name,
1834                params: params.clone(),
1835                generics: generics.clone(),
1836                body: stmt_arena.alloc_slice(new_body),
1837                return_type: *return_type,
1838                is_native: *is_native,
1839                native_path: *native_path,
1840                is_exported: *is_exported,
1841                export_target: *export_target,
1842                opt_flags: opt_flags.clone(),
1843            }
1844        }
1845        Stmt::Repeat {
1846            pattern,
1847            iterable,
1848            body,
1849        } => {
1850            let new_body = cleanup_pass(body, expr_arena, stmt_arena);
1851            Stmt::Repeat {
1852                pattern: pattern.clone(),
1853                iterable,
1854                body: stmt_arena.alloc_slice(new_body),
1855            }
1856        }
1857        other => other.clone(),
1858    }
1859}
1860
1861fn stmt_structurally_equal(a: &Stmt, b: &Stmt) -> bool {
1862    std::mem::discriminant(a) == std::mem::discriminant(b)
1863}