logicaffeine-compile 0.10.0

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
//! Deforestation (Stream Fusion).
//!
//! Detects producer-consumer loop chains over intermediate collections and fuses
//! them into a single loop, eliminating intermediate allocations.
//!
//! Pattern:
//!   Let mutable temp = new Seq of T.
//!   Repeat for x in source: ... Push <expr> to temp ...
//!   Repeat for y in temp: <body>
//!
//! Becomes:
//!   Repeat for x in source: ... Let y = <expr>. <body> ...

use std::collections::HashSet;

use crate::arena::Arena;
use crate::ast::stmt::{Block, Expr, Pattern, StringPart, Stmt};
use crate::intern::{Interner, Symbol};

pub fn deforest_stmts<'a>(
    stmts: Vec<Stmt<'a>>,
    expr_arena: &'a Arena<Expr<'a>>,
    stmt_arena: &'a Arena<Stmt<'a>>,
    interner: &Interner,
) -> Vec<Stmt<'a>> {
    // Run iteratively for multi-stage fusion (A→B→C fuses in 2 passes)
    let mut current = stmts;
    for _ in 0..4 {
        let prev_len = current.len();
        current = deforest_pass(current, expr_arena, stmt_arena, interner);
        if current.len() >= prev_len {
            break;
        }
    }
    current
}

fn deforest_pass<'a>(
    stmts: Vec<Stmt<'a>>,
    expr_arena: &'a Arena<Expr<'a>>,
    stmt_arena: &'a Arena<Stmt<'a>>,
    interner: &Interner,
) -> Vec<Stmt<'a>> {
    let mut result = Vec::with_capacity(stmts.len());
    let mut i = 0;

    while i < stmts.len() {
        if let Some((skip_to, fused)) = try_deforest(&stmts, i, expr_arena, stmt_arena, interner) {
            result.extend(fused);
            i = skip_to;
            continue;
        }

        let stmt = stmts[i].clone();
        result.push(recurse_deforest(stmt, expr_arena, stmt_arena, interner));
        i += 1;
    }

    result
}

fn recurse_deforest<'a>(
    stmt: Stmt<'a>,
    expr_arena: &'a Arena<Expr<'a>>,
    stmt_arena: &'a Arena<Stmt<'a>>,
    interner: &Interner,
) -> Stmt<'a> {
    match stmt {
        Stmt::FunctionDef { name, generics, params, body, return_type, is_native, native_path, is_exported, export_target, opt_flags } => {
            let new_body = deforest_stmts(body.to_vec(), expr_arena, stmt_arena, interner);
            Stmt::FunctionDef {
                name, generics, params,
                body: stmt_arena.alloc_slice(new_body),
                return_type, is_native, native_path, is_exported, export_target, opt_flags,
            }
        }
        Stmt::While { cond, body, decreasing } => {
            let new_body = deforest_stmts(body.to_vec(), expr_arena, stmt_arena, interner);
            Stmt::While {
                cond,
                body: stmt_arena.alloc_slice(new_body),
                decreasing,
            }
        }
        Stmt::If { cond, then_block, else_block } => {
            let new_then = deforest_stmts(then_block.to_vec(), expr_arena, stmt_arena, interner);
            let new_else = else_block.map(|eb| {
                let processed = deforest_stmts(eb.to_vec(), expr_arena, stmt_arena, interner);
                let b: Block = stmt_arena.alloc_slice(processed);
                b
            });
            Stmt::If {
                cond,
                then_block: stmt_arena.alloc_slice(new_then),
                else_block: new_else,
            }
        }
        Stmt::Repeat { pattern, iterable, body } => {
            let new_body = deforest_stmts(body.to_vec(), expr_arena, stmt_arena, interner);
            Stmt::Repeat {
                pattern,
                iterable,
                body: stmt_arena.alloc_slice(new_body),
            }
        }
        other => other,
    }
}

