Skip to main content

yomi_core/vm/
save.rs

1//! Saving and loading (position, variables, call stack, labels entered, `once` already chosen, random generator, history,
2//! packages' state slices, host-declared variables; `persistent var`s, passed stop points and persistent slices are
3//! persistent data in a separate byte string).
4
5mod container;
6mod migrate;
7mod resolve;
8mod schema;
9mod value;
10
11#[cfg(test)]
12pub(crate) use container::crc32;
13pub(super) use container::{unwrap, wrap};
14pub(super) use migrate::{apply as apply_migrations, migrated_types};
15pub(super) use resolve::find_label;
16use resolve::*;
17pub use schema::SchemaDiff;
18pub(super) use schema::{
19    check_version as check_schema_version, consistent as schema_consistent, script_var_diffs,
20};
21#[cfg(test)]
22pub(super) use value::SavedNode;
23pub(super) use value::SavedValue;
24
25use std::sync::Arc;
26
27use serde::{Deserialize, Serialize};
28
29use super::persistent::PersistentReport;
30use super::rng::Rng;
31use super::{
32    Frame, Inner, LoadPolicy, Rebuilt, State, StopRecord, Vm, VmConfig, VmError, VmErrorKind,
33    Yield, default_locals,
34};
35use crate::program::{LabelCode, ProgRef, Program, StopInfo, StopKind};
36use crate::registry::{Kind, Registry};
37use crate::value::{Identity, MAX_VALUE_DEPTH, Value, finite_float};
38
39/// The marker of save bytes (the first 4 bytes).
40const MAGIC: &[u8; 4] = b"YOMS";
41/// The format version. Before release, it is increased without keeping compatibility. Version 2 added the call stack,
42/// version 3 labels entered and `once` already chosen, version 4 the random generator and history, version 5 host-declared
43/// variables and packages' state slices, version 6 return values of stop points in the history, version 7 changed the
44/// value format so it can hold `list`, `Option`, `struct` and `enum` and added `struct` and `enum` declarations (type names
45/// and shapes), version 8 added `map` values (nodes in insertion order), version 9 added the label and kind of stop points
46/// to the history, version 10 added packages' rule versions (`rules`), and version 11 changed the random generator to
47/// xoshiro256++ (the state is 4 `u64`s), and version 12 added the schema (`schema_version`, `var_types`) and changed the
48/// position hash to the canonical form (versions 1 to 11 cannot be read). `persistent var`s, passed stop points and
49/// persistent slices are not included (they are persistent data; `YOMP`).
50pub(super) const FORMAT_VERSION: u32 = 12;
51
52/// One history entry.
53#[derive(Serialize, Deserialize)]
54struct SavedRecord {
55    /// The label of the stop point (`module.label`; added in version 9).
56    label: String,
57    /// The kind of stop point (`StopKind`; `0` is an `@` command, `1` a plain line, `2` a quote line, `3` a choice; added in
58    /// version 9).
59    kind: u8,
60    key: Option<String>,
61    command: String,
62    args: Vec<SavedValue>,
63    values: Vec<Vec<String>>,
64    /// The return value passed on resume (added in version 6).
65    ret: Option<SavedValue>,
66}
67
68impl SavedRecord {
69    /// Makes a record for saving from a record of the stop point history.
70    fn from_record(r: &StopRecord) -> Self {
71        Self {
72            label: r.label.clone(),
73            kind: match r.kind {
74                StopKind::Plain => 1,
75                StopKind::Quote => 2,
76                StopKind::Choice => 3,
77                _ => 0,
78            },
79            key: r.key.clone(),
80            command: r.command.clone(),
81            args: r.args.iter().map(SavedValue::from_value).collect(),
82            values: r.values.clone(),
83            ret: r.ret.as_ref().map(SavedValue::from_value),
84        }
85    }
86
87    /// Turns a record for saving back into a history record. `None` if the kind value is invalid.
88    fn into_record(self) -> Option<StopRecord> {
89        Some(StopRecord {
90            label: self.label,
91            kind: match self.kind {
92                0 => StopKind::Command,
93                1 => StopKind::Plain,
94                2 => StopKind::Quote,
95                3 => StopKind::Choice,
96                _ => return None,
97            },
98            key: self.key,
99            command: self.command,
100            args: self
101                .args
102                .iter()
103                .map(SavedValue::decode)
104                .collect::<Option<Vec<_>>>()?,
105            values: self.values,
106            ret: match self.ret {
107                Some(r) => Some(r.decode()?),
108                None => None,
109            },
110        })
111    }
112}
113
114/// The list of shapes of type declarations (`name`, `signature`). Put into saves and persistent data.
115pub(super) fn type_signatures(program: &Program) -> Vec<(String, String)> {
116    program
117        .types
118        .iter()
119        .map(|t| (t.name.clone(), t.signature()))
120        .collect()
121}
122
123/// A tool that checks whether saved values can be accepted for the types of the current scripts. Types whose saved
124/// declaration differs from the current one (and types containing them) are not accepted, even if the values fit
125/// structurally.
126pub(super) struct Compat<'p> {
127    types: &'p [crate::value::TypeDecl],
128    /// The names of types whose declarations changed (including types that contain changed types).
129    pub changed: std::collections::BTreeSet<String>,
130}
131
132impl<'p> Compat<'p> {
133    /// `saved` are the saved type declarations ([`type_signatures`]).
134    pub(super) fn new(program: &'p Program, saved: &[(String, String)]) -> Self {
135        let mut changed: std::collections::BTreeSet<String> = program
136            .types
137            .iter()
138            .filter(|t| {
139                saved
140                    .iter()
141                    .any(|(n, sig)| *n == t.name && *sig != t.signature())
142            })
143            .map(|t| t.name.clone())
144            .collect();
145        // Types that contain changed types are also treated as changed
146        loop {
147            let before = changed.len();
148            for t in &program.types {
149                if !changed.contains(&t.name) && t.used_types().iter().any(|u| changed.contains(*u))
150                {
151                    changed.insert(t.name.clone());
152                }
153            }
154            if changed.len() == before {
155                break;
156            }
157        }
158        Self {
159            types: &program.types,
160            changed,
161        }
162    }
163
164    /// Whether the value can be accepted as type `ty`.
165    pub(super) fn ok(&self, v: &Value, ty: &crate::value::Ty) -> bool {
166        let mut used = Vec::new();
167        ty.collect_user(&mut used);
168        !used.iter().any(|n| self.changed.contains(*n)) && v.matches_in(ty, self.types)
169    }
170}
171
172/// The position of a saved stop point (module, label, stable ID, position hash, ordinal within the label).
173#[derive(Serialize, Deserialize)]
174struct Position {
175    module: String,
176    label: String,
177    id: Option<String>,
178    hash: u64,
179    ordinal: u32,
180}
181
182/// One frame of the call stack. The position is the call line (the line with the `call`).
183#[derive(Serialize, Deserialize)]
184struct FrameBody {
185    /// The position of the call line. Call lines have no stable ID, so `id` is always `None` (searched by hash and ordinal).
186    position: Position,
187    locals: Vec<(u32, String, SavedValue)>,
188}
189
190/// One state slice of a package (the core does not interpret its contents).
191#[derive(Serialize, Deserialize, Clone)]
192pub(super) struct SavedSlice {
193    /// The name of the package.
194    pub name: String,
195    /// The version when saved (`Package::VERSION`, `PERSISTENT_VERSION`).
196    pub version: u32,
197    /// The bytes serialized with `postcard`.
198    pub bytes: Vec<u8>,
199}
200
201/// The body of a save (position, type declarations, module variables, local variables, call stack, random generator,
202/// history, packages' state, and so on).
203#[derive(Serialize, Deserialize)]
204struct SaveBody {
205    position: Position,
206    /// The schema version of the scripts when saved.
207    schema_version: u32,
208    /// The `struct` and `enum` declarations when saved (type names and the shapes of declarations). Compared with the
209    /// scripts' declarations on load.
210    types: Vec<(String, String)>,
211    /// The types of `vars` then `host_vars` (same names, same order), as type strings.
212    var_types: Vec<(String, String)>,
213    /// Module variables. Names are `module.variable`.
214    vars: Vec<(String, SavedValue)>,
215    /// Host-declared variables (`Kind::Save`). Names are `package.variable`.
216    host_vars: Vec<(String, SavedValue)>,
217    /// Packages' state slices (in registration order; those whose `State` is `()` are not included).
218    slices: Vec<SavedSlice>,
219    locals: Vec<(u32, String, SavedValue)>,
220    /// The call stack (the bottom is the first caller).
221    frames: Vec<FrameBody>,
222    /// Labels entered (`module`, `label`).
223    visited: Vec<(String, String)>,
224    /// `once` options already chosen (`module`, `label`, stable ID).
225    once_done: Vec<(String, String, String)>,
226    /// The state of the random generator, as of when computing the arguments of the current stop point began (rebuilding the
227    /// arguments on load brings it back to the current state).
228    rng: [u64; 4],
229    /// The history of stop points (oldest first; up to the newest `history_limit` entries).
230    history: Vec<SavedRecord>,
231    /// The rule versions of the registered packages (`Package::RULES_VERSION`; in registration order; all of them, with or
232    /// without state).
233    rules: Vec<(String, u32)>,
234}
235
236/// How the position was found.
237#[non_exhaustive]
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum ResolvedBy {
240    /// Label + stable ID.
241    Id,
242    /// Label + hash.
243    Hash,
244    /// Label + ordinal (the nearest stop point).
245    Ordinal,
246    /// The start of the label (the stop point could not be determined). In this case the VM is not stopped and starts with
247    /// `run`.
248    LabelStart,
249}
250
251/// The stop point a save is stopped at, read without restoring the VM ([`pending_stop`]).
252#[non_exhaustive]
253#[derive(Debug, Clone, PartialEq)]
254pub struct PendingStop {
255    /// The label the stop point is in (`module.label`).
256    pub label: String,
257    /// `module.label#id` (`None` for stop points without a stable ID and for choices).
258    pub key: Option<String>,
259    /// The name of the command it is stopped at (the name in the registry when the save was made).
260    pub command: String,
261    /// The arguments of the stop notification, as saved (the evaluated original).
262    pub args: Vec<Value>,
263    /// The version of the schema of the save (`spec/host/04-save.md`, 4.3).
264    pub schema_version: u32,
265}
266
267/// Reads the command and arguments a save is stopped at, without the scripts, the registry or a VM (`spec/host/04-save.md`,
268/// 4.9). `Ok(None)` if the save has no history (`VmConfig::history_limit` was 0).
269///
270/// It checks the magic, the format version, the checksum and the body like a load does. It does not check the schema, apply
271/// migrations or resolve the position.
272pub fn pending_stop(save: &[u8]) -> Result<Option<PendingStop>, LoadError> {
273    let (body, _, history) = decode_save(save)?;
274    Ok(history.last().map(|r| PendingStop {
275        label: r.label.clone(),
276        key: r.key.clone(),
277        command: r.command.clone(),
278        args: r.args.clone(),
279        schema_version: body.schema_version,
280    }))
281}
282
283/// The report of a load.
284#[non_exhaustive]
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct LoadReport {
287    /// How the position was found. When there is a call stack, the least reliable method among the stop point and the call
288    /// lines (`Hash` is less reliable than `Id`, `Ordinal` than `Hash`, `LabelStart` than `Ordinal`).
289    pub resolved_by: ResolvedBy,
290    /// Variables filled with default values (`module.variable`; only `save var`s; `persistent var`s are in the persistent data
291    /// report).
292    pub added_vars: Vec<String>,
293    /// Variables that were removed from the scripts and discarded (`module.variable`).
294    pub removed_vars: Vec<String>,
295    /// Variables whose type changed (`module.variable`; if any, it goes back to the start of the label).
296    pub type_changed_vars: Vec<String>,
297    /// `struct`s and `enum`s whose declarations changed (`module.TypeName`; including types that contain changed types).
298    /// Variables holding values of those types go into `type_changed_vars`.
299    pub changed_types: Vec<String>,
300    /// Local variables whose type changed (`module.label.variable`; the current label and the label of each call stack frame;
301    /// if any, it goes back to the start of the label). When only names or counts changed, they do not appear here
302    /// (`resolved_by` becomes `LabelStart`).
303    pub type_changed_locals: Vec<String>,
304    /// Slices of packages that are not registered, which were ignored (package names).
305    pub ignored_slices: Vec<String>,
306    /// Packages' state slices that were not in the save and got default values (`State::default()`) (package names).
307    pub defaulted_slices: Vec<String>,
308    /// Packages' state slices whose versions differed and were migrated with `migrate` (package names).
309    pub migrated_slices: Vec<String>,
310    /// Packages whose rule version (`Package::RULES_VERSION`) differs from when saved (package names, in registration order).
311    /// Execution continues with the current rules, so the same command with the same arguments may give a different result
312    /// than before the save. Packages that were not in the save are not included.
313    pub changed_rules: Vec<String>,
314    /// The schema version of the save.
315    pub from_schema_version: u32,
316    /// The schema version of the scripts.
317    pub to_schema_version: u32,
318    /// Variables converted by `migrate` (`module.variable`; renamed variables have the new name).
319    pub migrated_vars: Vec<String>,
320    /// Variables whose `migrate` conversion failed and were reset to their initial values under `LoadPolicy::Lenient`
321    /// (if any, it goes back to the start of the label).
322    pub migrate_failed_vars: Vec<String>,
323    /// The report from reading the persistent data in [`VmConfig::persistent`] (`None` if not given).
324    pub persistent: Option<PersistentReport>,
325}
326
327/// The kind of load failure.
328#[non_exhaustive]
329#[derive(Debug, Clone, PartialEq, Eq)]
330pub enum LoadErrorKind {
331    /// The magic does not match.
332    BadMagic,
333    /// An unknown format version.
334    UnsupportedVersion(u32),
335    /// The checksum does not match.
336    ChecksumMismatch,
337    /// The body is broken.
338    Corrupt,
339    /// The saved label is not in the scripts.
340    LabelNotFound(String),
341    /// The names of the saved modules differ from the scripts' modules.
342    ModuleMismatch(String),
343    /// A command used by the program is not in the registry.
344    CommandMissing(String),
345    /// The arguments of the stop point could not be rebuilt.
346    StopArgsFailed,
347    /// A package's slice could not be restored (broken, or `migrate` returned `Err`). The value is the package name.
348    PackageSlice(String),
349    /// Cannot load with a registry made from a declaration file (it has no functions to run commands).
350    DeclOnlyRegistry,
351    /// The save is from a newer schema version than the scripts.
352    SaveFromNewerVersion {
353        /// The schema version of the save.
354        saved: u32,
355        /// The schema version of the scripts.
356        current: u32,
357    },
358    /// The save is older than the oldest schema version the scripts support (`min_save_version`).
359    SaveVersionUnsupported {
360        /// The schema version of the save.
361        saved: u32,
362        /// The oldest supported version.
363        min: u32,
364    },
365    /// Under `LoadPolicy::Strict`, variables whose saved type differs from the scripts (all of them).
366    SchemaMismatch(Vec<SchemaDiff>),
367    /// Under `LoadPolicy::Strict`, variables whose `migrate` conversion failed (all of them).
368    MigrateFailed(Vec<String>),
369}
370
371impl LoadErrorKind {
372    /// The stable English name.
373    pub fn code(&self) -> &'static str {
374        match self {
375            LoadErrorKind::BadMagic => "bad_magic",
376            LoadErrorKind::UnsupportedVersion(_) => "unsupported_version",
377            LoadErrorKind::ChecksumMismatch => "checksum_mismatch",
378            LoadErrorKind::Corrupt => "corrupt",
379            LoadErrorKind::LabelNotFound(_) => "label_not_found",
380            LoadErrorKind::ModuleMismatch(_) => "module_mismatch",
381            LoadErrorKind::CommandMissing(_) => "command_missing",
382            LoadErrorKind::StopArgsFailed => "stop_args_failed",
383            LoadErrorKind::PackageSlice(_) => "package_slice",
384            LoadErrorKind::DeclOnlyRegistry => "decl_only_registry",
385            LoadErrorKind::SaveFromNewerVersion { .. } => "save_from_newer_version",
386            LoadErrorKind::SaveVersionUnsupported { .. } => "save_version_unsupported",
387            LoadErrorKind::SchemaMismatch(_) => "schema_mismatch",
388            LoadErrorKind::MigrateFailed(_) => "migrate_failed",
389        }
390    }
391}
392
393/// A load failure. Has no message text.
394#[non_exhaustive]
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct LoadError {
397    /// Kind.
398    pub kind: LoadErrorKind,
399}
400
401impl std::fmt::Display for LoadError {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        write!(f, "{}", self.kind.code())
404    }
405}
406
407impl std::error::Error for LoadError {}
408
409/// Makes a load failure of the given kind.
410fn fail<T>(kind: LoadErrorKind) -> Result<T, LoadError> {
411    Err(LoadError { kind })
412}
413
414/// Why [`Vm::reload`] failed.
415#[non_exhaustive]
416#[derive(Debug, Clone, PartialEq, Eq)]
417pub enum ReloadError {
418    /// The VM is not at a stop point.
419    NotStopped,
420    /// The state could not be handed over (the reasons of [`LoadError`]).
421    Load(LoadError),
422    /// The stop point could only be resolved as the start of a label.
423    PositionLost(ResolvedBy),
424}
425
426impl ReloadError {
427    /// The stable name of the failure.
428    pub fn code(&self) -> &'static str {
429        match self {
430            ReloadError::NotStopped => "not_stopped",
431            ReloadError::Load(e) => e.kind.code(),
432            ReloadError::PositionLost(_) => "position_lost",
433        }
434    }
435}
436
437impl std::fmt::Display for ReloadError {
438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439        write!(f, "{}", self.code())
440    }
441}
442
443impl std::error::Error for ReloadError {}
444
445/// The bytes that identify a state ([`Vm::state_key`]).
446pub(crate) struct StateKey {
447    /// The save without the history.
448    pub save: Vec<u8>,
449    /// The persistent data.
450    pub persistent: Vec<u8>,
451}
452
453impl<'a> Vm<'a> {
454    /// Makes the bytes of a save at a stop point.
455    ///
456    /// Includes the position, `save var`s, local variables, the call stack, labels entered, `once` already chosen, the random
457    /// generator and the history. `persistent var`s and passed stop points are not included ([`Vm::save_persistent`]).
458    pub fn save(&self) -> Result<Vec<u8>, VmError> {
459        let body = self.save_body(true)?;
460        let body = postcard::to_stdvec(&body).expect("メモリへの直列化は失敗しない");
461        Ok(wrap(MAGIC, FORMAT_VERSION, &body))
462    }
463
464    /// Hands the state at the current stop point over to a new program (`spec/host/04-save.md`, 4.10).
465    ///
466    /// Works like saving and loading, but the persistent data is carried over from this VM, and a position that can only be
467    /// resolved as the start of a label is an error. This VM is not changed.
468    pub fn reload(&self, program: &'a Program) -> Result<(Vm<'a>, LoadReport), ReloadError> {
469        let bytes = self.save().map_err(|_| ReloadError::NotStopped)?;
470        let mut cfg = self.cfg.clone();
471        cfg.persistent = Some(self.save_persistent());
472        let (vm, report) =
473            Vm::load(program, self.registry, cfg, &bytes).map_err(ReloadError::Load)?;
474        if report.resolved_by == ResolvedBy::LabelStart || !vm.is_stopped() {
475            return Err(ReloadError::PositionLost(report.resolved_by));
476        }
477        Ok((vm, report))
478    }
479
480    /// What identifies the state at a stop point: a save without the history, and the persistent data (`persistent var`s,
481    /// host persistent variables, persistent slices, passed stop points). Two stop points with the same bytes behave the
482    /// same from here on. Used by the exploration (`spec/host/08-test.md`).
483    pub(crate) fn state_key(&self) -> Result<StateKey, VmError> {
484        let body = self.save_body(false)?;
485        Ok(StateKey {
486            save: postcard::to_stdvec(&body).expect("メモリへの直列化は失敗しない"),
487            persistent: self.save_persistent(),
488        })
489    }
490
491    fn save_body(&self, with_history: bool) -> Result<SaveBody, VmError> {
492        let State::Stopped { ordinal } = self.state else {
493            return Err(self.misuse(VmErrorKind::NotStopped));
494        };
495        let program = &self.program;
496        let code = &program.labels[self.label];
497        let stop = &code.stops[ordinal as usize];
498        let frames = self
499            .frames
500            .iter()
501            .map(|f| {
502                let lc = &program.labels[f.label];
503                // The instruction just before the return point is the `Call` instruction
504                let site = lc
505                    .calls
506                    .iter()
507                    .position(|c| c.pc as usize + 1 == f.ret_pc)
508                    .unwrap_or(0);
509                FrameBody {
510                    position: Position {
511                        module: program.modules[lc.module as usize].clone(),
512                        label: lc.name.clone(),
513                        id: None,
514                        hash: lc.calls.get(site).map_or(0, |c| c.hash),
515                        ordinal: site as u32,
516                    },
517                    locals: save_locals(lc, &f.locals),
518                }
519            })
520            .collect();
521        let vars: Vec<(String, SavedValue)> = program
522            .globals
523            .iter()
524            .zip(&self.globals)
525            .filter(|(g, _)| !g.persistent)
526            .map(|(g, v)| {
527                (
528                    global_name(program, g.module, &g.name),
529                    SavedValue::from_value(v),
530                )
531            })
532            .collect();
533        let host_vars: Vec<(String, SavedValue)> = self
534            .registry
535            .vars()
536            .iter()
537            .zip(&self.host_vars)
538            .filter(|(d, _)| d.kind == Kind::Save)
539            .map(|(d, v)| (d.name.clone(), SavedValue::from_value(v)))
540            .collect();
541        let var_types = program
542            .globals
543            .iter()
544            .filter(|g| !g.persistent)
545            .map(|g| (global_name(program, g.module, &g.name), g.ty.name()))
546            .chain(
547                self.registry
548                    .vars()
549                    .iter()
550                    .filter(|d| d.kind == Kind::Save)
551                    .map(|d| (d.name.clone(), d.ty.name())),
552            )
553            .collect();
554        let body = SaveBody {
555            schema_version: program.schema_version(),
556            types: type_signatures(program),
557            var_types,
558            position: Position {
559                module: program.modules[code.module as usize].clone(),
560                label: code.name.clone(),
561                id: stop.id.clone(),
562                hash: stop.hash,
563                ordinal,
564            },
565            vars,
566            host_vars,
567            slices: match self.save_slices(false) {
568                Ok(s) => s,
569                Err(name) => return Err(self.misuse(VmErrorKind::SliceSerialize(name))),
570            },
571            locals: save_locals(code, &self.locals),
572            frames,
573            visited: self
574                .visited
575                .iter()
576                .map(|&l| {
577                    let lc = &program.labels[l as usize];
578                    (program.modules[lc.module as usize].clone(), lc.name.clone())
579                })
580                .collect(),
581            once_done: self
582                .once_done
583                .iter()
584                .map(|(l, id)| {
585                    let lc = &program.labels[*l as usize];
586                    (
587                        program.modules[lc.module as usize].clone(),
588                        lc.name.clone(),
589                        id.clone(),
590                    )
591                })
592                .collect(),
593            rng: self.args_rng.state(),
594            history: if with_history {
595                self.history()
596                    .iter()
597                    .map(|r| SavedRecord::from_record(r))
598                    .collect()
599            } else {
600                Vec::new()
601            },
602            rules: self
603                .registry
604                .package_entries()
605                .iter()
606                .map(|e| (e.name.clone(), e.rules_version))
607                .collect(),
608        };
609        Ok(body)
610    }
611
612    /// Makes a VM restored to a stop point from the bytes of a save.
613    ///
614    /// If `cfg` has [`VmConfig::persistent`], the persistent data is put in first (so that when the arguments of the stop
615    /// point are rebuilt, scripts that read `persistent var`s and `seen` get the same arguments as when saved).
616    pub fn load(
617        program: &'a Program,
618        registry: &'a Registry,
619        cfg: VmConfig,
620        bytes: &[u8],
621    ) -> Result<(Self, LoadReport), LoadError> {
622        let (mut body, rng, mut history) = decode_save(bytes)?;
623        schema::check_version(program, body.schema_version)?;
624        let migration = apply_migrations(
625            program,
626            registry,
627            &cfg,
628            body.schema_version,
629            false,
630            &body.types,
631            &mut body.vars,
632            &mut body.var_types,
633        )?;
634        // After a migration, the types of the variables are already expanded
635        let var_decls: &[(String, String)] = if migrated_types(program, body.schema_version) {
636            &[]
637        } else {
638            &body.types
639        };
640        let diffs =
641            schema::script_var_diffs(program, var_decls, &body.var_types, &body.vars, false)?;
642        if cfg.load_policy == LoadPolicy::Strict && !diffs.is_empty() {
643            return fail(LoadErrorKind::SchemaMismatch(diffs));
644        }
645        let mismatched: std::collections::BTreeSet<String> =
646            diffs.into_iter().map(|d| d.name).collect();
647        let compat = Compat::new(program, &body.types);
648        let persistent_body = match &cfg.persistent {
649            Some(b) => Some(super::persistent::parse(b)?),
650            None => None,
651        };
652        let mut vm = Vm::blank_for_load(program, registry, cfg)?;
653        let persistent_report = match persistent_body {
654            Some(b) => Some(vm.apply_persistent(b)?),
655            None => None,
656        };
657        // Packages' state slices (restored before rebuilding the arguments of the stop point, because query commands read them)
658        let slice_report = vm.apply_state_slices(&body.slices)?;
659        // Packages whose rule versions differ from when saved (only a warning; the load continues)
660        let changed_rules: Vec<String> = vm
661            .registry
662            .package_entries()
663            .iter()
664            .filter(|e| {
665                body.rules
666                    .iter()
667                    .any(|(n, v)| *n == e.name && *v != e.rules_version)
668            })
669            .map(|e| e.name.clone())
670            .collect();
671        vm.clear_cues();
672        vm.rng = rng.clone();
673        vm.args_rng = rng.clone();
674        let keep = history.len().saturating_sub(vm.cfg.history_limit);
675        history.drain(..keep);
676        vm.history = history;
677        let pos = &body.position;
678        if !program.modules.contains(&pos.module) {
679            return fail(LoadErrorKind::ModuleMismatch(pos.module.clone()));
680        }
681        let Some(label) = find_label(program, &pos.module, &pos.label) else {
682            return fail(LoadErrorKind::LabelNotFound(pos.label.clone()));
683        };
684        let code = &program.labels[label];
685
686        // Labels entered and `once` already chosen (those removed from the scripts are discarded)
687        for (m, l) in &body.visited {
688            if let Some(i) = find_label(program, m, l) {
689                vm.visited.insert(i as u32);
690            }
691        }
692        for (m, l, id) in &body.once_done {
693            if let Some(i) = find_label(program, m, l) {
694                vm.once_done.insert((i as u32, id.clone()));
695            }
696        }
697        vm.visited.insert(label as u32);
698
699        let VarChanges {
700            added,
701            removed,
702            type_changed,
703        } = vm.restore_save_vars(program, &body, &compat, &mismatched);
704        // A variable whose `convert` failed becomes its initial value (reported as `migrate_failed_vars`, not as added)
705        let added: Vec<String> = added
706            .into_iter()
707            .filter(|n| !migration.failed.contains(n))
708            .collect();
709        // Local variables whose type changed (the current label and each call stack frame)
710        let mut type_changed_locals = local_type_changes(program, code, &body.locals, &compat);
711        for fb in &body.frames {
712            if let Some(fl) = find_label(program, &fb.position.module, &fb.position.label) {
713                type_changed_locals.extend(local_type_changes(
714                    program,
715                    &program.labels[fl],
716                    &fb.locals,
717                    &compat,
718                ));
719            }
720        }
721        // Local variables. If even one name, type or count differs from when saved, the position of the stop point cannot be
722        // trusted, so go back to the start of the label.
723        let locals = restore_locals(program, code, &body.locals, &compat);
724        // The call stack. If any frame cannot be resolved, also go back to the start of the label (the call stack is discarded).
725        let stack = restore_frames(program, &body.frames, label, &compat);
726
727        // Resolve the position
728        let (ordinal, mut resolved_by) = match (&locals, &stack) {
729            (Some(_), Some(_)) if type_changed.is_empty() && migration.failed.is_empty() => {
730                resolve(code, pos)
731            }
732            _ => (None, ResolvedBy::LabelStart),
733        };
734        vm.label = label;
735        let report = |by: ResolvedBy| LoadReport {
736            resolved_by: by,
737            added_vars: added.clone(),
738            removed_vars: removed.clone(),
739            type_changed_vars: type_changed.clone(),
740            changed_types: compat.changed.iter().cloned().collect(),
741            type_changed_locals: type_changed_locals.clone(),
742            ignored_slices: slice_report.ignored.clone(),
743            defaulted_slices: slice_report.defaulted.clone(),
744            migrated_slices: slice_report.migrated.clone(),
745            changed_rules: changed_rules.clone(),
746            from_schema_version: body.schema_version,
747            to_schema_version: program.schema_version(),
748            migrated_vars: migration.migrated.clone(),
749            migrate_failed_vars: migration.failed.clone(),
750            persistent: persistent_report.clone(),
751        };
752        let (Some(ordinal), Some(locals), Some((frames, frames_by))) = (ordinal, locals, stack)
753        else {
754            // Go back to the start of the label (not stopped)
755            vm.restart_label(program, code);
756            return Ok((vm, report(ResolvedBy::LabelStart)));
757        };
758        vm.locals = locals;
759        vm.frames = frames;
760        for f in &vm.frames {
761            vm.visited.insert(f.label as u32);
762        }
763        // Make the stop notification from the stopping instruction (if the arguments cannot be re-evaluated, go back to the start
764        // of the label)
765        let Some(y) = vm.rebuild_yield(ordinal)? else {
766            // The arguments cannot be re-evaluated (the scripts changed). Go back to the start of the label.
767            vm.rng = rng.clone();
768            vm.args_rng = rng;
769            vm.stack.clear();
770            vm.frames.clear();
771            vm.restart_label(program, code);
772            return Ok((vm, report(ResolvedBy::LabelStart)));
773        };
774        vm.state = State::Stopped { ordinal };
775        vm.install_current(y, ordinal);
776        vm.sync_current_record();
777        resolved_by = weakest(resolved_by, frames_by);
778        Ok((vm, report(resolved_by)))
779    }
780
781    /// An empty VM for loading.
782    fn blank_for_load(
783        program: &'a Program,
784        registry: &'a Registry,
785        cfg: VmConfig,
786    ) -> Result<Self, LoadError> {
787        match Vm::blank(ProgRef::Borrowed(program), registry, cfg) {
788            Ok(vm) => Ok(vm),
789            Err(VmError {
790                kind: VmErrorKind::CommandMissing(n),
791                ..
792            }) => fail(LoadErrorKind::CommandMissing(n)),
793            Err(VmError {
794                kind: VmErrorKind::DeclOnlyRegistry,
795                ..
796            }) => fail(LoadErrorKind::DeclOnlyRegistry),
797            Err(_) => fail(LoadErrorKind::Corrupt),
798        }
799    }
800
801    /// Compatibility of variables (`save var`s and host-declared `Kind::Save`; `persistent var`s are persistent data). Only
802    /// values of matching types are put in.
803    fn restore_save_vars(
804        &mut self,
805        program: &Program,
806        body: &SaveBody,
807        compat: &Compat<'_>,
808        mismatched: &std::collections::BTreeSet<String>,
809    ) -> VarChanges {
810        let mut added = Vec::new();
811        let mut type_changed = Vec::new();
812        for (i, g) in program
813            .globals
814            .iter()
815            .enumerate()
816            .filter(|(_, g)| !g.persistent)
817        {
818            let name = global_name(program, g.module, &g.name);
819            match body.vars.iter().find(|(n, _)| *n == name) {
820                // The type was checked against the saved type in `schema::script_var_diffs`
821                Some((_, v)) if !mismatched.contains(&name) => {
822                    self.globals[i] = v.clone().into_value();
823                }
824                Some(_) => type_changed.push(name),
825                None => added.push(name),
826            }
827        }
828        // Host-declared variables (`Kind::Save`). Same rules as script variables
829        for (i, d) in self
830            .registry
831            .vars()
832            .iter()
833            .enumerate()
834            .filter(|(_, d)| d.kind == Kind::Save)
835        {
836            match body.host_vars.iter().find(|(n, _)| *n == d.name) {
837                Some((_, v)) if compat.ok(&v.clone().into_value(), &d.ty) => {
838                    self.host_vars[i] = v.clone().into_value();
839                }
840                Some(_) => type_changed.push(d.name.clone()),
841                None => added.push(d.name.clone()),
842            }
843        }
844        let mut removed: Vec<String> = body
845            .vars
846            .iter()
847            .filter(|(n, _)| {
848                !program
849                    .globals
850                    .iter()
851                    .any(|g| !g.persistent && global_name(program, g.module, &g.name) == *n)
852            })
853            .map(|(n, _)| n.clone())
854            .collect();
855        removed.extend(
856            body.host_vars
857                .iter()
858                .filter(|(n, _)| {
859                    !self
860                        .registry
861                        .vars()
862                        .iter()
863                        .any(|d| d.kind == Kind::Save && d.name == *n)
864                })
865                .map(|(n, _)| n.clone()),
866        );
867        VarChanges {
868            added,
869            removed,
870            type_changed,
871        }
872    }
873
874    /// Goes back to the start of the label (not stopped).
875    fn restart_label(&mut self, program: &Program, code: &LabelCode) {
876        self.pc = 0;
877        self.locals = default_locals(program, code);
878        self.state = State::Ready;
879    }
880
881    /// Rebuilds the arguments of the `ordinal`-th stop point of the current label by running the instructions.
882    ///
883    /// The random generator starts from the state when computing the arguments began (`args_rng`). If rebuilt, empties the
884    /// stack, advances past the stopping instruction, and returns the stop notification. If they could not be re-evaluated
885    /// (a runtime error, or no options to choose), `None`. `state` is left as it was before the call.
886    pub(super) fn rebuild_yield(&mut self, ordinal: u32) -> Result<Option<Yield>, LoadError> {
887        let program_ref = self.program.clone();
888        let program: &Program = &program_ref;
889        let code = &program.labels[self.label];
890        let stop = &code.stops[ordinal as usize];
891        let reached = matches!(self.rerun_stop_args(stop), Ok(Inner::Reached));
892        if !reached {
893            return Ok(None);
894        }
895        let rebuilt = match self.rebuilt_yield(code, stop) {
896            Rebuilt::Yield(y) => Some(y),
897            // Choice: if the list is empty, the scripts changed and there are no options to choose
898            Rebuilt::NoChoice => None,
899            Rebuilt::NotStop => return fail(LoadErrorKind::Corrupt),
900        };
901        self.stack.clear();
902        self.pc = stop.pc as usize + 1;
903        Ok(rebuilt)
904    }
905
906    /// Reruns the instructions that compute the arguments of the stop point, from the random state `args_rng`, up to just
907    /// before the stopping instruction. Even on failure, follows the `fn` frames back to the label's local variables, and
908    /// leaves `state` as it was before the call.
909    pub(super) fn rerun_stop_args(&mut self, stop: &StopInfo) -> Result<Inner, VmError> {
910        let before = self.state.clone();
911        self.stack.clear();
912        self.cap.clear();
913        self.rng.clone_from(&self.args_rng);
914        self.pc = stop.args_pc as usize;
915        self.fn_frames.clear();
916        self.cur_fn = None;
917        self.total = self.recount_total();
918        self.total_valid = true;
919        let result = self.exec(Some(stop.pc as usize));
920        while let Some(fr) = self.fn_frames.pop() {
921            self.locals = fr.locals;
922        }
923        self.cur_fn = None;
924        self.total_valid = false;
925        self.state = before;
926        result
927    }
928
929    /// Also reflects the rebuilt arguments in the last history record (the current stop point). So that `current()` and the
930    /// history do not diverge when `persistent var`s or `seen` changed after saving and the arguments changed.
931    pub(super) fn sync_current_record(&mut self) {
932        let (Some(Yield::Stop { command, id, .. }), Some(src)) = (&self.current, &self.cur_src)
933        else {
934            return;
935        };
936        let key = id
937            .as_ref()
938            .map(|id| format!("{}#{id}", super::label_path(&self.program, self.label)));
939        let name = &self.registry.command(*command).name;
940        if let Some(last) = self.history.last_mut()
941            && last.key == key
942            && last.command == *name
943        {
944            let last = Arc::make_mut(last);
945            last.args = src.args.clone();
946            last.values = src.values.clone();
947        }
948    }
949}
950
951/// Differences between the saved variables and the variables of the current scripts and registry.
952struct VarChanges {
953    added: Vec<String>,
954    removed: Vec<String>,
955    type_changed: Vec<String>,
956}
957
958/// Reads the bytes of a save. `Corrupt` if values (`NaN`, `±∞`, nesting that is too deep, sequences with the wrong number
959/// of nodes are broken), the random generator or the history are broken.
960/// The schema inside a save: its version, the type declarations, and the types of the script variables (without the
961/// host-declared ones).
962pub(crate) fn embedded_schema(bytes: &[u8]) -> Result<crate::schema_file::Embedded, LoadError> {
963    let body_bytes = unwrap(bytes, MAGIC, FORMAT_VERSION)?;
964    let body: SaveBody = match postcard::from_bytes(body_bytes) {
965        Ok(b) => b,
966        Err(_) => return fail(LoadErrorKind::Corrupt),
967    };
968    if !schema::consistent(&body.var_types, &body.vars, &body.host_vars) {
969        return fail(LoadErrorKind::Corrupt);
970    }
971    let mut var_types = body.var_types;
972    var_types.truncate(body.vars.len());
973    Ok(crate::schema_file::Embedded {
974        version: body.schema_version,
975        types: body.types,
976        var_types,
977    })
978}
979
980fn decode_save(bytes: &[u8]) -> Result<(SaveBody, Rng, Vec<Arc<StopRecord>>), LoadError> {
981    let body_bytes = unwrap(bytes, MAGIC, FORMAT_VERSION)?;
982    let mut body: SaveBody = match postcard::from_bytes(body_bytes) {
983        Ok(b) => b,
984        Err(_) => return fail(LoadErrorKind::Corrupt),
985    };
986    if !schema::consistent(&body.var_types, &body.vars, &body.host_vars) {
987        return fail(LoadErrorKind::Corrupt);
988    }
989    // Check that the values are not broken (`NaN`, `±∞`, nesting that is too deep, and sequences with the wrong number of
990    // nodes are broken). `-0.0` is normalized to `0.0`.
991    let all_values = body
992        .vars
993        .iter()
994        .chain(body.host_vars.iter())
995        .map(|(_, v)| v)
996        .chain(body.locals.iter().map(|(_, _, v)| v))
997        .chain(
998            body.frames
999                .iter()
1000                .flat_map(|f| f.locals.iter().map(|(_, _, v)| v)),
1001        );
1002    for v in all_values {
1003        if v.decode().is_none() {
1004            return fail(LoadErrorKind::Corrupt);
1005        }
1006    }
1007    let Some(rng) = Rng::from_state(body.rng) else {
1008        return fail(LoadErrorKind::Corrupt);
1009    };
1010    let mut history = Vec::with_capacity(body.history.len());
1011    for r in std::mem::take(&mut body.history) {
1012        match r.into_record() {
1013            Some(r) => history.push(Arc::new(r)),
1014            None => return fail(LoadErrorKind::Corrupt),
1015        }
1016    }
1017    Ok((body, rng, history))
1018}