neovm-core 0.0.1

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
//! Error and signal types for the evaluator.

use std::error::Error;
use std::fmt::{self, Display, Formatter};

use super::intern::{SymId, intern, resolve_sym};
use super::print::PrintOptions;
use super::value::{Value, ValueKind, VecLikeType};
use crate::emacs_core::eval::ResumeTarget;
use crate::window::WindowId;

/// Public-facing evaluation error.
#[derive(Clone, Debug)]
pub enum EvalError {
    Signal {
        symbol: SymId,
        data: Vec<Value>,
        raw_data: Option<Value>,
    },
    UncaughtThrow {
        tag: Value,
        value: Value,
    },
}

impl Display for EvalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Signal {
                symbol,
                data,
                raw_data,
            } => write!(
                f,
                "signal {} {}",
                resolve_sym(*symbol),
                format_signal_payload(raw_data.as_ref(), data),
            ),
            Self::UncaughtThrow { tag, value } => write!(
                f,
                "uncaught throw tag={} value={}",
                super::print::print_value(tag),
                super::print::print_value(value),
            ),
        }
    }
}

impl Error for EvalError {}

/// Internal non-local control flow.
#[derive(Clone, Debug)]
pub enum Flow {
    Signal(SignalData),
    Throw { tag: Value, value: Value },
}

#[derive(Clone, Debug)]
pub struct SignalData {
    pub symbol: SymId,
    pub data: Vec<Value>,
    /// Original cdr payload when a signal uses non-list data.
    pub raw_data: Option<Value>,
    pub(crate) suppress_signal_hook: bool,
    pub(crate) selected_resume: Option<ResumeTarget>,
    pub(crate) search_complete: bool,
}

impl SignalData {
    /// Resolve the signal symbol name via the interner.
    pub fn symbol_name(&self) -> &str {
        resolve_sym(self.symbol)
    }
}

pub(crate) type EvalResult = Result<Value, Flow>;

/// Create a signal flow.
pub(crate) fn signal(symbol: &str, data: Vec<Value>) -> Flow {
    signal_internal(symbol, data, None, false)
}

/// Create a signal flow without running `signal-hook-function`.
pub(crate) fn signal_suppressed(symbol: &str, data: Vec<Value>) -> Flow {
    signal_internal(symbol, data, None, true)
}

fn signal_internal(
    symbol: &str,
    data: Vec<Value>,
    raw_data: Option<Value>,
    suppress_signal_hook: bool,
) -> Flow {
    // Log void-variable signals at debug level for investigation
    if symbol == "void-variable" || symbol == "void-function" {
        let data_strs: Vec<String> = data.iter().map(|v| super::print::print_value(v)).collect();
        tracing::debug!("signal {symbol} ({})", data_strs.join(" "));
    }
    Flow::Signal(SignalData {
        symbol: intern(symbol),
        data,
        raw_data,
        suppress_signal_hook,
        selected_resume: None,
        search_complete: false,
    })
}

/// Create a signal where DATA is used as the raw cdr payload.
///
/// This preserves dotted signal data shapes such as `(foo . 1)`.
pub(crate) fn signal_with_data(symbol: &str, data: Value) -> Flow {
    signal_with_data_internal(symbol, data, false)
}

/// Create a signal with raw cdr payload without running `signal-hook-function`.
pub(crate) fn signal_with_data_suppressed(symbol: &str, data: Value) -> Flow {
    signal_with_data_internal(symbol, data, true)
}

fn signal_with_data_internal(symbol: &str, data: Value, suppress_signal_hook: bool) -> Flow {
    let normalized = super::value::list_to_vec(&data).unwrap_or_else(|| vec![data]);
    signal_internal(symbol, normalized, Some(data), suppress_signal_hook)
}

/// Convert internal flow to public EvalError.
pub fn map_flow(flow: Flow) -> EvalError {
    match flow {
        Flow::Signal(sig) => EvalError::Signal {
            symbol: sig.symbol,
            data: sig.data,
            raw_data: sig.raw_data,
        },
        Flow::Throw { tag, value } => EvalError::UncaughtThrow { tag, value },
    }
}

