htl 0.19.0

Holistic Typed Lua: Teal type-checked at cargo build and run on an embedded mlua state (umbrella over htl-core + htl-macros)
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
//! The C ABI `#[c_export]` generates, exercised through the generated symbols
//! themselves rather than through the Rust methods behind them.
//!
//! A C compiler is not needed for any of this: an `extern "C"` function is callable from
//! Rust, and calling it here is the same call a `dlopen`ed host makes — the same
//! decoding, the same panic guard, the same thread check. What a C program would add is
//! the linker, and that is covered by the C caller `htl new --target cdylib --lib` writes
//! (`crates/htl-cli/templates/ffi/main.c`), compiled and run by `just e2e`.

#![cfg(feature = "ffi")]

use htl::mlua::{HookTriggers, VmState};
use htl::{Htl, c_export, ffi};
use std::cell::Cell;
use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::rc::Rc;

#[derive(serde::Deserialize)]
struct Options {
    greeting: String,
}

/// What `game_state` hands back: a record, so it crosses as JSON with a `"v"`.
#[derive(serde::Serialize)]
pub struct State {
    depth: i32,
    greeting: String,
}

/// A host with one method of each shape.
pub struct Game {
    h: Htl,
    greeting: String,
    depth: i32,
    /// How often the host's own hook callback (`count`) fired.
    hits: Rc<Cell<i32>>,
}

#[c_export(prefix = "game")]
impl Game {
    /// The opener. Options as one JSON object, and the flag `game_interrupt` sets: the
    /// hook has to go on the state while it is being built, which is the only moment the
    /// handle and the state exist together.
    pub fn open(options: &str, interrupt: ffi::Interrupt) -> Result<Self, String> {
        let o: Options = ffi::from_json(options, "options_json")?;
        let h = Htl::new().map_err(|e| e.to_string())?;
        interrupt.install(&h).map_err(|e| e.to_string())?;
        Ok(Game {
            h,
            greeting: o.greeting,
            depth: 0,
            hits: Rc::default(),
        })
    }

