hexicon-vm 0.3.0

The Hexicon virtual machine: runs the games Hexicon builds
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! Saving and restoring the state of a program, and restarting it.
//!
//! A saved state holds the objects a program has created or changed
//! since it was loaded. It does not hold the stack: `restoreGame` returns
//! to its caller, in a world where the objects are as they were when
//! `saveGame` ran. The file format is the reference VM's, so that the two
//! can read each other's files for the same image.
//!
//! The layout: a signature; the size and checksum of everything after
//! them; the image's timestamp and file name, which tie the state to the
//! program; descriptive text the program supplied; the table of built-in
//! classes; the IDs of the objects the program created; each saved
//! object's data; and the objects and properties the VM itself added to
//! the program's symbols.

use std::collections::HashMap;
use std::rc::Rc;

use hexicon_host::FileError;

use crate::decimal::Big;
use crate::error::{VmError, VmResult, code};
use crate::map::Map;
use crate::meta::MetaKind;
use crate::object::{BuiltinClass, Object};
use crate::program_object::ProgramObject;
use crate::value::{ObjId, PropId, Value};
use crate::vm::Vm;

const SIGNATURE: &[u8] = b"HX-state-v000A\r\n\x1a";

/// The names under which the objects and properties the VM creates for
/// itself are saved.
const LAST_PROP_OBJ: &[u8] = b"*LastPropObj";
const CONST_STR_OBJ: &[u8] = b"*ConstStrObj";
const CONST_LST_OBJ: &[u8] = b"*ConstLstObj";
const EXCEPTION_MESSAGE: &[u8] = b"exceptionMessage";

/// The checksum of a saved state: CRC-32 as the reference computes it,
/// starting from zero and not inverted at the end.
pub(crate) fn checksum(bytes: &[u8]) -> u32 {
    let mut acc: u32 = 0;
    for &byte in bytes {
        let mut entry = (acc ^ u32::from(byte)) & 0xff;
        for _ in 0..8 {
            entry = if entry & 1 != 0 {
                (entry >> 1) ^ 0xedb8_8320
            } else {
                entry >> 1
            };
        }
        acc = entry ^ (acc >> 8);
    }
    acc
}

/// Bytes being written.
#[derive(Default)]
struct Writer {
    out: Vec<u8>,
}

impl Writer {
    fn u8(&mut self, value: u8) {
        self.out.push(value);
    }

    fn u16(&mut self, value: usize) {
        self.out.extend_from_slice(&(value as u16).to_le_bytes());
    }

    fn u32(&mut self, value: u32) {
        self.out.extend_from_slice(&value.to_le_bytes());
    }

    fn bytes(&mut self, bytes: &[u8]) {
        self.out.extend_from_slice(bytes);
    }

    fn value(&mut self, value: Value) {
        self.out.extend_from_slice(&value.to_holder());
    }

    /// Bytes with their length in front.
    fn counted(&mut self, bytes: &[u8]) {
        self.u16(bytes.len());
        self.bytes(bytes);
    }

    /// Fill in a 32-bit number left blank earlier.
    fn patch_u32(&mut self, at: usize, value: u32) {
        self.out[at..at + 4].copy_from_slice(&value.to_le_bytes());
    }

    fn patch_u16(&mut self, at: usize, value: usize) {
        self.out[at..at + 2].copy_from_slice(&(value as u16).to_le_bytes());
    }
}

/// Bytes being read. Running off the end is a read error.
struct Reader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn bytes(&mut self, len: usize) -> VmResult<&'a [u8]> {
        let end = self
            .pos
            .checked_add(len)
            .filter(|&end| end <= self.data.len());
        let Some(end) = end else {
            return Err(VmError::new(code::READ_FILE));
        };
        let bytes = &self.data[self.pos..end];
        self.pos = end;
        Ok(bytes)
    }

    fn u8(&mut self) -> VmResult<u8> {
        Ok(self.bytes(1)?[0])
    }

    fn u16(&mut self) -> VmResult<usize> {
        let b = self.bytes(2)?;
        Ok(usize::from(u16::from_le_bytes([b[0], b[1]])))
    }

    fn u32(&mut self) -> VmResult<u32> {
        let b = self.bytes(4)?;
        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn counted(&mut self) -> VmResult<&'a [u8]> {
        let len = self.u16()?;
        self.bytes(len)
    }
}

/// The new IDs of the objects in a saved state. An object the program
/// created gets whatever ID is free when the state is restored, so every
/// reference to it has to be changed to match.
struct Fixups {
    /// The new ID for each old one, or `None` for an object that was
    /// transient and so was not saved.
    map: HashMap<u32, Option<ObjId>>,
}

impl Fixups {
    /// The new ID for an old one. An ID that is not in the table belongs
    /// to an object from the image, which keeps its ID.
    fn id(&self, old: ObjId) -> ObjId {
        match self.map.get(&old.0) {
            Some(new) => new.unwrap_or(ObjId::INVALID),
            None => old,
        }
    }