/// Check if a condition-case pattern matches a signal symbol.
pub(crate) fn signal_matches(pattern: &super::expr::Expr, symbol: &str) -> bool {
    use super::expr::Expr;
    match pattern {
        Expr::Symbol(id) => {
            let name = resolve_sym(*id);
            name == symbol || name == "error" || name == "t"
        }
        Expr::List(items) => items.iter().any(|item| signal_matches(item, symbol)),
        _ => false,
    }
}

/// Build the binding value for condition-case variable: (symbol . data)
pub(crate) fn make_signal_binding_value(sig: &SignalData) -> Value {
    if let Some(raw) = &sig.raw_data {
        return Value::cons(Value::symbol(sig.symbol), *raw);
    }
    let mut values = Vec::with_capacity(sig.data.len() + 1);
    values.push(Value::symbol(sig.symbol));
    values.extend(sig.data.clone());
    Value::list(values)
}

/// Reconstruct a signal flow from a condition-case/thread error binding form.
pub(crate) fn signal_from_binding_value(value: Value) -> Option<Flow> {
    if !value.is_cons() {
        return None;
    };
    let pair_car = value.cons_car();
    let pair_cdr = value.cons_cdr();
    let symbol = pair_car;
    let tail = pair_cdr;
    let symbol_name = symbol.as_symbol_name()?;
    if tail.is_nil() {
        return Some(signal(symbol_name, vec![]));
    }
    if let Some(items) = super::value::list_to_vec(&tail) {
        return Some(signal(symbol_name, items));
    }
    Some(signal_with_data(symbol_name, tail))
}

/// Format an eval result for the compat test harness (TSV output).
pub fn format_eval_result(result: &Result<Value, EvalError>) -> String {
    match result {
        Ok(value) => format!("OK {}", super::print::print_value(value)),
        Err(EvalError::Signal {
            symbol,
            data,
            raw_data,
        }) => {
            let payload = format_signal_payload(raw_data.as_ref(), data);
            format!("ERR ({} {})", resolve_sym(*symbol), payload)
        }
        Err(EvalError::UncaughtThrow { tag, value }) => {
            format!(
                "ERR (no-catch ({} {}))",
                super::print::print_value(tag),
                super::print::print_value(value),
            )
        }
    }
}

fn format_signal_payload(raw_data: Option<&Value>, data: &[Value]) -> String {
    if let Some(raw) = raw_data {
        return super::print::print_value(raw);
    }
    if data.is_empty() {
        "nil".to_string()
    } else {
        super::print::print_value(&Value::list(data.to_vec()))
    }
}

fn format_opaque_handle_in_state(
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
) -> Option<String> {
    if let Some(handle) = super::terminal::pure::print_terminal_handle(value) {
        return Some(handle);
    }
    if super::marker::is_marker(value) {
        if let Some(marker) = value.as_marker_data() {
            let mut out = String::from("#<marker ");
            if marker.insertion_type {
                out.push_str("(moves after insertion) ");
            }
            if let Some(buffer_id) = marker.buffer
                && let Some(buffer) = buffers.get(buffer_id)
                && let Some(pos) = marker.position
            {
                out.push_str(&format!("at {pos} in {}", buffer.name));
            } else {
                out.push_str("in no buffer");
            }
            out.push('>');
            return Some(out);
        }
    }
    if let Some(overlay) = value.as_overlay_data() {
        if let Some(buffer_id) = overlay.buffer
            && let Some(buffer) = buffers.get(buffer_id)
        {
            return Some(format!(
                "#<overlay from {} to {} in {}>",
                buffer.text.byte_to_char(overlay.start) + 1,
                buffer.text.byte_to_char(overlay.end) + 1,
                buffer.name
            ));
        }
        return Some("#<overlay in no buffer>".to_string());
    }
    if let Some(id) = value.as_window_id() {
        return Some(format_window_handle_in_state(buffers, frames, id));
    }
    if let Some(id) = threads.thread_id_from_handle(value) {
        return Some(format!("#<thread {id}>"));
    }
    if let Some(id) = threads.mutex_id_from_handle(value) {
        return Some(format!("#<mutex {id}>"));
    }
    if let Some(id) = threads.condition_variable_id_from_handle(value) {
        return Some(format!("#<condvar {id}>"));
    }
    if let Some(buf_id) = value.as_buffer_id() {
        if let Some(buf) = buffers.get(buf_id) {
            return Some(format!("#<buffer {}>", buf.name));
        }
        if buffers.dead_buffer_last_name(buf_id).is_some() {
            return Some("#<killed buffer>".to_string());
        }
    }
    None
}

