1pub type ProtocolFn = Rc<dyn Fn(&[Value]) -> Result<Value, String>>;
2pub type ProtocolSupports = Rc<dyn Fn(&Value) -> bool>;
3
4#[derive(Clone)]
5struct ProtocolImplementation {
6 supports: ProtocolSupports,
7 invoke: ProtocolFn,
8}
9
10#[derive(Default, Clone)]
11pub struct ProtocolRegistry {
12 methods: Rc<RefCell<HashMap<(String, String), Vec<ProtocolImplementation>>>>,
13 markers: Rc<RefCell<HashMap<String, Vec<ProtocolSupports>>>>,
14 extension_methods: Rc<RefCell<HashMap<(String, String, String, String), ProtocolFn>>>,
15 extension_categories: Rc<RefCell<HashSet<(String, String, String)>>>,
16 guest_methods: Rc<RefCell<HashMap<(String, String, String), Rc<Function>>>>,
17 guest_declarations: Rc<RefCell<HashSet<(String, String)>>>,
18 guest_protocols: Rc<RefCell<HashMap<String, Rc<GuestProtocol>>>>,
19}
20
21#[derive(Clone)]
22pub(crate) struct ProtocolRegistrySnapshot {
23 methods: HashMap<(String, String), Vec<ProtocolImplementation>>,
24 markers: HashMap<String, Vec<ProtocolSupports>>,
25 extension_methods: HashMap<(String, String, String, String), ProtocolFn>,
26 extension_categories: HashSet<(String, String, String)>,
27 guest_methods: HashMap<(String, String, String), Rc<Function>>,
28 guest_declarations: HashSet<(String, String)>,
29 guest_protocols: HashMap<String, Rc<GuestProtocol>>,
30}
31
32#[allow(dead_code)]
33impl ProtocolRegistry {
34 pub fn new() -> Self {
35 Self::default()
36 }
37
38 pub(crate) fn snapshot(&self) -> ProtocolRegistrySnapshot {
39 ProtocolRegistrySnapshot {
40 methods: self.methods.borrow().clone(),
41 markers: self.markers.borrow().clone(),
42 extension_methods: self.extension_methods.borrow().clone(),
43 extension_categories: self.extension_categories.borrow().clone(),
44 guest_methods: self.guest_methods.borrow().clone(),
45 guest_declarations: self.guest_declarations.borrow().clone(),
46 guest_protocols: self.guest_protocols.borrow().clone(),
47 }
48 }
49
50 pub(crate) fn restore(&self, snapshot: ProtocolRegistrySnapshot) {
51 *self.methods.borrow_mut() = snapshot.methods;
52 *self.markers.borrow_mut() = snapshot.markers;
53 *self.extension_methods.borrow_mut() = snapshot.extension_methods;
54 *self.extension_categories.borrow_mut() = snapshot.extension_categories;
55 *self.guest_methods.borrow_mut() = snapshot.guest_methods;
56 *self.guest_declarations.borrow_mut() = snapshot.guest_declarations;
57 *self.guest_protocols.borrow_mut() = snapshot.guest_protocols;
58 }
59
60 pub fn register<F>(
61 &mut self,
62 protocol: impl Into<String>,
63 method: impl Into<String>,
64 function: F,
65 ) where
66 F: Fn(&[Value]) -> Result<Value, String> + 'static,
67 {
68 let protocol = protocol.into();
69 if crate::lang::protocol::find_protocol(&protocol).is_some() {
70 self.register_declared(protocol, method, function);
71 return;
72 }
73 let protocol = protocol;
74 let supported_protocol = protocol.clone();
75 self.register_when(
76 protocol,
77 method,
78 move |value| native_protocol_supports(&supported_protocol, value),
79 function,
80 );
81 }
82
83 pub(crate) fn register_declared<F>(
84 &mut self,
85 protocol: impl Into<String>,
86 method: impl Into<String>,
87 function: F,
88 ) where
89 F: Fn(&[Value]) -> Result<Value, String> + 'static,
90 {
91 let protocol = protocol.into();
92 let method = method.into();
93 let declaration = crate::lang::protocol::find_protocol(&protocol)
94 .unwrap_or_else(|| panic!("unknown built-in protocol declaration: {protocol}"));
95 assert!(
96 declaration.method(&method).is_some(),
97 "method {method} is not declared by protocol {}",
98 declaration.name
99 );
100 let protocol = declaration.runtime_name();
101 let supported_protocol = protocol.clone();
102 self.register_when(
103 protocol,
104 method,
105 move |value| native_protocol_supports(&supported_protocol, value),
106 function,
107 );
108 }
109
110 pub fn register_marker<S>(&mut self, protocol: impl Into<String>, supports: S)
111 where
112 S: Fn(&Value) -> bool + 'static,
113 {
114 self.markers
115 .borrow_mut()
116 .entry(protocol.into())
117 .or_default()
118 .push(Rc::new(supports));
119 }
120
121 pub(crate) fn register_marker_declared<S>(&mut self, protocol: impl Into<String>, supports: S)
122 where
123 S: Fn(&Value) -> bool + 'static,
124 {
125 let protocol = protocol.into();
126 let declaration = crate::lang::protocol::find_protocol(&protocol)
127 .unwrap_or_else(|| panic!("unknown built-in protocol declaration: {protocol}"));
128 self.register_marker(declaration.runtime_name(), supports);
129 }
130
131 pub fn register_when<S, F>(
132 &mut self,
133 protocol: impl Into<String>,
134 method: impl Into<String>,
135 supports: S,
136 function: F,
137 ) where
138 S: Fn(&Value) -> bool + 'static,
139 F: Fn(&[Value]) -> Result<Value, String> + 'static,
140 {
141 let protocol = protocol.into();
142 let protocol = crate::lang::protocol::find_protocol(&protocol)
143 .map(|declaration| declaration.runtime_name())
144 .unwrap_or(protocol);
145 self.methods
146 .borrow_mut()
147 .entry((protocol, method.into()))
148 .or_default()
149 .push(ProtocolImplementation {
150 supports: Rc::new(supports),
151 invoke: Rc::new(function),
152 });
153 }
154
155 pub fn register_extension<F>(
161 &mut self,
162 provider: impl Into<String>,
163 type_name: impl Into<String>,
164 protocol: impl Into<String>,
165 method: impl Into<String>,
166 function: F,
167 ) where
168 F: Fn(&[Value]) -> Result<Value, String> + 'static,
169 {
170 self.extension_methods.borrow_mut().insert(
171 (
172 provider.into(),
173 type_name.into(),
174 protocol.into(),
175 method.into(),
176 ),
177 Rc::new(function),
178 );
179 }
180
181 pub fn register_extension_category(
184 &mut self,
185 provider: impl Into<String>,
186 type_name: impl Into<String>,
187 category: impl Into<String>,
188 ) {
189 self.extension_categories.borrow_mut().insert((
190 provider.into(),
191 type_name.into(),
192 category.into(),
193 ));
194 }
195
196 pub fn invoke_extension(
197 &self,
198 receiver: &ExtensionValue,
199 protocol: &str,
200 method: &str,
201 arguments: &[Value],
202 ) -> Result<Value, String> {
203 let key = (
204 receiver.provider.clone(),
205 receiver.type_name.clone(),
206 protocol.to_owned(),
207 method.to_owned(),
208 );
209 self.extension_methods
210 .borrow()
211 .get(&key)
212 .cloned()
213 .ok_or_else(|| {
214 format!(
215 "protocol/unsupported-receiver: extension {}/{} has no {}/{} implementation",
216 receiver.provider, receiver.type_name, protocol, method
217 )
218 })?(arguments)
219 }
220
221 pub fn extension_has_category(&self, receiver: &ExtensionValue, category: &str) -> bool {
222 self.extension_categories.borrow().contains(&(
223 receiver.provider.clone(),
224 receiver.type_name.clone(),
225 category.to_owned(),
226 ))
227 }
228
229 pub fn register_guest(
230 &self,
231 protocol: impl Into<String>,
232 type_name: impl Into<String>,
233 method: impl Into<String>,
234 function: Rc<Function>,
235 ) {
236 self.guest_methods.borrow_mut().insert(
237 (
238 protocol.into(),
239 type_name.into(),
240 method.into(),
241 ),
242 function,
243 );
244 }
245
246 pub fn declare_guest(&self, protocol: impl Into<String>, method: impl Into<String>) {
247 self.guest_declarations
248 .borrow_mut()
249 .insert((protocol.into(), method.into()));
250 }
251
252 pub fn register_guest_protocol(&self, protocol: Rc<GuestProtocol>) {
253 self.guest_protocols
254 .borrow_mut()
255 .insert(protocol.name.clone(), protocol);
256 }
257
258 fn guest_protocol(&self, name: &str) -> Option<Rc<GuestProtocol>> {
259 self.guest_protocols.borrow().get(name).cloned()
260 }
261
262 pub fn guest_protocol_reaches(&self, source: &str, target: &str) -> bool {
263 let mut pending = vec![source.to_owned()];
264 let mut visited = HashSet::new();
265 while let Some(current) = pending.pop() {
266 if !visited.insert(current.clone()) {
267 continue;
268 }
269 if current == target {
270 return true;
271 }
272 if let Some(protocol) = self.guest_protocol(¤t) {
273 pending.extend(protocol.parents.iter().cloned());
274 }
275 }
276 false
277 }
278
279 pub fn replace_guest_protocol(&self, protocol: impl Into<String>) {
280 let protocol = protocol.into();
281 self.guest_declarations
282 .borrow_mut()
283 .retain(|(candidate, _)| candidate != &protocol);
284 self.guest_methods
285 .borrow_mut()
286 .retain(|(candidate, _, _), _| candidate != &protocol);
287 self.guest_protocols.borrow_mut().remove(&protocol);
288 }
289
290 #[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
291 pub(crate) fn has_interpreted_guest_functions(&self) -> bool {
292 self.guest_methods
293 .borrow()
294 .values()
295 .any(|function| !is_direct_native_function(function))
296 }
297
298 pub fn invoke(
299 &self,
300 protocol: &str,
301 method: &str,
302 arguments: &[Value],
303 ) -> Result<Value, String> {
304 let protocol = protocol;
305 let known_method = self
306 .methods
307 .borrow()
308 .contains_key(&(protocol.to_owned(), method.to_owned()))
309 || self
310 .guest_declarations
311 .borrow()
312 .contains(&(protocol.to_owned(), method.to_owned()))
313 || protocol_declarations()
314 .iter()
315 .any(|declaration| declaration.runtime_name() == protocol);
316 if !known_method {
317 return Err(format!("missing protocol method: {protocol}/{method}"));
318 }
319 if let Some(Value::Extension(receiver)) = arguments.first() {
320 let extension_method = self.extension_methods.borrow().contains_key(&(
321 receiver.provider.clone(),
322 receiver.type_name.clone(),
323 protocol.to_owned(),
324 method.to_owned(),
325 ));
326 if extension_method {
327 return self.invoke_extension(receiver, protocol, method, arguments);
328 }
329 }
330 let named_type = match arguments.first() {
331 Some(Value::Struct(receiver)) => Some(receiver.ty.name.as_str()),
332 Some(Value::Mutable(receiver)) => Some(receiver.ty.name.as_str()),
333 _ => None,
334 };
335 if let Some(type_name) = named_type {
336 let guest_function = self
337 .guest_methods
338 .borrow()
339 .get(&(protocol.to_owned(), type_name.to_owned(), method.to_owned()))
340 .cloned();
341 if let Some(function) = guest_function {
342 return call_function(&function, arguments.to_vec());
343 }
344 }
345 let methods = self.methods.borrow();
346 let receiver = arguments.first().ok_or_else(|| {
347 format!("protocol/arity: {protocol}/{method} expects at least one argument, received 0")
348 })?;
349 let last_error = format!(
350 "protocol/unsupported-receiver: missing protocol implementation: {protocol}/{method}"
351 );
352 if let Some(implementations) = methods.get(&(protocol.to_string(), method.to_string())) {
353 for implementation in implementations.iter().rev() {
354 if (implementation.supports)(receiver) {
355 return (implementation.invoke)(arguments);
356 }
357 }
358 }
359 if self
360 .guest_declarations
361 .borrow()
362 .contains(&(protocol.to_owned(), method.to_owned()))
363 || protocol_declarations()
364 .iter()
365 .any(|declaration| declaration.runtime_name() == protocol)
366 {
367 Err(last_error)
368 } else {
369 Err(format!("missing protocol method: {protocol}/{method}"))
370 }
371 }
372
373 pub fn contains(&self, protocol: &str, method: &str) -> bool {
374 let methods = self.methods.borrow();
375 methods
376 .get(&(protocol.to_owned(), method.to_string()))
377 .is_some_and(|implementations| !implementations.is_empty())
378 }
379
380 pub fn satisfies(&self, protocol: &GuestProtocol, value: &Value) -> bool {
381 if let Value::Extension(receiver) = value {
382 let protocol_name = protocol
383 .name
384 .rsplit(|character| character == '/' || character == '.')
385 .next()
386 .unwrap_or(protocol.name.as_str());
387 let category_matches = match protocol_name {
388 "IMapType" => self.extension_has_category(receiver, "map"),
389 "ISetType" => self.extension_has_category(receiver, "set"),
390 "ISequential" => {
391 self.extension_has_category(receiver, "sequential")
392 || self.extension_has_category(receiver, "linear")
393 }
394 "ILinearType" => self.extension_has_category(receiver, "linear"),
395 "IColl" => {
396 self.extension_has_category(receiver, "coll")
397 || ["map", "set", "linear"]
398 .iter()
399 .any(|category| self.extension_has_category(receiver, category))
400 }
401 _ => false,
402 };
403 if category_matches {
404 return true;
405 }
406 }
407 if !protocol.parents.iter().all(|parent| {
408 self.guest_protocol(parent)
409 .is_some_and(|parent| self.satisfies(&parent, value))
410 || crate::lang::protocol::find_protocol(parent)
411 .is_some_and(|declaration| self.satisfies(&guest_protocol(declaration), value))
412 }) {
413 return false;
414 }
415 let protocol_name = protocol.name.clone();
416 if protocol.methods.is_empty() {
417 if let Some(implementations) = self.markers.borrow().get(&protocol_name) {
418 return implementations.iter().rev().any(|supports| supports(value));
419 }
420 if !protocol.parents.is_empty() {
421 return true;
422 }
423 return false;
424 }
425 if let Value::Extension(receiver) = value {
426 let methods = self.methods.borrow();
427 let extensions = self.extension_methods.borrow();
428 return protocol.methods.keys().all(|method| {
429 extensions.contains_key(&(
430 receiver.provider.clone(),
431 receiver.type_name.clone(),
432 protocol_name.clone(),
433 method.clone(),
434 ))
435 || methods
436 .get(&(protocol_name.clone(), method.clone()))
437 .is_some_and(|implementations| {
438 implementations
439 .iter()
440 .rev()
441 .any(|implementation| (implementation.supports)(value))
442 })
443 });
444 }
445 if let Value::Struct(receiver) = value {
446 return protocol.methods.keys().all(|method| {
447 self.guest_methods.borrow().contains_key(&(
448 protocol_name.clone(),
449 receiver.ty.name.clone(),
450 method.clone(),
451 )) || self
452 .methods
453 .borrow()
454 .get(&(protocol_name.clone(), method.clone()))
455 .is_some_and(|implementations| {
456 implementations
457 .iter()
458 .rev()
459 .any(|implementation| (implementation.supports)(value))
460 })
461 });
462 }
463 if let Value::Mutable(receiver) = value {
464 return protocol.methods.keys().all(|method| {
465 self.guest_methods.borrow().contains_key(&(
466 protocol_name.clone(),
467 receiver.ty.name.clone(),
468 method.clone(),
469 )) || self
470 .methods
471 .borrow()
472 .get(&(protocol_name.clone(), method.clone()))
473 .is_some_and(|implementations| {
474 implementations
475 .iter()
476 .rev()
477 .any(|implementation| (implementation.supports)(value))
478 })
479 });
480 }
481 let methods = self.methods.borrow();
482 if protocol.methods.keys().all(|method| {
483 methods
484 .get(&(protocol_name.clone(), method.clone()))
485 .is_some_and(|implementations| {
486 implementations
487 .iter()
488 .rev()
489 .any(|implementation| (implementation.supports)(value))
490 })
491 }) {
492 return true;
493 }
494 false
495 }
496
497 pub fn core() -> Self {
499 let mut registry = Self::new();
500 registry.register_marker_declared("IMutable", |value| {
501 native_protocol_supports("IMutable", value)
502 });
503 registry.register_marker_declared("IPersistent", |value| {
504 native_protocol_supports("IPersistent", value)
505 });
506 registry.register_marker_declared("IMapType", |value| {
507 native_protocol_supports("IMapType", value)
508 });
509 registry.register_marker_declared("ISequential", |value| {
510 native_protocol_supports("ISequential", value)
511 });
512 registry.register_marker_declared("ILinearType", |value| {
513 native_protocol_supports("ILinearType", value)
514 });
515 registry.register_marker_declared("ISetType", |value| {
516 native_protocol_supports("ISetType", value)
517 });
518 registry.register_marker_declared("IOFn", |value| matches!(value, Value::Keyword(_)));
519 registry.register("std.protocol.icount.ICount", "count", protocol_count);
520 registry.register("std.protocol.inth.INth", "nth", protocol_nth);
521 registry.register("std.protocol.ilookup.ILookup", "lookup", protocol_lookup);
522 registry.register(
523 "std.protocol.ipointer.IPointer",
524 "ptr-context",
525 protocol_pointer_context,
526 );
527 registry.register("std.protocol.ifind.IFind", "find", protocol_find);
528 registry.register("std.protocol.iassoc.IAssoc", "assoc", protocol_assoc);
529 registry.register("std.protocol.iconj.IConj", "conj", protocol_conj);
530 registry.register("std.protocol.icons.ICons", "cons", protocol_cons);
531 registry.register("std.protocol.idissoc.IDissoc", "dissoc", protocol_dissoc);
532 registry.register("std.protocol.iempty.IEmpty", "empty", protocol_empty);
533 registry.register(
534 "std.protocol.iequality.IEquality",
535 "equality",
536 protocol_equality,
537 );
538 registry.register(
539 "std.protocol.idisplay.IDisplay",
540 "display",
541 protocol_display,
542 );
543 registry.register(
544 "std.protocol.iencodable.IEncodable",
545 "encode-with",
546 protocol_encode_with,
547 );
548 registry.register(
549 "std.protocol.iexinfo.IExInfo",
550 "data",
551 |arguments| match arguments {
552 [Value::ExceptionInfo(value)] => Ok((*value.data).clone()),
553 [_] => {
554 Err("missing protocol implementation: std.protocol.iexinfo.IExInfo/data".into())
555 }
556 _ => Err("IExInfo/data expects one argument".into()),
557 },
558 );
559 registry.register("std.protocol.ihash.IHash", "hash", protocol_hash);
560 registry.register(
561 "std.protocol.ihashcached.IHashCached",
562 "hash-current",
563 protocol_hash_current,
564 );
565 registry.register(
566 "std.protocol.ihashcached.IHashCached",
567 "hash-put",
568 protocol_hash_put,
569 );
570 registry.register_when(
571 "std.protocol.ifn.IFn",
572 "invoke",
573 Value::supports_native_ifn,
574 protocol_invoke,
575 );
576 registry.register("std.protocol.ipair.IPair", "key", protocol_pair_key);
577 registry.register("std.protocol.ipair.IPair", "value", protocol_pair_value);
578 registry.register(
579 "std.protocol.ipeekfirst.IPeekFirst",
580 "peek-first",
581 protocol_peek_first,
582 );
583 registry.register(
584 "std.protocol.ipeeklast.IPeekLast",
585 "peek-last",
586 protocol_peek_last,
587 );
588 registry.register(
589 "std.protocol.ipopfirst.IPopFirst",
590 "pop-first",
591 protocol_pop_first,
592 );
593 registry.register(
594 "std.protocol.ipoplast.IPopLast",
595 "pop-last",
596 protocol_pop_last,
597 );
598 registry.register(
599 "std.protocol.ipushfirst.IPushFirst",
600 "push-first",
601 protocol_push_first,
602 );
603 registry.register(
604 "std.protocol.ipushlast.IPushLast",
605 "push-last",
606 protocol_push_last,
607 );
608 registry.register("std.protocol.iiter.IIter", "iter", protocol_iter);
609 registry.register(
610 "std.protocol.iiterator.IIterator",
611 "iter-next?",
612 |arguments| {
613 arguments
614 .first()
615 .ok_or_else(|| "IIterator/iter-next? expects one argument".to_string())
616 .and_then(iterator_has_next)
617 },
618 );
619 registry.register(
620 "std.protocol.iiterator.IIterator",
621 "iter-next",
622 |arguments| {
623 arguments
624 .first()
625 .ok_or_else(|| "IIterator/iter-next expects one argument".to_string())
626 .and_then(iterator_next)
627 },
628 );
629 registry.register(
630 "std.protocol.iclose.IClose",
631 "close",
632 |arguments| match arguments {
633 [Value::Coroutine(coroutine)] => {
634 coroutine_close(coroutine)?;
635 Ok(Value::Coroutine(coroutine.clone()))
636 }
637 [Value::Stream(stream)] => {
638 stream_close(stream)?;
639 Ok(Value::Stream(stream.clone()))
640 }
641 [value] => iterator_close(value),
642 _ => Err("IClose/close expects one argument".into()),
643 },
644 );
645 registry.register(
646 "std.protocol.inamespaced.INamespaced",
647 "name",
648 protocol_namespaced_name,
649 );
650 registry.register(
651 "std.protocol.inamespaced.INamespaced",
652 "namespace",
653 protocol_namespaced_namespace,
654 );
655 registry.register(
656 "std.protocol.istringlike.IStringLike",
657 "to-string",
658 protocol_string_like_to_string,
659 );
660 registry.register(
661 "std.protocol.istringlike.IStringLike",
662 "from-string",
663 protocol_string_like_from_string,
664 );
665 registry.register("std.protocol.iobjtype.IObjType", "meta", protocol_meta);
666 registry.register(
667 "std.protocol.imetadata.IMetadata",
668 "metatype",
669 protocol_metatype,
670 );
671 registry.register(
672 "std.protocol.iobjtype.IObjType",
673 "with-meta",
674 protocol_with_meta,
675 );
676 registry.register(
677 "std.protocol.icoll.IColl",
678 "start-string",
679 protocol_coll_start,
680 );
681 registry.register("std.protocol.icoll.IColl", "end-string", protocol_coll_end);
682 registry.register("std.protocol.icoll.IColl", "sep-string", protocol_coll_sep);
683 registry.register("std.protocol.ideref.IDeref", "deref", protocol_deref);
684 registry.register(
685 "std.protocol.iapplicable.IApplicable",
686 "apply-default",
687 protocol_apply_default,
688 );
689 registry.register(
690 "std.protocol.iapplicable.IApplicable",
691 "apply-in",
692 protocol_apply_in,
693 );
694 registry.register(
695 "std.protocol.iapplicable.IApplicable",
696 "transform-in",
697 protocol_transform_in,
698 );
699 registry.register(
700 "std.protocol.iapplicable.IApplicable",
701 "transform-out",
702 protocol_transform_out,
703 );
704 registry.register(
705 "std.protocol.iinvokein.IInvokeIn",
706 "invoke-in",
707 protocol_invoke_in,
708 );
709 registry.register(
710 "std.protocol.idereftimeout.IDerefTimeout",
711 "deref-timeout",
712 protocol_deref_timeout,
713 );
714 registry.register("std.protocol.ireset.IReset", "reset", protocol_reset);
715 registry.register("std.protocol.icas.ICas", "cas", protocol_cas);
716 registry.register("std.protocol.ireduce.IReduce", "reduce", protocol_reduce);
717 registry.register(
718 "std.protocol.itomutable.IToMutable",
719 "to-mutable",
720 protocol_to_mutable,
721 );
722 registry.register(
723 "std.protocol.itopersistent.IToPersistent",
724 "to-persistent",
725 protocol_to_persistent,
726 );
727 registry.register(
728 "std.protocol.ipromise.IPromise",
729 "state",
730 protocol_promise_state,
731 );
732 registry.register(
733 "std.protocol.ipromise.IPromise",
734 "value",
735 protocol_promise_value,
736 );
737 registry.register("std.protocol.ipromise.IPromise", "then", |arguments| {
738 protocol_promise_chain("promise/then", arguments)
739 });
740 registry.register("std.protocol.ipromise.IPromise", "catch", |arguments| {
741 protocol_promise_chain("promise/catch", arguments)
742 });
743 registry.register("std.protocol.ipromise.IPromise", "finally", |arguments| {
744 protocol_promise_chain("promise/finally", arguments)
745 });
746 registry.register(
747 "std.protocol.ipromise.IPromise",
748 "cancel",
749 protocol_promise_cancel,
750 );
751 registry.register(
752 "std.protocol.icoroutine.ICoroutine",
753 "status",
754 protocol_coroutine_status,
755 );
756 registry.register(
757 "std.protocol.icoroutine.ICoroutine",
758 "resume",
759 protocol_coroutine_resume,
760 );
761 registry.register(
762 "std.protocol.istream.IStream",
763 "next",
764 |arguments| match arguments {
765 [Value::Stream(stream)] => Ok(stream_next(stream)),
766 [_] => Err("IStream/next expects a stream".into()),
767 _ => Err("IStream/next expects one argument".into()),
768 },
769 );
770 registry.register(
771 "std.protocol.istreamwrite.IStreamWrite",
772 "write",
773 |arguments| match arguments {
774 [_target, _value] => Err("IStreamWrite/write expects a writable stream".into()),
775 _ => Err("IStreamWrite/write expects two arguments".into()),
776 },
777 );
778 registry.register(
779 "std.protocol.iabort.IAbort",
780 "abort",
781 |arguments| match arguments {
782 [_target, _error] => Err("IAbort/abort expects an abortable stream".into()),
783 _ => Err("IAbort/abort expects two arguments".into()),
784 },
785 );
786 registry.register(
787 "std.protocol.iwatch.IWatch",
788 "watch-add",
789 protocol_watch_add,
790 );
791 registry.register(
792 "std.protocol.iwatch.IWatch",
793 "watch-remove",
794 protocol_watch_remove,
795 );
796 registry.register(
797 "std.protocol.iwatch.IWatch",
798 "watch-list",
799 protocol_watch_list,
800 );
801 registry
802 }
803}
804
805thread_local! {
806 static ACTIVE_PROTOCOLS: RefCell<Option<ProtocolRegistry>> = const { RefCell::new(None) };
807 static ACTIVE_NAMESPACES: RefCell<Option<NamespaceRegistry<Value>>> = const { RefCell::new(None) };
808 static ACTIVE_DEFINITION_ORIGIN: Cell<VarOrigin> = const { Cell::new(VarOrigin::Source) };
809 static ACTIVE_PROMISE_PROVIDER: RefCell<Option<Rc<dyn PromiseProvider>>> = const { RefCell::new(None) };
810 static ACTIVE_FILE_PROVIDER: RefCell<Option<Rc<dyn FileProvider>>> = const { RefCell::new(None) };
811 static ACTIVE_SOCKET_PROVIDER: RefCell<Option<Rc<dyn SocketProvider>>> = const { RefCell::new(None) };
812 static ACTIVE_KERNEL_PROVIDER: RefCell<Option<Rc<KernelProvider>>> = const { RefCell::new(None) };
813 static ACTIVE_PACKAGE_CATALOG: RefCell<Option<PackageCatalog>> = const { RefCell::new(None) };
814 static ACTIVE_PROCESS_ALLOWED: Cell<bool> = const { Cell::new(false) };
815 static ACTIVE_TEST_RUNNER: RefCell<String> = RefCell::new("code.test".into());
816 static HOST_CALL_HANDLER: RefCell<Option<Rc<dyn Fn(String, String, Vec<Value>) -> Result<Value, String>>>> = const { RefCell::new(None) };
817 static NAMESPACE_SOURCE_PROVIDER: RefCell<Option<Rc<dyn Fn(&str) -> Option<NamespaceResource>>>> = const { RefCell::new(None) };
818 static ACTIVE_THROWN_VALUE: RefCell<Option<(String, Value)>> = const { RefCell::new(None) };
819 static ACTIVE_MULTIMETHODS: RefCell<HashMap<String, Rc<RefCell<MultiMethod>>>> = RefCell::new(HashMap::new());
820 #[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
821 static ACTIVE_DIRECT_NATIVE_NAMESPACE_LOADER: RefCell<Option<Rc<dyn Fn(&str, NamespaceResource, &mut HashMap<String, Value>) -> Result<(), String>>>> = const { RefCell::new(None) };
822 #[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
823 static ACTIVE_DIRECT_NATIVE_EXECUTION: Cell<bool> = const { Cell::new(false) };
824}
825
826#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
827pub(crate) type MultiMethodRegistry =
828 Rc<RefCell<HashMap<String, Rc<RefCell<MultiMethod>>>>>;
829
830#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
831#[derive(Clone)]
832pub(crate) struct DirectNativeContext {
833 pub(crate) namespaces: NamespaceRegistry<Value>,
834 pub(crate) namespace: String,
839 pub(crate) protocols: ProtocolRegistry,
840 pub(crate) promise_provider: Rc<dyn PromiseProvider>,
841 pub(crate) file_provider: Option<Rc<dyn FileProvider>>,
842 pub(crate) socket_provider: Option<Rc<dyn SocketProvider>>,
843 pub(crate) process_allowed: bool,
844 pub(crate) kernel_provider: Option<Rc<KernelProvider>>,
845 pub(crate) package_catalog: PackageCatalog,
846 pub(crate) macros: Rc<RefCell<HashMap<(String, String), Rc<Function>>>>,
847 pub(crate) namespace_source:
848 Option<Rc<dyn Fn(&str) -> Option<NamespaceResource>>>,
849 pub(crate) host_handler:
850 Option<Rc<dyn Fn(String, String, Vec<Value>) -> Result<Value, String>>>,
851 pub(crate) test_runner: String,
852 pub(crate) definition_origin: VarOrigin,
853 pub(crate) multimethods: MultiMethodRegistry,
854 pub(crate) native_namespace_loader: Option<
855 Rc<dyn Fn(
856 &str,
857 NamespaceResource,
858 &mut HashMap<String, Value>,
859 ) -> Result<(), String>>,
860 >,
861 pub(crate) work_context: Option<crate::work::WorkContext>,
862}
863
864#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
865impl DirectNativeContext {
866 pub(crate) fn capture() -> Self {
867 let multimethods = Rc::new(RefCell::new(
868 ACTIVE_MULTIMETHODS.with(|active| active.borrow().clone()),
869 ));
870 Self::capture_with_multimethods(multimethods)
871 }
872
873 pub(crate) fn capture_with_multimethods(multimethods: MultiMethodRegistry) -> Self {
874 let namespaces = namespace_registry()
875 .unwrap_or_else(|_| NamespaceRegistry::new("user"));
876 let namespace = namespaces.current().name().as_str().to_owned();
877 let protocols = ACTIVE_PROTOCOLS
878 .with(|active| active.borrow().clone())
879 .unwrap_or_else(ProtocolRegistry::core);
880 let promise_provider = ACTIVE_PROMISE_PROVIDER
881 .with(|active| active.borrow().clone())
882 .unwrap_or_else(|| Rc::new(LocalPromiseProvider));
883 let file_provider = ACTIVE_FILE_PROVIDER.with(|active| active.borrow().clone());
884 let socket_provider = ACTIVE_SOCKET_PROVIDER.with(|active| active.borrow().clone());
885 let process_allowed = ACTIVE_PROCESS_ALLOWED.get();
886 let kernel_provider = ACTIVE_KERNEL_PROVIDER.with(|active| active.borrow().clone());
887 let package_catalog = ACTIVE_PACKAGE_CATALOG
888 .with(|active| active.borrow().clone())
889 .unwrap_or_default();
890 let macros = ACTIVE_MACROS.with(|active| {
891 active
892 .borrow()
893 .clone()
894 .unwrap_or_else(|| Rc::new(RefCell::new(HashMap::new())))
895 });
896 let namespace_source = NAMESPACE_SOURCE_PROVIDER
897 .with(|active| active.borrow().clone());
898 let host_handler = HOST_CALL_HANDLER.with(|active| active.borrow().clone());
899 let test_runner = ACTIVE_TEST_RUNNER.with(|active| active.borrow().clone());
900 let definition_origin = ACTIVE_DEFINITION_ORIGIN.with(Cell::get);
901 let native_namespace_loader = ACTIVE_DIRECT_NATIVE_NAMESPACE_LOADER
902 .with(|active| active.borrow().clone());
903 let work_context = crate::work::current_work_context();
904 Self {
905 namespaces,
906 namespace,
907 protocols,
908 promise_provider,
909 file_provider,
910 socket_provider,
911 process_allowed,
912 kernel_provider,
913 package_catalog,
914 macros,
915 namespace_source,
916 host_handler,
917 test_runner,
918 definition_origin,
919 multimethods,
920 native_namespace_loader,
921 work_context,
922 }
923 }
924
925 pub(crate) fn with<R>(&self, operation: impl FnOnce() -> R) -> R {
926 let namespaces = self.namespaces.clone();
927 let namespace = self.namespace.clone();
928 let run = || {
929 let previous = namespaces.current().name().as_str().to_owned();
930 namespaces.set_current(&namespace);
931 let result = with_test_runner(&self.test_runner, || {
932 with_capability_providers(
933 self.file_provider.clone(),
934 self.socket_provider.clone(),
935 self.process_allowed,
936 self.kernel_provider.clone(),
937 || {
938 with_package_catalog(&self.package_catalog, || {
939 with_promise_provider(self.promise_provider.clone(), || {
940 with_macros(self.macros.clone(), || {
941 with_namespace_registry(&self.namespaces, || {
942 with_definition_origin(self.definition_origin, || {
943 with_protocols(&self.protocols, || {
944 with_direct_native_context_values(self, operation)
945 })
946 })
947 })
948 })
949 })
950 })
951 },
952 )
953 });
954 namespaces.set_current(&previous);
955 result
956 };
957 if let Some(context) = self.work_context.clone() {
958 crate::work::with_current_work_context(context, run)
959 } else {
960 run()
961 }
962 }
963}
964
965#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
966fn with_direct_native_context_values<R>(
967 context: &DirectNativeContext,
968 operation: impl FnOnce() -> R,
969) -> R {
970 let run_with_multimethods = || {
971 ACTIVE_MULTIMETHODS.with(|active| {
972 let previous = std::mem::replace(
973 &mut *active.borrow_mut(),
974 context.multimethods.borrow().clone(),
975 );
976 let result = operation();
977 *context.multimethods.borrow_mut() = active.borrow().clone();
978 *active.borrow_mut() = previous;
979 result
980 })
981 };
982 let run_with_loader = || {
983 if let Some(loader) = context.native_namespace_loader.clone() {
984 with_direct_native_namespace_loader(loader, run_with_multimethods)
985 } else {
986 run_with_multimethods()
987 }
988 };
989 let run_with_source = || {
990 if let Some(provider) = context.namespace_source.clone() {
991 with_namespace_source(provider, run_with_loader)
992 } else {
993 run_with_loader()
994 }
995 };
996 if let Some(handler) = context.host_handler.clone() {
997 with_host_calls(handler, run_with_source)
998 } else {
999 run_with_source()
1000 }
1001}
1002
1003pub(crate) fn with_test_runner<R>(runner: &str, f: impl FnOnce() -> R) -> R {
1004 ACTIVE_TEST_RUNNER.with(|active| {
1005 let previous = active.replace(runner.into());
1006 let result = f();
1007 active.replace(previous);
1008 result
1009 })
1010}
1011
1012pub(crate) fn snapshot_multimethods() -> HashMap<String, MultiMethod> {
1013 ACTIVE_MULTIMETHODS.with(|active| {
1014 active
1015 .borrow()
1016 .iter()
1017 .map(|(name, state)| (name.clone(), state.borrow().clone()))
1018 .collect()
1019 })
1020}
1021
1022pub(crate) fn restore_multimethods(snapshot: HashMap<String, MultiMethod>) {
1023 ACTIVE_MULTIMETHODS.with(|active| {
1024 *active.borrow_mut() = snapshot
1025 .into_iter()
1026 .map(|(name, state)| (name, Rc::new(RefCell::new(state))))
1027 .collect();
1028 });
1029}
1030
1031pub(crate) fn register_multimethod(name: String, state: Rc<RefCell<MultiMethod>>) {
1032 ACTIVE_MULTIMETHODS.with(|active| {
1033 active.borrow_mut().insert(name, state);
1034 });
1035}
1036
1037pub(crate) fn multimethod_state(name: &str) -> Option<Rc<RefCell<MultiMethod>>> {
1038 ACTIVE_MULTIMETHODS.with(|active| active.borrow().get(name).cloned())
1039}
1040
1041pub(crate) fn active_protocol_registry() -> Result<ProtocolRegistry, String> {
1042 ACTIVE_PROTOCOLS
1043 .with(|active| active.borrow().clone())
1044 .ok_or_else(|| "protocol registry is unavailable".into())
1045}
1046
1047#[derive(Clone)]
1048pub enum NamespaceResource {
1049 Source(String),
1050 #[cfg(not(target_arch = "wasm32"))]
1053 SourcePath(std::path::PathBuf),
1054 #[cfg(feature = "bytecode-vm")]
1055 Bytecode {
1056 namespace_form: String,
1057 artifact: Vec<u8>,
1058 },
1059}
1060
1061#[cfg(not(target_arch = "wasm32"))]
1062pub(crate) fn read_source_resource(
1063 resource: &NamespaceResource,
1064 namespace: &str,
1065) -> Result<String, String> {
1066 match resource {
1067 NamespaceResource::Source(source) => Ok(source.clone()),
1068 NamespaceResource::SourcePath(path) => std::fs::read_to_string(path)
1069 .map_err(|error| format!("{namespace}: cannot read {}: {error}", path.display())),
1070 #[cfg(feature = "bytecode-vm")]
1071 NamespaceResource::Bytecode { .. } => {
1072 Err(format!("{namespace}: bytecode resource is not source text"))
1073 }
1074 }
1075}
1076
1077pub(crate) fn thrown_error(value: Value) -> String {
1078 thrown_error_at(value, current_exception_site())
1079}
1080
1081pub(crate) fn thrown_error_at(value: Value, site: Option<ExceptionSite>) -> String {
1082 record_exception_throw(&value, site);
1083 let error = format!("thrown: {}", value.display());
1084 ACTIVE_THROWN_VALUE.with(|active| {
1085 *active.borrow_mut() = Some((error.clone(), value));
1086 });
1087 error
1088}
1089
1090pub(crate) fn promise_rejection_error(error: PromiseRejection) -> String {
1091 match error {
1092 PromiseRejection::Message(message) => message,
1093 PromiseRejection::Value(value) | PromiseRejection::Cancelled(value) => thrown_error(value),
1094 }
1095}
1096
1097pub(crate) fn caught_error(error: &str) -> Value {
1098 ACTIVE_THROWN_VALUE.with(|active| {
1099 let mut active = active.borrow_mut();
1100 if active
1101 .as_ref()
1102 .is_some_and(|(thrown_error, _)| error.starts_with(thrown_error))
1103 {
1104 return active.take().unwrap().1;
1105 }
1106 Value::String(error.to_owned())
1107 })
1108}
1109
1110pub(crate) fn catch_matches(error: &str, class: &str) -> bool {
1111 if class == "Exception" || class == "Throwable" {
1112 return true;
1113 }
1114 if let Some(selectors) = class
1115 .strip_prefix('[')
1116 .and_then(|value| value.strip_suffix(']'))
1117 {
1118 return selectors
1119 .split(',')
1120 .any(|selector| catch_matches(error, selector));
1121 }
1122 if let Some(selector) = class.strip_prefix(':') {
1123 return ACTIVE_THROWN_VALUE.with(|active| {
1124 active.borrow().as_ref().is_some_and(|(message, value)| {
1125 error.starts_with(message)
1126 && matches!(value, Value::ExceptionInfo(info)
1127 if map_entries(&info.data).is_some_and(|entries| entries.iter().any(|(key, value)| {
1128 matches!(key, Value::Keyword(name) if name.as_str() == "ex/code")
1129 && matches!(value, Value::Keyword(code) if code.as_str() == selector)
1130 })))
1131 })
1132 });
1133 }
1134 ACTIVE_THROWN_VALUE.with(|active| {
1135 active.borrow().as_ref().is_some_and(|(message, value)| {
1136 error.starts_with(message)
1137 && match value {
1138 Value::Struct(value) => {
1139 value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1140 }
1141 Value::Mutable(value) => {
1142 value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1143 }
1144 _ => false,
1145 }
1146 })
1147 })
1148}
1149
1150pub fn with_namespace_registry<R>(
1152 registry: &NamespaceRegistry<Value>,
1153 operation: impl FnOnce() -> R,
1154) -> R {
1155 ACTIVE_NAMESPACES.with(|active| {
1156 let previous = active.replace(Some(registry.clone()));
1157 let result = operation();
1158 active.replace(previous);
1159 result
1160 })
1161}
1162
1163pub fn with_definition_origin<R>(origin: VarOrigin, operation: impl FnOnce() -> R) -> R {
1164 ACTIVE_DEFINITION_ORIGIN.with(|active| {
1165 let previous = active.replace(origin);
1166 let result = operation();
1167 active.set(previous);
1168 result
1169 })
1170}
1171
1172pub(crate) fn definition_origin() -> VarOrigin {
1173 ACTIVE_DEFINITION_ORIGIN.with(Cell::get)
1174}
1175
1176pub(crate) fn binding_is_local(var: &KernelVar<Value>) -> bool {
1177 namespace_registry()
1178 .map(|registry| {
1179 var.symbol().get_namespace().is_none()
1180 || var.symbol().get_namespace() == Some(registry.current().name().as_str())
1181 })
1182 .unwrap_or(true)
1183}
1184
1185pub(crate) fn local_var_name(name: &str) -> String {
1195 match namespace_registry() {
1196 Ok(registry) => format!("{}/{}", registry.current().name().as_str(), name),
1197 Err(_) => name.to_string(),
1198 }
1199}
1200
1201fn prepare_owned_definition(env: &mut HashMap<String, Value>, name: &str) -> Result<(), String> {
1202 if let Some(Value::Var(var)) = env.get(name) {
1203 if !binding_is_local(var) {
1204 if let Ok(registry) = namespace_registry() {
1205 registry.current().unmap(&Symbol::parse(name));
1206 }
1207 env.remove(name);
1208 }
1209 }
1210 Ok(())
1211}
1212
1213pub(crate) fn vm_def_global(
1219 name: &str,
1220 value: Value,
1221 metadata: Option<Rc<Metadata>>,
1222) -> Result<KernelVar<Value>, String> {
1223 let registry = namespace_registry()?;
1224 let current = registry.current();
1225 let local = Symbol::create(None, name);
1226 if let Some(existing) = current.resolve(&local) {
1227 if binding_is_local(&existing) {
1228 existing.reset_value(value);
1229 if metadata.is_some() {
1230 existing.set_hara_metadata(metadata);
1231 }
1232 existing.set_origin(definition_origin());
1233 refresh_schema_contract(&existing)?;
1234 return Ok(existing);
1235 }
1236 current.unmap(&local);
1237 }
1238 let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), value);
1239 var.set_hara_metadata(metadata);
1240 var.set_origin(definition_origin());
1241 current.map_var(local, var.clone());
1242 refresh_schema_contract(&var)?;
1243 Ok(var)
1244}
1245
1246pub(crate) fn vm_def_macro(
1247 name: &str,
1248 value: Value,
1249 metadata: Option<Rc<Metadata>>,
1250) -> Result<KernelVar<Value>, String> {
1251 let Value::Function(function) = &value else {
1252 return Err("defmacro expects a function value".into());
1253 };
1254 let function = function.clone();
1255 let namespace = namespace_registry()?.current().name().as_str().to_owned();
1256 let var = vm_def_global(name, value, metadata)?;
1257 register_macro(&namespace, name, function)?;
1258 Ok(var)
1259}
1260
1261pub(crate) fn vm_declare_global(name: &str) -> Result<KernelVar<Value>, String> {
1265 let registry = namespace_registry()?;
1266 let current = registry.current();
1267 let local = Symbol::create(None, name);
1268 if let Some(existing) = current.resolve(&local) {
1269 if binding_is_local(&existing) {
1270 existing.set_origin(definition_origin());
1271 return Ok(existing);
1272 }
1273 current.unmap(&local);
1278 }
1279 let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), Value::Nil);
1280 var.set_origin(definition_origin());
1281 current.map_var(local, var.clone());
1282 Ok(var)
1283}
1284
1285pub(crate) fn vm_resolve_global(name: &str) -> Result<KernelVar<Value>, String> {
1288 let registry = namespace_registry()?;
1289 if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1290 return Ok(var);
1291 }
1292 if let Some((namespace, _)) = name.rsplit_once('/') {
1293 if NAMESPACE_SOURCE_PROVIDER.with(|active| {
1294 active
1295 .borrow()
1296 .as_ref()
1297 .is_some_and(|provider| provider(namespace).is_some())
1298 }) {
1299 require_namespace(®istry, &mut HashMap::new(), namespace)?;
1300 if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1301 return Ok(var);
1302 }
1303 }
1304 }
1305 Err(format!("unbound symbol: {name}"))
1306}
1307
1308pub(crate) fn vm_resolve_namespace_value(name: &str) -> Result<Value, String> {
1314 let registry = namespace_registry()?;
1315 if let Some(namespace) = registry
1316 .current()
1317 .aliases()
1318 .into_iter()
1319 .find_map(|(alias, namespace)| (alias.as_str() == name).then_some(namespace))
1320 {
1321 return Ok(Value::Namespace(Rc::new(namespace)));
1322 }
1323 if let Some(target) = registry.current().lazy_target(name) {
1324 require_namespace(®istry, &mut HashMap::new(), target.as_str())?;
1325 let namespace = registry
1326 .find(target.as_str())
1327 .ok_or_else(|| format!("Cannot require missing namespace: {target}"))?;
1328 registry.current().alias(name, namespace.clone());
1329 return Ok(Value::Namespace(Rc::new(namespace)));
1330 }
1331 registry
1332 .find(name)
1333 .map(|namespace| Value::Namespace(Rc::new(namespace)))
1334 .ok_or_else(|| format!("unbound symbol: {name}"))
1335}
1336
1337fn validate_named_definition(kind: &str, name: &str, fields: &[NamedField]) -> Result<(), String> {
1338 if name.contains('/') {
1339 return Err(format!("{kind} name must be an unqualified symbol"));
1340 }
1341 if fields
1342 .iter()
1343 .any(|field| field.name.is_empty() || field.name.contains('/'))
1344 {
1345 return Err(format!("{kind} field names must be unqualified symbols"));
1346 }
1347 if fields
1348 .iter()
1349 .map(|field| &field.name)
1350 .collect::<HashSet<_>>()
1351 .len()
1352 != fields.len()
1353 {
1354 return Err(format!("Duplicate {kind} field"));
1355 }
1356 Ok(())
1357}
1358
1359pub(crate) fn with_declaration_transaction<R>(
1365 environment: &mut HashMap<String, Value>,
1366 operation: impl FnOnce(&mut HashMap<String, Value>) -> Result<R, String>,
1367) -> Result<R, String> {
1368 let registry = namespace_registry()?;
1369 let registry_snapshot = registry.snapshot();
1370 let environment_snapshot = environment.clone();
1371 let protocol_snapshot = ACTIVE_PROTOCOLS.with(|active| {
1372 active
1373 .borrow()
1374 .as_ref()
1375 .map(ProtocolRegistry::snapshot)
1376 });
1377 let multimethod_snapshot = snapshot_multimethods();
1378
1379 let result = operation(environment);
1380 if result.is_err() {
1381 registry.restore(registry_snapshot);
1382 *environment = environment_snapshot;
1383 if let Some(snapshot) = protocol_snapshot {
1384 ACTIVE_PROTOCOLS.with(|active| {
1385 if let Some(registry) = active.borrow().as_ref() {
1386 registry.restore(snapshot);
1387 }
1388 });
1389 }
1390 restore_multimethods(multimethod_snapshot);
1391 }
1392 result
1393}
1394
1395fn prepare_named_binding(namespace: &crate::kernel::Namespace<Value>, name: &str) {
1396 let symbol = Symbol::parse(name);
1397 if let Some(existing) = namespace.resolve(&symbol) {
1398 if existing.symbol().get_namespace() != Some(namespace.name().as_str()) {
1399 namespace.unmap(&symbol);
1400 }
1401 }
1402}
1403
1404pub(crate) fn publish_named_value(
1408 kind: &str,
1409 name: &str,
1410 fields: Vec<NamedField>,
1411 environment: &mut HashMap<String, Value>,
1412 metadata: Option<Rc<Metadata>>,
1413) -> Result<Value, String> {
1414 validate_named_definition(kind, name, &fields)?;
1415 let mutable = kind == "defmutable";
1416 let schema_form = named_value_schema_form(
1417 &format!("{}/{}", namespace_registry()?.current().name().as_str(), name),
1418 mutable,
1419 &fields,
1420 );
1421 let metadata = assoc_metadata(metadata, "schema", metadata_value(&schema_form)?)
1422 .ok_or_else(|| "named value schema metadata could not be created".to_string())?;
1423 let field_names = fields
1424 .iter()
1425 .map(|field| field.name.clone())
1426 .collect::<Vec<_>>();
1427 with_declaration_transaction(environment, |environment| {
1428 let registry = namespace_registry()?;
1429 let namespace = registry.current();
1430 let namespace_name = namespace.name().as_str().to_owned();
1431 let type_name = format!("{}/{}", namespace_name, name);
1432 let declaration = Rc::new(NamedDeclaration::new(
1433 type_name.clone(),
1434 mutable,
1435 fields.clone(),
1436 schema_form.clone(),
1437 ));
1438
1439 let (type_value, map_constructor) = if mutable {
1440 let ty = Rc::new(MutableType {
1441 name: type_name.clone(),
1442 fields: field_names.clone(),
1443 declaration: Some(declaration.clone()),
1444 });
1445 let map_type = ty.clone();
1446 let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1447 let source = values.first().expect("native arity is checked");
1448 let values = map_type
1449 .fields
1450 .iter()
1451 .map(|field| {
1452 map_value(source, &named_field_key(field))
1453 .cloned()
1454 .unwrap_or(Value::Nil)
1455 })
1456 .collect();
1457 Ok(Value::Mutable(Rc::new(MutableValue::from_values(
1458 map_type.clone(),
1459 values,
1460 None,
1461 )?)))
1462 });
1463 (Value::MutableType(ty), constructor)
1464 } else {
1465 let ty = Rc::new(StructType {
1466 name: type_name.clone(),
1467 fields: field_names,
1468 declaration: Some(declaration),
1469 });
1470 let map_type = ty.clone();
1471 let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1472 let source = values.first().expect("native arity is checked");
1473 let values = map_type
1474 .fields
1475 .iter()
1476 .map(|field| {
1477 map_value(source, &named_field_key(field))
1478 .cloned()
1479 .unwrap_or(Value::Nil)
1480 })
1481 .collect();
1482 Ok(Value::Struct(Rc::new(StructValue::from_values(
1483 map_type.clone(),
1484 values,
1485 None,
1486 )?)))
1487 });
1488 (Value::StructType(ty), constructor)
1489 };
1490
1491 let bindings = [
1492 (name.to_owned(), type_value.clone()),
1493 (format!("->{}", name), type_value),
1494 (format!("map->{}", name), map_constructor),
1495 ];
1496 for (binding, value) in bindings {
1497 prepare_named_binding(&namespace, &binding);
1498 let var = namespace.intern(&binding, value);
1499 var.set_origin(definition_origin());
1500 if binding == name {
1501 var.set_hara_metadata(Some(metadata.clone()));
1502 refresh_schema_contract(&var)?;
1503 }
1504 environment.insert(binding.clone(), Value::Var(var.clone()));
1505 environment.insert(
1506 format!("{}/{}", namespace_name, binding),
1507 Value::Var(var),
1508 );
1509 }
1510 Ok(Value::Nil)
1511 })
1512}
1513
1514pub(crate) fn publish_guest_protocol(
1517 name: &str,
1518 methods: HashMap<String, usize>,
1519 parents: Vec<String>,
1520 environment: &mut HashMap<String, Value>,
1521) -> Result<Value, String> {
1522 if name.contains('/') || name.is_empty() {
1523 return Err("defprotocol name must be an unqualified symbol".into());
1524 }
1525 if methods.keys().any(|method| method.contains('/')) {
1526 return Err("protocol method names must be unqualified symbols".into());
1527 }
1528 if methods
1529 .iter()
1530 .any(|(method, arity)| method.is_empty() || *arity == 0)
1531 {
1532 return Err("protocol methods must have a receiver and a non-empty name".into());
1533 }
1534 if parents.iter().any(|parent| parent.is_empty()) {
1535 return Err("protocol parent names must not be empty".into());
1536 }
1537 with_declaration_transaction(environment, |environment| {
1538 let registry = namespace_registry()?;
1539 let namespace = registry.current();
1540 let namespace_name = namespace.name().as_str().to_owned();
1541 let protocol_name = format!("{}.{}", namespace_name, name);
1542 ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1543 let registry = active.borrow();
1544 let registry = registry
1545 .as_ref()
1546 .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1547 if parents.iter().any(|parent| {
1548 parent == &protocol_name || registry.guest_protocol_reaches(parent, &protocol_name)
1549 }) {
1550 return Err(format!("protocol inheritance cycle: {protocol_name}"));
1551 }
1552 Ok(())
1553 })?;
1554 let previous_protocol = namespace
1555 .resolve(&Symbol::parse(name))
1556 .filter(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1557 .and_then(|var| match var.deref_value() {
1558 Value::Protocol(protocol) if protocol.name == protocol_name => Some(protocol),
1559 _ => None,
1560 });
1561
1562 for method in methods.keys() {
1563 for (local, var) in namespace.mappings() {
1564 if local.as_str() == name
1565 || var.symbol().get_namespace() != Some(namespace_name.as_str())
1566 {
1567 continue;
1568 }
1569 if let Value::Protocol(other) = var.deref_value() {
1570 if other.methods.contains_key(method) {
1571 return Err(format!(
1572 "Protocol method Var already belongs to {}: {}/{}",
1573 local.as_str(),
1574 namespace_name,
1575 method
1576 ));
1577 }
1578 }
1579 }
1580 let existing = namespace.resolve(&Symbol::parse(method));
1581 let same_protocol_reload = previous_protocol
1582 .as_ref()
1583 .is_some_and(|previous| previous.methods.contains_key(method));
1584 if existing
1585 .as_ref()
1586 .is_some_and(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1587 && !same_protocol_reload
1588 {
1589 return Err(format!(
1590 "Protocol method Var already exists: {}/{}",
1591 namespace_name,
1592 method
1593 ));
1594 }
1595 }
1596
1597 if let Some(previous) = &previous_protocol {
1598 for old_method in previous.methods.keys() {
1599 if !methods.contains_key(old_method) {
1600 let old = Symbol::parse(old_method);
1601 if namespace.resolve(&old).is_some_and(|var| {
1602 var.symbol().get_namespace() == Some(namespace_name.as_str())
1603 }) {
1604 namespace.unmap(&old);
1605 }
1606 environment.remove(old_method);
1607 environment.remove(&format!("{}/{}", namespace_name, old_method));
1608 }
1609 }
1610 }
1611
1612 for method in methods.keys() {
1613 prepare_named_binding(&namespace, method);
1614 }
1615 prepare_named_binding(&namespace, name);
1616
1617 let protocol = Rc::new(GuestProtocol {
1618 name: protocol_name.clone(),
1619 methods,
1620 parents,
1621 });
1622 let protocol_value = Value::Protocol(protocol.clone());
1623 ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1624 let registry = active.borrow();
1625 let registry = registry
1626 .as_ref()
1627 .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1628 registry.replace_guest_protocol(protocol_name.clone());
1629 registry.register_guest_protocol(protocol.clone());
1630 for method in protocol.methods.keys() {
1631 registry.declare_guest(protocol_name.clone(), method.clone());
1632 }
1633 Ok(())
1634 })?;
1635
1636 let protocol_var = namespace.intern(name, protocol_value.clone());
1637 protocol_var.set_origin(definition_origin());
1638 environment.insert(name.to_owned(), Value::Var(protocol_var.clone()));
1639 environment.insert(
1640 format!("{}/{}", namespace_name, name),
1641 Value::Var(protocol_var),
1642 );
1643 for method in protocol.methods.keys() {
1644 let protocol_name = protocol_name.clone();
1645 let method_name = method.clone();
1646 let display_name = format!("{}/{}", namespace_name, method);
1647 let method_value = native_variadic_function(&display_name, move |arguments| {
1648 protocol_call(&protocol_name, &method_name, &arguments)
1649 });
1650 let method_var = namespace.intern(method, method_value);
1651 method_var.set_origin(definition_origin());
1652 environment.insert(method.clone(), Value::Var(method_var.clone()));
1653 environment.insert(
1654 format!("{}/{}", namespace_name, method),
1655 Value::Var(method_var),
1656 );
1657 }
1658 Ok(protocol_value)
1659 })
1660}
1661
1662pub(crate) fn mutable_field_value(value: &Value, field: &str) -> Result<Value, String> {
1665 let Value::Mutable(value) = value else {
1666 return Err("field expects a mutable value".into());
1667 };
1668 value
1669 .get(field)
1670 .ok_or_else(|| format!("unknown mutable field: {field}"))
1671}
1672
1673pub(crate) fn mutable_field_set(
1675 value: &Value,
1676 field: &str,
1677 replacement: Value,
1678) -> Result<Value, String> {
1679 let Value::Mutable(value) = value else {
1680 return Err("field expects a mutable value".into());
1681 };
1682 value.set(field, replacement)
1683}
1684
1685pub(crate) fn named_instance_of(type_value: &Value, value: &Value) -> Result<Value, String> {
1687 let matches = match type_value {
1688 Value::StructType(ty) => {
1689 matches!(value, Value::Struct(value) if Rc::ptr_eq(ty, &value.ty))
1690 }
1691 Value::MutableType(ty) => {
1692 matches!(value, Value::Mutable(value) if Rc::ptr_eq(ty, &value.ty))
1693 }
1694 Value::NativeType(native) => native_type_instance(native, value)?,
1695 _ => return Err("instance? expects a struct or mutable type".into()),
1696 };
1697 Ok(Value::Bool(matches))
1698}
1699
1700pub(crate) fn namespace_registry() -> Result<NamespaceRegistry<Value>, String> {
1701 ACTIVE_NAMESPACES
1702 .with(|active| active.borrow().clone())
1703 .ok_or_else(|| "namespace runtime is unavailable".into())
1704}
1705
1706pub(crate) fn current_namespace_environment() -> Result<HashMap<String, Value>, String> {
1709 let registry = namespace_registry()?;
1710 let mut environment = registry
1711 .current()
1712 .mappings()
1713 .into_iter()
1714 .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1715 .collect();
1716 refresh_namespace_environment(®istry, &mut environment);
1717 Ok(environment)
1718}
1719
1720pub fn save_namespace_environment(
1722 registry: &NamespaceRegistry<Value>,
1723 env: &mut HashMap<String, Value>,
1724) {
1725 let namespace = registry.current();
1726 let namespace_name = namespace.name().as_str().to_owned();
1727 let locals = env
1728 .iter()
1729 .filter(|(name, _)| !name.contains('/'))
1730 .map(|(name, value)| (name.clone(), value.clone()))
1731 .collect::<Vec<_>>();
1732 for (name, value) in locals {
1733 let path = format!("{namespace_name}/{name}");
1734 if matches!(&value, Value::Var(var) if
1735 (var.symbol().get_namespace().is_some()
1736 && var.symbol().get_namespace() != Some(namespace_name.as_str()))
1737 || var.symbol().as_str().starts_with("std.native.")
1738 || var.symbol().as_str().starts_with("std.protocol.")
1739 )
1740 {
1741 continue;
1742 }
1743 let var = match value {
1744 Value::Var(var) if var.symbol().as_str() == path => var,
1745 Value::Var(var) => var.requalify(&path),
1746 value => namespace.intern(&name, value),
1747 };
1748 namespace.map_var(crate::lang::data::Symbol::parse(&name), var.clone());
1749 env.insert(name, Value::Var(var));
1750 }
1751}
1752
1753pub fn refresh_namespace_environment(
1755 registry: &NamespaceRegistry<Value>,
1756 env: &mut HashMap<String, Value>,
1757) {
1758 env.retain(|name, _| !name.contains('/'));
1759 for namespace in registry.all() {
1760 for (_, var) in namespace.mappings() {
1761 env.insert(var.symbol().as_str().to_owned(), Value::Var(var));
1762 }
1763 }
1764 for (alias, namespace) in registry.current().aliases() {
1765 for (local, var) in namespace.mappings() {
1766 env.insert(
1767 format!("{}/{}", alias.as_str(), local.as_str()),
1768 Value::Var(var),
1769 );
1770 }
1771 }
1772}
1773
1774pub fn select_namespace_environment(
1776 registry: &NamespaceRegistry<Value>,
1777 env: &mut HashMap<String, Value>,
1778 name: &str,
1779) {
1780 save_namespace_environment(registry, env);
1781 let namespace = registry.set_current(name);
1782 *env = namespace
1783 .mappings()
1784 .into_iter()
1785 .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1786 .collect();
1787 refresh_namespace_environment(registry, env);
1788}
1789
1790pub fn apply_global_aliases(registry: &NamespaceRegistry<Value>, namespace: &str) {
1791 let target = registry.find_or_create(namespace);
1792 for (alias, library) in registry.global_aliases() {
1793 if target.name() == &library {
1794 continue;
1795 }
1796 if let Some(source) = registry.find(library.as_str()) {
1797 target.alias(alias.as_str(), source);
1798 } else {
1799 target.lazy_alias(alias.as_str(), library.as_str());
1800 }
1801 }
1802}
1803
1804pub fn apply_global_imports(registry: &NamespaceRegistry<Value>, namespace: &str) {
1805 let target = registry.find_or_create(namespace);
1806 for (local, canonical) in registry.global_imports() {
1807 if target.resolve(&local).is_none() {
1808 if let Some(var) = registry.resolve(&canonical) {
1809 target.map_var(local, var);
1810 }
1811 }
1812 }
1813}
1814
1815pub fn with_protocols<R>(registry: &ProtocolRegistry, operation: impl FnOnce() -> R) -> R {
1817 ACTIVE_PROTOCOLS.with(|active| {
1818 let previous = active.replace(Some(registry.clone()));
1819 let result = operation();
1820 active.replace(previous);
1821 result
1822 })
1823}
1824
1825pub fn with_package_catalog<R>(catalog: &PackageCatalog, operation: impl FnOnce() -> R) -> R {
1826 ACTIVE_PACKAGE_CATALOG.with(|active| {
1827 let previous = active.replace(Some(catalog.clone()));
1828 let result = operation();
1829 active.replace(previous);
1830 result
1831 })
1832}
1833
1834fn package_catalog() -> PackageCatalog {
1835 ACTIVE_PACKAGE_CATALOG.with(|active| active.borrow().clone().unwrap_or_default())
1836}
1837
1838pub fn with_promise_provider<R>(
1840 provider: Rc<dyn PromiseProvider>,
1841 operation: impl FnOnce() -> R,
1842) -> R {
1843 ACTIVE_PROMISE_PROVIDER.with(|active| {
1844 let previous = active.replace(Some(provider));
1845 let result = operation();
1846 active.replace(previous);
1847 result
1848 })
1849}
1850
1851fn promise_provider() -> Rc<dyn PromiseProvider> {
1852 ACTIVE_PROMISE_PROVIDER.with(|active| {
1853 active
1854 .borrow()
1855 .clone()
1856 .unwrap_or_else(|| Rc::new(LocalPromiseProvider))
1857 })
1858}
1859pub fn with_capability_providers<R>(
1861 file: Option<Rc<dyn FileProvider>>,
1862 socket: Option<Rc<dyn SocketProvider>>,
1863 process: bool,
1864 kernel: Option<Rc<KernelProvider>>,
1865 operation: impl FnOnce() -> R,
1866) -> R {
1867 ACTIVE_FILE_PROVIDER.with(|active_file| {
1868 ACTIVE_SOCKET_PROVIDER.with(|active_socket| {
1869 ACTIVE_KERNEL_PROVIDER.with(|active_kernel| {
1870 ACTIVE_PROCESS_ALLOWED.with(|active_process| {
1871 let previous_file = active_file.replace(file);
1872 let previous_socket = active_socket.replace(socket);
1873 let previous_kernel = active_kernel.replace(kernel);
1874 let previous_process = active_process.replace(process);
1875 let result = operation();
1876 active_file.replace(previous_file);
1877 active_socket.replace(previous_socket);
1878 active_kernel.replace(previous_kernel);
1879 active_process.set(previous_process);
1880 result
1881 })
1882 })
1883 })
1884 })
1885}
1886
1887pub type KernelProvider = dyn Fn(String, Vec<Value>) -> Result<Value, String>;
1888
1889fn kernel_provider(operation: &str) -> Result<Rc<KernelProvider>, String> {
1890 ACTIVE_KERNEL_PROVIDER.with(|active| {
1891 active
1892 .borrow()
1893 .clone()
1894 .ok_or_else(|| format!("std.native.Kernel/{operation} requires a kernel provider"))
1895 })
1896}
1897
1898fn file_provider(operation: &str) -> Result<Rc<dyn FileProvider>, String> {
1899 ACTIVE_FILE_PROVIDER.with(|active| {
1900 active
1901 .borrow()
1902 .clone()
1903 .ok_or_else(|| format!("{operation} is unsupported or file access is denied"))
1904 })
1905}
1906
1907fn socket_provider(operation: &str) -> Result<Rc<dyn SocketProvider>, String> {
1908 ACTIVE_SOCKET_PROVIDER.with(|active| {
1909 active
1910 .borrow()
1911 .clone()
1912 .ok_or_else(|| format!("{operation} is unsupported or network access is denied"))
1913 })
1914}
1915
1916pub(crate) fn native_capability_granted(capability: &str) -> bool {
1917 match capability {
1918 "kernel" | "sandbox" => ACTIVE_KERNEL_PROVIDER.with(|active| active.borrow().is_some()),
1919 "file" => ACTIVE_FILE_PROVIDER.with(|active| active.borrow().is_some()),
1920 "network" => ACTIVE_SOCKET_PROVIDER.with(|active| active.borrow().is_some()),
1921 "native-runtime" => ACTIVE_PROCESS_ALLOWED.get(),
1922 "host-call" => HOST_CALL_HANDLER.with(|active| active.borrow().is_some()),
1923 _ => false,
1924 }
1925}
1926
1927pub(crate) fn native_capability_error_value(
1928 native_type: &str,
1929 method: &str,
1930 capability: &str,
1931) -> Value {
1932 Value::ExceptionInfo(Rc::new(ExceptionInfo {
1933 message: format!(
1934 "std.native.{native_type}/{method} requires capability :{capability}"
1935 ),
1936 data: Box::new(Value::Map(
1937 [
1938 (
1939 Value::Keyword("ex/code".into()),
1940 Value::Keyword("native/capability-denied".into()),
1941 ),
1942 (
1943 Value::Keyword("ex/class".into()),
1944 Value::Keyword("ex.class/host".into()),
1945 ),
1946 (
1947 Value::Keyword("native/type".into()),
1948 Value::String(format!("std.native.{native_type}")),
1949 ),
1950 (
1951 Value::Keyword("native/method".into()),
1952 Value::String(method.into()),
1953 ),
1954 (
1955 Value::Keyword("native/capability".into()),
1956 Value::Keyword(capability.into()),
1957 ),
1958 ]
1959 .into_iter()
1960 .collect(),
1961 )),
1962 cause: None,
1963 provenance: Rc::new(RefCell::new(Default::default())),
1964 }))
1965}
1966
1967pub(crate) fn native_capability_denied(
1968 native_type: &str,
1969 method: &str,
1970 capability: &str,
1971) -> String {
1972 thrown_error(native_capability_error_value(native_type, method, capability))
1973}
1974
1975pub(crate) fn native_capability_denied_promise(
1976 native_type: &str,
1977 method: &str,
1978 capability: &str,
1979) -> Value {
1980 let promise = Promise::new();
1981 promise.reject_value(native_capability_error_value(native_type, method, capability));
1982 Value::Promise(promise)
1983}
1984
1985pub(crate) fn require_native_capability(
1986 native_type: &str,
1987 method: &str,
1988 capability: &str,
1989) -> Result<(), String> {
1990 native_capability_granted(capability)
1991 .then_some(())
1992 .ok_or_else(|| native_capability_denied(native_type, method, capability))
1993}
1994
1995fn require_process_access(operation: &str) -> Result<(), String> {
1996 ACTIVE_PROCESS_ALLOWED.with(|allowed| {
1997 allowed
1998 .get()
1999 .then_some(())
2000 .ok_or_else(|| {
2001 let method = operation
2002 .strip_prefix("std.native.Process/")
2003 .unwrap_or(operation);
2004 native_capability_denied("Process", method, "native-runtime")
2005 })
2006 })
2007}