1#![allow(missing_docs)]
41
42use std::collections::HashMap;
43use std::sync::Arc;
44use std::time::{SystemTime, UNIX_EPOCH};
45
46use crate::bytecode::{Message, Value};
47use crate::output::{OutputSink, StdoutSink};
48use crate::vm::{expect_arg, expect_message, expect_u64, Fault, NativeTable};
49
50pub mod std_native {
53 pub const PRINT: u32 = 0;
54 pub const NOW_MS: u32 = 1;
55 pub const MAKE_MSG: u32 = 2;
56 pub const MSG_SENDER: u32 = 3;
57 pub const MSG_REQUEST_ID: u32 = 4;
58 pub const MSG_TAG: u32 = 5;
59 pub const MSG_PAYLOAD: u32 = 6;
60 pub const MSG_REPLY_CAP: u32 = 7;
61}
62
63pub fn std_native_map() -> HashMap<String, u32> {
69 HashMap::from([
70 ("print".to_owned(), std_native::PRINT),
71 ("now_ms".to_owned(), std_native::NOW_MS),
72 ("make_msg".to_owned(), std_native::MAKE_MSG),
73 ("msg_sender".to_owned(), std_native::MSG_SENDER),
74 ("msg_request_id".to_owned(), std_native::MSG_REQUEST_ID),
75 ("msg_tag".to_owned(), std_native::MSG_TAG),
76 ("msg_payload".to_owned(), std_native::MSG_PAYLOAD),
77 ("msg_reply_cap".to_owned(), std_native::MSG_REPLY_CAP),
78 ])
79}
80
81pub fn std_native_table() -> Arc<NativeTable> {
84 std_native_table_with(Arc::new(StdoutSink))
85}
86
87pub fn std_native_table_with(output: Arc<dyn OutputSink>) -> Arc<NativeTable> {
89 let built = NativeTable::builder()
90 .register_at(std_native::PRINT, "print", {
91 let output = Arc::clone(&output);
92 move |args| {
93 output.write(args);
94 Ok(Value::Unit)
95 }
96 })
97 .and_then(|b| {
98 b.register_at(std_native::NOW_MS, "now_ms", |_| {
99 let duration = SystemTime::now()
100 .duration_since(UNIX_EPOCH)
101 .map_err(|e| Fault::NativeError(format!("system clock error: {e}")))?;
102 let millis = i64::try_from(duration.as_millis())
103 .map_err(|_| Fault::NativeError("system clock value exceeds i64".into()))?;
104 Ok(Value::Int(millis))
105 })
106 })
107 .and_then(|b| {
108 b.register_at(std_native::MAKE_MSG, "make_msg", |args| {
109 let (request_id, tag, payload) = if args.len() >= 4 {
114 (
115 expect_u64(args, 1, "make_msg")?,
116 expect_u64(args, 2, "make_msg")?,
117 expect_arg(args, 3, "make_msg")?.clone(),
118 )
119 } else {
120 (
121 expect_u64(args, 0, "make_msg")?,
122 expect_u64(args, 1, "make_msg")?,
123 expect_arg(args, 2, "make_msg")?.clone(),
124 )
125 };
126 let tag = u16::try_from(tag).map_err(|_| {
127 Fault::NativeError(format!("make_msg: tag {tag} does not fit in u16"))
128 })?;
129 Ok(Value::Message(Message::new(0, request_id, tag, payload)))
130 })
131 })
132 .and_then(|b| {
133 b.register_at(std_native::MSG_SENDER, "msg_sender", |args| {
134 Ok(Value::Pid(expect_message(args, 0, "msg_sender")?.sender))
135 })
136 })
137 .and_then(|b| {
138 b.register_at(std_native::MSG_REQUEST_ID, "msg_request_id", |args| {
139 let id = expect_message(args, 0, "msg_request_id")?.request_id;
140 let id = i64::try_from(id).map_err(|_| {
141 Fault::NativeError(format!("msg_request_id: request_id {id} exceeds i64"))
142 })?;
143 Ok(Value::Int(id))
144 })
145 })
146 .and_then(|b| {
147 b.register_at(std_native::MSG_TAG, "msg_tag", |args| {
148 Ok(Value::Int(i64::from(
149 expect_message(args, 0, "msg_tag")?.tag,
150 )))
151 })
152 })
153 .and_then(|b| {
154 b.register_at(std_native::MSG_PAYLOAD, "msg_payload", |args| {
155 Ok(expect_message(args, 0, "msg_payload")?
156 .payload
157 .as_ref()
158 .clone())
159 })
160 })
161 .and_then(|b| {
162 b.register_at(std_native::MSG_REPLY_CAP, "msg_reply_cap", |args| {
163 Ok(Value::Cap(
164 expect_message(args, 0, "msg_reply_cap")?.reply_cap,
165 ))
166 })
167 });
168 match built {
169 Ok(b) => b.build(),
170 Err(error) => panic!("std native table: {error}"),
174 }
175}
176
177pub fn std_natives() -> (Arc<NativeTable>, HashMap<String, u32>) {
183 let table = std_native_table();
184 let map: HashMap<String, u32> = table
185 .names()
186 .filter_map(|n| table.index_of(n).map(|i| (n.to_string(), i)))
187 .collect();
188 (table, map)
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use crate::bytecode::{CapId, MapKey};
195 use crate::output::NullSink;
196 use crate::Fault;
197 use std::sync::Arc;
198
199 #[test]
200 fn std_native_indices_are_stable() {
201 let map = std_native_map();
202 assert_eq!(map.get("print"), Some(&0));
203 assert_eq!(map.get("now_ms"), Some(&1));
204 assert_eq!(map.get("make_msg"), Some(&2));
205 assert_eq!(map.get("msg_sender"), Some(&3));
206 assert_eq!(map.get("msg_request_id"), Some(&4));
207 assert_eq!(map.get("msg_tag"), Some(&5));
208 assert_eq!(map.get("msg_payload"), Some(&6));
209 assert_eq!(map.get("msg_reply_cap"), Some(&7));
210 }
211
212 #[test]
213 fn std_native_table_matches_map() {
214 let (table, map) = std_natives();
215 let declared = std_native_map();
216 assert_eq!(table.len(), 8);
217 assert_eq!(map, declared);
218 for (name, idx) in &declared {
219 assert_eq!(table.index_of(name), Some(*idx));
220 }
221 }
222
223 #[test]
224 fn now_ms_returns_non_negative_int() -> Result<(), Box<dyn std::error::Error>> {
225 let table = std_native_table();
226 let now_ms = table.get(1).ok_or("now_ms native")?;
227 let value = now_ms(&[])?;
228 assert!(matches!(value, Value::Int(ms) if ms >= 0));
229 Ok(())
230 }
231
232 #[test]
233 fn make_msg_and_unpack_round_trip() -> Result<(), Box<dyn std::error::Error>> {
234 let table = std_native_table();
235 let make = table.get(2).ok_or("make_msg")?;
236 let msg = make(&[Value::Int(3), Value::Int(7), Value::Int(42)])?;
237 let expected = Message::new(0, 3, 7, 42);
238 assert_eq!(msg.as_message(), Some(&expected));
239 let sender = table.get(3).ok_or("msg_sender")?;
240 let req = table.get(4).ok_or("msg_request_id")?;
241 let tag = table.get(5).ok_or("msg_tag")?;
242 let payload = table.get(6).ok_or("msg_payload")?;
243 let cap = table.get(7).ok_or("msg_reply_cap")?;
244 assert_eq!(sender(std::slice::from_ref(&msg))?, Value::Pid(0));
245 assert_eq!(req(std::slice::from_ref(&msg))?, Value::Int(3));
246 assert_eq!(tag(std::slice::from_ref(&msg))?, Value::Int(7));
247 assert_eq!(payload(std::slice::from_ref(&msg))?, Value::Int(42));
248 assert_eq!(cap(std::slice::from_ref(&msg))?, Value::Cap(CapId::NONE));
249 Ok(())
250 }
251
252 #[test]
253 fn msg_request_id_rejects_values_past_i64() -> Result<(), Box<dyn std::error::Error>> {
254 let table = std_native_table_with(Arc::new(NullSink));
255 let unpack = table
256 .get(std_native::MSG_REQUEST_ID)
257 .ok_or("msg_request_id")?;
258 let fits = Value::Message(Message::new(0, i64::MAX as u64, 1, Value::Int(0)));
259 assert_eq!(unpack(std::slice::from_ref(&fits))?, Value::Int(i64::MAX));
260 let too_wide = Value::Message(Message::new(0, u64::MAX, 1, Value::Int(0)));
261 match unpack(std::slice::from_ref(&too_wide)) {
262 Err(Fault::NativeError(text)) => assert!(text.contains("exceeds i64")),
263 other => panic!("expected NativeError, got {other:?}"),
264 }
265 Ok(())
266 }
267
268 #[test]
269 fn print_accepts_all_current_values() -> Result<(), Box<dyn std::error::Error>> {
270 let table = std_native_table_with(Arc::new(NullSink));
271 let print = table.get(std_native::PRINT).ok_or("print native")?;
272 let list = Value::try_list(vec![Value::Int(1)]).ok_or("list")?;
273 let map = Value::try_map(vec![(MapKey::Int(1), Value::Int(2))]).ok_or("map")?;
274 let values = [
275 Value::Unit,
276 Value::Bool(true),
277 Value::Int(42),
278 Value::Float(1.5),
279 Value::Pid(7),
280 Value::Message(Message::new(1, 2, 3, 4)),
281 Value::Cap(CapId::from_raw(9)),
282 Value::str("hello"),
283 Value::bytes([1u8, 2, 3]),
284 list,
285 map,
286 ];
287 assert_eq!(print(&values)?, Value::Unit);
288 Ok(())
289 }
290
291 #[test]
292 fn print_with_no_args_still_returns_unit() -> Result<(), Box<dyn std::error::Error>> {
293 let table = std_native_table();
294 let print = table.get(0).ok_or("print native")?;
295 assert_eq!(print(&[])?, Value::Unit);
296 Ok(())
297 }
298}