Skip to main content

yomi_core/vm/
snapshot.rs

1//! Rollback: snapshots (in-memory copies) per stop point, and a ring that stores them.
2//!
3//! A snapshot holds the same state as a save (variables, local variables, call stack, labels entered, `once` already
4//! chosen, random generator, history, position, packages' state slices). **It does not hold or restore `persistent var`s,
5//! host-declared persistent variables, persistent slices, or passed stop points (`seen`)**. It is not turned into bytes
6//! (what is written to disk is a save).
7
8use std::collections::{BTreeSet, VecDeque};
9use std::sync::Arc;
10
11use super::rng::Rng;
12use super::{ChoiceBuild, Frame, State, StopRecord, StopSrc, Vm, VmError, VmErrorKind, Yield};
13use crate::package::SliceBox;
14use crate::program::Program;
15use crate::registry::Kind;
16use crate::value::Value;
17
18/// A snapshot of the state at a stop point. Can only be restored into a VM of the same program.
19#[derive(Debug, Clone)]
20pub struct Snapshot {
21    /// The fingerprint of the program (a check against restoring into another program).
22    fingerprint: u64,
23    label: usize,
24    pc: usize,
25    ordinal: u32,
26    locals: Vec<Value>,
27    frames: Vec<Frame>,
28    stack: Vec<Value>,
29    /// The stop notification (its command and ID are used; the arguments are those after replacement).
30    current: Yield,
31    /// The original arguments and `${expr}` values (rebuilt with the current text table when restoring).
32    src: StopSrc,
33    visited: BTreeSet<u32>,
34    once_done: BTreeSet<(u32, String)>,
35    choice: ChoiceBuild,
36    /// Module variables (those of `persistent var`s are not used when restoring).
37    globals: Vec<Value>,
38    /// Host-declared variables (those of `Kind::Persistent` are not used when restoring).
39    host_vars: Vec<Value>,
40    /// Packages' state slices (persistent slices are not held).
41    states: Vec<SliceBox>,
42    rng: Rng,
43    args_rng: Rng,
44    history: Vec<Arc<StopRecord>>,
45}
46
47/// A rough fingerprint made from the shape of the program.
48fn fingerprint(program: &Program) -> u64 {
49    let ops: usize = program.labels.iter().map(|l| l.reg.ops.len()).sum();
50    let fn_ops: usize = program.fns.iter().map(|f| f.reg.ops.len()).sum();
51    ((program.labels.len() as u64) << 40)
52        ^ ((program.globals.len() as u64) << 20)
53        ^ ((program.fns.len() as u64) << 52)
54        ^ (ops + fn_ops) as u64
55}
56
57impl<'a> Vm<'a> {
58    /// Takes a snapshot at a stop point (`NotStopped` if not stopped).
59    ///
60    /// The host takes one at each stop point, stores it in a [`SnapshotLog`], and goes back with [`Vm::restore`].
61    pub fn snapshot(&self) -> Result<Snapshot, VmError> {
62        let (State::Stopped { ordinal }, Some(current)) = (&self.state, &self.current) else {
63            return Err(self.misuse(VmErrorKind::NotStopped));
64        };
65        Ok(Snapshot {
66            fingerprint: fingerprint(&self.program),
67            label: self.label,
68            pc: self.pc,
69            ordinal: *ordinal,
70            locals: self.locals.clone(),
71            frames: self.frames.clone(),
72            stack: self.stack.clone(),
73            current: current.clone(),
74            src: self.cur_src.clone().unwrap_or(StopSrc {
75                args: match current {
76                    Yield::Stop { args, .. } => args.clone(),
77                    Yield::End => Vec::new(),
78                },
79                values: Vec::new(),
80            }),
81            visited: self.visited.clone(),
82            once_done: self.once_done.clone(),
83            choice: self.choice.clone(),
84            globals: self.globals.clone(),
85            host_vars: self.host_vars.clone(),
86            states: self.states.clone(),
87            rng: self.rng.clone(),
88            args_rng: self.args_rng.clone(),
89            history: self.history().to_vec(),
90        })
91    }
92
93    /// Goes back to the state of the stop point where the snapshot was taken. The VM is left stopped at that stop point (it can
94    /// go back even after a runtime error).
95    ///
96    /// What is restored is the save state (`save var`s, local variables, call stack, labels entered, `once` already chosen,
97    /// random generator, history, position). **`persistent var`s and passed stop points are not restored**.
98    /// A snapshot of another program gives `SnapshotMismatch` (the VM is unchanged).
99    pub fn restore(&mut self, snap: &Snapshot) -> Result<(), VmError> {
100        let ok = snap.fingerprint == fingerprint(&self.program)
101            && snap.globals.len() == self.globals.len()
102            && snap.host_vars.len() == self.host_vars.len()
103            && snap.states.len() == self.states.len()
104            && snap.label < self.program.labels.len();
105        if !ok {
106            return Err(self.misuse(VmErrorKind::SnapshotMismatch));
107        }
108        for ((slot, saved), g) in self
109            .globals
110            .iter_mut()
111            .zip(&snap.globals)
112            .zip(&self.program.globals)
113        {
114            if !g.persistent {
115                *slot = saved.clone();
116            }
117        }
118        for ((slot, saved), d) in self
119            .host_vars
120            .iter_mut()
121            .zip(&snap.host_vars)
122            .zip(self.registry.vars())
123        {
124            if d.kind == Kind::Save {
125                *slot = saved.clone();
126            }
127        }
128        self.states = snap.states.clone();
129        self.clear_cues();
130        self.label = snap.label;
131        self.pc = snap.pc;
132        self.locals = snap.locals.clone();
133        self.frames = snap.frames.clone();
134        self.fn_frames.clear();
135        self.cur_fn = None;
136        self.dbg_last = None;
137        self.total_valid = false;
138        self.stack = snap.stack.clone();
139        self.visited = snap.visited.clone();
140        self.once_done = snap.once_done.clone();
141        self.choice = snap.choice.clone();
142        self.rng.clone_from(&snap.rng);
143        self.args_rng.clone_from(&snap.args_rng);
144        self.history = snap.history.clone();
145        self.cap.clear();
146        self.state = State::Stopped {
147            ordinal: snap.ordinal,
148        };
149        // The language is not part of the save or snapshot state. The body of the restored stop point is rebuilt with the
150        // current text table
151        self.current = Some(match &snap.current {
152            Yield::Stop { command, id, .. } => Yield::Stop {
153                command: *command,
154                args: self.localize(
155                    snap.ordinal,
156                    id.as_deref(),
157                    &snap.src.args,
158                    &snap.src.values,
159                ),
160                id: id.clone(),
161            },
162            other => other.clone(),
163        });
164        self.cur_src = Some(snap.src.clone());
165        self.generation += 1;
166        Ok(())
167    }
168}
169
170/// A ring of snapshots (with a maximum count; when full, the oldest are dropped).
171///
172/// The host `push`es a [`Vm::snapshot`] at each stop point and takes one out with `pop_back` to go back.
173#[derive(Debug, Clone)]
174pub struct SnapshotLog {
175    items: VecDeque<Snapshot>,
176    capacity: usize,
177}
178
179impl SnapshotLog {
180    /// Makes an empty ring. `capacity` is the maximum number of entries (0 holds nothing).
181    pub fn new(capacity: usize) -> Self {
182        Self {
183            items: VecDeque::new(),
184            capacity,
185        }
186    }
187
188    /// The maximum number of entries.
189    pub fn capacity(&self) -> usize {
190        self.capacity
191    }
192
193    /// The number of entries held now.
194    pub fn len(&self) -> usize {
195        self.items.len()
196    }
197
198    /// Whether it is empty.
199    pub fn is_empty(&self) -> bool {
200        self.items.is_empty()
201    }
202
203    /// Adds to the end (the newest). If over the limit, drops the front (the oldest).
204    pub fn push(&mut self, snapshot: Snapshot) {
205        if self.capacity == 0 {
206            return;
207        }
208        while self.items.len() >= self.capacity {
209            self.items.pop_front();
210        }
211        self.items.push_back(snapshot);
212    }
213
214    /// Takes out the end (the newest).
215    pub fn pop_back(&mut self) -> Option<Snapshot> {
216        self.items.pop_back()
217    }
218
219    /// Looks at the end (the newest).
220    pub fn back(&self) -> Option<&Snapshot> {
221        self.items.back()
222    }
223
224    /// Drops everything.
225    pub fn clear(&mut self) {
226        self.items.clear();
227    }
228}