fn try_deforest<'a>(
    stmts: &[Stmt<'a>],
    start: usize,
    expr_arena: &'a Arena<Expr<'a>>,
    stmt_arena: &'a Arena<Stmt<'a>>,
    interner: &Interner,
) -> Option<(usize, Vec<Stmt<'a>>)> {
    // Step 1: stmts[start] must be `Let mutable temp = new Seq/List`
    let temp_sym = match_temp_init(&stmts[start], interner)?;

    // Step 2: stmts[start+1] must be a Repeat that pushes to temp
    let producer_idx = start + 1;
    if producer_idx >= stmts.len() { return None; }
    if !is_repeat_producer(&stmts[producer_idx], temp_sym) { return None; }

    // Step 3: Find the consumer Repeat over temp, collecting intermediates
    let mut consumer_idx = None;
    let mut intermediates = Vec::new();
    for j in (producer_idx + 1)..stmts.len() {
        if is_repeat_over_sym(&stmts[j], temp_sym) {
            consumer_idx = Some(j);
            break;
        }
        if stmt_references_symbol(&stmts[j], temp_sym) {
            return None;
        }
        if !is_safe_intermediate(&stmts[j]) {
            return None;
        }
        intermediates.push(stmts[j].clone());
    }
    let consumer_idx = consumer_idx?;

    // Step 4: Verify temp is not referenced after the consumer
    for j in (consumer_idx + 1)..stmts.len() {
        if stmt_references_symbol(&stmts[j], temp_sym) {
            return None;
        }
    }

    // Step 5: Extract consumer details
    let (pattern_var, consumer_body) = match &stmts[consumer_idx] {
        Stmt::Repeat { pattern: Pattern::Identifier(var), body, .. } => (*var, *body),
        _ => return None,
    };

    // Step 6: Safety — consumer body must not write to producer's source symbols
    let producer_source = collect_iterable_symbols(&stmts[producer_idx]);
    let consumer_writes = collect_block_writes(consumer_body);
    if !consumer_writes.is_disjoint(&producer_source) {
        return None;
    }

    // Step 7: Build the fused loop
    let fused = build_fused_repeat(
        &stmts[producer_idx], temp_sym, pattern_var, consumer_body,
        expr_arena, stmt_arena,
    )?;

    // Verify no residual pushes to temp remain
    if fused_still_pushes_to(&fused, temp_sym) {
        return None;
    }

    // Output: intermediates first, then fused loop
    let mut output = intermediates;
    output.push(fused);

    Some((consumer_idx + 1, output))
}

/// Check if stmt is `Let mutable <var> = new Seq/List`
fn match_temp_init(stmt: &Stmt, interner: &Interner) -> Option<Symbol> {
    match stmt {
        Stmt::Let { var, value, mutable: true, .. } => {
            if let Expr::New { type_name, .. } = value {
                let name = interner.resolve(*type_name);
                if name == "Seq" || name == "List" {
                    return Some(*var);
                }
            }
            None
        }
        _ => None,
    }
}

/// Check if stmt is a Repeat loop whose body pushes to `temp_sym`
fn is_repeat_producer(stmt: &Stmt, temp_sym: Symbol) -> bool {
    match stmt {
        Stmt::Repeat { body, .. } => block_pushes_to(body, temp_sym),
        _ => false,
    }
}

/// Check if a block contains at least one Push to the given symbol
fn block_pushes_to(block: &[Stmt], sym: Symbol) -> bool {
    for stmt in block {
        match stmt {
            Stmt::Push { collection, .. } => {
                if let Expr::Identifier(s) = collection {
                    if *s == sym { return true; }
                }
            }
            Stmt::If { then_block, else_block, .. } => {
                if block_pushes_to(then_block, sym) { return true; }
                if let Some(eb) = else_block {
                    if block_pushes_to(eb, sym) { return true; }
                }
            }
            _ => {}
        }
    }
    false
}

/// Check if stmt is `Repeat for <var> in <sym>`
fn is_repeat_over_sym(stmt: &Stmt, sym: Symbol) -> bool {
    match stmt {
        Stmt::Repeat { pattern: Pattern::Identifier(_), iterable, .. } => {
            matches!(iterable, Expr::Identifier(s) if *s == sym)
        }
        _ => false,
    }
}