fn format_window_handle_in_state(
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    id: u64,
) -> String {
    let window_id = WindowId(id);
    if let Some(frame_id) = frames.find_window_frame_id(window_id) {
        if let Some(frame) = frames.get(frame_id) {
            if let Some(window) = frame.find_window(window_id) {
                if let Some(buffer_id) = window.buffer_id() {
                    if let Some(buffer) = buffers.get(buffer_id) {
                        return format!("#<window {id} on {}>", buffer.name);
                    }
                }
                return format!("#<window {id} on {}>", frame.name);
            }
        }
    }
    format!("#<window {id}>")
}

/// Build print options from the obarray.
/// With specbind, dynamic let-bindings are written directly to the obarray,
/// so this correctly handles (let ((print-escape-newlines t)) (format "%S" ...)).
pub(crate) fn print_options_from_state(obarray: &super::symbol::Obarray) -> PrintOptions {
    let print_gensym = obarray
        .symbol_value("print-gensym")
        .is_some_and(|v| v.is_truthy());
    let print_circle = obarray
        .symbol_value("print-circle")
        .is_some_and(|v| v.is_truthy());
    let print_escape_newlines = obarray
        .symbol_value("print-escape-newlines")
        .is_some_and(|v| v.is_truthy());
    let print_level = obarray
        .symbol_value("print-level")
        .and_then(|v| v.as_fixnum())
        .filter(|&n| n >= 0);
    let print_length = obarray
        .symbol_value("print-length")
        .and_then(|v| v.as_fixnum())
        .filter(|&n| n >= 0);
    let print_escape_nonascii = obarray
        .symbol_value("print-escape-nonascii")
        .is_some_and(|v| v.is_truthy());
    let print_escape_multibyte = obarray
        .symbol_value("print-escape-multibyte")
        .is_some_and(|v| v.is_truthy());
    let print_escape_control_characters = obarray
        .symbol_value("print-escape-control-characters")
        .is_some_and(|v| v.is_truthy());
    let mut opts = PrintOptions::new(print_gensym, print_circle, print_level, print_length);
    opts.print_escape_newlines = print_escape_newlines;
    opts.print_escape_nonascii = print_escape_nonascii;
    opts.print_escape_multibyte = print_escape_multibyte;
    opts.print_escape_control_characters = print_escape_control_characters;
    opts
}

pub(crate) fn print_value_in_state(
    ctx: &crate::emacs_core::eval::Context,
    value: &Value,
) -> String {
    format_value_in_state(
        &ctx.obarray,
        &ctx.buffers,
        &ctx.frames,
        &ctx.threads,
        value,
        print_options_from_state(&ctx.obarray),
    )
}

fn format_value_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> String {
    if let Some(handle) = format_opaque_handle_in_state(buffers, frames, threads, value) {
        return handle;
    }
    // Use the stateful printer when print-circle, print-level, or print-length
    // are active. This ensures correct handling of shared structure, depth
    // limiting, and length limiting throughout the entire value tree.
    if options.print_circle || options.print_level.is_some() || options.print_length.is_some() {
        return super::print::print_value_stateful(value, options);
    }
    match value.kind() {
        ValueKind::Cons | ValueKind::Veclike(VecLikeType::Vector) => {
            format_value_in_state_slow(obarray, buffers, frames, threads, value, options)
        }
        _ => super::print::print_value_with_options(value, options),
    }
}

