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
//! Built-in function sets: the functions the VM provides to programs.
//!
//! Each function follows the reference VM's implementation. A function
//! receives its arguments on
//! top of the stack, first argument uppermost, and leaves its result, if
//! it has one, in register 0. The caller removes the arguments.

use std::cmp::Ordering;

use crate::error::{ErrParam, VmError, VmResult, code};
use crate::identity;
use crate::object::Object;
use crate::value::{INVALID_PROP, NativeDesc, ObjId, Value};
use crate::vm::Vm;

/// A function set the VM knows about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FunctionSet {
    /// `hexicon-vm`: access to the VM itself.
    Machine,
    /// `hexicon-vm-test`: hooks for the VM's own test suite.
    MachineTest,
    /// `hexicon-gen`: general-purpose functions.
    Gen,
    /// `hexicon-io`: console input and output.
    Io,
    /// `hexicon-io-ext`: extended console functions. Not implemented.
    IoExt,
    /// `hexicon-net`: networking. Not implemented.
    Net,
}

/// The entries of a function set: name and calling interface.
type Table = &'static [(&'static str, NativeDesc)];

const fn fixed(min: u8) -> NativeDesc {
    NativeDesc::fixed(min)
}
const fn opt(min: u8, opt: u8) -> NativeDesc {
    NativeDesc::optional(min, opt)
}
const fn var(min: u8) -> NativeDesc {
    NativeDesc::variable(min)
}

const MACHINE: Table = &[
    ("collectGarbage", fixed(0)),
    ("setSay", fixed(1)),
    ("vmVersion", fixed(0)),
    ("vmId", fixed(0)),
    ("vmBanner", fixed(0)),
    ("inPreinit", fixed(0)),
    ("debugTrace", var(1)),
    ("globalSymbols", opt(0, 1)),
    ("newProperty", fixed(0)),
    ("stackTrace", opt(0, 2)),
    ("namedArg", opt(1, 1)),
    ("namedArgList", fixed(0)),
    ("definitionPlace", fixed(2)),
];

const MACHINE_TEST: Table = &[
    ("vmTestObjId", fixed(1)),
    ("vmTestObjGcState", fixed(1)),
    ("vmTestCharCode", fixed(1)),
];

const GEN: Table = &[
    ("typeOf", fixed(1)),
    ("arg", fixed(1)),
    ("firstObj", opt(0, 2)),
    ("nextObj", opt(1, 2)),
    ("randomize", var(0)),
    ("rand", var(0)),
    ("toString", opt(1, 2)),
    ("toInteger", opt(1, 1)),
    ("getTime", opt(0, 1)),
    ("regexMatch", opt(2, 1)),
    ("regexSearch", opt(2, 1)),
    ("regexGroup", fixed(1)),
    ("regexReplace", opt(3, 2)),
    ("savepoint", fixed(0)),
    ("undo", fixed(0)),
    ("saveGame", opt(1, 1)),
    ("restoreGame", fixed(1)),
    ("restartGame", fixed(0)),
    ("max", var(1)),
    ("min", var(1)),
    ("repeatString", opt(1, 1)),
    ("functionParams", fixed(1)),
    ("toNumber", opt(1, 1)),
    ("sprintf", var(1)),
    ("repeatList", opt(1, 1)),
    ("abs", fixed(1)),
    ("sgn", fixed(1)),
    ("concat", var(0)),
    ("regexSearchLast", opt(2, 1)),
];

const IO: Table = &[
    ("print", var(1)),
    ("setLogFile", opt(1, 1)),
    ("clearScreen", fixed(0)),
    ("pausePrompt", fixed(0)),
    ("inputLine", fixed(0)),
    ("inputKey", fixed(0)),
    ("inputEvent", opt(0, 1)),
    ("inputDialog", fixed(5)),
    ("inputFile", fixed(4)),
    ("timeDelay", fixed(1)),
    ("systemInfo", var(1)),
    ("statusMode", fixed(1)),
    ("statusRight", fixed(1)),
    ("resExists", fixed(1)),
    ("setScriptFile", opt(1, 1)),
    ("localCharSet", fixed(1)),
    ("flushOutput", fixed(0)),
    ("inputLineTimeout", opt(0, 1)),
    ("inputLineCancel", fixed(1)),
    ("paneCreate", fixed(8)),
    ("paneDelete", fixed(1)),
    ("paneClear", fixed(1)),
    ("paneSay", var(1)),
    ("paneFlush", fixed(1)),
    ("paneSizeToContents", fixed(1)),
    ("paneGoTo", fixed(3)),
    ("paneSetTextColor", fixed(3)),
    ("paneSetScreenColor", fixed(2)),
    ("paneInfo", fixed(1)),
    ("paneSetSize", fixed(4)),
    ("logConsoleCreate", fixed(3)),
    ("logConsoleClose", fixed(1)),
    ("logConsoleSay", var(1)),
    ("logInputEvent", fixed(1)),
];

