1use std::collections::{HashMap, HashSet};
2
3use crate::analysis::registry::{FieldType, TypeDef, TypeRegistry};
4use crate::ast::stmt::{Expr, Literal, ReadSource, Stmt, TypeExpr};
5use crate::intern::{Interner, Symbol};
6
7use super::field_is_boxed;
8use super::types::codegen_type_expr;
9
10pub(super) fn is_result_type(ty: &TypeExpr, interner: &Interner) -> bool {
11 if let TypeExpr::Generic { base, .. } = ty {
12 interner.resolve(*base) == "Result"
13 } else {
14 false
15 }
16}
17
18pub(super) fn serves(stmts: &[Stmt]) -> bool {
20 let mut found = false;
21 logicaffeine_language::ast_depth::for_each_node(stmts, |node| {
22 if let logicaffeine_language::ast_depth::Visited::Stmt(Stmt::Serve { .. }) = node {
23 found = true;
24 }
25 });
26 found
27}
28
29pub(super) fn requires_async(stmts: &[Stmt]) -> bool {
32 stmts.iter().any(|s| requires_async_stmt(s))
33}
34
35pub(super) fn requires_async_stmt(stmt: &Stmt) -> bool {
36 match stmt {
37 Stmt::Concurrent { tasks: _ } => true,
39 Stmt::Listen { .. } => true,
41 Stmt::ConnectTo { .. } => true,
42 Stmt::Serve { .. } => true,
44 Stmt::Sleep { .. } => true,
45 Stmt::Sync { .. } => true,
47 Stmt::Mount { .. } => true,
49 Stmt::ReadFrom {
51 source: ReadSource::File(_),
52 ..
53 } => true,
54 Stmt::WriteFile { .. } => true,
55 Stmt::LaunchTask { .. } => true,
57 Stmt::LaunchTaskWithHandle { .. } => true,
58 Stmt::SendPipe { .. } => true,
59 Stmt::ReceivePipe { .. } => true,
60 Stmt::Select { .. } => true,
61 Stmt::AwaitTask { .. } => true,
62 Stmt::CreatePipe { .. }
64 | Stmt::TrySendPipe { .. }
65 | Stmt::TryReceivePipe { .. }
66 | Stmt::StopTask { .. }
67 | Stmt::CloseChannel { .. } => super::deterministic_replay_enabled(),
68 Stmt::If {
72 then_block,
73 else_block,
74 ..
75 } => {
76 then_block.iter().any(|s| requires_async_stmt(s))
77 || else_block.map_or(false, |b| b.iter().any(|s| requires_async_stmt(s)))
78 }
79 Stmt::While { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
80 Stmt::Repeat { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
81 Stmt::Zone { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
82 Stmt::Parallel { tasks } => tasks.iter().any(|s| requires_async_stmt(s)),
83 Stmt::FunctionDef { body, .. } => body.iter().any(|s| requires_async_stmt(s)),
84 Stmt::Inspect { arms, .. } => arms
86 .iter()
87 .any(|arm| arm.body.iter().any(|s| requires_async_stmt(s))),
88 _ => false,
89 }
90}
91
92pub(super) fn requires_vfs(stmts: &[Stmt]) -> bool {
95 stmts.iter().any(|s| requires_vfs_stmt(s))
96}
97
98pub(super) fn requires_vfs_stmt(stmt: &Stmt) -> bool {
99 match stmt {
100 Stmt::Mount { .. } => true,
102 Stmt::ReadFrom {
104 source: ReadSource::File(_),
105 ..
106 } => true,
107 Stmt::WriteFile { .. } => true,
108 Stmt::If {
110 then_block,
111 else_block,
112 ..
113 } => {
114 then_block.iter().any(|s| requires_vfs_stmt(s))
115 || else_block.map_or(false, |b| b.iter().any(|s| requires_vfs_stmt(s)))
116 }
117 Stmt::While { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
118 Stmt::Repeat { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
119 Stmt::Zone { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
120 Stmt::Concurrent { tasks } => tasks.iter().any(|s| requires_vfs_stmt(s)),
121 Stmt::Parallel { tasks } => tasks.iter().any(|s| requires_vfs_stmt(s)),
122 Stmt::FunctionDef { body, .. } => body.iter().any(|s| requires_vfs_stmt(s)),
123 _ => false,
124 }
125}
126
127pub(super) fn collect_mutable_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
130 let mut targets = HashSet::new();
131 for stmt in stmts {
132 collect_mutable_vars_stmt(stmt, &mut targets);
133 }
134 targets
135}
136
137pub(super) fn collect_mutable_vars_stmt(stmt: &Stmt, targets: &mut HashSet<Symbol>) {
138 collect_written_vars_stmt(stmt, targets);
139 collect_lent_vars(std::slice::from_ref(stmt), targets);
140}
141
142fn collect_lent_vars(stmts: &[Stmt], targets: &mut HashSet<Symbol>) {
146 crate::analysis::callgraph::for_each_call_site(stmts, &mut |function, args| {
147 for at in crate::analysis::callgraph::lent_positions(function) {
148 if let Some(Expr::Identifier(sym)) = args.get(at) {
149 targets.insert(*sym);
150 }
151 }
152 });
153}
154
155fn collect_written_vars_stmt(stmt: &Stmt, targets: &mut HashSet<Symbol>) {
159 let writes = crate::optimize::WriteSet::of_stmt(stmt);
160 targets.extend(writes.assigned().iter().copied());
161 targets.extend(writes.mutated().iter().copied());
162}
163
164pub(super) fn collect_single_char_text_vars(
176 stmts: &[Stmt],
177 interner: &Interner,
178) -> HashSet<Symbol> {
179 let mut candidates: HashSet<Symbol> = HashSet::new();
180 let mut disqualified: HashSet<Symbol> = HashSet::new();
181
182 scan_single_char_candidates(stmts, interner, &mut candidates, &mut disqualified);
185
186 for sym in &disqualified {
188 candidates.remove(sym);
189 }
190
191 let mut usage_disqualified: HashSet<Symbol> = HashSet::new();
193 check_single_char_usage(stmts, &candidates, &mut usage_disqualified);
194
195 for sym in &usage_disqualified {
196 candidates.remove(sym);
197 }
198
199 crate::optimize::SwapClasses::of(stmts, interner).close_set(&mut candidates, interner);
201 candidates
202}
203
204fn is_single_char_text_literal<'a>(expr: &Expr<'a>, interner: &Interner) -> bool {
205 if let Expr::Literal(crate::ast::stmt::Literal::Text(sym)) = expr {
206 let text = interner.resolve(*sym);
207 text.len() == 1 && text.is_ascii()
208 } else {
209 false
210 }
211}
212
213fn scan_single_char_candidates(
214 stmts: &[Stmt],
215 interner: &Interner,
216 candidates: &mut HashSet<Symbol>,
217 disqualified: &mut HashSet<Symbol>,
218) {
219 for stmt in stmts {
220 match stmt {
221 Stmt::Let {
222 var,
223 value,
224 mutable,
225 ..
226 } => {
227 if *mutable && is_single_char_text_literal(value, interner) {
228 candidates.insert(*var);
229 }
230 }
232 Stmt::Set { target, value } => {
233 if candidates.contains(target) || !disqualified.contains(target) {
234 if !is_single_char_text_literal(value, interner) {
235 disqualified.insert(*target);
237 }
238 }
239 }
240 Stmt::If {
241 then_block,
242 else_block,
243 ..
244 } => {
245 scan_single_char_candidates(then_block, interner, candidates, disqualified);
246 if let Some(eb) = else_block {
247 scan_single_char_candidates(eb, interner, candidates, disqualified);
248 }
249 }
250 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
251 scan_single_char_candidates(body, interner, candidates, disqualified);
252 }
253 Stmt::FunctionDef { body, .. } => {
254 scan_single_char_candidates(body, interner, candidates, disqualified);
255 }
256 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
257 scan_single_char_candidates(tasks, interner, candidates, disqualified);
258 }
259 _ => {}
260 }
261 }
262}
263
264fn check_single_char_usage(
275 stmts: &[Stmt],
276 candidates: &HashSet<Symbol>,
277 disqualified: &mut HashSet<Symbol>,
278) {
279 for stmt in stmts {
280 match stmt {
281 Stmt::Set { target, value } => {
282 if !candidates.contains(target) {
286 check_expr_usage(value, candidates, disqualified, true);
289 }
290 }
291 Stmt::Show { object, .. } => {
292 if !matches!(object, Expr::Identifier(_)) {
297 check_expr_usage_strict(object, candidates, disqualified);
298 }
299 }
300 Stmt::Let { value, .. } => {
301 check_expr_usage_strict(value, candidates, disqualified);
304 }
305 Stmt::Return { value: Some(v) } => {
306 check_expr_usage_strict(v, candidates, disqualified);
307 }
308 Stmt::Call { args, .. } => {
309 for a in args.iter() {
310 check_expr_usage_strict(a, candidates, disqualified);
311 }
312 }
313 Stmt::Push { value, .. } => {
314 check_expr_usage_strict(value, candidates, disqualified);
316 }
317 Stmt::If {
318 cond: _,
319 then_block,
320 else_block,
321 } => {
322 check_single_char_usage(then_block, candidates, disqualified);
324 if let Some(eb) = else_block {
325 check_single_char_usage(eb, candidates, disqualified);
326 }
327 }
328 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
329 check_single_char_usage(body, candidates, disqualified);
330 }
331 Stmt::FunctionDef { body, .. } => {
332 check_single_char_usage(body, candidates, disqualified);
333 }
334 _ => {}
335 }
336 }
337}
338
339fn check_expr_usage(
343 expr: &Expr,
344 candidates: &HashSet<Symbol>,
345 disqualified: &mut HashSet<Symbol>,
346 is_self_append: bool,
347) {
348 match expr {
349 Expr::BinaryOp {
350 op: crate::ast::stmt::BinaryOpKind::Add,
351 left,
352 right,
353 } if is_self_append => {
354 check_expr_usage(left, candidates, disqualified, true);
356 if !matches!(right, Expr::Identifier(sym) if candidates.contains(sym)) {
358 check_expr_usage(right, candidates, disqualified, false);
359 }
360 }
361 Expr::Identifier(sym) if !is_self_append => {
362 if candidates.contains(sym) {
364 disqualified.insert(*sym);
365 }
366 }
367 Expr::InterpolatedString(parts) => {
369 for part in parts {
370 if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
371 check_expr_usage_strict(value, candidates, disqualified);
372 }
373 }
374 }
375 _ => {}
376 }
377}
378
379fn check_expr_usage_strict(
381 expr: &Expr,
382 candidates: &HashSet<Symbol>,
383 disqualified: &mut HashSet<Symbol>,
384) {
385 match expr {
386 Expr::Identifier(sym) => {
387 if candidates.contains(sym) {
388 disqualified.insert(*sym);
389 }
390 }
391 Expr::BinaryOp { left, right, .. } => {
392 check_expr_usage_strict(left, candidates, disqualified);
393 check_expr_usage_strict(right, candidates, disqualified);
394 }
395 Expr::Call { args, .. } => {
396 for a in args.iter() {
397 check_expr_usage_strict(a, candidates, disqualified);
398 }
399 }
400 Expr::Not { operand } => check_expr_usage_strict(operand, candidates, disqualified),
401 Expr::Index { collection, index } => {
402 check_expr_usage_strict(collection, candidates, disqualified);
403 check_expr_usage_strict(index, candidates, disqualified);
404 }
405 Expr::Length { collection } => {
406 check_expr_usage_strict(collection, candidates, disqualified)
407 }
408 Expr::List(items) => {
409 for item in items.iter() {
410 check_expr_usage_strict(item, candidates, disqualified);
411 }
412 }
413 Expr::InterpolatedString(parts) => {
415 for part in parts {
416 if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
417 check_expr_usage_strict(value, candidates, disqualified);
418 }
419 }
420 }
421 _ => {}
422 }
423}
424
425pub(super) fn collect_crdt_register_fields(
426 registry: &TypeRegistry,
427 interner: &Interner,
428) -> (HashSet<(String, String)>, HashSet<(String, String)>) {
429 let mut lww_fields = HashSet::new();
430 let mut mv_fields = HashSet::new();
431 for (type_sym, def) in registry.iter_types() {
432 if let TypeDef::Struct { fields, .. } = def {
433 let type_name = interner.resolve(*type_sym).to_string();
434 for field in fields {
435 if let FieldType::Generic { base, .. } = &field.ty {
436 let base_name = interner.resolve(*base);
437 let field_name = interner.resolve(field.name).to_string();
438 if base_name == "LastWriteWins" {
439 lww_fields.insert((type_name.clone(), field_name));
440 } else if base_name == "Divergent" || base_name == "MVRegister" {
441 mv_fields.insert((type_name.clone(), field_name));
442 }
443 }
444 }
445 }
446 }
447 (lww_fields, mv_fields)
448}
449
450pub(super) fn collect_boxed_fields(
452 registry: &TypeRegistry,
453 interner: &Interner,
454) -> HashSet<(String, String, String)> {
455 let mut boxed_fields = HashSet::new();
456 for (type_sym, def) in registry.iter_types() {
457 if let TypeDef::Enum { variants, .. } = def {
458 let enum_name = interner.resolve(*type_sym);
459 for variant in variants {
460 let variant_name = interner.resolve(variant.name);
461 for field in &variant.fields {
462 if field_is_boxed(&field.ty, enum_name, interner) {
463 let field_name = interner.resolve(field.name).to_string();
464 boxed_fields.insert((
465 enum_name.to_string(),
466 variant_name.to_string(),
467 field_name,
468 ));
469 }
470 }
471 }
472 }
473 }
474 boxed_fields
475}
476
477pub fn collect_async_functions(stmts: &[Stmt]) -> HashSet<Symbol> {
484 let mut func_bodies: HashMap<Symbol, &[Stmt]> = HashMap::new();
486 for stmt in stmts {
487 if let Stmt::FunctionDef { name, body, .. } = stmt {
488 func_bodies.insert(*name, *body);
489 }
490 }
491
492 let mut async_fns = HashSet::new();
494 for stmt in stmts {
495 if let Stmt::FunctionDef { name, body, .. } = stmt {
496 if body.iter().any(|s| requires_async_stmt(s)) {
497 async_fns.insert(*name);
498 }
499 }
500 }
501
502 loop {
504 let mut changed = false;
505 for (func_name, body) in &func_bodies {
506 if async_fns.contains(func_name) {
507 continue; }
509 if body.iter().any(|s| calls_async_function(s, &async_fns)) {
511 async_fns.insert(*func_name);
512 changed = true;
513 }
514 }
515 if !changed {
516 break;
517 }
518 }
519
520 async_fns
521}
522
523pub(super) fn calls_async_function(stmt: &Stmt, async_fns: &HashSet<Symbol>) -> bool {
525 match stmt {
526 Stmt::Call { function, args } => {
527 async_fns.contains(function)
529 || args
530 .iter()
531 .any(|a| calls_async_function_in_expr(a, async_fns))
532 }
533 Stmt::If {
534 cond,
535 then_block,
536 else_block,
537 } => {
538 calls_async_function_in_expr(cond, async_fns)
539 || then_block
540 .iter()
541 .any(|s| calls_async_function(s, async_fns))
542 || else_block.map_or(false, |b| {
543 b.iter().any(|s| calls_async_function(s, async_fns))
544 })
545 }
546 Stmt::While { cond, body, .. } => {
547 calls_async_function_in_expr(cond, async_fns)
548 || body.iter().any(|s| calls_async_function(s, async_fns))
549 }
550 Stmt::Repeat { iterable, body, .. } => {
551 calls_async_function_in_expr(iterable, async_fns)
552 || body.iter().any(|s| calls_async_function(s, async_fns))
553 }
554 Stmt::Zone { body, .. } => body.iter().any(|s| calls_async_function(s, async_fns)),
555 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
556 tasks.iter().any(|s| calls_async_function(s, async_fns))
557 }
558 Stmt::FunctionDef { body, .. } => body.iter().any(|s| calls_async_function(s, async_fns)),
559 Stmt::Let { value, .. } => calls_async_function_in_expr(value, async_fns),
561 Stmt::Set { value, .. } => calls_async_function_in_expr(value, async_fns),
563 Stmt::Return { value } => value
565 .as_ref()
566 .map_or(false, |v| calls_async_function_in_expr(v, async_fns)),
567 Stmt::RuntimeAssert { condition, .. } => calls_async_function_in_expr(condition, async_fns),
569 Stmt::Show { object, .. } => calls_async_function_in_expr(object, async_fns),
571 Stmt::Push { collection, value } => {
573 calls_async_function_in_expr(collection, async_fns)
574 || calls_async_function_in_expr(value, async_fns)
575 }
576 Stmt::SetIndex {
578 collection,
579 index,
580 value,
581 } => {
582 calls_async_function_in_expr(collection, async_fns)
583 || calls_async_function_in_expr(index, async_fns)
584 || calls_async_function_in_expr(value, async_fns)
585 }
586 Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
588 calls_async_function_in_expr(value, async_fns)
589 || calls_async_function_in_expr(pipe, async_fns)
590 }
591 Stmt::Inspect { target, arms, .. } => {
593 calls_async_function_in_expr(target, async_fns)
594 || arms
595 .iter()
596 .any(|arm| arm.body.iter().any(|s| calls_async_function(s, async_fns)))
597 }
598 _ => false,
599 }
600}
601
602fn calls_async_function_in_expr(expr: &Expr, async_fns: &HashSet<Symbol>) -> bool {
604 match expr {
605 Expr::Call { function, args } => {
606 async_fns.contains(function)
607 || args
608 .iter()
609 .any(|a| calls_async_function_in_expr(a, async_fns))
610 }
611 Expr::BinaryOp { left, right, .. } => {
612 calls_async_function_in_expr(left, async_fns)
613 || calls_async_function_in_expr(right, async_fns)
614 }
615 Expr::Index { collection, index } => {
616 calls_async_function_in_expr(collection, async_fns)
617 || calls_async_function_in_expr(index, async_fns)
618 }
619 Expr::FieldAccess { object, .. } => calls_async_function_in_expr(object, async_fns),
620 Expr::List(items) | Expr::Tuple(items) => items
621 .iter()
622 .any(|i| calls_async_function_in_expr(i, async_fns)),
623 Expr::Closure { body, .. } => match body {
624 crate::ast::stmt::ClosureBody::Expression(expr) => {
625 calls_async_function_in_expr(expr, async_fns)
626 }
627 crate::ast::stmt::ClosureBody::Block(_) => false,
628 },
629 Expr::CallExpr { callee, args } => {
630 calls_async_function_in_expr(callee, async_fns)
631 || args
632 .iter()
633 .any(|a| calls_async_function_in_expr(a, async_fns))
634 }
635 Expr::InterpolatedString(parts) => parts.iter().any(|p| {
636 if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
637 calls_async_function_in_expr(value, async_fns)
638 } else {
639 false
640 }
641 }),
642 _ => false,
643 }
644}
645
646pub(crate) fn collect_pure_functions(stmts: &[Stmt], interner: &Interner) -> HashSet<Symbol> {
653 crate::optimize::purity::Purity::of_program(stmts, interner).into_set()
654}
655
656pub(super) fn count_self_calls(func_name: Symbol, body: &[Stmt]) -> usize {
661 let mut count = 0;
662 for stmt in body {
663 count += count_self_calls_in_stmt(func_name, stmt);
664 }
665 count
666}
667
668fn count_self_calls_in_stmt(func_name: Symbol, stmt: &Stmt) -> usize {
669 match stmt {
670 Stmt::Return { value: Some(expr) } => count_self_calls_in_expr(func_name, expr),
671 Stmt::Let { value, .. } => count_self_calls_in_expr(func_name, value),
672 Stmt::Set { value, .. } => count_self_calls_in_expr(func_name, value),
673 Stmt::Call { function, args } => {
674 let mut c = if *function == func_name { 1 } else { 0 };
675 c += args
676 .iter()
677 .map(|a| count_self_calls_in_expr(func_name, a))
678 .sum::<usize>();
679 c
680 }
681 Stmt::If {
682 cond,
683 then_block,
684 else_block,
685 } => {
686 let mut c = count_self_calls_in_expr(func_name, cond);
687 c += count_self_calls(func_name, then_block);
688 if let Some(else_stmts) = else_block {
689 c += count_self_calls(func_name, else_stmts);
690 }
691 c
692 }
693 Stmt::While { cond, body, .. } => {
694 count_self_calls_in_expr(func_name, cond) + count_self_calls(func_name, body)
695 }
696 Stmt::Repeat { body, .. } => count_self_calls(func_name, body),
697 Stmt::Show { object, .. } => count_self_calls_in_expr(func_name, object),
698 _ => 0,
699 }
700}
701
702fn count_self_calls_in_expr(func_name: Symbol, expr: &Expr) -> usize {
703 match expr {
704 Expr::Call { function, args } => {
705 let mut c = if *function == func_name { 1 } else { 0 };
706 c += args
707 .iter()
708 .map(|a| count_self_calls_in_expr(func_name, a))
709 .sum::<usize>();
710 c
711 }
712 Expr::BinaryOp { left, right, .. } => {
713 count_self_calls_in_expr(func_name, left) + count_self_calls_in_expr(func_name, right)
714 }
715 Expr::Index { collection, index } => {
716 count_self_calls_in_expr(func_name, collection)
717 + count_self_calls_in_expr(func_name, index)
718 }
719 Expr::FieldAccess { object, .. } => count_self_calls_in_expr(func_name, object),
720 Expr::List(items) | Expr::Tuple(items) => items
721 .iter()
722 .map(|i| count_self_calls_in_expr(func_name, i))
723 .sum(),
724 Expr::InterpolatedString(parts) => parts
725 .iter()
726 .map(|p| {
727 if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
728 count_self_calls_in_expr(func_name, value)
729 } else {
730 0
731 }
732 })
733 .sum(),
734 _ => 0,
735 }
736}
737
738pub(super) fn is_hashable_type(ty: &TypeExpr, interner: &Interner) -> bool {
739 match ty {
740 TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
741 let name = interner.resolve(*sym);
742 matches!(
743 name,
744 "Int"
745 | "Nat"
746 | "Bool"
747 | "Char"
748 | "Byte"
749 | "Text"
750 | "i64"
751 | "u64"
752 | "bool"
753 | "char"
754 | "u8"
755 | "String"
756 )
757 }
758 TypeExpr::Refinement { base, .. } => is_hashable_type(base, interner),
759 _ => false,
760 }
761}
762
763pub(super) fn is_copy_type_expr(ty: &TypeExpr, interner: &Interner) -> bool {
764 match ty {
765 TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
766 let name = interner.resolve(*sym);
767 matches!(
768 name,
769 "Int" | "Nat" | "Bool" | "Char" | "Byte" | "i64" | "u64" | "bool" | "char" | "u8"
770 )
771 }
772 TypeExpr::Refinement { base, .. } => is_copy_type_expr(base, interner),
773 _ => false,
774 }
775}
776
777pub(super) fn should_memoize(
778 name: Symbol,
779 body: &[Stmt],
780 params: &[(Symbol, &TypeExpr)],
781 return_type: Option<&TypeExpr>,
782 is_pure: bool,
783 interner: &Interner,
784) -> bool {
785 if !is_pure {
786 return false;
787 }
788 if !body_contains_self_call(name, body) {
789 return false;
790 }
791 if count_self_calls(name, body) < 2 {
792 return false;
793 }
794 if params.is_empty() {
795 return false;
796 }
797 if !params.iter().all(|(_, ty)| is_hashable_type(ty, interner)) {
798 return false;
799 }
800 if return_type.is_none() {
801 return false;
802 }
803 true
804}
805
806pub(super) fn body_contains_self_call(func_name: Symbol, body: &[Stmt]) -> bool {
807 body.iter().any(|s| stmt_contains_self_call(func_name, s))
808}
809
810fn stmt_contains_self_call(func_name: Symbol, stmt: &Stmt) -> bool {
811 match stmt {
812 Stmt::Return { value: Some(expr) } => expr_contains_self_call(func_name, expr),
813 Stmt::Return { value: None } => false,
814 Stmt::Let { value, .. } => expr_contains_self_call(func_name, value),
815 Stmt::Set { value, .. } => expr_contains_self_call(func_name, value),
816 Stmt::Call { function, args } => {
817 *function == func_name || args.iter().any(|a| expr_contains_self_call(func_name, a))
818 }
819 Stmt::If {
820 cond,
821 then_block,
822 else_block,
823 } => {
824 expr_contains_self_call(func_name, cond)
825 || then_block
826 .iter()
827 .any(|s| stmt_contains_self_call(func_name, s))
828 || else_block.map_or(false, |b| {
829 b.iter().any(|s| stmt_contains_self_call(func_name, s))
830 })
831 }
832 Stmt::While { cond, body, .. } => {
833 expr_contains_self_call(func_name, cond)
834 || body.iter().any(|s| stmt_contains_self_call(func_name, s))
835 }
836 Stmt::Repeat { body, .. } => body.iter().any(|s| stmt_contains_self_call(func_name, s)),
837 Stmt::Show { object, .. } => expr_contains_self_call(func_name, object),
838 _ => false,
839 }
840}
841
842pub(super) fn expr_contains_self_call(func_name: Symbol, expr: &Expr) -> bool {
843 match expr {
844 Expr::Call { function, args } => {
845 *function == func_name || args.iter().any(|a| expr_contains_self_call(func_name, a))
846 }
847 Expr::BinaryOp { left, right, .. } => {
848 expr_contains_self_call(func_name, left) || expr_contains_self_call(func_name, right)
849 }
850 Expr::Index { collection, index } => {
851 expr_contains_self_call(func_name, collection)
852 || expr_contains_self_call(func_name, index)
853 }
854 Expr::FieldAccess { object, .. } => expr_contains_self_call(func_name, object),
855 Expr::List(items) | Expr::Tuple(items) => {
856 items.iter().any(|i| expr_contains_self_call(func_name, i))
857 }
858 Expr::InterpolatedString(parts) => parts.iter().any(|p| {
859 if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
860 expr_contains_self_call(func_name, value)
861 } else {
862 false
863 }
864 }),
865 _ => false,
866 }
867}
868
869pub(super) fn expr_reads_any_collection(expr: &Expr) -> bool {
878 match expr {
879 Expr::Index { .. } | Expr::Slice { .. } | Expr::Length { .. } => true,
880 Expr::BinaryOp { left, right, .. } => {
881 expr_reads_any_collection(left) || expr_reads_any_collection(right)
882 }
883 Expr::Call { args, .. } => args.iter().any(|a| expr_reads_any_collection(a)),
884 Expr::FieldAccess { object, .. } => expr_reads_any_collection(object),
885 Expr::Not { operand } => expr_reads_any_collection(operand),
886 Expr::List(items) | Expr::Tuple(items) => {
887 items.iter().any(|i| expr_reads_any_collection(i))
888 }
889 _ => false,
890 }
891}
892
893pub(super) fn should_inline(
898 name: Symbol,
899 body: &[Stmt],
900 is_native: bool,
901 is_exported: bool,
902 is_async: bool,
903) -> bool {
904 !is_native
905 && !is_exported
906 && !is_async
907 && body.len() <= 10
908 && !body_contains_self_call(name, body)
909}
910
911pub fn collect_pipe_sender_params(body: &[Stmt]) -> HashSet<Symbol> {
916 let mut senders = HashSet::new();
917 for stmt in body {
918 collect_pipe_sender_params_stmt(stmt, &mut senders);
919 }
920 senders
921}
922
923fn collect_pipe_sender_params_stmt(stmt: &Stmt, senders: &mut HashSet<Symbol>) {
924 match stmt {
925 Stmt::SendPipe { pipe, .. } | Stmt::TrySendPipe { pipe, .. } => {
926 if let Expr::Identifier(sym) = pipe {
927 senders.insert(*sym);
928 }
929 }
930 Stmt::If {
931 then_block,
932 else_block,
933 ..
934 } => {
935 for s in *then_block {
936 collect_pipe_sender_params_stmt(s, senders);
937 }
938 if let Some(else_stmts) = else_block {
939 for s in *else_stmts {
940 collect_pipe_sender_params_stmt(s, senders);
941 }
942 }
943 }
944 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
945 for s in *body {
946 collect_pipe_sender_params_stmt(s, senders);
947 }
948 }
949 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
950 for s in *tasks {
951 collect_pipe_sender_params_stmt(s, senders);
952 }
953 }
954 _ => {}
955 }
956}
957
958pub fn collect_pipe_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
961 let mut pipe_vars = HashSet::new();
962 for stmt in stmts {
963 collect_pipe_vars_stmt(stmt, &mut pipe_vars);
964 }
965 pipe_vars
966}
967
968fn collect_pipe_vars_stmt(stmt: &Stmt, pipe_vars: &mut HashSet<Symbol>) {
969 match stmt {
970 Stmt::CreatePipe { var, .. } => {
971 pipe_vars.insert(*var);
972 }
973 Stmt::If {
974 then_block,
975 else_block,
976 ..
977 } => {
978 for s in *then_block {
979 collect_pipe_vars_stmt(s, pipe_vars);
980 }
981 if let Some(else_stmts) = else_block {
982 for s in *else_stmts {
983 collect_pipe_vars_stmt(s, pipe_vars);
984 }
985 }
986 }
987 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
988 for s in *body {
989 collect_pipe_vars_stmt(s, pipe_vars);
990 }
991 }
992 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
993 for s in *tasks {
994 collect_pipe_vars_stmt(s, pipe_vars);
995 }
996 }
997 _ => {}
998 }
999}
1000
1001pub(super) fn collect_expr_identifiers(expr: &Expr, identifiers: &mut HashSet<Symbol>) {
1004 match expr {
1005 Expr::Dom(q) => {
1006 if let Some(sel) = q.selector() {
1007 collect_expr_identifiers(sel, identifiers);
1008 }
1009 }
1010 Expr::View(v) => {
1011 for e in v.exprs_and_blocks().0 {
1012 collect_expr_identifiers(e, identifiers);
1013 }
1014 }
1015 Expr::Identifier(sym) => {
1016 identifiers.insert(*sym);
1017 }
1018 Expr::BinaryOp { left, right, .. } => {
1019 collect_expr_identifiers(left, identifiers);
1020 collect_expr_identifiers(right, identifiers);
1021 }
1022 Expr::Call { args, .. } => {
1023 for arg in args {
1024 collect_expr_identifiers(arg, identifiers);
1025 }
1026 }
1027 Expr::Index { collection, index } => {
1028 collect_expr_identifiers(collection, identifiers);
1029 collect_expr_identifiers(index, identifiers);
1030 }
1031 Expr::Slice {
1032 collection,
1033 start,
1034 end,
1035 } => {
1036 collect_expr_identifiers(collection, identifiers);
1037 collect_expr_identifiers(start, identifiers);
1038 collect_expr_identifiers(end, identifiers);
1039 }
1040 Expr::Copy { expr: inner }
1041 | Expr::Give { value: inner }
1042 | Expr::Length { collection: inner }
1043 | Expr::Not { operand: inner } => {
1044 collect_expr_identifiers(inner, identifiers);
1045 }
1046 Expr::Contains { collection, value }
1047 | Expr::Union {
1048 left: collection,
1049 right: value,
1050 }
1051 | Expr::Intersection {
1052 left: collection,
1053 right: value,
1054 } => {
1055 collect_expr_identifiers(collection, identifiers);
1056 collect_expr_identifiers(value, identifiers);
1057 }
1058 Expr::ManifestOf { zone } | Expr::ChunkAt { zone, .. } => {
1059 collect_expr_identifiers(zone, identifiers);
1060 }
1061 Expr::List(items) | Expr::Tuple(items) => {
1062 for item in items {
1063 collect_expr_identifiers(item, identifiers);
1064 }
1065 }
1066 Expr::Range { start, end } => {
1067 collect_expr_identifiers(start, identifiers);
1068 collect_expr_identifiers(end, identifiers);
1069 }
1070 Expr::FieldAccess { object, .. } => {
1071 collect_expr_identifiers(object, identifiers);
1072 }
1073 Expr::New { init_fields, .. } => {
1074 for (_, value) in init_fields {
1075 collect_expr_identifiers(value, identifiers);
1076 }
1077 }
1078 Expr::NewVariant { fields, .. } => {
1079 for (_, value) in fields {
1080 collect_expr_identifiers(value, identifiers);
1081 }
1082 }
1083 Expr::OptionSome { value } => {
1084 collect_expr_identifiers(value, identifiers);
1085 }
1086 Expr::WithCapacity { value, capacity } => {
1087 collect_expr_identifiers(value, identifiers);
1088 collect_expr_identifiers(capacity, identifiers);
1089 }
1090 Expr::Closure { body, .. } => match body {
1091 crate::ast::stmt::ClosureBody::Expression(expr) => {
1092 collect_expr_identifiers(expr, identifiers)
1093 }
1094 crate::ast::stmt::ClosureBody::Block(_) => {}
1095 },
1096 Expr::CallExpr { callee, args } => {
1097 collect_expr_identifiers(callee, identifiers);
1098 for arg in args {
1099 collect_expr_identifiers(arg, identifiers);
1100 }
1101 }
1102 Expr::InterpolatedString(parts) => {
1103 for part in parts {
1104 if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
1105 collect_expr_identifiers(value, identifiers);
1106 }
1107 }
1108 }
1109 Expr::OptionNone => {}
1110 Expr::Escape { .. } => {}
1111 Expr::Literal(_) => {}
1112 }
1113}
1114
1115pub(crate) fn symbol_appears_in_stmts(sym: Symbol, stmts: &[&Stmt]) -> bool {
1118 stmts.iter().any(|s| symbol_appears_in_stmt(sym, s))
1119}
1120
1121pub(crate) fn value_read_after(sym: Symbol, block: &[&Stmt], at: usize) -> bool {
1125 let declared_here = block[..at]
1126 .iter()
1127 .any(|s| matches!(s, Stmt::Let { var, .. } if *var == sym));
1128 !declared_here || symbol_appears_in_stmts(sym, &block[at..])
1129}
1130
1131pub(super) fn symbol_appears_in_stmt(sym: Symbol, stmt: &Stmt) -> bool {
1134 match stmt {
1135 Stmt::FunctionDef { body, .. } => body.iter().any(|s| symbol_appears_in_stmt(sym, s)),
1136 other => crate::optimize::stmt_touches(other, sym),
1137 }
1138}
1139
1140pub(super) fn symbol_appears_in_expr(sym: Symbol, expr: &Expr) -> bool {
1142 crate::optimize::expr_touches(expr, sym)
1143}
1144
1145pub(crate) fn is_vec_type_expr(ty: &TypeExpr, interner: &Interner) -> bool {
1147 match ty {
1148 TypeExpr::Generic { base, .. } => {
1149 let name = interner.resolve(*base);
1150 matches!(name, "Seq" | "List" | "Vec")
1151 }
1152 _ => false,
1153 }
1154}
1155
1156pub(super) fn vec_to_slice_type(vec_type: &str) -> String {
1159 if let Some(inner) = vec_type
1160 .strip_prefix("Vec<")
1161 .and_then(|s| s.strip_suffix('>'))
1162 {
1163 format!("&[{}]", inner)
1164 } else if let Some(inner) = vec_type
1165 .strip_prefix("LogosSeq<")
1166 .and_then(|s| s.strip_suffix('>'))
1167 {
1168 format!("&[{}]", inner)
1169 } else if vec_type == "String" {
1170 "&str".to_string()
1173 } else {
1174 vec_type.to_string()
1175 }
1176}
1177
1178pub(super) fn vec_to_mut_slice_type(vec_type: &str) -> String {
1180 if let Some(inner) = vec_type
1181 .strip_prefix("Vec<")
1182 .and_then(|s| s.strip_suffix('>'))
1183 {
1184 format!("&mut [{}]", inner)
1185 } else if let Some(inner) = vec_type
1186 .strip_prefix("LogosSeq<")
1187 .and_then(|s| s.strip_suffix('>'))
1188 {
1189 format!("&mut [{}]", inner)
1190 } else {
1191 vec_type.to_string()
1192 }
1193}
1194
1195pub(crate) fn collect_de_rc_seqs(
1209 stmts: &[Stmt],
1210 interner: &Interner,
1211 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1212 mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1213 vec_return_fns: &HashSet<Symbol>,
1214 returns_vec: bool,
1215) -> HashSet<Symbol> {
1216 if !crate::optimize::active_config().is_on(crate::optimization::Opt::Unbox) {
1218 return HashSet::new();
1219 }
1220 let borrow_slots: HashMap<Symbol, HashSet<usize>> = if mut_borrow_params.is_empty() {
1226 borrow_params.clone()
1227 } else {
1228 let mut m = borrow_params.clone();
1229 for (f, idx) in mut_borrow_params {
1230 m.entry(*f).or_default().extend(idx.iter().copied());
1231 }
1232 m
1233 };
1234 let borrow_params = &borrow_slots;
1235 let mut candidates = HashSet::new();
1236 collect_de_rc_candidates_block(stmts, interner, vec_return_fns, &mut candidates);
1237 if candidates.is_empty() {
1238 return candidates;
1239 }
1240 let mut swaps = HashSet::new();
1253 collect_buffer_swap_pairs(stmts, interner, &mut swaps);
1254
1255 let mut disqualified = HashSet::new();
1256 derc_scan_uses(
1257 stmts,
1258 &candidates,
1259 &swaps,
1260 borrow_params,
1261 mut_borrow_params,
1262 vec_return_fns,
1263 returns_vec,
1264 interner,
1265 &mut disqualified,
1266 );
1267 candidates.retain(|c| !disqualified.contains(c));
1268
1269 let classes = crate::optimize::SwapClasses::of(stmts, interner);
1274 loop {
1275 let before = candidates.len();
1276 for (outer, inner) in &swaps {
1277 if candidates.contains(outer) != candidates.contains(inner) {
1278 candidates.remove(outer);
1279 candidates.remove(inner);
1280 }
1281 }
1282 classes.close_set(&mut candidates, interner);
1283 if candidates.len() == before {
1284 break;
1285 }
1286 }
1287 if !candidates.is_empty() {
1288 crate::optimize::mark_fired(crate::optimization::Opt::Unbox);
1289 }
1290 candidates
1291}
1292
1293pub(super) fn collect_vec_return_fns(
1304 stmts: &[Stmt],
1305 interner: &Interner,
1306 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1307 mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1308) -> HashSet<Symbol> {
1309 if !crate::optimize::active_config().is_on(crate::optimization::Opt::Unbox) {
1310 return HashSet::new();
1311 }
1312 let mut seq_fns: Vec<(Symbol, &[Stmt], &[(Symbol, &TypeExpr)])> = Vec::new();
1315 for s in stmts {
1316 if let Stmt::FunctionDef {
1317 name,
1318 body,
1319 params,
1320 return_type: Some(rt),
1321 is_native: false,
1322 ..
1323 } = s
1324 {
1325 if is_vec_type_expr(rt, interner) {
1326 seq_fns.push((*name, body, params));
1327 }
1328 }
1329 }
1330 if seq_fns.is_empty() {
1331 return HashSet::new();
1332 }
1333
1334 let mut vec_fns: HashSet<Symbol> = seq_fns.iter().map(|(n, _, _)| *n).collect();
1354 loop {
1355 let mut remove = HashSet::new();
1356
1357 flag_inline_vec_calls(stmts, &vec_fns, &mut remove);
1359
1360 let main_de_rc = collect_de_rc_seqs(
1365 stmts,
1366 interner,
1367 borrow_params,
1368 mut_borrow_params,
1369 &vec_fns,
1370 false,
1371 );
1372 collect_unsound_vec_returns(stmts, &vec_fns, &main_de_rc, &mut remove);
1373 for (name, body, params) in &seq_fns {
1374 let rv = vec_fns.contains(name);
1375 let de_rc = collect_de_rc_seqs(
1376 body,
1377 interner,
1378 borrow_params,
1379 mut_borrow_params,
1380 &vec_fns,
1381 rv,
1382 );
1383 collect_unsound_vec_returns(body, &vec_fns, &de_rc, &mut remove);
1384 if rv && !all_returns_vec_ownable(body, params, borrow_params.get(name), &de_rc) {
1385 remove.insert(*name);
1386 }
1387 }
1388
1389 if remove.is_empty() {
1390 break;
1391 }
1392 vec_fns.retain(|f| !remove.contains(f));
1393 }
1394 if !vec_fns.is_empty() {
1395 crate::optimize::mark_fired(crate::optimization::Opt::Unbox);
1396 }
1397 vec_fns
1398}
1399
1400fn collect_unsound_vec_returns(
1404 stmts: &[Stmt],
1405 vec_fns: &HashSet<Symbol>,
1406 de_rc: &HashSet<Symbol>,
1407 remove: &mut HashSet<Symbol>,
1408) {
1409 for stmt in stmts {
1410 let binding = match stmt {
1411 Stmt::Let { var, value, .. } => Some((*var, value)),
1412 Stmt::Set { target, value } => Some((*target, value)),
1413 _ => None,
1414 };
1415 if let Some((x, Expr::Call { function, .. })) = binding {
1416 if vec_fns.contains(function) && !de_rc.contains(&x) {
1417 remove.insert(*function);
1418 }
1419 }
1420 match stmt {
1421 Stmt::If {
1422 then_block,
1423 else_block,
1424 ..
1425 } => {
1426 collect_unsound_vec_returns(then_block, vec_fns, de_rc, remove);
1427 if let Some(eb) = else_block {
1428 collect_unsound_vec_returns(eb, vec_fns, de_rc, remove);
1429 }
1430 }
1431 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
1432 collect_unsound_vec_returns(body, vec_fns, de_rc, remove)
1433 }
1434 _ => {}
1435 }
1436 }
1437}
1438
1439fn all_returns_vec_ownable(
1449 body: &[Stmt],
1450 params: &[(Symbol, &TypeExpr)],
1451 borrow_idx: Option<&HashSet<usize>>,
1452 de_rc: &HashSet<Symbol>,
1453) -> bool {
1454 fn walk(
1455 stmts: &[Stmt],
1456 params: &[(Symbol, &TypeExpr)],
1457 borrow_idx: Option<&HashSet<usize>>,
1458 de_rc: &HashSet<Symbol>,
1459 ok: &mut bool,
1460 ) {
1461 for s in stmts {
1462 match s {
1463 Stmt::Return { value: Some(e) } => {
1464 if !is_vec_ownable_return(e, params, borrow_idx, de_rc) {
1465 *ok = false;
1466 }
1467 }
1468 Stmt::Return { value: None } => *ok = false,
1469 Stmt::If {
1470 then_block,
1471 else_block,
1472 ..
1473 } => {
1474 walk(then_block, params, borrow_idx, de_rc, ok);
1475 if let Some(eb) = else_block {
1476 walk(eb, params, borrow_idx, de_rc, ok);
1477 }
1478 }
1479 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
1480 walk(body, params, borrow_idx, de_rc, ok)
1481 }
1482 _ => {}
1483 }
1484 }
1485 }
1486 let mut ok = true;
1487 walk(body, params, borrow_idx, de_rc, &mut ok);
1488 ok
1489}
1490
1491fn is_vec_ownable_return(
1492 e: &Expr,
1493 params: &[(Symbol, &TypeExpr)],
1494 borrow_idx: Option<&HashSet<usize>>,
1495 de_rc: &HashSet<Symbol>,
1496) -> bool {
1497 match e {
1498 Expr::Identifier(x) => match params.iter().position(|(p, _)| p == x) {
1499 Some(idx) => borrow_idx.map_or(false, |b| b.contains(&idx)),
1501 None => de_rc.contains(x),
1503 },
1504 _ => false,
1505 }
1506}
1507
1508fn flag_inline_vec_calls(stmts: &[Stmt], vec_fns: &HashSet<Symbol>, remove: &mut HashSet<Symbol>) {
1516 let flag_in_expr = |e: &Expr, remove: &mut HashSet<Symbol>| {
1517 for &f in vec_fns {
1518 if symbol_appears_in_expr(f, e) {
1519 remove.insert(f);
1520 }
1521 }
1522 };
1523 for stmt in stmts {
1524 match stmt {
1525 Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
1526 if let Expr::Call { args, .. } = value {
1531 for a in args.iter() {
1532 flag_in_expr(a, remove);
1533 }
1534 } else {
1535 flag_in_expr(value, remove);
1536 }
1537 }
1538 Stmt::If {
1539 cond,
1540 then_block,
1541 else_block,
1542 } => {
1543 flag_in_expr(cond, remove);
1544 flag_inline_vec_calls(then_block, vec_fns, remove);
1545 if let Some(eb) = else_block {
1546 flag_inline_vec_calls(eb, vec_fns, remove);
1547 }
1548 }
1549 Stmt::While { cond, body, .. } => {
1550 flag_in_expr(cond, remove);
1551 flag_inline_vec_calls(body, vec_fns, remove);
1552 }
1553 Stmt::Repeat { iterable, body, .. } => {
1554 flag_in_expr(iterable, remove);
1555 flag_inline_vec_calls(body, vec_fns, remove);
1556 }
1557 Stmt::Zone { body, .. } | Stmt::FunctionDef { body, .. } => {
1558 flag_inline_vec_calls(body, vec_fns, remove)
1559 }
1560 other => {
1564 for &f in vec_fns {
1565 if symbol_appears_in_stmt(f, other) {
1566 remove.insert(f);
1567 }
1568 }
1569 }
1570 }
1571 }
1572}
1573
1574fn is_vec_return_call(value: &Expr, vec_return_fns: &HashSet<Symbol>) -> bool {
1578 matches!(value, Expr::Call { function, .. } if vec_return_fns.contains(function))
1579}
1580
1581fn is_mut_borrow_inplace_call(
1586 target: Symbol,
1587 value: &Expr,
1588 mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1589) -> bool {
1590 if let Expr::Call { function, args } = value {
1591 if let Some(slots) = mut_borrow_params.get(function) {
1592 return args.iter().enumerate().any(|(i, a)| {
1593 slots.contains(&i) && matches!(a, Expr::Identifier(s) if *s == target)
1594 });
1595 }
1596 }
1597 false
1598}
1599
1600fn collect_buffer_swap_pairs(
1606 stmts: &[Stmt],
1607 interner: &Interner,
1608 out: &mut HashSet<(Symbol, Symbol)>,
1609) {
1610 for stmt in stmts {
1611 match stmt {
1612 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
1613 detect_swap_in_body(body, interner, out);
1614 collect_buffer_swap_pairs(body, interner, out);
1615 }
1616 Stmt::If {
1617 then_block,
1618 else_block,
1619 ..
1620 } => {
1621 collect_buffer_swap_pairs(then_block, interner, out);
1622 if let Some(eb) = else_block {
1623 collect_buffer_swap_pairs(eb, interner, out);
1624 }
1625 }
1626 Stmt::Zone { body, .. } => collect_buffer_swap_pairs(body, interner, out),
1627 _ => {}
1628 }
1629 }
1630}
1631
1632fn detect_swap_in_body(body: &[Stmt], interner: &Interner, out: &mut HashSet<(Symbol, Symbol)>) {
1633 let mut fresh_inner: HashSet<Symbol> = HashSet::new();
1634 for stmt in body {
1635 if let Stmt::Let {
1636 var,
1637 value,
1638 mutable: true,
1639 ..
1640 } = stmt
1641 {
1642 if is_fresh_seq_value(value, interner) {
1643 fresh_inner.insert(*var);
1644 }
1645 }
1646 }
1647 if fresh_inner.is_empty() {
1648 return;
1649 }
1650 for (idx, stmt) in body.iter().enumerate() {
1651 if let Stmt::Set {
1652 target,
1653 value: Expr::Identifier(src),
1654 } = stmt
1655 {
1656 if *target != *src && fresh_inner.contains(src) {
1657 let used_after = body[idx + 1..]
1658 .iter()
1659 .any(|s| symbol_appears_in_stmt(*src, s));
1660 if !used_after {
1661 out.insert((*target, *src));
1662 }
1663 }
1664 }
1665 }
1666}
1667
1668fn derc_scan_uses(
1671 stmts: &[Stmt],
1672 cands: &HashSet<Symbol>,
1673 swaps: &HashSet<(Symbol, Symbol)>,
1674 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1675 mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1676 vec_return_fns: &HashSet<Symbol>,
1677 returns_vec: bool,
1678 interner: &Interner,
1679 dq: &mut HashSet<Symbol>,
1680) {
1681 for stmt in stmts {
1682 derc_scan_stmt(
1683 stmt,
1684 cands,
1685 swaps,
1686 borrow_params,
1687 mut_borrow_params,
1688 vec_return_fns,
1689 returns_vec,
1690 interner,
1691 dq,
1692 );
1693 }
1694}
1695
1696fn derc_scan_call_args(
1701 function: Symbol,
1702 args: &[&Expr],
1703 cands: &HashSet<Symbol>,
1704 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1705 dq: &mut HashSet<Symbol>,
1706) {
1707 let slots = borrow_params.get(&function);
1708 for (i, a) in args.iter().enumerate() {
1709 match a {
1710 Expr::Identifier(s) if cands.contains(s) => {
1711 let is_borrow_slot = slots.map_or(false, |set| set.contains(&i));
1712 if !is_borrow_slot {
1713 dq.insert(*s);
1714 }
1715 }
1716 _ => derc_scan_expr(a, cands, borrow_params, dq),
1717 }
1718 }
1719}
1720
1721fn is_fresh_seq_value(value: &Expr, interner: &Interner) -> bool {
1723 match value {
1724 Expr::New {
1725 type_name,
1726 init_fields,
1727 ..
1728 } if init_fields.is_empty() => {
1729 matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec")
1730 }
1731 Expr::WithCapacity { value: inner, .. } => is_fresh_seq_value(inner, interner),
1732 Expr::List(_) => true,
1733 _ => false,
1734 }
1735}
1736
1737fn derc_scan_stmt(
1738 stmt: &Stmt,
1739 cands: &HashSet<Symbol>,
1740 swaps: &HashSet<(Symbol, Symbol)>,
1741 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1742 mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
1743 vec_return_fns: &HashSet<Symbol>,
1744 returns_vec: bool,
1745 interner: &Interner,
1746 dq: &mut HashSet<Symbol>,
1747) {
1748 match stmt {
1749 Stmt::Let { value, .. } => {
1752 if is_vec_return_call(value, vec_return_fns) {
1753 if let Expr::Call { function, args } = value {
1757 derc_scan_call_args(*function, args, cands, borrow_params, dq);
1758 }
1759 } else if !is_fresh_seq_value(value, interner) {
1760 derc_scan_expr(value, cands, borrow_params, dq);
1761 }
1762 }
1763 Stmt::Set { target, value } => {
1764 if let Expr::Identifier(src) = value {
1765 if swaps.contains(&(*target, *src)) {
1766 } else if target != src {
1769 dq.insert(*src);
1772 dq.insert(*target);
1773 }
1774 } else if is_vec_return_call(value, vec_return_fns) {
1775 if let Expr::Call { function, args } = value {
1780 derc_scan_call_args(*function, args, cands, borrow_params, dq);
1781 }
1782 } else if is_mut_borrow_inplace_call(*target, value, mut_borrow_params) {
1783 if let Expr::Call { function, args } = value {
1789 derc_scan_call_args(*function, args, cands, borrow_params, dq);
1790 }
1791 } else if !is_fresh_seq_value(value, interner) {
1792 dq.insert(*target);
1797 derc_scan_expr(value, cands, borrow_params, dq);
1798 }
1799 }
1800 Stmt::Push { value, collection } | Stmt::Add { value, collection } => {
1803 derc_scan_collection_slot(collection, cands, borrow_params, dq);
1804 derc_scan_expr(value, cands, borrow_params, dq);
1805 }
1806 Stmt::Pop { collection, .. } => {
1807 derc_scan_collection_slot(collection, cands, borrow_params, dq)
1808 }
1809 Stmt::Remove { value, collection } => {
1810 derc_scan_collection_slot(collection, cands, borrow_params, dq);
1811 derc_scan_expr(value, cands, borrow_params, dq);
1812 }
1813 Stmt::SetIndex {
1814 collection,
1815 index,
1816 value,
1817 } => {
1818 derc_scan_collection_slot(collection, cands, borrow_params, dq);
1819 derc_scan_expr(index, cands, borrow_params, dq);
1820 derc_scan_expr(value, cands, borrow_params, dq);
1821 }
1822 Stmt::If {
1823 cond,
1824 then_block,
1825 else_block,
1826 } => {
1827 derc_scan_expr(cond, cands, borrow_params, dq);
1828 derc_scan_uses(
1829 then_block,
1830 cands,
1831 swaps,
1832 borrow_params,
1833 mut_borrow_params,
1834 vec_return_fns,
1835 returns_vec,
1836 interner,
1837 dq,
1838 );
1839 if let Some(eb) = else_block {
1840 derc_scan_uses(
1841 eb,
1842 cands,
1843 swaps,
1844 borrow_params,
1845 mut_borrow_params,
1846 vec_return_fns,
1847 returns_vec,
1848 interner,
1849 dq,
1850 );
1851 }
1852 }
1853 Stmt::While { cond, body, .. } => {
1854 derc_scan_expr(cond, cands, borrow_params, dq);
1855 derc_scan_uses(
1856 body,
1857 cands,
1858 swaps,
1859 borrow_params,
1860 mut_borrow_params,
1861 vec_return_fns,
1862 returns_vec,
1863 interner,
1864 dq,
1865 );
1866 }
1867 Stmt::Repeat { iterable, body, .. } => {
1868 derc_scan_expr(iterable, cands, borrow_params, dq);
1870 derc_scan_uses(
1871 body,
1872 cands,
1873 swaps,
1874 borrow_params,
1875 mut_borrow_params,
1876 vec_return_fns,
1877 returns_vec,
1878 interner,
1879 dq,
1880 );
1881 }
1882 Stmt::Zone { body, .. } => derc_scan_uses(
1883 body,
1884 cands,
1885 swaps,
1886 borrow_params,
1887 mut_borrow_params,
1888 vec_return_fns,
1889 returns_vec,
1890 interner,
1891 dq,
1892 ),
1893 Stmt::Call { function, args } => {
1896 derc_scan_call_args(*function, args, cands, borrow_params, dq);
1897 }
1898 Stmt::Return { value: Some(e) } => {
1901 if !(returns_vec && matches!(e, Expr::Identifier(x) if cands.contains(x))) {
1902 derc_scan_expr(e, cands, borrow_params, dq);
1903 }
1904 }
1905 Stmt::Return { value: None } => {}
1906 Stmt::Show { object, recipient } | Stmt::Give { object, recipient } => {
1907 derc_scan_expr(object, cands, borrow_params, dq);
1908 derc_scan_expr(recipient, cands, borrow_params, dq);
1909 }
1910 Stmt::FunctionDef { .. } => {}
1918 Stmt::Swap { .. } => {}
1921 other => {
1925 for &c in cands {
1926 if symbol_appears_in_stmt(c, other) {
1927 dq.insert(c);
1928 }
1929 }
1930 }
1931 }
1932}
1933
1934fn derc_scan_collection_slot(
1937 collection: &Expr,
1938 cands: &HashSet<Symbol>,
1939 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1940 dq: &mut HashSet<Symbol>,
1941) {
1942 match collection {
1943 Expr::Identifier(_) => {}
1944 other => derc_scan_expr(other, cands, borrow_params, dq),
1945 }
1946}
1947
1948fn derc_scan_expr(
1953 expr: &Expr,
1954 cands: &HashSet<Symbol>,
1955 borrow_params: &HashMap<Symbol, HashSet<usize>>,
1956 dq: &mut HashSet<Symbol>,
1957) {
1958 match expr {
1959 Expr::Identifier(s) => {
1960 if cands.contains(s) {
1961 dq.insert(*s);
1962 }
1963 }
1964 Expr::Index { collection, index } => {
1965 derc_scan_collection_slot(collection, cands, borrow_params, dq);
1966 derc_scan_expr(index, cands, borrow_params, dq);
1967 }
1968 Expr::Length { collection } => {
1969 derc_scan_collection_slot(collection, cands, borrow_params, dq)
1970 }
1971 Expr::BinaryOp { left, right, .. } => {
1972 derc_scan_expr(left, cands, borrow_params, dq);
1973 derc_scan_expr(right, cands, borrow_params, dq);
1974 }
1975 Expr::Not { operand } => derc_scan_expr(operand, cands, borrow_params, dq),
1976 Expr::Call { function, args } => {
1977 derc_scan_call_args(*function, args, cands, borrow_params, dq);
1978 }
1979 other => {
1983 for &c in cands {
1984 if symbol_appears_in_expr(c, other) {
1985 dq.insert(c);
1986 }
1987 }
1988 }
1989 }
1990}
1991
1992pub(crate) fn homogeneous_scalar_literal_elem(items: &[&Expr]) -> Option<String> {
1999 fn elem_ty(e: &Expr) -> Option<&'static str> {
2000 match e {
2001 Expr::Literal(Literal::Number(_)) => Some("i64"),
2002 Expr::Literal(Literal::Float(_)) => Some("f64"),
2003 Expr::Literal(Literal::Boolean(_)) => Some("bool"),
2004 Expr::Literal(Literal::Char(_)) => Some("char"),
2005 _ => None,
2006 }
2007 }
2008 let first = elem_ty(items.first()?)?;
2009 if items.iter().all(|i| elem_ty(i) == Some(first)) {
2010 Some(first.to_string())
2011 } else {
2012 None
2013 }
2014}
2015
2016fn fresh_scalar_seq_elem(value: &Expr, interner: &Interner) -> Option<String> {
2018 match value {
2019 Expr::New {
2020 type_name,
2021 type_args,
2022 init_fields,
2023 } if init_fields.is_empty() => match interner.resolve(*type_name) {
2024 "Seq" | "List" | "Vec" => {
2025 let elem = type_args.first()?;
2026 let ty = codegen_type_expr(elem, interner);
2027 if is_scalar_elem_type(&ty) {
2028 Some(ty)
2029 } else {
2030 None
2031 }
2032 }
2033 _ => None,
2034 },
2035 Expr::WithCapacity { value: inner, .. } => fresh_scalar_seq_elem(inner, interner),
2036 Expr::List(items) => homogeneous_scalar_literal_elem(items),
2041 _ => None,
2042 }
2043}
2044
2045fn is_scalar_elem_type(ty: &str) -> bool {
2047 matches!(
2048 ty,
2049 "i64" | "i32" | "i16" | "i8" | "u64" | "u32" | "u16" | "u8" | "usize" | "isize"
2050 | "f64" | "f32" | "bool" | "char" | "String"
2051 | "Word8" | "Word16" | "Word32" | "Word64"
2053 )
2054}
2055
2056fn collect_de_rc_candidates_block(
2057 stmts: &[Stmt],
2058 interner: &Interner,
2059 vec_return_fns: &HashSet<Symbol>,
2060 out: &mut HashSet<Symbol>,
2061) {
2062 for stmt in stmts {
2063 match stmt {
2064 Stmt::Let { var, value, .. } => {
2065 if fresh_scalar_seq_elem(value, interner).is_some()
2068 || is_vec_return_call(value, vec_return_fns)
2069 {
2070 out.insert(*var);
2071 }
2072 }
2073 Stmt::If {
2074 then_block,
2075 else_block,
2076 ..
2077 } => {
2078 collect_de_rc_candidates_block(then_block, interner, vec_return_fns, out);
2079 if let Some(eb) = else_block {
2080 collect_de_rc_candidates_block(eb, interner, vec_return_fns, out);
2081 }
2082 }
2083 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
2084 collect_de_rc_candidates_block(body, interner, vec_return_fns, out);
2085 }
2086 Stmt::Zone { body, .. } => {
2087 collect_de_rc_candidates_block(body, interner, vec_return_fns, out);
2088 }
2089 _ => {}
2090 }
2091 }
2092}
2093
2094pub(super) fn collect_escaping_collection_vars(stmts: &[Stmt]) -> HashSet<Symbol> {
2100 let mut escaped = HashSet::new();
2101 collect_escaping_vars_block(stmts, &mut escaped);
2102 escaped
2103}
2104
2105fn collect_escaping_vars_block(stmts: &[Stmt], escaped: &mut HashSet<Symbol>) {
2106 for stmt in stmts {
2107 collect_escaping_vars_stmt(stmt, escaped);
2108 }
2109}
2110
2111fn collect_escaping_vars_stmt(stmt: &Stmt, escaped: &mut HashSet<Symbol>) {
2112 match stmt {
2113 Stmt::Call { args, .. } => {
2114 for arg in args.iter() {
2115 collect_escaping_vars_from_call_arg(arg, escaped);
2116 }
2117 }
2118 Stmt::Return { value: Some(expr) } => {
2119 if let Expr::Identifier(sym) = expr {
2120 escaped.insert(*sym);
2121 }
2122 }
2123 Stmt::If {
2124 then_block,
2125 else_block,
2126 ..
2127 } => {
2128 collect_escaping_vars_block(then_block, escaped);
2129 if let Some(else_stmts) = else_block {
2130 collect_escaping_vars_block(else_stmts, escaped);
2131 }
2132 }
2133 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
2134 collect_escaping_vars_block(body, escaped);
2135 }
2136 Stmt::Let { value, .. } => {
2137 collect_escaping_vars_from_expr_calls(value, escaped);
2138 }
2139 Stmt::Set { value, .. } => {
2140 collect_escaping_vars_from_expr_calls(value, escaped);
2141 }
2142 _ => {}
2143 }
2144}
2145
2146fn collect_escaping_vars_from_call_arg(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2148 match expr {
2149 Expr::Identifier(sym) => {
2150 escaped.insert(*sym);
2151 }
2152 Expr::Copy { .. } => { }
2153 _ => {
2154 collect_escaping_vars_from_expr_ids(expr, escaped);
2156 }
2157 }
2158}
2159
2160fn collect_escaping_vars_from_expr_calls(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2162 match expr {
2163 Expr::Call { args, .. } => {
2164 for arg in args.iter() {
2165 collect_escaping_vars_from_call_arg(arg, escaped);
2166 }
2167 }
2168 Expr::BinaryOp { left, right, .. } => {
2169 collect_escaping_vars_from_expr_calls(left, escaped);
2170 collect_escaping_vars_from_expr_calls(right, escaped);
2171 }
2172 _ => {}
2173 }
2174}
2175
2176fn collect_escaping_vars_from_expr_ids(expr: &Expr, escaped: &mut HashSet<Symbol>) {
2178 match expr {
2179 Expr::Identifier(sym) => {
2180 escaped.insert(*sym);
2181 }
2182 Expr::BinaryOp { left, right, .. } => {
2183 collect_escaping_vars_from_expr_ids(left, escaped);
2184 collect_escaping_vars_from_expr_ids(right, escaped);
2185 }
2186 _ => {}
2187 }
2188}
2189
2190pub(super) fn expr_debug_prefix(expr: &Expr, interner: &Interner) -> String {
2192 match expr {
2193 Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
2194 _ => "expr".to_string(),
2195 }
2196}
2197
2198pub(super) fn collect_stmt_identifiers(stmt: &Stmt, identifiers: &mut HashSet<Symbol>) {
2200 match stmt {
2201 Stmt::Let { value, .. } => {
2202 collect_expr_identifiers(value, identifiers);
2203 }
2204 Stmt::Call { args, .. } => {
2205 for arg in args {
2206 collect_expr_identifiers(arg, identifiers);
2207 }
2208 }
2209 _ => {}
2210 }
2211}
2212
2213pub(super) fn collect_give_arg_indices(fn_sym: Symbol, stmts: &[Stmt]) -> HashSet<usize> {
2216 let mut result = HashSet::new();
2217 for stmt in stmts {
2218 scan_give_args_stmt(fn_sym, stmt, &mut result);
2219 }
2220 result
2221}
2222
2223fn scan_give_args_stmt(fn_sym: Symbol, stmt: &Stmt, result: &mut HashSet<usize>) {
2224 match stmt {
2225 Stmt::Call { function, args } => {
2226 if *function == fn_sym {
2227 for (i, arg) in args.iter().enumerate() {
2228 if matches!(arg, Expr::Give { .. }) {
2229 result.insert(i);
2230 }
2231 }
2232 }
2233 for arg in args {
2234 scan_give_args_expr(fn_sym, arg, result);
2235 }
2236 }
2237 Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
2238 scan_give_args_expr(fn_sym, value, result);
2239 }
2240 Stmt::Return { value: Some(v) } => scan_give_args_expr(fn_sym, v, result),
2241 Stmt::FunctionDef { body, .. } => {
2242 for s in *body {
2243 scan_give_args_stmt(fn_sym, s, result);
2244 }
2245 }
2246 Stmt::If {
2247 then_block,
2248 else_block,
2249 ..
2250 } => {
2251 for s in *then_block {
2252 scan_give_args_stmt(fn_sym, s, result);
2253 }
2254 if let Some(b) = else_block {
2255 for s in *b {
2256 scan_give_args_stmt(fn_sym, s, result);
2257 }
2258 }
2259 }
2260 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
2261 for s in *body {
2262 scan_give_args_stmt(fn_sym, s, result);
2263 }
2264 }
2265 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
2266 for s in *tasks {
2267 scan_give_args_stmt(fn_sym, s, result);
2268 }
2269 }
2270 Stmt::Inspect { arms, .. } => {
2271 for arm in arms.iter() {
2272 for s in arm.body.iter() {
2273 scan_give_args_stmt(fn_sym, s, result);
2274 }
2275 }
2276 }
2277 _ => {}
2278 }
2279}
2280
2281fn scan_give_args_expr(fn_sym: Symbol, expr: &Expr, result: &mut HashSet<usize>) {
2282 match expr {
2283 Expr::Call { function, args } => {
2284 if *function == fn_sym {
2285 for (i, arg) in args.iter().enumerate() {
2286 if matches!(arg, Expr::Give { .. }) {
2287 result.insert(i);
2288 }
2289 }
2290 }
2291 for arg in args {
2292 scan_give_args_expr(fn_sym, arg, result);
2293 }
2294 }
2295 Expr::BinaryOp { left, right, .. } => {
2296 scan_give_args_expr(fn_sym, left, result);
2297 scan_give_args_expr(fn_sym, right, result);
2298 }
2299 Expr::FieldAccess { object, .. }
2300 | Expr::Give { value: object }
2301 | Expr::Copy { expr: object }
2302 | Expr::Length { collection: object } => {
2303 scan_give_args_expr(fn_sym, object, result);
2304 }
2305 Expr::Index { collection, index } => {
2306 scan_give_args_expr(fn_sym, collection, result);
2307 scan_give_args_expr(fn_sym, index, result);
2308 }
2309 Expr::List(items) | Expr::Tuple(items) => {
2310 for item in items {
2311 scan_give_args_expr(fn_sym, item, result);
2312 }
2313 }
2314 _ => {}
2315 }
2316}
2317
2318pub(super) struct ClosedFormInfo {
2326 pub base: i64,
2327 pub k: i64,
2328}
2329
2330pub(super) fn detect_double_recursion_closed_form<'a>(
2338 func_name: Symbol,
2339 params: &[(Symbol, &'a TypeExpr<'a>)],
2340 body: &'a [Stmt<'a>],
2341 interner: &Interner,
2342) -> Option<ClosedFormInfo> {
2343 use crate::ast::stmt::BinaryOpKind;
2344
2345 if params.len() != 1 {
2346 return None;
2347 }
2348 let param_sym = params[0].0;
2349
2350 let is_integer_param = matches!(
2356 params[0].1,
2357 TypeExpr::Primitive(sym) | TypeExpr::Named(sym)
2358 if matches!(interner.resolve(*sym), "Int" | "Nat" | "Byte")
2359 );
2360 if !is_integer_param {
2361 return None;
2362 }
2363
2364 if body.len() != 2 {
2366 return None;
2367 }
2368
2369 let base_value = match &body[0] {
2371 Stmt::If {
2372 cond,
2373 then_block,
2374 else_block,
2375 } => {
2376 if else_block.is_some() {
2377 return None;
2378 }
2379 if then_block.len() != 1 {
2380 return None;
2381 }
2382 let base = match &then_block[0] {
2383 Stmt::Return { value: Some(expr) } => cf_extract_literal_int(expr)?,
2384 _ => return None,
2385 };
2386 match cond {
2387 Expr::BinaryOp {
2388 op: BinaryOpKind::Eq,
2389 left,
2390 right,
2391 } => {
2392 let ok = (cf_is_identifier(left, param_sym) && cf_is_literal_int(right, 0))
2393 || (cf_is_literal_int(left, 0) && cf_is_identifier(right, param_sym));
2394 if !ok {
2395 return None;
2396 }
2397 }
2398 _ => return None,
2399 }
2400 base
2401 }
2402 _ => return None,
2403 };
2404
2405 let recursive_expr = match &body[1] {
2407 Stmt::Return { value: Some(expr) } => *expr,
2408 _ => return None,
2409 };
2410
2411 let mut self_call_count = 0usize;
2414 let mut constant_sum = 0i64;
2415 if !cf_analyze_add_tree(
2416 recursive_expr,
2417 func_name,
2418 param_sym,
2419 &mut self_call_count,
2420 &mut constant_sum,
2421 ) {
2422 return None;
2423 }
2424
2425 if self_call_count != 2 {
2426 return None;
2427 }
2428
2429 Some(ClosedFormInfo {
2430 base: base_value,
2431 k: constant_sum,
2432 })
2433}
2434
2435fn cf_extract_literal_int(expr: &Expr) -> Option<i64> {
2436 if let Expr::Literal(crate::ast::stmt::Literal::Number(n)) = expr {
2437 Some(*n)
2438 } else {
2439 None
2440 }
2441}
2442
2443fn cf_is_identifier(expr: &Expr, sym: Symbol) -> bool {
2444 matches!(expr, Expr::Identifier(s) if *s == sym)
2445}
2446
2447fn cf_is_literal_int(expr: &Expr, val: i64) -> bool {
2448 matches!(expr, Expr::Literal(crate::ast::stmt::Literal::Number(n)) if *n == val)
2449}
2450
2451fn cf_is_self_call_with_decrement(expr: &Expr, func_name: Symbol, param_sym: Symbol) -> bool {
2452 use crate::ast::stmt::BinaryOpKind;
2453 if let Expr::Call { function, args } = expr {
2454 if *function != func_name || args.len() != 1 {
2455 return false;
2456 }
2457 if let Expr::BinaryOp {
2458 op: BinaryOpKind::Subtract,
2459 left,
2460 right,
2461 } = args[0]
2462 {
2463 cf_is_identifier(left, param_sym) && cf_is_literal_int(right, 1)
2464 } else {
2465 false
2466 }
2467 } else {
2468 false
2469 }
2470}
2471
2472fn cf_analyze_add_tree(
2475 expr: &Expr,
2476 func_name: Symbol,
2477 param_sym: Symbol,
2478 self_calls: &mut usize,
2479 constant_sum: &mut i64,
2480) -> bool {
2481 use crate::ast::stmt::BinaryOpKind;
2482 match expr {
2483 Expr::BinaryOp {
2484 op: BinaryOpKind::Add,
2485 left,
2486 right,
2487 } => {
2488 cf_analyze_add_tree(left, func_name, param_sym, self_calls, constant_sum)
2489 && cf_analyze_add_tree(right, func_name, param_sym, self_calls, constant_sum)
2490 }
2491 _ if cf_is_self_call_with_decrement(expr, func_name, param_sym) => {
2492 *self_calls += 1;
2493 true
2494 }
2495 _ => {
2496 if let Some(n) = cf_extract_literal_int(expr) {
2497 *constant_sum += n;
2498 true
2499 } else {
2500 false
2501 }
2502 }
2503 }
2504}
2505
2506pub(crate) struct ScalarizableSeq {
2515 pub elem_ty: String,
2516 pub len: usize,
2517}
2518
2519struct ScalarCand {
2520 elem_ty: String,
2521 len: usize,
2522 seen_use: bool,
2524 disqualified: bool,
2525}
2526
2527fn scalar_seq_elem_ty(value: &Expr, interner: &Interner) -> Option<String> {
2529 if let Expr::New {
2530 type_name,
2531 type_args,
2532 ..
2533 } = value
2534 {
2535 if matches!(interner.resolve(*type_name), "Seq" | "List") && type_args.len() == 1 {
2536 if let TypeExpr::Primitive(t) | TypeExpr::Named(t) = &type_args[0] {
2537 return match interner.resolve(*t) {
2538 "Int" | "Nat" => Some("i64".to_string()),
2539 "Float" => Some("f64".to_string()),
2540 "Bool" => Some("bool".to_string()),
2541 _ => None,
2542 };
2543 }
2544 }
2545 }
2546 None
2547}
2548
2549const MAX_SCALARIZE_LEN: usize = 64;
2551
2552pub(crate) fn collect_scalarizable_seqs(
2556 stmts: &[Stmt],
2557 interner: &Interner,
2558) -> HashMap<Symbol, ScalarizableSeq> {
2559 if !crate::optimize::active_config().is_on(crate::optimization::Opt::Scalarize) {
2561 return HashMap::new();
2562 }
2563 let mut cand: HashMap<Symbol, ScalarCand> = HashMap::new();
2564 scalar_walk_block(stmts, true, &mut cand, interner);
2565 let mut result: HashMap<Symbol, ScalarizableSeq> = cand
2566 .into_iter()
2567 .filter_map(|(sym, c)| {
2568 if c.disqualified || c.len == 0 || c.len > MAX_SCALARIZE_LEN {
2569 None
2570 } else {
2571 Some((
2572 sym,
2573 ScalarizableSeq {
2574 elem_ty: c.elem_ty,
2575 len: c.len,
2576 },
2577 ))
2578 }
2579 })
2580 .collect();
2581 crate::optimize::SwapClasses::of(stmts, interner).close_by(&mut result, interner, |x, y| {
2583 x.elem_ty == y.elem_ty && x.len == y.len
2584 });
2585 if !result.is_empty() {
2586 crate::optimize::mark_fired(crate::optimization::Opt::Scalarize);
2587 }
2588 result
2589}
2590
2591pub(crate) fn scalarizable_seq_symbols(
2600 stmts: &[Stmt],
2601 interner: &Interner,
2602) -> std::collections::HashSet<Symbol> {
2603 collect_scalarizable_seqs(stmts, interner)
2604 .into_keys()
2605 .collect()
2606}
2607
2608fn scalar_disq(cand: &mut HashMap<Symbol, ScalarCand>, sym: Symbol) {
2609 if let Some(c) = cand.get_mut(&sym) {
2610 c.disqualified = true;
2611 }
2612}
2613
2614pub(super) struct InterleaveGroup {
2624 pub members: Vec<Symbol>,
2626 pub len: usize,
2628 pub elem_ty: String,
2630}
2631
2632pub(super) fn collect_interleaved_groups(
2638 stmts: &[Stmt],
2639 scalarizable: &HashMap<Symbol, ScalarizableSeq>,
2640 interner: &Interner,
2641) -> Vec<InterleaveGroup> {
2642 if !crate::optimize::active_config().is_on(crate::optimization::Opt::Interleave) {
2644 return Vec::new();
2645 }
2646 if scalarizable.len() < 2 {
2647 return Vec::new();
2648 }
2649 let mut push_seq: Vec<Symbol> = Vec::new();
2652 for s in stmts {
2653 if let Stmt::Push { collection, .. } = s {
2654 if let Expr::Identifier(sym) = collection {
2655 if scalarizable.contains_key(sym) {
2656 push_seq.push(*sym);
2657 }
2658 }
2659 }
2660 }
2661 if push_seq.len() < 2 {
2662 return Vec::new();
2663 }
2664 let first = push_seq[0];
2666 let w = match push_seq.iter().skip(1).position(|&s| s == first) {
2667 Some(p) => p + 1,
2668 None => return Vec::new(),
2669 };
2670 if w < 2 || push_seq.len() % w != 0 {
2671 return Vec::new();
2672 }
2673 let group: Vec<Symbol> = push_seq[..w].to_vec();
2674 let mut seen = std::collections::HashSet::new();
2676 if !group.iter().all(|s| seen.insert(*s)) {
2677 return Vec::new();
2678 }
2679 let swaps = crate::optimize::SwapClasses::of(stmts, interner);
2681 if group.iter().any(|m| swaps.is_swapped(interner.resolve(*m))) {
2682 return Vec::new();
2683 }
2684 let rounds = push_seq.len() / w;
2686 for r in 0..rounds {
2687 for c in 0..w {
2688 if push_seq[r * w + c] != group[c] {
2689 return Vec::new();
2690 }
2691 }
2692 }
2693 if group.len() != scalarizable.len() {
2696 return Vec::new();
2697 }
2698 let elem_ty = scalarizable[&group[0]].elem_ty.clone();
2699 for m in &group {
2700 let info = &scalarizable[m];
2701 if info.elem_ty != elem_ty || info.len != rounds {
2702 return Vec::new();
2703 }
2704 }
2705 let force = std::env::var("LOGOS_AOS_FORCE")
2714 .map(|v| v == "1")
2715 .unwrap_or(false);
2716 let members: std::collections::HashSet<Symbol> = group.iter().copied().collect();
2717 if !force && block_has_const_member_index(stmts, &members) {
2718 crate::optimize::mark_preempted(
2721 crate::optimization::Opt::Scalarize,
2722 crate::optimization::Opt::Interleave,
2723 );
2724 crate::optimize::mark_preempted(
2725 crate::optimization::Opt::Unroll,
2726 crate::optimization::Opt::Interleave,
2727 );
2728 return Vec::new();
2729 }
2730 crate::optimize::mark_fired(crate::optimization::Opt::Interleave);
2731 vec![InterleaveGroup {
2732 members: group,
2733 len: rounds,
2734 elem_ty,
2735 }]
2736}
2737
2738fn block_has_const_member_index(
2741 stmts: &[Stmt],
2742 members: &std::collections::HashSet<Symbol>,
2743) -> bool {
2744 stmts
2745 .iter()
2746 .any(|s| stmt_has_const_member_index(s, members))
2747}
2748
2749fn is_member_const_index(
2750 collection: &Expr,
2751 index: &Expr,
2752 members: &std::collections::HashSet<Symbol>,
2753) -> bool {
2754 matches!(collection, Expr::Identifier(s) if members.contains(s))
2755 && matches!(index, Expr::Literal(Literal::Number(_)))
2756}
2757
2758fn stmt_has_const_member_index(s: &Stmt, members: &std::collections::HashSet<Symbol>) -> bool {
2759 match s {
2760 Stmt::SetIndex {
2761 collection,
2762 index,
2763 value,
2764 } => {
2765 is_member_const_index(collection, index, members)
2766 || expr_has_const_member_index(collection, members)
2767 || expr_has_const_member_index(index, members)
2768 || expr_has_const_member_index(value, members)
2769 }
2770 Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
2771 expr_has_const_member_index(value, members)
2772 }
2773 Stmt::Push { value, collection } => {
2774 expr_has_const_member_index(value, members)
2775 || expr_has_const_member_index(collection, members)
2776 }
2777 Stmt::Show { object, .. } => expr_has_const_member_index(object, members),
2778 Stmt::SetField { object, value, .. } => {
2779 expr_has_const_member_index(object, members)
2780 || expr_has_const_member_index(value, members)
2781 }
2782 Stmt::Give { object, recipient } => {
2783 expr_has_const_member_index(object, members)
2784 || expr_has_const_member_index(recipient, members)
2785 }
2786 Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
2787 expr_has_const_member_index(value, members)
2788 || expr_has_const_member_index(collection, members)
2789 }
2790 Stmt::RuntimeAssert { condition, .. } => expr_has_const_member_index(condition, members),
2791 Stmt::Return { value } => {
2792 matches!(value, Some(v) if expr_has_const_member_index(v, members))
2793 }
2794 Stmt::Call { args, .. } => args.iter().any(|a| expr_has_const_member_index(a, members)),
2795 Stmt::If {
2796 cond,
2797 then_block,
2798 else_block,
2799 } => {
2800 expr_has_const_member_index(cond, members)
2801 || block_has_const_member_index(then_block, members)
2802 || matches!(else_block, Some(eb) if block_has_const_member_index(eb, members))
2803 }
2804 Stmt::While { cond, body, .. } => {
2805 expr_has_const_member_index(cond, members)
2806 || block_has_const_member_index(body, members)
2807 }
2808 Stmt::Repeat { iterable, body, .. } => {
2809 expr_has_const_member_index(iterable, members)
2810 || block_has_const_member_index(body, members)
2811 }
2812 Stmt::Inspect { target, arms, .. } => {
2813 expr_has_const_member_index(target, members)
2814 || arms
2815 .iter()
2816 .any(|a| block_has_const_member_index(a.body, members))
2817 }
2818 _ => false,
2819 }
2820}
2821
2822fn expr_has_const_member_index(e: &Expr, members: &std::collections::HashSet<Symbol>) -> bool {
2823 match e {
2824 Expr::Index { collection, index } => {
2825 is_member_const_index(collection, index, members)
2826 || expr_has_const_member_index(collection, members)
2827 || expr_has_const_member_index(index, members)
2828 }
2829 Expr::Slice {
2830 collection,
2831 start,
2832 end,
2833 } => {
2834 expr_has_const_member_index(collection, members)
2835 || expr_has_const_member_index(start, members)
2836 || expr_has_const_member_index(end, members)
2837 }
2838 Expr::BinaryOp { left, right, .. } => {
2839 expr_has_const_member_index(left, members)
2840 || expr_has_const_member_index(right, members)
2841 }
2842 Expr::Not { operand } => expr_has_const_member_index(operand, members),
2843 Expr::Length { collection } => expr_has_const_member_index(collection, members),
2844 Expr::Contains { collection, value } => {
2845 expr_has_const_member_index(collection, members)
2846 || expr_has_const_member_index(value, members)
2847 }
2848 Expr::Union { left, right } | Expr::Intersection { left, right } => {
2849 expr_has_const_member_index(left, members)
2850 || expr_has_const_member_index(right, members)
2851 }
2852 Expr::Call { args, .. } | Expr::CallExpr { args, .. } => {
2853 args.iter().any(|a| expr_has_const_member_index(a, members))
2854 }
2855 Expr::FieldAccess { object, .. } => expr_has_const_member_index(object, members),
2856 Expr::Copy { expr } => expr_has_const_member_index(expr, members),
2857 Expr::Give { value } | Expr::OptionSome { value } => {
2858 expr_has_const_member_index(value, members)
2859 }
2860 Expr::WithCapacity { value, capacity } => {
2861 expr_has_const_member_index(value, members)
2862 || expr_has_const_member_index(capacity, members)
2863 }
2864 Expr::Range { start, end } => {
2865 expr_has_const_member_index(start, members) || expr_has_const_member_index(end, members)
2866 }
2867 Expr::List(items) | Expr::Tuple(items) => items
2868 .iter()
2869 .any(|i| expr_has_const_member_index(i, members)),
2870 Expr::InterpolatedString(parts) => parts.iter().any(|p| match p {
2871 crate::ast::stmt::StringPart::Expr { value, .. } => {
2872 expr_has_const_member_index(value, members)
2873 }
2874 _ => false,
2875 }),
2876 _ => false,
2877 }
2878}
2879
2880pub(super) struct AosTag {
2884 pub backing: String,
2885 pub col: usize,
2886 pub width: usize,
2887 pub len: usize,
2888 pub elem: String,
2889}
2890
2891pub(super) fn parse_aos_tag(ty: Option<&String>) -> Option<AosTag> {
2896 let rest = ty?.strip_prefix("__aos:")?;
2897 let mut parts = rest.split(':');
2898 let backing = parts.next()?.to_string();
2899 let col = parts.next()?.parse().ok()?;
2900 let width = parts.next()?.parse().ok()?;
2901 let len = parts.next()?.parse().ok()?;
2902 let elem = parts.next()?.to_string();
2903 Some(AosTag {
2904 backing,
2905 col,
2906 width,
2907 len,
2908 elem,
2909 })
2910}
2911
2912fn scalar_mark_use(cand: &mut HashMap<Symbol, ScalarCand>, sym: Symbol) {
2913 if let Some(c) = cand.get_mut(&sym) {
2914 c.seen_use = true;
2915 }
2916}
2917
2918fn scalar_note_access(e: &Expr, cand: &mut HashMap<Symbol, ScalarCand>) {
2921 if let Expr::Identifier(s) = e {
2922 scalar_mark_use(cand, *s);
2923 } else {
2924 scalar_note_value(e, cand);
2925 }
2926}
2927
2928fn scalar_note_value(e: &Expr, cand: &mut HashMap<Symbol, ScalarCand>) {
2932 match e {
2933 Expr::Identifier(s) => scalar_disq(cand, *s),
2934 Expr::Literal(_) | Expr::OptionNone => {}
2935 Expr::Index { collection, index } => {
2936 scalar_note_access(collection, cand);
2937 scalar_note_value(index, cand);
2938 }
2939 Expr::Length { collection } => scalar_note_access(collection, cand),
2940 Expr::Slice {
2941 collection,
2942 start,
2943 end,
2944 } => {
2945 if let Expr::Identifier(s) = collection {
2947 scalar_disq(cand, *s);
2948 } else {
2949 scalar_note_value(collection, cand);
2950 }
2951 scalar_note_value(start, cand);
2952 scalar_note_value(end, cand);
2953 }
2954 Expr::Contains { collection, value } => {
2955 if let Expr::Identifier(s) = collection {
2956 scalar_disq(cand, *s);
2957 } else {
2958 scalar_note_value(collection, cand);
2959 }
2960 scalar_note_value(value, cand);
2961 }
2962 Expr::Copy { expr } => {
2963 if let Expr::Identifier(s) = expr {
2964 scalar_disq(cand, *s);
2965 } else {
2966 scalar_note_value(expr, cand);
2967 }
2968 }
2969 Expr::BinaryOp { left, right, .. }
2970 | Expr::Union { left, right }
2971 | Expr::Intersection { left, right }
2972 | Expr::Range {
2973 start: left,
2974 end: right,
2975 } => {
2976 scalar_note_value(left, cand);
2977 scalar_note_value(right, cand);
2978 }
2979 Expr::Not { operand } => scalar_note_value(operand, cand),
2980 Expr::FieldAccess { object, .. } => scalar_note_value(object, cand),
2981 Expr::OptionSome { value } | Expr::Give { value } => scalar_note_value(value, cand),
2982 Expr::WithCapacity { value, capacity } => {
2983 scalar_note_value(value, cand);
2984 scalar_note_value(capacity, cand);
2985 }
2986 Expr::List(items) | Expr::Tuple(items) => {
2987 for it in items {
2988 scalar_note_value(it, cand);
2989 }
2990 }
2991 Expr::New { init_fields, .. } => {
2992 for (_, v) in init_fields {
2993 scalar_note_value(v, cand);
2994 }
2995 }
2996 Expr::NewVariant { fields, .. } => {
2997 for (_, v) in fields {
2998 scalar_note_value(v, cand);
2999 }
3000 }
3001 Expr::Call { args, .. } => {
3002 for a in args {
3003 scalar_note_value(a, cand);
3004 }
3005 }
3006 Expr::CallExpr { callee, args } => {
3007 scalar_note_value(callee, cand);
3008 for a in args {
3009 scalar_note_value(a, cand);
3010 }
3011 }
3012 Expr::InterpolatedString(parts) => {
3013 for p in parts {
3014 if let crate::ast::stmt::StringPart::Expr { value, .. } = p {
3015 scalar_note_value(value, cand);
3016 }
3017 }
3018 }
3019 Expr::ManifestOf { zone } => scalar_note_value(zone, cand),
3020 Expr::ChunkAt { index, zone } => {
3021 scalar_note_value(index, cand);
3022 scalar_note_value(zone, cand);
3023 }
3024 _ => {
3029 for c in cand.values_mut() {
3030 c.disqualified = true;
3031 }
3032 }
3033 }
3034}
3035
3036fn scalar_walk_block(
3037 stmts: &[Stmt],
3038 top_level: bool,
3039 cand: &mut HashMap<Symbol, ScalarCand>,
3040 interner: &Interner,
3041) {
3042 for stmt in stmts {
3043 match stmt {
3044 Stmt::Let {
3045 var,
3046 value,
3047 mutable,
3048 ..
3049 } => {
3050 if top_level && *mutable {
3051 if let Some(elem) = scalar_seq_elem_ty(value, interner) {
3052 cand.insert(
3053 *var,
3054 ScalarCand {
3055 elem_ty: elem,
3056 len: 0,
3057 seen_use: false,
3058 disqualified: false,
3059 },
3060 );
3061 continue;
3062 }
3063 }
3064 if let Expr::Identifier(s) = value {
3066 scalar_disq(cand, *s);
3067 } else {
3068 scalar_note_value(value, cand);
3069 }
3070 }
3071 Stmt::Push { value, collection } => {
3072 if let Expr::Identifier(s) = value {
3074 scalar_disq(cand, *s);
3075 } else {
3076 scalar_note_value(value, cand);
3077 }
3078 if let Expr::Identifier(x) = collection {
3079 let nested_or_used = {
3080 match cand.get(x) {
3081 Some(c) => !top_level || c.seen_use || c.disqualified,
3082 None => false,
3083 }
3084 };
3085 if cand.contains_key(x) {
3086 if nested_or_used {
3087 scalar_disq(cand, *x);
3088 } else if let Some(c) = cand.get_mut(x) {
3089 c.len += 1;
3090 }
3091 }
3092 } else {
3093 scalar_note_value(collection, cand);
3094 }
3095 }
3096 Stmt::SetIndex {
3097 collection,
3098 index,
3099 value,
3100 } => {
3101 if let Expr::Identifier(x) = collection {
3102 scalar_mark_use(cand, *x);
3103 } else {
3104 scalar_note_value(collection, cand);
3105 }
3106 scalar_note_value(index, cand);
3107 scalar_note_value(value, cand);
3108 }
3109 Stmt::Set { target, value } => {
3110 scalar_disq(cand, *target);
3112 if let Expr::Identifier(s) = value {
3113 scalar_disq(cand, *s);
3114 } else {
3115 scalar_note_value(value, cand);
3116 }
3117 }
3118 Stmt::Pop { collection, .. } => {
3119 if let Expr::Identifier(x) = collection {
3120 scalar_disq(cand, *x);
3121 } else {
3122 scalar_note_value(collection, cand);
3123 }
3124 }
3125 Stmt::Add { collection, value } | Stmt::Remove { collection, value } => {
3126 if let Expr::Identifier(x) = collection {
3127 scalar_disq(cand, *x);
3128 } else {
3129 scalar_note_value(collection, cand);
3130 }
3131 scalar_note_value(value, cand);
3132 }
3133 Stmt::Show { object, recipient } => {
3134 scalar_note_value(object, cand);
3135 scalar_note_value(recipient, cand);
3136 }
3137 Stmt::Give { object, recipient } => {
3138 if let Expr::Identifier(s) = object {
3139 scalar_disq(cand, *s);
3140 } else {
3141 scalar_note_value(object, cand);
3142 }
3143 scalar_note_value(recipient, cand);
3144 }
3145 Stmt::Return { value: Some(v) } => {
3146 if let Expr::Identifier(s) = v {
3147 scalar_disq(cand, *s);
3148 } else {
3149 scalar_note_value(v, cand);
3150 }
3151 }
3152 Stmt::SetField { object, value, .. } => {
3153 scalar_note_value(object, cand);
3154 scalar_note_value(value, cand);
3155 }
3156 Stmt::If {
3157 cond,
3158 then_block,
3159 else_block,
3160 } => {
3161 scalar_note_value(cond, cand);
3162 scalar_walk_block(then_block, false, cand, interner);
3163 if let Some(eb) = else_block {
3164 scalar_walk_block(eb, false, cand, interner);
3165 }
3166 }
3167 Stmt::While { cond, body, .. } => {
3168 scalar_note_value(cond, cand);
3169 scalar_walk_block(body, false, cand, interner);
3170 }
3171 Stmt::Repeat { iterable, body, .. } => {
3172 if let Expr::Identifier(x) = iterable {
3173 scalar_disq(cand, *x);
3174 } else {
3175 scalar_note_value(iterable, cand);
3176 }
3177 scalar_walk_block(body, false, cand, interner);
3178 }
3179 Stmt::Inspect { target, arms, .. } => {
3180 scalar_note_value(target, cand);
3181 for arm in arms {
3182 scalar_walk_block(&arm.body, false, cand, interner);
3183 }
3184 }
3185 Stmt::RuntimeAssert { condition, .. } => scalar_note_value(condition, cand),
3186 Stmt::Call { args, .. } => {
3187 for a in args {
3188 if let Expr::Identifier(s) = a {
3189 scalar_disq(cand, *s);
3190 } else {
3191 scalar_note_value(a, cand);
3192 }
3193 }
3194 }
3195 Stmt::Zone { body, .. } => scalar_walk_block(body, false, cand, interner),
3196 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
3197 scalar_walk_block(tasks, false, cand, interner)
3198 }
3199 Stmt::Splice { body } => scalar_walk_block(body, top_level, cand, interner),
3202 Stmt::Swap { a, b } => {
3205 scalar_mark_use(cand, *a);
3206 scalar_mark_use(cand, *b);
3207 }
3208 Stmt::FunctionDef { .. } => {}
3210 other => {
3213 let touched = crate::optimize::Mentions::of_stmt(other);
3214 for (sym, c) in cand.iter_mut() {
3215 if touched.touches(interner.resolve(*sym), interner) {
3216 c.disqualified = true;
3217 }
3218 }
3219 }
3220 }
3221 }
3222}