1use std::cell::RefCell;
9use std::rc::Rc;
10
11use serde::{Deserialize, Serialize};
12
13use crate::interpreter::{InductiveValue, ListRepr, RuntimeValue};
14use logicaffeine_base::{Decimal, LanesVal, Word16, Word32, Word64, Word8, WordVal};
15
16pub(crate) fn result_ok(v: RuntimeValue) -> RuntimeValue {
20 RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
21 inductive_type: "Result".to_string(),
22 constructor: "Ok".to_string(),
23 args: vec![v],
24 }))
25}
26
27pub(crate) fn result_err(msg: String) -> RuntimeValue {
28 RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
29 inductive_type: "Result".to_string(),
30 constructor: "Err".to_string(),
31 args: vec![RuntimeValue::Text(Rc::new(msg))],
32 }))
33}
34
35pub fn system_native(name: &str, argc: usize) -> Option<BuiltinId> {
41 match (name, argc) {
42 ("read", 1) => Some(BuiltinId::FileRead),
43 ("write", 2) => Some(BuiltinId::FileWrite),
44 ("randomInt", 2) => Some(BuiltinId::RandomInt),
45 ("randomFloat", 0) => Some(BuiltinId::RandomFloat),
46 ("get", 1) => Some(BuiltinId::EnvGet),
47 ("now", 0) => Some(BuiltinId::TimeNow),
48 _ => None,
49 }
50}
51
52pub fn rust_only_native(name: &str) -> Option<(&'static str, &'static str)> {
57 match name {
58 "sha3_256" => Some(("keccak", "sha3_256")),
59 "sha3_512" => Some(("keccak", "sha3_512")),
60 "shake128" => Some(("keccak", "shake128")),
61 "shake256" => Some(("keccak", "shake256")),
62 _ => None,
63 }
64}
65
66pub fn unimplemented_native(name: &str, rust_path: Option<&str>) -> String {
72 let linked = rust_only_native(name)
73 .map(|(module, function)| format!("logicaffeine_system::{module}::{function}"));
74 match rust_path.map(str::to_string).or(linked) {
75 Some(path) => format!(
76 "`{name}` is the Rust function `{path}`, which only the Rust backends compile. \
77 Use `largo build` or `largo run` to compile and run this program."
78 ),
79 None => format!(
80 "Unknown system native function: '{name}'. Use `is native \"crate::path\"` syntax for \
81 user-defined native functions."
82 ),
83 }
84}
85
86fn environment_variable(key: &str) -> Option<String> {
90 #[cfg(not(target_arch = "wasm32"))]
91 {
92 logicaffeine_system::env::get(key.to_string())
93 }
94 #[cfg(target_arch = "wasm32")]
95 {
96 logicaffeine_system::testworld::intercept_env_get(key).flatten()
97 }
98}
99
100pub fn vfs_read_failure(e: &logicaffeine_system::fs::VfsError) -> String {
104 format!("Read error: {e}")
105}
106
107pub fn vfs_write_failure(e: &logicaffeine_system::fs::VfsError) -> String {
109 format!("Write error: {e}")
110}
111
112fn sandboxed<T>(op: impl std::future::Future<Output = T>) -> Result<T, String> {
116 use futures::FutureExt as _;
117 Box::pin(op)
118 .now_or_never()
119 .ok_or_else(|| "the sandboxed file system did not answer at once".to_string())
120}
121
122pub(crate) fn byte_seq(v: &RuntimeValue) -> Result<Vec<u8>, String> {
123 match v {
124 RuntimeValue::List(l) => {
125 let l = l.borrow();
126 let mut out = Vec::with_capacity(l.len());
127 for i in 0..l.len() {
128 match l.get(i) {
129 Some(RuntimeValue::Int(n)) => out.push((n & 0xff) as u8),
130 _ => {
131 return Err(format!(
132 "expected a Seq of Int (bytes); element {} is not an Int",
133 i + 1
134 ))
135 }
136 }
137 }
138 Ok(out)
139 }
140 _ => Err(format!(
141 "expected a Seq of Int (bytes), got {}",
142 v.type_name()
143 )),
144 }
145}
146
147pub(crate) fn exact_byte_seq(function: &str, what: &str, v: &RuntimeValue) -> Result<Vec<u8>, String> {
150 let RuntimeValue::List(l) = v else {
151 return Err(format!(
152 "{function}(): the {what} must be a Seq of Int (bytes), got {}",
153 v.type_name()
154 ));
155 };
156 let l = l.borrow();
157 let mut out = Vec::with_capacity(l.len());
158 for i in 0..l.len() {
159 match l.get(i) {
160 Some(RuntimeValue::Int(n)) => match u8::try_from(n) {
161 Ok(b) => out.push(b),
162 Err(_) => {
163 return Err(format!(
164 "{function}(): the {what} must be bytes (0 to 255); item {} is {n}",
165 i + 1
166 ))
167 }
168 },
169 _ => {
170 return Err(format!(
171 "{function}(): the {what} must be a Seq of Int (bytes); item {} is not an Int",
172 i + 1
173 ))
174 }
175 }
176 }
177 Ok(out)
178}
179
180pub(crate) fn pbkdf2_arguments(
184 password: &RuntimeValue,
185 salt: &RuntimeValue,
186 iters: &RuntimeValue,
187) -> Result<(Vec<u8>, Vec<u8>, u32), String> {
188 let password = exact_byte_seq("pbkdf2Sha256", "password", password)?;
189 let salt = exact_byte_seq("pbkdf2Sha256", "salt", salt)?;
190 let iters = match iters {
191 RuntimeValue::Int(n) => u32::try_from(*n).ok().filter(|&c| c >= 1).ok_or_else(|| {
192 format!("pbkdf2Sha256(): the iteration count must be from 1 to 4294967295; it is {n}")
193 })?,
194 other => {
195 return Err(format!(
196 "pbkdf2Sha256(): the iteration count must be an Int, got {}",
197 other.type_name()
198 ))
199 }
200 };
201 Ok((password, salt, iters))
202}
203
204fn fetch_header_pairs(v: &RuntimeValue) -> Result<Vec<(String, String)>, String> {
208 let RuntimeValue::List(l) = v else {
209 return Err(format!(
210 "fetchSend headers must be a Seq of Text alternating name,value, got {}",
211 v.type_name()
212 ));
213 };
214 let l = l.borrow();
215 if l.len() % 2 != 0 {
216 return Err(format!(
217 "fetchSend headers must alternate name,value ({} elements is odd)",
218 l.len()
219 ));
220 }
221 let mut out = Vec::with_capacity(l.len() / 2);
222 for i in (0..l.len()).step_by(2) {
223 let name = l.get(i).map(|x| x.to_display_string()).unwrap_or_default();
224 let value = l
225 .get(i + 1)
226 .map(|x| x.to_display_string())
227 .unwrap_or_default();
228 out.push((name, value));
229 }
230 Ok(out)
231}
232
233pub fn random_int(lo: i64, hi: i64) -> Result<i64, String> {
237 if lo > hi {
238 return Err(format!(
239 "randomInt({lo}, {hi}): the low bound is above the high bound"
240 ));
241 }
242 Ok(logicaffeine_system::random::randomInt(lo, hi))
243}
244
245fn journal_changes(v: &RuntimeValue) -> Result<Vec<(String, String, String)>, String> {
248 let RuntimeValue::List(l) = v else {
249 return Err(format!(
250 "noteTurn changes must be a Seq of Text [field, before, after, …], got {}",
251 v.type_name()
252 ));
253 };
254 let l = l.borrow();
255 if l.len() % 3 != 0 {
256 return Err(format!(
257 "noteTurn changes come in [field, before, after] triples ({} elements is not one)",
258 l.len()
259 ));
260 }
261 let text = |i: usize| l.get(i).map(|x| x.to_display_string()).unwrap_or_default();
262 Ok((0..l.len())
263 .step_by(3)
264 .map(|i| (text(i), text(i + 1), text(i + 2)))
265 .collect())
266}
267
268fn read_aead_key(v: &RuntimeValue, who: &str) -> Result<[u8; 32], String> {
271 let bytes = exact_byte_seq(who, "key", v)?;
272 bytes
273 .as_slice()
274 .try_into()
275 .map_err(|_| format!("{who}(): key must be exactly 32 bytes, got {}", bytes.len()))
276}
277
278fn read_box(v: &RuntimeValue, who: &str) -> Result<Vec<u8>, String> {
280 let sealed = exact_byte_seq(who, "box", v)?;
281 if sealed.len() < logicaffeine_system::aead::BOX_OVERHEAD {
282 return Err(format!(
283 "{who}(): the box is {} bytes; a box is at least {}",
284 sealed.len(),
285 logicaffeine_system::aead::BOX_OVERHEAD
286 ));
287 }
288 Ok(sealed)
289}
290
291fn box_refused(who: &str) -> String {
293 format!("{who}(): authentication failed — the box was tampered, truncated, or the key is wrong")
294}
295
296fn read_aead_nonce(v: &RuntimeValue, who: &str) -> Result<[u8; 12], String> {
299 let bytes = exact_byte_seq(who, "nonce", v)?;
300 bytes.as_slice().try_into().map_err(|_| {
301 format!(
302 "{who}(): nonce must be exactly 12 bytes, got {}",
303 bytes.len()
304 )
305 })
306}
307
308pub(crate) fn bytes_to_seq(bytes: &[u8]) -> RuntimeValue {
310 RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(
311 bytes.iter().map(|&b| b as i64).collect(),
312 ))))
313}
314
315fn read_shards(v: &RuntimeValue) -> Result<Vec<Vec<u8>>, String> {
318 match v {
319 RuntimeValue::List(l) => {
320 let l = l.borrow();
321 let mut shards = Vec::with_capacity(l.len());
322 for i in 0..l.len() {
323 match l.get(i) {
324 Some(elem) => shards.push(byte_seq(&elem)?),
325 None => return Err(format!("shard {} is missing", i + 1)),
326 }
327 }
328 Ok(shards)
329 }
330 _ => Err(format!(
331 "expected a Seq of Seq of Int (shards), got {}",
332 v.type_name()
333 )),
334 }
335}
336
337fn read_received(v: &RuntimeValue) -> Result<Vec<Option<Vec<u8>>>, String> {
340 match v {
341 RuntimeValue::List(l) => {
342 let l = l.borrow();
343 let mut out = Vec::with_capacity(l.len());
344 for i in 0..l.len() {
345 match l.get(i) {
346 Some(RuntimeValue::Nothing) => out.push(None),
347 Some(elem) => out.push(Some(byte_seq(&elem)?)),
348 None => return Err(format!("received slot {} is missing", i + 1)),
349 }
350 }
351 Ok(out)
352 }
353 _ => Err(format!(
354 "expected a Seq of (Seq of Int or nothing), got {}",
355 v.type_name()
356 )),
357 }
358}
359
360fn shards_to_seq(shards: &[Vec<u8>]) -> RuntimeValue {
362 let rows: Vec<RuntimeValue> = shards.iter().map(|s| bytes_to_seq(s)).collect();
363 RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(rows))))
364}
365
366fn read_positive_count(v: RuntimeValue, label: &str) -> Result<usize, String> {
368 match v {
369 RuntimeValue::Int(n) if n > 0 => Ok(n as usize),
370 RuntimeValue::Int(n) => Err(format!("{label} must be positive, got {n}")),
371 other => Err(format!("{label} must be an Int, got {}", other.type_name())),
372 }
373}
374
375#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
376pub enum BuiltinId {
377 Length,
378 Contains,
381 Format,
382 ParseInt,
383 ParseFloat,
384 Chr,
385 Abs,
386 Sqrt,
387 Min,
388 Max,
389 Floor,
390 Ceil,
391 Round,
392 Pow,
393 Decimal,
397 Complex,
400 Conjugate,
404 RealPart,
406 ImagPart,
408 Modular,
410 Quantity,
413 Money,
417 SetRate,
420 ToCurrency,
423 SetRates,
427 Uuid,
429 UuidNil,
431 UuidMax,
432 UuidVersion,
434 UuidDns,
436 UuidUrl,
437 UuidOid,
438 UuidX500,
439 TextBytes,
443 TextFromBytes,
446 WireBytes,
450 CompressBytes,
457 DecompressBytes,
460 SealBytes,
466 OpenBytes,
470 FromWireBytes,
474 SealFrame,
478 OpenFrame,
481 ReadWireProgram,
486 WriteWireResidual,
490 UuidBytes,
491 UuidFromBytes,
492 Convert,
495 ParseTimestamp,
498 FormatTimestamp,
500 YearOf,
503 MonthOf,
504 DayOf,
505 WeekdayOf,
506 HourOf,
507 MinuteOf,
508 SecondOf,
509 WeekOf,
511 QuarterOf,
513 DateOf,
515 TimeOf,
517 MakeDate,
519 MakeMoment,
522 LocalInstant,
525 SecondsBetween,
527 MonthsBetween,
529 YearsBetween,
530 AddSeconds,
532 InZone,
535 Copy,
536 CountOnes,
537 LeadingZeros,
540 TrailingZeros,
543 RunAccepted,
544 Word32,
546 Word64,
547 Rotl,
549 Rotr,
550 Wand,
554 Wor,
555 Wnot,
556 Lanes4Word32Make,
560 Lanes4Of,
562 SeqOfLanes4W32,
563 Sha1Rnds4,
564 Sha1Msg1,
565 Sha1Msg2,
566 Sha1Nexte,
567 Lanes16Word8Make,
570 SeqOfLanes16W8,
571 Splat16Word8,
572 Shuffle16,
573 ShrBytes16,
574 InterleaveLo16,
575 InterleaveHi16,
576 ByteAdd16,
577 Maddubs16,
578 Packus16,
579 Lanes8Word32,
581 SeqOfLanes8,
583 Splat8Word32,
585 IntOfWord32,
587 IntOfWord64,
589 Word64Shl,
591 Word64Shr,
593 Word64And,
595 Word32Shr,
598 Word16Make,
600 IntOfWord16,
602 Lanes4Word64,
604 SeqOfLanes4,
606 Mul32x32To64,
608 HsumLanes4,
610 Splat4Word64,
612 AndNot4,
614 Lanes16Word16,
616 SeqOfLanes16,
618 Splat16Word16,
620 Mulhi16,
622 Montmul32,
625 NttBcastLo,
628 NttBcastHi,
630 NttBlend,
633 MapOf,
638 SetOf,
641 RepeatSeq,
645 ReedSolomonEncode,
650 ReedSolomonRecover,
654 FecProtect,
657 FecRestore,
660 DomBody,
666 DomCreateElement,
668 DomCreateTextNode,
670 DomSetText,
672 DomSetHtml,
674 DomClearChildren,
677 DomOnMessage,
686 DomMoveChildren,
691 DomBeginPaint,
696 DomSetAttribute,
698 DomAppendChild,
700 DomGetText,
702 DomGetValue,
704 DomSetValue,
706 DomApplyPatches,
716 DomSetChecked,
723 DomPreventDefault,
725 StorageSet,
735 StorageGet,
736 StorageGetOr,
746 StorageRemove,
747 DomSetStream,
750 RtcPeerConnection,
755 RtcDataChannel,
756 RtcCreateOffer,
757 RtcCreateAnswer,
758 RtcSetLocal,
759 RtcSetRemote,
760 RtcAddIce,
761 RtcSend,
762 DomQuerySelector,
765 DomAddEventListener,
769 DomEventValue,
771 DomEventKey,
773 TryReadBytes,
776 DomEventTarget,
778 DomFetchText,
781 DomResponseText,
783 ReadBytes,
786 SignalNew,
788 SignalSet,
790 SignalGetInt,
792 SignalGetText,
794 SignalBeginRender,
797 SignalNewText,
800 SignalSetText,
802 SignalEnterComponent,
805 SignalExitComponent,
807 SignalNewSeq,
812 SignalGetSeq,
814 SignalSetSeq,
816 SignalNewFloat,
827 SignalGetFloat,
829 SignalSetFloat,
831 FileRead,
836 FileWrite,
839 RandomInt,
845 RandomFloat,
848 DomFetchSend,
858 DomResponseStatus,
861 DomResponseBody,
863 DomResponseHeader,
866 DomResponseError,
869 DomFetchAbort,
872 DomFetchSetTimeout,
875 DomRoutePath,
883 DomRouteQuery,
885 DomNavigate,
888 DomReplaceRoute,
890 DomSetTitle,
893 DomClipboardWrite,
901 DomDownloadFile,
903 DomNotify,
905 DomPublish,
912 DomElementCommand,
919 DomEventFileName,
924 DomSetInterval,
928 DomScrollGap,
934 DomOnWindowEvent,
938 DomGetAttribute,
944 DomGoBack,
947 DomReload,
952 DomOnRoute,
956 Fail,
961 FailReason,
964 Word8Make,
966 IntOfWord8,
968 NativeKernel,
974 NoteTurn,
983 DomSetHeadHtml,
989 InspectUnhandledDynamic,
999 DomEventFileSize,
1005 DomEventFileType,
1008 DomEventFileBytes,
1013 DomListenFlags,
1019 DomAssignLocation,
1025 DomJournalDetail,
1031 DomApplyWords,
1036 DomWakeAfter,
1042 DomEnterValue,
1049 DomDispatchEntry,
1059 VfsReadFile,
1064 VfsWriteFile,
1069 VfsMount,
1074 EnvGet,
1080 TimeNow,
1084 EnvHas,
1089 EnvValue,
1092 Infinitesimal,
1095 StandardPart,
1100 IsInfinitesimal,
1103 IsLimited,
1106 InfinitelyClose,
1108 GeneratorOf,
1110 LimitOf,
1112 Provisional,
1114 AtTheLimit,
1116 EveryNatural,
1119 TripCount,
1121 AffinePower,
1123 CycleAt,
1125 SearchCandidates,
1127 StateSize,
1129 PolynomialFlow,
1131 ExactSqrt,
1135 ExactExp,
1136 ExactLn,
1137 ExactPi,
1139 ExactE,
1140 ExactOmega,
1142 HybridFlow,
1145 FirstExit,
1148 DefinedReal,
1152 ExactPower,
1155 OrderedInfinitesimal,
1159 SealBox,
1163 OpenBox,
1166 SealValueBox,
1169 OpenValueBox,
1172 ReadReals,
1176}
1177
1178impl BuiltinId {
1179 pub fn extension(self) -> Option<logicaffeine_base::extension::Builtin> {
1182 use logicaffeine_base::extension::Builtin;
1183 Some(match self {
1184 BuiltinId::Infinitesimal => Builtin::Infinitesimal,
1185 BuiltinId::StandardPart => Builtin::StandardPart,
1186 BuiltinId::IsInfinitesimal => Builtin::IsInfinitesimal,
1187 BuiltinId::IsLimited => Builtin::IsLimited,
1188 BuiltinId::InfinitelyClose => Builtin::InfinitelyClose,
1189 BuiltinId::GeneratorOf => Builtin::GeneratorOf,
1190 BuiltinId::LimitOf => Builtin::LimitOf,
1191 BuiltinId::Provisional => Builtin::Provisional,
1192 BuiltinId::AtTheLimit => Builtin::AtTheLimit,
1193 BuiltinId::TripCount => Builtin::TripCount,
1194 BuiltinId::AffinePower => Builtin::AffinePower,
1195 BuiltinId::PolynomialFlow => Builtin::PolynomialFlow,
1196 BuiltinId::HybridFlow => Builtin::HybridFlow,
1197 BuiltinId::FirstExit => Builtin::FirstExit,
1198 BuiltinId::ExactPower => Builtin::ExactPower,
1199 BuiltinId::OrderedInfinitesimal => Builtin::OrderedInfinitesimal,
1200 BuiltinId::CycleAt => Builtin::CycleAt,
1201 BuiltinId::SearchCandidates => Builtin::SearchCandidates,
1202 BuiltinId::StateSize => Builtin::StateSize,
1203 BuiltinId::EveryNatural => Builtin::EveryNatural,
1204 BuiltinId::ExactSqrt => Builtin::ExactSqrt,
1205 BuiltinId::ExactExp => Builtin::ExactExp,
1206 BuiltinId::ExactLn => Builtin::ExactLn,
1207 BuiltinId::ExactPi => Builtin::ExactPi,
1208 BuiltinId::ExactE => Builtin::ExactE,
1209 BuiltinId::ExactOmega => Builtin::ExactOmega,
1210 _ => return None,
1211 })
1212 }
1213
1214 pub fn answers_exact(self) -> bool {
1217 self.extension().is_some() || matches!(self, BuiltinId::DefinedReal)
1218 }
1219
1220 pub fn word_result(self, arg: Option<u8>) -> Option<u8> {
1224 match self {
1225 BuiltinId::Word8Make => Some(8),
1226 BuiltinId::Word16Make => Some(16),
1227 BuiltinId::Word32 | BuiltinId::Word32Shr => Some(32),
1228 BuiltinId::Word64
1229 | BuiltinId::Word64Shl
1230 | BuiltinId::Word64Shr
1231 | BuiltinId::Word64And => Some(64),
1232 BuiltinId::Rotl
1233 | BuiltinId::Rotr
1234 | BuiltinId::Wnot
1235 | BuiltinId::Wand
1236 | BuiltinId::Wor => arg,
1237 _ => None,
1238 }
1239 }
1240
1241 pub fn word_seq_result(self) -> Option<u8> {
1244 match self {
1245 BuiltinId::SeqOfLanes8 => Some(32),
1246 _ => None,
1247 }
1248 }
1249
1250 pub fn is_browser_only(self) -> bool {
1259 match self {
1260 BuiltinId::DomBody
1261 | BuiltinId::DomCreateElement
1262 | BuiltinId::DomCreateTextNode
1263 | BuiltinId::DomSetText
1264 | BuiltinId::DomSetHtml
1265 | BuiltinId::DomClearChildren
1266 | BuiltinId::DomMoveChildren
1267 | BuiltinId::DomOnMessage
1268 | BuiltinId::DomBeginPaint
1269 | BuiltinId::DomSetAttribute
1270 | BuiltinId::DomAppendChild
1271 | BuiltinId::DomGetText
1272 | BuiltinId::DomGetValue
1273 | BuiltinId::DomSetValue
1274 | BuiltinId::DomSetChecked
1275 | BuiltinId::DomPreventDefault
1276 | BuiltinId::DomApplyPatches
1277 | BuiltinId::DomApplyWords
1278 | BuiltinId::DomWakeAfter
1279 | BuiltinId::DomEnterValue
1280 | BuiltinId::DomDispatchEntry
1281 | BuiltinId::StorageSet
1282 | BuiltinId::StorageGet
1283 | BuiltinId::StorageGetOr
1284 | BuiltinId::StorageRemove
1285 | BuiltinId::DomSetStream
1286 | BuiltinId::RtcPeerConnection
1287 | BuiltinId::RtcDataChannel
1288 | BuiltinId::RtcCreateOffer
1289 | BuiltinId::RtcCreateAnswer
1290 | BuiltinId::RtcSetLocal
1291 | BuiltinId::RtcSetRemote
1292 | BuiltinId::RtcAddIce
1293 | BuiltinId::RtcSend
1294 | BuiltinId::DomQuerySelector
1295 | BuiltinId::DomAddEventListener
1296 | BuiltinId::DomEventValue
1297 | BuiltinId::DomEventKey
1298 | BuiltinId::DomEventTarget
1299 | BuiltinId::DomFetchText
1300 | BuiltinId::DomResponseText
1301 | BuiltinId::SignalNew
1302 | BuiltinId::SignalSet
1303 | BuiltinId::SignalGetInt
1304 | BuiltinId::SignalGetText
1305 | BuiltinId::SignalBeginRender
1306 | BuiltinId::SignalNewText
1307 | BuiltinId::SignalSetText
1308 | BuiltinId::SignalEnterComponent
1309 | BuiltinId::SignalExitComponent
1310 | BuiltinId::SignalNewSeq
1311 | BuiltinId::SignalGetSeq
1312 | BuiltinId::SignalSetSeq
1313 | BuiltinId::SignalNewFloat
1314 | BuiltinId::SignalGetFloat
1315 | BuiltinId::SignalSetFloat
1316 | BuiltinId::DomFetchSend
1317 | BuiltinId::DomResponseStatus
1318 | BuiltinId::DomResponseBody
1319 | BuiltinId::DomResponseHeader
1320 | BuiltinId::DomResponseError
1321 | BuiltinId::DomFetchAbort
1322 | BuiltinId::DomFetchSetTimeout
1323 | BuiltinId::DomRoutePath
1324 | BuiltinId::DomRouteQuery
1325 | BuiltinId::DomNavigate
1326 | BuiltinId::DomReplaceRoute
1327 | BuiltinId::DomOnRoute
1328 | BuiltinId::DomSetTitle
1329 | BuiltinId::DomSetHeadHtml
1330 | BuiltinId::DomReload
1331 | BuiltinId::DomGoBack
1332 | BuiltinId::DomGetAttribute
1333 | BuiltinId::DomOnWindowEvent
1334 | BuiltinId::DomScrollGap
1335 | BuiltinId::DomSetInterval
1336 | BuiltinId::DomEventFileName
1337 | BuiltinId::DomEventFileSize
1338 | BuiltinId::DomEventFileType
1339 | BuiltinId::DomEventFileBytes
1340 | BuiltinId::DomListenFlags
1341 | BuiltinId::DomAssignLocation
1342 | BuiltinId::DomJournalDetail
1343 | BuiltinId::DomElementCommand
1344 | BuiltinId::DomClipboardWrite
1345 | BuiltinId::DomDownloadFile
1346 | BuiltinId::DomNotify
1347 | BuiltinId::DomPublish
1348 | BuiltinId::NoteTurn => true,
1349 _ => false,
1350 }
1351 }
1352
1353 pub const ALL: &'static [BuiltinId] = &[
1359 BuiltinId::Length,
1360 BuiltinId::Contains,
1361 BuiltinId::Format,
1362 BuiltinId::ParseInt,
1363 BuiltinId::ParseFloat,
1364 BuiltinId::Chr,
1365 BuiltinId::Abs,
1366 BuiltinId::Sqrt,
1367 BuiltinId::Min,
1368 BuiltinId::Max,
1369 BuiltinId::Floor,
1370 BuiltinId::Ceil,
1371 BuiltinId::Round,
1372 BuiltinId::Pow,
1373 BuiltinId::Decimal,
1374 BuiltinId::Complex,
1375 BuiltinId::Conjugate,
1376 BuiltinId::RealPart,
1377 BuiltinId::ImagPart,
1378 BuiltinId::Modular,
1379 BuiltinId::Quantity,
1380 BuiltinId::Money,
1381 BuiltinId::SetRate,
1382 BuiltinId::ToCurrency,
1383 BuiltinId::SetRates,
1384 BuiltinId::Uuid,
1385 BuiltinId::UuidNil,
1386 BuiltinId::UuidMax,
1387 BuiltinId::UuidVersion,
1388 BuiltinId::UuidDns,
1389 BuiltinId::UuidUrl,
1390 BuiltinId::UuidOid,
1391 BuiltinId::UuidX500,
1392 BuiltinId::TextBytes,
1393 BuiltinId::TextFromBytes,
1394 BuiltinId::WireBytes,
1395 BuiltinId::CompressBytes,
1396 BuiltinId::DecompressBytes,
1397 BuiltinId::SealBytes,
1398 BuiltinId::OpenBytes,
1399 BuiltinId::FromWireBytes,
1400 BuiltinId::SealFrame,
1401 BuiltinId::OpenFrame,
1402 BuiltinId::ReadWireProgram,
1403 BuiltinId::WriteWireResidual,
1404 BuiltinId::UuidBytes,
1405 BuiltinId::UuidFromBytes,
1406 BuiltinId::Convert,
1407 BuiltinId::ParseTimestamp,
1408 BuiltinId::FormatTimestamp,
1409 BuiltinId::YearOf,
1410 BuiltinId::MonthOf,
1411 BuiltinId::DayOf,
1412 BuiltinId::WeekdayOf,
1413 BuiltinId::HourOf,
1414 BuiltinId::MinuteOf,
1415 BuiltinId::SecondOf,
1416 BuiltinId::WeekOf,
1417 BuiltinId::QuarterOf,
1418 BuiltinId::DateOf,
1419 BuiltinId::TimeOf,
1420 BuiltinId::MakeDate,
1421 BuiltinId::MakeMoment,
1422 BuiltinId::LocalInstant,
1423 BuiltinId::SecondsBetween,
1424 BuiltinId::MonthsBetween,
1425 BuiltinId::YearsBetween,
1426 BuiltinId::AddSeconds,
1427 BuiltinId::InZone,
1428 BuiltinId::Copy,
1429 BuiltinId::CountOnes,
1430 BuiltinId::LeadingZeros,
1431 BuiltinId::TrailingZeros,
1432 BuiltinId::RunAccepted,
1433 BuiltinId::Word32,
1434 BuiltinId::Word64,
1435 BuiltinId::Rotl,
1436 BuiltinId::Rotr,
1437 BuiltinId::Wand,
1438 BuiltinId::Wor,
1439 BuiltinId::Wnot,
1440 BuiltinId::Lanes4Word32Make,
1441 BuiltinId::Lanes4Of,
1442 BuiltinId::SeqOfLanes4W32,
1443 BuiltinId::Sha1Rnds4,
1444 BuiltinId::Sha1Msg1,
1445 BuiltinId::Sha1Msg2,
1446 BuiltinId::Sha1Nexte,
1447 BuiltinId::Lanes16Word8Make,
1448 BuiltinId::SeqOfLanes16W8,
1449 BuiltinId::Splat16Word8,
1450 BuiltinId::Shuffle16,
1451 BuiltinId::ShrBytes16,
1452 BuiltinId::InterleaveLo16,
1453 BuiltinId::InterleaveHi16,
1454 BuiltinId::ByteAdd16,
1455 BuiltinId::Maddubs16,
1456 BuiltinId::Packus16,
1457 BuiltinId::Lanes8Word32,
1458 BuiltinId::SeqOfLanes8,
1459 BuiltinId::Splat8Word32,
1460 BuiltinId::IntOfWord32,
1461 BuiltinId::IntOfWord64,
1462 BuiltinId::Word64Shl,
1463 BuiltinId::Word64Shr,
1464 BuiltinId::Word64And,
1465 BuiltinId::Word32Shr,
1466 BuiltinId::Word16Make,
1467 BuiltinId::IntOfWord16,
1468 BuiltinId::Lanes4Word64,
1469 BuiltinId::SeqOfLanes4,
1470 BuiltinId::Mul32x32To64,
1471 BuiltinId::HsumLanes4,
1472 BuiltinId::Splat4Word64,
1473 BuiltinId::AndNot4,
1474 BuiltinId::Lanes16Word16,
1475 BuiltinId::SeqOfLanes16,
1476 BuiltinId::Splat16Word16,
1477 BuiltinId::Mulhi16,
1478 BuiltinId::Montmul32,
1479 BuiltinId::NttBcastLo,
1480 BuiltinId::NttBcastHi,
1481 BuiltinId::NttBlend,
1482 BuiltinId::MapOf,
1483 BuiltinId::SetOf,
1484 BuiltinId::RepeatSeq,
1485 BuiltinId::ReedSolomonEncode,
1486 BuiltinId::ReedSolomonRecover,
1487 BuiltinId::FecProtect,
1488 BuiltinId::FecRestore,
1489 BuiltinId::DomBody,
1490 BuiltinId::DomCreateElement,
1491 BuiltinId::DomCreateTextNode,
1492 BuiltinId::DomSetText,
1493 BuiltinId::DomSetHtml,
1494 BuiltinId::DomClearChildren,
1495 BuiltinId::DomMoveChildren,
1496 BuiltinId::DomOnMessage,
1497 BuiltinId::DomBeginPaint,
1498 BuiltinId::DomSetAttribute,
1499 BuiltinId::DomAppendChild,
1500 BuiltinId::DomGetText,
1501 BuiltinId::DomGetValue,
1502 BuiltinId::DomSetValue,
1503 BuiltinId::DomSetChecked,
1504 BuiltinId::DomPreventDefault,
1505 BuiltinId::DomApplyPatches,
1506 BuiltinId::StorageSet,
1507 BuiltinId::StorageGet,
1508 BuiltinId::StorageGetOr,
1509 BuiltinId::StorageRemove,
1510 BuiltinId::DomSetStream,
1511 BuiltinId::RtcPeerConnection,
1512 BuiltinId::RtcDataChannel,
1513 BuiltinId::RtcCreateOffer,
1514 BuiltinId::RtcCreateAnswer,
1515 BuiltinId::RtcSetLocal,
1516 BuiltinId::RtcSetRemote,
1517 BuiltinId::RtcAddIce,
1518 BuiltinId::RtcSend,
1519 BuiltinId::DomQuerySelector,
1520 BuiltinId::DomAddEventListener,
1521 BuiltinId::DomEventValue,
1522 BuiltinId::DomEventKey,
1523 BuiltinId::DomEventTarget,
1524 BuiltinId::DomFetchText,
1525 BuiltinId::DomResponseText,
1526 BuiltinId::ReadBytes,
1527 BuiltinId::TryReadBytes,
1528 BuiltinId::SignalNew,
1529 BuiltinId::SignalSet,
1530 BuiltinId::SignalGetInt,
1531 BuiltinId::SignalGetText,
1532 BuiltinId::SignalBeginRender,
1533 BuiltinId::SignalNewText,
1534 BuiltinId::SignalSetText,
1535 BuiltinId::SignalEnterComponent,
1536 BuiltinId::SignalExitComponent,
1537 BuiltinId::SignalNewSeq,
1538 BuiltinId::SignalGetSeq,
1539 BuiltinId::SignalSetSeq,
1540 BuiltinId::SignalNewFloat,
1541 BuiltinId::SignalGetFloat,
1542 BuiltinId::SignalSetFloat,
1543 BuiltinId::FileRead,
1544 BuiltinId::FileWrite,
1545 BuiltinId::RandomInt,
1546 BuiltinId::RandomFloat,
1547 BuiltinId::DomFetchSend,
1548 BuiltinId::DomResponseStatus,
1549 BuiltinId::DomResponseBody,
1550 BuiltinId::DomResponseHeader,
1551 BuiltinId::DomResponseError,
1552 BuiltinId::DomFetchAbort,
1553 BuiltinId::DomFetchSetTimeout,
1554 BuiltinId::DomRoutePath,
1555 BuiltinId::DomRouteQuery,
1556 BuiltinId::DomNavigate,
1557 BuiltinId::DomReplaceRoute,
1558 BuiltinId::DomOnRoute,
1559 BuiltinId::DomSetTitle,
1560 BuiltinId::DomSetHeadHtml,
1561 BuiltinId::DomReload,
1562 BuiltinId::DomGoBack,
1563 BuiltinId::DomGetAttribute,
1564 BuiltinId::DomOnWindowEvent,
1565 BuiltinId::DomScrollGap,
1566 BuiltinId::DomSetInterval,
1567 BuiltinId::DomEventFileName,
1568 BuiltinId::DomElementCommand,
1569 BuiltinId::DomClipboardWrite,
1570 BuiltinId::DomDownloadFile,
1571 BuiltinId::DomNotify,
1572 BuiltinId::DomPublish,
1573 BuiltinId::Fail,
1574 BuiltinId::FailReason,
1575 BuiltinId::Word8Make,
1576 BuiltinId::IntOfWord8,
1577 BuiltinId::NativeKernel,
1578 BuiltinId::NoteTurn,
1579 BuiltinId::InspectUnhandledDynamic,
1580 BuiltinId::DomEventFileSize,
1581 BuiltinId::DomEventFileType,
1582 BuiltinId::DomEventFileBytes,
1583 BuiltinId::DomListenFlags,
1584 BuiltinId::DomAssignLocation,
1585 BuiltinId::DomJournalDetail,
1586 BuiltinId::DomApplyWords,
1587 BuiltinId::DomWakeAfter,
1588 BuiltinId::DomEnterValue,
1589 BuiltinId::DomDispatchEntry,
1590 BuiltinId::VfsReadFile,
1591 BuiltinId::VfsWriteFile,
1592 BuiltinId::VfsMount,
1593 BuiltinId::EnvGet,
1594 BuiltinId::TimeNow,
1595 BuiltinId::EnvHas,
1596 BuiltinId::EnvValue,
1597 BuiltinId::Infinitesimal,
1598 BuiltinId::StandardPart,
1599 BuiltinId::IsInfinitesimal,
1600 BuiltinId::IsLimited,
1601 BuiltinId::InfinitelyClose,
1602 BuiltinId::GeneratorOf,
1603 BuiltinId::LimitOf,
1604 BuiltinId::Provisional,
1605 BuiltinId::AtTheLimit,
1606 BuiltinId::EveryNatural,
1607 BuiltinId::TripCount,
1608 BuiltinId::AffinePower,
1609 BuiltinId::CycleAt,
1610 BuiltinId::SearchCandidates,
1611 BuiltinId::StateSize,
1612 BuiltinId::PolynomialFlow,
1613 BuiltinId::ExactSqrt,
1614 BuiltinId::ExactExp,
1615 BuiltinId::ExactLn,
1616 BuiltinId::ExactPi,
1617 BuiltinId::ExactE,
1618 BuiltinId::ExactOmega,
1619 BuiltinId::HybridFlow,
1620 BuiltinId::FirstExit,
1621 BuiltinId::DefinedReal,
1622 BuiltinId::ExactPower,
1623 BuiltinId::OrderedInfinitesimal,
1624 BuiltinId::SealBox,
1625 BuiltinId::OpenBox,
1626 BuiltinId::SealValueBox,
1627 BuiltinId::OpenValueBox,
1628 BuiltinId::ReadReals,
1629 ];
1630}
1631
1632pub const BEGIN_PAINT_RETIRED: &str = "`beginPaint` is gone: a repaint keeps its nodes by drawing through the retained tree — `vdOpen`/`vdText`/`vdClose`, then `vdCommit` and `vdApply` — which an LGX component's view does for you.";
1634
1635pub const MOVE_CHILDREN_RETIRED: &str = "`moveChildren` is gone: a caller's children are drawn where the caller is, as a range of the retained tree's tape (`vdRangeOpen`/`vdRangeClose`), and placed where the callee says `{children}` (`vdSlot`) — which an LGX component's view does for you.";
1637
1638pub const RETIRED_BUILTINS: &[(BuiltinId, &str, &str)] = &[
1641 (BuiltinId::DomBeginPaint, "beginPaint", BEGIN_PAINT_RETIRED),
1642 (
1643 BuiltinId::DomMoveChildren,
1644 "moveChildren",
1645 MOVE_CHILDREN_RETIRED,
1646 ),
1647];
1648
1649pub fn retired_builtin(name: &str) -> Option<&'static str> {
1653 RETIRED_BUILTINS
1654 .iter()
1655 .find(|(_, spelling, _)| *spelling == name)
1656 .map(|(_, _, why)| *why)
1657}
1658
1659pub fn builtin_from_name(name: &str) -> Option<BuiltinId> {
1661 Some(match name {
1662 "length" => BuiltinId::Length,
1663 "contains" => BuiltinId::Contains,
1664 "format" => BuiltinId::Format,
1665 "mapOf" => BuiltinId::MapOf,
1666 "setOf" => BuiltinId::SetOf,
1667 "repeatSeq" => BuiltinId::RepeatSeq,
1668 "reedSolomonEncode" => BuiltinId::ReedSolomonEncode,
1669 "reedSolomonRecover" => BuiltinId::ReedSolomonRecover,
1670 "fecProtect" => BuiltinId::FecProtect,
1671 "fecRestore" => BuiltinId::FecRestore,
1672 "body" => BuiltinId::DomBody,
1673 "createElement" => BuiltinId::DomCreateElement,
1674 "createTextNode" => BuiltinId::DomCreateTextNode,
1675 "setText" => BuiltinId::DomSetText,
1676 "setHtml" => BuiltinId::DomSetHtml,
1677 "clearChildren" => BuiltinId::DomClearChildren,
1678 "onMessage" => BuiltinId::DomOnMessage,
1679 "setAttribute" => BuiltinId::DomSetAttribute,
1680 "appendChild" => BuiltinId::DomAppendChild,
1681 "getText" => BuiltinId::DomGetText,
1682 "getValue" => BuiltinId::DomGetValue,
1683 "setValue" => BuiltinId::DomSetValue,
1684 "setChecked" => BuiltinId::DomSetChecked,
1685 "preventDefault" => BuiltinId::DomPreventDefault,
1686 "applyPatches" => BuiltinId::DomApplyPatches,
1687 "applyPatchWords" => BuiltinId::DomApplyWords,
1688 "wakeAfter" => BuiltinId::DomWakeAfter,
1689 "storageSet" => BuiltinId::StorageSet,
1690 "storageGet" => BuiltinId::StorageGet,
1691 "storageGetOr" => BuiltinId::StorageGetOr,
1692 "storageRemove" => BuiltinId::StorageRemove,
1693 "setStream" => BuiltinId::DomSetStream,
1694 "peerConnection" => BuiltinId::RtcPeerConnection,
1695 "dataChannel" => BuiltinId::RtcDataChannel,
1696 "createOffer" => BuiltinId::RtcCreateOffer,
1697 "createAnswer" => BuiltinId::RtcCreateAnswer,
1698 "setLocalDescription" => BuiltinId::RtcSetLocal,
1699 "setRemoteDescription" => BuiltinId::RtcSetRemote,
1700 "addIceCandidate" => BuiltinId::RtcAddIce,
1701 "channelSend" => BuiltinId::RtcSend,
1702 "querySelector" => BuiltinId::DomQuerySelector,
1703 "addEventListener" => BuiltinId::DomAddEventListener,
1704 "eventValue" => BuiltinId::DomEventValue,
1705 "eventKey" => BuiltinId::DomEventKey,
1706 "eventTarget" => BuiltinId::DomEventTarget,
1707 "fetchText" => BuiltinId::DomFetchText,
1708 "responseText" => BuiltinId::DomResponseText,
1709 "fetchSend" => BuiltinId::DomFetchSend,
1710 "responseStatus" => BuiltinId::DomResponseStatus,
1711 "responseBody" => BuiltinId::DomResponseBody,
1712 "responseHeader" => BuiltinId::DomResponseHeader,
1713 "responseError" => BuiltinId::DomResponseError,
1714 "fetchAbort" => BuiltinId::DomFetchAbort,
1715 "fetchSetTimeout" => BuiltinId::DomFetchSetTimeout,
1716 "routePath" => BuiltinId::DomRoutePath,
1717 "routeQuery" => BuiltinId::DomRouteQuery,
1718 "navigate" => BuiltinId::DomNavigate,
1719 "replaceRoute" => BuiltinId::DomReplaceRoute,
1720 "onRoute" => BuiltinId::DomOnRoute,
1721 "setTitle" => BuiltinId::DomSetTitle,
1722 "setHeadHtml" => BuiltinId::DomSetHeadHtml,
1723 "reloadPage" => BuiltinId::DomReload,
1724 "goBack" => BuiltinId::DomGoBack,
1725 "getAttribute" => BuiltinId::DomGetAttribute,
1726 "onWindowEvent" => BuiltinId::DomOnWindowEvent,
1727 "scrollGap" => BuiltinId::DomScrollGap,
1728 "setInterval" => BuiltinId::DomSetInterval,
1729 "eventFileName" => BuiltinId::DomEventFileName,
1730 "eventFileSize" => BuiltinId::DomEventFileSize,
1731 "eventFileType" => BuiltinId::DomEventFileType,
1732 "eventFileBytes" => BuiltinId::DomEventFileBytes,
1733 "listenFlags" => BuiltinId::DomListenFlags,
1734 "assignLocation" => BuiltinId::DomAssignLocation,
1735 "journalDetail" => BuiltinId::DomJournalDetail,
1736 "elementCommand" => BuiltinId::DomElementCommand,
1737 "clipboardWrite" => BuiltinId::DomClipboardWrite,
1738 "downloadFile" => BuiltinId::DomDownloadFile,
1739 "notify" => BuiltinId::DomNotify,
1740 "publish" => BuiltinId::DomPublish,
1741 "readBytes" => BuiltinId::ReadBytes,
1742 "tryReadBytes" => BuiltinId::TryReadBytes,
1743 "parseInt" => BuiltinId::ParseInt,
1744 "parseFloat" => BuiltinId::ParseFloat,
1745 "chr" => BuiltinId::Chr,
1746 "abs" => BuiltinId::Abs,
1747 "sqrt" => BuiltinId::Sqrt,
1748 "min" => BuiltinId::Min,
1749 "max" => BuiltinId::Max,
1750 "floor" => BuiltinId::Floor,
1751 "ceil" => BuiltinId::Ceil,
1752 "round" => BuiltinId::Round,
1753 "pow" => BuiltinId::Pow,
1754 "decimal" => BuiltinId::Decimal,
1755 "complex" => BuiltinId::Complex,
1756 "conjugate" => BuiltinId::Conjugate,
1757 "infinitesimal" => BuiltinId::Infinitesimal,
1758 "standardPart" => BuiltinId::StandardPart,
1759 "isInfinitesimal" => BuiltinId::IsInfinitesimal,
1760 "isLimited" => BuiltinId::IsLimited,
1761 "infinitelyClose" => BuiltinId::InfinitelyClose,
1762 "generatorOf" => BuiltinId::GeneratorOf,
1763 "limitOf" => BuiltinId::LimitOf,
1764 "provisional" => BuiltinId::Provisional,
1765 "atTheLimit" => BuiltinId::AtTheLimit,
1766 "everyNatural" => BuiltinId::EveryNatural,
1767 "exactSqrt" => BuiltinId::ExactSqrt,
1768 "exactExp" => BuiltinId::ExactExp,
1769 "exactLn" => BuiltinId::ExactLn,
1770 "exactPi" => BuiltinId::ExactPi,
1771 "exactE" => BuiltinId::ExactE,
1772 "exactOmega" => BuiltinId::ExactOmega,
1773 "tripCount" => BuiltinId::TripCount,
1774 "affinePower" => BuiltinId::AffinePower,
1775 "cycleAt" => BuiltinId::CycleAt,
1776 "searchCandidates" => BuiltinId::SearchCandidates,
1777 "stateSize" => BuiltinId::StateSize,
1778 "polynomialFlow" => BuiltinId::PolynomialFlow,
1779 "hybridFlow" => BuiltinId::HybridFlow,
1780 "firstExit" => BuiltinId::FirstExit,
1781 "exactPower" => BuiltinId::ExactPower,
1782 "orderedInfinitesimal" => BuiltinId::OrderedInfinitesimal,
1783 "definedReal" => BuiltinId::DefinedReal,
1784 "re" => BuiltinId::RealPart,
1785 "im" => BuiltinId::ImagPart,
1786 "modular" => BuiltinId::Modular,
1787 "quantity" => BuiltinId::Quantity,
1788 "money" => BuiltinId::Money,
1789 "set_rate" => BuiltinId::SetRate,
1790 "set_rates" => BuiltinId::SetRates,
1791 "to_currency" => BuiltinId::ToCurrency,
1792 "uuid" => BuiltinId::Uuid,
1793 "uuid_nil" => BuiltinId::UuidNil,
1794 "uuid_max" => BuiltinId::UuidMax,
1795 "uuid_version" => BuiltinId::UuidVersion,
1796 "uuid_dns" => BuiltinId::UuidDns,
1797 "uuid_url" => BuiltinId::UuidUrl,
1798 "uuid_oid" => BuiltinId::UuidOid,
1799 "uuid_x500" => BuiltinId::UuidX500,
1800 "text_bytes" => BuiltinId::TextBytes,
1801 "text_from_bytes" => BuiltinId::TextFromBytes,
1802 "wireBytes" => BuiltinId::WireBytes,
1803 "compressBytes" => BuiltinId::CompressBytes,
1804 "decompressBytes" => BuiltinId::DecompressBytes,
1805 "sealBytes" => BuiltinId::SealBytes,
1806 "openBytes" => BuiltinId::OpenBytes,
1807 "sealBox" => BuiltinId::SealBox,
1808 "openBox" => BuiltinId::OpenBox,
1809 "sealValueBox" => BuiltinId::SealValueBox,
1810 "openValueBox" => BuiltinId::OpenValueBox,
1811 "readReals" => BuiltinId::ReadReals,
1812 "fromWireBytes" => BuiltinId::FromWireBytes,
1813 "sealFrame" => BuiltinId::SealFrame,
1814 "openFrame" => BuiltinId::OpenFrame,
1815 "readWireProgram" => BuiltinId::ReadWireProgram,
1816 "writeWireResidual" => BuiltinId::WriteWireResidual,
1817 "uuid_bytes" => BuiltinId::UuidBytes,
1818 "uuid_from_bytes" => BuiltinId::UuidFromBytes,
1819 "convert" => BuiltinId::Convert,
1820 "parse_timestamp" => BuiltinId::ParseTimestamp,
1821 "format_timestamp" => BuiltinId::FormatTimestamp,
1822 "year_of" => BuiltinId::YearOf,
1823 "month_of" => BuiltinId::MonthOf,
1824 "day_of" => BuiltinId::DayOf,
1825 "weekday_of" => BuiltinId::WeekdayOf,
1826 "hour_of" => BuiltinId::HourOf,
1827 "minute_of" => BuiltinId::MinuteOf,
1828 "second_of" => BuiltinId::SecondOf,
1829 "week_of" => BuiltinId::WeekOf,
1830 "quarter_of" => BuiltinId::QuarterOf,
1831 "date_of" => BuiltinId::DateOf,
1832 "time_of" => BuiltinId::TimeOf,
1833 "makeDate" => BuiltinId::MakeDate,
1834 "makeMoment" => BuiltinId::MakeMoment,
1835 "local_instant" => BuiltinId::LocalInstant,
1836 "seconds_between" => BuiltinId::SecondsBetween,
1837 "months_between" => BuiltinId::MonthsBetween,
1838 "years_between" => BuiltinId::YearsBetween,
1839 "add_seconds" => BuiltinId::AddSeconds,
1840 "in_zone" => BuiltinId::InZone,
1841 "copy" => BuiltinId::Copy,
1842 "__logos_fail" => BuiltinId::Fail,
1843 "__logos_fail_reason" => BuiltinId::FailReason,
1844 "count_ones" => BuiltinId::CountOnes,
1845 "leading_zeros" => BuiltinId::LeadingZeros,
1846 "trailing_zeros" => BuiltinId::TrailingZeros,
1847 "run_accepted" => BuiltinId::RunAccepted,
1848 "word32" => BuiltinId::Word32,
1849 "word64" => BuiltinId::Word64,
1850 "lanes8Word32" => BuiltinId::Lanes8Word32,
1851 "seqOfLanes8" => BuiltinId::SeqOfLanes8,
1852 "splat8Word32" => BuiltinId::Splat8Word32,
1853 "intOfWord32" => BuiltinId::IntOfWord32,
1854 "intOfWord64" => BuiltinId::IntOfWord64,
1855 "word64Shl" => BuiltinId::Word64Shl,
1856 "word64Shr" => BuiltinId::Word64Shr,
1857 "word32Shr" => BuiltinId::Word32Shr,
1858 "word64And" => BuiltinId::Word64And,
1859 "word16" => BuiltinId::Word16Make,
1860 "word8" => BuiltinId::Word8Make,
1861 "intOfWord8" => BuiltinId::IntOfWord8,
1862 "__logos_native_kernel" => BuiltinId::NativeKernel,
1863 "noteTurn" => BuiltinId::NoteTurn,
1864 "intOfWord16" => BuiltinId::IntOfWord16,
1865 "lanes4Word64" => BuiltinId::Lanes4Word64,
1866 "seqOfLanes4" => BuiltinId::SeqOfLanes4,
1867 "mul32x32to64" => BuiltinId::Mul32x32To64,
1868 "hsumLanes4" => BuiltinId::HsumLanes4,
1869 "splat4Word64" => BuiltinId::Splat4Word64,
1870 "andNot4" => BuiltinId::AndNot4,
1871 "lanes16Word16" => BuiltinId::Lanes16Word16,
1872 "seqOfLanes16" => BuiltinId::SeqOfLanes16,
1873 "splat16Word16" => BuiltinId::Splat16Word16,
1874 "mulhi16" => BuiltinId::Mulhi16,
1875 "montmul32" => BuiltinId::Montmul32,
1876 "nttBcastLo" => BuiltinId::NttBcastLo,
1877 "nttBcastHi" => BuiltinId::NttBcastHi,
1878 "nttBlend" => BuiltinId::NttBlend,
1879 "rotl" => BuiltinId::Rotl,
1880 "word_and" => BuiltinId::Wand,
1881 "word_or" => BuiltinId::Wor,
1882 "word_not" => BuiltinId::Wnot,
1883 "lanes4Word32" => BuiltinId::Lanes4Word32Make,
1884 "lanes4Of" => BuiltinId::Lanes4Of,
1885 "seqOfLanes4W32" => BuiltinId::SeqOfLanes4W32,
1886 "sha1rnds4" => BuiltinId::Sha1Rnds4,
1887 "sha1msg1" => BuiltinId::Sha1Msg1,
1888 "sha1msg2" => BuiltinId::Sha1Msg2,
1889 "sha1nexte" => BuiltinId::Sha1Nexte,
1890 "lanes16Word8" => BuiltinId::Lanes16Word8Make,
1891 "seqOfLanes16W8" => BuiltinId::SeqOfLanes16W8,
1892 "splat16Word8" => BuiltinId::Splat16Word8,
1893 "shuffle16" => BuiltinId::Shuffle16,
1894 "shrBytes16" => BuiltinId::ShrBytes16,
1895 "interleaveLo16" => BuiltinId::InterleaveLo16,
1896 "interleaveHi16" => BuiltinId::InterleaveHi16,
1897 "byteAdd16" => BuiltinId::ByteAdd16,
1898 "maddubs16" => BuiltinId::Maddubs16,
1899 "packus16" => BuiltinId::Packus16,
1900 "rotr" => BuiltinId::Rotr,
1901 _ => return None,
1902 })
1903}
1904
1905pub fn check_arity(id: BuiltinId, n: usize) -> Result<(), String> {
1908 let expected: usize = match id {
1909 BuiltinId::Format => return Ok(()),
1910 BuiltinId::NativeKernel => {
1912 if n == 0 {
1913 return Err("a native kernel call carries its kernel code".to_string());
1914 }
1915 return Ok(());
1916 }
1917 BuiltinId::MapOf => {
1918 if n == 0 || n % 2 != 0 {
1919 return Err(format!(
1920 "mapOf takes flat key/value pairs (an even, nonzero number of arguments), got {}",
1921 n
1922 ));
1923 }
1924 return Ok(());
1925 }
1926 BuiltinId::SetOf => {
1927 if n == 0 {
1928 return Err("setOf takes at least one element (an empty set is `{} of T`)".to_string());
1929 }
1930 return Ok(());
1931 }
1932 BuiltinId::Infinitesimal => {
1933 if n < 2 {
1934 return Err("infinitesimal takes a name, a modulus and the allowed residues".to_string());
1935 }
1936 return Ok(());
1937 }
1938 BuiltinId::OrderedInfinitesimal => {
1939 if n < 4 {
1940 return Err(
1941 "orderedInfinitesimal takes a name, the infinitesimals above and below, a modulus and the allowed residues"
1942 .to_string(),
1943 );
1944 }
1945 return Ok(());
1946 }
1947 BuiltinId::StandardPart | BuiltinId::IsInfinitesimal | BuiltinId::IsLimited => {
1948 if !(1..=2).contains(&n) {
1949 let name = id.extension().expect("a builtin of the exact extension").name();
1950 return Err(format!(
1951 "{name} takes a value and, relative to an infinitesimal, that infinitesimal; got {n} arguments"
1952 ));
1953 }
1954 return Ok(());
1955 }
1956 BuiltinId::InfinitelyClose => {
1957 if !(2..=3).contains(&n) {
1958 return Err(format!(
1959 "infinitelyClose takes two values and, relative to an infinitesimal, that infinitesimal; got {n} arguments"
1960 ));
1961 }
1962 return Ok(());
1963 }
1964 BuiltinId::LimitOf | BuiltinId::SearchCandidates | BuiltinId::ExactPower => 2,
1965 BuiltinId::Provisional
1966 | BuiltinId::AffinePower
1967 | BuiltinId::CycleAt
1968 | BuiltinId::PolynomialFlow
1969 | BuiltinId::HybridFlow
1970 | BuiltinId::FirstExit => 3,
1971 BuiltinId::TripCount | BuiltinId::DefinedReal => 4,
1972 BuiltinId::ExactPi | BuiltinId::ExactE | BuiltinId::ExactOmega => 0,
1973 BuiltinId::Min | BuiltinId::Max | BuiltinId::Pow => 2,
1974 BuiltinId::Contains => 2,
1975 BuiltinId::RepeatSeq => 2,
1976 BuiltinId::ReedSolomonEncode | BuiltinId::ReedSolomonRecover => 2,
1977 BuiltinId::FecRestore => 2,
1978 BuiltinId::FecProtect => 3,
1979 BuiltinId::SealBytes | BuiltinId::OpenBytes => 3,
1980 BuiltinId::SealBox
1981 | BuiltinId::OpenBox
1982 | BuiltinId::SealValueBox
1983 | BuiltinId::OpenValueBox => 2,
1984 BuiltinId::SealFrame | BuiltinId::OpenFrame => 3,
1985 BuiltinId::Complex => 2,
1986 BuiltinId::Modular => 2,
1987 BuiltinId::Quantity | BuiltinId::Convert | BuiltinId::Money => 2,
1988 BuiltinId::SetRate | BuiltinId::ToCurrency => 2,
1989 BuiltinId::SetRates => 1,
1990 BuiltinId::UuidNil
1991 | BuiltinId::UuidMax
1992 | BuiltinId::UuidDns
1993 | BuiltinId::UuidUrl
1994 | BuiltinId::UuidOid
1995 | BuiltinId::ReadWireProgram
1996 | BuiltinId::UuidX500 => 0,
1997 BuiltinId::Uuid | BuiltinId::UuidVersion => 1,
1998 BuiltinId::TextBytes | BuiltinId::TextFromBytes | BuiltinId::WireBytes | BuiltinId::FromWireBytes | BuiltinId::CompressBytes | BuiltinId::DecompressBytes | BuiltinId::WriteWireResidual | BuiltinId::UuidBytes | BuiltinId::UuidFromBytes => 1,
1999 BuiltinId::SecondsBetween | BuiltinId::AddSeconds | BuiltinId::InZone => 2,
2000 BuiltinId::MonthsBetween | BuiltinId::YearsBetween => 2,
2001 BuiltinId::MakeDate => 3,
2002 BuiltinId::MakeMoment => 6,
2003 BuiltinId::LocalInstant => 2,
2004 BuiltinId::Rotl | BuiltinId::Rotr => 2,
2005 BuiltinId::Wand | BuiltinId::Wor => 2,
2006 BuiltinId::Wnot => 1,
2007 BuiltinId::Lanes4Word32Make | BuiltinId::SeqOfLanes4W32 => 1,
2008 BuiltinId::AndNot4 => 2,
2009 BuiltinId::Lanes4Of => 4,
2010 BuiltinId::Sha1Rnds4 => 3,
2011 BuiltinId::Sha1Msg1 | BuiltinId::Sha1Msg2 | BuiltinId::Sha1Nexte => 2,
2012 BuiltinId::Lanes16Word8Make | BuiltinId::SeqOfLanes16W8 | BuiltinId::Splat16Word8 => 1,
2013 BuiltinId::Shuffle16 | BuiltinId::ShrBytes16 => 2,
2014 BuiltinId::InterleaveLo16 | BuiltinId::InterleaveHi16 => 2,
2015 BuiltinId::ByteAdd16 | BuiltinId::Maddubs16 | BuiltinId::Packus16 => 2,
2016 BuiltinId::Mul32x32To64 => 2,
2017 BuiltinId::DomBody => 0,
2018 BuiltinId::DomCreateElement
2019 | BuiltinId::DomCreateTextNode
2020 | BuiltinId::DomGetText
2021 | BuiltinId::DomGetValue
2022 | BuiltinId::DomClearChildren
2023 | BuiltinId::DomApplyPatches
2024 | BuiltinId::DomWakeAfter
2025 | BuiltinId::DomQuerySelector => 1,
2026 BuiltinId::DomApplyWords => 4,
2027 BuiltinId::DomSetText
2028 | BuiltinId::DomSetHtml
2029 | BuiltinId::DomMoveChildren
2030 | BuiltinId::DomOnMessage
2031 | BuiltinId::DomAppendChild
2032 | BuiltinId::DomSetValue
2033 | BuiltinId::DomSetChecked
2034 | BuiltinId::DomPreventDefault
2039 | BuiltinId::DomSetStream => 2,
2040 BuiltinId::RtcPeerConnection => 0,
2041 BuiltinId::RtcCreateOffer | BuiltinId::RtcCreateAnswer => 1,
2042 BuiltinId::RtcDataChannel
2043 | BuiltinId::RtcSetLocal
2044 | BuiltinId::RtcSetRemote
2045 | BuiltinId::RtcAddIce
2046 | BuiltinId::RtcSend => 2,
2047 BuiltinId::StorageGet | BuiltinId::StorageRemove => 2,
2048 BuiltinId::StorageSet | BuiltinId::StorageGetOr => 3,
2049 BuiltinId::DomSetAttribute | BuiltinId::DomAddEventListener | BuiltinId::DomListenFlags | BuiltinId::DomEnterValue => 3,
2050 BuiltinId::DomDispatchEntry => 6,
2051 BuiltinId::DomGetAttribute
2052 | BuiltinId::DomOnWindowEvent
2053 | BuiltinId::DomElementCommand => 2,
2054 BuiltinId::DomScrollGap
2055 | BuiltinId::DomEventFileName
2056 | BuiltinId::DomClipboardWrite => 1,
2057 BuiltinId::DomDownloadFile | BuiltinId::DomNotify | BuiltinId::DomPublish => 2,
2058 BuiltinId::NoteTurn => 4,
2059 BuiltinId::DomSetInterval => 2,
2060 BuiltinId::DomEventValue | BuiltinId::DomEventKey | BuiltinId::DomEventTarget => 1,
2061 BuiltinId::DomFetchText => 2,
2062 BuiltinId::DomResponseText | BuiltinId::DomBeginPaint => 0,
2063 BuiltinId::DomFetchSend => 5,
2064 BuiltinId::DomResponseStatus
2065 | BuiltinId::DomResponseBody
2066 | BuiltinId::DomResponseError
2067 | BuiltinId::DomFetchAbort => 1,
2068 BuiltinId::DomResponseHeader | BuiltinId::DomFetchSetTimeout => 2,
2069 BuiltinId::DomRoutePath | BuiltinId::DomReload | BuiltinId::DomGoBack | BuiltinId::DomJournalDetail => 0,
2070 BuiltinId::DomRouteQuery
2071 | BuiltinId::DomNavigate
2072 | BuiltinId::DomReplaceRoute
2073 | BuiltinId::DomOnRoute
2074 | BuiltinId::DomSetTitle
2075 | BuiltinId::DomSetHeadHtml => 1,
2076 BuiltinId::ReadBytes | BuiltinId::TryReadBytes | BuiltinId::ReadReals => 1,
2077 BuiltinId::FileRead => 1,
2078 BuiltinId::FileWrite => 2,
2079 BuiltinId::VfsWriteFile => 2,
2080 BuiltinId::RandomInt => 2,
2081 BuiltinId::RandomFloat => 0,
2082 BuiltinId::EnvGet | BuiltinId::EnvHas | BuiltinId::EnvValue => 1,
2083 BuiltinId::TimeNow => 0,
2084 BuiltinId::SignalNew | BuiltinId::SignalGetInt | BuiltinId::SignalGetText | BuiltinId::SignalNewText => 1,
2087 BuiltinId::SignalSet | BuiltinId::SignalSetText => 2,
2088 BuiltinId::SignalBeginRender | BuiltinId::SignalExitComponent => 0,
2089 BuiltinId::SignalEnterComponent => 1,
2090 BuiltinId::SignalNewSeq | BuiltinId::SignalGetSeq => 1,
2091 BuiltinId::SignalSetSeq => 2,
2092 BuiltinId::SignalNewFloat | BuiltinId::SignalGetFloat => 1,
2093 BuiltinId::SignalSetFloat => 2,
2094 BuiltinId::Mulhi16 => 2,
2095 BuiltinId::Montmul32 => 4,
2096 BuiltinId::Word64Shl | BuiltinId::Word64Shr | BuiltinId::Word64And => 2,
2097 BuiltinId::Word32Shr => 2,
2098 BuiltinId::NttBcastLo | BuiltinId::NttBcastHi => 2,
2099 BuiltinId::NttBlend => 3,
2100 BuiltinId::RunAccepted => 4,
2103 _ => 1,
2104 };
2105 if n != expected {
2106 let name = match id {
2107 BuiltinId::Length => "length",
2108 BuiltinId::Contains => "contains",
2109 BuiltinId::Format => unreachable!(),
2110 BuiltinId::MapOf | BuiltinId::SetOf => unreachable!(),
2112 BuiltinId::RepeatSeq => "repeatSeq",
2113 BuiltinId::ReedSolomonEncode => "reedSolomonEncode",
2114 BuiltinId::ReedSolomonRecover => "reedSolomonRecover",
2115 BuiltinId::FecProtect => "fecProtect",
2116 BuiltinId::FecRestore => "fecRestore",
2117 BuiltinId::ParseInt => "parseInt",
2118 BuiltinId::ParseFloat => "parseFloat",
2119 BuiltinId::Chr => "chr",
2120 BuiltinId::Abs => "abs",
2121 BuiltinId::Sqrt => "sqrt",
2122 BuiltinId::Min => "min",
2123 BuiltinId::Max => "max",
2124 BuiltinId::Floor => "floor",
2125 BuiltinId::Ceil => "ceil",
2126 BuiltinId::Round => "round",
2127 BuiltinId::Pow => "pow",
2128 BuiltinId::Decimal => "decimal",
2129 BuiltinId::Complex => "complex",
2130 BuiltinId::Conjugate => "conjugate",
2131 BuiltinId::Infinitesimal => "infinitesimal",
2132 BuiltinId::StandardPart => "standardPart",
2133 BuiltinId::IsInfinitesimal => "isInfinitesimal",
2134 BuiltinId::IsLimited => "isLimited",
2135 BuiltinId::InfinitelyClose => "infinitelyClose",
2136 BuiltinId::GeneratorOf => "generatorOf",
2137 BuiltinId::LimitOf => "limitOf",
2138 BuiltinId::Provisional => "provisional",
2139 BuiltinId::AtTheLimit => "atTheLimit",
2140 BuiltinId::EveryNatural => "everyNatural",
2141 BuiltinId::ExactSqrt => "exactSqrt",
2142 BuiltinId::ExactExp => "exactExp",
2143 BuiltinId::ExactLn => "exactLn",
2144 BuiltinId::ExactPi => "exactPi",
2145 BuiltinId::ExactE => "exactE",
2146 BuiltinId::ExactOmega => "exactOmega",
2147 BuiltinId::TripCount => "tripCount",
2148 BuiltinId::AffinePower => "affinePower",
2149 BuiltinId::CycleAt => "cycleAt",
2150 BuiltinId::SearchCandidates => "searchCandidates",
2151 BuiltinId::StateSize => "stateSize",
2152 BuiltinId::PolynomialFlow => "polynomialFlow",
2153 BuiltinId::HybridFlow => "hybridFlow",
2154 BuiltinId::FirstExit => "firstExit",
2155 BuiltinId::ExactPower => "exactPower",
2156 BuiltinId::OrderedInfinitesimal => "orderedInfinitesimal",
2157 BuiltinId::DefinedReal => "definedReal",
2158 BuiltinId::RealPart => "re",
2159 BuiltinId::ImagPart => "im",
2160 BuiltinId::Modular => "modular",
2161 BuiltinId::Quantity => "quantity",
2162 BuiltinId::Money => "money",
2163 BuiltinId::SetRate => "set_rate",
2164 BuiltinId::SetRates => "set_rates",
2165 BuiltinId::ToCurrency => "to_currency",
2166 BuiltinId::Uuid => "uuid",
2167 BuiltinId::UuidNil => "uuid_nil",
2168 BuiltinId::UuidMax => "uuid_max",
2169 BuiltinId::UuidVersion => "uuid_version",
2170 BuiltinId::UuidDns => "uuid_dns",
2171 BuiltinId::UuidUrl => "uuid_url",
2172 BuiltinId::UuidOid => "uuid_oid",
2173 BuiltinId::UuidX500 => "uuid_x500",
2174 BuiltinId::TextBytes => "text_bytes",
2175 BuiltinId::TextFromBytes => "text_from_bytes",
2176 BuiltinId::WireBytes => "wireBytes",
2177 BuiltinId::CompressBytes => "compressBytes",
2178 BuiltinId::DecompressBytes => "decompressBytes",
2179 BuiltinId::SealBytes => "sealBytes",
2180 BuiltinId::OpenBytes => "openBytes",
2181 BuiltinId::SealBox => "sealBox",
2182 BuiltinId::OpenBox => "openBox",
2183 BuiltinId::SealValueBox => "sealValueBox",
2184 BuiltinId::OpenValueBox => "openValueBox",
2185 BuiltinId::ReadReals => "readReals",
2186 BuiltinId::FromWireBytes => "fromWireBytes",
2187 BuiltinId::SealFrame => "sealFrame",
2188 BuiltinId::OpenFrame => "openFrame",
2189 BuiltinId::ReadWireProgram => "readWireProgram",
2190 BuiltinId::WriteWireResidual => "writeWireResidual",
2191 BuiltinId::UuidBytes => "uuid_bytes",
2192 BuiltinId::UuidFromBytes => "uuid_from_bytes",
2193 BuiltinId::Convert => "convert",
2194 BuiltinId::ParseTimestamp => "parse_timestamp",
2195 BuiltinId::FormatTimestamp => "format_timestamp",
2196 BuiltinId::YearOf => "year_of",
2197 BuiltinId::MonthOf => "month_of",
2198 BuiltinId::DayOf => "day_of",
2199 BuiltinId::WeekdayOf => "weekday_of",
2200 BuiltinId::HourOf => "hour_of",
2201 BuiltinId::MinuteOf => "minute_of",
2202 BuiltinId::SecondOf => "second_of",
2203 BuiltinId::WeekOf => "week_of",
2204 BuiltinId::QuarterOf => "quarter_of",
2205 BuiltinId::DateOf => "date_of",
2206 BuiltinId::TimeOf => "time_of",
2207 BuiltinId::MakeDate => "makeDate",
2208 BuiltinId::MakeMoment => "makeMoment",
2209 BuiltinId::LocalInstant => "local_instant",
2210 BuiltinId::SecondsBetween => "seconds_between",
2211 BuiltinId::MonthsBetween => "months_between",
2212 BuiltinId::YearsBetween => "years_between",
2213 BuiltinId::AddSeconds => "add_seconds",
2214 BuiltinId::InZone => "in_zone",
2215 BuiltinId::Copy => "copy",
2216 BuiltinId::Fail => "__logos_fail",
2217 BuiltinId::FailReason => "__logos_fail_reason",
2218 BuiltinId::CountOnes => "count_ones",
2219 BuiltinId::LeadingZeros => "leading_zeros",
2220 BuiltinId::TrailingZeros => "trailing_zeros",
2221 BuiltinId::RunAccepted => "run_accepted",
2222 BuiltinId::Word32 => "word32",
2223 BuiltinId::Word64 => "word64",
2224 BuiltinId::Lanes8Word32 => "lanes8Word32",
2225 BuiltinId::SeqOfLanes8 => "seqOfLanes8",
2226 BuiltinId::Splat8Word32 => "splat8Word32",
2227 BuiltinId::IntOfWord32 => "intOfWord32",
2228 BuiltinId::IntOfWord64 => "intOfWord64",
2229 BuiltinId::Word64Shl => "word64Shl",
2230 BuiltinId::Word64Shr => "word64Shr",
2231 BuiltinId::Word32Shr => "word32Shr",
2232 BuiltinId::Word64And => "word64And",
2233 BuiltinId::Word16Make => "word16",
2234 BuiltinId::Word8Make => "word8",
2235 BuiltinId::IntOfWord8 => "intOfWord8",
2236 BuiltinId::NativeKernel => "__logos_native_kernel",
2237 BuiltinId::NoteTurn => "noteTurn",
2238 BuiltinId::IntOfWord16 => "intOfWord16",
2239 BuiltinId::Lanes4Word64 => "lanes4Word64",
2240 BuiltinId::SeqOfLanes4 => "seqOfLanes4",
2241 BuiltinId::Mul32x32To64 => "mul32x32to64",
2242 BuiltinId::HsumLanes4 => "hsumLanes4",
2243 BuiltinId::Splat4Word64 => "splat4Word64",
2244 BuiltinId::AndNot4 => "andNot4",
2245 BuiltinId::Lanes16Word16 => "lanes16Word16",
2246 BuiltinId::SeqOfLanes16 => "seqOfLanes16",
2247 BuiltinId::Splat16Word16 => "splat16Word16",
2248 BuiltinId::Mulhi16 => "mulhi16",
2249 BuiltinId::Montmul32 => "montmul32",
2250 BuiltinId::NttBcastLo => "nttBcastLo",
2251 BuiltinId::NttBcastHi => "nttBcastHi",
2252 BuiltinId::NttBlend => "nttBlend",
2253 BuiltinId::Rotl => "rotl",
2254 BuiltinId::Wand => "word_and",
2255 BuiltinId::Wor => "word_or",
2256 BuiltinId::Wnot => "word_not",
2257 BuiltinId::Lanes4Word32Make => "lanes4Word32",
2258 BuiltinId::Lanes4Of => "lanes4Of",
2259 BuiltinId::SeqOfLanes4W32 => "seqOfLanes4W32",
2260 BuiltinId::Sha1Rnds4 => "sha1rnds4",
2261 BuiltinId::Sha1Msg1 => "sha1msg1",
2262 BuiltinId::Sha1Msg2 => "sha1msg2",
2263 BuiltinId::Sha1Nexte => "sha1nexte",
2264 BuiltinId::Lanes16Word8Make => "lanes16Word8",
2265 BuiltinId::SeqOfLanes16W8 => "seqOfLanes16W8",
2266 BuiltinId::Splat16Word8 => "splat16Word8",
2267 BuiltinId::Shuffle16 => "shuffle16",
2268 BuiltinId::ShrBytes16 => "shrBytes16",
2269 BuiltinId::InterleaveLo16 => "interleaveLo16",
2270 BuiltinId::InterleaveHi16 => "interleaveHi16",
2271 BuiltinId::ByteAdd16 => "byteAdd16",
2272 BuiltinId::Maddubs16 => "maddubs16",
2273 BuiltinId::Packus16 => "packus16",
2274 BuiltinId::Rotr => "rotr",
2275 BuiltinId::DomBody => "body",
2276 BuiltinId::DomCreateElement => "createElement",
2277 BuiltinId::DomCreateTextNode => "createTextNode",
2278 BuiltinId::DomSetText => "setText",
2279 BuiltinId::DomSetHtml => "setHtml",
2280 BuiltinId::DomClearChildren => "clearChildren",
2281 BuiltinId::DomMoveChildren => "moveChildren",
2282 BuiltinId::DomOnMessage => "onMessage",
2283 BuiltinId::DomBeginPaint => "beginPaint",
2284 BuiltinId::DomSetAttribute => "setAttribute",
2285 BuiltinId::DomAppendChild => "appendChild",
2286 BuiltinId::DomGetText => "getText",
2287 BuiltinId::DomGetValue => "getValue",
2288 BuiltinId::DomSetValue => "setValue",
2289 BuiltinId::DomSetChecked => "setChecked",
2290 BuiltinId::DomPreventDefault => "preventDefault",
2291 BuiltinId::DomApplyPatches => "applyPatches",
2292 BuiltinId::DomApplyWords => "applyPatchWords",
2293 BuiltinId::DomWakeAfter => "wakeAfter",
2294 BuiltinId::DomEnterValue => "enterValue",
2295 BuiltinId::DomDispatchEntry => "dispatchEntry",
2296 BuiltinId::StorageSet => "storageSet",
2297 BuiltinId::StorageGet => "storageGet",
2298 BuiltinId::StorageGetOr => "storageGetOr",
2299 BuiltinId::StorageRemove => "storageRemove",
2300 BuiltinId::DomSetStream => "setStream",
2301 BuiltinId::RtcPeerConnection => "peerConnection",
2302 BuiltinId::RtcDataChannel => "dataChannel",
2303 BuiltinId::RtcCreateOffer => "createOffer",
2304 BuiltinId::RtcCreateAnswer => "createAnswer",
2305 BuiltinId::RtcSetLocal => "setLocalDescription",
2306 BuiltinId::RtcSetRemote => "setRemoteDescription",
2307 BuiltinId::RtcAddIce => "addIceCandidate",
2308 BuiltinId::RtcSend => "channelSend",
2309 BuiltinId::DomQuerySelector => "querySelector",
2310 BuiltinId::DomAddEventListener => "addEventListener",
2311 BuiltinId::DomEventValue => "eventValue",
2312 BuiltinId::DomEventKey => "eventKey",
2313 BuiltinId::DomEventTarget => "eventTarget",
2314 BuiltinId::DomFetchText => "fetchText",
2315 BuiltinId::DomResponseText => "responseText",
2316 BuiltinId::DomFetchSend => "fetchSend",
2317 BuiltinId::DomResponseStatus => "responseStatus",
2318 BuiltinId::DomResponseBody => "responseBody",
2319 BuiltinId::DomResponseHeader => "responseHeader",
2320 BuiltinId::DomResponseError => "responseError",
2321 BuiltinId::DomFetchAbort => "fetchAbort",
2322 BuiltinId::DomFetchSetTimeout => "fetchSetTimeout",
2323 BuiltinId::DomRoutePath => "routePath",
2324 BuiltinId::DomRouteQuery => "routeQuery",
2325 BuiltinId::DomNavigate => "navigate",
2326 BuiltinId::DomReplaceRoute => "replaceRoute",
2327 BuiltinId::DomOnRoute => "onRoute",
2328 BuiltinId::DomSetTitle => "setTitle",
2329 BuiltinId::DomSetHeadHtml => "setHeadHtml",
2330 BuiltinId::DomReload => "reloadPage",
2331 BuiltinId::DomGoBack => "goBack",
2332 BuiltinId::DomGetAttribute => "getAttribute",
2333 BuiltinId::DomOnWindowEvent => "onWindowEvent",
2334 BuiltinId::DomScrollGap => "scrollGap",
2335 BuiltinId::DomSetInterval => "setInterval",
2336 BuiltinId::DomEventFileName => "eventFileName",
2337 BuiltinId::DomElementCommand => "elementCommand",
2338 BuiltinId::DomClipboardWrite => "clipboardWrite",
2339 BuiltinId::DomDownloadFile => "downloadFile",
2340 BuiltinId::DomNotify => "notify",
2341 BuiltinId::DomPublish => "publish",
2342 BuiltinId::ReadBytes => "readBytes",
2343 BuiltinId::TryReadBytes => "tryReadBytes",
2344 BuiltinId::FileRead => "read",
2345 BuiltinId::FileWrite => "write",
2346 BuiltinId::VfsReadFile => "__logos_read_from_file",
2347 BuiltinId::VfsWriteFile => "__logos_write_to_file",
2348 BuiltinId::VfsMount => "__logos_mount_at",
2349 BuiltinId::RandomInt => "randomInt",
2350 BuiltinId::RandomFloat => "randomFloat",
2351 BuiltinId::EnvGet => "get",
2352 BuiltinId::TimeNow => "now",
2353 BuiltinId::EnvHas => "__logos_env_has",
2354 BuiltinId::EnvValue => "__logos_env_value",
2355 BuiltinId::SignalNew => "signal",
2359 BuiltinId::SignalSet => "signalSet",
2360 BuiltinId::SignalGetInt => "signalGetInt",
2361 BuiltinId::SignalGetText => "signalGetText",
2362 BuiltinId::SignalBeginRender => "beginRender",
2363 BuiltinId::SignalNewText => "signalNewText",
2364 BuiltinId::SignalSetText => "signalSetText",
2365 BuiltinId::SignalEnterComponent => "enterComponent",
2366 BuiltinId::SignalExitComponent => "exitComponent",
2367 BuiltinId::SignalNewSeq => "signalNewSeq",
2368 BuiltinId::SignalGetSeq => "signalGetSeq",
2369 BuiltinId::SignalSetSeq => "signalSetSeq",
2370 BuiltinId::SignalNewFloat => "signalNewFloat",
2371 BuiltinId::SignalGetFloat => "signalGetFloat",
2372 BuiltinId::SignalSetFloat => "signalSetFloat",
2373 BuiltinId::InspectUnhandledDynamic => "__logos_inspect_unhandled",
2374 BuiltinId::DomEventFileSize => "eventFileSize",
2375 BuiltinId::DomEventFileType => "eventFileType",
2376 BuiltinId::DomEventFileBytes => "eventFileBytes",
2377 BuiltinId::DomListenFlags => "listenFlags",
2378 BuiltinId::DomAssignLocation => "assignLocation",
2379 BuiltinId::DomJournalDetail => "journalDetail",
2380 };
2381 return Err(format!(
2382 "{}() takes exactly {} argument{}",
2383 name,
2384 expected,
2385 if expected == 1 { "" } else { "s" }
2386 ));
2387 }
2388 Ok(())
2389}
2390
2391fn ntt_stride(v: RuntimeValue, name: &str) -> Result<usize, String> {
2396 match v {
2397 RuntimeValue::Int(n @ (8 | 4 | 2 | 1)) => Ok(n as usize),
2399 RuntimeValue::Int(n) => Err(format!("{name} stride must be 8, 4, 2, or 1, got {n}")),
2400 other => Err(format!(
2401 "{name} stride must be an Int, got {}",
2402 other.type_name()
2403 )),
2404 }
2405}
2406
2407pub fn call_builtin(id: BuiltinId, args: Vec<RuntimeValue>) -> Result<RuntimeValue, String> {
2408 if let Some(builtin) = id.extension() {
2409 return logicaffeine_base::extension::call(builtin, args);
2410 }
2411 if id == BuiltinId::DefinedReal {
2412 return crate::semantics::defined::outside_a_run(args);
2413 }
2414 let mut args = args;
2415 match id {
2416 BuiltinId::MapOf => {
2417 let mut m = crate::interpreter::MapStorage::default();
2420 let mut it = args.into_iter();
2421 while let (Some(k), Some(v)) = (it.next(), it.next()) {
2422 crate::semantics::collections::assert_hashable_key(&k)?;
2423 m.insert(k, v);
2424 }
2425 Ok(RuntimeValue::Map(Rc::new(RefCell::new(m))))
2426 }
2427 BuiltinId::SetOf => {
2428 let set = RuntimeValue::Set(Rc::new(RefCell::new(Vec::new())));
2431 for v in args {
2432 crate::semantics::collections::set_add(&set, v)?;
2433 }
2434 Ok(set)
2435 }
2436 BuiltinId::RepeatSeq => {
2437 let count = args.remove(1);
2440 let element = args.remove(0);
2441 let n = match count {
2442 RuntimeValue::Int(n) => n.max(0) as usize,
2443 other => {
2444 return Err(format!(
2445 "repeatSeq count must be an Int, got {}",
2446 other.type_name()
2447 ))
2448 }
2449 };
2450 let slots: Vec<RuntimeValue> = (0..n).map(|_| element.deep_clone()).collect();
2451 Ok(RuntimeValue::List(Rc::new(RefCell::new(
2452 ListRepr::from_values(slots),
2453 ))))
2454 }
2455 BuiltinId::ReedSolomonEncode => {
2456 let parity = args.remove(1);
2459 let data = args.remove(0);
2460 let m = match parity {
2461 RuntimeValue::Int(n) if n > 0 => n as usize,
2462 RuntimeValue::Int(n) => {
2463 return Err(format!(
2464 "reedSolomonEncode parity count must be positive, got {}",
2465 n
2466 ))
2467 }
2468 other => {
2469 return Err(format!(
2470 "reedSolomonEncode parity count must be an Int, got {}",
2471 other.type_name()
2472 ))
2473 }
2474 };
2475 let shards = read_shards(&data)?;
2476 let k = shards.len();
2477 let rs = logicaffeine_base::fec::ReedSolomon::new(k, m).ok_or_else(|| {
2478 format!(
2479 "reedSolomonEncode: invalid code ({k} data + {m} parity) — need at least one \
2480 data shard, at least one parity shard, and a total of at most 256"
2481 )
2482 })?;
2483 let encoded = rs.encode(&shards).ok_or_else(|| {
2484 format!(
2485 "reedSolomonEncode: the {k} data shards must be non-empty and of equal length"
2486 )
2487 })?;
2488 Ok(shards_to_seq(&encoded))
2489 }
2490 BuiltinId::ReedSolomonRecover => {
2491 let kv = args.remove(1);
2494 let received = args.remove(0);
2495 let k = match kv {
2496 RuntimeValue::Int(n) if n > 0 => n as usize,
2497 RuntimeValue::Int(n) => {
2498 return Err(format!(
2499 "reedSolomonRecover data-shard count must be positive, got {}",
2500 n
2501 ))
2502 }
2503 other => {
2504 return Err(format!(
2505 "reedSolomonRecover data-shard count must be an Int, got {}",
2506 other.type_name()
2507 ))
2508 }
2509 };
2510 let slots = read_received(&received)?;
2511 let n = slots.len();
2512 if n <= k {
2513 return Err(format!(
2514 "reedSolomonRecover: {n} slots cannot carry {k} data shards plus parity"
2515 ));
2516 }
2517 let rs = logicaffeine_base::fec::ReedSolomon::new(k, n - k).ok_or_else(|| {
2518 format!(
2519 "reedSolomonRecover: invalid code ({k} data + {} parity)",
2520 n - k
2521 )
2522 })?;
2523 let recovered = rs.reconstruct(&slots).ok_or_else(|| {
2524 "reedSolomonRecover: insufficient surviving shards to reconstruct".to_string()
2525 })?;
2526 Ok(shards_to_seq(&recovered))
2527 }
2528 BuiltinId::FecProtect => {
2529 let m_arg = args.remove(2);
2532 let k_arg = args.remove(1);
2533 let payload_arg = args.remove(0);
2534 let k = read_positive_count(k_arg, "fecProtect data-shard count")?;
2535 let m = read_positive_count(m_arg, "fecProtect parity-shard count")?;
2536 let payload = byte_seq(&payload_arg)?;
2537 if payload.len() > u32::MAX as usize {
2538 return Err("fecProtect: payload is too large to frame (over 4 GiB)".to_string());
2539 }
2540 let mut framed = Vec::with_capacity(4 + payload.len());
2541 framed.extend_from_slice(&(payload.len() as u32).to_be_bytes());
2542 framed.extend_from_slice(&payload);
2543 let shard_len = (framed.len() + k - 1) / k; framed.resize(shard_len * k, 0); let shards: Vec<Vec<u8>> = framed.chunks(shard_len).map(|c| c.to_vec()).collect();
2546 let rs = logicaffeine_base::fec::ReedSolomon::new(k, m).ok_or_else(|| {
2547 format!("fecProtect: invalid code ({k} data + {m} parity; total must be ≤ 256)")
2548 })?;
2549 let encoded = rs
2550 .encode(&shards)
2551 .ok_or_else(|| "fecProtect: shard encoding failed".to_string())?;
2552 Ok(shards_to_seq(&encoded))
2553 }
2554 BuiltinId::FecRestore => {
2555 let k_arg = args.remove(1);
2558 let received_arg = args.remove(0);
2559 let k = read_positive_count(k_arg, "fecRestore data-shard count")?;
2560 let slots = read_received(&received_arg)?;
2561 let n = slots.len();
2562 if n <= k {
2563 return Err(format!(
2564 "fecRestore: {n} packets cannot carry {k} data shards plus parity"
2565 ));
2566 }
2567 let rs = logicaffeine_base::fec::ReedSolomon::new(k, n - k)
2568 .ok_or_else(|| format!("fecRestore: invalid code ({k} data + {} parity)", n - k))?;
2569 let recovered = rs.reconstruct(&slots).ok_or_else(|| {
2570 "fecRestore: insufficient surviving packets to reconstruct".to_string()
2571 })?;
2572 let mut framed: Vec<u8> = Vec::new();
2573 for shard in recovered.iter().take(k) {
2574 framed.extend_from_slice(shard);
2575 }
2576 if framed.len() < 4 {
2577 return Err(
2578 "fecRestore: recovered data is too short for a length header".to_string(),
2579 );
2580 }
2581 let len = u32::from_be_bytes([framed[0], framed[1], framed[2], framed[3]]) as usize;
2582 if 4 + len > framed.len() {
2583 return Err("fecRestore: length header exceeds the recovered data".to_string());
2584 }
2585 Ok(bytes_to_seq(&framed[4..4 + len]))
2586 }
2587 BuiltinId::Length => {
2588 let val = args.remove(0);
2589 match &val {
2590 RuntimeValue::List(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
2591 RuntimeValue::Text(s) => Ok(RuntimeValue::Int(s.len() as i64)),
2592 RuntimeValue::Map(map) => Ok(RuntimeValue::Int(map.borrow().len() as i64)),
2593 _ => Err(format!("Cannot get length of {}", val.type_name())),
2594 }
2595 }
2596 BuiltinId::Contains => {
2597 let needle = args.remove(1);
2598 let haystack = args.remove(0);
2599 match (&haystack, &needle) {
2600 (RuntimeValue::Text(h), RuntimeValue::Text(n)) => {
2601 Ok(RuntimeValue::Bool(h.contains(n.as_str())))
2602 }
2603 _ => Err(format!(
2604 "contains expects two Text arguments, got {} and {}",
2605 haystack.type_name(),
2606 needle.type_name()
2607 )),
2608 }
2609 }
2610 BuiltinId::Format => {
2611 if args.is_empty() {
2612 return Ok(RuntimeValue::Text(Rc::new(String::new())));
2613 }
2614 let val = args.remove(0);
2615 Ok(RuntimeValue::Text(Rc::new(val.to_display_string())))
2616 }
2617 BuiltinId::ParseInt => {
2618 let val = args.remove(0);
2619 if let RuntimeValue::Text(s) = &val {
2620 Ok(RuntimeValue::Int(
2621 s.trim()
2622 .parse::<i64>()
2623 .map_err(|_| format!("Cannot parse '{}' as Int", s))?,
2624 ))
2625 } else {
2626 Err("parseInt requires a Text argument".to_string())
2627 }
2628 }
2629 BuiltinId::ParseFloat => {
2630 let val = args.remove(0);
2631 if let RuntimeValue::Text(s) = &val {
2632 Ok(RuntimeValue::Float(
2633 s.trim()
2634 .parse::<f64>()
2635 .map_err(|_| format!("Cannot parse '{}' as Float", s))?,
2636 ))
2637 } else {
2638 Err("parseFloat requires a Text argument".to_string())
2639 }
2640 }
2641 BuiltinId::Chr => {
2642 let val = args.remove(0);
2643 if let RuntimeValue::Int(code) = val {
2644 match char::from_u32(code as u32) {
2645 Some(c) => Ok(RuntimeValue::Text(Rc::new(c.to_string()))),
2646 None => Err(format!("Invalid character code: {}", code)),
2647 }
2648 } else {
2649 Err("chr() requires an Int argument".to_string())
2650 }
2651 }
2652 BuiltinId::Abs => {
2653 let val = args.remove(0);
2654 match val {
2655 RuntimeValue::Int(n) => Ok(match n.checked_abs() {
2658 Some(a) => RuntimeValue::Int(a),
2659 None => RuntimeValue::from_bigint(logicaffeine_base::BigInt::from_i64(n).abs()),
2660 }),
2661 RuntimeValue::BigInt(b) => Ok(RuntimeValue::from_bigint(b.abs())),
2662 RuntimeValue::Rational(r) => Ok(RuntimeValue::from_rational(r.abs())),
2664 RuntimeValue::Decimal(d) => Ok(RuntimeValue::Decimal(Rc::new(d.abs()))),
2666 RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.abs_f64())),
2668 RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.abs())),
2670 RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f.abs())),
2671 _ => Err(format!("abs() requires a number, got {}", val.type_name())),
2672 }
2673 }
2674 BuiltinId::Sqrt => {
2675 let val = args.remove(0);
2676 match val {
2677 RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f.sqrt())),
2678 RuntimeValue::Int(n) => Ok(RuntimeValue::Float((n as f64).sqrt())),
2679 RuntimeValue::BigInt(b) => Ok(RuntimeValue::Float(b.to_f64().sqrt())),
2680 RuntimeValue::ComplexF(c) => Ok(RuntimeValue::ComplexF(Rc::new(c.sqrt()))),
2683 RuntimeValue::Complex(c) => {
2685 let cf = logicaffeine_base::ComplexF::new(c.re().to_f64(), c.im().to_f64());
2686 Ok(RuntimeValue::ComplexF(Rc::new(cf.sqrt())))
2687 }
2688 _ => Err(format!("sqrt() requires a number, got {}", val.type_name())),
2689 }
2690 }
2691 BuiltinId::Infinitesimal
2692 | BuiltinId::StandardPart
2693 | BuiltinId::IsInfinitesimal
2694 | BuiltinId::IsLimited
2695 | BuiltinId::InfinitelyClose
2696 | BuiltinId::GeneratorOf
2697 | BuiltinId::LimitOf
2698 | BuiltinId::Provisional
2699 | BuiltinId::AtTheLimit
2700 | BuiltinId::TripCount
2701 | BuiltinId::AffinePower
2702 | BuiltinId::PolynomialFlow
2703 | BuiltinId::HybridFlow
2704 | BuiltinId::FirstExit
2705 | BuiltinId::CycleAt
2706 | BuiltinId::SearchCandidates
2707 | BuiltinId::StateSize
2708 | BuiltinId::EveryNatural
2709 | BuiltinId::ExactSqrt
2710 | BuiltinId::ExactExp
2711 | BuiltinId::ExactLn
2712 | BuiltinId::ExactPi
2713 | BuiltinId::ExactE
2714 | BuiltinId::ExactOmega
2715 | BuiltinId::ExactPower
2716 | BuiltinId::OrderedInfinitesimal => unreachable!("answered by logicaffeine_base::extension above"),
2717 BuiltinId::DefinedReal => unreachable!("refused by semantics::defined above"),
2718 BuiltinId::Conjugate => {
2719 let val = args.remove(0);
2720 match val {
2721 RuntimeValue::Complex(c) => Ok(RuntimeValue::Complex(Rc::new(c.conjugate()))),
2724 RuntimeValue::ComplexF(c) => Ok(RuntimeValue::ComplexF(Rc::new(c.conjugate()))),
2725 RuntimeValue::Int(_)
2728 | RuntimeValue::BigInt(_)
2729 | RuntimeValue::Rational(_)
2730 | RuntimeValue::Decimal(_)
2731 | RuntimeValue::Float(_) => Ok(val),
2732 _ => Err(format!(
2733 "conjugate() requires a number, got {}",
2734 val.type_name()
2735 )),
2736 }
2737 }
2738 BuiltinId::RealPart => {
2739 let val = args.remove(0);
2740 match val {
2741 RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.re())),
2742 RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.re().to_f64())),
2743 RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f)),
2744 RuntimeValue::Int(n) => Ok(RuntimeValue::Float(n as f64)),
2745 RuntimeValue::BigInt(b) => Ok(RuntimeValue::Float(b.to_f64())),
2746 RuntimeValue::Rational(r) => Ok(RuntimeValue::Float(r.to_f64())),
2747 _ => Err(format!("re() requires a number, got {}", val.type_name())),
2748 }
2749 }
2750 BuiltinId::ImagPart => {
2751 let val = args.remove(0);
2752 match val {
2753 RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.im())),
2754 RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.im().to_f64())),
2755 RuntimeValue::Float(_)
2757 | RuntimeValue::Int(_)
2758 | RuntimeValue::BigInt(_)
2759 | RuntimeValue::Rational(_) => Ok(RuntimeValue::Float(0.0)),
2760 _ => Err(format!("im() requires a number, got {}", val.type_name())),
2761 }
2762 }
2763 BuiltinId::Min => {
2764 let b = args.remove(1);
2765 let a = args.remove(0);
2766 match (&a, &b) {
2767 (RuntimeValue::Int(x), RuntimeValue::Int(y)) => Ok(RuntimeValue::Int(*x.min(y))),
2768 (RuntimeValue::Float(x), RuntimeValue::Float(y)) => {
2769 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x, *y)))
2770 }
2771 (RuntimeValue::Int(x), RuntimeValue::Float(y)) => {
2772 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x as f64, *y)))
2773 }
2774 (RuntimeValue::Float(x), RuntimeValue::Int(y)) => {
2775 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x, *y as f64)))
2776 }
2777 (RuntimeValue::Decimal(x), RuntimeValue::Decimal(y)) => {
2779 Ok(RuntimeValue::Decimal(if x <= y {
2780 x.clone()
2781 } else {
2782 y.clone()
2783 }))
2784 }
2785 _ => Err("min() requires numbers".to_string()),
2786 }
2787 }
2788 BuiltinId::Max => {
2789 let b = args.remove(1);
2790 let a = args.remove(0);
2791 match (&a, &b) {
2792 (RuntimeValue::Int(x), RuntimeValue::Int(y)) => Ok(RuntimeValue::Int(*x.max(y))),
2793 (RuntimeValue::Float(x), RuntimeValue::Float(y)) => {
2794 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x, *y)))
2795 }
2796 (RuntimeValue::Int(x), RuntimeValue::Float(y)) => {
2797 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x as f64, *y)))
2798 }
2799 (RuntimeValue::Float(x), RuntimeValue::Int(y)) => {
2800 Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x, *y as f64)))
2801 }
2802 (RuntimeValue::Decimal(x), RuntimeValue::Decimal(y)) => {
2804 Ok(RuntimeValue::Decimal(if x >= y {
2805 x.clone()
2806 } else {
2807 y.clone()
2808 }))
2809 }
2810 _ => Err("max() requires numbers".to_string()),
2811 }
2812 }
2813 BuiltinId::Floor => {
2814 let val = args.remove(0);
2815 let recurse = |x| call_builtin(BuiltinId::Floor, vec![x]);
2816 if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Floor, &recurse) {
2817 return r;
2818 }
2819 match &val {
2822 RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.floor() as i64)),
2823 RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2824 RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.floor())),
2825 RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().floor())),
2826 _ => Err(format!(
2827 "floor() requires a number, got {}",
2828 val.type_name()
2829 )),
2830 }
2831 }
2832 BuiltinId::Ceil => {
2833 let val = args.remove(0);
2834 let recurse = |x| call_builtin(BuiltinId::Ceil, vec![x]);
2835 if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Ceil, &recurse) {
2836 return r;
2837 }
2838 match &val {
2839 RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.ceil() as i64)),
2840 RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2841 RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.ceil())),
2842 RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().ceil())),
2843 _ => Err(format!("ceil() requires a number, got {}", val.type_name())),
2844 }
2845 }
2846 BuiltinId::Round => {
2847 let val = args.remove(0);
2848 let recurse = |x| call_builtin(BuiltinId::Round, vec![x]);
2849 if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Nearest, &recurse) {
2850 return r;
2851 }
2852 match &val {
2853 RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.round() as i64)),
2854 RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2855 RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.round())),
2856 RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().round())),
2857 _ => Err(format!(
2858 "round() requires a number, got {}",
2859 val.type_name()
2860 )),
2861 }
2862 }
2863 BuiltinId::Pow => {
2864 let exp = args.remove(1);
2865 let base = args.remove(0);
2866 match (&base, &exp) {
2867 (RuntimeValue::Int(b), RuntimeValue::Int(e)) => {
2871 if *e >= 0 {
2872 Ok(match b.checked_pow(*e as u32) {
2873 Some(p) => RuntimeValue::Int(p),
2874 None => RuntimeValue::from_bigint(
2875 logicaffeine_base::BigInt::from_i64(*b).pow(*e as u32),
2876 ),
2877 })
2878 } else {
2879 Ok(RuntimeValue::Float((*b as f64).powi(*e as i32)))
2880 }
2881 }
2882 (RuntimeValue::BigInt(b), RuntimeValue::Int(e)) => {
2883 if *e >= 0 {
2884 Ok(RuntimeValue::from_bigint(b.pow(*e as u32)))
2885 } else {
2886 Ok(RuntimeValue::Float(b.to_f64().powi(*e as i32)))
2887 }
2888 }
2889 (RuntimeValue::Float(b), RuntimeValue::Int(e)) => {
2890 Ok(RuntimeValue::Float(b.powi(*e as i32)))
2891 }
2892 (RuntimeValue::Float(b), RuntimeValue::Float(e)) => {
2893 Ok(RuntimeValue::Float(b.powf(*e)))
2894 }
2895 (RuntimeValue::Int(b), RuntimeValue::Float(e)) => {
2896 Ok(RuntimeValue::Float((*b as f64).powf(*e)))
2897 }
2898 (RuntimeValue::Modular(b), RuntimeValue::Int(e)) if *e >= 0 => {
2900 Ok(RuntimeValue::Modular(Rc::new(b.pow(*e as u64))))
2901 }
2902 _ => Err("pow() requires numbers".to_string()),
2903 }
2904 }
2905 BuiltinId::Decimal => {
2906 let val = args.remove(0);
2907 match &val {
2908 RuntimeValue::Text(s) => Decimal::parse(s)
2910 .map(|d| RuntimeValue::Decimal(Rc::new(d)))
2911 .ok_or_else(|| logicaffeine_data::failure::not_a_decimal(s)),
2912 RuntimeValue::Int(n) => Ok(RuntimeValue::Decimal(Rc::new(Decimal::from_i64(*n)))),
2914 RuntimeValue::BigInt(b) => Decimal::parse(&b.to_string())
2915 .map(|d| RuntimeValue::Decimal(Rc::new(d)))
2916 .ok_or_else(|| logicaffeine_data::failure::not_a_decimal(&b.to_string())),
2917 RuntimeValue::Decimal(_) => Ok(val.clone()),
2919 _ => Err(logicaffeine_data::failure::decimal_needs_text_or_int(
2920 val.type_name(),
2921 )),
2922 }
2923 }
2924 BuiltinId::Complex => {
2925 let im = args.remove(1);
2926 let re = args.remove(0);
2927 let to_rat = |v: &RuntimeValue| -> Option<logicaffeine_base::Rational> {
2928 match v {
2929 RuntimeValue::Int(n) => Some(logicaffeine_base::Rational::from_i64(*n)),
2930 RuntimeValue::BigInt(b) => {
2931 Some(logicaffeine_base::Rational::from_bigint((**b).clone()))
2932 }
2933 RuntimeValue::Rational(r) => Some((**r).clone()),
2934 RuntimeValue::Decimal(d) => Some(d.to_rational()),
2935 _ => None,
2936 }
2937 };
2938 let has_float =
2942 matches!(re, RuntimeValue::Float(_)) || matches!(im, RuntimeValue::Float(_));
2943 if has_float {
2944 let to_f = |v: &RuntimeValue| -> Option<f64> {
2945 if let RuntimeValue::Float(f) = v {
2946 Some(*f)
2947 } else {
2948 to_rat(v).map(|r| r.to_f64())
2949 }
2950 };
2951 match (to_f(&re), to_f(&im)) {
2952 (Some(a), Some(b)) => Ok(RuntimeValue::ComplexF(Rc::new(
2953 logicaffeine_base::ComplexF::new(a, b),
2954 ))),
2955 _ => Err(format!(
2956 "complex() requires two real numbers, got {} and {}",
2957 re.type_name(),
2958 im.type_name()
2959 )),
2960 }
2961 } else {
2962 match (to_rat(&re), to_rat(&im)) {
2963 (Some(re_r), Some(im_r)) => Ok(RuntimeValue::Complex(Rc::new(
2964 logicaffeine_base::Complex::new(re_r, im_r),
2965 ))),
2966 _ => Err(format!(
2967 "complex() requires two real numbers, got {} and {}",
2968 re.type_name(),
2969 im.type_name()
2970 )),
2971 }
2972 }
2973 }
2974 BuiltinId::Modular => {
2975 let modulus = args.remove(1);
2976 let value = args.remove(0);
2977 let to_int = |v: &RuntimeValue| -> Option<logicaffeine_base::BigInt> {
2978 match v {
2979 RuntimeValue::Int(n) => Some(logicaffeine_base::BigInt::from_i64(*n)),
2980 RuntimeValue::BigInt(b) => Some((**b).clone()),
2981 _ => None,
2982 }
2983 };
2984 match (to_int(&value), to_int(&modulus)) {
2985 (Some(v), Some(n)) => match logicaffeine_base::Modular::new(v, n) {
2986 Some(m) => Ok(RuntimeValue::Modular(Rc::new(m))),
2987 None => Err(logicaffeine_data::failure::MODULUS_NOT_POSITIVE.to_string()),
2988 },
2989 _ => Err(format!(
2990 "modular() requires two integers, got {} and {}",
2991 value.type_name(),
2992 modulus.type_name()
2993 )),
2994 }
2995 }
2996 BuiltinId::Quantity => {
2997 let unit_arg = args.remove(1);
2998 let value = args.remove(0);
2999 let magnitude = match &value {
3002 RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3003 RuntimeValue::BigInt(b) => logicaffeine_base::Rational::from_bigint((**b).clone()),
3004 RuntimeValue::Rational(r) => (**r).clone(),
3005 RuntimeValue::Decimal(d) => d.to_rational(),
3006 _ => {
3007 return Err(format!(
3008 "quantity() requires an exact number, got {}",
3009 value.type_name()
3010 ))
3011 }
3012 };
3013 let unit = match &unit_arg {
3014 RuntimeValue::Text(s) => logicaffeine_base::quantity::units::by_name(s)
3015 .ok_or_else(|| logicaffeine_data::failure::unknown_unit(s))?,
3016 _ => {
3017 return Err(format!(
3018 "quantity() requires a unit name (Text), got {}",
3019 unit_arg.type_name()
3020 ))
3021 }
3022 };
3023 let q = logicaffeine_base::Quantity::of(magnitude, &unit);
3024 Ok(RuntimeValue::Quantity(Rc::new(
3025 crate::interpreter::QuantityValue { q, unit },
3026 )))
3027 }
3028 BuiltinId::Money => {
3029 let code_arg = args.remove(1);
3030 let value = args.remove(0);
3031 let amount = match &value {
3034 RuntimeValue::Int(n) => logicaffeine_base::Decimal::from_i64(*n),
3035 RuntimeValue::Decimal(d) => (**d).clone(),
3036 _ => {
3037 return Err(format!(
3038 "money() requires an exact base-10 amount (Int or Decimal), got {}",
3039 value.type_name()
3040 ))
3041 }
3042 };
3043 let currency = match &code_arg {
3044 RuntimeValue::Text(s) => logicaffeine_base::money::currency::by_code(s)
3045 .ok_or_else(|| logicaffeine_data::failure::unknown_currency(s))?,
3046 _ => {
3047 return Err(format!(
3048 "money() requires a currency code (Text), got {}",
3049 code_arg.type_name()
3050 ))
3051 }
3052 };
3053 Ok(RuntimeValue::Money(Rc::new(logicaffeine_base::Money::of(
3054 amount, currency,
3055 ))))
3056 }
3057 BuiltinId::SetRate => {
3058 let rate_arg = args.remove(1);
3059 let code_arg = args.remove(0);
3060 let code = match &code_arg {
3061 RuntimeValue::Text(s) => s.to_string(),
3062 _ => {
3063 return Err(format!(
3064 "set_rate() requires a currency code (Text), got {}",
3065 code_arg.type_name()
3066 ))
3067 }
3068 };
3069 let rate = match &rate_arg {
3070 RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3071 RuntimeValue::Decimal(d) => d.to_rational(),
3072 RuntimeValue::Rational(r) => (**r).clone(),
3073 _ => {
3074 return Err(format!(
3075 "set_rate() requires an exact rate (Int/Decimal), got {}",
3076 rate_arg.type_name()
3077 ))
3078 }
3079 };
3080 logicaffeine_base::money::set_ambient_rate(&code, rate);
3081 Ok(RuntimeValue::Nothing)
3082 }
3083 BuiltinId::SetRates => {
3084 let table = args.remove(0);
3085 let map = match &table {
3086 RuntimeValue::Map(m) => m,
3087 _ => {
3088 return Err(format!(
3089 "set_rates() requires a Map of currency code to rate, got {}",
3090 table.type_name()
3091 ))
3092 }
3093 };
3094 for (key, value) in map.borrow().iter() {
3095 let code = match key {
3096 RuntimeValue::Text(s) => s.to_string(),
3097 _ => {
3098 return Err(format!(
3099 "set_rates() keys must be currency codes (Text), got {}",
3100 key.type_name()
3101 ))
3102 }
3103 };
3104 let rate = match value {
3105 RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3106 RuntimeValue::Decimal(d) => d.to_rational(),
3107 RuntimeValue::Rational(r) => (**r).clone(),
3108 _ => {
3109 return Err(format!(
3110 "set_rates() values must be exact rates (Int/Decimal), got {}",
3111 value.type_name()
3112 ))
3113 }
3114 };
3115 logicaffeine_base::money::set_ambient_rate(&code, rate);
3116 }
3117 Ok(RuntimeValue::Nothing)
3118 }
3119 BuiltinId::Uuid => {
3120 let arg = args.remove(0);
3121 match &arg {
3122 RuntimeValue::Text(s) => logicaffeine_base::Uuid::parse(s)
3123 .map(|u| RuntimeValue::Uuid(Rc::new(u)))
3124 .ok_or_else(|| logicaffeine_data::failure::invalid_uuid(s)),
3125 _ => Err(format!("uuid() requires text, got {}", arg.type_name())),
3126 }
3127 }
3128 BuiltinId::UuidNil => Ok(RuntimeValue::Uuid(Rc::new(logicaffeine_base::Uuid::NIL))),
3129 BuiltinId::UuidMax => Ok(RuntimeValue::Uuid(Rc::new(logicaffeine_base::Uuid::MAX))),
3130 BuiltinId::UuidDns => Ok(RuntimeValue::Uuid(Rc::new(
3131 logicaffeine_base::Uuid::NAMESPACE_DNS,
3132 ))),
3133 BuiltinId::UuidUrl => Ok(RuntimeValue::Uuid(Rc::new(
3134 logicaffeine_base::Uuid::NAMESPACE_URL,
3135 ))),
3136 BuiltinId::UuidOid => Ok(RuntimeValue::Uuid(Rc::new(
3137 logicaffeine_base::Uuid::NAMESPACE_OID,
3138 ))),
3139 BuiltinId::UuidX500 => Ok(RuntimeValue::Uuid(Rc::new(
3140 logicaffeine_base::Uuid::NAMESPACE_X500,
3141 ))),
3142 BuiltinId::UuidVersion => {
3143 let arg = args.remove(0);
3144 match &arg {
3145 RuntimeValue::Uuid(u) => Ok(RuntimeValue::Int(u.version() as i64)),
3146 _ => Err(format!(
3147 "uuid_version() requires a Uuid, got {}",
3148 arg.type_name()
3149 )),
3150 }
3151 }
3152 BuiltinId::TextBytes => {
3153 let arg = args.remove(0);
3154 match &arg {
3155 RuntimeValue::Text(s) => Ok(bytes_to_seq(s.as_bytes())),
3156 _ => Err(format!(
3157 "text_bytes() requires text, got {}",
3158 arg.type_name()
3159 )),
3160 }
3161 }
3162 BuiltinId::TextFromBytes => {
3163 let bytes = byte_seq(&args.remove(0))?;
3164 match String::from_utf8(bytes) {
3165 Ok(s) => Ok(RuntimeValue::Text(Rc::new(s))),
3166 Err(e) => Err(logicaffeine_data::failure::invalid_utf8(e)),
3167 }
3168 }
3169 BuiltinId::WireBytes => {
3170 let arg = args.remove(0);
3171 match crate::concurrency::marshal::encode_value_raw(&arg) {
3172 Ok(bytes) => Ok(bytes_to_seq(&bytes)),
3173 Err(e) => Err(format!("wireBytes(): {}", e)),
3174 }
3175 }
3176 BuiltinId::CompressBytes => {
3177 let bytes = byte_seq(&args.remove(0))?;
3178 Ok(bytes_to_seq(&crate::concurrency::marshal::compress_best(
3179 &bytes,
3180 )))
3181 }
3182 BuiltinId::DecompressBytes => {
3183 let frame = byte_seq(&args.remove(0))?;
3184 match crate::concurrency::marshal::decompress_any(&frame) {
3185 Some(bytes) => Ok(bytes_to_seq(&bytes)),
3186 None => {
3187 Err("decompressBytes(): malformed or oversized compressed frame".to_string())
3188 }
3189 }
3190 }
3191 BuiltinId::SealBytes => {
3192 let key = read_aead_key(&args.remove(0), "sealBytes")?;
3193 let nonce = read_aead_nonce(&args.remove(0), "sealBytes")?;
3194 let plaintext = exact_byte_seq("sealBytes", "plaintext", &args.remove(0))?;
3195 let sealed =
3198 logicaffeine_system::aead::chacha20poly1305_seal(&key, &nonce, &[], &plaintext);
3199 Ok(bytes_to_seq(&sealed))
3200 }
3201 BuiltinId::OpenBytes => {
3202 let key = read_aead_key(&args.remove(0), "openBytes")?;
3203 let nonce = read_aead_nonce(&args.remove(0), "openBytes")?;
3204 let sealed = exact_byte_seq("openBytes", "sealed frame", &args.remove(0))?;
3205 let plaintext = logicaffeine_system::aead::chacha20poly1305_open(&key, &nonce, &[], &sealed)
3206 .ok_or_else(|| {
3207 "openBytes(): authentication failed — the frame was tampered, truncated, or the key is wrong".to_string()
3208 })?;
3209 Ok(bytes_to_seq(&plaintext))
3210 }
3211 BuiltinId::FromWireBytes => {
3212 let bytes = byte_seq(&args.remove(0))?;
3213 crate::concurrency::marshal::decode_value_raw(&bytes)
3214 .ok_or_else(|| "fromWireBytes(): malformed or trailing-byte wire input".to_string())
3215 }
3216 BuiltinId::SealFrame => {
3217 let key = read_aead_key(&args.remove(0), "sealFrame")?;
3218 let nonce = read_aead_nonce(&args.remove(0), "sealFrame")?;
3219 let value = args.remove(0);
3220 let wire = crate::concurrency::marshal::encode_value_raw(&value)
3223 .map_err(|e| format!("sealFrame(): {}", e))?;
3224 let sealed = logicaffeine_system::aead::chacha20poly1305_seal(&key, &nonce, &[], &wire);
3225 Ok(bytes_to_seq(&sealed))
3226 }
3227 BuiltinId::OpenFrame => {
3228 let key = read_aead_key(&args.remove(0), "openFrame")?;
3229 let nonce = read_aead_nonce(&args.remove(0), "openFrame")?;
3230 let sealed = exact_byte_seq("openFrame", "sealed frame", &args.remove(0))?;
3231 let wire = logicaffeine_system::aead::chacha20poly1305_open(&key, &nonce, &[], &sealed)
3232 .ok_or_else(|| {
3233 "openFrame(): authentication failed — the frame was tampered, truncated, or the key is wrong".to_string()
3234 })?;
3235 crate::concurrency::marshal::decode_value_raw(&wire)
3236 .ok_or_else(|| "openFrame(): malformed wire value after decryption".to_string())
3237 }
3238 BuiltinId::SealBox => {
3239 let key = read_aead_key(&args.remove(0), "sealBox")?;
3240 let plaintext = exact_byte_seq("sealBox", "plaintext", &args.remove(0))?;
3241 let sealed = logicaffeine_system::aead::seal_box(
3242 &key,
3243 logicaffeine_system::aead::BOX_BYTES_LABEL,
3244 &plaintext,
3245 )
3246 .map_err(|why| format!("sealBox(): {why}"))?;
3247 Ok(bytes_to_seq(&sealed))
3248 }
3249 BuiltinId::OpenBox => {
3250 let key = read_aead_key(&args.remove(0), "openBox")?;
3251 let sealed = read_box(&args.remove(0), "openBox")?;
3252 let plaintext =
3253 logicaffeine_system::aead::open_box(&key, logicaffeine_system::aead::BOX_BYTES_LABEL, &sealed)
3254 .ok_or_else(|| box_refused("openBox"))?;
3255 Ok(bytes_to_seq(&plaintext))
3256 }
3257 BuiltinId::SealValueBox => {
3258 let key = read_aead_key(&args.remove(0), "sealValueBox")?;
3259 let wire = crate::concurrency::marshal::encode_value_raw(&args.remove(0))
3260 .map_err(|e| format!("sealValueBox(): {e}"))?;
3261 let sealed =
3262 logicaffeine_system::aead::seal_box(&key, logicaffeine_system::aead::BOX_VALUE_LABEL, &wire)
3263 .map_err(|why| format!("sealValueBox(): {why}"))?;
3264 Ok(bytes_to_seq(&sealed))
3265 }
3266 BuiltinId::OpenValueBox => {
3267 let key = read_aead_key(&args.remove(0), "openValueBox")?;
3268 let sealed = read_box(&args.remove(0), "openValueBox")?;
3269 let wire =
3270 logicaffeine_system::aead::open_box(&key, logicaffeine_system::aead::BOX_VALUE_LABEL, &sealed)
3271 .ok_or_else(|| box_refused("openValueBox"))?;
3272 crate::concurrency::marshal::decode_value_raw(&wire)
3273 .ok_or_else(|| "openValueBox(): malformed wire value after decryption".to_string())
3274 }
3275 BuiltinId::ReadWireProgram => {
3276 use std::io::Read;
3277 let mut len = [0u8; 4];
3278 if std::io::stdin().read_exact(&mut len).is_err() {
3279 std::process::exit(0);
3280 }
3281 let n = u32::from_le_bytes(len) as usize;
3282 let mut buf = vec![0u8; n];
3283 std::io::stdin()
3284 .read_exact(&mut buf)
3285 .map_err(|e| format!("readWireProgram(): frame read failed: {e}"))?;
3286 crate::concurrency::marshal::decode_value_raw(&buf)
3287 .ok_or_else(|| "readWireProgram(): malformed wire program".to_string())
3288 }
3289 BuiltinId::WriteWireResidual => {
3290 use std::io::Write;
3291 let arg = args.remove(0);
3292 let s = match &arg {
3293 RuntimeValue::Text(t) => (**t).clone(),
3294 _ => return Err("writeWireResidual() expects text".to_string()),
3295 };
3296 let b = s.as_bytes();
3297 let out = std::io::stdout();
3298 let mut h = out.lock();
3299 h.write_all(&(b.len() as u32).to_le_bytes())
3300 .and_then(|_| h.write_all(b))
3301 .and_then(|_| h.flush())
3302 .map_err(|e| format!("writeWireResidual(): {e}"))?;
3303 Ok(RuntimeValue::Int(b.len() as i64))
3304 }
3305 BuiltinId::UuidBytes => {
3306 let arg = args.remove(0);
3307 match &arg {
3308 RuntimeValue::Uuid(u) => Ok(bytes_to_seq(u.as_bytes())),
3309 _ => Err(format!(
3310 "uuid_bytes() requires a Uuid, got {}",
3311 arg.type_name()
3312 )),
3313 }
3314 }
3315 BuiltinId::UuidFromBytes => {
3316 let bytes = byte_seq(&args.remove(0))?;
3317 if bytes.len() < 16 {
3318 return Err(logicaffeine_data::failure::uuid_needs_16_bytes(bytes.len()));
3319 }
3320 let mut b = [0u8; 16];
3321 b.copy_from_slice(&bytes[..16]);
3322 Ok(RuntimeValue::Uuid(Rc::new(
3323 logicaffeine_base::Uuid::from_bytes(b),
3324 )))
3325 }
3326 BuiltinId::ToCurrency => {
3327 let code_arg = args.remove(1);
3328 let money = args.remove(0);
3329 match (&money, &code_arg) {
3330 (RuntimeValue::Money(m), RuntimeValue::Text(code)) => {
3331 let to = logicaffeine_base::money::currency::by_code(code)
3332 .ok_or_else(|| logicaffeine_data::failure::unknown_currency(code))?;
3333 logicaffeine_base::money::ambient_convert(m, to)
3334 .map(|c| RuntimeValue::Money(Rc::new(c)))
3335 .ok_or_else(|| {
3336 if logicaffeine_base::money::has_ambient_rates() {
3337 logicaffeine_data::failure::no_exchange_rate(
3338 m.currency.code,
3339 to.code,
3340 )
3341 } else {
3342 logicaffeine_data::failure::NO_EXCHANGE_RATES.to_string()
3343 }
3344 })
3345 }
3346 _ => Err(format!(
3347 "to_currency() requires money and a currency code, got {} and {}",
3348 money.type_name(),
3349 code_arg.type_name()
3350 )),
3351 }
3352 }
3353 BuiltinId::Convert => {
3354 let unit_arg = args.remove(1);
3355 let value = args.remove(0);
3356 let unit = match &unit_arg {
3357 RuntimeValue::Text(s) => logicaffeine_base::quantity::units::by_name(s)
3358 .ok_or_else(|| logicaffeine_data::failure::unknown_unit(s))?,
3359 _ => {
3360 return Err(format!(
3361 "convert() requires a unit name (Text), got {}",
3362 unit_arg.type_name()
3363 ))
3364 }
3365 };
3366 match &value {
3367 RuntimeValue::Quantity(qv) => {
3370 if qv.q.dimension() != unit.dimension {
3371 return Err(logicaffeine_data::failure::cannot_convert(
3372 qv.unit.symbol,
3373 unit.symbol,
3374 ));
3375 }
3376 Ok(RuntimeValue::Quantity(Rc::new(
3377 crate::interpreter::QuantityValue {
3378 q: qv.q.clone(),
3379 unit,
3380 },
3381 )))
3382 }
3383 _ => Err(format!(
3384 "convert() requires a quantity, got {}",
3385 value.type_name()
3386 )),
3387 }
3388 }
3389 BuiltinId::ParseTimestamp => {
3390 let val = args.remove(0);
3391 match &val {
3392 RuntimeValue::Text(s) => logicaffeine_base::temporal::parse_rfc3339(s.trim())
3393 .map(RuntimeValue::Moment)
3394 .ok_or_else(|| logicaffeine_data::failure::not_a_timestamp(s)),
3395 _ => Err(format!(
3396 "parse_timestamp() requires a Text, got {}",
3397 val.type_name()
3398 )),
3399 }
3400 }
3401 BuiltinId::FormatTimestamp => {
3402 let val = args.remove(0);
3403 match &val {
3404 RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Text(Rc::new(
3405 logicaffeine_base::temporal::format_rfc3339(*nanos),
3406 ))),
3407 _ => Err(format!(
3408 "format_timestamp() requires a Moment, got {}",
3409 val.type_name()
3410 )),
3411 }
3412 }
3413 BuiltinId::YearOf
3414 | BuiltinId::MonthOf
3415 | BuiltinId::DayOf
3416 | BuiltinId::WeekdayOf
3417 | BuiltinId::WeekOf
3418 | BuiltinId::QuarterOf
3419 | BuiltinId::HourOf
3420 | BuiltinId::MinuteOf
3421 | BuiltinId::SecondOf => {
3422 let val = args.remove(0);
3423 match &val {
3424 RuntimeValue::Moment(nanos) => {
3425 use logicaffeine_base::temporal;
3426 let civil = temporal::civil_from_unix_nanos(*nanos);
3427 let component = match id {
3428 BuiltinId::YearOf => civil.year,
3429 BuiltinId::MonthOf => civil.month as i64,
3430 BuiltinId::DayOf => civil.day as i64,
3431 BuiltinId::HourOf => civil.hour as i64,
3432 BuiltinId::MinuteOf => civil.minute as i64,
3433 BuiltinId::SecondOf => civil.second as i64,
3434 BuiltinId::WeekdayOf => temporal::iso_weekday_from_days(
3435 nanos.div_euclid(temporal::NANOS_PER_DAY),
3436 ) as i64,
3437 BuiltinId::WeekOf => {
3438 temporal::iso_week_from_days(nanos.div_euclid(temporal::NANOS_PER_DAY))
3439 .1 as i64
3440 }
3441 BuiltinId::QuarterOf => (civil.month as i64 - 1) / 3 + 1,
3442 _ => unreachable!(),
3443 };
3444 Ok(RuntimeValue::Int(component))
3445 }
3446 RuntimeValue::Date(days) => {
3449 use logicaffeine_base::temporal;
3450 let (y, m, d) = temporal::civil_from_days(*days as i64);
3451 let component = match id {
3452 BuiltinId::YearOf => y,
3453 BuiltinId::MonthOf => m as i64,
3454 BuiltinId::DayOf => d as i64,
3455 BuiltinId::WeekdayOf => {
3456 temporal::iso_weekday_from_days(*days as i64) as i64
3457 }
3458 BuiltinId::WeekOf => temporal::iso_week_from_days(*days as i64).1 as i64,
3459 BuiltinId::QuarterOf => (m as i64 - 1) / 3 + 1,
3460 BuiltinId::HourOf | BuiltinId::MinuteOf | BuiltinId::SecondOf => {
3461 return Err(
3462 "a Date has no time-of-day — use a timestamp/Moment".to_string()
3463 );
3464 }
3465 _ => unreachable!(),
3466 };
3467 Ok(RuntimeValue::Int(component))
3468 }
3469 _ => Err(format!(
3470 "a date component extractor requires a Moment or Date, got {}",
3471 val.type_name()
3472 )),
3473 }
3474 }
3475 BuiltinId::DateOf => {
3476 let val = args.remove(0);
3477 match &val {
3478 RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Date(
3480 nanos.div_euclid(logicaffeine_base::temporal::NANOS_PER_DAY) as i32,
3481 )),
3482 RuntimeValue::Date(days) => Ok(RuntimeValue::Date(*days)),
3483 _ => Err(format!(
3484 "date_of() requires a Moment or Date, got {}",
3485 val.type_name()
3486 )),
3487 }
3488 }
3489 BuiltinId::TimeOf => {
3490 let val = args.remove(0);
3491 match &val {
3492 RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Time(
3494 nanos.rem_euclid(logicaffeine_base::temporal::NANOS_PER_DAY),
3495 )),
3496 RuntimeValue::Date(_) => {
3497 Err("a Date has no time-of-day — use a timestamp/Moment".to_string())
3498 }
3499 _ => Err(format!(
3500 "time_of() requires a Moment, got {}",
3501 val.type_name()
3502 )),
3503 }
3504 }
3505 BuiltinId::MakeDate => {
3506 let d = args.remove(2);
3507 let m = args.remove(1);
3508 let y = args.remove(0);
3509 match (&y, &m, &d) {
3510 (RuntimeValue::Int(y), RuntimeValue::Int(mo), RuntimeValue::Int(da)) => Ok(
3511 RuntimeValue::Date(logicaffeine_base::temporal::days_from_civil(
3512 *y, *mo as u32, *da as u32,
3513 ) as i32),
3514 ),
3515 _ => Err(format!(
3516 "makeDate() requires three Ints (year, month, day), got {}, {}, {}",
3517 y.type_name(),
3518 m.type_name(),
3519 d.type_name()
3520 )),
3521 }
3522 }
3523 BuiltinId::MakeMoment => {
3524 let s = args.remove(5);
3525 let mi = args.remove(4);
3526 let h = args.remove(3);
3527 let d = args.remove(2);
3528 let m = args.remove(1);
3529 let y = args.remove(0);
3530 match (&y, &m, &d, &h, &mi, &s) {
3531 (
3532 RuntimeValue::Int(y),
3533 RuntimeValue::Int(mo),
3534 RuntimeValue::Int(da),
3535 RuntimeValue::Int(hr),
3536 RuntimeValue::Int(min),
3537 RuntimeValue::Int(sec),
3538 ) => {
3539 let days =
3540 logicaffeine_base::temporal::days_from_civil(*y, *mo as u32, *da as u32);
3541 let nanos = days * logicaffeine_base::temporal::NANOS_PER_DAY
3542 + (*hr * 3600 + *min * 60 + *sec)
3543 * logicaffeine_base::temporal::NANOS_PER_SECOND;
3544 Ok(RuntimeValue::Moment(nanos))
3545 }
3546 _ => Err(
3547 "makeMoment() requires six Ints (year, month, day, hour, minute, second)"
3548 .to_string(),
3549 ),
3550 }
3551 }
3552 BuiltinId::SecondsBetween => {
3553 let b = args.remove(1);
3554 let a = args.remove(0);
3555 match (&a, &b) {
3556 (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
3557 Ok(RuntimeValue::Int((b - a) / 1_000_000_000))
3558 }
3559 _ => Err(format!(
3560 "seconds_between() requires two Moments, got {} and {}",
3561 a.type_name(),
3562 b.type_name()
3563 )),
3564 }
3565 }
3566 BuiltinId::MonthsBetween | BuiltinId::YearsBetween => {
3567 let b = args.remove(1);
3568 let a = args.remove(0);
3569 match (&a, &b) {
3570 (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
3571 let n = if matches!(id, BuiltinId::MonthsBetween) {
3572 logicaffeine_base::temporal::months_between(*a, *b)
3573 } else {
3574 logicaffeine_base::temporal::years_between(*a, *b)
3575 };
3576 Ok(RuntimeValue::Int(n))
3577 }
3578 _ => {
3579 let name = if matches!(id, BuiltinId::MonthsBetween) {
3580 "months_between"
3581 } else {
3582 "years_between"
3583 };
3584 Err(format!(
3585 "{name}() requires two Moments, got {} and {}",
3586 a.type_name(),
3587 b.type_name()
3588 ))
3589 }
3590 }
3591 }
3592 BuiltinId::AddSeconds => {
3593 let secs = args.remove(1);
3594 let moment = args.remove(0);
3595 match (&moment, &secs) {
3596 (RuntimeValue::Moment(nanos), RuntimeValue::Int(n)) => {
3597 Ok(RuntimeValue::Moment(nanos + n * 1_000_000_000))
3598 }
3599 _ => Err(format!(
3600 "add_seconds() requires a Moment and an Int, got {} and {}",
3601 moment.type_name(),
3602 secs.type_name()
3603 )),
3604 }
3605 }
3606 BuiltinId::InZone => {
3607 let zone = args.remove(1);
3608 let moment = args.remove(0);
3609 match (&moment, &zone) {
3610 (RuntimeValue::Moment(nanos), RuntimeValue::Text(z)) => {
3611 logicaffeine_base::temporal::format_zoned(*nanos, z)
3612 .map(|s| RuntimeValue::Text(Rc::new(s)))
3613 .ok_or_else(|| logicaffeine_data::failure::unknown_time_zone(z))
3614 }
3615 _ => Err(format!(
3616 "in_zone() requires a Moment and a zone name (Text), got {} and {}",
3617 moment.type_name(),
3618 zone.type_name()
3619 )),
3620 }
3621 }
3622 BuiltinId::LocalInstant => {
3623 let zone = args.remove(1);
3624 let moment = args.remove(0);
3625 match (&moment, &zone) {
3626 (RuntimeValue::Moment(nanos), RuntimeValue::Text(z)) => {
3627 logicaffeine_base::temporal::local_instant_nanos(*nanos, z)
3628 .map(RuntimeValue::Moment)
3629 .ok_or_else(|| logicaffeine_data::failure::unknown_time_zone(z))
3630 }
3631 _ => Err(format!(
3632 "local_instant() requires a Moment and a zone name (Text), got {} and {}",
3633 moment.type_name(),
3634 zone.type_name()
3635 )),
3636 }
3637 }
3638 BuiltinId::Copy => {
3639 let val = args.remove(0);
3640 Ok(val.deep_clone())
3641 }
3642 BuiltinId::Fail => Err(args.remove(0).to_display_string()),
3643 BuiltinId::FailReason => Err(contract_reason_text(args.remove(0))?),
3644 BuiltinId::InspectUnhandledDynamic => {
3650 let target = args.remove(0);
3651 let variant = match &target {
3652 RuntimeValue::Inductive(i) => i.constructor.as_str(),
3653 _ => "the value",
3654 };
3655 Err(inspect_unhandled_message(target.type_name(), variant))
3656 }
3657 BuiltinId::NativeKernel => {
3658 use crate::semantics::native_kernels::NativeKernel;
3659 let kernel = match args.first() {
3660 Some(RuntimeValue::Int(code)) => NativeKernel::from_code(*code)
3661 .ok_or_else(|| format!("unknown native kernel code {code}"))?,
3662 _ => return Err("a native kernel call carries its kernel code".to_string()),
3663 };
3664 kernel.call(&args[1..])
3665 }
3666 BuiltinId::CountOnes => {
3667 let val = args.remove(0);
3668 match val {
3669 RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).count_ones() as i64)),
3672 _ => Err(format!(
3673 "count_ones() requires an Int, got {}",
3674 val.type_name()
3675 )),
3676 }
3677 }
3678 BuiltinId::LeadingZeros => {
3679 let val = args.remove(0);
3680 match val {
3681 RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).leading_zeros() as i64)),
3684 _ => Err(format!(
3685 "leading_zeros() requires an Int, got {}",
3686 val.type_name()
3687 )),
3688 }
3689 }
3690 BuiltinId::TrailingZeros => {
3691 let val = args.remove(0);
3692 match val {
3693 RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).trailing_zeros() as i64)),
3696 _ => Err(format!(
3697 "trailing_zeros() requires an Int, got {}",
3698 val.type_name()
3699 )),
3700 }
3701 }
3702 BuiltinId::Word32 => {
3703 let n = args.remove(0);
3704 match n {
3705 RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W32(Word32(v as u32)))),
3706 RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W32(Word32(
3707 v.wrapping_u64() as u32,
3708 )))),
3709 RuntimeValue::Word(w) => {
3710 Ok(RuntimeValue::Word(WordVal::W32(Word32(w.to_u64() as u32))))
3711 }
3712 _ => Err(format!("word32() requires an Int, got {}", n.type_name())),
3713 }
3714 }
3715 BuiltinId::Word64 => {
3716 let n = args.remove(0);
3717 match n {
3718 RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W64(Word64(v as u64)))),
3719 RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W64(Word64(
3720 v.wrapping_u64() as u64,
3721 )))),
3722 RuntimeValue::Word(w) => Ok(RuntimeValue::Word(WordVal::W64(Word64(w.to_u64())))),
3723 _ => Err(format!("word64() requires an Int, got {}", n.type_name())),
3724 }
3725 }
3726 BuiltinId::Rotl | BuiltinId::Rotr => {
3727 let w = args.remove(0);
3728 let n = args.remove(0);
3729 let count = match n {
3730 RuntimeValue::Int(c) => c as u32,
3731 RuntimeValue::Word(c) => c.to_u64() as u32,
3732 _ => {
3733 return Err(format!(
3734 "rotate count must be an Int, got {}",
3735 n.type_name()
3736 ))
3737 }
3738 };
3739 match w {
3740 RuntimeValue::Word(word) => {
3741 let r = if matches!(id, BuiltinId::Rotl) {
3742 word.rotl(count)
3743 } else {
3744 word.rotr(count)
3745 };
3746 Ok(RuntimeValue::Word(r))
3747 }
3748 RuntimeValue::Lanes(lanes) if matches!(id, BuiltinId::Rotl) => {
3751 match lanes.rotl(count) {
3752 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3753 None => Err(format!("rotl is not defined for {}", lanes.type_name())),
3754 }
3755 }
3756 _ => Err(format!("rotate requires a Word, got {}", w.type_name())),
3757 }
3758 }
3759 BuiltinId::Wand | BuiltinId::Wor => {
3760 let b = args.remove(1);
3761 let a = args.remove(0);
3762 match (&a, &b) {
3763 (RuntimeValue::Word(x), RuntimeValue::Word(y)) => {
3764 let r = if id == BuiltinId::Wand {
3765 x.bitand(*y)
3766 } else {
3767 x.bitor(*y)
3768 };
3769 match r {
3770 Some(w) => Ok(RuntimeValue::Word(w)),
3771 None => Err(format!(
3772 "word_and/or width mismatch: {} vs {}",
3773 a.type_name(),
3774 b.type_name()
3775 )),
3776 }
3777 }
3778 (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3780 let r = if id == BuiltinId::Wand {
3781 (**x).bitand(**y)
3782 } else {
3783 (**x).bitor(**y)
3784 };
3785 match r {
3786 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3787 None => Err(format!(
3788 "word_and/or lane-config mismatch: {} vs {}",
3789 a.type_name(),
3790 b.type_name()
3791 )),
3792 }
3793 }
3794 _ => Err(format!(
3795 "word_and/or requires two Words, got {} and {}",
3796 a.type_name(),
3797 b.type_name()
3798 )),
3799 }
3800 }
3801 BuiltinId::Wnot => {
3802 let a = args.remove(0);
3803 match &a {
3804 RuntimeValue::Word(x) => Ok(RuntimeValue::Word(x.not())),
3805 RuntimeValue::Lanes(x) => match (**x).lane_not() {
3806 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3807 None => Err(format!(
3808 "word_not: lane config has no complement: {}",
3809 a.type_name()
3810 )),
3811 },
3812 _ => Err(format!("word_not requires a Word, got {}", a.type_name())),
3813 }
3814 }
3815 BuiltinId::Lanes4Word32Make => {
3816 let s = args.remove(0);
3818 match s {
3819 RuntimeValue::List(items) => {
3820 let vals = items.borrow().to_values();
3821 let mut words = Vec::with_capacity(vals.len());
3822 for v in &vals {
3823 match v {
3824 RuntimeValue::Word(WordVal::W32(w)) => words.push(*w),
3825 RuntimeValue::Int(n) => words.push(Word32(*n as u32)),
3826 other => {
3827 return Err(format!(
3828 "lanes4Word32() needs a Seq of Word32, found {}",
3829 other.type_name()
3830 ))
3831 }
3832 }
3833 }
3834 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W32(
3835 logicaffeine_base::Lanes4Word32::from_words(&words),
3836 ))))
3837 }
3838 other => Err(format!(
3839 "lanes4Word32() requires a Seq of Word32, got {}",
3840 other.type_name()
3841 )),
3842 }
3843 }
3844 BuiltinId::Lanes4Of => {
3845 let mut w = [Word32(0); 4];
3848 for slot in w.iter_mut() {
3849 *slot = match args.remove(0) {
3850 RuntimeValue::Word(WordVal::W32(x)) => x,
3851 RuntimeValue::Int(n) => Word32(n as u32),
3852 other => {
3853 return Err(format!(
3854 "lanes4Of() needs four Word32, found {}",
3855 other.type_name()
3856 ))
3857 }
3858 };
3859 }
3860 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W32(
3861 logicaffeine_base::Lanes4Word32::from_words(&w),
3862 ))))
3863 }
3864 BuiltinId::SeqOfLanes4W32 => {
3865 let v = args.remove(0);
3866 match v {
3867 RuntimeValue::Lanes(lanes) => match *lanes {
3868 LanesVal::L4W32(lv) => {
3869 let vals: Vec<RuntimeValue> = lv
3870 .to_words()
3871 .iter()
3872 .map(|w| RuntimeValue::Word(WordVal::W32(*w)))
3873 .collect();
3874 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
3875 crate::interpreter::ListRepr::from_values(vals),
3876 ))))
3877 }
3878 other => Err(format!(
3879 "seqOfLanes4W32() requires a Lanes4Word32, got {}",
3880 other.type_name()
3881 )),
3882 },
3883 other => Err(format!(
3884 "seqOfLanes4W32() requires a Lanes4Word32, got {}",
3885 other.type_name()
3886 )),
3887 }
3888 }
3889 BuiltinId::Sha1Rnds4 => {
3890 let func = args.remove(2);
3891 let msg = args.remove(1);
3892 let abcd = args.remove(0);
3893 let f = match &func {
3894 RuntimeValue::Int(n) => *n as u32,
3895 _ => {
3896 return Err(format!(
3897 "sha1rnds4() func must be an Int, got {}",
3898 func.type_name()
3899 ))
3900 }
3901 };
3902 match (&abcd, &msg) {
3903 (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) => (**a)
3904 .sha1rnds4(**b, f)
3905 .map(|r| RuntimeValue::Lanes(Rc::new(r)))
3906 .ok_or_else(|| "sha1rnds4() requires two Lanes4Word32".to_string()),
3907 _ => Err(format!(
3908 "sha1rnds4() requires two Lanes4Word32, got {} and {}",
3909 abcd.type_name(),
3910 msg.type_name()
3911 )),
3912 }
3913 }
3914 BuiltinId::Sha1Msg1 | BuiltinId::Sha1Msg2 | BuiltinId::Sha1Nexte => {
3915 let b = args.remove(1);
3916 let a = args.remove(0);
3917 match (&a, &b) {
3918 (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3919 let r = match id {
3920 BuiltinId::Sha1Msg1 => (**x).sha1msg1(**y),
3921 BuiltinId::Sha1Msg2 => (**x).sha1msg2(**y),
3922 _ => (**x).sha1nexte(**y),
3923 };
3924 r.map(|v| RuntimeValue::Lanes(Rc::new(v)))
3925 .ok_or_else(|| "sha1msg/nexte requires two Lanes4Word32".to_string())
3926 }
3927 _ => Err(format!(
3928 "sha1 message op requires two Lanes4Word32, got {} and {}",
3929 a.type_name(),
3930 b.type_name()
3931 )),
3932 }
3933 }
3934 BuiltinId::Lanes16Word8Make => {
3935 let bytes = byte_seq(&args.remove(0))?;
3938 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W8(
3939 logicaffeine_base::Lanes16Word8::from_bytes(&bytes),
3940 ))))
3941 }
3942 BuiltinId::SeqOfLanes16W8 => {
3943 let v = args.remove(0);
3944 match v {
3945 RuntimeValue::Lanes(lanes) => match *lanes {
3946 LanesVal::L16W8(lv) => Ok(bytes_to_seq(&lv.to_bytes())),
3947 other => Err(format!(
3948 "seqOfLanes16W8() requires a Lanes16Word8, got {}",
3949 other.type_name()
3950 )),
3951 },
3952 other => Err(format!(
3953 "seqOfLanes16W8() requires a Lanes16Word8, got {}",
3954 other.type_name()
3955 )),
3956 }
3957 }
3958 BuiltinId::Splat16Word8 => match args.remove(0) {
3959 RuntimeValue::Int(n) => Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W8(
3960 logicaffeine_base::Lanes16Word8::splat(n as u8),
3961 )))),
3962 other => Err(format!(
3963 "splat16Word8() requires an Int, got {}",
3964 other.type_name()
3965 )),
3966 },
3967 BuiltinId::Shuffle16
3968 | BuiltinId::InterleaveLo16
3969 | BuiltinId::InterleaveHi16
3970 | BuiltinId::ByteAdd16
3971 | BuiltinId::Maddubs16
3972 | BuiltinId::Packus16 => {
3973 let b = args.remove(1);
3974 let a = args.remove(0);
3975 match (&a, &b) {
3976 (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3977 let r = match id {
3978 BuiltinId::Shuffle16 => (**x).shuffle(**y),
3979 BuiltinId::InterleaveLo16 => (**x).interleave_lo(**y),
3980 BuiltinId::InterleaveHi16 => (**x).interleave_hi(**y),
3981 BuiltinId::ByteAdd16 => (**x).byte_add(**y),
3982 BuiltinId::Maddubs16 => (**x).maddubs_bytes(**y),
3983 _ => (**x).packus_bytes(**y),
3984 };
3985 r.map(|v| RuntimeValue::Lanes(Rc::new(v)))
3986 .ok_or_else(|| "byte-lane op requires two Lanes16Word8".to_string())
3987 }
3988 _ => Err(format!(
3989 "byte-lane op requires two Lanes16Word8, got {} and {}",
3990 a.type_name(),
3991 b.type_name()
3992 )),
3993 }
3994 }
3995 BuiltinId::ShrBytes16 => {
3996 let n = args.remove(1);
3997 let v = args.remove(0);
3998 match (&v, &n) {
3999 (RuntimeValue::Lanes(x), RuntimeValue::Int(k)) => (**x)
4000 .shr_bytes(*k as u32)
4001 .map(|r| RuntimeValue::Lanes(Rc::new(r)))
4002 .ok_or_else(|| "shrBytes16() requires a Lanes16Word8".to_string()),
4003 _ => Err(format!(
4004 "shrBytes16() requires a Lanes16Word8 and an Int, got {} and {}",
4005 v.type_name(),
4006 n.type_name()
4007 )),
4008 }
4009 }
4010 BuiltinId::Lanes8Word32 => {
4011 let s = args.remove(0);
4014 match s {
4015 RuntimeValue::List(items) => {
4016 let vals = items.borrow().to_values();
4017 let mut words = Vec::with_capacity(vals.len());
4018 for v in &vals {
4019 match v {
4020 RuntimeValue::Word(WordVal::W32(w)) => words.push(*w),
4021 RuntimeValue::Int(n) => words.push(Word32(*n as u32)),
4022 other => {
4023 return Err(format!(
4024 "lanes8Word32() needs a Seq of Word32, found {}",
4025 other.type_name()
4026 ))
4027 }
4028 }
4029 }
4030 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L8W32(
4031 logicaffeine_base::Lanes8Word32::from_words(&words),
4032 ))))
4033 }
4034 other => Err(format!(
4035 "lanes8Word32() requires a Seq of Word32, got {}",
4036 other.type_name()
4037 )),
4038 }
4039 }
4040 BuiltinId::IntOfWord32 => {
4041 let x = args.remove(0);
4043 match x {
4044 RuntimeValue::Word(w) => Ok(RuntimeValue::Int(w.to_u64() as i64)),
4045 RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n)),
4046 other => Err(format!(
4047 "intOfWord32() requires a Word32, got {}",
4048 other.type_name()
4049 )),
4050 }
4051 }
4052 BuiltinId::IntOfWord64 => {
4053 let x = args.remove(0);
4055 match x {
4056 RuntimeValue::Word(w) => Ok(RuntimeValue::Int(w.to_u64() as i64)),
4057 RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n)),
4058 other => Err(format!(
4059 "intOfWord64() requires a Word64, got {}",
4060 other.type_name()
4061 )),
4062 }
4063 }
4064 BuiltinId::Word64Shl | BuiltinId::Word64Shr => {
4065 let is_shl = matches!(id, BuiltinId::Word64Shl);
4066 let w = args.remove(0);
4067 let n = args.remove(0);
4068 let wv = match w {
4069 RuntimeValue::Word(w) => w.to_u64(),
4070 RuntimeValue::Int(v) => v as u64,
4071 other => {
4072 return Err(format!(
4073 "word64 shift requires a Word64, got {}",
4074 other.type_name()
4075 ))
4076 }
4077 };
4078 let nv = match n {
4079 RuntimeValue::Int(v) => v as u32,
4080 other => {
4081 return Err(format!(
4082 "word64 shift amount requires an Int, got {}",
4083 other.type_name()
4084 ))
4085 }
4086 };
4087 let r = if is_shl {
4088 wv.wrapping_shl(nv)
4089 } else {
4090 wv.wrapping_shr(nv)
4091 };
4092 Ok(RuntimeValue::Word(WordVal::W64(Word64(r))))
4093 }
4094 BuiltinId::Word64And => {
4095 let a = args.remove(0);
4096 let b = args.remove(0);
4097 let av = match a {
4098 RuntimeValue::Word(w) => w.to_u64(),
4099 RuntimeValue::Int(v) => v as u64,
4100 other => {
4101 return Err(format!(
4102 "word64And requires a Word64, got {}",
4103 other.type_name()
4104 ))
4105 }
4106 };
4107 let bv = match b {
4108 RuntimeValue::Word(w) => w.to_u64(),
4109 RuntimeValue::Int(v) => v as u64,
4110 other => {
4111 return Err(format!(
4112 "word64And requires a Word64, got {}",
4113 other.type_name()
4114 ))
4115 }
4116 };
4117 Ok(RuntimeValue::Word(WordVal::W64(Word64(av & bv))))
4118 }
4119 BuiltinId::Word32Shr => {
4120 let w = args.remove(0);
4121 let n = args.remove(0);
4122 let wv = match w {
4123 RuntimeValue::Word(word) => word.to_u64() as u32,
4124 RuntimeValue::Int(v) => v as u32,
4125 other => {
4126 return Err(format!(
4127 "word32Shr requires a Word32, got {}",
4128 other.type_name()
4129 ))
4130 }
4131 };
4132 let nv = match n {
4133 RuntimeValue::Int(v) => v as u32,
4134 other => {
4135 return Err(format!(
4136 "word32Shr amount requires an Int, got {}",
4137 other.type_name()
4138 ))
4139 }
4140 };
4141 Ok(RuntimeValue::Word(WordVal::W32(Word32(
4142 wv.wrapping_shr(nv),
4143 ))))
4144 }
4145 BuiltinId::Word16Make => {
4146 let n = args.remove(0);
4148 match n {
4149 RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W16(Word16(v as u16)))),
4150 RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W16(Word16(
4151 v.wrapping_u64() as u16,
4152 )))),
4153 RuntimeValue::Word(w) => {
4154 Ok(RuntimeValue::Word(WordVal::W16(Word16(w.to_u64() as u16))))
4155 }
4156 other => Err(format!(
4157 "word16() requires an Int, got {}",
4158 other.type_name()
4159 )),
4160 }
4161 }
4162 BuiltinId::IntOfWord16 => {
4163 let x = args.remove(0);
4165 match x {
4166 RuntimeValue::Word(WordVal::W16(w)) => Ok(RuntimeValue::Int(w.0 as i64)),
4167 RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n as u16 as i64)),
4168 other => Err(format!(
4169 "intOfWord16() requires a Word16, got {}",
4170 other.type_name()
4171 )),
4172 }
4173 }
4174 BuiltinId::Word8Make => {
4175 let n = args.remove(0);
4177 match n {
4178 RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W8(Word8(v as u8)))),
4179 RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W8(Word8(
4180 v.wrapping_u64() as u8,
4181 )))),
4182 RuntimeValue::Word(w) => {
4183 Ok(RuntimeValue::Word(WordVal::W8(Word8(w.to_u64() as u8))))
4184 }
4185 other => Err(format!(
4186 "word8() requires an Int, got {}",
4187 other.type_name()
4188 )),
4189 }
4190 }
4191 BuiltinId::IntOfWord8 => {
4192 let x = args.remove(0);
4194 match x {
4195 RuntimeValue::Word(WordVal::W8(w)) => Ok(RuntimeValue::Int(w.0 as i64)),
4196 RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n as u8 as i64)),
4197 other => Err(format!(
4198 "intOfWord8() requires a Word8, got {}",
4199 other.type_name()
4200 )),
4201 }
4202 }
4203 BuiltinId::Lanes4Word64 => {
4204 let s = args.remove(0);
4206 match s {
4207 RuntimeValue::List(items) => {
4208 let vals = items.borrow().to_values();
4209 let mut words = Vec::with_capacity(vals.len());
4210 for v in &vals {
4211 match v {
4212 RuntimeValue::Word(WordVal::W64(w)) => words.push(*w),
4213 RuntimeValue::Int(n) => words.push(Word64(*n as u64)),
4214 other => {
4215 return Err(format!(
4216 "lanes4Word64() needs a Seq of Word64/Int, found {}",
4217 other.type_name()
4218 ))
4219 }
4220 }
4221 }
4222 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W64(
4223 logicaffeine_base::Lanes4Word64::from_words(&words),
4224 ))))
4225 }
4226 other => Err(format!(
4227 "lanes4Word64() requires a Seq, got {}",
4228 other.type_name()
4229 )),
4230 }
4231 }
4232 BuiltinId::SeqOfLanes4 => {
4233 let v = args.remove(0);
4235 match v {
4236 RuntimeValue::Lanes(lanes) => {
4237 let vals: Vec<RuntimeValue> = (0..lanes.lanes())
4238 .map(|i| RuntimeValue::Int(lanes.lane(i) as i64))
4239 .collect();
4240 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4241 crate::interpreter::ListRepr::from_values(vals),
4242 ))))
4243 }
4244 other => Err(format!(
4245 "seqOfLanes4() requires a lane vector, got {}",
4246 other.type_name()
4247 )),
4248 }
4249 }
4250 BuiltinId::Mul32x32To64 => {
4251 let a = args.remove(0);
4253 let b = args.remove(0);
4254 match (a, b) {
4255 (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.mul_lo32_wide(*lb) {
4256 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4257 None => Err(format!(
4258 "mul32x32to64 requires two Lanes4Word64, got {} and {}",
4259 la.type_name(),
4260 lb.type_name()
4261 )),
4262 },
4263 (a, b) => Err(format!(
4264 "mul32x32to64 requires two lane vectors, got {} and {}",
4265 a.type_name(),
4266 b.type_name()
4267 )),
4268 }
4269 }
4270 BuiltinId::HsumLanes4 => {
4271 let v = args.remove(0);
4273 match v {
4274 RuntimeValue::Lanes(lanes) => Ok(RuntimeValue::Int(lanes.hsum())),
4275 other => Err(format!(
4276 "hsumLanes4 requires a lane vector, got {}",
4277 other.type_name()
4278 )),
4279 }
4280 }
4281 BuiltinId::Splat4Word64 => {
4282 let w = args.remove(0);
4286 match w {
4287 RuntimeValue::Word(WordVal::W64(x)) => Ok(RuntimeValue::Lanes(Rc::new(
4288 LanesVal::L4W64(logicaffeine_base::Lanes4Word64::splat(x.0)),
4289 ))),
4290 RuntimeValue::Int(n) => Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W64(
4291 logicaffeine_base::Lanes4Word64::splat(n as u64),
4292 )))),
4293 other => Err(format!(
4294 "splat4Word64() requires a Word64, got {}",
4295 other.type_name()
4296 )),
4297 }
4298 }
4299 BuiltinId::AndNot4 => {
4300 let a = args.remove(0);
4302 let b = args.remove(0);
4303 match (a, b) {
4304 (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match (&*la, &*lb) {
4305 (LanesVal::L4W64(x), LanesVal::L4W64(y)) => Ok(RuntimeValue::Lanes(Rc::new(
4306 LanesVal::L4W64((*x).andnot(*y)),
4307 ))),
4308 _ => Err(format!(
4309 "andNot4 requires two Lanes4Word64, got {} and {}",
4310 la.type_name(),
4311 lb.type_name()
4312 )),
4313 },
4314 (a, b) => Err(format!(
4315 "andNot4 requires two lane vectors, got {} and {}",
4316 a.type_name(),
4317 b.type_name()
4318 )),
4319 }
4320 }
4321 BuiltinId::Lanes16Word16 => {
4322 let s = args.remove(0);
4324 match s {
4325 RuntimeValue::List(items) => {
4326 let vals = items.borrow().to_values();
4327 let mut words = Vec::with_capacity(vals.len());
4328 for v in &vals {
4329 match v {
4330 RuntimeValue::Word(WordVal::W16(w)) => words.push(*w),
4331 RuntimeValue::Int(n) => words.push(Word16(*n as u16)),
4332 other => {
4333 return Err(format!(
4334 "lanes16Word16() needs a Seq of Word16/Int, found {}",
4335 other.type_name()
4336 ))
4337 }
4338 }
4339 }
4340 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W16(
4341 logicaffeine_base::Lanes16Word16::from_words(&words),
4342 ))))
4343 }
4344 other => Err(format!(
4345 "lanes16Word16() requires a Seq, got {}",
4346 other.type_name()
4347 )),
4348 }
4349 }
4350 BuiltinId::SeqOfLanes16 => {
4351 let v = args.remove(0);
4353 match v {
4354 RuntimeValue::Lanes(lanes) => {
4355 let vals: Vec<RuntimeValue> = (0..lanes.lanes())
4356 .map(|i| RuntimeValue::Int(lanes.lane(i) as i64))
4357 .collect();
4358 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4359 crate::interpreter::ListRepr::from_values(vals),
4360 ))))
4361 }
4362 other => Err(format!(
4363 "seqOfLanes16() requires a lane vector, got {}",
4364 other.type_name()
4365 )),
4366 }
4367 }
4368 BuiltinId::Splat16Word16 => {
4369 let x = args.remove(0);
4371 let w = match x {
4372 RuntimeValue::Word(WordVal::W16(w)) => w.0,
4373 RuntimeValue::Int(n) => n as u16,
4374 other => {
4375 return Err(format!(
4376 "splat16Word16() requires a Word16/Int, got {}",
4377 other.type_name()
4378 ))
4379 }
4380 };
4381 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W16(
4382 logicaffeine_base::Lanes16Word16::splat(w),
4383 ))))
4384 }
4385 BuiltinId::Mulhi16 => {
4386 let a = args.remove(0);
4388 let b = args.remove(0);
4389 match (a, b) {
4390 (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.mulhi(*lb) {
4391 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4392 None => Err(format!(
4393 "mulhi16 requires two Lanes16Word16, got {} and {}",
4394 la.type_name(),
4395 lb.type_name()
4396 )),
4397 },
4398 (a, b) => Err(format!(
4399 "mulhi16 requires two lane vectors, got {} and {}",
4400 a.type_name(),
4401 b.type_name()
4402 )),
4403 }
4404 }
4405 BuiltinId::Montmul32 => {
4406 let a = args.remove(0);
4408 let b = args.remove(0);
4409 let q = args.remove(0);
4410 let qi = args.remove(0);
4411 match (a, b, q, qi) {
4412 (
4413 RuntimeValue::Lanes(la),
4414 RuntimeValue::Lanes(lb),
4415 RuntimeValue::Lanes(lq),
4416 RuntimeValue::Lanes(lqi),
4417 ) => match la.montmul32(*lb, *lq, *lqi) {
4418 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4419 None => Err(format!(
4420 "montmul32 requires four Lanes8Word32, got {}, {}, {}, {}",
4421 la.type_name(),
4422 lb.type_name(),
4423 lq.type_name(),
4424 lqi.type_name()
4425 )),
4426 },
4427 (a, b, q, qi) => Err(format!(
4428 "montmul32 requires four lane vectors, got {}, {}, {}, {}",
4429 a.type_name(),
4430 b.type_name(),
4431 q.type_name(),
4432 qi.type_name()
4433 )),
4434 }
4435 }
4436 BuiltinId::NttBcastLo | BuiltinId::NttBcastHi => {
4437 let is_low = matches!(id, BuiltinId::NttBcastLo);
4439 let name = if is_low { "nttBcastLo" } else { "nttBcastHi" };
4440 let v = args.remove(0);
4441 let h = ntt_stride(args.remove(0), name)?;
4442 match v {
4443 RuntimeValue::Lanes(lv) => {
4444 let r = if is_low {
4445 lv.ntt_bcast_lo(h)
4446 } else {
4447 lv.ntt_bcast_hi(h)
4448 };
4449 match r {
4450 Some(out) => Ok(RuntimeValue::Lanes(Rc::new(out))),
4451 None => Err(format!(
4452 "{} requires a Lanes16Word16, got {}",
4453 name,
4454 lv.type_name()
4455 )),
4456 }
4457 }
4458 other => Err(format!(
4459 "{} requires a lane vector, got {}",
4460 name,
4461 other.type_name()
4462 )),
4463 }
4464 }
4465 BuiltinId::NttBlend => {
4466 let a = args.remove(0);
4468 let b = args.remove(0);
4469 let h = ntt_stride(args.remove(0), "nttBlend")?;
4470 match (a, b) {
4471 (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.ntt_blend(*lb, h) {
4472 Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4473 None => Err(format!(
4474 "nttBlend requires two Lanes16Word16, got {} and {}",
4475 la.type_name(),
4476 lb.type_name()
4477 )),
4478 },
4479 (a, b) => Err(format!(
4480 "nttBlend requires two lane vectors, got {} and {}",
4481 a.type_name(),
4482 b.type_name()
4483 )),
4484 }
4485 }
4486 BuiltinId::Splat8Word32 => {
4487 let x = args.remove(0);
4489 let w = match x {
4490 RuntimeValue::Word(WordVal::W32(w)) => w,
4491 RuntimeValue::Int(n) => Word32(n as u32),
4492 other => {
4493 return Err(format!(
4494 "splat8Word32() requires a Word32, got {}",
4495 other.type_name()
4496 ))
4497 }
4498 };
4499 Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L8W32(
4500 logicaffeine_base::Lanes8Word32::splat(w.0),
4501 ))))
4502 }
4503 BuiltinId::SeqOfLanes8 => {
4504 let v = args.remove(0);
4506 match v {
4507 RuntimeValue::Lanes(lanes) => match *lanes {
4508 LanesVal::L8W32(lv) => {
4509 let vals: Vec<RuntimeValue> = lv
4510 .to_words()
4511 .iter()
4512 .map(|w| RuntimeValue::Word(WordVal::W32(*w)))
4513 .collect();
4514 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4515 crate::interpreter::ListRepr::from_values(vals),
4516 ))))
4517 }
4518 other => Err(format!(
4519 "seqOfLanes8() requires a Lanes8Word32, got {}",
4520 other.type_name()
4521 )),
4522 },
4523 other => Err(format!(
4524 "seqOfLanes8() requires a Lanes8Word32, got {}",
4525 other.type_name()
4526 )),
4527 }
4528 }
4529 BuiltinId::RunAccepted => {
4530 let int_arg = |v: &RuntimeValue, what: &str| -> Result<i64, String> {
4535 match v {
4536 RuntimeValue::Int(n) => Ok(*n),
4537 other => Err(format!(
4538 "run_accepted: {what} must be an Int, got {}",
4539 other.type_name()
4540 )),
4541 }
4542 };
4543 let arg = int_arg(&args[1], "the argument")?;
4544 let lo = int_arg(&args[2], "the lower bound")?;
4545 let hi = int_arg(&args[3], "the upper bound")?;
4546 let contract = crate::semantics::acceptance::AcceptanceContract::new(lo, hi);
4547 contract.apply(&args[0], arg).map(RuntimeValue::Int)
4548 }
4549 BuiltinId::DomBody => Ok(RuntimeValue::Int(crate::semantics::dom::body())),
4553 BuiltinId::DomCreateElement => {
4554 let tag = args.remove(0);
4555 Ok(RuntimeValue::Int(crate::semantics::dom::create_element(
4556 &tag.to_display_string(),
4557 )))
4558 }
4559 BuiltinId::DomCreateTextNode => {
4560 let text = args.remove(0);
4561 Ok(RuntimeValue::Int(crate::semantics::dom::create_text_node(
4562 &text.to_display_string(),
4563 )))
4564 }
4565 BuiltinId::DomSetText => {
4566 let el = dom_handle(args.remove(0), "setText")?;
4567 let text = args.remove(0);
4568 crate::semantics::dom::set_text(el, &text.to_display_string());
4569 Ok(RuntimeValue::Nothing)
4570 }
4571 BuiltinId::DomSetHtml => {
4572 let el = dom_handle(args.remove(0), "setHtml")?;
4573 let html = args.remove(0);
4574 crate::semantics::dom::set_html(el, &html.to_display_string());
4575 Ok(RuntimeValue::Nothing)
4576 }
4577 BuiltinId::DomBeginPaint => Err(BEGIN_PAINT_RETIRED.to_string()),
4578 BuiltinId::DomClearChildren => {
4579 let el = dom_handle(args.remove(0), "clearChildren")?;
4580 crate::semantics::dom::clear_children(el);
4581 Ok(RuntimeValue::Nothing)
4582 }
4583 BuiltinId::DomMoveChildren => Err(MOVE_CHILDREN_RETIRED.to_string()),
4584 BuiltinId::DomOnMessage => Ok(RuntimeValue::Nothing),
4590 BuiltinId::DomSetAttribute => {
4591 let el = dom_handle(args.remove(0), "setAttribute")?;
4592 let name = args.remove(0);
4593 let value = args.remove(0);
4594 crate::semantics::dom::set_attribute_value(el, &name.to_display_string(), &value);
4597 Ok(RuntimeValue::Nothing)
4598 }
4599 BuiltinId::DomAppendChild => {
4600 let parent = dom_handle(args.remove(0), "appendChild")?;
4601 let child = dom_handle(args.remove(0), "appendChild")?;
4602 crate::semantics::dom::append_child(parent, child);
4603 Ok(RuntimeValue::Nothing)
4604 }
4605 BuiltinId::DomGetText => {
4606 let el = dom_handle(args.remove(0), "getText")?;
4607 Ok(RuntimeValue::Text(Rc::new(
4608 crate::semantics::dom::get_text(el),
4609 )))
4610 }
4611 BuiltinId::DomGetValue => {
4612 let el = dom_handle(args.remove(0), "getValue")?;
4613 Ok(RuntimeValue::Text(Rc::new(
4614 crate::semantics::dom::get_value(el),
4615 )))
4616 }
4617 BuiltinId::DomSetValue => {
4618 let el = dom_handle(args.remove(0), "setValue")?;
4619 let value = args.remove(0);
4620 crate::semantics::dom::set_value(el, &value.to_display_string());
4621 Ok(RuntimeValue::Nothing)
4622 }
4623 BuiltinId::DomApplyPatches => {
4624 let buffer = args.remove(0);
4625 let bytes = crate::semantics::patch::bytes_from_value(&buffer)?;
4626 let ops = crate::semantics::patch::decode(&bytes)?;
4629 crate::semantics::patch::apply(&ops)?;
4630 Ok(RuntimeValue::Nothing)
4631 }
4632 BuiltinId::DomApplyWords => {
4633 let count = |v: RuntimeValue, what: &str| match v {
4634 RuntimeValue::Int(n) => Ok(n),
4635 other => Err(format!(
4636 "applyPatchWords takes its {what} count as an Int, got {}",
4637 other.type_name()
4638 )),
4639 };
4640 let words = args.remove(0);
4641 let word_count = count(args.remove(0), "word")?;
4642 let strings = args.remove(0);
4643 let string_count = count(args.remove(0), "string")?;
4644 let words = crate::semantics::patch::words_from_value(&words, word_count)?;
4645 let strings = crate::semantics::patch::strings_from_value(&strings, string_count)?;
4646 let ops = crate::semantics::patch::decode_words(&words, &strings)?;
4647 Ok(RuntimeValue::Int(crate::semantics::patch::apply(&ops)?))
4648 }
4649 BuiltinId::StorageSet => {
4652 let area = args.remove(0).to_display_string();
4653 let key = args.remove(0).to_display_string();
4654 let value = args.remove(0).to_display_string();
4655 crate::semantics::storage::set(&area, &key, &value)?;
4656 Ok(RuntimeValue::Nothing)
4657 }
4658 BuiltinId::StorageGet => {
4661 let area = args.remove(0).to_display_string();
4662 let key = args.remove(0).to_display_string();
4663 Ok(match crate::semantics::storage::get(&area, &key)? {
4674 Some(v) => crate::interpreter::option_some(RuntimeValue::Text(Rc::new(v))),
4675 None => crate::interpreter::option_none(),
4676 })
4677 }
4678 BuiltinId::StorageGetOr => {
4679 let area = args.remove(0).to_display_string();
4680 let key = args.remove(0).to_display_string();
4681 let fallback = args.remove(0);
4682 Ok(match crate::semantics::storage::get(&area, &key)? {
4683 Some(v) => RuntimeValue::Text(Rc::new(v)),
4684 None => fallback,
4685 })
4686 }
4687 BuiltinId::StorageRemove => {
4688 let area = args.remove(0).to_display_string();
4689 let key = args.remove(0).to_display_string();
4690 crate::semantics::storage::remove(&area, &key)?;
4691 Ok(RuntimeValue::Nothing)
4692 }
4693 BuiltinId::DomSetChecked => {
4694 let el = dom_handle(args.remove(0), "setChecked")?;
4695 let on = args.remove(0);
4696 crate::semantics::dom::set_checked(el, on.is_truthy());
4697 Ok(RuntimeValue::Nothing)
4698 }
4699 BuiltinId::DomPreventDefault => {
4700 let el = dom_handle(args.remove(0), "preventDefault")?;
4701 let event = args.remove(0).to_display_string();
4702 crate::semantics::dom::prevent_default(el, &event);
4703 Ok(RuntimeValue::Nothing)
4704 }
4705 BuiltinId::DomSetStream => {
4706 let el = dom_handle(args.remove(0), "setStream")?;
4707 let stream = match args.remove(0) {
4708 RuntimeValue::Int(n) => n,
4709 other => {
4710 return Err(format!(
4711 "setStream expects an Int media-stream handle, got {}",
4712 other.type_name()
4713 ))
4714 }
4715 };
4716 crate::semantics::dom::set_stream(el, stream);
4717 Ok(RuntimeValue::Nothing)
4718 }
4719 BuiltinId::RtcPeerConnection => Ok(RuntimeValue::Int(
4720 crate::semantics::dom::rtc_peer_connection(),
4721 )),
4722 BuiltinId::RtcDataChannel => {
4723 let pc = dom_handle(args.remove(0), "dataChannel")?;
4724 let label = args.remove(0);
4725 Ok(RuntimeValue::Int(crate::semantics::dom::rtc_data_channel(
4726 pc,
4727 &label.to_display_string(),
4728 )))
4729 }
4730 BuiltinId::RtcCreateOffer => {
4731 let pc = dom_handle(args.remove(0), "createOffer")?;
4732 Ok(RuntimeValue::Text(Rc::new(
4733 crate::semantics::dom::rtc_create_offer(pc),
4734 )))
4735 }
4736 BuiltinId::RtcCreateAnswer => {
4737 let pc = dom_handle(args.remove(0), "createAnswer")?;
4738 Ok(RuntimeValue::Text(Rc::new(
4739 crate::semantics::dom::rtc_create_answer(pc),
4740 )))
4741 }
4742 BuiltinId::RtcSetLocal => {
4743 let pc = dom_handle(args.remove(0), "setLocalDescription")?;
4744 let sdp = args.remove(0);
4745 crate::semantics::dom::rtc_set_local(pc, &sdp.to_display_string());
4746 Ok(RuntimeValue::Nothing)
4747 }
4748 BuiltinId::RtcSetRemote => {
4749 let pc = dom_handle(args.remove(0), "setRemoteDescription")?;
4750 let sdp = args.remove(0);
4751 crate::semantics::dom::rtc_set_remote(pc, &sdp.to_display_string());
4752 Ok(RuntimeValue::Nothing)
4753 }
4754 BuiltinId::RtcAddIce => {
4755 let pc = dom_handle(args.remove(0), "addIceCandidate")?;
4756 let candidate = args.remove(0);
4757 crate::semantics::dom::rtc_add_ice(pc, &candidate.to_display_string());
4758 Ok(RuntimeValue::Nothing)
4759 }
4760 BuiltinId::RtcSend => {
4761 let channel = dom_handle(args.remove(0), "channelSend")?;
4762 let data = args.remove(0);
4763 let bytes = byte_seq(&data)?.len() as u64;
4764 crate::semantics::dom::rtc_send(channel, bytes);
4765 Ok(RuntimeValue::Nothing)
4766 }
4767 BuiltinId::DomQuerySelector => {
4768 let sel = args.remove(0);
4769 Ok(RuntimeValue::Int(crate::semantics::dom::query_selector(
4770 &sel.to_display_string(),
4771 )))
4772 }
4773 BuiltinId::DomAddEventListener => {
4774 let el = dom_handle(args.remove(0), "addEventListener")?;
4775 let event = args.remove(0).to_display_string();
4776 let handler = args.remove(0); crate::semantics::dom::add_event_listener(el, &event, handler);
4778 Ok(RuntimeValue::Nothing)
4779 }
4780 BuiltinId::DomEventValue => {
4781 let _event = args.remove(0);
4782 Ok(RuntimeValue::Text(Rc::new(
4783 crate::semantics::dom::event_value(),
4784 )))
4785 }
4786 BuiltinId::DomEventKey => {
4787 let _event = args.remove(0);
4788 Ok(RuntimeValue::Text(Rc::new(
4789 crate::semantics::dom::event_key(),
4790 )))
4791 }
4792 BuiltinId::DomEventTarget => {
4793 let _event = args.remove(0);
4794 Ok(RuntimeValue::Int(crate::semantics::dom::event_target()))
4795 }
4796 BuiltinId::DomFetchText => {
4797 let url = args.remove(0).to_display_string();
4798 let on_done = args.remove(0); crate::semantics::dom::fetch_start(&url, on_done);
4800 Ok(RuntimeValue::Nothing)
4801 }
4802 BuiltinId::DomResponseText => Ok(RuntimeValue::Text(Rc::new(
4803 crate::semantics::dom::response_text(),
4804 ))),
4805 BuiltinId::DomFetchSend => {
4806 let method = args.remove(0).to_display_string();
4807 let url = args.remove(0).to_display_string();
4808 let body = args.remove(0).to_display_string();
4809 let headers = fetch_header_pairs(&args.remove(0))?;
4810 let on_done = args.remove(0); Ok(RuntimeValue::Int(crate::semantics::dom::fetch_send(
4812 &method, &url, &body, headers, on_done,
4813 )))
4814 }
4815 BuiltinId::DomResponseStatus => {
4816 let req = dom_handle(args.remove(0), "responseStatus")?;
4817 Ok(RuntimeValue::Int(crate::semantics::dom::response_status(
4818 req,
4819 )))
4820 }
4821 BuiltinId::DomResponseBody => {
4822 let req = dom_handle(args.remove(0), "responseBody")?;
4823 Ok(RuntimeValue::Text(Rc::new(
4824 crate::semantics::dom::response_body(req),
4825 )))
4826 }
4827 BuiltinId::DomResponseHeader => {
4828 let req = dom_handle(args.remove(0), "responseHeader")?;
4829 let name = args.remove(0).to_display_string();
4830 Ok(RuntimeValue::Text(Rc::new(
4831 crate::semantics::dom::response_header(req, &name),
4832 )))
4833 }
4834 BuiltinId::DomResponseError => {
4835 let req = dom_handle(args.remove(0), "responseError")?;
4836 Ok(RuntimeValue::Text(Rc::new(
4837 crate::semantics::dom::response_error(req),
4838 )))
4839 }
4840 BuiltinId::DomFetchAbort => {
4841 let req = dom_handle(args.remove(0), "fetchAbort")?;
4842 crate::semantics::dom::fetch_abort(req);
4843 Ok(RuntimeValue::Nothing)
4844 }
4845 BuiltinId::DomFetchSetTimeout => {
4846 let req = dom_handle(args.remove(0), "fetchSetTimeout")?;
4847 let millis = dom_handle(args.remove(0), "fetchSetTimeout")?;
4848 crate::semantics::dom::fetch_set_timeout(req, millis);
4849 Ok(RuntimeValue::Nothing)
4850 }
4851 BuiltinId::DomRoutePath => Ok(RuntimeValue::Text(Rc::new(
4855 crate::semantics::dom::route_path(),
4856 ))),
4857 BuiltinId::DomRouteQuery => {
4858 let name = args.remove(0).to_display_string();
4859 Ok(RuntimeValue::Text(Rc::new(
4860 crate::semantics::dom::route_query(&name),
4861 )))
4862 }
4863 BuiltinId::DomClipboardWrite => {
4864 let t = args.remove(0).to_display_string();
4865 crate::semantics::dom::write_clipboard(&t);
4866 Ok(RuntimeValue::Nothing)
4867 }
4868 BuiltinId::DomDownloadFile => {
4869 let content = args.remove(0).to_display_string();
4870 let name = args.remove(0).to_display_string();
4871 crate::semantics::dom::offer_download(&name, &content);
4872 Ok(RuntimeValue::Nothing)
4873 }
4874 BuiltinId::DomNotify => {
4875 let message = args.remove(0).to_display_string();
4876 let tone = args.remove(0).to_display_string();
4877 crate::semantics::dom::notify(&message, &tone);
4878 Ok(RuntimeValue::Nothing)
4879 }
4880 BuiltinId::DomPublish => {
4881 let topic = args.remove(0).to_display_string();
4882 let message = args.remove(0).to_display_string();
4883 crate::semantics::dom::publish(&topic, &message);
4884 Ok(RuntimeValue::Nothing)
4885 }
4886 BuiltinId::DomElementCommand => {
4887 let el = dom_handle(args.remove(0), "elementCommand")?;
4888 let command = args.remove(0).to_display_string();
4889 match command.as_str() {
4893 "focus" => crate::semantics::dom::element_focus(el),
4894 "blur" => crate::semantics::dom::element_blur(el),
4895 "scrollto" => crate::semantics::dom::scroll_to(el),
4896 "selecttext" => crate::semantics::dom::select_text(el),
4897 _ => {}
4898 }
4899 Ok(RuntimeValue::Nothing)
4900 }
4901 BuiltinId::DomEventFileName => {
4906 let _ev = args.remove(0);
4907 Ok(RuntimeValue::Text(Rc::new(
4908 crate::semantics::dom::dropped_file().name,
4909 )))
4910 }
4911 BuiltinId::DomEventFileSize => {
4912 let _ev = args.remove(0);
4913 Ok(RuntimeValue::Int(
4914 crate::semantics::dom::dropped_file().size(),
4915 ))
4916 }
4917 BuiltinId::DomEventFileType => {
4918 let _ev = args.remove(0);
4919 Ok(RuntimeValue::Text(Rc::new(
4920 crate::semantics::dom::dropped_file()
4921 .mime_type()
4922 .to_string(),
4923 )))
4924 }
4925 BuiltinId::DomEventFileBytes => {
4926 let _ev = args.remove(0);
4927 Ok(bytes_to_seq(&crate::semantics::dom::dropped_file().bytes))
4928 }
4929 BuiltinId::DomListenFlags => {
4930 let el = dom_handle(args.remove(0), "listenFlags")?;
4931 let event = args.remove(0).to_display_string();
4932 let flags = match args.remove(0) {
4933 RuntimeValue::Int(n) if (0..32).contains(&n) => n as u8,
4934 RuntimeValue::Int(n) => {
4935 return Err(format!(
4936 "listenFlags takes flags from 0 to 31 (prevent 1, stop 2, once 4, capture 8, \
4937 passive 16), got {n}"
4938 ))
4939 }
4940 other => {
4941 return Err(format!(
4942 "listenFlags takes its flags as an Int, got {}",
4943 other.type_name()
4944 ))
4945 }
4946 };
4947 crate::semantics::dom::listen(el, &event, flags);
4948 Ok(RuntimeValue::Nothing)
4949 }
4950 BuiltinId::DomAssignLocation => {
4951 let url = args.remove(0).to_display_string();
4952 crate::semantics::dom::request_load(&url);
4953 Ok(RuntimeValue::Nothing)
4954 }
4955 BuiltinId::DomJournalDetail => Ok(RuntimeValue::Bool(true)),
4957 BuiltinId::DomWakeAfter => Ok(RuntimeValue::Nothing),
4960 BuiltinId::DomEnterValue => {
4961 let verb = match args.remove(0).to_display_string().as_str() {
4962 "type" => crate::semantics::drive::Verb::Type,
4963 "choose" => crate::semantics::drive::Verb::Choose,
4964 other => {
4965 return Err(format!(
4966 "enterValue: `{other}` is not a verb that enters a value"
4967 ))
4968 }
4969 };
4970 let selector = args.remove(0).to_display_string();
4971 let value = args.remove(0).to_display_string();
4972 let takes = crate::semantics::dom::answers_by_itself(verb, &selector, &value);
4973 crate::semantics::dom::enter_value(verb, &selector, &value);
4974 Ok(RuntimeValue::Bool(takes))
4975 }
4976 BuiltinId::DomDispatchEntry => Err(
4979 "dispatchEntry: the engine running the page takes the entry; it has no pure form"
4980 .to_string(),
4981 ),
4982 BuiltinId::DomSetInterval => {
4983 let ms = match args.remove(0) {
4988 RuntimeValue::Int(n) => n,
4989 other => {
4990 return Err(format!(
4991 "setInterval takes a period in milliseconds, got {}",
4992 other.type_name()
4993 ))
4994 }
4995 };
4996 let handler = args.remove(0);
4997 crate::semantics::drive::arm_interval(ms, handler);
4998 Ok(RuntimeValue::Nothing)
4999 }
5000 BuiltinId::DomScrollGap => {
5001 let _el = args.remove(0);
5004 Ok(RuntimeValue::Int(0))
5005 }
5006 BuiltinId::DomOnWindowEvent => {
5007 let event = args.remove(0).to_display_string();
5011 let handler = args.remove(0);
5012 crate::semantics::dom::add_event_listener(
5013 crate::semantics::dom::body(),
5014 &event,
5015 handler,
5016 );
5017 Ok(RuntimeValue::Nothing)
5018 }
5019 BuiltinId::DomGetAttribute => {
5020 let el = dom_handle(args.remove(0), "getAttribute")?;
5021 let name = args.remove(0).to_display_string();
5022 let v = crate::semantics::dom::attribute(el, &name).unwrap_or_default();
5025 Ok(RuntimeValue::Text(Rc::new(v)))
5026 }
5027 BuiltinId::DomGoBack => {
5028 let _ = crate::semantics::dom::go_back();
5032 Ok(RuntimeValue::Nothing)
5033 }
5034 BuiltinId::DomReload => {
5035 crate::semantics::dom::request_reload();
5038 Ok(RuntimeValue::Nothing)
5039 }
5040 BuiltinId::NoteTurn => {
5041 let action = args.remove(0).to_display_string();
5042 let instance = args.remove(0).to_display_string();
5043 let changes = journal_changes(&args.remove(0))?;
5044 let failure = args.remove(0).to_display_string();
5045 crate::semantics::world::journal_push(crate::semantics::world::JournalEntry {
5046 instance,
5047 action,
5048 changes,
5049 failed: (!failure.is_empty()).then_some(failure),
5050 });
5051 Ok(RuntimeValue::Nothing)
5052 }
5053 BuiltinId::DomSetTitle => {
5054 let t = args.remove(0).to_display_string();
5055 crate::semantics::dom::set_title(&t);
5056 Ok(RuntimeValue::Nothing)
5057 }
5058 BuiltinId::DomSetHeadHtml => {
5059 let t = args.remove(0).to_display_string();
5060 crate::semantics::dom::set_head_html(&t);
5061 Ok(RuntimeValue::Nothing)
5062 }
5063 BuiltinId::DomNavigate => {
5064 let path = args.remove(0).to_display_string();
5065 crate::semantics::dom::navigate(&path);
5066 Ok(RuntimeValue::Nothing)
5067 }
5068 BuiltinId::DomReplaceRoute => {
5069 let path = args.remove(0).to_display_string();
5070 crate::semantics::dom::replace_route(&path);
5071 Ok(RuntimeValue::Nothing)
5072 }
5073 BuiltinId::DomOnRoute => {
5074 let handler = args.remove(0); crate::semantics::dom::on_route(handler);
5076 Ok(RuntimeValue::Nothing)
5077 }
5078 BuiltinId::ReadBytes => {
5079 let path = args.remove(0).to_display_string();
5080 match std::fs::read(&path) {
5081 Ok(bytes) => Ok(bytes_to_seq(&bytes)),
5082 Err(e) => Err(logicaffeine_data::failure::cannot_read_bytes(&path, e)),
5083 }
5084 }
5085 BuiltinId::ReadReals => {
5090 let path = args.remove(0).to_display_string();
5091 let reals = logicaffeine_system::file::read_reals(path)?;
5092 Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Floats(reals)))))
5093 }
5094 BuiltinId::TryReadBytes => {
5095 let path = args.remove(0).to_display_string();
5096 Ok(match logicaffeine_system::file::read_bytes(path) {
5097 Ok(bytes) => result_ok(bytes_to_seq(&bytes)),
5098 Err(e) => result_err(e),
5099 })
5100 }
5101 BuiltinId::FileRead => {
5102 let path = match args.remove(0) {
5103 RuntimeValue::Text(t) => t.to_string(),
5104 other => return Err(format!("read needs a Text path, got {}", other.type_name())),
5105 };
5106 Ok(match logicaffeine_system::file::read(path) {
5107 Ok(content) => result_ok(RuntimeValue::Text(Rc::new(content))),
5108 Err(e) => result_err(e),
5109 })
5110 }
5111 BuiltinId::FileWrite => {
5112 let content = match args.remove(1) {
5113 RuntimeValue::Text(t) => t.to_string(),
5114 other => {
5115 return Err(format!(
5116 "write needs Text content, got {}",
5117 other.type_name()
5118 ))
5119 }
5120 };
5121 let path = match args.remove(0) {
5122 RuntimeValue::Text(t) => t.to_string(),
5123 other => {
5124 return Err(format!(
5125 "write needs a Text path, got {}",
5126 other.type_name()
5127 ))
5128 }
5129 };
5130 Ok(match logicaffeine_system::file::write(path, content) {
5131 Ok(()) => result_ok(RuntimeValue::Nothing),
5132 Err(e) => result_err(e),
5133 })
5134 }
5135 BuiltinId::VfsReadFile => {
5141 use logicaffeine_system::fs::Vfs as _;
5142 let path = args.remove(0).to_display_string();
5143 sandboxed(logicaffeine_system::fs::MemVfs::new().read_to_string(&path))?
5144 .map(|content| RuntimeValue::Text(Rc::new(content)))
5145 .map_err(|e| vfs_read_failure(&e))
5146 }
5147 BuiltinId::VfsWriteFile => {
5151 use logicaffeine_system::fs::Vfs as _;
5152 let path = args.remove(1).to_display_string();
5153 let content = args.remove(0).to_display_string();
5154 sandboxed(logicaffeine_system::fs::MemVfs::new().write(&path, content.as_bytes()))?
5155 .map(|()| RuntimeValue::Nothing)
5156 .map_err(|e| vfs_write_failure(&e))
5157 }
5158 BuiltinId::VfsMount => {
5161 use logicaffeine_system::fs::Vfs as _;
5162 let path = args.remove(0).to_display_string();
5163 let content = sandboxed(logicaffeine_system::fs::MemVfs::new().read_to_string(&path))?
5164 .unwrap_or_default();
5165 Ok(RuntimeValue::Text(Rc::new(content)))
5166 }
5167 BuiltinId::RandomInt => {
5168 let hi = match args.remove(1) {
5169 RuntimeValue::Int(n) => n,
5170 other => {
5171 return Err(format!(
5172 "randomInt needs Int bounds, got {}",
5173 other.type_name()
5174 ))
5175 }
5176 };
5177 let lo = match args.remove(0) {
5178 RuntimeValue::Int(n) => n,
5179 other => {
5180 return Err(format!(
5181 "randomInt needs Int bounds, got {}",
5182 other.type_name()
5183 ))
5184 }
5185 };
5186 random_int(lo, hi).map(RuntimeValue::Int)
5187 }
5188 BuiltinId::RandomFloat => Ok(RuntimeValue::Float(
5189 logicaffeine_system::random::randomFloat(),
5190 )),
5191 BuiltinId::EnvGet => {
5192 let key = match args.remove(0) {
5193 RuntimeValue::Text(t) => t.to_string(),
5194 other => return Err(format!("get needs a Text name, got {}", other.type_name())),
5195 };
5196 Ok(match environment_variable(&key) {
5197 Some(v) => crate::interpreter::option_some(RuntimeValue::Text(Rc::new(v))),
5198 None => crate::interpreter::option_none(),
5199 })
5200 }
5201 BuiltinId::TimeNow => Ok(RuntimeValue::Int(logicaffeine_system::time::now() as i64)),
5202 BuiltinId::EnvHas | BuiltinId::EnvValue => {
5203 let key = match args.remove(0) {
5204 RuntimeValue::Text(t) => t.to_string(),
5205 other => return Err(format!("get needs a Text name, got {}", other.type_name())),
5206 };
5207 let value = environment_variable(&key);
5208 Ok(if id == BuiltinId::EnvHas {
5209 RuntimeValue::Bool(value.is_some())
5210 } else {
5211 RuntimeValue::Text(Rc::new(value.unwrap_or_default()))
5212 })
5213 }
5214 BuiltinId::SignalNew
5219 | BuiltinId::SignalSet
5220 | BuiltinId::SignalGetInt
5221 | BuiltinId::SignalGetText
5222 | BuiltinId::SignalBeginRender
5223 | BuiltinId::SignalNewText
5224 | BuiltinId::SignalSetText
5225 | BuiltinId::SignalEnterComponent
5226 | BuiltinId::SignalExitComponent
5227 | BuiltinId::SignalNewSeq
5228 | BuiltinId::SignalGetSeq
5229 | BuiltinId::SignalSetSeq
5230 | BuiltinId::SignalNewFloat
5231 | BuiltinId::SignalGetFloat
5232 | BuiltinId::SignalSetFloat => Err(
5233 "the reactive-signal dialect is retired; this builtin id is wire-frozen only"
5234 .to_string(),
5235 ),
5236 }
5237}
5238
5239fn dom_handle(v: RuntimeValue, what: &str) -> Result<i64, String> {
5241 match v {
5242 RuntimeValue::Int(h) => Ok(h),
5243 other => Err(format!(
5244 "{what} requires an Element handle, got {}",
5245 other.type_name()
5246 )),
5247 }
5248}
5249
5250#[cfg(test)]
5251#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/builtins/tests.rs"]
5252mod tests;
5253
5254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5257pub enum BuiltinEffect {
5258 Pure,
5260 Fallible,
5262 Nondeterministic,
5264 Effectful,
5266}
5267
5268impl BuiltinId {
5269 pub fn effect(self) -> BuiltinEffect {
5273 use BuiltinId as B;
5274 match self {
5275 B::Length | B::Contains | B::Format | B::Abs | B::Sqrt | B::Min | B::Max | B::Complex
5276 | B::Conjugate | B::RealPart | B::ImagPart | B::UuidNil | B::UuidMax | B::UuidVersion
5277 | B::UuidDns | B::UuidUrl | B::UuidOid | B::UuidX500 | B::TextBytes | B::UuidBytes
5278 | B::FormatTimestamp | B::YearOf | B::MonthOf | B::DayOf | B::WeekdayOf | B::HourOf
5279 | B::MinuteOf | B::SecondOf | B::WeekOf | B::QuarterOf | B::DateOf | B::TimeOf
5280 | B::SecondsBetween | B::MonthsBetween | B::YearsBetween | B::AddSeconds | B::Copy
5281 | B::CountOnes | B::LeadingZeros | B::TrailingZeros | B::Word32 | B::Word64 | B::Rotl
5282 | B::Rotr | B::Wand | B::Wor | B::Wnot | B::Lanes4Word32Make | B::SeqOfLanes4W32
5283 | B::Sha1Rnds4 | B::Sha1Msg1 | B::Sha1Msg2 | B::Sha1Nexte | B::SeqOfLanes16W8
5284 | B::Splat16Word8 | B::Shuffle16 | B::ShrBytes16 | B::InterleaveLo16 | B::InterleaveHi16
5285 | B::ByteAdd16 | B::Maddubs16 | B::Packus16 | B::SeqOfLanes8 | B::Splat8Word32
5286 | B::IntOfWord32 | B::IntOfWord64 | B::Word64Shl | B::Word64Shr | B::Word64And
5287 | B::Word32Shr | B::Word16Make | B::IntOfWord16 | B::Word8Make | B::IntOfWord8 | B::NativeKernel | B::SeqOfLanes4 | B::Mul32x32To64
5288 | B::HsumLanes4 | B::Splat4Word64 | B::AndNot4 | B::SeqOfLanes16 | B::Splat16Word16
5289 | B::Mulhi16 | B::Montmul32 | B::NttBcastLo | B::NttBcastHi | B::NttBlend | B::MapOf
5290 | B::SetOf | B::Provisional | B::StateSize | B::ExactPi | B::ExactE | B::ExactOmega => {
5291 BuiltinEffect::Pure
5292 }
5293 B::Infinitesimal | B::OrderedInfinitesimal | B::StandardPart | B::IsInfinitesimal | B::IsLimited
5294 | B::InfinitelyClose | B::GeneratorOf | B::LimitOf | B::AtTheLimit | B::EveryNatural
5295 | B::TripCount | B::AffinePower | B::CycleAt | B::SearchCandidates | B::PolynomialFlow | B::HybridFlow
5296 | B::FirstExit
5297 | B::DefinedReal
5298 | B::ExactSqrt | B::ExactExp | B::ExactLn | B::ExactPower | B::ParseInt | B::ParseFloat | B::Chr | B::Floor | B::Ceil | B::Round | B::Pow
5299 | B::Decimal | B::Modular | B::Quantity | B::Money | B::ToCurrency | B::Convert
5300 | B::Uuid | B::TextFromBytes | B::WireBytes | B::CompressBytes | B::DecompressBytes
5301 | B::SealBytes | B::OpenBytes | B::FromWireBytes | B::SealFrame | B::OpenFrame
5302 | B::OpenBox | B::OpenValueBox | B::UuidFromBytes | B::ParseTimestamp | B::MakeDate | B::MakeMoment | B::LocalInstant
5303 | B::InZone | B::RunAccepted | B::Lanes4Of | B::Lanes16Word8Make | B::Lanes8Word32
5304 | B::Lanes4Word64 | B::Lanes16Word16 | B::RepeatSeq | B::ReedSolomonEncode
5305 | B::ReedSolomonRecover | B::FecProtect | B::FecRestore | B::Fail | B::FailReason
5306 | B::InspectUnhandledDynamic => BuiltinEffect::Fallible,
5307 B::RandomInt | B::RandomFloat | B::TimeNow | B::SealBox | B::SealValueBox => {
5308 BuiltinEffect::Nondeterministic
5309 }
5310 B::SetRate | B::SetRates | B::ReadWireProgram | B::WriteWireResidual | B::FileRead
5311 | B::FileWrite | B::EnvGet | B::EnvHas | B::EnvValue | B::VfsReadFile | B::VfsWriteFile | B::VfsMount | B::ReadBytes | B::TryReadBytes | B::ReadReals | B::StorageSet | B::StorageGet
5312 | B::StorageGetOr | B::StorageRemove | B::DomBody | B::DomCreateElement
5313 | B::DomCreateTextNode | B::DomSetText | B::DomSetHtml | B::DomClearChildren
5314 | B::DomOnMessage | B::DomMoveChildren | B::DomBeginPaint | B::DomSetAttribute
5315 | B::DomAppendChild | B::DomGetText | B::DomGetValue | B::DomSetValue
5316 | B::DomApplyPatches | B::DomApplyWords | B::DomWakeAfter | B::DomEnterValue | B::DomDispatchEntry | B::DomSetChecked | B::DomPreventDefault | B::DomSetStream
5317 | B::RtcPeerConnection | B::RtcDataChannel | B::RtcCreateOffer | B::RtcCreateAnswer
5318 | B::RtcSetLocal | B::RtcSetRemote | B::RtcAddIce | B::RtcSend | B::DomQuerySelector
5319 | B::DomAddEventListener | B::DomEventValue | B::DomEventKey | B::DomEventTarget
5320 | B::DomFetchText | B::DomResponseText
5321 | B::DomFetchSend | B::DomResponseStatus | B::DomResponseBody | B::DomResponseHeader
5322 | B::DomResponseError | B::DomFetchAbort | B::DomFetchSetTimeout | B::DomRoutePath
5323 | B::DomRouteQuery | B::DomNavigate | B::DomReplaceRoute | B::DomSetTitle | B::DomSetHeadHtml
5324 | B::DomClipboardWrite | B::DomDownloadFile | B::DomNotify | B::DomPublish
5325 | B::DomElementCommand | B::DomEventFileName | B::DomEventFileSize | B::DomEventFileType
5326 | B::DomEventFileBytes | B::DomListenFlags | B::DomAssignLocation | B::DomJournalDetail
5327 | B::DomSetInterval | B::DomScrollGap
5328 | B::DomOnWindowEvent | B::DomGetAttribute | B::DomGoBack | B::DomReload | B::DomOnRoute
5329 | B::NoteTurn
5330 | B::SignalNew | B::SignalSet | B::SignalGetInt | B::SignalGetText | B::SignalBeginRender
5332 | B::SignalNewText | B::SignalSetText | B::SignalEnterComponent | B::SignalExitComponent
5333 | B::SignalNewSeq | B::SignalGetSeq | B::SignalSetSeq | B::SignalNewFloat
5334 | B::SignalGetFloat | B::SignalSetFloat => BuiltinEffect::Effectful,
5335 }
5336 }
5337}
5338
5339pub fn contract_reason_text(reason: RuntimeValue) -> Result<String, String> {
5342 match reason {
5343 RuntimeValue::Text(t) => Ok(t.to_string()),
5344 other => Err(format!(
5345 "The reason after `otherwise` must be Text, but it was {}.",
5346 other.type_name()
5347 )),
5348 }
5349}
5350
5351pub fn inspect_unhandled_message(type_name: &str, variant_name: &str) -> String {
5360 format!(
5361 "Inspect has no arm for `{variant_name}` (a `{type_name}`) and no Otherwise (matches must \
5362 be exhaustive) — add a `When {variant_name} (…):` arm, or an `Otherwise:` to cover it."
5363 )
5364}
5365
5366#[cfg(test)]
5367#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/builtins/builtin_effect_tests.rs"]
5368mod builtin_effect_tests;