beamr 0.4.0

A Rust runtime with the BEAM's execution model, targeting Gleam
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
//! Unit tests for OTP stub BIFs.

use super::*;
use crate::atom::AtomTable;
use crate::native::BifRegistryImpl;
use crate::native::code_management_bifs::CodeManagementFacility;
use crate::native::otp_stubs::gleam_stubs::{GleamResultState, resume_gleam_result_continuation};
use crate::native::stdlib_stubs::maps_bifs::ContinuationStep;
use crate::native::NativeContinuation;
use crate::process::Process;
use crate::term::binary_ref::BinaryRef;
use crate::term::boxed::{Cons, Tuple, write_closure};
use crate::{
    error::LoadError,
    module::{ModuleOrigin, PurgeError},
    scheduler::{HotLoadResult, PurgeResult},
};
use std::collections::HashMap;
use std::sync::Arc;

#[test]
fn application_stopped_returns_ok() {
    let mut context = ProcessContext::new();
    let result = bif_application_stopped(&[], &mut context);
    assert_eq!(result, Ok(Term::atom(Atom::OK)));
}

#[test]
fn application_stopped_rejects_args() {
    let mut context = ProcessContext::new();
    let result = bif_application_stopped(&[Term::atom(Atom::OK)], &mut context);
    assert!(result.is_err());
}

#[test]
fn supervisor_start_link_rejects_wrong_arity() {
    let mut context = ProcessContext::new();
    let result = bif_supervisor_start_link(&[], &mut context);
    assert!(result.is_err());
}

#[test]
fn register_otp_stubs_registers_all_entries() {
    let atom_table = AtomTable::with_common_atoms();
    init_otp_atoms(&atom_table);
    let registry = BifRegistryImpl::new();

    register_otp_stubs(&registry, &atom_table).expect("otp stub registration");

    let gleam_otp_ext = atom_table.intern("gleam_otp_external");
    let app_stopped = atom_table.intern("application_stopped");
    assert!(
        registry.lookup(gleam_otp_ext, app_stopped, 0).is_some(),
        "gleam_otp_external:application_stopped/0 should be registered"
    );

    let supervisor = atom_table.intern("supervisor");
    let start_link = atom_table.intern("start_link");
    assert!(
        registry.lookup(supervisor, start_link, 2).is_some(),
        "supervisor:start_link/2 should be registered"
    );

    let gleam_string = atom_table.intern("gleam@string");
    let inspect = atom_table.intern("inspect");
    assert!(
        registry.lookup(gleam_string, inspect, 1).is_some(),
        "gleam@string:inspect/1 should be registered"
    );

    let os = atom_table.intern("os");
    let getenv = atom_table.intern("getenv");
    assert!(
        registry.lookup(os, getenv, 0).is_some(),
        "os:getenv/0 should be registered"
    );
}

#[test]
fn register_otp_stubs_rejects_duplicate_registration() {
    let atom_table = AtomTable::with_common_atoms();
    init_otp_atoms(&atom_table);
    let registry = BifRegistryImpl::new();

    register_otp_stubs(&registry, &atom_table).expect("first");
    assert!(register_otp_stubs(&registry, &atom_table).is_err());
}

#[test]
fn dynamic_int_returns_ok_for_integers() {
    let mut process = Process::new(1, 128);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);
    let result = gleam_stubs::bif_dynamic_int(&[Term::small_int(42)], &mut context);
    assert!(result.is_ok());
}

#[test]
fn dynamic_int_returns_error_for_atoms() {
    let mut process = Process::new(1, 128);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);
    let result = gleam_stubs::bif_dynamic_int(&[Term::atom(Atom::OK)], &mut context);
    assert!(result.is_ok());
}

#[test]
fn os_getenv_0_returns_non_empty_environment_list() {
    let mut process = Process::new(1, 262_144);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);

    let result = erlang_stubs::bif_os_getenv_0(&[], &mut context).expect("environment list");
    let variables = list_terms(result);
    assert!(!variables.is_empty());
    assert!(
        variables
            .into_iter()
            .all(|variable| BinaryRef::new(variable).is_some())
    );
}

