keleusma 0.2.2

Total Functional Stream Processor with definitive WCET and WCMU verification, targeting no_std + alloc embedded scripting
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Compile-level and run-level smoke tests for the rogue
//! example's Keleusma scripts. These tests exercise the lex /
//! parse / compile pipeline and a stubbed-out native surface so
//! script errors surface in `cargo test` rather than at SDL3
//! startup. The tests are guarded by the `text` feature because
//! the host scripts may use string literals or f-strings.

#![cfg(all(feature = "compile", feature = "verify"))]

use std::sync::{Arc, Mutex};

use keleusma::bytecode::Value;
use keleusma::compiler::compile;
use keleusma::lexer::tokenize;
use keleusma::parser::parse;
use keleusma::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmError, VmState};
use keleusma::{Arena, Module};

/// Materialize the components of an all-`Word` tuple returned by a
/// rogue script, handling both the flat and boxed bodies (B28 P2).
///
/// The rogue AI, combat, and item scripts return tuples whose elements
/// are all `Word`, so each component reads back as an `i64`. A flat
/// body carries no element count, so the arity is derived from the
/// byte length at the bundled runtime's eight-byte word width; this is
/// the typed read the host performs now that a scalar tuple is pure
/// bytes. Panics if the value is not such a tuple.
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn word_tuple(arena: &keleusma::Arena, v: &Value) -> Vec<i64> {
    use keleusma::bytecode::TupleBody;
    use keleusma::value_layout::ScalarKind;
    match v {
        Value::Tuple(TupleBody::Boxed(elems)) => elems
            .iter()
            .map(|e| match e {
                Value::Int(n) => *n,
                other => panic!("non-int tuple element: {:?}", other),
            })
            .collect(),
        Value::Tuple(TupleBody::Flat(fc)) => {
            // Read-before-resume (B28 P3 item 5 C3): a yielded/returned tuple
            // is arena-resident, so resolve its body against the arena rather
            // than assuming an inline body. The host reads it before the next
            // resume, which would RESET the arena and make it stale.
            let bytes = fc
                .resolve(arena)
                .expect("flat tuple body resolves (read-before-resume)");
            (0..bytes.len() / 8)
                .map(|i| {
                    match Value::read_scalar_le(bytes, i * 8, ScalarKind::Int, 8, 8)
                        .expect("flat tuple element decodes")
                    {
                        Value::Int(n) => n,
                        other => panic!("non-int flat tuple element: {:?}", other),
                    }
                })
                .collect()
        }
        other => panic!("expected a Word tuple, got {:?}", other),
    }
}

