sim-lib-function 0.1.0

Language-neutral function plans and managed function instances for SIM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// conformance: managed function instances preserve captures and callable identity.

use std::{any::Any, error::Error, fmt};

use sim_kernel::{
    Args, Callable, ClassRef, Cx, Object, ObjectCompat, Result as KernelResult, ShapeRef, Value,
};
use sim_lib_binding::BindingCell;
use sim_lib_mutation::{
    EdgeId, EdgeVisitor, ManagedHandle, ManagedId, ManagedNode, ManagedObject,
    StrongEdgeMutationError,
};

use crate::{BoundCall, CallInput, FunctionPlan, bind};

/// Guest-owned execution policy for one concrete function body type.
///
/// The policy is statically selected by [`FunctionInstance`]. It receives the
/// neutral call record and shared capture cells, leaving defaults, keyword
/// rules, receiver behavior, evaluation, and diagnostics to the guest.
pub trait FunctionBodyPolicy: Send + Sync + 'static {
    /// Executes this body using the immutable declaration and live captures.
    fn invoke(
        &self,
        cx: &mut Cx,
        plan: &FunctionPlan,
        captures: &[CapturedBinding],
        call: BoundCall,
    ) -> KernelResult<Value>;
}

/// One shared binding cell paired with its identity in the managed graph.
#[derive(Clone, Debug)]
pub struct CapturedBinding {
    cell: BindingCell,
    managed: ManagedHandle,
}

impl CapturedBinding {
    /// Associates an existing binding cell with its managed allocation.
    pub const fn new(cell: BindingCell, managed: ManagedHandle) -> Self {
        Self { cell, managed }
    }

    /// Borrows the shared lexical cell.
    pub const fn cell(&self) -> &BindingCell {
        &self.cell
    }

    /// Returns the managed identity traced for this capture.
    pub const fn managed(&self) -> ManagedHandle {
        self.managed
    }
}

/// Failure to construct a managed function instance.
#[derive(Debug)]
pub enum InstanceError {
    /// Capture cells must exactly follow the plan's declared slots.
    CaptureMismatch {
        /// Number of capture descriptors in the plan.
        expected: usize,
        /// Number of supplied managed binding cells.
        actual: usize,
    },
    /// A supplied cell did not match the corresponding frozen capture slot.
    CaptureNameMismatch {
        /// Zero-based position in the frozen capture sequence.
        index: usize,
        /// Name declared by the immutable function plan.
        expected: String,
        /// Name carried by the supplied shared binding cell.
        actual: String,
    },
    /// The shared managed node refused a capture edge.
    ManagedEdge(StrongEdgeMutationError),
}

impl fmt::Display for InstanceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CaptureMismatch { expected, actual } => write!(
                formatter,
                "function plan declares {expected} captures but {actual} were supplied"
            ),
            Self::CaptureNameMismatch {
                index,
                expected,
                actual,
            } => write!(
                formatter,
                "function capture {index} is named {actual}, expected {expected}"
            ),
            Self::ManagedEdge(error) => write!(formatter, "cannot trace function capture: {error}"),
        }
    }
}

impl Error for InstanceError {}

/// The typed payload retained by a managed function node.
#[derive(Clone)]
struct FunctionRole<B> {
    plan: FunctionPlan,
    body: B,
    captures: Vec<CapturedBinding>,
    class: ClassRef,
    args_shape: Option<ShapeRef>,
    result_shape: Option<ShapeRef>,
}

/// A language-neutral, managed function object with a concrete guest body.
///
/// Each capture is represented twice for distinct purposes: its existing
/// [`BindingCell`] supplies shared lexical mutation, while its `ManagedHandle`
/// becomes a strong edge in the common managed graph. No private environment
/// graph or body registry is involved.
#[derive(Clone)]
pub struct FunctionInstance<B: FunctionBodyPolicy> {
    node: ManagedNode<FunctionRole<B>>,
}

impl<B: FunctionBodyPolicy> FunctionInstance<B> {
    /// Builds an instance from a plan, typed body, managed captures, and runtime metadata.
    pub fn new(
        plan: FunctionPlan,
        body: B,
        captures: Vec<CapturedBinding>,
        class: ClassRef,
        args_shape: Option<ShapeRef>,
        result_shape: Option<ShapeRef>,
    ) -> Result<Self, InstanceError> {
        validate_capture_bindings(&plan, &captures)?;
        let targets = captures
            .iter()
            .map(|capture| capture.managed().id())
            .collect::<Vec<_>>();
        let mut node = ManagedNode::new(FunctionRole {
            plan,
            body,
            captures,
            class,
            args_shape,
            result_shape,
        });
        for target in targets {
            node.insert_strong(target)
                .map_err(InstanceError::ManagedEdge)?;
        }
        Ok(Self { node })
    }

    /// Borrows the immutable declaration plan.
    pub const fn plan(&self) -> &FunctionPlan {
        &self.node.role().plan
    }

