byteflow/natives.rs
1//! Standard native (FFI) table shipped with the facade.
2//!
3//! # Why Message make/unpack lives here (not as new opcodes)
4//!
5//! [`crate::Value::Message`] is already a first-class wire/register value
6//! (ABI v2). Building and tearing it apart in bytecode could be ISA ops
7//! (`MakeMessage`, `MsgSender`, …), but that would burn opcode space and
8//! force every embedder that never does request-reply to carry the
9//! dispatch cost. Natives keep the envelope **generic in the core** while
10//! the std table opts into the helpers — same pattern as `print` / `now_ms`
11//! (design notes §30-31): host Rust owns the operation, bytecode only
12//! picks a slot.
13//!
14//! # Stable indices are an embed contract
15//!
16//! Flash / separately-built `.bf` modules hard-code `CallNative` indices.
17//! Renumbering an existing slot is a **breaking** change. Keep
18//! [`std_native_map`] and [`std_native_table`] in lockstep; append only.
19//!
20//! | Index | Name | Role |
21//! |------:|------|------|
22//! | 0 | `print` | host stdout log line (actor-visible) |
23//! | 1 | `now_ms` | wall-clock millis as `Value::Int` |
24//! | 2 | `make_msg` | build [`crate::Message`] from four scalars (**untrusted** `sender`) |
25//! | 3 | `msg_sender` | extract `sender` → `Value::Pid` (authenticated **after** delivery) |
26//! | 4 | `msg_request_id` | extract `request_id` → `Value::Int` |
27//! | 5 | `msg_tag` | extract `tag` → `Value::Int` |
28//! | 6 | `msg_payload` | extract `payload` → `Value::Int` |
29//! | 7 | `msg_reply_cap` | extract `reply_cap` → `Value::Cap` (SEND grant) |
30//!
31//! # `CallNative` argument layout
32//!
33//! `CallNative ra, fb, nc` takes args from `r[a .. a+nc]` and writes the
34//! result back into `r[a]` — so a call **destroys** the first argument
35//! register. Samples that need to keep a `Message` while unpacking must
36//! `Move` it into the dest register first (see
37//! [`crate::samples::atomic_request_reply`]).
38
39use std::collections::HashMap;
40use std::sync::Arc;
41use std::time::{SystemTime, UNIX_EPOCH};
42
43use crate::bytecode::{Message, Value};
44use crate::vm::{expect_message, expect_u64, Fault, NativeTable};
45
46/// Name → `CallNative` index for documentation / host-side lookups.
47///
48/// Prefer this (or [`std_natives`]) over hard-coding integers in host code
49/// so renames stay discoverable; bytecode itself still embeds the numeric
50/// slot once assembled.
51pub fn std_native_map() -> HashMap<String, u32> {
52 HashMap::from([
53 ("print".to_owned(), 0),
54 ("now_ms".to_owned(), 1),
55 ("make_msg".to_owned(), 2),
56 ("msg_sender".to_owned(), 3),
57 ("msg_request_id".to_owned(), 4),
58 ("msg_tag".to_owned(), 5),
59 ("msg_payload".to_owned(), 6),
60 ("msg_reply_cap".to_owned(), 7),
61 ])
62}
63
64/// Default FFI table: print, clock, and Message make/unpack.
65///
66/// Pass this to [`crate::Runtime::with_natives`] (or
67/// `with_natives_and_config`) whenever the chunk emits the Message helpers
68/// or `print` / `now_ms`. Chunks that never `CallNative` can keep
69/// [`crate::NativeTable::empty`].
70pub fn std_native_table() -> Arc<NativeTable> {
71 NativeTable::builder()
72 .register("print", |args| {
73 // Space-separated Display forms, trailing newline — mirrors a
74 // tiny "println!("{:?}", …)" for bytecode without allocating a
75 // format string in the VM.
76 let mut first = true;
77 for value in args {
78 if !first {
79 print!(" ");
80 }
81 print!("{value}");
82 first = false;
83 }
84 println!();
85 Ok(Value::Unit)
86 })
87 .register("now_ms", |_| {
88 let duration = SystemTime::now()
89 .duration_since(UNIX_EPOCH)
90 .map_err(|e| Fault::NativeError(format!("system clock error: {e}")))?;
91 let millis = i64::try_from(duration.as_millis())
92 .map_err(|_| Fault::NativeError("system clock value exceeds i64".into()))?;
93 Ok(Value::Int(millis))
94 })
95 .register("make_msg", |args| {
96 // Args: sender, request_id, tag, payload — each Int≥0, Pid, Cap, or Bool.
97 // Tag must fit `u16` (protocol discriminator width on the wire).
98 //
99 // # Security (crates.io contract)
100 //
101 // The first argument is retained so existing `.bf` modules and
102 // samples keep a stable CallNative layout (indices 0–6 frozen;
103 // 7 = msg_reply_cap appended). It is **not** an authentication
104 // primitive:
105 //
106 // - Before `Send` / `Ask`, `sender` is ordinary register data.
107 // - At delivery, the worker stamps `Message.sender` and mints
108 // `reply_cap` (`Message::authenticate`).
109 // - After a hop is received, `msg_sender` / `msg_reply_cap`
110 // reflect runtime identity and the SEND grant (S1 + FlowCap).
111 //
112 // Host code that only builds messages in memory (never sends)
113 // still sees the constructed field unchanged.
114 let sender = expect_u64(args, 0, "make_msg")?;
115 let request_id = expect_u64(args, 1, "make_msg")?;
116 let tag = expect_u64(args, 2, "make_msg")?;
117 let payload = expect_u64(args, 3, "make_msg")?;
118 let tag = u16::try_from(tag).map_err(|_| {
119 Fault::NativeError(format!("make_msg: tag {tag} does not fit in u16"))
120 })?;
121 Ok(Value::Message(Message::new(sender, request_id, tag, payload)))
122 })
123 .register("msg_sender", |args| {
124 // After mailbox delivery this is the runtime-stamped origin.
125 // Identity only — not a Send/Ask address (use `msg_reply_cap`).
126 Ok(Value::Pid(expect_message(args, 0, "msg_sender")?.sender))
127 })
128 .register("msg_request_id", |args| {
129 Ok(Value::Int(
130 expect_message(args, 0, "msg_request_id")?.request_id as i64,
131 ))
132 })
133 .register("msg_tag", |args| {
134 Ok(Value::Int(i64::from(
135 expect_message(args, 0, "msg_tag")?.tag,
136 )))
137 })
138 .register("msg_payload", |args| {
139 Ok(Value::Int(
140 expect_message(args, 0, "msg_payload")?.payload as i64,
141 ))
142 })
143 .register("msg_reply_cap", |args| {
144 Ok(Value::Cap(
145 expect_message(args, 0, "msg_reply_cap")?.reply_cap,
146 ))
147 })
148 .build()
149}
150
151/// Build the default native table and its matching name map together.
152///
153/// Prefer this when the host both registers natives and resolves names to
154/// indices for `ChunkBuilder` — one source of truth, no drift between map
155/// and table.
156pub fn std_natives() -> (Arc<NativeTable>, HashMap<String, u32>) {
157 let table = std_native_table();
158 let map: HashMap<String, u32> = table
159 .names()
160 .filter_map(|n| table.index_of(n).map(|i| (n.to_string(), i)))
161 .collect();
162 (table, map)
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn std_native_indices_are_stable() {
171 let map = std_native_map();
172 assert_eq!(map["print"], 0);
173 assert_eq!(map["now_ms"], 1);
174 assert_eq!(map["make_msg"], 2);
175 assert_eq!(map["msg_sender"], 3);
176 assert_eq!(map["msg_request_id"], 4);
177 assert_eq!(map["msg_tag"], 5);
178 assert_eq!(map["msg_payload"], 6);
179 assert_eq!(map["msg_reply_cap"], 7);
180 }
181
182 #[test]
183 fn std_native_table_matches_map() {
184 let (table, map) = std_natives();
185 assert_eq!(table.len(), 8);
186 for (name, idx) in &map {
187 assert_eq!(table.index_of(name), Some(*idx));
188 }
189 }
190
191 #[test]
192 fn now_ms_returns_non_negative_int() {
193 let table = std_native_table();
194 let now_ms = table.get(1).expect("now_ms native");
195 let value = now_ms(&[]).expect("clock read");
196 assert!(matches!(value, Value::Int(ms) if ms >= 0));
197 }
198
199 #[test]
200 fn make_msg_and_unpack_round_trip() {
201 let table = std_native_table();
202 let make = table.get(2).expect("make_msg");
203 let msg = make(&[
204 Value::Pid(9),
205 Value::Int(3),
206 Value::Int(7),
207 Value::Int(42),
208 ])
209 .unwrap();
210 assert_eq!(msg.as_message(), Some(Message::new(9, 3, 7, 42)));
211 assert_eq!(
212 table.get(3).unwrap()(std::slice::from_ref(&msg)).unwrap(),
213 Value::Pid(9)
214 );
215 assert_eq!(
216 table.get(4).unwrap()(std::slice::from_ref(&msg)).unwrap(),
217 Value::Int(3)
218 );
219 assert_eq!(
220 table.get(5).unwrap()(std::slice::from_ref(&msg)).unwrap(),
221 Value::Int(7)
222 );
223 assert_eq!(
224 table.get(6).unwrap()(std::slice::from_ref(&msg)).unwrap(),
225 Value::Int(42)
226 );
227 assert_eq!(
228 table.get(7).unwrap()(std::slice::from_ref(&msg)).unwrap(),
229 Value::Cap(0)
230 );
231 }
232
233 #[test]
234 fn print_accepts_all_current_values() {
235 let table = std_native_table();
236 let print = table.get(0).expect("print native");
237 let values = [
238 Value::Unit,
239 Value::Bool(true),
240 Value::Int(42),
241 Value::Float(1.5),
242 Value::Pid(7),
243 Value::Message(Message::new(1, 2, 3, 4)),
244 Value::Cap(9),
245 Value::str("hello"),
246 Value::bytes([1u8, 2, 3]),
247 ];
248 assert_eq!(print(&values).unwrap(), Value::Unit);
249 }
250
251 #[test]
252 fn print_with_no_args_still_returns_unit() {
253 let table = std_native_table();
254 let print = table.get(0).expect("print native");
255 assert_eq!(print(&[]).unwrap(), Value::Unit);
256 }
257}