    /// The host's own callback on the state's hook owner, beside the interrupt's: every
    /// thousandth instruction, counted in `hits`.
    pub fn count(&self) -> Result<(), String> {
        let hits = self.hits.clone();
        self.h
            .hook_owner()
            .map_err(|e| e.to_string())?
            .add_hook(
                HookTriggers::new().every_nth_instruction(1000),
                move |_, _| {
                    hits.set(hits.get() + 1);
                    Ok(VmState::Continue)
                },
            )
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    /// `hits` since the last call.
    pub fn counted(&self) -> i32 {
        self.hits.replace(0)
    }

    /// Coverage on the same state: the third callback on the one hook.
    pub fn cover(&self) -> Result<(), String> {
        self.h.coverage_start().map_err(|e| e.to_string())
    }

    /// Stop coverage; the chunks it saw, comma-separated.
    pub fn covered(&self) -> Result<String, String> {
        let cov = self.h.coverage_stop().map_err(|e| e.to_string())?;
        Ok(cov
            .into_iter()
            .map(|(src, _)| src)
            .collect::<Vec<_>>()
            .join(","))
    }

    /// `String` -> `char *`: the text itself.
    pub fn greet(&self, who: &str) -> String {
        format!("{}, {who}", self.greeting)
    }

    /// A record -> `char *`: JSON.
    pub fn state(&self) -> State {
        State {
            depth: self.depth,
            greeting: self.greeting.clone(),
        }
    }

    /// `Result<(), E>` -> `int`: a status and nothing else.
    pub fn deeper(&mut self, by: i32) -> Result<(), String> {
        if by < 0 {
            return Err("cannot go up".into());
        }
        self.depth += by;
        Ok(())
    }

    /// `i32` -> `int` with an out-parameter: the value never rides in the status.
    pub fn depth(&self) -> i32 {
        self.depth
    }

    /// `()` -> `void`.
    pub fn reset(&mut self) {
        self.depth = 0;
    }

    /// Runs Lua, so a Lua `error()` can reach the boundary.
    pub fn run(&self, src: &str) -> Result<String, htl::mlua::Error> {
        self.h.lua().load(src).eval()
    }

    /// `run`, but as a root on the executor (`Htl::run_blocking`), the way `htl run`
    /// runs a program: the interrupt has to reach a program there too, as the type
    /// `Status::Interrupted` is read from.
    pub fn run_root(&self, src: &str) -> Result<String, anyhow::Error> {
        let token = htl::mlua_isle::runtime::CancelToken::new();
        let f = self.h.lua().load(src).into_function()?;
        let mut out = self.h.call_blocking(f, (), &token)?;
        Ok(match out.pop_front() {
            Some(htl::mlua::Value::String(s)) => s.to_str()?.to_string(),
            _ => String::new(),
        })
    }

    /// A Rust panic, which since 1.81 aborts the process if it reaches `extern "C"`.
    pub fn boom(&self) -> String {
        panic!("boom from Rust")
    }

    /// A string a C caller cannot be handed: the NUL is in the middle of it.
    pub fn with_nul(&self) -> String {
        "before\0after".to_string()
    }
}

// ---------------------------------------------------------------- helpers

fn options(greeting: &str) -> CString {
    CString::new(format!(r#"{{"greeting":"{greeting}"}}"#)).unwrap()
}

/// Open a handle on this thread, or explain why not.
fn open(greeting: &str) -> *mut c_void {
    let o = options(greeting);
    let h = unsafe { game_open(o.as_ptr()) };
    assert!(!h.is_null(), "open failed: {}", last_error());
    h
}

/// Take a `char *` the library returned, as a `String`, and give it back.
fn take(p: *mut c_char) -> String {
    assert!(!p.is_null(), "expected a string: {}", last_error());
    let s = unsafe { CStr::from_ptr(p) }.to_str().unwrap().to_string();
    unsafe { game_free(p) };
    s
}

fn last_error() -> String {
    let p = game_last_error();
    if p.is_null() {
        return "(no error)".to_string();
    }
    unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
}

fn cstr(s: &str) -> CString {
    CString::new(s).unwrap()
}

// ---------------------------------------------------------------- the ABI

#[test]
fn the_library_says_what_it_is() {
    assert_eq!(game_abi_version(), ffi::ABI_VERSION);
    assert_eq!(<Game as ffi::CExport>::PREFIX, "game");
    assert_eq!(
        game_threadsafe(),
        0,
        "one handle per thread, the sqlite3_threadsafe convention"
    );
    let v = unsafe { CStr::from_ptr(game_version()) }.to_str().unwrap();
    assert_eq!(v, env!("CARGO_PKG_VERSION"));
}

#[test]
fn the_header_declares_what_was_generated() {
    let h = <Game as ffi::CExport>::HEADER;
    for want in [
        "game_handle *game_open(const char *options_json);",
        "char *game_greet(game_handle *h, const char *who);",
        "char *game_state(game_handle *h);",
        "int game_deeper(game_handle *h, int by);",
        "int game_depth(game_handle *h, int *out);",
        "void game_reset(game_handle *h);",
        "int game_interrupt(game_handle *h);",
        "void game_free(char *s);",
        "#define GAME_LUA 4",
    ] {
        assert!(h.contains(want), "the header is missing `{want}`:\n{h}");
    }
}

#[test]
fn a_round_trip_returns_text_json_and_an_out_parameter() {
    let h = open("hello");

    assert_eq!(
        take(unsafe { game_greet(h, cstr("Ada").as_ptr()) }),
        "hello, Ada"
    );

    assert_eq!(unsafe { game_deeper(h, 3) }, 0, "{}", last_error());
    let mut depth: c_int = -1;
    assert_eq!(unsafe { game_depth(h, &mut depth) }, 0);
    assert_eq!(depth, 3, "the value comes back through the out-parameter");

    let state = take(unsafe { game_state(h) });
    let parsed: serde_json::Value = serde_json::from_str(&state).unwrap();
    assert_eq!(parsed["depth"], 3);
    assert_eq!(parsed["greeting"], "hello");
    assert_eq!(
        parsed["v"], 1,
        "an object payload carries its schema version: {state}"
    );

    unsafe { game_reset(h) };
    assert_eq!(unsafe { game_depth(h, &mut depth) }, 0);
    assert_eq!(depth, 0);

    unsafe { game_close(h) };
}

#[test]
fn a_failing_method_answers_a_status_and_a_message() {
    let h = open("hi");
    assert_eq!(
        unsafe { game_deeper(h, -1) },
        ffi::Status::Err.code(),
        "a Result::Err is a status, not a value"
    );
    assert_eq!(last_error(), "cannot go up");
    assert_eq!(game_last_status(), ffi::Status::Err.code());
    unsafe { game_close(h) };
}

#[test]
fn a_lua_error_crosses_as_a_status_and_a_message() {
    let h = open("hi");
    let p = unsafe { game_run(h, cstr("error('from the mod')").as_ptr()) };
    assert!(p.is_null(), "a failed char * function answers NULL");
    assert_eq!(
        game_last_status(),
        ffi::Status::Lua.code(),
        "an mlua error is LUA, not ERR"
    );
    assert!(
        last_error().contains("from the mod"),
        "the message is Lua's: {}",
        last_error()
    );
    assert!(
        !last_error().contains("stack traceback"),
        "and it is the one a host shows a player, not the log: {}",
        last_error()
    );
    // The handle is not poisoned by a Lua error: the state is still the state.
    assert_eq!(
        take(unsafe { game_run(h, cstr("return 'ok'").as_ptr()) }),
        "ok"
    );
    unsafe { game_close(h) };
}

#[test]
fn a_rust_panic_is_caught_and_poisons_the_handle() {
    let h = open("hi");
    let p = unsafe { game_boom(h) };
    assert!(p.is_null(), "the process must still be here");
    assert_eq!(game_last_status(), ffi::Status::Panic.code());
    assert!(
        last_error().contains("boom from Rust"),
        "the panic message is the error: {}",
        last_error()
    );
    // Everything after it is refused rather than run on a state nobody has reasoned
    // about.
    let mut depth: c_int = -1;
    assert_eq!(
        unsafe { game_depth(h, &mut depth) },
        ffi::Status::Panic.code()
    );
    assert!(
        last_error().contains("poisoned"),
        "and it says so: {}",
        last_error()
    );
    unsafe { game_close(h) };
}

#[test]
fn a_handle_used_from_another_thread_answers_wrong_thread() {
    let h = open("hi");
    let addr = h as usize;
    let (status, message) = std::thread::spawn(move || {
        let h = addr as *mut c_void;
        let p = unsafe { game_greet(h, cstr("Ada").as_ptr()) };
        assert!(p.is_null(), "nothing was run, so nothing came back");
        // The error slot is per thread: this is the one this thread just filled.
        (game_last_status(), last_error())
    })
    .join()
    .unwrap();
    assert_eq!(status, ffi::Status::WrongThread.code());
    assert!(message.contains("thread that opened it"), "{message}");
    unsafe { game_close(h) };
}

#[test]
fn a_string_with_a_nul_is_refused_rather_than_cut_short() {
    let h = open("hi");
    let p = unsafe { game_with_nul(h) };
    assert!(p.is_null(), "half a string must not cross");
    assert_eq!(game_last_status(), ffi::Status::Err.code());
    assert!(
        last_error().contains("NUL byte at index 6"),
        "and it says where: {}",
        last_error()
    );
    unsafe { game_close(h) };
}

#[test]
fn freeing_null_and_closing_null_are_no_ops() {
    unsafe { game_free(std::ptr::null_mut()) };
    unsafe { game_close(std::ptr::null_mut()) };
}

#[test]
fn a_bad_handle_is_answered_rather_than_dereferenced() {
    let mut not_a_handle: u64 = 0;
    let p = (&mut not_a_handle) as *mut u64 as *mut c_void;
    let mut depth: c_int = -1;
    assert_eq!(
        unsafe { game_depth(p, &mut depth) },
        ffi::Status::BadHandle.code()
    );
    assert_eq!(
        unsafe { game_depth(std::ptr::null_mut(), &mut depth) },
        ffi::Status::BadHandle.code()
    );
}

#[test]
fn a_null_out_parameter_is_refused() {
    let h = open("hi");
    assert_eq!(
        unsafe { game_depth(h, std::ptr::null_mut()) },
        ffi::Status::Err.code()
    );
    assert!(last_error().contains("`out` is NULL"), "{}", last_error());
    unsafe { game_close(h) };
}

#[test]
fn an_argument_that_is_not_a_string_is_refused_before_the_handle_is_entered() {
    let h = open("hi");
    let p = unsafe { game_greet(h, std::ptr::null()) };
    assert!(p.is_null());
    assert!(last_error().contains("`who` is NULL"), "{}", last_error());
    // The handle is untouched: the caller's mistake is not the handle's.
    assert_eq!(
        take(unsafe { game_greet(h, cstr("Ada").as_ptr()) }),
        "hi, Ada"
    );
    unsafe { game_close(h) };
}

#[test]
fn bad_options_are_a_failed_open_rather_than_a_handle() {
    let bad = cstr("not json");
    let h = unsafe { game_open(bad.as_ptr()) };
    assert!(h.is_null());
    assert!(last_error().contains("not valid JSON"), "{}", last_error());
    let h = unsafe { game_open(std::ptr::null()) };
    assert!(h.is_null());
    assert!(last_error().contains("is NULL"), "{}", last_error());
}

/// The one function callable from another thread, doing the one thing it is for.
#[test]
fn interrupt_stops_a_runaway_script_from_another_thread() {
    let h = open("hi");
    let addr = h as usize;
    let stopper = std::thread::spawn(move || {
        // Long enough that the loop below is running, short enough not to stall the
        // suite if it is not.
        std::thread::sleep(std::time::Duration::from_millis(150));
        unsafe { game_interrupt(addr as *mut c_void) }
    });

    let started = std::time::Instant::now();
    let p = unsafe { game_run(h, cstr("while true do end").as_ptr()) };
    let took = started.elapsed();

    assert_eq!(stopper.join().unwrap(), ffi::Status::Ok.code());
    assert!(
        p.is_null(),
        "the script did not finish, so there is no value"
    );
    assert_eq!(
        game_last_status(),
        ffi::Status::Interrupted.code(),
        "an interrupt is its own status, not a generic Lua error: {}",
        last_error()
    );
    assert!(
        took < std::time::Duration::from_secs(20),
        "it stopped when it was asked to, after {took:?}"
    );

    // The handle still works: an interrupt stops one run, not the game.
    assert_eq!(
        take(unsafe { game_run(h, cstr("return 'ok'").as_ptr()) }),
        "ok"
    );
    unsafe { game_close(h) };
}

/// The interrupt, coverage and the host's own callback are three registrations on the
/// state's one hook (#350): with all three on, the interrupt still stops the loop, the
/// host's callback fired while it ran, and coverage saw the chunk. Before, whichever was
/// installed last was the only one left.
#[test]
fn interrupt_stops_a_loop_with_coverage_on_and_a_host_callback_registered() {
    let h = open("hi");
    assert_eq!(
        unsafe { game_count(h) },
        ffi::Status::Ok.code(),
        "{}",
        last_error()
    );
    assert_eq!(
        unsafe { game_cover(h) },
        ffi::Status::Ok.code(),
        "{}",
        last_error()
    );
    let addr = h as usize;
    let stopper = std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_millis(150));
        unsafe { game_interrupt(addr as *mut c_void) }
    });