impl FunctionSet {
    /// The function set with a given name and version, as an image names
    /// it (`name/version`).
    pub(crate) fn from_image_name(image_name: &str) -> VmResult<Self> {
        let (name, version) = image_name.split_once('/').unwrap_or((image_name, "000000"));
        let (set, provided) = match name {
            "hexicon-vm" => (Self::Machine, "010007"),
            "hexicon-vm-test" => (Self::MachineTest, "010000"),
            "hexicon-gen" => (Self::Gen, "030008"),
            "hexicon-io" => (Self::Io, "030007"),
            "hexicon-io-ext" => (Self::IoExt, "030000"),
            "hexicon-net" => (Self::Net, "030001"),
            _ => {
                return Err(VmError::with(
                    code::UNKNOWN_FUNC_SET,
                    vec![ErrParam::Str(image_name.to_owned())],
                ));
            }
        };
        if version > provided {
            return Err(VmError::with(
                code::FUNCSET_TOO_OLD,
                vec![
                    ErrParam::Str(image_name.to_owned()),
                    ErrParam::Str(provided.to_owned()),
                ],
            ));
        }
        Ok(set)
    }

    fn table(self) -> Table {
        match self {
            Self::Machine => MACHINE,
            Self::MachineTest => MACHINE_TEST,
            Self::Gen => GEN,
            Self::Io => IO,
            Self::IoExt | Self::Net => &[],
        }
    }
}

// `firstObj` and `nextObj` flags.
const ENUM_INSTANCES: i32 = 1;
const ENUM_CLASSES: i32 = 2;

// `setSay` arguments that clear a setting.
const SETSAY_NO_FUNC: i32 = 1;
const SETSAY_NO_METHOD: i32 = 2;

impl Vm {
    /// The calling interface of a built-in function, or `None` if the
    /// function does not exist.
    pub(crate) fn bif_desc(&self, set: u16, index: u16) -> Option<NativeDesc> {
        let table = self.function_sets.get(set as usize)?.table();
        table.get(index as usize).map(|(_, desc)| *desc)
    }

