1use 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
46pub 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
59pub fn std_native_map() -> HashMap<String, u32> {
65 HashMap::from([
66 ("print".to_owned(), std_native::PRINT),
67 ("now_ms".to_owned(), std_native::NOW_MS),
68 ("make_msg".to_owned(), std_native::MAKE_MSG),
69 ("msg_sender".to_owned(), std_native::MSG_SENDER),
70 ("msg_request_id".to_owned(), std_native::MSG_REQUEST_ID),
71 ("msg_tag".to_owned(), std_native::MSG_TAG),
72 ("msg_payload".to_owned(), std_native::MSG_PAYLOAD),
73 ("msg_reply_cap".to_owned(), std_native::MSG_REPLY_CAP),
74 ])
75}
76
77pub fn std_native_table() -> Arc<NativeTable> {
80 std_native_table_with(Arc::new(StdoutSink))
81}
82
83pub fn std_native_table_with(output: Arc<dyn OutputSink>) -> Arc<NativeTable> {
85 let built = NativeTable::builder()
86 .register_at(std_native::PRINT, "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_at(std_native::NOW_MS, "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_at(std_native::MAKE_MSG, "make_msg", |args| {
105 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_at(std_native::MSG_SENDER, "msg_sender", |args| {
130 Ok(Value::Pid(expect_message(args, 0, "msg_sender")?.sender))
131 })
132 })
133 .and_then(|b| {
134 b.register_at(std_native::MSG_REQUEST_ID, "msg_request_id", |args| {
135 let id = expect_message(args, 0, "msg_request_id")?.request_id;
136 let id = i64::try_from(id).map_err(|_| {
137 Fault::NativeError(format!("msg_request_id: request_id {id} exceeds i64"))
138 })?;
139 Ok(Value::Int(id))
140 })
141 })
142 .and_then(|b| {
143 b.register_at(std_native::MSG_TAG, "msg_tag", |args| {
144 Ok(Value::Int(i64::from(
145 expect_message(args, 0, "msg_tag")?.tag,
146 )))
147 })
148 })
149 .and_then(|b| {
150 b.register_at(std_native::MSG_PAYLOAD, "msg_payload", |args| {
151 Ok(expect_message(args, 0, "msg_payload")?
152 .payload
153 .as_ref()
154 .clone())
155 })
156 })
157 .and_then(|b| {
158 b.register_at(std_native::MSG_REPLY_CAP, "msg_reply_cap", |args| {
159 Ok(Value::Cap(
160 expect_message(args, 0, "msg_reply_cap")?.reply_cap,
161 ))
162 })
163 });
164 match built {
165 Ok(b) => b.build(),
166 Err(error) => panic!("std native table: {error}"),
170 }
171}
172
173pub fn std_natives() -> (Arc<NativeTable>, HashMap<String, u32>) {
179 let table = std_native_table();
180 let map: HashMap<String, u32> = table
181 .names()
182 .filter_map(|n| table.index_of(n).map(|i| (n.to_string(), i)))
183 .collect();
184 (table, map)
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190 use crate::bytecode::{CapId, MapKey};
191 use crate::output::NullSink;
192 use crate::Fault;
193 use std::sync::Arc;
194
195 #[test]
196 fn std_native_indices_are_stable() {
197 let map = std_native_map();
198 assert_eq!(map.get("print"), Some(&0));
199 assert_eq!(map.get("now_ms"), Some(&1));
200 assert_eq!(map.get("make_msg"), Some(&2));
201 assert_eq!(map.get("msg_sender"), Some(&3));
202 assert_eq!(map.get("msg_request_id"), Some(&4));
203 assert_eq!(map.get("msg_tag"), Some(&5));
204 assert_eq!(map.get("msg_payload"), Some(&6));
205 assert_eq!(map.get("msg_reply_cap"), Some(&7));
206 }
207
208 #[test]
209 fn std_native_table_matches_map() {
210 let (table, map) = std_natives();
211 let declared = std_native_map();
212 assert_eq!(table.len(), 8);
213 assert_eq!(map, declared);
214 for (name, idx) in &declared {
215 assert_eq!(table.index_of(name), Some(*idx));
216 }
217 }
218
219 #[test]
220 fn now_ms_returns_non_negative_int() -> Result<(), Box<dyn std::error::Error>> {
221 let table = std_native_table();
222 let now_ms = table.get(1).ok_or("now_ms native")?;
223 let value = now_ms(&[])?;
224 assert!(matches!(value, Value::Int(ms) if ms >= 0));
225 Ok(())
226 }
227
228 #[test]
229 fn make_msg_and_unpack_round_trip() -> Result<(), Box<dyn std::error::Error>> {
230 let table = std_native_table();
231 let make = table.get(2).ok_or("make_msg")?;
232 let msg = make(&[Value::Int(3), Value::Int(7), Value::Int(42)])?;
233 let expected = Message::new(0, 3, 7, 42);
234 assert_eq!(msg.as_message(), Some(&expected));
235 let sender = table.get(3).ok_or("msg_sender")?;
236 let req = table.get(4).ok_or("msg_request_id")?;
237 let tag = table.get(5).ok_or("msg_tag")?;
238 let payload = table.get(6).ok_or("msg_payload")?;
239 let cap = table.get(7).ok_or("msg_reply_cap")?;
240 assert_eq!(sender(std::slice::from_ref(&msg))?, Value::Pid(0));
241 assert_eq!(req(std::slice::from_ref(&msg))?, Value::Int(3));
242 assert_eq!(tag(std::slice::from_ref(&msg))?, Value::Int(7));
243 assert_eq!(payload(std::slice::from_ref(&msg))?, Value::Int(42));
244 assert_eq!(cap(std::slice::from_ref(&msg))?, Value::Cap(CapId::NONE));
245 Ok(())
246 }
247
248 #[test]
249 fn msg_request_id_rejects_values_past_i64() -> Result<(), Box<dyn std::error::Error>> {
250 let table = std_native_table_with(Arc::new(NullSink));
251 let unpack = table
252 .get(std_native::MSG_REQUEST_ID)
253 .ok_or("msg_request_id")?;
254 let fits = Value::Message(Message::new(0, i64::MAX as u64, 1, Value::Int(0)));
255 assert_eq!(unpack(std::slice::from_ref(&fits))?, Value::Int(i64::MAX));
256 let too_wide = Value::Message(Message::new(0, u64::MAX, 1, Value::Int(0)));
257 match unpack(std::slice::from_ref(&too_wide)) {
258 Err(Fault::NativeError(text)) => assert!(text.contains("exceeds i64")),
259 other => panic!("expected NativeError, got {other:?}"),
260 }
261 Ok(())
262 }
263
264 #[test]
265 fn print_accepts_all_current_values() -> Result<(), Box<dyn std::error::Error>> {
266 let table = std_native_table_with(Arc::new(NullSink));
267 let print = table.get(std_native::PRINT).ok_or("print native")?;
268 let list = Value::try_list(vec![Value::Int(1)]).ok_or("list")?;
269 let map = Value::try_map(vec![(MapKey::Int(1), Value::Int(2))]).ok_or("map")?;
270 let values = [
271 Value::Unit,
272 Value::Bool(true),
273 Value::Int(42),
274 Value::Float(1.5),
275 Value::Pid(7),
276 Value::Message(Message::new(1, 2, 3, 4)),
277 Value::Cap(CapId::from_raw(9)),
278 Value::str("hello"),
279 Value::bytes([1u8, 2, 3]),
280 list,
281 map,
282 ];
283 assert_eq!(print(&values)?, Value::Unit);
284 Ok(())
285 }
286
287 #[test]
288 fn print_with_no_args_still_returns_unit() -> Result<(), Box<dyn std::error::Error>> {
289 let table = std_native_table();
290 let print = table.get(0).ok_or("print native")?;
291 assert_eq!(print(&[])?, Value::Unit);
292 Ok(())
293 }
294}