    let started = std::time::Instant::now();
    let src = "local t = os.clock()\nwhile os.clock() - t < 5 do end\nreturn 'finished'";
    let p = unsafe { game_run(h, cstr(src).as_ptr()) };
    let took = started.elapsed();

    assert_eq!(stopper.join().unwrap(), ffi::Status::Ok.code());
    assert!(p.is_null(), "the loop ran to the end of its five seconds");
    assert_eq!(
        game_last_status(),
        ffi::Status::Interrupted.code(),
        "{}",
        last_error()
    );
    assert!(
        took < std::time::Duration::from_secs(4),
        "it stopped when it was asked to, after {took:?}"
    );
    let mut hits: c_int = 0;
    assert_eq!(
        unsafe { game_counted(h, &mut hits) },
        ffi::Status::Ok.code()
    );
    assert!(hits > 0, "the host's callback fired while the loop ran");
    let covered = take(unsafe { game_covered(h) });
    assert!(!covered.is_empty(), "coverage saw the chunk that looped");

    assert_eq!(
        take(unsafe { game_run(h, cstr("return 'ok'").as_ptr()) }),
        "ok"
    );
    unsafe { game_close(h) };
}

/// Acceptance 9 of the async design: the same loop as a root on the executor (what `htl
/// run` does). The interrupt stops it and comes back as `Status::Interrupted`, not as a
/// plain Lua error, and the host's callback fired while it ran.
#[test]
fn interrupt_stops_a_loop_under_the_executor_beside_a_host_callback() {
    let h = open("hi");
    assert_eq!(
        unsafe { game_count(h) },
        ffi::Status::Ok.code(),
        "{}",
        last_error()
    );
    let addr = h as usize;
    let stopper = std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_millis(150));
        unsafe { game_interrupt(addr as *mut c_void) }
    });

    let started = std::time::Instant::now();
    let src = "local t = os.clock()\nwhile os.clock() - t < 5 do end\nreturn 'finished'";
    let p = unsafe { game_run_root(h, cstr(src).as_ptr()) };
    let took = started.elapsed();

    assert_eq!(stopper.join().unwrap(), ffi::Status::Ok.code());
    assert!(p.is_null(), "the loop ran to the end of its five seconds");
    assert_eq!(
        game_last_status(),
        ffi::Status::Interrupted.code(),
        "{}",
        last_error()
    );
    assert!(
        took < std::time::Duration::from_secs(4),
        "it stopped when it was asked to, after {took:?}"
    );
    let mut hits: c_int = 0;
    assert_eq!(
        unsafe { game_counted(h, &mut hits) },
        ffi::Status::Ok.code()
    );
    assert!(hits > 0, "the host's callback fired while the loop ran");
    // The next run on the handle starts clean.
    assert_eq!(
        take(unsafe { game_run_root(h, cstr("return 'ok'").as_ptr()) }),
        "ok",
        "{}",
        last_error()
    );
    unsafe { game_close(h) };
}

