beamr 0.19.1

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
//! Process-supporting value types — exit reasons, exceptions, monitors,
//! scheduling metadata, and JIT runtime state.

use std::fmt;
use std::sync::Arc;

use crate::atom::{Atom, AtomTable};
use crate::module::Module;
use crate::term::{
    Term,
    boxed::{Cons, Tuple},
    format::format_term,
};

/// Per-process monitor metadata.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Monitor {
    reference: u64,
    watcher: u64,
    target: u64,
}

impl Monitor {
    /// Create monitor metadata for `watcher` observing `target`.
    #[must_use]
    pub const fn new(reference: u64, watcher: u64, target: u64) -> Self {
        Self {
            reference,
            watcher,
            target,
        }
    }

    /// Unique monitor reference id.
    #[must_use]
    pub const fn reference(self) -> u64 {
        self.reference
    }

    /// PID that owns the monitor and receives DOWN messages.
    #[must_use]
    pub const fn watcher(self) -> u64 {
        self.watcher
    }

    /// PID being observed by the monitor.
    #[must_use]
    pub const fn target(self) -> u64 {
        self.target
    }
}

/// Current code location for a process.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct CodePosition {
    /// Current module.
    pub module: Atom,
    /// Current instruction pointer in `module`.
    pub instruction_pointer: usize,
}

/// A process register addressed by BEAM X/Y register operands.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Register {
    /// X register index.
    X(u16),
    /// Y register index in the current stack frame.
    Y(u16),
}

/// Kind of exception handler installed on a process.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum HandlerKind {
    /// BEAM `try` handler exposing class/reason/stacktrace through `try_case`.
    Try,
    /// BEAM `catch` handler wrapping the raised value in catch-compatible form.
    Catch,
}

/// A try/catch handler installed by BEAM try-family opcodes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ExceptionHandler {
    /// Whether this handler was installed by `try` or `catch`.
    pub kind: HandlerKind,
    /// Stack depth to restore before transferring control to this handler.
    pub stack_depth: usize,
    /// Label/IP to jump to when an exception is raised.
    pub catch_position: CodePosition,
    /// Destination register supplied by the decoded try/catch instruction.
    pub destination: Register,
}

/// Exception payload propagated through try handlers.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Exception {
    /// Exception class, normally atom(error).
    pub class: Term,
    /// Exception reason term.
    pub reason: Term,
    /// Stacktrace term associated with the original raise.
    pub stacktrace: Term,
}

impl Exception {
    /// Format exception details for user-facing diagnostics using atom-name
    /// resolution from `atom_table`.
    #[must_use]
    pub fn format_with_atoms(&self, atom_table: &AtomTable) -> String {
        let mut output = format!(
            "{}: {}",
            format_term(self.class, atom_table),
            format_term(self.reason, atom_table)
        );

        if !self.stacktrace.is_nil() {
            append_stacktrace(&mut output, self.stacktrace, atom_table);
        }

        output
    }
}

fn append_stacktrace(output: &mut String, stacktrace: Term, atom_table: &AtomTable) {
    let mut current = stacktrace;
    let mut appended_frame = false;

    loop {
        if current.is_nil() {
            return;
        }

        let Some(cons) = Cons::new(current) else {
            if !appended_frame {
                output.push_str("\n  stacktrace: ");
                output.push_str(&format_term(stacktrace, atom_table));
            } else {
                output.push_str("\n  at ");
                output.push_str(&format_term(current, atom_table));
            }
            return;
        };

        output.push_str("\n  at ");
        output.push_str(&format_stacktrace_frame(cons.head(), atom_table));
        appended_frame = true;
        current = cons.tail();
    }
}

fn format_stacktrace_frame(frame: Term, atom_table: &AtomTable) -> String {
    let Some(tuple) = Tuple::new(frame) else {
        return format_term(frame, atom_table);
    };

    if tuple.arity() != 4 {
        return format_term(frame, atom_table);
    }

    let module = tuple
        .get(0)
        .map(|term| format_term(term, atom_table))
        .unwrap_or_else(|| "#<missing module>".to_owned());
    let function = tuple
        .get(1)
        .map(|term| format_term(term, atom_table))
        .unwrap_or_else(|| "#<missing function>".to_owned());
    let arity = tuple
        .get(2)
        .and_then(Term::as_small_int)
        .map(|value| value.to_string())
        .unwrap_or_else(|| {
            tuple
                .get(2)
                .map(|term| format_term(term, atom_table))
                .unwrap_or_else(|| "#<missing arity>".to_owned())
        });

    let mut formatted = format!("{module}:{function}/{arity}");
    if let Some(info) = tuple.get(3)
        && let Some(line) = stacktrace_line(info)
    {
        formatted.push(':');
        formatted.push_str(&line.to_string());
    }
    formatted
}

fn stacktrace_line(info: Term) -> Option<i64> {
    let mut current = info;
    loop {
        if current.is_nil() {
            return None;
        }
        let cons = Cons::new(current)?;
        let tuple = Tuple::new(cons.head())?;
        if tuple.arity() == 2 && tuple.get(0).and_then(Term::as_atom) == Some(Atom::LINE) {
            return tuple.get(1).and_then(Term::as_small_int);
        }
        current = cons.tail();
    }
}

/// Raw stack frame captured at raise time for later stacktrace construction.
#[derive(Clone, Debug)]
pub struct RawStackEntry {
    /// Pinned module version containing the instruction pointer.
    pub module: Arc<Module>,
    /// Instruction pointer within `module`.
    pub ip: usize,
    /// Optional module/function/arity metadata from a preceding `func_info`.
    pub mfa: Option<(Atom, Atom, u8)>,
    /// Precomputed source-location info for frames that do not map to an interpreted IP.
    pub location_info: Term,
    /// True when this entry represents a compiled frame rather than an interpreted IP.
    pub compiled: bool,
}