fn format_value_in_state_slow(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> String {
    match value.kind() {
        ValueKind::Cons => {
            if let Some(shorthand) =
                format_list_shorthand_in_state(obarray, buffers, frames, threads, value, options)
            {
                return shorthand;
            }
            let mut out = String::from("(");
            format_cons_in_state(obarray, buffers, frames, threads, value, &mut out, options);
            out.push(')');
            out
        }
        ValueKind::Veclike(VecLikeType::Vector) => {
            let mut out = String::from("[");
            let items = value.as_vector_data().unwrap().clone();
            for (idx, item) in items.iter().enumerate() {
                if idx > 0 {
                    out.push(' ');
                }
                out.push_str(&format_value_in_state(
                    obarray, buffers, frames, threads, item, options,
                ));
            }
            out.push(']');
            out
        }
        _ => super::print::print_value_with_options(value, options),
    }
}

fn format_list_shorthand_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> Option<String> {
    let items = super::value::list_to_vec(value)?;
    if items.len() != 2 {
        return None;
    }

    let head = match items[0].kind() {
        ValueKind::Symbol(id) => resolve_sym(id),
        _ => return None,
    };

    if head == "make-hash-table-from-literal" {
        let payload = quote_payload(&items[1])?;
        return Some(format!(
            "#s{}",
            format_value_in_state(obarray, buffers, frames, threads, &payload, options)
        ));
    }

    let (prefix, quoted, nested_options) = match head {
        "quote" => Some(("'", &items[1], options)),
        "function" => Some(("#'", &items[1], options)),
        "`" => Some(("`", &items[1], options.enter_backquote())),
        "," => {
            options
                .allow_unquote_shorthand()
                .then_some((",", &items[1], options.exit_backquote()))
        }
        ",@" => {
            options
                .allow_unquote_shorthand()
                .then_some((",@", &items[1], options.exit_backquote()))
        }
        _ => None,
    }?;

    Some(format!(
        "{prefix}{}",
        format_value_in_state(obarray, buffers, frames, threads, quoted, nested_options)
    ))
}

fn format_cons_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    out: &mut String,
    options: PrintOptions,
) {
    let mut cursor = *value;
    let mut first = true;
    loop {
        match cursor.kind() {
            ValueKind::Cons => {
                if !first {
                    out.push(' ');
                }
                let pair_car = cursor.cons_car();
                let pair_cdr = cursor.cons_cdr();
                out.push_str(&format_value_in_state(
                    obarray, buffers, frames, threads, &pair_car, options,
                ));
                cursor = pair_cdr;
                first = false;
            }
            ValueKind::Nil => return,
            _ => {
                if !first {
                    out.push_str(" . ");
                }
                out.push_str(&format_value_in_state(
                    obarray, buffers, frames, threads, &cursor, options,
                ));
                return;
            }
        }
    }
}

pub(crate) fn print_value_bytes_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
) -> Vec<u8> {
    if let Some(handle) = format_opaque_handle_in_state(buffers, frames, threads, value) {
        return handle.into_bytes();
    }
    format_value_bytes_in_state_with_options(
        obarray,
        buffers,
        frames,
        threads,
        value,
        print_options_from_state(obarray),
    )
}

