logicaffeine-compile 0.9.13

LOGOS compilation pipeline - codegen and interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Binding-Time Analysis (BTA)
//!
//! Classifies every variable and expression as Static (S) — value known at compile
//! time — or Dynamic (D) — value depends on runtime input. This classification
//! drives function specialization in the partial evaluator.
//!
//! BTA is polyvariant: the same function analyzed at different call sites with
//! different argument divisions produces different results.

use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};

use crate::analysis::DiscoveryPass;
use crate::arena::Arena;
use crate::arena_ctx::AstContext;
use crate::ast::stmt::{BinaryOpKind, Block, Expr, Literal, Stmt, TypeExpr};
use crate::drs::WorldState;
use crate::error::ParseError;
use crate::intern::{Interner, Symbol};
use crate::lexer::Lexer;
use crate::parser::Parser;

// =============================================================================
// Core Types
// =============================================================================

#[derive(Debug, Clone)]
pub enum BindingTime {
    Static(Literal),
    Dynamic,
}

impl PartialEq for BindingTime {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (BindingTime::Static(a), BindingTime::Static(b)) => match (a, b) {
                (Literal::Float(x), Literal::Float(y)) => x.to_bits() == y.to_bits(),
                _ => a == b,
            },
            (BindingTime::Dynamic, BindingTime::Dynamic) => true,
            _ => false,
        }
    }
}

impl Eq for BindingTime {}

impl Hash for BindingTime {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            BindingTime::Static(lit) => hash_literal(lit, state),
            BindingTime::Dynamic => {}
        }
    }
}

fn hash_literal<H: Hasher>(lit: &Literal, state: &mut H) {
    std::mem::discriminant(lit).hash(state);
    match lit {
        Literal::Number(n) => n.hash(state),
        Literal::Float(f) => f.to_bits().hash(state),
        Literal::Text(s) => s.hash(state),
        Literal::Boolean(b) => b.hash(state),
        Literal::Nothing => {}
        Literal::Char(c) => c.hash(state),
        Literal::Duration(d) => d.hash(state),
        Literal::Date(d) => d.hash(state),
        Literal::Moment(m) => m.hash(state),
        Literal::Span { months, days } => {
            months.hash(state);
            days.hash(state);
        }
        Literal::Time(t) => t.hash(state),
    }
}

impl BindingTime {
    pub fn is_static(&self) -> bool {
        matches!(self, BindingTime::Static(_))
    }

    pub fn is_dynamic(&self) -> bool {
        matches!(self, BindingTime::Dynamic)
    }
}

pub type Division = HashMap<Symbol, BindingTime>;

#[derive(Debug, Clone, PartialEq)]
pub struct BtaResult {
    pub division: Division,
    pub return_bt: BindingTime,
}

pub type BtaCache = HashMap<(Symbol, Vec<BindingTime>), BtaResult>;

// =============================================================================
// Expression Analysis
// =============================================================================

pub fn analyze_expr(expr: &Expr, division: &Division) -> BindingTime {
    match expr {
        Expr::Literal(lit) => BindingTime::Static(lit.clone()),

        Expr::Identifier(sym) => {
            division.get(sym).cloned().unwrap_or(BindingTime::Dynamic)
        }

        Expr::BinaryOp { op, left, right } => {
            let bt_left = analyze_expr(left, division);
            let bt_right = analyze_expr(right, division);
            match (&bt_left, &bt_right) {
                (BindingTime::Static(l), BindingTime::Static(r)) => {
                    match eval_literal_binop(*op, l, r) {
                        Some(result) => BindingTime::Static(result),
                        None => BindingTime::Dynamic,
                    }
                }
                _ => BindingTime::Dynamic,
            }
        }

        Expr::Not { operand } => {
            match analyze_expr(operand, division) {
                BindingTime::Static(Literal::Boolean(b)) => {
                    BindingTime::Static(Literal::Boolean(!b))
                }
                _ => BindingTime::Dynamic,
            }
        }

        Expr::Length { .. } => BindingTime::Dynamic,
        Expr::Index { .. } => BindingTime::Dynamic,

        Expr::Call { .. } => BindingTime::Dynamic,

        _ => BindingTime::Dynamic,
    }
}