/// Check if an intermediate statement is safe to move before the fused loop.
/// Only allow Let bindings (new variables, no mutation of existing ones).
fn is_safe_intermediate(stmt: &Stmt) -> bool {
    matches!(stmt, Stmt::Let { .. })
}

/// Collect symbols from the producer's iterable expression.
fn collect_iterable_symbols(stmt: &Stmt) -> HashSet<Symbol> {
    let mut syms = HashSet::new();
    if let Stmt::Repeat { iterable, .. } = stmt {
        collect_expr_symbols(iterable, &mut syms);
    }
    syms
}

/// Collect all symbols written (Set targets, Push collections) in a block.
fn collect_block_writes(block: &[Stmt]) -> HashSet<Symbol> {
    let mut writes = HashSet::new();
    for stmt in block {
        collect_stmt_writes(stmt, &mut writes);
    }
    writes
}

fn collect_stmt_writes(stmt: &Stmt, writes: &mut HashSet<Symbol>) {
    match stmt {
        Stmt::Set { target, .. } => { writes.insert(*target); }
        Stmt::Push { collection, .. } | Stmt::Pop { collection, .. }
        | Stmt::Add { collection, .. } | Stmt::Remove { collection, .. } => {
            if let Expr::Identifier(sym) = collection {
                writes.insert(*sym);
            }
        }
        Stmt::SetIndex { collection, .. } | Stmt::SetField { object: collection, .. } => {
            if let Expr::Identifier(sym) = collection {
                writes.insert(*sym);
            }
        }
        Stmt::If { then_block, else_block, .. } => {
            for s in then_block.iter() { collect_stmt_writes(s, writes); }
            if let Some(eb) = else_block {
                for s in eb.iter() { collect_stmt_writes(s, writes); }
            }
        }
        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
            for s in body.iter() { collect_stmt_writes(s, writes); }
        }
        _ => {}
    }
}

fn collect_expr_symbols(expr: &Expr, syms: &mut HashSet<Symbol>) {
    match expr {
        Expr::Identifier(s) => { syms.insert(*s); }
        Expr::Literal(_) | Expr::OptionNone => {}
        Expr::BinaryOp { left, right, .. } => {
            collect_expr_symbols(left, syms);
            collect_expr_symbols(right, syms);
        }
        Expr::Not { operand } | Expr::Length { collection: operand }
        | Expr::Copy { expr: operand } | Expr::Give { value: operand }
        | Expr::OptionSome { value: operand } | Expr::ManifestOf { zone: operand }
        | Expr::FieldAccess { object: operand, .. } => {
            collect_expr_symbols(operand, syms);
        }
        Expr::Index { collection, index } | Expr::Contains { collection, value: index }
        | Expr::Union { left: collection, right: index }
        | Expr::Intersection { left: collection, right: index }
        | Expr::Range { start: collection, end: index }
        | Expr::WithCapacity { value: collection, capacity: index }
        | Expr::ChunkAt { index, zone: collection } => {
            collect_expr_symbols(collection, syms);
            collect_expr_symbols(index, syms);
        }
        Expr::Slice { collection, start, end } => {
            collect_expr_symbols(collection, syms);
            collect_expr_symbols(start, syms);
            collect_expr_symbols(end, syms);
        }
        Expr::List(items) | Expr::Tuple(items) => {
            for item in items { collect_expr_symbols(item, syms); }
        }
        Expr::New { init_fields, .. } => {
            for (_, val) in init_fields { collect_expr_symbols(val, syms); }
        }
        Expr::NewVariant { fields, .. } => {
            for (_, val) in fields { collect_expr_symbols(val, syms); }
        }
        Expr::InterpolatedString(parts) => {
            for part in parts {
                if let StringPart::Expr { value, .. } = part {
                    collect_expr_symbols(value, syms);
                }
            }
        }
        Expr::Call { args, .. } => {
            for arg in args { collect_expr_symbols(arg, syms); }
        }
        Expr::CallExpr { callee, args } => {
            collect_expr_symbols(callee, syms);
            for arg in args { collect_expr_symbols(arg, syms); }
        }
        Expr::Closure { .. } | Expr::Escape { .. } => {}
    }
}

