Skip to main content

logicaffeine_compile/optimize/
bta.rs

1//! Binding-Time Analysis (BTA)
2//!
3//! Classifies every variable and expression as Static (S) — value known at compile
4//! time — or Dynamic (D) — value depends on runtime input. This classification
5//! drives function specialization in the partial evaluator.
6//!
7//! BTA is polyvariant: the same function analyzed at different call sites with
8//! different argument divisions produces different results.
9
10use std::collections::{HashMap, HashSet};
11use std::hash::{Hash, Hasher};
12
13use super::writes::{CalleeGlobals, WriteSet};
14use crate::analysis::DiscoveryPass;
15use crate::arena::Arena;
16use crate::arena_ctx::AstContext;
17use crate::ast::stmt::{BinaryOpKind, Block, Expr, Literal, Stmt, TypeExpr};
18use crate::drs::WorldState;
19use crate::error::ParseError;
20use crate::intern::{Interner, Symbol};
21use crate::lexer::Lexer;
22use crate::parser::Parser;
23
24// =============================================================================
25// Core Types
26// =============================================================================
27
28#[derive(Debug, Clone)]
29pub enum BindingTime {
30    Static(Literal),
31    Dynamic,
32}
33
34impl PartialEq for BindingTime {
35    fn eq(&self, other: &Self) -> bool {
36        match (self, other) {
37            (BindingTime::Static(a), BindingTime::Static(b)) => match (a, b) {
38                (Literal::Float(x), Literal::Float(y)) => x.to_bits() == y.to_bits(),
39                _ => a == b,
40            },
41            (BindingTime::Dynamic, BindingTime::Dynamic) => true,
42            _ => false,
43        }
44    }
45}
46
47impl Eq for BindingTime {}
48
49impl Hash for BindingTime {
50    fn hash<H: Hasher>(&self, state: &mut H) {
51        std::mem::discriminant(self).hash(state);
52        match self {
53            BindingTime::Static(lit) => hash_literal(lit, state),
54            BindingTime::Dynamic => {}
55        }
56    }
57}
58
59fn hash_literal<H: Hasher>(lit: &Literal, state: &mut H) {
60    std::mem::discriminant(lit).hash(state);
61    match lit {
62        Literal::Number(n) => n.hash(state),
63        Literal::Float(f) => f.to_bits().hash(state),
64        Literal::Text(s) => s.hash(state),
65        Literal::Boolean(b) => b.hash(state),
66        Literal::Nothing => {}
67        Literal::Char(c) => c.hash(state),
68        Literal::Duration(d) => d.hash(state),
69        Literal::Date(d) => d.hash(state),
70        Literal::Moment(m) => m.hash(state),
71        Literal::Span { months, days } => {
72            months.hash(state);
73            days.hash(state);
74        }
75        Literal::Time(t) => t.hash(state),
76    }
77}
78
79impl BindingTime {
80    pub fn is_static(&self) -> bool {
81        matches!(self, BindingTime::Static(_))
82    }
83
84    pub fn is_dynamic(&self) -> bool {
85        matches!(self, BindingTime::Dynamic)
86    }
87}
88
89pub type Division = HashMap<Symbol, BindingTime>;
90
91#[derive(Debug, Clone, PartialEq)]
92pub struct BtaResult {
93    pub division: Division,
94    pub return_bt: BindingTime,
95}
96
97pub type BtaCache = HashMap<(Symbol, Vec<BindingTime>), BtaResult>;
98
99// =============================================================================
100// Expression Analysis
101// =============================================================================
102
103pub fn analyze_expr(expr: &Expr, division: &Division) -> BindingTime {
104    match expr {
105        Expr::Literal(lit) => BindingTime::Static(lit.clone()),
106
107        Expr::Identifier(sym) => division.get(sym).cloned().unwrap_or(BindingTime::Dynamic),
108
109        Expr::BinaryOp { op, left, right } => {
110            let bt_left = analyze_expr(left, division);
111            let bt_right = analyze_expr(right, division);
112            match (&bt_left, &bt_right) {
113                (BindingTime::Static(l), BindingTime::Static(r)) => {
114                    match eval_literal_binop(*op, l, r) {
115                        Some(result) => BindingTime::Static(result),
116                        None => BindingTime::Dynamic,
117                    }
118                }
119                _ => BindingTime::Dynamic,
120            }
121        }
122
123        Expr::Not { operand } => match analyze_expr(operand, division) {
124            BindingTime::Static(Literal::Boolean(b)) => BindingTime::Static(Literal::Boolean(!b)),
125            _ => BindingTime::Dynamic,
126        },
127
128        Expr::Length { .. } => BindingTime::Dynamic,
129        Expr::Index { .. } => BindingTime::Dynamic,
130
131        Expr::Call { .. } => BindingTime::Dynamic,
132
133        _ => BindingTime::Dynamic,
134    }
135}
136
137fn eval_literal_binop(op: BinaryOpKind, left: &Literal, right: &Literal) -> Option<Literal> {
138    match (op, left, right) {
139        // Fold only when it fits i64; overflow → None so the exact runtime promotes.
140        (BinaryOpKind::Add, Literal::Number(a), Literal::Number(b)) => {
141            a.checked_add(*b).map(Literal::Number)
142        }
143        (BinaryOpKind::Subtract, Literal::Number(a), Literal::Number(b)) => {
144            a.checked_sub(*b).map(Literal::Number)
145        }
146        (BinaryOpKind::Multiply, Literal::Number(a), Literal::Number(b)) => {
147            a.checked_mul(*b).map(Literal::Number)
148        }
149        (BinaryOpKind::Divide, Literal::Number(a), Literal::Number(b)) if *b != 0 => {
150            a.checked_div(*b).map(Literal::Number)
151        }
152        (BinaryOpKind::Modulo, Literal::Number(a), Literal::Number(b)) if *b != 0 => {
153            a.checked_rem(*b).map(Literal::Number)
154        }
155        (BinaryOpKind::Eq, Literal::Number(a), Literal::Number(b)) => {
156            Some(Literal::Boolean(a == b))
157        }
158        (BinaryOpKind::NotEq, Literal::Number(a), Literal::Number(b)) => {
159            Some(Literal::Boolean(a != b))
160        }
161        (BinaryOpKind::Lt, Literal::Number(a), Literal::Number(b)) => Some(Literal::Boolean(a < b)),
162        (BinaryOpKind::Gt, Literal::Number(a), Literal::Number(b)) => Some(Literal::Boolean(a > b)),
163        (BinaryOpKind::LtEq, Literal::Number(a), Literal::Number(b)) => {
164            Some(Literal::Boolean(a <= b))
165        }
166        (BinaryOpKind::GtEq, Literal::Number(a), Literal::Number(b)) => {
167            Some(Literal::Boolean(a >= b))
168        }
169        (BinaryOpKind::Add, Literal::Float(a), Literal::Float(b)) => Some(Literal::Float(a + b)),
170        (BinaryOpKind::Subtract, Literal::Float(a), Literal::Float(b)) => {
171            Some(Literal::Float(a - b))
172        }
173        (BinaryOpKind::Multiply, Literal::Float(a), Literal::Float(b)) => {
174            Some(Literal::Float(a * b))
175        }
176        (BinaryOpKind::Divide, Literal::Float(a), Literal::Float(b)) if *b != 0.0 => {
177            Some(Literal::Float(a / b))
178        }
179        (BinaryOpKind::And, Literal::Boolean(a), Literal::Boolean(b)) => {
180            Some(Literal::Boolean(*a && *b))
181        }
182        (BinaryOpKind::Or, Literal::Boolean(a), Literal::Boolean(b)) => {
183            Some(Literal::Boolean(*a || *b))
184        }
185        _ => None,
186    }
187}
188
189// =============================================================================
190// Statement / Block Analysis
191// =============================================================================
192
193/// Every global a call may assign becomes Dynamic — every binding does, if some callee holds raw
194/// foreign code.
195fn clobber_callee_globals(division: &mut Division, globals: &CalleeGlobals) {
196    if globals.opaque {
197        for bt in division.values_mut() {
198            *bt = BindingTime::Dynamic;
199        }
200        return;
201    }
202    for g in &globals.symbols {
203        division.insert(*g, BindingTime::Dynamic);
204    }
205}
206
207/// Evaluating `expr` may run a call: the callee-written globals are no longer static afterwards.
208fn clobber_call_effects(expr: &Expr, division: &mut Division, globals: &CalleeGlobals) {
209    if WriteSet::of_expr(expr).has_calls() {
210        clobber_callee_globals(division, globals);
211    }
212}
213
214fn analyze_block<'a>(
215    stmts: &[Stmt<'a>],
216    division: &mut Division,
217    globals: &CalleeGlobals,
218) -> BindingTime {
219    let mut return_bt = BindingTime::Dynamic;
220    for stmt in stmts {
221        if let Some(bt) = analyze_stmt(stmt, division, globals) {
222            return_bt = bt;
223        }
224    }
225    return_bt
226}
227
228fn analyze_stmt<'a>(
229    stmt: &Stmt<'a>,
230    division: &mut Division,
231    globals: &CalleeGlobals,
232) -> Option<BindingTime> {
233    match stmt {
234        Stmt::Let { var, value, .. } => {
235            clobber_call_effects(value, division, globals);
236            let bt = analyze_expr(value, division);
237            division.insert(*var, bt);
238            None
239        }
240        Stmt::Set { target, value } => {
241            clobber_call_effects(value, division, globals);
242            let bt = analyze_expr(value, division);
243            division.insert(*target, bt);
244            None
245        }
246        Stmt::Return { value } => {
247            let bt = match value {
248                Some(expr) => {
249                    clobber_call_effects(expr, division, globals);
250                    analyze_expr(expr, division)
251                }
252                None => BindingTime::Static(Literal::Nothing),
253            };
254            Some(bt)
255        }
256        Stmt::Show { object, .. } => {
257            clobber_call_effects(object, division, globals);
258            None
259        }
260        Stmt::Call { args, .. } => {
261            for arg in args {
262                analyze_expr(arg, division);
263            }
264            clobber_callee_globals(division, globals);
265            None
266        }
267        other => {
268            // Every name the statement may write — a variable rebound from a runtime source (channel
269            // receive, Mount, console read, peer message, …), a `Swap`, a nested block's `Set`, a
270            // global its calls reach — is Dynamic regardless of any prior static binding.
271            let effects = WriteSet::of_stmt(other).with_callee_globals(globals);
272            if effects.is_opaque() {
273                clobber_callee_globals(
274                    division,
275                    &CalleeGlobals {
276                        symbols: HashSet::new(),
277                        opaque: true,
278                    },
279                );
280            } else {
281                for var in effects.symbols() {
282                    division.insert(var, BindingTime::Dynamic);
283                }
284            }
285            None
286        }
287    }
288}
289
290// =============================================================================
291// Function Definition Storage
292// =============================================================================
293
294struct FuncDef<'a> {
295    params: Vec<(Symbol, &'a TypeExpr<'a>)>,
296    body: Block<'a>,
297}
298
299pub fn analyze_function_bt<'a>(
300    func_name: Symbol,
301    params: &[(Symbol, &'a TypeExpr<'a>)],
302    body: &[Stmt<'a>],
303    arg_bts: &[BindingTime],
304    cache: &mut BtaCache,
305    globals: &CalleeGlobals,
306) -> BtaResult {
307    let cache_key = (func_name, arg_bts.to_vec());
308    if let Some(cached) = cache.get(&cache_key) {
309        return cached.clone();
310    }
311
312    let mut division = Division::new();
313    for (i, (param_sym, _)) in params.iter().enumerate() {
314        if let Some(bt) = arg_bts.get(i) {
315            division.insert(*param_sym, bt.clone());
316        } else {
317            division.insert(*param_sym, BindingTime::Dynamic);
318        }
319    }
320
321    let return_bt = analyze_block(body, &mut division, globals);
322
323    let result = BtaResult {
324        division,
325        return_bt,
326    };
327    cache.insert(cache_key, result.clone());
328    result
329}
330
331// =============================================================================
332// SCC-Ordered Analysis
333// =============================================================================
334
335pub fn analyze_with_sccs<'a>(stmts: &[Stmt<'a>], interner: &Interner) -> BtaCache {
336    use crate::analysis::callgraph::CallGraph;
337
338    let cg = CallGraph::build(stmts, interner);
339
340    let mut funcs: HashMap<Symbol, FuncDef<'a>> = HashMap::new();
341    for stmt in stmts {
342        if let Stmt::FunctionDef {
343            name,
344            params,
345            body,
346            is_native: false,
347            ..
348        } = stmt
349        {
350            funcs.insert(
351                *name,
352                FuncDef {
353                    params: params.clone(),
354                    body,
355                },
356            );
357        }
358    }
359
360    let mut cache = BtaCache::new();
361    let globals = CalleeGlobals::of_program(stmts);
362
363    // Process SCCs in topological order (sccs are already in reverse topo order from Kosaraju)
364    for scc in cg.sccs.iter().rev() {
365        if scc.len() == 1 {
366            // Non-recursive (or self-recursive): analyze once
367            let sym = scc[0];
368            if let Some(func_def) = funcs.get(&sym) {
369                let arg_bts: Vec<BindingTime> = func_def
370                    .params
371                    .iter()
372                    .map(|_| BindingTime::Dynamic)
373                    .collect();
374                analyze_function_bt(
375                    sym,
376                    &func_def.params,
377                    func_def.body,
378                    &arg_bts,
379                    &mut cache,
380                    &globals,
381                );
382            }
383        } else {
384            // Mutually recursive SCC: iterate to fixed point
385            for _iteration in 0..10 {
386                let mut changed = false;
387                for &sym in scc {
388                    if let Some(func_def) = funcs.get(&sym) {
389                        let arg_bts: Vec<BindingTime> = func_def
390                            .params
391                            .iter()
392                            .map(|_| BindingTime::Dynamic)
393                            .collect();
394                        let key = (sym, arg_bts.clone());
395                        let old = cache.get(&key).cloned();
396                        let result = analyze_function_bt(
397                            sym,
398                            &func_def.params,
399                            func_def.body,
400                            &arg_bts,
401                            &mut cache,
402                            &globals,
403                        );
404                        if old.as_ref() != Some(&result) {
405                            changed = true;
406                        }
407                    }
408                }
409                if !changed {
410                    break;
411                }
412            }
413        }
414    }
415
416    cache
417}
418
419// =============================================================================
420// Test-Friendly Wrapper
421// =============================================================================
422
423pub struct BtaEnv {
424    interner: Interner,
425    main_stmts: Vec<BtaStmt>,
426    functions: Vec<BtaFunc>,
427    callee_globals: CalleeGlobals,
428}
429
430#[derive(Clone)]
431struct BtaStmt {
432    kind: BtaStmtKind,
433}
434
435#[derive(Clone)]
436enum BtaStmtKind {
437    Let {
438        var: Symbol,
439        value: BtaExpr,
440    },
441    Set {
442        target: Symbol,
443        value: BtaExpr,
444    },
445    Return {
446        value: Option<BtaExpr>,
447    },
448    Show,
449    Call {
450        args: Vec<BtaExpr>,
451    },
452    If {
453        cond: BtaExpr,
454        then_block: Vec<BtaStmt>,
455        else_block: Option<Vec<BtaStmt>>,
456    },
457    While {
458        cond: BtaExpr,
459        body: Vec<BtaStmt>,
460    },
461    /// A statement that binds one or more variables to a *runtime* value (a channel
462    /// receive, Mount, console read, peer message, …). Each named variable becomes
463    /// Dynamic, overwriting any prior static binding.
464    ClobberDynamic {
465        vars: Vec<Symbol>,
466    },
467    /// Raw foreign code ran: every binding is Dynamic afterwards.
468    ClobberAll,
469    Other,
470}
471
472#[derive(Clone)]
473enum BtaExpr {
474    Literal(Literal),
475    Identifier(Symbol),
476    BinaryOp {
477        op: BinaryOpKind,
478        left: Box<BtaExpr>,
479        right: Box<BtaExpr>,
480    },
481    Not {
482        operand: Box<BtaExpr>,
483    },
484    Length {
485        collection: Box<BtaExpr>,
486    },
487    Index {
488        collection: Box<BtaExpr>,
489        index: Box<BtaExpr>,
490    },
491    Call {
492        function: Symbol,
493        args: Vec<BtaExpr>,
494    },
495    /// An expression this analysis does not model that runs a call (a closure call, a call nested
496    /// in a constructor, …): Dynamic, and its callee may have written the program's globals.
497    OtherCall,
498    Other,
499}
500
501impl BtaExpr {
502    fn has_call(&self) -> bool {
503        match self {
504            BtaExpr::Call { .. } | BtaExpr::OtherCall => true,
505            BtaExpr::Literal(_) | BtaExpr::Identifier(_) => false,
506            BtaExpr::BinaryOp { left, right, .. } => left.has_call() || right.has_call(),
507            BtaExpr::Not { operand } => operand.has_call(),
508            BtaExpr::Length { collection } => collection.has_call(),
509            BtaExpr::Index { collection, index } => collection.has_call() || index.has_call(),
510            BtaExpr::Other => false,
511        }
512    }
513}
514
515#[derive(Clone)]
516struct BtaFunc {
517    name: Symbol,
518    params: Vec<(Symbol, bool)>, // (name, is_collection_type)
519    body: Vec<BtaStmt>,
520}
521
522struct BtaContext {
523    cache: BtaCache,
524    on_stack: HashSet<(Symbol, Vec<BindingTime>)>,
525    callee_globals: CalleeGlobals,
526}
527
528fn convert_expr(expr: &Expr) -> BtaExpr {
529    match expr {
530        Expr::Literal(lit) => BtaExpr::Literal(lit.clone()),
531        Expr::Identifier(sym) => BtaExpr::Identifier(*sym),
532        Expr::BinaryOp { op, left, right } => BtaExpr::BinaryOp {
533            op: *op,
534            left: Box::new(convert_expr(left)),
535            right: Box::new(convert_expr(right)),
536        },
537        Expr::Not { operand } => BtaExpr::Not {
538            operand: Box::new(convert_expr(operand)),
539        },
540        Expr::Length { collection } => BtaExpr::Length {
541            collection: Box::new(convert_expr(collection)),
542        },
543        Expr::Index { collection, index } => BtaExpr::Index {
544            collection: Box::new(convert_expr(collection)),
545            index: Box::new(convert_expr(index)),
546        },
547        Expr::Call { function, args } => BtaExpr::Call {
548            function: *function,
549            args: args.iter().map(|a| convert_expr(a)).collect(),
550        },
551        _ => {
552            if WriteSet::of_expr(expr).has_calls() {
553                BtaExpr::OtherCall
554            } else {
555                BtaExpr::Other
556            }
557        }
558    }
559}
560
561fn convert_stmt(stmt: &Stmt, globals: &CalleeGlobals) -> BtaStmt {
562    let kind = match stmt {
563        Stmt::Let { var, value, .. } => BtaStmtKind::Let {
564            var: *var,
565            value: convert_expr(value),
566        },
567        Stmt::Set { target, value } => BtaStmtKind::Set {
568            target: *target,
569            value: convert_expr(value),
570        },
571        Stmt::Return { value } => BtaStmtKind::Return {
572            value: value.map(|v| convert_expr(v)),
573        },
574        Stmt::Call { args, .. } => BtaStmtKind::Call {
575            args: args.iter().map(|a| convert_expr(a)).collect(),
576        },
577        Stmt::If {
578            cond,
579            then_block,
580            else_block,
581        } => BtaStmtKind::If {
582            cond: convert_expr(cond),
583            then_block: then_block
584                .iter()
585                .map(|s| convert_stmt(s, globals))
586                .collect(),
587            else_block: else_block.map(|eb| eb.iter().map(|s| convert_stmt(s, globals)).collect()),
588        },
589        Stmt::While { cond, body, .. } => BtaStmtKind::While {
590            cond: convert_expr(cond),
591            body: body.iter().map(|s| convert_stmt(s, globals)).collect(),
592        },
593        // Every other statement: whatever it may write — a variable rebound from a runtime source
594        // (channel receive, Mount, console read, peer message, …), a `Swap`, a nested block's `Set`,
595        // a global its calls reach — is Dynamic afterwards; a `Show` writes nothing unless it calls.
596        other => {
597            let effects = WriteSet::of_stmt(other).with_callee_globals(globals);
598            if effects.is_opaque() {
599                BtaStmtKind::ClobberAll
600            } else {
601                let vars: Vec<Symbol> = effects.symbols().collect();
602                if vars.is_empty() {
603                    if matches!(other, Stmt::Show { .. }) {
604                        BtaStmtKind::Show
605                    } else {
606                        BtaStmtKind::Other
607                    }
608                } else {
609                    BtaStmtKind::ClobberDynamic { vars }
610                }
611            }
612        }
613    };
614    BtaStmt { kind }
615}
616
617fn convert_block(block: &[Stmt], globals: &CalleeGlobals) -> Vec<BtaStmt> {
618    block.iter().map(|s| convert_stmt(s, globals)).collect()
619}
620
621fn is_collection_type(ty: &TypeExpr) -> bool {
622    match ty {
623        TypeExpr::Generic { .. } => true,
624        _ => false,
625    }
626}
627
628fn analyze_bta_expr(
629    expr: &BtaExpr,
630    division: &Division,
631    functions: &[BtaFunc],
632    ctx: &mut BtaContext,
633) -> BindingTime {
634    match expr {
635        BtaExpr::Literal(lit) => BindingTime::Static(lit.clone()),
636        BtaExpr::Identifier(sym) => division.get(sym).cloned().unwrap_or(BindingTime::Dynamic),
637        BtaExpr::BinaryOp { op, left, right } => {
638            let bt_left = analyze_bta_expr(left, division, functions, ctx);
639            let bt_right = analyze_bta_expr(right, division, functions, ctx);
640            match (&bt_left, &bt_right) {
641                (BindingTime::Static(l), BindingTime::Static(r)) => {
642                    match eval_literal_binop(*op, l, r) {
643                        Some(result) => BindingTime::Static(result),
644                        None => BindingTime::Dynamic,
645                    }
646                }
647                _ => BindingTime::Dynamic,
648            }
649        }
650        BtaExpr::Not { operand } => match analyze_bta_expr(operand, division, functions, ctx) {
651            BindingTime::Static(Literal::Boolean(b)) => BindingTime::Static(Literal::Boolean(!b)),
652            _ => BindingTime::Dynamic,
653        },
654        BtaExpr::Length { .. } => BindingTime::Dynamic,
655        BtaExpr::Index { .. } => BindingTime::Dynamic,
656        BtaExpr::Call { function, args } => {
657            let arg_bts: Vec<BindingTime> = args
658                .iter()
659                .map(|a| analyze_bta_expr(a, division, functions, ctx))
660                .collect();
661
662            let cache_key = (*function, arg_bts.clone());
663
664            if let Some(cached) = ctx.cache.get(&cache_key) {
665                return cached.return_bt.clone();
666            }
667
668            if ctx.on_stack.contains(&cache_key) {
669                return BindingTime::Dynamic;
670            }
671
672            let func = match functions.iter().find(|f| f.name == *function) {
673                Some(f) => f.clone(),
674                None => return BindingTime::Dynamic,
675            };
676
677            ctx.on_stack.insert(cache_key.clone());
678
679            let mut func_div = Division::new();
680            for (i, (param_sym, is_collection)) in func.params.iter().enumerate() {
681                if *is_collection {
682                    func_div.insert(*param_sym, BindingTime::Dynamic);
683                } else if let Some(bt) = arg_bts.get(i) {
684                    func_div.insert(*param_sym, bt.clone());
685                } else {
686                    func_div.insert(*param_sym, BindingTime::Dynamic);
687                }
688            }
689
690            let return_bt = analyze_bta_block(&func.body, &mut func_div, functions, ctx);
691
692            ctx.on_stack.remove(&cache_key);
693
694            let result = BtaResult {
695                division: func_div,
696                return_bt: return_bt.clone(),
697            };
698            ctx.cache.insert(cache_key, result);
699
700            return_bt
701        }
702        BtaExpr::Other | BtaExpr::OtherCall => BindingTime::Dynamic,
703    }
704}
705
706fn analyze_bta_block(
707    stmts: &[BtaStmt],
708    division: &mut Division,
709    functions: &[BtaFunc],
710    ctx: &mut BtaContext,
711) -> BindingTime {
712    analyze_bta_block_opt(stmts, division, functions, ctx).unwrap_or(BindingTime::Dynamic)
713}
714
715fn analyze_bta_block_opt(
716    stmts: &[BtaStmt],
717    division: &mut Division,
718    functions: &[BtaFunc],
719    ctx: &mut BtaContext,
720) -> Option<BindingTime> {
721    for stmt in stmts {
722        if let Some(bt) = analyze_bta_stmt(stmt, division, functions, ctx) {
723            return Some(bt);
724        }
725    }
726    None
727}
728
729fn join_bt(a: &BindingTime, b: &BindingTime) -> BindingTime {
730    match (a, b) {
731        (BindingTime::Static(l1), BindingTime::Static(l2)) => {
732            if l1 == l2 {
733                a.clone()
734            } else {
735                BindingTime::Dynamic
736            }
737        }
738        _ => BindingTime::Dynamic,
739    }
740}
741
742fn join_divisions(a: &Division, b: &Division) -> Division {
743    let mut joined = Division::new();
744    for (sym, bt_a) in a {
745        if let Some(bt_b) = b.get(sym) {
746            joined.insert(*sym, join_bt(bt_a, bt_b));
747        }
748    }
749    // Variables only in one branch get their value from that branch,
750    // but since the other branch doesn't define them, treat as Dynamic
751    for (sym, _) in b {
752        if !a.contains_key(sym) {
753            joined.insert(*sym, BindingTime::Dynamic);
754        }
755    }
756    for (sym, _) in a {
757        if !b.contains_key(sym) {
758            joined.insert(*sym, BindingTime::Dynamic);
759        }
760    }
761    joined
762}
763
764fn analyze_bta_stmt(
765    stmt: &BtaStmt,
766    division: &mut Division,
767    functions: &[BtaFunc],
768    ctx: &mut BtaContext,
769) -> Option<BindingTime> {
770    match &stmt.kind {
771        BtaStmtKind::Let { var, value } => {
772            if value.has_call() {
773                clobber_callee_globals(division, &ctx.callee_globals);
774            }
775            let bt = analyze_bta_expr(value, division, functions, ctx);
776            division.insert(*var, bt);
777            None
778        }
779        BtaStmtKind::Set { target, value } => {
780            if value.has_call() {
781                clobber_callee_globals(division, &ctx.callee_globals);
782            }
783            let bt = analyze_bta_expr(value, division, functions, ctx);
784            division.insert(*target, bt);
785            None
786        }
787        BtaStmtKind::Return { value } => {
788            let bt = match value {
789                Some(expr) => {
790                    if expr.has_call() {
791                        clobber_callee_globals(division, &ctx.callee_globals);
792                    }
793                    analyze_bta_expr(expr, division, functions, ctx)
794                }
795                None => BindingTime::Static(Literal::Nothing),
796            };
797            Some(bt)
798        }
799        BtaStmtKind::Show => None,
800        BtaStmtKind::Call { args } => {
801            for a in args {
802                analyze_bta_expr(a, division, functions, ctx);
803            }
804            clobber_callee_globals(division, &ctx.callee_globals);
805            None
806        }
807        BtaStmtKind::ClobberAll => {
808            for bt in division.values_mut() {
809                *bt = BindingTime::Dynamic;
810            }
811            None
812        }
813        BtaStmtKind::If {
814            cond,
815            then_block,
816            else_block,
817        } => {
818            if cond.has_call() {
819                clobber_callee_globals(division, &ctx.callee_globals);
820            }
821            let cond_bt = analyze_bta_expr(cond, division, functions, ctx);
822            match cond_bt {
823                BindingTime::Static(Literal::Boolean(true)) => {
824                    analyze_bta_block_opt(then_block, division, functions, ctx)
825                }
826                BindingTime::Static(Literal::Boolean(false)) => {
827                    if let Some(else_b) = else_block {
828                        analyze_bta_block_opt(else_b, division, functions, ctx)
829                    } else {
830                        None
831                    }
832                }
833                _ => {
834                    let snapshot = division.clone();
835
836                    let then_ret = analyze_bta_block_opt(then_block, division, functions, ctx);
837                    let then_div = division.clone();
838
839                    *division = snapshot;
840                    let else_ret = if let Some(else_b) = else_block {
841                        analyze_bta_block_opt(else_b, division, functions, ctx)
842                    } else {
843                        None
844                    };
845                    let else_div = division.clone();
846
847                    *division = join_divisions(&then_div, &else_div);
848                    match (then_ret, else_ret) {
849                        (Some(t), Some(e)) => Some(join_bt(&t, &e)),
850                        _ => None,
851                    }
852                }
853            }
854        }
855        BtaStmtKind::While { cond, body } => {
856            let max_iterations = 256;
857            for _ in 0..max_iterations {
858                if cond.has_call() {
859                    clobber_callee_globals(division, &ctx.callee_globals);
860                }
861                let cond_bt = analyze_bta_expr(cond, division, functions, ctx);
862
863                match cond_bt {
864                    BindingTime::Static(Literal::Boolean(false)) => break,
865                    BindingTime::Static(Literal::Boolean(true)) => {
866                        // Static true: unroll this iteration directly
867                        analyze_bta_block(body, division, functions, ctx);
868                    }
869                    _ => {
870                        // Dynamic condition: fixed-point with join
871                        let snapshot = division.clone();
872                        let mut body_div = snapshot.clone();
873                        analyze_bta_block(body, &mut body_div, functions, ctx);
874
875                        let joined = join_divisions(&snapshot, &body_div);
876                        if joined == *division {
877                            break;
878                        }
879                        *division = joined;
880                    }
881                }
882            }
883            None
884        }
885        BtaStmtKind::ClobberDynamic { vars } => {
886            for var in vars {
887                division.insert(*var, BindingTime::Dynamic);
888            }
889            None
890        }
891        BtaStmtKind::Other => None,
892    }
893}
894
895impl BtaEnv {
896    pub fn analyze_source(source: &str) -> Result<Self, ParseError> {
897        let mut interner = Interner::new();
898        let mut lexer = Lexer::new(source, &mut interner);
899        let tokens = lexer.tokenize();
900
901        let type_registry = {
902            let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
903            let result = discovery.run_full();
904            result.types
905        };
906
907        let mut world_state = WorldState::new();
908        let expr_arena = Arena::new();
909        let term_arena = Arena::new();
910        let np_arena = Arena::new();
911        let sym_arena = Arena::new();
912        let role_arena = Arena::new();
913        let pp_arena = Arena::new();
914        let stmt_arena = Arena::new();
915        let _compile_facts = super::facts::scope();
916        let imperative_expr_arena = Arena::new();
917        let type_expr_arena = Arena::new();
918
919        let ast_ctx = AstContext::with_types(
920            &expr_arena,
921            &term_arena,
922            &np_arena,
923            &sym_arena,
924            &role_arena,
925            &pp_arena,
926            &stmt_arena,
927            &imperative_expr_arena,
928            &type_expr_arena,
929        );
930
931        let mut parser = Parser::new(
932            tokens,
933            &mut world_state,
934            &mut interner,
935            ast_ctx,
936            type_registry,
937        );
938        let stmts = parser.parse_program()?;
939
940        let callee_globals = CalleeGlobals::of_program(&stmts);
941        let mut main_stmts = Vec::new();
942        let mut functions = Vec::new();
943
944        for stmt in &stmts {
945            match stmt {
946                Stmt::FunctionDef {
947                    name,
948                    params,
949                    body,
950                    is_native,
951                    ..
952                } => {
953                    if !is_native {
954                        let param_info: Vec<(Symbol, bool)> = params
955                            .iter()
956                            .map(|(sym, ty)| (*sym, is_collection_type(ty)))
957                            .collect();
958                        functions.push(BtaFunc {
959                            name: *name,
960                            params: param_info,
961                            body: convert_block(body, &callee_globals),
962                        });
963                    }
964                }
965                _ => {
966                    main_stmts.push(convert_stmt(stmt, &callee_globals));
967                }
968            }
969        }
970
971        Ok(BtaEnv {
972            interner,
973            main_stmts,
974            functions,
975            callee_globals,
976        })
977    }
978
979    pub fn analyze_main(&mut self) -> BtaResult {
980        let mut division = Division::new();
981        let mut ctx = BtaContext {
982            cache: BtaCache::new(),
983            on_stack: HashSet::new(),
984            callee_globals: self.callee_globals.clone(),
985        };
986        let return_bt =
987            analyze_bta_block(&self.main_stmts, &mut division, &self.functions, &mut ctx);
988        BtaResult {
989            division,
990            return_bt,
991        }
992    }
993
994    pub fn analyze_function(&mut self, func_name: &str, arg_bts: Vec<BindingTime>) -> BtaResult {
995        let func_sym = self
996            .interner
997            .lookup(func_name)
998            .unwrap_or_else(|| panic!("Function '{}' not found in interner", func_name));
999
1000        let func = self
1001            .functions
1002            .iter()
1003            .find(|f| f.name == func_sym)
1004            .unwrap_or_else(|| panic!("Function '{}' not found", func_name))
1005            .clone();
1006
1007        let mut division = Division::new();
1008        for (i, (param_sym, is_collection)) in func.params.iter().enumerate() {
1009            if *is_collection {
1010                division.insert(*param_sym, BindingTime::Dynamic);
1011            } else if let Some(bt) = arg_bts.get(i) {
1012                division.insert(*param_sym, bt.clone());
1013            } else {
1014                division.insert(*param_sym, BindingTime::Dynamic);
1015            }
1016        }
1017
1018        let mut ctx = BtaContext {
1019            cache: BtaCache::new(),
1020            on_stack: HashSet::new(),
1021            callee_globals: self.callee_globals.clone(),
1022        };
1023        let return_bt = analyze_bta_block(&func.body, &mut division, &self.functions, &mut ctx);
1024        BtaResult {
1025            division,
1026            return_bt,
1027        }
1028    }
1029
1030    pub fn lookup(&self, name: &str) -> Option<Symbol> {
1031        self.interner.lookup(name)
1032    }
1033}