monty 0.0.19-beta.2

A sandboxed, snapshotable Python interpreter written in Rust.
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! This module defines the public types returned by [`MontyRun::start()`](crate::MontyRun::start)
//! and their resume methods. Each variant of [`RunProgress`] wraps a dedicated struct
//! (`FunctionCall`, `OsCall`, `NameLookup`, `ResolveFutures`) that carries only the
//! fields and resume methods relevant to that suspension point.
//!
//! The internal [`Snapshot`] type is `pub(crate)` — callers interact exclusively with
//! the per-variant structs.

use std::mem;

use serde::de::DeserializeOwned;

use crate::{
    ExcType, MontyException,
    asyncio::CallId,
    bytecode::{FrameExit, VM, VMSnapshot},
    exception_private::{RunError, RunResult},
    heap::{Heap, HeapReader},
    io::PrintWriter,
    object::MontyObject,
    os::OsFunctionCall,
    resource::ResourceTracker,
    run::Executor,
};

// ---------------------------------------------------------------------------
// RunProgress enum
// ---------------------------------------------------------------------------

/// Result of a single step of iterative execution.
///
/// Each variant wraps a dedicated struct that owns the execution state and
/// exposes only the resume methods relevant to that suspension reason.
///
/// # Type Parameters
/// * `T` — Resource tracker implementation (e.g. `NoLimitTracker` or `LimitedTracker`).
///
/// Serialization requires `T: Serialize + Deserialize`.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub enum RunProgress<T: ResourceTracker> {
    /// Execution paused at an external function call or dataclass method call.
    FunctionCall(FunctionCall<T>),
    /// Execution paused for an OS-level operation (filesystem, network, etc.).
    OsCall(OsCall<T>),
    /// All async tasks are blocked waiting for external futures to resolve.
    ResolveFutures(ResolveFutures<T>),
    /// Execution paused for an unresolved name lookup.
    NameLookup(NameLookup<T>),
    /// Execution completed with a final result.
    Complete(MontyObject),
}

impl<T: ResourceTracker> RunProgress<T> {
    /// Consumes the progress and returns the `FunctionCall` struct if this is a function call.
    #[must_use]
    pub fn into_function_call(self) -> Option<FunctionCall<T>> {
        match self {
            Self::FunctionCall(call) => Some(call),
            _ => None,
        }
    }

    /// Consumes the progress and returns the `OsCall` struct if this is an OS call.
    #[must_use]
    pub fn into_os_call(self) -> Option<OsCall<T>> {
        match self {
            Self::OsCall(call) => Some(call),
            _ => None,
        }
    }

    /// Consumes the progress and returns the final value if execution completed.
    #[must_use]
    pub fn into_complete(self) -> Option<MontyObject> {
        match self {
            Self::Complete(value) => Some(value),
            _ => None,
        }
    }

    /// Consumes the progress and returns the `ResolveFutures` struct.
    #[must_use]
    pub fn into_resolve_futures(self) -> Option<ResolveFutures<T>> {
        match self {
            Self::ResolveFutures(state) => Some(state),
            _ => None,
        }
    }

    /// Consumes the progress and returns the `NameLookup` struct.
    #[must_use]
    pub fn into_name_lookup(self) -> Option<NameLookup<T>> {
        match self {
            Self::NameLookup(lookup) => Some(lookup),
            _ => None,
        }
    }
}

impl<T: ResourceTracker + serde::Serialize> RunProgress<T> {
    /// Serializes the execution state to a binary format.
    ///
    /// # Errors
    /// Returns an error if serialization fails.
    pub fn dump(&self) -> Result<Vec<u8>, postcard::Error> {
        postcard::to_allocvec(self)
    }
}

impl<T: ResourceTracker + DeserializeOwned> RunProgress<T> {
    /// Deserializes execution state from binary format.
    ///
    /// # Errors
    /// Returns an error if deserialization fails.
    pub fn load(bytes: &[u8]) -> Result<Self, postcard::Error> {
        postcard::from_bytes(bytes)
    }
}