#[test]
fn os_getenv_returns_binary_values_and_false_for_missing() {
    let mut process = Process::new(1, 4096);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);

    let key = context.alloc_binary(b"PATH").expect("key binary");
    let path = erlang_stubs::bif_os_getenv_1(&[key], &mut context).expect("PATH lookup");
    let bytes = BinaryRef::new(path).expect("PATH value should be binary");
    assert!(!bytes.is_empty());

    let missing = context
        .alloc_binary(b"BEAMR_TEST_NONEXISTENT_VAR")
        .expect("missing key binary");
    assert_eq!(
        erlang_stubs::bif_os_getenv_1(&[missing], &mut context),
        Ok(Term::atom(Atom::FALSE))
    );
    assert!(erlang_stubs::bif_os_getenv_1(&[Term::small_int(1)], &mut context).is_err());
}

#[test]
fn os_putenv_and_unsetenv_round_trip() {
    let mut process = Process::new(1, 4096);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);
    let key_name = b"BEAMR_TEST_B170_PUTENV";
    let key = context.alloc_binary(key_name).expect("key binary");
    let value = context.alloc_binary(b"hello").expect("value binary");
    let previous = std::env::var("BEAMR_TEST_B170_PUTENV").ok();

    assert_eq!(
        erlang_stubs::bif_os_putenv(&[key, value], &mut context),
        Ok(Term::atom(Atom::TRUE))
    );
    let lookup_key = context.alloc_binary(key_name).expect("lookup key binary");
    let lookup = erlang_stubs::bif_os_getenv_1(&[lookup_key], &mut context).expect("lookup");
    assert_eq!(binary_bytes(lookup), b"hello");

    let unset_key = context.alloc_binary(key_name).expect("unset key binary");
    assert_eq!(
        erlang_stubs::bif_os_unsetenv(&[unset_key], &mut context),
        Ok(Term::atom(Atom::TRUE))
    );
    let missing_key = context.alloc_binary(key_name).expect("missing key binary");
    assert_eq!(
        erlang_stubs::bif_os_getenv_1(&[missing_key], &mut context),
        Ok(Term::atom(Atom::FALSE))
    );
    assert!(erlang_stubs::bif_os_putenv(&[Term::small_int(1), value], &mut context).is_err());

    if let Some(previous) = previous {
        let restore_key = context.alloc_binary(key_name).expect("restore key");
        let restore_value = context
            .alloc_binary(previous.as_bytes())
            .expect("restore value");
        assert_eq!(
            erlang_stubs::bif_os_putenv(&[restore_key, restore_value], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
    }
}

#[test]
fn os_type_returns_platform_tuple() {
    let atom_table = Arc::new(AtomTable::with_common_atoms());
    init_otp_atoms(&atom_table);
    let mut process = Process::new(1, 128);
    let mut context = ProcessContext::new();
    context.set_atom_table(Some(atom_table.clone()));
    context.attach_process(&mut process, 0);

    let result = erlang_stubs::bif_os_type(&[], &mut context).expect("os:type");
    let tuple = Tuple::new(result).expect("os:type tuple");
    assert_eq!(tuple.arity(), 2);
    if cfg!(target_os = "macos") {
        assert_eq!(
            tuple.get(0).and_then(Term::as_atom),
            Some(atom_table.intern("unix"))
        );
        assert_eq!(
            tuple.get(1).and_then(Term::as_atom),
            Some(atom_table.intern("darwin"))
        );
    } else if cfg!(target_os = "linux") {
        assert_eq!(
            tuple.get(0).and_then(Term::as_atom),
            Some(atom_table.intern("unix"))
        );
        assert_eq!(
            tuple.get(1).and_then(Term::as_atom),
            Some(atom_table.intern("linux"))
        );
    } else if cfg!(target_os = "windows") {
        assert_eq!(
            tuple.get(0).and_then(Term::as_atom),
            Some(atom_table.intern("win32"))
        );
        assert_eq!(
            tuple.get(1).and_then(Term::as_atom),
            Some(atom_table.intern("nt"))
        );
    }
}

#[test]
fn code_priv_dir_resolves_sibling_priv_for_loaded_filesystem_module() {
    let atom_table = Arc::new(AtomTable::with_common_atoms());
    init_otp_atoms(&atom_table);
    let app = atom_table.intern("beamr_b170_app");
    let app_dir = unique_test_dir("beamr_b170_priv_dir");
    let ebin_dir = app_dir.join("ebin");
    let priv_dir = app_dir.join("priv");
    std::fs::create_dir_all(&ebin_dir).expect("create ebin");
    std::fs::create_dir_all(&priv_dir).expect("create priv");
    let beam_path = ebin_dir.join("beamr_b170_app.beam");
    std::fs::write(&beam_path, []).expect("create beam placeholder");

    let mut process = Process::new(1, 4096);
    let mut context = ProcessContext::new();
    context.set_atom_table(Some(atom_table));
    context.set_code_management_facility(Some(Arc::new(MockCodeFacility::with_origin(
        app,
        ModuleOrigin::Filesystem(beam_path),
    ))));
    context.attach_process(&mut process, 0);

    let result =
        erlang_stubs::bif_code_priv_dir(&[Term::atom(app)], &mut context).expect("code:priv_dir");
    assert_eq!(binary_bytes(result), priv_dir.to_string_lossy().as_bytes());
    assert!(erlang_stubs::bif_code_priv_dir(&[Term::small_int(1)], &mut context).is_err());

    std::fs::remove_dir_all(app_dir).expect("remove temp app dir");
}

#[test]
fn code_priv_dir_returns_error_bad_name_for_missing_app() {
    let atom_table = Arc::new(AtomTable::with_common_atoms());
    init_otp_atoms(&atom_table);
    let missing = atom_table.intern("missing_app");
    let mut process = Process::new(1, 1024);
    let mut context = ProcessContext::new();
    context.set_atom_table(Some(atom_table.clone()));
    context.set_code_management_facility(Some(Arc::new(MockCodeFacility::default())));
    context.attach_process(&mut process, 0);

    let result = erlang_stubs::bif_code_priv_dir(&[Term::atom(missing)], &mut context)
        .expect("bad_name tuple");
    let tuple = Tuple::new(result).expect("error tuple");
    assert_eq!(tuple.get(0), Some(Term::atom(Atom::ERROR)));
    assert_eq!(
        tuple.get(1).and_then(Term::as_atom),
        Some(atom_table.intern("bad_name"))
    );
}

#[test]
fn string_split_preserves_binary_and_list_representations() {
    let mut process = Process::new(1, 4096);
    let mut context = ProcessContext::new();
    context.attach_process(&mut process, 0);

    let input = context.alloc_binary(b"a.b.c").expect("input");
    let pattern = context.alloc_binary(b".").expect("pattern");
    let result = erlang_stubs::bif_string_split(&[input, pattern], &mut context).expect("split");
    let parts = list_terms(result);
    assert_eq!(parts.len(), 2);
    assert_eq!(binary_bytes(parts[0]), b"a");
    assert_eq!(binary_bytes(parts[1]), b"b.c");

    let no_match_input = context.alloc_binary(b"hello").expect("no match input");
    let no_match_pattern = context.alloc_binary(b".").expect("no match pattern");
    let no_match =
        erlang_stubs::bif_string_split(&[no_match_input, no_match_pattern], &mut context)
            .expect("no match split");
    assert_eq!(list_terms(no_match), vec![no_match_input]);

    let empty = context.alloc_binary(b"").expect("empty input");
    let dot = context.alloc_binary(b".").expect("dot");
    let empty_result =
        erlang_stubs::bif_string_split(&[empty, dot], &mut context).expect("empty no match");
    assert_eq!(list_terms(empty_result), vec![empty]);

    let list_input = byte_list(&mut context, b"a.b");
    let list_pattern = byte_list(&mut context, b".");
    let list_result = erlang_stubs::bif_string_split(&[list_input, list_pattern], &mut context)
        .expect("list split");
    let list_parts = list_terms(list_result);
    assert_eq!(list_bytes(list_parts[0]), b"a");
    assert_eq!(list_bytes(list_parts[1]), b"b");
    assert!(erlang_stubs::bif_string_split(&[Term::small_int(1), pattern], &mut context).is_err());
}

#[test]
fn ensure_all_started_reports_loaded_and_missing_modules() {
    let atom_table = Arc::new(AtomTable::with_common_atoms());
    init_otp_atoms(&atom_table);
    let loaded = atom_table.intern("loaded_app");
    let missing = atom_table.intern("missing_app");
    let mut process = Process::new(1, 4096);
    let mut context = ProcessContext::new();
    context.set_atom_table(Some(atom_table.clone()));
    context.set_code_management_facility(Some(Arc::new(MockCodeFacility::with_origin(
        loaded,
        ModuleOrigin::Preloaded,
    ))));
    context.attach_process(&mut process, 0);

    let ok = erlang_stubs::bif_ensure_all_started(&[Term::atom(loaded)], &mut context)
        .expect("loaded result");
    let ok_tuple = Tuple::new(ok).expect("ok tuple");
    assert_eq!(ok_tuple.get(0), Some(Term::atom(Atom::OK)));
    assert_eq!(
        list_terms(ok_tuple.get(1).expect("started app list")),
        vec![Term::atom(loaded)]
    );

    let error = erlang_stubs::bif_ensure_all_started(&[Term::atom(missing)], &mut context)
        .expect("missing result");
    let error_tuple = Tuple::new(error).expect("error tuple");
    assert_eq!(error_tuple.get(0), Some(Term::atom(Atom::ERROR)));
    let reason = Tuple::new(error_tuple.get(1).expect("reason tuple")).expect("reason tuple");
    assert_eq!(reason.get(0), Some(Term::atom(missing)));
    let inner = Tuple::new(reason.get(1).expect("inner tuple")).expect("inner tuple");
    assert_eq!(
        inner.get(0).and_then(Term::as_atom),
        Some(atom_table.intern("not_loaded"))
    );
    assert_eq!(inner.get(1), Some(Term::atom(missing)));
    assert!(erlang_stubs::bif_ensure_all_started(&[Term::small_int(1)], &mut context).is_err());
}

#[test]
fn erlang_not_negates_booleans() {
    use crate::native::gate3_bifs::bif_not;

    let mut context = ProcessContext::new();
    assert_eq!(
        bif_not(&[Term::atom(Atom::TRUE)], &mut context),
        Ok(Term::atom(Atom::FALSE))
    );
    assert_eq!(
        bif_not(&[Term::atom(Atom::FALSE)], &mut context),
        Ok(Term::atom(Atom::TRUE))
    );
    assert!(bif_not(&[Term::atom(Atom::OK)], &mut context).is_err());
}

#[test]
fn erlang_length_counts_empty_list() {
    use crate::native::gate3_bifs::bif_length;

    let mut context = ProcessContext::new();
    assert_eq!(
        bif_length(&[Term::NIL], &mut context),
        Ok(Term::small_int(0))
    );
}

#[derive(Default)]
struct MockCodeFacility {
    origins: HashMap<Atom, ModuleOrigin>,
}

impl MockCodeFacility {
    fn with_origin(module: Atom, origin: ModuleOrigin) -> Self {
        Self {
            origins: HashMap::from([(module, origin)]),
        }
    }
}

impl CodeManagementFacility for MockCodeFacility {
    fn load_module(&self, _bytes: &[u8]) -> Result<HotLoadResult, LoadError> {
        unimplemented!("not needed by OTP stub tests")
    }

    fn purge_module(&self, _module: Atom) -> Result<PurgeResult, PurgeError> {
        unimplemented!("not needed by OTP stub tests")
    }

    fn delete_module(&self, _module: Atom) -> bool {
        unimplemented!("not needed by OTP stub tests")
    }

    fn check_old_code(&self, _module: Atom) -> bool {
        false
    }

    fn check_process_code(&self, _pid: u64, _module: Atom) -> bool {
        false
    }

    fn module_origin(&self, module: Atom) -> Option<ModuleOrigin> {
        self.origins.get(&module).cloned()
    }

    fn all_loaded_modules(&self) -> Vec<(Atom, ModuleOrigin)> {
        self.origins
            .iter()
            .map(|(module, origin)| (*module, origin.clone()))
            .collect()
    }
}

fn binary_bytes(term: Term) -> &'static [u8] {
    BinaryRef::new(term).expect("binary term").as_bytes()
}