fn eval_literal_binop(op: BinaryOpKind, left: &Literal, right: &Literal) -> Option<Literal> {
    match (op, left, right) {
        (BinaryOpKind::Add, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Number(a.wrapping_add(*b)))
        }
        (BinaryOpKind::Subtract, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Number(a.wrapping_sub(*b)))
        }
        (BinaryOpKind::Multiply, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Number(a.wrapping_mul(*b)))
        }
        (BinaryOpKind::Divide, Literal::Number(a), Literal::Number(b)) if *b != 0 => {
            Some(Literal::Number(a / b))
        }
        (BinaryOpKind::Modulo, Literal::Number(a), Literal::Number(b)) if *b != 0 => {
            Some(Literal::Number(a % b))
        }
        (BinaryOpKind::Eq, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a == b))
        }
        (BinaryOpKind::NotEq, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a != b))
        }
        (BinaryOpKind::Lt, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a < b))
        }
        (BinaryOpKind::Gt, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a > b))
        }
        (BinaryOpKind::LtEq, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a <= b))
        }
        (BinaryOpKind::GtEq, Literal::Number(a), Literal::Number(b)) => {
            Some(Literal::Boolean(a >= b))
        }
        (BinaryOpKind::Add, Literal::Float(a), Literal::Float(b)) => {
            Some(Literal::Float(a + b))
        }
        (BinaryOpKind::Subtract, Literal::Float(a), Literal::Float(b)) => {
            Some(Literal::Float(a - b))
        }
        (BinaryOpKind::Multiply, Literal::Float(a), Literal::Float(b)) => {
            Some(Literal::Float(a * b))
        }
        (BinaryOpKind::Divide, Literal::Float(a), Literal::Float(b)) if *b != 0.0 => {
            Some(Literal::Float(a / b))
        }
        (BinaryOpKind::And, Literal::Boolean(a), Literal::Boolean(b)) => {
            Some(Literal::Boolean(*a && *b))
        }
        (BinaryOpKind::Or, Literal::Boolean(a), Literal::Boolean(b)) => {
            Some(Literal::Boolean(*a || *b))
        }
        _ => None,
    }
}

// =============================================================================
// Statement / Block Analysis
// =============================================================================

fn analyze_block<'a>(
    stmts: &[Stmt<'a>],
    division: &mut Division,
    funcs: &HashMap<Symbol, FuncDef<'a>>,
    cache: &mut BtaCache,
) -> BindingTime {
    let mut return_bt = BindingTime::Dynamic;
    for stmt in stmts {
        if let Some(bt) = analyze_stmt(stmt, division, funcs, cache) {
            return_bt = bt;
        }
    }
    return_bt
}

fn analyze_stmt<'a>(
    stmt: &Stmt<'a>,
    division: &mut Division,
    funcs: &HashMap<Symbol, FuncDef<'a>>,
    cache: &mut BtaCache,
) -> Option<BindingTime> {
    match stmt {
        Stmt::Let { var, value, .. } => {
            let bt = analyze_expr(value, division);
            division.insert(*var, bt);
            None
        }
        Stmt::Set { target, value } => {
            let bt = analyze_expr(value, division);
            division.insert(*target, bt);
            None
        }
        Stmt::Return { value } => {
            let bt = match value {
                Some(expr) => analyze_expr(expr, division),
                None => BindingTime::Static(Literal::Nothing),
            };
            Some(bt)
        }
        Stmt::Show { .. } => None,
        Stmt::Call { function, args } => {
            for arg in args {
                analyze_expr(arg, division);
            }
            None
        }
        _ => None,
    }
}

// =============================================================================
// Function Definition Storage
// =============================================================================

struct FuncDef<'a> {
    params: Vec<(Symbol, &'a TypeExpr<'a>)>,
    body: Block<'a>,
}

pub fn analyze_function_bt<'a>(
    func_name: Symbol,
    params: &[(Symbol, &'a TypeExpr<'a>)],
    body: &[Stmt<'a>],
    arg_bts: &[BindingTime],
    funcs: &HashMap<Symbol, FuncDef<'a>>,
    cache: &mut BtaCache,
) -> BtaResult {
    let cache_key = (func_name, arg_bts.to_vec());
    if let Some(cached) = cache.get(&cache_key) {
        return cached.clone();
    }

    let mut division = Division::new();
    for (i, (param_sym, _)) in params.iter().enumerate() {
        if let Some(bt) = arg_bts.get(i) {
            division.insert(*param_sym, bt.clone());
        } else {
            division.insert(*param_sym, BindingTime::Dynamic);
        }
    }

    let return_bt = analyze_block(body, &mut division, funcs, cache);

    let result = BtaResult {
        division,
        return_bt,
    };
    cache.insert(cache_key, result.clone());
    result
}