// ---------------------------------------------------------------------------
// FunctionCall
// ---------------------------------------------------------------------------

/// Execution paused at an external function call or dataclass method call.
///
/// The host can choose how to handle this:
/// - **Sync resolution**: Call `resume(return_value, print)` to push the result and continue.
/// - **Async resolution**: Call `resume_pending(print)` to push an `ExternalFuture` and continue.
///
/// When using async resolution, the code continues and may `await` the future later.
/// If the future isn't resolved when awaited, execution yields with `ResolveFutures`.
///
/// When `method_call` is true, this represents a dataclass method call where the first
/// positional arg is the dataclass instance (`self`).
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub struct FunctionCall<T: ResourceTracker> {
    /// The name of the function or method being called.
    pub function_name: String,
    /// The positional arguments passed to the function.
    pub args: Vec<MontyObject>,
    /// The keyword arguments passed to the function (key, value pairs).
    pub kwargs: Vec<(MontyObject, MontyObject)>,
    /// Unique identifier for this call (used for async correlation).
    pub call_id: u32,
    /// Whether this is a dataclass method call (first arg is `self`).
    pub method_call: bool,
    /// Internal execution snapshot.
    snapshot: Snapshot<T>,
}

impl<T: ResourceTracker> FunctionCall<T> {
    /// Creates a new `FunctionCall` from its parts.
    fn new(
        function_name: String,
        args: Vec<MontyObject>,
        kwargs: Vec<(MontyObject, MontyObject)>,
        call_id: u32,
        method_call: bool,
        snapshot: Snapshot<T>,
    ) -> Self {
        Self {
            function_name,
            args,
            kwargs,
            call_id,
            method_call,
            snapshot,
        }
    }

    /// Returns a mutable reference to the resource tracker.
    ///
    /// This allows modifying resource limits between execution phases,
    /// e.g. setting a time limit before resuming after an external function call.
    pub fn tracker_mut(&mut self) -> &mut T {
        self.snapshot.heap.tracker_mut()
    }

    /// Resumes execution with the return value or exception from the external function.
    ///
    /// Consumes self and returns the next execution progress.
    ///
    /// # Arguments
    /// * `result` — The return value, exception, or pending future marker.
    /// * `print` — Writer for `print()` output.
    pub fn resume(
        self,
        result: impl Into<ExtFunctionResult>,
        print: PrintWriter<'_>,
    ) -> Result<RunProgress<T>, MontyException> {
        self.snapshot.run(result, print)
    }

    /// Resumes execution by pushing an `ExternalFuture` instead of a concrete value.
    ///
    /// This is the async resolution pattern: the host continues execution with a
    /// pending future. The code can then `await` this future later. If the code
    /// awaits the future before it's resolved, execution will yield with
    /// `RunProgress::ResolveFutures`.
    ///
    /// Uses `self.call_id` internally — no need to pass it again.
    ///
    /// # Arguments
    /// * `print` — Writer for print output.
    pub fn resume_pending(self, print: PrintWriter<'_>) -> Result<RunProgress<T>, MontyException> {
        self.snapshot.run(ExtFunctionResult::Future(self.call_id), print)
    }
}

// ---------------------------------------------------------------------------
// OsCall
// ---------------------------------------------------------------------------

/// Execution paused for an OS-level operation.
///
/// The host should execute the OS operation (filesystem, network, etc.) and
/// call `resume(return_value, print)` to provide the result and continue.
///
/// This enables sandboxed execution where the interpreter never directly performs I/O.
///
/// `function_call` is a tagged [`OsFunctionCall`] whose variants carry the
/// typed args directly. Host bindings that need a generic
/// `(positional, keyword)` `MontyObject` view can call [`OsFunctionCall::to_args`]
/// (the public projection method).
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub struct OsCall<T: ResourceTracker> {
    /// Typed OS-call dispatch value (variant + args).
    pub function_call: OsFunctionCall,
    /// Unique identifier for this call (used for async correlation).
    pub call_id: u32,
    /// Internal execution snapshot.
    snapshot: Snapshot<T>,
}