    /// Borrows the concrete guest body policy without erasure or downcasting.
    pub const fn body(&self) -> &B {
        &self.node.role().body
    }

    /// Borrows the capture cells in plan declaration order.
    pub fn captures(&self) -> &[CapturedBinding] {
        &self.node.role().captures
    }

    /// Borrows the caller-supplied runtime class.
    pub const fn supplied_class(&self) -> &ClassRef {
        &self.node.role().class
    }

    /// Borrows the caller-supplied argument Shape, when present.
    pub const fn args_shape(&self) -> Option<&ShapeRef> {
        self.node.role().args_shape.as_ref()
    }

    /// Borrows the caller-supplied result Shape, when present.
    pub const fn result_shape(&self) -> Option<&ShapeRef> {
        self.node.role().result_shape.as_ref()
    }

    /// Invokes the guest policy through the neutral evaluated-value boundary.
    ///
    /// Kernel calls and optional dispatch-method adaptation both use this path,
    /// so neither surface can change the policy-visible [`BoundCall`].
    pub fn invoke_bound(&self, cx: &mut Cx, call: BoundCall) -> KernelResult<Value> {
        self.body().invoke(cx, self.plan(), self.captures(), call)
    }

    pub(crate) fn invoke_values(&self, cx: &mut Cx, values: Vec<Value>) -> KernelResult<Value> {
        self.invoke_bound(cx, bind(CallInput::from(Args::new(values))))
    }
}

/// Validates that concrete capture cells exactly match every frozen plan slot.
pub fn validate_capture_bindings(
    plan: &FunctionPlan,
    captures: &[CapturedBinding],
) -> Result<(), InstanceError> {
    if plan.captures().len() != captures.len() {
        return Err(InstanceError::CaptureMismatch {
            expected: plan.captures().len(),
            actual: captures.len(),
        });
    }
    for (index, (descriptor, capture)) in plan.captures().iter().zip(captures).enumerate() {
        if descriptor.name() != capture.cell().name() {
            return Err(InstanceError::CaptureNameMismatch {
                index,
                expected: descriptor.name().to_string(),
                actual: capture.cell().name().to_string(),
            });
        }
    }
    Ok(())
}

impl<B: FunctionBodyPolicy> ManagedObject for FunctionInstance<B> {
    fn trace_edges(&self, visitor: &mut dyn EdgeVisitor) {
        self.node.trace_edges(visitor);
    }

    fn clear_weak_edge(&mut self, edge: EdgeId, expected: ManagedId) -> bool {
        self.node.clear_weak_edge(edge, expected)
    }

    fn clear_ephemeron_edge(
        &mut self,
        edge: EdgeId,
        expected_key: ManagedId,
        expected_value: ManagedId,
    ) -> bool {
        self.node
            .clear_ephemeron_edge(edge, expected_key, expected_value)
    }
}

