neovm-core 0.0.2

Core runtime structures for NeoVM
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
use super::*;
use crate::emacs_core::string_escape;
use crate::emacs_core::{Context, format_eval_result};
use crate::test_utils::load_minimal_gnu_backquote_runtime;

fn bootstrap_eval(src: &str) -> Vec<String> {
    let mut ev = Context::new();
    load_minimal_gnu_backquote_runtime(&mut ev);
    ev.eval_str_each(src)
        .iter()
        .map(format_eval_result)
        .collect()
}

// ----- copy-alist -----

#[test]
fn copy_alist_basic() {
    crate::test_utils::init_test_tracing();
    let alist = Value::list(vec![
        Value::cons(Value::symbol("a"), Value::fixnum(1)),
        Value::cons(Value::symbol("b"), Value::fixnum(2)),
    ]);
    let result = builtin_copy_alist(vec![alist]).unwrap();
    let items = list_to_vec(&result).unwrap();
    assert_eq!(items.len(), 2);
    // Original and copy should have equal structure (`equal`).
    assert!(equal_value(&alist, &result, 0));
    // But the cons cells should not be eq (different heap objects).
    // GNU `eq` is pointer-equal, so check via eq_value not the
    // Rust PartialEq impl (which is structural `equal`).
    assert!(items[0].is_cons());
    let orig_first = &list_to_vec(&alist).unwrap()[0];
    assert!(orig_first.is_cons());
    assert!(
        !crate::emacs_core::value::eq_value(&items[0], orig_first),
        "copy-alist must produce a fresh cons cell, not eq the original"
    );
}

#[test]
fn copy_alist_empty() {
    crate::test_utils::init_test_tracing();
    let result = builtin_copy_alist(vec![Value::NIL]).unwrap();
    assert!(result.is_nil());
}

// ----- rassoc / rassq -----

#[test]
fn rassoc_found() {
    crate::test_utils::init_test_tracing();
    let alist = Value::list(vec![
        Value::cons(Value::symbol("a"), Value::fixnum(1)),
        Value::cons(Value::symbol("b"), Value::fixnum(2)),
        Value::cons(Value::symbol("c"), Value::fixnum(3)),
    ]);
    let result = builtin_rassoc(vec![Value::fixnum(2), alist]).unwrap();
    // Should return (b . 2)
    if result.is_cons() {
        let pair_car = result.cons_car();
        let pair_cdr = result.cons_cdr();
        assert!(eq_value(&pair_car, &Value::symbol("b")));
    } else {
        panic!("expected cons");
    }
}

#[test]
fn rassoc_not_found() {
    crate::test_utils::init_test_tracing();
    let alist = Value::list(vec![Value::cons(Value::symbol("a"), Value::fixnum(1))]);
    let result = builtin_rassoc(vec![Value::fixnum(99), alist]).unwrap();
    assert!(result.is_nil());
}

#[test]
fn rassq_found() {
    crate::test_utils::init_test_tracing();
    let alist = Value::list(vec![
        Value::cons(Value::symbol("x"), Value::symbol("yes")),
        Value::cons(Value::symbol("y"), Value::symbol("no")),
    ]);
    let result = builtin_rassq(vec![Value::symbol("yes"), alist]).unwrap();
    if result.is_cons() {
        let pair_car = result.cons_car();
        let pair_cdr = result.cons_cdr();
        assert!(eq_value(&pair_car, &Value::symbol("x")));
    } else {
        panic!("expected cons");
    }
}

#[test]
fn rassq_not_found() {
    crate::test_utils::init_test_tracing();
    let alist = Value::list(vec![Value::cons(Value::symbol("a"), Value::fixnum(1))]);
    let result = builtin_rassq(vec![Value::fixnum(99), alist]).unwrap();
    assert!(result.is_nil());
}

// ----- assoc-default -----