    fn value(&self, value: Value) -> Value {
        match value {
            Value::Obj(id) => Value::obj_or_nil(self.id(id)),
            Value::ObjX(id) => match self.id(id) {
                ObjId::INVALID => Value::Nil,
                id => Value::ObjX(id),
            },
            other => other,
        }
    }

    fn read_value(&self, reader: &mut Reader) -> VmResult<Value> {
        Ok(self.value(Value::from_holder(reader.bytes(Value::HOLDER_SIZE)?)))
    }
}

impl Vm {
    /// Whether an object from the image has to be saved: whether it can
    /// have changed since it was loaded.
    fn changed_since_load(&self, id: ObjId) -> bool {
        match self.objects.get(id) {
            Some(Object::Program(object) | Object::IntClassMod(object)) => object.modified,
            Some(
                Object::Vector(_)
                | Object::AnonFn(_)
                | Object::Map(_)
                | Object::StringBuilder(_)
                | Object::ByteArray(_)
                | Object::IndexedIter { .. }
                | Object::MapIter { .. },
            ) => true,
            Some(Object::Dict(dictionary)) => dictionary.modified,
            Some(Object::Class(_)) => self.objects.was_changed(id),
            _ => false,
        }
    }

    /// Whether a kind of lookup table is saved with its default value,
    /// which depends on the version of the class the image was built
    /// for. The two kinds of table have versions of their own.
    fn table_has_default(&self, kind: MetaKind) -> bool {
        self.meta
            .entry(kind)
            .and_then(|entry| entry.image_name.split_once('/'))
            .is_some_and(|(_, version)| version >= "030003")
    }

    /// Write one object's data.
    fn save_object(&self, id: ObjId, w: &mut Writer) -> VmResult<()> {
        let Some(object) = self.objects.get(id) else {
            return Ok(());
        };
        match object {
            Object::Program(obj) | Object::IntClassMod(obj) => {
                // The superclasses, and the properties that have changed.
                let changed: Vec<_> = obj.props().iter().filter(|p| p.modified).collect();
                w.u16(changed.len());
                w.u16(obj.superclasses.len());
                for superclass in &obj.superclasses {
                    w.u32(superclass.0);
                }
                for entry in changed {
                    w.u16(entry.prop.into());
                    w.value(entry.value);
                }
            }
            Object::String(text) => w.counted(text),
            Object::List(items) => {
                w.u16(items.len());
                for &item in items.iter() {
                    w.value(item);
                }
            }
            Object::Vector(items) | Object::AnonFn(items) => {
                // The space allocated, then the number in use.
                w.u16(self.objects.vector_alloc(id).max(items.len()));
                w.u16(items.len());
                for &item in items {
                    w.value(item);
                }
            }
            Object::IndexedIter {
                collection,
                current,
                first,
                last,
            } => {
                w.value(*collection);
                w.u32(*current as u32);
                w.u32(*first as u32);
                w.u32(*last as u32);
                w.u32(0);
            }
            Object::Map(table) => {
                let (buckets, slots, first_free) = table.save_parts();
                w.u16(buckets.len());
                w.u16(slots.len());
                w.u16(first_free);
                let kind = if table.weak {
                    MetaKind::WeakMap
                } else {
                    MetaKind::Map
                };
                if self.table_has_default(kind) {
                    w.value(table.default_value);
                }
                for bucket in buckets {
                    w.u16(bucket);
                }
                for (key, value, next) in slots {
                    w.value(key);
                    w.value(value);
                    w.u16(next);
                }
            }
            Object::MapIter { table, slot } => {
                w.value(Value::Obj(*table));
                w.u16(*slot as usize);
                w.u16(0);
            }
            Object::CharSet { name, .. } => w.counted(name.as_bytes()),
            Object::FileName(name) => {
                w.u32(name.special as u32);
                if name.special == 0 {
                    w.counted(name.path.as_bytes());
                }
            }
            Object::Date { dayno, daytime } => {
                w.u32(*dayno as u32);
                w.u32(*daytime as u32);
            }
            Object::TimeZone(zone) => {
                // The offsets and abbreviation now, in case the name
                // means nothing where the state is restored.
                let (gmtofs, save, abbr, name) = self.zone_saved_form(zone);
                w.u32(gmtofs as u32);
                w.u32(save as u32);
                for text in [abbr, name] {
                    let text = &text.as_bytes()[..text.len().min(255)];
                    w.u8(text.len() as u8);
                    w.bytes(text);
                }
            }
            // These are transient, so they are never saved.
            Object::File(_) | Object::TempFile(_) => {}
            Object::StrComp(comparator) => w.bytes(&comparator.to_bytes()),
            // A production from the image is never saved, so one that is
            // being saved is one the program made.
            Object::GrammarRule(production) => w.bytes(&production.to_bytes()),
            Object::Dict(dictionary) => {
                // The comparator, then each word with its entries for
                // objects that are saved too.
                w.u32(dictionary.comparator.0);
                let at = w.out.len();
                w.u32(0);
                let mut count = 0;
                for word in dictionary.words() {
                    let entries: Vec<_> = word
                        .entries
                        .iter()
                        .filter(|&&(object, _)| {
                            !self.objects.is_transient(object)
                                && (self.objects.is_in_root_set(object)
                                    || self.objects.is_marked(object))
                        })
                        .collect();
                    if entries.is_empty() {
                        continue;
                    }
                    count += 1;
                    w.counted(&word.text);
                    w.u16(entries.len());
                    for &&(object, prop) in &entries {
                        w.u32(object.0);
                        w.u16(prop.into());
                    }
                }
                w.patch_u32(at, count);
            }
            Object::ByteArray(bytes) => {
                w.u32(bytes.len() as u32);
                w.bytes(bytes);
            }
            Object::Decimal(big) => w.bytes(&big.to_bytes()),
            // The number of locals and of arguments, the function, the
            // method context, what was called, and the variables, taken
            // from the stack while the call runs.
            Object::FrameRef(fref) => {
                let vars = self.frame_vars(id).unwrap_or_else(|| fref.vars.clone());
                w.u16(fref.nlocals);
                w.u16(fref.nparams);
                w.value(fref.entry);
                w.value(fref.self_value);
                w.u32(fref.definer.0);
                w.u32(fref.target.0);
                w.u16(fref.prop.into());
                w.value(fref.invokee);
                for index in 0..fref.nlocals + fref.nparams {
                    w.value(vars.get(index).copied().unwrap_or(Value::Nil));
                }
            }
            Object::FrameDesc(desc) => {
                w.u32(desc.fref.0);
                w.u16(desc.scope.into());
                w.u16(desc.offset.into());
            }
            Object::CompiledCode(func) => {
                w.u16(func.code.len());
                w.u16(func.obj_refs.len());
                w.value(func.method_ctx);
                w.value(func.source);
                w.bytes(&func.code);
                for &at in &func.obj_refs {
                    w.u16(usize::from(at));
                }
            }
            Object::StringBuilder(buffer) => {
                // The space allocated, the amount to grow by, the length,
                // and the text in UTF-16.
                w.u32(buffer.room);
                w.u32(buffer.step);
                w.u32(buffer.len() as u32);
                for &c in buffer.iter() {
                    w.u16(u32::from(c) as usize);
                }
            }
            Object::Pattern { source, .. } => w.value(*source),
            Object::Class(class) => {
                w.u16(2 + 2 + 4 + Value::HOLDER_SIZE);
                w.u16(class.meta_index.into());
                w.u32(class.modifier.0);
                w.value(class.class_state);
            }
            Object::Opaque { meta_index, .. } => {
                let name = self
                    .meta
                    .get(usize::from(*meta_index))
                    .map_or("unknown", |entry| entry.kind.name());
                return Err(VmError::unimplemented(format!(
                    "saving an object of built-in class {name}"
                )));
            }
        }
        Ok(())
    }