/// Check if any expression in a statement references a given symbol.
fn stmt_references_symbol(stmt: &Stmt, sym: Symbol) -> bool {
    match stmt {
        Stmt::Let { var, value, .. } => {
            *var == sym || expr_references_symbol(value, sym)
        }
        Stmt::Set { target, value } => {
            *target == sym || expr_references_symbol(value, sym)
        }
        Stmt::Show { object, recipient } => {
            expr_references_symbol(object, sym) || expr_references_symbol(recipient, sym)
        }
        Stmt::Push { collection, value } | Stmt::Add { collection, value }
        | Stmt::Remove { collection, value } => {
            expr_references_symbol(collection, sym) || expr_references_symbol(value, sym)
        }
        Stmt::Pop { collection, into } => {
            expr_references_symbol(collection, sym) ||
            into.map_or(false, |s| s == sym)
        }
        Stmt::SetIndex { collection, index, value } => {
            expr_references_symbol(collection, sym) ||
            expr_references_symbol(index, sym) ||
            expr_references_symbol(value, sym)
        }
        Stmt::SetField { object, value, .. } => {
            expr_references_symbol(object, sym) || expr_references_symbol(value, sym)
        }
        Stmt::Return { value } => {
            value.map_or(false, |v| expr_references_symbol(v, sym))
        }
        Stmt::Call { args, .. } => {
            args.iter().any(|a| expr_references_symbol(a, sym))
        }
        Stmt::If { cond, then_block, else_block } => {
            expr_references_symbol(cond, sym) ||
            then_block.iter().any(|s| stmt_references_symbol(s, sym)) ||
            else_block.map_or(false, |eb| eb.iter().any(|s| stmt_references_symbol(s, sym)))
        }
        Stmt::While { cond, body, .. } => {
            expr_references_symbol(cond, sym) ||
            body.iter().any(|s| stmt_references_symbol(s, sym))
        }
        Stmt::Repeat { iterable, body, pattern } => {
            let pattern_matches = match pattern {
                Pattern::Identifier(s) => *s == sym,
                Pattern::Tuple(syms) => syms.contains(&sym),
            };
            pattern_matches ||
            expr_references_symbol(iterable, sym) ||
            body.iter().any(|s| stmt_references_symbol(s, sym))
        }
        Stmt::Inspect { target, arms, .. } => {
            expr_references_symbol(target, sym) ||
            arms.iter().any(|arm| arm.body.iter().any(|s| stmt_references_symbol(s, sym)))
        }
        // Conservative: unknown statement types are assumed to reference the symbol
        _ => true,
    }
}