const SRC_BESTIARY: &str = include_str!("../examples/scripts/rogue/rogue_bestiary.kel");
const SRC_GEAR: &str = include_str!("../examples/scripts/rogue/rogue_gear.kel");
const SRC_DUNGEN: &str = include_str!("../examples/scripts/rogue/rogue_dungen.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_IDLE: &str = include_str!("../examples/scripts/rogue/rogue_ai_idle.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_CHASER: &str = include_str!("../examples/scripts/rogue/rogue_ai_chaser.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_WANDER: &str = include_str!("../examples/scripts/rogue/rogue_ai_wander.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_SLEEPER: &str = include_str!("../examples/scripts/rogue/rogue_ai_sleeper.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_RANGED: &str = include_str!("../examples/scripts/rogue/rogue_ai_ranged.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_FAST: &str = include_str!("../examples/scripts/rogue/rogue_ai_fast.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_SMART: &str = include_str!("../examples/scripts/rogue/rogue_ai_smart.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_AI_BOSS: &str = include_str!("../examples/scripts/rogue/rogue_ai_boss.kel");
const SRC_AI_TRACKER: &str = include_str!("../examples/scripts/rogue/rogue_ai_tracker.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_ITEM_POTION: &str = include_str!("../examples/scripts/rogue/rogue_item_potion.kel");
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
const SRC_ITEM_SCROLL: &str = include_str!("../examples/scripts/rogue/rogue_item_scroll.kel");
const SRC_GAME: &str = include_str!("../examples/scripts/rogue/rogue_game.kel");
const SRC_PLAYER_AI: &str = include_str!("../examples/scripts/rogue/rogue_player_ai.kel");
const SRC_COMBAT: &str = include_str!("../examples/scripts/rogue/rogue_combat.kel");

fn build(src: &str) -> Module {
    let tokens = tokenize(src).expect("lex error");
    let program = parse(&tokens).expect("parse error");
    compile(&program).expect("compile error")
}

/// Stub-natives runner. Each native called by dungen returns a
/// deterministic value so the script's control flow exercises
/// every code path without panicking on missing natives.
struct DungenStub {
    rng_state: u32,
    map_set_count: usize,
    spawn_monster_count: usize,
    spawn_item_count: usize,
    place_player: Option<(i32, i32)>,
    place_stairs: Option<(i32, i32)>,
    place_exit: Option<(i32, i32)>,
    clear_count: usize,
}

impl DungenStub {
    fn new() -> Self {
        Self {
            rng_state: 0x9E37_79B9,
            map_set_count: 0,
            spawn_monster_count: 0,
            spawn_item_count: 0,
            place_player: None,
            place_stairs: None,
            place_exit: None,
            clear_count: 0,
        }
    }

    fn rng_next(&mut self) -> u32 {
        let mut s = self.rng_state;
        s ^= s << 13;
        s ^= s >> 17;
        s ^= s << 5;
        self.rng_state = s;
        s
    }
}

fn register_dungen_stub(vm: &mut Vm, state: &Arc<Mutex<DungenStub>>) {
    let s = state.clone();
    vm.register_native_closure(
        "host::rng_range",
        Box::new(move |args: &[Value]| -> Result<Value, VmError> {
            let lo = match args[0] {
                Value::Int(n) => n,
                _ => 0,
            };
            let hi = match args[1] {
                Value::Int(n) => n,
                _ => 1,
            };
            if hi <= lo {
                return Err(VmError::NativeError(format!(
                    "rng_range: hi {} not greater than lo {}",
                    hi, lo
                )));
            }
            let mut st = s.lock().unwrap();
            let r = st.rng_next() % (hi - lo) as u32;
            Ok(Value::Int(lo + r as i64))
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::map_set",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            s.lock().unwrap().map_set_count += 1;
            Ok(Value::Unit)
        }),
    );

    vm.register_native_closure(
        "host::map_get",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(1)) }),
    );

    vm.register_native_closure(
        "host::map_w",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(80)) }),
    );

    vm.register_native_closure(
        "host::map_h",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(24)) }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::clear_floor",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            s.lock().unwrap().clear_count += 1;
            Ok(Value::Unit)
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::place_player",
        Box::new(move |args: &[Value]| -> Result<Value, VmError> {
            let (x, y) = match (&args[0], &args[1]) {
                (Value::Int(x), Value::Int(y)) => (*x as i32, *y as i32),
                _ => (0, 0),
            };
            s.lock().unwrap().place_player = Some((x, y));
            Ok(Value::Unit)
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::place_stairs",
        Box::new(move |args: &[Value]| -> Result<Value, VmError> {
            let (x, y) = match (&args[0], &args[1]) {
                (Value::Int(x), Value::Int(y)) => (*x as i32, *y as i32),
                _ => (0, 0),
            };
            s.lock().unwrap().place_stairs = Some((x, y));
            Ok(Value::Unit)
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::place_exit",
        Box::new(move |args: &[Value]| -> Result<Value, VmError> {
            let (x, y) = match (&args[0], &args[1]) {
                (Value::Int(x), Value::Int(y)) => (*x as i32, *y as i32),
                _ => (0, 0),
            };
            s.lock().unwrap().place_exit = Some((x, y));
            Ok(Value::Unit)
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::spawn_monster",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            s.lock().unwrap().spawn_monster_count += 1;
            Ok(Value::Unit)
        }),
    );

    let s = state.clone();
    vm.register_native_closure(
        "host::spawn_item",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            s.lock().unwrap().spawn_item_count += 1;
            Ok(Value::Unit)
        }),
    );

    vm.register_native_closure(
        "host::floor",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(1)) }),
    );
}

