logicaffeine_compile/codegen/hoist.rs
1//! O1 — borrow hoisting (scoped slice extraction).
2//!
3//! A loop body that indexes `LogosSeq` handles pays one `RefCell` flag
4//! operation per access. When the handles provably keep their identity for
5//! the whole loop, the borrow moves to a scope around the loop and the body
6//! indexes plain slices:
7//!
8//! ```text
9//! {
10//! let __prev_g = prev.borrow();
11//! let prev = &__prev_g[..];
12//! let mut __curr_g = curr.borrow_mut();
13//! let curr = &mut __curr_g[..];
14//! for w in 0..n { curr[w as usize] = prev[w as usize]; }
15//! }
16//! ```
17//!
18//! Shadowing the original name and flipping its tracked type to `&[T]` /
19//! `&mut [T]` means every existing emission path (indexing, SetIndex, swap
20//! fusion, zero-based lowering, length) works unchanged through its slice
21//! arms.
22//!
23//! SOUNDNESS. A mut-hoisted handle holds a `RefMut` across the whole loop;
24//! a shared-hoisted handle holds a `Ref`. Any other access to the same
25//! allocation while one is held panics at runtime. A handle is therefore
26//! hoisted only when ALL of these hold:
27//!
28//! - its tracked type is `LogosSeq<T>` (Maps, Strings, zone arenas, and
29//! already-sliced params are out);
30//! - the body neither rebinds, redeclares, resizes, nor pops it;
31//! - it never appears as a bare value (pushed into a container, passed to
32//! a call, given away, shown whole, interpolated, field-stored);
33//! - the body contains no calls and no opaque/concurrent statements
34//! (anything could touch any handle behind them);
35//! - the alias oracle PROVES it distinct, at this loop's invariant, from
36//! every other handle the loop touches (for mut hoists), or from every
37//! handle the loop mutates (for shared hoists). Read-read aliasing is
38//! RefCell-legal and allowed.
39//!
40//! Refusal is always the default: no oracle, no snapshot, an unknown
41//! statement kind, an unknown expression kind — hoist nothing.
42//!
43//! VALUE SEMANTICS. A copy (`Let mutable b be a.`) shares `a`'s buffer until
44//! its first write, and the un-hoisted body copies-on-write before each one.
45//! The hoisted body writes through a slice or `&mut Vec` that the copy-on-write
46//! gate cannot see, so a mut hoist passes the handle through that same gate
47//! ([`emit_cow`]) before it takes the loop's `borrow_mut()`: the held borrow is
48//! on the handle's own buffer, and a `mutable` parameter still writes through
49//! to its caller.
50
51use std::collections::HashSet;
52use std::fmt::Write;
53
54use crate::analysis::types::RustNames;
55use crate::ast::stmt::{Expr, Stmt};
56use crate::intern::{Interner, Symbol};
57
58use super::context::RefinementContext;
59use super::peephole::body_modifies_var;
60use super::stmt::emit_cow;
61
62thread_local! {
63 /// Per-thread test override for the borrow-hoist kill switch. Tests set
64 /// this on their own thread (race-free), unlike the process-global
65 /// `LOGOS_HOIST` env var.
66 static FORCE_DISABLE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
67}
68
69/// Force borrow hoisting off (or back on) for the current thread only.
70/// Used by tests to verify the kill switch without the env-var data race.
71pub fn force_disable_for_test(disabled: bool) {
72 FORCE_DISABLE.with(|c| c.set(disabled));
73}
74
75/// Is borrow hoisting disabled? True when the thread-local test override is
76/// set, or the operational `LOGOS_HOIST=0` env var is present.
77pub fn hoisting_disabled() -> bool {
78 FORCE_DISABLE.with(|c| c.get())
79 || !crate::optimize::active_config().is_on(crate::optimization::Opt::HoistBorrows)
80}
81
82/// Could a value of this tracked type share a Seq's `Rc<RefCell>` — i.e.
83/// could it conflict with a hoisted Seq borrow? Only Seq-shaped types can;
84/// known scalars, strings, and maps cannot. Unknown types are treated
85/// conservatively as "could" so an untyped handle never escapes the check.
86fn could_alias_seq(ty: Option<&String>) -> bool {
87 let t = match ty {
88 Some(t) => t,
89 None => return true,
90 };
91 let base = t.split("|__hl:").next().unwrap_or(t.as_str());
92 let definitely_not = matches!(
93 base,
94 "i64"
95 | "f64"
96 | "bool"
97 | "char"
98 | "u8"
99 | "usize"
100 | "i32"
101 | "u64"
102 | "String"
103 | "&str"
104 | "()"
105 | "__zero_based_i64"
106 | "__single_char_u8"
107 ) || base.starts_with("LogosMap")
108 || base.starts_with("LogosI64Map")
109 || base.starts_with("LogosI64Set")
110 || base.starts_with("HashMap")
111 || base.starts_with("FxHashMap")
112 || base.starts_with("std::collections::HashMap")
113 || base.starts_with("rustc_hash::FxHashMap");
114 !definitely_not
115}
116
117/// How a handle is hoisted out of the loop.
118#[derive(Clone, Copy, PartialEq)]
119pub(crate) enum HoistKind {
120 /// Read-only: `let __g = x.borrow(); let x = &__g[..];` (`&[T]`).
121 Shared,
122 /// Indexed read/write, never resized: `&mut __g[..]` (`&mut [T]`).
123 MutSlice,
124 /// Resized (pushed/popped): hold the `RefMut` as a `&mut Vec` so push
125 /// goes through it — `let mut __g = x.borrow_mut(); let x = &mut *__g;`.
126 MutVec,
127}
128
129/// One handle's hoist decision.
130pub(crate) struct HoistEntry {
131 pub sym: Symbol,
132 pub kind: HoistKind,
133 pub elem_ty: String,
134 pub old_type: String,
135 /// True for a de-Rc'd `Vec<T>`: extract the noalias slice WITHOUT a
136 /// `.borrow()` (there is no `RefCell`). The slice still matters — it hands
137 /// LLVM the same `&[T]`/`&mut [T]` noalias the LogosSeq path gives, which
138 /// is what unlocks bounds-check elision and vectorization.
139 pub is_vec: bool,
140}
141
142/// A pure scalar builtin that maps to a Rust method call (sqrt, abs, …) —
143/// takes scalars, returns a scalar, never touches a Seq's `RefCell`. The
144/// name+arity pairs mirror the dispatch in codegen/expr.rs, so a body that
145/// only calls these can still be hoisted. Anything else is opaque and bails.
146fn is_pure_scalar_builtin(name: &str, argc: usize) -> bool {
147 matches!(
148 (name, argc),
149 ("sqrt", 1)
150 | ("abs", 1)
151 | ("conjugate", 1)
152 | ("re", 1)
153 | ("im", 1)
154 | ("floor", 1)
155 | ("ceil", 1)
156 | ("round", 1)
157 | ("pow", 2)
158 | ("min", 2)
159 | ("max", 2)
160 )
161}
162
163struct AccessRoles<'i> {
164 /// Read through a collection position (Index/Slice/Length/Contains).
165 read: HashSet<Symbol>,
166 /// Written through SetIndex.
167 written: HashSet<Symbol>,
168 /// Resized in place (Push/Pop/Add/Remove collection target). Hoistable
169 /// as a held `&mut Vec` (push goes through the RefMut) when not also
170 /// leaked.
171 resized: HashSet<Symbol>,
172 /// Leaked: bare-value uses, call args, whole-handle Show/Give/Return,
173 /// pushed-as-a-value into another collection, Repeat iterables. Never
174 /// hoistable; mut-hoists must be proven distinct from these too.
175 other: HashSet<Symbol>,
176 /// Symbols (re)bound inside the body: `Let`, `Pop into`, Repeat
177 /// patterns, Inspect bindings. A guard for these would capture a stale
178 /// or undeclared name.
179 rebound: HashSet<Symbol>,
180 /// Insertion order of first sighting, for deterministic emission.
181 order: Vec<Symbol>,
182 /// Something opaque appeared — hoist nothing in this loop.
183 bail: bool,
184 /// For resolving called-function names against the builtin whitelist.
185 interner: &'i Interner,
186}
187
188impl<'i> AccessRoles<'i> {
189 fn new(interner: &'i Interner) -> Self {
190 AccessRoles {
191 read: HashSet::new(),
192 written: HashSet::new(),
193 resized: HashSet::new(),
194 other: HashSet::new(),
195 rebound: HashSet::new(),
196 order: Vec::new(),
197 bail: false,
198 interner,
199 }
200 }
201
202 fn note(&mut self, sym: Symbol) {
203 if !self.order.contains(&sym) {
204 self.order.push(sym);
205 }
206 }
207 fn read(&mut self, sym: Symbol) {
208 self.note(sym);
209 self.read.insert(sym);
210 }
211 fn written(&mut self, sym: Symbol) {
212 self.note(sym);
213 self.written.insert(sym);
214 }
215 fn resized(&mut self, sym: Symbol) {
216 self.note(sym);
217 self.resized.insert(sym);
218 }
219 fn other(&mut self, sym: Symbol) {
220 self.note(sym);
221 self.other.insert(sym);
222 }
223}
224
225/// Walk an expression in VALUE position: collection positions of the
226/// indexing forms count as reads; any bare identifier is an `other` use
227/// (it may flow anywhere); opaque forms bail.
228fn scan_value_expr(e: &Expr, roles: &mut AccessRoles) {
229 match e {
230 Expr::Identifier(s) => roles.other(*s),
231 Expr::Literal(_) | Expr::OptionNone => {}
232 Expr::Index { collection, index } => {
233 scan_collection_pos(collection, roles);
234 scan_value_expr(index, roles);
235 }
236 Expr::Slice {
237 collection,
238 start,
239 end,
240 } => {
241 scan_collection_pos(collection, roles);
242 scan_value_expr(start, roles);
243 scan_value_expr(end, roles);
244 }
245 Expr::Length { collection } => scan_collection_pos(collection, roles),
246 Expr::Contains { collection, value } => {
247 scan_collection_pos(collection, roles);
248 scan_value_expr(value, roles);
249 }
250 Expr::BinaryOp { left, right, .. } => {
251 scan_value_expr(left, roles);
252 scan_value_expr(right, roles);
253 }
254 Expr::Not { operand } => scan_value_expr(operand, roles),
255 Expr::Range { start, end } => {
256 scan_value_expr(start, roles);
257 scan_value_expr(end, roles);
258 }
259 Expr::List(items) | Expr::Tuple(items) => {
260 for it in items {
261 scan_value_expr(it, roles);
262 }
263 }
264 Expr::New { init_fields, .. } => {
265 for (_, v) in init_fields {
266 scan_value_expr(v, roles);
267 }
268 }
269 Expr::NewVariant { fields, .. } => {
270 for (_, v) in fields {
271 scan_value_expr(v, roles);
272 }
273 }
274 Expr::FieldAccess { object, .. } => scan_value_expr(object, roles),
275 Expr::Copy { expr } => scan_value_expr(expr, roles),
276 Expr::WithCapacity { value, capacity } => {
277 scan_value_expr(value, roles);
278 scan_value_expr(capacity, roles);
279 }
280 Expr::OptionSome { value } => scan_value_expr(value, roles),
281 Expr::Give { value } => scan_value_expr(value, roles),
282 Expr::InterpolatedString(parts) => {
283 for p in parts {
284 if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
285 scan_value_expr(value, roles);
286 }
287 }
288 }
289 Expr::Union { left, right } | Expr::Intersection { left, right } => {
290 scan_value_expr(left, roles);
291 scan_value_expr(right, roles);
292 }
293 Expr::Call { function, args } => {
294 // A pure scalar builtin (sqrt/abs/min/…) can't touch a Seq's
295 // RefCell — scan its args for index reads and carry on. Any
296 // other call may alias or mutate any handle: bail.
297 if is_pure_scalar_builtin(roles.interner.resolve(*function), args.len()) {
298 for a in args {
299 scan_value_expr(a, roles);
300 }
301 } else {
302 roles.bail = true;
303 }
304 }
305 // Closures, escapes, zone accessors, opaque calls — bail.
306 _ => roles.bail = true,
307 }
308}
309
310/// A collection position: a bare identifier here is a READ borrow; any
311/// other expression is scanned as a value.
312fn scan_collection_pos(e: &Expr, roles: &mut AccessRoles) {
313 if let Expr::Identifier(s) = e {
314 roles.read(*s);
315 } else {
316 scan_value_expr(e, roles);
317 }
318}
319
320fn scan_stmts(stmts: &[Stmt], roles: &mut AccessRoles) {
321 for stmt in stmts {
322 if roles.bail {
323 return;
324 }
325 match stmt {
326 Stmt::Let { var, value, .. } => {
327 roles.rebound.insert(*var);
328 scan_value_expr(value, roles);
329 }
330 Stmt::Set { target, value } => {
331 // The rebind itself is caught by body_modifies_var; the
332 // RHS may leak a handle.
333 let _ = target;
334 scan_value_expr(value, roles);
335 }
336 Stmt::SetIndex {
337 collection,
338 index,
339 value,
340 } => {
341 if let Expr::Identifier(s) = collection {
342 roles.written(*s);
343 } else {
344 scan_value_expr(collection, roles);
345 }
346 scan_value_expr(index, roles);
347 scan_value_expr(value, roles);
348 }
349 Stmt::Push { value, collection }
350 | Stmt::Add { value, collection }
351 | Stmt::Remove { value, collection } => {
352 // The pushed VALUE may leak a handle (a Seq pushed into a
353 // Seq-of-Seq escapes); the COLLECTION is resized in place.
354 scan_value_expr(value, roles);
355 if let Expr::Identifier(s) = collection {
356 roles.resized(*s);
357 } else {
358 scan_value_expr(collection, roles);
359 }
360 }
361 Stmt::Pop { collection, into } => {
362 if let Expr::Identifier(s) = collection {
363 roles.resized(*s);
364 } else {
365 scan_value_expr(collection, roles);
366 }
367 if let Some(v) = into {
368 roles.rebound.insert(*v);
369 }
370 }
371 Stmt::If {
372 cond,
373 then_block,
374 else_block,
375 } => {
376 scan_value_expr(cond, roles);
377 scan_stmts(then_block, roles);
378 if let Some(eb) = else_block {
379 scan_stmts(eb, roles);
380 }
381 }
382 Stmt::While { cond, body, .. } => {
383 scan_value_expr(cond, roles);
384 scan_stmts(body, roles);
385 }
386 Stmt::Repeat {
387 pattern,
388 iterable,
389 body,
390 } => {
391 if let Expr::Identifier(s) = iterable {
392 roles.other(*s);
393 } else {
394 scan_value_expr(iterable, roles);
395 }
396 if let crate::ast::stmt::Pattern::Identifier(s) = pattern {
397 roles.rebound.insert(*s);
398 }
399 scan_stmts(body, roles);
400 }
401 Stmt::Show { object, recipient } => {
402 // Indexed reads are fine; showing a whole handle is opaque
403 // (display borrows it in library code).
404 scan_value_expr(object, roles);
405 scan_value_expr(recipient, roles);
406 }
407 Stmt::Return { value } => {
408 if let Some(v) = value {
409 scan_value_expr(v, roles);
410 }
411 }
412 Stmt::Break => {}
413 Stmt::SetField { object, value, .. } => {
414 scan_value_expr(object, roles);
415 scan_value_expr(value, roles);
416 }
417 Stmt::Inspect { target, arms, .. } => {
418 scan_value_expr(target, roles);
419 for arm in arms {
420 for (_, binding) in &arm.bindings {
421 roles.rebound.insert(*binding);
422 }
423 scan_stmts(arm.body, roles);
424 }
425 }
426 Stmt::RuntimeAssert { condition, .. } => scan_value_expr(condition, roles),
427 // Calls, concurrency, zones, escapes, IO — opaque: bail.
428 _ => roles.bail = true,
429 }
430 }
431}
432
433/// Decide which handles to hoist around this loop. Empty when anything is
434/// uncertain.
435pub(crate) fn plan_borrow_hoist<'a>(
436 loop_stmt: &Stmt<'a>,
437 cond: Option<&Expr<'a>>,
438 body: &[Stmt<'a>],
439 ctx: &RefinementContext<'a>,
440 interner: &Interner,
441) -> Vec<HoistEntry> {
442 // The kill switch (env var or test thread-local) nulls the oracle in
443 // codegen_program, so a present oracle already means hoisting is on.
444 let oracle = match ctx.oracle() {
445 Some(o) => o,
446 None => return Vec::new(),
447 };
448
449 let mut roles = AccessRoles::new(interner);
450 if let Some(c) = cond {
451 scan_value_expr(c, &mut roles);
452 }
453 scan_stmts(body, &mut roles);
454 if roles.bail {
455 return Vec::new();
456 }
457
458 // Candidates: handles accessed through collection positions whose
459 // identity provably survives the loop. A resized (pushed/popped) handle
460 // becomes a held `&mut Vec` (MutVec); a written-but-not-resized handle a
461 // `&mut [T]` (MutSlice); a read-only handle a `&[T]` (Shared).
462 let types = ctx.get_variable_types();
463 let mut hoisted: Vec<(Symbol, HoistKind, String, String)> = Vec::new();
464 // De-Rc'd `Vec<T>` handles are owned and provably non-aliased (that is the
465 // de-Rc precondition), so they bypass the alias gating and always get the
466 // noalias slice extraction.
467 let mut derc_hoisted: Vec<(Symbol, HoistKind, String, String)> = Vec::new();
468 for sym in &roles.order {
469 let sym = *sym;
470 if roles.other.contains(&sym) || roles.rebound.contains(&sym) {
471 continue;
472 }
473 let resized = roles.resized.contains(&sym);
474 let written = roles.written.contains(&sym);
475 let read = roles.read.contains(&sym);
476 if !resized && !written && !read {
477 continue;
478 }
479 let full_ty = match types.get(&sym) {
480 Some(t) => t.clone(),
481 None => continue,
482 };
483 // A length-hoisted handle (`|__hl:` sentinel) already has a `_len`
484 // binding the loop uses; shadowing it as a slice would orphan that
485 // binding. Leave such handles per-access.
486 if full_ty.contains("|__hl:") {
487 continue;
488 }
489 let base_ty = full_ty.split("|__hl:").next().unwrap_or(&full_ty);
490 // A LogosSeq hoists with a `.borrow()`; a de-Rc'd `Vec<T>` hoists the
491 // slice directly (no borrow) — both give LLVM the noalias `&[T]`.
492 // `is_de_rc` is authoritative: the registered type string can lag a
493 // de-Rc'd decl, but the emitted variable is the `Vec`.
494 let elem_ty = if let Some(e) = base_ty
495 .strip_prefix("LogosSeq<")
496 .and_then(|s| s.strip_suffix('>'))
497 {
498 e.to_string()
499 } else if let Some(e) = base_ty
500 .strip_prefix("Vec<")
501 .and_then(|s| s.strip_suffix('>'))
502 {
503 e.to_string()
504 } else {
505 continue;
506 };
507 let is_vec = ctx.is_de_rc(sym) || base_ty.starts_with("Vec<");
508 // A rebind (`Set x to …`) inside the body makes the held borrow
509 // stale; resize (push/pop) is fine — that's exactly the MutVec case.
510 if body_modifies_var(body, sym) {
511 continue;
512 }
513 let kind = if resized {
514 HoistKind::MutVec
515 } else if written {
516 HoistKind::MutSlice
517 } else {
518 HoistKind::Shared
519 };
520 if is_vec {
521 derc_hoisted.push((sym, kind, elem_ty, full_ty));
522 } else {
523 hoisted.push((sym, kind, elem_ty, full_ty));
524 }
525 }
526
527 // Alias gating to a fixpoint: a dropped handle becomes an unhoisted
528 // per-access toucher, which can invalidate remaining ones.
529 //
530 // Only handles that could share a Seq's `Rc<RefCell>` matter — a scalar,
531 // String, or Map can never conflict with a Seq borrow, and demanding the
532 // oracle prove `arr ≠ i` for a scalar `i` would needlessly require a loop
533 // snapshot. Any REAL aliaser is Seq-typed (codegen propagates the type
534 // through `Let`/`Set`, the oracle tracks the edge), so restricting the
535 // distinctness checks to Seq-typed touched symbols is sound.
536 let all_touched: Vec<Symbol> = roles
537 .order
538 .iter()
539 .copied()
540 .filter(|s| could_alias_seq(types.get(s)))
541 .collect();
542 loop {
543 let hoisted_syms: HashSet<Symbol> = hoisted.iter().map(|(s, _, _, _)| *s).collect();
544 let mut_hoisted: Vec<Symbol> = hoisted
545 .iter()
546 .filter(|(_, k, _, _)| *k != HoistKind::Shared)
547 .map(|(s, _, _, _)| *s)
548 .collect();
549 let unhoisted_mut: Vec<Symbol> = all_touched
550 .iter()
551 .filter(|s| {
552 !hoisted_syms.contains(s)
553 && (roles.written.contains(s)
554 || roles.resized.contains(s)
555 || roles.other.contains(s))
556 })
557 .cloned()
558 .collect();
559 let keep: Vec<bool> = hoisted
560 .iter()
561 .map(|(sym, kind, _, _)| {
562 if *kind != HoistKind::Shared {
563 // A RefMut must be alone: distinct from every other
564 // touched handle, hoisted or not.
565 all_touched
566 .iter()
567 .filter(|t| **t != *sym)
568 .all(|t| oracle.loop_handles_definitely_distinct(loop_stmt, *sym, *t))
569 } else {
570 // A Ref tolerates other Refs; it must be distinct from
571 // every mut-hoisted handle and every unhoisted mutator.
572 mut_hoisted
573 .iter()
574 .filter(|s| **s != *sym)
575 .all(|s| oracle.loop_handles_definitely_distinct(loop_stmt, *sym, *s))
576 && unhoisted_mut
577 .iter()
578 .all(|t| oracle.loop_handles_definitely_distinct(loop_stmt, *sym, *t))
579 }
580 })
581 .collect();
582 if keep.iter().all(|k| *k) {
583 break;
584 }
585 let mut it = keep.into_iter();
586 hoisted.retain(|_| it.next().unwrap());
587 }
588
589 let entries: Vec<HoistEntry> = derc_hoisted
590 .into_iter()
591 .map(|(sym, kind, elem_ty, old_type)| HoistEntry {
592 sym,
593 kind,
594 elem_ty,
595 old_type,
596 is_vec: true,
597 })
598 .chain(
599 hoisted
600 .into_iter()
601 .map(|(sym, kind, elem_ty, old_type)| HoistEntry {
602 sym,
603 kind,
604 elem_ty,
605 old_type,
606 is_vec: false,
607 }),
608 )
609 .collect();
610 // Reaching here with entries means the oracle is present, which (per the kill
611 // switch nulling it in codegen_program) means hoisting is enabled.
612 if !entries.is_empty() {
613 crate::optimize::mark_fired(crate::optimization::Opt::HoistBorrows);
614 }
615 entries
616}
617
618/// Open the hoist scope: guards, shadows, and the slice type flips.
619/// Returns nothing to restore beyond what the entries carry — call
620/// [`emit_hoist_close`] with the same entries on the way out.
621pub(crate) fn emit_hoist_open(
622 entries: &[HoistEntry],
623 interner: &Interner,
624 indent_str: &str,
625 ctx: &mut RefinementContext,
626 output: &mut String,
627) {
628 if entries.is_empty() {
629 return;
630 }
631 let names = RustNames::new(interner);
632 let inner = format!("{indent_str} ");
633 writeln!(output, "{}{{", indent_str).unwrap();
634 for e in entries {
635 let n = names.ident(e.sym);
636 match (e.kind, e.is_vec) {
637 // LogosSeq: a `.borrow()` guard + slice shadow.
638 (HoistKind::Shared, false) => {
639 writeln!(output, "{} let __{}_g = {}.borrow();", indent_str, n, n).unwrap();
640 writeln!(output, "{} let {} = &__{}_g[..];", indent_str, n, n).unwrap();
641 ctx.register_variable_type(e.sym, format!("&[{}]", e.elem_ty));
642 }
643 (HoistKind::MutSlice, false) => {
644 emit_cow(&Expr::Identifier(e.sym), ctx, &names, &inner, output);
645 writeln!(
646 output,
647 "{} let mut __{}_g = {}.borrow_mut();",
648 indent_str, n, n
649 )
650 .unwrap();
651 writeln!(output, "{} let {} = &mut __{}_g[..];", indent_str, n, n).unwrap();
652 ctx.register_variable_type(e.sym, format!("&mut [{}]", e.elem_ty));
653 }
654 (HoistKind::MutVec, false) => {
655 // Hold the RefMut as a `&mut Vec` so push/pop go through it
656 // without a per-call borrow. Registered as `Vec<T>` to reuse
657 // the existing owned-Vec emission (index, push, length all
658 // auto-deref through the `&mut Vec` shadow).
659 emit_cow(&Expr::Identifier(e.sym), ctx, &names, &inner, output);
660 writeln!(
661 output,
662 "{} let mut __{}_g = {}.borrow_mut();",
663 indent_str, n, n
664 )
665 .unwrap();
666 writeln!(output, "{} let {} = &mut *__{}_g;", indent_str, n, n).unwrap();
667 ctx.register_variable_type(e.sym, format!("Vec<{}>", e.elem_ty));
668 }
669 // De-Rc'd Vec: the SAME noalias slice, but no `.borrow()`.
670 (HoistKind::Shared, true) => {
671 writeln!(output, "{} let {} = &{}[..];", indent_str, n, n).unwrap();
672 ctx.register_variable_type(e.sym, format!("&[{}]", e.elem_ty));
673 }
674 (HoistKind::MutSlice, true) => {
675 writeln!(output, "{} let {} = &mut {}[..];", indent_str, n, n).unwrap();
676 ctx.register_variable_type(e.sym, format!("&mut [{}]", e.elem_ty));
677 }
678 (HoistKind::MutVec, true) => {
679 // Resized in the loop — keep it a `&mut Vec` (a slice can't
680 // push) but reborrow so LLVM gets the `&mut` noalias. The
681 // binding is `mut` so a NESTED loop can reborrow it again
682 // (`let mut a = &mut a;` then inner `let mut a = &mut a;`).
683 writeln!(output, "{} let mut {} = &mut {};", indent_str, n, n).unwrap();
684 ctx.register_variable_type(e.sym, format!("Vec<{}>", e.elem_ty));
685 }
686 }
687 }
688}
689
690/// Close the hoist scope and restore the handles' tracked types.
691pub(crate) fn emit_hoist_close(
692 entries: &[HoistEntry],
693 indent_str: &str,
694 ctx: &mut RefinementContext,
695 output: &mut String,
696) {
697 if entries.is_empty() {
698 return;
699 }
700 for e in entries {
701 ctx.register_variable_type(e.sym, e.old_type.clone());
702 }
703 writeln!(output, "{}}}", indent_str).unwrap();
704}