fn format_value_bytes_in_state_with_options(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> Vec<u8> {
    if let Some(handle) = format_opaque_handle_in_state(buffers, frames, threads, value) {
        return handle.into_bytes();
    }
    // Use the stateful printer when print-circle, print-level, or print-length
    // are active, then convert the result to bytes.
    if options.print_circle || options.print_level.is_some() || options.print_length.is_some() {
        return super::print::print_value_stateful(value, options).into_bytes();
    }
    match value.kind() {
        ValueKind::Cons => {
            format_cons_bytes_in_state(obarray, buffers, frames, threads, value, options)
        }
        ValueKind::Veclike(VecLikeType::Vector) => {
            format_vector_bytes_in_state(obarray, buffers, frames, threads, value, options)
        }
        _ => super::print::print_value_bytes_with_options(value, options),
    }
}

fn format_cons_bytes_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> Vec<u8> {
    if let Some(shorthand) =
        format_list_shorthand_bytes_in_state(obarray, buffers, frames, threads, value, options)
    {
        return shorthand;
    }
    let mut out = Vec::new();
    out.push(b'(');
    append_cons_bytes_in_state(obarray, buffers, frames, threads, value, &mut out, options);
    out.push(b')');
    out
}

fn format_vector_bytes_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> Vec<u8> {
    if super::chartable::bool_vector_length(value).is_some()
        || super::chartable::char_table_external_slots(value).is_some()
    {
        return super::print::print_value_bytes_with_options(value, options);
    }
    let mut out = Vec::new();
    out.push(b'[');
    let Some(values) = value.as_vector_data() else {
        out.push(b']');
        return out;
    };
    for (idx, item) in values.iter().enumerate() {
        if idx > 0 {
            out.push(b' ');
        }
        out.extend(format_value_bytes_in_state_with_options(
            obarray, buffers, frames, threads, item, options,
        ));
    }
    out.push(b']');
    out
}

fn format_list_shorthand_bytes_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    options: PrintOptions,
) -> Option<Vec<u8>> {
    let items = super::value::list_to_vec(value)?;
    if items.len() != 2 {
        return None;
    }

    let head = match items[0].kind() {
        ValueKind::Symbol(id) => resolve_sym(id),
        _ => return None,
    };

    if head == "make-hash-table-from-literal" {
        let payload = quote_payload(&items[1])?;
        let mut out = Vec::new();
        out.extend_from_slice(b"#s");
        out.extend(format_value_bytes_in_state_with_options(
            obarray, buffers, frames, threads, &payload, options,
        ));
        return Some(out);
    }

    let (prefix, quoted, nested_options) = match head {
        "quote" => Some((b"'" as &[u8], &items[1], options)),
        "function" => Some((b"#'" as &[u8], &items[1], options)),
        "`" => Some((b"`" as &[u8], &items[1], options.enter_backquote())),
        "," => options.allow_unquote_shorthand().then_some((
            b"," as &[u8],
            &items[1],
            options.exit_backquote(),
        )),
        ",@" => options.allow_unquote_shorthand().then_some((
            b",@" as &[u8],
            &items[1],
            options.exit_backquote(),
        )),
        _ => None,
    }?;

    let mut out = Vec::new();
    out.extend_from_slice(prefix);
    out.extend(format_value_bytes_in_state_with_options(
        obarray,
        buffers,
        frames,
        threads,
        quoted,
        nested_options,
    ));
    Some(out)
}

fn quote_payload(value: &Value) -> Option<Value> {
    let items = super::value::list_to_vec(value)?;
    if items.len() != 2 {
        return None;
    }
    match items[0].kind() {
        ValueKind::Symbol(id) if resolve_sym(id) == "quote" => Some(items[1]),
        _ => None,
    }
}

fn append_cons_bytes_in_state(
    obarray: &super::symbol::Obarray,
    buffers: &crate::buffer::BufferManager,
    frames: &crate::window::FrameManager,
    threads: &super::threads::ThreadManager,
    value: &Value,
    out: &mut Vec<u8>,
    options: PrintOptions,
) {
    let mut cursor = *value;
    let mut first = true;
    loop {
        match cursor.kind() {
            ValueKind::Cons => {
                if !first {
                    out.push(b' ');
                }
                let pair_car = cursor.cons_car();
                let pair_cdr = cursor.cons_cdr();
                out.extend(format_value_bytes_in_state_with_options(
                    obarray, buffers, frames, threads, &pair_car, options,
                ));
                cursor = pair_cdr;
                first = false;
            }
            ValueKind::Nil => return,
            _ => {
                if !first {
                    out.extend_from_slice(b" . ");
                }
                out.extend(format_value_bytes_in_state_with_options(
                    obarray, buffers, frames, threads, &cursor, options,
                ));
                return;
            }
        }
    }
}

/// Render a value with evaluator-context-aware opaque handle formatting.
pub fn print_value_with_eval(eval: &super::eval::Context, value: &Value) -> String {
    print_value_in_state(eval, value)
}