#[test]
fn dungen_compiles() {
    let _ = build(SRC_DUNGEN);
}

#[test]
fn game_tick_compiles() {
    let _ = build(SRC_GAME);
}

#[test]
fn player_ai_compiles() {
    let _ = build(SRC_PLAYER_AI);
}

#[test]
fn ai_tracker_compiles() {
    let _ = build(SRC_AI_TRACKER);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_tracker_chases_when_seen() {
    let module = build(SRC_AI_TRACKER);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let input = Value::tuple(vec![
        Value::Int(5),
        Value::Int(5),
        Value::Int(10),
        Value::Int(10),
        Value::Int(1),
    ]);
    let result = vm.call_with_shared(&mut shared, &[input]).expect("vm call");
    match result {
        VmState::Yielded(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(&arena, v);
            assert_eq!(c.len(), 3, "expected Yielded triple");
            assert_eq!(c[0], 1);
            assert_eq!((c[1], c[2]), (6, 6));
        }
        other => panic!("expected Yielded triple, got {:?}", other),
    }
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_tracker_pursues_last_known_when_unseen() {
    let module = build(SRC_AI_TRACKER);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    // First turn: player visible at (10, 10). Tracker chases and
    // records the last known position.
    let visible_input = Value::tuple(vec![
        Value::Int(5),
        Value::Int(5),
        Value::Int(10),
        Value::Int(10),
        Value::Int(1),
    ]);
    vm.call_with_shared(&mut shared, &[visible_input])
        .expect("vm call");
    // Loop main wraps; the host walks past Reset to the next
    // Yielded with a fresh input. Second turn: player not
    // visible. Tracker should move toward the stored last
    // position.
    let unseen_input = Value::tuple(vec![
        Value::Int(6),
        Value::Int(6),
        Value::Int(0),
        Value::Int(0),
        Value::Int(0),
    ]);
    let mut state = vm
        .resume_with_shared(&mut shared, unseen_input.clone())
        .expect("vm resume");
    for _ in 0..16 {
        match state {
            VmState::Yielded(ref v @ Value::Tuple(_)) => {
                let c = word_tuple(&arena, v);
                assert_eq!(c.len(), 3, "non-int tuple");
                assert_eq!(c[0], 1, "should chase last known");
                assert_eq!((c[1], c[2]), (7, 7), "step toward (10, 10)");
                return;
            }
            VmState::Reset => {
                state = vm
                    .resume_with_shared(&mut shared, unseen_input.clone())
                    .expect("vm resume");
            }
            other => panic!("expected Yielded or Reset, got {:?}", other),
        }
    }
    panic!("tracker did not yield within sixteen resumes");
}

#[test]
fn combat_compiles() {
    let _ = build(SRC_COMBAT);
}

#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn run_player_ai(mx: i64, my: i64, cmd: i64) -> (i64, i64, i64) {
    let module = build(SRC_PLAYER_AI);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let result = vm
        .call(&[Value::Int(mx), Value::Int(my), Value::Int(cmd)])
        .expect("vm call");
    match result {
        VmState::Finished(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(&arena, v);
            assert_eq!(c.len(), 3, "player ai returned non-int tuple components");
            (c[0], c[1], c[2])
        }
        other => panic!("expected Finished triple, got {:?}", other),
    }
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_wait_returns_action_zero() {
    let (action, tx, ty) = run_player_ai(5, 5, 0);
    assert_eq!(action, 0);
    assert_eq!((tx, ty), (5, 5));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_move_north_returns_action_one() {
    let (action, tx, ty) = run_player_ai(5, 5, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (5, 4));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_move_diagonal_southeast() {
    let (action, tx, ty) = run_player_ai(5, 5, 8);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 6));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_descend_returns_action_three() {
    let (action, _tx, _ty) = run_player_ai(5, 5, 9);
    assert_eq!(action, 3);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_quaff_returns_action_four() {
    let (action, _tx, _ty) = run_player_ai(5, 5, 10);
    assert_eq!(action, 4);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn player_ai_read_returns_action_five() {
    let (action, _tx, _ty) = run_player_ai(5, 5, 11);
    assert_eq!(action, 5);
}

#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn run_combat(skill: i64, dmg: i64, evasion: i64, armor: i64, roll: i64) -> (i64, i64) {
    let module = build(SRC_COMBAT);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let result = vm
        .call(&[
            Value::Int(skill),
            Value::Int(dmg),
            Value::Int(evasion),
            Value::Int(armor),
            Value::Int(roll),
        ])
        .expect("vm call");
    match result {
        VmState::Finished(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(&arena, v);
            assert_eq!(c.len(), 2, "combat returned non-int tuple");
            (c[0], c[1])
        }
        other => panic!("expected Finished pair, got {:?}", other),
    }
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn combat_fumble_always_misses() {
    let (hit, dmg) = run_combat(20, 10, 0, 0, 1);
    assert_eq!((hit, dmg), (0, 0));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn combat_critical_always_hits() {
    let (hit, dmg) = run_combat(0, 5, 50, 0, 20);
    assert_eq!(hit, 2);
    assert_eq!(dmg, 10);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn combat_ordinary_hit_subtracts_armor() {
    let (hit, dmg) = run_combat(10, 8, 0, 3, 12);
    assert_eq!(hit, 1);
    assert_eq!(dmg, 5);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn combat_miss_returns_zero_damage() {
    let (hit, dmg) = run_combat(0, 8, 5, 0, 10);
    assert_eq!((hit, dmg), (0, 0));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn combat_damage_floored_at_one() {
    let (hit, dmg) = run_combat(10, 2, 0, 8, 12);
    assert_eq!(hit, 1);
    assert_eq!(dmg, 1);
}

#[test]
fn game_tick_runs_with_stubbed_natives() {
    // Drive the game-tick loop main with stubbed natives. The
    // four natives return deterministic values so the script's
    // control flow is exercised end-to-end without the full
    // host. The test verifies that the script reaches a yielded
    // outcome on the first turn.
    use std::cell::RefCell;
    let module = build(SRC_GAME);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];

    let monster_calls = std::rc::Rc::new(RefCell::new(0_i64));
    let book_calls = std::rc::Rc::new(RefCell::new(0_i64));

    vm.register_native_closure(
        "host::run_player_turn",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(0)) }),
    );
    vm.register_native_closure(
        "host::monster_count",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> { Ok(Value::Int(3)) }),
    );
    let mc = monster_calls.clone();
    vm.register_native_closure(
        "host::run_monster_ai",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            *mc.borrow_mut() += 1;
            Ok(Value::Unit)
        }),
    );
    let bc = book_calls.clone();
    vm.register_native_closure(
        "host::tick_book_keeping",
        Box::new(move |_args: &[Value]| -> Result<Value, VmError> {
            *bc.borrow_mut() += 1;
            Ok(Value::Int(0))
        }),
    );

    let result = vm
        .call_with_shared(&mut shared, &[Value::Int(0)])
        .expect("vm call");
    match result {
        VmState::Yielded(Value::Int(outcome)) => {
            assert_eq!(outcome, 0, "first turn should yield continue");
        }
        other => panic!("expected Yielded(Int), got {:?}", other),
    }
    assert_eq!(
        *monster_calls.borrow(),
        3,
        "run_monster_ai should fire once per declared monster"
    );
    assert_eq!(
        *book_calls.borrow(),
        1,
        "tick_book_keeping should fire once per turn"
    );
}

#[test]
fn bestiary_compiles() {
    let _ = build(SRC_BESTIARY);
}

#[test]
fn bestiary_negative_one_returns_last_entry() {
    let module = build(SRC_BESTIARY);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    vm.call_with_shared(&mut shared, &[Value::Int(-1)])
        .expect("call -1");
    let last_id = match vm.get_shared(&shared, 0).expect("get_shared id") {
        Value::Int(n) => n,
        other => panic!("expected Int, got {:?}", other),
    };
    assert_eq!(last_id, 99, "the bestiary ships with one hundred entries");
}

#[test]
fn bestiary_returns_name_as_text() {
    let module = build(SRC_BESTIARY);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let state = vm
        .call_with_shared(&mut shared, &[Value::Int(0)])
        .expect("call 0");
    match state {
        // A returned string constant is now a rodata `KStr` rather than an
        // owned `StaticStr` (B28 P3 item 4); resolve its content through the
        // arena while the VM is alive.
        VmState::Finished(v) => {
            let s = v.as_str_with_arena(&arena).expect("resolve").unwrap_or("");
            assert_eq!(s, "Sewer Rat");
        }
        other => panic!("expected Finished, got {:?}", other),
    }
}

#[test]
fn bestiary_corpse_data_derived_from_shape() {
    // Entry 0 is the Sewer Rat (shape Tiny=0). Tiny corpse:
    // drop_chance=50, satiation=8, hp_delta=0.
    let module = build(SRC_BESTIARY);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    vm.call_with_shared(&mut shared, &[Value::Int(0)])
        .expect("call 0");
    let read = |slot: usize| -> i64 {
        match vm.get_shared(&shared, slot).expect("get_shared") {
            Value::Int(n) => n,
            _ => panic!(),
        }
    };
    assert_eq!(read(16), 50, "Tiny corpse drop chance");
    assert_eq!(read(17), 8, "Tiny corpse satiation");
    assert_eq!(read(18), 0, "Tiny corpse hp delta");
}

#[test]
fn bestiary_entry_zero_is_sewer_rat_stats() {
    let module = build(SRC_BESTIARY);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    vm.call_with_shared(&mut shared, &[Value::Int(0)])
        .expect("call 0");
    // Sewer Rat: shape Tiny=0, max_hp=3, ai Chaser=2,
    // first_floor=1, score=1. See rogue_bestiary.kel entry 0.
    let read = |slot: usize| -> i64 {
        match vm.get_shared(&shared, slot).expect("get_shared") {
            Value::Int(n) => n,
            _ => panic!(),
        }
    };
    assert_eq!(read(0), 0, "id");
    assert_eq!(read(1), 0, "shape Tiny");
    assert_eq!(read(8), 3, "max_hp");
    assert_eq!(read(13), 2, "ai Chaser");
    assert_eq!(read(14), 1, "first_floor");
    assert_eq!(read(15), 1, "score");
}

#[test]
fn gear_compiles() {
    let _ = build(SRC_GEAR);
}

#[test]
fn gear_weapon_zero_is_fists_damage_two() {
    let module = build(SRC_GEAR);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    // table 0 = weapons, tier 0 = fists, damage 2.
    vm.call_with_shared(&mut shared, &[Value::Int(0), Value::Int(0)])
        .expect("call");
    let value = match vm.get_shared(&shared, 1).expect("get_shared") {
        Value::Int(n) => n,
        _ => panic!(),
    };
    assert_eq!(value, 2, "fists damage");
}

#[test]
fn gear_armor_negative_one_is_last_guard_defense_forty() {
    let module = build(SRC_GEAR);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    // table 1 = armors, tier -1 = last guard, defense 40.
    vm.call_with_shared(&mut shared, &[Value::Int(1), Value::Int(-1)])
        .expect("call");
    let read = |slot: usize| -> i64 {
        match vm.get_shared(&shared, slot).expect("get_shared") {
            Value::Int(n) => n,
            _ => panic!(),
        }
    };
    assert_eq!(read(0), 19, "last guard id");
    assert_eq!(read(1), 40, "last guard defense");
}

#[test]
fn dungen_runs_floor_1() {
    let module = build(SRC_DUNGEN);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let stub = Arc::new(Mutex::new(DungenStub::new()));
    register_dungen_stub(&mut vm, &stub);
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let result = vm
        .call_with_shared(&mut shared, &[Value::Int(1)])
        .expect("vm call");
    match result {
        VmState::Finished(_) => {}
        other => panic!("expected Finished, got {:?}", other),
    }
    let st = stub.lock().unwrap();
    assert_eq!(st.clear_count, 1, "clear_floor should be called once");
    assert!(st.place_player.is_some(), "player should be placed");
    assert!(
        st.place_stairs.is_some(),
        "stairs should be placed on floor 1"
    );
    assert!(st.place_exit.is_none(), "exit should not appear on floor 1");
    assert!(
        st.spawn_monster_count > 0,
        "at least one monster should spawn"
    );
    assert!(st.spawn_item_count > 0, "at least one item should spawn");
    assert!(st.map_set_count > 100, "many map cells should be written");
}

// -- Artificial-intelligence script tests ---------------------------

#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn call_ai(src: &str, mx: i64, my: i64, px: i64, py: i64, sees: i64) -> (i64, i64, i64) {
    let module = build(src);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    // Provide rng_range for archetypes that import it. Returns
    // a deterministic value chosen to exercise the random path.
    vm.register_native_closure(
        "host::rng_range",
        Box::new(move |args: &[Value]| -> Result<Value, VmError> {
            let lo = match args[0] {
                Value::Int(n) => n,
                _ => 0,
            };
            Ok(Value::Int(lo))
        }),
    );
    let result = vm
        .call(&[
            Value::Int(mx),
            Value::Int(my),
            Value::Int(px),
            Value::Int(py),
            Value::Int(sees),
        ])
        .expect("ai vm call");
    match result {
        VmState::Finished(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(&arena, v);
            assert_eq!(c.len(), 3, "ai returned non-int tuple components");
            (c[0], c[1], c[2])
        }
        other => panic!("expected Finished tuple, got {:?}", other),
    }
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_idle_waits_in_place() {
    let (action, tx, ty) = call_ai(SRC_AI_IDLE, 5, 5, 10, 10, 1);
    assert_eq!(action, 0);
    assert_eq!((tx, ty), (5, 5));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_chaser_steps_toward_player_when_seen() {
    let (action, tx, ty) = call_ai(SRC_AI_CHASER, 5, 5, 10, 10, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 6));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_chaser_waits_when_unseen() {
    let (action, _tx, _ty) = call_ai(SRC_AI_CHASER, 5, 5, 10, 10, 0);
    assert_eq!(action, 0);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_wander_chases_when_seen() {
    let (action, tx, ty) = call_ai(SRC_AI_WANDER, 5, 5, 10, 10, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 6));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_sleeper_chases_when_seen() {
    let (action, tx, ty) = call_ai(SRC_AI_SLEEPER, 5, 5, 10, 10, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 6));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_sleeper_waits_when_unseen() {
    let (action, _tx, _ty) = call_ai(SRC_AI_SLEEPER, 5, 5, 10, 10, 0);
    assert_eq!(action, 0);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_ranged_attacks_when_distant() {
    let (action, tx, ty) = call_ai(SRC_AI_RANGED, 5, 5, 10, 10, 1);
    assert_eq!(action, 2);
    assert_eq!((tx, ty), (10, 10));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_ranged_retreats_when_adjacent() {
    let (action, tx, ty) = call_ai(SRC_AI_RANGED, 5, 5, 6, 5, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (4, 5));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_fast_steps_toward_player() {
    let (action, tx, ty) = call_ai(SRC_AI_FAST, 5, 5, 10, 10, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 6));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_smart_dominant_axis_step() {
    // Player far east, same row. Smart picks the dominant axis.
    let (action, tx, ty) = call_ai(SRC_AI_SMART, 5, 5, 20, 5, 1);
    assert_eq!(action, 1);
    assert_eq!((tx, ty), (6, 5));
}

/// Helper for the boss archetype which uses `loop main` with a
/// five-tuple input. Returns the yielded action triple for the
/// supplied turn inputs.
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn call_boss_first(
    mx: i64,
    my: i64,
    px: i64,
    py: i64,
    sees: i64,
) -> (i64, i64, i64, Vm<'static, 'static>, Vec<u8>) {
    let module = build(SRC_AI_BOSS);
    // The arena and vm need to escape this helper for callers
    // that want to resume. Return them by value.
    let arena: Arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    // Safety. We leak the arena reference because the borrow
    // checker cannot prove the vm's reference outlives the
    // function frame. The test process is short-lived so the
    // leak is irrelevant.
    let arena_ref: &'static Arena = Box::leak(Box::new(arena));
    let mut vm: Vm<'static, 'static> = Vm::new(module, arena_ref).expect("vm new");
    // The boss shared buffer travels with the returned vm so a caller can
    // resume against the same persistent shared state (B28 item 2).
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let input = Value::tuple(vec![
        Value::Int(mx),
        Value::Int(my),
        Value::Int(px),
        Value::Int(py),
        Value::Int(sees),
    ]);
    let result = vm.call_with_shared(&mut shared, &[input]).expect("vm call");
    let triple = match result {
        VmState::Yielded(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(arena_ref, v);
            assert_eq!(c.len(), 3, "boss yielded non-int tuple components");
            (c[0], c[1], c[2])
        }
        other => panic!("expected Yielded triple, got {:?}", other),
    };
    (triple.0, triple.1, triple.2, vm, shared)
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_boss_first_turn_attacks_at_range_when_distant() {
    // Phase zero is a ranged attack when the player is visible.
    let (action, tx, ty, _vm, _shared) = call_boss_first(5, 5, 12, 12, 1);
    assert_eq!(action, 2);
    assert_eq!((tx, ty), (12, 12));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_boss_first_turn_waits_when_unseen() {
    let (action, _tx, _ty, _vm, _shared) = call_boss_first(5, 5, 12, 12, 0);
    assert_eq!(action, 0);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn ai_boss_second_turn_chases() {
    // The boss alternates ranged and chase. The second visible
    // turn lands on phase one which is a chase step. `loop main`
    // emits Reset at the body's wrap point so the helper loops
    // past Reset until the next Yielded.
    let (_a1, _x1, _y1, mut vm, mut shared) = call_boss_first(5, 5, 12, 12, 1);
    let input = Value::tuple(vec![
        Value::Int(5),
        Value::Int(5),
        Value::Int(12),
        Value::Int(12),
        Value::Int(1),
    ]);
    let mut state = vm
        .resume_with_shared(&mut shared, input.clone())
        .expect("vm resume");
    for _ in 0..16 {
        match state {
            VmState::Yielded(ref v @ Value::Tuple(_)) => {
                let c = word_tuple(vm.arena(), v);
                assert_eq!(c.len(), 3, "non-int tuple components");
                assert_eq!(c[0], 1, "second turn should chase");
                assert_eq!((c[1], c[2]), (6, 6), "should step diagonally toward player");
                return;
            }
            VmState::Reset => {
                state = vm
                    .resume_with_shared(&mut shared, input.clone())
                    .expect("vm resume after reset");
            }
            other => panic!("expected Yielded or Reset, got {:?}", other),
        }
    }
    panic!("boss vm did not yield within sixteen resume cycles");
}

// -- Item-effect script tests --------------------------------------

#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn call_5_tuple(src: &str, args: &[i64]) -> (i64, i64, i64, i64, i64) {
    let module = build(src);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let values: Vec<Value> = args.iter().map(|n| Value::Int(*n)).collect();
    let result = vm.call(&values).expect("vm call");
    match result {
        VmState::Finished(ref v @ Value::Tuple(_)) => {
            let c = word_tuple(&arena, v);
            assert_eq!(c.len(), 5, "expected 5-tuple");
            (c[0], c[1], c[2], c[3], c[4])
        }
        other => panic!("expected 5-tuple, got {:?}", other),
    }
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_healing_heals_five() {
    let (hp, _, _, _, _) = call_5_tuple(SRC_ITEM_POTION, &[0, 5, 12]);
    assert_eq!(hp, 5);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_greater_healing_heals_fifteen() {
    let (hp, _, _, _, _) = call_5_tuple(SRC_ITEM_POTION, &[1, 5, 30]);
    assert_eq!(hp, 15);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_restoration_returns_status_11() {
    let (_, _, _, status, _) = call_5_tuple(SRC_ITEM_POTION, &[2, 5, 30]);
    assert_eq!(status, 11);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_poison_damages_three() {
    let (hp, _, _, _, _) = call_5_tuple(SRC_ITEM_POTION, &[3, 5, 30]);
    assert_eq!(hp, -3);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_strength_raises_max_hp() {
    let (hp, max_hp, _, _, _) = call_5_tuple(SRC_ITEM_POTION, &[5, 5, 12]);
    assert_eq!((hp, max_hp), (2, 2));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn potion_skill_raises_skill() {
    let (_, _, skill, _, _) = call_5_tuple(SRC_ITEM_POTION, &[6, 5, 12]);
    assert_eq!(skill, 1);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn scroll_identify_returns_status_3() {
    let (_, _, _, status, _) = call_5_tuple(SRC_ITEM_SCROLL, &[0]);
    assert_eq!(status, 3);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn scroll_magic_mapping_returns_status_1() {
    let (_, _, _, status, _) = call_5_tuple(SRC_ITEM_SCROLL, &[1]);
    assert_eq!(status, 1);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn scroll_teleport_returns_status_2() {
    let (_, _, _, status, _) = call_5_tuple(SRC_ITEM_SCROLL, &[2]);
    assert_eq!(status, 2);
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn scroll_enchant_weapon_returns_status_4_arg_1() {
    let (_, _, _, status, arg) = call_5_tuple(SRC_ITEM_SCROLL, &[3]);
    assert_eq!((status, arg), (4, 1));
}

#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn scroll_enchant_armor_returns_status_5_arg_1() {
    let (_, _, _, status, arg) = call_5_tuple(SRC_ITEM_SCROLL, &[4]);
    assert_eq!((status, arg), (5, 1));
}

// Gated against narrow-word runtimes because the dungeon-generator
// at depth 100 computes intermediate values (e.g., a width seeded
// from `floor * scaling`) that wrap on a narrow Word and trip a
// runtime range check (`rng_range: hi -108 not greater than lo 100`).
// The smaller-depth test (`dungen_runs_floor_1`) stays within range
// on every supported Word and continues to run on narrowed builds.
#[test]
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
fn dungen_runs_floor_100_places_exit() {
    let module = build(SRC_DUNGEN);
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).expect("vm new");
    let stub = Arc::new(Mutex::new(DungenStub::new()));
    register_dungen_stub(&mut vm, &stub);
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    vm.call_with_shared(&mut shared, &[Value::Int(100)])
        .expect("vm call");
    let st = stub.lock().unwrap();
    assert!(st.place_exit.is_some(), "floor 100 should place the exit");
    assert!(
        st.place_stairs.is_none(),
        "floor 100 should not place stairs down"
    );
}