impl<T: ResourceTracker> OsCall<T> {
    /// Creates a new `OsCall` from its parts.
    fn new(function_call: OsFunctionCall, call_id: u32, snapshot: Snapshot<T>) -> Self {
        Self {
            function_call,
            call_id,
            snapshot,
        }
    }

    /// Resumes execution with the OS call result.
    ///
    /// # Arguments
    /// * `result` — The return value or exception from the OS operation.
    /// * `print` — Writer for `print()` output.
    pub fn resume(
        self,
        result: impl Into<ExtFunctionResult>,
        print: PrintWriter<'_>,
    ) -> Result<RunProgress<T>, MontyException> {
        self.snapshot.run(result.into(), print)
    }

    /// Takes the [`OsFunctionCall`] out by value, leaving an
    /// [`OsFunctionCall::Used`] placeholder so the host can dispatch the
    /// call without cloning large `WriteText` / `WriteBytes` payloads.
    /// `self` is still safe to call [`Self::resume`] on; the placeholder
    /// must not be inspected.
    #[must_use]
    pub fn take_function_call(&mut self) -> OsFunctionCall {
        mem::replace(&mut self.function_call, OsFunctionCall::Used)
    }

    /// Returns a reference to the resource tracker.
    ///
    /// Useful for assertions in tests that need to verify
    /// memory/allocation accounting between OS-call resumes (e.g. that a
    /// `read()` correctly counts the file buffer against `max_memory`).
    pub fn tracker(&self) -> &T {
        self.snapshot.heap.tracker()
    }
}

// ---------------------------------------------------------------------------
// NameLookup
// ---------------------------------------------------------------------------

/// Execution paused for an unresolved name lookup.
///
/// The host should check if the name corresponds to a known external function or
/// value. Call `resume(result, print)` with `NameLookupResult::Value(obj)` to
/// cache it in the namespace and continue, or `NameLookupResult::Undefined` to
/// raise `NameError`.
///
/// The namespace slot and scope are managed internally — the host only needs to
/// provide the name resolution result.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub struct NameLookup<T: ResourceTracker> {
    /// The name being looked up.
    pub name: String,
    /// The namespace slot where the resolved value should be cached.
    namespace_slot: u16,
    /// Whether this is a global slot or a local/function slot.
    is_global: bool,
    /// Internal execution snapshot.
    snapshot: Snapshot<T>,
}

impl<T: ResourceTracker> NameLookup<T> {
    /// Creates a new `NameLookup` from its parts.
    fn new(name: String, namespace_slot: u16, is_global: bool, snapshot: Snapshot<T>) -> Self {
        Self {
            name,
            namespace_slot,
            is_global,
            snapshot,
        }
    }