fn byte_list(context: &mut ProcessContext, bytes: &[u8]) -> Term {
    let elements: Vec<_> = bytes
        .iter()
        .map(|byte| Term::small_int(i64::from(*byte)))
        .collect();
    context.alloc_list(&elements).expect("byte list")
}

fn list_terms(term: Term) -> Vec<Term> {
    let mut terms = Vec::new();
    let mut current = term;
    while !current.is_nil() {
        let cons = Cons::new(current).expect("proper list");
        terms.push(cons.head());
        current = cons.tail();
    }
    terms
}

fn list_bytes(term: Term) -> Vec<u8> {
    list_terms(term)
        .into_iter()
        .map(|term| u8::try_from(term.as_small_int().expect("byte integer")).expect("u8 byte"))
        .collect()
}

fn unique_test_dir(prefix: &str) -> std::path::PathBuf {
    std::env::temp_dir().join(format!(
        "{prefix}_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock after epoch")
            .as_nanos()
    ))
}

fn attached_context(process: &mut Process) -> ProcessContext<'_> {
    let mut context = ProcessContext::new();
    context.set_atom_table(Some(std::sync::Arc::new(AtomTable::with_common_atoms())));
    context.attach_process(process, 0);
    context
}

fn closure(process: &mut Process, arity: u8, unique_id: u64) -> Term {
    let heap = process.heap_mut().alloc_slice(7).expect("closure heap");
    write_closure(heap, Atom::OK, 0, arity, 1, unique_id, &[]).expect("closure")
}

