generic-lang-api 0.1.0

Plugin ABI and authoring API for the generic programming language
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
//! End-to-end test of the `export_module!` glue: descriptor generation and
//! the panic/error mapping of the generated wrappers, driven through a mock
//! host vtable.

// The mock callbacks must match the ABI's fn-pointer types exactly, and the
// exported plugin fns keep the `Result` wrapper even when they never fail.
#![allow(clippy::missing_const_for_fn, clippy::unnecessary_wraps)]

use core::ffi::c_void;
use core::mem::MaybeUninit;
use std::cell::RefCell;

use generic_lang_api::{
    FfiReturn, FfiStatus, FfiStr, GENERIC_PLUGIN_ABI_VERSION, GenericValue, Host, HostApi,
    PluginError, ValueKind,
};

/// A blob carrying `first` in its first opaque limb (the rest zeroed) - the
/// tests build values this way to check bytes survive the FFI glue.
fn blob(first: u64) -> GenericValue {
    GenericValue {
        opaque: [
            MaybeUninit::new(first),
            MaybeUninit::new(0),
            MaybeUninit::new(0),
            MaybeUninit::new(0),
        ],
    }
}

/// Read the first opaque limb of a blob built by [`blob`].
///
/// # Safety
///
/// The first limb must be initialized - it is for anything from `blob` or a
/// mock echoing such a value.
unsafe fn limb0(value: GenericValue) -> u64 {
    // SAFETY: guaranteed by the caller.
    unsafe { value.opaque[0].assume_init() }
}

fn add(host: &mut Host, args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    let (Some(a), Some(b)) = (host.as_int(args[0]), host.as_int(args[1])) else {
        return Err(host.type_error("add expects two integers"));
    };
    Ok(host.make_int(a + b))
}

fn fail(host: &mut Host, _args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    Err(host.index_error("out of bounds"))
}

fn explode(_host: &mut Host, _args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    panic!("kaboom");
}

fn forward_fatal(_host: &mut Host, _args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    Err(PluginError::Fatal)
}

fn explode_any(_host: &mut Host, _args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    std::panic::panic_any(42);
}

/// Multi-arity export: sums however many integers it receives.
fn sum_any(host: &mut Host, args: &[GenericValue]) -> Result<GenericValue, PluginError> {
    let mut sum = 0;
    for arg in args {
        let Some(value) = host.as_int(*arg) else {
            return Err(host.type_error("sum_any expects integers"));
        };
        sum += value;
    }
    Ok(host.make_int(sum))
}

/// A method body used by the `Widget` class in the export test. Methods take
/// the receiver as a separate parameter.
fn widget_method(
    host: &mut Host,
    _this: GenericValue,
    _args: &[GenericValue],
) -> Result<GenericValue, PluginError> {
    Ok(host.make_nil())
}

extern "C" fn widget_drop(_ptr: *mut c_void) {}

extern "C" fn widget_traverse(
    _ptr: *mut c_void,
    _visit: generic_lang_api::PluginVisitFn,
    _visit_ctx: *mut c_void,
) -> i32 {
    0
}

fn make_seven(_host: &mut Host) -> Result<GenericValue, PluginError> {
    Ok(blob(7))
}

fn value_fail(host: &mut Host) -> Result<GenericValue, PluginError> {
    Err(host.type_error("value creation failed"))
}

generic_lang_api::export_module![
    value("seven", make_seven),
    value("broken", value_fail),
    ("add", &[2], add),
    ("fail", &[0], fail),
    ("explode", &[0], explode),
    ("forward_fatal", &[0], forward_fatal),
    ("explode_any", &[0], explode_any),
    ("sum_any", &[1, 3], sum_any),
    class("Widget") {
        ("__init__", &[0], widget_method),
        ("poke", &[0, 1], widget_method),
        drop: widget_drop,
        traverse: widget_traverse,
    },
    class("Plain") {
        ("ping", &[0], widget_method),
    },
];

// --- mock host ---