impl RawStackEntry {
    /// Resolves this frame's `(module, function, arity)` identity.
    ///
    /// The module comes from `mfa` whenever `mfa` is present, and only falls
    /// back to the pinned module's own name when it is absent. That ordering is
    /// load-bearing for compiled frames: a JIT frame records the identity of the
    /// function that was *compiled*, while `module` is merely wherever the
    /// process happened to be positioned when the frame was pushed. When
    /// compiled code from one module is entered from another, those two
    /// disagree, and taking the module from the pinned side splices one
    /// module's name onto another module's function — naming a function that
    /// does not exist in the module the frame claims.
    ///
    /// Interpreted frames are unaffected by construction: their `mfa` is
    /// derived by [`Module::mfa_at_ip`], which pairs the function with that same
    /// module's own name, so both sources always agree.
    #[must_use]
    pub fn identity(&self) -> (Atom, Atom, u8) {
        match self.mfa {
            Some((module, function, arity)) => (module, function, arity),
            None => match self.module.function_at_ip(self.ip) {
                Some((function, arity)) => (self.module.name, function, arity),
                None => (self.module.name, Atom::UNDEFINED, 0),
            },
        }
    }
}

/// Receive timeout state recorded while a process is waiting.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ReceiveTimeout {
    /// Instruction pointer to resume at if the receive timeout expires.
    pub timeout_position: CodePosition,
    /// Timeout duration in milliseconds.
    pub milliseconds: u64,
}

/// Reason a process exited.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ExitReason {
    /// Normal process completion.
    Normal,
    /// Untrappable kill exit.
    Kill,
    /// Terminal reason reported by a process that received `kill`.
    Killed,
    /// Placeholder error exit until error terms land.
    Error,
    /// Distribution connection to a linked or monitored remote process was lost.
    NoConnection,
    /// The target process was already dead when a distribution request
    /// (e.g. an inbound LINK) reached it.
    NoProc,
}

impl ExitReason {
    /// Atom representation used in EXIT and DOWN messages.
    #[must_use]
    pub const fn as_atom(self) -> Atom {
        match self {
            Self::Normal => Atom::NORMAL,
            Self::Kill => Atom::KILL,
            Self::Killed => Atom::KILLED,
            Self::Error => Atom::ERROR,
            Self::NoConnection => Atom::NOCONNECTION,
            Self::NoProc => Atom::NOPROC,
        }
    }

    /// Term representation used in EXIT and DOWN messages.
    #[must_use]
    pub const fn as_term(self) -> Term {
        Term::atom(self.as_atom())
    }
}

/// Transient runtime context installed while the interpreter is inside native JIT code.
#[cfg(feature = "jit")]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct JitRuntimeContext {
    /// Current module for import-table resolution.
    pub module: *const Module,
    /// Registry used by mixed-mode fallback calls.
    pub registry: *const crate::module::ModuleRegistry,
    /// Optional native-code cache used by helper-backed dynamic dispatch.
    pub jit_cache: *const crate::jit::JitCache,
    /// Native services used by mixed-mode fallback calls.
    pub services: *const crate::interpreter::NativeServices,
}

#[cfg(feature = "jit")]
impl JitRuntimeContext {
    /// Creates a runtime context from borrowed interpreter dispatch state.
    #[must_use]
    pub const fn new(
        module: *const Module,
        registry: *const crate::module::ModuleRegistry,
        jit_cache: *const crate::jit::JitCache,
        services: *const crate::interpreter::NativeServices,
    ) -> Self {
        Self {
            module,
            registry,
            jit_cache,
            services,
        }
    }
}

/// Out-of-band status set by native JIT helpers when a raw return word is not a normal term.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum JitStatus {
    /// The compiled function consumed the current reduction budget and yielded.
    Yield,
}

/// Stable identity for a PID hosted by another distribution node.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct RemotePid {
    /// Remote node atom.
    pub node: Atom,
    /// Remote process id number.
    pub pid_number: u64,
    /// Remote pid serial.
    pub serial: u64,
}

/// Lifecycle state for a process.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ProcessStatus {
    /// Allocated but not yet running.
    New,
    /// Currently runnable/running.
    Running,
    /// Yielded after exhausting or giving up a scheduler time slice.
    Yielded,
    /// Waiting for a message or timeout.
    Waiting,
    /// Paused by the scheduler hook; will be requeued or waited on resume.
    Suspended,
    /// Terminal state with exit reason.
    Exited(ExitReason),
}

/// BEAM process scheduling priority.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
pub enum Priority {
    /// Low-priority process.
    Low,
    /// Normal process priority.
    #[default]
    Normal,
    /// High-priority process.
    High,
    /// Maximum process priority.
    Max,
}

/// Process operation errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ProcessError {
    /// The requested status transition is not allowed by the lifecycle graph.
    InvalidStatusTransition {
        /// Current status.
        from: ProcessStatus,
        /// Requested next status.
        to: ProcessStatus,
    },
    /// The requested float register index is outside BEAM's fr0-fr15 range.
    InvalidFloatRegister {
        /// Requested float register index.
        index: u16,
    },
}

impl fmt::Display for ProcessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidStatusTransition { from, to } => {
                write!(
                    f,
                    "invalid process status transition from {from:?} to {to:?}"
                )
            }
            Self::InvalidFloatRegister { index } => {
                write!(f, "invalid float register index {index}")
            }
        }
    }
}

impl std::error::Error for ProcessError {}