beamr 0.15.4

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
//! 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 {
    /// Not in the native BIF registry and the target module is not loaded.
    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 {
            Self::Deferred => {
                "native BIF registry has no entry and the target module is not loaded"
            }
            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())
    }
}

/// 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.
    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,
    },
    /// 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,
            } => {
                let fallback = AtomTable::with_common_atoms();
                write!(
                    formatter,
                    "guard bif {}:{}/{} unavailable: import resolved {} ({})",
                    fallback.resolve(*module).unwrap_or("#<unknown atom>"),
                    fallback.resolve(*function).unwrap_or("#<unknown atom>"),
                    arity,
                    resolution.label(),
                    resolution.hint(),
                )
            }
            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,
            } => format!(
                "guard bif {}:{}/{} unavailable: import resolved {} ({})",
                atom_table.resolve(*module).unwrap_or("#<unknown atom>"),
                atom_table.resolve(*function).unwrap_or("#<unknown atom>"),
                arity,
                resolution.label(),
                resolution.hint(),
            ),
            _ => 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());
    }
}