    /// The state of the program as a saved state file. `metadata` is the
    /// table of descriptive text the program passed to `saveGame`, or
    /// nil.
    pub(crate) fn save_state(&mut self, metadata: Value) -> VmResult<Vec<u8>> {
        self.note_save_time();
        let mut w = Writer::default();
        w.bytes(SIGNATURE);
        let start = w.out.len();
        w.u32(0);
        w.u32(0);
        let mut timestamp = self.image_timestamp.clone();
        timestamp.resize(24, 0);
        w.bytes(&timestamp);
        w.counted(self.image_name.clone().as_bytes());

        // The program's description of the state: pairs of strings.
        match metadata {
            Value::Obj(id) => {
                let entries = match self.objects.get(id) {
                    Some(Object::Map(table)) => table.entries(),
                    _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
                };
                let at = w.out.len();
                w.u16(0);
                w.u16(0);
                let mut count = 0;
                for (key, value) in entries {
                    if let (Some(key), Some(value)) = (self.as_str(key), self.as_str(value)) {
                        w.counted(&key);
                        w.counted(&value);
                        count += 1;
                    }
                }
                let size = w.out.len() - at;
                if size > 0xffff {
                    return Err(VmError::new(code::DESC_TAB_OVERFLOW));
                }
                w.patch_u16(at, size - 2);
                w.patch_u16(at + 2, count);
            }
            _ => w.u16(0),
        }

        // Only what a restored program could still reach is worth saving.
        self.collect_garbage(false);

        // Find what will be saved. A class the image does not list can
        // still have instances, which the table of classes has to cover.
        let roots = self.gc_global_roots();
        self.objects.mark_persistent(&roots);
        let ids: Vec<ObjId> = self.objects.ids().collect();
        for &id in &ids {
            if self.objects.is_marked(id)
                && let Some(kind) = self.kind_of(id)
            {
                self.meta.add_if_new(kind);
            }
        }

        // The built-in classes, as the image numbers them.
        w.u16(self.meta.len());
        for index in 0..self.meta.len() {
            let Some(entry) = self.meta.get(index) else {
                continue;
            };
            w.counted(entry.image_name.as_bytes());
            w.u32(entry.class_obj.0);
            w.u16(entry.method_props.len());
            let (first, count) = entry.prop_range();
            w.u16(first.into());
            w.u16(usize::from(first) + count);
            for &prop in &entry.method_props {
                w.u16(prop.into());
            }
        }

        // Every object the program created that is still reachable, so
        // that each can be given a new ID when the state is restored.
        // Reaching an object through a transient one does not count:
        // transient objects are not saved.
        let at = w.out.len();
        w.u32(0);
        let mut listed = 0;
        let mut to_save = Vec::new();
        for &id in &ids {
            let root = self.objects.is_in_root_set(id);
            let transient = self.objects.is_transient(id);
            let reachable = self.objects.is_marked(id);
            if reachable && !root {
                w.u32(id.0);
                w.u32(u32::from(transient));
                listed += 1;
            }
            if reachable && !transient && (!root || self.changed_since_load(id)) {
                to_save.push(id);
            }
        }
        w.patch_u32(at, listed);

        // The objects themselves.
        w.u32(to_save.len() as u32);
        for id in to_save {
            w.u32(id.0);
            w.u8(u8::from(self.objects.is_in_root_set(id)));
            let kind = self.kind_of(id);
            let index = match self.objects.get(id) {
                Some(Object::Opaque { meta_index, .. }) => Some(usize::from(*meta_index)),
                _ => kind.and_then(|kind| self.meta.index_of(kind)),
            };
            w.u8(index.unwrap_or(0) as u8);
            self.save_object(id, &mut w)?;
        }

        // What the VM added to the program's symbols.
        let mut symbols: Vec<(&[u8], Value)> = vec![
            (LAST_PROP_OBJ, Value::Obj(self.predef.last_prop_obj)),
            (CONST_STR_OBJ, Value::Obj(self.predef.const_str_obj)),
            (CONST_LST_OBJ, Value::Obj(self.predef.const_lst_obj)),
        ];
        if self.exception_message_synthesized {
            symbols.push((
                EXCEPTION_MESSAGE,
                Value::Prop(self.predef.exception_message),
            ));
        }
        w.u32(symbols.len() as u32);
        for (name, value) in symbols {
            w.counted(name);
            w.value(value);
        }

        let size = (w.out.len() - start - 8) as u32;
        let crc = checksum(&w.out[start + 8..]);
        w.patch_u32(start, size);
        w.patch_u32(start + 4, crc);
        Ok(w.out)
    }