// =============================================================================
// SCC-Ordered Analysis
// =============================================================================

pub fn analyze_with_sccs<'a>(
    stmts: &[Stmt<'a>],
    interner: &Interner,
) -> BtaCache {
    use crate::analysis::callgraph::CallGraph;

    let cg = CallGraph::build(stmts, interner);

    let mut funcs: HashMap<Symbol, FuncDef<'a>> = HashMap::new();
    for stmt in stmts {
        if let Stmt::FunctionDef { name, params, body, is_native: false, .. } = stmt {
            funcs.insert(*name, FuncDef { params: params.clone(), body });
        }
    }

    let mut cache = BtaCache::new();

    // Process SCCs in topological order (sccs are already in reverse topo order from Kosaraju)
    for scc in cg.sccs.iter().rev() {
        if scc.len() == 1 {
            // Non-recursive (or self-recursive): analyze once
            let sym = scc[0];
            if let Some(func_def) = funcs.get(&sym) {
                let arg_bts: Vec<BindingTime> = func_def.params.iter()
                    .map(|_| BindingTime::Dynamic)
                    .collect();
                analyze_function_bt(sym, &func_def.params, func_def.body, &arg_bts, &funcs, &mut cache);
            }
        } else {
            // Mutually recursive SCC: iterate to fixed point
            for _iteration in 0..10 {
                let mut changed = false;
                for &sym in scc {
                    if let Some(func_def) = funcs.get(&sym) {
                        let arg_bts: Vec<BindingTime> = func_def.params.iter()
                            .map(|_| BindingTime::Dynamic)
                            .collect();
                        let key = (sym, arg_bts.clone());
                        let old = cache.get(&key).cloned();
                        let result = analyze_function_bt(sym, &func_def.params, func_def.body, &arg_bts, &funcs, &mut cache);
                        if old.as_ref() != Some(&result) {
                            changed = true;
                        }
                    }
                }
                if !changed {
                    break;
                }
            }
        }
    }

    cache
}

// =============================================================================
// Test-Friendly Wrapper
// =============================================================================

pub struct BtaEnv {
    interner: Interner,
    main_stmts: Vec<BtaStmt>,
    functions: Vec<BtaFunc>,
}

#[derive(Clone)]
struct BtaStmt {
    kind: BtaStmtKind,
}

#[derive(Clone)]
enum BtaStmtKind {
    Let { var: Symbol, value: BtaExpr },
    Set { target: Symbol, value: BtaExpr },
    Return { value: Option<BtaExpr> },
    Show,
    Call { function: Symbol, args: Vec<BtaExpr> },
    If { cond: BtaExpr, then_block: Vec<BtaStmt>, else_block: Option<Vec<BtaStmt>> },
    While { cond: BtaExpr, body: Vec<BtaStmt> },
    Other,
}

#[derive(Clone)]
enum BtaExpr {
    Literal(Literal),
    Identifier(Symbol),
    BinaryOp { op: BinaryOpKind, left: Box<BtaExpr>, right: Box<BtaExpr> },
    Not { operand: Box<BtaExpr> },
    Length { collection: Box<BtaExpr> },
    Index { collection: Box<BtaExpr>, index: Box<BtaExpr> },
    Call { function: Symbol, args: Vec<BtaExpr> },
    Other,
}

#[derive(Clone)]
struct BtaFunc {
    name: Symbol,
    params: Vec<(Symbol, bool)>, // (name, is_collection_type)
    body: Vec<BtaStmt>,
}

struct BtaContext {
    cache: BtaCache,
    on_stack: HashSet<(Symbol, Vec<BindingTime>)>,
}

