diff --git a/docs/result.md b/docs/result.md index b9779110..8782ab92 100644 --- a/docs/result.md +++ b/docs/result.md @@ -66,8 +66,97 @@ Ok type; the error type must match without implicit conversion. Root scripts, non-Result-returning functions, non-Result operands, optional Result operands, and incompatible error types reject `?`. `T?` remains an optional type, and `object?.field` remains optional access. Other parser dialects do not gain -this syntax unless they enable the Result dialect capability. There are no -`unwrap`, `map`, `and_then`, generic Try traits, or guest throw/catch/finally here. +this syntax unless they enable the Result dialect capability. There is no implicit +error conversion, generic Try trait, or guest throw/catch/finally. + +## Combine Result values + +`Result` provides `map`, `map_err`, `and_then`, `or_else`, `unwrap_or`, and +`unwrap_or_else`. `map` and `map_err` transform only their selected channel; +`and_then` keeps the receiver's error type, and `or_else` keeps the receiver's +success type. `unwrap_or` returns the success payload or an eager fallback +value; `unwrap_or_else` returns the success payload or the value produced by an +error callback. + +The receiver is evaluated once. The method argument is evaluated once in +left-to-right order, and the callback body runs only for the selected payload +branch. A callback expression is still created by the normal call semantics even +when that body is not invoked; do not rely on skipping its construction or +captured values. `unwrap_or` evaluates its fallback eagerly, even when the +receiver is `Ok`. `unwrap_or_else` evaluates the callback body lazily, only for +`Err`. The callback may be a closure or an existing function value, with exact +parameter and return types. + +```rss +// expected: 16 +fn build(flag: bool) -> Result { + if flag => { Result::Ok(2) } else => { Result::Err("bad") } +} +fn relay(flag: bool) -> Result { + let value = build(flag); + let combined: Result = value + .map(|item| item + 1) + .map_err(|error| 8) + .and_then(|item| Result::Ok(item * 3)) + .or_else(|error| Result::Ok(error - 1)); + combined +} +let ok_result = relay(true); +let err_result = relay(false); +let ok_value: int = match ok_result { + Result::Ok(value) => value, + Result::Err(error) => -1, +}; +let err_value: int = match err_result { + Result::Ok(value) => value, + Result::Err(error) => -1, +}; +ok_value + err_value; +``` + +The Ok path maps `2` to `3` and then to `9`. The Err path maps the string error +`"bad"` to `8`, then recovers with `or_else` to `7`. Both channels flow through +the same chain from left to right. + +`unwrap_or` is eager, while `unwrap_or_else` is lazy: + +```rss +// expected: 83 +let ok_value: Result = Result::Ok(11); +let err_eager: Result = Result::Err(2); +let err_lazy: Result = Result::Err(2); +let eager_ok: int = ok_value.unwrap_or(20); +let eager_err: int = err_eager.unwrap_or(30); +let lazy_err: int = err_lazy.unwrap_or_else(|error| error + 40); +eager_ok + eager_err + lazy_err; +``` + +`map_err` changes only the error type. Because `?` requires the enclosing +function's error type to match exactly, the explicit conversion must happen +before `?`; no `From` conversion or special Try implementation is inserted: + +```rss +// expected: 7 +fn load() -> Result { + Result::Err("bad") +} +fn convert(error: string) -> int { + 7 +} +fn relay() -> Result { + let value: int = load().map_err(convert)?; + Result::Ok(value) +} +let result = relay(); +match result { + Result::Ok(value) => value, + Result::Err(error) => error, +}; +``` + +The `?` operand has error type `int` after `map_err`; `relay` also returns +`Result`. The original string error becomes `7` before propagation, +and the final match observes that propagated error. ## Ownership and cleanup: explicit normal close, automatic Err cleanup @@ -95,6 +184,24 @@ typed API; storing a numeric handle or an externally held container is not an ownership declaration. Unresolved publication ownership quarantines execution and new publications until explicit scope shutdown/reset actually completes. +The combination methods follow the same ownership contract. `map`, `map_err`, +`and_then`, and `or_else` consume the receiver; the selected payload owner is +transferred once, and the unselected branch receives no second copy. A selected +guest resource remains observable until it is returned or explicitly closed, and +an Err payload consumed by a typed native take has one final destination. +`unwrap_or` takes its fallback eagerly, so a resource-typed fallback is refused +statically. An inline closure that moves a resource into its capture cell is also +refused. Temporary resource-capturing factories, callable sources made +shared-mutable by a recorded writer, and unbound generic positions that could +later be instantiated with a resource are treated conservatively as unknown +ownership and refused when no owner can be proven. Resource-free callbacks, +named function values, and an already-bound caller-owned callable remain +supported. These are compile-time ownership refusals; they are not evidence that +every rejected shape leaks at runtime, and not every temporary resource factory +is accepted. The VM-aware SDK integration test proves that path's own publication +and cleanup behavior; it does not certify every lower-level entry point for +arbitrary combinator shapes. + The maintained generated-host example in [`result_sdk_try_integration_tests.rs`](../tests/result_sdk_try_integration_tests.rs) uses `ResourceOwned`, `ResourceRef<'_, T>`, `HostResourceType`, @@ -127,11 +234,77 @@ invalid representation, and outer `VmError` never become catchable guest Errs. Host descriptors and build-script schema generation preserve both parameters and resource effects. Borrowed-resource returns remain rejected, including nested GuestResult combinations. Existing HTTP/database business return types are not -implicitly migrated. +implicitly migrated. `Result<(), E>` continues to use the existing Null-backed +unit payload; a distinct guest `()` schema is outside this contract. + +### Calling an RSS Result from Rust + +The typed callback for an exported RSS function returns the same +`GuestResult` wrapper. The following file is a complete standalone Rust +program: it compiles an RSS export, initializes a `Store`, runs the program to +`Halted`, obtains the typed callback, and converts both guest variants into a +native Rust `Result` through the existing `From` implementation. `main` returns +`Box` so `?` can carry compilation, VM, store, and callback +setup failures. + +```rust +use vm::{GuestResult, Store, Vm, VmResult, VmStatus}; + +fn main() -> Result<(), Box> { + let compiled = vm::compile_source( + "pub fn echo(value: Result) -> Result { value }", + )?; + let mut store = Store::new( + Vm::new(compiled.program.with_local_count(compiled.locals)), + (), + ); + store.vm_mut().set_fuel(100_000); + assert_eq!(store.run()?, VmStatus::Halted); + + let callback = store.script_callback_by_name::< + (GuestResult,), + GuestResult, + >("echo")?; + + let ok: Result = callback.call(&mut store, (GuestResult::Ok(0),))?.into(); + assert_eq!(ok, Ok(0)); + + let err: Result = callback + .call(&mut store, (GuestResult::Err(String::new()),))? + .into(); + assert_eq!(err, Err(String::new())); + + let native: VmResult> = callback + .call(&mut store, (GuestResult::Ok(7),)) + .map(Into::into); + assert_eq!(native?, Ok(7)); + + let guest_error: VmResult> = callback + .call(&mut store, (GuestResult::Err("guest failure".into()),)) + .map(Into::into); + assert_eq!(guest_error?, Err("guest failure".to_string())); + + Ok(()) +} +``` + +`Ok(0)` and `Err("")` remain distinct because the carrier's Boolean `tag` +selects the branch; payload truthiness does not. The explicit +`VmResult>` binding keeps the transport channel visible: +the outer result reports fatal VM, transport, fuel, cancellation, or ownership +failures, while a guest error is only the inner `Result::Err` and is never +wrapped as an outer `VmError`. The example constructs no document-specific host +module, mock, or resource token. + +### Ordinary and resource-owning callbacks + +Context-free callbacks use `script_callback_by_name` with +`IntoScriptValue` / `ScriptResult`. Resource-owning callbacks use +`vm_script_callback_by_name` with `VmScriptValue` / `VmScriptArgs` and invoke +through `call_with_vm` while the VM is halted. That VM-aware path keeps a live +`ScriptValueContext` for typed publication and resource ownership and is the +entry for callbacks returning `ResourceOwned`. -Ordinary context-free callbacks use `IntoScriptValue` / `ScriptResult` and -`script_callback_by_name`. Resource-owning callbacks use `VmScriptValue`, -`VmScriptArgs`, and a live `ScriptValueContext` through the VM-aware callback API. Use the generated descriptor's exact catalog; host-call admission validates the selected payload before entering a guest body, and typed host return validation runs before the guest continues. Callback handles are Store/VM/Program-bound and diff --git a/docs/result_callback_example.rs b/docs/result_callback_example.rs new file mode 100644 index 00000000..a157f2bc --- /dev/null +++ b/docs/result_callback_example.rs @@ -0,0 +1,38 @@ +use vm::{GuestResult, Store, Vm, VmResult, VmStatus}; + +fn main() -> Result<(), Box> { + let compiled = vm::compile_source( + "pub fn echo(value: Result) -> Result { value }", + )?; + let mut store = Store::new( + Vm::new(compiled.program.with_local_count(compiled.locals)), + (), + ); + store.vm_mut().set_fuel(100_000); + assert_eq!(store.run()?, VmStatus::Halted); + + let callback = store.script_callback_by_name::< + (GuestResult,), + GuestResult, + >("echo")?; + + let ok: Result = callback.call(&mut store, (GuestResult::Ok(0),))?.into(); + assert_eq!(ok, Ok(0)); + + let err: Result = callback + .call(&mut store, (GuestResult::Err(String::new()),))? + .into(); + assert_eq!(err, Err(String::new())); + + let native: VmResult> = callback + .call(&mut store, (GuestResult::Ok(7),)) + .map(Into::into); + assert_eq!(native?, Ok(7)); + + let guest_error: VmResult> = callback + .call(&mut store, (GuestResult::Err("guest failure".into()),)) + .map(Into::into); + assert_eq!(guest_error?, Err("guest failure".to_string())); + + Ok(()) +} diff --git a/src/compiler/codegen.rs b/src/compiler/codegen.rs index af9a9ead..386bf72c 100644 --- a/src/compiler/codegen.rs +++ b/src/compiler/codegen.rs @@ -1177,6 +1177,15 @@ impl Compiler { span, .. } => self.compile_result_try(value, *value_slot, *payload_slot, exit_cleanup, *span)?, + Expr::ResultMethod { span, .. } => { + return Err(CompileError::StrictTypingRequired { + line: None, + source_name: None, + detail: "unresolved Result combinator method reached code generation" + .to_string(), + span: Some(*span), + }); + } } Ok(()) } diff --git a/src/compiler/frontends/mod.rs b/src/compiler/frontends/mod.rs index 11c89069..abc38081 100644 --- a/src/compiler/frontends/mod.rs +++ b/src/compiler/frontends/mod.rs @@ -962,6 +962,16 @@ fn remap_result_expr_spans(expr: &mut super::ir::Expr, map: &impl Fn(&mut Span)) remap_result_expr_spans(ok_expr, map); remap_result_expr_spans(err_expr, map); } + Expr::ResultMethod { + receiver, + argument, + span, + .. + } => { + map(span); + remap_result_expr_spans(receiver, map); + remap_result_expr_spans(argument, map); + } Expr::OptionalGet { container, key, .. } => { remap_result_expr_spans(container, map); remap_result_expr_spans(key, map); @@ -2419,7 +2429,7 @@ mod lowered_provenance_remap_tests { /// slice helper `Len` calls) keeps `None` ids. #[cfg(test)] mod postfix_provenance_tests { - use crate::compiler::ir::{Expr, ParsedCallTarget, SemanticNodeId, Stmt}; + use crate::compiler::ir::{Expr, ParsedCallTarget, ResultMethod, SemanticNodeId, Stmt}; use crate::compiler::source_map::Span; use crate::compiler::{CompileSourceFileOptions, SharedParserOptions}; @@ -2610,8 +2620,9 @@ mod postfix_provenance_tests { } /// `.unwrap_or(d)` records the member token as callee, the full - /// `o.unwrap_or(5)` expr span, an `Unresolved` target, and the - /// `OptionUnwrapOr` node carries the same id. + /// `o.unwrap_or(5)` expr span, an `Unresolved` target, and the current + /// `ResultMethod` carrier node carries the same id. Non-Result receivers + /// lower to the pre-existing `OptionUnwrapOr` nullable path with that id. #[test] fn unwrap_or_records_member_callee_and_node_id() { let source = "let o = null;\no.unwrap_or(5);\n"; @@ -2632,10 +2643,14 @@ mod postfix_provenance_tests { }) .expect("expr stmt"); match expr { - Expr::OptionUnwrapOr { semantic_id, .. } => { + Expr::ResultMethod { + method: ResultMethod::UnwrapOr, + semantic_id, + .. + } => { assert_eq!(*semantic_id, Some(unwrap.id), "node shares site id") } - other => panic!("expected OptionUnwrapOr, got {other:?}"), + other => panic!("expected ResultMethod UnwrapOr, got {other:?}"), } } diff --git a/src/compiler/ir.rs b/src/compiler/ir.rs index df3b9815..e04f17fc 100644 --- a/src/compiler/ir.rs +++ b/src/compiler/ir.rs @@ -533,6 +533,64 @@ pub enum MatchTypePattern { Map, } +/// The Result combinator methods that keep a typed, structured shape until +/// the Result type owner resolves the receiver's schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ResultMethod { + Map, + MapErr, + AndThen, + OrElse, + UnwrapOr, + UnwrapOrElse, +} + +impl ResultMethod { + pub(crate) fn name(self) -> &'static str { + match self { + Self::Map => "map", + Self::MapErr => "map_err", + Self::AndThen => "and_then", + Self::OrElse => "or_else", + Self::UnwrapOr => "unwrap_or", + Self::UnwrapOrElse => "unwrap_or_else", + } + } + + pub(crate) fn from_member(member: &str) -> Option { + match member { + "map" => Some(Self::Map), + "map_err" => Some(Self::MapErr), + "and_then" => Some(Self::AndThen), + "or_else" => Some(Self::OrElse), + "unwrap_or" => Some(Self::UnwrapOr), + "unwrap_or_else" => Some(Self::UnwrapOrElse), + _ => None, + } + } + + /// `unwrap_or` keeps the pre-existing nullable lowering when the receiver + /// is not a `Result`. + pub(crate) fn retains_option_lowering_on_non_result(self) -> bool { + matches!(self, Self::UnwrapOr) + } +} + +/// Parser-assigned evaluation slots for a [`Expr::ResultMethod`]. +/// +/// `receiver` and `argument` receive the receiver/callback evaluation results +/// in source order; `ok_binding`/`err_binding` receive the selected `Result` +/// payload in the lowered match. The lowered block declares the receiver and +/// argument local schemas explicitly so strict typing validates the callback +/// body against the contextually expected callable signature. +#[derive(Clone, Copy, Debug)] +pub struct ResultMethodSlots { + pub receiver: LocalSlot, + pub argument: LocalSlot, + pub ok_binding: LocalSlot, + pub err_binding: Option, +} + #[derive(Clone, Debug)] pub enum Expr { Null, @@ -709,6 +767,24 @@ pub enum Expr { span: Span, semantic_id: Option, }, + /// A postfix Result combinator method preserved from source until the + /// Result type owner resolves the receiver's actual schema. + /// + /// The parser keeps the receiver and the callback/fallback argument as + /// structured children plus their evaluation slots; only the Result + /// resolver decides whether the receiver is a `Result` (and lowers + /// the call into an ordinary typed `ResultMatch`) or whether + /// `.unwrap_or(...)` keeps the pre-existing nullable lowering. A + /// non-Result receiver never has its ordinary member-call semantics + /// stolen by the method name at parse time. + ResultMethod { + method: ResultMethod, + receiver: Box, + argument: Box, + slots: ResultMethodSlots, + span: Span, + semantic_id: Option, + }, /// Postfix `?`. Evaluates `value` once. Ok continues as `T`; Err returns /// the active carrier from the lexical function through the existing `Ret`. ResultTry { @@ -742,6 +818,12 @@ impl Expr { visit(err_expr); } Expr::ResultTry { value, .. } => visit(value), + Expr::ResultMethod { + receiver, argument, .. + } => { + visit(receiver); + visit(argument); + } _ => {} } } diff --git a/src/compiler/lifetime/availability.rs b/src/compiler/lifetime/availability.rs index a0157f55..4926fc96 100644 --- a/src/compiler/lifetime/availability.rs +++ b/src/compiler/lifetime/availability.rs @@ -1286,6 +1286,27 @@ impl AvailabilityAnalyzer { Ok(out) } Expr::ResultQuery { value, .. } => self.analyze_expr_to_owned(value, state, line), + // Unresolved combinator carriers only reach analysis when host + // resolution already failed; model their evaluation order and + // hidden-local bindings without lowering. + Expr::ResultMethod { + receiver, + argument, + slots, + .. + } => { + let mut out = self.analyze_expr(receiver, state, line)?; + self.mark_owned_value_reads_moved(receiver, &mut out); + self.mark_available(&mut out, slots.receiver, line)?; + out = self.analyze_expr(argument, &out, line)?; + self.mark_owned_value_reads_moved(argument, &mut out); + self.mark_available(&mut out, slots.argument, line)?; + self.mark_available(&mut out, slots.ok_binding, line)?; + if let Some(slot) = slots.err_binding { + self.mark_available(&mut out, slot, line)?; + } + Ok(out) + } Expr::ResultTry { value, value_slot, .. } => { @@ -1837,7 +1858,8 @@ impl AvailabilityAnalyzer { other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { let mut found = false; other.visit_result_children(|child| found |= self.expr_contains_owned_local(child)); found @@ -2427,6 +2449,29 @@ impl AvailabilityAnalyzer { semantic_id: *semantic_id, }) } + Expr::ResultMethod { + method, + receiver, + argument, + slots, + span, + semantic_id, + } => { + let (receiver, mut receiver_state) = + self.rewrite_expr_and_state(receiver, false, state, 1)?; + self.mark_owned_value_reads_moved(&receiver, &mut receiver_state); + self.mark_available(&mut receiver_state, slots.receiver, 1)?; + let argument = + self.rewrite_expr_ownership_inner(argument, false, &receiver_state)?; + Ok(Expr::ResultMethod { + method: *method, + receiver: Box::new(receiver), + argument: Box::new(argument), + slots: *slots, + span: *span, + semantic_id: *semantic_id, + }) + } Expr::Block { .. } => self.rewrite_expr_for_ownership_with_state(expr, state, 0), Expr::Null | Expr::Int(_) diff --git a/src/compiler/lifetime/availability/captures.rs b/src/compiler/lifetime/availability/captures.rs index 370f3d48..ca21f7e1 100644 --- a/src/compiler/lifetime/availability/captures.rs +++ b/src/compiler/lifetime/availability/captures.rs @@ -625,7 +625,8 @@ impl AvailabilityAnalyzer { other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { other.visit_result_children(|child| { self.capture_mode_for_expr(child, captured_slot, context, implicit, scan); }); diff --git a/src/compiler/lifetime/availability/consumption.rs b/src/compiler/lifetime/availability/consumption.rs index 5b6dd040..923349d7 100644 --- a/src/compiler/lifetime/availability/consumption.rs +++ b/src/compiler/lifetime/availability/consumption.rs @@ -277,7 +277,8 @@ pub(super) fn expr_uses_slot(expr: &Expr, slot: LocalSlot) -> bool { other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { let mut used = false; other.visit_result_children(|child| used |= expr_uses_slot(child, slot)); if let Expr::ResultTry { exit_cleanup, .. } = other { @@ -285,6 +286,12 @@ pub(super) fn expr_uses_slot(expr: &Expr, slot: LocalSlot) -> bool { .iter() .any(|(cleanup_slot, _)| *cleanup_slot == slot); } + if let Expr::ResultMethod { slots, .. } = other { + used |= slots.receiver == slot + || slots.argument == slot + || slots.ok_binding == slot + || slots.err_binding == Some(slot); + } used } Expr::Block { stmts, expr } => { @@ -640,7 +647,8 @@ pub(super) fn collect_consumed_positions_from_expr( other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { other.visit_result_children(|child| { collect_consumed_positions_from_expr( child, diff --git a/src/compiler/lifetime/liveness.rs b/src/compiler/lifetime/liveness.rs index b43865dc..a73d692a 100644 --- a/src/compiler/lifetime/liveness.rs +++ b/src/compiler/lifetime/liveness.rs @@ -678,7 +678,8 @@ impl LivenessRewriter { other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { other.visit_result_children(|child| { self.add_expr_uses_impl(child, live, conservative) }); @@ -687,6 +688,10 @@ impl LivenessRewriter { self.mark_live(live, *slot); } } + if let Expr::ResultMethod { slots, .. } = other { + self.mark_live(live, slots.receiver); + self.mark_live(live, slots.argument); + } } Expr::Block { stmts, expr } => { let live_out = if conservative { @@ -1280,6 +1285,21 @@ impl LocalSlotAllocator { } self.collect_expr_constraints(value, &live_during, protected_slots)?; } + Expr::ResultMethod { + receiver, + argument, + slots, + .. + } => { + self.add_slot_live_edges(slots.receiver, &live_during); + self.add_slot_live_edges(slots.argument, &live_during); + self.add_slot_live_edges(slots.ok_binding, &live_during); + if let Some(slot) = slots.err_binding { + self.add_slot_live_edges(slot, &live_during); + } + self.collect_expr_constraints(receiver, &live_during, protected_slots)?; + self.collect_expr_constraints(argument, &live_during, protected_slots)?; + } Expr::ResultMatch { value, value_slot, @@ -1573,6 +1593,21 @@ impl LocalSlotAllocator { } self.collect_expr_footprint(value, set, stack); } + Expr::ResultMethod { + receiver, + argument, + slots, + .. + } => { + self.mark_set_slot(set, slots.receiver); + self.mark_set_slot(set, slots.argument); + self.mark_set_slot(set, slots.ok_binding); + if let Some(slot) = slots.err_binding { + self.mark_set_slot(set, slot); + } + self.collect_expr_footprint(receiver, set, stack); + self.collect_expr_footprint(argument, set, stack); + } Expr::ResultMatch { value, value_slot, @@ -1950,7 +1985,8 @@ fn collect_persistent_closure_sources_from_expr(expr: &Expr, slots: &mut BTreeSe other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } - | Expr::ResultTry { .. }) => { + | Expr::ResultTry { .. } + | Expr::ResultMethod { .. }) => { other.visit_result_children(|child| { collect_persistent_closure_sources_from_expr(child, slots) }); @@ -2181,6 +2217,21 @@ fn remap_expr_slots(expr: &mut Expr, mapping: &[LocalSlot]) -> Result<(), ParseE remap_expr_slots(ok_expr, mapping)?; remap_expr_slots(err_expr, mapping)?; } + Expr::ResultMethod { + receiver, + argument, + slots, + .. + } => { + slots.receiver = remap_slot(slots.receiver, mapping)?; + slots.argument = remap_slot(slots.argument, mapping)?; + slots.ok_binding = remap_slot(slots.ok_binding, mapping)?; + if let Some(slot) = slots.err_binding.as_mut() { + *slot = remap_slot(*slot, mapping)?; + } + remap_expr_slots(receiver, mapping)?; + remap_expr_slots(argument, mapping)?; + } Expr::Block { stmts, expr } => { for nested in stmts { remap_stmt_slots(nested, mapping)?; diff --git a/src/compiler/linker.rs b/src/compiler/linker.rs index b8ab97ee..1ce18a49 100644 --- a/src/compiler/linker.rs +++ b/src/compiler/linker.rs @@ -378,6 +378,12 @@ fn remap_expression_type_names(expression: &mut Expr, names: &HashMap { + remap_expression_type_names(receiver, names); + remap_expression_type_names(argument, names); + } Expr::Block { stmts, expr } => { for statement in stmts { remap_statement_type_names(statement, names); @@ -1605,6 +1611,35 @@ fn remap_expr_indices( flat_index_by_symbol, )?; } + Expr::ResultMethod { + receiver, + argument, + slots, + semantic_id, + .. + } => { + slots.receiver = remap_local_index(slots.receiver, local_base)?; + slots.argument = remap_local_index(slots.argument, local_base)?; + slots.ok_binding = remap_local_index(slots.ok_binding, local_base)?; + if let Some(slot) = slots.err_binding.as_mut() { + *slot = remap_local_index(*slot, local_base)?; + } + rebase_semantic_id(semantic_id, node_offset); + remap_expr_indices( + receiver, + local_base, + node_offset, + function_map, + flat_index_by_symbol, + )?; + remap_expr_indices( + argument, + local_base, + node_offset, + function_map, + flat_index_by_symbol, + )?; + } Expr::Add(lhs, rhs) | Expr::Sub(lhs, rhs) | Expr::Mul(lhs, rhs) diff --git a/src/compiler/materialization.rs b/src/compiler/materialization.rs index 0c3a2431..2b257c54 100644 --- a/src/compiler/materialization.rs +++ b/src/compiler/materialization.rs @@ -488,6 +488,12 @@ impl Classifier { } self.expr(frame, default); } + Expr::ResultMethod { + receiver, argument, .. + } => { + self.expr(frame, receiver); + self.expr(frame, argument); + } other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } diff --git a/src/compiler/parser/expressions.rs b/src/compiler/parser/expressions.rs index 2f0a66c4..4a29b8ce 100644 --- a/src/compiler/parser/expressions.rs +++ b/src/compiler/parser/expressions.rs @@ -1340,12 +1340,44 @@ impl Parser { chain_start.lo, self.tokens[self.pos - 1].span.hi, ); - expr = self.build_option_unwrap_or_expr( + if self.dialect.allow_result_syntax() { + expr = self.build_result_method_expr( + ResultMethod::UnwrapOr, + expr, + fallback, + member_span, + expr_span, + )?; + } else { + expr = self.build_option_unwrap_or_expr( + expr, + fallback, + member_span, + expr_span, + "unwrap_or".to_string(), + )?; + } + } else if self.dialect.allow_result_syntax() + && self.check(&TokenKind::LParen) + && let Some(method) = ResultMethod::from_member(&member) + { + self.expect(&TokenKind::LParen, "expected '(' after Result method")?; + let argument = self.parse_expr()?; + self.expect( + &TokenKind::RParen, + "expected ')' after Result method argument", + )?; + let expr_span = Span::new( + chain_start.source_id, + chain_start.lo, + self.tokens[self.pos - 1].span.hi, + ); + expr = self.build_result_method_expr( + method, expr, - fallback, + argument, member_span, expr_span, - "unwrap_or".to_string(), )?; } else if self.dialect.allow_result_syntax() && (member == "is_ok" || member == "is_err") @@ -1716,6 +1748,47 @@ impl Parser { }) } + /// Build the structured, type-preserving carrier for a postfix Result + /// combinator. All evaluation/ binding slots are parser-assigned hidden + /// locals; the Result type owner later decides the actual semantics. + pub(super) fn build_result_method_expr( + &mut self, + method: ResultMethod, + receiver: Expr, + argument: Expr, + callee_span: Span, + expr_span: Span, + ) -> Result { + let semantic_id = self.alloc_call_id( + callee_span, + expr_span, + ParsedCallTarget::Unresolved, + method.name().to_string(), + false, + ); + let receiver_slot = self.allocate_hidden_local()?; + let argument_slot = self.allocate_hidden_local()?; + let ok_binding = self.allocate_hidden_local()?; + let err_binding = if method.retains_option_lowering_on_non_result() { + None + } else { + Some(self.allocate_hidden_local()?) + }; + Ok(Expr::ResultMethod { + method, + receiver: Box::new(receiver), + argument: Box::new(argument), + slots: ResultMethodSlots { + receiver: receiver_slot, + argument: argument_slot, + ok_binding, + err_binding, + }, + span: expr_span, + semantic_id, + }) + } + pub(super) fn bind_hidden_local_expr( &mut self, value_slot: LocalSlot, diff --git a/src/compiler/parser/mod.rs b/src/compiler/parser/mod.rs index 6fa9506f..c1460f71 100644 --- a/src/compiler/parser/mod.rs +++ b/src/compiler/parser/mod.rs @@ -29,8 +29,8 @@ use super::{ FunctionImpl, FunctionParam, FunctionRefSite, FunctionRefTarget, HostApiIrMetadata, LexerToken, LocalDeclSite, LocalRefSite, LocalSlot, MatchPattern, MatchTypePattern, ModuleNamespaceAlias, ParsedCallSite, ParsedCallTarget, ParsedLexicalScope, - ParsedSemanticIndex, ResolvedHostCall, ScopeId, SemanticNodeId, Stmt, StmtSpanSite, - StructDecl, StructDeclSite, TypeSchema, + ParsedSemanticIndex, ResolvedHostCall, ResultMethod, ResultMethodSlots, ScopeId, + SemanticNodeId, Stmt, StmtSpanSite, StructDecl, StructDeclSite, TypeSchema, }, }; diff --git a/src/compiler/pipeline.rs b/src/compiler/pipeline.rs index 3e004869..7feaf695 100644 --- a/src/compiler/pipeline.rs +++ b/src/compiler/pipeline.rs @@ -726,6 +726,21 @@ fn record_expr_local_debug_ranges( } record_expr_local_debug_ranges(default, line, ranges); } + Expr::ResultMethod { + receiver, + argument, + slots, + .. + } => { + note_local_use(ranges, slots.receiver, line); + note_local_use(ranges, slots.argument, line); + note_local_use(ranges, slots.ok_binding, line); + if let Some(slot) = slots.err_binding { + note_local_use(ranges, slot, line); + } + record_expr_local_debug_ranges(receiver, line, ranges); + record_expr_local_debug_ranges(argument, line, ranges); + } other @ (Expr::ResultConstruct { .. } | Expr::ResultQuery { .. } | Expr::ResultMatch { .. } @@ -3432,12 +3447,17 @@ mod tests { .1; for stmt in &mut parsed.stmts { if let Stmt::Let { - expr: Expr::OptionUnwrapOr { value, .. }, + expr: + Expr::ResultMethod { + method: crate::compiler::ir::ResultMethod::UnwrapOr, + receiver, + .. + }, .. } = stmt && let Expr::OptionalGet { field_projection, .. - } = value.as_mut() + } = receiver.as_mut() { *field_projection = true; } @@ -3459,6 +3479,47 @@ mod tests { assert!(record.get(&crate::Value::string("note")).is_none()); } + /// Runtime alias control for the nested projection test above: without + /// explicit field-projection intent, native `?.` keeps value mode and + /// the present non-copy child stays owned by the retained record. This + /// distinguishes producer-intent detachment from an unconditional copy + /// or alias change in the `unwrap_or` carrier. + #[test] + fn native_ir_nested_optional_value_mode_retains_child() { + let source = "struct Entry { note: string? }\nlet entry: Entry = { note: \"ready\" };\nlet note = (entry?.note).unwrap_or(\"fallback\");\nnote;"; + let parsed = crate::compiler::frontends::parse_source( + source, + SourceFlavor::RustScript, + &CompileSourceFileOptions::new(), + ) + .unwrap(); + let root = parsed + .local_bindings + .iter() + .find(|(name, _)| name == "entry") + .unwrap() + .1; + let compiled = compile_parsed_output( + source.to_string(), + parsed, + CompileBehavior::REPL, + TypingMode::Strict, + true, + ) + .unwrap(); + let mut machine = crate::Vm::new(compiled.program); + assert_eq!(machine.run().unwrap(), crate::VmStatus::Halted); + assert_eq!(machine.stack(), &[crate::Value::string("ready")]); + let crate::Value::Map(record) = &machine.locals()[root as usize] else { + panic!("record retained in REPL"); + }; + assert_eq!( + record.get(&crate::Value::string("note")), + Some(&crate::Value::string("ready")), + "value-mode `?.` retains container ownership: {record:?}" + ); + } + #[test] #[cfg(feature = "http-client")] fn ordered_argument_provenance_reaches_rejected_call_consumer() { diff --git a/src/compiler/result.rs b/src/compiler/result.rs index 11880b29..324dc584 100644 --- a/src/compiler/result.rs +++ b/src/compiler/result.rs @@ -5,12 +5,13 @@ //! allows null. This pass fills constructor schemas from annotations and //! rejects non-exhaustive or mistyped Result matches before bytecode emission. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; use super::CompileError; use super::ir::{ - AssignmentKind, ClosureExpr, Expr, FrontendIr, FunctionDecl, FunctionImpl, LocalSlot, Stmt, - TypeSchema, + AssignmentKind, ClosureExpr, Expr, FrontendIr, FunctionDecl, FunctionImpl, LocalSlot, + ResultMethod, ResultMethodSlots, SemanticNodeId, Stmt, TypeSchema, }; use super::source_map::Span; @@ -23,11 +24,42 @@ struct Env { function_list: Vec, function_impls: HashMap, struct_schemas: HashMap, + /// Local callable bindings captured for temporary-factory provenance. + /// Only callable-typed locals are recorded so ordinary value flow does not + /// retain expression clones in this pass. + local_defs: HashMap, + /// Callable source slots in the current producer lexical scope that may be + /// written through a shared capture cell. This is a persistent scope fact: + /// later assignments and branch joins must not re-establish a trusted + /// `Free` definition or target for those slots. + volatile_sources: HashSet, /// Return schema of the function or closure currently being resolved. /// `None` at root and inside a callable that does not return `Result`. lexical_return: Option, } +#[derive(Clone)] +struct LocalDefinition { + /// Capture provenance frozen when this value was bound. Reading an alias + /// or a closure-copied callable must not chase a newer definition of the + /// slot it was copied from. + capture: TemporaryCallableCapture, + /// Immutable callable target resolved at the binding point. Factory calls + /// through an alias resolve this frozen target rather than the slot's + /// current definition; `None` means the target is not independently + /// resolvable and call provenance is `Unknown`. + target: Option>, + /// Slot schemas at the definition point, so capture provenance stays + /// accurate after later bindings change the same slot map. + slots: HashMap, +} + +#[derive(Clone, Debug)] +enum CallableTarget { + Function(u16), + Closure(ClosureExpr), +} + pub(crate) fn resolve_result_types( ir: &mut FrontendIr, entry_local_types: &[super::typing::EntryLocalType], @@ -49,6 +81,8 @@ pub(crate) fn resolve_result_types( function_list, function_impls: ir.function_impls.clone(), struct_schemas: ir.struct_schemas.clone(), + local_defs: HashMap::new(), + volatile_sources: HashSet::new(), lexical_return: None, }; resolve_stmts(&mut ir.stmts, None, &mut env)?; @@ -66,6 +100,8 @@ fn resolve_function( env: &mut Env, ) -> Result<(), CompileError> { let saved = env.slots.clone(); + let saved_defs = env.local_defs.clone(); + let saved_volatile = std::mem::take(&mut env.volatile_sources); let saved_return = env.lexical_return.clone(); if let Some(function) = env.functions.get(&index).cloned() { env.lexical_return = function.return_schema.clone(); @@ -93,6 +129,8 @@ fn resolve_function( resolve_expr(&mut function_impl.body_expr, None, env)?; } env.slots = saved; + env.local_defs = saved_defs; + env.volatile_sources = saved_volatile; env.lexical_return = saved_return; Ok(()) } @@ -114,7 +152,14 @@ fn resolve_stmt( env: &mut Env, ) -> Result<(), CompileError> { match stmt { - Stmt::Noop { .. } | Stmt::FuncDecl { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => { + Stmt::Noop { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => Ok(()), + Stmt::FuncDecl { + index, has_impl, .. + } => { + if *has_impl { + let sources = function_capture_targets(*index, env); + mark_env_volatile_sources(env, sources); + } Ok(()) } Stmt::Let { @@ -140,6 +185,20 @@ fn resolve_stmt( { env.slots.insert(*index, schema); } + let is_callable = env + .slots + .get(index) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })); + if is_callable { + let definition = if env.volatile_sources.contains(index) { + volatile_definition(&env.slots) + } else { + callable_env_definition(expr, env) + }; + env.local_defs.insert(*index, definition); + } else { + env.local_defs.remove(index); + } Ok(()) } Stmt::Assign { @@ -156,6 +215,20 @@ fn resolve_stmt( if let Some(schema) = infer_schema(expr, env) { env.slots.insert(*index, schema); } + let is_callable = env + .slots + .get(index) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })); + if is_callable { + let definition = if env.volatile_sources.contains(index) { + volatile_definition(&env.slots) + } else { + callable_env_definition(expr, env) + }; + env.local_defs.insert(*index, definition); + } else { + env.local_defs.remove(index); + } Ok(()) } Stmt::ClosureLet { @@ -163,7 +236,13 @@ fn resolve_stmt( expected_schema, .. } => resolve_closure(closure, expected_schema.as_ref(), env), - Stmt::Expr { expr, .. } => resolve_expr(expr, None, env), + Stmt::Expr { expr, .. } => { + resolve_expr(expr, None, env)?; + let mut written = HashSet::new(); + collect_expr_writes(expr, &mut written); + invalidate_local_definitions(&mut env.local_defs, &written); + Ok(()) + } Stmt::IfElse { condition, then_branch, @@ -171,8 +250,21 @@ fn resolve_stmt( .. } => { resolve_expr(condition, Some(&TypeSchema::Bool), env)?; + let mut condition_writes = HashSet::new(); + collect_expr_writes(condition, &mut condition_writes); + invalidate_local_definitions(&mut env.local_defs, &condition_writes); + let before_defs = env.local_defs.clone(); + invalidate_local_definitions(&mut env.local_defs, &env.volatile_sources); resolve_stmts(then_branch, expected_tail.cloned(), env)?; - resolve_stmts(else_branch, expected_tail.cloned(), env) + let then_defs = env.local_defs.clone(); + env.local_defs = before_defs.clone(); + invalidate_local_definitions(&mut env.local_defs, &env.volatile_sources); + resolve_stmts(else_branch, expected_tail.cloned(), env)?; + let else_defs = env.local_defs.clone(); + let mut joined = join_definitions(&before_defs, &then_defs, &else_defs); + invalidate_local_definitions(&mut joined, &env.volatile_sources); + env.local_defs = joined; + Ok(()) } Stmt::For { init, @@ -184,16 +276,29 @@ fn resolve_stmt( resolve_stmt(init, None, env)?; resolve_expr(condition, Some(&TypeSchema::Bool), env)?; resolve_stmt(post, None, env)?; - resolve_stmts(body, None, env) + resolve_stmts(body, None, env)?; + let mut written = HashSet::new(); + collect_stmt_writes(init, &mut written); + collect_expr_writes(condition, &mut written); + collect_stmt_writes(post, &mut written); + collect_stmt_list_writes(body, &mut written); + invalidate_local_definitions(&mut env.local_defs, &written); + Ok(()) } Stmt::While { condition, body, .. } => { resolve_expr(condition, Some(&TypeSchema::Bool), env)?; - resolve_stmts(body, None, env) + resolve_stmts(body, None, env)?; + let mut written = HashSet::new(); + collect_expr_writes(condition, &mut written); + collect_stmt_list_writes(body, &mut written); + invalidate_local_definitions(&mut env.local_defs, &written); + Ok(()) } Stmt::Drop { index, .. } => { env.slots.remove(index); + env.local_defs.remove(index); Ok(()) } } @@ -240,6 +345,33 @@ fn resolve_expr( "is_ok/is_err", ) } + Expr::ResultMethod { + method, + receiver, + argument, + slots, + span, + semantic_id, + } => { + let receiver = std::mem::replace(receiver.as_mut(), Expr::Null); + let argument = std::mem::replace(argument.as_mut(), Expr::Null); + let lowered = resolve_method( + *method, + receiver, + argument, + *slots, + *span, + *semantic_id, + expected, + env, + )?; + *expr = lowered; + // The lowered branch already resolved its receiver, callback and + // arm payloads exactly once; re-walking the same tree would + // re-resolve nested closure bodies without their contextual + // callable schema. + Ok(()) + } Expr::ResultTry { value, operand_schema, @@ -266,91 +398,2597 @@ fn resolve_expr( default, .. } => { - resolve_expr(value, None, env)?; + resolve_expr(value, None, env)?; + for (_, arm) in arms { + resolve_expr(arm, expected, env)?; + } + resolve_expr(default, expected, env) + } + Expr::OptionalGet { container, key, .. } => { + resolve_expr(container, None, env)?; + resolve_expr(key, None, env) + } + Expr::OptionUnwrapOr { + value, fallback, .. + } => { + resolve_expr(value, None, env)?; + resolve_expr(fallback, expected, env) + } + Expr::Call(index, type_args, args, _, _) => { + let expected_args = super::typing::argument_schemas_for_call( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + *index, + type_args, + ) + .or_else(|| { + super::typing::expected_container_argument_schemas( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + *index, + args, + expected, + ) + }); + for (offset, arg) in args.iter_mut().enumerate() { + let expected_arg = expected_args + .as_ref() + .and_then(|schemas| schemas.get(offset)) + .and_then(|schema| schema.as_ref()); + resolve_expr(arg, expected_arg, env)?; + } + Ok(()) + } + Expr::LocalCall(slot, _, args, _) => { + let params = env.slots.get(slot).and_then(|schema| match schema { + TypeSchema::Callable { params, .. } => Some(params.clone()), + _ => None, + }); + for (offset, arg) in args.iter_mut().enumerate() { + let expected_arg = params.as_ref().and_then(|schemas| schemas.get(offset)); + resolve_expr(arg, expected_arg, env)?; + } + Ok(()) + } + Expr::ModuleCall(symbol, type_args, args, _) => { + let expected_args = env + .function_list + .iter() + .find(|function| function.symbol.as_ref() == Some(symbol)) + .and_then(|function| { + super::typing::argument_schemas_for_call( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + function.index, + type_args, + ) + }); + for (offset, arg) in args.iter_mut().enumerate() { + let expected_arg = expected_args + .as_ref() + .and_then(|schemas| schemas.get(offset)) + .and_then(|schema| schema.as_ref()); + resolve_expr(arg, expected_arg, env)?; + } + Ok(()) + } + Expr::Closure(closure) => resolve_closure(closure, expected, env), + Expr::ClosureCall(closure, args) => { + resolve_closure(closure, expected, env)?; + for arg in args.iter_mut() { + resolve_expr(arg, None, env)?; + } + Ok(()) + } + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) + | Expr::And(lhs, rhs) + | Expr::Or(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + resolve_expr(lhs, None, env)?; + resolve_expr(rhs, None, env) + } + Expr::Neg(inner) + | Expr::Not(inner) + | Expr::ToOwned(inner) + | Expr::Borrow(inner) + | Expr::BorrowMut(inner) => resolve_expr(inner, None, env), + Expr::FunctionRef(index, _) => { + let sources = function_capture_targets(*index, env); + mark_env_volatile_sources(env, sources); + Ok(()) + } + Expr::Null + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) + | Expr::ModuleFunctionRef(_, _) + | Expr::UnresolvedFunctionRef { .. } + | Expr::Var(_) + | Expr::MoveVar(_) + | Expr::MoveField { .. } + | Expr::MoveIndex { .. } => Ok(()), + } +} + +/// Resolve a structured Result combinator method into ordinary typed IR. +/// +/// The receiver is evaluated once and then the callback/fallback argument is +/// evaluated once, both before the branch is selected. The selected branch +/// reuses [`Expr::ResultMatch`] payload binding plus a typed +/// `Call`/`LocalCall`; `unwrap_or` keeps the eager fallback value in a hidden +/// local and only projects it from the Err arm, while `unwrap_or_else` calls +/// the callback lazily from the Err arm. +#[allow(clippy::too_many_arguments)] +fn resolve_method( + method: ResultMethod, + mut receiver: Expr, + mut argument: Expr, + slots: ResultMethodSlots, + span: Span, + semantic_id: Option, + expected: Option<&TypeSchema>, + env: &mut Env, +) -> Result { + let annotated = match expected { + None | Some(TypeSchema::Unknown) => None, + Some(schema) => Some(schema.clone()), + }; + // Propagate the one Result branch the method keeps into the receiver so + // unannotated chains such as `value.map(..).map_err(..).and_then(..)` can + // still type callback constructors from the head annotation. A branch the + // method replaces or leaves free is not constrained. + let receiver_hint = combinator_receiver_hint(method, annotated.as_ref(), expected); + resolve_expr(&mut receiver, receiver_hint.as_ref(), env)?; + let receiver_schema = authoritative_schema(&receiver, env); + let result_schema = match receiver_schema { + Some(schema @ TypeSchema::Result { .. }) => schema, + other => { + // `.unwrap_or(...)` keeps the pre-existing nullable lowering for + // every non-Result receiver; the Result methods are new syntax and + // require an actual Result receiver. + if method.retains_option_lowering_on_non_result() { + resolve_expr(&mut argument, expected, env)?; + return Ok(Expr::OptionUnwrapOr { + value: Box::new(receiver), + value_slot: slots.receiver, + fallback: Box::new(argument), + semantic_id, + }); + } + let found = other + .as_ref() + .map(render_schema) + .unwrap_or_else(|| "an untyped value".to_string()); + return Err(result_error( + span, + format!( + ".{} requires a Result receiver, found {}", + method.name(), + found + ), + )); + } + }; + let (ok_schema, err_schema) = branch_schemas(&result_schema).expect("driver matched Result"); + // Only the methods that keep an outer `Result` return enforce the + // surrounding annotation as a `Result`. `unwrap_or(T) -> T` and + // `unwrap_or_else((E) -> T) -> T` use the annotation as the payload type; + // their fallback/callback results are checked against the receiver's + // payload below instead. + let annotated_result = match method { + ResultMethod::Map | ResultMethod::MapErr | ResultMethod::AndThen | ResultMethod::OrElse => { + match &annotated { + Some(schema @ TypeSchema::Result { .. }) if !schema_contains_unknown(schema) => { + Some(schema.clone()) + } + Some(TypeSchema::Result { .. }) | None => None, + Some(other) => { + return Err(result_error( + span, + format!( + ".{} produces a Result value, not {}", + method.name(), + render_schema(other) + ), + )); + } + } + } + ResultMethod::UnwrapOr | ResultMethod::UnwrapOrElse => None, + }; + + match method { + ResultMethod::UnwrapOr => { + resolve_expr(&mut argument, Some(&ok_schema), env)?; + let fallback_schema = authoritative_schema(&argument, env).ok_or_else(|| { + result_error( + span, + ".unwrap_or fallback must have a concrete compile-time type".to_string(), + ) + })?; + require_method_schema(env, &ok_schema, &fallback_schema, span, method, "fallback")?; + if ok_schema.contains_resource_with_named_types(&env.struct_schemas) { + return Err(result_error( + span, + format!( + ".unwrap_or on Result<{}, {}> cannot discard an eager fallback owner: the unselected Ok branch has no destination for resource-typed fallback value {}", + render_schema(&ok_schema), + render_schema(&err_schema), + render_schema(&fallback_schema) + ), + )); + } + // The selected Err branch has no binding to receive the error + // payload: the lowering extracts it and pops it. A resource-typed + // error owner therefore has no destination on that side, exactly + // like the eager fallback above. Reject the composition statically + // instead of deferring the owner to VM teardown. + if err_schema.contains_resource_with_named_types(&env.struct_schemas) { + return Err(result_error( + span, + format!( + ".unwrap_or on Result<{}, {}> cannot discard the selected Err payload owner: the Err branch has no destination for resource-typed error value {}", + render_schema(&ok_schema), + render_schema(&err_schema), + render_schema(&err_schema) + ), + )); + } + // A generic parameter is not proven resource-free at this + // definition: a later instantiation can bind it to a resource + // type, and both the eager fallback and the selected Err payload + // would be discarded without an owner destination. Reject the + // unresolved branch instead of guessing from the generic body. + if schema_contains_generic_param(&ok_schema) + || schema_contains_generic_param(&err_schema) + { + let owner = if schema_contains_generic_param(&err_schema) { + format!("selected Err payload ({})", render_schema(&err_schema)) + } else { + format!( + "eager fallback against the Ok payload ({})", + render_schema(&ok_schema) + ) + }; + return Err(result_error( + span, + format!( + ".unwrap_or on Result<{}, {}> cannot discard the {} owner: its branch contains an unresolved generic parameter that may be instantiated with a resource; use a concrete Result type or preserve the payload explicitly", + render_schema(&ok_schema), + render_schema(&err_schema), + owner + ), + )); + } + if let Some(annotated) = &annotated + && !schema_contains_unknown(annotated) + { + require_method_schema(env, annotated, &ok_schema, span, method, "result")?; + } + reject_resource_capturing_closure(&argument, &fallback_schema, span, method, env)?; + env.slots.insert(slots.receiver, result_schema.clone()); + env.slots.insert(slots.argument, fallback_schema.clone()); + env.slots.insert(slots.ok_binding, ok_schema.clone()); + let mut branch = Expr::ResultMatch { + value: Box::new(Expr::Var(slots.receiver)), + value_slot: slots.receiver, + ok_binding: Some(slots.ok_binding), + ok_expr: Box::new(Expr::Var(slots.ok_binding)), + err_binding: None, + err_expr: Box::new(Expr::Var(slots.argument)), + scrutinee_schema: result_schema.clone(), + span, + semantic_id: None, + }; + resolve_lowered_result_match(&mut branch, expected, env)?; + let lowered = bind_method_evaluations( + &slots, + receiver, + argument, + result_schema, + fallback_schema, + branch, + ); + return Ok(lowered); + } + ResultMethod::UnwrapOrElse => { + let hint = annotated.clone().unwrap_or(TypeSchema::Unknown); + let callback_hint = TypeSchema::Callable { + params: vec![err_schema.clone()], + result: Box::new(hint), + }; + resolve_expr(&mut argument, Some(&callback_hint), env)?; + let callback_schema = + method_callback_schema(&argument, &err_schema, span, method, env)?; + let TypeSchema::Callable { params, result } = &callback_schema else { + unreachable!("method_callback_schema returns a Callable"); + }; + if params.len() != 1 { + return Err(result_error( + span, + format!( + ".unwrap_or_else callback must take exactly one error argument, found {}", + params.len() + ), + )); + } + require_method_schema( + env, + &err_schema, + ¶ms[0], + span, + method, + "callback parameter", + )?; + let returned = result.as_ref(); + require_concrete_schema(returned, span, method, "callback return")?; + require_method_schema(env, &ok_schema, returned, span, method, "callback result")?; + if let Some(annotated) = &annotated + && !schema_contains_unknown(annotated) + { + require_method_schema(env, annotated, &ok_schema, span, method, "result")?; + } + reject_resource_capturing_closure(&argument, &callback_schema, span, method, env)?; + env.slots.insert(slots.receiver, result_schema.clone()); + env.slots.insert(slots.argument, callback_schema.clone()); + env.slots.insert(slots.ok_binding, ok_schema.clone()); + if let Some(err_binding) = slots.err_binding { + env.slots.insert(err_binding, err_schema.clone()); + } + let mut branch = Expr::ResultMatch { + value: Box::new(Expr::Var(slots.receiver)), + value_slot: slots.receiver, + ok_binding: Some(slots.ok_binding), + ok_expr: Box::new(Expr::Var(slots.ok_binding)), + err_binding: slots.err_binding, + err_expr: Box::new(Expr::LocalCall( + slots.argument, + Vec::new(), + vec![Expr::Var(expect_error_binding(&slots))], + None, + )), + scrutinee_schema: result_schema.clone(), + span, + semantic_id: None, + }; + resolve_lowered_result_match(&mut branch, expected, env)?; + let lowered = bind_method_evaluations( + &slots, + receiver, + argument, + result_schema, + callback_schema, + branch, + ); + return Ok(lowered); + } + ResultMethod::Map | ResultMethod::MapErr | ResultMethod::AndThen | ResultMethod::OrElse => { + } + } + + let (param, callback_result_hint) = match method { + ResultMethod::Map => ( + ok_schema.clone(), + annotated_result + .as_ref() + .and_then(branch_schemas) + .map(|(ok, _)| ok), + ), + ResultMethod::MapErr => ( + err_schema.clone(), + annotated_result + .as_ref() + .and_then(branch_schemas) + .map(|(_, err)| err), + ), + ResultMethod::AndThen => ( + ok_schema.clone(), + // and_then keeps the receiver's error type, so the callback's + // Result error branch is always known even without an annotation. + Some(TypeSchema::Result { + ok: Box::new( + annotated_result + .as_ref() + .and_then(branch_schemas) + .map(|(ok, _)| ok) + .unwrap_or(TypeSchema::Unknown), + ), + err: Box::new(err_schema.clone()), + }), + ), + ResultMethod::OrElse => ( + err_schema.clone(), + // or_else keeps the receiver's success type, so the callback's + // Result success branch is always known even without an annotation. + Some(TypeSchema::Result { + ok: Box::new(ok_schema.clone()), + err: Box::new( + annotated_result + .as_ref() + .and_then(branch_schemas) + .map(|(_, err)| err) + .unwrap_or(TypeSchema::Unknown), + ), + }), + ), + ResultMethod::UnwrapOr | ResultMethod::UnwrapOrElse => unreachable!("handled above"), + }; + let callback_hint = TypeSchema::Callable { + params: vec![param.clone()], + result: Box::new(callback_result_hint.unwrap_or(TypeSchema::Unknown)), + }; + resolve_expr(&mut argument, Some(&callback_hint), env)?; + let callback_schema = method_callback_schema(&argument, ¶m, span, method, env)?; + let TypeSchema::Callable { params, result } = &callback_schema else { + unreachable!("method_callback_schema returns a Callable"); + }; + if params.len() != 1 { + return Err(result_error( + span, + format!( + ".{} callback must take exactly one argument, found {}", + method.name(), + params.len() + ), + )); + } + require_method_schema(env, ¶m, ¶ms[0], span, method, "callback parameter")?; + require_concrete_schema(result, span, method, "callback return")?; + reject_resource_capturing_closure(&argument, &callback_schema, span, method, env)?; + + let (ok_expr, err_expr) = match method { + ResultMethod::Map => { + let output_ok = result.as_ref().clone(); + if let Some(annotated_result) = &annotated_result { + let (annotated_ok, _) = + branch_schemas(annotated_result).expect("matched Result annotation"); + require_method_schema(env, &annotated_ok, &output_ok, span, method, "result")?; + } + let output = TypeSchema::Result { + ok: Box::new(output_ok), + err: Box::new(err_schema.clone()), + }; + let ok_expr = result_construct( + true, + Expr::LocalCall( + slots.argument, + Vec::new(), + vec![Expr::Var(expect_ok_binding(&slots))], + None, + ), + &output, + span, + ); + let err_expr = result_construct( + false, + Expr::Var(expect_error_binding(&slots)), + &output, + span, + ); + (ok_expr, err_expr) + } + ResultMethod::MapErr => { + let output_err = result.as_ref().clone(); + if let Some(annotated_result) = &annotated_result { + let (_, annotated_err) = + branch_schemas(annotated_result).expect("matched Result annotation"); + require_method_schema(env, &annotated_err, &output_err, span, method, "result")?; + } + let output = TypeSchema::Result { + ok: Box::new(ok_schema.clone()), + err: Box::new(output_err), + }; + let ok_expr = + result_construct(true, Expr::Var(expect_ok_binding(&slots)), &output, span); + let err_expr = result_construct( + false, + Expr::LocalCall( + slots.argument, + Vec::new(), + vec![Expr::Var(expect_error_binding(&slots))], + None, + ), + &output, + span, + ); + (ok_expr, err_expr) + } + ResultMethod::AndThen => { + let TypeSchema::Result { + ok: output_ok, + err: callback_err, + } = result.as_ref() + else { + return Err(result_error( + span, + format!( + ".and_then callback must return Result, found {}", + render_schema(result) + ), + )); + }; + let output_ok = output_ok.as_ref().clone(); + require_concrete_schema(&output_ok, span, method, "callback success type")?; + let callback_err = callback_err.as_ref().clone(); + require_method_schema( + env, + &err_schema, + &callback_err, + span, + method, + "callback error type", + )?; + if let Some(annotated_result) = &annotated_result { + let (annotated_ok, annotated_err) = + branch_schemas(annotated_result).expect("matched Result annotation"); + require_method_schema(env, &annotated_ok, &output_ok, span, method, "result")?; + require_method_schema( + env, + &annotated_err, + &err_schema, + span, + method, + "result error type", + )?; + } + let output = TypeSchema::Result { + ok: Box::new(output_ok), + err: Box::new(err_schema.clone()), + }; + let ok_expr = Expr::LocalCall( + slots.argument, + Vec::new(), + vec![Expr::Var(expect_ok_binding(&slots))], + None, + ); + let err_expr = result_construct( + false, + Expr::Var(expect_error_binding(&slots)), + &output, + span, + ); + (ok_expr, err_expr) + } + ResultMethod::OrElse => { + let TypeSchema::Result { + ok: callback_ok, + err: output_err, + } = result.as_ref() + else { + return Err(result_error( + span, + format!( + ".or_else callback must return Result, found {}", + render_schema(result) + ), + )); + }; + let callback_ok = callback_ok.as_ref().clone(); + let output_err = output_err.as_ref().clone(); + require_concrete_schema(&output_err, span, method, "callback error type")?; + require_method_schema( + env, + &ok_schema, + &callback_ok, + span, + method, + "callback success type", + )?; + if let Some(annotated_result) = &annotated_result { + let (annotated_ok, annotated_err) = + branch_schemas(annotated_result).expect("matched Result annotation"); + require_method_schema(env, &annotated_ok, &ok_schema, span, method, "result")?; + require_method_schema( + env, + &annotated_err, + &output_err, + span, + method, + "result error type", + )?; + } + let output = TypeSchema::Result { + ok: Box::new(ok_schema.clone()), + err: Box::new(output_err), + }; + let ok_expr = + result_construct(true, Expr::Var(expect_ok_binding(&slots)), &output, span); + let err_expr = Expr::LocalCall( + slots.argument, + Vec::new(), + vec![Expr::Var(expect_error_binding(&slots))], + None, + ); + (ok_expr, err_expr) + } + ResultMethod::UnwrapOr | ResultMethod::UnwrapOrElse => unreachable!("handled above"), + }; + + env.slots.insert(slots.receiver, result_schema.clone()); + env.slots.insert(slots.argument, callback_schema.clone()); + env.slots.insert(slots.ok_binding, ok_schema); + if let Some(err_binding) = slots.err_binding { + env.slots.insert(err_binding, err_schema); + } + let mut branch = Expr::ResultMatch { + value: Box::new(Expr::Var(slots.receiver)), + value_slot: slots.receiver, + ok_binding: Some(slots.ok_binding), + ok_expr: Box::new(ok_expr), + err_binding: slots.err_binding, + err_expr: Box::new(err_expr), + scrutinee_schema: result_schema.clone(), + span, + semantic_id: None, + }; + resolve_lowered_result_match(&mut branch, expected, env)?; + let lowered = bind_method_evaluations( + &slots, + receiver, + argument, + result_schema, + callback_schema, + branch, + ); + Ok(lowered) +} + +/// Resolve the lowered branch exactly once: it validates the typed arms and +/// payload schemas through the shared ResultMatch owner without re-walking the +/// already-resolved receiver/callback binder expressions. +fn resolve_lowered_result_match( + branch: &mut Expr, + expected: Option<&TypeSchema>, + env: &mut Env, +) -> Result<(), CompileError> { + let Expr::ResultMatch { + value, + ok_binding, + ok_expr, + err_binding, + err_expr, + scrutinee_schema, + span, + .. + } = branch + else { + return Ok(()); + }; + resolve_match( + value, + *ok_binding, + ok_expr, + *err_binding, + err_expr, + scrutinee_schema, + *span, + expected, + env, + ) +} + +/// Sequence the receiver evaluation and then the callback/fallback evaluation +/// through parser-assigned hidden locals whose declared schemas are the +/// resolved receiver/callback types. The branch then reuses the existing +/// ResultMatch lowering. Explicit declarations keep strict typing on the +/// callback body instead of letting a closure parameter degrade to `Unknown`. +fn bind_method_evaluations( + slots: &ResultMethodSlots, + receiver: Expr, + argument: Expr, + receiver_schema: TypeSchema, + argument_schema: TypeSchema, + branch: Expr, +) -> Expr { + Expr::Block { + stmts: vec![ + Stmt::Let { + index: slots.receiver, + declared_schema: Some(receiver_schema), + expr: receiver, + line: 1, + }, + Stmt::Let { + index: slots.argument, + declared_schema: Some(argument_schema), + expr: argument, + line: 1, + }, + ], + expr: Box::new(branch), + } +} + +fn expect_ok_binding(slots: &ResultMethodSlots) -> LocalSlot { + slots.ok_binding +} + +fn expect_error_binding(slots: &ResultMethodSlots) -> LocalSlot { + slots + .err_binding + .expect("Result method branch requires an error binding slot") +} + +fn result_construct(ok: bool, payload: Expr, result_schema: &TypeSchema, span: Span) -> Expr { + Expr::ResultConstruct { + ok, + payload: Box::new(payload), + result_schema: result_schema.clone(), + span, + semantic_id: None, + } +} + +fn branch_schemas(schema: &TypeSchema) -> Option<(TypeSchema, TypeSchema)> { + match schema { + TypeSchema::Result { ok, err } => Some(((**ok).clone(), (**err).clone())), + _ => None, + } +} + +/// The partial Result expectation propagated into a combinator receiver. +/// +/// Only the branch the outer method keeps is constrained; the branch it +/// replaces (or leaves free) stays `Unknown` so it cannot reject an +/// unrelated receiver schema. `unwrap_or`/`unwrap_or_else` constrain only the +/// payload branch. +fn combinator_receiver_hint( + method: ResultMethod, + annotated: Option<&TypeSchema>, + expected: Option<&TypeSchema>, +) -> Option { + let known = |schema: &TypeSchema| !matches!(schema, TypeSchema::Unknown); + match method { + ResultMethod::Map | ResultMethod::AndThen => { + let err = annotated + .and_then(branch_schemas) + .map(|(_, err)| err) + .filter(known)?; + Some(TypeSchema::Result { + ok: Box::new(TypeSchema::Unknown), + err: Box::new(err), + }) + } + ResultMethod::MapErr | ResultMethod::OrElse => { + let ok = annotated + .and_then(branch_schemas) + .map(|(ok, _)| ok) + .filter(known)?; + Some(TypeSchema::Result { + ok: Box::new(ok), + err: Box::new(TypeSchema::Unknown), + }) + } + ResultMethod::UnwrapOr | ResultMethod::UnwrapOrElse => { + let payload = expected.filter(|schema| known(schema))?.clone(); + Some(TypeSchema::Result { + ok: Box::new(payload), + err: Box::new(TypeSchema::Unknown), + }) + } + } +} + +fn require_concrete_schema( + schema: &TypeSchema, + span: Span, + method: ResultMethod, + position: &str, +) -> Result<(), CompileError> { + if schema_contains_unknown(schema) { + return Err(result_error( + span, + format!( + ".{} cannot type {}: callback/fallback schema {} is unresolved", + method.name(), + position, + render_schema(schema) + ), + )); + } + Ok(()) +} + +fn schema_contains_unknown(schema: &TypeSchema) -> bool { + match schema { + TypeSchema::Unknown => true, + TypeSchema::Optional(inner) | TypeSchema::Array(inner) | TypeSchema::Map(inner) => { + schema_contains_unknown(inner) + } + TypeSchema::Result { ok, err } => { + schema_contains_unknown(ok) || schema_contains_unknown(err) + } + TypeSchema::ArrayTuple(items) => items.iter().any(schema_contains_unknown), + TypeSchema::ArrayTupleRest { prefix, rest } => { + prefix.iter().any(schema_contains_unknown) || schema_contains_unknown(rest) + } + TypeSchema::Object(fields) => fields.values().any(schema_contains_unknown), + TypeSchema::Named(_, args) => args.iter().any(schema_contains_unknown), + TypeSchema::Callable { params, result } => { + params.iter().any(schema_contains_unknown) || schema_contains_unknown(result) + } + _ => false, + } +} + +/// Whether a schema still contains an unsubstituted generic parameter. A +/// branch carrying one cannot be proven resource-free at the generic +/// definition, because a later instantiation may bind it to a resource type. +fn schema_contains_generic_param(schema: &TypeSchema) -> bool { + match schema { + TypeSchema::GenericParam(_) => true, + TypeSchema::Optional(inner) | TypeSchema::Array(inner) | TypeSchema::Map(inner) => { + schema_contains_generic_param(inner) + } + TypeSchema::Result { ok, err } => { + schema_contains_generic_param(ok) || schema_contains_generic_param(err) + } + TypeSchema::ArrayTuple(items) => items.iter().any(schema_contains_generic_param), + TypeSchema::ArrayTupleRest { prefix, rest } => { + prefix.iter().any(schema_contains_generic_param) || schema_contains_generic_param(rest) + } + TypeSchema::Object(fields) => fields.values().any(schema_contains_generic_param), + TypeSchema::Named(_, args) => args.iter().any(schema_contains_generic_param), + TypeSchema::Callable { params, result } => { + params.iter().any(schema_contains_generic_param) + || schema_contains_generic_param(result) + } + _ => false, + } +} + +fn require_method_schema( + env: &Env, + expected: &TypeSchema, + actual: &TypeSchema, + span: Span, + method: ResultMethod, + position: &str, +) -> Result<(), CompileError> { + let mismatch = super::typing::schema_assignment_mismatch( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + expected, + actual, + ); + if let Some(detail) = mismatch { + return Err(result_error( + span, + format!( + ".{} {} expects {} but found {} ({detail})", + method.name(), + position, + render_schema(expected), + render_schema(actual) + ), + )); + } + Ok(()) +} + +/// Infer the callback/fallback argument's callable schema, giving an inline +/// closure its contextual parameter types so strict typing never depends on a +/// placeholder `Unknown` parameter. +fn method_callback_schema( + argument: &Expr, + param: &TypeSchema, + span: Span, + method: ResultMethod, + env: &Env, +) -> Result { + // Callable-producing expressions must contribute a callable schema whose + // closure parameters are the contextually expected ones. Inferring an + // `if`/`match`/block of closures from the outer state would otherwise + // produce `Unknown` parameters for unannotated closure parameters. + match argument { + Expr::Closure(closure) => { + let mut nested = env.slots.clone(); + nested.extend(super::typing::contextual_callable_slot_schemas( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + &env.slots, + &closure.param_slots, + Some(std::slice::from_ref(param)), + &closure.capture_copies, + )); + infer_callable_callback(argument, &nested, span, method, env) + } + Expr::IfElse { + then_expr, + else_expr, + .. + } => { + let then_schema = method_callback_schema(then_expr, param, span, method, env)?; + let else_schema = method_callback_schema(else_expr, param, span, method, env)?; + merge_callable_branches(then_schema, else_schema, span, method) + } + Expr::Match { arms, default, .. } => { + let mut merged: Option = None; + for (_, arm) in arms { + let arm_schema = method_callback_schema(arm, param, span, method, env)?; + merged = Some(match merged { + Some(existing) => merge_callable_branches(existing, arm_schema, span, method)?, + None => arm_schema, + }); + } + let default_schema = method_callback_schema(default, param, span, method, env)?; + match merged { + Some(existing) => merge_callable_branches(existing, default_schema, span, method), + None => Ok(default_schema), + } + } + Expr::Block { expr, .. } => method_callback_schema(expr, param, span, method, env), + _ => infer_callable_callback(argument, &env.slots, span, method, env), + } +} + +fn infer_callable_callback( + argument: &Expr, + slots: &HashMap, + span: Span, + method: ResultMethod, + env: &Env, +) -> Result { + let inferred = super::typing::infer_value_schema( + &env.function_list, + &env.function_impls, + &env.struct_schemas, + argument, + slots, + ) + .ok_or_else(|| { + result_error( + span, + format!( + ".{} requires a typed callable callback, found an untyped value", + method.name() + ), + ) + })?; + if !matches!(inferred, TypeSchema::Callable { .. }) { + return Err(result_error( + span, + format!( + ".{} requires a callable callback, found {}", + method.name(), + render_schema(&inferred) + ), + )); + } + Ok(inferred) +} + +fn merge_callable_branches( + then_schema: TypeSchema, + else_schema: TypeSchema, + span: Span, + method: ResultMethod, +) -> Result { + if then_schema != else_schema { + return Err(result_error( + span, + format!( + ".{} callback branches produce different callable schemas: {} vs {}", + method.name(), + render_schema(&then_schema), + render_schema(&else_schema) + ), + )); + } + Ok(then_schema) +} + +/// The unselected branch of a combinator has no owner destination for +/// resources moved into a closure capture cell, so that composition +/// is rejected rather than silently leaked or copied. A callable produced +/// by a temporary factory call can carry the same owner with no surviving +/// local binding; the factory's returned expression is checked for that +/// capture provenance before lowering. Already-bound callable locals keep +/// their existing owner. +fn reject_resource_capturing_closure( + argument: &Expr, + argument_schema: &TypeSchema, + span: Span, + method: ResultMethod, + env: &Env, +) -> Result<(), CompileError> { + // The inline capture and temporary-factory checks both describe callable + // callback ownership. A non-callable fallback (`unwrap_or` on a scalar + // payload) keeps its ordinary ownership rules. + if !matches!(argument_schema, TypeSchema::Callable { .. }) { + return Ok(()); + } + if let Some(schema) = find_resource_capturing_closure(argument, env) { + return Err(result_error( + span, + format!( + ".{} callback/fallback cannot move a resource value into a closure capture ({}): the unselected branch has no destination for that owner; pass a named function or bind the callable before the method", + method.name(), + render_schema(&schema) + ), + )); + } + match find_temporary_callable_capture(argument, env) { + TemporaryCallableCapture::Free => Ok(()), + TemporaryCallableCapture::Resource(schema) => Err(result_error( + span, + format!( + ".{} callback/fallback cannot use a temporary callable whose factory moves a resource value into its captures ({}): the unselected branch has no destination for that owner; bind the callable before the method", + method.name(), + render_schema(&schema) + ), + )), + TemporaryCallableCapture::Unknown => Err(result_error( + span, + format!( + ".{} cannot prove the capture ownership of the temporary callable produced by this call: bind the callable before the method or pass a named function", + method.name() + ), + )), + } +} + +#[derive(Clone, Debug)] +enum TemporaryCallableCapture { + Free, + Resource(TypeSchema), + Unknown, +} + +impl TemporaryCallableCapture { + fn merge(self, other: Self) -> Self { + match (self, other) { + (Self::Resource(schema), _) | (_, Self::Resource(schema)) => Self::Resource(schema), + (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown, + (Self::Free, Self::Free) => Self::Free, + } + } +} + +/// A snapshot of local slot schemas plus callable-typed local definitions, +/// used to inspect a factory's returned value without re-entering the main +/// Result resolver. +#[derive(Clone)] +struct CaptureWalk<'a> { + slots: HashMap, + defs: HashMap, + /// Slots whose storage belongs to the producer scope currently being + /// walked. A returned `Var` of one of these dies with the producer; a + /// `Var` of any other slot is a caller-owned binding and keeps its + /// existing owner rule. The root walk starts with an empty set. + owned_locals: HashSet, + /// Capture facts for callable-typed parameters, derived from the actual + /// argument expressions at the call site. + param_facts: HashMap, + /// Callable source slots in this producer scope that may be written + /// through a shared capture cell. Persisted across assignments, branch + /// joins, blocks and loops; a later binding must not restore `Free`. + volatile_sources: HashSet, + env: &'a Env, +} + +fn find_temporary_callable_capture(expr: &Expr, env: &Env) -> TemporaryCallableCapture { + let walk = CaptureWalk { + slots: env.slots.clone(), + defs: env.local_defs.clone(), + owned_locals: HashSet::new(), + param_facts: HashMap::new(), + volatile_sources: env.volatile_sources.clone(), + env, + }; + let mut visiting_slots = HashSet::new(); + let mut visiting_functions = HashSet::new(); + temporary_callable_capture(expr, &walk, &mut visiting_slots, &mut visiting_functions, 0) +} + +/// Capture provenance of the callable value produced by `expr` at runtime. +/// Bare locals stay with their existing owner rules; only call-produced, +/// IIFE-produced and structured-expression callables are inspected here. +fn temporary_callable_capture( + expr: &Expr, + walk: &CaptureWalk<'_>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> TemporaryCallableCapture { + if depth > 8 { + return TemporaryCallableCapture::Unknown; + } + match expr { + Expr::Call(index, _, args, _, _) => call_return_capture( + *index, + args, + walk, + visiting_slots, + visiting_functions, + depth, + ), + Expr::LocalCall(slot, _, args, _) => { + local_call_capture(*slot, args, walk, visiting_slots, visiting_functions, depth) + } + Expr::ClosureCall(closure, args) => closure_call_return_capture( + closure, + args, + walk, + visiting_slots, + visiting_functions, + depth, + ), + Expr::Block { stmts, expr } => { + let mut nested = CaptureWalk { + slots: walk.slots.clone(), + defs: walk.defs.clone(), + owned_locals: walk.owned_locals.clone(), + param_facts: walk.param_facts.clone(), + volatile_sources: walk.volatile_sources.clone(), + env: walk.env, + }; + bind_stmts(stmts, &mut nested); + temporary_callable_capture(expr, &nested, visiting_slots, visiting_functions, depth + 1) + } + Expr::IfElse { + then_expr, + else_expr, + .. + } => { + let then_capture = temporary_callable_capture( + then_expr, + walk, + visiting_slots, + visiting_functions, + depth + 1, + ); + let else_capture = temporary_callable_capture( + else_expr, + walk, + visiting_slots, + visiting_functions, + depth + 1, + ); + then_capture.merge(else_capture) + } + Expr::Match { arms, default, .. } => { + let mut merged = TemporaryCallableCapture::Free; + for (_, arm) in arms { + merged = merged.merge(temporary_callable_capture( + arm, + walk, + visiting_slots, + visiting_functions, + depth + 1, + )); + } + merged.merge(temporary_callable_capture( + default, + walk, + visiting_slots, + visiting_functions, + depth + 1, + )) + } + Expr::Closure(closure) => closure_capture(closure, walk), + Expr::FunctionRef(index, _) => function_value_capture(*index, walk, visiting_functions), + // A returned producer-local resolves through the definition/capture + // facts recorded for that scope. A caller-owned binding (the root + // prebound local, or a captured user local) keeps its existing owner. + Expr::Var(slot) | Expr::MoveVar(slot) => local_value_capture(*slot, walk), + // Scalar leaves cannot produce a callable value; every other + // unmodeled callable-producing expression is unproven, not Free. + Expr::Null + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) => TemporaryCallableCapture::Free, + _ => TemporaryCallableCapture::Unknown, + } +} + +/// Capture provenance of the callable value read from `slot` at runtime. +fn local_value_capture(slot: LocalSlot, walk: &CaptureWalk<'_>) -> TemporaryCallableCapture { + if let Some(fact) = walk.param_facts.get(&slot) { + return fact.clone(); + } + if !walk.owned_locals.contains(&slot) { + // A persistent caller binding is not a temporary producer owner. + return TemporaryCallableCapture::Free; + } + match walk.defs.get(&slot) { + Some(definition) => definition.capture.clone(), + None => TemporaryCallableCapture::Unknown, + } +} + +fn call_return_capture( + index: u16, + args: &[Expr], + walk: &CaptureWalk<'_>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> TemporaryCallableCapture { + if depth > 8 || !visiting_functions.insert(index) { + return TemporaryCallableCapture::Unknown; + } + let result = match ( + walk.env.functions.get(&index), + walk.env.function_impls.get(&index), + ) { + (Some(function), Some(implementation)) => { + let nested = function_capture_walk( + function, + implementation, + args, + walk, + visiting_slots, + visiting_functions, + depth, + ); + // The callee's own local slots are a distinct lexical scope even + // when a sibling function reuses the same numeric LocalSlot. + let mut callee_slots = HashSet::new(); + temporary_callable_capture( + &implementation.body_expr, + &nested, + &mut callee_slots, + visiting_functions, + depth + 1, + ) + } + // A host-produced callable has no inspectable guest capture story. + (Some(_), None) => TemporaryCallableCapture::Unknown, + (None, _) => TemporaryCallableCapture::Unknown, + }; + visiting_functions.remove(&index); + result +} + +fn local_call_capture( + slot: LocalSlot, + args: &[Expr], + walk: &CaptureWalk<'_>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> TemporaryCallableCapture { + local_callable_return_capture( + slot, + args, + walk, + visiting_slots, + visiting_functions, + depth, + 0, + ) +} + +fn local_callable_return_capture( + slot: LocalSlot, + args: &[Expr], + walk: &CaptureWalk<'_>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, + hops: usize, +) -> TemporaryCallableCapture { + if hops > 8 || depth > 8 || !visiting_slots.insert(slot) { + return TemporaryCallableCapture::Unknown; + } + let result = match walk.defs.get(&slot) { + Some(definition) => match definition.target.as_deref() { + Some(CallableTarget::Function(index)) => { + // The callable value's target is frozen at binding time; only + // the actual arguments are evaluated against the call-site + // facts. Captured source schemas use the binding snapshot. + let target_walk = CaptureWalk { + slots: definition.slots.clone(), + defs: walk.defs.clone(), + owned_locals: walk.owned_locals.clone(), + param_facts: walk.param_facts.clone(), + volatile_sources: walk.volatile_sources.clone(), + env: walk.env, + }; + call_return_capture( + *index, + args, + &target_walk, + visiting_slots, + visiting_functions, + depth, + ) + } + Some(CallableTarget::Closure(closure)) => { + let mut callee_slots = HashSet::new(); + let nested = closure_body_walk( + closure, + &definition.slots, + args, + walk, + visiting_slots, + visiting_functions, + depth, + ); + temporary_callable_capture( + &closure.body, + &nested, + &mut callee_slots, + visiting_functions, + depth + 1, + ) + } + None => TemporaryCallableCapture::Unknown, + }, + None => TemporaryCallableCapture::Unknown, + }; + visiting_slots.remove(&slot); + result +} + +fn closure_call_return_capture( + closure: &ClosureExpr, + args: &[Expr], + walk: &CaptureWalk<'_>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> TemporaryCallableCapture { + let mut callee_slots = HashSet::new(); + let nested = closure_body_walk( + closure, + &walk.slots, + args, + walk, + visiting_slots, + visiting_functions, + depth, + ); + temporary_callable_capture( + &closure.body, + &nested, + &mut callee_slots, + visiting_functions, + depth + 1, + ) +} + +fn argument_schemas( + param_slots: &[LocalSlot], + args: &[Expr], + walk: &CaptureWalk<'_>, +) -> Option> { + let mut schemas = HashMap::new(); + for (slot, argument) in param_slots.iter().zip(args.iter()) { + let schema = super::typing::infer_value_schema( + &walk.env.function_list, + &walk.env.function_impls, + &walk.env.struct_schemas, + argument, + &walk.slots, + )?; + schemas.insert(*slot, schema); + } + Some(schemas) +} + +fn closure_body_walk<'a>( + closure: &ClosureExpr, + slots: &HashMap, + args: &[Expr], + caller: &CaptureWalk<'a>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> CaptureWalk<'a> { + let mut nested_slots = slots.clone(); + for (source, captured) in &closure.capture_copies { + if let Some(schema) = slots.get(source) { + nested_slots.insert(*captured, schema.clone()); + } + } + if let Some(arg_schemas) = argument_schemas(&closure.param_slots, args, caller) { + nested_slots.extend(arg_schemas); + } + let mut param_facts = HashMap::new(); + for (slot, argument) in closure.param_slots.iter().zip(args.iter()) { + param_facts.insert( + *slot, + temporary_callable_capture( + argument, + caller, + visiting_slots, + visiting_functions, + depth + 1, + ), + ); + } + let mut owned_locals: HashSet = closure.param_slots.iter().copied().collect(); + owned_locals.extend(closure.capture_copies.iter().map(|(_, captured)| *captured)); + let volatile_sources = captured_volatile_slots( + &closure.capture_copies, + &caller.volatile_sources, + &nested_slots, + ); + CaptureWalk { + slots: nested_slots, + defs: HashMap::new(), + owned_locals, + param_facts, + volatile_sources, + env: caller.env, + } +} + +fn function_value_capture( + index: u16, + walk: &CaptureWalk<'_>, + visiting_functions: &mut HashSet, +) -> TemporaryCallableCapture { + if !visiting_functions.insert(index) { + return TemporaryCallableCapture::Unknown; + } + let result = match walk.env.function_impls.get(&index) { + Some(implementation) => { + let mut verdict = TemporaryCallableCapture::Free; + for (source, _) in &implementation.capture_copies { + match walk.slots.get(source) { + Some(schema) + if schema.contains_resource_with_named_types(&walk.env.struct_schemas) => + { + verdict = TemporaryCallableCapture::Resource(schema.clone()); + break; + } + Some(_) => {} + None => verdict = TemporaryCallableCapture::Unknown, + } + } + verdict + } + None => TemporaryCallableCapture::Free, + }; + visiting_functions.remove(&index); + result +} + +fn closure_capture(closure: &ClosureExpr, walk: &CaptureWalk<'_>) -> TemporaryCallableCapture { + let mut verdict = TemporaryCallableCapture::Free; + for (source, _) in &closure.capture_copies { + match walk.slots.get(source) { + Some(schema) if schema.contains_resource_with_named_types(&walk.env.struct_schemas) => { + return TemporaryCallableCapture::Resource(schema.clone()); + } + Some(TypeSchema::Callable { .. }) => { + let nested = if let Some(fact) = walk.param_facts.get(source) { + fact.clone() + } else { + match walk.defs.get(source) { + Some(definition) => definition.capture.clone(), + None => TemporaryCallableCapture::Unknown, + } + }; + verdict = verdict.merge(nested); + } + Some(_) => {} + None => verdict = verdict.merge(TemporaryCallableCapture::Unknown), + } + } + verdict +} + +/// Capture fact frozen for the callable value produced by `expr` at this +/// binding point. +fn binding_value_capture(expr: &Expr, walk: &CaptureWalk<'_>) -> TemporaryCallableCapture { + temporary_callable_capture(expr, walk, &mut HashSet::new(), &mut HashSet::new(), 0) +} + +/// Resolve an immutable callable target at the binding point. Aliases copy +/// the target already resolved for the source definition; a callable derived +/// from an opaque argument has no statically known target. +fn binding_target( + expr: &Expr, + defs: &HashMap, + param_facts: Option<&HashMap>, +) -> Option> { + match expr { + Expr::FunctionRef(index, _) => Some(Arc::new(CallableTarget::Function(*index))), + Expr::Closure(closure) => Some(Arc::new(CallableTarget::Closure(closure.clone()))), + Expr::Var(slot) | Expr::MoveVar(slot) => { + if param_facts.is_some_and(|facts| facts.contains_key(slot)) { + return None; + } + defs.get(slot) + .and_then(|definition| definition.target.clone()) + } + _ => None, + } +} + +fn callable_env_definition(expr: &Expr, env: &Env) -> LocalDefinition { + let walk = CaptureWalk { + slots: env.slots.clone(), + defs: env.local_defs.clone(), + owned_locals: HashSet::new(), + param_facts: HashMap::new(), + volatile_sources: env.volatile_sources.clone(), + env, + }; + LocalDefinition { + capture: binding_value_capture(expr, &walk), + target: binding_target(expr, &walk.defs, None), + slots: env.slots.clone(), + } +} + +fn definition_capture(definition: Option<&LocalDefinition>) -> TemporaryCallableCapture { + definition + .map(|definition| definition.capture.clone()) + .unwrap_or(TemporaryCallableCapture::Unknown) +} + +fn same_binding_target( + then_definition: Option<&LocalDefinition>, + else_definition: Option<&LocalDefinition>, +) -> Option> { + let then_target = then_definition?.target.as_ref()?; + let else_target = else_definition?.target.as_ref()?; + if Arc::ptr_eq(then_target, else_target) { + return Some(then_target.clone()); + } + match (then_target.as_ref(), else_target.as_ref()) { + (CallableTarget::Function(then_index), CallableTarget::Function(else_index)) + if then_index == else_index => + { + Some(then_target.clone()) + } + _ => None, + } +} + +/// Join two branch outcomes for every callable binding that existed before +/// the branch. Bindings introduced inside one branch are branch-local; a +/// binding dropped on one path becomes `Unknown`. +fn join_definitions( + before: &HashMap, + then_defs: &HashMap, + else_defs: &HashMap, +) -> HashMap { + let mut merged = HashMap::new(); + for slot in before.keys() { + let then_definition = then_defs.get(slot); + let else_definition = else_defs.get(slot); + let slots = then_definition + .or(else_definition) + .or_else(|| before.get(slot)) + .map(|definition| definition.slots.clone()) + .unwrap_or_default(); + merged.insert( + *slot, + LocalDefinition { + capture: definition_capture(then_definition) + .merge(definition_capture(else_definition)), + target: same_binding_target(then_definition, else_definition), + slots, + }, + ); + } + merged +} + +fn invalidate_local_definitions( + defs: &mut HashMap, + written: &HashSet, +) { + for slot in written { + if let Some(definition) = defs.get_mut(slot) { + definition.capture = TemporaryCallableCapture::Unknown; + definition.target = None; + } + } +} + +fn function_capture_walk<'a>( + function: &FunctionDecl, + implementation: &FunctionImpl, + args: &[Expr], + caller: &CaptureWalk<'a>, + visiting_slots: &mut HashSet, + visiting_functions: &mut HashSet, + depth: usize, +) -> CaptureWalk<'a> { + let mut slots = HashMap::new(); + let mut owned_locals = HashSet::new(); + for (slot, schema) in implementation + .param_slots + .iter() + .zip(function.arg_schemas.iter()) + { + if let Some(schema) = schema { + slots.insert(*slot, schema.clone()); + } + owned_locals.insert(*slot); + } + for (source, captured) in &implementation.capture_copies { + if let Some(schema) = caller + .slots + .get(source) + .or_else(|| caller.env.slots.get(source)) + { + slots.insert(*captured, schema.clone()); + } + owned_locals.insert(*captured); + } + let mut param_facts = HashMap::new(); + for ((slot, schema), argument) in implementation + .param_slots + .iter() + .zip(function.arg_schemas.iter()) + .zip(args.iter()) + { + if schema + .as_ref() + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })) + { + param_facts.insert( + *slot, + temporary_callable_capture( + argument, + caller, + visiting_slots, + visiting_functions, + depth + 1, + ), + ); + } + } + let volatile_sources = captured_volatile_slots( + &implementation.capture_copies, + &caller.volatile_sources, + &slots, + ); + let mut walk = CaptureWalk { + slots, + defs: HashMap::new(), + owned_locals, + param_facts, + volatile_sources, + env: caller.env, + }; + bind_stmts(&implementation.body_stmts, &mut walk); + walk +} + +fn bind_stmts(stmts: &[Stmt], walk: &mut CaptureWalk<'_>) { + for stmt in stmts { + bind_stmt(stmt, walk); + } +} + +fn bind_stmt(stmt: &Stmt, walk: &mut CaptureWalk<'_>) { + match stmt { + Stmt::Noop { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => {} + Stmt::FuncDecl { + index, has_impl, .. + } => { + if *has_impl { + let sources = function_capture_targets(*index, walk.env); + mark_walk_volatile_sources(walk, sources); + } + } + Stmt::ClosureLet { closure, .. } => { + let sources = closure_capture_targets(closure, walk.env); + mark_walk_volatile_sources(walk, sources); + } + Stmt::Let { + index, + declared_schema, + expr, + .. + } => { + apply_expr_effects(expr, walk); + record_callable_binding(*index, expr, declared_schema.as_ref(), true, walk); + } + Stmt::Assign { index, expr, .. } => { + apply_expr_effects(expr, walk); + record_callable_binding(*index, expr, None, false, walk); + } + Stmt::Expr { expr, .. } => apply_expr_effects(expr, walk), + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + apply_expr_effects(condition, walk); + let mut then_walk = walk.clone(); + bind_stmts(then_branch, &mut then_walk); + let mut else_walk = walk.clone(); + bind_stmts(else_branch, &mut else_walk); + join_branch_walks(walk, &then_walk, &else_walk); + } + Stmt::While { + condition, body, .. + } => { + apply_expr_effects(condition, walk); + let mut written = HashSet::new(); + collect_expr_writes(condition, &mut written); + collect_stmt_list_writes(body, &mut written); + invalidate_possible_writes(walk, &written); + } + Stmt::For { + init, + condition, + post, + body, + .. + } => { + bind_stmt(init, walk); + apply_expr_effects(condition, walk); + let mut written = HashSet::new(); + collect_expr_writes(condition, &mut written); + collect_stmt_writes(post, &mut written); + collect_stmt_list_writes(body, &mut written); + invalidate_possible_writes(walk, &written); + } + Stmt::Drop { index, .. } => { + walk.slots.remove(index); + walk.defs.remove(index); + walk.owned_locals.remove(index); + walk.param_facts.remove(index); + } + } +} + +fn record_callable_binding( + index: LocalSlot, + expr: &Expr, + declared_schema: Option<&TypeSchema>, + declare: bool, + walk: &mut CaptureWalk<'_>, +) { + let schema = declared_schema + .cloned() + .or_else(|| { + super::typing::infer_value_schema( + &walk.env.function_list, + &walk.env.function_impls, + &walk.env.struct_schemas, + expr, + &walk.slots, + ) + }) + .filter(|schema| !matches!(schema, TypeSchema::Unknown)); + if let Some(schema) = schema { + walk.slots.insert(index, schema); + } + if declare { + walk.owned_locals.insert(index); + } + walk.param_facts.remove(&index); + if walk.volatile_sources.contains(&index) { + if is_callable_slot(&walk.slots, index) { + walk.defs.insert(index, volatile_definition(&walk.slots)); + } else { + walk.defs.remove(&index); + } + return; + } + let is_callable = walk + .slots + .get(&index) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })); + if is_callable { + let capture = binding_value_capture(expr, walk); + let target = binding_target(expr, &walk.defs, Some(&walk.param_facts)); + walk.defs.insert( + index, + LocalDefinition { + capture, + target, + slots: walk.slots.clone(), + }, + ); + } else { + walk.defs.remove(&index); + } +} + +fn is_callable_slot(slots: &HashMap, slot: LocalSlot) -> bool { + slots + .get(&slot) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })) +} + +fn callable_outer_slots(walk: &CaptureWalk<'_>) -> HashSet { + let mut slots: HashSet = walk.defs.keys().copied().collect(); + slots.extend(walk.param_facts.keys().copied()); + for slot in &walk.owned_locals { + if walk + .slots + .get(slot) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })) + { + slots.insert(*slot); + } + } + slots +} + +fn join_branch_walks( + walk: &mut CaptureWalk<'_>, + then_walk: &CaptureWalk<'_>, + else_walk: &CaptureWalk<'_>, +) { + let before_defs = walk.defs.clone(); + let before_params = walk.param_facts.clone(); + let mut slots: HashSet = callable_outer_slots(walk); + slots.extend(before_defs.keys().copied()); + let mut merged_defs = HashMap::new(); + for slot in slots { + let then_definition = then_walk.defs.get(&slot); + let else_definition = else_walk.defs.get(&slot); + let before_definition = before_defs.get(&slot); + if then_definition.is_none() && else_definition.is_none() && before_definition.is_none() { + continue; + } + let slots = then_definition + .or(else_definition) + .or(before_definition) + .map(|definition| definition.slots.clone()) + .unwrap_or_default(); + merged_defs.insert( + slot, + LocalDefinition { + capture: definition_capture(then_definition) + .merge(definition_capture(else_definition)), + target: same_binding_target(then_definition, else_definition), + slots, + }, + ); + } + let mut merged_params = HashMap::new(); + for (slot, before_fact) in &before_params { + if let (Some(then_fact), Some(else_fact)) = ( + then_walk.param_facts.get(slot), + else_walk.param_facts.get(slot), + ) { + merged_params.insert( + *slot, + before_fact + .clone() + .merge(then_fact.clone()) + .merge(else_fact.clone()), + ); + } + } + walk.defs = merged_defs; + walk.param_facts = merged_params; + walk.volatile_sources + .extend(then_walk.volatile_sources.iter().copied()); + walk.volatile_sources + .extend(else_walk.volatile_sources.iter().copied()); + let volatile = walk.volatile_sources.clone(); + invalidate_possible_writes(walk, &volatile); +} + +fn invalidate_possible_writes(walk: &mut CaptureWalk<'_>, written: &HashSet) { + for slot in written { + let callable_slot = walk.defs.contains_key(slot) + || walk + .slots + .get(slot) + .is_some_and(|schema| matches!(schema, TypeSchema::Callable { .. })); + if !callable_slot || (!walk.owned_locals.contains(slot) && !walk.defs.contains_key(slot)) { + continue; + } + walk.param_facts.remove(slot); + walk.defs.insert(*slot, volatile_definition(&walk.slots)); + } +} + +fn volatile_definition(slots: &HashMap) -> LocalDefinition { + LocalDefinition { + capture: TemporaryCallableCapture::Unknown, + target: None, + slots: slots.clone(), + } +} + +fn mark_env_volatile_sources(env: &mut Env, sources: HashSet) { + let sources: HashSet = sources + .into_iter() + .filter(|slot| is_callable_slot(&env.slots, *slot)) + .collect(); + env.volatile_sources.extend(sources.iter().copied()); + invalidate_local_definitions(&mut env.local_defs, &sources); +} + +fn mark_walk_volatile_sources(walk: &mut CaptureWalk<'_>, sources: HashSet) { + let sources: HashSet = sources + .into_iter() + .filter(|slot| is_callable_slot(&walk.slots, *slot)) + .collect(); + walk.volatile_sources.extend(sources.iter().copied()); + invalidate_possible_writes(walk, &sources); +} + +/// Volatile facts for a fresh callee frame, derived only from the actual +/// `(source, captured)` capture pairs. A caller volatile source poisons the +/// callee slot that captures it; the caller's numeric slot set is never +/// copied across the lexical frame, so an unrelated private/parameter slot +/// that happens to reuse the same integer id keeps its own trust. +fn captured_volatile_slots( + capture_copies: &[(LocalSlot, LocalSlot)], + caller_volatile_sources: &HashSet, + callee_slots: &HashMap, +) -> HashSet { + capture_copies + .iter() + .filter(|(source, _)| caller_volatile_sources.contains(source)) + .map(|(_, captured)| *captured) + .filter(|captured| is_callable_slot(callee_slots, *captured)) + .collect() +} + +/// Slots in the frame enclosing `closure` whose values its body may write +/// through the closure's shared capture cells. Nested capture producers are +/// mapped through their own `capture_copies`; the closure is conservatively +/// treated as possibly invoked. +fn closure_capture_targets(closure: &ClosureExpr, env: &Env) -> HashSet { + closure_capture_targets_inner(closure, env, &mut HashSet::new()) +} + +fn closure_capture_targets_inner( + closure: &ClosureExpr, + env: &Env, + visiting_functions: &mut HashSet, +) -> HashSet { + let mut written = HashSet::new(); + collect_capture_body_writes(&closure.body, env, &mut written, visiting_functions); + closure + .capture_copies + .iter() + .filter(|(_, captured)| written.contains(captured)) + .map(|(source, _)| *source) + .collect() +} + +fn function_capture_targets(index: u16, env: &Env) -> HashSet { + function_capture_targets_inner(index, env, &mut HashSet::new()) +} + +fn function_capture_targets_inner( + index: u16, + env: &Env, + visiting_functions: &mut HashSet, +) -> HashSet { + let Some(implementation) = env.function_impls.get(&index) else { + return HashSet::new(); + }; + if !visiting_functions.insert(index) { + return HashSet::new(); + } + let mut written = HashSet::new(); + for stmt in &implementation.body_stmts { + collect_capture_stmt_writes(stmt, env, &mut written, visiting_functions); + } + collect_capture_body_writes( + &implementation.body_expr, + env, + &mut written, + visiting_functions, + ); + let targets = implementation + .capture_copies + .iter() + .filter(|(_, captured)| written.contains(captured)) + .map(|(source, _)| *source) + .collect(); + visiting_functions.remove(&index); + targets +} + +fn collect_capture_body_writes( + expr: &Expr, + env: &Env, + written: &mut HashSet, + visiting_functions: &mut HashSet, +) { + collect_expr_writes(expr, written); + collect_capture_expr_producers(expr, env, written, visiting_functions); +} + +fn collect_capture_stmt_writes( + stmt: &Stmt, + env: &Env, + written: &mut HashSet, + visiting_functions: &mut HashSet, +) { + match stmt { + Stmt::Noop { .. } | Stmt::Break { .. } | Stmt::Continue { .. } => {} + Stmt::Let { index, expr, .. } | Stmt::Assign { index, expr, .. } => { + written.insert(*index); + collect_capture_body_writes(expr, env, written, visiting_functions); + } + Stmt::ClosureLet { closure, .. } => { + written.extend(closure_capture_targets_inner( + closure, + env, + visiting_functions, + )); + } + Stmt::FuncDecl { + index, has_impl, .. + } => { + if *has_impl { + written.extend(function_capture_targets_inner( + *index, + env, + visiting_functions, + )); + } + } + Stmt::Expr { expr, .. } => { + collect_capture_body_writes(expr, env, written, visiting_functions); + } + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + collect_capture_body_writes(condition, env, written, visiting_functions); + for nested in then_branch { + collect_capture_stmt_writes(nested, env, written, visiting_functions); + } + for nested in else_branch { + collect_capture_stmt_writes(nested, env, written, visiting_functions); + } + } + Stmt::For { + init, + condition, + post, + body, + .. + } => { + collect_capture_stmt_writes(init, env, written, visiting_functions); + collect_capture_body_writes(condition, env, written, visiting_functions); + collect_capture_stmt_writes(post, env, written, visiting_functions); + for nested in body { + collect_capture_stmt_writes(nested, env, written, visiting_functions); + } + } + Stmt::While { + condition, body, .. + } => { + collect_capture_body_writes(condition, env, written, visiting_functions); + for nested in body { + collect_capture_stmt_writes(nested, env, written, visiting_functions); + } + } + Stmt::Drop { index, .. } => { + written.insert(*index); + } + } +} + +fn collect_capture_expr_producers( + expr: &Expr, + env: &Env, + written: &mut HashSet, + visiting_functions: &mut HashSet, +) { + match expr { + Expr::Closure(closure) => { + written.extend(closure_capture_targets_inner( + closure, + env, + visiting_functions, + )); + } + Expr::ClosureCall(closure, args) => { + written.extend(closure_capture_targets_inner( + closure, + env, + visiting_functions, + )); + for argument in args { + collect_capture_expr_producers(argument, env, written, visiting_functions); + } + } + Expr::FunctionRef(index, _) => { + written.extend(function_capture_targets_inner( + *index, + env, + visiting_functions, + )); + } + Expr::Block { stmts, expr } => { + for stmt in stmts { + collect_capture_stmt_writes(stmt, env, written, visiting_functions); + } + collect_capture_expr_producers(expr, env, written, visiting_functions); + } + Expr::OptionalGet { container, key, .. } => { + collect_capture_expr_producers(container, env, written, visiting_functions); + collect_capture_expr_producers(key, env, written, visiting_functions); + } + Expr::OptionUnwrapOr { + value, fallback, .. + } => { + collect_capture_expr_producers(value, env, written, visiting_functions); + collect_capture_expr_producers(fallback, env, written, visiting_functions); + } + Expr::Call(_, _, args, _, _) + | Expr::ModuleCall(_, _, args, _) + | Expr::LocalCall(_, _, args, _) => { + for argument in args { + collect_capture_expr_producers(argument, env, written, visiting_functions); + } + } + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) + | Expr::And(lhs, rhs) + | Expr::Or(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + collect_capture_expr_producers(lhs, env, written, visiting_functions); + collect_capture_expr_producers(rhs, env, written, visiting_functions); + } + Expr::Neg(inner) + | Expr::Not(inner) + | Expr::ToOwned(inner) + | Expr::Borrow(inner) + | Expr::BorrowMut(inner) => { + collect_capture_expr_producers(inner, env, written, visiting_functions); + } + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + collect_capture_expr_producers(condition, env, written, visiting_functions); + collect_capture_expr_producers(then_expr, env, written, visiting_functions); + collect_capture_expr_producers(else_expr, env, written, visiting_functions); + } + Expr::Match { + value, + arms, + default, + .. + } => { + collect_capture_expr_producers(value, env, written, visiting_functions); + for (_, arm) in arms { + collect_capture_expr_producers(arm, env, written, visiting_functions); + } + collect_capture_expr_producers(default, env, written, visiting_functions); + } + Expr::ResultConstruct { payload, .. } => { + collect_capture_expr_producers(payload, env, written, visiting_functions); + } + Expr::ResultQuery { value, .. } => { + collect_capture_expr_producers(value, env, written, visiting_functions); + } + Expr::ResultTry { value, .. } => { + collect_capture_expr_producers(value, env, written, visiting_functions); + } + Expr::ResultMatch { + value, + ok_expr, + err_expr, + .. + } => { + collect_capture_expr_producers(value, env, written, visiting_functions); + collect_capture_expr_producers(ok_expr, env, written, visiting_functions); + collect_capture_expr_producers(err_expr, env, written, visiting_functions); + } + Expr::ResultMethod { + receiver, argument, .. + } => { + collect_capture_expr_producers(receiver, env, written, visiting_functions); + collect_capture_expr_producers(argument, env, written, visiting_functions); + } + Expr::Null + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) + | Expr::ModuleFunctionRef(_, _) + | Expr::UnresolvedFunctionRef { .. } + | Expr::Var(_) + | Expr::MoveVar(_) + | Expr::MoveField { .. } + | Expr::MoveIndex { .. } => {} + } +} + +fn copy_outer_callable_state(walk: &mut CaptureWalk<'_>, nested: &CaptureWalk<'_>) { + let outer = callable_outer_slots(walk); + let mut defs = HashMap::new(); + for slot in outer { + if let Some(definition) = nested.defs.get(&slot) { + defs.insert(slot, definition.clone()); + } else if walk.defs.contains_key(&slot) { + defs.insert( + slot, + LocalDefinition { + capture: TemporaryCallableCapture::Unknown, + target: None, + slots: walk.slots.clone(), + }, + ); + } + } + let mut param_facts = HashMap::new(); + for slot in walk.param_facts.keys() { + if let Some(fact) = nested.param_facts.get(slot) { + param_facts.insert(*slot, fact.clone()); + } + } + walk.defs = defs; + walk.param_facts = param_facts; + walk.volatile_sources + .extend(nested.volatile_sources.iter().copied()); + let volatile = walk.volatile_sources.clone(); + invalidate_possible_writes(walk, &volatile); +} + +/// Apply the writes that evaluating `expr` can perform on callable slots in +/// the enclosing walk. Branch arms are analyzed from the same input state and +/// joined; the right operand of `&&`/`||` is joined with the state where it +/// is skipped. +fn apply_expr_effects(expr: &Expr, walk: &mut CaptureWalk<'_>) { + match expr { + Expr::Null + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) + | Expr::ModuleFunctionRef(_, _) + | Expr::UnresolvedFunctionRef { .. } + | Expr::Var(_) + | Expr::MoveVar(_) + | Expr::MoveField { .. } + | Expr::MoveIndex { .. } => {} + Expr::Closure(closure) => { + let sources = closure_capture_targets(closure, walk.env); + mark_walk_volatile_sources(walk, sources); + } + Expr::FunctionRef(index, _) => { + let sources = function_capture_targets(*index, walk.env); + mark_walk_volatile_sources(walk, sources); + } + Expr::OptionalGet { container, key, .. } => { + apply_expr_effects(container, walk); + apply_expr_effects(key, walk); + } + Expr::OptionUnwrapOr { + value, fallback, .. + } => { + apply_expr_effects(value, walk); + apply_expr_effects(fallback, walk); + } + Expr::Call(_, _, args, _, _) + | Expr::ModuleCall(_, _, args, _) + | Expr::LocalCall(_, _, args, _) => { + for argument in args { + apply_expr_effects(argument, walk); + } + } + Expr::ClosureCall(closure, args) => { + let sources = closure_capture_targets(closure, walk.env); + mark_walk_volatile_sources(walk, sources); + for argument in args { + apply_expr_effects(argument, walk); + } + } + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + apply_expr_effects(lhs, walk); + apply_expr_effects(rhs, walk); + } + Expr::And(lhs, rhs) | Expr::Or(lhs, rhs) => { + apply_expr_effects(lhs, walk); + let skipped = walk.clone(); + let mut executed = skipped.clone(); + apply_expr_effects(rhs, &mut executed); + join_branch_walks(walk, &skipped, &executed); + } + Expr::Neg(inner) + | Expr::Not(inner) + | Expr::ToOwned(inner) + | Expr::Borrow(inner) + | Expr::BorrowMut(inner) => apply_expr_effects(inner, walk), + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + apply_expr_effects(condition, walk); + let mut then_walk = walk.clone(); + apply_expr_effects(then_expr, &mut then_walk); + let mut else_walk = walk.clone(); + apply_expr_effects(else_expr, &mut else_walk); + join_branch_walks(walk, &then_walk, &else_walk); + } + Expr::Match { + value, + arms, + default, + .. + } => { + apply_expr_effects(value, walk); + let mut branches = Vec::new(); + for (_, arm) in arms { + let mut branch = walk.clone(); + apply_expr_effects(arm, &mut branch); + branches.push(branch); + } + let mut default_branch = walk.clone(); + apply_expr_effects(default, &mut default_branch); + branches.push(default_branch); + let mut merged = branches.remove(0); + for branch in branches { + let previous = merged.clone(); + join_branch_walks(&mut merged, &previous, &branch); + } + *walk = merged; + } + Expr::Block { stmts, expr } => { + let mut nested = walk.clone(); + bind_stmts(stmts, &mut nested); + apply_expr_effects(expr, &mut nested); + copy_outer_callable_state(walk, &nested); + } + Expr::ResultConstruct { payload, .. } => apply_expr_effects(payload, walk), + Expr::ResultQuery { value, .. } => apply_expr_effects(value, walk), + Expr::ResultTry { value, .. } => apply_expr_effects(value, walk), + Expr::ResultMatch { + value, + ok_expr, + err_expr, + .. + } => { + apply_expr_effects(value, walk); + let mut ok_walk = walk.clone(); + apply_expr_effects(ok_expr, &mut ok_walk); + let mut err_walk = walk.clone(); + apply_expr_effects(err_expr, &mut err_walk); + join_branch_walks(walk, &ok_walk, &err_walk); + } + Expr::ResultMethod { + receiver, argument, .. + } => { + apply_expr_effects(receiver, walk); + apply_expr_effects(argument, walk); + } + } +} + +fn collect_stmt_list_writes(stmts: &[Stmt], written: &mut HashSet) { + for stmt in stmts { + collect_stmt_writes(stmt, written); + } +} + +fn collect_stmt_writes(stmt: &Stmt, written: &mut HashSet) { + match stmt { + Stmt::Noop { .. } + | Stmt::FuncDecl { .. } + | Stmt::Break { .. } + | Stmt::Continue { .. } + | Stmt::ClosureLet { .. } => {} + Stmt::Let { index, expr, .. } => { + written.insert(*index); + collect_expr_writes(expr, written); + } + Stmt::Assign { index, expr, .. } => { + written.insert(*index); + collect_expr_writes(expr, written); + } + Stmt::Expr { expr, .. } => collect_expr_writes(expr, written), + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + collect_expr_writes(condition, written); + collect_stmt_list_writes(then_branch, written); + collect_stmt_list_writes(else_branch, written); + } + Stmt::For { + init, + condition, + post, + body, + .. + } => { + collect_stmt_writes(init, written); + collect_expr_writes(condition, written); + collect_stmt_writes(post, written); + collect_stmt_list_writes(body, written); + } + Stmt::While { + condition, body, .. + } => { + collect_expr_writes(condition, written); + collect_stmt_list_writes(body, written); + } + Stmt::Drop { index, .. } => { + written.insert(*index); + } + } +} + +fn collect_expr_writes(expr: &Expr, written: &mut HashSet) { + match expr { + Expr::Null + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) + | Expr::FunctionRef(_, _) + | Expr::ModuleFunctionRef(_, _) + | Expr::UnresolvedFunctionRef { .. } + | Expr::Var(_) + | Expr::MoveVar(_) + | Expr::MoveField { .. } + | Expr::MoveIndex { .. } + | Expr::Closure(_) => {} + Expr::OptionalGet { container, key, .. } => { + collect_expr_writes(container, written); + collect_expr_writes(key, written); + } + Expr::OptionUnwrapOr { + value, fallback, .. + } => { + collect_expr_writes(value, written); + collect_expr_writes(fallback, written); + } + Expr::Call(_, _, args, _, _) + | Expr::ModuleCall(_, _, args, _) + | Expr::LocalCall(_, _, args, _) => { + for argument in args { + collect_expr_writes(argument, written); + } + } + Expr::ClosureCall(_, args) => { + for argument in args { + collect_expr_writes(argument, written); + } + } + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) + | Expr::And(lhs, rhs) + | Expr::Or(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + collect_expr_writes(lhs, written); + collect_expr_writes(rhs, written); + } + Expr::Neg(inner) + | Expr::Not(inner) + | Expr::ToOwned(inner) + | Expr::Borrow(inner) + | Expr::BorrowMut(inner) => collect_expr_writes(inner, written), + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + collect_expr_writes(condition, written); + collect_expr_writes(then_expr, written); + collect_expr_writes(else_expr, written); + } + Expr::Match { + value, + arms, + default, + .. + } => { + collect_expr_writes(value, written); for (_, arm) in arms { - resolve_expr(arm, expected, env)?; + collect_expr_writes(arm, written); } - resolve_expr(default, expected, env) + collect_expr_writes(default, written); } - Expr::OptionalGet { container, key, .. } => { - resolve_expr(container, None, env)?; - resolve_expr(key, None, env) + Expr::Block { stmts, expr } => { + collect_stmt_list_writes(stmts, written); + collect_expr_writes(expr, written); } - Expr::OptionUnwrapOr { - value, fallback, .. + Expr::ResultConstruct { payload, .. } => collect_expr_writes(payload, written), + Expr::ResultQuery { value, .. } => collect_expr_writes(value, written), + Expr::ResultTry { value, .. } => collect_expr_writes(value, written), + Expr::ResultMatch { + value, + ok_expr, + err_expr, + .. } => { - resolve_expr(value, None, env)?; - resolve_expr(fallback, expected, env) - } - Expr::Call(index, type_args, args, _, _) => { - let expected_args = super::typing::argument_schemas_for_call( - &env.function_list, - &env.function_impls, - &env.struct_schemas, - *index, - type_args, - ) - .or_else(|| { - super::typing::expected_container_argument_schemas( - &env.function_list, - &env.function_impls, - &env.struct_schemas, - *index, - args, - expected, - ) - }); - for (offset, arg) in args.iter_mut().enumerate() { - let expected_arg = expected_args - .as_ref() - .and_then(|schemas| schemas.get(offset)) - .and_then(|schema| schema.as_ref()); - resolve_expr(arg, expected_arg, env)?; - } - Ok(()) - } - Expr::LocalCall(slot, _, args, _) => { - let params = env.slots.get(slot).and_then(|schema| match schema { - TypeSchema::Callable { params, .. } => Some(params.clone()), - _ => None, - }); - for (offset, arg) in args.iter_mut().enumerate() { - let expected_arg = params.as_ref().and_then(|schemas| schemas.get(offset)); - resolve_expr(arg, expected_arg, env)?; - } - Ok(()) + collect_expr_writes(value, written); + collect_expr_writes(ok_expr, written); + collect_expr_writes(err_expr, written); } - Expr::ModuleCall(symbol, type_args, args, _) => { - let expected_args = env - .function_list - .iter() - .find(|function| function.symbol.as_ref() == Some(symbol)) - .and_then(|function| { - super::typing::argument_schemas_for_call( - &env.function_list, - &env.function_impls, - &env.struct_schemas, - function.index, - type_args, - ) - }); - for (offset, arg) in args.iter_mut().enumerate() { - let expected_arg = expected_args - .as_ref() - .and_then(|schemas| schemas.get(offset)) - .and_then(|schema| schema.as_ref()); - resolve_expr(arg, expected_arg, env)?; - } - Ok(()) + Expr::ResultMethod { + receiver, argument, .. + } => { + collect_expr_writes(receiver, written); + collect_expr_writes(argument, written); } - Expr::Closure(closure) => resolve_closure(closure, expected, env), + } +} + +fn find_resource_capturing_closure(expr: &Expr, env: &Env) -> Option { + match expr { + Expr::Closure(closure) => closure.capture_copies.iter().find_map(|(source, _)| { + env.slots + .get(source) + .filter(|schema| schema.contains_resource_with_named_types(&env.struct_schemas)) + .cloned() + }), + // An immediately invoked closure consumes its captures in the call. Expr::ClosureCall(closure, args) => { - resolve_closure(closure, expected, env)?; - for arg in args.iter_mut() { - resolve_expr(arg, None, env)?; - } - Ok(()) + let _ = closure; + args.iter() + .find_map(|child| find_resource_capturing_closure(child, env)) } + Expr::Block { stmts, expr } => stmts + .iter() + .find_map(|stmt| stmt_resource_capturing_closure(stmt, env)) + .or_else(|| find_resource_capturing_closure(expr, env)), + Expr::IfElse { + condition, + then_expr, + else_expr, + } => [condition.as_ref(), then_expr, else_expr] + .into_iter() + .find_map(|child| find_resource_capturing_closure(child, env)), + Expr::Match { + value, + arms, + default, + .. + } => find_resource_capturing_closure(value, env) + .or_else(|| { + arms.iter() + .find_map(|(_, arm)| find_resource_capturing_closure(arm, env)) + }) + .or_else(|| find_resource_capturing_closure(default, env)), + Expr::Call(_, _, args, _, _) + | Expr::ModuleCall(_, _, args, _) + | Expr::LocalCall(_, _, args, _) => args + .iter() + .find_map(|child| find_resource_capturing_closure(child, env)), Expr::Add(lhs, rhs) | Expr::Sub(lhs, rhs) | Expr::Mul(lhs, rhs) @@ -360,15 +2998,34 @@ fn resolve_expr( | Expr::Or(lhs, rhs) | Expr::Eq(lhs, rhs) | Expr::Lt(lhs, rhs) - | Expr::Gt(lhs, rhs) => { - resolve_expr(lhs, None, env)?; - resolve_expr(rhs, None, env) - } + | Expr::Gt(lhs, rhs) => find_resource_capturing_closure(lhs, env) + .or_else(|| find_resource_capturing_closure(rhs, env)), Expr::Neg(inner) | Expr::Not(inner) | Expr::ToOwned(inner) | Expr::Borrow(inner) - | Expr::BorrowMut(inner) => resolve_expr(inner, None, env), + | Expr::BorrowMut(inner) => find_resource_capturing_closure(inner, env), + Expr::ResultConstruct { payload, .. } => find_resource_capturing_closure(payload, env), + Expr::ResultQuery { value, .. } => find_resource_capturing_closure(value, env), + Expr::ResultTry { value, .. } => find_resource_capturing_closure(value, env), + Expr::ResultMatch { + value, + ok_expr, + err_expr, + .. + } => find_resource_capturing_closure(value, env) + .or_else(|| find_resource_capturing_closure(ok_expr, env)) + .or_else(|| find_resource_capturing_closure(err_expr, env)), + Expr::ResultMethod { + receiver, argument, .. + } => find_resource_capturing_closure(receiver, env) + .or_else(|| find_resource_capturing_closure(argument, env)), + Expr::OptionalGet { container, key, .. } => find_resource_capturing_closure(container, env) + .or_else(|| find_resource_capturing_closure(key, env)), + Expr::OptionUnwrapOr { + value, fallback, .. + } => find_resource_capturing_closure(value, env) + .or_else(|| find_resource_capturing_closure(fallback, env)), Expr::Null | Expr::Int(_) | Expr::Float(_) @@ -381,7 +3038,65 @@ fn resolve_expr( | Expr::Var(_) | Expr::MoveVar(_) | Expr::MoveField { .. } - | Expr::MoveIndex { .. } => Ok(()), + | Expr::MoveIndex { .. } => None, + } +} + +fn stmt_resource_capturing_closure(stmt: &Stmt, env: &Env) -> Option { + match stmt { + Stmt::Noop { .. } + | Stmt::FuncDecl { .. } + | Stmt::Break { .. } + | Stmt::Continue { .. } + | Stmt::Drop { .. } => None, + Stmt::Let { expr, .. } | Stmt::Assign { expr, .. } | Stmt::Expr { expr, .. } => { + find_resource_capturing_closure(expr, env) + } + Stmt::ClosureLet { closure, .. } => closure + .capture_copies + .iter() + .find_map(|(source, _)| { + env.slots + .get(source) + .filter(|schema| schema.contains_resource_with_named_types(&env.struct_schemas)) + .cloned() + }) + .or_else(|| find_resource_capturing_closure(&closure.body, env)), + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => find_resource_capturing_closure(condition, env) + .or_else(|| { + then_branch + .iter() + .find_map(|nested| stmt_resource_capturing_closure(nested, env)) + }) + .or_else(|| { + else_branch + .iter() + .find_map(|nested| stmt_resource_capturing_closure(nested, env)) + }), + Stmt::For { + init, + condition, + post, + body, + .. + } => stmt_resource_capturing_closure(init, env) + .or_else(|| find_resource_capturing_closure(condition, env)) + .or_else(|| stmt_resource_capturing_closure(post, env)) + .or_else(|| { + body.iter() + .find_map(|nested| stmt_resource_capturing_closure(nested, env)) + }), + Stmt::While { + condition, body, .. + } => find_resource_capturing_closure(condition, env).or_else(|| { + body.iter() + .find_map(|nested| stmt_resource_capturing_closure(nested, env)) + }), } } @@ -397,15 +3112,9 @@ fn resolve_construct( TypeSchema::Result { .. } => Some(result_schema.clone()), _ => None, }; - let contextual = match (expected, explicit.as_ref()) { + let expected_schema = match (expected, explicit.as_ref()) { (Some(expected_schema @ TypeSchema::Result { .. }), Some(explicit_schema)) => { - if !super::typing::result_branch_schemas_compatible( - &env.function_list, - &env.function_impls, - &env.struct_schemas, - expected_schema, - explicit_schema, - ) { + if !result_branches_partially_compatible(expected_schema, explicit_schema) { return Err(result_error( span, format!( @@ -414,41 +3123,92 @@ fn resolve_construct( ), )); } - Some(expected_schema.clone()) + expected_schema.clone() } - (Some(expected_schema @ TypeSchema::Result { .. }), None) => Some(expected_schema.clone()), - (None, Some(explicit_schema)) => Some(explicit_schema.clone()), + (Some(expected_schema @ TypeSchema::Result { .. }), None) => expected_schema.clone(), (Some(other), _) => { return Err(result_error( span, format!("Result::{} is not a value of type {other:?}", ctor_name(ok)), )); } - (None, None) => None, + (None, Some(explicit_schema)) => explicit_schema.clone(), + (None, None) => { + return Err(result_error( + span, + format!( + "Result::{} needs an explicit Result annotation for the inactive branch", + ctor_name(ok) + ), + )); + } }; - let Some(expected_schema) = contextual else { - return Err(result_error( - span, - format!( - "Result::{} needs an explicit Result annotation for the inactive branch", - ctor_name(ok) - ), - )); + let expected_branches = branch_schemas(&expected_schema).expect("driver matched Result"); + let explicit_branches = explicit.as_ref().and_then(branch_schemas); + let (expected_active, expected_inactive) = if ok { + (&expected_branches.0, &expected_branches.1) + } else { + (&expected_branches.1, &expected_branches.0) }; - let branch_expected = active_branch(&expected_schema, ok); - resolve_expr(payload, branch_expected, env)?; - let Some(active) = active_branch(&expected_schema, ok) else { - return Err(result_error( - span, - "internal Result schema lost its active branch".to_string(), - )); + let (explicit_active, explicit_inactive) = match &explicit_branches { + Some((ok_branch, err_branch)) if ok => (Some(ok_branch), Some(err_branch)), + Some((ok_branch, err_branch)) => (Some(err_branch), Some(ok_branch)), + None => (None, None), + }; + // A branch that is `Unknown` in the expectation is not a constraint; the + // explicit schema or the payload itself supplies it. This is what lets a + // method's fixed branch (for example `and_then`'s receiver error type) + // contextualize a constructor inside a callback while the free branch + // stays inferred. + let concrete_branch = |expected_branch: &TypeSchema, + explicit_branch: Option<&TypeSchema>| + -> Option { + if !matches!(expected_branch, TypeSchema::Unknown) { + return Some(expected_branch.clone()); + } + explicit_branch + .filter(|branch| !matches!(branch, TypeSchema::Unknown)) + .cloned() + }; + let active_schema = match concrete_branch(expected_active, explicit_active) { + Some(active_schema) => active_schema, + None => { + resolve_expr(payload, None, env)?; + let actual = authoritative_schema(payload, env).ok_or_else(|| { + result_error( + span, + format!("Result::{} payload type is unresolved", ctor_name(ok)), + ) + })?; + if schema_contains_unknown(&actual) { + return Err(result_error( + span, + format!("Result::{} payload type is unresolved", ctor_name(ok)), + )); + } + let inactive_schema = concrete_branch(expected_inactive, explicit_inactive) + .unwrap_or(TypeSchema::Unknown); + *result_schema = if ok { + TypeSchema::Result { + ok: Box::new(actual), + err: Box::new(inactive_schema), + } + } else { + TypeSchema::Result { + ok: Box::new(inactive_schema), + err: Box::new(actual), + } + }; + return Ok(()); + } }; + resolve_expr(payload, Some(&active_schema), env)?; if let Err(detail) = super::typing::check_result_payload( &env.function_list, &env.function_impls, &env.struct_schemas, payload, - active, + &active_schema, &env.slots, ) { return Err(result_error( @@ -456,10 +3216,36 @@ fn resolve_construct( format!("Result::{} payload: {detail}", ctor_name(ok)), )); } - *result_schema = expected_schema; + let inactive_schema = + concrete_branch(expected_inactive, explicit_inactive).unwrap_or(TypeSchema::Unknown); + *result_schema = if ok { + TypeSchema::Result { + ok: Box::new(active_schema), + err: Box::new(inactive_schema), + } + } else { + TypeSchema::Result { + ok: Box::new(inactive_schema), + err: Box::new(active_schema), + } + }; Ok(()) } +fn result_branches_partially_compatible(expected: &TypeSchema, explicit: &TypeSchema) -> bool { + let (Some((expected_ok, expected_err)), Some((explicit_ok, explicit_err))) = + (branch_schemas(expected), branch_schemas(explicit)) + else { + return false; + }; + branch_partially_compatible(&expected_ok, &explicit_ok) + && branch_partially_compatible(&expected_err, &explicit_err) +} + +fn branch_partially_compatible(expected: &TypeSchema, explicit: &TypeSchema) -> bool { + matches!(expected, TypeSchema::Unknown) || expected == explicit +} + // Each Result arm keeps its binding and expression explicit. The remaining // arguments are the scrutinee, its schema, the span, the expected type, and env. #[allow(clippy::too_many_arguments)] @@ -690,14 +3476,30 @@ fn resolve_closure( &closure.capture_copies, ); let saved = std::mem::replace(&mut env.slots, nested); + let saved_defs = env.local_defs.clone(); + let saved_volatile = std::mem::take(&mut env.volatile_sources); let saved_return = env.lexical_return.clone(); env.lexical_return = match expected_return { Some(schema @ TypeSchema::Result { .. }) => Some(schema.clone()), _ => None, }; let resolved = resolve_expr(&mut closure.body, expected_return, env); + let body_volatile = std::mem::replace(&mut env.volatile_sources, saved_volatile); env.slots = saved; + env.local_defs = saved_defs; env.lexical_return = saved_return; + if resolved.is_ok() { + let mut written = HashSet::new(); + collect_expr_writes(&closure.body, &mut written); + written.extend(body_volatile); + let sources: HashSet = closure + .capture_copies + .iter() + .filter(|(_, captured)| written.contains(captured)) + .map(|(source, _)| *source) + .collect(); + mark_env_volatile_sources(env, sources); + } resolved } @@ -719,15 +3521,6 @@ fn require_result_schema( } } -pub(crate) fn active_branch(schema: &TypeSchema, ok: bool) -> Option<&TypeSchema> { - match schema { - TypeSchema::Result { ok: ok_ty, err } => { - Some(if ok { ok_ty.as_ref() } else { err.as_ref() }) - } - _ => None, - } -} - fn infer_schema(expr: &Expr, env: &Env) -> Option { match expr { Expr::Null => Some(TypeSchema::Null), @@ -904,4 +3697,340 @@ mod tests { "{detail}" ); } + + fn callable_int_schema() -> TypeSchema { + TypeSchema::Callable { + params: vec![TypeSchema::Int], + result: Box::new(TypeSchema::Int), + } + } + + fn callable_source_env(source: LocalSlot, captured: LocalSlot) -> Env { + let mut slots = HashMap::new(); + slots.insert(source, callable_int_schema()); + slots.insert(captured, callable_int_schema()); + let mut local_defs = HashMap::new(); + local_defs.insert( + source, + LocalDefinition { + capture: TemporaryCallableCapture::Free, + target: None, + slots: slots.clone(), + }, + ); + Env { + slots, + functions: HashMap::new(), + function_list: Vec::new(), + function_impls: HashMap::new(), + struct_schemas: HashMap::new(), + local_defs, + volatile_sources: HashSet::new(), + lexical_return: None, + } + } + + fn shared_writer_closure(source: LocalSlot, captured: LocalSlot) -> ClosureExpr { + ClosureExpr { + param_slots: Vec::new(), + capture_copies: vec![(source, captured)], + body: Box::new(Expr::Block { + stmts: vec![Stmt::Assign { + kind: AssignmentKind::Set, + index: captured, + expr: Expr::FunctionRef(0, Vec::new()), + line: 1, + }], + expr: Box::new(Expr::Int(0)), + }), + } + } + + fn capture_walk<'a>(env: &'a Env, source: LocalSlot) -> CaptureWalk<'a> { + CaptureWalk { + slots: env.slots.clone(), + defs: env.local_defs.clone(), + owned_locals: HashSet::from([source]), + param_facts: HashMap::new(), + volatile_sources: HashSet::new(), + env, + } + } + + #[test] + fn closure_call_entry_marks_shared_callable_source_volatile() { + let source = 1; + let captured = 2; + let env = callable_source_env(source, captured); + let mut walk = capture_walk(&env, source); + let closure = shared_writer_closure(source, captured); + apply_expr_effects(&Expr::ClosureCall(closure, Vec::new()), &mut walk); + assert!(walk.volatile_sources.contains(&source)); + assert!(matches!( + walk.defs.get(&source).map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Unknown) + )); + assert!(walk.defs[&source].target.is_none()); + } + + #[test] + fn closure_let_entry_marks_shared_callable_source_volatile() { + let source = 1; + let captured = 2; + let env = callable_source_env(source, captured); + let mut walk = capture_walk(&env, source); + let closure = shared_writer_closure(source, captured); + bind_stmt( + &Stmt::ClosureLet { + line: 1, + closure, + expected_schema: None, + }, + &mut walk, + ); + assert!(walk.volatile_sources.contains(&source)); + assert!(matches!( + walk.defs.get(&source).map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Unknown) + )); + assert!(walk.defs[&source].target.is_none()); + } + + #[test] + fn nested_closure_capture_write_maps_back_to_outer_source() { + let outer_source = 1; + let outer_captured = 2; + let inner_captured = 3; + let env = callable_source_env(outer_source, outer_captured); + let inner = shared_writer_closure(outer_captured, inner_captured); + let outer = ClosureExpr { + param_slots: Vec::new(), + capture_copies: vec![(outer_source, outer_captured)], + body: Box::new(Expr::Closure(inner)), + }; + assert_eq!( + closure_capture_targets(&outer, &env), + HashSet::from([outer_source]) + ); + } + + #[test] + fn named_function_capture_write_maps_back_to_source() { + let source = 1; + let captured = 2; + let env = callable_source_env(source, captured); + let implementation = FunctionImpl { + param_slots: Vec::new(), + capture_copies: vec![(source, captured)], + body_stmts: vec![Stmt::Assign { + kind: AssignmentKind::Set, + index: captured, + expr: Expr::FunctionRef(0, Vec::new()), + line: 1, + }], + body_expr: Expr::Int(0), + body_expr_line: 1, + }; + assert_eq!( + function_capture_targets( + 7, + &Env { + function_impls: HashMap::from([(7, implementation)]), + ..env + } + ), + HashSet::from([source]) + ); + } + + fn free_factory_decl(index: u16, arity: u8) -> FunctionDecl { + FunctionDecl { + name: format!("free_factory_{index}"), + arity, + index, + args: (0..arity).map(|offset| format!("arg{offset}")).collect(), + arg_schemas: (0..arity).map(|_| Some(callable_int_schema())).collect(), + return_schema: Some(callable_int_schema()), + type_params: Vec::new(), + exported: false, + return_type: ValueType::Callable, + symbol: None, + } + } + + fn free_factory_impl() -> FunctionImpl { + FunctionImpl { + param_slots: Vec::new(), + capture_copies: Vec::new(), + body_stmts: Vec::new(), + body_expr: Expr::Closure(ClosureExpr { + param_slots: Vec::new(), + capture_copies: Vec::new(), + body: Box::new(Expr::Int(0)), + }), + body_expr_line: 1, + } + } + + #[test] + fn diagnostic_walk_inherits_same_frame_volatile_sources() { + let source = 1; + let mut env = callable_source_env(source, 2); + env.functions.insert(0, free_factory_decl(0, 0)); + env.function_list.push(free_factory_decl(0, 0)); + env.function_impls.insert(0, free_factory_impl()); + env.volatile_sources.insert(source); + env.local_defs + .insert(source, volatile_definition(&env.slots)); + let expr = Expr::Block { + stmts: vec![Stmt::Assign { + kind: AssignmentKind::Set, + index: source, + expr: Expr::FunctionRef(0, Vec::new()), + line: 1, + }], + expr: Box::new(Expr::LocalCall(source, Vec::new(), Vec::new(), None)), + }; + let capture = find_temporary_callable_capture(&expr, &env); + assert!( + matches!(capture, TemporaryCallableCapture::Unknown), + "the diagnostic walk must keep the same-frame volatile source untrusted, got {capture:?}" + ); + } + + #[test] + fn named_callee_maps_caller_volatile_source_and_keeps_equal_id_param_fresh() { + let source = 7; + let captured = 20; + let unrelated = 9; + let mut env = callable_source_env(source, 2); + env.slots.insert(unrelated, callable_int_schema()); + env.functions.insert(1, free_factory_decl(1, 0)); + env.function_list.push(free_factory_decl(1, 0)); + env.function_impls.insert(1, free_factory_impl()); + let mut caller = capture_walk(&env, source); + caller.volatile_sources.insert(source); + caller.volatile_sources.insert(unrelated); + let function = free_factory_decl(0, 1); + let implementation = FunctionImpl { + param_slots: vec![unrelated], + capture_copies: vec![(source, captured)], + body_stmts: vec![ + Stmt::Assign { + kind: AssignmentKind::Set, + index: captured, + expr: Expr::FunctionRef(1, Vec::new()), + line: 1, + }, + Stmt::Assign { + kind: AssignmentKind::Set, + index: unrelated, + expr: Expr::FunctionRef(1, Vec::new()), + line: 1, + }, + ], + body_expr: Expr::Int(0), + body_expr_line: 1, + }; + let callee = function_capture_walk( + &function, + &implementation, + &[], + &caller, + &mut HashSet::new(), + &mut HashSet::new(), + 0, + ); + assert_eq!( + callee.volatile_sources, + HashSet::from([captured]), + "only the actual capture pair may seed the callee frame" + ); + assert!(matches!( + callee + .defs + .get(&captured) + .map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Unknown) + )); + assert!(callee.defs[&captured].target.is_none()); + assert!(matches!( + callee + .defs + .get(&unrelated) + .map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Free) + )); + assert!(matches!( + callee.defs[&unrelated].target.as_deref(), + Some(CallableTarget::Function(1)) + )); + } + + #[test] + fn closure_body_maps_caller_volatile_source_and_keeps_equal_id_param_fresh() { + let source = 30; + let captured = 31; + let unrelated = 9; + let mut env = callable_source_env(source, 2); + env.slots.insert(unrelated, callable_int_schema()); + env.functions.insert(1, free_factory_decl(1, 0)); + env.function_list.push(free_factory_decl(1, 0)); + env.function_impls.insert(1, free_factory_impl()); + let mut caller = capture_walk(&env, source); + caller.volatile_sources.insert(source); + caller.volatile_sources.insert(unrelated); + let stmts = vec![ + Stmt::Assign { + kind: AssignmentKind::Set, + index: captured, + expr: Expr::FunctionRef(1, Vec::new()), + line: 1, + }, + Stmt::Assign { + kind: AssignmentKind::Set, + index: unrelated, + expr: Expr::FunctionRef(1, Vec::new()), + line: 1, + }, + ]; + let closure = ClosureExpr { + param_slots: vec![unrelated], + capture_copies: vec![(source, captured)], + body: Box::new(Expr::Block { + stmts: stmts.clone(), + expr: Box::new(Expr::Int(0)), + }), + }; + let mut nested = closure_body_walk( + &closure, + &caller.slots, + &[], + &caller, + &mut HashSet::new(), + &mut HashSet::new(), + 0, + ); + assert_eq!( + nested.volatile_sources, + HashSet::from([captured]), + "only the actual capture pair may seed the closure body frame" + ); + bind_stmts(&stmts, &mut nested); + assert!(matches!( + nested + .defs + .get(&captured) + .map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Unknown) + )); + assert!(nested.defs[&captured].target.is_none()); + assert!(matches!( + nested + .defs + .get(&unrelated) + .map(|definition| &definition.capture), + Some(TemporaryCallableCapture::Free) + )); + } } diff --git a/src/compiler/source_loader/graph.rs b/src/compiler/source_loader/graph.rs index 576c79fd..1144f56b 100644 --- a/src/compiler/source_loader/graph.rs +++ b/src/compiler/source_loader/graph.rs @@ -1875,6 +1875,12 @@ fn resolve_expr_imported_calls( | Expr::BorrowMut(inner) => { resolve_expr_imported_calls(ctx, inner, line, parsed_semantic_index.as_deref_mut())?; } + Expr::ResultMethod { + receiver, argument, .. + } => { + resolve_expr_imported_calls(ctx, receiver, line, parsed_semantic_index.as_deref_mut())?; + resolve_expr_imported_calls(ctx, argument, line, parsed_semantic_index.as_deref_mut())?; + } Expr::ResultConstruct { payload, .. } => { resolve_expr_imported_calls(ctx, payload, line, parsed_semantic_index.as_deref_mut())?; } diff --git a/src/compiler/try_anf.rs b/src/compiler/try_anf.rs index 8cae52ab..9932cca9 100644 --- a/src/compiler/try_anf.rs +++ b/src/compiler/try_anf.rs @@ -182,6 +182,12 @@ fn attach_expr_schema( Expr::ResultQuery { value, .. } | Expr::ResultTry { value, .. } => { attach_expr_schema(value, schemas, structs); } + Expr::ResultMethod { + receiver, argument, .. + } => { + attach_expr_schema(receiver, schemas, structs); + attach_expr_schema(argument, schemas, structs); + } Expr::Null | Expr::Int(_) | Expr::Float(_) @@ -356,6 +362,12 @@ fn rewrite_children(expr: &mut Expr, locals: &mut usize) -> Result<(), ParseErro Expr::ResultQuery { value, .. } | Expr::ResultTry { value, .. } => { rewrite_expr(value, locals) } + Expr::ResultMethod { + receiver, argument, .. + } => { + rewrite_expr(receiver, locals)?; + rewrite_expr(argument, locals) + } Expr::Null | Expr::Int(_) | Expr::Float(_) @@ -567,6 +579,9 @@ fn contains_try(expr: &Expr) -> bool { .. } => contains_try(value) || contains_try(ok_expr) || contains_try(err_expr), Expr::ResultQuery { value, .. } => contains_try(value), + Expr::ResultMethod { + receiver, argument, .. + } => contains_try(receiver) || contains_try(argument), Expr::Null | Expr::Int(_) | Expr::Float(_) diff --git a/src/compiler/typing.rs b/src/compiler/typing.rs index bd4d72e0..f4bb3fe2 100644 --- a/src/compiler/typing.rs +++ b/src/compiler/typing.rs @@ -1080,6 +1080,26 @@ pub(crate) fn check_result_payload( Ok(()) } +/// Schema-assignment compatibility check without a payload expression. +/// +/// Used by the Result type owner for combinator receiver/callback contracts +/// (callback parameter and return schemas, fallback schemas and annotated +/// result branches). Numeric widening and nominal resource identity follow the +/// same strict rules as `check_result_payload`, and generic parameters must +/// match exactly rather than degrading to `Unknown`. +pub(crate) fn schema_assignment_mismatch( + functions: &[FunctionDecl], + function_impls: &HashMap, + struct_schemas: &HashMap, + expected: &TypeSchema, + actual: &TypeSchema, +) -> Option { + let typing = ResultTyping::new(functions, function_impls, struct_schemas); + let mut context = typing.context(); + context.result_payload_strict = true; + helpers::find_declared_schema_mismatch(expected, actual, &mut context, String::new()) +} + pub(crate) fn contextual_callable_slot_schemas( functions: &[FunctionDecl], function_impls: &HashMap, @@ -1208,18 +1228,6 @@ fn expected_named_or_container_field_schema( (!matches!(schema, TypeSchema::Unknown)).then_some(schema) } -pub(crate) fn result_branch_schemas_compatible( - functions: &[FunctionDecl], - function_impls: &HashMap, - struct_schemas: &HashMap, - expected: &TypeSchema, - actual: &TypeSchema, -) -> bool { - let typing = ResultTyping::new(functions, function_impls, struct_schemas); - let context = typing.context(); - context.substitute_schema_generics(expected) == context.substitute_schema_generics(actual) -} - #[cfg(test)] mod catalog_call_resolution_tests { use std::sync::Arc; diff --git a/src/compiler/typing/collect.rs b/src/compiler/typing/collect.rs index 3312bec1..fe73f6fa 100644 --- a/src/compiler/typing/collect.rs +++ b/src/compiler/typing/collect.rs @@ -342,6 +342,12 @@ fn collect_root_expr( operand(value, false); operand(fallback, true); } + Expr::ResultMethod { + receiver, argument, .. + } => { + operand(receiver, false); + operand(argument, false); + } Expr::And(lhs, rhs) | Expr::Or(lhs, rhs) => { operand(lhs, false); operand(rhs, true); @@ -1199,6 +1205,31 @@ fn collect_expr_types( ); let _ = context.infer_expr_type(expr, state); } + Expr::ResultMethod { + receiver, argument, .. + } => { + collect_expr_types( + receiver, + state, + local_types, + local_schemas, + local_schema_labels, + callable_slots, + optional_slots, + context, + ); + collect_expr_types( + argument, + state, + local_types, + local_schemas, + local_schema_labels, + callable_slots, + optional_slots, + context, + ); + let _ = context.infer_expr_type(expr, state); + } Expr::ResultConstruct { payload, .. } => { collect_expr_types( payload, diff --git a/src/compiler/typing/context.rs b/src/compiler/typing/context.rs index 52ebc059..27cffd3f 100644 --- a/src/compiler/typing/context.rs +++ b/src/compiler/typing/context.rs @@ -1604,6 +1604,13 @@ impl<'a> TypeContext<'a> { let _ = self.infer_expr_type(value, state); BoundType::Bool } + Expr::ResultMethod { + receiver, argument, .. + } => { + let _ = self.infer_expr_type(receiver, state); + let _ = self.infer_expr_type(argument, state); + BoundType::Unknown + } Expr::ResultTry { value, operand_schema, diff --git a/src/compiler/typing/helpers.rs b/src/compiler/typing/helpers.rs index 04158e1a..e73c5998 100644 --- a/src/compiler/typing/helpers.rs +++ b/src/compiler/typing/helpers.rs @@ -1916,6 +1916,12 @@ pub(super) fn expr_contains_param_add(expr: &Expr, param_slots: &[LocalSlot]) -> expr_contains_param_add(value, param_slots) || expr_contains_param_add(fallback, param_slots) } + Expr::ResultMethod { + receiver, argument, .. + } => { + expr_contains_param_add(receiver, param_slots) + || expr_contains_param_add(argument, param_slots) + } Expr::Call(_, _, args, _, _) | Expr::LocalCall(_, _, args, _) | Expr::ModuleCall(_, _, args, _) => args @@ -1999,6 +2005,9 @@ pub(super) fn expr_uses_param(expr: &Expr, param_slots: &[LocalSlot]) -> bool { Expr::OptionUnwrapOr { value, fallback, .. } => expr_uses_param(value, param_slots) || expr_uses_param(fallback, param_slots), + Expr::ResultMethod { + receiver, argument, .. + } => expr_uses_param(receiver, param_slots) || expr_uses_param(argument, param_slots), Expr::Call(_, _, args, _, _) | Expr::LocalCall(_, _, args, _) | Expr::ModuleCall(_, _, args, _) => { @@ -2251,6 +2260,13 @@ pub(super) fn legalize_expr( BoundType::Unknown } } + Expr::ResultMethod { + receiver, argument, .. + } => { + let _ = legalize_expr(receiver, state, context, site, host_resolution); + let _ = legalize_expr(argument, state, context, site, host_resolution); + BoundType::Unknown + } Expr::ResultConstruct { payload, .. } => { let _ = legalize_expr(payload, state, context, site, host_resolution); BoundType::Map diff --git a/src/compiler/typing/validate.rs b/src/compiler/typing/validate.rs index cfeb5675..1bfa81ad 100644 --- a/src/compiler/typing/validate.rs +++ b/src/compiler/typing/validate.rs @@ -1053,6 +1053,27 @@ pub(super) fn validate_expr( merge_bound_types(arm_type, default_ty) } } + Expr::ResultMethod { + receiver, argument, .. + } => { + let _ = validate_expr( + receiver, + state, + line_context, + source_name, + context, + strict_function_add_types, + )?; + let _ = validate_expr( + argument, + state, + line_context, + source_name, + context, + strict_function_add_types, + )?; + BoundType::Unknown + } Expr::ResultConstruct { payload, .. } => { let _ = validate_expr( payload, diff --git a/tests/result_combinator_tests.rs b/tests/result_combinator_tests.rs new file mode 100644 index 00000000..972032f5 --- /dev/null +++ b/tests/result_combinator_tests.rs @@ -0,0 +1,1068 @@ +#![cfg(feature = "runtime")] + +use std::sync::{Arc, Mutex}; + +use pd_host_function::pd_host_function; +use vm::{ + CompileSourceFileOptions, HostFunctionDescriptor, HostFunctionRegistry, HostModuleDescriptor, + SourceFlavor, Value, Vm, VmResult, VmStatus, compile_source, +}; + +fn eval(source: &str) -> Value { + let compiled = compile_source(source).expect("Result combinator source should compile"); + let mut machine = Vm::new(compiled.program.with_local_count(compiled.locals)); + machine.set_fuel(100_000); + assert_eq!( + machine.run().expect("Result combinator program should run"), + VmStatus::Halted + ); + machine + .stack() + .last() + .cloned() + .expect("Result combinator program should leave a value") +} + +fn reject(source: &str) -> String { + match compile_source(source) { + Ok(_) => panic!("Result combinator source should be rejected: {source}"), + Err(error) => error.to_string(), + } +} + +#[test] +fn map_transforms_ok_payload_and_passes_err_payload_through() { + let source = r#" + let ok_value: Result = Result::Ok(2); + let err_value: Result = Result::Err(9); + let ok_mapped = ok_value.map(|value| value + 1); + let err_mapped = err_value.map(|value| value + 1); + let ok_payload = match ok_mapped { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_payload = match err_mapped { + Result::Ok(value) => -1, + Result::Err(error) => error, + }; + let ok_flag = ok_mapped.is_ok(); + let err_flag = err_mapped.is_err(); + let observed = if ok_flag && err_flag => { 1 } else => { 0 }; + ok_payload + err_payload + observed; + "#; + // Ok(2) -> Ok(3); Err(9) stays Err(9); both tag checks hold. + assert_eq!(eval(source), Value::Int(13)); +} + +#[test] +fn map_rejects_non_result_receivers() { + let diagnostic = reject("let value: int = 1; let mapped = value.map(|item| item + 1);"); + assert!( + diagnostic.contains("Result"), + "map on a scalar must report the Result receiver requirement: {diagnostic}" + ); +} + +#[test] +fn map_err_converts_the_error_branch_and_passes_ok_payload_through() { + let source = r#" + fn map_number(error: int) -> string { + "converted" + } + let ok_value: Result = Result::Ok(4); + let err_value: Result = Result::Err(6); + let ok_mapped = ok_value.map_err(map_number); + let err_mapped = err_value.map_err(map_number); + let ok_payload = match ok_mapped { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_observed = match err_mapped { + Result::Ok(value) => "none", + Result::Err(error) => error, + }; + let ok_flag = ok_mapped.is_ok(); + let err_flag = err_mapped.is_err(); + let observed = if ok_flag && err_flag && err_observed == "converted" => { 1 } else => { 0 }; + ok_payload + observed; + "#; + assert_eq!(eval(source), Value::Int(5)); +} + +#[test] +fn map_err_conversion_feeds_question_mark_with_matching_error_type() { + let source = r#" + fn load() -> Result { + Result::Err("bad") + } + fn convert(error: string) -> int { + 7 + } + fn relay() -> Result { + let value = load().map_err(convert)?; + Result::Ok(value) + } + let result = relay(); + let observed = match result { + Result::Ok(value) => value, + Result::Err(error) => error, + }; + observed; + "#; + assert_eq!(eval(source), Value::Int(7)); +} + +#[test] +fn map_err_requires_the_closure_error_type_to_match_the_question_mark_error() { + let diagnostic = reject( + r#" + fn load() -> Result { + Result::Err("bad") + } + fn convert(error: string) -> int { + 7 + } + fn relay() -> Result { + load().map_err(convert)? + } + relay(); + "#, + ); + assert!( + diagnostic.contains("error") || diagnostic.contains("map_err"), + "mismatched mapped error type must be rejected: {diagnostic}" + ); +} + +#[test] +fn and_then_uses_the_selected_branch_result() { + let source = r#" + fn continue_with(value: int) -> Result { + if value > 0 => { Result::Ok(value * 2) } else => { Result::Err(-3) } + } + let ok_value: Result = Result::Ok(5); + let err_value: Result = Result::Err(9); + let ok_chained = ok_value.and_then(continue_with); + let err_chained = err_value.and_then(continue_with); + let ok_payload = match ok_chained { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_payload = match err_chained { + Result::Ok(value) => -1, + Result::Err(error) => error, + }; + ok_payload + err_payload; + "#; + assert_eq!(eval(source), Value::Int(19)); +} + +#[test] +fn and_then_rejects_a_callback_error_type_mismatch() { + let diagnostic = reject( + r#" + fn continue_with(value: int) -> Result { + Result::Ok(value) + } + let value: Result = Result::Ok(1); + let chained = value.and_then(continue_with); + chained; + "#, + ); + assert!( + diagnostic.contains("and_then"), + "and_then must keep the receiver error type: {diagnostic}" + ); +} + +#[test] +fn or_else_recovers_the_error_branch_and_keeps_the_ok_branch() { + let source = r#" + fn recover(error: int) -> Result { + Result::Ok(error + 10) + } + let ok_value: Result = Result::Ok(3); + let err_value: Result = Result::Err(8); + let ok_chained: Result = ok_value.or_else(recover); + let err_chained: Result = err_value.or_else(recover); + let ok_payload = match ok_chained { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_payload = match err_chained { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + ok_payload + err_payload; + "#; + assert_eq!(eval(source), Value::Int(21)); +} + +#[test] +fn or_else_rejects_a_callback_success_type_mismatch() { + let diagnostic = reject( + r#" + fn recover(error: int) -> Result { + Result::Ok("no") + } + let value: Result = Result::Err(1); + let recovered = value.or_else(recover); + recovered; + "#, + ); + assert!( + diagnostic.contains("or_else"), + "or_else must keep the receiver success type: {diagnostic}" + ); +} + +#[test] +fn unwrap_or_returns_the_selected_payload_or_eager_fallback() { + let source = r#" + let ok_value: Result = Result::Ok(11); + let err_value: Result = Result::Err(2); + let ok_out = ok_value.unwrap_or(20); + let err_out = err_value.unwrap_or(30); + ok_out + err_out; + "#; + assert_eq!(eval(source), Value::Int(41)); +} + +#[test] +fn unwrap_or_fallback_is_eagerly_evaluated_even_when_ok_is_selected() { + let source = r#" + fn fail() -> Result { + Result::Err(7) + } + fn relay(value: Result) -> Result { + let out = value.unwrap_or(fail()?); + Result::Ok(out) + } + let result = relay(Result::Ok(3)); + let observed = match result { + Result::Ok(value) => -value, + Result::Err(error) => error, + }; + observed; + "#; + // The eager fallback `fail()?` exits with Err(7) even though the receiver + // is Ok(3): a lazy fallback would have produced Ok(3). + assert_eq!(eval(source), Value::Int(7)); +} + +#[test] +fn unwrap_or_else_calls_only_the_err_branch_callback_body() { + let source = r#" + fn relay(value: Result) -> Result { + let out = value.unwrap_or_else(|error| error + 100); + Result::Ok(out) + } + let ok_result = relay(Result::Ok(9)); + let err_result = relay(Result::Err(1)); + let ok_payload = match ok_result { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_payload = match err_result { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + ok_payload + err_payload; + "#; + // Ok(9) keeps the payload; Err(1) runs the lazy fallback body. + assert_eq!(eval(source), Value::Int(110)); +} + +#[test] +fn unwrap_or_else_rejects_a_callback_return_mismatch() { + let diagnostic = reject( + r#" + fn recover(error: int) -> string { + "no" + } + let value: Result = Result::Err(1); + let out = value.unwrap_or_else(recover); + out; + "#, + ); + assert!( + diagnostic.contains("unwrap_or_else"), + "unwrap_or_else must require the payload type: {diagnostic}" + ); +} + +#[test] +fn combinators_chain_left_to_right_across_both_error_channels() { + let source = r#" + fn build(value: bool) -> Result { + if value => { Result::Ok(2) } else => { Result::Err("bad") } + } + fn relay(ok: bool) -> Result { + let value = build(ok); + let final_result: Result = value + .map(|item| item + 1) + .map_err(|error| 8) + .and_then(|item| Result::Ok(item * 3)) + .or_else(|error| Result::Ok(error - 1)); + final_result + } + let ok_result = relay(true); + let err_result = relay(false); + let ok_payload = match ok_result { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let err_payload = match err_result { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + ok_payload + err_payload; + "#; + // Ok path: 2 -> 3 -> 9. Err path: "bad" -> 8 -> recovered 7. + assert_eq!(eval(source), Value::Int(16)); +} + +#[test] +fn callable_alias_and_generic_receivers_keep_their_schemas() { + let source = r#" + fn add_one(value: int) -> int { + value + 1 + } + fn wrap(value: T) -> Result { + Result::Ok(value) + } + fn apply_identity(value: Result) -> Result { + let mapped: Result = value.and_then(|item| Result::Ok(item)); + mapped + } + let alias = add_one; + let number: Result = Result::Ok(4); + let incremented = number.map(alias); + let text_result = apply_identity::(wrap::("hi")); + let number_payload = match incremented { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let text_ok = match text_result { + Result::Ok(value) => value == "hi", + Result::Err(error) => false, + }; + let observed = if text_ok => { 1 } else => { 0 }; + number_payload + observed; + "#; + assert_eq!(eval(source), Value::Int(6)); +} + +#[test] +fn named_payload_and_named_error_keep_their_declarations() { + let source = r#" + struct Payload { value: int } + struct Failure { code: int } + let value: Result = Result::Ok({ value: 3 }); + let mapped = value.map(|item| item); + let payload = match mapped { + Result::Ok(item) => item.value, + Result::Err(error) => -1, + }; + let failed: Result = Result::Err({ code: 12 }); + let converted = failed.map_err(|error| error.code); + let code = match converted { + Result::Ok(item) => -1, + Result::Err(error) => error, + }; + payload + code; + "#; + assert_eq!(eval(source), Value::Int(15)); +} + +#[test] +fn nullable_unwrap_or_keeps_the_existing_nullable_semantics() { + let source = r#" + let present: int? = 3; + let missing: int? = null; + let present_out = present.unwrap_or(9); + let missing_out = missing.unwrap_or(8); + present_out + missing_out; + "#; + assert_eq!(eval(source), Value::Int(11)); +} + +#[test] +fn plain_member_named_map_stays_a_field_read() { + let source = r#" + let record = { "map": 5 }; + let value = record.map; + value; + "#; + assert_eq!(eval(source), Value::Int(5)); +} + +#[test] +fn map_rejects_a_non_callable_argument() { + let diagnostic = reject( + r#" + let value: Result = Result::Ok(1); + let mapped = value.map(7); + mapped; + "#, + ); + assert!( + diagnostic.contains("callable"), + "map must require a callable callback: {diagnostic}" + ); +} + +#[test] +fn unwrap_or_rejects_a_fallback_type_mismatch() { + let diagnostic = reject( + r#" + let value: Result = Result::Ok(1); + let out = value.unwrap_or("no"); + out; + "#, + ); + assert!( + diagnostic.contains("unwrap_or"), + "unwrap_or must require the payload type: {diagnostic}" + ); +} + +#[test] +fn map_callback_captures_outer_local_by_value() { + let source = r#" + let bonus = 3; + let value: Result = Result::Ok(4); + let mapped = value.map(|item| item + bonus); + let out = match mapped { + Result::Ok(item) => item, + Result::Err(error) => -1, + }; + out; + "#; + assert_eq!(eval(source), Value::Int(7)); +} + +#[test] +fn map_rejects_a_callback_parameter_type_mismatch() { + let diagnostic = reject( + r#" + fn takes_text(value: string) -> string { + value + } + let value: Result = Result::Ok(1); + let mapped = value.map(takes_text); + mapped; + "#, + ); + assert!( + diagnostic.contains("map"), + "map must require the payload parameter type: {diagnostic}" + ); +} + +mod probe { + pub use vm::borrow_arg; + pub mod functions { + use super::super::*; + + static EVENTS: Mutex> = Mutex::new(Vec::new()); + + pub fn clear() { + EVENTS.lock().expect("probe log").clear(); + } + + pub fn events() -> Vec { + EVENTS.lock().expect("probe log").clone() + } + + fn record(tag: i64) { + EVENTS.lock().expect("probe log").push(tag); + } + + /// Appends a probe event and returns the tag. + #[pd_host_function(name = "probe::mark")] + fn mark(tag: i64) -> i64 { + record(tag); + tag + } + + /// Appends a probe event and publishes an Ok carrier. + #[pd_host_function(name = "probe::ok")] + fn ok(tag: i64) -> vm::VmResult> { + record(tag); + Ok(vm::GuestResult::Ok(tag)) + } + + /// Appends a probe event and publishes an Err carrier. + #[pd_host_function(name = "probe::err")] + fn err(tag: i64) -> vm::VmResult> { + record(tag); + Ok(vm::GuestResult::Err(tag)) + } + } +} + +static PROBE_LOCK: Mutex<()> = Mutex::new(()); + +fn probe_machine(source: &str) -> Vm { + let descriptors = vec![ + probe::functions::mark_descriptor(), + probe::functions::ok_descriptor(), + probe::functions::err_descriptor(), + ]; + let catalog = Arc::new(HostFunctionDescriptor::collect_catalog(&descriptors).unwrap()); + let compiled = vm::compile_source_with_flavor_and_options( + source, + SourceFlavor::RustScript, + CompileSourceFileOptions::default().with_host_api_catalog(catalog), + ) + .expect("probe source should compile"); + let mut registry = HostFunctionRegistry::empty(); + registry.set_capability_profile(vm::CapabilityProfile::deny_all()); + HostModuleDescriptor::install_descriptors(&mut registry, &descriptors).unwrap(); + for descriptor in &descriptors { + registry.authorize_registered_builtin_import(&descriptor.schema.name); + } + let mut machine = Vm::new(compiled.program.with_local_count(compiled.locals)); + registry.bind_vm_cached(&mut machine).unwrap(); + machine.set_fuel(100_000); + machine +} + +fn run_probe(source: &str) -> (Value, Vec) { + probe::functions::clear(); + let mut machine = probe_machine(source); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + let value = machine + .stack() + .last() + .cloned() + .expect("probe program should leave a value"); + (value, probe::functions::events()) +} + +#[test] +fn receiver_and_callback_are_evaluated_once_left_to_right() { + let _guard = PROBE_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let source = r#" + use probe; + fn relay(value: int, ok: bool) -> int { + let receiver = if ok => { probe::ok(value) } else => { probe::err(value) }; + let mapped = receiver.map(if probe::mark(20) == 20 => { |item| item + probe::mark(30) } else => { |item| item + probe::mark(40) }); + let out = match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + }; + out + } + relay(5, true) + relay(7, false); + "#; + let (value, events) = run_probe(source); + assert_eq!(value, Value::Int(42)); + // Receiver first (5), then the callback expression once (20), then only + // the selected Ok callback body (30). The Err pass never runs a body. + assert_eq!(events, vec![5, 20, 30, 7, 20]); +} + +#[test] +fn only_the_selected_callback_body_runs_for_err_receivers() { + let _guard = PROBE_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let source = r#" + use probe; + let receiver = probe::err(8); + let mapped = receiver.map(|item| item + probe::mark(90)); + let observed = match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + }; + observed; + "#; + let (value, events) = run_probe(source); + assert_eq!(value, Value::Int(8)); + assert_eq!(events, vec![8]); +} + +#[test] +fn eager_unwrap_or_fallback_runs_on_both_branches() { + let _guard = PROBE_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let source = r#" + use probe; + let ok_value = probe::ok(1); + let err_value = probe::err(2); + let ok_out = ok_value.unwrap_or(probe::mark(50)); + let err_out = err_value.unwrap_or(probe::mark(60)); + ok_out + err_out; + "#; + let (value, events) = run_probe(source); + assert_eq!(value, Value::Int(61)); + // The eager fallback runs for the Ok receiver too; only the Err receiver + // actually selects the fallback value. Both receivers are created first. + assert_eq!(events, vec![1, 2, 50, 60]); +} + +#[test] +fn unwrap_or_else_callback_body_is_lazy() { + let _guard = PROBE_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let source = r#" + use probe; + let ok_value = probe::ok(3); + let err_value = probe::err(4); + let ok_out = ok_value.unwrap_or_else(|error| probe::mark(70) + error); + let err_out = err_value.unwrap_or_else(|error| probe::mark(80) + error); + ok_out + err_out; + "#; + let (value, events) = run_probe(source); + assert_eq!(value, Value::Int(3 + 80 + 4)); + // Ok(3) never executes the callback body (no 70); Err(4) does (80). + assert_eq!(events, vec![3, 4, 80]); +} + +#[test] +fn callback_expression_question_mark_exits_before_the_method_branch() { + let _guard = PROBE_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let source = r#" + use probe; + fn checked(tag: int) -> Result { + Result::Err(tag) + } + fn relay() -> Result { + let receiver = probe::ok(9); + let mapped = receiver.map(if checked(20)? == 20 => { |item| probe::mark(30) + item } else => { |item| probe::mark(40) + item }); + mapped + } + let observed = relay(); + let out = match observed { + Result::Ok(value) => -value, + Result::Err(error) => error, + }; + out; + "#; + let (value, events) = run_probe(source); + assert_eq!(value, Value::Int(20)); + // Receiver evaluated first (9), then the callback argument stopped at the + // `?` exit (20); the branch and both callback bodies never ran (no 30/40). + assert_eq!(events, vec![9]); +} + +#[test] +fn module_function_receiver_and_callbacks_keep_typed_signatures() { + let lib = r#" + pub fn provide() -> Result { + Result::Ok(4) + } + pub fn transform(value: int) -> int { + value + 1 + } + pub fn convert(error: int) -> string { + "module" + } + "#; + let main = r#" + use self::lib; + let mapped = lib::provide().map(transform); + let payload = match mapped { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + let failed: Result = Result::Err(7); + let converted = failed.map_err(convert); + let converted_text = match converted { + Result::Ok(value) => "none", + Result::Err(error) => error, + }; + let observed = if converted_text == "module" => { 1 } else => { 0 }; + payload + observed; + "#; + let path = std::path::Path::new("/result-combinator/main.rss"); + let options = CompileSourceFileOptions::new().with_module_override_source("lib.rss", lib); + let compiled = vm::compile_source_at_path_with_flavor_and_options( + path, + main, + SourceFlavor::RustScript, + options, + ) + .expect("module combinator source should compile"); + let mut machine = Vm::new(compiled.program.with_local_count(compiled.locals)); + machine.set_fuel(100_000); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + assert_eq!(machine.stack().last(), Some(&Value::Int(6))); +} + +#[test] +fn repl_entry_types_combinators_with_carried_locals() { + let source = r#" + let value: Result = Result::Ok(2); + let mapped = value.map(|item| item + 1); + let out = match mapped { + Result::Ok(item) => item, + Result::Err(error) => -1, + }; + out; + "#; + let compiled = + vm::compile_source_for_repl_with_locals(source, &[]).expect("REPL source should compile"); + let mut machine = Vm::new( + compiled + .compiled + .program + .with_local_count(compiled.compiled.locals), + ); + machine.set_fuel(100_000); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + assert_eq!(machine.stack().last(), Some(&Value::Int(3))); +} + +#[test] +fn analyzer_entry_accepts_typed_combinators() { + let source = r#" + let value: Result = Result::Ok(1); + let mapped = value.map(|item| item + 1); + let failed: Result = Result::Err(2); + let recovered = failed.unwrap_or_else(|error| error + 1); + "#; + let model = vm::analyze_source(source).expect("analyzer must accept typed combinators"); + assert!(model.diagnostics().is_empty(), "{:?}", model.diagnostics()); +} + +#[test] +fn resource_free_temporary_factory_callback_keeps_construction_and_selected_body() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn make_callback(tag: int) -> fn(int) -> int { + probe::mark(tag); + |item| item + probe::mark(tag + 1) + } + fn relay(value: Result, tag: int) -> int { + let mapped = value.map(make_callback(tag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + let ok_out = relay(probe::ok(1), 20); + let err_out = relay(probe::err(2), 30); + ok_out + err_out; + "#; + let (value, events) = run_probe(source); + // Ok: 1 -> factory 20 -> body 21 => 22. Err: 2 -> factory 30, no body. + assert_eq!(value, Value::Int(24)); + assert_eq!(events, vec![1, 20, 21, 2, 30]); +} + +#[test] +fn resource_free_local_return_factory_and_forwarding_stay_executable() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn make_callback(tag: int) -> fn(int) -> int { + let callback = |item| item + tag; + probe::mark(tag); + callback + } + fn id(callback: fn(int) -> int) -> fn(int) -> int { + callback + } + fn relay(value: Result, tag: int) -> int { + let mapped = value.map(id(make_callback(tag))); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + let ok_out = relay(probe::ok(1), 20); + let err_out = relay(probe::err(2), 30); + ok_out + err_out; + "#; + let (value, events) = run_probe(source); + // Ok: 1 -> factory 20 -> selected body 1 + 20 => 21. Err: 2 -> factory 30, + // the unselected body never runs and the error payload passes through. + assert_eq!(value, Value::Int(23)); + assert_eq!(events, vec![1, 20, 2, 30]); +} + +#[test] +fn resource_free_statement_if_and_alias_reassignment_stay_executable() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn make_if(tag: int, flag: bool) -> fn(int) -> int { + let mut callback = |value| value + tag; + if flag { + callback = |value| value + probe::mark(tag + 1); + } else { + callback = |value| value + tag; + } + callback + } + fn make_alias(tag: int) -> fn(int) -> int { + let mut callback = |value| value + tag; + let alias = callback; + callback = |value| value + probe::mark(tag + 2); + alias + } + fn relay_if(value: Result, tag: int, flag: bool) -> int { + let mapped = value.map(make_if(tag, flag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + fn relay_alias(value: Result, tag: int) -> int { + let mapped = value.map(make_alias(tag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + let selected = relay_if(probe::ok(1), 10, true); + let fallback = relay_if(probe::ok(2), 20, false); + let aliased = relay_alias(probe::ok(3), 30); + selected + fallback + aliased; + "#; + let (value, events) = run_probe(source); + // Then branch: 1 + mark(11) = 12. Else branch: 2 + 20 = 22. The alias + // keeps the callback bound before the source slot is reassigned: + // 3 + 30 = 33. 12 + 22 + 33 = 67. + assert_eq!(value, Value::Int(12 + 22 + 33)); + assert_eq!(events, vec![1, 11, 2, 3]); +} + +#[test] +fn resource_free_frozen_alias_before_shared_writer_stays_executable() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn make_free(tag: int) -> fn(int) -> int { + |item| item + } + fn make_writing(tag: int) -> fn(int) -> int { + |item| item + probe::mark(tag) + } + fn make(tag: int) -> fn(int) -> int { + let mut factory = make_free; + let alias = factory; + let writer = || if true => { + factory = make_writing; + 0 + } else => { + factory = make_free; + 0 + }; + writer(); + alias(tag) + } + fn relay(value: Result, tag: int) -> int { + let mapped = value.map(make(tag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + let ok_out = relay(probe::ok(1), 20); + let err_out = relay(probe::err(2), 30); + ok_out + err_out; + "#; + let (value, events) = run_probe(source); + // The alias keeps the target frozen before the writer barrier. make_writing + // must not run, and map still passes both payloads through. + assert_eq!(value, Value::Int(3)); + assert_eq!(events, vec![1, 2]); +} + +#[test] +fn resource_free_scalar_loop_in_temporary_factory_stays_executable() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn make_while(n: int, tag: int) -> fn(int) -> int { + let mut total = 0; + let mut index = 0; + while index < n { + total = total + index; + index = index + 1; + } + let callback = |value| value + total + tag; + callback + } + fn make_for(n: int, tag: int) -> fn(int) -> int { + let mut total = 0; + for index in 0..n { + total = total + index; + } + let callback = |value| value + total + tag; + callback + } + fn relay_while(value: Result, n: int, tag: int) -> int { + let mapped = value.map(make_while(n, tag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + fn relay_for(value: Result, n: int, tag: int) -> int { + let mapped = value.map(make_for(n, tag)); + match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + } + } + let while_out = relay_while(probe::ok(4), 3, 7); + let for_out = relay_for(probe::ok(5), 3, 9); + while_out + for_out; + "#; + let (value, events) = run_probe(source); + // while total 0+1+2=3: 4+3+7=14; for total 3: 5+3+9=17. + assert_eq!(value, Value::Int(31)); + assert_eq!(events, vec![4, 5]); +} + +#[test] +fn typed_unwrap_payload_in_function_tail_and_annotated_let() { + let _guard = PROBE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use probe; + fn pick_tail(value: Result) -> int { + value.unwrap_or(probe::mark(10)) + } + fn pick_let(value: Result) -> int { + let out: int = value.unwrap_or(probe::mark(11)); + out + } + fn pick_else_tail(value: Result) -> int { + value.unwrap_or_else(|error| probe::mark(12) + error) + } + fn pick_else_let(value: Result) -> int { + let out: int = value.unwrap_or_else(|error| probe::mark(13) + error); + out + } + let ok_out = pick_tail(probe::ok(1)); + let err_let = pick_let(probe::err(2)); + let ok_else = pick_else_tail(probe::ok(3)); + let err_else_let = pick_else_let(probe::err(4)); + ok_out + err_let + ok_else + err_else_let; + "#; + let (value, events) = run_probe(source); + // Ok(1) selects 1 after the eager fallback mark 10; Err(2) selects the + // eager fallback 11; Ok(3) leaves the lazy callback body unrun; Err(4) + // runs the lazy body (13 + 4 = 17). 1 + 11 + 3 + 17 = 32. + assert_eq!(value, Value::Int(32)); + assert_eq!(events, vec![1, 10, 2, 11, 3, 4, 13]); +} + +#[test] +fn typed_unwrap_payload_supports_non_int_and_nested_result() { + let source = r#" + fn pick_text(value: Result) -> string { + value.unwrap_or("fallback") + } + fn pick_text_else(value: Result) -> string { + value.unwrap_or_else(|error| error) + } + fn pick_nested(value: Result, int>) -> Result { + value.unwrap_or(Result::Ok(7)) + } + fn pick_nested_else(value: Result, int>) -> Result { + value.unwrap_or_else(|error| Result::Ok(error + 1)) + } + let ok_text: Result = Result::Ok("ok"); + let err_text: Result = Result::Err("bad"); + let text_out = pick_text(ok_text); + let text_else_out = pick_text_else(err_text); + let inner: Result = Result::Ok(5); + let outer_ok: Result, int> = Result::Ok(inner); + let outer_err: Result, int> = Result::Err(6); + let nested_ok = pick_nested(outer_ok); + let nested_fallback = pick_nested(outer_err); + let nested_else_ok = pick_nested_else(outer_ok); + let nested_else_err = pick_nested_else(outer_err); + let nested_ok_payload = match nested_ok { + Result::Ok(item) => item, + Result::Err(error) => -error, + }; + let nested_fallback_payload = match nested_fallback { + Result::Ok(item) => item, + Result::Err(error) => -error, + }; + let nested_else_ok_payload = match nested_else_ok { + Result::Ok(item) => item, + Result::Err(error) => -error, + }; + let nested_else_err_payload = match nested_else_err { + Result::Ok(item) => item, + Result::Err(error) => -error, + }; + let text_flag = if text_out == "ok" && text_else_out == "bad" => { 1 } else => { 0 }; + text_flag + nested_ok_payload + nested_fallback_payload + nested_else_ok_payload + + nested_else_err_payload; + "#; + assert_eq!(eval(source), Value::Int(1 + 5 + 7 + 5 + 7)); +} + +#[test] +fn result_returning_combinators_still_reject_non_result_annotations() { + for (label, source) in [ + ( + "map", + r#" + fn bad(value: Result) -> int { + value.map(|item| item + 1) + } + "#, + ), + ( + "and_then", + r#" + fn bad(value: Result) -> int { + value.and_then(|item| Result::Ok(item + 1)) + } + "#, + ), + ] { + let diagnostic = reject(source); + assert!( + diagnostic.contains("produces a Result value, not int"), + "{label}: {diagnostic}" + ); + } +} + +#[test] +fn typed_unwrap_payload_still_requires_the_payload_type() { + for (label, source) in [ + ( + "unwrap_or", + r#" + fn bad(value: Result) -> string { + value.unwrap_or(0) + } + "#, + ), + ( + "unwrap_or_else", + r#" + fn bad(value: Result) -> string { + value.unwrap_or_else(|error| error) + } + "#, + ), + ] { + let diagnostic = reject(source); + assert!( + diagnostic.contains(label) && diagnostic.contains("expects string"), + "{label}: {diagnostic}" + ); + } +} diff --git a/tests/result_docs_tests.rs b/tests/result_docs_tests.rs index 8a172921..4a6b3bf3 100644 --- a/tests/result_docs_tests.rs +++ b/tests/result_docs_tests.rs @@ -33,7 +33,7 @@ fn product_result_rss_examples_compile_roundtrip_and_execute() { assert_eq!(machine.stack().last(), Some(&vm::Value::Int(expected))); count += 1; } - assert_eq!(count, 2); + assert_eq!(count, 5); } mod rust_example { @@ -95,3 +95,14 @@ mod rust_example { } } } + +mod callback_example { + include!("../docs/result_callback_example.rs"); + + #[test] + fn documented_rust_callback_example_is_exact_and_executes() { + let docs = include_str!("../docs/result.md"); + assert!(docs.contains(include_str!("../docs/result_callback_example.rs").trim())); + main().expect("documented callback example should run its full RSS-to-Rust path"); + } +} diff --git a/tests/result_host_tests.rs b/tests/result_host_tests.rs index 9649bd87..0942442e 100644 --- a/tests/result_host_tests.rs +++ b/tests/result_host_tests.rs @@ -366,3 +366,72 @@ fn callback_guest_result_both_variants_and_store_identity() { store.reset_for_reuse().unwrap(); assert!(callback.call(&mut store, (GuestResult::Ok(1),)).is_err()); } + +#[test] +fn callback_guest_result_converts_to_native_result_without_losing_branch_identity() { + let compiled = vm::compile_source( + "pub fn choose(mode: int) -> Result {\n\ + if mode == 0 => { Result::Ok(0) } else => { Result::Err(\"\") }\n\ + }\n\ + pub fn choose_bool(flag: bool) -> Result {\n\ + if flag => { Result::Ok(false) } else => { Result::Err(false) }\n\ + }\n\ + pub fn choose_zero(flag: bool) -> Result {\n\ + if flag => { Result::Ok(0) } else => { Result::Err(0) }\n\ + }", + ) + .unwrap(); + let mut store = vm::Store::new( + Vm::new(compiled.program.with_local_count(compiled.locals)), + (), + ); + store.vm_mut().set_fuel(100_000); + assert_eq!(store.run().unwrap(), VmStatus::Halted); + + let int_callback = store + .script_callback_by_name::<(i64,), GuestResult>("choose") + .unwrap(); + for (mode, expected) in [(0, Ok::(0)), (1, Err(String::new()))] { + let native: Result = int_callback.call(&mut store, (mode,)).unwrap().into(); + assert_eq!(native, expected); + } + + let bool_callback = store + .script_callback_by_name::<(bool,), GuestResult>("choose_bool") + .unwrap(); + for (flag, expected) in [(true, Ok(false)), (false, Err(false))] { + let native: Result = bool_callback.call(&mut store, (flag,)).unwrap().into(); + assert_eq!(native, expected); + } + + let zero_callback = store + .script_callback_by_name::<(bool,), GuestResult>("choose_zero") + .unwrap(); + for (flag, expected) in [(true, Ok::(0)), (false, Err(0))] { + let native: Result = zero_callback.call(&mut store, (flag,)).unwrap().into(); + assert_eq!(native, expected); + } +} + +#[test] +fn callback_native_result_keeps_outer_vm_errors_fatal() { + let source = "use result_sdk; pub fn host_call(mode: int) -> Result { result_sdk::tri(mode) }"; + let mut store = vm::Store::from_vm(machine(source)); + assert_eq!(store.run().unwrap(), VmStatus::Halted); + let callback = store + .script_callback_by_name::<(i64,), GuestResult>("host_call") + .unwrap(); + for (mode, expected) in [ + (0, Ok::(7)), + (1, Err("guest failure".to_string())), + ] { + let native: Result = callback.call(&mut store, (mode,)).unwrap().into(); + assert_eq!(native, expected); + } + match callback.call(&mut store, (2,)) { + Err(VmError::HostError(message)) => { + assert!(message.contains("transport failure"), "{message}"); + } + other => panic!("outer VM error must stay fatal, got {other:?}"), + } +} diff --git a/tests/result_language_service_tests.rs b/tests/result_language_service_tests.rs index 52215603..c5a99376 100644 --- a/tests/result_language_service_tests.rs +++ b/tests/result_language_service_tests.rs @@ -108,6 +108,33 @@ fn result_diagnostic_source_map_owns_constructor_and_match() { } } +#[test] +fn result_combinator_diagnostic_owns_exact_source_span() { + let source = "// 変換\r\npub fn relay() -> Result {\r\n let value: Result = Result::Ok(1);\r\n value.and_then(|item| Result::Ok(item))\r\n}\r\n"; + let slice = "value.and_then(|item| Result::Ok(item))"; + for _ in 0..2 { + assert_origin(source, source, false, slice); + assert_origin( + source, + "use self::lib as lib;\r\nlib::relay();\r\n", + true, + slice, + ); + } +} + +#[test] +fn compact_result_combinator_format_is_idempotent_and_preserves_execution() { + let source = "fn relay(value:Result)->Result{value.map(|item|item+1).map_err(|error|error-1)}let result=relay(Result::Ok(2));let answer=result.unwrap_or(9);answer;"; + let formatted = assert_format(source); + for method in [".map(", ".map_err(", ".unwrap_or("] { + assert!( + formatted.contains(method), + "formatted combinator source must keep {method}: {formatted}" + ); + } +} + fn execute(source: &str) -> Vec { let compiled = vm::compile_source(source).expect("formatter control must type check"); let mut machine = vm::Vm::new(compiled.program.with_local_count(compiled.locals)); diff --git a/tests/result_language_tests.rs b/tests/result_language_tests.rs index 4ee1e449..9a53138c 100644 --- a/tests/result_language_tests.rs +++ b/tests/result_language_tests.rs @@ -761,3 +761,25 @@ fn no_result_nested_inner_outer_returns_three() { "no-Result nested inner/outer", ); } + +#[test] +fn result_combinators_keep_generic_language_schemas() { + let source = r#" + fn wrap(value: T) -> Result { + Result::Ok(value) + } + fn identity(value: T) -> T { + value + } + let wrapped = wrap::(4); + let mapped = wrapped.map(identity::); + let recovered: Result = mapped.map_err(|error| 0); + let selected = recovered.unwrap_or(-1); + let value = match recovered { + Result::Ok(item) => item, + Result::Err(error) => error, + }; + selected + value; + "#; + assert_eq!(eval(source), vm::Value::Int(8)); +} diff --git a/tests/result_native_tests.rs b/tests/result_native_tests.rs index e8bb7403..3d082b94 100644 --- a/tests/result_native_tests.rs +++ b/tests/result_native_tests.rs @@ -540,3 +540,160 @@ fn dynamic_string_payload_both_branches_all_backends() { } } } + +fn combinator_loop_source() -> &'static str { + r#" + pub fn runner(flag: bool, seed: int) -> Result { + let mut i = 0; + let mut acc = seed; + while i < 64 { + let step: Result = if flag || i != 32 => { Result::Ok(i + seed) } else => { Result::Err(acc) }; + let mapped = step.map(|item| item + 1).map_err(|error| error + 2).unwrap_or(0); + let recovered: Result = if flag || i != 32 => { Result::Ok(acc + mapped) } else => { Result::Err(mapped) }; + let selected = recovered.and_then(|item| Result::Ok(item + 1)).unwrap_or_else(|error| error - 1); + acc = (acc + selected) % 1000; + i = i + 1; + } + Result::Ok(acc) + } + runner(input::flag(), input::value()); + "# +} + +fn expected_combinator_loop(flag: bool, seed: i64) -> i64 { + let mut acc = seed; + for i in 0..64i64 { + // `map`/`map_err` pass the selected branch through and `unwrap_or(0)` + // replaces the Err branch with the eager fallback 0. + let mapped = if flag || i != 32 { (i + seed) + 1 } else { 0 }; + let selected = if flag || i != 32 { + acc + mapped + 1 + } else { + // Err(0) -> and_then passes through -> unwrap_or_else body 0 - 1. + -1 + }; + acc = (acc + selected) % 1000; + } + acc +} + +fn combinator_machine( + decoded: bool, + trace: bool, + aot: bool, +) -> (Vm, Arc, Arc) { + let mut builder = vm::HostApiBuilder::new(); + builder.function(vm::HostFunctionSchema::with_return( + "input::flag", + vec![], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + "input::value", + vec![], + HostTypeSchema::Int, + )); + let compiled = vm::compile_source_with_flavor_and_options( + combinator_loop_source(), + vm::SourceFlavor::RustScript, + vm::CompileSourceFileOptions::new() + .with_host_api_catalog(Arc::new(builder.build().unwrap())), + ) + .unwrap(); + let program = compiled.program.with_local_count(compiled.locals); + let program = if decoded { + let bytes = vm::encode_program(&program).unwrap(); + let decoded = vm::decode_program(&bytes).unwrap(); + assert_eq!(vm::encode_program(&decoded).unwrap(), bytes); + decoded + } else { + program + }; + let mut machine = Vm::new_with_jit_config( + program, + vm::JitConfig { + enabled: trace, + hot_loop_threshold: 1, + max_trace_len: 512, + }, + ); + let flags = Arc::new(AtomicUsize::new(0)); + let values = Arc::new(AtomicUsize::new(0)); + machine.bind_function( + "input::flag", + Box::new(Input(Value::Bool(false), flags.clone())), + ); + machine.bind_function( + "input::value", + Box::new(Input(Value::Int(7), values.clone())), + ); + machine.set_fuel(100_000); + if aot { + machine + .compile_aot() + .expect("combinator loop must admit native AOT lowering"); + } + (machine, flags, values) +} + +fn assert_combinator_run( + label: &str, + machine: &mut Vm, + flags: &Arc, + values: &Arc, +) { + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + let (tag, payload) = vm::result::payload(machine.stack().last().unwrap()).unwrap(); + assert!(tag); + assert_eq!(payload, &Value::Int(expected_combinator_loop(false, 7))); + assert_eq!(flags.load(Ordering::SeqCst), 1); + assert_eq!(values.load(Ordering::SeqCst), 1); + eprintln!( + "B combinator native label={label} trace_native={} aot={} payload={payload:?}", + machine.jit_native_exec_count(), + machine.aot_exec_count() + ); +} + +#[test] +fn dynamic_result_combinator_loop_all_backends_and_loaded_bytecode() { + for mode in ["interpreter", "trace", "aot"] { + let (mut machine, flags, values) = + combinator_machine(false, mode == "trace", mode == "aot"); + assert_combinator_run(mode, &mut machine, &flags, &values); + if mode == "interpreter" { + assert_eq!(machine.jit_native_exec_count(), 0); + assert_eq!(machine.aot_exec_count(), 0); + } + if mode == "aot" { + let dump = machine.dump_aot_info(); + assert!( + dump.contains("lowering=ssa"), + "combinator AOT must keep native lowering: {dump}" + ); + assert!(machine.aot_exec_count() > 0); + } + if mode == "trace" { + let snapshot = machine.jit_snapshot(); + let native: Vec<_> = snapshot + .traces + .iter() + .filter(|trace| trace.executions > 0 && trace.ssa_text().contains("payload")) + .collect(); + assert!( + !native.is_empty(), + "combinator trace must execute a native payload region: {:?}", + snapshot.attempts + ); + assert!(machine.jit_native_exec_count() > 0); + } + } + // Loaded std bytecode must keep the lowered combinator control flow and + // still execute both in the interpreter and through native AOT. + let (mut loaded, flags, values) = combinator_machine(true, false, false); + assert_combinator_run("loaded-interpreter", &mut loaded, &flags, &values); + assert_eq!(loaded.aot_exec_count(), 0); + let (mut loaded_aot, flags, values) = combinator_machine(true, false, true); + assert_combinator_run("loaded-aot", &mut loaded_aot, &flags, &values); + assert!(loaded_aot.aot_exec_count() > 0); +} diff --git a/tests/result_sdk_callback_tests.rs b/tests/result_sdk_callback_tests.rs index 630b4eaa..db6ac988 100644 --- a/tests/result_sdk_callback_tests.rs +++ b/tests/result_sdk_callback_tests.rs @@ -156,3 +156,24 @@ fn malformed_result_callback_arguments_rejected_without_poisoning_store() { GuestResult::Ok(0) ); } + +#[test] +fn vm_aware_result_callback_converts_to_native_result() { + type R = GuestResult; + let compiled = vm::compile_source( + "pub fn echo(value: Result) -> Result { value }", + ) + .unwrap(); + let mut store = vm::Store::from_vm(Vm::new(compiled.program.with_local_count(compiled.locals))); + store.vm_mut().set_fuel(100_000); + assert_eq!(store.run().unwrap(), VmStatus::Halted); + let callback = store.vm_script_callback_by_name::<(R,), R>("echo").unwrap(); + for (input, expected) in [ + (GuestResult::Ok(0), Ok::(0)), + (GuestResult::Err(String::new()), Err(String::new())), + ] { + let native: Result = + callback.call_with_vm(&mut store, (input,)).unwrap().into(); + assert_eq!(native, expected); + } +} diff --git a/tests/result_sdk_resource_tests.rs b/tests/result_sdk_resource_tests.rs index 437ab707..bca49930 100644 --- a/tests/result_sdk_resource_tests.rs +++ b/tests/result_sdk_resource_tests.rs @@ -78,6 +78,7 @@ macro_rules! resource_type { resource_type!(Success, "result.success"); resource_type!(Failure, "result.failure"); mod generated { + pub use vm::arg; pub use vm::borrow_arg; pub mod functions { use super::super::*; @@ -104,6 +105,13 @@ mod generated { vm.host_context().set_module_state(value); 1 } + /// Consumes a bare success resource so a closure can move its capture + /// directly into a `TakeOwned` host parameter. + #[pd_host_function(name = "result_resource::consume_token")] + fn consume_token(value: ResourceOwned) -> i64 { + HANDLER_CALLS.fetch_add(1, Ordering::SeqCst); + value.into_inner().0 + } /// Takes the fixture's initial capture without a guest MoveLocal detach. #[pd_host_function(name = "result_resource::retire_initial")] fn retire_initial(vm: &mut Vm) -> VmResult { @@ -150,6 +158,7 @@ fn descriptors() -> Vec { generated::functions::fatal_descriptor(), generated::functions::borrow_descriptor(), generated::functions::retain_descriptor(), + generated::functions::consume_token_descriptor(), generated::functions::retire_initial_descriptor(), abort::suspend_descriptor(), ] @@ -196,6 +205,14 @@ fn callback_store() -> vm::Store { pub fn return_first_three(first: Result, resource>, second: Result, resource>, third: Result, resource>) -> Result, resource> { result_resource::observe(); first } pub fn retain_success(value: Result, resource>) -> int { result_resource::retain(value) } pub fn nullable(value: Result?, resource>) -> Result?, resource> { result_resource::observe(); value } + pub fn map_echo(value: Result, resource>) -> Result, resource> { result_resource::observe(); let mapped = value.map(|item| item); result_resource::observe(); mapped } + pub fn map_err_echo(value: Result, resource>) -> Result, resource> { result_resource::observe(); let mapped = value.map_err(|error| error); result_resource::observe(); mapped } + pub fn and_then_echo(value: Result, resource>) -> Result, resource> { result_resource::observe(); let mapped = value.and_then(|item| Result::Ok(item)); result_resource::observe(); mapped } + pub fn or_else_echo(value: Result, resource>) -> Result, resource> { result_resource::observe(); let mapped = value.or_else(|error| Result::Err(error)); result_resource::observe(); mapped } + pub fn to_error_result(value: Result, resource>) -> Result> { match value { Result::Ok(item) => Result::Ok(0), Result::Err(error) => Result::Err(error) } } + pub fn take_error(error: resource) -> int { let wrapped: Result, resource> = Result::Err(error); result_resource::take(wrapped) } + pub fn map_err_take(value: Result, resource>) -> Result { let narrowed = to_error_result(value); narrowed.map_err(take_error) } + pub fn map_fatal(value: Result) -> Result { value.map(|item| item + result_resource::fatal()) } "#, )); store.run().unwrap(); @@ -782,3 +799,1701 @@ fn generated_owned_result_both_branches_publish_then_take_exactly_once() { assert_eq!(descriptors[0].effects.len(), 2); assert_eq!(descriptors[1].effects.len(), 2); } + +fn compile_with_fixture_catalog(source: &str) -> Result<(), String> { + let descriptors = descriptors(); + let catalog = Arc::new(vm::HostFunctionDescriptor::collect_catalog(&descriptors).unwrap()); + match vm::compile_source_with_flavor_and_options( + source, + vm::SourceFlavor::RustScript, + vm::CompileSourceFileOptions::default().with_host_api_catalog(catalog), + ) { + Ok(_) => Ok(()), + Err(error) => Err(error.to_string()), + } +} + +fn resource_store(source: &str) -> vm::Store { + let mut store = vm::Store::from_vm(machine(source)); + store.run().unwrap(); + store +} + +fn assert_combinator_both_branches(name: &str) { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut store = callback_store(); + let callback = store + .vm_script_callback_by_name::<(OwnedResult,), OwnedResult>(name) + .unwrap(); + let closed = CLOSED.load(Ordering::SeqCst); + let dropped_ok = DROPPED_OK.load(Ordering::SeqCst); + let dropped_err = DROPPED_ERR.load(Ordering::SeqCst); + let observations = OBSERVATIONS.load(Ordering::SeqCst); + for (index, branch) in [true, false].into_iter().enumerate() { + let value = if branch { + GuestResult::Ok(ResourceOwned::new(Success(61))) + } else { + GuestResult::Err(ResourceOwned::new(Failure(73))) + }; + let returned = callback.call_with_vm(&mut store, (value,)).unwrap(); + // The post-combinator observe inside the guest callback sees the + // selected payload still owned by the generated carrier. + assert_eq!(OBSERVED_RESOURCE_COUNT.load(Ordering::SeqCst), 1); + assert_eq!( + OBSERVATIONS.load(Ordering::SeqCst), + observations + 2 * (index + 1) + ); + // The carrier return publishes the selected resource before the VM + // frame retires, so the host owns the only live handle. + assert_eq!(store.vm_mut().host_context().resource_count(), 0); + match returned { + GuestResult::Ok(value) => { + assert!(branch); + let mut value = value.into_inner(); + assert_eq!(value.0, 61); + value.begin_close(ResourceCloseReason::Requested).unwrap(); + } + GuestResult::Err(value) => { + assert!(!branch); + let mut value = value.into_inner(); + assert_eq!(value.0, 73); + value.begin_close(ResourceCloseReason::Requested).unwrap(); + } + } + } + assert_eq!(CLOSED.load(Ordering::SeqCst), closed + 2); + assert_eq!(DROPPED_OK.load(Ordering::SeqCst), dropped_ok + 1); + assert_eq!(DROPPED_ERR.load(Ordering::SeqCst), dropped_err + 1); +} + +#[test] +fn owned_result_combinator_map_transfers_payload_resource_on_both_branches() { + assert_combinator_both_branches("map_echo"); +} + +#[test] +fn owned_result_combinator_map_err_transfers_error_resource_on_both_branches() { + assert_combinator_both_branches("map_err_echo"); +} + +#[test] +fn owned_result_combinator_and_then_transfers_payload_resource_on_both_branches() { + assert_combinator_both_branches("and_then_echo"); +} + +#[test] +fn owned_result_combinator_or_else_transfers_error_resource_on_both_branches() { + assert_combinator_both_branches("or_else_echo"); +} + +#[test] +fn owned_result_map_err_consumes_error_resource_through_native_take() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut store = callback_store(); + let callback = store + .vm_script_callback_by_name::<(OwnedResult,), vm::GuestResult>("map_err_take") + .unwrap(); + let handler_calls = HANDLER_CALLS.load(Ordering::SeqCst); + let dropped_err = DROPPED_ERR.load(Ordering::SeqCst); + let returned = callback + .call_with_vm( + &mut store, + (GuestResult::Err(ResourceOwned::new(Failure(73))),), + ) + .unwrap(); + assert!( + matches!(returned, vm::GuestResult::Err(ref error) if *error == 73), + "{returned:?}" + ); + assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), handler_calls + 1); + assert_eq!(DROPPED_ERR.load(Ordering::SeqCst), dropped_err + 1); + assert_eq!(store.vm_mut().host_context().resource_count(), 0); +} + +#[test] +fn owned_result_combinator_fatal_callback_is_not_guest_err() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut store = callback_store(); + let callback = store + .vm_script_callback_by_name::<(vm::GuestResult,), vm::GuestResult>( + "map_fatal", + ) + .unwrap(); + let error = callback + .call_with_vm(&mut store, (vm::GuestResult::Ok(1),)) + .expect_err("host transport failure must stay outside the guest union"); + assert!( + matches!(error, vm::VmError::HostError(ref detail) if detail.contains("callback transport failure")), + "{error:?}" + ); +} + +#[test] +fn owned_result_combinator_rejects_resource_closure_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn take_ok(token: resource) -> int { + let wrapped: Result, resource> = Result::Ok(token); + result_resource::take(wrapped) + } + pub fn leak(value: Result, resource>, token: resource) -> Result> { + value.map(|item| take_ok(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("an unselected resource-capturing callback must be rejected"); + let text = error.to_string(); + assert!( + text.contains("closure capture") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_eager_unwrap_or_resource_fallback() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn discard(value: Result, resource>, fallback: resource) -> resource { + value.unwrap_or(fallback) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("an eager resource fallback has no unselected-branch destination"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_temporary_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.map(make_callback(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a temporary factory callback that captured a resource must be rejected"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_factory_created_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(flag: bool) -> fn(int) -> int { + let made: Result, resource> = result_resource::make(flag); + |value| result_resource::take(made) + } + pub fn leak(value: Result>) -> Result> { + value.map(make_callback(true)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a factory-created resource capture has no temporary owner either"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_aliased_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result>, token: resource) -> Result> { + let factory = make_callback; + value.map(factory(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a callable alias still resolves to the resource-capturing factory"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_temporary_factory_rejection_covers_callable_sites() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let cases = [ + ( + "map", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.map(make_callback(token)) + } + "#, + ), + ( + "map_err", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map_err(make_callback(token)) + } + "#, + ), + ( + "and_then", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> Result> { + |value| Result::Ok(result_resource::consume_token(token) + value) + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.and_then(make_callback(token)) + } + "#, + ), + ( + "or_else", + r#" + use result_resource; + pub fn dispose_failure(error: resource) -> int { + let wrapped: Result, resource> = Result::Err(error); + result_resource::take(wrapped) + } + pub fn make_callback(token: resource) -> fn(resource) -> Result> { + |error| Result::Ok(result_resource::consume_token(token)) + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.or_else(make_callback(token)) + } + "#, + ), + ( + "unwrap_or_else", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result, token: resource) -> int { + let out = value.unwrap_or_else(make_callback(token)); + out + } + "#, + ), + ]; + for (method, source) in cases { + let error = compile_with_fixture_catalog(source).expect_err(method); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{method}: {text}" + ); + } +} + +#[test] +fn owned_result_combinator_rejects_unproven_factory_alias_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn leak(value: Result, token: resource) -> Result { + let factory = if true => { make_callback } else => { make_callback }; + value.map(factory(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("an unproven temporary factory must not pass silently"); + let text = error.to_string(); + assert!( + text.contains("cannot prove the capture ownership"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_local_return_rejection_covers_callable_sites() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let cases = [ + ( + "map", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.map(make_callback(token)) + } + "#, + ), + ( + "map_err", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn leak(value: Result, token: resource) -> Result { + value.map_err(make_callback(token)) + } + "#, + ), + ( + "and_then", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> Result> { + let callback: fn(int) -> Result> = + |value| Result::Ok(result_resource::consume_token(token) + value); + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.and_then(make_callback(token)) + } + "#, + ), + ( + "or_else", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(resource) -> Result> { + let callback: fn(resource) -> Result> = + |error| Result::Ok(result_resource::consume_token(token)); + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.or_else(make_callback(token)) + } + "#, + ), + ( + "unwrap_or_else", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn leak(value: Result, token: resource) -> int { + let out = value.unwrap_or_else(make_callback(token)); + out + } + "#, + ), + ]; + for (method, source) in cases { + let error = compile_with_fixture_catalog(source).expect_err(method); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{method}: {text}" + ); + } +} + +#[test] +fn owned_result_combinator_allows_prebound_resource_capture_callback() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn keep(value: Result>, token: resource) -> Result> { + let callback = make_callback(token); + value.map(callback) + } + "#; + compile_with_fixture_catalog(source) + .expect("a callable bound in a user local keeps the existing owner rule"); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_discarded_err_resource() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn leak(value: Result>) -> int { + let out = value.unwrap_or(0); + out + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("unwrap_or must reject the selected Err resource it discards"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("Err") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_discarded_err_resource_in_typed_tail() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn leak(value: Result>) -> int { + value.unwrap_or(0) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a typed tail must reach the selected Err resource rejection"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("Err") && text.contains("resource"), + "{text}" + ); + assert!( + !text.contains("produces a Result value"), + "typed unwrap must not be rejected by the outer Result annotation rule: {text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_local_return_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make_callback(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a factory that returns a resource-capturing local callable is temporary"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_forwarded_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn id(callback: fn(int) -> int) -> fn(int) -> int { + callback + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(id(make_callback(token))) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("callable argument capture facts must flow into the forwarding parameter"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_block_local_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(int) -> int { + if flag => { + let callback = |value| result_resource::consume_token(token); + callback + } else => { + |value| value + } + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make_callback(token, true)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a block that returns a resource-capturing local callable is temporary"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_aliased_local_return_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn leak(value: Result, token: resource) -> Result { + let factory = make_callback; + value.map(factory(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a callable alias still resolves the local-return factory capture"); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_statement_if_reassigned_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_if(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + if flag { + callback = |value| result_resource::consume_token(token); + } + callback + } + + pub fn leak_if(value: Result, token: resource) -> Result { + value.map(make_if(token, true)) + } + "#; + let error = compile_with_fixture_catalog(source).expect_err( + "a statement-if reassignment still returns a temporary resource-capturing callable", + ); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_alias_after_factory_source_reassignment() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_alias(token: resource) -> fn(int) -> int { + let mut captured = |value| result_resource::consume_token(token); + let alias = captured; + captured = |value| value; + alias + } + + pub fn leak_alias(value: Result, token: resource) -> Result { + value.map(make_alias(token)) + } + "#; + let error = compile_with_fixture_catalog(source).expect_err( + "an alias keeps the capture fact from its binding even after the source slot changes", + ); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_statement_if_else_reassigned_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_if_else(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + if flag { + callback = |value| result_resource::consume_token(token); + } else { + callback = |value| value; + } + callback + } + + pub fn leak_if_else(value: Result, token: resource) -> Result { + value.map(make_if_else(token, true)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("either statement branch may return the resource-capturing temporary callable"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_statement_expression_outer_assignment_factory_resource_capture() +{ + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn touch(value: int) -> int { + value + } + + pub fn make_statement_expression(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + touch(if flag => { + callback = |value| result_resource::consume_token(token); + 0 + } else => { + callback = |value| value; + 0 + }); + callback + } + + pub fn leak_statement_expression(value: Result, token: resource) -> Result { + value.map(make_statement_expression(token, true)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a discarded expression statement still evaluates its branch writes"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_if_expression_outer_assignment_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_if_expr(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + let ignored = if flag => { + callback = |value| result_resource::consume_token(token); + 0 + } else => { + callback = |value| value; + 0 + }; + callback + } + + pub fn leak_if_expr(value: Result, token: resource) -> Result { + value.map(make_if_expr(token, true)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("an expression-if in a let initializer may write the outer callable slot"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_alias_of_factory_target_after_target_reassignment() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + + pub fn make_free_callback(token: resource) -> fn(int) -> int { + |value| value + } + + pub fn make_factory_alias(token: resource) -> fn(int) -> int { + let mut factory = make_callback; + let alias = factory; + factory = make_free_callback; + alias(token) + } + + pub fn leak_alias(value: Result, token: resource) -> Result { + value.map(make_factory_alias(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("calling the aliased factory must use the target captured at alias binding"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_closure_capture_after_source_reassignment() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_captured(token: resource) -> fn(int) -> int { + let mut captured = |value| result_resource::consume_token(token); + let callback = |value| captured(value); + captured = |value| value; + callback + } + + pub fn leak_captured(value: Result, token: resource) -> Result { + value.map(make_captured(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a closure keeps the capture fact of the callable it copied by value"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("resource") + && text.contains("bind the callable before the method"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_branch_or_loop_reassigned_factory_in_plain_resolver() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let cases = [ + ( + "branch", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn make_free_callback(token: resource) -> fn(int) -> int { + |value| value + } + pub fn leak(value: Result, token: resource, flag: bool) -> Result { + let mut factory = make_callback; + if flag { + factory = make_free_callback; + } + value.map(factory(token)) + } + "#, + ), + ( + "loop", + r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn make_free_callback(token: resource) -> fn(int) -> int { + |value| value + } + pub fn leak(value: Result, token: resource) -> Result { + let mut factory = make_callback; + let mut index = 0; + while index < 2 { + factory = make_free_callback; + index = index + 1; + } + value.map(factory(token)) + } + "#, + ), + ]; + for (label, source) in cases { + let error = compile_with_fixture_catalog(source).expect_err(label); + let text = error.to_string(); + assert!( + text.contains("temporary callable") && text.contains("cannot prove"), + "{label}: {text}" + ); + } +} + +#[test] +fn owned_result_combinator_rejects_while_assigned_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_while(token: resource) -> fn(int) -> int { + let mut callback = |value| value; + let mut index = 0; + while index < 2 { + callback = |value| value + index; + index = index + 1; + } + callback + } + + pub fn leak_while(value: Result, token: resource) -> Result { + value.map(make_while(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a callable written in a loop cannot keep its pre-loop Free fact"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") && text.contains("cannot prove"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_for_assigned_factory_resource_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + + pub fn make_for(token: resource) -> fn(int) -> int { + let mut callback = |value| value; + for index in 0..2 { + callback = |value| value + index; + } + callback + } + + pub fn leak_for(value: Result, token: resource) -> Result { + value.map(make_for(token)) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a callable written in a for body cannot keep its pre-loop Free fact"); + let text = error.to_string(); + assert!( + text.contains("temporary callable") && text.contains("cannot prove"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_statement_if_rejection_covers_callable_sites() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let cases = [ + ( + "map", + r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + if flag { + callback = |value| result_resource::consume_token(token); + } + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.map(make_callback(token, true)) + } + "#, + ), + ( + "map_err", + r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + if flag { + callback = |value| result_resource::consume_token(token); + } + callback + } + pub fn leak(value: Result, token: resource) -> Result { + value.map_err(make_callback(token, true)) + } + "#, + ), + ( + "and_then", + r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(int) -> Result> { + let mut callback: fn(int) -> Result> = + |value| Result::Ok(value); + if flag { + callback = |value| Result::Ok(result_resource::consume_token(token) + value); + } + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.and_then(make_callback(token, true)) + } + "#, + ), + ( + "or_else", + r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(resource) -> Result> { + let mut callback: fn(resource) -> Result> = + |error| Result::Ok(0); + if flag { + callback = |error| Result::Ok(result_resource::consume_token(token)); + } + callback + } + pub fn leak(value: Result>, token: resource) -> Result> { + value.or_else(make_callback(token, true)) + } + "#, + ), + ( + "unwrap_or_else", + r#" + use result_resource; + pub fn make_callback(token: resource, flag: bool) -> fn(int) -> int { + let mut callback = |value| value; + if flag { + callback = |value| result_resource::consume_token(token); + } + callback + } + pub fn leak(value: Result, token: resource) -> int { + let out = value.unwrap_or_else(make_callback(token, true)); + out + } + "#, + ), + ]; + for (method, source) in cases { + let error = compile_with_fixture_catalog(source).expect_err(method); + let text = error.to_string(); + assert!( + text.contains("temporary") && text.contains("resource") && text.contains("captur"), + "{method}: {text}" + ); + } +} + +#[test] +fn owned_result_combinator_allows_prebound_forwarded_resource_capture_callback() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + |value| result_resource::consume_token(token) + } + pub fn id(callback: fn(int) -> int) -> fn(int) -> int { + callback + } + pub fn keep(value: Result, token: resource) -> Result { + let callback = make_callback(token); + value.map(id(callback)) + } + "#; + compile_with_fixture_catalog(source) + .expect("a caller-owned prebound callable forwarded through a helper keeps its owner"); +} + +#[test] +fn owned_result_combinator_keeps_prebound_callback_usable_before_teardown() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn keep(value: Result, token: resource) -> int { + let callback = make_callback(token); + let mapped = value.map(callback); + let selected = match mapped { + Result::Ok(item) => item, + Result::Err(error) => error, + }; + callback(0) + selected + } + "#; + let mut store = resource_store(source); + let callback = store + .vm_script_callback_by_name::<(vm::GuestResult, ResourceOwned), i64>( + "keep", + ) + .unwrap(); + let handler_calls = HANDLER_CALLS.load(Ordering::SeqCst); + let closed = CLOSED.load(Ordering::SeqCst); + let dropped_ok = DROPPED_OK.load(Ordering::SeqCst); + let returned = callback + .call_with_vm( + &mut store, + (vm::GuestResult::Err(5), ResourceOwned::new(Success(61))), + ) + .unwrap(); + // The unselected Err branch does not call the callback body, and the + // surviving user binding is still callable afterwards: it consumes the + // captured token exactly once before VM teardown. + assert_eq!(returned, 5 + 61); + assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), handler_calls + 1); + assert_eq!(DROPPED_OK.load(Ordering::SeqCst), dropped_ok + 1); + assert_eq!(store.vm_mut().host_context().resource_count(), 0); + // A TakeOwned consumption vacates the resource slot; it does not route + // through HostResource::begin_close, so CLOSED stays at its baseline. + assert_eq!(CLOSED.load(Ordering::SeqCst), closed); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_discarded_generic_named_err_resource() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + struct Guarded { value: T } + pub fn leak(value: Result>>) -> int { + let out = value.unwrap_or(0); + out + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a generic named Err instance that owns a resource must be rejected"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("Err") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_discarded_nested_err_resource() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn leak(value: Result>>) -> int { + let out = value.unwrap_or(0); + out + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("a nested Err Result that owns a resource must be rejected"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("Err") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_unresolved_generic_branch_owner() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn generic_leak(value: Result, fallback: T) -> T { + let out = value.unwrap_or(fallback); + out + } + pub fn caller(value: Result>) -> int { + generic_leak::>(value, 0) + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("an unresolved generic branch may be instantiated with a resource owner"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("generic") && text.contains("resource"), + "{text}" + ); +} + +#[test] +fn owned_result_combinator_unwrap_or_rejects_discarded_named_err_resource() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + struct Guarded { token: resource } + pub fn leak(value: Result) -> int { + let out = value.unwrap_or(0); + out + } + "#; + let error = compile_with_fixture_catalog(source) + .expect_err("unwrap_or must reject a named Err schema that owns a resource"); + let text = error.to_string(); + assert!( + text.contains("unwrap_or") && text.contains("Err") && text.contains("resource"), + "{text}" + ); +} + +// --------------------------------------------------------------------------- +// Scope B address4: shared-callable producer volatility regressions +// --------------------------------------------------------------------------- + +fn assert_temporary_capture_rejection(method: &str, source: &str, detail: &str) { + let error = compile_with_fixture_catalog(source).expect_err(detail); + let text = error.to_string(); + assert!( + text.contains("temporary callable") + && text.contains("capture ownership") + && text.contains("bind the callable before the method"), + "{method}: {text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_writer_reassigned_local_return_factory_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn leak(value: Result, token: resource) -> Result { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + writer(); + value.map(factory(token)) + } + "#; + assert_temporary_capture_rejection( + "writer", + source, + "a called writer must not leave the shared factory definition trusted", + ); +} + +#[test] +fn owned_result_combinator_rejects_branched_writer_shared_factory_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource, flag: bool) -> fn(int) -> int { + let mut factory = make_free; + let writer = if flag => { + || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + } + } else => { + || 0 + }; + writer(); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token, true)) + } + "#; + assert_temporary_capture_rejection( + "branched-writer", + source, + "a branch-wrapped writer has no frozen target but still writes the shared factory", + ); +} + +#[test] +fn owned_result_combinator_rejects_named_higher_order_run_of_writer() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn run(action: fn() -> int) -> int { + action() + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + run(writer); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_temporary_capture_rejection( + "named-higher-order", + source, + "a capture-free named callee must not hide the invoked writer's shared write", + ); +} + +#[test] +fn owned_result_combinator_rejects_writer_reassignment_after_barrier() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + factory = make_free; + writer(); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_temporary_capture_rejection( + "reassignment-after-barrier", + source, + "a later assignment to the shared source must not restore a trusted Free target", + ); +} + +#[test] +fn owned_result_combinator_rejects_branch_join_after_barrier() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource, flag: bool) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + if flag { + factory = make_free; + } else { + factory = make_free; + } + writer(); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token, true)) + } + "#; + assert_temporary_capture_rejection( + "branch-join-after-barrier", + source, + "a branch join must not re-trust a volatile shared source", + ); +} + +#[test] +fn owned_result_combinator_rejects_alias_created_after_barrier() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn leak(value: Result, token: resource) -> Result { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + writer(); + let alias = factory; + value.map(alias(token)) + } + "#; + assert_temporary_capture_rejection( + "alias-after-barrier", + source, + "an alias created after the barrier cannot recover a trusted shared target", + ); +} + +#[test] +fn owned_result_combinator_rejects_nested_closure_writer_capture() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + let nested = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + nested(); + 0 + } else => { + factory = make_free; + 0 + }; + writer(); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_temporary_capture_rejection( + "nested-closure-writer", + source, + "a nested writer must map its captured slot back to the caller factory source", + ); +} + +#[test] +fn owned_result_combinator_rejects_named_capture_writer_after_barrier() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + fn install() { + factory = make_callback; + 0 + } + install(); + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_temporary_capture_rejection( + "named-capture-writer", + source, + "a capture-bearing named function must poison its shared callable source", + ); +} + +#[test] +fn owned_result_combinator_conservatively_rejects_uncalled_shared_writer() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + factory(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_temporary_capture_rejection( + "uncalled-writer", + source, + "a potential shared writer is conservatively volatile even before invocation", + ); +} + +#[test] +fn owned_result_combinator_keeps_frozen_alias_before_shared_source_write() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let alias = factory; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + writer(); + alias(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + compile_with_fixture_catalog(source) + .expect("an alias frozen before the barrier keeps its independent Free target"); +} + +#[test] +fn owned_result_combinator_writer_volatility_only_covers_its_shared_source() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + pub fn make_free(tag: int) -> fn(int) -> int { + |value| value + } + pub fn make_writing(tag: int) -> fn(int) -> int { + |value| value + 1 + } + pub fn make(tag: int) -> fn(int) -> int { + let mut other = make_free; + let factory = make_free; + let writer = || if true => { + other = make_writing; + 0 + } else => { + other = make_free; + 0 + }; + writer(); + factory(tag) + } + pub fn leak(value: Result) -> Result { + value.map(make(7)) + } + "#; + compile_with_fixture_catalog(source) + .expect("writing an unrelated private callable must not poison the safe factory"); +} + +// --------------------------------------------------------------------------- +// Scope B address5: volatile facts must survive the diagnostic walk and the +// caller-to-callee captured-slot mapping. +// --------------------------------------------------------------------------- + +fn assert_address5_rejection(probe: &str, source: &str, detail: &str) { + let text = match compile_with_fixture_catalog(source) { + Ok(()) => panic!( + "{probe}: {detail}: source was accepted, expected a temporary-callable capture rejection" + ), + Err(text) => text, + }; + assert!( + text.contains("temporary callable") + && text.contains("capture ownership") + && text.contains("bind the callable before the method"), + "{probe}: unexpected rejection: {text}" + ); +} + +#[test] +fn owned_result_combinator_rejects_expression_if_argument_rebind_after_shared_writer() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn leak(value: Result, token: resource) -> Result { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + value.map(if true => { + factory = make_free; + writer(); + factory(token) + } else => { + factory = make_free; + writer(); + factory(token) + }) + } + "#; + assert_address5_rejection( + "expression-if-argument", + source, + "the diagnostic walk must keep the same-frame shared factory volatile across an argument rebind", + ); +} + +#[test] +fn owned_result_combinator_rejects_nested_named_produce_rebind_after_shared_writer() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + fn produce(token: resource) -> fn(int) -> int { + factory = make_free; + writer(); + factory(token) + } + produce(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_address5_rejection( + "nested-named-produce", + source, + "a callee frame must inherit the caller's volatile source through its capture pair", + ); +} + +#[test] +fn owned_result_combinator_rejects_nested_closure_produce_rebind_after_shared_writer() { + let _lock = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let source = r#" + use result_resource; + pub fn make_callback(token: resource) -> fn(int) -> int { + let callback = |value| result_resource::consume_token(token); + callback + } + pub fn make_free(token: resource) -> fn(int) -> int { + |value| value + } + pub fn make(token: resource) -> fn(int) -> int { + let mut factory = make_free; + let writer = || if true => { + factory = make_callback; + 0 + } else => { + factory = make_free; + 0 + }; + let callback: fn(resource) -> fn(int) -> int = |token| if true => { + factory = make_free; + writer(); + factory(token) + } else => { + factory = make_free; + writer(); + factory(token) + }; + callback(token) + } + pub fn leak(value: Result, token: resource) -> Result { + value.map(make(token)) + } + "#; + assert_address5_rejection( + "nested-closure-produce", + source, + "a closure body frame must inherit the caller's volatile source through its capture pair", + ); +} diff --git a/tests/result_sdk_try_integration_tests.rs b/tests/result_sdk_try_integration_tests.rs index a17e7f7e..e1c6db9f 100644 --- a/tests/result_sdk_try_integration_tests.rs +++ b/tests/result_sdk_try_integration_tests.rs @@ -563,3 +563,56 @@ fn owned_callback_try_ret_and_publication_reclaim_preserve_return_and_unrelated_ } } } + +#[test] +fn owned_combinator_map_before_try_keeps_selected_owner_across_v13() { + let _lock = LOCK.lock().unwrap_or_else(|p| p.into_inner()); + for decoded in [false, true] { + for ok in [true, false] { + EVENTS.lock().unwrap().clear(); + let tick = if ok { 0 } else { 2 }; + let source = format!( + r#" + use joined; + fn relay(flag: bool) -> Result, resource> {{ + let produced = joined::make(flag, 301); + let mapped = produced.map(|item| item); + let selected = mapped?; + joined::tick(3); + let local = joined::make(true, 101); + joined::close(local); + Result::Ok(selected) + }} + relay(joined::tick({tick}) == 0);"# + ); + let mut machine = machine(&source, decoded); + machine.set_fuel(100_000); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + let (tag, payload) = vm::result::payload(machine.stack().last().unwrap()).unwrap(); + assert_eq!(tag, ok); + let handle = vm::result::resource_handle(payload).expect("active owner handle"); + assert_eq!(machine.host_context().resource_count(), 1); + let events = EVENTS.lock().unwrap().clone(); + assert!(events.contains(&("make", 301))); + assert!(events.contains(&("tick", tick as i64))); + assert_eq!(events.contains(&("tick", 3)), ok); + assert_eq!(events.contains(&("make", 101)), ok); + assert_eq!(events.contains(&("close", 101)), ok); + assert!(!events.contains(&("close", 301))); + machine + .host_context() + .close_resource::(handle, ResourceCloseReason::Requested) + .unwrap(); + assert_eq!(machine.host_context().resource_count(), 0); + let events = EVENTS.lock().unwrap().clone(); + assert_eq!( + events + .iter() + .filter(|event| **event == ("close", 301)) + .count(), + 1 + ); + eprintln!("B combinator try decoded={decoded} ok={ok} events={events:?}"); + } + } +} diff --git a/tests/result_try_tests.rs b/tests/result_try_tests.rs index 29f961d7..a5907079 100644 --- a/tests/result_try_tests.rs +++ b/tests/result_try_tests.rs @@ -1186,3 +1186,92 @@ fn host_overload_sees_selected_try_success_type() { "{rejected:?}" ); } + +#[test] +fn result_combinator_chain_propagates_through_question_mark() { + let source = r#" + fn fail() -> Result { + Result::Err("bad") + } + fn relay() -> Result { + let mapped = fail().map(|value| value + 1); + let selected = mapped?; + Result::Ok(selected + 1) + } + let result = relay(); + let observed = match result { + Result::Ok(value) => "unexpected", + Result::Err(error) => error, + }; + observed; + "#; + // The mapped carrier keeps the error payload and the `?` returns it. + match vm::compile_source(source) { + Ok(compiled) => { + let mut machine = vm::Vm::new(compiled.program.with_local_count(compiled.locals)); + machine.set_fuel(100_000); + assert_eq!(machine.run().unwrap(), vm::VmStatus::Halted); + assert_eq!(machine.stack().last(), Some(&vm::Value::string("bad"))); + } + Err(error) => panic!("combinator + question mark must compile: {error}"), + } +} + +#[test] +fn fuel_yields_inside_combinator_callback_then_completes() { + let compiled = compile_source( + r#" + fn heavy(value: int) -> int { + let mut i = 0; + while i < 100 { i = i + 1; } + value + i + } + fn relay(value: Result) -> Result { + let mapped = value.map(heavy); + mapped + } + let caught = match relay(Result::Ok(1)) { + Result::Ok(value) => value, + Result::Err(error) => -1, + }; + caught; + "#, + ) + .expect("combinator fuel source admission"); + let mut machine = Vm::new_with_jit_config( + compiled.program.with_local_count(compiled.locals), + vm::JitConfig { + enabled: false, + hot_loop_threshold: 1, + max_trace_len: 512, + }, + ); + machine.set_fuel(1); + assert_eq!( + machine.run().expect("fuel suspension is not guest Err"), + VmStatus::Yielded + ); + assert_eq!(machine.last_yield_reason(), Some(vm::VmYieldReason::Fuel)); + let mut halted = false; + let mut yielded_inside_callback = false; + for _ in 0..1024 { + machine.recharge_fuel(32).unwrap(); + match machine.run().expect("resumed combinator") { + VmStatus::Halted => { + halted = true; + break; + } + VmStatus::Yielded => { + assert_eq!(machine.last_yield_reason(), Some(vm::VmYieldReason::Fuel)); + yielded_inside_callback |= machine.call_depth() >= 2; + } + status => panic!("unexpected status {status:?}"), + } + } + assert!(halted, "bounded fuel driver must finish"); + assert!( + yielded_inside_callback, + "fuel must yield inside the selected map callback body" + ); + assert_eq!(machine.stack().last(), Some(&vm::Value::Int(101))); +}