thread_local! {
    /// Message strings interned through the mock `string_new`.
    static INTERNED: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

// --- Mocks with real behavior: they read arguments, encode values, or
// intern strings, so the tests can check data survives the FFI glue. ---

// `int_get`/`int_new` carry integers in the first opaque limb, so the
// tests verify values travel through the glue byte-exact.
#[allow(clippy::cast_possible_wrap)]
extern "C" fn mock_int_get(_ctx: *mut c_void, value: GenericValue, out: *mut i64) -> bool {
    // SAFETY: the out-pointer is valid, and the first limb is initialized
    // for the values the tests build with `blob` and pass in.
    unsafe { *out = limb0(value) as i64 };
    true
}
#[allow(clippy::cast_sign_loss)]
extern "C" fn mock_int_new(_ctx: *mut c_void, value: i64) -> GenericValue {
    blob(value as u64)
}
extern "C" fn mock_string_new(_ctx: *mut c_void, value: FfiStr) -> FfiReturn {
    // SAFETY: callers pass valid UTF-8 of the given length.
    let s = unsafe {
        core::str::from_utf8_unchecked(core::slice::from_raw_parts(value.ptr, value.len))
    };
    INTERNED.with_borrow_mut(|strings| strings.push(s.to_owned()));
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
// `builtin_get`/`exception_new` intern class names and messages, and hand
// back values echoing the class handle, so the tests can check both travel
// through the glue.
extern "C" fn mock_builtin_get(_ctx: *mut c_void, name: FfiStr) -> FfiReturn {
    // SAFETY: callers pass valid UTF-8 of the given length.
    let s =
        unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(name.ptr, name.len)) };
    INTERNED.with_borrow_mut(|strings| strings.push(s.to_owned()));
    // A fake class handle tagged by the name's length.
    FfiReturn {
        status: 0,
        value: blob(name.len as u64),
    }
}
extern "C" fn mock_exception_new(
    _ctx: *mut c_void,
    class: GenericValue,
    message: FfiStr,
) -> FfiReturn {
    // SAFETY: callers pass valid UTF-8 of the given length.
    let s = unsafe {
        core::str::from_utf8_unchecked(core::slice::from_raw_parts(message.ptr, message.len))
    };
    INTERNED.with_borrow_mut(|strings| strings.push(s.to_owned()));
    // Echo the class handle so the test can see which class was used.
    FfiReturn {
        status: 0,
        value: class,
    }
}

// --- Inert stubs: return a fixed placeholder regardless of input, present
// only to fill out the vtable. ---

