beamr 0.18.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
//! Crate-wide error types for beamr.
//!
//! All runtime failures are represented as values, never panics.
//! Process-level errors become exit reasons; loader errors prevent
//! module registration; interpreter errors halt the faulting process.

use std::error::Error;
use std::fmt;

use crate::atom::AtomTable;
use crate::namespace::NamespaceId;
use crate::term::format::format_term;

/// Failures that can occur while loading and validating BEAM bytecode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadError {
    /// The input is not a valid BEAM file or uses an unsupported container shape.
    InvalidFormat,
    /// A required BEAM chunk is absent from the module being loaded.
    MissingChunk(String),
    /// Bytecode or chunk payload decoding failed.
    DecodeError(String),
    /// Decoded module contents failed semantic validation.
    ValidationError(String),
    /// A second old code version would be created before the existing old
    /// version was purged.
    OldCodeStillRunning,
    /// The requested module namespace does not exist.
    UnknownNamespace { namespace: NamespaceId },
}

impl fmt::Display for LoadError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat => formatter.write_str("invalid BEAM file format"),
            Self::MissingChunk(chunk) => write!(formatter, "missing required BEAM chunk: {chunk}"),
            Self::DecodeError(message) => {
                write!(formatter, "failed to decode BEAM data: {message}")
            }
            Self::ValidationError(message) => {
                write!(formatter, "BEAM module validation failed: {message}")
            }
            Self::OldCodeStillRunning => formatter
                .write_str("old code is still running and must be purged before loading again"),
            Self::UnknownNamespace { namespace } => {
                write!(formatter, "unknown module namespace {:?}", namespace)
            }
        }
    }
}

impl Error for LoadError {}

/// The non-`Native` resolution state a guard/BIF import landed in when the
/// guard-BIF dispatch demanded a native entry and did not get one.
///
/// Guard and BIF opcodes can only call a Rust [`Native`](crate::module::ResolvedImportTarget::Native)
/// entry; every other resolution shape is a composition or bytecode-shape
/// error at the dispatch seam. This enum names WHICH shape so the refusal can
/// say so (see [`ExecError::GuardBifUnavailable`]). It carries no payload — the
/// loader's denied/unresolved report is the detail channel — which keeps it
/// `Copy` and its `Display` a single fixed word.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum GuardBifResolution {
    /// At load time, neither the native BIF registry nor the module registry
    /// held the target.
    Deferred,
    /// Registered as a native BIF but capability-denied at load time.
    Denied,
    /// Resolved to a bytecode export — illegal in guard/BIF position.
    CodeTarget,
    /// The target module was loaded but did not export the requested MFA.
    Unresolved,
}

impl GuardBifResolution {
    /// The one-word resolution label used in the refusal's one-log-line form.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Deferred => "Deferred",
            Self::Denied => "Denied",
            Self::CodeTarget => "CodeTarget",
            Self::Unresolved => "Unresolved",
        }
    }

    /// The fixed diagnostic hint for this resolution arm.
    #[must_use]
    pub const fn hint(self) -> &'static str {
        match self {
            // BOTH conjuncts are load-time facts, and both say so. Imports
            // resolve exactly once, at load; the runtime BIF registry is a
            // different object that may well hold the entry, and a `Deferred`
            // import is late-bound against the LIVE module registry on the call
            // path, so the target module may well be loaded by now. Stamping
            // only one clause leaves the other reading as a present-tense claim
            // this mint point cannot substantiate.
            Self::Deferred => {
                "the LOAD-TIME native BIF registry had no entry and the LOAD-TIME module \
                 registry did not hold the target"
            }
            Self::Denied => "registered but capability-denied at load",
            Self::CodeTarget => "resolved to a bytecode export — guard BIFs must be native",
            Self::Unresolved => "target module loaded but export missing",
        }
    }
}

impl fmt::Display for GuardBifResolution {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.label())
    }
}