fn expr_references_symbol(expr: &Expr, sym: Symbol) -> bool {
    match expr {
        Expr::Identifier(s) => *s == sym,
        Expr::Literal(_) | Expr::OptionNone => false,
        Expr::BinaryOp { left, right, .. } => {
            expr_references_symbol(left, sym) || expr_references_symbol(right, sym)
        }
        Expr::Not { operand } | Expr::Length { collection: operand }
        | Expr::Copy { expr: operand } | Expr::Give { value: operand }
        | Expr::OptionSome { value: operand } | Expr::ManifestOf { zone: operand }
        | Expr::FieldAccess { object: operand, .. } => {
            expr_references_symbol(operand, sym)
        }
        Expr::Index { collection, index } | Expr::Contains { collection, value: index }
        | Expr::Union { left: collection, right: index }
        | Expr::Intersection { left: collection, right: index }
        | Expr::Range { start: collection, end: index }
        | Expr::WithCapacity { value: collection, capacity: index }
        | Expr::ChunkAt { index, zone: collection } => {
            expr_references_symbol(collection, sym) || expr_references_symbol(index, sym)
        }
        Expr::Slice { collection, start, end } => {
            expr_references_symbol(collection, sym) ||
            expr_references_symbol(start, sym) ||
            expr_references_symbol(end, sym)
        }
        Expr::List(items) | Expr::Tuple(items) => {
            items.iter().any(|item| expr_references_symbol(item, sym))
        }
        Expr::New { init_fields, .. } => {
            init_fields.iter().any(|(_, val)| expr_references_symbol(val, sym))
        }
        Expr::NewVariant { fields, .. } => {
            fields.iter().any(|(_, val)| expr_references_symbol(val, sym))
        }
        Expr::InterpolatedString(parts) => {
            parts.iter().any(|part| {
                if let StringPart::Expr { value, .. } = part {
                    expr_references_symbol(value, sym)
                } else {
                    false
                }
            })
        }
        Expr::Call { args, .. } => args.iter().any(|a| expr_references_symbol(a, sym)),
        Expr::CallExpr { callee, args } => {
            expr_references_symbol(callee, sym) ||
            args.iter().any(|a| expr_references_symbol(a, sym))
        }
        // Conservative for opaque expressions
        Expr::Closure { .. } | Expr::Escape { .. } => true,
    }
}

/// Build the fused Repeat loop. Replaces each `Push val to temp` in the producer
/// body with `Let pattern_var = val. <consumer body>`.
fn build_fused_repeat<'a>(
    producer: &Stmt<'a>,
    temp_sym: Symbol,
    pattern_var: Symbol,
    consumer_body: Block<'a>,
    _expr_arena: &'a Arena<Expr<'a>>,
    stmt_arena: &'a Arena<Stmt<'a>>,
) -> Option<Stmt<'a>> {
    match producer {
        Stmt::Repeat { pattern, iterable, body } => {
            let new_body = replace_pushes(
                body, temp_sym, pattern_var, consumer_body, stmt_arena,
            );
            Some(Stmt::Repeat {
                pattern: pattern.clone(),
                iterable,
                body: stmt_arena.alloc_slice(new_body),
            })
        }
        _ => None,
    }
}

/// In a block, replace each `Push val to temp` with
/// `Let pattern_var = val. <consumer_body>`.
/// Recurses into If branches to handle filter patterns.
fn replace_pushes<'a>(
    body: &[Stmt<'a>],
    temp_sym: Symbol,
    pattern_var: Symbol,
    consumer_body: Block<'a>,
    stmt_arena: &'a Arena<Stmt<'a>>,
) -> Vec<Stmt<'a>> {
    let mut result = Vec::new();
    for stmt in body {
        match stmt {
            Stmt::Push { value, collection } => {
                if let Expr::Identifier(sym) = collection {
                    if *sym == temp_sym {
                        result.push(Stmt::Let {
                            var: pattern_var,
                            ty: None,
                            value,
                            mutable: true,
                        });
                        result.extend(consumer_body.iter().cloned());
                        continue;
                    }
                }
                result.push(stmt.clone());
            }
            Stmt::If { cond, then_block, else_block } => {
                let new_then = replace_pushes(
                    then_block, temp_sym, pattern_var, consumer_body, stmt_arena,
                );
                let new_else = else_block.map(|eb| {
                    let replaced = replace_pushes(
                        eb, temp_sym, pattern_var, consumer_body, stmt_arena,
                    );
                    let b: Block = stmt_arena.alloc_slice(replaced);
                    b
                });
                result.push(Stmt::If {
                    cond,
                    then_block: stmt_arena.alloc_slice(new_then),
                    else_block: new_else,
                });
            }
            other => result.push(other.clone()),
        }
    }
    result
}

/// Check if the fused result still contains pushes to temp (incomplete replacement).
fn fused_still_pushes_to(stmt: &Stmt, temp_sym: Symbol) -> bool {
    match stmt {
        Stmt::Repeat { body, .. } => block_pushes_to(body, temp_sym),
        _ => false,
    }
}