Skip to main content

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 [`crate::OutputSink`] (CLI uses stdout) |
23//! | 1 | `now_ms` | wall-clock millis as `Value::Int` |
24//! | 2 | `make_msg` | build [`crate::Message`]; no sender operand (stamped on `Send`) |
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` → any [`crate::Value`] |
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. One-arg unpacking uses `CallNativeFrom ra, rb, native`
36//! (`r[a] = native(r[b])`), which leaves the source `Message` in place.
37
38use std::collections::HashMap;
39use std::sync::Arc;
40use std::time::{SystemTime, UNIX_EPOCH};
41
42use crate::bytecode::{Message, Value};
43use crate::output::{OutputSink, StdoutSink};
44use crate::vm::{expect_arg, expect_message, expect_u64, Fault, NativeTable};
45
46/// Stable `CallNative` indices for [`std_native_table`]. Bytecode embeds these
47/// once assembled — append only; never renumber.
48pub mod std_native {
49    pub const PRINT: u32 = 0;
50    pub const NOW_MS: u32 = 1;
51    pub const MAKE_MSG: u32 = 2;
52    pub const MSG_SENDER: u32 = 3;
53    pub const MSG_REQUEST_ID: u32 = 4;
54    pub const MSG_TAG: u32 = 5;
55    pub const MSG_PAYLOAD: u32 = 6;
56    pub const MSG_REPLY_CAP: u32 = 7;
57}
58
59/// Name → `CallNative` index for documentation / host-side lookups.
60///
61/// Prefer this (or [`std_natives`]) over hard-coding integers in host code
62/// so renames stay discoverable; bytecode itself still embeds the numeric
63/// slot once assembled.
64pub fn std_native_map() -> HashMap<String, u32> {
65    HashMap::from([
66        ("print".to_owned(), 0),
67        ("now_ms".to_owned(), 1),
68        ("make_msg".to_owned(), 2),
69        ("msg_sender".to_owned(), 3),
70        ("msg_request_id".to_owned(), 4),
71        ("msg_tag".to_owned(), 5),
72        ("msg_payload".to_owned(), 6),
73        ("msg_reply_cap".to_owned(), 7),
74    ])
75}
76
77/// Default FFI table with [`StdoutSink`]. Prefer [`std_native_table_with`]
78/// in embedders that must not touch stdout.
79pub fn std_native_table() -> Arc<NativeTable> {
80    std_native_table_with(Arc::new(StdoutSink))
81}
82
83/// Std natives with an explicit print sink (`NullSink` in tests / libraries).
84pub fn std_native_table_with(output: Arc<dyn OutputSink>) -> Arc<NativeTable> {
85    let built = NativeTable::builder()
86        .register("print", {
87            let output = Arc::clone(&output);
88            move |args| {
89                output.write(args);
90                Ok(Value::Unit)
91            }
92        })
93        .and_then(|b| {
94            b.register("now_ms", |_| {
95                let duration = SystemTime::now()
96                    .duration_since(UNIX_EPOCH)
97                    .map_err(|e| Fault::NativeError(format!("system clock error: {e}")))?;
98                let millis = i64::try_from(duration.as_millis())
99                    .map_err(|_| Fault::NativeError("system clock value exceeds i64".into()))?;
100                Ok(Value::Int(millis))
101            })
102        })
103        .and_then(|b| {
104            b.register("make_msg", |args| {
105                // 3-arg form: (request_id, tag, payload).
106                // 4-arg legacy: (sender, request_id, tag, payload) — the sender
107                // operand is discarded. Message.sender is always 0 here;
108                // only authenticate_outgoing_message / send() writes identity.
109                let (request_id, tag, payload) = if args.len() >= 4 {
110                    (
111                        expect_u64(args, 1, "make_msg")?,
112                        expect_u64(args, 2, "make_msg")?,
113                        expect_arg(args, 3, "make_msg")?.clone(),
114                    )
115                } else {
116                    (
117                        expect_u64(args, 0, "make_msg")?,
118                        expect_u64(args, 1, "make_msg")?,
119                        expect_arg(args, 2, "make_msg")?.clone(),
120                    )
121                };
122                let tag = u16::try_from(tag).map_err(|_| {
123                    Fault::NativeError(format!("make_msg: tag {tag} does not fit in u16"))
124                })?;
125                Ok(Value::Message(Message::new(0, request_id, tag, payload)))
126            })
127        })
128        .and_then(|b| {
129            b.register("msg_sender", |args| {
130                Ok(Value::Pid(expect_message(args, 0, "msg_sender")?.sender))
131            })
132        })
133        .and_then(|b| {
134            b.register("msg_request_id", |args| {
135                Ok(Value::Int(
136                    expect_message(args, 0, "msg_request_id")?.request_id as i64,
137                ))
138            })
139        })
140        .and_then(|b| {
141            b.register("msg_tag", |args| {
142                Ok(Value::Int(i64::from(
143                    expect_message(args, 0, "msg_tag")?.tag,
144                )))
145            })
146        })
147        .and_then(|b| {
148            b.register("msg_payload", |args| {
149                Ok(expect_message(args, 0, "msg_payload")?
150                    .payload
151                    .as_ref()
152                    .clone())
153            })
154        })
155        .and_then(|b| {
156            b.register("msg_reply_cap", |args| {
157                Ok(Value::Cap(
158                    expect_message(args, 0, "msg_reply_cap")?.reply_cap,
159                ))
160            })
161        });
162    match built {
163        Ok(b) => b.build(),
164        Err(_) => NativeTable::empty(),
165    }
166}
167
168/// Build the default native table and its matching name map together.
169///
170/// Prefer this when the host both registers natives and resolves names to
171/// indices for `ChunkBuilder` — one source of truth, no drift between map
172/// and table.
173pub fn std_natives() -> (Arc<NativeTable>, HashMap<String, u32>) {
174    let table = std_native_table();
175    let map: HashMap<String, u32> = table
176        .names()
177        .filter_map(|n| table.index_of(n).map(|i| (n.to_string(), i)))
178        .collect();
179    (table, map)
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn std_native_indices_are_stable() {
188        let map = std_native_map();
189        assert_eq!(map.get("print"), Some(&0));
190        assert_eq!(map.get("now_ms"), Some(&1));
191        assert_eq!(map.get("make_msg"), Some(&2));
192        assert_eq!(map.get("msg_sender"), Some(&3));
193        assert_eq!(map.get("msg_request_id"), Some(&4));
194        assert_eq!(map.get("msg_tag"), Some(&5));
195        assert_eq!(map.get("msg_payload"), Some(&6));
196        assert_eq!(map.get("msg_reply_cap"), Some(&7));
197    }
198
199    #[test]
200    fn std_native_table_matches_map() {
201        let (table, map) = std_natives();
202        assert_eq!(table.len(), 8);
203        for (name, idx) in &map {
204            assert_eq!(table.index_of(name), Some(*idx));
205        }
206    }
207
208    #[test]
209    fn now_ms_returns_non_negative_int() -> Result<(), Box<dyn std::error::Error>> {
210        let table = std_native_table();
211        let now_ms = table.get(1).ok_or("now_ms native")?;
212        let value = now_ms(&[])?;
213        assert!(matches!(value, Value::Int(ms) if ms >= 0));
214        Ok(())
215    }
216
217    use crate::bytecode::CapId;
218
219    #[test]
220    fn make_msg_and_unpack_round_trip() -> Result<(), Box<dyn std::error::Error>> {
221        let table = std_native_table();
222        let make = table.get(2).ok_or("make_msg")?;
223        let msg = make(&[Value::Int(3), Value::Int(7), Value::Int(42)])?;
224        let expected = Message::new(0, 3, 7, 42);
225        assert_eq!(msg.as_message(), Some(&expected));
226        let sender = table.get(3).ok_or("msg_sender")?;
227        let req = table.get(4).ok_or("msg_request_id")?;
228        let tag = table.get(5).ok_or("msg_tag")?;
229        let payload = table.get(6).ok_or("msg_payload")?;
230        let cap = table.get(7).ok_or("msg_reply_cap")?;
231        assert_eq!(sender(std::slice::from_ref(&msg))?, Value::Pid(0));
232        assert_eq!(req(std::slice::from_ref(&msg))?, Value::Int(3));
233        assert_eq!(tag(std::slice::from_ref(&msg))?, Value::Int(7));
234        assert_eq!(payload(std::slice::from_ref(&msg))?, Value::Int(42));
235        assert_eq!(cap(std::slice::from_ref(&msg))?, Value::Cap(CapId::NONE));
236        Ok(())
237    }
238
239    #[test]
240    fn print_accepts_all_current_values() -> Result<(), Box<dyn std::error::Error>> {
241        let table = std_native_table();
242        let print = table.get(0).ok_or("print native")?;
243        let values = [
244            Value::Unit,
245            Value::Bool(true),
246            Value::Int(42),
247            Value::Float(1.5),
248            Value::Pid(7),
249            Value::Message(Message::new(1, 2, 3, 4)),
250            Value::Cap(CapId::from_raw(9)),
251            Value::str("hello"),
252            Value::bytes([1u8, 2, 3]),
253        ];
254        assert_eq!(print(&values)?, Value::Unit);
255        Ok(())
256    }
257
258    #[test]
259    fn print_with_no_args_still_returns_unit() -> Result<(), Box<dyn std::error::Error>> {
260        let table = std_native_table();
261        let print = table.get(0).ok_or("print native")?;
262        assert_eq!(print(&[])?, Value::Unit);
263        Ok(())
264    }
265}