extern "C" fn mock_value_kind(_ctx: *mut c_void, _value: GenericValue) -> u32 {
    ValueKind::Int as u32
}
extern "C" fn mock_bool_get(_ctx: *mut c_void, _value: GenericValue, _out: *mut bool) -> bool {
    false
}
extern "C" fn mock_float_get(_ctx: *mut c_void, _value: GenericValue, _out: *mut f64) -> bool {
    false
}
extern "C" fn mock_string_get(_ctx: *mut c_void, _value: GenericValue, _out: *mut FfiStr) -> bool {
    false
}
extern "C" fn mock_list_len(_ctx: *mut c_void, _value: GenericValue, _out: *mut usize) -> bool {
    false
}
extern "C" fn mock_list_get(_ctx: *mut c_void, _value: GenericValue, _index: usize) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_nil_new(_ctx: *mut c_void) -> GenericValue {
    blob(0)
}
extern "C" fn mock_bool_new(_ctx: *mut c_void, _value: bool) -> GenericValue {
    blob(0)
}
extern "C" fn mock_float_new(_ctx: *mut c_void, _value: f64) -> GenericValue {
    blob(0)
}
extern "C" fn mock_list_new(_ctx: *mut c_void) -> GenericValue {
    blob(0)
}
extern "C" fn mock_list_push(
    _ctx: *mut c_void,
    _list: GenericValue,
    _item: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_value_display(_ctx: *mut c_void, _value: GenericValue) -> GenericValue {
    blob(0)
}
extern "C" fn mock_call_value(
    _ctx: *mut c_void,
    _callee: GenericValue,
    _args: *const GenericValue,
    _nargs: usize,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_invoke_method(
    _ctx: *mut c_void,
    _receiver: GenericValue,
    _name: FfiStr,
    _args: *const GenericValue,
    _nargs: usize,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_value_str(_ctx: *mut c_void, _value: GenericValue) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_root(_ctx: *mut c_void, _value: GenericValue) {}
extern "C" fn mock_unroot(_ctx: *mut c_void, _n: usize) {}
extern "C" fn mock_tuple_len(_ctx: *mut c_void, _value: GenericValue, _out: *mut usize) -> bool {
    false
}
extern "C" fn mock_tuple_get(_ctx: *mut c_void, _value: GenericValue, _index: usize) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_container_len(
    _ctx: *mut c_void,
    _value: GenericValue,
    _out: *mut usize,
) -> bool {
    false
}
extern "C" fn mock_attr_get(
    _ctx: *mut c_void,
    _receiver: GenericValue,
    _name: FfiStr,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_attr_set(
    _ctx: *mut c_void,
    _receiver: GenericValue,
    _name: FfiStr,
    _value: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_attr_has(
    _ctx: *mut c_void,
    _receiver: GenericValue,
    _name: FfiStr,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_list_set(
    _ctx: *mut c_void,
    _list: GenericValue,
    _index: usize,
    _value: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_value_binary(
    _ctx: *mut c_void,
    _a: GenericValue,
    _b: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_dict_set(
    _ctx: *mut c_void,
    _dict: GenericValue,
    _key: GenericValue,
    _value: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_value_unary(_ctx: *mut c_void, _value: GenericValue) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_is_instance(
    _ctx: *mut c_void,
    _value: GenericValue,
    _class: GenericValue,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}

fn mock_host_api() -> HostApi {
    HostApi {
        abi_version: GENERIC_PLUGIN_ABI_VERSION,
        ctx: core::ptr::null_mut(),
        value_kind: mock_value_kind,
        bool_get: mock_bool_get,
        int_get: mock_int_get,
        float_get: mock_float_get,
        string_get: mock_string_get,
        list_len: mock_list_len,
        list_get: mock_list_get,
        tuple_len: mock_tuple_len,
        tuple_get: mock_tuple_get,
        dict_len: mock_container_len,
        set_len: mock_container_len,
        builtin_get: mock_builtin_get,
        is_instance: mock_is_instance,
        class_of: mock_value_unary,
        attr_get: mock_attr_get,
        attr_set: mock_attr_set,
        attr_has: mock_attr_has,
        nil_new: mock_nil_new,
        bool_new: mock_bool_new,
        int_new: mock_int_new,
        float_new: mock_float_new,
        string_new: mock_string_new,
        list_new: mock_list_new,
        list_push: mock_list_push,
        list_set: mock_list_set,
        exception_new: mock_exception_new,
        value_display: mock_value_display,
        call_value: mock_call_value,
        invoke_method: mock_invoke_method,
        value_str: mock_value_str,
        dict_get: mock_value_binary,
        dict_set: mock_dict_set,
        dict_contains: mock_value_binary,
        set_add: mock_value_binary,
        set_contains: mock_value_binary,
        value_truthy: mock_value_unary,
        value_equals: mock_value_binary,
        value_hash: mock_value_unary,
        root: mock_root,
        unroot: mock_unroot,
        instance_set_opaque: mock_instance_set_opaque,
        instance_get_opaque: mock_instance_get_opaque,
    }
}

extern "C" fn mock_instance_set_opaque(
    _ctx: *mut c_void,
    _receiver: GenericValue,
    _ptr: *mut c_void,
) -> FfiReturn {
    FfiReturn {
        status: 0,
        value: blob(0),
    }
}
extern "C" fn mock_instance_get_opaque(_ctx: *mut c_void, _receiver: GenericValue) -> *mut c_void {
    core::ptr::null_mut()
}

fn last_interned() -> String {
    INTERNED.with_borrow(|strings| strings.last().cloned().unwrap_or_default())
}

#[test]
fn descriptor_contents() {
    // Descriptor is non-null and init is idempotent
    let desc = generic_plugin_init();
    assert!(!desc.is_null());
    assert_eq!(desc, generic_plugin_init());

    // ABI version and function count are correct
    // SAFETY: generic_plugin_init returns a valid, leaked descriptor.
    let desc = unsafe { &*desc };
    assert_eq!(desc.abi_version, GENERIC_PLUGIN_ABI_VERSION);
    assert_eq!(desc.functions_len, 6);

    // The exported names, in declaration order.
    // SAFETY: the descriptor references a leaked slice of functions_len entries.
    let functions = unsafe { core::slice::from_raw_parts(desc.functions, desc.functions_len) };
    let names: Vec<&str> = functions
        .iter()
        .map(|f| {
            // SAFETY: names are leaked static strings.
            unsafe {
                core::str::from_utf8_unchecked(core::slice::from_raw_parts(f.name.ptr, f.name.len))
            }
        })
        .collect();
    assert_eq!(
        names,
        [
            "add",
            "fail",
            "explode",
            "forward_fatal",
            "explode_any",
            "sum_any"
        ]
    );

    // Every function's full arity list survives the glue, including the
    // multi-arity `sum_any`.
    let expected_arities: [&[u8]; 6] = [&[2], &[0], &[0], &[0], &[0], &[1, 3]];
    for (function, expected) in functions.iter().zip(expected_arities) {
        // SAFETY: arities are leaked static slices of arities_len entries.
        let arities =
            unsafe { core::slice::from_raw_parts(function.arities, function.arities_len) };
        assert_eq!(arities, expected);
    }

    // The macro always emits a non-null function pointer.
    assert!(functions.iter().all(|f| f.fun.is_some()));
}

#[test]
fn value_descriptor_contents_and_creators() {
    // SAFETY: generic_plugin_init returns a valid, leaked descriptor.
    let desc = unsafe { &*generic_plugin_init() };
    assert_eq!(desc.values_len, 2);
    // SAFETY: the descriptor references a leaked slice of values_len entries.
    let values = unsafe { core::slice::from_raw_parts(desc.values, desc.values_len) };

    // SAFETY: names are leaked static strings.
    let names: Vec<&str> = values.iter().map(|v| unsafe { ffi_str(v.name) }).collect();
    assert_eq!(names, ["seven", "broken"]);
    assert!(values.iter().all(|v| v.fun.is_some()));

    // The generated creator glue passes the host through and returns the
    // built value byte-exact.
    let api = mock_host_api();
    let ret = values[0].fun.expect("checked non-null above")(&raw const api);
    assert_eq!(ret.status, FfiStatus::Ok as u32);
    // SAFETY: the mock encodes integers in the first opaque limb.
    assert_eq!(unsafe { limb0(ret.value) }, 7);

    // A failing creator surfaces as an exception, like a failing function.
    let ret = values[1].fun.expect("checked non-null above")(&raw const api);
    assert_eq!(ret.status, FfiStatus::Exception as u32);
}

/// # Safety
///
/// `s` must reference `s.len` bytes of valid UTF-8, valid for the read.
unsafe fn ffi_str(s: FfiStr) -> &'static str {
    // SAFETY: guaranteed by the caller; names are leaked static strings.
    unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(s.ptr, s.len)) }
}

#[test]
fn class_descriptor_contents() {
    // SAFETY: generic_plugin_init returns a valid, leaked descriptor.
    let desc = unsafe { &*generic_plugin_init() };
    assert_eq!(desc.classes_len, 2);

    // SAFETY: the descriptor references a leaked slice of classes_len entries.
    let classes = unsafe { core::slice::from_raw_parts(desc.classes, desc.classes_len) };

    // First class: methods, drop, and traverse all present.
    let widget = &classes[0];
    assert_eq!(unsafe { ffi_str(widget.name) }, "Widget");
    assert_eq!(widget.methods_len, 2);
    assert!(widget.drop.is_some());
    assert!(widget.traverse.is_some());

    // SAFETY: leaked slice of methods_len entries.
    let methods = unsafe { core::slice::from_raw_parts(widget.methods, widget.methods_len) };
    let method_names: Vec<&str> = methods.iter().map(|m| unsafe { ffi_str(m.name) }).collect();
    assert_eq!(method_names, ["__init__", "poke"]);
    // Method arities survive, including the multi-arity `poke` (self + 0/1).
    let poke_arities =
        unsafe { core::slice::from_raw_parts(methods[1].arities, methods[1].arities_len) };
    assert_eq!(poke_arities, &[0, 1]);
    assert!(methods.iter().all(|m| m.fun.is_some()));

    // Second class: no drop/traverse (the optional fields default to None).
    let plain = &classes[1];
    assert_eq!(unsafe { ffi_str(plain.name) }, "Plain");
    assert_eq!(plain.methods_len, 1);
    assert!(plain.drop.is_none());
    assert!(plain.traverse.is_none());
}

fn call_exported(index: usize, args: &[GenericValue]) -> FfiReturn {
    // SAFETY: valid leaked descriptor, see descriptor_contents.
    let desc = unsafe { &*generic_plugin_init() };
    // SAFETY: see above.
    let functions = unsafe { core::slice::from_raw_parts(desc.functions, desc.functions_len) };
    let api = mock_host_api();
    let fun = functions[index]
        .fun
        .expect("export_module! emits non-null function pointers");
    fun(&raw const api, args.as_ptr(), args.len())
}

#[test]
fn multi_arity_export_runs_at_each_declared_arity() {
    // Arity enforcement lives in the host's dispatch, not the glue - this
    // pins that the wrapper handles whichever declared argument count
    // arrives.
    let ret = call_exported(5, &[blob(40), blob(1), blob(1)]);
    assert_eq!(ret.status, 0);
    // SAFETY: `sum_any` returns an int built via the mock, so limb 0 is set.
    assert_eq!(unsafe { limb0(ret.value) }, 42);

    let ret = call_exported(5, &[blob(7)]);
    assert_eq!(ret.status, 0);
    // SAFETY: as above.
    assert_eq!(unsafe { limb0(ret.value) }, 7);
}

#[test]
fn ok_path() {
    // The mock encodes integers in the first opaque limb, so this checks
    // the arguments and the result travel through the glue byte-exact:
    // 19 + 23 must come back as 42.
    let args = [blob(19), blob(23)];
    let ret = call_exported(0, &args);
    assert_eq!(ret.status, 0);
    // SAFETY: `add` returns an int built via `blob`, so limb 0 is set.
    assert_eq!(unsafe { limb0(ret.value) }, 42);
}

#[test]
fn typed_error_path() {
    let ret = call_exported(1, &[]);
    // A typed error materializes as an exception instance of the class
    // looked up by name and built through `exception_new` (the mock class
    // handle carries the name's length; "IndexError" is 10 long).
    assert_eq!(ret.status, FfiStatus::Exception as u32);
    // SAFETY: the class handle is built via `blob`, so limb 0 is set.
    assert_eq!(unsafe { limb0(ret.value) }, "IndexError".len() as u64);
    let interned = INTERNED.with_borrow(Clone::clone);
    assert_eq!(
        &interned[interned.len() - 2..],
        ["IndexError", "out of bounds"]
    );
}

/// `string_get` answering success but writing a null pointer (or not
/// writing at all - the out-param is initialized null): a protocol
/// violation. `Host::as_str` must report "not a string" instead of
/// building a slice from the null pointer or fabricating an empty string.
extern "C" fn mock_string_get_null_ptr(
    _ctx: *mut c_void,
    _value: GenericValue,
    out: *mut FfiStr,
) -> bool {
    // SAFETY: the out-pointer is valid (test-controlled).
    unsafe { *out = FfiStr::null() };
    true
}

#[test]
fn as_str_rejects_a_null_pointer() {
    let mut api = mock_host_api();
    api.string_get = mock_string_get_null_ptr;
    let host = Host::new(&api);
    assert_eq!(host.as_str(blob(0)), None);
}

#[test]
fn panic_becomes_exception() {
    // Silence the default panic hook for the expected panic.
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let ret = call_exported(2, &[]);
    std::panic::set_hook(previous);

    assert_eq!(ret.status, FfiStatus::Exception as u32);
    // SAFETY: the class handle is built via `blob`, so limb 0 is set.
    assert_eq!(unsafe { limb0(ret.value) }, "Exception".len() as u64);
    assert_eq!(last_interned(), "panic: kaboom");
}

#[test]
fn fatal_forwards_unchanged() {
    let ret = call_exported(3, &[]);
    assert_eq!(ret.status, FfiStatus::Fatal as u32);
    // Pin the wire value: 99 is part of the C ABI.
    assert_eq!(ret.status, 99);
}

#[test]
fn non_string_panic_payload_gets_the_fallback_message() {
    // Silence the default panic hook for the expected panic.
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let ret = call_exported(4, &[]);
    std::panic::set_hook(previous);

    assert_eq!(ret.status, FfiStatus::Exception as u32);
    assert_eq!(last_interned(), "panic: plugin function panicked");
}

#[test]
fn null_args_with_zero_nargs_is_accepted() {
    // A C host may pass a null argument pointer for a zero-argument call;
    // the glue must not build a slice from it.
    let desc = unsafe { &*generic_plugin_init() };
    // SAFETY: valid leaked descriptor, see descriptor_contents.
    let functions = unsafe { core::slice::from_raw_parts(desc.functions, desc.functions_len) };
    let api = mock_host_api();
    let fun = functions[1]
        .fun
        .expect("export_module! emits non-null function pointers");
    let ret = fun(&raw const api, core::ptr::null(), 0);
    // `fail` still runs and produces its IndexError.
    assert_eq!(ret.status, FfiStatus::Exception as u32);
}

/// A host callback answering with a status outside the enum: the safe
/// wrapper must surface it as a protocol-violation exception, never
/// interpret `value`.
extern "C" fn mock_call_value_unknown_status(
    _ctx: *mut c_void,
    _callee: GenericValue,
    _args: *const GenericValue,
    _nargs: usize,
) -> FfiReturn {
    FfiReturn {
        status: 7,
        value: blob(0),
    }
}

#[test]
fn unknown_host_status_is_a_protocol_violation_exception() {
    let mut api = mock_host_api();
    api.call_value = mock_call_value_unknown_status;
    let mut host = Host::new(&api);
    let result = host.call(blob(0), &[]);
    assert!(matches!(result, Err(PluginError::Exception(_))));
    assert_eq!(last_interned(), "host callback returned unknown status 7");
}

/// A host answering `builtin_get` with an unknown status too - the very
/// callback the protocol-violation path uses to build its exception. Error
/// construction must bottom out at a nil-carrying exception instead of
/// recursing through itself until the stack overflows.
extern "C" fn mock_builtin_get_unknown_status(_ctx: *mut c_void, _name: FfiStr) -> FfiReturn {
    FfiReturn {
        status: 7,
        value: blob(0),
    }
}

#[test]
fn unknown_status_during_error_construction_does_not_recurse() {
    let mut api = mock_host_api();
    api.call_value = mock_call_value_unknown_status;
    api.builtin_get = mock_builtin_get_unknown_status;
    let mut host = Host::new(&api);
    let result = host.call(blob(0), &[]);
    assert!(matches!(result, Err(PluginError::Exception(_))));
}

/// A host whose `builtin_get` reports a fatal error: error construction
/// must propagate `Fatal` instead of downgrading it to a catchable
/// exception carrying nil.
extern "C" fn mock_builtin_get_fatal(_ctx: *mut c_void, _name: FfiStr) -> FfiReturn {
    FfiReturn {
        status: FfiStatus::Fatal as u32,
        value: blob(0),
    }
}

#[test]
fn fatal_during_error_construction_stays_fatal() {
    let mut api = mock_host_api();
    api.builtin_get = mock_builtin_get_fatal;
    let host = Host::new(&api);
    assert!(matches!(host.type_error("boom"), PluginError::Fatal));
}