/// Whether a native BIF registry was reachable from the execution context that
/// refused a guard/BIF import.
///
/// Says nothing about what such a registry CONTAINS: no emptiness predicate
/// exists on [`BifRegistry`](crate::native::BifRegistry), and the registry an
/// import bound against at LOAD time is a different object from the one wired
/// at runtime, with no provenance recorded on
/// [`ResolvedImport`](crate::module::ResolvedImport) to relate them. Each arm is
/// true by construction at the refusal's mint point and nothing more is claimed,
/// because a stronger claim could accuse a correctly-composed caller — which is
/// how the attribution this type exists to repair went wrong in the first place.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum RuntimeBifRegistryState {
    /// No native services bundle reached this dispatch.
    Absent,
    /// A services bundle reached it, carrying no BIF registry.
    Unwired,
    /// A BIF registry was wired into this execution.
    Wired,
}

impl RuntimeBifRegistryState {
    /// The one-word label used in the refusal's one-log-line form.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Absent => "Absent",
            Self::Unwired => "Unwired",
            Self::Wired => "Wired",
        }
    }
}

impl fmt::Display for RuntimeBifRegistryState {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.label())
    }
}

/// The fixed clause every guard-BIF refusal carries after its runtime state.
///
/// A POINTER at the construction site, never a claim about the caller's
/// registry. The `NativeBifs::none()` sentence is load-bearing rather than
/// decorative: `Wired` is what every scheduler-path refusal renders — a
/// scheduler declared with no natives wires the registry it minted — so the
/// state read alone would sound like absolution in exactly the composition that
/// is at fault.
///
/// The constructor family it names is BUILD-DEPENDENT, because the constructor
/// family IS. `NativeBifs` and the threaded `Scheduler` exist only under the
/// `threads` feature; the cooperative build — the one `beamr-wasm` ships, and
/// the one that hands this line to JavaScript as the `detail` field of its
/// reason mapping — has neither. Its scheduler is `WasmScheduler`, whose `new`
/// already takes the registry as a required argument. A pointer at a type the
/// embedder's build does not export is not a pointer, so each build names the
/// family it actually has.
#[cfg(feature = "threads")]
const GUARD_BIF_CONSTRUCTION_POINTER: &str = "imports bind at LOAD time against the loader's \
     registry, and a scheduler declared NativeBifs::none() also reports Wired because none() \
     wires a registry with no BIFs registered; schedulers declare natives at construction (see \
     NativeBifs::none / NativeBifs::registry)";

/// The cooperative build's form of [`GUARD_BIF_CONSTRUCTION_POINTER`].
///
/// Same clause, same standard, pointed at the constructor this build has:
/// `WasmScheduler::new` takes its `bif_registry` as a required argument, so the
/// declaration is the argument itself and there is no `none()` to name. The
/// non-exculpatory reading still needs saying — a registry with no BIFs
/// registered is a wired registry — because `Wired` is what this path renders
/// too.
#[cfg(not(feature = "threads"))]
const GUARD_BIF_CONSTRUCTION_POINTER: &str = "imports bind at LOAD time against the loader's \
     registry, and a scheduler wired with a registry that has no BIFs registered also reports \
     Wired; schedulers declare natives at construction (see WasmScheduler::new's bif_registry \
     argument)";

/// Render the guard-BIF refusal's one-log-line from already-resolved atom names.
///
/// Both rendering channels ([`fmt::Display`] and
/// [`ExecError::format_with_atoms`]) go through here so they cannot drift apart:
/// they differ only in which atom table resolved the MFA.
fn render_guard_bif_unavailable(
    module: &str,
    function: &str,
    arity: u8,
    resolution: GuardBifResolution,
    runtime_natives: RuntimeBifRegistryState,
) -> String {
    format!(
        "guard bif {module}:{function}/{arity} unavailable: import resolved {} ({}); \
         runtime natives: {}{GUARD_BIF_CONSTRUCTION_POINTER}",
        resolution.label(),
        resolution.hint(),
        runtime_natives.label(),
    )
}