#[test]
fn option_map_some_sets_trampoline_and_resume_wraps_some() {
    let mut process = Process::new(1, 512);
    let fun = closure(&mut process, 1, 0x201);
    let mut context = attached_context(&mut process);
    let some = context
        .alloc_tuple(&[Term::atom(Atom::OK), Term::small_int(1)])
        .expect("some tuple");

    let placeholder = gleam_stubs::bif_option_map(&[some, fun], &mut context).expect("map some");
    assert_eq!(placeholder, Term::NIL);
    let request = context.take_trampoline().expect("option trampoline");
    assert_eq!(request.fun, fun);
    assert_eq!(request.args, vec![Term::small_int(1)]);
    let Some(NativeContinuation::GleamOption(state)) = request.continuation else {
        panic!("expected option continuation");
    };
    let done =
        gleam_stubs::resume_gleam_option_continuation(state, Term::small_int(2), &mut context)
            .expect("option resume");
    let ContinuationStep::Done(result) = done else {
        panic!("expected done");
    };
    let tuple = Tuple::new(result).expect("some result");
    assert_eq!(tuple.get(0), Some(Term::atom(Atom::OK)));
    assert_eq!(tuple.get(1), Some(Term::small_int(2)));
}

#[test]
fn option_map_none_returns_without_trampoline() {
    let mut process = Process::new(1, 512);
    let fun = closure(&mut process, 1, 0x202);
    let mut context = attached_context(&mut process);

    let result = gleam_stubs::bif_option_map(&[Term::atom(Atom::NIL), fun], &mut context);
    assert_eq!(result, Ok(Term::atom(Atom::NIL)));
    assert!(!context.has_trampoline());
}