fn convert_expr(expr: &Expr) -> BtaExpr {
    match expr {
        Expr::Literal(lit) => BtaExpr::Literal(lit.clone()),
        Expr::Identifier(sym) => BtaExpr::Identifier(*sym),
        Expr::BinaryOp { op, left, right } => BtaExpr::BinaryOp {
            op: *op,
            left: Box::new(convert_expr(left)),
            right: Box::new(convert_expr(right)),
        },
        Expr::Not { operand } => BtaExpr::Not {
            operand: Box::new(convert_expr(operand)),
        },
        Expr::Length { collection } => BtaExpr::Length {
            collection: Box::new(convert_expr(collection)),
        },
        Expr::Index { collection, index } => BtaExpr::Index {
            collection: Box::new(convert_expr(collection)),
            index: Box::new(convert_expr(index)),
        },
        Expr::Call { function, args } => BtaExpr::Call {
            function: *function,
            args: args.iter().map(|a| convert_expr(a)).collect(),
        },
        _ => BtaExpr::Other,
    }
}

fn convert_stmt(stmt: &Stmt) -> BtaStmt {
    let kind = match stmt {
        Stmt::Let { var, value, .. } => BtaStmtKind::Let {
            var: *var,
            value: convert_expr(value),
        },
        Stmt::Set { target, value } => BtaStmtKind::Set {
            target: *target,
            value: convert_expr(value),
        },
        Stmt::Return { value } => BtaStmtKind::Return {
            value: value.map(|v| convert_expr(v)),
        },
        Stmt::Show { .. } => BtaStmtKind::Show,
        Stmt::Call { function, args } => BtaStmtKind::Call {
            function: *function,
            args: args.iter().map(|a| convert_expr(a)).collect(),
        },
        Stmt::If { cond, then_block, else_block } => BtaStmtKind::If {
            cond: convert_expr(cond),
            then_block: then_block.iter().map(|s| convert_stmt(s)).collect(),
            else_block: else_block.map(|eb| eb.iter().map(|s| convert_stmt(s)).collect()),
        },
        Stmt::While { cond, body, .. } => BtaStmtKind::While {
            cond: convert_expr(cond),
            body: body.iter().map(|s| convert_stmt(s)).collect(),
        },
        _ => BtaStmtKind::Other,
    };
    BtaStmt { kind }
}

fn convert_block(block: &[Stmt]) -> Vec<BtaStmt> {
    block.iter().map(|s| convert_stmt(s)).collect()
}

fn is_collection_type(ty: &TypeExpr) -> bool {
    match ty {
        TypeExpr::Generic { .. } => true,
        _ => false,
    }
}

fn analyze_bta_expr(
    expr: &BtaExpr,
    division: &Division,
    functions: &[BtaFunc],
    ctx: &mut BtaContext,
) -> BindingTime {
    match expr {
        BtaExpr::Literal(lit) => BindingTime::Static(lit.clone()),
        BtaExpr::Identifier(sym) => {
            division.get(sym).cloned().unwrap_or(BindingTime::Dynamic)
        }
        BtaExpr::BinaryOp { op, left, right } => {
            let bt_left = analyze_bta_expr(left, division, functions, ctx);
            let bt_right = analyze_bta_expr(right, division, functions, ctx);
            match (&bt_left, &bt_right) {
                (BindingTime::Static(l), BindingTime::Static(r)) => {
                    match eval_literal_binop(*op, l, r) {
                        Some(result) => BindingTime::Static(result),
                        None => BindingTime::Dynamic,
                    }
                }
                _ => BindingTime::Dynamic,
            }
        }
        BtaExpr::Not { operand } => {
            match analyze_bta_expr(operand, division, functions, ctx) {
                BindingTime::Static(Literal::Boolean(b)) => {
                    BindingTime::Static(Literal::Boolean(!b))
                }
                _ => BindingTime::Dynamic,
            }
        }
        BtaExpr::Length { .. } => BindingTime::Dynamic,
        BtaExpr::Index { .. } => BindingTime::Dynamic,
        BtaExpr::Call { function, args } => {
            let arg_bts: Vec<BindingTime> = args.iter()
                .map(|a| analyze_bta_expr(a, division, functions, ctx))
                .collect();

            let cache_key = (*function, arg_bts.clone());

            if let Some(cached) = ctx.cache.get(&cache_key) {
                return cached.return_bt.clone();
            }

            if ctx.on_stack.contains(&cache_key) {
                return BindingTime::Dynamic;
            }

            let func = match functions.iter().find(|f| f.name == *function) {
                Some(f) => f.clone(),
                None => return BindingTime::Dynamic,
            };

            ctx.on_stack.insert(cache_key.clone());

            let mut func_div = Division::new();
            for (i, (param_sym, is_collection)) in func.params.iter().enumerate() {
                if *is_collection {
                    func_div.insert(*param_sym, BindingTime::Dynamic);
                } else if let Some(bt) = arg_bts.get(i) {
                    func_div.insert(*param_sym, bt.clone());
                } else {
                    func_div.insert(*param_sym, BindingTime::Dynamic);
                }
            }

            let return_bt = analyze_bta_block(&func.body, &mut func_div, functions, ctx);

            ctx.on_stack.remove(&cache_key);

            let result = BtaResult {
                division: func_div,
                return_bt: return_bt.clone(),
            };
            ctx.cache.insert(cache_key, result);

            return_bt
        }
        BtaExpr::Other => BindingTime::Dynamic,
    }
}