#[test]
fn assoc_default_bootstrap_matches_gnu_subr() {
    crate::test_utils::init_test_tracing();
    let results = bootstrap_eval(
        r#"
        (subrp (symbol-function 'assoc-default))
        (assoc-default "key" '(("key" . 42)))
        (assoc-default "missing" '(("key" . 42)) nil -1)
        (assoc-default 'foo '((foo . 10)) 'eq)
        (assoc-default 'foo '(foo) nil 'fallback)
        "#,
    );
    assert_eq!(results[0], "OK nil");
    assert_eq!(results[1], "OK 42");
    assert_eq!(results[2], "OK nil");
    assert_eq!(results[3], "OK 10");
    assert_eq!(results[4], "OK fallback");
}

#[test]
fn assoc_default_bootstrap_error_shapes_match_gnu_subr() {
    crate::test_utils::init_test_tracing();
    let results = bootstrap_eval(
        r#"
        (condition-case err
            (assoc-default 'foo 1)
          (wrong-type-argument (list (car err) (nth 1 err))))
        (condition-case err
            (assoc-default 'foo '((foo . 10)) 1)
          (error (car err)))
        "#,
    );
    assert_eq!(results[0], "OK (wrong-type-argument listp)");
    assert_eq!(results[1], "OK invalid-function");
}

// ----- make-list -----

#[test]
fn make_list_basic() {
    crate::test_utils::init_test_tracing();
    let result = builtin_make_list(vec![Value::fixnum(3), Value::symbol("x")]).unwrap();
    let items = list_to_vec(&result).unwrap();
    assert_eq!(items.len(), 3);
    for item in &items {
        assert!(eq_value(item, &Value::symbol("x")));
    }
}

#[test]
fn make_list_zero() {
    crate::test_utils::init_test_tracing();
    let result = builtin_make_list(vec![Value::fixnum(0), Value::fixnum(1)]).unwrap();
    assert!(result.is_nil());
}

#[test]
fn make_list_validates_wholenump_length() {
    crate::test_utils::init_test_tracing();
    let negative = builtin_make_list(vec![Value::fixnum(-1), Value::fixnum(1)]).unwrap_err();
    let float = builtin_make_list(vec![Value::make_float(3.2), Value::fixnum(1)]).unwrap_err();
    match negative {
        Flow::Signal(sig) => {
            assert_eq!(sig.symbol_name(), "wrong-type-argument");
            assert_eq!(
                sig.data,
                vec![Value::symbol("wholenump"), Value::fixnum(-1)]
            );
        }
        other => panic!("expected wrong-type-argument signal, got {other:?}"),
    }
    match float {
        Flow::Signal(sig) => {
            assert_eq!(sig.symbol_name(), "wrong-type-argument");
            assert_eq!(
                sig.data,
                vec![Value::symbol("wholenump"), Value::make_float(3.2)]
            );
        }
        other => panic!("expected wrong-type-argument signal, got {other:?}"),
    }
}

#[test]
fn string_repeat_basic() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_repeat(vec![Value::string("ab"), Value::fixnum(3)]).unwrap();
    assert_eq!(result.as_utf8_str().unwrap(), "ababab");
}

#[test]
fn string_repeat_zero() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_repeat(vec![Value::string("ab"), Value::fixnum(0)]).unwrap();
    assert_eq!(result.as_utf8_str().unwrap(), "");
}

#[test]
fn string_repeat_errors() {
    crate::test_utils::init_test_tracing();
    assert!(builtin_string_repeat(vec![]).is_err());
    assert!(builtin_string_repeat(vec![Value::string("ab")]).is_err());
    assert!(builtin_string_repeat(vec![Value::string("ab"), Value::fixnum(-1)]).is_err());
    assert!(builtin_string_repeat(vec![Value::fixnum(1), Value::fixnum(2)]).is_err());
}

// ----- safe-length -----

#[test]
fn safe_length_proper_list() {
    crate::test_utils::init_test_tracing();
    let list = Value::list(vec![Value::fixnum(1), Value::fixnum(2), Value::fixnum(3)]);
    let result = builtin_safe_length(vec![list]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(3)));
}

#[test]
fn safe_length_nil() {
    crate::test_utils::init_test_tracing();
    let result = builtin_safe_length(vec![Value::NIL]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(0)));
}

#[test]
fn safe_length_non_list() {
    crate::test_utils::init_test_tracing();
    let result = builtin_safe_length(vec![Value::fixnum(42)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(0)));
}

// ----- subst-char-in-string -----

#[test]
fn subst_char_in_string_preserves_nonunicode_character_codes() {
    crate::test_utils::init_test_tracing();
    let mut buf = [0u8; crate::emacs_core::emacs_char::MAX_MULTIBYTE_LENGTH];
    let len = crate::emacs_core::emacs_char::char_string(0x3F_FFFF, &mut buf);
    let value = Value::heap_string(crate::heap_types::LispString::from_emacs_bytes(
        buf[..len].to_vec(),
    ));
    let result = builtin_subst_char_in_string(vec![
        Value::fixnum(0x3F_FFFF),
        Value::fixnum(0x3F_FFFE),
        value,
    ])
    .unwrap();
    let ls = result
        .as_lisp_string()
        .expect("subst-char-in-string result");
    assert_eq!(
        crate::emacs_core::builtins::lisp_string_char_codes(ls),
        vec![0x3F_FFFE]
    );
}

#[test]
fn subst_char_basic() {
    crate::test_utils::init_test_tracing();
    let result = builtin_subst_char_in_string(vec![
        Value::char('.'),
        Value::char('/'),
        Value::string("a.b.c"),
    ])
    .unwrap();
    assert_eq!(result.as_utf8_str().unwrap(), "a/b/c");
}

#[test]
fn subst_char_no_match() {
    crate::test_utils::init_test_tracing();
    let result = builtin_subst_char_in_string(vec![
        Value::char('z'),
        Value::char('!'),
        Value::string("hello"),
    ])
    .unwrap();
    assert_eq!(result.as_utf8_str().unwrap(), "hello");
}

// ----- string encoding identity stubs -----

#[test]
fn string_to_multibyte_identity() {
    crate::test_utils::init_test_tracing();
    let s = Value::string("hello");
    let result = builtin_string_to_multibyte(vec![s]).unwrap();
    assert!(equal_value(&s, &result, 0));
}

#[test]
fn string_to_multibyte_converts_unibyte_high_bytes_to_raw_byte_chars() {
    crate::test_utils::init_test_tracing();
    // Create a unibyte string with byte 0xFF
    let v = Value::heap_string(crate::heap_types::LispString::from_unibyte(vec![0xFF]));
    let result = builtin_string_to_multibyte(vec![v]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(ls.is_multibyte());
    assert_eq!(ls.sbytes(), 2); // raw byte 0xFF -> 2-byte overlong
    assert_eq!(ls.schars(), 1);
    // Decode: should be 0x3FFFFF (byte8_to_char(0xFF))
    let codes: Vec<u32> = crate::emacs_core::builtins::lisp_string_char_codes(ls);
    assert_eq!(codes, vec![0x3FFFFF]);
}

#[test]
fn string_to_unibyte_ascii_storage() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_to_unibyte(vec![Value::string("world")]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(!ls.is_multibyte());
    assert_eq!(ls.sbytes(), 5);
    assert_eq!(ls.as_bytes(), b"world");
}

#[test]
fn string_to_unibyte_rejects_unicode_scalar() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_to_unibyte(vec![Value::string("é")]);
    match result {
        Err(Flow::Signal(sig)) => {
            assert_eq!(sig.symbol_name(), "error");
            assert_eq!(
                sig.data,
                vec![Value::string(
                    "Cannot convert character at index 0 to unibyte"
                )]
            );
        }
        other => panic!("expected conversion error, got {other:?}"),
    }
}

#[test]
fn string_to_unibyte_preserves_existing_unibyte_storage() {
    crate::test_utils::init_test_tracing();
    // Create a unibyte string with byte 0xFF
    let v = Value::heap_string(crate::heap_types::LispString::from_unibyte(vec![0xFF]));
    let result = builtin_string_to_unibyte(vec![v]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(!ls.is_multibyte());
    assert_eq!(ls.sbytes(), 1);
    assert_eq!(ls.as_bytes(), &[0xFF]);
}

#[test]
fn string_as_unibyte_utf8_bytes_for_unicode() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_as_unibyte(vec![Value::string("é")]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(!ls.is_multibyte());
    assert_eq!(ls.sbytes(), 2);
    assert_eq!(ls.as_bytes(), &[0xC3, 0xA9]); // UTF-8 encoding of é
}

#[test]
fn string_as_unibyte_ascii_passthrough_bytes() {
    crate::test_utils::init_test_tracing();
    let result = builtin_string_as_unibyte(vec![Value::string("test")]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(!ls.is_multibyte());
    assert_eq!(ls.sbytes(), 4);
    assert_eq!(ls.as_bytes(), b"test");
}

#[test]
fn string_as_unibyte_preserves_unibyte_storage_bytes() {
    crate::test_utils::init_test_tracing();
    // Create a unibyte string with byte 0xFF
    let v = Value::heap_string(crate::heap_types::LispString::from_unibyte(vec![0xFF]));
    let result = builtin_string_as_unibyte(vec![v]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(!ls.is_multibyte());
    assert_eq!(ls.sbytes(), 1);
    assert_eq!(ls.as_bytes(), &[0xFF]);
}

#[test]
fn string_as_multibyte_identity_for_multibyte_input() {
    crate::test_utils::init_test_tracing();
    let s = Value::string("test");
    let result = builtin_string_as_multibyte(vec![s]).unwrap();
    assert!(equal_value(&s, &result, 0));
}

#[test]
fn string_as_multibyte_converts_unibyte_high_bytes_to_raw_byte_chars() {
    crate::test_utils::init_test_tracing();
    // Create a unibyte string with byte 0xFF
    let v = Value::heap_string(crate::heap_types::LispString::from_unibyte(vec![0xFF]));
    let result = builtin_string_as_multibyte(vec![v]).unwrap();
    let ls = result.as_lisp_string().unwrap();
    assert!(ls.is_multibyte());
    assert_eq!(ls.sbytes(), 2); // raw byte 0xFF -> 2-byte overlong
    let codes: Vec<u32> = crate::emacs_core::builtins::lisp_string_char_codes(ls);
    assert_eq!(codes, vec![0x3FFFFF]);
}

// ----- char encoding conversions -----

#[test]
fn unibyte_char_to_multibyte_ascii_identity() {
    crate::test_utils::init_test_tracing();
    let result = builtin_unibyte_char_to_multibyte(vec![Value::fixnum(65)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(65)));
}

#[test]
fn unibyte_char_to_multibyte_high_byte_maps_to_raw_range() {
    crate::test_utils::init_test_tracing();
    let result = builtin_unibyte_char_to_multibyte(vec![Value::fixnum(255)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(0x3FFFFF)));
}

#[test]
fn unibyte_char_to_multibyte_rejects_non_unibyte_code() {
    crate::test_utils::init_test_tracing();
    let result = builtin_unibyte_char_to_multibyte(vec![Value::fixnum(256)]);
    match result {
        Err(Flow::Signal(sig)) => {
            assert_eq!(sig.symbol_name(), "error");
            assert_eq!(
                sig.data,
                vec![Value::string("Not a unibyte character: 256")]
            );
        }
        other => panic!("expected conversion error, got {other:?}"),
    }
}

#[test]
fn multibyte_char_to_unibyte_ascii_passthrough() {
    crate::test_utils::init_test_tracing();
    let result = builtin_multibyte_char_to_unibyte(vec![Value::fixnum(65)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(65)));
}

#[test]
fn multibyte_char_to_unibyte_raw_range_maps_to_byte() {
    crate::test_utils::init_test_tracing();
    let result = builtin_multibyte_char_to_unibyte(vec![Value::fixnum(0x3FFFFF)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(255)));
}

#[test]
fn multibyte_char_to_unibyte_returns_minus_one_for_non_unibyte_unicode() {
    crate::test_utils::init_test_tracing();
    let result = builtin_multibyte_char_to_unibyte(vec![Value::fixnum(256)]).unwrap();
    assert!(eq_value(&result, &Value::fixnum(-1)));
}

// ----- locale-info -----

#[test]
fn locale_info_codeset_returns_utf8() {
    crate::test_utils::init_test_tracing();
    let result = builtin_locale_info(vec![Value::symbol("codeset")]).unwrap();
    assert_eq!(result.as_utf8_str(), Some("UTF-8"));
}

#[test]
fn locale_info_days_months_and_paper_return_oracle_shapes() {
    crate::test_utils::init_test_tracing();
    let days = builtin_locale_info(vec![Value::symbol("days")]).unwrap();
    let days_vec = match days.kind() {
        ValueKind::Veclike(VecLikeType::Vector) => days.as_vector_data().unwrap().clone(),
        other => panic!("days should be a vector, got {other:?}"),
    };
    assert_eq!(days_vec.len(), 7);
    assert_eq!(days_vec[0], Value::string("Sunday"));
    assert_eq!(days_vec[6], Value::string("Saturday"));

    let months = builtin_locale_info(vec![Value::symbol("months")]).unwrap();
    let months_vec = match months.kind() {
        ValueKind::Veclike(VecLikeType::Vector) => months.as_vector_data().unwrap().clone(),
        other => panic!("months should be a vector, got {other:?}"),
    };
    assert_eq!(months_vec.len(), 12);
    assert_eq!(months_vec[0], Value::string("January"));
    assert_eq!(months_vec[11], Value::string("December"));

    let paper = builtin_locale_info(vec![Value::symbol("paper")]).unwrap();
    assert_eq!(
        paper,
        Value::list(vec![Value::fixnum(210), Value::fixnum(297)])
    );
}

#[test]
fn locale_info_unknown_or_non_symbol_items_return_nil() {
    crate::test_utils::init_test_tracing();
    let result = builtin_locale_info(vec![Value::symbol("time")]).unwrap();
    assert!(result.is_nil());
    let result = builtin_locale_info(vec![Value::string("codeset")]).unwrap();
    assert!(result.is_nil());
    let result = builtin_locale_info(vec![Value::fixnum(1)]).unwrap();
    assert!(result.is_nil());
}

#[test]
fn display_line_numbers_update_width_is_noop() {
    crate::test_utils::init_test_tracing();
    let result = builtin_display_line_numbers_update_width(vec![]).unwrap();
    assert_eq!(result, Value::NIL);
}

#[test]
fn display_line_numbers_update_width_arity() {
    crate::test_utils::init_test_tracing();
    assert!(builtin_display_line_numbers_update_width(vec![Value::NIL]).is_err());
}

// ----- eval-dependent builtins (need Context) -----

#[test]
fn recursion_depth_zero() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();
    let result = builtin_recursion_depth(&mut eval, vec![]).unwrap();
    // At top level, depth is 0
    assert!(eq_value(&result, &Value::fixnum(0)));
}

// Regression tests for `backtrace-frame--internal` — the real
// introspection primitive that walks the specpdl. GNU's
// `backtrace_frame_apply` (eval.c:3984) reads each SPECPDL_BACKTRACE
// entry and invokes the callback with (evald func args flags).
// Neomacs's `runtime_backtrace_frames_from_base` + `apply_backtrace_callback`
// do the same for `SpecBinding::Backtrace`. These tests exercise the
// live path including a frame pushed by `push_backtrace_frame` (which
// fires on every bytecode and interpreter call, see vm.rs:3443 and
// eval.rs:8858).

#[test]
fn backtrace_frame_internal_surfaces_live_frame() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();

    // Push a backtrace frame ourselves so the walker has something to
    // surface without needing a full compile/call round-trip.
    eval.push_backtrace_frame(
        Value::symbol("my-func"),
        &[Value::fixnum(1), Value::fixnum(2)],
    );

    // Call backtrace-frame--internal with a callback that just
    // returns its four args as a list.  base=nil walks from the top
    // of the stack; nframes=0 grabs the newest frame.
    let callback = eval
        .eval_str("(lambda (evald func args flags) (list evald func args flags))")
        .expect("build callback");
    let result = super::builtin_backtrace_frame_internal(
        &mut eval,
        vec![callback, Value::fixnum(0), Value::NIL],
    )
    .expect("walk");

    let items = list_to_vec(&result).expect("four-element list");
    assert_eq!(items.len(), 4);
    assert_eq!(items[0], Value::T, "evald should be t");
    assert_eq!(items[1], Value::symbol("my-func"), "func symbol");
    assert_eq!(
        items[2],
        Value::list(vec![Value::fixnum(1), Value::fixnum(2)]),
        "args list"
    );
    assert!(items[3].is_nil(), "no flags on this frame");
}

/// Regression for GNU `nargs == UNEVALLED` parity (eval.c:2585, 3993).
/// `eval_sub_cons` must push an UNEVALLED backtrace frame around every
/// public special-form dispatch (`if`, `while`, `let`, etc.). The frame
/// exists only during dispatch; we observe it from inside the body via
/// a Rust probe subr that snapshots the live specpdl.
#[test]
fn eval_sub_cons_pushes_unevalled_frame_for_special_forms() {
    use std::cell::RefCell;

    thread_local! {
        static PROBE: RefCell<Vec<(Value, bool)>> = const { RefCell::new(Vec::new()) };
    }

    fn probe(eval: &mut super::super::eval::Context) -> EvalResult {
        let snap: Vec<(Value, bool)> = eval
            .specpdl
            .iter()
            .filter_map(|e| match e {
                super::super::eval::SpecBinding::Backtrace { function, args, .. } => {
                    Some((*function, args.is_unevalled()))
                }
                _ => None,
            })
            .collect();
        PROBE.with(|p| *p.borrow_mut() = snap);
        Ok(Value::NIL)
    }

    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();
    eval.defsubr_0("__unevalled_probe__", probe);

    PROBE.with(|p| p.borrow_mut().clear());
    eval.eval_str("(if t (__unevalled_probe__) nil)")
        .expect("eval if-body");
    let snap = PROBE.with(|p| p.borrow().clone());
    assert!(
        snap.iter().any(|(f, u)| *f == Value::symbol("if") && *u),
        "expected an UNEVALLED `if' frame while body runs, got {:?}",
        snap
    );
}

/// Regression for the Phase 2 architectural change: GNU `eval_sub`
/// pushes an UNEVALLED backtrace frame for EVERY cons-form call
/// (eval.c:2585), not just special forms. During arg evaluation of
/// `(foo (probe))`, walkers must see the outer `foo` frame on the
/// stack.
#[test]
fn eval_sub_cons_pushes_outer_unevalled_during_arg_eval() {
    use std::cell::RefCell;

    thread_local! {
        static ARG_PROBE: RefCell<Vec<(Value, bool)>> = const { RefCell::new(Vec::new()) };
    }

    fn probe(eval: &mut super::super::eval::Context) -> EvalResult {
        let snap: Vec<(Value, bool)> = eval
            .specpdl
            .iter()
            .filter_map(|e| match e {
                super::super::eval::SpecBinding::Backtrace { function, args, .. } => {
                    Some((*function, args.is_unevalled()))
                }
                _ => None,
            })
            .collect();
        ARG_PROBE.with(|p| *p.borrow_mut() = snap);
        Ok(Value::NIL)
    }

    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();
    eval.defsubr_0("__arg_eval_probe__", probe);

    // Wrap in a user lambda so there's an "outer" non-builtin frame we
    // can look for. `defun` is an elisp macro not available in a bare
    // Context; `fset` with a literal lambda is primitive and works.
    eval.eval_str("(fset 'my-outer-fn (lambda (x) x))")
        .expect("fset outer");

    ARG_PROBE.with(|p| p.borrow_mut().clear());
    eval.eval_str("(my-outer-fn (__arg_eval_probe__))")
        .expect("eval outer call");
    let snap = ARG_PROBE.with(|p| p.borrow().clone());
    assert!(
        snap.iter()
            .any(|(f, u)| *f == Value::symbol("my-outer-fn") && *u),
        "expected UNEVALLED my-outer-fn frame visible during arg eval, \
         got {:?}",
        snap
    );
}

/// Unit test for `set_backtrace_args_evalled` — mirrors GNU
/// `set_backtrace_args` (eval.c:144-156) called at eval.c:2638, 2660,
/// 3299 to promote a UNEVALLED frame to EVALD in place.
#[test]
fn set_backtrace_args_evalled_mutates_in_place() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();

    let bt_count = eval.specpdl.len();
    let original_args = Value::list(vec![
        Value::symbol("x"),
        Value::list(vec![Value::symbol("+"), Value::fixnum(1), Value::fixnum(2)]),
    ]);
    eval.push_unevalled_backtrace_frame(Value::symbol("my-func"), original_args);

    // Promote to EVALD with evaluated values.
    let evaluated = [Value::fixnum(42), Value::fixnum(3)];
    eval.set_backtrace_args_evalled(bt_count, &evaluated);

    // Inspect slot — should now be EVALD with the evaluated values.
    match eval.specpdl.last().expect("frame present") {
        super::super::eval::SpecBinding::Backtrace { function, args, .. } => {
            assert!(!args.is_unevalled(), "flag cleared after promotion");
            assert_eq!(*function, Value::symbol("my-func"), "function preserved");
            let got: Vec<Value> = args.as_slice().iter().copied().collect();
            assert_eq!(got, evaluated, "args replaced with evaluated values");
        }
        other => panic!("expected Backtrace, got {other:?}"),
    }
}

/// Regression for `backtrace-frame--internal` UNEVALLED dispatch. Set
/// up an artificial UNEVALLED frame via `push_unevalled_backtrace_frame`
/// and assert the callback receives `(nil FUNC FORMS nil)`.
#[test]
fn backtrace_frame_internal_surfaces_unevalled_frame() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();

    let original_args = Value::list(vec![
        Value::symbol("x"),
        Value::list(vec![Value::symbol("+"), Value::fixnum(1), Value::fixnum(2)]),
    ]);
    eval.push_unevalled_backtrace_frame(Value::symbol("if"), original_args);

    let callback = eval
        .eval_str("(lambda (evald func args flags) (list evald func args flags))")
        .expect("build callback");
    let result = super::builtin_backtrace_frame_internal(
        &mut eval,
        vec![callback, Value::fixnum(0), Value::NIL],
    )
    .expect("walk");

    let items = list_to_vec(&result).expect("four-element list");
    assert_eq!(items.len(), 4);
    assert!(items[0].is_nil(), "UNEVALLED → evald=nil");
    assert_eq!(items[1], Value::symbol("if"));
    // args should be the cons list of un-evaluated forms, not a wrapping list.
    assert_eq!(
        items[2], original_args,
        "forms list passed through verbatim"
    );
    assert!(items[3].is_nil());
}

#[test]
fn handler_bind_sees_signaling_eval_frames_before_unwind() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();

    let result = eval.eval_str(
        r#"(let (seen-eval seen-progn)
                 (condition-case nil
                     (handler-bind-1
                       (lambda () (eval '(progn hb-missing-symbol) t))
                       '(error)
                       (lambda (_err)
                         (mapbacktrace
                          (lambda (evald func args _flags)
                            (if (and evald
                                     (eq func 'eval)
                                     (equal args '((progn hb-missing-symbol) t)))
                                (setq seen-eval t))
                            (if (and (null evald)
                                     (eq func 'progn)
                                     (equal args '(hb-missing-symbol)))
                                (setq seen-progn t))))))
                   (error nil))
                 (list seen-eval seen-progn))"#,
    );

    assert!(
        result.is_ok(),
        "handler-bind probe failed: {}",
        format_eval_result(&result)
    );
    let result = result.unwrap();

    assert_eq!(
        super::super::print::print_value(&result),
        "(t t)",
        "GNU keeps eval and inner UNEVALLED form frames visible while handler-bind runs"
    );
}

#[test]
fn handler_bind_sees_eval_symbol_frame_before_feval_unwind() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();

    let result = eval.eval_str(
        r#"(let (seen-eval)
                 (condition-case nil
                     (handler-bind-1
                       (lambda () (eval 'hb-missing-symbol t))
                       '(error)
                       (lambda (_err)
                         (mapbacktrace
                          (lambda (evald func args _flags)
                            (if (and evald
                                     (eq func 'eval)
                                     (equal args '(hb-missing-symbol t)))
                                (setq seen-eval t))))))
                   (error nil))
                 seen-eval)"#,
    );

    assert!(
        result.is_ok(),
        "handler-bind eval-symbol probe failed: {}",
        format_eval_result(&result)
    );
    let result = result.unwrap();

    assert_eq!(
        super::super::print::print_value(&result),
        "t",
        "GNU keeps the active eval frame visible while a bare-symbol eval signal is handled"
    );
}

#[test]
fn backtrace_helper_stubs_shape_and_errors() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();
    let thread = super::super::threads::builtin_current_thread(&mut eval, vec![]).unwrap();
    let frames = builtin_backtrace_frames_from_thread(&mut eval, vec![thread]).unwrap();
    assert!(frames.is_list());
    assert!(matches!(
        builtin_backtrace_frames_from_thread(&mut eval, vec![Value::NIL]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-type-argument"
                && sig.data == vec![Value::symbol("threadp"), Value::NIL]
    ));

    assert!(matches!(
        builtin_backtrace_locals(&mut eval, vec![Value::NIL]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-type-argument"
                && sig.data == vec![Value::symbol("wholenump"), Value::NIL]
    ));
    assert!(matches!(
        builtin_backtrace_locals(&mut eval, vec![Value::fixnum(0)]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-type-argument"
                && sig.data == vec![Value::symbol("wholenump"), Value::fixnum(-1)]
    ));
    assert!(matches!(
        builtin_backtrace_eval(&mut eval, vec![Value::fixnum(0), Value::NIL]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-type-argument"
                && sig.data == vec![Value::symbol("wholenump"), Value::NIL]
    ));

    eval.push_backtrace_frame(Value::symbol("outer-frame"), &[]);
    eval.push_backtrace_frame(Value::symbol("base-frame"), &[]);
    assert_eq!(
        builtin_backtrace_locals(
            &mut eval,
            vec![Value::fixnum(1), Value::symbol("base-frame")]
        )
        .expect("base function should be accepted"),
        Value::NIL
    );
    assert_eq!(
        builtin_backtrace_debug(
            &mut eval,
            vec![Value::fixnum(1), Value::T, Value::symbol("base-frame")]
        )
        .expect("backtrace-debug should accept a non-numeric flag and function base"),
        Value::T
    );
    assert_eq!(
        builtin_backtrace_eval(
            &mut eval,
            vec![
                Value::fixnum(42),
                Value::fixnum(1),
                Value::symbol("base-frame")
            ]
        )
        .expect("backtrace-eval should accept expression, frame number, and function base"),
        Value::fixnum(42)
    );
}

#[test]
fn backtrace_helper_stubs_arity_checks() {
    crate::test_utils::init_test_tracing();
    let mut eval = super::super::eval::Context::new();
    assert!(matches!(
        builtin_backtrace_debug(&mut eval, vec![]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-number-of-arguments"
                && sig.data == vec![Value::symbol("backtrace-debug"), Value::fixnum(0)]
    ));
    assert!(matches!(
        builtin_backtrace_debug(&mut eval, vec![Value::fixnum(0)]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-number-of-arguments"
                && sig.data == vec![Value::symbol("backtrace-debug"), Value::fixnum(1)]
    ));
    assert!(matches!(
        builtin_backtrace_frame_internal(&mut eval, vec![]),
        Err(Flow::Signal(sig))
            if sig.symbol_name() == "wrong-number-of-arguments"
                && sig.data == vec![Value::symbol("backtrace-frame--internal"), Value::fixnum(0)]
    ));
}

#[test]
fn backtrace_frame_internal_tracks_runtime_funcall_interactively_marker() {
    crate::test_utils::init_test_tracing();
    let mut ev = super::super::eval::Context::new();
    let results = ev.eval_str_each(
        r#"
        (progn
          (fset 'neovm--misc-bt-target
                (lambda ()
                  (interactive)
                  (let (frame)
                    (backtrace-frame--internal
                     (lambda (evald func args flags)
                       (setq frame (list evald func args flags)))
                     1
                     'neovm--misc-bt-target)
                    (nth 1 frame))))
          (unwind-protect
              (list
               (funcall-interactively 'neovm--misc-bt-target)
               (call-interactively 'neovm--misc-bt-target))
            (fmakunbound 'neovm--misc-bt-target)))
        "#,
    );
    assert_eq!(
        results.iter().map(format_eval_result).collect::<Vec<_>>(),
        vec!["OK (funcall-interactively funcall-interactively)"]
    );
}

// ----- special form: save-current-buffer -----

#[test]
fn sf_save_current_buffer_restores() {
    crate::test_utils::init_test_tracing();
    let mut ev = crate::test_utils::runtime_startup_context();
    // Create a buffer and make it current
    let buf_id = ev.buffers.create_buffer("*test*");
    ev.buffers.set_current(buf_id);

    // save-current-buffer with body that just returns 42
    let result = ev.eval_str("(save-current-buffer 42)").unwrap();
    assert!(eq_value(&result, &Value::fixnum(42)));
    // Current buffer should still be *test*
    assert_eq!(ev.buffers.current_buffer().unwrap().id, buf_id);
}

// ----- with-syntax-table (Elisp macro in GNU subr.el:6394) -----

#[test]
fn sf_with_syntax_table_evaluates_body() {
    crate::test_utils::init_test_tracing();
    let mut ev = Context::new();
    load_minimal_gnu_backquote_runtime(&mut ev);
    let result = ev
        .eval_str("(with-syntax-table (make-syntax-table) 30)")
        .expect("eval");
    assert!(eq_value(&result, &Value::fixnum(30)));
}

#[test]
fn sf_with_syntax_table_restores_original_table_on_success() {
    crate::test_utils::init_test_tracing();
    let mut ev = Context::new();
    load_minimal_gnu_backquote_runtime(&mut ev);
    let original = crate::emacs_core::syntax::builtin_syntax_table(&mut ev, vec![]).unwrap();
    ev.eval_str("(with-syntax-table (make-syntax-table) 1)")
        .expect("eval");
    let restored = crate::emacs_core::syntax::builtin_syntax_table(&mut ev, vec![]).unwrap();
    assert!(eq_value(&restored, &original));
}

#[test]
fn with_syntax_table_restores_original_table_on_error() {
    crate::test_utils::init_test_tracing();
    let mut ev = Context::new();
    load_minimal_gnu_backquote_runtime(&mut ev);
    let original = crate::emacs_core::syntax::builtin_syntax_table(&mut ev, vec![]).unwrap();
    let _ = ev.eval_str("(ignore-errors (with-syntax-table (make-syntax-table) missing-var))");
    let restored = crate::emacs_core::syntax::builtin_syntax_table(&mut ev, vec![]).unwrap();
    assert!(eq_value(&restored, &original));
}