#[test]
fn result_map_error_trampolines_only_error_and_wraps_result() {
    let mut process = Process::new(1, 512);
    let fun = closure(&mut process, 1, 0x203);
    let mut context = attached_context(&mut process);
    let error = context
        .alloc_tuple(&[Term::atom(Atom::ERROR), Term::atom(Atom::BADARG)])
        .expect("error tuple");

    let placeholder =
        gleam_stubs::bif_result_map_error(&[error, fun], &mut context).expect("map_error error");
    assert_eq!(placeholder, Term::NIL);
    let request = context.take_trampoline().expect("result trampoline");
    assert_eq!(request.args, vec![Term::atom(Atom::BADARG)]);
    let Some(NativeContinuation::GleamResult(GleamResultState::MapError)) = request.continuation
    else {
        panic!("expected map_error continuation");
    };

    let done = resume_gleam_result_continuation(
        GleamResultState::MapError,
        Term::small_int(7),
        &mut context,
    )
    .expect("map_error resume");
    let ContinuationStep::Done(result) = done else {
        panic!("expected done");
    };
    let tuple = Tuple::new(result).expect("mapped error");
    assert_eq!(tuple.get(0), Some(Term::atom(Atom::ERROR)));
    assert_eq!(tuple.get(1), Some(Term::small_int(7)));

    let ok = context
        .alloc_tuple(&[Term::atom(Atom::OK), Term::small_int(42)])
        .expect("ok tuple");
    assert_eq!(
        gleam_stubs::bif_result_map_error(&[ok, fun], &mut context),
        Ok(ok)
    );
    assert!(!context.has_trampoline());
}