    /// Call a built-in function with `argc` arguments on the stack.
    pub(crate) fn call_bif(&mut self, set: u16, index: u16, argc: u32) -> VmResult<()> {
        prof_scope!(crate::prof::BIF + (u32::from(set) << 8) + u32::from(index));
        let Some(&function_set) = self.function_sets.get(set as usize) else {
            return Err(VmError::with(
                code::UNAVAIL_INTRINSIC,
                vec![
                    ErrParam::Int(index.into()),
                    ErrParam::Str(format!("#{set}")),
                ],
            ));
        };
        if argc as usize > self.stack.len() {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let base = self.stack.len() - argc as usize;
        match function_set {
            FunctionSet::Machine => self.call_machine(index, argc)?,
            FunctionSet::MachineTest => self.call_machine_test(index, argc)?,
            FunctionSet::Gen => self.call_gen(index, argc)?,
            FunctionSet::Io => self.call_io(index, argc)?,
            FunctionSet::IoExt | FunctionSet::Net => {
                return Err(self.unimplemented_bif(function_set, index));
            }
        }
        self.stack.truncate(base);
        Ok(())
    }

    fn unimplemented_bif(&self, set: FunctionSet, index: u16) -> VmError {
        match set.table().get(index as usize) {
            Some((name, _)) => VmError::unimplemented(format!("built-in function {name}")),
            None => VmError::unimplemented(format!("built-in function {index} of {set:?}")),
        }
    }

    pub(crate) fn check_argc(argc: u32, expected: u32) -> VmResult<()> {
        Self::check_argc_range(argc, expected, expected)
    }

    pub(crate) fn check_argc_range(argc: u32, min: u32, max: u32) -> VmResult<()> {
        if argc < min || argc > max {
            Err(VmError::new(code::WRONG_NUM_OF_ARGS))
        } else {
            Ok(())
        }
    }

    // ---- hexicon-vm ----

    fn call_machine(&mut self, index: u16, argc: u32) -> VmResult<()> {
        match index {
            // collectGarbage()
            0 => {
                Self::check_argc(argc, 0)?;
                self.collect_garbage(false);
            }
            1 => self.set_say(argc)?,
            2 => {
                Self::check_argc(argc, 0)?;
                self.r0 = Value::Int(identity::version_number());
            }
            3 => {
                Self::check_argc(argc, 0)?;
                self.r0 = self.new_str(identity::ID);
            }
            4 => {
                Self::check_argc(argc, 0)?;
                self.r0 = self.new_str(&identity::banner());
            }
            5 => {
                Self::check_argc(argc, 0)?;
                self.r0 = Value::Int(self.preinit_mode.into());
            }
            // debugTrace(mode, ...): there is no debugger.
            6 => {
                if argc < 1 {
                    return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
                }
                self.int_arg(self.arg(0))?;
                self.r0 = Value::Nil;
            }
            // globalSymbols(which?): the table of global symbols, or
            // of macros. Only a program compiled for debugging has them.
            7 => {
                Self::check_argc_range(argc, 0, 1)?;
                let which = if argc >= 1 {
                    self.int_arg(self.arg(0))?
                } else {
                    1
                };
                let table = match which {
                    1 => self.symbol_table,
                    2 => self.macro_table,
                    _ => None,
                };
                self.r0 = table.map_or(Value::Nil, Value::Obj);
            }
            8 => {
                Self::check_argc(argc, 0)?;
                self.r0 = Value::Prop(self.alloc_prop()?);
            }
            9 => self.stack_trace(argc)?,
            10 => self.named_arg(argc)?,
            11 => self.named_arg_list(argc)?,
            // definitionPlace(obj, prop): where the method obj.prop is
            // written, as 'file:line'; nil if it is not a method, or if
            // the image does not record where its code came from.
            12 => {
                Self::check_argc(argc, 2)?;
                let (Value::Obj(object), Value::Prop(prop)) = (self.arg(0), self.arg(1)) else {
                    return Err(VmError::new(code::BAD_TYPE_BIF));
                };
                let place = match crate::program_object::find_prop(&self.objects, object, prop) {
                    Some((Value::CodeOfs(func), _)) => self.definition_place(func),
                    _ => None,
                };
                self.r0 = match place {
                    Some(place) => self.new_str(&place),
                    None => Value::Nil,
                };
            }
            _ => return Err(self.unimplemented_bif(FunctionSet::Machine, index)),
        }
        Ok(())
    }

    /// `setSay(val)`: set the default output function or method, and
    /// return the previous setting.
    fn set_say(&mut self, argc: u32) -> VmResult<()> {
        Self::check_argc(argc, 1)?;
        match self.arg(0) {
            arg @ (Value::Prop(_) | Value::Int(SETSAY_NO_METHOD)) => {
                self.r0 = match self.say_method {
                    INVALID_PROP => Value::Int(SETSAY_NO_METHOD),
                    prop => Value::Prop(prop),
                };
                self.say_method = match arg {
                    Value::Prop(prop) => prop,
                    _ => INVALID_PROP,
                };
            }
            arg @ (Value::FuncPtr(_)
            | Value::Obj(_)
            | Value::BifPtr { .. }
            | Value::Int(SETSAY_NO_FUNC)) => {
                self.r0 = match self.say_function {
                    Value::Nil => Value::Int(SETSAY_NO_FUNC),
                    function => function,
                };
                self.say_function = match arg {
                    Value::Int(_) => Value::Nil,
                    function => function,
                };
            }
            _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
        }
        Ok(())
    }

    /// Allocate a property ID that the program does not use.
    fn alloc_prop(&mut self) -> VmResult<u16> {
        let holder = self.predef.last_prop_obj;
        let Some(Object::Vector(items)) = self.objects.get_mut(holder) else {
            return Err(VmError::new(code::OUT_OF_PROPIDS));
        };
        let last = match items.first() {
            Some(Value::Prop(prop)) => *prop,
            _ => 0,
        };
        if last == u16::MAX {
            return Err(VmError::new(code::OUT_OF_PROPIDS));
        }
        if items.is_empty() {
            items.push(Value::Nil);
        }
        items[0] = Value::Prop(last + 1);
        Ok(last + 1)
    }

    // ---- hexicon-vm-test ----

    fn call_machine_test(&mut self, index: u16, argc: u32) -> VmResult<()> {
        match index {
            0 => {
                Self::check_argc(argc, 1)?;
                let id = self.obj_arg(self.arg(0))?;
                self.r0 = Value::Int(id.0 as i32);
            }
            2 => {
                Self::check_argc(argc, 1)?;
                let text = self.require_str(self.arg(0))?;
                self.r0 = match std::str::from_utf8(&text)
                    .ok()
                    .and_then(|s| s.chars().next())
                {
                    Some(c) => Value::Int(c as i32),
                    None => Value::Nil,
                };
            }
            _ => return Err(self.unimplemented_bif(FunctionSet::MachineTest, index)),
        }
        Ok(())
    }

    // ---- hexicon-gen ----

    fn call_gen(&mut self, index: u16, argc: u32) -> VmResult<()> {
        match index {
            // dataType(val)
            0 => {
                Self::check_argc(argc, 1)?;
                self.r0 = Value::Int(self.datatype(self.arg(0)));
            }
            // getArg(idx): an argument of the calling function.
            1 => {
                Self::check_argc(argc, 1)?;
                let index = self.int_arg(self.arg(0))?;
                let frame = self.frames.last().ok_or(VmError::new(code::BAD_VAL_BIF))?;
                if index < 1 || index as u32 > frame.argc {
                    return Err(VmError::new(code::BAD_VAL_BIF));
                }
                self.r0 = self.stack[frame.base as usize - index as usize];
            }
            // firstObj(cls?, flags?)
            2 => {
                Self::check_argc_range(argc, 0, 2)?;
                self.enum_objects(argc, 0, 1)?;
            }
            // nextObj(obj, cls?, flags?)
            3 => {
                Self::check_argc_range(argc, 1, 3)?;
                let previous = self.obj_arg(self.arg(0))?;
                self.enum_objects(argc - 1, 1, previous.0 + 1)?;
            }
            4 => self.bif_randomize(argc)?,
            5 => self.bif_rand(argc)?,
            // toString(val, radix?, isSigned?)
            6 => {
                Self::check_argc_range(argc, 1, 3)?;
                let radix = if argc >= 2 {
                    self.int_arg(self.arg(1))?
                } else {
                    10
                };
                if !(2..=36).contains(&radix) {
                    return Err(VmError::new(code::BAD_VAL_BIF));
                }
                let value = self.arg(0);
                // In any radix but 10, a number is shown unsigned unless
                // the caller asks otherwise.
                let signed = if argc >= 3 {
                    match self.arg(2) {
                        Value::True => true,
                        Value::Nil => false,
                        _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
                    }
                } else {
                    radix == 10
                };
                let (string, _) = self.radix_text(value, radix as u32, signed)?;
                self.r0 = match string {
                    Value::Obj(_) => string,
                    // The result is always a string object.
                    other => self.const_to_object(other),
                };
            }
            // savepoint()
            13 => {
                Self::check_argc(argc, 0)?;
                self.objects.savepoint();
            }
            // undo(): true if there was a savepoint to return to.
            14 => {
                Self::check_argc(argc, 0)?;
                self.r0 = Value::logical(self.objects.undo());
            }
            15 => self.bif_save(argc)?,
            16 => self.bif_restore(argc)?,
            17 => self.bif_restart(argc)?,
            // toInteger(val, radix?)
            7 => {
                Self::check_argc_range(argc, 1, 2)?;
                self.r0 = self.parse_integer(argc, true)?;
            }
            // sprintf(format, ...)
            23 => self.r0 = self.sprintf(argc)?,
            // toNumber(val, radix?)
            22 => {
                Self::check_argc_range(argc, 1, 2)?;
                self.r0 = self.parse_integer(argc, false)?;
            }
            // rexMatch(pat, str, index?)
            9 => {
                Self::check_argc_range(argc, 2, 3)?;
                self.r0 = self.rex_match(argc)?;
            }
            // rexSearch(pat, str, index?) and rexSearchLast(pat, str, index?)
            10 | 28 => {
                Self::check_argc_range(argc, 2, 3)?;
                self.r0 = self.rex_search(argc, index == 10)?;
            }
            // rexGroup(n)
            11 => {
                Self::check_argc(argc, 1)?;
                self.r0 = self.rex_group()?;
            }
            // rexReplace(pat, str, replacement, flags?, index?, limit?)
            12 => {
                Self::check_argc_range(argc, 3, 6)?;
                self.r0 = self.find_replace(self.arg(1), argc, true)?;
            }
            // makeString(val, repeatCount?)
            20 => {
                Self::check_argc_range(argc, 1, 2)?;
                self.r0 = self.make_string(argc)?;
            }
            // max(...) and min(...)
            18 | 19 => {
                let wanted = if index == 18 {
                    Ordering::Greater
                } else {
                    Ordering::Less
                };
                self.r0 = self.extreme(argc, wanted)?;
            }
            // getFuncParams(func)
            21 => {
                Self::check_argc(argc, 1)?;
                let Some((min, opt, varargs)) = self.value_interface(self.arg(0)) else {
                    return Err(VmError::new(code::FUNCPTR_VAL_REQD));
                };
                self.r0 = self.new_list(vec![
                    Value::Int(min),
                    Value::Int(opt),
                    Value::logical(varargs),
                ]);
            }
            // makeList(val, repeatCount?)
            24 => {
                Self::check_argc_range(argc, 1, 2)?;
                let count = if argc >= 2 {
                    self.int_arg(self.arg(1))?
                } else {
                    1
                };
                if count < 0 {
                    return Err(VmError::new(code::BAD_VAL_BIF));
                }
                self.r0 = self.new_list(vec![self.arg(0); count as usize]);
            }
            // abs(val)
            25 => {
                Self::check_argc(argc, 1)?;
                self.r0 = match self.arg(0) {
                    Value::Int(n) => Value::Int(n.wrapping_abs()),
                    other => match self.as_big(other).cloned() {
                        Some(big) if big.neg && big.kind != crate::decimal::Kind::NaN => {
                            let mut positive = big;
                            positive.neg = false;
                            self.new_big(positive)
                        }
                        Some(_) => other,
                        None => return Err(VmError::new(code::BAD_TYPE_BIF)),
                    },
                };
            }
            // sgn(val)
            26 => {
                Self::check_argc(argc, 1)?;
                self.r0 = match self.arg(0) {
                    Value::Int(n) => Value::Int(n.signum()),
                    other => match self.as_big(other) {
                        Some(big) if big.zero => Value::Int(0),
                        Some(big) if big.neg => Value::Int(-1),
                        Some(_) => Value::Int(1),
                        None => return Err(VmError::new(code::BAD_TYPE_BIF)),
                    },
                };
            }
            // concat(...)
            27 => {
                let mut text = Vec::new();
                for index in 0..argc as usize {
                    let (_, piece) = self.text_cast(self.arg(index))?;
                    text.extend_from_slice(&piece);
                }
                self.r0 = self.try_new_string(text)?;
            }
            // getTime(type?)
            8 => {
                Self::check_argc_range(argc, 0, 1)?;
                let kind = if argc >= 1 {
                    self.int_arg(self.arg(0))?
                } else {
                    1
                };
                self.r0 = self.get_time(kind)?;
            }
            _ => return Err(self.unimplemented_bif(FunctionSet::Gen, index)),
        }
        Ok(())
    }

    /// Find the first object at or after an ID that passes the filters of
    /// `firstObj` and `nextObj`. The filter arguments start at stack
    /// position `first_arg`.
    fn enum_objects(&mut self, argc: u32, first_arg: usize, start: u32) -> VmResult<()> {
        let mut class = ObjId::INVALID;
        let mut flags = ENUM_INSTANCES;
        match argc {
            2 => {
                class = self.obj_arg(self.arg(first_arg))?;
                flags = self.int_arg(self.arg(first_arg + 1))?;
            }
            1 => match self.arg(first_arg) {
                Value::Int(n) => flags = n,
                Value::Obj(id) => class = id,
                _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
            },
            _ => {}
        }
        self.r0 = Value::Nil;
        for id in (start..self.objects.id_limit()).map(ObjId) {
            let is_class = match self.objects.get(id) {
                None | Some(Object::IntClassMod(_)) => continue,
                Some(Object::Program(object)) => object.is_class(),
                Some(Object::Class(_)) => true,
                Some(_) => false,
            };
            let wanted = if is_class {
                ENUM_CLASSES
            } else {
                ENUM_INSTANCES
            };
            if flags & wanted == 0 {
                continue;
            }
            let matches = if class.is_valid() {
                self.is_instance_of(id, class)
            } else {
                // Without a class, skip the strings and lists that
                // programs create as temporary values.
                !matches!(
                    self.objects.get(id),
                    Some(Object::String(_) | Object::List(_))
                )
            };
            if matches {
                self.r0 = Value::Obj(id);
                break;
            }
        }
        Ok(())
    }

    /// The index of a function set in the image's dependency list.
    pub(crate) fn function_set_index(&self, name: &str) -> Option<u16> {
        let wanted = FunctionSet::from_image_name(name).ok()?;
        self.function_sets
            .iter()
            .position(|&set| set == wanted)
            .map(|index| index as u16)
    }

    /// `makeString(val, repeatCount?)`: a string from a string, a
    /// character code, or a list of character codes, repeated.
    fn make_string(&mut self, argc: u32) -> VmResult<Value> {
        let value = self.arg(0);
        let repeat = if argc >= 2 {
            self.int_arg(self.arg(1))?
        } else {
            1
        };
        if repeat < 0 {
            return Err(VmError::new(code::BAD_VAL_BIF));
        }
        let code_point = |n: i32| char::from_u32(n as u32).unwrap_or('\u{fffd}');
        let unit: Vec<u8> = if let Some(text) = self.as_str(value) {
            text.to_vec()
        } else if let Value::Int(n) = value {
            code_point(n).to_string().into_bytes()
        } else if let Some(len) = self.list_like_len(value)? {
            let mut text = String::new();
            for index in 1..=len {
                match self.list_like_get(value, index)? {
                    Value::Int(n) => text.push(code_point(n)),
                    _ => return Err(VmError::new(code::INT_VAL_REQD)),
                }
            }
            text.into_bytes()
        } else {
            return Err(VmError::new(code::BAD_TYPE_BIF));
        };
        if unit.len() * repeat as usize > 0xffff - 2 {
            return Err(VmError::new(code::BAD_VAL_BIF));
        }
        self.try_new_string(unit.repeat(repeat as usize))
    }

    /// Convert a value to text, showing numbers in a radix. That reaches
    /// into lists, whose elements are converted the same way.
    fn radix_text(
        &mut self,
        value: Value,
        radix: u32,
        signed: bool,
    ) -> VmResult<(Value, std::rc::Rc<[u8]>)> {
        if radix == 10 && signed {
            return self.text_of(value);
        }
        let text: Vec<u8> = match value {
            Value::Int(n) => int_to_radix(n, radix, signed).into_bytes(),
            _ => {
                if let Some(big) = self.as_big(value) {
                    if radix == 10 || !big.is_frac_zero() {
                        return self.text_of(value);
                    }
                    big.to_radix_text(radix).into_bytes()
                } else if let Some(len) = self.list_like_len(value)? {
                    let mut joined = Vec::new();
                    for index in 1..=len {
                        let element = self.list_like_get(value, index)?;
                        if index != 1 {
                            joined.push(b',');
                        }
                        joined.extend_from_slice(&self.radix_text(element, radix, signed)?.1);
                    }
                    joined
                } else {
                    return self.text_of(value);
                }
            }
        };
        let text: std::rc::Rc<[u8]> = text.into();
        Ok((self.try_new_string(text.clone())?, text))
    }

    /// `toInteger(val, radix?)`.
    fn parse_integer(&mut self, argc: u32, int_only: bool) -> VmResult<Value> {
        let value = self.arg(0);
        if let Some(big) = self.as_big(value) {
            return if int_only {
                Self::big_to_int(big).map(Value::Int)
            } else {
                Ok(value)
            };
        }
        match value {
            Value::Int(_) => return Ok(value),
            Value::True => return Ok(Value::Int(1)),
            Value::Nil => return Ok(Value::Int(0)),
            _ => {}
        }
        let text = self.require_str(value)?;
        let radix = if argc >= 2 {
            let radix = self.int_arg(self.arg(1))?;
            if !(2..=36).contains(&radix) {
                return Err(VmError::new(code::BAD_VAL_BIF));
            }
            radix as u32
        } else {
            10
        };
        let trimmed = text.trim_ascii();
        if trimmed == b"nil" {
            return Ok(Value::Int(0));
        }
        // The reference VM compares only the first three characters here.
        if trimmed.len() == 4 && trimmed.starts_with(b"tru") {
            return Ok(Value::Int(1));
        }
        self.parse_number(&text, radix, int_only)
    }

    /// Parse text as a number in a radix. Unless only an integer will
    /// do, a decimal number with a fraction or an exponent, or one too
    /// large for an integer, is a Decimal.
    pub(crate) fn parse_number(
        &mut self,
        text: &[u8],
        radix: u32,
        int_only: bool,
    ) -> VmResult<Value> {
        let big = |vm: &mut Vm| {
            let source = String::from_utf8_lossy(text).into_owned();
            if radix != 10 {
                return vm.new_big(crate::decimal::Big::parse_radix(&source, radix));
            }
            let prec = crate::decimal::Big::precision_from_str(&source);
            vm.new_big(crate::decimal::Big::parse(&source, prec))
        };
        if !int_only && radix == 10 {
            let source = String::from_utf8_lossy(text);
            let digits = source
                .trim_start()
                .trim_start_matches(['-', '+'])
                .trim_start();
            let body_end = digits
                .find(|c: char| !c.is_ascii_digit())
                .unwrap_or(digits.len());
            let rest = &digits[body_end..];
            let has_exponent = rest
                .strip_prefix(['e', 'E'])
                .map(|r| r.trim_start_matches(['+', '-']))
                .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()));
            if rest.starts_with('.') || has_exponent {
                return Ok(big(self));
            }
        }
        match parse_int(text, radix) {
            Ok(n) => Ok(Value::Int(n)),
            Err(_) if !int_only => Ok(big(self)),
            Err(error) => Err(error),
        }
    }

    /// Convert a value to a number, as an explicit cast does: an integer
    /// or a Decimal stays as it is, true and nil are 1 and 0, and text
    /// is parsed.
    pub(crate) fn cast_to_num(&mut self, value: Value) -> VmResult<Value> {
        match value {
            Value::Int(_) => Ok(value),
            Value::True => Ok(Value::Int(1)),
            Value::Nil => Ok(Value::Int(0)),
            _ if self.as_big(value).is_some() => Ok(value),
            _ => match self.as_str(value) {
                Some(text) => {
                    let text = text.to_vec();
                    self.parse_number(&text, 10, false)
                }
                None => Err(VmError::new(code::NO_NUM_CONV)),
            },
        }
    }

    /// Convert a value to an integer, as an explicit cast does.
    pub(crate) fn cast_to_int(&mut self, value: Value) -> VmResult<i32> {
        match value {
            Value::Int(n) => Ok(n),
            Value::True => Ok(1),
            Value::Nil => Ok(0),
            _ => {
                if let Some(big) = self.as_big(value) {
                    return Self::big_to_int(big);
                }
                match self.as_str(value) {
                    Some(text) => parse_int(&text, 10),
                    None => Err(VmError::new(code::NO_INT_CONV)),
                }
            }
        }
    }

    /// `max(...)` or `min(...)`: the extreme of the arguments, or of the
    /// elements of a single list-like argument.
    fn extreme(&mut self, argc: u32, wanted: Ordering) -> VmResult<Value> {
        if argc < 1 {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let first = self.arg(0);
        let values: Vec<Value> = match (argc, self.list_like_len(first)?) {
            (1, Some(len)) => {
                if len == 0 {
                    return Err(VmError::new(code::BAD_VAL_BIF));
                }
                let mut values = Vec::with_capacity(len);
                for index in 1..=len {
                    values.push(self.list_like_get(first, index)?);
                }
                values
            }
            _ => (0..argc as usize).map(|index| self.arg(index)).collect(),
        };
        let mut best = values[0];
        for &value in &values[1..] {
            if self.compare(value, best)? == wanted {
                best = value;
            }
        }
        Ok(best)
    }

    /// The text of a value where a string is expected, as output and
    /// `concat` convert it: `nil` is the empty string.
    pub(crate) fn cast_to_text(&mut self, value: Value) -> VmResult<std::rc::Rc<[u8]>> {
        match value {
            Value::Nil => Ok(Vec::new().into()),
            Value::SString(_) | Value::Obj(_) | Value::Int(_) | Value::True | Value::List(_) => {
                Ok(self.text_bytes(value)?)
            }
            _ => Err(VmError::new(code::NO_STR_CONV)),
        }
    }

    // ---- hexicon-io ----

    fn call_io(&mut self, index: u16, argc: u32) -> VmResult<()> {
        match index {
            // print(...): display each argument.
            0 => {
                for index in 0..argc as usize {
                    if let Some(text) = self.say_text(self.arg(index))? {
                        self.print(&text);
                    }
                }
            }
            _ => {
                if !self.bif_io(index, argc)? {
                    return Err(self.unimplemented_bif(FunctionSet::Io, index));
                }
            }
        }
        Ok(())
    }

    /// The text to display for a value, or `None` for nil, which displays
    /// nothing.
    pub(crate) fn say_text(&mut self, value: Value) -> VmResult<Option<std::rc::Rc<[u8]>>> {
        match value {
            Value::Nil => Ok(None),
            Value::Int(_) => Ok(Some(self.text_bytes(value)?)),
            Value::SString(_) | Value::Obj(_) | Value::List(_) => {
                let (_, text) = self.text_cast(value)?;
                Ok(Some(text))
            }
            _ => Err(VmError::new(code::BAD_TYPE_BIF)),
        }
    }
}