/// A script that does its looping inside a coroutine is on another Lua thread, and a
/// thread hook would not see it. The interrupt is the state's global hook, so it does.
/// The loop is bounded by the clock rather than infinite: if the interrupt does not reach
/// it, the test fails on the status after five seconds instead of hanging the suite.
#[test]
fn interrupt_reaches_a_loop_inside_a_coroutine() {
    let h = open("hi");
    let addr = h as usize;
    let stopper = std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_millis(150));
        unsafe { game_interrupt(addr as *mut c_void) }
    });

    let started = std::time::Instant::now();
    let src = "local t = os.clock()\n\
               coroutine.wrap(function() while os.clock() - t < 5 do end end)()\n\
               return 'finished'";
    let p = unsafe { game_run(h, cstr(src).as_ptr()) };
    let took = started.elapsed();

    assert_eq!(stopper.join().unwrap(), ffi::Status::Ok.code());
    assert!(
        p.is_null(),
        "the coroutine ran to the end of its five seconds"
    );
    assert_eq!(
        game_last_status(),
        ffi::Status::Interrupted.code(),
        "{}",
        last_error()
    );
    assert!(
        took < std::time::Duration::from_secs(4),
        "it stopped when it was asked to, after {took:?}"
    );

    assert_eq!(
        take(unsafe { game_run(h, cstr("return 'ok'").as_ptr()) }),
        "ok"
    );
    unsafe { game_close(h) };
}

/// The status codes the header states and the ones the runtime answers with are two
/// tables in two modules behind two features. This is what keeps them one set.
#[test]
fn the_generator_and_the_runtime_agree_on_the_status_codes() {
    let runtime: Vec<(&str, i32)> = ffi::Status::ALL
        .iter()
        .map(|s| (s.name(), s.code()))
        .collect();
    assert_eq!(runtime, htl::cexport::STATUSES.to_vec());
    assert_eq!(ffi::ABI_VERSION, htl::cexport::ABI_VERSION);
}