    /// Resumes execution after name resolution.
    ///
    /// Caches the resolved value in the appropriate slot (globals or stack)
    /// before restoring the VM, then either pushes the value or raises `NameError`.
    ///
    /// # Arguments
    /// * `result` — The resolved value or `Undefined`.
    /// * `print` — Writer for print output.
    pub fn resume(
        self,
        result: impl Into<NameLookupResult>,
        print: PrintWriter<'_>,
    ) -> Result<RunProgress<T>, MontyException> {
        let result = result.into();

        let Snapshot {
            mut heap,
            executor,
            vm_state: snapshot_vm_state,
        } = self.snapshot;
        let namespace_slot = self.namespace_slot;
        let is_global = self.is_global;
        let name = self.name;

        let (converted, vm_state) =
            HeapReader::with(&mut heap, &mut (&executor, print), |reader, (executor, print)| {
                // Restore the VM first, then convert inside its lifetime
                let mut vm = VM::restore(
                    snapshot_vm_state,
                    &executor.module_code,
                    reader,
                    &executor.interns,
                    print.reborrow(),
                );

                // Resolve the name lookup result with the VM alive
                let vm_result = match result {
                    NameLookupResult::Value(obj) => {
                        let value = obj
                            .to_value(&mut vm)
                            .map_err(|e| MontyException::runtime_error(format!("invalid name lookup result: {e}")))?;

                        // Cache the resolved value in the appropriate slot
                        let slot_idx = namespace_slot as usize;
                        let cloned = value.clone_with_heap(&vm);
                        let slot = if is_global {
                            &mut vm.globals[slot_idx]
                        } else {
                            let stack_base = vm.current_stack_base();
                            &mut vm.stack[stack_base + slot_idx]
                        };
                        let old = mem::replace(slot, cloned);
                        old.drop_with_heap(&mut vm);

                        vm.push(value);
                        vm.run_external()
                    }
                    NameLookupResult::Undefined => {
                        let err = ExcType::name_error(&name);
                        vm.resume_with_exception(err.into())
                    }
                };

                // Three-phase: convert while VM alive, snapshot, build progress
                let converted = convert_frame_exit(vm_result, &mut vm);
                let vm_state = check_snapshot_from_converted(&converted, vm);
                Ok((converted, vm_state))
            })?;
        build_run_progress(converted, vm_state, executor, heap)
    }
}

// ---------------------------------------------------------------------------
// ResolveFutures
// ---------------------------------------------------------------------------

/// Execution state paused while waiting for external future results.
///
/// Supports incremental resolution — you can provide partial results and Monty
/// will continue running until all tasks are blocked again.
///
/// Use `pending_call_ids()` to see which calls are pending, then call
/// `resume(results, print)` with some or all of the results.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub struct ResolveFutures<T: ResourceTracker> {
    /// The executor containing compiled code and interns.
    executor: Executor,
    /// The VM state containing stack, frames, globals, and exception state.
    vm_state: VMSnapshot,
    /// The heap containing all allocated objects.
    heap: Heap<T>,
    /// The pending call_ids that this snapshot is waiting on.
    pending_call_ids: Vec<u32>,
}

impl<T: ResourceTracker> ResolveFutures<T> {
    /// Creates a new `ResolveFutures` from its parts.
    fn new(executor: Executor, vm_state: VMSnapshot, heap: Heap<T>, pending_call_ids: Vec<u32>) -> Self {
        Self {
            executor,
            vm_state,
            heap,
            pending_call_ids,
        }
    }

    /// Returns unresolved call IDs for this suspended state.
    #[must_use]
    pub fn pending_call_ids(&self) -> &[u32] {
        &self.pending_call_ids
    }

    /// Forces a GC cycle against the exact root walk used by the live VM.
    ///
    /// This is test-only support for reproducing GC bugs while execution is
    /// suspended in a `ResolveFutures` snapshot. The method round-trips through
    /// `VM::restore()` and `VM::snapshot()` so the production scheduler/stack root
    /// logic is exercised rather than duplicated in the test.
    #[cfg(feature = "test-hooks")]
    #[doc(hidden)]
    #[must_use]
    pub fn __force_gc_for_tests(self) -> Self {
        let Self {
            executor,
            vm_state,
            mut heap,
            pending_call_ids,
        } = self;

        let vm_state = HeapReader::with(&mut heap, &mut &executor, |reader, executor| {
            let mut vm = VM::restore(
                vm_state,
                &executor.module_code,
                reader,
                &executor.interns,
                PrintWriter::Stdout,
            );
            vm.__force_gc_for_tests();
            vm.snapshot()
        });

        Self::new(executor, vm_state, heap, pending_call_ids)
    }