    /// Read one object's data into an object. `existing` is the object
    /// from the image, for an object that came from there.
    fn restore_object(
        &self,
        kind: MetaKind,
        meta_index: u16,
        existing: Option<&Object>,
        r: &mut Reader,
        fixups: &Fixups,
    ) -> VmResult<Object> {
        let bad = || VmError::new(code::BAD_SAVED_META_DATA);
        Ok(match kind {
            MetaKind::ProgramObject | MetaKind::IntClassMod => {
                let changed = r.u16()?;
                let superclass_count = r.u16()?;
                let mut obj = match existing {
                    Some(Object::Program(obj) | Object::IntClassMod(obj)) => obj.clone(),
                    _ => ProgramObject::default(),
                };
                let mut superclasses = Vec::with_capacity(superclass_count);
                for _ in 0..superclass_count {
                    superclasses.push(fixups.id(ObjId(r.u32()?)));
                }
                obj.set_superclasses(superclasses);
                for _ in 0..changed {
                    let prop = r.u16()? as PropId;
                    let value = fixups.read_value(r)?;
                    obj.set(prop, value);
                }
                obj.modified = true;
                if kind == MetaKind::ProgramObject {
                    Object::Program(obj)
                } else {
                    Object::IntClassMod(obj)
                }
            }
            MetaKind::String => Object::String(r.counted()?.into()),
            MetaKind::List => {
                let count = r.u16()?;
                let mut items = Vec::with_capacity(count);
                for _ in 0..count {
                    items.push(fixups.read_value(r)?);
                }
                Object::List(items.into())
            }
            MetaKind::Vector | MetaKind::Function => {
                let _allocated = r.u16()?;
                let count = r.u16()?;
                let mut items = Vec::with_capacity(count);
                for _ in 0..count {
                    items.push(fixups.read_value(r)?);
                }
                if kind == MetaKind::Vector {
                    Object::Vector(items)
                } else {
                    Object::AnonFn(items)
                }
            }
            MetaKind::IndexedIterator => {
                let collection = fixups.read_value(r)?;
                let current = r.u32()? as i32;
                let first = r.u32()? as i32;
                let last = r.u32()? as i32;
                r.u32()?;
                Object::IndexedIter {
                    collection,
                    current,
                    first,
                    last,
                }
            }
            MetaKind::Map | MetaKind::WeakMap => {
                let bucket_count = r.u16()?;
                let slot_count = r.u16()?;
                let first_free = r.u16()?;
                let default_value = if self.table_has_default(kind) {
                    fixups.read_value(r)?
                } else {
                    Value::Nil
                };
                let mut buckets = Vec::with_capacity(bucket_count);
                for _ in 0..bucket_count {
                    buckets.push(r.u16()?);
                }
                let mut slots = Vec::with_capacity(slot_count);
                for _ in 0..slot_count {
                    let key = fixups.read_value(r)?;
                    let value = fixups.read_value(r)?;
                    slots.push((key, value, r.u16()?));
                }
                Object::Map(Box::new(Map::from_parts(
                    buckets,
                    slots,
                    first_free,
                    default_value,
                    kind == MetaKind::WeakMap,
                )))
            }
            MetaKind::MapIterator => {
                let table = fixups.read_value(r)?;
                let slot = r.u16()? as u32;
                r.u16()?;
                Object::MapIter {
                    table: table.as_obj().unwrap_or(ObjId::INVALID),
                    slot,
                }
            }
            MetaKind::CharacterSet => {
                let name = String::from_utf8_lossy(r.counted()?).into_owned();
                let map = crate::charset::CharMap::load(&name).map(Rc::new);
                Object::CharSet { name, map }
            }
            MetaKind::Date => Object::Date {
                dayno: r.u32()? as i32,
                daytime: r.u32()? as i32,
            },
            MetaKind::TimeZone => {
                let gmtofs = r.u32()? as i32;
                let save = r.u32()? as i32;
                let len = usize::from(r.u8()?);
                let abbr = String::from_utf8_lossy(r.bytes(len)?).into_owned();
                let len = usize::from(r.u8()?);
                let name = String::from_utf8_lossy(r.bytes(len)?).into_owned();
                Object::TimeZone(Rc::new(crate::tz::Zone::recorded(
                    &name, gmtofs, save, &abbr,
                )))
            }
            MetaKind::FileName => {
                let special = r.u32()? as i32;
                let path = if special == 0 {
                    String::from_utf8_lossy(r.counted()?).into_owned()
                } else {
                    String::new()
                };
                Object::FileName(Box::new(crate::file::FileNameObj {
                    path,
                    special,
                    from_ui: 0,
                }))
            }
            MetaKind::GrammarRule => {
                let (mut production, used) =
                    crate::gram::GrammarRule::from_bytes(&r.data[r.pos..]).ok_or_else(bad)?;
                r.bytes(used)?;
                production.fix_ids(&|id| fixups.id(id));
                production.modified = true;
                Object::GrammarRule(Box::new(production))
            }
            MetaKind::StringComparator => {
                let (comparator, used) =
                    crate::strcomp::StrComp::from_bytes(&r.data[r.pos..]).ok_or_else(bad)?;
                r.bytes(used)?;
                Object::StrComp(Rc::new(comparator))
            }
            MetaKind::Dictionary => {
                // The words go in by their plain hash, and are moved for
                // the comparator once every object is back.
                let comparator = fixups.id(ObjId(r.u32()?));
                let mut dictionary = crate::dict::Dictionary::new(ObjId::INVALID);
                let plain = |text: &[u8]| text.iter().fold(0u32, |h, &b| h.wrapping_add(b.into()));
                let count = r.u32()?;
                for _ in 0..count {
                    let text = r.counted()?;
                    let entries = r.u16()?;
                    for _ in 0..entries {
                        let object = fixups.id(ObjId(r.u32()?));
                        let prop = r.u16()? as PropId;
                        if object.is_valid() {
                            dictionary.add(plain(text), text, object, prop);
                        }
                    }
                }
                dictionary.comparator = comparator;
                dictionary.modified = true;
                Object::Dict(Box::new(dictionary))
            }
            MetaKind::ByteArray => {
                let len = r.u32()? as usize;
                Object::ByteArray(r.bytes(len)?.to_vec())
            }
            MetaKind::Decimal => {
                // The length depends on the precision, which comes first.
                let start = r.pos;
                let prec = r.u16()?;
                r.pos = start;
                let data = r.bytes(5 + prec.div_ceil(2))?;
                Object::Decimal(Box::new(Big::from_bytes(data).ok_or_else(bad)?))
            }
            MetaKind::StackFrameRef => {
                let len = crate::frameref::FrameRef::data_len(&r.data[r.pos..]).ok_or_else(bad)?;
                let data = r.bytes(len)?;
                let mut failed = false;
                let fref = crate::frameref::FrameRef::read(
                    data,
                    &mut |holder| {
                        let mut reader = Reader {
                            data: holder,
                            pos: 0,
                        };
                        let value = fixups.read_value(&mut reader);
                        failed |= value.is_err();
                        value.ok()
                    },
                    &|id| fixups.id(id),
                )
                .ok_or_else(bad)?;
                if failed {
                    return Err(bad());
                }
                Object::FrameRef(Box::new(fref))
            }
            MetaKind::StackFrame => {
                let mut desc = crate::frameref::FrameDesc::read(r.bytes(8)?).ok_or_else(bad)?;
                desc.fref = fixups.id(desc.fref);
                Object::FrameDesc(desc)
            }
            MetaKind::CompiledCode => {
                // The objects its code refers to have their numbers in
                // this run, as any reference to an object does.
                let len = crate::compiled_code::CompiledCode::data_len(&r.data[r.pos..])
                    .ok_or_else(bad)?;
                let data = r.bytes(len)?;
                let mut failed = false;
                let mut func = crate::compiled_code::CompiledCode::read(data, &mut |holder| {
                    let mut reader = Reader {
                        data: holder,
                        pos: 0,
                    };
                    let value = fixups.read_value(&mut reader);
                    failed |= value.is_err();
                    value.ok()
                })
                .ok_or_else(bad)?;
                if failed {
                    return Err(bad());
                }
                let mut code = func.code.to_vec();
                for &at in &func.obj_refs {
                    let at = usize::from(at);
                    let Some(bytes) = code.get_mut(at..at + 4) else {
                        return Err(bad());
                    };
                    let old = ObjId(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));
                    bytes.copy_from_slice(&fixups.id(old).0.to_le_bytes());
                }
                func.code = code.into();
                Object::CompiledCode(Box::new(func))
            }
            MetaKind::StringBuilder => {
                // A saved game's sizes are taken as they are.
                let room = r.u32()?;
                let mut buffer = crate::object::StringBuilder::new(room, r.u32()?);
                let len = r.u32()?.min(room) as usize;
                for _ in 0..len {
                    let unit = r.u16()? as u32;
                    buffer
                        .chars
                        .push(char::from_u32(unit).unwrap_or('\u{fffd}'));
                }
                Object::StringBuilder(buffer)
            }
            MetaKind::Regex => Object::Pattern {
                source: fixups.read_value(r)?,
                compiled: None,
            },
            MetaKind::BuiltinClass => {
                let len = r.u16()?;
                let expected = 2 + 2 + 4 + Value::HOLDER_SIZE;
                let meta_index = r.u16()? as u16;
                let modifier = ObjId(r.u32()?);
                let class_state = if len >= expected {
                    fixups.read_value(r)?
                } else {
                    Value::Nil
                };
                if len > expected {
                    r.bytes(len - expected)?;
                }
                Object::Class(BuiltinClass {
                    meta_index,
                    modifier,
                    class_state,
                })
            }
            other => {
                let _ = meta_index;
                return Err(VmError::unimplemented(format!(
                    "restoring an object of built-in class {}",
                    other.name()
                )));
            }
        })
    }

    /// Put every object from the image back as it was loaded, and forget
    /// what depends on the objects the program created.
    fn reset_to_image(&mut self) {
        self.objects.drop_undo();
        self.objects.reset_to_image();
        // The built-in class objects the image defines are the ones in
        // force again.
        for index in 0..self.meta.len() {
            if let Some(entry) = self.meta.get_mut(index) {
                entry.class_obj = ObjId::INVALID;
            }
        }
        let ids: Vec<ObjId> = self.objects.ids().collect();
        for id in ids {
            if !self.objects.is_in_root_set(id) {
                continue;
            }
            if let Some(Object::Class(class)) = self.objects.get(id) {
                let index = usize::from(class.meta_index);
                if let Some(entry) = self.meta.get_mut(index) {
                    entry.class_obj = id;
                }
            }
        }
    }

    /// Replace the state of the program with a saved one.
    #[cfg(test)]
    pub(crate) fn restore_state(&mut self, data: &[u8]) -> VmResult<()> {
        self.restore_state_with(data, RestoreMode::Plain)
    }

    /// Replace the state of the program with a saved one, treating the
    /// savepoints UNDO goes back to as `mode` says.
    pub(crate) fn restore_state_with(&mut self, data: &[u8], mode: RestoreMode) -> VmResult<()> {
        let mut r = Reader { data, pos: 0 };
        // A file too short to hold the signature is one that could not
        // be read, not one of the wrong kind.
        let signature = r.bytes(SIGNATURE.len())?;
        if signature != SIGNATURE {
            return Err(VmError::new(code::NOT_SAVED_STATE));
        }
        let size = r.u32()? as usize;
        let crc = r.u32()?;
        let body = data.get(r.pos..r.pos + size);
        if body.map(checksum) != Some(crc) {
            return Err(VmError::new(code::BAD_SAVED_STATE));
        }
        let mut timestamp = self.image_timestamp.clone();
        timestamp.resize(24, 0);
        if r.bytes(24)? != timestamp.as_slice() {
            return Err(VmError::new(code::WRONG_SAVED_STATE));
        }
        // The image's file name and the descriptive text are for whoever
        // is choosing a file, not for restoring it.
        r.counted()?;
        r.counted()?;

        // The built-in class table. The state is for this image, so the
        // classes are the ones already here, but the state numbers them
        // its own way, and can have some the image does not list.
        let class_count = r.u16()?;
        let mut classes: Vec<Option<usize>> = Vec::with_capacity(class_count);
        for _ in 0..class_count {
            let name = r.counted()?;
            if name.len() > 255 {
                return Err(VmError::new(code::SAVED_META_TOO_LONG));
            }
            r.u32()?;
            let method_count = r.u16()?;
            r.bytes(4 + method_count * 2)?;
            let name = String::from_utf8_lossy(name).into_owned();
            let stem = |full: &str| full.split('/').next().unwrap_or("").to_owned();
            let find = |vm: &Vm| {
                (0..vm.meta.len()).find(|&index| {
                    vm.meta
                        .get(index)
                        .is_some_and(|entry| stem(&entry.image_name) == stem(&name))
                })
            };
            let mut found = find(self);
            if found.is_none() && self.meta.add(&name, Vec::new()).is_ok() {
                found = find(self);
            }
            classes.push(found);
        }

        match mode {
            RestoreMode::Plain => {
                self.undo_stash = None;
                self.objects.release_reserved();
            }
            RestoreMode::SetUndoAside => self.undo_stash = Some(self.objects.take_undo()),
            RestoreMode::ReturnKeepingUndo => {}
        }
        self.reset_to_image();

        // A new ID for each object the program had created; returning,
        // the ID it had, where that is free.
        let keep_ids = mode == RestoreMode::ReturnKeepingUndo;
        let mut kept = std::collections::HashSet::new();
        let mut moved = false;
        let mut fixups = Fixups {
            map: HashMap::new(),
        };
        let listed = r.u32()?;
        for _ in 0..listed {
            let old = r.u32()?;
            let transient = r.u32()? & 1 != 0;
            let placeholder = || Object::List(Rc::from(&[][..]));
            let new = if transient {
                None
            } else if keep_ids && self.objects.alloc_at(ObjId(old), placeholder()) {
                kept.insert(old);
                Some(ObjId(old))
            } else {
                moved |= keep_ids;
                Some(self.objects.alloc(placeholder()))
            };
            fixups.map.insert(old, new);
        }

        // The objects.
        let mut dictionaries = Vec::new();
        let saved = r.u32()?;
        for _ in 0..saved {
            let old = ObjId(r.u32()?);
            let from_image = r.u8()? != 0;
            let saved_index = usize::from(r.u8()?);
            let Some(meta_index) = classes.get(saved_index).copied().flatten() else {
                return Err(VmError::new(code::BAD_SAVED_META_DATA));
            };
            let meta_index = meta_index as u16;
            let id = if from_image {
                if self.objects.get(old).is_none() {
                    return Err(VmError::new(code::SAVED_OBJ_ID_INVALID));
                }
                old
            } else {
                fixups.id(old)
            };
            let Some(kind) = self.meta.get(usize::from(meta_index)).map(|e| e.kind) else {
                return Err(VmError::new(code::BAD_SAVED_META_DATA));
            };
            let existing = if from_image {
                self.objects.get(id)
            } else {
                None
            };
            // A vector's data starts with the room it has.
            let data_room = r
                .data
                .get(r.pos..r.pos + 2)
                .map(|room| usize::from(u16::from_le_bytes([room[0], room[1]])));
            let mut object = self.restore_object(kind, meta_index, existing, &mut r, &fixups)?;
            if matches!(object, Object::Dict(_)) {
                dictionaries.push(id);
            }
            if let Object::Class(class) = &mut object {
                // The class is named by its number in the saved table.
                let local = classes
                    .get(usize::from(class.meta_index))
                    .copied()
                    .flatten();
                class.meta_index = local.unwrap_or(usize::from(u16::MAX)) as u16;
                if let Some(entry) = self.meta.get_mut(usize::from(class.meta_index)) {
                    entry.class_obj = id;
                }
            }
            if id.is_valid() {
                if let Some(slot) = self.objects.get_mut(id) {
                    *slot = object;
                }
                // A vector has the room the saved state says.
                if matches!(kind, MetaKind::Vector | MetaKind::Function)
                    && let Some(room) = data_room
                {
                    let room = room.max(self.objects.vector_alloc(id));
                    self.objects.set_vector_alloc(id, room);
                }
            }
        }

        // What the VM had added to the program's symbols.
        let symbols = r.u32()?;
        for _ in 0..symbols {
            let name = r.counted()?;
            let value = fixups.read_value(&mut r)?;
            match (name, value) {
                (LAST_PROP_OBJ, Value::Obj(id)) => self.predef.last_prop_obj = id,
                (CONST_STR_OBJ, Value::Obj(id)) => self.predef.const_str_obj = id,
                (CONST_LST_OBJ, Value::Obj(id)) => self.predef.const_lst_obj = id,
                (EXCEPTION_MESSAGE, Value::Prop(prop)) => self.predef.exception_message = prop,
                _ => {}
            }
        }
        self.create_class_objects();
        for id in dictionaries {
            self.dict_rehash(id)?;
        }
        self.resolve_zones();
        self.place_dynamic_code();
        self.last_match = Default::default();
        self.collect_garbage(false);

        // Returning, the savepoints set aside go back if every object they
        // name is the one it was: from the image, transient (which no
        // restore touches), given back its own ID, or under an ID reserved
        // when they were set aside, which no other object has had since
        // (the objects only they refer to are kept for them meanwhile).
        // Otherwise they are forgotten, as by any restore.
        if mode == RestoreMode::ReturnKeepingUndo
            && let Some(stash) = self.undo_stash.take()
        {
            let same = !moved
                && stash.ids().all(|id| {
                    self.objects.is_in_root_set(id)
                        || self.objects.is_transient(id)
                        || kept.contains(&id.0)
                        || self.objects.is_reserved(id)
                });
            if same {
                self.objects.put_undo(stash);
            }
        }
        if mode == RestoreMode::ReturnKeepingUndo {
            self.objects.release_reserved();
        }
        Ok(())
    }

    /// Return the program to the state it was loaded in.
    pub(crate) fn restart_state(&mut self) -> VmResult<()> {
        self.undo_stash = None;
        self.objects.release_reserved();
        self.reset_to_image();
        self.create_synthesized_objects()?;
        self.create_class_objects();
        self.last_match = Default::default();
        self.collect_garbage(false);
        self.run_static_initializers()
    }

    // ---- the functions a program calls ----

    /// `saveGame(file, metadata?)`.
    pub(crate) fn bif_save(&mut self, argc: u32) -> VmResult<()> {
        if !(1..=2).contains(&argc) {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let metadata = if argc >= 2 { self.arg(1) } else { Value::Nil };
        if !matches!(metadata, Value::Nil | Value::Obj(_)) {
            return Err(VmError::new(code::BAD_TYPE_BIF));
        }
        let name = self.file_name_arg(self.arg(0), crate::file::Access::Write)?;
        let state = self.save_state(metadata)?;
        self.host
            .write_file(&name, &state)
            .map_err(|_| VmError::new(code::CREATE_FILE))?;
        self.r0 = Value::Nil;
        Ok(())
    }

    /// `restoreGame(file, mode?)`. The mode is Hexicon's, for Hexad's
    /// snapshots: 1 sets the savepoints aside, 2 returns keeping them
    /// (see `RestoreMode`); without it, or 0, they are forgotten, as in
    /// the reference.
    pub(crate) fn bif_restore(&mut self, argc: u32) -> VmResult<()> {
        if !(1..=2).contains(&argc) {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let mode = match if argc == 2 { self.arg(1) } else { Value::Nil } {
            Value::Nil | Value::Int(0) => RestoreMode::Plain,
            Value::Int(1) => RestoreMode::SetUndoAside,
            Value::Int(2) => RestoreMode::ReturnKeepingUndo,
            _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
        };
        let name = self.file_name_arg(self.arg(0), crate::file::Access::Read)?;
        self.sync_files();
        let state = self.host.read_file(&name).map_err(|error| {
            VmError::new(match error {
                FileError::NotFound => code::FILE_NOT_FOUND,
                _ => code::READ_FILE,
            })
        })?;
        self.restore_state_with(&state, mode)?;
        self.r0 = Value::Nil;
        Ok(())
    }

    /// `restartGame()`.
    pub(crate) fn bif_restart(&mut self, argc: u32) -> VmResult<()> {
        if argc != 0 {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        self.restart_state()?;
        self.r0 = Value::Nil;
        Ok(())
    }
}

/// How a restore treats the savepoints UNDO goes back to.
///
/// A visit to an earlier state and back (Hexad's branch points) restores
/// twice, and a restore forgets the savepoints, so the player could not
/// UNDO the turns before the visit. Going, they can be set aside instead;
/// coming back to the state they were set aside from, they can be put
/// back, if every object is under the ID it had, which the restore that
/// returns sees to where it can. That they describe changes from this
/// very state is the caller's to make sure of: it is so when the state
/// returned to was saved just before setting them aside.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RestoreMode {
    /// Forget them, as the reference does.
    Plain,
    /// Set them aside, to be put back by a later `ReturnKeepingUndo`.
    SetUndoAside,
    /// Give each object the ID it was saved with, and put back the
    /// savepoints set aside if every object they name is the same.
    ReturnKeepingUndo,
}