/// Failures that can occur while executing BEAM code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecError {
    /// A pattern match failed.
    Badmatch,
    /// No function clause matched the provided arguments.
    FunctionClause,
    /// The target module, function, or arity is undefined.
    Undef {
        /// Module atom.
        module: crate::atom::Atom,
        /// Function atom.
        function: crate::atom::Atom,
        /// Function arity.
        arity: u8,
    },
    /// An arithmetic operation failed.
    Badarith,
    /// An argument or term type was invalid for the opcode.
    Badarg,
    /// Attempted to call a term that is not a closure.
    Badfun { term: crate::term::Term },
    /// Attempted to call a closure with the wrong number of arguments.
    Badarity {
        fun: crate::term::Term,
        args: Vec<crate::term::Term>,
    },
    /// User code exited explicitly.
    UserExit,
    /// Decoded instruction opcode is not known to the VM.
    UnknownOpcode { opcode: u8 },
    /// Decoded instruction is valid but belongs to a future implementation gate.
    UnsupportedOpcode { name: &'static str },
    /// Operand shape or value was invalid for the opcode.
    InvalidOperand(&'static str),
    /// A local label could not be resolved to an instruction pointer.
    InvalidLabel { label: u32 },
    /// Import table entry was missing.
    InvalidImport { index: usize },
    /// A heap check failed and GC must run before continuing. No longer
    /// raised: binary opcodes reserve heap space and collect directly via
    /// `gc::ensure_space`. Kept because removing a variant from this
    /// exhaustively-matchable enum would break downstream matches.
    GcNeeded { requested: usize, available: usize },
    /// A boxed literal cannot be materialized by the no-allocation move opcode.
    UnsupportedLiteral,
    /// Stack operation failed.
    Stack(crate::process::stack::StackError),
    /// Heap allocation failed.
    HeapFull { requested: usize, available: usize },
    /// A distributed send could not reach the target node.
    NoConnection,
    /// An ancillary VM service the process tried to use is disabled on this
    /// scheduler (spec §3.2, Q-B). Distinct from [`Badarg`](Self::Badarg) so the
    /// embedder can tell "this scheduler was composed without that service"
    /// apart from a genuine bad argument; `service` is the inventory label of
    /// the refused service (e.g. `"dirty-cpu"`). The refusal happens before any
    /// suspension/queue side effect, so the calling process terminates promptly
    /// rather than parking forever with no worker to wake it.
    ServiceUnavailable {
        /// Inventory label of the disabled service.
        service: &'static str,
    },
    /// A guard/BIF opcode dispatched an import that did not resolve to a native
    /// entry. Extends the [`ServiceUnavailable`](Self::ServiceUnavailable)
    /// composition-honesty doctrine to the guard-BIF import seam: rather than a
    /// bare `InvalidOperand`, the refusal names the failing MFA AND the
    /// resolution state ([`GuardBifResolution`]) so an empty-registry
    /// composition (`erlang:'+'/2` resolving `Deferred`) is diagnosable from one
    /// log line instead of a multi-seat attribution. Same mint point, same
    /// process-fatal outcome, same fail-label handling as the operand refusals
    /// it replaces — only the error VALUE gains structure.
    ///
    /// The refusal points at the CONSTRUCTION site rather than accusing the
    /// module that happened to be executing: `runtime_natives` reports what was
    /// reachable at the dispatch, and the rendered line closes with a fixed
    /// pointer at the constructor family that declares a scheduler's natives.
    GuardBifUnavailable {
        /// Imported module atom.
        module: crate::atom::Atom,
        /// Imported function atom.
        function: crate::atom::Atom,
        /// Imported arity.
        arity: u8,
        /// The non-`Native` resolution state the import landed in.
        resolution: GuardBifResolution,
        /// Whether a native BIF registry was reachable at the refusal.
        runtime_natives: RuntimeBifRegistryState,
    },
    /// Replay mode reached a decision point that does not match the recorded log.
    ReplayMismatch(String),
}

impl fmt::Display for ExecError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Badmatch => formatter.write_str("pattern match failed"),
            Self::FunctionClause => formatter.write_str("no matching function clause"),
            Self::Undef {
                module,
                function,
                arity,
            } => {
                let fallback = AtomTable::with_common_atoms();
                write!(
                    formatter,
                    "undefined function {}:{}/{}",
                    fallback.resolve(*module).unwrap_or("#<unknown atom>"),
                    fallback.resolve(*function).unwrap_or("#<unknown atom>"),
                    arity
                )
            }
            Self::Badarith => formatter.write_str("arithmetic operation failed"),
            Self::Badarg => formatter.write_str("bad argument"),
            Self::Badfun { term } => {
                let fallback = AtomTable::with_common_atoms();
                write!(
                    formatter,
                    "bad function term {}",
                    format_term(*term, &fallback)
                )
            }
            Self::Badarity { fun, args } => {
                let fallback = AtomTable::with_common_atoms();
                let formatted_args = args
                    .iter()
                    .map(|arg| format_term(*arg, &fallback))
                    .collect::<Vec<_>>()
                    .join(", ");
                write!(
                    formatter,
                    "bad arity for function {} with args [{}]",
                    format_term(*fun, &fallback),
                    formatted_args
                )
            }
            Self::UserExit => formatter.write_str("process exited explicitly"),
            Self::UnknownOpcode { opcode } => write!(formatter, "unknown opcode {opcode}"),
            Self::UnsupportedOpcode { name } => write!(formatter, "unsupported opcode {name}"),
            Self::InvalidOperand(context) => write!(formatter, "invalid operand for {context}"),
            Self::InvalidLabel { label } => write!(formatter, "invalid code label {label}"),
            Self::InvalidImport { index } => write!(formatter, "invalid import index {index}"),
            Self::GcNeeded {
                requested,
                available,
            } => write!(
                formatter,
                "GC needed before allocating/checking {requested} heap words ({available} available)"
            ),
            Self::UnsupportedLiteral => formatter.write_str("unsupported boxed literal"),
            Self::Stack(error) => write!(formatter, "stack error: {error}"),
            Self::HeapFull {
                requested,
                available,
            } => write!(
                formatter,
                "heap full: requested {requested} words with {available} available"
            ),
            Self::NoConnection => formatter.write_str("distributed send failed: noconnection"),
            Self::ServiceUnavailable { service } => {
                write!(formatter, "scheduler service unavailable: {service}")
            }
            Self::GuardBifUnavailable {
                module,
                function,
                arity,
                resolution,
                runtime_natives,
            } => {
                let fallback = AtomTable::with_common_atoms();
                formatter.write_str(&render_guard_bif_unavailable(
                    fallback.resolve(*module).unwrap_or("#<unknown atom>"),
                    fallback.resolve(*function).unwrap_or("#<unknown atom>"),
                    *arity,
                    *resolution,
                    *runtime_natives,
                ))
            }
            Self::ReplayMismatch(message) => write!(formatter, "replay mismatch: {message}"),
        }
    }
}