/// Render a value as bytes with evaluator-context-aware opaque handle formatting.
pub fn print_value_bytes_with_eval(eval: &super::eval::Context, value: &Value) -> Vec<u8> {
    print_value_bytes_in_state(
        &eval.obarray,
        &eval.buffers,
        &eval.frames,
        &eval.threads,
        value,
    )
}

fn print_data_payload_with_eval(eval: &super::eval::Context, data: &[Value]) -> String {
    if data.is_empty() {
        "nil".to_string()
    } else {
        let parts = data
            .iter()
            .map(|v| print_value_with_eval(eval, v))
            .collect::<Vec<_>>();
        format!("({})", parts.join(" "))
    }
}

fn print_signal_payload_with_eval(
    eval: &super::eval::Context,
    raw_data: Option<&Value>,
    data: &[Value],
) -> String {
    if let Some(raw) = raw_data {
        return print_value_with_eval(eval, raw);
    }
    print_data_payload_with_eval(eval, data)
}

fn append_print_value_bytes_with_eval(
    eval: &super::eval::Context,
    value: &Value,
    out: &mut Vec<u8>,
) {
    out.extend_from_slice(&print_value_bytes_with_eval(eval, value));
}

/// Format an eval result for harnesses that have evaluator context and need
/// opaque handle rendering for thread/mutex/condvar/terminal values.
pub fn format_eval_result_with_eval(
    eval: &super::eval::Context,
    result: &Result<Value, EvalError>,
) -> String {
    match result {
        Ok(value) => format!("OK {}", print_value_with_eval(eval, value)),
        Err(EvalError::Signal {
            symbol,
            data,
            raw_data,
        }) => {
            let payload = print_signal_payload_with_eval(eval, raw_data.as_ref(), data);
            format!("ERR ({} {})", resolve_sym(*symbol), payload)
        }
        Err(EvalError::UncaughtThrow { tag, value }) => {
            format!(
                "ERR (no-catch ({} {}))",
                print_value_with_eval(eval, tag),
                print_value_with_eval(eval, value),
            )
        }
    }
}

fn append_signal_payload_bytes_with_eval(
    eval: &super::eval::Context,
    raw_data: Option<&Value>,
    data: &[Value],
    out: &mut Vec<u8>,
) {
    if let Some(raw) = raw_data {
        append_print_value_bytes_with_eval(eval, raw, out);
    } else if data.is_empty() {
        out.extend_from_slice(b"nil");
    } else {
        out.push(b'(');
        for (idx, item) in data.iter().enumerate() {
            if idx > 0 {
                out.push(b' ');
            }
            append_print_value_bytes_with_eval(eval, item, out);
        }
        out.push(b')');
    }
}

/// Byte-preserving variant of `format_eval_result_with_eval`.
///
/// This preserves non-UTF-8 byte payloads in printed string literals used by
/// vm-compat corpus checks while still applying evaluator-aware opaque-handle
/// rendering for thread/mutex/condvar/terminal values.
pub fn format_eval_result_bytes_with_eval(
    eval: &super::eval::Context,
    result: &Result<Value, EvalError>,
) -> Vec<u8> {
    let mut out = Vec::new();
    match result {
        Ok(value) => {
            out.extend_from_slice(b"OK ");
            append_print_value_bytes_with_eval(eval, value, &mut out);
        }
        Err(EvalError::Signal {
            symbol,
            data,
            raw_data,
        }) => {
            out.extend_from_slice(b"ERR (");
            out.extend_from_slice(resolve_sym(*symbol).as_bytes());
            out.push(b' ');
            append_signal_payload_bytes_with_eval(eval, raw_data.as_ref(), data, &mut out);
            out.push(b')');
        }
        Err(EvalError::UncaughtThrow { tag, value }) => {
            out.extend_from_slice(b"ERR (no-catch (");
            append_print_value_bytes_with_eval(eval, tag, &mut out);
            out.push(b' ');
            append_print_value_bytes_with_eval(eval, value, &mut out);
            out.extend_from_slice(b"))");
        }
    }
    out
}
#[cfg(test)]
#[path = "error_test.rs"]
mod tests;