impl<B: FunctionBodyPolicy> Object for FunctionInstance<B> {
    fn display(&self, _cx: &mut Cx) -> KernelResult<String> {
        Ok(format!("#<function {}>", self.plan().display_identity()))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<B: FunctionBodyPolicy> ObjectCompat for FunctionInstance<B> {
    fn class(&self, _cx: &mut Cx) -> KernelResult<ClassRef> {
        Ok(self.supplied_class().clone())
    }

    fn as_callable(&self) -> Option<&dyn Callable> {
        Some(self)
    }
}

impl<B: FunctionBodyPolicy> Callable for FunctionInstance<B> {
    fn call(&self, cx: &mut Cx, args: Args) -> KernelResult<Value> {
        self.invoke_values(cx, args.into_vec())
    }

    fn browse_args_shape(&self, _cx: &mut Cx) -> KernelResult<Option<ShapeRef>> {
        Ok(self.args_shape().cloned())
    }

    fn browse_result_shape(&self, _cx: &mut Cx) -> KernelResult<Option<ShapeRef>> {
        Ok(self.result_shape().cloned())
    }
}

#[cfg(test)]
mod tests {
    use sim_kernel::{ShapeId, Symbol, testing::bare_cx};
    use sim_lib_gc_tracing::{CollectionLimits, ManagedHeap};
    use sim_lib_mutation::{EdgeSnapshot, ManagedNode};

    use super::*;
    use crate::CaptureDescriptor;

    #[derive(Clone)]
    struct EchoBody;

    impl FunctionBodyPolicy for EchoBody {
        fn invoke(
            &self,
            _cx: &mut Cx,
            _plan: &FunctionPlan,
            _captures: &[CapturedBinding],
            call: BoundCall,
        ) -> KernelResult<Value> {
            match call.arguments()[0].input() {
                crate::ArgumentInput::Positional(value) => Ok(value.clone()),
                _ => unreachable!("kernel arguments are positional"),
            }
        }
    }

    fn plan(captures: usize) -> FunctionPlan {
        FunctionPlan::new(
            Symbol::new("guest:echo"),
            Vec::new(),
            (0..captures)
                .map(|index| CaptureDescriptor::new(Symbol::new(format!("slot-{index}")), None))
                .collect(),
            Some(ShapeId(9)),
        )
        .unwrap()
    }

    fn metadata(cx: &mut Cx) -> (ClassRef, ShapeRef, ShapeRef) {
        (
            cx.factory().symbol(Symbol::new("guest-class")).unwrap(),
            cx.factory().symbol(Symbol::new("args-shape")).unwrap(),
            cx.factory().symbol(Symbol::new("result-shape")).unwrap(),
        )
    }

    fn collection_limits() -> CollectionLimits {
        CollectionLimits {
            objects: 4,
            edges: 4,
            stack: 4,
            work: 32,
            clears: 4,
            finalizers: 4,
        }
    }

    #[test]
    fn invocation_and_runtime_metadata_are_delegated_without_body_erasure() {
        let mut cx = bare_cx();
        let (class, args_shape, result_shape) = metadata(&mut cx);
        let instance = FunctionInstance::new(
            plan(0),
            EchoBody,
            Vec::new(),
            class.clone(),
            Some(args_shape.clone()),
            Some(result_shape.clone()),
        )
        .unwrap();
        let argument = cx.factory().symbol(Symbol::new("answer")).unwrap();

        assert!(std::ptr::eq(instance.body(), &instance.node.role().body));
        assert_eq!(instance.class(&mut cx).unwrap(), class);
        assert_eq!(
            instance.browse_args_shape(&mut cx).unwrap(),
            Some(args_shape)
        );
        assert_eq!(
            instance.browse_result_shape(&mut cx).unwrap(),
            Some(result_shape)
        );
        assert_eq!(
            instance
                .call(&mut cx, Args::new(vec![argument.clone()]))
                .unwrap(),
            argument
        );
    }

    #[test]
    fn same_plan_instances_receive_distinct_managed_identities() {
        let mut cx = bare_cx();
        let (class, _, _) = metadata(&mut cx);
        let mut heap = ManagedHeap::tracing(4, collection_limits()).unwrap();
        let first = heap
            .allocate(
                FunctionInstance::new(plan(0), EchoBody, vec![], class.clone(), None, None)
                    .unwrap(),
            )
            .unwrap();
        let second = heap
            .allocate(FunctionInstance::new(plan(0), EchoBody, vec![], class, None, None).unwrap())
            .unwrap();

        assert_ne!(first.id(), second.id());
    }

    #[derive(Clone)]
    enum CycleObject {
        Function(FunctionInstance<EchoBody>),
        Environment(ManagedNode<()>),
    }

    impl ManagedObject for CycleObject {
        fn trace_edges(&self, visitor: &mut dyn EdgeVisitor) {
            match self {
                Self::Function(function) => function.trace_edges(visitor),
                Self::Environment(environment) => environment.trace_edges(visitor),
            }
        }

        fn clear_weak_edge(&mut self, edge: EdgeId, expected: ManagedId) -> bool {
            match self {
                Self::Function(function) => function.clear_weak_edge(edge, expected),
                Self::Environment(environment) => environment.clear_weak_edge(edge, expected),
            }
        }

        fn clear_ephemeron_edge(
            &mut self,
            edge: EdgeId,
            expected_key: ManagedId,
            expected_value: ManagedId,
        ) -> bool {
            match self {
                Self::Function(function) => {
                    function.clear_ephemeron_edge(edge, expected_key, expected_value)
                }
                Self::Environment(environment) => {
                    environment.clear_ephemeron_edge(edge, expected_key, expected_value)
                }
            }
        }
    }

    #[test]
    fn closure_environment_cycle_is_collected_through_capture_edge() {
        let mut cx = bare_cx();
        let (class, _, _) = metadata(&mut cx);
        let mut heap = ManagedHeap::tracing(4, collection_limits()).unwrap();
        let environment = heap
            .allocate(CycleObject::Environment(ManagedNode::new(())))
            .unwrap();
        let cell = BindingCell::uninitialized(Symbol::new("slot-0"));
        let function = FunctionInstance::new(
            plan(1),
            EchoBody,
            vec![CapturedBinding::new(cell, environment)],
            class,
            None,
            None,
        )
        .unwrap();
        assert_eq!(
            function.node.edge_snapshot(),
            vec![EdgeSnapshot::Strong {
                edge: EdgeId(0),
                target: environment.id(),
            }]
        );
        let function = heap.allocate(CycleObject::Function(function)).unwrap();
        match heap.get_mut(environment).unwrap() {
            CycleObject::Environment(node) => {
                node.insert_strong(function.id()).unwrap();
            }
            CycleObject::Function(_) => unreachable!(),
        }

        let receipt = heap.collect().unwrap().unwrap();
        assert_eq!(receipt.swept, vec![environment.id(), function.id()]);
        assert_eq!(heap.live_len(), 0);
    }
}