    /// Resumes execution with results for some or all pending futures.
    ///
    /// **Incremental resolution**: You don't need to provide all results at once.
    /// If you provide a partial list, Monty will:
    /// 1. Mark those futures as resolved
    /// 2. Unblock any tasks waiting on those futures
    /// 3. Continue running until all tasks are blocked again
    /// 4. Return `ResolveFutures` with the remaining pending calls
    ///
    /// # Arguments
    /// * `results` — List of `(call_id, result)` pairs. Can be a subset of pending calls.
    /// * `print` — Writer for print output.
    ///
    /// # Errors
    /// Returns `Err(MontyException)` if any `call_id` in `results` is not in the pending set.
    pub fn resume(
        self,
        results: Vec<(u32, ExtFunctionResult)>,
        print: PrintWriter<'_>,
    ) -> Result<RunProgress<T>, MontyException> {
        let Self {
            executor,
            vm_state,
            mut heap,
            pending_call_ids,
        } = self;

        // Validate that all provided call_ids are in the pending set before restoring VM.
        let invalid_call_id = results
            .iter()
            .find(|(call_id, _)| !pending_call_ids.contains(call_id))
            .map(|(call_id, _)| *call_id);

        let (converted, vm_state) =
            HeapReader::with(&mut heap, &mut (&executor, print), |reader, (executor, print)| {
                // Restore the VM from the snapshot (must happen before any error return to clean up properly).
                let mut vm = VM::restore(
                    vm_state,
                    &executor.module_code,
                    reader,
                    &executor.interns,
                    print.reborrow(),
                );

                // Now check for invalid call_ids after VM is restored.
                if let Some(call_id) = invalid_call_id {
                    return Err(MontyException::runtime_error(format!(
                        "unknown call_id {call_id}, expected one of: {pending_call_ids:?}"
                    )));
                }

                let result = vm.resume_with_resolved_futures(results);

                // Three-phase: convert while VM alive, snapshot, build progress
                let converted = convert_frame_exit(result, &mut vm);
                let vm_state = check_snapshot_from_converted(&converted, vm);
                Ok((converted, vm_state))
            })?;
        build_run_progress(converted, vm_state, executor, heap)
    }
}

// ---------------------------------------------------------------------------
// Snapshot (pub(crate))
// ---------------------------------------------------------------------------

/// Internal execution state that can be resumed after suspension.
///
/// This is a `pub(crate)` implementation detail wrapped by the per-variant
/// structs (`FunctionCall`, `OsCall`, `NameLookup`). It is not exposed in the
/// public API.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(serialize = "T: serde::Serialize", deserialize = "T: serde::de::DeserializeOwned"))]
pub(crate) struct Snapshot<T: ResourceTracker> {
    /// The executor containing compiled code and interns.
    pub(crate) executor: Executor,
    /// The VM state containing stack, frames, globals, and exception state.
    pub(crate) vm_state: VMSnapshot,
    /// The heap containing all allocated objects.
    pub(crate) heap: Heap<T>,
}

impl<T: ResourceTracker> Snapshot<T> {
    /// Continues execution with the return value or exception from the external call.
    pub(crate) fn run(
        self,
        result: impl Into<ExtFunctionResult>,
        print: PrintWriter<'_>,
    ) -> Result<RunProgress<T>, MontyException> {
        let ext_result = result.into();

        let Self {
            executor,
            vm_state,
            mut heap,
        } = self;

        let (converted, vm_state) =
            HeapReader::with(&mut heap, &mut (&executor, print), |reader, (executor, print)| {
                let mut vm = VM::restore(
                    vm_state,
                    &executor.module_code,
                    reader,
                    &executor.interns,
                    print.reborrow(),
                );

                let vm_result = match ext_result {
                    ExtFunctionResult::Return(obj) => vm.resume(obj),
                    ExtFunctionResult::Error(exc) => vm.resume_with_exception(exc.into()),
                    ExtFunctionResult::Future(raw_call_id) => {
                        let call_id = CallId::new(raw_call_id);
                        match vm.add_pending_call(call_id) {
                            Ok(()) => vm.run_external(),
                            Err(err) => vm.resume_with_exception(err),
                        }
                    }
                    ExtFunctionResult::NotFound(function_name) => {
                        vm.resume_with_exception(ExtFunctionResult::not_found_exc(&function_name))
                    }
                };

                // Three-phase: convert while VM alive, snapshot, build progress
                let converted = convert_frame_exit(vm_result, &mut vm);
                let vm_state = check_snapshot_from_converted(&converted, vm);
                (converted, vm_state)
            });
        build_run_progress(converted, vm_state, executor, heap)
    }
}