/// Format an integer in a radix from 2 to 36, with capital letters for
/// the digits past 9.
pub(crate) fn int_to_radix(value: i32, radix: u32, signed: bool) -> String {
    let (negative, mut magnitude) = if value >= 0 || !signed {
        (false, value as u32)
    } else {
        (true, value.unsigned_abs())
    };
    let mut digits = Vec::new();
    loop {
        let digit = char::from_digit(magnitude % radix, radix).unwrap_or('0');
        digits.push(digit.to_ascii_uppercase());
        magnitude /= radix;
        if magnitude == 0 {
            break;
        }
    }
    if negative {
        digits.push('-');
    }
    digits.iter().rev().collect()
}

/// Parse an integer the way `toInteger` does: optional spaces, an optional
/// sign, optional spaces, then digits up to the first character that is
/// not a digit of the radix.
fn parse_int(text: &[u8], radix: u32) -> VmResult<i32> {
    let mut chars = String::from_utf8_lossy(text)
        .chars()
        .collect::<Vec<_>>()
        .into_iter()
        .peekable();
    while chars.next_if(|c| c.is_whitespace()).is_some() {}
    let negative = match chars.peek() {
        Some('-') => {
            chars.next();
            true
        }
        Some('+') => {
            chars.next();
            false
        }
        _ => false,
    };
    while chars.next_if(|c| c.is_whitespace()).is_some() {}
    // Unsigned values are allowed to fill all 32 bits in the radixes
    // normally used for bit patterns.
    let limit: u64 = if !negative && matches!(radix, 2 | 8 | 16) {
        0xffff_ffff
    } else if negative {
        0x8000_0000
    } else {
        0x7fff_ffff
    };
    let mut acc: u64 = 0;
    for c in chars {
        let Some(digit) = c.to_digit(36).filter(|&d| d < radix) else {
            break;
        };
        acc = acc * u64::from(radix) + u64::from(digit);
        if acc > limit {
            return Err(VmError::new(code::NUM_OVERFLOW));
        }
    }
    Ok(if negative && acc <= 0x7fff_ffff {
        -(acc as i64) as i32
    } else {
        acc as u32 as i32
    })
}