impl ExecError {
    /// Format this execution error for user-facing diagnostics using atom-name
    /// resolution from `atom_table`.
    #[must_use]
    pub fn format_with_atoms(&self, atom_table: &AtomTable) -> String {
        match self {
            Self::Undef {
                module,
                function,
                arity,
            } => format!(
                "undefined function {}:{}/{}",
                atom_table.resolve(*module).unwrap_or("#<unknown atom>"),
                atom_table.resolve(*function).unwrap_or("#<unknown atom>"),
                arity
            ),
            Self::Badfun { term } => {
                format!("bad function term {}", format_term(*term, atom_table))
            }
            Self::Badarity { fun, args } => {
                let formatted_args = args
                    .iter()
                    .map(|arg| format_term(*arg, atom_table))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "bad arity for function {} with args [{}]",
                    format_term(*fun, atom_table),
                    formatted_args
                )
            }
            Self::GuardBifUnavailable {
                module,
                function,
                arity,
                resolution,
                runtime_natives,
            } => render_guard_bif_unavailable(
                atom_table.resolve(*module).unwrap_or("#<unknown atom>"),
                atom_table.resolve(*function).unwrap_or("#<unknown atom>"),
                *arity,
                *resolution,
                *runtime_natives,
            ),
            _ => self.to_string(),
        }
    }
}