fn analyze_bta_block(
    stmts: &[BtaStmt],
    division: &mut Division,
    functions: &[BtaFunc],
    ctx: &mut BtaContext,
) -> BindingTime {
    analyze_bta_block_opt(stmts, division, functions, ctx)
        .unwrap_or(BindingTime::Dynamic)
}

fn analyze_bta_block_opt(
    stmts: &[BtaStmt],
    division: &mut Division,
    functions: &[BtaFunc],
    ctx: &mut BtaContext,
) -> Option<BindingTime> {
    for stmt in stmts {
        if let Some(bt) = analyze_bta_stmt(stmt, division, functions, ctx) {
            return Some(bt);
        }
    }
    None
}

fn join_bt(a: &BindingTime, b: &BindingTime) -> BindingTime {
    match (a, b) {
        (BindingTime::Static(l1), BindingTime::Static(l2)) => {
            if l1 == l2 {
                a.clone()
            } else {
                BindingTime::Dynamic
            }
        }
        _ => BindingTime::Dynamic,
    }
}

fn join_divisions(a: &Division, b: &Division) -> Division {
    let mut joined = Division::new();
    for (sym, bt_a) in a {
        if let Some(bt_b) = b.get(sym) {
            joined.insert(*sym, join_bt(bt_a, bt_b));
        }
    }
    // Variables only in one branch get their value from that branch,
    // but since the other branch doesn't define them, treat as Dynamic
    for (sym, _) in b {
        if !a.contains_key(sym) {
            joined.insert(*sym, BindingTime::Dynamic);
        }
    }
    for (sym, _) in a {
        if !b.contains_key(sym) {
            joined.insert(*sym, BindingTime::Dynamic);
        }
    }
    joined
}

fn analyze_bta_stmt(
    stmt: &BtaStmt,
    division: &mut Division,
    functions: &[BtaFunc],
    ctx: &mut BtaContext,
) -> Option<BindingTime> {
    match &stmt.kind {
        BtaStmtKind::Let { var, value } => {
            let bt = analyze_bta_expr(value, division, functions, ctx);
            division.insert(*var, bt);
            None
        }
        BtaStmtKind::Set { target, value } => {
            let bt = analyze_bta_expr(value, division, functions, ctx);
            division.insert(*target, bt);
            None
        }
        BtaStmtKind::Return { value } => {
            let bt = match value {
                Some(expr) => analyze_bta_expr(expr, division, functions, ctx),
                None => BindingTime::Static(Literal::Nothing),
            };
            Some(bt)
        }
        BtaStmtKind::Show => None,
        BtaStmtKind::Call { .. } => None,
        BtaStmtKind::If { cond, then_block, else_block } => {
            let cond_bt = analyze_bta_expr(cond, division, functions, ctx);
            match cond_bt {
                BindingTime::Static(Literal::Boolean(true)) => {
                    analyze_bta_block_opt(then_block, division, functions, ctx)
                }
                BindingTime::Static(Literal::Boolean(false)) => {
                    if let Some(else_b) = else_block {
                        analyze_bta_block_opt(else_b, division, functions, ctx)
                    } else {
                        None
                    }
                }
                _ => {
                    let snapshot = division.clone();

                    let then_ret = analyze_bta_block_opt(then_block, division, functions, ctx);
                    let then_div = division.clone();

                    *division = snapshot;
                    let else_ret = if let Some(else_b) = else_block {
                        analyze_bta_block_opt(else_b, division, functions, ctx)
                    } else {
                        None
                    };
                    let else_div = division.clone();

                    *division = join_divisions(&then_div, &else_div);
                    match (then_ret, else_ret) {
                        (Some(t), Some(e)) => Some(join_bt(&t, &e)),
                        _ => None,
                    }
                }
            }
        }
        BtaStmtKind::While { cond, body } => {
            let max_iterations = 256;
            for _ in 0..max_iterations {
                let cond_bt = analyze_bta_expr(cond, division, functions, ctx);

                match cond_bt {
                    BindingTime::Static(Literal::Boolean(false)) => break,
                    BindingTime::Static(Literal::Boolean(true)) => {
                        // Static true: unroll this iteration directly
                        analyze_bta_block(body, division, functions, ctx);
                    }
                    _ => {
                        // Dynamic condition: fixed-point with join
                        let snapshot = division.clone();
                        let mut body_div = snapshot.clone();
                        analyze_bta_block(body, &mut body_div, functions, ctx);

                        let joined = join_divisions(&snapshot, &body_div);
                        if joined == *division {
                            break;
                        }
                        *division = joined;
                    }
                }
            }
            None
        }
        BtaStmtKind::Other => None,
    }
}