/// Result of a name lookup from the host.
///
/// When the VM encounters an unresolved name, the host provides one of these:
/// - `Value(obj)`: The name resolves to this value (cached in the namespace for future access).
/// - `Undefined`: The name is truly undefined, causing `NameError`.
#[derive(Debug)]
pub enum NameLookupResult {
    /// The name resolves to this value.
    Value(MontyObject),
    /// The name is undefined — VM will raise `NameError`.
    Undefined,
}

impl From<MontyObject> for NameLookupResult {
    fn from(value: MontyObject) -> Self {
        Self::Value(value)
    }
}

/// Return value or exception from an external function.
#[derive(Debug)]
pub enum ExtFunctionResult {
    /// Continues execution with the return value from the external function.
    Return(MontyObject),
    /// Continues execution with the exception raised by the external function.
    Error(MontyException),
    /// Pending future — the external function is a coroutine.
    ///
    /// The `u32` is the `call_id` from the `FunctionCall` that created this
    /// snapshot. It is used to track the pending future so it can be resolved
    /// later via `ResolveFutures::resume()`.
    Future(u32),
    /// The function was not found, should result in a `NameError` exception.
    NotFound(String),
}

impl ExtFunctionResult {
    pub(crate) fn not_found_exc(function_name: &str) -> RunError {
        let msg = format!("name '{function_name}' is not defined");
        MontyException::new(ExcType::NameError, Some(msg)).into()
    }
}

impl From<MontyObject> for ExtFunctionResult {
    fn from(value: MontyObject) -> Self {
        Self::Return(value)
    }
}

impl From<MontyException> for ExtFunctionResult {
    fn from(exception: MontyException) -> Self {
        Self::Error(exception)
    }
}

// ---------------------------------------------------------------------------
// handle_vm_result
// ---------------------------------------------------------------------------

/// Pre-converted frame exit data, produced while the VM is still alive.
///
/// This intermediate enum holds `MontyObject`s and `String`s instead of `Value`s
/// and `StringId`s. It exists to separate the conversion phase (needs `&mut VM`)
/// from the snapshot/progress construction phase (needs owned `Heap`).
pub(crate) enum ConvertedExit {
    /// Execution completed with a final result.
    Complete(MontyObject),
    /// External function call or dataclass method call.
    FunctionCall {
        function_name: String,
        args: Vec<MontyObject>,
        kwargs: Vec<(MontyObject, MontyObject)>,
        call_id: u32,
        method_call: bool,
    },
    /// OS-level operation.
    OsCall {
        function_call: OsFunctionCall,
        call_id: u32,
    },
    /// All async tasks are blocked waiting for external futures.
    ResolveFutures(Vec<u32>),
    /// Unresolved name lookup.
    NameLookup {
        name: String,
        namespace_slot: u16,
        is_global: bool,
    },
    /// Runtime error.
    Error(RunError),
}

impl ConvertedExit {
    /// Returns true if this exit requires a VM snapshot for later resumption.
    pub(crate) fn needs_snapshot(&self) -> bool {
        !matches!(self, Self::Complete(_) | Self::Error(_))
    }
}

