Skip to main content

logicaffeine_compile/optimize/
effects.rs

1use std::collections::{HashMap, HashSet};
2
3use crate::analysis::DiscoveryPass;
4use crate::arena::Arena;
5use crate::arena_ctx::AstContext;
6use crate::ast::stmt::{Expr, Stmt};
7use crate::drs::WorldState;
8use crate::error::ParseError;
9use crate::intern::{Interner, Symbol};
10use crate::lexer::Lexer;
11use crate::parser::Parser;
12
13use crate::analysis::callgraph::CallGraph;
14
15/// Effect classification for expressions, statements, and functions.
16///
17/// Effects form a lattice: Pure ⊂ Read ⊂ Write ⊂ IO ⊂ Unknown.
18/// Each EffectSet tracks the precise set of variables read/written,
19/// plus boolean flags for allocation, IO, security checks, divergence,
20/// and unknown (escape blocks).
21#[derive(Debug, Clone, Default)]
22pub struct EffectSet {
23    pub reads: HashSet<Symbol>,
24    pub writes: HashSet<Symbol>,
25    pub allocates: bool,
26    pub io: bool,
27    pub security_check: bool,
28    pub diverges: bool,
29    pub unknown: bool,
30    /// Nondeterministic choice — `Select`, `Try*` (depends on instantaneous buffer
31    /// state), and cooperative `StopTask`. The outcome is not a function of the inputs,
32    /// so a function carrying one must never be specialized on a static argument.
33    pub nondet: bool,
34    /// Spawns or communicates across a concurrency boundary — `LaunchTask`, `CreatePipe`,
35    /// `Spawn`, and the networking statements. Opaque to the partial evaluator.
36    pub concurrent: bool,
37}
38
39impl EffectSet {
40    pub fn pure() -> Self {
41        Self::default()
42    }
43
44    pub fn read(sym: Symbol) -> Self {
45        let mut s = Self::default();
46        s.reads.insert(sym);
47        s
48    }
49
50    pub fn write(sym: Symbol) -> Self {
51        let mut s = Self::default();
52        s.writes.insert(sym);
53        s
54    }
55
56    pub fn io() -> Self {
57        let mut s = Self::default();
58        s.io = true;
59        s
60    }
61
62    pub fn alloc() -> Self {
63        let mut s = Self::default();
64        s.allocates = true;
65        s
66    }
67
68    pub fn unknown() -> Self {
69        let mut s = Self::default();
70        s.unknown = true;
71        s
72    }
73
74    pub fn nondet() -> Self {
75        let mut s = Self::default();
76        s.nondet = true;
77        s
78    }
79
80    pub fn concurrent() -> Self {
81        let mut s = Self::default();
82        s.concurrent = true;
83        s
84    }
85
86    pub fn is_pure(&self) -> bool {
87        self.reads.is_empty()
88            && self.writes.is_empty()
89            && !self.allocates
90            && !self.io
91            && !self.security_check
92            && !self.diverges
93            && !self.unknown
94            && !self.nondet
95            && !self.concurrent
96    }
97
98    /// Join two EffectSets (union of all effects).
99    pub fn join(&mut self, other: &EffectSet) {
100        self.reads.extend(&other.reads);
101        self.writes.extend(&other.writes);
102        self.allocates |= other.allocates;
103        self.io |= other.io;
104        self.security_check |= other.security_check;
105        self.diverges |= other.diverges;
106        self.unknown |= other.unknown;
107        self.nondet |= other.nondet;
108        self.concurrent |= other.concurrent;
109    }
110}
111
112/// Environment tracking effects for variables and functions.
113///
114/// For each variable binding (`Let x be <expr>`), tracks the EffectSet
115/// of the bound expression. For each function, tracks the aggregate
116/// EffectSet of its body.
117pub struct EffectEnv {
118    /// Binding-level effects: var_sym → effect of the bound expression
119    bindings: HashMap<Symbol, EffectSet>,
120    /// Statement-level aggregate effects (joined across all statements)
121    aggregate: EffectSet,
122    /// Function-level effects: fn_sym → aggregate effect of body
123    functions: HashMap<Symbol, EffectSet>,
124    /// Interner for name resolution in test queries
125    interner: Interner,
126}
127
128impl EffectEnv {
129    /// Analyze already-parsed statements and return the EffectEnv.
130    pub fn from_stmts(stmts: &[Stmt<'_>], interner: &Interner) -> Self {
131        let env = analyze_program(stmts, interner);
132        Self {
133            bindings: env.bindings,
134            aggregate: env.aggregate,
135            functions: env.functions,
136            interner: interner.clone(),
137        }
138    }
139
140    /// Analyze a complete LOGOS source and return the EffectEnv.
141    pub fn analyze_source(source: &str) -> Result<Self, ParseError> {
142        let mut interner = Interner::new();
143        let mut lexer = Lexer::new(source, &mut interner);
144        let tokens = lexer.tokenize();
145
146        let type_registry = {
147            let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
148            let result = discovery.run_full();
149            result.types
150        };
151
152        let mut world_state = WorldState::new();
153        let expr_arena = Arena::new();
154        let term_arena = Arena::new();
155        let np_arena = Arena::new();
156        let sym_arena = Arena::new();
157        let role_arena = Arena::new();
158        let pp_arena = Arena::new();
159        let stmt_arena = Arena::new();
160        let _compile_facts = super::facts::scope();
161        let imperative_expr_arena = Arena::new();
162        let type_expr_arena = Arena::new();
163
164        let ast_ctx = AstContext::with_types(
165            &expr_arena,
166            &term_arena,
167            &np_arena,
168            &sym_arena,
169            &role_arena,
170            &pp_arena,
171            &stmt_arena,
172            &imperative_expr_arena,
173            &type_expr_arena,
174        );
175
176        let mut parser = Parser::new(
177            tokens,
178            &mut world_state,
179            &mut interner,
180            ast_ctx,
181            type_registry,
182        );
183        let stmts = parser.parse_program()?;
184
185        let env = analyze_program(&stmts, &interner);
186
187        Ok(Self {
188            bindings: env.bindings,
189            aggregate: env.aggregate,
190            functions: env.functions,
191            interner,
192        })
193    }
194
195    fn resolve_name(&self, name: &str) -> Option<Symbol> {
196        // Try to find the symbol in the interner
197        self.interner.lookup(name)
198    }
199
200    pub fn is_binding_pure(&self, var_name: &str) -> bool {
201        if let Some(sym) = self.resolve_name(var_name) {
202            self.bindings.get(&sym).map(|e| e.is_pure()).unwrap_or(true)
203        } else {
204            true
205        }
206    }
207
208    pub fn binding_reads(&self, var_name: &str, read_var: &str) -> bool {
209        let var_sym = match self.resolve_name(var_name) {
210            Some(s) => s,
211            None => return false,
212        };
213        let read_sym = match self.resolve_name(read_var) {
214            Some(s) => s,
215            None => return false,
216        };
217        self.bindings
218            .get(&var_sym)
219            .map(|e| e.reads.contains(&read_sym))
220            .unwrap_or(false)
221    }
222
223    pub fn binding_allocates(&self, var_name: &str) -> bool {
224        if let Some(sym) = self.resolve_name(var_name) {
225            self.bindings
226                .get(&sym)
227                .map(|e| e.allocates)
228                .unwrap_or(false)
229        } else {
230            false
231        }
232    }
233
234    pub fn has_write_to(&self, var_name: &str) -> bool {
235        if let Some(sym) = self.resolve_name(var_name) {
236            self.aggregate.writes.contains(&sym)
237        } else {
238            false
239        }
240    }
241
242    pub fn has_io(&self) -> bool {
243        self.aggregate.io
244    }
245
246    pub fn has_unknown(&self) -> bool {
247        self.aggregate.unknown
248    }
249
250    pub fn has_security_check(&self) -> bool {
251        self.aggregate.security_check
252    }
253
254    pub fn may_diverge(&self) -> bool {
255        self.aggregate.diverges
256    }
257
258    pub fn function_is_pure(&self, fn_name: &str) -> bool {
259        if let Some(sym) = self.resolve_name(fn_name) {
260            self.functions
261                .get(&sym)
262                .map(|e| e.is_pure())
263                .unwrap_or(true)
264        } else {
265            true
266        }
267    }
268
269    pub fn function_has_io(&self, fn_name: &str) -> bool {
270        if let Some(sym) = self.resolve_name(fn_name) {
271            self.functions.get(&sym).map(|e| e.io).unwrap_or(false)
272        } else {
273            false
274        }
275    }
276
277    /// Whether the partial evaluator may specialize a call to `fn_name` on a static
278    /// argument. Reads, writes, allocation, and divergence are ordinary PE targets and
279    /// stay safe. IO already blocks specialization (the historical gate). Nondeterminism
280    /// and concurrency are the new exclusions: a concurrency / networking statement carries
281    /// expression arguments (a timeout, spawn args, a branch body) that reference the
282    /// static parameter, and the specializer's substitution does not enter those
283    /// statements — folding across one would drop the parameter and leave a dangling
284    /// reference. A `Check` (security_check) is deliberately *not* excluded: it is preserved
285    /// verbatim and never references a foldable parameter, so specializing across it is
286    /// sound (see `pe_effect_env_check_is_not_io`). Escape blocks (`unknown`) are handled by
287    /// the caller's separate `body_has_escape` guard.
288    /// Whether a call to `fn_name` may be RE-RUN from the start after a failure partway through —
289    /// what the native tier does when compiled code stops (a broken contract, `Fail with`, a zero
290    /// divisor): it hands the call back to bytecode, which raises the exact error at the exact
291    /// point. Sound only when nothing the first attempt did is observable: no IO (a `Show` would
292    /// print twice), no nondeterminism, no concurrency, nothing unknown. Divergence is exactly what
293    /// the replay is for, and reads/writes/allocation are private to the call.
294    pub fn function_is_replayable(&self, fn_name: &str) -> bool {
295        self.resolve_name(fn_name)
296            .and_then(|sym| self.functions.get(&sym))
297            .is_some_and(|e| !e.io && !e.nondet && !e.concurrent && !e.unknown)
298    }
299
300    pub fn function_is_specialization_safe(&self, fn_name: &str) -> bool {
301        if let Some(sym) = self.resolve_name(fn_name) {
302            match self.functions.get(&sym) {
303                Some(e) => !e.io && !e.nondet && !e.concurrent,
304                None => false,
305            }
306        } else {
307            false
308        }
309    }
310}
311
312// =============================================================================
313// Internal analysis
314// =============================================================================
315
316struct AnalysisResult {
317    bindings: HashMap<Symbol, EffectSet>,
318    aggregate: EffectSet,
319    functions: HashMap<Symbol, EffectSet>,
320}
321
322fn analyze_program(stmts: &[Stmt<'_>], interner: &Interner) -> AnalysisResult {
323    let callgraph = CallGraph::build(stmts, interner);
324
325    // Phase 1: Analyze function bodies
326    let mut functions: HashMap<Symbol, EffectSet> = HashMap::new();
327
328    // Collect all known function names first; builtins resolve through the interner.
329    let mut known_fns = KnownCallees::new(interner);
330    for stmt in stmts {
331        if let Stmt::FunctionDef { name, .. } = stmt {
332            known_fns.fns.insert(*name);
333        }
334    }
335
336    // Initialize all functions with their direct effects
337    for stmt in stmts {
338        if let Stmt::FunctionDef {
339            name,
340            body,
341            is_native,
342            params,
343            ..
344        } = stmt
345        {
346            if *is_native {
347                // Native functions: classify by name
348                let effects = classify_native_function(*name, interner);
349                functions.insert(*name, effects);
350            } else {
351                let mut effects = analyze_block_effects_with(body, &known_fns);
352                // Remove parameter reads — reading a parameter is not a side effect
353                for (param_sym, _) in params {
354                    effects.reads.remove(param_sym);
355                }
356                functions.insert(*name, effects);
357            }
358        }
359    }
360
361    // Fixed-point: propagate effects through call graph
362    let mut changed = true;
363    while changed {
364        changed = false;
365        for scc in &callgraph.sccs {
366            // For each SCC, join effects of all callees
367            for &fn_sym in scc {
368                if callgraph.native_fns.contains(&fn_sym) {
369                    continue;
370                }
371                let callees = callgraph.edges.get(&fn_sym).cloned().unwrap_or_default();
372                for callee in &callees {
373                    if let Some(callee_effects) = functions.get(callee).cloned() {
374                        if let Some(fn_effects) = functions.get_mut(&fn_sym) {
375                            let before = format!("{:?}", fn_effects);
376                            fn_effects.join(&callee_effects);
377                            let after = format!("{:?}", fn_effects);
378                            if before != after {
379                                changed = true;
380                            }
381                        }
382                    }
383                }
384            }
385
386            // Recursive SCCs always diverge
387            if scc.len() > 1 {
388                for &fn_sym in scc {
389                    if let Some(fn_effects) = functions.get_mut(&fn_sym) {
390                        if !fn_effects.diverges {
391                            fn_effects.diverges = true;
392                            changed = true;
393                        }
394                    }
395                }
396            } else if scc.len() == 1 {
397                let fn_sym = scc[0];
398                if callgraph
399                    .edges
400                    .get(&fn_sym)
401                    .map(|e| e.contains(&fn_sym))
402                    .unwrap_or(false)
403                {
404                    if let Some(fn_effects) = functions.get_mut(&fn_sym) {
405                        if !fn_effects.diverges {
406                            fn_effects.diverges = true;
407                            changed = true;
408                        }
409                    }
410                }
411            }
412        }
413    }
414
415    // Phase 2: Analyze main body and bindings
416    let mut bindings: HashMap<Symbol, EffectSet> = HashMap::new();
417    let mut aggregate = EffectSet::default();
418
419    for stmt in stmts {
420        let effects = analyze_stmt_effects(stmt, &functions);
421        aggregate.join(&effects);
422
423        // Track per-binding effects
424        if let Stmt::Let { var, value, .. } = stmt {
425            let expr_effects = analyze_expr_effects_core(value, &known_fns);
426            bindings.insert(*var, expr_effects);
427        }
428    }
429
430    AnalysisResult {
431        bindings,
432        aggregate,
433        functions,
434    }
435}
436
437/// The callees whose effects the analysis can name: the program's own functions (their effects
438/// flow through the call-graph fixpoint) and the builtins (their [`BuiltinEffect`] classification).
439/// A call to anything else is `unknown`.
440#[derive(Default)]
441struct KnownCallees<'i> {
442    fns: HashSet<Symbol>,
443    interner: Option<&'i Interner>,
444}
445
446impl<'i> KnownCallees<'i> {
447    fn new(interner: &'i Interner) -> Self {
448        KnownCallees {
449            fns: HashSet::new(),
450            interner: Some(interner),
451        }
452    }
453
454    /// Join what calling `function` can do into `effects`.
455    fn apply_call(&self, function: Symbol, effects: &mut EffectSet) {
456        use crate::semantics::builtins::{builtin_from_name, BuiltinEffect};
457        if self.fns.contains(&function) {
458            return;
459        }
460        match self
461            .interner
462            .and_then(|i| builtin_from_name(i.resolve(function)))
463        {
464            Some(b) => match b.effect() {
465                BuiltinEffect::Pure => {}
466                BuiltinEffect::Fallible => effects.diverges = true,
467                BuiltinEffect::Nondeterministic => effects.nondet = true,
468                BuiltinEffect::Effectful => effects.io = true,
469            },
470            None => effects.unknown = true,
471        }
472    }
473}
474
475fn analyze_block_effects_with(stmts: &[Stmt<'_>], known_fns: &KnownCallees<'_>) -> EffectSet {
476    let mut result = EffectSet::default();
477    for stmt in stmts {
478        let effects = analyze_stmt_effects_initial(stmt, known_fns);
479        result.join(&effects);
480    }
481    result
482}
483
484/// Analyze statement effects during initial function body analysis.
485/// known_fns tracks which functions are defined in the program so calls to them
486/// don't get marked as unknown (the fixed-point iteration handles transitive effects).
487fn analyze_stmt_effects_initial(stmt: &Stmt<'_>, known_fns: &KnownCallees<'_>) -> EffectSet {
488    analyze_stmt_effects_core(stmt, None, known_fns)
489}
490
491fn analyze_stmt_effects(stmt: &Stmt<'_>, functions: &HashMap<Symbol, EffectSet>) -> EffectSet {
492    analyze_stmt_effects_core(stmt, Some(functions), &KnownCallees::default())
493}
494
495fn analyze_stmt_effects_core(
496    stmt: &Stmt<'_>,
497    functions: Option<&HashMap<Symbol, EffectSet>>,
498    known_fns: &KnownCallees<'_>,
499) -> EffectSet {
500    match stmt {
501        Stmt::Let { var, value, .. } => {
502            let mut effects = analyze_expr_effects_core(value, known_fns);
503            effects.writes.insert(*var);
504            effects
505        }
506        Stmt::Set { target, value } => {
507            let mut effects = analyze_expr_effects_core(value, known_fns);
508            effects.writes.insert(*target);
509            effects
510        }
511        Stmt::Call { function, args } => {
512            let mut effects = EffectSet::default();
513            for arg in args {
514                effects.join(&analyze_expr_effects_core(arg, known_fns));
515            }
516            if let Some(fns) = functions {
517                if let Some(fn_effects) = fns.get(function) {
518                    effects.join(fn_effects);
519                } else {
520                    known_fns.apply_call(*function, &mut effects);
521                }
522            } else {
523                known_fns.apply_call(*function, &mut effects);
524            }
525            effects
526        }
527        Stmt::If {
528            cond,
529            then_block,
530            else_block,
531        } => {
532            let mut effects = analyze_expr_effects_core(cond, known_fns);
533            let then_effects = analyze_block_effects_with(then_block, known_fns);
534            effects.join(&then_effects);
535            if let Some(else_b) = else_block {
536                let else_effects = analyze_block_effects_with(else_b, known_fns);
537                effects.join(&else_effects);
538            }
539            effects
540        }
541        Stmt::While { cond, body, .. } => {
542            let mut effects = analyze_expr_effects_core(cond, known_fns);
543            let body_effects = analyze_block_effects_with(body, known_fns);
544            effects.join(&body_effects);
545            effects.diverges = true;
546            effects
547        }
548        Stmt::Repeat { iterable, body, .. } => {
549            let mut effects = analyze_expr_effects_core(iterable, known_fns);
550            let body_effects = analyze_block_effects_with(body, known_fns);
551            effects.join(&body_effects);
552            effects
553        }
554        Stmt::Return { value } => {
555            if let Some(v) = value {
556                analyze_expr_effects_core(v, known_fns)
557            } else {
558                EffectSet::pure()
559            }
560        }
561        Stmt::Show { object, .. } => {
562            let mut effects = analyze_expr_effects_core(object, known_fns);
563            effects.io = true;
564            effects
565        }
566        Stmt::Push { value, collection } => {
567            let mut effects = analyze_expr_effects_core(value, known_fns);
568            effects.join(&analyze_expr_effects_core(collection, known_fns));
569            if let Expr::Identifier(sym) = collection {
570                effects.writes.insert(*sym);
571            }
572            effects
573        }
574        Stmt::Pop { collection, into } => {
575            let mut effects = analyze_expr_effects_core(collection, known_fns);
576            if let Expr::Identifier(sym) = collection {
577                effects.writes.insert(*sym);
578            }
579            if let Some(into_sym) = into {
580                effects.writes.insert(*into_sym);
581            }
582            effects
583        }
584        Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
585            let mut effects = analyze_expr_effects_core(value, known_fns);
586            effects.join(&analyze_expr_effects_core(collection, known_fns));
587            if let Expr::Identifier(sym) = collection {
588                effects.writes.insert(*sym);
589            }
590            effects
591        }
592        Stmt::SetIndex {
593            collection,
594            index,
595            value,
596        } => {
597            let mut effects = analyze_expr_effects_core(value, known_fns);
598            effects.join(&analyze_expr_effects_core(index, known_fns));
599            if let Expr::Identifier(sym) = collection {
600                effects.writes.insert(*sym);
601            }
602            effects
603        }
604        Stmt::SetField { object, value, .. } => {
605            let mut effects = analyze_expr_effects_core(value, known_fns);
606            if let Expr::Identifier(sym) = object {
607                effects.writes.insert(*sym);
608            }
609            effects
610        }
611        Stmt::Give { object, recipient } => {
612            let mut effects = analyze_expr_effects_core(object, known_fns);
613            effects.join(&analyze_expr_effects_core(recipient, known_fns));
614            effects
615        }
616        Stmt::Escape { .. } => EffectSet::unknown(),
617        Stmt::Check { .. } => {
618            let mut effects = EffectSet::default();
619            effects.security_check = true;
620            effects
621        }
622        Stmt::RuntimeAssert {
623            condition, reason, ..
624        } => {
625            let mut effects = analyze_expr_effects_core(condition, known_fns);
626            if let Some(r) = reason {
627                effects.join(&analyze_expr_effects_core(r, known_fns));
628            }
629            effects
630        }
631        // `Fail with …` never completes normally.
632        Stmt::Fail { reason } => {
633            let mut effects = analyze_expr_effects_core(reason, known_fns);
634            effects.diverges = true;
635            effects
636        }
637        Stmt::FunctionDef { .. } | Stmt::StructDef { .. } => EffectSet::pure(),
638        Stmt::Inspect { target, arms, .. } => {
639            let mut effects = analyze_expr_effects_core(target, known_fns);
640            for arm in arms {
641                let arm_effects = analyze_block_effects_with(arm.body, known_fns);
642                effects.join(&arm_effects);
643            }
644            effects
645        }
646        Stmt::Zone { body, .. } => analyze_block_effects_with(body, known_fns),
647        // A `Reversibly:` block is output-transparent: its effects are exactly its body's effects
648        // (the reversible lowering changes no observable behaviour), so they bubble up unchanged.
649        Stmt::Reversibly { body } => analyze_block_effects_with(body, known_fns),
650        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
651            let mut effects = analyze_block_effects_with(tasks, known_fns);
652            effects.concurrent = true;
653            effects
654        }
655        Stmt::WriteFile { content, path } => {
656            let mut effects = analyze_expr_effects_core(content, known_fns);
657            effects.join(&analyze_expr_effects_core(path, known_fns));
658            effects.io = true;
659            effects
660        }
661        Stmt::SendMessage {
662            message,
663            destination,
664            ..
665        } => {
666            let mut effects = analyze_expr_effects_core(message, known_fns);
667            effects.join(&analyze_expr_effects_core(destination, known_fns));
668            effects.io = true;
669            effects
670        }
671        Stmt::StreamMessage {
672            values,
673            destination,
674        } => {
675            let mut effects = analyze_expr_effects_core(values, known_fns);
676            effects.join(&analyze_expr_effects_core(destination, known_fns));
677            effects.io = true;
678            effects
679        }
680        Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
681            let mut effects = analyze_expr_effects_core(object, known_fns);
682            effects.join(&analyze_expr_effects_core(amount, known_fns));
683            if let Expr::Identifier(sym) = object {
684                effects.writes.insert(*sym);
685            }
686            effects
687        }
688        Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
689            let mut effects = analyze_expr_effects_core(source, known_fns);
690            effects.join(&analyze_expr_effects_core(target, known_fns));
691            if let Expr::Identifier(sym) = target {
692                effects.writes.insert(*sym);
693            }
694            effects
695        }
696        Stmt::Sleep { milliseconds } => {
697            let mut effects = analyze_expr_effects_core(milliseconds, known_fns);
698            effects.io = true;
699            effects
700        }
701        Stmt::SendPipe { value, pipe } => {
702            let mut effects = analyze_expr_effects_core(value, known_fns);
703            effects.join(&analyze_expr_effects_core(pipe, known_fns));
704            effects.io = true;
705            effects.diverges = true;
706            effects.concurrent = true;
707            effects
708        }
709        Stmt::TrySendPipe {
710            value,
711            pipe,
712            result,
713        } => {
714            let mut effects = analyze_expr_effects_core(value, known_fns);
715            effects.join(&analyze_expr_effects_core(pipe, known_fns));
716            effects.io = true;
717            effects.concurrent = true;
718            // Success depends on instantaneous buffer state — nondeterministic.
719            effects.nondet = true;
720            if let Some(result_sym) = result {
721                effects.writes.insert(*result_sym);
722            }
723            effects
724        }
725        Stmt::ReceivePipe { pipe, var, .. } => {
726            let mut effects = analyze_expr_effects_core(pipe, known_fns);
727            effects.writes.insert(*var);
728            effects.io = true;
729            effects.diverges = true;
730            effects.concurrent = true;
731            effects
732        }
733        Stmt::ReadFrom { var, .. } => {
734            let mut effects = EffectSet::default();
735            effects.writes.insert(*var);
736            effects.io = true;
737            effects
738        }
739        // ----- Go-like concurrency: opaque effectful boundaries -----
740        Stmt::Select { branches } => {
741            // A Select is a nondeterministic choice over its ready branches. Its outcome
742            // is not a function of the inputs, and each branch body is part of the effect.
743            let mut effects = EffectSet::nondet();
744            for branch in branches {
745                match branch {
746                    crate::ast::stmt::SelectBranch::Receive { var, pipe, body } => {
747                        effects.join(&analyze_expr_effects_core(pipe, known_fns));
748                        effects.writes.insert(*var);
749                        effects.join(&analyze_block_effects_with(body, known_fns));
750                    }
751                    crate::ast::stmt::SelectBranch::Timeout { milliseconds, body } => {
752                        effects.join(&analyze_expr_effects_core(milliseconds, known_fns));
753                        effects.join(&analyze_block_effects_with(body, known_fns));
754                    }
755                }
756            }
757            effects.concurrent = true;
758            effects
759        }
760        Stmt::LaunchTask { args, .. } => {
761            let mut effects = EffectSet::concurrent();
762            for arg in args {
763                effects.join(&analyze_expr_effects_core(arg, known_fns));
764            }
765            effects
766        }
767        Stmt::LaunchTaskWithHandle { handle, args, .. } => {
768            let mut effects = EffectSet::concurrent();
769            effects.writes.insert(*handle);
770            for arg in args {
771                effects.join(&analyze_expr_effects_core(arg, known_fns));
772            }
773            effects
774        }
775        Stmt::CreatePipe { var, .. } => {
776            let mut effects = EffectSet::concurrent();
777            effects.allocates = true;
778            effects.writes.insert(*var);
779            effects
780        }
781        Stmt::TryReceivePipe { var, pipe } => {
782            // Non-blocking receive: returns value-or-Nothing depending on instantaneous
783            // buffer state — nondeterministic, and it binds `var`.
784            let mut effects = analyze_expr_effects_core(pipe, known_fns);
785            effects.writes.insert(*var);
786            effects.io = true;
787            effects.nondet = true;
788            effects.concurrent = true;
789            effects
790        }
791        Stmt::StopTask { handle } => {
792            // Cooperative cancellation — scheduling-dependent.
793            let mut effects = analyze_expr_effects_core(handle, known_fns);
794            effects.nondet = true;
795            effects.concurrent = true;
796            effects
797        }
798        Stmt::CloseChannel { channel } => {
799            // Closing wakes parked receivers — a concurrency-visible effect. Deterministic on the
800            // scheduler (unlike `Stop`), so it is not marked nondet.
801            let mut effects = analyze_expr_effects_core(channel, known_fns);
802            effects.concurrent = true;
803            effects
804        }
805        Stmt::AwaitTask { handle, result } => {
806            // Joining a task reads the handle, may bind the result, and is a scheduling point.
807            let mut effects = analyze_expr_effects_core(handle, known_fns);
808            if let Some(r) = result {
809                effects.writes.insert(*r);
810            }
811            effects.concurrent = true;
812            effects
813        }
814        Stmt::Spawn { name, .. } => {
815            let mut effects = EffectSet::concurrent();
816            effects.writes.insert(*name);
817            effects
818        }
819        // ----- Networking over the relay: I/O boundaries -----
820        Stmt::AwaitMessage {
821            source,
822            into,
823            view: _,
824            stream: _,
825        } => {
826            let mut effects = analyze_expr_effects_core(source, known_fns);
827            effects.writes.insert(*into);
828            effects.io = true;
829            effects.concurrent = true;
830            effects
831        }
832        Stmt::Listen { address, secure } | Stmt::ConnectTo { address, secure } => {
833            let mut effects = analyze_expr_effects_core(address, known_fns);
834            if let Some(bind) = secure {
835                // The pad path is evaluated too; fold in its (read-only) effects for completeness.
836                let pad_fx = analyze_expr_effects_core(bind.pad, known_fns);
837                effects.io |= pad_fx.io;
838                effects.concurrent |= pad_fx.concurrent;
839                effects.writes.extend(pad_fx.writes);
840            }
841            effects.io = true;
842            effects.concurrent = true;
843            effects
844        }
845        Stmt::LetPeerAgent { var, address } => {
846            let mut effects = analyze_expr_effects_core(address, known_fns);
847            effects.writes.insert(*var);
848            effects.io = true;
849            effects.concurrent = true;
850            effects
851        }
852        Stmt::Sync { var, topic } => {
853            // Subscribe + auto-publish-on-mutation + auto-merge-on-receive: reads and
854            // writes the synced CRDT and talks to the relay.
855            let mut effects = analyze_expr_effects_core(topic, known_fns);
856            effects.reads.insert(*var);
857            effects.writes.insert(*var);
858            effects.io = true;
859            effects.concurrent = true;
860            effects
861        }
862        Stmt::Mount { var, path } => {
863            let mut effects = analyze_expr_effects_core(path, known_fns);
864            effects.writes.insert(*var);
865            effects.io = true;
866            effects
867        }
868        // ----- CRDT structural mutations not covered above -----
869        Stmt::AppendToSequence { sequence, value } => {
870            let mut effects = analyze_expr_effects_core(sequence, known_fns);
871            effects.join(&analyze_expr_effects_core(value, known_fns));
872            if let Expr::Identifier(sym) = sequence {
873                effects.writes.insert(*sym);
874            }
875            effects
876        }
877        Stmt::ResolveConflict { object, value, .. } => {
878            let mut effects = analyze_expr_effects_core(object, known_fns);
879            effects.join(&analyze_expr_effects_core(value, known_fns));
880            if let Expr::Identifier(sym) = object {
881                effects.writes.insert(*sym);
882            }
883            effects
884        }
885        _ => EffectSet::default(),
886    }
887}
888
889fn analyze_expr_effects_core(expr: &Expr<'_>, known_fns: &KnownCallees<'_>) -> EffectSet {
890    match expr {
891        // Evaluating a view evaluates its holes; its handler blocks run later, on events.
892        // Reading the page is an effect on the host, not a pure computation.
893        Expr::Dom(q) => {
894            let mut effects = EffectSet::io();
895            if let Some(sel) = q.selector() {
896                effects.join(&analyze_expr_effects_core(sel, known_fns));
897            }
898            effects
899        }
900        Expr::View(v) => {
901            let mut effects = EffectSet::default();
902            for e in v.exprs_and_blocks().0 {
903                effects.join(&analyze_expr_effects_core(e, known_fns));
904            }
905            effects
906        }
907        Expr::Literal(_) | Expr::OptionNone => EffectSet::pure(),
908        Expr::Identifier(sym) => EffectSet::read(*sym),
909        Expr::BinaryOp { left, right, .. } => {
910            let mut effects = analyze_expr_effects_core(left, known_fns);
911            effects.join(&analyze_expr_effects_core(right, known_fns));
912            effects
913        }
914        Expr::Not { operand } => analyze_expr_effects_core(operand, known_fns),
915        Expr::Call { function, args, .. } => {
916            let mut effects = EffectSet::default();
917            for arg in args {
918                effects.join(&analyze_expr_effects_core(arg, known_fns));
919            }
920            // A program function's effects propagate through the fixpoint; a builtin's are its
921            // classification; anything else is unknown.
922            known_fns.apply_call(*function, &mut effects);
923            effects
924        }
925        Expr::CallExpr { callee, args } => {
926            let mut effects = analyze_expr_effects_core(callee, known_fns);
927            for arg in args {
928                effects.join(&analyze_expr_effects_core(arg, known_fns));
929            }
930            effects.unknown = true;
931            effects
932        }
933        Expr::Index { collection, index } => {
934            let mut effects = analyze_expr_effects_core(collection, known_fns);
935            effects.join(&analyze_expr_effects_core(index, known_fns));
936            effects
937        }
938        Expr::Slice {
939            collection,
940            start,
941            end,
942        } => {
943            let mut effects = analyze_expr_effects_core(collection, known_fns);
944            effects.join(&analyze_expr_effects_core(start, known_fns));
945            effects.join(&analyze_expr_effects_core(end, known_fns));
946            effects
947        }
948        Expr::Length { collection } => analyze_expr_effects_core(collection, known_fns),
949        Expr::Contains { collection, value } => {
950            let mut effects = analyze_expr_effects_core(collection, known_fns);
951            effects.join(&analyze_expr_effects_core(value, known_fns));
952            effects
953        }
954        Expr::Union { left, right }
955        | Expr::Intersection { left, right }
956        | Expr::Range {
957            start: left,
958            end: right,
959        } => {
960            let mut effects = analyze_expr_effects_core(left, known_fns);
961            effects.join(&analyze_expr_effects_core(right, known_fns));
962            effects
963        }
964        Expr::Copy { expr } => {
965            let mut effects = analyze_expr_effects_core(expr, known_fns);
966            effects.allocates = true;
967            effects
968        }
969        Expr::Give { value } => analyze_expr_effects_core(value, known_fns),
970        Expr::FieldAccess { object, .. } => analyze_expr_effects_core(object, known_fns),
971        Expr::OptionSome { value } => analyze_expr_effects_core(value, known_fns),
972        Expr::ManifestOf { zone } => analyze_expr_effects_core(zone, known_fns),
973        Expr::ChunkAt { index, zone } => {
974            let mut effects = analyze_expr_effects_core(index, known_fns);
975            effects.join(&analyze_expr_effects_core(zone, known_fns));
976            effects
977        }
978        Expr::New { init_fields, .. } => {
979            let mut effects = EffectSet::default();
980            effects.allocates = true;
981            for (_, val) in init_fields {
982                effects.join(&analyze_expr_effects_core(val, known_fns));
983            }
984            effects
985        }
986        Expr::NewVariant { fields, .. } => {
987            let mut effects = EffectSet::default();
988            for (_, val) in fields {
989                effects.join(&analyze_expr_effects_core(val, known_fns));
990            }
991            effects
992        }
993        Expr::WithCapacity { value, capacity } => {
994            let mut effects = analyze_expr_effects_core(value, known_fns);
995            effects.join(&analyze_expr_effects_core(capacity, known_fns));
996            effects.allocates = true;
997            effects
998        }
999        Expr::List(elems) | Expr::Tuple(elems) => {
1000            let mut effects = EffectSet::default();
1001            for elem in elems {
1002                effects.join(&analyze_expr_effects_core(elem, known_fns));
1003            }
1004            effects
1005        }
1006        Expr::Closure { .. } => EffectSet::pure(),
1007        Expr::Escape { .. } => EffectSet::unknown(),
1008        Expr::InterpolatedString(parts) => {
1009            let mut effects = EffectSet::default();
1010            for part in parts {
1011                if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
1012                    effects.join(&analyze_expr_effects_core(value, known_fns));
1013                }
1014            }
1015            effects
1016        }
1017    }
1018}
1019
1020/// Classify a native function's effects by name.
1021fn classify_native_function(sym: Symbol, interner: &Interner) -> EffectSet {
1022    let name = interner.resolve(sym);
1023    match name {
1024        // Pure functions
1025        "parseInt" | "parseFloat" | "decimal" | "complex" | "conjugate" | "re" | "im"
1026        | "modular" | "quantity" | "convert" | "money" | "uuid" | "uuid_nil" | "uuid_max"
1027        | "uuid_v3" | "uuid_v5" | "uuid_version" | "uuid_dns" | "uuid_url" | "uuid_oid"
1028        | "uuid_x500" | "md5" | "sha1" | "text_bytes" | "uuid_bytes" | "uuid_from_bytes"
1029        | "parse_timestamp" | "format_timestamp" | "year_of" | "month_of" | "day_of"
1030        | "weekday_of" | "hour_of" | "minute_of" | "second_of" | "week_of" | "quarter_of"
1031        | "date_of" | "time_of" | "seconds_between" | "months_between" | "years_between"
1032        | "add_seconds" | "in_zone" | "local_instant" | "makeDate" | "makeMoment" | "abs"
1033        | "min" | "max" | "sqrt" | "floor" | "ceil" | "round" | "pow" | "log" | "sin" | "cos"
1034        | "tan" | "toString" | "toInt" | "toFloat" | "trim" | "uppercase" | "lowercase"
1035        | "split" | "join" | "replace" | "startsWith" | "endsWith" | "substring" | "charAt"
1036        | "indexOf" | "lastIndexOf" | "repeat" => EffectSet::pure(),
1037        // IO functions
1038        "args" | "show" | "readLine" | "sleep" | "readFile" | "writeFile" | "print" | "println"
1039        | "eprintln" | "exit" => EffectSet::io(),
1040        // Alloc functions
1041        "newSeq" | "newMap" | "newSet" | "copy" | "clone" | "mapOf" | "setOf" | "repeatSeq" => {
1042            EffectSet::alloc()
1043        }
1044        // Default: IO (conservative for unknown natives)
1045        _ => EffectSet::io(),
1046    }
1047}
1048
1049#[cfg(test)]
1050#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/effects/concurrency_effect_tests.rs"]
1051mod concurrency_effect_tests;