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(), 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
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("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 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
168pub 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}