impl Error for ExecError {}

#[cfg(any(feature = "threads", feature = "cooperative"))]
impl From<crate::replay::ReplayMismatch> for ExecError {
    fn from(error: crate::replay::ReplayMismatch) -> Self {
        Self::ReplayMismatch(error.to_string())
    }
}

impl From<crate::process::stack::StackError> for ExecError {
    fn from(error: crate::process::stack::StackError) -> Self {
        Self::Stack(error)
    }
}

impl From<crate::process::heap::HeapFull> for ExecError {
    fn from(error: crate::process::heap::HeapFull) -> Self {
        Self::HeapFull {
            requested: error.requested(),
            available: error.available(),
        }
    }
}

/// Top-level error type for beamr operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BeamrError {
    /// A module loading failure.
    Load(LoadError),
    /// A runtime execution failure.
    Exec(ExecError),
}

impl From<LoadError> for BeamrError {
    fn from(error: LoadError) -> Self {
        Self::Load(error)
    }
}

impl From<ExecError> for BeamrError {
    fn from(error: ExecError) -> Self {
        Self::Exec(error)
    }
}

impl fmt::Display for BeamrError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Load(error) => write!(formatter, "load error: {error}"),
            Self::Exec(error) => write!(formatter, "execution error: {error}"),
        }
    }
}

impl Error for BeamrError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Load(error) => Some(error),
            Self::Exec(error) => Some(error),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BeamrError, ExecError, LoadError};
    use crate::atom::{Atom, AtomTable};
    use crate::term::Term;
    use crate::term::boxed::{write_cons, write_tuple};

    #[test]
    fn load_error_display_is_human_readable() {
        let formatted = LoadError::MissingChunk("Atom".into()).to_string();

        assert!(!formatted.is_empty());
        assert!(formatted.contains("missing required BEAM chunk"));
        assert!(formatted.contains("Atom"));
    }

    #[test]
    fn exec_error_display_is_human_readable() {
        let formatted = ExecError::Badarith.to_string();

        assert!(!formatted.is_empty());
        assert!(formatted.contains("arithmetic"));
    }

    #[test]
    fn exec_error_format_with_atoms_resolves_undef_mfa() {
        let table = AtomTable::with_common_atoms();
        let module = table.intern("my_mod");
        let function = table.intern("my_fun");
        let error = ExecError::Undef {
            module,
            function,
            arity: 2,
        };

        assert_eq!(
            error.format_with_atoms(&table),
            "undefined function my_mod:my_fun/2"
        );
    }

    #[test]
    fn exec_error_format_with_atoms_formats_badfun_and_badarity_terms() {
        let table = AtomTable::with_common_atoms();
        let mut tuple_heap = [0_u64; 3];
        let fun = match write_tuple(&mut tuple_heap, &[Term::atom(Atom::OK), Term::small_int(1)]) {
            Some(term) => term,
            None => Term::NIL,
        };
        let mut args_heap = [0_u64; 2];
        let args = match write_cons(&mut args_heap, Term::atom(Atom::BADARG), Term::NIL) {
            Some(term) => term,
            None => Term::NIL,
        };

        assert_eq!(
            ExecError::Badfun { term: fun }.format_with_atoms(&table),
            "bad function term {ok, 1}"
        );
        assert_eq!(
            ExecError::Badarity {
                fun,
                args: vec![args],
            }
            .format_with_atoms(&table),
            "bad arity for function {ok, 1} with args [[badarg]]"
        );
    }

    #[test]
    fn beamr_error_wraps_load_errors() {
        let error = BeamrError::from(LoadError::InvalidFormat);

        assert!(matches!(error, BeamrError::Load(LoadError::InvalidFormat)));
        assert!(!error.to_string().is_empty());
    }

    #[test]
    fn beamr_error_wraps_exec_errors() {
        let error = BeamrError::from(ExecError::Badarith);

        assert!(matches!(error, BeamrError::Exec(ExecError::Badarith)));
        assert!(!error.to_string().is_empty());
    }
}