impl BtaEnv {
    pub fn analyze_source(source: &str) -> Result<Self, ParseError> {
        let mut interner = Interner::new();
        let mut lexer = Lexer::new(source, &mut interner);
        let tokens = lexer.tokenize();

        let type_registry = {
            let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
            let result = discovery.run_full();
            result.types
        };

        let mut world_state = WorldState::new();
        let expr_arena = Arena::new();
        let term_arena = Arena::new();
        let np_arena = Arena::new();
        let sym_arena = Arena::new();
        let role_arena = Arena::new();
        let pp_arena = Arena::new();
        let stmt_arena = Arena::new();
        let imperative_expr_arena = Arena::new();
        let type_expr_arena = Arena::new();

        let ast_ctx = AstContext::with_types(
            &expr_arena,
            &term_arena,
            &np_arena,
            &sym_arena,
            &role_arena,
            &pp_arena,
            &stmt_arena,
            &imperative_expr_arena,
            &type_expr_arena,
        );

        let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
        let stmts = parser.parse_program()?;

        let mut main_stmts = Vec::new();
        let mut functions = Vec::new();

        for stmt in &stmts {
            match stmt {
                Stmt::FunctionDef { name, params, body, is_native, .. } => {
                    if !is_native {
                        let param_info: Vec<(Symbol, bool)> = params.iter().map(|(sym, ty)| {
                            (*sym, is_collection_type(ty))
                        }).collect();
                        functions.push(BtaFunc {
                            name: *name,
                            params: param_info,
                            body: convert_block(body),
                        });
                    }
                }
                _ => {
                    main_stmts.push(convert_stmt(stmt));
                }
            }
        }

        Ok(BtaEnv {
            interner,
            main_stmts,
            functions,
        })
    }

    pub fn analyze_main(&mut self) -> BtaResult {
        let mut division = Division::new();
        let mut ctx = BtaContext {
            cache: BtaCache::new(),
            on_stack: HashSet::new(),
        };
        let return_bt = analyze_bta_block(&self.main_stmts, &mut division, &self.functions, &mut ctx);
        BtaResult { division, return_bt }
    }

    pub fn analyze_function(&mut self, func_name: &str, arg_bts: Vec<BindingTime>) -> BtaResult {
        let func_sym = self.interner.lookup(func_name)
            .unwrap_or_else(|| panic!("Function '{}' not found in interner", func_name));

        let func = self.functions.iter()
            .find(|f| f.name == func_sym)
            .unwrap_or_else(|| panic!("Function '{}' not found", func_name))
            .clone();

        let mut division = Division::new();
        for (i, (param_sym, is_collection)) in func.params.iter().enumerate() {
            if *is_collection {
                division.insert(*param_sym, BindingTime::Dynamic);
            } else if let Some(bt) = arg_bts.get(i) {
                division.insert(*param_sym, bt.clone());
            } else {
                division.insert(*param_sym, BindingTime::Dynamic);
            }
        }

        let mut ctx = BtaContext {
            cache: BtaCache::new(),
            on_stack: HashSet::new(),
        };
        let return_bt = analyze_bta_block(&func.body, &mut division, &self.functions, &mut ctx);
        BtaResult { division, return_bt }
    }

    pub fn lookup(&self, name: &str) -> Option<Symbol> {
        self.interner.lookup(name)
    }
}