/// Converts a `FrameExit` into a `ConvertedExit` while the VM is still alive.
///
/// All `Value` → `MontyObject` and `StringId` → `String` conversions happen here,
/// while the VM (and its heap/interns) are still accessible.
pub(crate) fn convert_frame_exit(result: RunResult<FrameExit>, vm: &mut VM<'_, impl ResourceTracker>) -> ConvertedExit {
    match result {
        Ok(FrameExit::Return(value)) => ConvertedExit::Complete(MontyObject::new(value, vm)),
        Ok(FrameExit::ExternalCall {
            function_name,
            args,
            call_id,
            ..
        }) => {
            let name = function_name.into_string(vm.interns);
            let (args_py, kwargs_py) = args.into_py_objects(vm);
            ConvertedExit::FunctionCall {
                function_name: name,
                args: args_py,
                kwargs: kwargs_py,
                call_id: call_id.raw(),
                method_call: false,
            }
        }
        Ok(FrameExit::OsCall { function_call, call_id }) => ConvertedExit::OsCall {
            function_call,
            call_id: call_id.raw(),
        },
        Ok(FrameExit::MethodCall {
            method_name,
            args,
            call_id,
        }) => {
            let name = method_name.into_string(vm.interns);
            let (args_py, kwargs_py) = args.into_py_objects(vm);
            ConvertedExit::FunctionCall {
                function_name: name,
                args: args_py,
                kwargs: kwargs_py,
                call_id: call_id.raw(),
                method_call: true,
            }
        }
        Ok(FrameExit::ResolveFutures(pending_call_ids)) => {
            ConvertedExit::ResolveFutures(pending_call_ids.iter().map(|id| id.raw()).collect())
        }
        Ok(FrameExit::NameLookup {
            name_id,
            namespace_slot,
            is_global,
        }) => {
            let name = vm.interns.get_str(name_id).to_owned();
            ConvertedExit::NameLookup {
                name,
                namespace_slot,
                is_global,
            }
        }
        Err(err) => ConvertedExit::Error(err),
    }
}

/// Decides whether to snapshot or clean up the VM based on the converted exit.
///
/// Consumes the VM. Returns `Some(VMSnapshot)` for suspendable exits, `None` for
/// completion/error (in which case the VM's `Drop` impl handles cleanup).
pub(crate) fn check_snapshot_from_converted(
    converted: &ConvertedExit,
    vm: VM<'_, impl ResourceTracker>,
) -> Option<VMSnapshot> {
    if converted.needs_snapshot() {
        Some(vm.snapshot())
    } else {
        None
    }
}

/// Assembles a `RunProgress` from already-converted data and owned heap.
///
/// This runs after the VM has been dropped (releasing the heap borrow),
/// so the heap can be moved into `Snapshot` structs.
pub(crate) fn build_run_progress<T: ResourceTracker>(
    converted: ConvertedExit,
    vm_state: Option<VMSnapshot>,
    executor: Executor,
    heap: Heap<T>,
) -> Result<RunProgress<T>, MontyException> {
    macro_rules! new_snapshot {
        () => {
            Snapshot {
                executor,
                vm_state: vm_state.expect("snapshot should exist"),
                heap,
            }
        };
    }

    match converted {
        ConvertedExit::Complete(obj) => Ok(RunProgress::Complete(obj)),
        ConvertedExit::FunctionCall {
            function_name,
            args,
            kwargs,
            call_id,
            method_call,
        } => Ok(RunProgress::FunctionCall(FunctionCall::new(
            function_name,
            args,
            kwargs,
            call_id,
            method_call,
            new_snapshot!(),
        ))),
        ConvertedExit::OsCall { function_call, call_id } => Ok(RunProgress::OsCall(OsCall::new(
            function_call,
            call_id,
            new_snapshot!(),
        ))),
        ConvertedExit::ResolveFutures(pending_call_ids) => Ok(RunProgress::ResolveFutures(ResolveFutures::new(
            executor,
            vm_state.expect("snapshot should exist for ResolveFutures"),
            heap,
            pending_call_ids,
        ))),
        ConvertedExit::NameLookup {
            name,
            namespace_slot,
            is_global,
        } => Ok(RunProgress::NameLookup(NameLookup::new(
            name,
            namespace_slot,
            is_global,
            new_snapshot!(),
        ))),
        ConvertedExit::Error(err) => {
            Err(err.into_python_exception(&executor.interns, |_| Some(executor.code.as_str())))
        }
    }
}