#[test]
fn result_then_trampolines_only_ok_and_returns_closure_result() {
    let mut process = Process::new(1, 512);
    let fun = closure(&mut process, 1, 0x204);
    let mut context = attached_context(&mut process);
    let ok = context
        .alloc_tuple(&[Term::atom(Atom::OK), Term::small_int(1)])
        .expect("ok tuple");

    let placeholder = gleam_stubs::bif_result_then(&[ok, fun], &mut context).expect("then ok");
    assert_eq!(placeholder, Term::NIL);
    let request = context.take_trampoline().expect("then trampoline");
    assert_eq!(request.args, vec![Term::small_int(1)]);
    assert!(matches!(
        request.continuation,
        Some(NativeContinuation::GleamResult(GleamResultState::Then))
    ));

    let error = context
        .alloc_tuple(&[Term::atom(Atom::ERROR), Term::atom(Atom::BADARG)])
        .expect("error tuple");
    assert_eq!(
        gleam_stubs::bif_result_then(&[error, fun], &mut context),
        Ok(error)
    );
    assert!(!context.has_trampoline());
}

#[test]
fn intensity_tracker_add_event_increments_and_tags_by_previous_count() {
    let mut process = Process::new(1, 512);
    let mut context = attached_context(&mut process);
    let tracker = gleam_stubs::bif_intensity_tracker_new(
        &[Term::small_int(2), Term::small_int(1000)],
        &mut context,
    )
    .expect("tracker new");
    let result = gleam_stubs::bif_intensity_tracker_add_event(&[tracker], &mut context)
        .expect("tracker event");
    let tuple = Tuple::new(result).expect("ok tuple");
    assert_eq!(tuple.get(0), Some(Term::atom(Atom::OK)));
    let updated = Tuple::new(tuple.get(1).expect("updated tracker")).expect("updated tuple");
    assert_eq!(updated.get(0), Some(Term::small_int(1)));

    let saturated = context
        .alloc_tuple(&[
            Term::small_int(2),
            Term::small_int(2),
            Term::small_int(1000),
            Term::NIL,
        ])
        .expect("saturated tracker");
    let result = gleam_stubs::bif_intensity_tracker_add_event(&[saturated], &mut context)
        .expect("tracker error");
    let tuple = Tuple::new(result).expect("error tuple");
    assert_eq!(tuple.get(0), Some(Term::atom(Atom::ERROR)));
    assert!(!context.has_trampoline());
}