Skip to main content

logicaffeine_compile/codegen/
context.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3
4use crate::ast::logic::LogicExpr;
5use crate::ast::stmt::Stmt;
6use crate::intern::{Interner, Symbol};
7
8use super::{codegen_assertion, codegen_expr};
9
10// =============================================================================
11// Refinement Type Enforcement
12// =============================================================================
13
14/// Tracks refinement type constraints across scopes for mutation enforcement.
15///
16/// When a variable with a refinement type is defined, its constraint is registered
17/// in the current scope. When that variable is mutated via `Set`, the assertion is
18/// re-emitted to ensure the invariant is preserved.
19///
20/// # Scope Management
21///
22/// The context maintains a stack of scopes to handle nested blocks:
23///
24/// ```text
25/// ┌─────────────────────────────┐
26/// │ Global Scope               │ ← x: { it > 0 }
27/// │  ┌──────────────────────┐  │
28/// │  │ Zone Scope           │  │ ← y: { it < 100 }
29/// │  │  ┌────────────────┐  │  │
30/// │  │  │ If Block Scope │  │  │ ← z: { it != 0 }
31/// │  │  └────────────────┘  │  │
32/// │  └──────────────────────┘  │
33/// └─────────────────────────────┘
34/// ```
35///
36/// # Variable Type Tracking
37///
38/// The context also tracks variable types for capability resolution. This allows
39/// statements like `Check that user can publish the document` to resolve "the document"
40/// to a variable named `doc` of type `Document`.
41pub struct RefinementContext<'a> {
42    /// Stack of scopes. Each scope maps variable Symbol to (bound_var, predicate).
43    scopes: Vec<HashMap<Symbol, (Symbol, &'a LogicExpr<'a>)>>,
44
45    /// Maps variable name Symbol to Rust type name (for capability resolution and optimization).
46    variable_types: HashMap<Symbol, String>,
47
48    /// The program's top-level function bodies, for the SIMD-reduce lifter (`simd_reduce::try_plan`)
49    /// to inline liftable transcendentals into an AVX2 kernel. Populated per-function from `all_stmts`.
50    simd_fns: crate::codegen::simd_reduce::FnMap<'a>,
51
52    /// Tracks variables that are known to be String type.
53    /// Used for proper string concatenation codegen (format! vs +).
54    string_vars: HashSet<Symbol>,
55
56    /// Maps function Symbol to its return type string.
57    /// Used to infer variable types from function call results.
58    fn_returns: HashMap<Symbol, String>,
59
60    /// Collection variables that escape the function (passed to calls, returned).
61    /// Variables NOT in this set can use Vec<T> instead of LogosSeq<T> for zero-overhead indexing.
62    escaping_vars: HashSet<Symbol>,
63
64    /// Oracle facts computed on the SAME statement slice codegen walks, so
65    /// the pointer-keyed loop alias snapshots match. Borrow hoisting reads
66    /// the distinctness queries from here; `None` (tests, unset) hoists
67    /// nothing.
68    oracle: Option<std::rc::Rc<crate::optimize::OracleFacts>>,
69
70    /// O3 scalarization: next fill index for each `[T; N]`-scalarized Seq.
71    /// Incremented as the init pushes are emitted (`x[0] = …`, `x[1] = …`).
72    array_fill_pos: HashMap<Symbol, usize>,
73
74    /// O2 de-Rc: Seq variables proven to never need reference semantics, so
75    /// they are emitted as a plain `Vec<T>` (no Rc/RefCell). The Let arm flips
76    /// the declaration; access sites then dispatch on the `Vec<T>` type.
77    de_rc_vars: HashSet<Symbol>,
78    /// Phase 4: the function being codegen'd returns an owned `Vec<T>` (not
79    /// `LogosSeq<T>`), so a `Return` of a borrowed-slice param emits `.to_vec()`
80    /// without the `LogosSeq::from_vec(...)` wrapper.
81    returns_vec: bool,
82    /// Opt::TextSliceReturn — `Some(param_index)` when the current function returns a borrowed
83    /// `&'a str` sub-slice of that Text param, so the terminal builder + `text_from_bytes(out)`
84    /// lowers to `return &s[lo-1..hi]` and the signature carries the `'a` lifetime.
85    str_slice_source: Option<usize>,
86    /// Opt::ByteSliceReturn — `Some(param_index)` when the current function returns a borrowed
87    /// `&'a [i64]` sub-slice of that `Seq of Int` param, so the terminal builder + `Return out`
88    /// lowers to `return &xs[lo-1..hi]` and the signature carries the `'a` lifetime.
89    byte_slice_source: Option<usize>,
90    /// The current function is typed `-> LogosInt` (its `Int` return can exceed i64).
91    returns_bigint: bool,
92    /// The Rust type the current function returns where it holds rationals: a `Return` of an integer returns the
93    /// rational it equals.
94    returns_rationals: Option<String>,
95
96    /// Wave-2 A1 buffer-fill conversion: reused buffers (the inner partner of a
97    /// `Set outer to inner` ping-pong swap) that are refilled by a COUNTED push
98    /// loop. They are emitted as a SIZED `Vec` (`.resize` per round, not
99    /// `Vec::new()`+`.clear()`), and the loop's `Push v to buf` becomes an
100    /// INDEXED WRITE `buf[counter] = v` — removing the per-iteration `len`
101    /// mutation that blocks vectorization of the DP scan.
102    buffer_reuse_fill: HashSet<Symbol>,
103    /// Loop-local scratch buffers whose per-iteration allocation has been
104    /// hoisted out of the enclosing `while`: the buffer is declared once
105    /// (`Vec::new()`) before the loop, and the per-iteration full-copy fill
106    /// (`buf = src[..].to_vec()`) is lowered to `buf.clear(); buf.extend_from_slice(&src[..])`
107    /// — reusing the allocation instead of mallocing/freeing each iteration.
108    /// Populated by the `Stmt::While` handler after `detect_scratch_hoist_in_body`
109    /// proves the buffer is de-Rc'd (uniquely owned), declared in the body, and
110    /// non-escaping; cleared when the loop closes.
111    scratch_hoist: HashSet<Symbol>,
112    /// Active fill loop: `(buffer, counter_name)` while emitting the body of a
113    /// counted loop that refills a `buffer_reuse_fill` buffer. The `Push`
114    /// codegen reads this to emit `buffer[counter] = v` instead of `.push(v)`.
115    fill_loop: Option<(Symbol, String)>,
116    /// Strings built by cursor-lockstep appends in a counted loop (string_search's
117    /// `text`): declared as a pre-zeroed byte buffer and written at the cursor
118    /// (`*text.as_mut_vec().get_unchecked_mut(cursor) = b`) instead of `push`,
119    /// then truncated to the cursor after the loop. Keyed by the string symbol →
120    /// the cursor variable name. See `codegen/peephole.rs::try_emit_indexed_string_build`.
121    indexed_string_builds: HashMap<Symbol, String>,
122    /// Append-only worklists (BFS/DFS frontiers) proven bounded by a monotone
123    /// visited-set guard: emitted as a pre-sized buffer + a register tail
124    /// (`q[tail]=x; tail+=1`) instead of `Vec::push` — C's exact frontier code.
125    /// Keyed by the worklist symbol; see `codegen/worklist.rs`.
126    worklists: HashMap<Symbol, super::worklist::WorklistInfo>,
127    /// Affine read-only arrays (CSR offset arrays): a Seq built `push f(i) to A`
128    /// with affine `f`, IV from 0 step 1, never mutated after. Deleted entirely;
129    /// every `item k of A` becomes `coeff*(k-1)+offset` and `length of A` the
130    /// trip count. Keyed by the array symbol; see `codegen/affine_array.rs`.
131    affine_arrays: HashMap<Symbol, super::affine_array::AffineArrayInfo>,
132    /// Constant-table locals kept but emitted as stack arrays `[T; N]` (zero heap,
133    /// direct index) instead of a per-call `Vec`. See `codegen/affine_array.rs`.
134    const_tables: HashMap<Symbol, super::affine_array::ConstTableInfo>,
135    /// Fixed-size, non-escaping scratch buffers built by a constant-trip fill loop,
136    /// emitted in place as `[T; N]` via `from_fn` instead of a per-entry `Vec`. See
137    /// `codegen/affine_array.rs::detect_scratch_buffers`.
138    scratch_buffers: HashMap<Symbol, super::affine_array::ScratchInfo>,
139    /// Zero-init fixed-size buffers mutated by indexed writes (`Set item i of buf`),
140    /// emitted as a `[T; N]` stack array (`[0; N]` + indexed stores). See
141    /// `codegen/affine_array.rs::detect_indexed_buffers`.
142    indexed_buffers: HashMap<Symbol, super::affine_array::IndexedBufInfo>,
143    /// LOOP-built `[T; N]` return buffers (the digest): symbol → RUNTIME fill-cursor variable name. The
144    /// `Let` declares `[0; N]` + the cursor; each `Push` becomes `out[cursor]=v; cursor+=1`.
145    loop_fill_arrays: HashMap<Symbol, String>,
146    /// `Seq of Int` sequences proven to hold only `i32`-range values → stored as
147    /// `Vec<i32>` (half the footprint). Keyed by the sequence symbol; carries any
148    /// runtime guard (`% m` divisor bound). See `codegen/narrow.rs`. Gated by
149    /// `LOGOS_NARROW`, so empty unless that flag is set.
150    narrowed: HashMap<Symbol, super::narrow::NarrowInfo>,
151    /// `Seq of Bool` locals held one bit per item (`LogosBits`). See `codegen/bits.rs`.
152    bitpacked: HashSet<Symbol>,
153
154    /// Non-aliased local `Map of Int to Int` variables proven safe to lower to
155    /// the specialized open-addressing `LogosI64Map` (no `Rc<RefCell>`, no
156    /// clone) instead of `LogosMap<i64, i64>`; see `codegen/i64_map.rs`.
157    i64_maps: HashSet<Symbol>,
158    /// The subset of `i64_maps` whose value is never read (`contains` + `insert`
159    /// only) — lowered to the keys-only `LogosI64Set` instead of `LogosI64Map`.
160    i64_sets: HashSet<Symbol>,
161    /// The subset of `i64_maps` whose key domain is PROVEN bounded within the
162    /// map's `with capacity` hint → lowered to a direct-addressed flat array
163    /// (`LogosDenseI64Map`/`…NoPresence`/`LogosDenseI64Set`). Carries the proven
164    /// window offset `lo` and which representation to emit; see the dense gate in
165    /// `codegen/i64_map.rs`. Empty unless that gate fires (and it can be forced off
166    /// with `LOGOS_DENSE_MAP=0`).
167    dense_i64: HashMap<Symbol, super::i64_map::DenseMapInfo>,
168    /// Non-dense `Map of Int to Int` locals whose keys+values provably fit i32 →
169    /// lowered to the half-width `LogosI32Map` / quarter-width `LogosI32Set`. A
170    /// memory-traffic fallback for hash maps the dense gate cannot capture; empty
171    /// unless the narrowing gate fires (forced off with `LOGOS_NARROW_MAP=0`).
172    i32_maps: HashSet<Symbol>,
173    i32_sets: HashSet<Symbol>,
174    /// Push-built de-Rc Vecs that should be declared `Vec::with_capacity(cap)`
175    /// rather than `Vec::new()` — keyed `sym -> capacity expr` — because a later
176    /// counted loop index-reads them up to a proven bound (so growth reallocs
177    /// are pure overhead C avoids by sizing the buffer exactly).
178    vec_presize: HashMap<Symbol, String>,
179    /// Loop-invariant positive divisors lowered to a precomputed `LogosDivU64`
180    /// magic multiply — keyed `divisor sym -> helper variable name`. The `% n` /
181    /// `/ n` sites read this to emit `helper.rem(..)` / `helper.div(..)` instead
182    /// of a hardware division (O9 libdivide).
183    fast_div: HashMap<Symbol, String>,
184    /// Integer variables whose assignments can overflow `i64` (a bignum constant,
185    /// a promotable-derived value, or a multiplicative/doubling accumulator) — the
186    /// `Let`/`Set` emitter stores these as the overflow-promoting `LogosInt` rather
187    /// than a bare `i64`. Computed once per body by `bigint_promote`.
188    promotable_int_candidates: HashSet<Symbol>,
189    /// The bindings an exact join holds as rationals, with the Rust type each is declared ([`super::rational::joins`]):
190    /// the `Let`, `Set`, push and item-store emitters convert each integer they store into one.
191    rational_joins: HashMap<Symbol, String>,
192}
193
194impl<'a> RefinementContext<'a> {
195    pub fn new() -> Self {
196        Self {
197            scopes: vec![HashMap::new()],
198            variable_types: HashMap::new(),
199            simd_fns: crate::codegen::simd_reduce::FnMap::new(),
200            string_vars: HashSet::new(),
201            escaping_vars: HashSet::new(),
202            fn_returns: HashMap::new(),
203            oracle: None,
204            array_fill_pos: HashMap::new(),
205            de_rc_vars: HashSet::new(),
206            returns_vec: false,
207            str_slice_source: None,
208            byte_slice_source: None,
209            returns_bigint: false,
210            returns_rationals: None,
211            buffer_reuse_fill: HashSet::new(),
212            scratch_hoist: HashSet::new(),
213            fill_loop: None,
214            indexed_string_builds: HashMap::new(),
215            worklists: HashMap::new(),
216            affine_arrays: HashMap::new(),
217            const_tables: HashMap::new(),
218            scratch_buffers: HashMap::new(),
219            indexed_buffers: HashMap::new(),
220            loop_fill_arrays: HashMap::new(),
221            narrowed: HashMap::new(),
222            bitpacked: HashSet::new(),
223            i64_maps: HashSet::new(),
224            i64_sets: HashSet::new(),
225            dense_i64: HashMap::new(),
226            i32_maps: HashSet::new(),
227            i32_sets: HashSet::new(),
228            vec_presize: HashMap::new(),
229            fast_div: HashMap::new(),
230            promotable_int_candidates: HashSet::new(),
231            rational_joins: HashMap::new(),
232        }
233    }
234
235    /// Create a RefinementContext seeded from a TypeEnv.
236    pub fn from_type_env(type_env: &crate::analysis::types::TypeEnv) -> Self {
237        Self {
238            scopes: vec![HashMap::new()],
239            variable_types: type_env.to_legacy_variable_types(),
240            simd_fns: crate::codegen::simd_reduce::FnMap::new(),
241            string_vars: type_env.to_legacy_string_vars(),
242            escaping_vars: HashSet::new(),
243            fn_returns: HashMap::new(),
244            oracle: None,
245            array_fill_pos: HashMap::new(),
246            de_rc_vars: HashSet::new(),
247            returns_vec: false,
248            str_slice_source: None,
249            byte_slice_source: None,
250            returns_bigint: false,
251            returns_rationals: None,
252            buffer_reuse_fill: HashSet::new(),
253            scratch_hoist: HashSet::new(),
254            fill_loop: None,
255            indexed_string_builds: HashMap::new(),
256            worklists: HashMap::new(),
257            affine_arrays: HashMap::new(),
258            const_tables: HashMap::new(),
259            scratch_buffers: HashMap::new(),
260            indexed_buffers: HashMap::new(),
261            loop_fill_arrays: HashMap::new(),
262            narrowed: HashMap::new(),
263            bitpacked: HashSet::new(),
264            i64_maps: HashSet::new(),
265            i64_sets: HashSet::new(),
266            dense_i64: HashMap::new(),
267            i32_maps: HashSet::new(),
268            i32_sets: HashSet::new(),
269            vec_presize: HashMap::new(),
270            fast_div: HashMap::new(),
271            promotable_int_candidates: HashSet::new(),
272            rational_joins: HashMap::new(),
273        }
274    }
275
276    /// Attach the oracle fact table for borrow-hoist distinctness queries.
277    pub fn set_oracle(&mut self, oracle: std::rc::Rc<crate::optimize::OracleFacts>) {
278        self.oracle = Some(oracle);
279    }
280
281    /// The attached oracle facts, if any.
282    pub fn oracle(&self) -> Option<&crate::optimize::OracleFacts> {
283        self.oracle.as_deref()
284    }
285
286    /// Begin tracking a scalarized `[T; N]` array's fill position at 0.
287    pub(super) fn init_array_fill(&mut self, sym: Symbol) {
288        self.array_fill_pos.insert(sym, 0);
289    }
290
291    /// Return the next fill index for a scalarized array and advance it.
292    pub(super) fn next_array_fill(&mut self, sym: Symbol) -> usize {
293        let slot = self.array_fill_pos.entry(sym).or_insert(0);
294        let k = *slot;
295        *slot += 1;
296        k
297    }
298
299    /// Is this symbol a scalarized `[T; N]` array (registered with a `[` type)?
300    pub(super) fn is_scalarized_array(&self, sym: Symbol) -> bool {
301        self.variable_types
302            .get(&sym)
303            .map_or(false, |t| t.starts_with('['))
304    }
305
306    /// A1: mark a reused buffer to be filled by indexed write (not push).
307    pub(super) fn register_buffer_reuse_fill(&mut self, sym: Symbol) {
308        self.buffer_reuse_fill.insert(sym);
309    }
310
311    /// A1: is this buffer one whose counted push-refill becomes indexed writes?
312    pub(super) fn is_buffer_reuse_fill(&self, sym: Symbol) -> bool {
313        self.buffer_reuse_fill.contains(&sym)
314    }
315
316    /// Scratch-hoist: mark a loop-local buffer whose allocation was hoisted
317    /// before the enclosing `while`. Its per-iteration full-copy fill is then
318    /// lowered to `clear()` + `extend_from_slice` (reuse, not realloc).
319    pub(super) fn register_scratch_hoist(&mut self, sym: Symbol) {
320        self.scratch_hoist.insert(sym);
321    }
322
323    /// Scratch-hoist: is this buffer's allocation hoisted (refill via reuse)?
324    pub(super) fn is_scratch_hoist(&self, sym: Symbol) -> bool {
325        self.scratch_hoist.contains(&sym)
326    }
327
328    /// Scratch-hoist: stop treating `sym` as hoisted once its loop closes, so a
329    /// same-named buffer in a sibling loop is not mis-rewritten.
330    pub(super) fn clear_scratch_hoist(&mut self, sym: Symbol) {
331        self.scratch_hoist.remove(&sym);
332    }
333
334    /// A1: enter a fill loop — `Push v to buffer` inside it becomes
335    /// `buffer[counter] = v`. `counter` is the (0-based) loop counter name.
336    pub(super) fn set_fill_loop(&mut self, buffer: Symbol, counter: String) {
337        self.fill_loop = Some((buffer, counter));
338    }
339
340    /// A1: the active fill loop `(buffer, counter_name)`, if any.
341    pub(super) fn fill_loop(&self) -> Option<(Symbol, &str)> {
342        self.fill_loop.as_ref().map(|(b, c)| (*b, c.as_str()))
343    }
344
345    /// A1: leave the current fill loop.
346    pub(super) fn clear_fill_loop(&mut self) {
347        self.fill_loop = None;
348    }
349
350    /// Mark `text` as a cursor-indexed string build with the given cursor var name:
351    /// its `Set text to text + X` appends become `text[cursor] = …` writes.
352    pub(super) fn register_indexed_string_build(&mut self, text: Symbol, cursor: String) {
353        self.indexed_string_builds.insert(text, cursor);
354    }
355
356    /// The cursor variable name for a cursor-indexed string build, if `text` is one.
357    pub(super) fn indexed_string_build(&self, text: Symbol) -> Option<&str> {
358        self.indexed_string_builds.get(&text).map(String::as_str)
359    }
360
361    /// Record the recognized append-only worklists for this function body.
362    pub(super) fn set_worklists(&mut self, w: HashMap<Symbol, super::worklist::WorklistInfo>) {
363        self.worklists = w;
364    }
365
366    /// The worklist conversion for `sym` (pre-sized buffer + register tail), if
367    /// it was recognized.
368    pub(super) fn worklist(&self, sym: Symbol) -> Option<&super::worklist::WorklistInfo> {
369        self.worklists.get(&sym)
370    }
371
372    /// Record the recognized affine read-only arrays for this function body.
373    pub(super) fn set_affine_arrays(
374        &mut self,
375        a: HashMap<Symbol, super::affine_array::AffineArrayInfo>,
376    ) {
377        self.affine_arrays = a;
378    }
379
380    /// The affine-array scalarization for `sym` (deleted array + closed-form
381    /// reads), if it was recognized.
382    pub(super) fn affine_array(
383        &self,
384        sym: Symbol,
385    ) -> Option<&super::affine_array::AffineArrayInfo> {
386        self.affine_arrays.get(&sym)
387    }
388
389    /// Record the constant-table locals emitted as stack arrays `[T; N]`.
390    pub(super) fn set_const_tables(
391        &mut self,
392        c: HashMap<Symbol, super::affine_array::ConstTableInfo>,
393    ) {
394        self.const_tables = c;
395    }
396
397    /// The constant-table stack-array info for `sym`, if it was recognized.
398    pub(super) fn const_table(&self, sym: Symbol) -> Option<&super::affine_array::ConstTableInfo> {
399        self.const_tables.get(&sym)
400    }
401
402    /// Record the fixed-size scratch buffers emitted in place as `[T; N]` via `from_fn`.
403    pub(super) fn set_scratch_buffers(
404        &mut self,
405        s: HashMap<Symbol, super::affine_array::ScratchInfo>,
406    ) {
407        self.scratch_buffers = s;
408    }
409
410    /// The scratch-buffer scalarization info for `sym`, if it was recognized.
411    pub(super) fn scratch_buffer(&self, sym: Symbol) -> Option<&super::affine_array::ScratchInfo> {
412        self.scratch_buffers.get(&sym)
413    }
414
415    /// Record the zero-init indexed-write fixed-size buffers emitted as `[T; N]` stack arrays.
416    pub(super) fn set_indexed_buffers(
417        &mut self,
418        m: HashMap<Symbol, super::affine_array::IndexedBufInfo>,
419    ) {
420        self.indexed_buffers = m;
421    }
422
423    /// Is `sym` a zero-init indexed-write fixed-size buffer (`[T; N]` stack array)?
424    pub(super) fn is_indexed_buffer(&self, sym: Symbol) -> bool {
425        self.indexed_buffers.contains_key(&sym)
426    }
427
428    /// Register a loop-built `[T; N]` return buffer with its runtime fill-cursor variable name.
429    pub(super) fn set_loop_fill_array(&mut self, sym: Symbol, counter: String) {
430        self.loop_fill_arrays.insert(sym, counter);
431    }
432
433    /// The runtime fill-cursor variable name for `sym`, if it is a loop-built `[T; N]` return buffer.
434    pub(super) fn loop_fill_cursor(&self, sym: Symbol) -> Option<&str> {
435        self.loop_fill_arrays.get(&sym).map(|s| s.as_str())
436    }
437
438    /// Record the `Seq of Int` sequences narrowed to `Vec<i32>`.
439    pub(super) fn set_narrowed(&mut self, n: HashMap<Symbol, super::narrow::NarrowInfo>) {
440        self.narrowed = n;
441    }
442
443    /// Record the `Seq of Bool` locals held one bit per item.
444    pub(super) fn set_bitpacked(&mut self, b: HashSet<Symbol>) {
445        self.bitpacked = b;
446    }
447
448    /// Whether `sym` is a `LogosBits`, one bit per item.
449    pub(super) fn is_bitpacked(&self, sym: Symbol) -> bool {
450        self.bitpacked.contains(&sym)
451    }
452
453    /// Whether `sym` is stored as `Vec<i32>` (loads sign-extend, stores truncate).
454    pub(super) fn is_narrowed(&self, sym: Symbol) -> bool {
455        self.narrowed.contains_key(&sym)
456    }
457
458    /// The runtime guards `sym`'s narrowing depends on (asserted at its decl).
459    pub(super) fn narrow_guards(&self, sym: Symbol) -> &[String] {
460        self.narrowed
461            .get(&sym)
462            .map(|i| i.guards.as_slice())
463            .unwrap_or(&[])
464    }
465
466    /// Record the `Map of Int to Int` locals lowered to `LogosI64Map`.
467    pub(super) fn set_i64_maps(&mut self, m: HashSet<Symbol>) {
468        self.i64_maps = m;
469    }
470
471    /// Record the subset lowered to the keys-only `LogosI64Set` (value unread).
472    pub(super) fn set_i64_sets(&mut self, s: HashSet<Symbol>) {
473        self.i64_sets = s;
474    }
475
476    /// Is this Map variable lowered to the specialized `LogosI64Map`
477    /// (open-addressing, no Rc/RefCell)?
478    pub(super) fn is_i64_map(&self, sym: Symbol) -> bool {
479        self.i64_maps.contains(&sym)
480    }
481
482    /// Is this Map variable lowered to the keys-only `LogosI64Set`?
483    pub(super) fn is_i64_set(&self, sym: Symbol) -> bool {
484        self.i64_sets.contains(&sym)
485    }
486
487    /// Record the `Map of Int to Int` locals proven dense (direct-addressed
488    /// array), keyed `sym -> {lo, kind}`. These are a subset of `i64_maps`.
489    pub(super) fn set_dense_i64(&mut self, m: HashMap<Symbol, super::i64_map::DenseMapInfo>) {
490        self.dense_i64 = m;
491    }
492
493    /// Which dense representation this Map variable lowers to, if any.
494    pub(super) fn dense_kind(&self, sym: Symbol) -> Option<super::i64_map::DenseKind> {
495        self.dense_i64.get(&sym).map(|i| i.kind)
496    }
497
498    /// The proven dense window info (`lo`, `kind`) for this Map variable, if any.
499    pub(super) fn dense_info(&self, sym: Symbol) -> Option<super::i64_map::DenseMapInfo> {
500        self.dense_i64.get(&sym).copied()
501    }
502
503    /// Record the non-dense `Map of Int to Int` locals narrowed to i32 storage,
504    /// split into value-read maps (`LogosI32Map`) and keys-only sets (`LogosI32Set`).
505    pub(super) fn set_i32_maps(&mut self, maps: HashSet<Symbol>, sets: HashSet<Symbol>) {
506        self.i32_maps = maps;
507        self.i32_sets = sets;
508    }
509
510    /// Is this Map variable lowered to the i32-narrowed `LogosI32Map`?
511    pub(super) fn is_i32_map(&self, sym: Symbol) -> bool {
512        self.i32_maps.contains(&sym)
513    }
514
515    /// Is this Map variable lowered to the i32-narrowed keys-only `LogosI32Set`?
516    pub(super) fn is_i32_set(&self, sym: Symbol) -> bool {
517        self.i32_sets.contains(&sym)
518    }
519
520    /// Record the push-built Vecs to pre-size (`sym -> capacity expr`).
521    pub(super) fn set_vec_presize(&mut self, m: HashMap<Symbol, String>) {
522        self.vec_presize = m;
523    }
524
525    /// The `with_capacity` argument for a push-built de-Rc Vec, if it is
526    /// index-read up to a proven bound (else `None` → plain `Vec::new()`).
527    pub(super) fn get_vec_presize(&self, sym: Symbol) -> Option<&String> {
528        self.vec_presize.get(&sym)
529    }
530
531    /// Record the loop-invariant positive divisors to lower to `LogosDivU64`
532    /// (`divisor sym -> helper variable name`).
533    pub(super) fn set_fast_div(&mut self, m: HashMap<Symbol, String>) {
534        self.fast_div = m;
535    }
536
537    /// The whole `divisor sym -> helper name` map, threaded into expression
538    /// codegen so each `% n` / `/ n` site can emit the magic multiply.
539    pub(super) fn get_fast_div(&self) -> &HashMap<Symbol, String> {
540        &self.fast_div
541    }
542
543    /// Set the de-Rc'd Seq variables (emitted as plain `Vec<T>`).
544    pub fn set_de_rc_vars(&mut self, vars: HashSet<Symbol>) {
545        self.de_rc_vars = vars;
546    }
547
548    /// Phase 4: mark that the current function returns an owned `Vec<T>`.
549    pub fn set_returns_vec(&mut self, v: bool) {
550        self.returns_vec = v;
551    }
552
553    /// Does the current function return an owned `Vec<T>` (Phase 4)?
554    pub(super) fn returns_vec(&self) -> bool {
555        self.returns_vec
556    }
557
558    /// Opt::TextSliceReturn — record the borrowed Text param index this fn returns a slice of.
559    pub fn set_str_slice_source(&mut self, src: Option<usize>) {
560        self.str_slice_source = src;
561    }
562
563    /// The param index this fn returns a `&'a str` sub-slice of, if any (Opt::TextSliceReturn).
564    pub(super) fn str_slice_source(&self) -> Option<usize> {
565        self.str_slice_source
566    }
567
568    pub fn set_byte_slice_source(&mut self, src: Option<usize>) {
569        self.byte_slice_source = src;
570    }
571
572    /// The param index this fn returns a `&'a [i64]` sub-slice of, if any (Opt::ByteSliceReturn).
573    pub(super) fn byte_slice_source(&self) -> Option<usize> {
574        self.byte_slice_source
575    }
576
577    /// Mark that the current function returns an overflow-promoting `LogosInt`
578    /// (its `Int` return can exceed i64), so `Return` emits an un-narrowed value.
579    pub(super) fn set_returns_bigint(&mut self, v: bool) {
580        self.returns_bigint = v;
581    }
582
583    /// Mark the current function as returning `ty`, a type that holds rationals.
584    pub(super) fn set_returns_rationals(&mut self, ty: Option<String>) {
585        self.returns_rationals = ty;
586    }
587
588    /// The Rust type the current function returns where it holds rationals.
589    pub(super) fn returns_rationals(&self) -> Option<&String> {
590        self.returns_rationals.as_ref()
591    }
592
593    /// Does the current function return a `LogosInt`?
594    pub(super) fn returns_bigint(&self) -> bool {
595        self.returns_bigint
596    }
597
598    /// Is this Seq variable de-Rc'd to a plain `Vec<T>` (no Rc/RefCell)?
599    pub(super) fn is_de_rc(&self, sym: Symbol) -> bool {
600        self.de_rc_vars.contains(&sym)
601    }
602
603    /// Seed the set of integer variables whose assignments can overflow `i64`
604    /// (computed by `bigint_promote::promotable_int_vars`). The `Let` emitter
605    /// promotes such a variable to `LogosInt` when its initializer is integer.
606    pub(super) fn set_promotable_candidates(&mut self, vars: HashSet<Symbol>) {
607        self.promotable_int_candidates = vars;
608    }
609
610    /// Is this variable a promotion candidate (overflow-capable integer)?
611    pub(super) fn is_promotable_candidate(&self, sym: Symbol) -> bool {
612        self.promotable_int_candidates.contains(&sym)
613    }
614
615    /// Hold the scope's exactly joined bindings as rationals: each is declared its joined type, which holds every
616    /// integer it is given whole, so none is an overflow-promoting integer as well.
617    pub(super) fn set_rational_joins(&mut self, joins: HashMap<Symbol, String>) {
618        for (sym, ty) in &joins {
619            self.promotable_int_candidates.remove(sym);
620            self.variable_types.insert(*sym, ty.clone());
621        }
622        self.rational_joins = joins;
623    }
624
625    /// The Rust type an exact join holds `sym` as.
626    pub(super) fn rational_join(&self, sym: Symbol) -> Option<&String> {
627        self.rational_joins.get(&sym)
628    }
629
630    /// Is this variable currently stored as the overflow-promoting `LogosInt`
631    /// (registered with the `|__bigint` sentinel)?
632    pub(super) fn is_bigint_var(&self, sym: Symbol) -> bool {
633        self.variable_types
634            .get(&sym)
635            .map_or(false, |t| t.contains("__bigint"))
636    }
637
638    /// Set the escaping vars for local Vec optimization.
639    pub fn set_escaping_vars(&mut self, vars: HashSet<Symbol>) {
640        self.escaping_vars = vars;
641    }
642
643    pub(super) fn set_simd_fns(&mut self, fns: crate::codegen::simd_reduce::FnMap<'a>) {
644        self.simd_fns = fns;
645    }
646
647    pub(super) fn simd_fns(&self) -> &crate::codegen::simd_reduce::FnMap<'a> {
648        &self.simd_fns
649    }
650
651    /// Check if a variable escapes (and thus must remain LogosSeq).
652    pub fn var_escapes(&self, sym: &Symbol) -> bool {
653        self.escaping_vars.contains(sym)
654    }
655
656    /// Register a function's return type.
657    pub fn register_fn_return(&mut self, fn_sym: Symbol, return_type: String) {
658        self.fn_returns.insert(fn_sym, return_type);
659    }
660
661    /// Get a function's return type.
662    pub fn get_fn_return(&self, fn_sym: &Symbol) -> Option<&String> {
663        self.fn_returns.get(fn_sym)
664    }
665
666    pub(super) fn push_scope(&mut self) {
667        self.scopes.push(HashMap::new());
668    }
669
670    pub(super) fn pop_scope(&mut self) {
671        self.scopes.pop();
672    }
673
674    /// Register a variable as having String type.
675    pub(super) fn register_string_var(&mut self, var: Symbol) {
676        self.string_vars.insert(var);
677    }
678
679    /// Check if a variable is known to be a String.
680    pub(super) fn is_string_var(&self, var: Symbol) -> bool {
681        self.string_vars.contains(&var)
682    }
683
684    /// Get a reference to the string_vars set for expression codegen.
685    pub(super) fn get_string_vars(&self) -> &HashSet<Symbol> {
686        &self.string_vars
687    }
688
689    pub(super) fn register(
690        &mut self,
691        var: Symbol,
692        bound_var: Symbol,
693        predicate: &'a LogicExpr<'a>,
694    ) {
695        if let Some(scope) = self.scopes.last_mut() {
696            scope.insert(var, (bound_var, predicate));
697        }
698    }
699
700    pub(super) fn get_constraint(&self, var: Symbol) -> Option<(Symbol, &'a LogicExpr<'a>)> {
701        for scope in self.scopes.iter().rev() {
702            if let Some(entry) = scope.get(&var) {
703                return Some(*entry);
704            }
705        }
706        None
707    }
708
709    /// Register a variable with its type for capability resolution.
710    pub(super) fn register_variable_type(&mut self, var: Symbol, type_name: String) {
711        self.variable_types.insert(var, type_name);
712    }
713
714    /// Get variable type map for expression codegen optimization.
715    pub(super) fn get_variable_types(&self) -> &HashMap<Symbol, String> {
716        &self.variable_types
717    }
718
719    /// Get mutable variable type map for restoring types after hoisting scope.
720    pub(super) fn get_variable_types_mut(&mut self) -> &mut HashMap<Symbol, String> {
721        &mut self.variable_types
722    }
723
724    /// Find a variable name by its type (for resolving "the document" to "doc").
725    pub(super) fn find_variable_by_type(
726        &self,
727        type_name: &str,
728        interner: &Interner,
729    ) -> Option<String> {
730        let type_lower = type_name.to_lowercase();
731        for (var_sym, var_type) in &self.variable_types {
732            if var_type.to_lowercase() == type_lower {
733                return Some(interner.resolve(*var_sym).to_string());
734            }
735        }
736        None
737    }
738}
739
740/// Emits a debug_assert for a refinement predicate, substituting the bound variable.
741pub(super) fn emit_refinement_check(
742    var_name: &str,
743    bound_var: Symbol,
744    predicate: &LogicExpr,
745    interner: &Interner,
746    indent_str: &str,
747    output: &mut String,
748) {
749    let assertion = codegen_assertion(predicate, interner);
750    let bound = interner.resolve(bound_var);
751    let check = if bound == var_name {
752        assertion
753    } else {
754        replace_word(&assertion, bound, var_name)
755    };
756    writeln!(output, "{}debug_assert!({});", indent_str, check).unwrap();
757}
758
759/// Word-boundary replacement to substitute bound variable with actual variable.
760pub(super) fn replace_word(text: &str, from: &str, to: &str) -> String {
761    let mut result = String::with_capacity(text.len());
762    let mut word = String::new();
763    for c in text.chars() {
764        if c.is_alphanumeric() || c == '_' {
765            word.push(c);
766        } else {
767            if !word.is_empty() {
768                result.push_str(if word == from { to } else { &word });
769                word.clear();
770            }
771            result.push(c);
772        }
773    }
774    if !word.is_empty() {
775        result.push_str(if word == from { to } else { &word });
776    }
777    result
778}
779
780// =============================================================================
781// Mount+Sync Detection for Distributed<T>
782// =============================================================================
783
784/// Tracks which variables have Mount and/or Sync statements.
785///
786/// This is used to detect when a variable needs `Distributed<T>` instead of
787/// separate persistence and synchronization wrappers. A variable that is both
788/// mounted and synced can use the unified `Distributed<T>` type.
789///
790/// # Detection Flow
791///
792/// ```text
793/// Pre-scan all statements
794///       ↓
795/// Found "Mount x at path"  →  x.mounted = true, x.mount_path = Some(path)
796/// Found "Sync x on topic"  →  x.synced = true, x.sync_topic = Some(topic)
797///       ↓
798/// If x.mounted && x.synced  →  Use Distributed<T> with both
799/// ```
800#[derive(Debug, Default)]
801pub struct VariableCapabilities {
802    /// Variable has a Mount statement (persistence).
803    pub(super) mounted: bool,
804    /// Variable has a Sync statement (network synchronization).
805    pub(super) synced: bool,
806    /// Path expression for Mount (as generated code string).
807    pub(super) mount_path: Option<String>,
808    /// Topic expression for Sync (as generated code string).
809    pub(super) sync_topic: Option<String>,
810}
811
812/// Helper to create an empty VariableCapabilities map (for tests).
813pub fn empty_var_caps() -> HashMap<Symbol, VariableCapabilities> {
814    HashMap::new()
815}
816
817/// Pre-scan statements to detect variables that have both Mount and Sync.
818/// Returns a map from variable Symbol to its capabilities.
819pub(super) fn analyze_variable_capabilities<'a>(
820    stmts: &[Stmt<'a>],
821    interner: &Interner,
822) -> HashMap<Symbol, VariableCapabilities> {
823    let mut caps: HashMap<Symbol, VariableCapabilities> = HashMap::new();
824    let empty_synced = HashSet::new();
825
826    for stmt in stmts {
827        match stmt {
828            Stmt::Mount { var, path } => {
829                let entry = caps.entry(*var).or_default();
830                entry.mounted = true;
831                entry.mount_path = Some(codegen_expr(path, interner, &empty_synced));
832            }
833            Stmt::Sync { var, topic } => {
834                let entry = caps.entry(*var).or_default();
835                entry.synced = true;
836                entry.sync_topic = Some(codegen_expr(topic, interner, &empty_synced));
837            }
838            // Recursively check nested blocks (Block<'a> is &[Stmt<'a>])
839            Stmt::If {
840                then_block,
841                else_block,
842                ..
843            } => {
844                let nested = analyze_variable_capabilities(then_block, interner);
845                for (var, cap) in nested {
846                    let entry = caps.entry(var).or_default();
847                    if cap.mounted {
848                        entry.mounted = true;
849                        entry.mount_path = cap.mount_path;
850                    }
851                    if cap.synced {
852                        entry.synced = true;
853                        entry.sync_topic = cap.sync_topic;
854                    }
855                }
856                if let Some(else_b) = else_block {
857                    let nested = analyze_variable_capabilities(else_b, interner);
858                    for (var, cap) in nested {
859                        let entry = caps.entry(var).or_default();
860                        if cap.mounted {
861                            entry.mounted = true;
862                            entry.mount_path = cap.mount_path;
863                        }
864                        if cap.synced {
865                            entry.synced = true;
866                            entry.sync_topic = cap.sync_topic;
867                        }
868                    }
869                }
870            }
871            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
872                let nested = analyze_variable_capabilities(body, interner);
873                for (var, cap) in nested {
874                    let entry = caps.entry(var).or_default();
875                    if cap.mounted {
876                        entry.mounted = true;
877                        entry.mount_path = cap.mount_path;
878                    }
879                    if cap.synced {
880                        entry.synced = true;
881                        entry.sync_topic = cap.sync_topic;
882                    }
883                }
884            }
885            _ => {}
886        }
887    }
888
889    caps
890}