1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3
4use crate::analysis::registry::{FieldType, TypeDef, TypeRegistry};
5use crate::analysis::types::RustNames;
6use crate::ast::stmt::{
7 BinaryOpKind, Block, Expr, Literal, MatchArm, Pattern, ReadSource, Stmt, TypeExpr, ZoneSource,
8};
9use crate::intern::{Interner, Symbol};
10
11use super::context::{emit_refinement_check, RefinementContext, VariableCapabilities};
12use super::detection::{
13 calls_async_function, collect_expr_identifiers, collect_stmt_identifiers, expr_debug_prefix,
14 expr_reads_any_collection, parse_aos_tag, requires_async_stmt,
15};
16use super::expr::{
17 codegen_assertion, codegen_expr_boxed_with_types, codegen_expr_boxed_with_types_oracle,
18 codegen_expr_boxed_with_types_oracle_tolerant, codegen_expr_with_async,
19 codegen_expr_with_async_and_strings, codegen_expr_with_async_oracle,
20 collect_string_concat_operands, is_definitely_string_expr_with_vars, is_rational_expr,
21 set_movable_last_use,
22};
23
24fn count_target_reads(e: &Expr, target: Symbol) -> usize {
31 match e {
32 Expr::Identifier(s) => usize::from(*s == target),
33 Expr::Literal(_) => 0,
34 Expr::BinaryOp { left, right, .. } => {
35 count_target_reads(left, target) + count_target_reads(right, target)
36 }
37 Expr::Not { operand } => count_target_reads(operand, target),
38 Expr::Call { args, .. } => args.iter().map(|a| count_target_reads(a, target)).sum(),
39 _ => 2,
40 }
41}
42use super::escape_rust_ident;
43use super::i64_map::{dense_type_name, is_logos_map_type, map_rust_type};
44use super::peephole::{
45 body_declares_var, body_has_early_exit, body_modifies_var, body_mutates_collection,
46 body_resizes_collection, collect_expr_symbols, emit_bounds_hint_header,
47 emit_bounds_hint_preheader, exprs_equal, is_counter_increment, plan_bounds_hints,
48 simplify_1based_index, try_emit_byte_compare_window, try_emit_drain_tail_in_while,
49 BoundsHintPlan,
50};
51use super::types::{
52 codegen_type_expr, infer_numeric_type, infer_rust_type_from_expr, infer_variant_type_annotation,
53};
54
55pub(crate) fn rust_string_escape(text: &str) -> String {
66 let mut out = String::with_capacity(text.len());
67 for ch in text.chars() {
68 match ch {
69 '\n' => out.push_str("\\n"),
70 '\r' => out.push_str("\\r"),
71 '\t' => out.push_str("\\t"),
72 '\\' => out.push_str("\\\\"),
73 '"' => out.push_str("\\\""),
74 _ => out.push(ch),
75 }
76 }
77 out
78}
79
80fn rust_char_escape(ch: char) -> String {
82 match ch {
83 '\n' => "\\n".to_string(),
84 '\r' => "\\r".to_string(),
85 '\t' => "\\t".to_string(),
86 '\\' => "\\\\".to_string(),
87 '\'' => "\\'".to_string(),
88 _ => ch.to_string(),
89 }
90}
91
92fn derc_vec_decl<'a>(
97 value: &Expr<'a>,
98 interner: &Interner,
99 synced_vars: &HashSet<Symbol>,
100 boxed_fields: &HashSet<(String, String, String)>,
101 registry: &TypeRegistry,
102 async_functions: &HashSet<Symbol>,
103 ctx: &RefinementContext<'a>,
104) -> Option<(String, String)> {
105 match value {
106 Expr::New {
107 type_name,
108 type_args,
109 init_fields,
110 } if init_fields.is_empty() => match interner.resolve(*type_name) {
111 "Seq" | "List" | "Vec" => {
112 let elem = codegen_type_expr(type_args.first()?, interner);
113 Some((format!("Vec<{}>", elem), "Vec::new()".to_string()))
114 }
115 _ => None,
116 },
117 Expr::WithCapacity {
118 value: inner,
119 capacity,
120 } => {
121 if let Expr::New {
122 type_name,
123 type_args,
124 ..
125 } = inner
126 {
127 if matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec") {
128 let elem = codegen_type_expr(type_args.first()?, interner);
129 let cap = codegen_expr_boxed_with_types(
130 capacity,
131 interner,
132 synced_vars,
133 boxed_fields,
134 registry,
135 async_functions,
136 ctx.get_string_vars(),
137 ctx.get_variable_types(),
138 ctx.get_fast_div(),
139 );
140 return Some((
141 format!("Vec<{}>", elem),
142 format!("Vec::with_capacity(({}) as usize)", cap),
143 ));
144 }
145 }
146 None
147 }
148 Expr::Call { function, .. } => {
153 let ret = ctx.get_fn_return(function)?;
154 if !ret.starts_with("Vec<") {
155 return None;
156 }
157 let vec_ty = ret.clone();
158 let init = codegen_expr_boxed_with_types(
159 value,
160 interner,
161 synced_vars,
162 boxed_fields,
163 registry,
164 async_functions,
165 ctx.get_string_vars(),
166 ctx.get_variable_types(),
167 ctx.get_fast_div(),
168 );
169 Some((vec_ty, init))
170 }
171 Expr::List(items) => {
175 let elem = crate::codegen::detection::homogeneous_scalar_literal_elem(items)?;
176 let item_strs: Vec<String> = items
177 .iter()
178 .map(|i| {
179 codegen_expr_boxed_with_types(
180 i,
181 interner,
182 synced_vars,
183 boxed_fields,
184 registry,
185 async_functions,
186 ctx.get_string_vars(),
187 ctx.get_variable_types(),
188 ctx.get_fast_div(),
189 )
190 })
191 .collect();
192 Some((
193 format!("Vec<{}>", elem),
194 format!("vec![{}]", item_strs.join(", ")),
195 ))
196 }
197 _ => None,
198 }
199}
200
201fn i64_map_ctor<'a>(
206 value: &Expr<'a>,
207 ty: &str,
208 dense_lo: Option<i64>,
209 interner: &Interner,
210 synced_vars: &HashSet<Symbol>,
211 boxed_fields: &HashSet<(String, String, String)>,
212 registry: &TypeRegistry,
213 async_functions: &HashSet<Symbol>,
214 ctx: &RefinementContext<'a>,
215) -> Option<String> {
216 match value {
217 Expr::New {
218 type_name,
219 init_fields,
220 ..
221 } if init_fields.is_empty()
222 && matches!(interner.resolve(*type_name), "Map" | "HashMap") =>
223 {
224 Some(format!("{}::new()", ty))
225 }
226 Expr::WithCapacity {
227 value: inner,
228 capacity,
229 } => {
230 if let Expr::New { type_name, .. } = inner {
231 if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
232 let cap = codegen_expr_boxed_with_types(
233 capacity,
234 interner,
235 synced_vars,
236 boxed_fields,
237 registry,
238 async_functions,
239 ctx.get_string_vars(),
240 ctx.get_variable_types(),
241 ctx.get_fast_div(),
242 );
243 return Some(match dense_lo {
249 Some(lo) => {
250 format!("{}::with_bounds({}, (({}) + 1) as usize)", ty, lo, cap)
251 }
252 None => format!("{}::with_capacity(({}) as usize)", ty, cap),
253 });
254 }
255 }
256 None
257 }
258 _ => None,
259 }
260}
261
262fn store_offset(
265 index: &Expr,
266 zero_based: Option<&str>,
267 interner: &Interner,
268 ctx: &RefinementContext,
269) -> String {
270 match zero_based {
271 Some(s) => format!("{} as usize", s),
272 None => simplify_1based_index(index, interner, true, ctx.get_variable_types()),
273 }
274}
275
276fn emit_oracle_index_hints<'a>(
282 stmt: &Stmt<'a>,
283 ctx: &RefinementContext<'a>,
284 interner: &Interner,
285 registry: &TypeRegistry,
286 indent_str: &str,
287) -> String {
288 if !crate::optimize::active_config().is_on(crate::optimization::Opt::OracleHints) {
291 return String::new();
292 }
293 let oracle = match ctx.oracle() {
294 Some(o) => o,
295 None => return String::new(),
296 };
297 let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
298 collect_index_accesses_in_stmt(stmt, &mut accesses);
299 if accesses.is_empty() {
300 return String::new();
301 }
302 let names = RustNames::new(interner);
303 let mut out = String::new();
304 let mut seen: HashSet<usize> = HashSet::new();
305 for (coll, idx) in accesses {
306 let arr = match coll {
307 Expr::Identifier(s) => *s,
308 _ => continue,
309 };
310 if ctx.affine_array(arr).is_some() {
313 continue;
314 }
315 if ctx
318 .get_variable_types()
319 .get(&arr)
320 .is_some_and(|t| t == super::tower::VALUE)
321 {
322 continue;
323 }
324 let typing = super::rational::Typing {
327 interner,
328 variable_types: ctx.get_variable_types(),
329 registry,
330 };
331 if super::rational::read_as_exact(idx, typing) {
332 continue;
333 }
334 let aos_backing = parse_aos_tag(ctx.get_variable_types().get(&arr)).map(|t| t.backing);
340 if !seen.insert(idx as *const Expr as usize) {
341 continue;
342 }
343 if !oracle.index_provably_in_bounds(coll, idx) {
344 continue;
345 }
346 for &m in oracle.index_positivity_guards(idx) {
353 let mn = names.ident(m);
354 writeln!(
355 out,
356 "{}assert!(({mn}) > 0, \"LOGOS positivity guard: element bound on `% {mn}` requires {mn} > 0\");",
357 indent_str, mn = mn
358 )
359 .unwrap();
360 }
361 let i0 = match super::expr::zero_based_index_str(idx, ctx.get_variable_types(), interner) {
365 Some(s) => s,
366 None => simplify_1based_index(idx, interner, false, ctx.get_variable_types()),
367 };
368 let arr_name = aos_backing.unwrap_or_else(|| names.ident(arr));
369 let cond = format!("({}) >= 0 && ({}) < ({}.len() as i64)", i0, i0, arr_name);
370 writeln!(out, "{}debug_assert!({}, \"LOGOS oracle bounds hint violated: indexing `{}` out of range\");", indent_str, cond, arr_name).unwrap();
371 writeln!(
372 out,
373 "{}unsafe {{ std::hint::assert_unchecked({}); }}",
374 indent_str, cond
375 )
376 .unwrap();
377 }
378 if !out.is_empty() {
379 crate::optimize::mark_fired(crate::optimization::Opt::OracleHints);
380 }
381 out
382}
383
384fn collect_index_accesses_in_stmt<'a>(
385 stmt: &'a Stmt<'a>,
386 out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>,
387) {
388 match stmt {
389 Stmt::Let { value, .. } | Stmt::Set { value, .. } => collect_index_in_expr(value, out),
390 Stmt::SetIndex {
391 collection,
392 index,
393 value,
394 } => {
395 out.push((collection, index));
396 collect_index_in_expr(index, out);
397 collect_index_in_expr(value, out);
398 }
399 Stmt::If { cond, .. } | Stmt::While { cond, .. } => collect_index_in_expr(cond, out),
400 Stmt::Show { object, .. } | Stmt::Give { object, .. } => collect_index_in_expr(object, out),
401 Stmt::Return { value: Some(e) } => collect_index_in_expr(e, out),
402 Stmt::Push { value, .. } | Stmt::Add { value, .. } | Stmt::Remove { value, .. } => {
403 collect_index_in_expr(value, out)
404 }
405 _ => {}
406 }
407}
408
409fn collect_index_in_expr<'a>(e: &'a Expr<'a>, out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>) {
410 match e {
411 Expr::Index { collection, index } => {
412 out.push((collection, index));
413 collect_index_in_expr(collection, out);
414 collect_index_in_expr(index, out);
415 }
416 Expr::BinaryOp { left, right, .. } => {
417 collect_index_in_expr(left, out);
418 collect_index_in_expr(right, out);
419 }
420 Expr::Not { operand } => collect_index_in_expr(operand, out),
421 Expr::Call { args, .. } => {
422 for a in args.iter() {
423 collect_index_in_expr(a, out);
424 }
425 }
426 Expr::Length { collection } => collect_index_in_expr(collection, out),
427 _ => {}
428 }
429}
430
431pub(crate) struct AffineOffsetGuard<'a> {
440 arr_sym: Symbol,
441 offset: &'a Expr<'a>,
443 emitted_index: &'a Expr<'a>,
445 covered: Vec<&'a Expr<'a>>,
447}
448
449fn match_affine_offset_index<'a>(
453 index: &'a Expr<'a>,
454 counter: Symbol,
455) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
456 if let Expr::BinaryOp {
457 op: BinaryOpKind::Add,
458 left,
459 right,
460 } = index
461 {
462 if matches!(right, Expr::Literal(Literal::Number(1))) {
463 if let Expr::BinaryOp {
464 op: BinaryOpKind::Add,
465 left: a,
466 right: b,
467 } = left
468 {
469 if matches!(b, Expr::Identifier(s) if *s == counter) {
470 return Some((a, left));
471 }
472 if matches!(a, Expr::Identifier(s) if *s == counter) {
473 return Some((b, left));
474 }
475 }
476 }
477 }
478 None
479}
480
481pub(crate) fn plan_affine_offset_guards<'a>(
487 body: &'a [Stmt<'a>],
488 counter_sym: Symbol,
489 is_exclusive: bool,
490 var_types: &HashMap<Symbol, String>,
491) -> Vec<AffineOffsetGuard<'a>> {
492 if !is_exclusive || body_has_early_exit(body) {
493 return Vec::new();
494 }
495 let mut guards: Vec<AffineOffsetGuard> = Vec::new();
496 let mut seen: HashSet<Symbol> = HashSet::new();
497 for stmt in body {
498 let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
499 collect_index_accesses_in_stmt(stmt, &mut accesses);
500 for (coll, index) in accesses {
501 let arr_sym = match coll {
502 Expr::Identifier(s) => *s,
503 _ => continue,
504 };
505 if !crate::optimize::facts::holds_expr(crate::optimize::facts::Fact::InBounds, index) {
506 continue;
507 }
508 let Some((offset, emitted)) = match_affine_offset_index(index, counter_sym) else {
509 continue;
510 };
511 let base_ty = var_types
512 .get(&arr_sym)
513 .map(|t| t.split("|__hl:").next().unwrap_or(t.as_str()));
514 let qualifies = matches!(
515 base_ty,
516 Some(t) if t.starts_with("Vec<") || t.starts_with("LogosSeq")
517 || t.starts_with("&[") || t.starts_with("&mut [")
518 );
519 if !qualifies
520 || body_resizes_collection(body, arr_sym)
521 || body_modifies_var(body, arr_sym)
522 {
523 continue;
524 }
525 let mut osyms = Vec::new();
526 collect_expr_symbols(offset, &mut osyms);
527 if osyms.contains(&counter_sym)
528 || osyms
529 .iter()
530 .any(|s| body_modifies_var(body, *s) || body_mutates_collection(body, *s))
531 {
532 continue;
533 }
534 if seen.insert(arr_sym) {
535 guards.push(AffineOffsetGuard {
536 arr_sym,
537 offset,
538 emitted_index: emitted,
539 covered: vec![index],
540 });
541 } else if let Some(g) = guards
542 .iter_mut()
543 .find(|g| g.arr_sym == arr_sym && exprs_equal(g.offset, offset))
544 {
545 g.covered.push(index);
546 }
547 }
548 }
549 guards
550}
551
552pub(crate) fn emit_affine_offset_header(
556 guards: &[AffineOffsetGuard],
557 interner: &Interner,
558 synced_vars: &HashSet<Symbol>,
559 async_functions: &HashSet<Symbol>,
560 var_types: &HashMap<Symbol, String>,
561 body_indent: &str,
562 output: &mut String,
563) {
564 let names = RustNames::new(interner);
565 for g in guards {
566 let arr = names.ident(g.arr_sym);
567 let e = codegen_expr_with_async(
568 g.emitted_index,
569 interner,
570 synced_vars,
571 async_functions,
572 var_types,
573 );
574 writeln!(
575 output,
576 "{}unsafe {{ std::hint::assert_unchecked(({e}) >= 0 && ({e}) < ({arr}.len() as i64)); }}",
577 body_indent, e = e, arr = arr
578 ).unwrap();
579 }
580}
581
582#[allow(clippy::too_many_arguments)]
585fn write_tokio_select<'a>(
586 output: &mut String,
587 branches: &[crate::ast::stmt::SelectBranch<'a>],
588 interner: &Interner,
589 indent: usize,
590 mutable_vars: &HashSet<Symbol>,
591 ctx: &mut RefinementContext<'a>,
592 lww_fields: &HashSet<(String, String)>,
593 mv_fields: &HashSet<(String, String)>,
594 synced_vars: &mut HashSet<Symbol>,
595 var_caps: &HashMap<Symbol, VariableCapabilities>,
596 async_functions: &HashSet<Symbol>,
597 pipe_vars: &HashSet<Symbol>,
598 boxed_fields: &HashSet<(String, String, String)>,
599 registry: &TypeRegistry,
600 type_env: &crate::analysis::types::TypeEnv,
601) {
602 use crate::ast::stmt::SelectBranch;
603 let indent_str = " ".repeat(indent);
604 writeln!(output, "{}tokio::select! {{", indent_str).unwrap();
605 for branch in branches {
606 match branch {
607 SelectBranch::Receive { var, pipe, body } => {
608 let var_name = interner.resolve(*var);
609 let pipe_str = codegen_expr_with_async(
610 pipe,
611 interner,
612 synced_vars,
613 async_functions,
614 ctx.get_variable_types(),
615 );
616 let is_local_pipe = if let Expr::Identifier(sym) = pipe {
617 pipe_vars.contains(sym)
618 } else {
619 false
620 };
621 let suffix = if is_local_pipe { "_rx" } else { "" };
622 writeln!(
623 output,
624 "{} {} = {}{}.recv() => {{",
625 indent_str, var_name, pipe_str, suffix
626 )
627 .unwrap();
628 writeln!(
629 output,
630 "{} if let Some({}) = {} {{",
631 indent_str, var_name, var_name
632 )
633 .unwrap();
634 for stmt in *body {
635 let stmt_code = codegen_stmt(
636 stmt,
637 interner,
638 indent + 3,
639 mutable_vars,
640 ctx,
641 lww_fields,
642 mv_fields,
643 synced_vars,
644 var_caps,
645 async_functions,
646 pipe_vars,
647 boxed_fields,
648 registry,
649 type_env,
650 );
651 write!(output, "{}", stmt_code).unwrap();
652 }
653 writeln!(output, "{} }}", indent_str).unwrap();
654 writeln!(output, "{} }}", indent_str).unwrap();
655 }
656 SelectBranch::Timeout { milliseconds, body } => {
657 let dur = match milliseconds {
658 Expr::Literal(Literal::Duration(_)) => codegen_expr_with_async(
659 milliseconds,
660 interner,
661 synced_vars,
662 async_functions,
663 ctx.get_variable_types(),
664 ),
665 Expr::Literal(Literal::Span { months, days }) => {
666 let secs = ((*months as i64) * 30 + (*days as i64)) * 86_400;
667 format!("std::time::Duration::from_secs({}u64)", secs.max(0))
668 }
669 _ => {
670 let n = codegen_expr_with_async(
671 milliseconds,
672 interner,
673 synced_vars,
674 async_functions,
675 ctx.get_variable_types(),
676 );
677 format!("std::time::Duration::from_secs({} as u64)", n)
678 }
679 };
680 writeln!(
681 output,
682 "{} _ = tokio::time::sleep({}) => {{",
683 indent_str, dur
684 )
685 .unwrap();
686 for stmt in *body {
687 let stmt_code = codegen_stmt(
688 stmt,
689 interner,
690 indent + 2,
691 mutable_vars,
692 ctx,
693 lww_fields,
694 mv_fields,
695 synced_vars,
696 var_caps,
697 async_functions,
698 pipe_vars,
699 boxed_fields,
700 registry,
701 type_env,
702 );
703 write!(output, "{}", stmt_code).unwrap();
704 }
705 writeln!(output, "{} }}", indent_str).unwrap();
706 }
707 }
708 }
709 writeln!(output, "{}}}", indent_str).unwrap();
710}
711
712fn launched_future(function: &str, args: &[(String, bool)], tail: &str) -> String {
718 let mut lets = String::new();
719 let mut call_args = Vec::with_capacity(args.len());
720 for (i, (value, literal)) in args.iter().enumerate() {
721 if *literal {
722 call_args.push(value.clone());
723 } else {
724 lets.push_str(&format!("let __logos_arg{i} = {value}; "));
725 call_args.push(format!("__logos_arg{i}"));
726 }
727 }
728 let future = format!(
729 "async move {{ {function}({}){tail} }}",
730 call_args.join(", ")
731 );
732 if lets.is_empty() {
733 future
734 } else {
735 format!("{{ {lets}{future} }}")
736 }
737}
738
739pub(super) fn emit_cow(
742 collection: &Expr,
743 ctx: &RefinementContext,
744 names: &RustNames,
745 indent_str: &str,
746 output: &mut String,
747) {
748 if let Some(name) = super::expr::cow_handle(collection, ctx.get_variable_types(), names) {
749 writeln!(output, "{}{}.cow();", indent_str, name).unwrap();
750 }
751}
752
753fn scratch_fill_target<'a>(
757 body: &[Stmt<'a>],
758 ctx: &RefinementContext<'a>,
759) -> Option<(Symbol, super::affine_array::ScratchInfo)> {
760 for s in body {
761 if let Stmt::Push {
762 collection: Expr::Identifier(c),
763 ..
764 } = s
765 {
766 if let Some(info) = ctx.scratch_buffer(*c) {
767 return Some((*c, info.clone()));
768 }
769 }
770 }
771 None
772}
773
774#[allow(clippy::too_many_arguments)]
778fn try_emit_stride_fill<'a>(
779 cond: &'a Expr<'a>,
780 body: Block<'a>,
781 interner: &Interner,
782 indent: usize,
783 mutable_vars: &HashSet<Symbol>,
784 ctx: &mut RefinementContext<'a>,
785 lww_fields: &HashSet<(String, String)>,
786 mv_fields: &HashSet<(String, String)>,
787 synced_vars: &mut HashSet<Symbol>,
788 var_caps: &HashMap<Symbol, VariableCapabilities>,
789 async_functions: &HashSet<Symbol>,
790 pipe_vars: &HashSet<Symbol>,
791 boxed_fields: &HashSet<(String, String, String)>,
792 registry: &TypeRegistry,
793 type_env: &crate::analysis::types::TypeEnv,
794 indent_str: &str,
795) -> Option<String> {
796 let config = crate::optimize::active_config();
797 if !config.is_on(crate::optimization::Opt::StrideFill)
798 || !config.is_on(crate::optimization::Opt::Unchecked)
799 {
800 return None;
801 }
802 let fill = super::bits::match_stride_fill(
803 cond,
804 body,
805 ctx.get_variable_types(),
806 ctx.oracle()?,
807 interner,
808 )?;
809 crate::optimize::mark_fired(crate::optimization::Opt::StrideFill);
810 crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
811 let names = RustNames::new(interner);
812 let types = ctx.get_variable_types();
813 let counter = names.ident(fill.counter);
814 let bits = names.ident(fill.bits);
815 let emit = |e: &Expr| codegen_expr_with_async(e, interner, synced_vars, async_functions, types);
816 let cond_str = codegen_expr_with_async_oracle(
817 cond,
818 interner,
819 synced_vars,
820 async_functions,
821 types,
822 ctx.oracle(),
823 );
824 let cond_str = truthy_cond_wrap(cond, cond_str, interner, types);
825 let (bound, step, value) = (emit(fill.bound), emit(fill.step), emit(fill.value));
826 let first = simplify_1based_index(fill.index, interner, false, types);
827 let below = if fill.strict { " - 1" } else { "" };
828 let inner = " ".repeat(indent + 1);
829 let mut out = String::new();
830 writeln!(out, "{indent_str}if {cond_str} {{").unwrap();
831 writeln!(out, "{inner}let __sf_step: i64 = {step};").unwrap();
832 writeln!(
833 out,
834 "{inner}debug_assert!(({first}) >= 0, \"LOGOS oracle BCE: strided fill out of range\");"
835 )
836 .unwrap();
837 writeln!(
838 out,
839 "{inner}let __sf_more = unsafe {{ {bits}.fill_stride_through_unchecked(({first}) as usize, ({first}).wrapping_add((({bound}) as i64{below}).wrapping_sub({counter})) as usize, __sf_step as usize, {value}) }} as i64;"
840 )
841 .unwrap();
842 writeln!(out, "{inner}{counter} = {counter} + __sf_more * __sf_step;").unwrap();
843 out.push_str(&codegen_stmt(
844 fill.increment,
845 interner,
846 indent + 1,
847 mutable_vars,
848 ctx,
849 lww_fields,
850 mv_fields,
851 synced_vars,
852 var_caps,
853 async_functions,
854 pipe_vars,
855 boxed_fields,
856 registry,
857 type_env,
858 ));
859 writeln!(out, "{indent_str}}}").unwrap();
860 Some(out)
861}
862
863#[inline(never)]
865#[allow(clippy::too_many_arguments)]
866fn codegen_while_stmt<'a>(
867 mut output: String,
868 stmt: &Stmt<'a>,
869 cond: &&'a Expr<'a>,
870 body: &Block<'a>,
871 interner: &Interner,
872 indent: usize,
873 mutable_vars: &HashSet<Symbol>,
874 ctx: &mut RefinementContext<'a>,
875 lww_fields: &HashSet<(String, String)>,
876 mv_fields: &HashSet<(String, String)>,
877 synced_vars: &mut HashSet<Symbol>,
878 var_caps: &HashMap<Symbol, VariableCapabilities>,
879 async_functions: &HashSet<Symbol>,
880 pipe_vars: &HashSet<Symbol>,
881 boxed_fields: &HashSet<(String, String, String)>,
882 registry: &TypeRegistry,
883 type_env: &crate::analysis::types::TypeEnv,
884 indent_str: &str,
885) -> String {
886 if let Some(code) = try_emit_byte_compare_window(
889 stmt,
890 interner,
891 indent,
892 ctx.get_variable_types(),
893 ctx.oracle(),
894 ) {
895 return code;
896 }
897 if let Some(code) = try_emit_stride_fill(
898 *cond,
899 *body,
900 interner,
901 indent,
902 mutable_vars,
903 ctx,
904 lww_fields,
905 mv_fields,
906 synced_vars,
907 var_caps,
908 async_functions,
909 pipe_vars,
910 boxed_fields,
911 registry,
912 type_env,
913 indent_str,
914 ) {
915 output.push_str(&code);
916 return output;
917 }
918 let mut all_length_syms_raw = extract_length_expr_syms(cond);
926 collect_length_syms_from_stmts(body, &mut all_length_syms_raw);
927 let mut seen = HashSet::new();
928 let all_length_syms: Vec<Symbol> = all_length_syms_raw
929 .into_iter()
930 .filter(|s| seen.insert(*s))
931 .collect();
932
933 let mut hoisted_syms: Vec<(Symbol, Option<String>)> = Vec::new();
934 for len_sym in &all_length_syms {
935 if ctx.affine_array(*len_sym).is_some() {
938 continue;
939 }
940 if !body_mutates_collection(body, *len_sym)
941 && !body_modifies_var(body, *len_sym)
942 && !body_declares_var(body, *len_sym)
943 {
944 let name = interner.resolve(*len_sym);
945 let hoisted_name = format!("{}_len", name);
946 writeln!(
947 output,
948 "{}let {} = ({}.len() as i64);",
949 indent_str, hoisted_name, name
950 )
951 .unwrap();
952 let old_type = ctx.get_variable_types().get(len_sym).cloned();
953 let new_type = match &old_type {
957 Some(existing) => format!("{}|__hl:{}", existing, hoisted_name),
958 None => format!("|__hl:{}", hoisted_name),
959 };
960 ctx.register_variable_type(*len_sym, new_type);
961 hoisted_syms.push((*len_sym, old_type));
962 }
963 }
964
965 let mut while_bounds_hints: Vec<BoundsHintPlan> = Vec::new();
973 let mut affine_guards: Vec<AffineOffsetGuard> = Vec::new();
974 if let Expr::BinaryOp {
975 op: op @ (BinaryOpKind::LtEq | BinaryOpKind::Lt),
976 left: Expr::Identifier(counter_sym),
977 right: bound_expr,
978 } = cond
979 {
980 let body_sans_inc =
981 if !body.is_empty() && is_counter_increment(&body[body.len() - 1], *counter_sym) {
982 Some(&body[..body.len() - 1])
983 } else {
984 None
985 };
986 if let Some(body_sans_inc) = body_sans_inc {
987 let counter_clean = !body_modifies_var(body_sans_inc, *counter_sym);
988 let mut bound_syms = Vec::new();
989 collect_expr_symbols(bound_expr, &mut bound_syms);
990 let bound_invariant = bound_syms
991 .iter()
992 .all(|s| !body_modifies_var(body, *s) && !body_mutates_collection(body, *s));
993 if counter_clean && bound_invariant {
994 let bound_str = codegen_expr_with_async(
995 bound_expr,
996 interner,
997 synced_vars,
998 async_functions,
999 ctx.get_variable_types(),
1000 );
1001 while_bounds_hints = plan_bounds_hints(
1002 body_sans_inc,
1003 *counter_sym,
1004 matches!(op, BinaryOpKind::Lt),
1005 false,
1006 bound_expr,
1007 &bound_str,
1008 ctx.get_variable_types(),
1009 );
1010 emit_bounds_hint_preheader(&while_bounds_hints, interner, &indent_str, &mut output);
1011
1012 affine_guards = plan_affine_offset_guards(
1015 body_sans_inc,
1016 *counter_sym,
1017 matches!(op, BinaryOpKind::Lt),
1018 ctx.get_variable_types(),
1019 );
1020 }
1021 }
1022 }
1023
1024 let scratch_hoisted: Vec<Symbol> =
1032 super::peephole::detect_scratch_hoist_in_body(body, interner, ctx)
1033 .into_iter()
1034 .map(|(dst, elem_type)| {
1035 writeln!(
1036 output,
1037 "{}let mut {}: Vec<{}> = Vec::new();",
1038 indent_str,
1039 interner.resolve(dst),
1040 elem_type
1041 )
1042 .unwrap();
1043 ctx.register_variable_type(dst, format!("Vec<{}>", elem_type));
1044 ctx.register_scratch_hoist(dst);
1045 dst
1046 })
1047 .collect();
1048
1049 let hoist_plan = super::hoist::plan_borrow_hoist(stmt, Some(cond), body, ctx, interner);
1054 super::hoist::emit_hoist_open(&hoist_plan, interner, &indent_str, ctx, &mut output);
1055
1056 let cond_str = codegen_expr_with_async_oracle(
1057 cond,
1058 interner,
1059 synced_vars,
1060 async_functions,
1061 ctx.get_variable_types(),
1062 ctx.oracle(),
1063 );
1064 let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
1065 let loop_start = output.len();
1066 writeln!(output, "{}while {} {{", indent_str, cond_str).unwrap();
1067 emit_bounds_hint_header(
1068 &while_bounds_hints,
1069 interner,
1070 &" ".repeat(indent + 1),
1071 &mut output,
1072 );
1073 emit_affine_offset_header(
1074 &affine_guards,
1075 interner,
1076 synced_vars,
1077 async_functions,
1078 ctx.get_variable_types(),
1079 &" ".repeat(indent + 1),
1080 &mut output,
1081 );
1082 ctx.push_scope();
1083
1084 let sentinel_ctx: Option<(Symbol, &Expr)> = match cond {
1088 Expr::BinaryOp {
1089 op: BinaryOpKind::Lt,
1090 left,
1091 right,
1092 } => {
1093 if let Expr::Identifier(sym) = left {
1094 Some((*sym, *right))
1095 } else {
1096 None
1097 }
1098 }
1099 _ => None,
1100 };
1101
1102 let body_refs: Vec<&Stmt> = body.iter().collect();
1104 let mut bi = 0;
1105 while bi < body_refs.len() {
1106 if let Some((code, skip)) = super::peephole::try_block_peepholes(
1107 &body_refs,
1108 bi,
1109 interner,
1110 indent + 1,
1111 mutable_vars,
1112 ctx,
1113 lww_fields,
1114 mv_fields,
1115 synced_vars,
1116 var_caps,
1117 async_functions,
1118 pipe_vars,
1119 boxed_fields,
1120 registry,
1121 type_env,
1122 ) {
1123 output.push_str(&code);
1124 bi += 1 + skip;
1125 continue;
1126 }
1127 if let Some(code) = try_emit_drain_tail_in_while(
1131 body_refs[bi],
1132 cond,
1133 interner,
1134 indent + 1,
1135 mutable_vars,
1136 ctx,
1137 lww_fields,
1138 mv_fields,
1139 synced_vars,
1140 var_caps,
1141 async_functions,
1142 pipe_vars,
1143 boxed_fields,
1144 registry,
1145 type_env,
1146 ) {
1147 output.push_str(&code);
1148 bi += 1;
1149 continue;
1150 }
1151 if let Some((counter_sym, limit_expr)) = &sentinel_ctx {
1155 if let Some(code) = try_emit_sentinel_break(
1156 body_refs[bi],
1157 *counter_sym,
1158 limit_expr,
1159 interner,
1160 indent + 1,
1161 mutable_vars,
1162 ctx,
1163 lww_fields,
1164 mv_fields,
1165 synced_vars,
1166 var_caps,
1167 async_functions,
1168 pipe_vars,
1169 boxed_fields,
1170 registry,
1171 type_env,
1172 ) {
1173 output.push_str(&emit_oracle_index_hints(
1177 body_refs[bi],
1178 ctx,
1179 interner,
1180 registry,
1181 &" ".repeat(indent + 1),
1182 ));
1183 output.push_str(&code);
1184 bi += 1;
1185 continue;
1186 }
1187 }
1188 output.push_str(&codegen_stmt(
1189 body_refs[bi],
1190 interner,
1191 indent + 1,
1192 mutable_vars,
1193 ctx,
1194 lww_fields,
1195 mv_fields,
1196 synced_vars,
1197 var_caps,
1198 async_functions,
1199 pipe_vars,
1200 boxed_fields,
1201 registry,
1202 type_env,
1203 ));
1204 bi += 1;
1205 }
1206 ctx.pop_scope();
1207
1208 for (sym, old_type) in hoisted_syms {
1211 if let Some(old) = old_type {
1212 ctx.register_variable_type(sym, old);
1213 } else {
1214 ctx.get_variable_types_mut().remove(&sym);
1215 }
1216 }
1217
1218 for dst in scratch_hoisted {
1222 ctx.clear_scratch_hoist(dst);
1223 }
1224
1225 writeln!(output, "{}}}", indent_str).unwrap();
1226 super::peephole::version_on_bounds_hints(
1227 &mut output,
1228 loop_start,
1229 &while_bounds_hints,
1230 body,
1231 ctx.oracle(),
1232 interner,
1233 &indent_str,
1234 );
1235 super::hoist::emit_hoist_close(&hoist_plan, &indent_str, ctx, &mut output);
1237 output
1238}
1239
1240fn mark_fixed_array_counter_accesses(
1245 counter: Symbol,
1246 iterable: &Expr,
1247 body: &[Stmt],
1248 var_types: &HashMap<Symbol, String>,
1249) {
1250 let Expr::Range { start, end } = iterable else {
1251 return;
1252 };
1253 let (Expr::Literal(Literal::Number(lo)), Expr::Literal(Literal::Number(hi))) = (start, end)
1254 else {
1255 return;
1256 };
1257 if *lo < 1 || crate::optimize::WriteSet::of_block(body).may_write(counter) {
1258 return;
1259 }
1260 let fixed_len = |arr: Symbol| -> Option<i64> {
1261 let t = var_types.get(&arr)?;
1262 let t = t.split("|__hl:").next().unwrap_or(t.as_str());
1263 t.strip_prefix('[')?
1264 .strip_suffix(']')?
1265 .rsplit_once("; ")?
1266 .1
1267 .trim()
1268 .parse()
1269 .ok()
1270 };
1271 use logicaffeine_language::ast_depth::{walk_nodes, Visited, Walk};
1272 walk_nodes(body, |node| {
1273 let (arr, index) = match node {
1274 Visited::Stmt(Stmt::FunctionDef { .. }) | Visited::Expr(Expr::Closure { .. }) => {
1275 return Walk::Past
1276 }
1277 Visited::Expr(Expr::Index {
1278 collection: Expr::Identifier(arr),
1279 index,
1280 }) => (*arr, *index),
1281 Visited::Stmt(Stmt::SetIndex {
1282 collection: Expr::Identifier(arr),
1283 index,
1284 ..
1285 }) => (*arr, *index),
1286 _ => return Walk::Into,
1287 };
1288 if matches!(index, Expr::Identifier(s) if *s == counter)
1289 && fixed_len(arr).is_some_and(|n| *hi <= n)
1290 {
1291 super::expr::mark_index_in_range(index);
1292 }
1293 Walk::Into
1294 });
1295}
1296
1297#[inline(never)]
1299#[allow(clippy::too_many_arguments)]
1300fn codegen_repeat_stmt<'a>(
1301 mut output: String,
1302 repeat: &Stmt<'a>,
1303 pattern: &Pattern,
1304 iterable: &&'a Expr<'a>,
1305 body: &Block<'a>,
1306 interner: &Interner,
1307 indent: usize,
1308 mutable_vars: &HashSet<Symbol>,
1309 ctx: &mut RefinementContext<'a>,
1310 lww_fields: &HashSet<(String, String)>,
1311 mv_fields: &HashSet<(String, String)>,
1312 synced_vars: &mut HashSet<Symbol>,
1313 var_caps: &HashMap<Symbol, VariableCapabilities>,
1314 async_functions: &HashSet<Symbol>,
1315 pipe_vars: &HashSet<Symbol>,
1316 boxed_fields: &HashSet<(String, String, String)>,
1317 registry: &TypeRegistry,
1318 type_env: &crate::analysis::types::TypeEnv,
1319 indent_str: &str,
1320 names: &RustNames,
1321) -> String {
1322 use crate::ast::stmt::Pattern;
1323
1324 let written = crate::optimize::WriteSet::of_block(body);
1327 let binding = |sym: Symbol| {
1328 let name = interner.resolve(sym);
1329 if written.may_write(sym) {
1330 format!("mut {name}")
1331 } else {
1332 name.to_string()
1333 }
1334 };
1335 let pattern_str = match pattern {
1336 Pattern::Identifier(sym) => binding(*sym),
1337 Pattern::Tuple(syms) => {
1338 let names = syms.iter().map(|s| binding(*s)).collect::<Vec<_>>().join(", ");
1339 format!("({})", names)
1340 }
1341 };
1342
1343 if super::tower::is_tower_expr(iterable, ctx.get_variable_types(), interner) {
1345 let items = super::tower::statement_value(
1346 iterable,
1347 interner,
1348 synced_vars,
1349 async_functions,
1350 boxed_fields,
1351 registry,
1352 ctx.get_variable_types(),
1353 );
1354 let bound: Vec<Symbol> = match pattern {
1355 Pattern::Identifier(sym) => {
1356 writeln!(
1357 output,
1358 "{}for {} in logicaffeine_data::failure::answered(({}).items()) {{",
1359 indent_str, pattern_str, items
1360 )
1361 .unwrap();
1362 vec![*sym]
1363 }
1364 Pattern::Tuple(syms) => {
1365 writeln!(
1366 output,
1367 "{}for __tower_item in logicaffeine_data::failure::answered(({}).items()) {{",
1368 indent_str, items
1369 )
1370 .unwrap();
1371 for (k, sym) in syms.iter().enumerate() {
1372 writeln!(
1373 output,
1374 "{} let {}: {} = logicaffeine_data::failure::answered(__tower_item.item(&LogosValue::Int({}_i64)));",
1375 indent_str,
1376 binding(*sym),
1377 super::tower::VALUE,
1378 k + 1
1379 )
1380 .unwrap();
1381 }
1382 syms.clone()
1383 }
1384 };
1385 ctx.push_scope();
1386 let shadowed: Vec<(Symbol, Option<String>)> = bound
1387 .iter()
1388 .map(|sym| (*sym, ctx.get_variable_types().get(sym).cloned()))
1389 .collect();
1390 for sym in &bound {
1391 ctx.register_variable_type(*sym, super::tower::VALUE.to_string());
1392 }
1393 for s in body.iter() {
1394 output.push_str(&codegen_stmt(
1395 s,
1396 interner,
1397 indent + 1,
1398 mutable_vars,
1399 ctx,
1400 lww_fields,
1401 mv_fields,
1402 synced_vars,
1403 var_caps,
1404 async_functions,
1405 pipe_vars,
1406 boxed_fields,
1407 registry,
1408 type_env,
1409 ));
1410 }
1411 for (sym, before) in shadowed {
1412 match before {
1413 Some(t) => ctx.register_variable_type(sym, t),
1414 None => {
1415 ctx.get_variable_types_mut().remove(&sym);
1416 }
1417 }
1418 }
1419 ctx.pop_scope();
1420 writeln!(output, "{}}}", indent_str).unwrap();
1421 return output;
1422 }
1423
1424 let held = match pattern {
1426 Pattern::Identifier(item) => {
1427 let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
1428 super::absent::iteration(iterable, &ecx).map(|(items, ty)| (*item, items, ty))
1429 }
1430 Pattern::Tuple(_) => None,
1431 };
1432 if let Some((item, items, ty)) = held {
1433 writeln!(output, "{}for {} in {} {{", indent_str, pattern_str, items).unwrap();
1434 ctx.push_scope();
1435 let before = ctx.get_variable_types().get(&item).cloned();
1436 ctx.register_variable_type(item, ty);
1437 for s in body.iter() {
1438 output.push_str(&codegen_stmt(
1439 s,
1440 interner,
1441 indent + 1,
1442 mutable_vars,
1443 ctx,
1444 lww_fields,
1445 mv_fields,
1446 synced_vars,
1447 var_caps,
1448 async_functions,
1449 pipe_vars,
1450 boxed_fields,
1451 registry,
1452 type_env,
1453 ));
1454 }
1455 match before {
1456 Some(t) => ctx.register_variable_type(item, t),
1457 None => {
1458 ctx.get_variable_types_mut().remove(&item);
1459 }
1460 }
1461 ctx.pop_scope();
1462 writeln!(output, "{}}}", indent_str).unwrap();
1463 return output;
1464 }
1465
1466 if super::affine_array::is_indexed_init_loop(body, |s| ctx.is_indexed_buffer(s)) {
1471 return output;
1472 }
1473
1474 if let Pattern::Identifier(loop_var) = pattern {
1480 if let Some((w, info)) = scratch_fill_target(body, ctx) {
1481 let wname = names.ident(w);
1482 writeln!(
1483 output,
1484 "{}let {}{}: [{}; {}] = ::std::array::from_fn(|__k: usize| {{",
1485 indent_str,
1486 if info.mutated { "mut " } else { "" },
1487 wname,
1488 info.elem_ty,
1489 info.len
1490 )
1491 .unwrap();
1492 writeln!(
1493 output,
1494 "{} let {} = ({} as i64) + (__k as i64);",
1495 indent_str,
1496 interner.resolve(*loop_var),
1497 info.lo
1498 )
1499 .unwrap();
1500 ctx.push_scope();
1501 ctx.register_variable_type(*loop_var, "i64".to_string());
1502 let mut push_val: Option<&Expr> = None;
1503 for s in body.iter() {
1504 match s {
1505 Stmt::Push {
1506 collection: Expr::Identifier(c),
1507 value,
1508 } if *c == w => {
1509 push_val = Some(value);
1510 }
1511 other => output.push_str(&codegen_stmt(
1512 other,
1513 interner,
1514 indent + 1,
1515 mutable_vars,
1516 ctx,
1517 lww_fields,
1518 mv_fields,
1519 synced_vars,
1520 var_caps,
1521 async_functions,
1522 pipe_vars,
1523 boxed_fields,
1524 registry,
1525 type_env,
1526 )),
1527 }
1528 }
1529 let val = codegen_expr_boxed_with_types_oracle(
1530 push_val.expect("scratch fill loop has exactly one push"),
1531 interner,
1532 synced_vars,
1533 boxed_fields,
1534 registry,
1535 async_functions,
1536 ctx.get_string_vars(),
1537 ctx.get_variable_types(),
1538 ctx.get_fast_div(),
1539 ctx.oracle(),
1540 );
1541 writeln!(output, "{} {}", indent_str, val).unwrap();
1542 ctx.pop_scope();
1543 writeln!(output, "{}}});", indent_str).unwrap();
1544 return output;
1545 }
1546 }
1547
1548 let iter_str = codegen_expr_with_async(
1549 iterable,
1550 interner,
1551 synced_vars,
1552 async_functions,
1553 ctx.get_variable_types(),
1554 );
1555 if let Pattern::Identifier(counter) = pattern {
1556 mark_fixed_array_counter_accesses(*counter, iterable, body, ctx.get_variable_types());
1557 }
1558
1559 let par_emitted = if let Pattern::Identifier(var_sym) = pattern {
1563 if let Some(par_code) = try_emit_parallel_reduction(
1564 *var_sym,
1565 &pattern_str,
1566 &iter_str,
1567 iterable,
1568 body,
1569 interner,
1570 indent,
1571 ctx,
1572 synced_vars,
1573 async_functions,
1574 ) {
1575 output.push_str(&par_code);
1576 true
1577 } else {
1578 false
1579 }
1580 } else {
1581 false
1582 };
1583
1584 if par_emitted {
1585 } else if body
1587 .iter()
1588 .any(|s| requires_async_stmt(s) || calls_async_function(s, async_functions))
1589 {
1590 writeln!(
1592 output,
1593 "{}let mut __iter = ({}).into_iter();",
1594 indent_str, iter_str
1595 )
1596 .unwrap();
1597 writeln!(
1598 output,
1599 "{}while let Some({}) = __iter.next() {{",
1600 indent_str, pattern_str
1601 )
1602 .unwrap();
1603 } else {
1604 let is_logos_seq = if let Expr::Identifier(coll_sym) = iterable {
1606 ctx.get_variable_types()
1607 .get(coll_sym)
1608 .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
1609 .map_or(false, |t| t.starts_with("LogosSeq"))
1610 } else {
1611 false
1612 };
1613 let is_text_bytes = if let Expr::Identifier(coll_sym) = iterable {
1616 ctx.get_variable_types()
1617 .get(coll_sym)
1618 .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
1619 .map_or(false, |t| t == "TextBytes")
1620 } else {
1621 false
1622 };
1623
1624 let iterates_text = matches!(
1636 super::types::infer_logos_type(iterable, interner, ctx.get_variable_types()),
1637 crate::analysis::types::LogosType::String
1638 );
1639 if let (Pattern::Identifier(_), Expr::Range { start, end }) = (pattern, iterable) {
1640 let emit = |e: &Expr| {
1641 let ecx = super::expr::ExprCtx {
1642 async_functions,
1643 variable_types: ctx.get_variable_types(),
1644 ..super::expr::ExprCtx::bare(interner, synced_vars)
1645 };
1646 super::rational::integer_operand(e, crate::semantics::collections::IntegerPlace::Range, &ecx)
1647 .unwrap_or_else(|| {
1648 codegen_expr_with_async(
1649 e,
1650 interner,
1651 synced_vars,
1652 async_functions,
1653 ctx.get_variable_types(),
1654 )
1655 })
1656 };
1657 let (start_str, end_str) = super::expr::range_bound_strs(start, end, emit);
1658 let range =
1659 super::expr::counted_loop_range(start, end, &start_str, &end_str, ctx.oracle());
1660 writeln!(output, "{}for {} in {} {{", indent_str, pattern_str, range).unwrap();
1661 } else if iterates_text {
1662 if let Pattern::Identifier(sym) = pattern {
1667 ctx.register_variable_type(*sym, "String".to_string());
1668 }
1669 writeln!(
1670 output,
1671 "{}for {} in {}.chars().map(|__c| __c.to_string()).collect::<Vec<String>>() {{",
1672 indent_str, pattern_str, iter_str
1673 )
1674 .unwrap();
1675 } else if is_text_bytes {
1676 if let Pattern::Identifier(sym) = pattern {
1680 ctx.register_variable_type(*sym, "i64".to_string());
1681 }
1682 writeln!(
1683 output,
1684 "{}for {} in {}.iter().map(|&__x| __x as i64) {{",
1685 indent_str, pattern_str, iter_str
1686 )
1687 .unwrap();
1688 } else if is_logos_seq {
1689 let coll = match iterable {
1693 Expr::Identifier(xs) => Some(*xs),
1694 _ => None,
1695 };
1696 let lent = crate::optimize::facts::holds_stmt(
1697 crate::optimize::facts::Fact::LentIteration,
1698 repeat,
1699 );
1700 if lent {
1701 crate::optimize::mark_fired(crate::optimization::Opt::Borrow);
1702 let seq_ty = coll
1703 .and_then(|xs| ctx.get_variable_types().get(&xs))
1704 .cloned()
1705 .unwrap_or_default();
1706 let held = seq_ty.split("|__hl:").next().unwrap_or(&seq_ty);
1707 let elem = held
1708 .strip_prefix("LogosSeq<")
1709 .and_then(|t| t.strip_suffix('>'))
1710 .unwrap_or("_");
1711 let each = if is_copy_type(elem) {
1712 "copied"
1713 } else {
1714 "cloned"
1715 };
1716 writeln!(
1717 output,
1718 "{}for {} in {}.borrow().iter().{}() {{",
1719 indent_str, pattern_str, iter_str, each
1720 )
1721 .unwrap();
1722 } else {
1723 writeln!(
1724 output,
1725 "{}for {} in {}.to_vec() {{",
1726 indent_str, pattern_str, iter_str
1727 )
1728 .unwrap();
1729 }
1730 } else {
1731 let (use_iter_copied, use_iter_cloned) = if let Expr::Identifier(coll_sym) = iterable {
1735 if let Some(coll_type_raw) = ctx.get_variable_types().get(coll_sym) {
1736 let coll_type = coll_type_raw
1738 .split("|__hl:")
1739 .next()
1740 .unwrap_or(coll_type_raw.as_str());
1741 if coll_type.starts_with('[') {
1742 let elem = coll_type
1744 .strip_prefix('[')
1745 .and_then(|s| s.split(';').next())
1746 .unwrap_or("_")
1747 .trim();
1748 if is_copy_type(elem) {
1749 (true, false)
1750 } else {
1751 (false, true)
1752 }
1753 } else if coll_type.starts_with("&[") {
1754 let inner = coll_type
1758 .strip_prefix("&[")
1759 .and_then(|s| s.strip_suffix(']'))
1760 .unwrap_or("_");
1761 let elem = inner.split(';').next().unwrap_or(inner).trim();
1762 if is_copy_type(elem) {
1763 (true, false)
1764 } else {
1765 (false, true)
1766 }
1767 } else if coll_type.starts_with("Vec")
1768 && has_copy_element_type(coll_type)
1769 && !body_mutates_collection(body, *coll_sym)
1770 {
1771 (true, false)
1772 } else if coll_type.starts_with("Vec")
1773 && !body_mutates_collection(body, *coll_sym)
1774 {
1775 (false, true)
1779 } else {
1780 (false, false)
1781 }
1782 } else {
1783 (false, false)
1784 }
1785 } else {
1786 (false, false)
1787 };
1788
1789 if use_iter_copied {
1790 writeln!(
1791 output,
1792 "{}for {} in {}.iter().copied() {{",
1793 indent_str, pattern_str, iter_str
1794 )
1795 .unwrap();
1796 } else if use_iter_cloned {
1797 writeln!(
1798 output,
1799 "{}for {} in {}.iter().cloned() {{",
1800 indent_str, pattern_str, iter_str
1801 )
1802 .unwrap();
1803 } else {
1804 writeln!(
1807 output,
1808 "{}for {} in {}.clone() {{",
1809 indent_str, pattern_str, iter_str
1810 )
1811 .unwrap();
1812 }
1813 }
1814 }
1815 if !par_emitted {
1816 ctx.push_scope();
1817 if let Pattern::Identifier(pvar) = pattern {
1819 if let Some(list) = super::rational::rational_type_of(iterable, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
1820 if let crate::analysis::types::LogosType::Seq(item) = super::rational::named(&list) {
1821 ctx.register_variable_type(*pvar, item.to_rust_type());
1822 }
1823 }
1824 }
1825 if let (Pattern::Identifier(pvar), Expr::Identifier(coll_sym)) = (pattern, iterable) {
1830 if let Some(ct) = ctx.get_variable_types().get(coll_sym).cloned() {
1831 let inner = ct.split("|__hl:").next().unwrap_or(ct.as_str());
1832 let elem = inner
1833 .strip_prefix("LogosSeq<")
1834 .and_then(|s| s.strip_suffix('>'))
1835 .or_else(|| inner.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>')))
1836 .or_else(|| {
1840 inner
1841 .strip_prefix("&[")
1842 .and_then(|s| s.strip_suffix(']'))
1843 .map(|s| s.split(';').next().unwrap_or(s))
1844 })
1845 .or_else(|| {
1846 inner
1847 .strip_prefix('[')
1848 .and_then(|s| s.strip_suffix(']'))
1849 .map(|s| s.split(';').next().unwrap_or(s))
1850 })
1851 .map(str::trim);
1852 if let Some(e) = elem {
1853 if matches!(
1854 e,
1855 "LogosMoney"
1856 | "LogosQuantity"
1857 | "LogosModular"
1858 | "LogosUuid"
1859 | "LogosComplex"
1860 | "LogosDecimal"
1861 ) {
1862 ctx.register_variable_type(*pvar, e.to_string());
1863 } else if registry.iter_types().any(|(sym, def)| {
1864 matches!(def, TypeDef::Struct { .. })
1865 && crate::codegen::types::rust_type_ident(interner.resolve(*sym)) == e
1866 }) && !ctx.get_variable_types().contains_key(pvar)
1867 {
1868 ctx.register_variable_type(*pvar, e.to_string());
1877 } else if e == "String" && !ctx.get_variable_types().contains_key(pvar) {
1878 ctx.register_variable_type(*pvar, "String".to_string());
1883 } else if e.starts_with("LogosTuple ")
1884 && !ctx.get_variable_types().contains_key(pvar)
1885 {
1886 ctx.register_variable_type(*pvar, e.to_string());
1889 }
1890 }
1891 }
1892 }
1893 {
1895 let body_refs: Vec<&Stmt> = body.iter().collect();
1896 let mut bi = 0;
1897 while bi < body_refs.len() {
1898 if let Some((code, skip)) = super::peephole::try_block_peepholes(
1899 &body_refs,
1900 bi,
1901 interner,
1902 indent + 1,
1903 mutable_vars,
1904 ctx,
1905 lww_fields,
1906 mv_fields,
1907 synced_vars,
1908 var_caps,
1909 async_functions,
1910 pipe_vars,
1911 boxed_fields,
1912 registry,
1913 type_env,
1914 ) {
1915 output.push_str(&code);
1916 bi += 1 + skip;
1917 continue;
1918 }
1919 output.push_str(&codegen_stmt(
1920 body_refs[bi],
1921 interner,
1922 indent + 1,
1923 mutable_vars,
1924 ctx,
1925 lww_fields,
1926 mv_fields,
1927 synced_vars,
1928 var_caps,
1929 async_functions,
1930 pipe_vars,
1931 boxed_fields,
1932 registry,
1933 type_env,
1934 ));
1935 bi += 1;
1936 }
1937 }
1938 ctx.pop_scope();
1939 writeln!(output, "{}}}", indent_str).unwrap();
1940 }
1941 output
1942}
1943
1944#[inline(never)]
1946#[allow(clippy::too_many_arguments)]
1947fn codegen_inspect_stmt<'a>(
1948 mut output: String,
1949 target: &&'a Expr<'a>,
1950 arms: &[MatchArm<'a>],
1951 interner: &Interner,
1952 indent: usize,
1953 mutable_vars: &HashSet<Symbol>,
1954 ctx: &mut RefinementContext<'a>,
1955 lww_fields: &HashSet<(String, String)>,
1956 mv_fields: &HashSet<(String, String)>,
1957 synced_vars: &mut HashSet<Symbol>,
1958 var_caps: &HashMap<Symbol, VariableCapabilities>,
1959 async_functions: &HashSet<Symbol>,
1960 pipe_vars: &HashSet<Symbol>,
1961 boxed_fields: &HashSet<(String, String, String)>,
1962 registry: &TypeRegistry,
1963 type_env: &crate::analysis::types::TypeEnv,
1964 indent_str: &str,
1965) -> String {
1966 let target_str = codegen_expr_with_async(
1967 target,
1968 interner,
1969 synced_vars,
1970 async_functions,
1971 ctx.get_variable_types(),
1972 );
1973
1974 let hoist = matches!(
2003 target,
2004 Expr::Call { .. } | Expr::CallExpr { .. } | Expr::New { .. } | Expr::NewVariant { .. }
2005 );
2006 let lent_scrutinee = matches!(target, Expr::Identifier(t)
2009 if ctx.get_variable_types().get(t).is_some_and(|ty| super::expr::is_lent_record(ty)));
2010 if hoist {
2011 writeln!(
2014 output,
2015 "{}let __inspect_target = {};",
2016 indent_str, target_str
2017 )
2018 .unwrap();
2019 writeln!(output, "{}match __inspect_target {{", indent_str).unwrap();
2020 } else if lent_scrutinee {
2021 writeln!(output, "{}match *{} {{", indent_str, target_str).unwrap();
2022 } else {
2023 writeln!(output, "{}match {} {{", indent_str, target_str).unwrap();
2024 }
2025
2026 for arm in arms {
2027 let mut inner_boxed_binding_names: HashSet<String> = HashSet::new();
2032 if let (Some(variant), Some(enum_name)) =
2034 (arm.variant, enum_name_of_arm(arm, registry, interner))
2035 {
2036 for (field, binding) in arm.bindings.iter() {
2037 let key = (
2038 enum_name.clone(),
2039 interner.resolve(variant).to_string(),
2040 interner.resolve(*field).to_string(),
2041 );
2042 if boxed_fields.contains(&key) {
2043 inner_boxed_binding_names.insert(interner.resolve(*binding).to_string());
2044 }
2045 }
2046 }
2047 let (pattern, prelude) = inspect_arm_pattern(arm, registry, interner);
2048 writeln!(output, "{} {} => {{", indent_str, pattern).unwrap();
2049 if !prelude.is_empty() {
2050 writeln!(output, "{} {}", indent_str, prelude).unwrap();
2051 }
2052
2053 ctx.push_scope();
2054
2055 let mut lent_bindings: HashSet<Symbol> = HashSet::new();
2058
2059 if let Some(variant_sym) = arm.variant {
2062 if let Some((_enum_name, variant_def)) = registry.find_variant(variant_sym) {
2063 for (field_sym, binding_sym) in &arm.bindings {
2064 if let Some(field_def) =
2065 variant_def.fields.iter().find(|f| f.name == *field_sym)
2066 {
2067 let rust_type = super::types::codegen_field_type(&field_def.ty, interner);
2068 let lendable = field_is_user_enum(&field_def.ty, registry)
2069 && !mutable_vars.contains(binding_sym)
2070 && super::lent::only_borrowed_uses(
2071 arm.body,
2072 *binding_sym,
2073 interner,
2074 &|f, j| {
2075 super::expr::lends_record_at(f, j, ctx.get_variable_types())
2076 },
2077 );
2078 if lendable {
2079 lent_bindings.insert(*binding_sym);
2080 ctx.register_variable_type(*binding_sym, format!("&{}", rust_type));
2081 } else {
2082 ctx.register_variable_type(*binding_sym, rust_type);
2083 }
2084 }
2085 }
2086 }
2087 }
2088 for sym in &lent_bindings {
2089 inner_boxed_binding_names.remove(interner.resolve(*sym));
2090 }
2091
2092 let written = |name: &str| {
2096 if mutable_vars.iter().any(|s| interner.resolve(*s) == name) {
2097 "mut "
2098 } else {
2099 ""
2100 }
2101 };
2102
2103 for binding_name in &inner_boxed_binding_names {
2106 let ident = escape_rust_ident(binding_name);
2107 writeln!(
2108 output,
2109 "{} let {}{} = (**{}).clone();",
2110 indent_str,
2111 written(binding_name),
2112 ident,
2113 ident
2114 )
2115 .unwrap();
2116 }
2117
2118 if let Some(_) = arm.variant {
2121 for (_field, binding) in &arm.bindings {
2122 let binding_name = interner.resolve(*binding);
2123 let ident = escape_rust_ident(binding_name);
2124 if lent_bindings.contains(binding) {
2125 if arm_binding_is_boxed(
2126 arm,
2127 *binding,
2128 enum_name_of_arm(arm, registry, interner).as_deref(),
2129 boxed_fields,
2130 interner,
2131 ) {
2132 writeln!(
2133 output,
2134 "{} let {} = &**{};",
2135 indent_str, ident, ident
2136 )
2137 .unwrap();
2138 }
2139 } else if !inner_boxed_binding_names.contains(binding_name) {
2140 writeln!(
2141 output,
2142 "{} let {}{} = {}.clone();",
2143 indent_str,
2144 written(binding_name),
2145 ident,
2146 ident
2147 )
2148 .unwrap();
2149 }
2150 }
2151 }
2152
2153 for stmt in arm.body {
2154 let inner_stmt_code = if let Stmt::Inspect {
2158 target: inner_target,
2159 ..
2160 } = stmt
2161 {
2162 if let Expr::Identifier(sym) = inner_target {
2165 let target_name = interner.resolve(*sym);
2166 if inner_boxed_binding_names.contains(target_name) {
2167 let mut inner_output = String::new();
2169 writeln!(
2170 inner_output,
2171 "{}match {} {{",
2172 " ".repeat(indent + 2),
2173 escape_rust_ident(target_name)
2174 )
2175 .unwrap();
2176
2177 if let Stmt::Inspect {
2178 arms: inner_arms, ..
2179 } = stmt
2180 {
2181 for inner_arm in inner_arms.iter() {
2182 let (pattern, prelude) =
2183 inspect_arm_pattern(inner_arm, registry, interner);
2184 let inner_indent = " ".repeat(indent + 2);
2185 writeln!(inner_output, "{inner_indent} {pattern} => {{")
2186 .unwrap();
2187 if !prelude.is_empty() {
2188 writeln!(inner_output, "{inner_indent} {prelude}")
2189 .unwrap();
2190 }
2191
2192 ctx.push_scope();
2193 for inner_stmt in inner_arm.body {
2194 inner_output.push_str(&codegen_stmt(
2195 inner_stmt,
2196 interner,
2197 indent + 4,
2198 mutable_vars,
2199 ctx,
2200 lww_fields,
2201 mv_fields,
2202 synced_vars,
2203 var_caps,
2204 async_functions,
2205 pipe_vars,
2206 boxed_fields,
2207 registry,
2208 type_env,
2209 ));
2210 }
2211 ctx.pop_scope();
2212 writeln!(inner_output, "{} }}", " ".repeat(indent + 2))
2213 .unwrap();
2214 }
2215 }
2216 writeln!(inner_output, "{}}}", " ".repeat(indent + 2)).unwrap();
2217 inner_output
2218 } else {
2219 codegen_stmt(
2220 stmt,
2221 interner,
2222 indent + 2,
2223 mutable_vars,
2224 ctx,
2225 lww_fields,
2226 mv_fields,
2227 synced_vars,
2228 var_caps,
2229 async_functions,
2230 pipe_vars,
2231 boxed_fields,
2232 registry,
2233 type_env,
2234 )
2235 }
2236 } else {
2237 codegen_stmt(
2238 stmt,
2239 interner,
2240 indent + 2,
2241 mutable_vars,
2242 ctx,
2243 lww_fields,
2244 mv_fields,
2245 synced_vars,
2246 var_caps,
2247 async_functions,
2248 pipe_vars,
2249 boxed_fields,
2250 registry,
2251 type_env,
2252 )
2253 }
2254 } else {
2255 codegen_stmt(
2256 stmt,
2257 interner,
2258 indent + 2,
2259 mutable_vars,
2260 ctx,
2261 lww_fields,
2262 mv_fields,
2263 synced_vars,
2264 var_caps,
2265 async_functions,
2266 pipe_vars,
2267 boxed_fields,
2268 registry,
2269 type_env,
2270 )
2271 };
2272 output.push_str(&inner_stmt_code);
2273 }
2274 ctx.pop_scope();
2275 writeln!(output, "{} }}", indent_str).unwrap();
2276 }
2277
2278 writeln!(output, "{}}}", indent_str).unwrap();
2279 output
2280}
2281
2282fn field_is_user_enum(ty: &FieldType, registry: &TypeRegistry) -> bool {
2284 let name = match ty {
2285 FieldType::Named(s) | FieldType::Primitive(s) => *s,
2286 FieldType::Generic { base, .. } => *base,
2287 _ => return false,
2288 };
2289 matches!(registry.get(name), Some(TypeDef::Enum { .. }))
2290}
2291
2292fn enum_name_of_arm(
2294 arm: &MatchArm,
2295 registry: &TypeRegistry,
2296 interner: &Interner,
2297) -> Option<String> {
2298 arm.enum_name
2299 .map(|e| interner.resolve(e).to_string())
2300 .or_else(|| {
2301 arm.variant.and_then(|v| {
2302 registry
2303 .find_variant(v)
2304 .map(|(e, _)| interner.resolve(e).to_string())
2305 })
2306 })
2307}
2308
2309fn inspect_arm_pattern(
2312 arm: &MatchArm,
2313 registry: &TypeRegistry,
2314 interner: &Interner,
2315) -> (String, String) {
2316 let Some(variant) = arm.variant else {
2317 return ("_".to_string(), String::new());
2318 };
2319 let variant_name = interner.resolve(variant);
2320 let enum_name = enum_name_of_arm(arm, registry, interner);
2327 let path = match enum_name.as_deref() {
2328 Some(e) => format!("{}::{}", super::types::rust_type_ident(e), variant_name),
2329 None => variant_name.to_string(),
2330 };
2331 if arm.bindings.is_empty() {
2332 return (path, String::new());
2333 }
2334 if variant_name == "Some" {
2335 let binding = escape_rust_ident(interner.resolve(arm.bindings[0].1));
2339 return (format!("Some(ref {binding})"), String::new());
2340 }
2341 let binds: Vec<(String, String)> = arm
2342 .bindings
2343 .iter()
2344 .map(|(f, b)| {
2345 (
2346 escape_rust_ident(interner.resolve(*f)),
2347 escape_rust_ident(interner.resolve(*b)),
2348 )
2349 })
2350 .collect();
2351 let variant_def = match arm.enum_name {
2352 Some(e) => registry.variant_in(e, variant),
2353 None => registry.find_variant(variant).map(|(_, v)| v),
2354 };
2355 let shape = match (variant_def, enum_name.as_deref()) {
2356 (Some(v), Some(e)) => super::types::VariantShape::of(v, e, interner),
2357 _ => super::types::VariantShape::InPlace,
2358 };
2359 shape.pattern(&path, &binds, true)
2360}
2361
2362fn arm_binding_is_boxed(
2364 arm: &MatchArm,
2365 binding: Symbol,
2366 enum_name: Option<&str>,
2367 boxed_fields: &HashSet<(String, String, String)>,
2368 interner: &Interner,
2369) -> bool {
2370 let (Some(enum_name), Some(variant)) = (enum_name, arm.variant) else {
2371 return false;
2372 };
2373 arm.bindings.iter().any(|(field, b)| {
2374 *b == binding
2375 && boxed_fields.contains(&(
2376 enum_name.to_string(),
2377 interner.resolve(variant).to_string(),
2378 interner.resolve(*field).to_string(),
2379 ))
2380 })
2381}
2382
2383#[inline(never)]
2385#[allow(clippy::too_many_arguments)]
2386fn codegen_concurrent_stmt<'a>(
2387 mut output: String,
2388 tasks: &Block<'a>,
2389 interner: &Interner,
2390 indent: usize,
2391 mutable_vars: &HashSet<Symbol>,
2392 ctx: &mut RefinementContext<'a>,
2393 lww_fields: &HashSet<(String, String)>,
2394 mv_fields: &HashSet<(String, String)>,
2395 synced_vars: &mut HashSet<Symbol>,
2396 var_caps: &HashMap<Symbol, VariableCapabilities>,
2397 async_functions: &HashSet<Symbol>,
2398 pipe_vars: &HashSet<Symbol>,
2399 boxed_fields: &HashSet<(String, String, String)>,
2400 registry: &TypeRegistry,
2401 type_env: &crate::analysis::types::TypeEnv,
2402 indent_str: &str,
2403) -> String {
2404 let let_bindings: Vec<_> = tasks
2406 .iter()
2407 .filter_map(|s| {
2408 if let Stmt::Let { var, .. } = s {
2409 Some(interner.resolve(*var).to_string())
2410 } else {
2411 None
2412 }
2413 })
2414 .collect();
2415
2416 let defined_vars: HashSet<Symbol> = tasks
2418 .iter()
2419 .filter_map(|s| {
2420 if let Stmt::Let { var, .. } = s {
2421 Some(*var)
2422 } else {
2423 None
2424 }
2425 })
2426 .collect();
2427
2428 let mut has_intra_dependency = false;
2431 let mut seen_defs: HashSet<Symbol> = HashSet::new();
2432 for s in *tasks {
2433 let mut used_in_task: HashSet<Symbol> = HashSet::new();
2435 collect_stmt_identifiers(s, &mut used_in_task);
2436 for used_var in &used_in_task {
2437 if seen_defs.contains(used_var) {
2438 has_intra_dependency = true;
2439 break;
2440 }
2441 }
2442 if let Stmt::Let { var, .. } = s {
2444 seen_defs.insert(*var);
2445 }
2446 if has_intra_dependency {
2447 break;
2448 }
2449 }
2450
2451 let mut used_syms: HashSet<Symbol> = HashSet::new();
2454 for s in *tasks {
2455 collect_stmt_identifiers(s, &mut used_syms);
2456 }
2457 for def_var in &defined_vars {
2459 used_syms.remove(def_var);
2460 }
2461 let used_vars: HashSet<String> = used_syms
2462 .iter()
2463 .map(|sym| interner.resolve(*sym).to_string())
2464 .collect();
2465
2466 if has_intra_dependency {
2468 for stmt in *tasks {
2470 output.push_str(&codegen_stmt(
2471 stmt,
2472 interner,
2473 indent,
2474 mutable_vars,
2475 ctx,
2476 lww_fields,
2477 mv_fields,
2478 synced_vars,
2479 var_caps,
2480 async_functions,
2481 pipe_vars,
2482 boxed_fields,
2483 registry,
2484 type_env,
2485 ));
2486 }
2487 } else {
2488 if !let_bindings.is_empty() {
2490 writeln!(
2492 output,
2493 "{}let ({}) = tokio::join!(",
2494 indent_str,
2495 let_bindings.join(", ")
2496 )
2497 .unwrap();
2498 } else {
2499 writeln!(output, "{}tokio::join!(", indent_str).unwrap();
2500 }
2501
2502 for (i, stmt) in tasks.iter().enumerate() {
2503 let inner_code = match stmt {
2506 Stmt::Let { value, .. } => {
2507 codegen_expr_with_async(
2510 value,
2511 interner,
2512 synced_vars,
2513 async_functions,
2514 ctx.get_variable_types(),
2515 )
2516 }
2517 Stmt::Call { function, args } => {
2518 let func_name = interner.resolve(*function);
2519 let args_str: Vec<String> = args
2520 .iter()
2521 .map(|a| {
2522 codegen_expr_with_async(
2523 a,
2524 interner,
2525 synced_vars,
2526 async_functions,
2527 ctx.get_variable_types(),
2528 )
2529 })
2530 .collect();
2531 let await_suffix = if async_functions.contains(function) {
2533 ".await"
2534 } else {
2535 ""
2536 };
2537 format!("{}({}){}", func_name, args_str.join(", "), await_suffix)
2538 }
2539 _ => {
2540 let inner = codegen_stmt(
2542 stmt,
2543 interner,
2544 indent + 1,
2545 mutable_vars,
2546 ctx,
2547 lww_fields,
2548 mv_fields,
2549 synced_vars,
2550 var_caps,
2551 async_functions,
2552 pipe_vars,
2553 boxed_fields,
2554 registry,
2555 type_env,
2556 );
2557 inner.trim().to_string()
2558 }
2559 };
2560
2561 if !used_vars.is_empty() && i < tasks.len() - 1 {
2563 let clones: Vec<String> = used_vars
2565 .iter()
2566 .map(|v| format!("let {} = {}.clone();", v, v))
2567 .collect();
2568 write!(
2569 output,
2570 "{} {{ {} async move {{ {} }} }}",
2571 indent_str,
2572 clones.join(" "),
2573 inner_code
2574 )
2575 .unwrap();
2576 } else {
2577 write!(output, "{} async {{ {} }}", indent_str, inner_code).unwrap();
2579 }
2580
2581 if i < tasks.len() - 1 {
2582 writeln!(output, ",").unwrap();
2583 } else {
2584 writeln!(output).unwrap();
2585 }
2586 }
2587
2588 writeln!(output, "{});", indent_str).unwrap();
2589 }
2590 output
2591}
2592
2593#[inline(never)]
2595#[allow(clippy::too_many_arguments)]
2596fn codegen_parallel_stmt<'a>(
2597 mut output: String,
2598 tasks: &Block<'a>,
2599 interner: &Interner,
2600 indent: usize,
2601 mutable_vars: &HashSet<Symbol>,
2602 ctx: &mut RefinementContext<'a>,
2603 lww_fields: &HashSet<(String, String)>,
2604 mv_fields: &HashSet<(String, String)>,
2605 synced_vars: &mut HashSet<Symbol>,
2606 var_caps: &HashMap<Symbol, VariableCapabilities>,
2607 async_functions: &HashSet<Symbol>,
2608 pipe_vars: &HashSet<Symbol>,
2609 boxed_fields: &HashSet<(String, String, String)>,
2610 registry: &TypeRegistry,
2611 type_env: &crate::analysis::types::TypeEnv,
2612 indent_str: &str,
2613) -> String {
2614 if tasks.len() < 2 {
2615 for stmt in tasks.iter() {
2616 output.push_str(&codegen_stmt(
2617 stmt,
2618 interner,
2619 indent,
2620 mutable_vars,
2621 ctx,
2622 lww_fields,
2623 mv_fields,
2624 synced_vars,
2625 var_caps,
2626 async_functions,
2627 pipe_vars,
2628 boxed_fields,
2629 registry,
2630 type_env,
2631 ));
2632 }
2633 return output;
2634 }
2635 let names = RustNames::new(interner);
2636 let leaves: Vec<(String, String)> = tasks
2639 .iter()
2640 .map(|stmt| match stmt {
2641 Stmt::Let {
2642 var,
2643 value,
2644 mutable,
2645 ..
2646 } => {
2647 let code = super::types::type_silent_int_i64(value).unwrap_or_else(|| {
2648 codegen_expr_with_async(
2649 value,
2650 interner,
2651 synced_vars,
2652 async_functions,
2653 ctx.get_variable_types(),
2654 )
2655 });
2656 let name = names.ident(*var);
2657 let pattern = if *mutable || mutable_vars.contains(var) {
2658 format!("mut {name}")
2659 } else {
2660 name.to_string()
2661 };
2662 (format!("{{ {code} }}"), pattern)
2663 }
2664 _ => {
2665 let inner = codegen_stmt(
2666 stmt,
2667 interner,
2668 indent + 1,
2669 mutable_vars,
2670 ctx,
2671 lww_fields,
2672 mv_fields,
2673 synced_vars,
2674 var_caps,
2675 async_functions,
2676 pipe_vars,
2677 boxed_fields,
2678 registry,
2679 type_env,
2680 );
2681 (format!("{{ {} }}", inner.trim()), "_".to_string())
2682 }
2683 })
2684 .collect();
2685 fn tree(leaves: &[(String, String)]) -> (String, String) {
2688 if let [(code, pattern)] = leaves {
2689 return (code.clone(), pattern.clone());
2690 }
2691 let (left, right) = leaves.split_at(leaves.len() / 2);
2692 let ((lc, lp), (rc, rp)) = (tree(left), tree(right));
2693 let pattern = if lp == "_" && rp == "_" {
2694 "_".to_string()
2695 } else {
2696 format!("({lp}, {rp})")
2697 };
2698 (format!("rayon::join(|| {lc}, || {rc})"), pattern)
2699 }
2700 let (left, right) = leaves.split_at(leaves.len() / 2);
2701 let ((lc, lp), (rc, rp)) = (tree(left), tree(right));
2702 if lp == "_" && rp == "_" {
2703 writeln!(output, "{indent_str}rayon::join(").unwrap();
2704 } else {
2705 writeln!(output, "{indent_str}let ({lp}, {rp}) = rayon::join(").unwrap();
2706 }
2707 writeln!(output, "{indent_str} || {lc},").unwrap();
2708 writeln!(output, "{indent_str} || {rc}").unwrap();
2709 writeln!(output, "{indent_str});").unwrap();
2710 output
2711}
2712
2713#[inline(never)]
2715#[allow(clippy::too_many_arguments)]
2716fn codegen_zone_stmt<'a>(
2717 mut output: String,
2718 name: &Symbol,
2719 capacity: &Option<usize>,
2720 source_file: &Option<ZoneSource>,
2721 body: &Block<'a>,
2722 interner: &Interner,
2723 indent: usize,
2724 mutable_vars: &HashSet<Symbol>,
2725 ctx: &mut RefinementContext<'a>,
2726 lww_fields: &HashSet<(String, String)>,
2727 mv_fields: &HashSet<(String, String)>,
2728 synced_vars: &mut HashSet<Symbol>,
2729 var_caps: &HashMap<Symbol, VariableCapabilities>,
2730 async_functions: &HashSet<Symbol>,
2731 pipe_vars: &HashSet<Symbol>,
2732 boxed_fields: &HashSet<(String, String, String)>,
2733 registry: &TypeRegistry,
2734 type_env: &crate::analysis::types::TypeEnv,
2735 indent_str: &str,
2736) -> String {
2737 let zone_name = interner.resolve(*name);
2738
2739 if let Some(src) = source_file {
2741 use crate::ast::stmt::ZoneSource;
2744 let path_expr = match src {
2745 ZoneSource::Literal(p) => format!("\"{}\"", interner.resolve(*p)),
2746 ZoneSource::Variable(v) => format!("&{}", interner.resolve(*v)),
2747 };
2748 writeln!(
2749 output,
2750 "{}let {} = logicaffeine_system::memory::Zone::new_mapped({}).expect(\"Failed to map file\");",
2751 indent_str, zone_name, path_expr
2752 ).unwrap();
2753 } else {
2754 let cap = capacity.unwrap_or(4096); writeln!(
2757 output,
2758 "{}let {} = logicaffeine_system::memory::Zone::new_heap({});",
2759 indent_str, zone_name, cap
2760 )
2761 .unwrap();
2762 }
2763
2764 let exit = super::control::break_label().expect("a zone is a boundary");
2766 writeln!(output, "{indent_str}'{exit}: {{").unwrap();
2767 ctx.push_scope();
2768
2769 for stmt in *body {
2771 output.push_str(&codegen_stmt(
2772 stmt,
2773 interner,
2774 indent + 1,
2775 mutable_vars,
2776 ctx,
2777 lww_fields,
2778 mv_fields,
2779 synced_vars,
2780 var_caps,
2781 async_functions,
2782 pipe_vars,
2783 boxed_fields,
2784 registry,
2785 type_env,
2786 ));
2787 }
2788
2789 ctx.pop_scope();
2790 writeln!(output, "{}}}", indent_str).unwrap();
2791 output
2792}
2793
2794#[inline(never)]
2796#[allow(clippy::too_many_arguments)]
2797fn collect_count_accumulators(
2803 stmts: &[Stmt],
2804 bignum_vars: &std::collections::HashSet<Symbol>,
2805 restrict_reads: bool,
2806 allow_length_bound: bool,
2807 pure_calls: &std::collections::HashSet<Symbol>,
2808) -> std::collections::HashSet<Symbol> {
2809 use std::collections::{HashMap, HashSet};
2810 fn is_zero(e: &Expr) -> bool {
2811 matches!(e, Expr::Literal(Literal::Number(0)))
2812 }
2813 fn is_plus1(e: &Expr, x: Symbol) -> bool {
2814 matches!(e, Expr::BinaryOp { op: BinaryOpKind::Add, left, right }
2815 if matches!(left, Expr::Identifier(l) if *l == x)
2816 && matches!(right, Expr::Literal(Literal::Number(1))))
2817 }
2818 fn counted_i64(cond: &Expr, bignum: &HashSet<Symbol>, allow_length_bound: bool) -> bool {
2821 if let Expr::BinaryOp { op, left, right } = cond {
2822 if matches!(op, BinaryOpKind::Lt | BinaryOpKind::LtEq)
2823 && matches!(left, Expr::Identifier(_))
2824 {
2825 return match right {
2826 Expr::Literal(Literal::Number(_)) => true,
2827 Expr::Identifier(b) => !bignum.contains(b),
2828 Expr::Length { .. } => allow_length_bound,
2829 _ => false,
2830 };
2831 }
2832 }
2833 false
2834 }
2835 struct S {
2836 zero_let: HashSet<Symbol>, bad_let: HashSet<Symbol>, inc_loop: HashMap<Symbol, Option<usize>>, disq: HashSet<Symbol>, bail: bool, }
2842 fn disq_reads(e: &Expr, s: &mut S, restrict_reads: bool) {
2845 if !restrict_reads {
2846 return;
2847 }
2848 let mut stack = vec![e];
2849 while let Some(x) = stack.pop() {
2850 if let Expr::Identifier(r) = x {
2851 s.disq.insert(*r);
2852 }
2853 stack.extend(logicaffeine_language::ast_depth::expr_children(x));
2854 }
2855 }
2856 fn walk(
2859 stmts: &[Stmt],
2860 loop_ctx: Option<usize>,
2861 loop_depth: usize,
2862 next_id: &mut usize,
2863 bignum: &HashSet<Symbol>,
2864 restrict_reads: bool,
2865 allow_length_bound: bool,
2866 s: &mut S,
2867 ) {
2868 for st in stmts {
2869 match st {
2870 Stmt::Let { var, value, .. } => {
2871 if loop_ctx.is_none() && is_zero(value) {
2872 if !s.zero_let.insert(*var) {
2873 s.bad_let.insert(*var);
2874 }
2875 } else {
2876 s.bad_let.insert(*var);
2877 }
2878 disq_reads(value, s, restrict_reads); }
2880 Stmt::Set { target, value } => {
2881 if let Some(id) = loop_ctx {
2882 if is_plus1(value, *target) {
2883 match s.inc_loop.get(target) {
2884 None => {
2885 s.inc_loop.insert(*target, Some(id));
2886 }
2887 Some(Some(prev)) if *prev == id => {}
2888 _ => {
2889 s.inc_loop.insert(*target, None);
2890 }
2891 }
2892 continue; }
2894 }
2895 s.disq.insert(*target);
2896 disq_reads(value, s, restrict_reads);
2897 }
2898 Stmt::Show { object, .. } => {
2899 if !matches!(object, Expr::Identifier(_)) {
2900 disq_reads(object, s, restrict_reads); }
2902 }
2903 Stmt::If {
2904 cond,
2905 then_block,
2906 else_block,
2907 } => {
2908 disq_reads(cond, s, restrict_reads);
2909 walk(
2910 then_block,
2911 loop_ctx,
2912 loop_depth,
2913 next_id,
2914 bignum,
2915 restrict_reads,
2916 allow_length_bound,
2917 s,
2918 );
2919 if let Some(eb) = else_block {
2920 walk(
2921 eb,
2922 loop_ctx,
2923 loop_depth,
2924 next_id,
2925 bignum,
2926 restrict_reads,
2927 allow_length_bound,
2928 s,
2929 );
2930 }
2931 }
2932 Stmt::While { cond, body, .. } => {
2933 disq_reads(cond, s, restrict_reads);
2934 let inner = if loop_depth == 0 && counted_i64(cond, bignum, allow_length_bound)
2935 {
2936 let id = *next_id;
2937 *next_id += 1;
2938 Some(id)
2939 } else {
2940 None
2941 };
2942 walk(
2943 body,
2944 inner,
2945 loop_depth + 1,
2946 next_id,
2947 bignum,
2948 restrict_reads,
2949 allow_length_bound,
2950 s,
2951 );
2952 }
2953 Stmt::Repeat { iterable, body, .. } => {
2954 disq_reads(iterable, s, restrict_reads);
2955 walk(
2956 body,
2957 None,
2958 loop_depth + 1,
2959 next_id,
2960 bignum,
2961 restrict_reads,
2962 allow_length_bound,
2963 s,
2964 );
2965 }
2966 Stmt::Zone { body, .. } => {
2967 walk(
2968 body,
2969 None,
2970 loop_depth + 1,
2971 next_id,
2972 bignum,
2973 restrict_reads,
2974 allow_length_bound,
2975 s,
2976 );
2977 }
2978 Stmt::Inspect { target, arms, .. } => {
2979 disq_reads(target, s, restrict_reads);
2980 for arm in arms.iter() {
2981 walk(
2982 arm.body,
2983 None,
2984 loop_depth,
2985 next_id,
2986 bignum,
2987 restrict_reads,
2988 allow_length_bound,
2989 s,
2990 );
2991 }
2992 }
2993 Stmt::Return { value } => {
2994 if let Some(v) = value {
2995 disq_reads(v, s, restrict_reads);
2996 }
2997 }
2998 Stmt::Push { value, collection } => {
2999 disq_reads(value, s, restrict_reads);
3000 disq_reads(collection, s, restrict_reads);
3001 }
3002 Stmt::Call { args, .. } => {
3003 for arg in args.iter() {
3005 disq_reads(arg, s, restrict_reads);
3006 }
3007 }
3008 Stmt::Break => {}
3009 Stmt::FunctionDef { .. } => {}
3012 _ => {
3013 s.bail = true;
3016 }
3017 }
3018 }
3019 }
3020 let mut effectful = false;
3023 logicaffeine_language::ast_depth::walk_nodes(stmts, |node| {
3024 use logicaffeine_language::ast_depth::{Visited, Walk};
3025 match node {
3026 Visited::Stmt(Stmt::FunctionDef { .. }) | Visited::Expr(Expr::Closure { .. }) => {
3027 Walk::Past
3028 }
3029 Visited::Expr(Expr::Call { function, .. })
3030 | Visited::Stmt(Stmt::Call { function, .. })
3031 if !pure_calls.contains(function) =>
3032 {
3033 effectful = true;
3034 Walk::Past
3035 }
3036 Visited::Expr(Expr::CallExpr { .. } | Expr::Escape { .. }) => {
3037 effectful = true;
3038 Walk::Past
3039 }
3040 _ => Walk::Into,
3041 }
3042 });
3043 if effectful {
3044 return HashSet::new();
3045 }
3046 let mut s = S {
3047 zero_let: HashSet::new(),
3048 bad_let: HashSet::new(),
3049 inc_loop: HashMap::new(),
3050 disq: HashSet::new(),
3051 bail: false,
3052 };
3053 let mut next_id = 0usize;
3054 walk(
3055 stmts,
3056 None,
3057 0,
3058 &mut next_id,
3059 bignum_vars,
3060 restrict_reads,
3061 allow_length_bound,
3062 &mut s,
3063 );
3064 if s.bail {
3065 return HashSet::new();
3066 }
3067 s.zero_let
3068 .iter()
3069 .copied()
3070 .filter(|x| {
3071 !s.bad_let.contains(x)
3072 && !s.disq.contains(x)
3073 && matches!(s.inc_loop.get(x), Some(Some(_)))
3074 })
3075 .collect()
3076}
3077
3078pub(crate) fn collect_wide_accumulators(
3079 stmts: &[Stmt],
3080 bignum_vars: &std::collections::HashSet<Symbol>,
3081 pure_calls: &std::collections::HashSet<Symbol>,
3082) -> std::collections::HashSet<Symbol> {
3083 collect_count_accumulators(stmts, bignum_vars, true, false, pure_calls)
3084}
3085
3086pub(crate) fn collect_bounded_count_accumulators(
3090 stmts: &[Stmt],
3091 bignum_vars: &std::collections::HashSet<Symbol>,
3092) -> std::collections::HashSet<Symbol> {
3093 collect_bounded_count_accumulators_with_purity(stmts, bignum_vars, &Default::default())
3094}
3095
3096pub(crate) fn collect_bounded_count_accumulators_with_purity(
3098 stmts: &[Stmt],
3099 bignum_vars: &std::collections::HashSet<Symbol>,
3100 pure_calls: &std::collections::HashSet<Symbol>,
3101) -> std::collections::HashSet<Symbol> {
3102 use std::collections::{HashMap, HashSet};
3103
3104 fn is_plus1(e: &Expr, x: Symbol) -> bool {
3105 matches!(e, Expr::BinaryOp { op: BinaryOpKind::Add, left, right }
3106 if matches!(left, Expr::Identifier(l) if *l == x)
3107 && matches!(right, Expr::Literal(Literal::Number(1))))
3108 }
3109
3110 fn counter_advances_once(body: &[Stmt], counter: Symbol) -> bool {
3111 fn walk(block: &[Stmt], counter: Symbol, direct: bool, count: &mut usize, bad: &mut bool) {
3112 for stmt in block {
3113 match stmt {
3114 Stmt::Set { target, value } if *target == counter => {
3115 if direct && is_plus1(value, counter) {
3116 *count += 1;
3117 } else {
3118 *bad = true;
3119 }
3120 }
3121 Stmt::Let { var, .. } if *var == counter => *bad = true,
3122 Stmt::If {
3123 then_block,
3124 else_block,
3125 ..
3126 } => {
3127 walk(then_block, counter, false, count, bad);
3128 if let Some(eb) = else_block {
3129 walk(eb, counter, false, count, bad);
3130 }
3131 }
3132 Stmt::While { body, .. }
3133 | Stmt::Repeat { body, .. }
3134 | Stmt::Zone { body, .. } => walk(body, counter, false, count, bad),
3135 Stmt::Inspect { arms, .. } => {
3136 for arm in arms.iter() {
3137 walk(arm.body, counter, false, count, bad);
3138 }
3139 }
3140 Stmt::FunctionDef { .. } => {}
3141 _ => {}
3142 }
3143 }
3144 }
3145 let (mut count, mut bad) = (0, false);
3146 walk(body, counter, true, &mut count, &mut bad);
3147 !bad && count == 1
3148 }
3149
3150 fn certified_loop(
3151 cond: &Expr,
3152 body: &[Stmt],
3153 bignum: &HashSet<Symbol>,
3154 nonnegative: &HashSet<Symbol>,
3155 positive: &HashSet<Symbol>,
3156 ) -> bool {
3157 let Expr::BinaryOp { op, left, right } = cond else {
3158 return false;
3159 };
3160 let Expr::Identifier(counter) = left else {
3161 return false;
3162 };
3163 if !nonnegative.contains(counter) || !counter_advances_once(body, *counter) {
3164 return false;
3165 }
3166 match (op, right) {
3167 (BinaryOpKind::Lt, Expr::Literal(Literal::Number(_))) => true,
3168 (BinaryOpKind::Lt, Expr::Identifier(bound)) => !bignum.contains(bound),
3169 (BinaryOpKind::Lt, Expr::Length { .. }) => true,
3170 (BinaryOpKind::LtEq, Expr::Literal(Literal::Number(bound))) => {
3171 *bound < i64::MAX || positive.contains(counter)
3172 }
3173 (BinaryOpKind::LtEq, Expr::Identifier(bound)) => {
3174 positive.contains(counter) && !bignum.contains(bound)
3175 }
3176 (BinaryOpKind::LtEq, Expr::Length { .. }) => true,
3177 _ => false,
3178 }
3179 }
3180
3181 fn plus1_sites(block: &[Stmt], out: &mut HashMap<Symbol, usize>) {
3182 for stmt in block {
3183 match stmt {
3184 Stmt::Set { target, value } if is_plus1(value, *target) => {
3185 *out.entry(*target).or_insert(0) += 1;
3186 }
3187 Stmt::If {
3188 then_block,
3189 else_block,
3190 ..
3191 } => {
3192 plus1_sites(then_block, out);
3193 if let Some(eb) = else_block {
3194 plus1_sites(eb, out);
3195 }
3196 }
3197 Stmt::Zone { body, .. } => plus1_sites(body, out),
3198 Stmt::Inspect { arms, .. } => {
3199 for arm in arms.iter() {
3200 plus1_sites(arm.body, out);
3201 }
3202 }
3203 Stmt::While { .. } | Stmt::Repeat { .. } | Stmt::FunctionDef { .. } => {}
3205 _ => {}
3206 }
3207 }
3208 }
3209
3210 fn visit_loops(
3211 block: &[Stmt],
3212 bignum: &HashSet<Symbol>,
3213 nonnegative: &HashSet<Symbol>,
3214 positive: &HashSet<Symbol>,
3215 certified: &mut HashSet<Symbol>,
3216 ) {
3217 let mut positive = positive.clone();
3218 for stmt in block {
3219 match stmt {
3220 Stmt::While { cond, body, .. } => {
3221 if certified_loop(cond, body, bignum, nonnegative, &positive) {
3222 let mut sites = HashMap::new();
3223 plus1_sites(body, &mut sites);
3224 certified.extend(
3225 sites
3226 .into_iter()
3227 .filter_map(|(target, n)| (n == 1).then_some(target)),
3228 );
3229 }
3230 visit_loops(body, bignum, nonnegative, &positive, certified);
3231 }
3232 Stmt::If {
3233 then_block,
3234 else_block,
3235 ..
3236 } => {
3237 visit_loops(then_block, bignum, nonnegative, &positive, certified);
3238 if let Some(eb) = else_block {
3239 visit_loops(eb, bignum, nonnegative, &positive, certified);
3240 }
3241 }
3242 Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
3243 visit_loops(body, bignum, nonnegative, &positive, certified)
3244 }
3245 Stmt::Inspect { arms, .. } => {
3246 for arm in arms.iter() {
3247 visit_loops(arm.body, bignum, nonnegative, &positive, certified);
3248 }
3249 }
3250 Stmt::FunctionDef { .. } => {}
3251 _ => {}
3252 }
3253 match stmt {
3256 Stmt::Let { var, value, .. } | Stmt::Set { target: var, value } if matches!(value, Expr::Literal(Literal::Number(n)) if *n > 0) =>
3257 {
3258 positive.insert(*var);
3259 }
3260 Stmt::Set { target, value } if is_plus1(value, *target) => {}
3261 _ => {
3262 logicaffeine_language::ast_depth::walk_nodes(
3263 std::slice::from_ref(stmt),
3264 |node| {
3265 use logicaffeine_language::ast_depth::{Visited, Walk};
3266 match node {
3267 Visited::Stmt(Stmt::FunctionDef { .. })
3268 | Visited::Expr(Expr::Closure { .. }) => Walk::Past,
3269 Visited::Stmt(
3270 Stmt::Let { var, .. } | Stmt::Set { target: var, .. },
3271 ) => {
3272 positive.remove(var);
3273 Walk::Into
3274 }
3275 _ => Walk::Into,
3276 }
3277 },
3278 );
3279 }
3280 }
3281 }
3282 }
3283
3284 let candidates = collect_count_accumulators(stmts, bignum_vars, false, true, pure_calls);
3285 let nonnegative = super::expr::collect_always_nonneg(stmts);
3286 let mut certified = HashSet::new();
3287 visit_loops(
3288 stmts,
3289 bignum_vars,
3290 &nonnegative,
3291 &HashSet::new(),
3292 &mut certified,
3293 );
3294 candidates.intersection(&certified).copied().collect()
3295}
3296
3297fn codegen_if_stmt<'a>(
3298 mut output: String,
3299 cond: &&'a Expr<'a>,
3300 then_block: &Block<'a>,
3301 else_block: &Option<Block<'a>>,
3302 interner: &Interner,
3303 indent: usize,
3304 mutable_vars: &HashSet<Symbol>,
3305 ctx: &mut RefinementContext<'a>,
3306 lww_fields: &HashSet<(String, String)>,
3307 mv_fields: &HashSet<(String, String)>,
3308 synced_vars: &mut HashSet<Symbol>,
3309 var_caps: &HashMap<Symbol, VariableCapabilities>,
3310 async_functions: &HashSet<Symbol>,
3311 pipe_vars: &HashSet<Symbol>,
3312 boxed_fields: &HashSet<(String, String, String)>,
3313 registry: &TypeRegistry,
3314 type_env: &crate::analysis::types::TypeEnv,
3315 indent_str: &str,
3316) -> String {
3317 if let Some(fusion) = probe_fusion(
3319 cond,
3320 then_block,
3321 interner,
3322 synced_vars,
3323 async_functions,
3324 ctx,
3325 ) {
3326 let fused_head = format!(
3327 "{}if let Some::<{}>({}) = {}.get(&({})) {{",
3328 indent_str, fusion.value_ty, fusion.probe.name, fusion.map, fusion.key
3329 );
3330 let (out, served) = codegen_if_arms(
3331 output,
3332 fused_head.clone(),
3333 then_block,
3334 Some(fusion.probe),
3335 else_block,
3336 interner,
3337 indent,
3338 mutable_vars,
3339 ctx,
3340 lww_fields,
3341 mv_fields,
3342 synced_vars,
3343 var_caps,
3344 async_functions,
3345 pipe_vars,
3346 boxed_fields,
3347 registry,
3348 type_env,
3349 indent_str,
3350 );
3351 if served == 0 {
3352 let plain_head = format!(
3353 "{}if {}.logos_contains(&({})) {{",
3354 indent_str, fusion.map, fusion.key
3355 );
3356 return out.replacen(&fused_head, &plain_head, 1);
3357 }
3358 crate::optimize::mark_fired(crate::optimization::Opt::ProbeFuse);
3359 return out;
3360 }
3361 if else_block.is_none()
3365 && then_block.len() == 1
3366 && crate::optimize::active_config().is_on(crate::optimization::Opt::BranchlessAccumulate)
3367 {
3368 if let Some(Stmt::Set { target, value }) = then_block.first() {
3369 if let Expr::BinaryOp {
3370 op: BinaryOpKind::Add,
3371 left,
3372 right,
3373 } = value
3374 {
3375 let self_add = matches!(left, Expr::Identifier(l) if *l == *target);
3376 if let (true, Expr::Literal(Literal::Number(k))) = (self_add, right) {
3377 let plain_i64 = match ctx.get_variable_types().get(target) {
3380 None => true,
3381 Some(t) => {
3382 !(t.contains("bigint")
3383 || t.contains("LogosInt")
3384 || t == "f64"
3385 || t == "String"
3386 || t == "Text"
3387 || t.contains("__"))
3388 }
3389 };
3390 if plain_i64 {
3391 crate::optimize::mark_fired(crate::optimization::Opt::BranchlessAccumulate);
3392 let cs = codegen_expr_with_async_oracle(
3393 cond,
3394 interner,
3395 synced_vars,
3396 async_functions,
3397 ctx.get_variable_types(),
3398 ctx.oracle(),
3399 );
3400 let cs = truthy_cond_wrap(cond, cs, interner, ctx.get_variable_types());
3401 let xn = RustNames::new(interner).ident(*target);
3402 if super::expr::is_wide_acc(*target)
3405 && crate::optimize::active_config()
3406 .is_on(crate::optimization::Opt::WideAccumulator)
3407 {
3408 crate::optimize::mark_fired(crate::optimization::Opt::WideAccumulator);
3409 let delta = if *k == 1 {
3410 format!("(({}) as i128)", cs)
3411 } else {
3412 format!("(({}) as i128 * {})", cs, k)
3413 };
3414 writeln!(output, "{}{} = {} + {};", indent_str, xn, xn, delta).unwrap();
3415 } else {
3416 let delta = if *k == 1 {
3417 format!("(({}) as i64)", cs)
3418 } else {
3419 format!("(({}) as i64 * {})", cs, k)
3420 };
3421 writeln!(
3422 output,
3423 "{}{} = logos_add_i64({}, {});",
3424 indent_str, xn, xn, delta
3425 )
3426 .unwrap();
3427 }
3428 return output;
3429 }
3430 }
3431 }
3432 }
3433 }
3434 if let Some(select) = branchless_select(
3437 then_block,
3438 else_block,
3439 interner,
3440 synced_vars,
3441 async_functions,
3442 ctx,
3443 ) {
3444 crate::optimize::mark_fired(crate::optimization::Opt::BranchlessSelect);
3445 let cond_str = codegen_expr_with_async_oracle(
3446 cond,
3447 interner,
3448 synced_vars,
3449 async_functions,
3450 ctx.get_variable_types(),
3451 ctx.oracle(),
3452 );
3453 let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
3454 let target = RustNames::new(interner).ident(select.target);
3455 writeln!(output, "{}if {} {{", indent_str, select.guard).unwrap();
3456 writeln!(
3457 output,
3458 "{} let __select_then: i64 = {};",
3459 indent_str, select.then_word
3460 )
3461 .unwrap();
3462 writeln!(
3463 output,
3464 "{} let __select_else: i64 = {};",
3465 indent_str, select.else_word
3466 )
3467 .unwrap();
3468 writeln!(
3469 output,
3470 "{} {} = if {} {{ __select_then }} else {{ __select_else }};",
3471 indent_str, target, cond_str
3472 )
3473 .unwrap();
3474 writeln!(output, "{}}} else {{", indent_str).unwrap();
3475 let output = codegen_if_branches(
3476 output,
3477 cond,
3478 then_block,
3479 else_block,
3480 interner,
3481 indent + 1,
3482 mutable_vars,
3483 ctx,
3484 lww_fields,
3485 mv_fields,
3486 synced_vars,
3487 var_caps,
3488 async_functions,
3489 pipe_vars,
3490 boxed_fields,
3491 registry,
3492 type_env,
3493 &" ".repeat(indent + 1),
3494 );
3495 return output + &format!("{}}}\n", indent_str);
3496 }
3497 codegen_if_branches(
3498 output,
3499 cond,
3500 then_block,
3501 else_block,
3502 interner,
3503 indent,
3504 mutable_vars,
3505 ctx,
3506 lww_fields,
3507 mv_fields,
3508 synced_vars,
3509 var_caps,
3510 async_functions,
3511 pipe_vars,
3512 boxed_fields,
3513 registry,
3514 type_env,
3515 indent_str,
3516 )
3517}
3518
3519struct ProbeFusion {
3522 map: String,
3523 key: String,
3524 value_ty: String,
3525 probe: super::probe::Probe,
3526}
3527
3528fn probe_fusion<'a>(
3533 cond: &Expr<'a>,
3534 then_block: &Block<'a>,
3535 interner: &Interner,
3536 synced_vars: &HashSet<Symbol>,
3537 async_functions: &HashSet<Symbol>,
3538 ctx: &RefinementContext<'a>,
3539) -> Option<ProbeFusion> {
3540 if !crate::optimize::active_config().is_on(crate::optimization::Opt::ProbeFuse) {
3541 return None;
3542 }
3543 let Expr::Contains {
3544 collection: map_expr @ Expr::Identifier(map),
3545 value: key,
3546 } = cond
3547 else {
3548 return None;
3549 };
3550 let probe_key = super::probe::ProbeKey::of(key)?;
3551 let writes = crate::optimize::writes::WriteSet::of_block(then_block);
3552 if writes.is_opaque()
3553 || writes.has_calls()
3554 || writes.may_write(*map)
3555 || matches!(probe_key, super::probe::ProbeKey::Name(k) if writes.may_write(k))
3556 {
3557 return None;
3558 }
3559 let types = ctx.get_variable_types();
3560 let map_ty = types
3561 .get(map)?
3562 .split("|__hl:")
3563 .next()?
3564 .trim_start_matches("&mut ")
3565 .trim_start_matches('&')
3566 .to_string();
3567 let (key_ty, value_ty) = if map_ty.starts_with("LogosI64Map")
3568 || map_ty.starts_with("LogosI32Map")
3569 || map_ty.starts_with("LogosDenseI64Map")
3570 {
3571 ("i64".to_string(), "i64".to_string())
3572 } else {
3573 let args = map_ty.strip_prefix("LogosMap<")?.strip_suffix('>')?;
3574 let mut depth = 0i32;
3575 let comma = args.char_indices().find(|&(_, c)| {
3576 match c {
3577 '<' | '(' | '[' => depth += 1,
3578 '>' | ')' | ']' => depth -= 1,
3579 _ => {}
3580 }
3581 c == ',' && depth == 0
3582 })?;
3583 (
3584 args[..comma.0].trim().to_string(),
3585 args[comma.0 + 1..].trim().to_string(),
3586 )
3587 };
3588 if !matches!(value_ty.as_str(), "i64" | "f64" | "bool") {
3589 return None;
3590 }
3591 let key_fits = match probe_key {
3592 super::probe::ProbeKey::Int(_) => key_ty == "i64",
3593 super::probe::ProbeKey::Text(_) => key_ty == "String",
3594 super::probe::ProbeKey::Name(_) if key_ty == "i64" => {
3595 super::types::infer_numeric_type(key, interner, types) == "i64"
3596 }
3597 super::probe::ProbeKey::Name(k) => types.get(&k).is_some_and(|t| *t == key_ty),
3598 };
3599 if !key_fits {
3600 return None;
3601 }
3602 let emit = |e: &Expr<'a>| {
3603 codegen_expr_with_async_oracle(
3604 e,
3605 interner,
3606 synced_vars,
3607 async_functions,
3608 types,
3609 ctx.oracle(),
3610 )
3611 };
3612 Some(ProbeFusion {
3613 map: emit(map_expr),
3614 key: emit(key),
3615 value_ty,
3616 probe: super::probe::Probe {
3617 map: *map,
3618 key: probe_key,
3619 name: super::probe::fresh_name(),
3620 reads: 0,
3621 },
3622 })
3623}
3624
3625struct BranchlessSelect {
3628 guard: String,
3629 then_word: String,
3630 else_word: String,
3631 target: Symbol,
3632}
3633
3634fn branchless_select<'a>(
3638 then_block: &Block<'a>,
3639 else_block: &Option<Block<'a>>,
3640 interner: &Interner,
3641 synced_vars: &HashSet<Symbol>,
3642 async_functions: &HashSet<Symbol>,
3643 ctx: &RefinementContext<'a>,
3644) -> Option<BranchlessSelect> {
3645 if !crate::optimize::active_config().is_on(crate::optimization::Opt::BranchlessSelect) {
3646 return None;
3647 }
3648 let (
3649 [Stmt::Set {
3650 target,
3651 value: then_value,
3652 }],
3653 Some(
3654 [Stmt::Set {
3655 target: else_target,
3656 value: else_value,
3657 }],
3658 ),
3659 ) = (&then_block[..], else_block.as_deref())
3660 else {
3661 return None;
3662 };
3663 if target != else_target {
3664 return None;
3665 }
3666 let word = ctx
3667 .get_variable_types()
3668 .get(target)
3669 .map(|t| t.split("|__hl:").next().unwrap_or(t.as_str()));
3670 if word != Some("i64") {
3671 return None;
3672 }
3673 let arm = |value| {
3674 super::expr::select_arm(
3675 value,
3676 interner,
3677 synced_vars,
3678 async_functions,
3679 ctx.get_variable_types(),
3680 ctx.oracle(),
3681 )
3682 };
3683 let (then_arm, else_arm) = (arm(then_value)?, arm(else_value)?);
3684 let guard = match (then_arm.guard, else_arm.guard) {
3685 (None, None) => return None,
3686 (Some(g), None) | (None, Some(g)) => g,
3687 (Some(a), Some(b)) if a == b => a,
3688 (Some(a), Some(b)) => format!("({a}) && ({b})"),
3689 };
3690 Some(BranchlessSelect {
3691 guard,
3692 then_word: then_arm.fast,
3693 else_word: else_arm.fast,
3694 target: *target,
3695 })
3696}
3697
3698#[allow(clippy::too_many_arguments)]
3700fn codegen_if_branches<'a>(
3701 output: String,
3702 cond: &&'a Expr<'a>,
3703 then_block: &Block<'a>,
3704 else_block: &Option<Block<'a>>,
3705 interner: &Interner,
3706 indent: usize,
3707 mutable_vars: &HashSet<Symbol>,
3708 ctx: &mut RefinementContext<'a>,
3709 lww_fields: &HashSet<(String, String)>,
3710 mv_fields: &HashSet<(String, String)>,
3711 synced_vars: &mut HashSet<Symbol>,
3712 var_caps: &HashMap<Symbol, VariableCapabilities>,
3713 async_functions: &HashSet<Symbol>,
3714 pipe_vars: &HashSet<Symbol>,
3715 boxed_fields: &HashSet<(String, String, String)>,
3716 registry: &TypeRegistry,
3717 type_env: &crate::analysis::types::TypeEnv,
3718 indent_str: &str,
3719) -> String {
3720 let cond_str = codegen_expr_with_async_oracle(
3721 cond,
3722 interner,
3723 synced_vars,
3724 async_functions,
3725 ctx.get_variable_types(),
3726 ctx.oracle(),
3727 );
3728 let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
3729 let head = format!("{}if {} {{", indent_str, cond_str);
3730 let (output, _) = codegen_if_arms(
3731 output,
3732 head,
3733 then_block,
3734 None,
3735 else_block,
3736 interner,
3737 indent,
3738 mutable_vars,
3739 ctx,
3740 lww_fields,
3741 mv_fields,
3742 synced_vars,
3743 var_caps,
3744 async_functions,
3745 pipe_vars,
3746 boxed_fields,
3747 registry,
3748 type_env,
3749 indent_str,
3750 );
3751 output
3752}
3753
3754#[allow(clippy::too_many_arguments)]
3757fn codegen_if_arms<'a>(
3758 mut output: String,
3759 head: String,
3760 then_stmts: &[Stmt<'a>],
3761 probe: Option<super::probe::Probe>,
3762 else_block: &Option<Block<'a>>,
3763 interner: &Interner,
3764 indent: usize,
3765 mutable_vars: &HashSet<Symbol>,
3766 ctx: &mut RefinementContext<'a>,
3767 lww_fields: &HashSet<(String, String)>,
3768 mv_fields: &HashSet<(String, String)>,
3769 synced_vars: &mut HashSet<Symbol>,
3770 var_caps: &HashMap<Symbol, VariableCapabilities>,
3771 async_functions: &HashSet<Symbol>,
3772 pipe_vars: &HashSet<Symbol>,
3773 boxed_fields: &HashSet<(String, String, String)>,
3774 registry: &TypeRegistry,
3775 type_env: &crate::analysis::types::TypeEnv,
3776 indent_str: &str,
3777) -> (String, usize) {
3778 writeln!(output, "{}", head).unwrap();
3779 ctx.push_scope();
3780 let mut then_code = String::new();
3781 let mut emit_then = || {
3782 let block_refs: Vec<&Stmt> = then_stmts.iter().collect();
3783 let mut bi = 0;
3784 while bi < block_refs.len() {
3785 if let Some((code, skip)) = super::peephole::try_block_peepholes(
3786 &block_refs,
3787 bi,
3788 interner,
3789 indent + 1,
3790 mutable_vars,
3791 ctx,
3792 lww_fields,
3793 mv_fields,
3794 synced_vars,
3795 var_caps,
3796 async_functions,
3797 pipe_vars,
3798 boxed_fields,
3799 registry,
3800 type_env,
3801 ) {
3802 then_code.push_str(&code);
3803 bi += 1 + skip;
3804 continue;
3805 }
3806 then_code.push_str(&codegen_stmt(
3807 block_refs[bi],
3808 interner,
3809 indent + 1,
3810 mutable_vars,
3811 ctx,
3812 lww_fields,
3813 mv_fields,
3814 synced_vars,
3815 var_caps,
3816 async_functions,
3817 pipe_vars,
3818 boxed_fields,
3819 registry,
3820 type_env,
3821 ));
3822 bi += 1;
3823 }
3824 };
3825 let served = match probe {
3826 Some(probe) => super::probe::within(probe, emit_then).1,
3827 None => {
3828 emit_then();
3829 0
3830 }
3831 };
3832 output.push_str(&then_code);
3833 ctx.pop_scope();
3834 if let Some(else_stmts) = else_block {
3835 writeln!(output, "{}}} else {{", indent_str).unwrap();
3836 ctx.push_scope();
3837 {
3838 let block_refs: Vec<&Stmt> = else_stmts.iter().collect();
3839 let mut bi = 0;
3840 while bi < block_refs.len() {
3841 if let Some((code, skip)) = super::peephole::try_block_peepholes(
3842 &block_refs,
3843 bi,
3844 interner,
3845 indent + 1,
3846 mutable_vars,
3847 ctx,
3848 lww_fields,
3849 mv_fields,
3850 synced_vars,
3851 var_caps,
3852 async_functions,
3853 pipe_vars,
3854 boxed_fields,
3855 registry,
3856 type_env,
3857 ) {
3858 output.push_str(&code);
3859 bi += 1 + skip;
3860 continue;
3861 }
3862 output.push_str(&codegen_stmt(
3863 block_refs[bi],
3864 interner,
3865 indent + 1,
3866 mutable_vars,
3867 ctx,
3868 lww_fields,
3869 mv_fields,
3870 synced_vars,
3871 var_caps,
3872 async_functions,
3873 pipe_vars,
3874 boxed_fields,
3875 registry,
3876 type_env,
3877 ));
3878 bi += 1;
3879 }
3880 }
3881 ctx.pop_scope();
3882 }
3883 writeln!(output, "{}}}", indent_str).unwrap();
3884 (output, served)
3885}
3886
3887#[inline(never)]
3889#[allow(clippy::too_many_arguments)]
3890fn codegen_show_stmt<'a>(
3891 mut output: String,
3892 object: &&'a Expr<'a>,
3893 recipient: &&'a Expr<'a>,
3894 interner: &Interner,
3895 ctx: &mut RefinementContext<'a>,
3896 synced_vars: &mut HashSet<Symbol>,
3897 async_functions: &HashSet<Symbol>,
3898 registry: &TypeRegistry,
3899 indent_str: &str,
3900 names: &RustNames,
3901) -> String {
3902 if let Expr::Identifier(sym) = object {
3904 if ctx
3905 .get_variable_types()
3906 .get(sym)
3907 .map_or(false, |t| t == "__single_char_u8")
3908 {
3909 let var_name = names.ident(*sym);
3910 writeln!(
3911 output,
3912 "{}logicaffeine_system::io::println({} as char);",
3913 indent_str, var_name
3914 )
3915 .unwrap();
3916 return output;
3917 }
3918 }
3919 if let Expr::Identifier(sym) = object {
3922 if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
3923 && super::expr::is_wide_acc(*sym)
3924 {
3925 let recv = if let Expr::Identifier(r) = recipient {
3926 super::expr::called_function_path(*r, names.ident(*r), ctx.get_variable_types())
3927 } else {
3928 "show".to_string()
3929 };
3930 let var_name = names.ident(*sym);
3931 let narrowed = format!("(({}) as i64)", var_name);
3932 writeln!(
3933 output,
3934 "{}{}({});",
3935 indent_str,
3936 recv,
3937 super::expr::lend_to(recipient, &narrowed)
3938 )
3939 .unwrap();
3940 return output;
3941 }
3942 }
3943 if let Expr::InterpolatedString(parts) = object {
3945 let recv_name = if let Expr::Identifier(sym) = recipient {
3946 interner.resolve(*sym).to_string()
3947 } else {
3948 String::new()
3949 };
3950 if recv_name == "show" {
3951 let mut fmt_str = String::new();
3953 let mut args = Vec::new();
3954 for part in parts {
3955 match part {
3956 crate::ast::stmt::StringPart::Literal(sym) => {
3957 let text = interner.resolve(*sym);
3958 for ch in text.chars() {
3959 match ch {
3960 '{' => fmt_str.push_str("{{"),
3961 '}' => fmt_str.push_str("}}"),
3962 '\n' => fmt_str.push_str("\\n"),
3963 '\t' => fmt_str.push_str("\\t"),
3964 '\r' => fmt_str.push_str("\\r"),
3965 '"' => fmt_str.push_str("\\\""),
3968 '\\' => fmt_str.push_str("\\\\"),
3969 _ => fmt_str.push(ch),
3970 }
3971 }
3972 }
3973 crate::ast::stmt::StringPart::Expr {
3974 value,
3975 format_spec,
3976 debug,
3977 } => {
3978 if *debug {
3979 let debug_prefix = expr_debug_prefix(value, interner);
3980 for ch in debug_prefix.chars() {
3981 match ch {
3982 '{' => fmt_str.push_str("{{"),
3983 '}' => fmt_str.push_str("}}"),
3984 '"' => fmt_str.push_str("\\\""),
3985 '\\' => fmt_str.push_str("\\\\"),
3986 _ => fmt_str.push(ch),
3987 }
3988 }
3989 fmt_str.push('=');
3990 }
3991 let arg_str = codegen_expr_with_async_and_strings(
3992 value,
3993 interner,
3994 synced_vars,
3995 async_functions,
3996 ctx.get_string_vars(),
3997 ctx.get_variable_types(),
3998 ctx.get_fast_div(),
3999 registry,
4000 );
4001 let (piece, arg) = super::expr::interpolation_hole(
4002 format_spec.map(|s| interner.resolve(s)),
4003 &arg_str,
4004 );
4005 fmt_str.push_str(&piece);
4006 args.push(arg);
4007 }
4008 }
4009 }
4010 writeln!(
4011 output,
4012 "{}logicaffeine_system::io::println(format_args!(\"{}\"{}));",
4013 indent_str,
4014 fmt_str,
4015 args.iter().map(|a| format!(", {}", a)).collect::<String>()
4016 )
4017 .unwrap();
4018 } else {
4019 let obj_str = codegen_expr_with_async_and_strings(
4020 object,
4021 interner,
4022 synced_vars,
4023 async_functions,
4024 ctx.get_string_vars(),
4025 ctx.get_variable_types(),
4026 ctx.get_fast_div(),
4027 registry,
4028 );
4029 let recv_str = recipient_path(
4030 recipient,
4031 interner,
4032 synced_vars,
4033 async_functions,
4034 ctx.get_variable_types(),
4035 );
4036 writeln!(
4037 output,
4038 "{}{}({});",
4039 indent_str,
4040 recv_str,
4041 super::expr::lend_to(recipient, &obj_str)
4042 )
4043 .unwrap();
4044 }
4045 } else {
4046 let obj_str = codegen_expr_with_async_and_strings(
4049 object,
4050 interner,
4051 synced_vars,
4052 async_functions,
4053 ctx.get_string_vars(),
4054 ctx.get_variable_types(),
4055 ctx.get_fast_div(),
4056 registry,
4057 );
4058 let recv_str = recipient_path(
4059 recipient,
4060 interner,
4061 synced_vars,
4062 async_functions,
4063 ctx.get_variable_types(),
4064 );
4065 writeln!(
4066 output,
4067 "{}{}({});",
4068 indent_str,
4069 recv_str,
4070 super::expr::lend_to(recipient, &obj_str)
4071 )
4072 .unwrap();
4073 }
4074 output
4075}
4076
4077fn recipient_path(
4080 recipient: &Expr,
4081 interner: &Interner,
4082 synced_vars: &HashSet<Symbol>,
4083 async_functions: &HashSet<Symbol>,
4084 variable_types: &HashMap<Symbol, String>,
4085) -> String {
4086 match recipient {
4087 Expr::Identifier(f) => super::expr::called_function_path(
4088 *f,
4089 RustNames::new(interner).ident(*f),
4090 variable_types,
4091 ),
4092 other => codegen_expr_with_async(
4093 other,
4094 interner,
4095 synced_vars,
4096 async_functions,
4097 variable_types,
4098 ),
4099 }
4100}
4101
4102const PEER_AGENT_TYPE: &str = "logicaffeine_system::network::PeerAgent";
4104
4105#[inline(never)]
4107#[allow(clippy::too_many_arguments)]
4108fn codegen_call_stmt<'a>(
4109 mut output: String,
4110 function: &Symbol,
4111 fish: &str,
4112 args: &[&'a Expr<'a>],
4113 interner: &Interner,
4114 ctx: &mut RefinementContext<'a>,
4115 synced_vars: &mut HashSet<Symbol>,
4116 async_functions: &HashSet<Symbol>,
4117 indent_str: &str,
4118 names: &RustNames,
4119) -> String {
4120 let func_name = super::expr::called_function_path(
4121 *function,
4122 names.ident(*function),
4123 ctx.get_variable_types(),
4124 );
4125 let ecx = super::expr::ExprCtx {
4126 async_functions,
4127 variable_types: ctx.get_variable_types(),
4128 ..super::expr::ExprCtx::bare(interner, synced_vars)
4129 };
4130 if let Some(code) = super::tower::extension_call(*function, args, &ecx) {
4131 writeln!(output, "{}{};", indent_str, code).unwrap();
4132 return output;
4133 }
4134 let args_str: Vec<String> = super::expr::call_arguments(*function, args, &ecx);
4135 let await_suffix = if async_functions.contains(function) {
4136 ".await"
4137 } else {
4138 ""
4139 };
4140 let path = format!("{func_name}{fish}");
4141 let call = super::expr::sequenced_call(
4142 &path,
4143 *function,
4144 args,
4145 args_str,
4146 await_suffix,
4147 ctx.get_variable_types(),
4148 );
4149 writeln!(output, "{}{};", indent_str, call).unwrap();
4150 output
4151}
4152
4153#[inline(never)]
4155#[allow(clippy::too_many_arguments)]
4156fn codegen_push_stmt<'a>(
4157 mut output: String,
4158 value: &&'a Expr<'a>,
4159 collection: &&'a Expr<'a>,
4160 interner: &Interner,
4161 ctx: &mut RefinementContext<'a>,
4162 synced_vars: &mut HashSet<Symbol>,
4163 async_functions: &HashSet<Symbol>,
4164 boxed_fields: &HashSet<(String, String, String)>,
4165 registry: &TypeRegistry,
4166 indent_str: &str,
4167 names: &RustNames,
4168) -> String {
4169 if let Expr::Identifier(coll_sym) = collection {
4170 if ctx
4171 .get_variable_types()
4172 .get(coll_sym)
4173 .is_some_and(|t| t == super::tower::VALUE)
4174 {
4175 let pushed = super::tower::statement_value(
4176 value,
4177 interner,
4178 synced_vars,
4179 async_functions,
4180 boxed_fields,
4181 registry,
4182 ctx.get_variable_types(),
4183 );
4184 writeln!(
4185 output,
4186 "{}logicaffeine_data::failure::answered({}.push_value({}));",
4187 indent_str,
4188 names.ident(*coll_sym),
4189 pushed
4190 )
4191 .unwrap();
4192 return output;
4193 }
4194 }
4195 if let Expr::Identifier(coll_sym) = collection {
4199 if ctx
4203 .get_variable_types()
4204 .get(coll_sym)
4205 .map_or(false, |t| t == "ByteBuilder")
4206 {
4207 let val_str = codegen_expr_boxed_with_types_oracle(
4208 value,
4209 interner,
4210 synced_vars,
4211 boxed_fields,
4212 registry,
4213 async_functions,
4214 ctx.get_string_vars(),
4215 ctx.get_variable_types(),
4216 ctx.get_fast_div(),
4217 ctx.oracle(),
4218 );
4219 writeln!(
4220 output,
4221 "{}{}.push(({}) as u8);",
4222 indent_str,
4223 names.ident(*coll_sym),
4224 val_str
4225 )
4226 .unwrap();
4227 return output;
4228 }
4229 if let Some(cursor) = ctx.loop_fill_cursor(*coll_sym).map(|s| s.to_string()) {
4233 let val_str = codegen_expr_boxed_with_types_oracle(
4234 value,
4235 interner,
4236 synced_vars,
4237 boxed_fields,
4238 registry,
4239 async_functions,
4240 ctx.get_string_vars(),
4241 ctx.get_variable_types(),
4242 ctx.get_fast_div(),
4243 ctx.oracle(),
4244 );
4245 let coll_name = names.ident(*coll_sym);
4246 writeln!(
4247 output,
4248 "{}{}[{}] = {}; {} += 1;",
4249 indent_str, coll_name, cursor, val_str, cursor
4250 )
4251 .unwrap();
4252 return output;
4253 }
4254 if ctx.affine_array(*coll_sym).is_some() {
4257 return output;
4258 }
4259 if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(coll_sym)) {
4262 let val_str = codegen_expr_boxed_with_types_oracle(
4263 value,
4264 interner,
4265 synced_vars,
4266 boxed_fields,
4267 registry,
4268 async_functions,
4269 ctx.get_string_vars(),
4270 ctx.get_variable_types(),
4271 ctx.get_fast_div(),
4272 ctx.oracle(),
4273 );
4274 let k = ctx.next_array_fill(*coll_sym);
4275 writeln!(
4276 output,
4277 "{}{}[{}][{}] = {};",
4278 indent_str, tag.backing, k, tag.col, val_str
4279 )
4280 .unwrap();
4281 return output;
4282 }
4283 if ctx.is_scalarized_array(*coll_sym) {
4284 let val_str = codegen_expr_boxed_with_types_oracle(
4285 value,
4286 interner,
4287 synced_vars,
4288 boxed_fields,
4289 registry,
4290 async_functions,
4291 ctx.get_string_vars(),
4292 ctx.get_variable_types(),
4293 ctx.get_fast_div(),
4294 ctx.oracle(),
4295 );
4296 let k = ctx.next_array_fill(*coll_sym);
4297 let coll_name = names.ident(*coll_sym);
4298 writeln!(output, "{}{}[{}] = {};", indent_str, coll_name, k, val_str).unwrap();
4299 return output;
4300 }
4301 if let Some((buf, counter)) = ctx.fill_loop().map(|(b, c)| (b, c.to_string())) {
4305 if buf == *coll_sym {
4306 let val_str = codegen_expr_boxed_with_types_oracle(
4307 value,
4308 interner,
4309 synced_vars,
4310 boxed_fields,
4311 registry,
4312 async_functions,
4313 ctx.get_string_vars(),
4314 ctx.get_variable_types(),
4315 ctx.get_fast_div(),
4316 ctx.oracle(),
4317 );
4318 let coll_name = names.ident(*coll_sym);
4319 writeln!(output, "{}debug_assert!(({} as usize) < {}.len(), \"LOGOS fill-loop store out of range\");", indent_str, counter, coll_name).unwrap();
4329 writeln!(
4330 output,
4331 "{}unsafe {{ std::hint::assert_unchecked(({} as usize) < {}.len()); }}",
4332 indent_str, counter, coll_name
4333 )
4334 .unwrap();
4335 writeln!(
4336 output,
4337 "{}{}[{} as usize] = {};",
4338 indent_str, coll_name, counter, val_str
4339 )
4340 .unwrap();
4341 return output;
4342 }
4343 }
4344 if let Some(tail) = ctx.worklist(*coll_sym).map(|w| w.tail_var.clone()) {
4349 let val_str = codegen_expr_boxed_with_types_oracle(
4350 value,
4351 interner,
4352 synced_vars,
4353 boxed_fields,
4354 registry,
4355 async_functions,
4356 ctx.get_string_vars(),
4357 ctx.get_variable_types(),
4358 ctx.get_fast_div(),
4359 ctx.oracle(),
4360 );
4361 let coll_name = names.ident(*coll_sym);
4362 writeln!(
4363 output,
4364 "{}unsafe {{ std::hint::assert_unchecked({tail} < {coll_name}.len()); }}",
4365 indent_str
4366 )
4367 .unwrap();
4368 writeln!(output, "{}{coll_name}[{tail}] = {val_str};", indent_str).unwrap();
4369 writeln!(output, "{}{tail} += 1;", indent_str).unwrap();
4370 return output;
4371 }
4372 }
4373 let val_str = codegen_expr_boxed_with_types_oracle(
4374 value,
4375 interner,
4376 synced_vars,
4377 boxed_fields,
4378 registry,
4379 async_functions,
4380 ctx.get_string_vars(),
4381 ctx.get_variable_types(),
4382 ctx.get_fast_div(),
4383 ctx.oracle(),
4384 );
4385 let val_str = match super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
4387 Some(item) => rational_value(
4388 value,
4389 &item,
4390 interner,
4391 ctx,
4392 synced_vars,
4393 async_functions,
4394 boxed_fields,
4395 registry,
4396 )
4397 .unwrap_or(val_str),
4398 None => val_str,
4399 };
4400 let val_str = stored_value(value, val_str, ctx.get_variable_types());
4401 let val_str =
4402 value_taken_before_the_write(value, collection, val_str, ctx, indent_str, &mut output);
4403 let coll_str = codegen_expr_with_async(
4404 collection,
4405 interner,
4406 synced_vars,
4407 async_functions,
4408 ctx.get_variable_types(),
4409 );
4410 emit_cow(collection, ctx, &names, &indent_str, &mut output);
4413 let narrowed_push = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
4416 if narrowed_push {
4417 writeln!(
4435 output,
4436 "{}{}.push({{ let __nv: i64 = {}; __nv as i32 }});",
4437 indent_str, coll_str, val_str
4438 )
4439 .unwrap();
4440 } else {
4441 writeln!(output, "{}{}.push({});", indent_str, coll_str, val_str).unwrap();
4442 }
4443 output
4444}
4445
4446pub(super) fn stored_value(
4454 value: &Expr,
4455 value_str: String,
4456 variable_types: &HashMap<Symbol, String>,
4457) -> String {
4458 let bare = match value {
4459 Expr::Copy { expr } => *expr,
4460 other => other,
4461 };
4462 if matches!(bare, Expr::FieldAccess { .. })
4463 && super::expr::copies_out_of_a_lend(bare, variable_types)
4464 {
4465 return format!("{value_str}.clone()");
4466 }
4467 let Expr::Identifier(sym) = bare else {
4468 return value_str;
4469 };
4470 if super::expr::lent_by_sharing(*sym, variable_types) {
4471 return format!("{value_str}.deep_clone()");
4472 }
4473 let copies = match variable_types.get(sym) {
4474 Some(ty) => {
4475 let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
4476 let moved = is_copy_type(ty)
4477 || ty.contains("__bigint")
4478 || ty.starts_with('&')
4479 || ty.starts_with("Vec<")
4480 || ty.starts_with("HashMap")
4481 || ty.starts_with("FxHashMap")
4482 || ty.starts_with('[');
4483 !moved || super::expr::mentions_generic_param(ty)
4484 }
4485 None => true,
4486 };
4487 if copies {
4488 format!("{value_str}.clone()")
4489 } else {
4490 value_str
4491 }
4492}
4493
4494fn value_taken_before_the_write(
4499 value: &Expr,
4500 collection: &Expr,
4501 val_str: String,
4502 ctx: &RefinementContext,
4503 indent_str: &str,
4504 output: &mut String,
4505) -> String {
4506 match get_root_identifier(collection) {
4507 Some(root) if super::expr::lends_binding(value, root, ctx.get_variable_types()) => {
4508 writeln!(output, "{}let __lent_value = {};", indent_str, val_str).unwrap();
4509 "__lent_value".to_string()
4510 }
4511 _ => val_str,
4512 }
4513}
4514
4515#[inline(never)]
4517#[allow(clippy::too_many_arguments)]
4518fn codegen_return_stmt<'a>(
4519 mut output: String,
4520 value: &Option<&'a Expr<'a>>,
4521 interner: &Interner,
4522 ctx: &mut RefinementContext<'a>,
4523 synced_vars: &mut HashSet<Symbol>,
4524 async_functions: &HashSet<Symbol>,
4525 boxed_fields: &HashSet<(String, String, String)>,
4526 registry: &TypeRegistry,
4527 indent_str: &str,
4528) -> String {
4529 if let (Some(v), Some(held)) = (value, super::absent::returning()) {
4531 let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
4532 if let Some(code) = super::absent::stored(v, &held, &ecx) {
4533 writeln!(output, "{}return {};", indent_str, code).unwrap();
4534 return output;
4535 }
4536 }
4537 if let (Some(v), true) = (value, super::tower::emitting_a_reached_function()) {
4538 let code = super::tower::statement_value(
4539 v,
4540 interner,
4541 synced_vars,
4542 async_functions,
4543 boxed_fields,
4544 registry,
4545 ctx.get_variable_types(),
4546 );
4547 writeln!(output, "{}return {};", indent_str, code).unwrap();
4548 return output;
4549 }
4550 if let (Some(v), Some(held)) = (value, ctx.returns_rationals().cloned()) {
4552 if let Some(code) = rational_value(
4553 v,
4554 &held,
4555 interner,
4556 ctx,
4557 synced_vars,
4558 async_functions,
4559 boxed_fields,
4560 registry,
4561 ) {
4562 writeln!(output, "{}return {};", indent_str, code).unwrap();
4563 return output;
4564 }
4565 }
4566 if let Some(v) = value {
4567 if ctx.returns_bigint() {
4570 let movable_ret = matches!(v, Expr::Identifier(sym) if ctx.is_bigint_var(*sym));
4572 if let Expr::Identifier(sym) = v {
4573 if movable_ret {
4574 set_movable_last_use(Some(*sym));
4575 }
4576 }
4577 let raw = codegen_expr_boxed_with_types_oracle_tolerant(
4578 v,
4579 interner,
4580 synced_vars,
4581 boxed_fields,
4582 registry,
4583 async_functions,
4584 ctx.get_string_vars(),
4585 ctx.get_variable_types(),
4586 ctx.get_fast_div(),
4587 ctx.oracle(),
4588 );
4589 if movable_ret {
4590 set_movable_last_use(None);
4591 }
4592 writeln!(
4593 output,
4594 "{}return logicaffeine_data::LogosInt::from({});",
4595 indent_str, raw
4596 )
4597 .unwrap();
4598 return output;
4599 }
4600 let value_str = codegen_expr_boxed_with_types_oracle(
4601 v,
4602 interner,
4603 synced_vars,
4604 boxed_fields,
4605 registry,
4606 async_functions,
4607 ctx.get_string_vars(),
4608 ctx.get_variable_types(),
4609 ctx.get_fast_div(),
4610 ctx.oracle(),
4611 );
4612 let slice_sym = match v {
4614 Expr::Identifier(sym) => Some(*sym),
4615 Expr::Copy { expr: inner } => {
4616 if let Expr::Identifier(sym) = inner {
4617 Some(*sym)
4618 } else {
4619 None
4620 }
4621 }
4622 _ => None,
4623 };
4624 let needs_to_vec = slice_sym
4625 .and_then(|sym| ctx.get_variable_types().get(&sym))
4626 .map(|t| t.starts_with("&["))
4627 .unwrap_or(false);
4628 let ret_ty_is_scalar_array = slice_sym
4634 .and_then(|sym| ctx.get_variable_types().get(&sym))
4635 .map(|t| t.starts_with('['))
4636 .unwrap_or(false);
4637 let is_mut_borrow_return = if let Expr::Identifier(sym) = v {
4639 ctx.get_variable_types()
4640 .get(sym)
4641 .map(|t| t.starts_with("&mut ["))
4642 .unwrap_or(false)
4643 } else {
4644 false
4645 };
4646 if is_mut_borrow_return {
4647 writeln!(output, "{}return;", indent_str).unwrap();
4648 } else if (needs_to_vec || ret_ty_is_scalar_array) && ctx.returns_vec() {
4649 writeln!(output, "{}return {}.to_vec();", indent_str, value_str).unwrap();
4652 } else if needs_to_vec {
4653 writeln!(
4654 output,
4655 "{}return LogosSeq::from_vec({}.to_vec());",
4656 indent_str, value_str
4657 )
4658 .unwrap();
4659 } else if super::expr::copies_out_of_a_lend(v, ctx.get_variable_types()) {
4660 writeln!(output, "{}return {}.clone();", indent_str, value_str).unwrap();
4661 } else {
4662 writeln!(output, "{}return {};", indent_str, value_str).unwrap();
4663 }
4664 } else {
4665 writeln!(output, "{}return;", indent_str).unwrap();
4666 }
4667 output
4668}
4669
4670#[derive(Default)]
4673struct ServeFacts {
4674 declares_session: bool,
4675 lends_program: HashSet<Symbol>,
4676}
4677
4678thread_local! {
4679 static SERVE_FACTS: std::cell::RefCell<ServeFacts> = std::cell::RefCell::new(ServeFacts::default());
4683}
4684
4685pub(crate) fn set_serve_facts(stmts: &[Stmt], interner: &Interner) {
4686 let program = interner.lookup(crate::program_bindings::PROGRAM_BINDING);
4687 let lends_program = stmts
4688 .iter()
4689 .filter_map(|s| match s {
4690 Stmt::FunctionDef { name, params, .. }
4691 if program.is_some() && params.first().map(|(p, _)| *p) == program =>
4692 {
4693 Some(*name)
4694 }
4695 _ => None,
4696 })
4697 .collect();
4698 let declares_session =
4699 logicaffeine_language::parser::lgx_lower::declares_session(stmts, interner);
4700 SERVE_FACTS.with(|facts| {
4701 *facts.borrow_mut() = ServeFacts {
4702 declares_session,
4703 lends_program,
4704 }
4705 });
4706}
4707
4708fn emit_wire_response(output: &mut String, indent: &str, resp: &str) {
4715 writeln!(
4716 output,
4717 "{indent}let mut __headers = std::collections::BTreeMap::new();"
4718 )
4719 .unwrap();
4720 writeln!(
4721 output,
4722 "{indent}for (__k, __v) in {resp}.headers.borrow().iter() {{"
4723 )
4724 .unwrap();
4725 writeln!(output, "{indent} if logicaffeine_system::http::wire::response_header_allowed(__k, __v) {{ __headers.insert(__k.clone(), __v.clone()); }}").unwrap();
4726 writeln!(output, "{indent}}}").unwrap();
4727 writeln!(output, "{indent}__headers.insert(\"Content-Type\".to_string(), logicaffeine_system::http::wire::safe_content_type(&{resp}.contentType).to_string());").unwrap();
4728 writeln!(
4729 output,
4730 "{indent}let __bytes: Vec<u8> = {resp}.bytes.iter().map(|__b| __b as u8).collect();"
4731 )
4732 .unwrap();
4733 writeln!(output, "{indent}let __body = if __bytes.is_empty() {{ {resp}.body.into_bytes() }} else {{ __bytes }};").unwrap();
4734 writeln!(output, "{indent}logicaffeine_system::http::wire::HttpResponse {{ status: {resp}.status as u16, headers: __headers, body: __body }}").unwrap();
4735}
4736
4737#[inline(never)]
4739#[allow(clippy::too_many_arguments)]
4740fn codegen_serve_stmt<'a>(
4741 mut output: String,
4742 port: &&'a Expr<'a>,
4743 handler: &&'a Expr<'a>,
4744 interner: &Interner,
4745 ctx: &mut RefinementContext<'a>,
4746 synced_vars: &mut HashSet<Symbol>,
4747 async_functions: &HashSet<Symbol>,
4748 indent_str: &str,
4749) -> String {
4750 let port_str = codegen_expr_with_async(
4751 port,
4752 interner,
4753 synced_vars,
4754 async_functions,
4755 ctx.get_variable_types(),
4756 );
4757 let handler_sym = match handler {
4758 Expr::Identifier(sym) => *sym,
4759 _ => {
4760 writeln!(
4761 output,
4762 "{}compile_error!(\"Serve: the handler must be a named function\");",
4763 indent_str
4764 )
4765 .unwrap();
4766 return output;
4767 }
4768 };
4769 let handler_name = interner.resolve(handler_sym).to_string();
4770 let (declares_session, lends_program) = SERVE_FACTS.with(|facts| {
4771 let facts = facts.borrow();
4772 (
4773 facts.declares_session,
4774 facts.lends_program.contains(&handler_sym),
4775 )
4776 });
4777 let lend = if lends_program {
4782 let program = crate::program_bindings::PROGRAM_BINDING;
4783 let through_a_parameter = interner
4784 .lookup(program)
4785 .and_then(|sym| ctx.get_variable_types().get(&sym))
4786 .is_some_and(|ty| ty.starts_with('&'));
4787 if through_a_parameter {
4788 format!("&mut *{program}, ")
4789 } else {
4790 format!("&mut {program}, ")
4791 }
4792 } else {
4793 String::new()
4794 };
4795 let upgrades = crate::codegen::embed_assets_enabled().then(|| {
4805 "if logos_assets::USES_RELAY { logicaffeine_system::relay::RelayHub::new().upgrades() } else { ::std::vec::Vec::new() }"
4806 .to_string()
4807 });
4808 let entry = match (lends_program, upgrades.is_some()) {
4809 (false, false) => "serve",
4810 (false, true) => "serve_with_upgrades",
4811 (true, false) => "serve_here",
4812 (true, true) => "serve_here_with_upgrades",
4813 };
4814 writeln!(output, "{indent_str}logicaffeine_system::http::server::{entry}(&logicaffeine_system::http::server::env_bind_address(logicaffeine_system::http::server::env_port_override(({port_str}) as u16)), |__raw: logicaffeine_system::http::wire::HttpRequest| {{").unwrap();
4815 if crate::codegen::embed_assets_enabled() {
4827 writeln!(output, "{indent_str} if __raw.method == \"GET\" {{").unwrap();
4828 writeln!(output, "{indent_str} if let Some((__ct, __cc, __et, __asset)) = logos_assets::lookup(&__raw.path) {{").unwrap();
4829 writeln!(
4830 output,
4831 "{indent_str} let mut __ah = std::collections::BTreeMap::new();"
4832 )
4833 .unwrap();
4834 writeln!(
4835 output,
4836 "{indent_str} __ah.insert(\"Content-Type\".to_string(), __ct.to_string());"
4837 )
4838 .unwrap();
4839 writeln!(
4843 output,
4844 "{indent_str} __ah.insert(\"Cache-Control\".to_string(), __cc.to_string());"
4845 )
4846 .unwrap();
4847 writeln!(
4848 output,
4849 "{indent_str} __ah.insert(\"ETag\".to_string(), __et.to_string());"
4850 )
4851 .unwrap();
4852 if declares_session {
4860 let token_path = logicaffeine_language::parser::lgx_lower::CSRF_TOKEN_PATH;
4861 writeln!(
4862 output,
4863 "{indent_str} if logos_assets::is_page(&__raw.path) {{"
4864 )
4865 .unwrap();
4866 writeln!(
4867 output,
4868 "{indent_str} let __th = LogosMap::new();"
4869 )
4870 .unwrap();
4871 writeln!(output, "{indent_str} if let Some((_, __c)) = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"cookie\")) {{ __th.insert(\"cookie\".to_string(), __c.clone()); }}").unwrap();
4872 writeln!(output, "{indent_str} let __tr = {handler_name}({lend}Request {{ method: \"GET\".to_string(), path: {token_path:?}.to_string(), body: String::new(), headers: __th, query: LogosMap::new(), ..Default::default() }});").unwrap();
4873 writeln!(output, "{indent_str} let __tok = {{").unwrap();
4874 emit_wire_response(
4875 &mut output,
4876 &format!("{indent_str} "),
4877 "__tr",
4878 );
4879 writeln!(output, "{indent_str} }};").unwrap();
4880 writeln!(output, "{indent_str} let __page = logicaffeine_system::http::wire::HttpResponse {{ status: 200, headers: __ah.clone(), body: __asset.to_vec() }};").unwrap();
4881 writeln!(output, "{indent_str} if let Some(__composed) = logicaffeine_system::http::server::page_with_visitor_token(&__page, &__tok) {{ return __composed; }}").unwrap();
4882 writeln!(output, "{indent_str} }}").unwrap();
4883 }
4884 writeln!(output, "{indent_str} let __ae = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"accept-encoding\")).map(|(_, __v)| __v.as_str()).unwrap_or(\"\");").unwrap();
4890 writeln!(output, "{indent_str} let __gz = if __ae.split(',').any(|__e| __e.trim().split(';').next().unwrap_or(\"\").eq_ignore_ascii_case(\"gzip\")) {{ logos_assets::encoded(&__raw.path) }} else {{ None }};").unwrap();
4891 writeln!(output, "{indent_str} if __gz.is_some() {{ __ah.insert(\"Vary\".to_string(), \"Accept-Encoding\".to_string()); }}").unwrap();
4892 writeln!(output, "{indent_str} let (__et, __body_src): (&str, &[u8]) = match __gz {{ Some((__e, __b)) => {{ __ah.insert(\"Content-Encoding\".to_string(), \"gzip\".to_string()); (__e, __b) }}, None => (__et, __asset) }};").unwrap();
4893 writeln!(output, "{indent_str} __ah.insert(\"ETag\".to_string(), format!(\"\\\"{{}}\\\"\", __et.trim_matches('\\\"')));").unwrap();
4894 writeln!(output, "{indent_str} let __inm = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"if-none-match\")).map(|(_, __v)| __v.as_str());").unwrap();
4895 writeln!(
4896 output,
4897 "{indent_str} if logos_assets::fresh(__et, __inm) {{"
4898 )
4899 .unwrap();
4900 writeln!(output, "{indent_str} return logicaffeine_system::http::wire::HttpResponse {{ status: 304, headers: __ah, body: Vec::new() }};").unwrap();
4901 writeln!(output, "{indent_str} }}").unwrap();
4902 writeln!(output, "{indent_str} return logicaffeine_system::http::wire::HttpResponse {{ status: 200, headers: __ah, body: __body_src.to_vec() }};").unwrap();
4903 writeln!(output, "{indent_str} }}").unwrap();
4904 writeln!(output, "{indent_str} }}").unwrap();
4905 }
4906 writeln!(output, "{indent_str} let __hdrs = LogosMap::new();").unwrap();
4910 writeln!(
4911 output,
4912 "{indent_str} for (__k, __v) in __raw.headers {{ __hdrs.insert(__k, __v); }}"
4913 )
4914 .unwrap();
4915 writeln!(output, "{indent_str} let __qry = LogosMap::new();").unwrap();
4916 writeln!(
4917 output,
4918 "{indent_str} for (__k, __v) in __raw.query {{ __qry.insert(__k, __v); }}"
4919 )
4920 .unwrap();
4921 writeln!(output, "{indent_str} let __req = Request {{ method: __raw.method, path: __raw.path, body: String::from_utf8_lossy(&__raw.body).into_owned(), headers: __hdrs, query: __qry, ..Default::default() }};").unwrap();
4922 writeln!(
4923 output,
4924 "{indent_str} let __resp = {handler_name}({lend}__req);"
4925 )
4926 .unwrap();
4927 emit_wire_response(&mut output, &format!("{indent_str} "), "__resp");
4928 match upgrades {
4929 Some(table) => {
4930 writeln!(output, "{indent_str}}}, {table}).await.expect(\"serve\");").unwrap()
4931 }
4932 None => writeln!(output, "{indent_str}}}).await.expect(\"serve\");").unwrap(),
4933 }
4934 output
4935}
4936
4937#[inline(never)]
4939#[allow(clippy::too_many_arguments)]
4940fn codegen_set_index_stmt<'a>(
4941 mut output: String,
4942 collection: &&'a Expr<'a>,
4943 index: &&'a Expr<'a>,
4944 value: &&'a Expr<'a>,
4945 interner: &Interner,
4946 ctx: &mut RefinementContext<'a>,
4947 synced_vars: &mut HashSet<Symbol>,
4948 async_functions: &HashSet<Symbol>,
4949 boxed_fields: &HashSet<(String, String, String)>,
4950 registry: &TypeRegistry,
4951 indent_str: &str,
4952 names: &RustNames,
4953) -> String {
4954 if let Expr::Identifier(coll_sym) = collection {
4955 if ctx
4956 .get_variable_types()
4957 .get(coll_sym)
4958 .is_some_and(|t| t == super::tower::VALUE)
4959 {
4960 let value_of = |e: &Expr| {
4961 super::tower::statement_value(
4962 e,
4963 interner,
4964 synced_vars,
4965 async_functions,
4966 boxed_fields,
4967 registry,
4968 ctx.get_variable_types(),
4969 )
4970 };
4971 let (at, stored) = (value_of(index), value_of(value));
4972 writeln!(
4973 output,
4974 "{}logicaffeine_data::failure::answered({}.set_item(&({}), {}));",
4975 indent_str,
4976 names.ident(*coll_sym),
4977 at,
4978 stored
4979 )
4980 .unwrap();
4981 return output;
4982 }
4983 }
4984 if let Expr::Index {
4991 collection: base,
4992 index: outer_idx,
4993 } = collection
4994 {
4995 if let Expr::Identifier(base_sym) = base {
4996 let is_nested_seq = ctx.get_variable_types().get(base_sym).map_or(false, |t| {
4997 t.split("|__hl:")
4998 .next()
4999 .unwrap_or(t)
5000 .starts_with("LogosSeq<LogosSeq")
5001 });
5002 if is_nested_seq {
5003 let value_str = codegen_expr_boxed_with_types_oracle(
5004 value,
5005 interner,
5006 synced_vars,
5007 boxed_fields,
5008 registry,
5009 async_functions,
5010 ctx.get_string_vars(),
5011 ctx.get_variable_types(),
5012 ctx.get_fast_div(),
5013 ctx.oracle(),
5014 );
5015 let mut k_idx =
5016 super::peephole::logos_index(outer_idx, interner, ctx.get_variable_types());
5017 let mut i_idx = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5018 let mut value_str = value_str;
5019 if ordered(&[*index, *value, *outer_idx]) {
5023 let full = |e: &Expr| {
5024 codegen_expr_with_async(e, interner, synced_vars, async_functions, ctx.get_variable_types())
5025 };
5026 let (i_full, k_full) = (full(index), full(outer_idx));
5027 writeln!(output, "{indent_str}let __place_index = {i_full};").unwrap();
5028 writeln!(output, "{indent_str}let __place_value = {value_str};").unwrap();
5029 writeln!(output, "{indent_str}let __place_key = {k_full};").unwrap();
5030 (i_idx, value_str, k_idx) =
5031 ("__place_index".to_string(), "__place_value".to_string(), "__place_key".to_string());
5032 }
5033 emit_cow(base, ctx, &names, &indent_str, &mut output);
5034 writeln!(
5035 output,
5036 "{}{}.set_nested({}, {}, {});",
5037 indent_str,
5038 names.ident(*base_sym),
5039 k_idx,
5040 i_idx,
5041 value_str
5042 )
5043 .unwrap();
5044 return output;
5045 }
5046 }
5047 }
5048 if let Expr::Identifier(sym) = collection {
5050 if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(sym)) {
5051 let value_str = codegen_expr_boxed_with_types_oracle(
5052 value,
5053 interner,
5054 synced_vars,
5055 boxed_fields,
5056 registry,
5057 async_functions,
5058 ctx.get_string_vars(),
5059 ctx.get_variable_types(),
5060 ctx.get_fast_div(),
5061 ctx.oracle(),
5062 );
5063 let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5064 let item = super::expr::item_accessor(index, ctx.oracle(), true);
5065 writeln!(
5066 output,
5067 "{}{}.{}({})[{}] = {};",
5068 indent_str, tag.backing, item, at, tag.col, value_str
5069 )
5070 .unwrap();
5071 return output;
5072 }
5073 }
5074 let coll_str = codegen_expr_with_async(
5075 collection,
5076 interner,
5077 synced_vars,
5078 async_functions,
5079 ctx.get_variable_types(),
5080 );
5081 let value_str = codegen_expr_boxed_with_types_oracle(
5082 value,
5083 interner,
5084 synced_vars,
5085 boxed_fields,
5086 registry,
5087 async_functions,
5088 ctx.get_string_vars(),
5089 ctx.get_variable_types(),
5090 ctx.get_fast_div(),
5091 ctx.oracle(),
5092 );
5093 let value_str = match super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
5095 Some(item) => rational_value(
5096 value,
5097 &item,
5098 interner,
5099 ctx,
5100 synced_vars,
5101 async_functions,
5102 boxed_fields,
5103 registry,
5104 )
5105 .unwrap_or(value_str),
5106 None => value_str,
5107 };
5108 let value_str = stored_value(value, value_str, ctx.get_variable_types());
5109
5110 let rational_index = {
5112 let ecx = super::expr::ExprCtx {
5113 async_functions,
5114 variable_types: ctx.get_variable_types(),
5115 ..super::expr::ExprCtx::bare(interner, synced_vars)
5116 };
5117 super::rational::item_index(
5118 collection,
5119 index,
5120 crate::semantics::collections::IntegerPlace::ListStore,
5121 &ecx,
5122 )
5123 };
5124 if let Some(at) = rational_index {
5125 writeln!(output, "{}let __rational_index: i64 = {};", indent_str, at).unwrap();
5126 writeln!(output, "{}let __rational_value = {};", indent_str, value_str).unwrap();
5127 emit_cow(collection, ctx, &names, &indent_str, &mut output);
5128 writeln!(
5129 output,
5130 "{}LogosIndexMut::logos_set(&mut {}, __rational_index, __rational_value);",
5131 indent_str, coll_str
5132 )
5133 .unwrap();
5134 return output;
5135 }
5136
5137 if let Some(root) = get_root_identifier(collection) {
5142 let types = ctx.get_variable_types();
5143 if ordered(&[*index, *value])
5144 || super::expr::lends_binding(index, root, types)
5145 || super::expr::lends_binding(value, root, types)
5146 {
5147 let index_str = codegen_expr_with_async(
5148 index,
5149 interner,
5150 synced_vars,
5151 async_functions,
5152 ctx.get_variable_types(),
5153 );
5154 writeln!(output, "{}let __lent_index = {};", indent_str, index_str).unwrap();
5155 writeln!(output, "{}let __lent_value = {};", indent_str, value_str).unwrap();
5156 emit_cow(collection, ctx, &names, &indent_str, &mut output);
5157 writeln!(
5158 output,
5159 "{}LogosIndexMut::logos_set(&mut {}, __lent_index, __lent_value);",
5160 indent_str, coll_str
5161 )
5162 .unwrap();
5163 return output;
5164 }
5165 }
5166
5167 emit_cow(collection, ctx, &names, &indent_str, &mut output);
5171
5172 let known_type = if let Expr::Identifier(sym) = collection {
5175 ctx.get_variable_types()
5176 .get(sym)
5177 .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
5178 } else {
5179 None
5180 };
5181
5182 match known_type {
5183 Some("LogosBits") => {
5186 let store_unchecked = crate::optimize::active_config()
5187 .is_on(crate::optimization::Opt::Unchecked)
5188 && ctx
5189 .oracle()
5190 .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5191 if store_unchecked {
5192 crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5193 let zb_index =
5194 super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5195 let i0 = match &zb_index {
5196 Some(s) => s.clone(),
5197 None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5198 };
5199 let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5200 writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5201 if matches!(value, Expr::Literal(Literal::Boolean(true))) {
5202 writeln!(
5203 output,
5204 "{}unsafe {{ {}.set_true_unchecked({}); }}",
5205 indent_str, coll_str, offset
5206 )
5207 .unwrap();
5208 } else {
5209 writeln!(output, "{}let __set_val: bool = {};", indent_str, value_str).unwrap();
5210 writeln!(
5211 output,
5212 "{}unsafe {{ {}.set_unchecked({}, __set_val); }}",
5213 indent_str, coll_str, offset
5214 )
5215 .unwrap();
5216 }
5217 } else {
5218 let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5219 writeln!(output, "{}let __set_val: bool = {};", indent_str, value_str).unwrap();
5220 writeln!(
5221 output,
5222 "{}{}.set_item({}, __set_val);",
5223 indent_str, coll_str, at
5224 )
5225 .unwrap();
5226 }
5227 }
5228 Some(t) if t.starts_with("LogosSeq") => {
5229 let zb_index =
5231 super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5232 let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5233 let store_unchecked = crate::optimize::active_config()
5241 .is_on(crate::optimization::Opt::Unchecked)
5242 && ctx
5243 .oracle()
5244 .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5245 let place = if super::expr::range_proves_index(collection, index) {
5247 format!(
5248 "{}.borrow_mut()[{}]",
5249 coll_str,
5250 store_offset(index, zb_index.as_deref(), interner, ctx)
5251 )
5252 } else {
5253 format!(
5254 "*{}.borrow_mut().{}({})",
5255 coll_str,
5256 super::expr::item_accessor(index, ctx.oracle(), true),
5257 at
5258 )
5259 };
5260 let needs_tmp = store_unchecked || expr_reads_any_collection(value);
5265 if store_unchecked {
5266 crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5267 let i0 = match &zb_index {
5268 Some(s) => s.clone(),
5269 None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5270 };
5271 let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5272 writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5273 writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5274 writeln!(
5275 output,
5276 "{}unsafe {{ *{}.borrow_mut().get_unchecked_mut({}) = __set_val; }}",
5277 indent_str, coll_str, offset
5278 )
5279 .unwrap();
5280 } else if needs_tmp {
5281 writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5282 writeln!(output, "{}{} = __set_val;", indent_str, place).unwrap();
5283 } else {
5284 writeln!(output, "{}{} = {};", indent_str, place, value_str).unwrap();
5285 }
5286 }
5287 Some(t) if is_logos_map_type(t) => {
5288 let index_str = codegen_expr_with_async(
5289 index,
5290 interner,
5291 synced_vars,
5292 async_functions,
5293 ctx.get_variable_types(),
5294 );
5295 writeln!(
5296 output,
5297 "{}{}.insert({}, {});",
5298 indent_str, coll_str, index_str, value_str
5299 )
5300 .unwrap();
5301 }
5302 Some(t)
5303 if t.starts_with("Vec")
5304 || t.starts_with("&mut [")
5305 || t.starts_with("&[")
5306 || t.starts_with('[') =>
5307 {
5308 let zb_index =
5310 super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5311 let narrowed = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
5316 let value_str = if narrowed {
5317 format!("{{ let __nv: i64 = {}; __nv as i32 }}", value_str)
5318 } else {
5319 value_str
5320 };
5321 let store_unchecked = crate::optimize::active_config()
5326 .is_on(crate::optimization::Opt::Unchecked)
5327 && ctx
5328 .oracle()
5329 .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5330 if store_unchecked {
5331 crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5332 let i0 = match &zb_index {
5333 Some(s) => s.clone(),
5334 None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5335 };
5336 let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5337 writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5338 writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5343 writeln!(
5344 output,
5345 "{}unsafe {{ *{}.get_unchecked_mut({}) = __set_val; }}",
5346 indent_str, coll_str, offset
5347 )
5348 .unwrap();
5349 } else if super::expr::range_proves_index(collection, index) {
5350 let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5352 writeln!(
5353 output,
5354 "{}{}[{}] = {};",
5355 indent_str, coll_str, offset, value_str
5356 )
5357 .unwrap();
5358 } else {
5359 let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5360 writeln!(
5361 output,
5362 "{}*{}.{}({}) = {};",
5363 indent_str,
5364 coll_str,
5365 super::expr::item_accessor(index, ctx.oracle(), true),
5366 at,
5367 value_str
5368 )
5369 .unwrap();
5370 }
5371 }
5372 Some(t)
5373 if t.starts_with("std::collections::HashMap")
5374 || t.starts_with("HashMap")
5375 || t.starts_with("rustc_hash::FxHashMap")
5376 || t.starts_with("FxHashMap") =>
5377 {
5378 let index_str = codegen_expr_with_async(
5379 index,
5380 interner,
5381 synced_vars,
5382 async_functions,
5383 ctx.get_variable_types(),
5384 );
5385 writeln!(
5386 output,
5387 "{}{}.insert({}, {});",
5388 indent_str, coll_str, index_str, value_str
5389 )
5390 .unwrap();
5391 }
5392 _ => {
5393 let index_str = codegen_expr_with_async(
5394 index,
5395 interner,
5396 synced_vars,
5397 async_functions,
5398 ctx.get_variable_types(),
5399 );
5400 let needs_tmp = expr_reads_any_collection(value);
5406 if needs_tmp {
5407 writeln!(output, "{}let __set_tmp = {};", indent_str, value_str).unwrap();
5408 writeln!(
5409 output,
5410 "{}LogosIndexMut::logos_set(&mut {}, {}, __set_tmp);",
5411 indent_str, coll_str, index_str
5412 )
5413 .unwrap();
5414 } else {
5415 writeln!(
5416 output,
5417 "{}LogosIndexMut::logos_set(&mut {}, {}, {});",
5418 indent_str, coll_str, index_str, value_str
5419 )
5420 .unwrap();
5421 }
5422 }
5423 }
5424 output
5425}
5426
5427fn interferes(writer: &Expr, reader: &Expr) -> bool {
5430 let writes = crate::optimize::WriteSet::of_expr(writer);
5431 writes.is_opaque() || crate::optimize::Mentions::of_expr(reader).symbols().any(|s| writes.may_write(s))
5432}
5433
5434fn ordered(operands: &[&Expr]) -> bool {
5437 operands.iter().enumerate().any(|(i, a)| operands.iter().enumerate().any(|(j, b)| i != j && interferes(a, b)))
5438}
5439
5440#[inline(never)]
5444#[allow(clippy::too_many_arguments)]
5445fn collect_concat_leaves<'a>(e: &'a Expr<'a>, out: &mut Vec<&'a Expr<'a>>) {
5448 match e {
5449 Expr::BinaryOp {
5450 op: BinaryOpKind::Concat | BinaryOpKind::Add,
5451 left,
5452 right,
5453 } => {
5454 collect_concat_leaves(left, out);
5455 out.push(right);
5456 }
5457 _ => out.push(e),
5458 }
5459}
5460
5461fn concat_leaf_is_string(e: &Expr, ctx: &RefinementContext) -> bool {
5469 match e {
5470 Expr::Literal(Literal::Text(_)) => true,
5471 Expr::Identifier(s) => {
5472 ctx.get_string_vars().contains(s)
5473 || matches!(
5474 ctx.get_variable_types().get(s).map(String::as_str),
5475 Some("String") | Some("&str")
5476 )
5477 }
5478 Expr::Index { collection, .. } => matches!(
5479 crate::codegen::expr::seq_element_rust_type(collection, ctx.get_variable_types()),
5480 Some("String") | Some("&str")
5481 ),
5482 _ => false,
5483 }
5484}
5485
5486fn try_string_accum_push_str<'a>(
5491 target: &Symbol,
5492 value: &'a Expr<'a>,
5493 target_name: &str,
5494 interner: &Interner,
5495 ctx: &RefinementContext<'a>,
5496 synced_vars: &mut HashSet<Symbol>,
5497 async_functions: &HashSet<Symbol>,
5498 indent_str: &str,
5499) -> Option<String> {
5500 if ctx.get_variable_types().get(target).map(String::as_str) != Some("String") {
5502 return None;
5503 }
5504 let mut leaves: Vec<&Expr> = Vec::new();
5506 collect_concat_leaves(value, &mut leaves);
5507 if leaves.len() < 2 {
5508 return None;
5509 }
5510 match leaves[0] {
5511 Expr::Identifier(s) if *s == *target => {}
5512 _ => return None,
5513 }
5514 let vt = ctx.get_variable_types();
5517 for leaf in &leaves[1..] {
5518 if !concat_leaf_is_string(leaf, ctx) {
5519 return None;
5520 }
5521 let mut syms: Vec<Symbol> = Vec::new();
5522 collect_expr_symbols(leaf, &mut syms);
5523 if syms.contains(target) {
5524 return None;
5525 }
5526 }
5527 let mut code = String::new();
5528 for leaf in &leaves[1..] {
5529 push_concat_leaf(
5530 &mut code,
5531 target_name,
5532 leaf,
5533 interner,
5534 synced_vars,
5535 async_functions,
5536 vt,
5537 indent_str,
5538 );
5539 }
5540 Some(code)
5541}
5542
5543fn push_concat_leaf<'a>(
5549 code: &mut String,
5550 target_name: &str,
5551 leaf: &Expr<'a>,
5552 interner: &Interner,
5553 synced_vars: &mut HashSet<Symbol>,
5554 async_functions: &HashSet<Symbol>,
5555 vt: &HashMap<Symbol, String>,
5556 indent_str: &str,
5557) {
5558 match leaf {
5559 Expr::Literal(Literal::Text(sym)) => {
5560 writeln!(
5561 code,
5562 "{}{}.push_str(\"{}\");",
5563 indent_str,
5564 target_name,
5565 rust_string_escape(interner.resolve(*sym))
5566 )
5567 .unwrap();
5568 }
5569 Expr::Identifier(sym) if vt.get(sym).map(String::as_str) == Some("__single_char_u8") => {
5570 let ch = codegen_expr_with_async(leaf, interner, synced_vars, async_functions, vt);
5571 writeln!(code, "{}{}.push({} as char);", indent_str, target_name, ch).unwrap();
5572 }
5573 _ => {
5574 let s = codegen_expr_with_async(leaf, interner, synced_vars, async_functions, vt);
5575 writeln!(code, "{}{}.push_str(&({}));", indent_str, target_name, s).unwrap();
5576 }
5577 }
5578}
5579
5580fn try_string_concat_let<'a>(
5587 var: &Symbol,
5588 value: &'a Expr<'a>,
5589 var_name: &str,
5590 interner: &Interner,
5591 ctx: &RefinementContext<'a>,
5592 synced_vars: &mut HashSet<Symbol>,
5593 async_functions: &HashSet<Symbol>,
5594 indent_str: &str,
5595) -> Option<String> {
5596 let mut leaves: Vec<&Expr> = Vec::new();
5597 collect_concat_leaves(value, &mut leaves);
5598 if leaves.len() < 2 {
5599 return None;
5600 }
5601 let a_owned_string = match leaves[0] {
5603 Expr::Call { function, .. } => {
5604 ctx.get_fn_return(function).map(String::as_str) == Some("String")
5605 }
5606 _ => false,
5607 };
5608 if !a_owned_string {
5609 return None;
5610 }
5611 for leaf in &leaves[1..] {
5614 if !concat_leaf_is_string(leaf, ctx) {
5615 return None;
5616 }
5617 let mut syms: Vec<Symbol> = Vec::new();
5618 collect_expr_symbols(leaf, &mut syms);
5619 if syms.contains(var) {
5620 return None;
5621 }
5622 }
5623 let vt = ctx.get_variable_types();
5624 let a_code = codegen_expr_with_async(leaves[0], interner, synced_vars, async_functions, vt);
5625 let mut code = format!("{}let mut {} = {};\n", indent_str, var_name, a_code);
5626 for leaf in &leaves[1..] {
5627 push_concat_leaf(
5628 &mut code,
5629 var_name,
5630 leaf,
5631 interner,
5632 synced_vars,
5633 async_functions,
5634 vt,
5635 indent_str,
5636 );
5637 }
5638 Some(code)
5639}
5640
5641fn codegen_set_stmt<'a>(
5642 mut output: String,
5643 target: &Symbol,
5644 value: &&'a Expr<'a>,
5645 interner: &Interner,
5646 ctx: &mut RefinementContext<'a>,
5647 synced_vars: &mut HashSet<Symbol>,
5648 async_functions: &HashSet<Symbol>,
5649 boxed_fields: &HashSet<(String, String, String)>,
5650 registry: &TypeRegistry,
5651 indent_str: &str,
5652 names: &RustNames,
5653 live_vars_after: Option<HashSet<Symbol>>,
5654) -> String {
5655 let target_name = if super::expr::lent_in_place(*target, ctx.get_variable_types()) {
5657 format!("(*{})", names.ident(*target))
5658 } else {
5659 names.ident(*target)
5660 };
5661
5662 if super::expr::lent_by_sharing(*target, ctx.get_variable_types()) {
5665 let held = ctx.get_variable_types().get(target).cloned().unwrap_or_default();
5666 let value_str = codegen_expr_with_async(value, interner, synced_vars, async_functions, ctx.get_variable_types());
5667 let contents = if held.starts_with("LogosSeq") { "to_vec()" } else { "borrow().clone()" };
5668 writeln!(
5669 output,
5670 "{}{{ let __replacement = {}; let __contents = __replacement.{}; *{}.borrow_mut() = __contents; }}",
5671 indent_str, value_str, contents, target_name
5672 )
5673 .unwrap();
5674 return output;
5675 }
5676
5677 if let Some(held) = ctx.get_variable_types().get(target).cloned() {
5679 let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
5680 if let Some(code) = super::absent::stored(value, &held, &ecx) {
5681 writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5682 return output;
5683 }
5684 }
5685
5686 if ctx
5687 .get_variable_types()
5688 .get(target)
5689 .is_some_and(|t| t == super::tower::VALUE)
5690 {
5691 let code = super::tower::statement_value(
5692 value,
5693 interner,
5694 synced_vars,
5695 async_functions,
5696 boxed_fields,
5697 registry,
5698 ctx.get_variable_types(),
5699 );
5700 writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5701 return output;
5702 }
5703
5704 if let Some(held) = ctx
5706 .get_variable_types()
5707 .get(target)
5708 .filter(|t| t.contains(super::rational::RATIONAL))
5709 .cloned()
5710 {
5711 if let Some(code) = rational_value(
5712 value,
5713 &held,
5714 interner,
5715 ctx,
5716 synced_vars,
5717 async_functions,
5718 boxed_fields,
5719 registry,
5720 ) {
5721 writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5722 return output;
5723 }
5724 }
5725
5726 if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
5730 && super::expr::is_wide_acc(*target)
5731 {
5732 let val: &Expr = value;
5733 if let Expr::BinaryOp {
5734 op: BinaryOpKind::Add,
5735 left,
5736 right,
5737 } = val
5738 {
5739 if matches!(left, Expr::Identifier(l) if *l == *target) {
5740 if let Expr::Literal(Literal::Number(k)) = right {
5741 crate::optimize::mark_fired(crate::optimization::Opt::WideAccumulator);
5742 writeln!(
5743 output,
5744 "{}{} = {} + {}i128;",
5745 indent_str, target_name, target_name, k
5746 )
5747 .unwrap();
5748 return output;
5749 }
5750 }
5751 }
5752 }
5753
5754 if let Expr::Identifier(sym) = value {
5759 if *sym == *target {
5760 return output;
5761 }
5762 }
5763
5764 if crate::optimize::active_config().is_on(crate::optimization::Opt::StringAccumReuse)
5769 && !ctx.is_bigint_var(*target)
5770 && ctx.indexed_string_build(*target).is_none()
5771 {
5772 if let Some(code) = try_string_accum_push_str(
5773 target,
5774 *value,
5775 &target_name,
5776 interner,
5777 ctx,
5778 synced_vars,
5779 async_functions,
5780 indent_str,
5781 ) {
5782 crate::optimize::mark_fired(crate::optimization::Opt::StringAccumReuse);
5783 output.push_str(&code);
5784 return output;
5785 }
5786 }
5787
5788 if ctx.is_bigint_var(*target) {
5794 if let Expr::BinaryOp {
5803 op: BinaryOpKind::Multiply,
5804 left,
5805 right,
5806 } = value
5807 {
5808 if crate::optimize::active_config().is_on(crate::optimization::Opt::BignumInPlace) {
5809 let left_is_acc = matches!(left, Expr::Identifier(s) if *s == *target);
5810 let right_is_acc = matches!(right, Expr::Identifier(s) if *s == *target);
5811 let scalar = match (left_is_acc, right_is_acc) {
5812 (true, false) => Some(right),
5813 (false, true) => Some(left),
5814 _ => None,
5815 };
5816 if let Some(scalar) = scalar {
5817 let scalar_str = match scalar {
5818 Expr::Identifier(s) if !ctx.is_bigint_var(*s) => Some(names.ident(*s)),
5819 Expr::Literal(Literal::Number(n)) => Some(format!("{}i64", n)),
5820 _ => None,
5821 };
5822 if let Some(scalar_str) = scalar_str {
5823 if count_target_reads(value, *target) == 1 {
5824 crate::optimize::mark_fired(crate::optimization::Opt::BignumInPlace);
5825 writeln!(
5826 output,
5827 "{}{}.mul_assign_i64({});",
5828 indent_str, target_name, scalar_str
5829 )
5830 .unwrap();
5831 if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
5832 emit_refinement_check(
5833 &target_name,
5834 bound_var,
5835 predicate,
5836 interner,
5837 &indent_str,
5838 &mut output,
5839 );
5840 }
5841 return output;
5842 }
5843 }
5844 }
5845 }
5846 }
5847 let movable = count_target_reads(value, *target) == 1;
5850 if movable {
5851 set_movable_last_use(Some(*target));
5852 }
5853 let raw = codegen_expr_boxed_with_types_oracle_tolerant(
5854 value,
5855 interner,
5856 synced_vars,
5857 boxed_fields,
5858 registry,
5859 async_functions,
5860 ctx.get_string_vars(),
5861 ctx.get_variable_types(),
5862 ctx.get_fast_div(),
5863 ctx.oracle(),
5864 );
5865 if movable {
5866 set_movable_last_use(None);
5867 }
5868 writeln!(
5869 output,
5870 "{}{} = logicaffeine_data::LogosInt::from({});",
5871 indent_str, target_name, raw
5872 )
5873 .unwrap();
5874 if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
5875 emit_refinement_check(
5876 &target_name,
5877 bound_var,
5878 predicate,
5879 interner,
5880 &indent_str,
5881 &mut output,
5882 );
5883 }
5884 return output;
5885 }
5886
5887 if let Some(cursor) = ctx.indexed_string_build(*target).map(|c| c.to_string()) {
5892 if let Expr::BinaryOp {
5893 op: BinaryOpKind::Add,
5894 right,
5895 ..
5896 } = value
5897 {
5898 match right {
5899 Expr::Literal(Literal::Text(sym)) => {
5900 let lit = interner.resolve(*sym);
5901 let bytes: Vec<String> = lit.bytes().map(|b| format!("{}u8", b)).collect();
5902 writeln!(
5903 output,
5904 "{ind}unsafe {{ std::ptr::copy_nonoverlapping([{b}].as_ptr(), {t}.as_mut_vec().as_mut_ptr().add(({c}) as usize), {k}); }}",
5905 ind = indent_str, t = target_name, c = cursor, k = lit.len(), b = bytes.join(", ")
5906 )
5907 .unwrap();
5908 return output;
5909 }
5910 Expr::Identifier(v)
5911 if ctx.get_variable_types().get(v).map(String::as_str)
5912 == Some("__single_char_u8") =>
5913 {
5914 let vn = names.ident(*v);
5915 writeln!(
5916 output,
5917 "{ind}unsafe {{ *{t}.as_mut_vec().as_mut_ptr().add(({c}) as usize) = {vn}; }}",
5918 ind = indent_str, t = target_name, c = cursor
5919 )
5920 .unwrap();
5921 return output;
5922 }
5923 _ => {}
5924 }
5925 }
5926 }
5927
5928 if ctx.is_de_rc(*target) {
5931 if let Some((_, init)) = derc_vec_decl(
5932 value,
5933 interner,
5934 synced_vars,
5935 boxed_fields,
5936 registry,
5937 async_functions,
5938 ctx,
5939 ) {
5940 writeln!(output, "{}{} = {};", indent_str, target_name, init).unwrap();
5941 return output;
5942 }
5943 }
5944
5945 let is_target_single_char_u8 = ctx
5947 .get_variable_types()
5948 .get(target)
5949 .map_or(false, |t| t == "__single_char_u8");
5950 if is_target_single_char_u8 {
5951 if let Expr::Literal(Literal::Text(sym)) = value {
5952 let text = interner.resolve(*sym);
5953 if text.len() == 1 {
5954 let ch = text.as_bytes()[0];
5955 writeln!(output, "{}{} = b'{}';", indent_str, target_name, ch as char).unwrap();
5956 return output;
5957 }
5958 }
5959 }
5960
5961 let string_vars = ctx.get_string_vars();
5962 let var_types = ctx.get_variable_types();
5963
5964 let used_write = if ctx.is_string_var(*target)
5968 && is_definitely_string_expr_with_vars(value, string_vars)
5969 {
5970 let mut operands = Vec::new();
5971 collect_string_concat_operands(value, string_vars, &mut operands);
5972
5973 if operands.len() >= 2 && matches!(operands[0], Expr::Identifier(sym) if *sym == *target) {
5975 let tail = &operands[1..];
5977 let mut tail_ids = HashSet::new();
5978 for op in tail {
5979 collect_expr_identifiers(op, &mut tail_ids);
5980 }
5981
5982 if !tail_ids.contains(target) {
5983 if tail.len() == 1 {
5984 let operand = tail[0];
5986 if let Expr::Literal(Literal::Text(sym)) = operand {
5987 let text = interner.resolve(*sym);
5988 if text.len() == 1 {
5989 let ch = text.chars().next().unwrap();
5990 writeln!(
5991 output,
5992 "{}{}.push('{}');",
5993 indent_str,
5994 target_name,
5995 rust_char_escape(ch)
5996 )
5997 .unwrap();
5998 } else {
5999 writeln!(
6000 output,
6001 "{}{}.push_str(\"{}\");",
6002 indent_str,
6003 target_name,
6004 rust_string_escape(text)
6005 )
6006 .unwrap();
6007 }
6008 } else if let Expr::Identifier(sym) = operand {
6009 if var_types
6010 .get(sym)
6011 .map_or(false, |t| t == "__single_char_u8")
6012 {
6013 let val_str = codegen_expr_boxed_with_types(
6015 operand,
6016 interner,
6017 synced_vars,
6018 boxed_fields,
6019 registry,
6020 async_functions,
6021 string_vars,
6022 var_types,
6023 ctx.get_fast_div(),
6024 );
6025 writeln!(
6026 output,
6027 "{}{}.push({} as char);",
6028 indent_str, target_name, val_str
6029 )
6030 .unwrap();
6031 } else if string_vars.contains(sym) {
6032 let val_str = codegen_expr_boxed_with_types(
6033 operand,
6034 interner,
6035 synced_vars,
6036 boxed_fields,
6037 registry,
6038 async_functions,
6039 string_vars,
6040 var_types,
6041 ctx.get_fast_div(),
6042 );
6043 writeln!(
6044 output,
6045 "{}{}.push_str(&{});",
6046 indent_str, target_name, val_str
6047 )
6048 .unwrap();
6049 } else {
6050 let val_str = codegen_expr_boxed_with_types(
6052 operand,
6053 interner,
6054 synced_vars,
6055 boxed_fields,
6056 registry,
6057 async_functions,
6058 string_vars,
6059 var_types,
6060 ctx.get_fast_div(),
6061 );
6062 writeln!(
6063 output,
6064 "{}write!({}, \"{{}}\", {}).unwrap();",
6065 indent_str, target_name, val_str
6066 )
6067 .unwrap();
6068 }
6069 } else {
6070 let val_str = codegen_expr_boxed_with_types(
6072 operand,
6073 interner,
6074 synced_vars,
6075 boxed_fields,
6076 registry,
6077 async_functions,
6078 string_vars,
6079 var_types,
6080 ctx.get_fast_div(),
6081 );
6082 writeln!(
6083 output,
6084 "{}write!({}, \"{{}}\", {}).unwrap();",
6085 indent_str, target_name, val_str
6086 )
6087 .unwrap();
6088 }
6089 } else if tail.iter().any(|op| {
6090 crate::codegen::types::infer_numeric_type(op, interner, var_types) == "i64"
6091 }) {
6092 for op in tail {
6100 if let Expr::Literal(Literal::Text(sym)) = op {
6101 let text = interner.resolve(*sym);
6102 if text.chars().count() == 1 {
6103 writeln!(
6104 output,
6105 "{}{}.push('{}');",
6106 indent_str,
6107 target_name,
6108 rust_char_escape(text.chars().next().unwrap())
6109 )
6110 .unwrap();
6111 } else {
6112 writeln!(
6113 output,
6114 "{}{}.push_str(\"{}\");",
6115 indent_str,
6116 target_name,
6117 rust_string_escape(text)
6118 )
6119 .unwrap();
6120 }
6121 continue;
6122 }
6123 let val_str = codegen_expr_boxed_with_types(
6124 op,
6125 interner,
6126 synced_vars,
6127 boxed_fields,
6128 registry,
6129 async_functions,
6130 string_vars,
6131 var_types,
6132 ctx.get_fast_div(),
6133 );
6134 if let Expr::Identifier(sym) = op {
6135 if string_vars.contains(sym) {
6136 writeln!(
6137 output,
6138 "{}{}.push_str(&{});",
6139 indent_str, target_name, val_str
6140 )
6141 .unwrap();
6142 continue;
6143 }
6144 if var_types
6145 .get(sym)
6146 .map_or(false, |t| t == "__single_char_u8")
6147 {
6148 writeln!(
6149 output,
6150 "{}{}.push({} as char);",
6151 indent_str, target_name, val_str
6152 )
6153 .unwrap();
6154 continue;
6155 }
6156 }
6157 if crate::codegen::types::infer_numeric_type(op, interner, var_types)
6158 == "i64"
6159 {
6160 writeln!(
6161 output,
6162 "{}{}.push_i64({});",
6163 indent_str, target_name, val_str
6164 )
6165 .unwrap();
6166 } else {
6167 writeln!(
6168 output,
6169 "{}write!({}, \"{{}}\", {}).unwrap();",
6170 indent_str, target_name, val_str
6171 )
6172 .unwrap();
6173 }
6174 }
6175 } else {
6176 let mut fmt = String::new();
6184 let mut args = Vec::new();
6185 for op in tail {
6186 fmt.push_str("{}");
6187 if let Expr::Literal(Literal::Text(sym)) = op {
6188 args.push(format!(
6189 "\"{}\"",
6190 rust_string_escape(interner.resolve(*sym))
6191 ));
6192 continue;
6193 }
6194 if let Expr::Identifier(sym) = op {
6195 if string_vars.contains(sym) {
6196 args.push(format!("&{}", names.ident(*sym)));
6197 continue;
6198 }
6199 }
6200 args.push(codegen_expr_boxed_with_types(
6201 op,
6202 interner,
6203 synced_vars,
6204 boxed_fields,
6205 registry,
6206 async_functions,
6207 string_vars,
6208 var_types,
6209 ctx.get_fast_div(),
6210 ));
6211 }
6212 writeln!(
6213 output,
6214 "{}write!({}, \"{}\", {}).unwrap();",
6215 indent_str,
6216 target_name,
6217 fmt,
6218 args.join(", ")
6219 )
6220 .unwrap();
6221 }
6222 true
6223 } else {
6224 false
6225 }
6226 } else {
6227 false
6228 }
6229 } else {
6230 false
6231 };
6232
6233 if !used_write {
6234 let mut used_mut_borrow = false;
6238 if let Expr::Call { function, args } = value {
6239 let callee_mut_borrow_indices: HashSet<usize> =
6240 super::fn_role_indices(var_types.get(function), super::FnRole::MutBorrow);
6241 if !callee_mut_borrow_indices.is_empty() {
6242 let target_at_mut_borrow = args.iter().enumerate().any(|(i, a)| {
6244 callee_mut_borrow_indices.contains(&i)
6245 && matches!(a, Expr::Identifier(sym) if *sym == *target)
6246 });
6247 if target_at_mut_borrow {
6248 let callee_borrow_indices: HashSet<usize> =
6249 super::fn_role_indices(var_types.get(function), super::FnRole::Borrow);
6250 let func_name = names.ident(*function);
6251 let args_str: Vec<String> = args
6252 .iter()
6253 .enumerate()
6254 .map(|(i, a)| {
6255 let s = codegen_expr_boxed_with_types(
6256 a,
6257 interner,
6258 synced_vars,
6259 boxed_fields,
6260 registry,
6261 async_functions,
6262 string_vars,
6263 var_types,
6264 ctx.get_fast_div(),
6265 );
6266 if callee_mut_borrow_indices.contains(&i) {
6267 if let Expr::Identifier(sym) = a {
6269 if let Some(ty) = var_types.get(sym) {
6270 let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
6271 if ty.starts_with("&mut [") {
6272 return s; }
6274 if ty.starts_with("Vec<") {
6277 return format!("&mut {}", s);
6278 }
6279 if ty.starts_with("LogosSeq") {
6280 return format!("&mut *{}.borrow_mut()", s);
6281 }
6282 }
6283 return format!("&mut *{}.borrow_mut()", s);
6285 }
6286 format!("&mut {}", s)
6287 } else if callee_borrow_indices.contains(&i) {
6288 if let Expr::Identifier(sym) = a {
6289 if let Some(ty) = var_types.get(sym) {
6290 let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
6291 if ty.starts_with("&[") || ty.starts_with("&mut [") {
6292 return s;
6293 }
6294 if ty.starts_with("Vec<") {
6295 return format!("&{}", s);
6296 }
6297 if ty.starts_with('[') {
6298 return format!("&{}", s);
6300 }
6301 if ty.starts_with("LogosSeq") {
6302 return format!("&*{}.borrow()", s);
6303 }
6304 }
6305 return format!("&*{}.borrow()", s);
6307 }
6308 format!("&*{}.borrow()", s)
6309 } else {
6310 s
6311 }
6312 })
6313 .collect();
6314 if crate::semantics::collections::value_semantics_enabled() {
6320 for (i, a) in args.iter().enumerate() {
6321 if !callee_mut_borrow_indices.contains(&i) {
6322 continue;
6323 }
6324 if let Expr::Identifier(sym) = a {
6325 let lends_refcell = match var_types.get(sym) {
6326 Some(t) => t
6327 .split("|__hl:")
6328 .next()
6329 .unwrap_or(t.as_str())
6330 .starts_with("LogosSeq"),
6331 None => true, };
6333 if lends_refcell {
6334 writeln!(output, "{}{}.cow();", indent_str, names.ident(*sym))
6335 .unwrap();
6336 }
6337 }
6338 }
6339 }
6340 let await_suffix = if async_functions.contains(function) {
6341 ".await"
6342 } else {
6343 ""
6344 };
6345 writeln!(
6346 output,
6347 "{}{}({}){};",
6348 indent_str,
6349 func_name,
6350 args_str.join(", "),
6351 await_suffix
6352 )
6353 .unwrap();
6354 used_mut_borrow = true;
6355 }
6356 }
6357 }
6358
6359 let value_str = if used_mut_borrow {
6364 String::new() } else if let Expr::Call { function, args } = value {
6366 if crate::semantics::builtins::builtin_from_name(interner.resolve(*function)).is_some()
6367 {
6368 codegen_expr_boxed_with_types(
6373 value,
6374 interner,
6375 synced_vars,
6376 boxed_fields,
6377 registry,
6378 async_functions,
6379 string_vars,
6380 var_types,
6381 ctx.get_fast_div(),
6382 )
6383 } else {
6384 let ecx = super::expr::ExprCtx {
6391 boxed_fields,
6392 registry,
6393 async_functions,
6394 string_vars,
6395 variable_types: var_types,
6396 fast_div: ctx.get_fast_div(),
6397 ..super::expr::ExprCtx::bare(interner, synced_vars)
6398 };
6399 let mut args_str = super::expr::call_arguments(*function, args, &ecx);
6400 for (i, a) in args.iter().enumerate() {
6401 let Expr::Identifier(sym) = a else { continue };
6402 let read = codegen_expr_boxed_with_types(
6403 a,
6404 interner,
6405 synced_vars,
6406 boxed_fields,
6407 registry,
6408 async_functions,
6409 string_vars,
6410 var_types,
6411 ctx.get_fast_div(),
6412 );
6413 let elsewhere = args.iter().enumerate().any(|(j, b)| {
6414 j != i && {
6415 let mut ids = HashSet::new();
6416 collect_expr_identifiers(b, &mut ids);
6417 ids.contains(sym)
6418 }
6419 });
6420 if *sym == *target && args_str[i] == format!("&*{read}.borrow()") {
6421 args_str[i] = format!("&*{read}.clone().borrow()");
6422 continue;
6423 }
6424 let last_read = *sym == *target
6425 || live_vars_after
6426 .as_ref()
6427 .is_some_and(|live| !live.contains(sym));
6428 if last_read && !elsewhere && args_str[i] == format!("{read}.clone()") {
6429 args_str[i] = read;
6430 }
6431 }
6432 let func_name =
6433 super::expr::called_function_path(*function, names.ident(*function), var_types);
6434 let await_suffix = if async_functions.contains(function) {
6435 ".await"
6436 } else {
6437 ""
6438 };
6439 super::expr::sequenced_call(
6440 &func_name,
6441 *function,
6442 args,
6443 args_str,
6444 await_suffix,
6445 var_types,
6446 )
6447 }
6448 } else {
6449 let vs = codegen_expr_boxed_with_types(
6450 value,
6451 interner,
6452 synced_vars,
6453 boxed_fields,
6454 registry,
6455 async_functions,
6456 string_vars,
6457 var_types,
6458 ctx.get_fast_div(),
6459 );
6460 stored_value(value, vs, var_types)
6461 };
6462 if !used_mut_borrow {
6463 writeln!(output, "{}{} = {};", indent_str, target_name, value_str).unwrap();
6464 }
6465 }
6466
6467 if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
6469 emit_refinement_check(
6470 &target_name,
6471 bound_var,
6472 predicate,
6473 interner,
6474 &indent_str,
6475 &mut output,
6476 );
6477 }
6478 output
6479}
6480
6481#[allow(clippy::too_many_arguments)]
6486fn rational_value(
6487 value: &Expr,
6488 held: &str,
6489 interner: &Interner,
6490 ctx: &RefinementContext,
6491 synced_vars: &HashSet<Symbol>,
6492 async_functions: &HashSet<Symbol>,
6493 boxed_fields: &HashSet<(String, String, String)>,
6494 registry: &TypeRegistry,
6495) -> Option<String> {
6496 let ecx = super::expr::ExprCtx {
6497 boxed_fields,
6498 registry,
6499 async_functions,
6500 string_vars: ctx.get_string_vars(),
6501 variable_types: ctx.get_variable_types(),
6502 fast_div: ctx.get_fast_div(),
6503 oracle: ctx.oracle(),
6504 ..super::expr::ExprCtx::bare(interner, synced_vars)
6505 };
6506 super::rational::value_as(value, &super::rational::named(held), &ecx)
6507}
6508
6509fn operand_ctx<'c>(
6511 interner: &'c Interner,
6512 ctx: &'c RefinementContext,
6513 synced_vars: &'c HashSet<Symbol>,
6514 async_functions: &'c HashSet<Symbol>,
6515 boxed_fields: &'c HashSet<(String, String, String)>,
6516 registry: &'c TypeRegistry,
6517) -> super::expr::ExprCtx<'c> {
6518 super::expr::ExprCtx {
6519 boxed_fields,
6520 registry,
6521 async_functions,
6522 string_vars: ctx.get_string_vars(),
6523 variable_types: ctx.get_variable_types(),
6524 fast_div: ctx.get_fast_div(),
6525 oracle: ctx.oracle(),
6526 ..super::expr::ExprCtx::bare(interner, synced_vars)
6527 }
6528}
6529
6530fn type_silent_let_annotation(value: &Expr, registered: Option<&String>) -> Option<String> {
6531 (super::types::type_silent_int(value).is_some() && registered.is_some_and(|t| t == "i64"))
6532 .then(|| "i64".to_string())
6533}
6534
6535#[inline(never)]
6542#[allow(clippy::too_many_arguments)]
6543fn codegen_let_stmt<'a>(
6544 mut output: String,
6545 stmt: &Stmt<'a>,
6546 var: &Symbol,
6547 ty: &Option<&'a TypeExpr<'a>>,
6548 value: &&'a Expr<'a>,
6549 mutable: &bool,
6550 interner: &Interner,
6551 mutable_vars: &HashSet<Symbol>,
6552 ctx: &mut RefinementContext<'a>,
6553 synced_vars: &mut HashSet<Symbol>,
6554 async_functions: &HashSet<Symbol>,
6555 boxed_fields: &HashSet<(String, String, String)>,
6556 registry: &TypeRegistry,
6557 indent_str: &str,
6558 names: &RustNames,
6559) -> String {
6560 let var_name = names.ident(*var);
6561
6562 let held = {
6564 let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
6565 super::absent::binding(stmt, *ty, value, &ecx).map(|held| {
6566 let code = super::absent::stored(value, &held, &ecx)
6567 .unwrap_or_else(|| super::absent::whole(value, &ecx));
6568 (held, code)
6569 })
6570 };
6571 if let Some((held, code)) = held {
6572 let decl_mut = if *mutable || mutable_vars.contains(var) { "mut " } else { "" };
6573 writeln!(output, "{}let {}{}: {} = {};", indent_str, decl_mut, var_name, held, code).unwrap();
6574 ctx.register_variable_type(*var, held);
6575 return output;
6576 }
6577
6578 if super::tower::binding(*var) {
6581 let code = super::tower::statement_value(
6582 value,
6583 interner,
6584 synced_vars,
6585 async_functions,
6586 boxed_fields,
6587 registry,
6588 ctx.get_variable_types(),
6589 );
6590 let decl_mut = if *mutable || mutable_vars.contains(var) { "mut " } else { "" };
6591 writeln!(
6592 output,
6593 "{}let {}{}: {} = {};",
6594 indent_str,
6595 decl_mut,
6596 var_name,
6597 super::tower::VALUE,
6598 code
6599 )
6600 .unwrap();
6601 ctx.register_variable_type(*var, super::tower::VALUE.to_string());
6602 return output;
6603 }
6604
6605 if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
6609 && super::expr::is_wide_acc(*var)
6610 {
6611 writeln!(output, "{}let mut {}: i128 = 0i128;", indent_str, var_name).unwrap();
6612 return output;
6613 }
6614
6615 if matches!(value, Expr::New { .. }) {
6620 if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(var)) {
6621 if tag.col == 0 {
6622 let default = match tag.elem.as_str() {
6623 "f64" => "0f64",
6624 "bool" => "false",
6625 _ => "0i64",
6626 };
6627 writeln!(
6628 output,
6629 "{}let mut {}: [[{}; {}]; {}] = [[{}; {}]; {}];",
6630 indent_str,
6631 tag.backing,
6632 tag.elem,
6633 tag.width,
6634 tag.len,
6635 default,
6636 tag.width,
6637 tag.len
6638 )
6639 .unwrap();
6640 }
6641 return output;
6642 }
6643 }
6644
6645 if crate::optimize::active_config().is_on(crate::optimization::Opt::StringConcatReuse) {
6649 if let Some(code) = try_string_concat_let(
6650 var,
6651 *value,
6652 &var_name,
6653 interner,
6654 ctx,
6655 synced_vars,
6656 async_functions,
6657 indent_str,
6658 ) {
6659 crate::optimize::mark_fired(crate::optimization::Opt::StringConcatReuse);
6660 ctx.register_variable_type(*var, "String".to_string());
6661 output.push_str(&code);
6662 return output;
6663 }
6664 }
6665
6666 if ctx.is_scalarized_array(*var) && matches!(value, Expr::New { .. }) {
6671 if let Some(arr_ty) = ctx.get_variable_types().get(var).cloned() {
6672 let inner = arr_ty.trim_start_matches('[').trim_end_matches(']');
6673 let mut parts = inner.split("; ");
6674 let elem = parts.next().unwrap_or("i64");
6675 let n = parts.next().unwrap_or("0");
6676 let default = match elem {
6677 "f64" => "0f64",
6678 "bool" => "false",
6679 "Word8" => "word8(0)",
6680 "Word16" => "word16(0)",
6681 "Word32" => "word32(0)",
6682 "Word64" => "word64(0)",
6683 _ => "0i64",
6684 };
6685 writeln!(
6686 output,
6687 "{}let mut {}: {} = [{}; {}];",
6688 indent_str, var_name, arr_ty, default, n
6689 )
6690 .unwrap();
6691 if let Some(cursor) = ctx.loop_fill_cursor(*var).map(|s| s.to_string()) {
6694 writeln!(output, "{}let mut {}: usize = 0;", indent_str, cursor).unwrap();
6695 }
6696 ctx.init_array_fill(*var);
6697 return output;
6698 }
6699 }
6700
6701 if matches!(value, Expr::New { .. }) && ctx.affine_array(*var).is_some() {
6706 return output;
6707 }
6708
6709 if matches!(value, Expr::New { .. }) {
6714 if let Some((cap, default, tail)) = ctx.worklist(*var).map(|w| {
6715 (
6716 w.capacity.clone(),
6717 w.elem_default.clone(),
6718 w.tail_var.clone(),
6719 )
6720 }) {
6721 writeln!(
6722 output,
6723 "{}let mut {}: Vec<i64> = vec![{}; {}];",
6724 indent_str, var_name, default, cap
6725 )
6726 .unwrap();
6727 writeln!(output, "{}let mut {}: usize = 0;", indent_str, tail).unwrap();
6728 ctx.register_variable_type(*var, format!("Vec<i64>|__hl:({} as i64)", tail));
6732 return output;
6733 }
6734 }
6735
6736 if ctx.is_bitpacked(*var) {
6739 let kw = if *mutable || mutable_vars.contains(var) {
6740 "let mut"
6741 } else {
6742 "let"
6743 };
6744 let init = match ctx.get_vec_presize(*var) {
6745 Some(cap) => format!(
6746 "logicaffeine_data::LogosBits::with_capacity(({}) as usize)",
6747 cap
6748 ),
6749 None => "logicaffeine_data::LogosBits::new()".to_string(),
6750 };
6751 writeln!(
6752 output,
6753 "{}{} {}: logicaffeine_data::LogosBits = {};",
6754 indent_str, kw, var_name, init
6755 )
6756 .unwrap();
6757 ctx.register_variable_type(*var, "LogosBits".to_string());
6758 return output;
6759 }
6760
6761 if ctx.is_de_rc(*var) {
6766 if let Some((vec_ty, init)) = derc_vec_decl(
6767 value,
6768 interner,
6769 synced_vars,
6770 boxed_fields,
6771 registry,
6772 async_functions,
6773 ctx,
6774 ) {
6775 let is_mut = *mutable || mutable_vars.contains(var);
6776 let kw = if is_mut { "let mut" } else { "let" };
6777 let init = match (init.as_str(), ctx.get_vec_presize(*var)) {
6781 ("Vec::new()", Some(cap)) => {
6782 format!("Vec::with_capacity(({}) as usize)", cap)
6783 }
6784 _ => init,
6785 };
6786 let vec_ty = if ctx.is_narrowed(*var) && vec_ty == "Vec<i64>" {
6789 "Vec<i32>".to_string()
6790 } else {
6791 vec_ty
6792 };
6793 writeln!(
6794 output,
6795 "{}{} {}: {} = {};",
6796 indent_str, kw, var_name, vec_ty, init
6797 )
6798 .unwrap();
6799 for g in ctx.narrow_guards(*var).to_vec() {
6800 writeln!(
6801 output,
6802 "{}assert!({}, \"LOGOS i32-narrowing guard: element value must fit i32\");",
6803 indent_str, g
6804 )
6805 .unwrap();
6806 }
6807 ctx.register_variable_type(*var, vec_ty);
6808 return output;
6809 }
6810 }
6811
6812 if let Some(TypeExpr::Generic { base, params }) = ty {
6815 let base_name = interner.resolve(*base);
6816 match base_name {
6817 "Seq" | "List" | "Vec" => {
6818 let rust_type = if !params.is_empty() {
6819 format!("LogosSeq<{}>", codegen_type_expr(¶ms[0], interner))
6820 } else {
6821 "LogosSeq<()>".to_string()
6822 };
6823 ctx.register_variable_type(*var, rust_type);
6824 }
6825 "Map" | "HashMap" => {
6826 let rust_type = if params.len() >= 2 {
6827 map_rust_type(
6828 &codegen_type_expr(¶ms[0], interner),
6829 &codegen_type_expr(¶ms[1], interner),
6830 *var,
6831 ctx,
6832 )
6833 } else {
6834 "LogosMap<String, String>".to_string()
6835 };
6836 ctx.register_variable_type(*var, rust_type);
6837 }
6838 _ => {}
6839 }
6840 } else if let Expr::New {
6841 type_name,
6842 type_args,
6843 ..
6844 } = value
6845 {
6846 let type_str = interner.resolve(*type_name);
6847 match type_str {
6848 "Seq" | "List" | "Vec" => {
6849 let rust_type = if !type_args.is_empty() {
6850 format!("LogosSeq<{}>", codegen_type_expr(&type_args[0], interner))
6851 } else {
6852 "LogosSeq<()>".to_string()
6853 };
6854 ctx.register_variable_type(*var, rust_type);
6855 }
6856 "Map" | "HashMap" => {
6857 let rust_type = if type_args.len() >= 2 {
6858 map_rust_type(
6859 &codegen_type_expr(&type_args[0], interner),
6860 &codegen_type_expr(&type_args[1], interner),
6861 *var,
6862 ctx,
6863 )
6864 } else {
6865 "LogosMap<String, String>".to_string()
6866 };
6867 ctx.register_variable_type(*var, rust_type);
6868 }
6869 other => {
6879 let is_struct = registry.iter_types().any(|(sym, def)| {
6880 matches!(def, TypeDef::Struct { .. })
6881 && super::types::rust_type_ident(interner.resolve(*sym)) == other
6882 });
6883 if is_struct {
6884 ctx.register_variable_type(*var, super::types::rust_type_ident(type_str));
6885 }
6886 }
6887 }
6888 } else if let Expr::List(items) = value {
6889 let held = super::rational::type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry });
6897 if held.holds_rational() {
6898 ctx.register_variable_type(*var, held.to_rust_type());
6899 } else {
6900 let elem_type = items
6901 .first()
6902 .and_then(|e| {
6903 crate::codegen::expr::value_rust_type(
6904 e,
6905 ctx.get_variable_types(),
6906 registry,
6907 interner,
6908 )
6909 })
6910 .unwrap_or_else(|| "_".to_string());
6911 ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem_type));
6912 }
6913 } else if matches!(value, Expr::Tuple(_) | Expr::NewVariant { .. }) {
6914 if let Some(rust_ty) = crate::codegen::expr::value_rust_type(
6917 value,
6918 ctx.get_variable_types(),
6919 registry,
6920 interner,
6921 ) {
6922 ctx.register_variable_type(*var, rust_ty);
6923 }
6924 } else if let Expr::Identifier(src_sym) = value {
6925 if let Some(src_type) = ctx.get_variable_types().get(src_sym).cloned() {
6928 if src_type.starts_with("&[") {
6929 ctx.register_variable_type(*var, src_type);
6931 } else if src_type.starts_with("&mut [") {
6932 ctx.register_variable_type(*var, src_type);
6935 } else if !super::is_fn_role_slot(&src_type) {
6936 ctx.register_variable_type(*var, src_type);
6937 }
6938 }
6939 } else if let Expr::Copy { expr: inner } = value {
6940 let src_sym = match inner {
6942 Expr::Slice { collection, .. } => {
6943 if let Expr::Identifier(s) = collection {
6944 Some(*s)
6945 } else {
6946 None
6947 }
6948 }
6949 Expr::Identifier(s) => Some(*s),
6950 _ => None,
6951 };
6952 if let Some(s) = src_sym {
6953 if let Some(src_type) = ctx.get_variable_types().get(&s).cloned() {
6954 if src_type.starts_with("LogosSeq")
6955 || src_type.starts_with("Vec")
6956 || src_type.starts_with("&[")
6957 {
6958 let elem = if src_type.starts_with("LogosSeq<") {
6959 src_type
6960 .strip_prefix("LogosSeq<")
6961 .and_then(|t| t.strip_suffix('>'))
6962 .unwrap_or("_")
6963 } else if src_type.starts_with("Vec<") {
6964 src_type
6965 .strip_prefix("Vec<")
6966 .and_then(|t| t.strip_suffix('>'))
6967 .unwrap_or("_")
6968 } else {
6969 src_type
6970 .strip_prefix("&[")
6971 .and_then(|t| t.strip_suffix(']'))
6972 .unwrap_or("_")
6973 };
6974 ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem));
6975 } else if src_type.starts_with("LogosMap") {
6976 ctx.register_variable_type(*var, src_type);
6977 }
6978 }
6979 }
6980 }
6981
6982 if let Some(exact) =
6988 crate::codegen::expr::exact_value_type_of(value, ctx.get_variable_types(), interner)
6989 {
6990 ctx.register_variable_type(*var, exact.to_string());
6991 }
6992
6993 if let Expr::FieldAccess { object, field } = value {
6997 if let Expr::Identifier(obj_sym) = object {
6998 if let Some(struct_name) = ctx.get_variable_types().get(obj_sym).cloned() {
6999 let field_name = interner.resolve(*field);
7000 for (tname, tdef) in registry.iter_types() {
7001 if interner.resolve(*tname) == struct_name {
7002 if let crate::analysis::registry::TypeDef::Struct { fields, .. } = tdef {
7003 if let Some(fd) = fields
7004 .iter()
7005 .find(|fd| interner.resolve(fd.name) == field_name)
7006 {
7007 let rust_ty =
7008 crate::codegen::types::codegen_field_type(&fd.ty, interner);
7009 ctx.register_variable_type(*var, rust_ty);
7010 }
7011 }
7012 break;
7013 }
7014 }
7015 }
7016 }
7017 }
7018
7019 if !ctx.get_variable_types().contains_key(var) {
7021 if let Expr::Call { function, .. } = value {
7022 if interner.resolve(*function) == "decimal" {
7025 ctx.register_variable_type(*var, "LogosDecimal".to_string());
7026 } else if interner.resolve(*function) == "complex" {
7027 ctx.register_variable_type(*var, "LogosComplex".to_string());
7029 } else if interner.resolve(*function) == "modular" {
7030 ctx.register_variable_type(*var, "LogosModular".to_string());
7031 } else if matches!(interner.resolve(*function), "quantity" | "convert") {
7032 ctx.register_variable_type(*var, "LogosQuantity".to_string());
7035 } else if interner.resolve(*function) == "money" {
7036 ctx.register_variable_type(*var, "LogosMoney".to_string());
7039 } else if matches!(
7040 interner.resolve(*function),
7041 "uuid"
7042 | "uuid_nil"
7043 | "uuid_max"
7044 | "uuid_v3"
7045 | "uuid_v5"
7046 | "uuid_dns"
7047 | "uuid_url"
7048 | "uuid_oid"
7049 | "uuid_x500"
7050 ) {
7051 ctx.register_variable_type(*var, "LogosUuid".to_string());
7054 } else if interner.resolve(*function) == "text_from_bytes" {
7055 ctx.register_variable_type(*var, "String".to_string());
7059 } else if let Some(rt) = ctx.get_fn_return(function).cloned() {
7060 ctx.register_variable_type(*var, rt);
7061 }
7062 }
7063 }
7064
7065 if !ctx.get_variable_types().contains_key(var) {
7067 let inferred = infer_rust_type_from_expr(value, interner);
7068 if inferred != "_" {
7069 ctx.register_variable_type(*var, inferred);
7070 } else {
7071 let numeric = infer_numeric_type(value, interner, ctx.get_variable_types());
7073 if numeric != "unknown" {
7074 ctx.register_variable_type(*var, numeric.to_string());
7075 } else if let crate::analysis::types::LogosType::Map(k, v) =
7076 super::types::infer_logos_type(value, interner, ctx.get_variable_types())
7077 {
7078 ctx.register_variable_type(
7083 *var,
7084 crate::analysis::types::LogosType::Map(k, v).to_rust_type(),
7085 );
7086 }
7087 }
7088 }
7089
7090 if !ctx.get_variable_types().contains_key(var) {
7097 if let Expr::Index {
7098 collection,
7099 index: Expr::Literal(Literal::Number(n)),
7100 } = value
7101 {
7102 if *n >= 1 {
7103 let tuple_type = match collection {
7104 Expr::Identifier(tuple_sym) => ctx.get_variable_types().get(tuple_sym).cloned(),
7105 other => crate::codegen::expr::record_field_rust_type(
7106 other,
7107 interner,
7108 ctx.get_variable_types(),
7109 registry,
7110 ),
7111 };
7112 if let Some(ty) = tuple_type
7113 .as_deref()
7114 .and_then(|t| super::types::logos_tuple_elem_type(t, *n).map(str::to_string))
7115 {
7116 ctx.register_variable_type(*var, ty);
7117 }
7118 }
7119 }
7120 }
7121
7122 if matches!(value, Expr::List(_))
7127 && ctx
7128 .get_variable_types()
7129 .get(var)
7130 .map_or(false, |t| t == "LogosSeq<_>")
7131 {
7132 if let crate::analysis::types::LogosType::Seq(inner) =
7133 super::types::infer_logos_type(value, interner, ctx.get_variable_types())
7134 {
7135 if matches!(*inner, crate::analysis::types::LogosType::Seq(_)) {
7136 ctx.register_variable_type(
7137 *var,
7138 crate::analysis::types::LogosType::Seq(inner).to_rust_type(),
7139 );
7140 }
7141 }
7142 }
7143
7144 let is_single_char_u8 = ctx
7147 .get_variable_types()
7148 .get(var)
7149 .map_or(false, |t| t == "__single_char_u8");
7150
7151 if is_single_char_u8 {
7152 if let Expr::Literal(Literal::Text(sym)) = value {
7153 let text = interner.resolve(*sym);
7154 if text.len() == 1 {
7155 let ch = text.as_bytes()[0];
7156 let is_mutable = *mutable || mutable_vars.contains(var);
7157 if is_mutable {
7158 writeln!(
7159 output,
7160 "{}let mut {}: u8 = b'{}';",
7161 indent_str, var_name, ch as char
7162 )
7163 .unwrap();
7164 } else {
7165 writeln!(
7166 output,
7167 "{}let {}: u8 = b'{}';",
7168 indent_str, var_name, ch as char
7169 )
7170 .unwrap();
7171 }
7172 return output;
7174 }
7175 }
7176 }
7177
7178 if let Expr::Slice {
7183 collection,
7184 start,
7185 end,
7186 } = value
7187 {
7188 if let Expr::Identifier(coll_sym) = collection {
7189 if let Some(coll_type) = ctx.get_variable_types().get(coll_sym).cloned() {
7190 if coll_type.starts_with("LogosSeq<") {
7191 let elem_type = coll_type
7192 .strip_prefix("LogosSeq<")
7193 .and_then(|t| t.strip_suffix('>'))
7194 .unwrap_or("_");
7195 let coll_name = names.ident(*coll_sym);
7196 let start_str = codegen_expr_boxed_with_types(
7197 start,
7198 interner,
7199 synced_vars,
7200 boxed_fields,
7201 registry,
7202 async_functions,
7203 ctx.get_string_vars(),
7204 ctx.get_variable_types(),
7205 ctx.get_fast_div(),
7206 );
7207 let end_str = codegen_expr_boxed_with_types(
7208 end,
7209 interner,
7210 synced_vars,
7211 boxed_fields,
7212 registry,
7213 async_functions,
7214 ctx.get_string_vars(),
7215 ctx.get_variable_types(),
7216 ctx.get_fast_div(),
7217 );
7218 let is_mutable = *mutable || mutable_vars.contains(var);
7219 let mutk = if is_mutable { "mut " } else { "" };
7220 writeln!(
7221 output,
7222 "{}let {}{}: Vec<{}> = {}.borrow().logos_slice({}, {}).to_vec();",
7223 indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str
7224 )
7225 .unwrap();
7226 ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
7229 if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7230 ctx.register_string_var(*var);
7231 }
7232 return output;
7233 } else if coll_type.starts_with("&[") {
7234 let elem_type = coll_type
7235 .strip_prefix("&[")
7236 .and_then(|t| t.strip_suffix(']'))
7237 .unwrap_or("_");
7238 let coll_name = names.ident(*coll_sym);
7239 let start_str = codegen_expr_boxed_with_types(
7240 start,
7241 interner,
7242 synced_vars,
7243 boxed_fields,
7244 registry,
7245 async_functions,
7246 ctx.get_string_vars(),
7247 ctx.get_variable_types(),
7248 ctx.get_fast_div(),
7249 );
7250 let end_str = codegen_expr_boxed_with_types(
7251 end,
7252 interner,
7253 synced_vars,
7254 boxed_fields,
7255 registry,
7256 async_functions,
7257 ctx.get_string_vars(),
7258 ctx.get_variable_types(),
7259 ctx.get_fast_div(),
7260 );
7261 let is_mutable = *mutable || mutable_vars.contains(var);
7262 let mutk = if is_mutable { "mut " } else { "" };
7263 writeln!(
7265 output,
7266 "{}let {}{}: Vec<{}> = {}.logos_slice({}, {}).to_vec();",
7267 indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str
7268 )
7269 .unwrap();
7270 ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
7271 if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7272 ctx.register_string_var(*var);
7273 }
7274 return output;
7275 }
7276 }
7277 }
7278 }
7279
7280 let is_bigint_binding = ty.is_none()
7285 && ctx.is_promotable_candidate(*var)
7286 && crate::codegen::types::infer_numeric_type(value, interner, ctx.get_variable_types())
7287 == "i64";
7288 if is_bigint_binding {
7289 ctx.register_variable_type(*var, "i64|__bigint".to_string());
7290 }
7291
7292 let mut value_str = if is_bigint_binding {
7294 let raw = codegen_expr_boxed_with_types_oracle_tolerant(
7297 value,
7298 interner,
7299 synced_vars,
7300 boxed_fields,
7301 registry,
7302 async_functions,
7303 ctx.get_string_vars(),
7304 ctx.get_variable_types(),
7305 ctx.get_fast_div(),
7306 ctx.oracle(),
7307 );
7308 format!("logicaffeine_data::LogosInt::from({})", raw)
7309 } else {
7310 codegen_expr_boxed_with_types_oracle(
7311 value,
7312 interner,
7313 synced_vars,
7314 boxed_fields,
7315 registry,
7316 async_functions,
7317 ctx.get_string_vars(),
7318 ctx.get_variable_types(),
7319 ctx.get_fast_div(),
7320 ctx.oracle(),
7321 )
7322 };
7323
7324 if ctx.is_i64_map(*var) {
7330 let dense = ctx.dense_info(*var);
7334 let i64_ty = if let Some(info) = dense {
7335 dense_type_name(info.kind)
7336 } else if ctx.is_i32_set(*var) {
7337 "LogosI32Set"
7338 } else if ctx.is_i32_map(*var) {
7339 "LogosI32Map"
7340 } else if ctx.is_i64_set(*var) {
7341 "LogosI64Set"
7342 } else {
7343 "LogosI64Map"
7344 };
7345 if let Some(ctor) = i64_map_ctor(
7346 value,
7347 i64_ty,
7348 dense.map(|i| i.lo),
7349 interner,
7350 synced_vars,
7351 boxed_fields,
7352 registry,
7353 async_functions,
7354 ctx,
7355 ) {
7356 value_str = ctor;
7357 ctx.register_variable_type(*var, i64_ty.to_string());
7358 }
7359 }
7360
7361 let is_mutable = *mutable || mutable_vars.contains(var) || ctx.is_i64_map(*var);
7365
7366 if let Expr::Identifier(src_sym) = value {
7375 if let Some(src_type) = ctx.get_variable_types().get(src_sym) {
7376 if super::expr::lent_by_sharing(*src_sym, ctx.get_variable_types()) {
7377 value_str = format!("{}.deep_clone()", value_str);
7378 } else if src_type.starts_with("LogosSeq") || src_type.starts_with("LogosMap") {
7379 value_str = format!("{}.clone()", value_str);
7380 } else if is_mutable && src_type.starts_with("&[") {
7381 value_str = format!("{}.to_vec()", value_str);
7382 } else if !is_copy_type(src_type)
7383 && !src_type.starts_with("&[")
7384 && !src_type.starts_with("&mut [")
7385 {
7386 value_str = format!("{}.clone()", value_str);
7387 }
7388 }
7389 }
7390
7391 if let Expr::FieldAccess { object, field } = value {
7400 let field_name = interner.resolve(*field);
7401 let is_copy_scalar = if let Expr::Identifier(obj_sym) = object {
7402 ctx.get_variable_types()
7403 .get(obj_sym)
7404 .and_then(|ty_name| interner.lookup(ty_name))
7405 .and_then(|ty_sym| registry.get(ty_sym))
7406 .and_then(|def| match def {
7407 logicaffeine_language::analysis::registry::TypeDef::Struct {
7408 fields, ..
7409 } => fields
7410 .iter()
7411 .find(|f| interner.resolve(f.name) == field_name),
7412 _ => None,
7413 })
7414 .map(|fd| {
7415 matches!(
7416 super::types::codegen_field_type(&fd.ty, interner).as_str(),
7417 "i64" | "f64" | "bool"
7418 )
7419 })
7420 .unwrap_or(false)
7421 } else {
7422 false
7423 };
7424 if !is_copy_scalar {
7425 value_str = format!("{}.clone()", value_str);
7426 }
7427 }
7428
7429 let type_annotation = if is_bigint_binding {
7431 Some("logicaffeine_data::LogosInt".to_string())
7432 } else {
7433 ty.map(|t| codegen_type_expr(t, interner))
7434 .or_else(|| ctx.rational_join(*var).cloned())
7435 .or_else(|| super::rational::rational_type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }))
7436 .or_else(|| infer_variant_type_annotation(value, registry, interner))
7437 .or_else(|| type_silent_let_annotation(value, ctx.get_variable_types().get(var)))
7438 };
7439
7440 if let Some(held) = type_annotation.clone().filter(|t| t.contains(super::rational::RATIONAL)) {
7443 let to = super::rational::named(&held);
7444 if let Some(code) = rational_value(
7445 value,
7446 &held,
7447 interner,
7448 ctx,
7449 synced_vars,
7450 async_functions,
7451 boxed_fields,
7452 registry,
7453 ) {
7454 value_str = code;
7455 } else if to == crate::analysis::types::LogosType::Rational
7456 && super::rational::type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry })
7457 == crate::analysis::types::LogosType::Unknown
7458 && !is_rational_expr(value, ctx.get_variable_types())
7459 {
7460 value_str = format!("LogosRational::from_i64(({}) as i64)", value_str);
7461 }
7462 ctx.register_variable_type(*var, held);
7463 }
7464
7465 match (is_mutable, type_annotation) {
7466 (true, Some(t)) => writeln!(
7467 output,
7468 "{}let mut {}: {} = {};",
7469 indent_str, var_name, t, value_str
7470 )
7471 .unwrap(),
7472 (true, None) => writeln!(
7473 output,
7474 "{}let mut {} = {};",
7475 indent_str, var_name, value_str
7476 )
7477 .unwrap(),
7478 (false, Some(t)) => writeln!(
7479 output,
7480 "{}let {}: {} = {};",
7481 indent_str, var_name, t, value_str
7482 )
7483 .unwrap(),
7484 (false, None) => {
7485 writeln!(output, "{}let {} = {};", indent_str, var_name, value_str).unwrap()
7486 }
7487 }
7488
7489 if let Some(helper) = ctx.get_fast_div().get(var) {
7494 writeln!(
7495 output,
7496 "{}let {} = logicaffeine_data::LogosDivU64::new(({}) as u64);",
7497 indent_str, helper, var_name
7498 )
7499 .unwrap();
7500 }
7501
7502 if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7504 ctx.register_string_var(*var);
7505 }
7506
7507 if let Some(TypeExpr::Refinement {
7509 base: _,
7510 var: bound_var,
7511 predicate,
7512 }) = ty
7513 {
7514 emit_refinement_check(
7515 &var_name,
7516 *bound_var,
7517 predicate,
7518 interner,
7519 &indent_str,
7520 &mut output,
7521 );
7522 ctx.register(*var, *bound_var, predicate);
7523 }
7524 output
7525}
7526
7527pub fn codegen_stmt<'a>(
7528 stmt: &Stmt<'a>,
7529 interner: &Interner,
7530 indent: usize,
7531 mutable_vars: &HashSet<Symbol>,
7532 ctx: &mut RefinementContext<'a>,
7533 lww_fields: &HashSet<(String, String)>,
7534 mv_fields: &HashSet<(String, String)>, synced_vars: &mut HashSet<Symbol>, var_caps: &HashMap<Symbol, VariableCapabilities>, async_functions: &HashSet<Symbol>, pipe_vars: &HashSet<Symbol>, boxed_fields: &HashSet<(String, String, String)>, registry: &TypeRegistry, type_env: &crate::analysis::types::TypeEnv,
7542) -> String {
7543 let indent_str = " ".repeat(indent);
7544 let mut output = String::new();
7545 let names = RustNames::new(interner);
7546
7547 let live_vars_after: Option<HashSet<Symbol>> = super::flow::live_after(stmt);
7550 let _flow = super::flow::enter(stmt);
7551 let _control = super::control::enter(stmt);
7552
7553 if super::deterministic_replay_enabled() {
7555 let mut scope = super::replay::Scope {
7556 interner,
7557 indent,
7558 mutable_vars,
7559 ctx: &mut *ctx,
7560 lww_fields,
7561 mv_fields,
7562 synced_vars: &mut *synced_vars,
7563 var_caps,
7564 async_functions,
7565 pipe_vars,
7566 boxed_fields,
7567 registry,
7568 type_env,
7569 };
7570 if let Some(code) = super::replay::replay_stmt(stmt, &mut scope) {
7571 output.push_str(&code);
7572 return output;
7573 }
7574 }
7575
7576 if let Stmt::Let { var, .. } = stmt {
7580 if ctx.scratch_buffer(*var).is_some() {
7581 return output;
7582 }
7583 }
7584
7585 output.push_str(&emit_oracle_index_hints(stmt, ctx, interner, registry, &indent_str));
7589
7590 let held = {
7592 let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
7593 super::absent::statement(stmt, &ecx, &indent_str)
7594 };
7595 if let Some((code, bound)) = held {
7596 output.push_str(&code);
7597 if let Some((var, ty)) = bound {
7598 ctx.register_variable_type(var, ty);
7599 }
7600 return output;
7601 }
7602
7603 match stmt {
7604 Stmt::RouteDef { method, path, .. } => {
7613 if let Some(why) = crate::codegen::expr::route_refusal(*method, *path) {
7614 output.push_str(&format!(
7615 "{indent_str}compile_error!(\"this `## Route` cannot run on this tier yet: {}.\");\n",
7616 why.replace('"', "'")
7617 ));
7618 }
7619 }
7620 Stmt::MiddlewareDef { .. } | Stmt::RedirectDef { .. } => {}
7622 Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => {}
7635 Stmt::Ui(_)
7639 | Stmt::Fetch { .. }
7640 | Stmt::GivenFetch { .. }
7641 | Stmt::ServeFetches
7642 | Stmt::Replay { .. } => {
7643 output.push_str(&format!("{indent_str}compile_error!(\"this needs a browser: mounting, fetching and replaying run in a page, not in a server binary\");\n"));
7644 }
7645 Stmt::TestDef { .. } => {
7646 }
7650 Stmt::Expect { .. }
7651 | Stmt::ExpectFail { .. }
7652 | Stmt::ExpectOutput { .. }
7653 | Stmt::AdvanceTime { .. }
7654 | Stmt::GivenFile { .. }
7655 | Stmt::ForAll { .. } => {
7656 unreachable!("test-only statement reached codegen outside a ## Test block")
7658 }
7659 Stmt::Observe {
7660 category,
7661 message,
7662 payloads,
7663 sample: _,
7664 } => {
7665 use logicaffeine_language::ast::stmt::ObsCategory;
7670 let kind = match category {
7671 ObsCategory::Note => "note",
7672 ObsCategory::Warn => "warn",
7673 ObsCategory::Record => "record",
7674 };
7675 let msg = interner.resolve(*message);
7676 let parts: Vec<String> = payloads
7677 .iter()
7678 .map(|(name, expr)| {
7679 let name_s = interner.resolve(*name);
7680 let expr_rust = codegen_expr_with_async_and_strings(
7681 expr,
7682 interner,
7683 synced_vars,
7684 async_functions,
7685 ctx.get_string_vars(),
7686 ctx.get_variable_types(),
7687 ctx.get_fast_div(),
7688 registry,
7689 );
7690 format!("({name_s:?}, format!(\"{{}}\", {expr_rust}))")
7691 })
7692 .collect();
7693 writeln!(
7694 output,
7695 "{indent_str}logicaffeine_system::obs::record({kind:?}, {msg:?}, &[{}]);",
7696 parts.join(", ")
7697 )
7698 .unwrap();
7699 }
7700 Stmt::During { label, body } => {
7701 let name = interner.resolve(*label);
7704 writeln!(
7705 output,
7706 "{indent_str}logicaffeine_system::obs::span_enter({name:?});"
7707 )
7708 .unwrap();
7709 for inner in body.iter() {
7710 output.push_str(&codegen_stmt(
7711 inner,
7712 interner,
7713 indent,
7714 mutable_vars,
7715 ctx,
7716 lww_fields,
7717 mv_fields,
7718 synced_vars,
7719 var_caps,
7720 async_functions,
7721 pipe_vars,
7722 boxed_fields,
7723 registry,
7724 type_env,
7725 ));
7726 }
7727 writeln!(
7728 output,
7729 "{indent_str}logicaffeine_system::obs::span_exit({name:?});"
7730 )
7731 .unwrap();
7732 }
7733 Stmt::Swap { a, b } => {
7734 let na = names.ident(*a);
7737 let nb = names.ident(*b);
7738 if na != nb {
7739 writeln!(output, "{indent_str}std::mem::swap(&mut {na}, &mut {nb});").unwrap();
7740 }
7741 }
7742 Stmt::Splice { body } => {
7743 for inner in body.iter() {
7747 output.push_str(&codegen_stmt(
7748 inner,
7749 interner,
7750 indent,
7751 mutable_vars,
7752 ctx,
7753 lww_fields,
7754 mv_fields,
7755 synced_vars,
7756 var_caps,
7757 async_functions,
7758 pipe_vars,
7759 boxed_fields,
7760 registry,
7761 type_env,
7762 ));
7763 }
7764 }
7765 Stmt::Reversibly { body } => {
7766 for inner in body.iter() {
7770 output.push_str(&codegen_stmt(
7771 inner,
7772 interner,
7773 indent,
7774 mutable_vars,
7775 ctx,
7776 lww_fields,
7777 mv_fields,
7778 synced_vars,
7779 var_caps,
7780 async_functions,
7781 pipe_vars,
7782 boxed_fields,
7783 registry,
7784 type_env,
7785 ));
7786 }
7787 }
7788 Stmt::Let {
7789 var,
7790 ty,
7791 value,
7792 mutable,
7793 } => {
7794 return codegen_let_stmt(
7795 output,
7796 stmt,
7797 var,
7798 ty,
7799 value,
7800 mutable,
7801 interner,
7802 mutable_vars,
7803 ctx,
7804 synced_vars,
7805 async_functions,
7806 boxed_fields,
7807 registry,
7808 &indent_str,
7809 &names,
7810 );
7811 }
7812
7813 Stmt::Set { target, value } => {
7814 return codegen_set_stmt(
7815 output,
7816 target,
7817 value,
7818 interner,
7819 ctx,
7820 synced_vars,
7821 async_functions,
7822 boxed_fields,
7823 registry,
7824 &indent_str,
7825 &names,
7826 live_vars_after,
7827 );
7828 }
7829
7830 Stmt::Call { function, args } => {
7831 let fish = super::instantiation::for_stmt(stmt);
7832 return codegen_call_stmt(
7833 output,
7834 function,
7835 &fish,
7836 args,
7837 interner,
7838 ctx,
7839 synced_vars,
7840 async_functions,
7841 &indent_str,
7842 &names,
7843 );
7844 }
7845
7846 Stmt::If {
7847 cond,
7848 then_block,
7849 else_block,
7850 } => {
7851 return codegen_if_stmt(
7852 output,
7853 cond,
7854 then_block,
7855 else_block,
7856 interner,
7857 indent,
7858 mutable_vars,
7859 ctx,
7860 lww_fields,
7861 mv_fields,
7862 synced_vars,
7863 var_caps,
7864 async_functions,
7865 pipe_vars,
7866 boxed_fields,
7867 registry,
7868 type_env,
7869 &indent_str,
7870 );
7871 }
7872
7873 Stmt::While {
7874 cond,
7875 body,
7876 decreasing: _,
7877 } => {
7878 return codegen_while_stmt(
7879 output,
7880 stmt,
7881 cond,
7882 body,
7883 interner,
7884 indent,
7885 mutable_vars,
7886 ctx,
7887 lww_fields,
7888 mv_fields,
7889 synced_vars,
7890 var_caps,
7891 async_functions,
7892 pipe_vars,
7893 boxed_fields,
7894 registry,
7895 type_env,
7896 &indent_str,
7897 );
7898 }
7899
7900 Stmt::Repeat {
7901 pattern,
7902 iterable,
7903 body,
7904 } => {
7905 return codegen_repeat_stmt(
7906 output,
7907 stmt,
7908 pattern,
7909 iterable,
7910 body,
7911 interner,
7912 indent,
7913 mutable_vars,
7914 ctx,
7915 lww_fields,
7916 mv_fields,
7917 synced_vars,
7918 var_caps,
7919 async_functions,
7920 pipe_vars,
7921 boxed_fields,
7922 registry,
7923 type_env,
7924 &indent_str,
7925 &names,
7926 );
7927 }
7928
7929 Stmt::Return { value } => {
7930 if let Some(exit) = super::control::return_label() {
7932 if let Some(value) = value {
7933 let value = codegen_expr_with_async(
7934 value,
7935 interner,
7936 synced_vars,
7937 async_functions,
7938 ctx.get_variable_types(),
7939 );
7940 writeln!(output, "{indent_str}let _ = {value};").unwrap();
7941 }
7942 writeln!(output, "{indent_str}break '{exit};").unwrap();
7943 return output;
7944 }
7945 return codegen_return_stmt(
7946 output,
7947 value,
7948 interner,
7949 ctx,
7950 synced_vars,
7951 async_functions,
7952 boxed_fields,
7953 registry,
7954 &indent_str,
7955 );
7956 }
7957
7958 Stmt::Break => match super::control::break_label() {
7959 Some(exit) => writeln!(output, "{indent_str}break '{exit};").unwrap(),
7960 None => writeln!(output, "{}break;", indent_str).unwrap(),
7961 },
7962
7963 Stmt::Assert { .. } => {}
7966
7967 Stmt::Trust { justification, .. } => {
7969 let reason = interner.resolve(*justification);
7970 let reason_clean = reason.trim_matches('"');
7972 writeln!(output, "{}// TRUST: {}", indent_str, reason_clean).unwrap();
7973 }
7974
7975 Stmt::RuntimeAssert {
7979 condition,
7980 hard: _,
7981 dim: _,
7982 reason,
7983 } => {
7984 let cond_str = codegen_expr_with_async_oracle(
7985 condition,
7986 interner,
7987 synced_vars,
7988 async_functions,
7989 ctx.get_variable_types(),
7990 ctx.oracle(),
7991 );
7992 match reason {
7993 None => {
7994 writeln!(
7996 output,
7997 "{}if !({}) {{ panic!(\"Assertion failed\"); }}",
7998 indent_str, cond_str
7999 )
8000 .unwrap();
8001 }
8002 Some(r) => {
8003 let reason_str = codegen_expr_with_async_oracle(
8004 r,
8005 interner,
8006 synced_vars,
8007 async_functions,
8008 ctx.get_variable_types(),
8009 ctx.oracle(),
8010 );
8011 writeln!(output, "{}if !({}) {{ panic!(\"{{}}\", logicaffeine_data::contract_reason(&({}))); }}", indent_str, cond_str, reason_str).unwrap();
8012 }
8013 }
8014 }
8015
8016 Stmt::Fail { reason } => {
8017 let reason_str = codegen_expr_with_async_oracle(
8018 reason,
8019 interner,
8020 synced_vars,
8021 async_functions,
8022 ctx.get_variable_types(),
8023 ctx.oracle(),
8024 );
8025 writeln!(
8027 output,
8028 "{}panic!(\"{{}}\", logicaffeine_system::io::show_string(&({})));",
8029 indent_str, reason_str
8030 )
8031 .unwrap();
8032 }
8033
8034 Stmt::Check {
8036 subject,
8037 predicate,
8038 is_capability,
8039 object,
8040 source_text,
8041 ..
8042 } => {
8043 let subj_name = interner.resolve(*subject);
8044 let pred_name = interner.resolve(*predicate).to_lowercase();
8045
8046 let call = if *is_capability {
8047 let obj_sym = object.expect("capability must have object");
8048 let obj_word = interner.resolve(obj_sym);
8049
8050 let obj_name = ctx
8054 .find_variable_by_type(obj_word, interner)
8055 .unwrap_or_else(|| obj_word.to_string());
8056
8057 format!("{}.can_{}(&{})", subj_name, pred_name, obj_name)
8058 } else {
8059 format!("{}.is_{}()", subj_name, pred_name)
8060 };
8061
8062 writeln!(output, "{}if !({}) {{", indent_str, call).unwrap();
8063 writeln!(
8064 output,
8065 "{} logicaffeine_system::panic_with({:?});",
8066 indent_str,
8067 crate::semantics::policy::check_failed(source_text)
8068 )
8069 .unwrap();
8070 writeln!(output, "{}}}", indent_str).unwrap();
8071 }
8072
8073 Stmt::Listen { address, secure } => {
8075 if secure.is_some() {
8078 writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
8079 return output;
8080 }
8081 let addr_str = codegen_expr_with_async(
8082 address,
8083 interner,
8084 synced_vars,
8085 async_functions,
8086 ctx.get_variable_types(),
8087 );
8088 writeln!(
8090 output,
8091 "{}logicaffeine_system::network::listen(&{}).await.expect(\"Failed to listen\");",
8092 indent_str, addr_str
8093 )
8094 .unwrap();
8095 }
8096
8097 Stmt::Serve { port, handler } => {
8103 return codegen_serve_stmt(
8104 output,
8105 port,
8106 handler,
8107 interner,
8108 ctx,
8109 synced_vars,
8110 async_functions,
8111 &indent_str,
8112 );
8113 }
8114
8115 Stmt::ConnectTo { address, secure } => {
8117 if secure.is_some() {
8118 writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
8119 return output;
8120 }
8121 let addr_str = codegen_expr_with_async(
8122 address,
8123 interner,
8124 synced_vars,
8125 async_functions,
8126 ctx.get_variable_types(),
8127 );
8128 writeln!(
8130 output,
8131 "{}logicaffeine_system::network::connect(&{}).await.expect(\"Failed to connect\");",
8132 indent_str, addr_str
8133 )
8134 .unwrap();
8135 }
8136
8137 Stmt::LetPeerAgent { var, address } => {
8139 let var_name = interner.resolve(*var);
8140 let addr_str = codegen_expr_with_async(
8141 address,
8142 interner,
8143 synced_vars,
8144 async_functions,
8145 ctx.get_variable_types(),
8146 );
8147 writeln!(output, "{}let {} = logicaffeine_system::network::PeerAgent::new(&{}).expect(\"Invalid address\");",
8149 indent_str, var_name, addr_str).unwrap();
8150 ctx.register_variable_type(*var, PEER_AGENT_TYPE.to_string());
8151 }
8152
8153 Stmt::Sleep { milliseconds } => {
8155 let expr_str = codegen_expr_with_async(
8156 milliseconds,
8157 interner,
8158 synced_vars,
8159 async_functions,
8160 ctx.get_variable_types(),
8161 );
8162 let inferred_type = infer_rust_type_from_expr(milliseconds, interner);
8163
8164 if inferred_type == "std::time::Duration" {
8165 writeln!(
8167 output,
8168 "{}tokio::time::sleep({}).await;",
8169 indent_str, expr_str
8170 )
8171 .unwrap();
8172 } else {
8173 writeln!(
8175 output,
8176 "{}tokio::time::sleep(std::time::Duration::from_millis({} as u64)).await;",
8177 indent_str, expr_str
8178 )
8179 .unwrap();
8180 }
8181 }
8182
8183 Stmt::Sync { var, topic } => {
8185 let var_name = interner.resolve(*var);
8186 let topic_str = codegen_expr_with_async(
8187 topic,
8188 interner,
8189 synced_vars,
8190 async_functions,
8191 ctx.get_variable_types(),
8192 );
8193
8194 if let Some(caps) = var_caps.get(var) {
8196 if caps.mounted {
8197 synced_vars.insert(*var);
8201 return output; }
8203 }
8204
8205 writeln!(
8207 output,
8208 "{}let {} = logicaffeine_system::crdt::Synced::new({}, &{}).await;",
8209 indent_str, var_name, var_name, topic_str
8210 )
8211 .unwrap();
8212 synced_vars.insert(*var);
8213 }
8214
8215 Stmt::Mount { var, path } => {
8217 let var_name = interner.resolve(*var);
8218 let path_str = codegen_expr_with_async(
8219 path,
8220 interner,
8221 synced_vars,
8222 async_functions,
8223 ctx.get_variable_types(),
8224 );
8225
8226 if let Some(caps) = var_caps.get(var) {
8228 if caps.synced {
8229 let topic_str = caps
8231 .sync_topic
8232 .as_ref()
8233 .map(|s| s.as_str())
8234 .unwrap_or("\"default\"");
8235 writeln!(
8236 output,
8237 "{}let {} = logicaffeine_system::distributed::Distributed::mount(vfs.clone(), &{}, Some({}.to_string())).await.expect(\"Failed to mount\");",
8238 indent_str, var_name, path_str, topic_str
8239 ).unwrap();
8240 synced_vars.insert(*var);
8241 return output;
8242 }
8243 }
8244
8245 writeln!(
8247 output,
8248 "{}let {} = logicaffeine_system::storage::Persistent::mount(vfs.clone(), &{}).await.expect(\"Failed to mount\");",
8249 indent_str, var_name, path_str
8250 ).unwrap();
8251 synced_vars.insert(*var);
8252 }
8253
8254 Stmt::LaunchTask { function, args } => {
8258 let fn_name = names.ident(*function);
8259 let args_str: Vec<String> = args
8261 .iter()
8262 .map(|a| {
8263 if let Expr::Identifier(sym) = a {
8264 if pipe_vars.contains(sym) {
8265 return format!("{}_tx.clone()", interner.resolve(*sym));
8266 }
8267 }
8268 let arg = codegen_expr_with_async(
8269 a,
8270 interner,
8271 synced_vars,
8272 async_functions,
8273 ctx.get_variable_types(),
8274 );
8275 super::tower::crossing_to_a_task(a, arg, ctx.get_variable_types(), interner)
8276 })
8277 .collect();
8278 let args_str: Vec<(String, bool)> = args_str
8279 .into_iter()
8280 .zip(args.iter())
8281 .map(|(s, a)| (s, matches!(a, Expr::Literal(_))))
8282 .collect();
8283 let await_suffix = if async_functions.contains(function) {
8285 ".await"
8286 } else {
8287 ""
8288 };
8289 writeln!(
8290 output,
8291 "{}tokio::spawn({});",
8292 indent_str,
8293 launched_future(&fn_name, &args_str, &format!("{await_suffix};"))
8294 )
8295 .unwrap();
8296 }
8297
8298 Stmt::LaunchTaskWithHandle {
8299 handle,
8300 function,
8301 args,
8302 } => {
8303 let handle_name = interner.resolve(*handle);
8304 let fn_name = names.ident(*function);
8305 let args_str: Vec<String> = args
8307 .iter()
8308 .map(|a| {
8309 if let Expr::Identifier(sym) = a {
8310 if pipe_vars.contains(sym) {
8311 return format!("{}_tx.clone()", interner.resolve(*sym));
8312 }
8313 }
8314 let arg = codegen_expr_with_async(
8315 a,
8316 interner,
8317 synced_vars,
8318 async_functions,
8319 ctx.get_variable_types(),
8320 );
8321 super::tower::crossing_to_a_task(a, arg, ctx.get_variable_types(), interner)
8322 })
8323 .collect();
8324 let args_str: Vec<(String, bool)> = args_str
8325 .into_iter()
8326 .zip(args.iter())
8327 .map(|(s, a)| (s, matches!(a, Expr::Literal(_))))
8328 .collect();
8329 let await_suffix = if async_functions.contains(function) {
8331 ".await"
8332 } else {
8333 ""
8334 };
8335 writeln!(
8336 output,
8337 "{}let {} = tokio::spawn({});",
8338 indent_str,
8339 handle_name,
8340 launched_future(&fn_name, &args_str, await_suffix)
8341 )
8342 .unwrap();
8343 }
8344
8345 Stmt::CreatePipe {
8346 var,
8347 element_type,
8348 capacity,
8349 } => {
8350 let var_name = interner.resolve(*var);
8351 let type_name = interner.resolve(*element_type);
8352 let cap = capacity.unwrap_or(32);
8353 let rust_type = match type_name {
8355 "Int" => "i64",
8356 "Nat" => "u64",
8357 "Text" => "String",
8358 "Bool" => "bool",
8359 _ => type_name,
8360 };
8361 writeln!(
8362 output,
8363 "{}let ({}_tx, mut {}_rx) = tokio::sync::mpsc::channel::<{}>({});",
8364 indent_str, var_name, var_name, rust_type, cap
8365 )
8366 .unwrap();
8367 }
8368
8369 Stmt::SendPipe { value, pipe } => {
8370 let val_str = codegen_expr_boxed_with_types_oracle(
8371 value,
8372 interner,
8373 synced_vars,
8374 boxed_fields,
8375 registry,
8376 async_functions,
8377 ctx.get_string_vars(),
8378 ctx.get_variable_types(),
8379 ctx.get_fast_div(),
8380 ctx.oracle(),
8381 );
8382 let pipe_str = codegen_expr_with_async(
8383 pipe,
8384 interner,
8385 synced_vars,
8386 async_functions,
8387 ctx.get_variable_types(),
8388 );
8389 let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8391 pipe_vars.contains(sym)
8392 } else {
8393 false
8394 };
8395 if is_local_pipe {
8396 writeln!(
8397 output,
8398 "{}{}_tx.send({}).await.expect(\"pipe send failed\");",
8399 indent_str, pipe_str, val_str
8400 )
8401 .unwrap();
8402 } else {
8403 writeln!(
8404 output,
8405 "{}{}.send({}).await.expect(\"pipe send failed\");",
8406 indent_str, pipe_str, val_str
8407 )
8408 .unwrap();
8409 }
8410 }
8411
8412 Stmt::ReceivePipe { var, pipe } => {
8413 let var_name = interner.resolve(*var);
8414 let pipe_str = codegen_expr_with_async(
8415 pipe,
8416 interner,
8417 synced_vars,
8418 async_functions,
8419 ctx.get_variable_types(),
8420 );
8421 let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8423 pipe_vars.contains(sym)
8424 } else {
8425 false
8426 };
8427 if is_local_pipe {
8428 writeln!(
8429 output,
8430 "{}let {} = {}_rx.recv().await.expect(\"pipe closed\");",
8431 indent_str, var_name, pipe_str
8432 )
8433 .unwrap();
8434 } else {
8435 writeln!(
8436 output,
8437 "{}let {} = {}.recv().await.expect(\"pipe closed\");",
8438 indent_str, var_name, pipe_str
8439 )
8440 .unwrap();
8441 }
8442 }
8443
8444 Stmt::TrySendPipe {
8445 value,
8446 pipe,
8447 result,
8448 } => {
8449 let val_str = codegen_expr_boxed_with_types_oracle(
8450 value,
8451 interner,
8452 synced_vars,
8453 boxed_fields,
8454 registry,
8455 async_functions,
8456 ctx.get_string_vars(),
8457 ctx.get_variable_types(),
8458 ctx.get_fast_div(),
8459 ctx.oracle(),
8460 );
8461 let pipe_str = codegen_expr_with_async(
8462 pipe,
8463 interner,
8464 synced_vars,
8465 async_functions,
8466 ctx.get_variable_types(),
8467 );
8468 let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8470 pipe_vars.contains(sym)
8471 } else {
8472 false
8473 };
8474 let suffix = if is_local_pipe { "_tx" } else { "" };
8475 if let Some(res) = result {
8476 let res_name = interner.resolve(*res);
8477 writeln!(
8478 output,
8479 "{}let {} = {}{}.try_send({}).is_ok();",
8480 indent_str, res_name, pipe_str, suffix, val_str
8481 )
8482 .unwrap();
8483 } else {
8484 writeln!(
8485 output,
8486 "{}let _ = {}{}.try_send({});",
8487 indent_str, pipe_str, suffix, val_str
8488 )
8489 .unwrap();
8490 }
8491 }
8492
8493 Stmt::TryReceivePipe { var, pipe } => {
8494 let var_name = interner.resolve(*var);
8495 let pipe_str = codegen_expr_with_async(
8496 pipe,
8497 interner,
8498 synced_vars,
8499 async_functions,
8500 ctx.get_variable_types(),
8501 );
8502 let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8504 pipe_vars.contains(sym)
8505 } else {
8506 false
8507 };
8508 let suffix = if is_local_pipe { "_rx" } else { "" };
8509 writeln!(
8510 output,
8511 "{}let {} = {}{}.try_recv().ok();",
8512 indent_str, var_name, pipe_str, suffix
8513 )
8514 .unwrap();
8515 }
8516
8517 Stmt::StopTask { handle } => {
8518 let handle_str = codegen_expr_with_async(
8519 handle,
8520 interner,
8521 synced_vars,
8522 async_functions,
8523 ctx.get_variable_types(),
8524 );
8525 writeln!(output, "{}{}.abort();", indent_str, handle_str).unwrap();
8526 }
8527
8528 Stmt::CloseChannel { channel } => {
8529 let chan_str = codegen_expr_with_async(
8530 channel,
8531 interner,
8532 synced_vars,
8533 async_functions,
8534 ctx.get_variable_types(),
8535 );
8536 let is_local_pipe = if let Expr::Identifier(sym) = channel {
8539 pipe_vars.contains(sym)
8540 } else {
8541 false
8542 };
8543 let suffix = if is_local_pipe { "_tx" } else { "" };
8544 writeln!(output, "{}{}{}.close();", indent_str, chan_str, suffix).unwrap();
8545 }
8546
8547 Stmt::AwaitTask { handle, result } => {
8548 let handle_str = codegen_expr_with_async(
8549 handle,
8550 interner,
8551 synced_vars,
8552 async_functions,
8553 ctx.get_variable_types(),
8554 );
8555 match result {
8558 Some(r) => {
8559 let r_name = interner.resolve(*r);
8560 writeln!(
8561 output,
8562 "{}let {} = {}.await.expect(\"task join failed\");",
8563 indent_str, r_name, handle_str
8564 )
8565 .unwrap();
8566 }
8567 None => {
8568 writeln!(output, "{}let _ = {}.await;", indent_str, handle_str).unwrap();
8569 }
8570 }
8571 }
8572
8573 Stmt::Select { branches } => {
8574 write_tokio_select(
8575 &mut output,
8576 branches,
8577 interner,
8578 indent,
8579 mutable_vars,
8580 ctx,
8581 lww_fields,
8582 mv_fields,
8583 synced_vars,
8584 var_caps,
8585 async_functions,
8586 pipe_vars,
8587 boxed_fields,
8588 registry,
8589 type_env,
8590 );
8591 }
8592
8593 Stmt::Give { object, recipient } => {
8594 let obj_str = codegen_expr_with_async(
8596 object,
8597 interner,
8598 synced_vars,
8599 async_functions,
8600 ctx.get_variable_types(),
8601 );
8602 let recv_str = recipient_path(
8603 recipient,
8604 interner,
8605 synced_vars,
8606 async_functions,
8607 ctx.get_variable_types(),
8608 );
8609 writeln!(output, "{}{}({});", indent_str, recv_str, obj_str).unwrap();
8610 }
8611
8612 Stmt::Show { object, recipient } => {
8613 return codegen_show_stmt(
8614 output,
8615 object,
8616 recipient,
8617 interner,
8618 ctx,
8619 synced_vars,
8620 async_functions,
8621 registry,
8622 &indent_str,
8623 &names,
8624 );
8625 }
8626
8627 Stmt::SetField {
8628 object,
8629 field,
8630 value,
8631 } => {
8632 let obj_str = codegen_expr_with_async(
8633 object,
8634 interner,
8635 synced_vars,
8636 async_functions,
8637 ctx.get_variable_types(),
8638 );
8639 let field_name = interner.resolve(*field);
8640 let value_str = codegen_expr_boxed_with_types_oracle(
8641 value,
8642 interner,
8643 synced_vars,
8644 boxed_fields,
8645 registry,
8646 async_functions,
8647 ctx.get_string_vars(),
8648 ctx.get_variable_types(),
8649 ctx.get_fast_div(),
8650 ctx.oracle(),
8651 );
8652 let value_str = stored_value(value, value_str, ctx.get_variable_types());
8653
8654 let is_lww = lww_fields.iter().any(|(_, f)| f == field_name);
8657 let is_mv = mv_fields.iter().any(|(_, f)| f == field_name);
8658 let field_name = escape_rust_ident(field_name);
8659 if is_lww {
8660 writeln!(output, "{}{}.{}.set({}, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_micros() as u64);", indent_str, obj_str, field_name, value_str).unwrap();
8662 } else if is_mv {
8663 writeln!(
8665 output,
8666 "{}{}.{}.set({});",
8667 indent_str, obj_str, field_name, value_str
8668 )
8669 .unwrap();
8670 } else {
8671 writeln!(
8672 output,
8673 "{}{}.{} = {};",
8674 indent_str, obj_str, field_name, value_str
8675 )
8676 .unwrap();
8677 }
8678 }
8679
8680 Stmt::StructDef { .. } => {
8681 }
8683
8684 Stmt::FunctionDef { .. } => {
8685 }
8687
8688 Stmt::Inspect { target, arms, .. } => {
8689 return codegen_inspect_stmt(
8690 output,
8691 target,
8692 arms,
8693 interner,
8694 indent,
8695 mutable_vars,
8696 ctx,
8697 lww_fields,
8698 mv_fields,
8699 synced_vars,
8700 var_caps,
8701 async_functions,
8702 pipe_vars,
8703 boxed_fields,
8704 registry,
8705 type_env,
8706 &indent_str,
8707 );
8708 }
8709
8710 Stmt::Push { value, collection } => {
8711 return codegen_push_stmt(
8712 output,
8713 value,
8714 collection,
8715 interner,
8716 ctx,
8717 synced_vars,
8718 async_functions,
8719 boxed_fields,
8720 registry,
8721 &indent_str,
8722 &names,
8723 );
8724 }
8725
8726 Stmt::Pop { collection, into } => {
8727 if let Expr::Identifier(coll_sym) = collection {
8728 if ctx
8729 .get_variable_types()
8730 .get(coll_sym)
8731 .is_some_and(|t| t == super::tower::VALUE)
8732 {
8733 let popped = format!(
8734 "logicaffeine_data::failure::answered({}.pop_value())",
8735 names.ident(*coll_sym)
8736 );
8737 match into {
8738 Some(var) => {
8739 writeln!(
8740 output,
8741 "{}let {}: {} = {};",
8742 indent_str,
8743 names.ident(*var),
8744 super::tower::VALUE,
8745 popped
8746 )
8747 .unwrap();
8748 ctx.register_variable_type(*var, super::tower::VALUE.to_string());
8749 }
8750 None => writeln!(output, "{}{};", indent_str, popped).unwrap(),
8751 }
8752 return output;
8753 }
8754 }
8755 let coll_str = codegen_expr_with_async(
8756 collection,
8757 interner,
8758 synced_vars,
8759 async_functions,
8760 ctx.get_variable_types(),
8761 );
8762 emit_cow(collection, ctx, &names, &indent_str, &mut output);
8764 match into {
8765 Some(var) => {
8766 let var_name = names.ident(*var);
8767 let rational = super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry });
8769 let typed = rational.as_ref().map(|t| format!(": {t}")).unwrap_or_default();
8770 writeln!(
8772 output,
8773 "{}let {}{} = {}.pop().expect(\"Pop from empty collection\");",
8774 indent_str, var_name, typed, coll_str
8775 )
8776 .unwrap();
8777 if let Some(item) = rational {
8778 ctx.register_variable_type(*var, item);
8779 }
8780 }
8781 None => {
8782 writeln!(output, "{}{}.pop();", indent_str, coll_str).unwrap();
8783 }
8784 }
8785 }
8786
8787 Stmt::Add { value, collection } => {
8788 let val_str = codegen_expr_boxed_with_types_oracle(
8789 value,
8790 interner,
8791 synced_vars,
8792 boxed_fields,
8793 registry,
8794 async_functions,
8795 ctx.get_string_vars(),
8796 ctx.get_variable_types(),
8797 ctx.get_fast_div(),
8798 ctx.oracle(),
8799 );
8800 let val_str = stored_value(value, val_str, ctx.get_variable_types());
8801 let val_str = value_taken_before_the_write(
8802 value,
8803 collection,
8804 val_str,
8805 ctx,
8806 &indent_str,
8807 &mut output,
8808 );
8809 let coll_str = codegen_expr_with_async(
8810 collection,
8811 interner,
8812 synced_vars,
8813 async_functions,
8814 ctx.get_variable_types(),
8815 );
8816 emit_cow(collection, ctx, &names, &indent_str, &mut output);
8819 writeln!(output, "{}{}.insert({});", indent_str, coll_str, val_str).unwrap();
8820 }
8821
8822 Stmt::Remove { value, collection } => {
8823 let val_str = codegen_expr_boxed_with_types_oracle(
8824 value,
8825 interner,
8826 synced_vars,
8827 boxed_fields,
8828 registry,
8829 async_functions,
8830 ctx.get_string_vars(),
8831 ctx.get_variable_types(),
8832 ctx.get_fast_div(),
8833 ctx.oracle(),
8834 );
8835 let val_str = value_taken_before_the_write(
8836 value,
8837 collection,
8838 val_str,
8839 ctx,
8840 &indent_str,
8841 &mut output,
8842 );
8843 let coll_str = codegen_expr_with_async(
8844 collection,
8845 interner,
8846 synced_vars,
8847 async_functions,
8848 ctx.get_variable_types(),
8849 );
8850 emit_cow(collection, ctx, &names, &indent_str, &mut output);
8852 let is_set = matches!(collection, Expr::Identifier(sym)
8856 if ctx.get_variable_types().get(sym).is_some_and(|t| t.starts_with("Set<") || t.starts_with("FxHashSet<")));
8857 let method = if is_set { "shift_remove" } else { "remove" };
8858 writeln!(
8859 output,
8860 "{}{}.{}(&{});",
8861 indent_str, coll_str, method, val_str
8862 )
8863 .unwrap();
8864 }
8865
8866 Stmt::SetIndex {
8867 collection,
8868 index,
8869 value,
8870 } => {
8871 return codegen_set_index_stmt(
8872 output,
8873 collection,
8874 index,
8875 value,
8876 interner,
8877 ctx,
8878 synced_vars,
8879 async_functions,
8880 boxed_fields,
8881 registry,
8882 &indent_str,
8883 &names,
8884 );
8885 }
8886
8887 Stmt::Zone {
8889 name,
8890 capacity,
8891 source_file,
8892 body,
8893 } => {
8894 return codegen_zone_stmt(
8895 output,
8896 name,
8897 capacity,
8898 source_file,
8899 body,
8900 interner,
8901 indent,
8902 mutable_vars,
8903 ctx,
8904 lww_fields,
8905 mv_fields,
8906 synced_vars,
8907 var_caps,
8908 async_functions,
8909 pipe_vars,
8910 boxed_fields,
8911 registry,
8912 type_env,
8913 &indent_str,
8914 );
8915 }
8916
8917 Stmt::Concurrent { tasks } => {
8921 return codegen_concurrent_stmt(
8922 output,
8923 tasks,
8924 interner,
8925 indent,
8926 mutable_vars,
8927 ctx,
8928 lww_fields,
8929 mv_fields,
8930 synced_vars,
8931 var_caps,
8932 async_functions,
8933 pipe_vars,
8934 boxed_fields,
8935 registry,
8936 type_env,
8937 &indent_str,
8938 );
8939 }
8940
8941 Stmt::Parallel { tasks } => {
8943 return codegen_parallel_stmt(
8944 output,
8945 tasks,
8946 interner,
8947 indent,
8948 mutable_vars,
8949 ctx,
8950 lww_fields,
8951 mv_fields,
8952 synced_vars,
8953 var_caps,
8954 async_functions,
8955 pipe_vars,
8956 boxed_fields,
8957 registry,
8958 type_env,
8959 &indent_str,
8960 );
8961 }
8962
8963 Stmt::ReadFrom { var, source } => {
8966 let var_name = interner.resolve(*var);
8967 match source {
8968 ReadSource::Console => {
8969 writeln!(
8970 output,
8971 "{}let {} = logicaffeine_system::io::read_line();",
8972 indent_str, var_name
8973 )
8974 .unwrap();
8975 }
8976 ReadSource::File(path_expr) => {
8977 let path_str = codegen_expr_with_async(
8978 path_expr,
8979 interner,
8980 synced_vars,
8981 async_functions,
8982 ctx.get_variable_types(),
8983 );
8984 writeln!(
8986 output,
8987 "{}let {} = vfs.read_to_string(&{}).await.expect(\"Failed to read file\");",
8988 indent_str, var_name, path_str
8989 )
8990 .unwrap();
8991 }
8992 }
8993 }
8994
8995 Stmt::WriteFile { content, path } => {
8998 let content_str = codegen_expr_with_async(
8999 content,
9000 interner,
9001 synced_vars,
9002 async_functions,
9003 ctx.get_variable_types(),
9004 );
9005 let path_str = codegen_expr_with_async(
9006 path,
9007 interner,
9008 synced_vars,
9009 async_functions,
9010 ctx.get_variable_types(),
9011 );
9012 writeln!(
9014 output,
9015 "{}vfs.write(&{}, {}.as_bytes()).await.expect(\"Failed to write file\");",
9016 indent_str, path_str, content_str
9017 )
9018 .unwrap();
9019 }
9020
9021 Stmt::Spawn { agent_type, name } => {
9023 let type_name = interner.resolve(*agent_type);
9024 let agent_name = interner.resolve(*name);
9025 writeln!(
9027 output,
9028 "{}let {} = tokio::spawn(async move {{ /* {} agent loop */ }});",
9029 indent_str, agent_name, type_name
9030 )
9031 .unwrap();
9032 }
9033
9034 Stmt::SendMessage {
9036 message,
9037 destination,
9038 ..
9039 } => {
9040 let msg_str = codegen_expr_with_async(
9041 message,
9042 interner,
9043 synced_vars,
9044 async_functions,
9045 ctx.get_variable_types(),
9046 );
9047 let dest_str = codegen_expr_with_async(
9048 destination,
9049 interner,
9050 synced_vars,
9051 async_functions,
9052 ctx.get_variable_types(),
9053 );
9054 let to_peer = matches!(destination, Expr::Identifier(sym)
9056 if ctx.get_variable_types().get(sym).is_some_and(|t| t == PEER_AGENT_TYPE));
9057 if to_peer {
9058 writeln!(
9059 output,
9060 "{}logicaffeine_system::network::send(&{}, &{}).await.expect(\"Failed to send message\");",
9061 indent_str, dest_str, msg_str
9062 ).unwrap();
9063 } else {
9064 writeln!(
9065 output,
9066 "{}{}.send({}).await.expect(\"Failed to send message\");",
9067 indent_str, dest_str, msg_str
9068 )
9069 .unwrap();
9070 }
9071 }
9072
9073 Stmt::StreamMessage { .. } => {
9076 writeln!(
9077 output,
9078 "{}// Stream: interpreter-only (not yet lowered to AOT)",
9079 indent_str
9080 )
9081 .unwrap();
9082 }
9083
9084 Stmt::AwaitMessage {
9087 source,
9088 into,
9089 view: _,
9090 stream: _,
9091 } => {
9092 let src_str = codegen_expr_with_async(
9093 source,
9094 interner,
9095 synced_vars,
9096 async_functions,
9097 ctx.get_variable_types(),
9098 );
9099 let var_name = interner.resolve(*into);
9100 writeln!(
9101 output,
9102 "{}let {} = {}.recv().await.expect(\"Failed to receive message\");",
9103 indent_str, var_name, src_str
9104 )
9105 .unwrap();
9106 }
9107
9108 Stmt::MergeCrdt { source, target } => {
9110 let src_str = codegen_expr_with_async(
9111 source,
9112 interner,
9113 synced_vars,
9114 async_functions,
9115 ctx.get_variable_types(),
9116 );
9117 let tgt_str = codegen_expr_with_async(
9118 target,
9119 interner,
9120 synced_vars,
9121 async_functions,
9122 ctx.get_variable_types(),
9123 );
9124 write_crdt_fold(
9125 &mut output,
9126 &indent_str,
9127 "merge",
9128 &tgt_str,
9129 &src_str,
9130 source,
9131 target,
9132 );
9133 }
9134
9135 Stmt::JoinCrdt { source, target } => {
9139 let src_str = codegen_expr_with_async(
9140 source,
9141 interner,
9142 synced_vars,
9143 async_functions,
9144 ctx.get_variable_types(),
9145 );
9146 let tgt_str = codegen_expr_with_async(
9147 target,
9148 interner,
9149 synced_vars,
9150 async_functions,
9151 ctx.get_variable_types(),
9152 );
9153 write_crdt_fold(
9154 &mut output,
9155 &indent_str,
9156 "join",
9157 &tgt_str,
9158 &src_str,
9159 source,
9160 target,
9161 );
9162 }
9163
9164 Stmt::IncreaseCrdt {
9167 object,
9168 field,
9169 amount,
9170 } => {
9171 let field_name = escape_rust_ident(interner.resolve(*field));
9172 let amount_str = codegen_expr_with_async(
9173 amount,
9174 interner,
9175 synced_vars,
9176 async_functions,
9177 ctx.get_variable_types(),
9178 );
9179
9180 let root_sym = get_root_identifier(object);
9182 if let Some(sym) = root_sym {
9183 if synced_vars.contains(&sym) {
9184 let obj_name = interner.resolve(sym);
9186 writeln!(
9187 output,
9188 "{}{}.mutate(|inner| inner.{}.increment({} as u64)).await;",
9189 indent_str, obj_name, field_name, amount_str
9190 )
9191 .unwrap();
9192 return output;
9193 }
9194 }
9195
9196 let obj_str = codegen_expr_with_async(
9198 object,
9199 interner,
9200 synced_vars,
9201 async_functions,
9202 ctx.get_variable_types(),
9203 );
9204 writeln!(
9205 output,
9206 "{}{}.{}.increment({} as u64);",
9207 indent_str, obj_str, field_name, amount_str
9208 )
9209 .unwrap();
9210 }
9211
9212 Stmt::DecreaseCrdt {
9214 object,
9215 field,
9216 amount,
9217 } => {
9218 let field_name = escape_rust_ident(interner.resolve(*field));
9219 let amount_str = codegen_expr_with_async(
9220 amount,
9221 interner,
9222 synced_vars,
9223 async_functions,
9224 ctx.get_variable_types(),
9225 );
9226
9227 let root_sym = get_root_identifier(object);
9229 if let Some(sym) = root_sym {
9230 if synced_vars.contains(&sym) {
9231 let obj_name = interner.resolve(sym);
9233 writeln!(
9234 output,
9235 "{}{}.mutate(|inner| inner.{}.decrement({} as u64)).await;",
9236 indent_str, obj_name, field_name, amount_str
9237 )
9238 .unwrap();
9239 return output;
9240 }
9241 }
9242
9243 let obj_str = codegen_expr_with_async(
9245 object,
9246 interner,
9247 synced_vars,
9248 async_functions,
9249 ctx.get_variable_types(),
9250 );
9251 writeln!(
9252 output,
9253 "{}{}.{}.decrement({} as u64);",
9254 indent_str, obj_str, field_name, amount_str
9255 )
9256 .unwrap();
9257 }
9258
9259 Stmt::AppendToSequence { sequence, value } => {
9261 let seq_str = codegen_expr_with_async(
9262 sequence,
9263 interner,
9264 synced_vars,
9265 async_functions,
9266 ctx.get_variable_types(),
9267 );
9268 let val_str = codegen_expr_boxed_with_types_oracle(
9269 value,
9270 interner,
9271 synced_vars,
9272 boxed_fields,
9273 registry,
9274 async_functions,
9275 ctx.get_string_vars(),
9276 ctx.get_variable_types(),
9277 ctx.get_fast_div(),
9278 ctx.oracle(),
9279 );
9280 writeln!(output, "{}{}.append({});", indent_str, seq_str, val_str).unwrap();
9281 }
9282
9283 Stmt::ResolveConflict {
9285 object,
9286 field,
9287 value,
9288 } => {
9289 let field_name = escape_rust_ident(interner.resolve(*field));
9290 let val_str = codegen_expr_boxed_with_types_oracle(
9291 value,
9292 interner,
9293 synced_vars,
9294 boxed_fields,
9295 registry,
9296 async_functions,
9297 ctx.get_string_vars(),
9298 ctx.get_variable_types(),
9299 ctx.get_fast_div(),
9300 ctx.oracle(),
9301 );
9302 let obj_str = codegen_expr_with_async(
9303 object,
9304 interner,
9305 synced_vars,
9306 async_functions,
9307 ctx.get_variable_types(),
9308 );
9309 writeln!(
9310 output,
9311 "{}{}.{}.resolve({});",
9312 indent_str, obj_str, field_name, val_str
9313 )
9314 .unwrap();
9315 }
9316
9317 Stmt::Escape { code, .. } => {
9319 let raw_code = interner.resolve(*code);
9320 writeln!(
9322 output,
9323 "{}logicaffeine_system::io::flush_stdout();",
9324 indent_str
9325 )
9326 .unwrap();
9327 write!(output, "{}{{\n", indent_str).unwrap();
9328 for line in raw_code.lines() {
9329 write!(output, "{} {}\n", indent_str, line).unwrap();
9330 }
9331 write!(output, "{}}}\n", indent_str).unwrap();
9332 }
9333
9334 Stmt::Require { .. } => {}
9336
9337 Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {}
9341
9342 Stmt::Site(_) => {}
9349 }
9350
9351 output
9352}
9353
9354fn try_emit_sentinel_break<'a>(
9362 stmt: &Stmt<'a>,
9363 counter_sym: Symbol,
9364 limit_expr: &Expr<'a>,
9365 interner: &Interner,
9366 indent: usize,
9367 mutable_vars: &HashSet<Symbol>,
9368 ctx: &mut RefinementContext<'a>,
9369 lww_fields: &HashSet<(String, String)>,
9370 mv_fields: &HashSet<(String, String)>,
9371 synced_vars: &mut HashSet<Symbol>,
9372 var_caps: &HashMap<Symbol, VariableCapabilities>,
9373 async_functions: &HashSet<Symbol>,
9374 pipe_vars: &HashSet<Symbol>,
9375 boxed_fields: &HashSet<(String, String, String)>,
9376 registry: &TypeRegistry,
9377 type_env: &crate::analysis::types::TypeEnv,
9378) -> Option<String> {
9379 let (if_cond, then_block, else_block) = match stmt {
9381 Stmt::If {
9382 cond,
9383 then_block,
9384 else_block,
9385 } => (cond, then_block, else_block),
9386 _ => return None,
9387 };
9388
9389 if else_block.is_some() {
9390 return None;
9391 }
9392
9393 if then_block.is_empty() {
9394 return None;
9395 }
9396
9397 let last = &then_block[then_block.len() - 1];
9399 match last {
9400 Stmt::Set { target, value, .. } => {
9401 if *target != counter_sym || !exprs_equal(value, limit_expr) {
9402 return None;
9403 }
9404 }
9405 _ => return None,
9406 }
9407
9408 let indent_str = " ".repeat(indent);
9410 let var_types = ctx.get_variable_types();
9411 let cond_str =
9412 codegen_expr_with_async(if_cond, interner, synced_vars, async_functions, var_types);
9413 let mut output = String::new();
9414 writeln!(output, "{}if {} {{", indent_str, cond_str).unwrap();
9415
9416 for s in &then_block[..then_block.len() - 1] {
9418 output.push_str(&codegen_stmt(
9419 s,
9420 interner,
9421 indent + 1,
9422 mutable_vars,
9423 ctx,
9424 lww_fields,
9425 mv_fields,
9426 synced_vars,
9427 var_caps,
9428 async_functions,
9429 pipe_vars,
9430 boxed_fields,
9431 registry,
9432 type_env,
9433 ));
9434 }
9435
9436 writeln!(output, "{} break;", indent_str).unwrap();
9438 writeln!(output, "{}}}", indent_str).unwrap();
9439
9440 Some(output)
9441}
9442
9443fn write_crdt_fold(
9448 output: &mut String,
9449 indent: &str,
9450 method: &str,
9451 tgt: &str,
9452 src: &str,
9453 source: &Expr,
9454 target: &Expr,
9455) {
9456 let shares_root = matches!(
9457 (get_root_identifier(source), get_root_identifier(target)),
9458 (Some(a), Some(b)) if a == b
9459 );
9460 if shares_root {
9461 writeln!(
9462 output,
9463 "{indent}{{ let __fold_src = ({src}).clone(); {tgt}.{method}(&__fold_src); }}"
9464 )
9465 .unwrap();
9466 } else {
9467 writeln!(output, "{indent}{tgt}.{method}(&{src});").unwrap();
9468 }
9469}
9470
9471pub(crate) fn get_root_identifier(expr: &Expr) -> Option<Symbol> {
9474 match expr {
9475 Expr::Identifier(sym) => Some(*sym),
9476 Expr::FieldAccess { object, .. } => get_root_identifier(object),
9477 _ => None,
9478 }
9479}
9480
9481pub(crate) fn extract_length_expr_syms(expr: &Expr) -> Vec<Symbol> {
9484 let mut out = Vec::new();
9485 collect_length_syms_from_expr(expr, &mut out);
9486 out
9487}
9488
9489fn collect_length_syms_from_expr(expr: &Expr, out: &mut Vec<Symbol>) {
9490 match expr {
9491 Expr::Length { collection } => {
9492 if let Expr::Identifier(sym) = collection {
9493 out.push(*sym);
9494 }
9495 }
9496 Expr::BinaryOp { left, right, .. } => {
9497 collect_length_syms_from_expr(left, out);
9498 collect_length_syms_from_expr(right, out);
9499 }
9500 Expr::Not { operand } => collect_length_syms_from_expr(operand, out),
9501 Expr::Index { collection, index } => {
9502 collect_length_syms_from_expr(collection, out);
9503 collect_length_syms_from_expr(index, out);
9504 }
9505 Expr::Call { args, .. } => {
9506 for arg in args.iter() {
9507 collect_length_syms_from_expr(arg, out);
9508 }
9509 }
9510 _ => {}
9511 }
9512}
9513
9514pub(crate) fn collect_length_syms_from_stmts(stmts: &[Stmt], out: &mut Vec<Symbol>) {
9516 for stmt in stmts {
9517 collect_length_syms_from_stmt(stmt, out);
9518 }
9519}
9520
9521fn collect_length_syms_from_stmt(stmt: &Stmt, out: &mut Vec<Symbol>) {
9522 match stmt {
9523 Stmt::Let { value, .. } => collect_length_syms_from_expr(value, out),
9524 Stmt::Set { value, .. } => collect_length_syms_from_expr(value, out),
9525 Stmt::Show { object, .. } => collect_length_syms_from_expr(object, out),
9526 Stmt::Push { value, collection } => {
9527 collect_length_syms_from_expr(value, out);
9528 collect_length_syms_from_expr(collection, out);
9529 }
9530 Stmt::SetIndex {
9531 collection,
9532 index,
9533 value,
9534 } => {
9535 collect_length_syms_from_expr(collection, out);
9536 collect_length_syms_from_expr(index, out);
9537 collect_length_syms_from_expr(value, out);
9538 }
9539 Stmt::If {
9540 cond,
9541 then_block,
9542 else_block,
9543 } => {
9544 collect_length_syms_from_expr(cond, out);
9545 collect_length_syms_from_stmts(then_block, out);
9546 if let Some(else_stmts) = else_block {
9547 collect_length_syms_from_stmts(else_stmts, out);
9548 }
9549 }
9550 Stmt::While { cond, body, .. } => {
9551 collect_length_syms_from_expr(cond, out);
9552 collect_length_syms_from_stmts(body, out);
9553 }
9554 Stmt::Repeat { body, .. } => {
9555 collect_length_syms_from_stmts(body, out);
9556 }
9557 Stmt::Return { value } => {
9558 if let Some(v) = value {
9559 collect_length_syms_from_expr(v, out);
9560 }
9561 }
9562 Stmt::Call { args, .. } => {
9563 for arg in args.iter() {
9564 collect_length_syms_from_expr(arg, out);
9565 }
9566 }
9567 _ => {}
9568 }
9569}
9570
9571pub(crate) fn is_copy_type(ty: &str) -> bool {
9574 crate::analysis::types::LogosType::from_rust_type_str(ty).is_copy()
9575}
9576
9577pub(super) fn truthy_cond_wrap(
9582 cond: &Expr,
9583 cond_str: String,
9584 interner: &Interner,
9585 variable_types: &HashMap<Symbol, String>,
9586) -> String {
9587 if super::tower::is_tower_expr(cond, variable_types, interner) {
9588 return format!("logos_truthy(&({}))", cond_str);
9589 }
9590 if matches!(
9591 super::types::infer_logos_type(cond, interner, variable_types),
9592 crate::analysis::types::LogosType::Bool
9593 ) {
9594 cond_str
9595 } else {
9596 format!("logos_truthy(&({}))", cond_str)
9597 }
9598}
9599
9600pub(crate) fn has_copy_element_type(vec_type: &str) -> bool {
9603 crate::analysis::types::LogosType::from_rust_type_str(vec_type)
9604 .element_type()
9605 .map_or(false, |e| e.is_copy())
9606}
9607
9608pub(crate) fn has_copy_value_type(map_type: &str) -> bool {
9611 crate::analysis::types::LogosType::from_rust_type_str(map_type)
9612 .value_type()
9613 .map_or(false, |v| v.is_copy())
9614}
9615
9616fn try_emit_parallel_reduction<'a>(
9628 var_sym: Symbol,
9629 pattern_str: &str,
9630 iter_str: &str,
9631 iterable: &'a Expr<'a>,
9632 body: &'a [Stmt<'a>],
9633 interner: &Interner,
9634 indent: usize,
9635 ctx: &RefinementContext<'a>,
9636 synced_vars: &HashSet<Symbol>,
9637 async_functions: &HashSet<Symbol>,
9638) -> Option<String> {
9639 if body.len() != 1 {
9641 return None;
9642 }
9643
9644 let (acc_sym, op, increment_expr) = match &body[0] {
9645 Stmt::Set { target, value } => {
9646 if let Expr::BinaryOp { op, left, right } = value {
9647 match op {
9648 BinaryOpKind::Add => {
9649 if let Expr::Identifier(lhs) = left {
9651 if *lhs == *target {
9652 Some((*target, BinaryOpKind::Add, *right))
9653 } else {
9654 None
9655 }
9656 } else if let Expr::Identifier(rhs) = right {
9657 if *rhs == *target {
9658 Some((*target, BinaryOpKind::Add, *left))
9659 } else {
9660 None
9661 }
9662 } else {
9663 None
9664 }
9665 }
9666 _ => None,
9667 }
9668 } else {
9669 None
9670 }
9671 }
9672 _ => None,
9673 }?;
9674
9675 if !expr_is_pure_of(increment_expr, var_sym) {
9677 return None;
9678 }
9679
9680 let is_vec_i64 = if let Expr::Identifier(coll_sym) = iterable {
9682 ctx.get_variable_types()
9683 .get(coll_sym)
9684 .map(|t| {
9685 let t = t.split("|__hl:").next().unwrap_or(t.as_str());
9686 (t.starts_with("LogosSeq<") || t.starts_with("Vec<") || t.starts_with("&["))
9687 && has_copy_element_type(t)
9688 })
9689 .unwrap_or(false)
9690 } else {
9691 false
9692 };
9693
9694 if !is_vec_i64 {
9695 return None;
9696 }
9697
9698 let indent_str = " ".repeat(indent);
9699 let acc_name = interner.resolve(acc_sym);
9700
9701 let acc_ty = ctx
9710 .get_variable_types()
9711 .get(&acc_sym)
9712 .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
9713 .unwrap_or("i64");
9714 let sum_ty = match acc_ty {
9715 "i64" | "u64" | "i32" | "u32" | "usize" | "isize" => acc_ty,
9716 _ => return None,
9717 };
9718
9719 let incr_code = codegen_expr_with_async(
9721 increment_expr,
9722 interner,
9723 synced_vars,
9724 async_functions,
9725 ctx.get_variable_types(),
9726 );
9727
9728 let needs_map = !matches!(increment_expr, Expr::Identifier(s) if *s == var_sym);
9730
9731 let mut out = String::new();
9732
9733 let (borrow_expr, len_expr) = if let Expr::Identifier(coll_sym) = iterable {
9737 let ty = ctx
9738 .get_variable_types()
9739 .get(coll_sym)
9740 .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()));
9741 if matches!(ty, Some(t) if t.starts_with("LogosSeq")) {
9742 (
9743 format!("{}.borrow()", iter_str),
9744 format!("{}.len()", iter_str),
9745 )
9746 } else {
9747 (iter_str.to_string(), format!("{}.len()", iter_str))
9748 }
9749 } else {
9750 (
9751 format!("{}.borrow()", iter_str),
9752 format!("{}.len()", iter_str),
9753 )
9754 };
9755 writeln!(out, "{}if {} >= 10000 {{", indent_str, len_expr).unwrap();
9756 writeln!(out, "{} use rayon::prelude::*;", indent_str).unwrap();
9757 writeln!(out, "{} let __par_ref = {};", indent_str, borrow_expr).unwrap();
9758 if needs_map {
9759 writeln!(
9760 out,
9761 "{} {} += __par_ref.par_iter().copied().map(|{}| {}).sum::<{}>();",
9762 indent_str, acc_name, pattern_str, incr_code, sum_ty
9763 )
9764 .unwrap();
9765 } else {
9766 writeln!(
9767 out,
9768 "{} {} += __par_ref.par_iter().copied().sum::<{}>();",
9769 indent_str, acc_name, sum_ty
9770 )
9771 .unwrap();
9772 }
9773 writeln!(out, "{}}} else {{", indent_str).unwrap();
9774 writeln!(
9775 out,
9776 "{} for {} in {}.to_vec() {{",
9777 indent_str, pattern_str, iter_str
9778 )
9779 .unwrap();
9780
9781 match op {
9782 BinaryOpKind::Add => {
9783 writeln!(out, "{} {} += {};", indent_str, acc_name, incr_code).unwrap();
9784 }
9785 _ => {
9786 writeln!(
9787 out,
9788 "{} {} = {} {:?} {};",
9789 indent_str, acc_name, acc_name, op, incr_code
9790 )
9791 .unwrap();
9792 }
9793 }
9794 writeln!(out, "{} }}", indent_str).unwrap();
9795 writeln!(out, "{}}}", indent_str).unwrap();
9796
9797 Some(out)
9798}
9799
9800fn expr_is_pure_of(expr: &Expr, allowed_sym: Symbol) -> bool {
9802 match expr {
9803 Expr::Identifier(s) => *s == allowed_sym,
9804 Expr::Literal(_) => true,
9805 Expr::BinaryOp { left, right, .. } => {
9806 expr_is_pure_of(left, allowed_sym) && expr_is_pure_of(right, allowed_sym)
9807 }
9808 Expr::Not { operand } => expr_is_pure_of(operand, allowed_sym),
9809 _ => false,
9810 }
9811}
9812
9813#[cfg(test)]
9814#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen/stmt/tests.rs"]
9815mod tests;