Skip to main content

hara_native/core/
environment.rs

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    /// Registers a protocol implementation for one opaque extension type.
156    ///
157    /// Extension methods are kept separate from the ordinary protocol fallback
158    /// chain so collection primitives can dispatch without recursively entering
159    /// their own built-in protocol implementation.
160    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    /// Marks an opaque extension type as a logical collection category such as
182    /// `map`. Predicates can then preserve the guest-language collection model.
183    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(&current) {
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    /// Returns the built-in collection protocol registry used by evaluator dispatch.
498    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    /// The namespace in which the frame was compiled. Namespace registries
835    /// share their mutable current pointer, so a suspended child must restore
836    /// this selection explicitly when it resumes instead of inheriting a
837    /// caller which happened to run in the meantime.
838    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    /// A native host source whose contents are read only when the namespace
1051    /// crosses the require boundary.
1052    #[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    record_trace_failure();
1084    let error = format!("thrown: {}", value.display());
1085    ACTIVE_THROWN_VALUE.with(|active| {
1086        *active.borrow_mut() = Some((error.clone(), value));
1087    });
1088    error
1089}
1090
1091/// Captures the uncaught exception value from one evaluator boundary without
1092/// changing the string error API used by the runtime.  The previous dynamic
1093/// value is restored so a diagnostic request cannot leak exception state into
1094/// a later evaluation in the same broker session.
1095pub fn with_thrown_value_capture<R>(operation: impl FnOnce() -> R) -> (R, Option<Value>) {
1096    ACTIVE_THROWN_VALUE.with(|active| {
1097        let previous = active.replace(None);
1098        let result = operation();
1099        let captured = active.take().map(|(_, value)| value);
1100        active.replace(previous);
1101        (result, captured)
1102    })
1103}
1104
1105pub(crate) fn promise_rejection_error(error: PromiseRejection) -> String {
1106    match error {
1107        PromiseRejection::Message(message) => message,
1108        PromiseRejection::Value(value) | PromiseRejection::Cancelled(value) => thrown_error(value),
1109    }
1110}
1111
1112pub(crate) fn caught_error(error: &str) -> Value {
1113    ACTIVE_THROWN_VALUE.with(|active| {
1114        let mut active = active.borrow_mut();
1115        if active
1116            .as_ref()
1117            .is_some_and(|(thrown_error, _)| error.starts_with(thrown_error))
1118        {
1119            return active.take().unwrap().1;
1120        }
1121        Value::String(error.to_owned())
1122    })
1123}
1124
1125pub(crate) fn catch_matches(error: &str, class: &str) -> bool {
1126    if class == "Exception" || class == "Throwable" {
1127        return true;
1128    }
1129    if let Some(selectors) = class
1130        .strip_prefix('[')
1131        .and_then(|value| value.strip_suffix(']'))
1132    {
1133        return selectors
1134            .split(',')
1135            .any(|selector| catch_matches(error, selector));
1136    }
1137    if let Some(selector) = class.strip_prefix(':') {
1138        return ACTIVE_THROWN_VALUE.with(|active| {
1139            active.borrow().as_ref().is_some_and(|(message, value)| {
1140                error.starts_with(message)
1141                    && matches!(value, Value::ExceptionInfo(info)
1142                        if map_entries(&info.data).is_some_and(|entries| entries.iter().any(|(key, value)| {
1143                            matches!(key, Value::Keyword(name) if name.as_str() == "ex/code")
1144                                && matches!(value, Value::Keyword(code) if code.as_str() == selector)
1145                        })))
1146            })
1147        });
1148    }
1149    ACTIVE_THROWN_VALUE.with(|active| {
1150        active.borrow().as_ref().is_some_and(|(message, value)| {
1151            error.starts_with(message)
1152                && match value {
1153                    Value::Struct(value) => {
1154                        value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1155                    }
1156                    Value::Mutable(value) => {
1157                        value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1158                    }
1159                    _ => false,
1160                }
1161        })
1162    })
1163}
1164
1165/// Runs an evaluation with a namespace registry available to namespace builtins.
1166pub fn with_namespace_registry<R>(
1167    registry: &NamespaceRegistry<Value>,
1168    operation: impl FnOnce() -> R,
1169) -> R {
1170    ACTIVE_NAMESPACES.with(|active| {
1171        let previous = active.replace(Some(registry.clone()));
1172        let result = operation();
1173        active.replace(previous);
1174        result
1175    })
1176}
1177
1178pub fn with_definition_origin<R>(origin: VarOrigin, operation: impl FnOnce() -> R) -> R {
1179    ACTIVE_DEFINITION_ORIGIN.with(|active| {
1180        let previous = active.replace(origin);
1181        let result = operation();
1182        active.set(previous);
1183        result
1184    })
1185}
1186
1187pub(crate) fn definition_origin() -> VarOrigin {
1188    ACTIVE_DEFINITION_ORIGIN.with(Cell::get)
1189}
1190
1191pub(crate) fn binding_is_local(var: &KernelVar<Value>) -> bool {
1192    namespace_registry()
1193        .map(|registry| {
1194            var.symbol().get_namespace().is_none()
1195                || var.symbol().get_namespace() == Some(registry.current().name().as_str())
1196        })
1197        .unwrap_or(true)
1198}
1199
1200/// Names a fresh local var cell: qualified to the current namespace when
1201/// a registry is active, bare otherwise. Qualifying matters: an
1202/// unqualified cell fails `binding_is_local`, so redefining the name in
1203/// the same eval used to shadow with a fresh cell instead of resetting
1204/// the existing one — the answer then depended on whether the name had
1205/// survived a previous eval's namespace save-back (which qualifies
1206/// cells). The JVM runtime always resets the same cell; qualifying at
1207/// creation makes the tree evaluator agree on both first and later
1208/// evals (issue #223).
1209pub(crate) fn local_var_name(name: &str) -> String {
1210    match namespace_registry() {
1211        Ok(registry) => format!("{}/{}", registry.current().name().as_str(), name),
1212        Err(_) => name.to_string(),
1213    }
1214}
1215
1216fn prepare_owned_definition(env: &mut HashMap<String, Value>, name: &str) -> Result<(), String> {
1217    if let Some(Value::Var(var)) = env.get(name) {
1218        if !binding_is_local(var) {
1219            if let Ok(registry) = namespace_registry() {
1220                registry.current().unmap(&Symbol::parse(name));
1221            }
1222            env.remove(name);
1223        }
1224    }
1225    Ok(())
1226}
1227
1228/// Defines or updates a global var in the current namespace, mirroring
1229/// the evaluator's `def` arm (`core.rs` special forms) without the flat
1230/// env bridge: an existing var local to the current namespace is reused
1231/// (identity preserved), a referred or missing name gets a fresh cell.
1232/// Used by the bytecode VM's `DefGlobal` (issue #223).
1233pub(crate) fn vm_def_global(
1234    name: &str,
1235    value: Value,
1236    metadata: Option<Rc<Metadata>>,
1237) -> Result<KernelVar<Value>, String> {
1238    let registry = namespace_registry()?;
1239    let current = registry.current();
1240    let local = Symbol::create(None, name);
1241    if let Some(existing) = current.resolve(&local) {
1242        if binding_is_local(&existing) {
1243            existing.reset_value(value);
1244            if metadata.is_some() {
1245                existing.set_hara_metadata(metadata);
1246            }
1247            existing.set_origin(definition_origin());
1248            refresh_schema_contract(&existing)?;
1249            return Ok(existing);
1250        }
1251        current.unmap(&local);
1252    }
1253    let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), value);
1254    var.set_hara_metadata(metadata);
1255    var.set_origin(definition_origin());
1256    current.map_var(local, var.clone());
1257    refresh_schema_contract(&var)?;
1258    Ok(var)
1259}
1260
1261pub(crate) fn vm_def_macro(
1262    name: &str,
1263    value: Value,
1264    metadata: Option<Rc<Metadata>>,
1265) -> Result<KernelVar<Value>, String> {
1266    let Value::Function(function) = &value else {
1267        return Err("defmacro expects a function value".into());
1268    };
1269    let function = function.clone();
1270    let namespace = namespace_registry()?.current().name().as_str().to_owned();
1271    let var = vm_def_global(name, value, metadata)?;
1272    register_macro(&namespace, name, function)?;
1273    Ok(var)
1274}
1275
1276/// Declares a global var without assigning it, mirroring the evaluator's
1277/// `declare` arm: an existing local var is kept (value untouched), a
1278/// missing name gets a fresh nil cell. Used by the VM (issue #223).
1279pub(crate) fn vm_declare_global(name: &str) -> Result<KernelVar<Value>, String> {
1280    let registry = namespace_registry()?;
1281    let current = registry.current();
1282    let local = Symbol::create(None, name);
1283    if let Some(existing) = current.resolve(&local) {
1284        if binding_is_local(&existing) {
1285            existing.set_origin(definition_origin());
1286            return Ok(existing);
1287        }
1288        // An explicit `declare` is the source-level ownership boundary.  It
1289        // authorizes the following definition to replace a referred Var in
1290        // this namespace; a direct definition still goes through the
1291        // compiler's ownership check and remains protected.
1292        current.unmap(&local);
1293    }
1294    let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), Value::Nil);
1295    var.set_origin(definition_origin());
1296    current.map_var(local, var.clone());
1297    Ok(var)
1298}
1299
1300/// Resolves a global var by (possibly qualified) name through the
1301/// registry: current-namespace mappings, aliases, and qualified names.
1302pub(crate) fn vm_resolve_global(name: &str) -> Result<KernelVar<Value>, String> {
1303    let registry = namespace_registry()?;
1304    if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1305        return Ok(var);
1306    }
1307    if let Some((namespace, _)) = name.rsplit_once('/') {
1308        if NAMESPACE_SOURCE_PROVIDER.with(|active| {
1309            active
1310                .borrow()
1311                .as_ref()
1312                .is_some_and(|provider| provider(namespace).is_some())
1313        }) {
1314            require_namespace(&registry, &mut HashMap::new(), namespace)?;
1315            if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1316                return Ok(var);
1317            }
1318        }
1319    }
1320    Err(format!("unbound symbol: {name}"))
1321}
1322
1323/// Resolves a bare namespace symbol as the evaluator does. Namespace aliases
1324/// are values (and therefore callable through their `run` Var), but they are
1325/// not Vars themselves and cannot be represented by `vm_resolve_global`.
1326/// Lazy aliases are materialized at execution time so compiled programs keep
1327/// the same load boundary as interpreted forms.
1328pub(crate) fn vm_resolve_namespace_value(name: &str) -> Result<Value, String> {
1329    let registry = namespace_registry()?;
1330    if let Some(namespace) = registry
1331        .current()
1332        .aliases()
1333        .into_iter()
1334        .find_map(|(alias, namespace)| (alias.as_str() == name).then_some(namespace))
1335    {
1336        return Ok(Value::Namespace(Rc::new(namespace)));
1337    }
1338    if let Some(target) = registry.current().lazy_target(name) {
1339        require_namespace(&registry, &mut HashMap::new(), target.as_str())?;
1340        let namespace = registry
1341            .find(target.as_str())
1342            .ok_or_else(|| format!("Cannot require missing namespace: {target}"))?;
1343        registry.current().alias(name, namespace.clone());
1344        return Ok(Value::Namespace(Rc::new(namespace)));
1345    }
1346    registry
1347        .find(name)
1348        .map(|namespace| Value::Namespace(Rc::new(namespace)))
1349        .ok_or_else(|| format!("unbound symbol: {name}"))
1350}
1351
1352fn validate_named_definition(kind: &str, name: &str, fields: &[NamedField]) -> Result<(), String> {
1353    if name.contains('/') {
1354        return Err(format!("{kind} name must be an unqualified symbol"));
1355    }
1356    if fields
1357        .iter()
1358        .any(|field| field.name.is_empty() || field.name.contains('/'))
1359    {
1360        return Err(format!("{kind} field names must be unqualified symbols"));
1361    }
1362    if fields
1363        .iter()
1364        .map(|field| &field.name)
1365        .collect::<HashSet<_>>()
1366        .len()
1367        != fields.len()
1368    {
1369        return Err(format!("Duplicate {kind} field"));
1370    }
1371    Ok(())
1372}
1373
1374/// Runs a source declaration as one registry operation.
1375///
1376/// Declarations touch the namespace registry, the active protocol dispatch
1377/// registry, and the flat evaluator environment. Restore all three views when
1378/// validation or a later inline extension fails.
1379pub(crate) fn with_declaration_transaction<R>(
1380    environment: &mut HashMap<String, Value>,
1381    operation: impl FnOnce(&mut HashMap<String, Value>) -> Result<R, String>,
1382) -> Result<R, String> {
1383    let registry = namespace_registry()?;
1384    let registry_snapshot = registry.snapshot();
1385    let environment_snapshot = environment.clone();
1386    let protocol_snapshot = ACTIVE_PROTOCOLS.with(|active| {
1387        active
1388            .borrow()
1389            .as_ref()
1390            .map(ProtocolRegistry::snapshot)
1391    });
1392    let multimethod_snapshot = snapshot_multimethods();
1393
1394    let result = operation(environment);
1395    if result.is_err() {
1396        registry.restore(registry_snapshot);
1397        *environment = environment_snapshot;
1398        if let Some(snapshot) = protocol_snapshot {
1399            ACTIVE_PROTOCOLS.with(|active| {
1400                if let Some(registry) = active.borrow().as_ref() {
1401                    registry.restore(snapshot);
1402                }
1403            });
1404        }
1405        restore_multimethods(multimethod_snapshot);
1406    }
1407    result
1408}
1409
1410fn prepare_named_binding(namespace: &crate::kernel::Namespace<Value>, name: &str) {
1411    let symbol = Symbol::parse(name);
1412    if let Some(existing) = namespace.resolve(&symbol) {
1413        if existing.symbol().get_namespace() != Some(namespace.name().as_str()) {
1414            namespace.unmap(&symbol);
1415        }
1416    }
1417}
1418
1419/// Publishes the type Var and its positional and map constructors for a
1420/// defstruct or defmutable declaration. `Base/struct` and `Base/mutable`
1421/// use this path after Foundation macro expansion.
1422pub(crate) fn publish_named_value(
1423    kind: &str,
1424    name: &str,
1425    fields: Vec<NamedField>,
1426    environment: &mut HashMap<String, Value>,
1427    metadata: Option<Rc<Metadata>>,
1428) -> Result<Value, String> {
1429    validate_named_definition(kind, name, &fields)?;
1430    let mutable = kind == "defmutable";
1431    let schema_form = named_value_schema_form(
1432        &format!("{}/{}", namespace_registry()?.current().name().as_str(), name),
1433        mutable,
1434        &fields,
1435    );
1436    let metadata = assoc_metadata(metadata, "schema", metadata_value(&schema_form)?)
1437        .ok_or_else(|| "named value schema metadata could not be created".to_string())?;
1438    let field_names = fields
1439        .iter()
1440        .map(|field| field.name.clone())
1441        .collect::<Vec<_>>();
1442    with_declaration_transaction(environment, |environment| {
1443        let registry = namespace_registry()?;
1444        let namespace = registry.current();
1445        let namespace_name = namespace.name().as_str().to_owned();
1446        let type_name = format!("{}/{}", namespace_name, name);
1447        let declaration = Rc::new(NamedDeclaration::new(
1448            type_name.clone(),
1449            mutable,
1450            fields.clone(),
1451            schema_form.clone(),
1452        ));
1453
1454        let (type_value, map_constructor) = if mutable {
1455            let ty = Rc::new(MutableType {
1456                name: type_name.clone(),
1457                fields: field_names.clone(),
1458                declaration: Some(declaration.clone()),
1459            });
1460            let map_type = ty.clone();
1461            let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1462                let source = values.first().expect("native arity is checked");
1463                let values = map_type
1464                    .fields
1465                    .iter()
1466                    .map(|field| {
1467                        map_value(source, &named_field_key(field))
1468                            .cloned()
1469                            .unwrap_or(Value::Nil)
1470                    })
1471                    .collect();
1472                Ok(Value::Mutable(Rc::new(MutableValue::from_values(
1473                    map_type.clone(),
1474                    values,
1475                    None,
1476                )?)))
1477            });
1478            (Value::MutableType(ty), constructor)
1479        } else {
1480            let ty = Rc::new(StructType {
1481                name: type_name.clone(),
1482                fields: field_names,
1483                declaration: Some(declaration),
1484            });
1485            let map_type = ty.clone();
1486            let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1487                let source = values.first().expect("native arity is checked");
1488                let values = map_type
1489                    .fields
1490                    .iter()
1491                    .map(|field| {
1492                        map_value(source, &named_field_key(field))
1493                            .cloned()
1494                            .unwrap_or(Value::Nil)
1495                    })
1496                    .collect();
1497                Ok(Value::Struct(Rc::new(StructValue::from_values(
1498                    map_type.clone(),
1499                    values,
1500                    None,
1501                )?)))
1502            });
1503            (Value::StructType(ty), constructor)
1504        };
1505
1506        let bindings = [
1507            (name.to_owned(), type_value.clone()),
1508            (format!("->{}", name), type_value),
1509            (format!("map->{}", name), map_constructor),
1510        ];
1511        for (binding, value) in bindings {
1512            prepare_named_binding(&namespace, &binding);
1513            let var = namespace.intern(&binding, value);
1514            var.set_origin(definition_origin());
1515            if binding == name {
1516                var.set_hara_metadata(Some(metadata.clone()));
1517                refresh_schema_contract(&var)?;
1518            }
1519            environment.insert(binding.clone(), Value::Var(var.clone()));
1520            environment.insert(
1521                format!("{}/{}", namespace_name, binding),
1522                Value::Var(var),
1523            );
1524        }
1525        Ok(Value::Nil)
1526    })
1527}
1528
1529/// Publishes a guest protocol and all of its method Vars through one
1530/// namespace/dispatch transaction.
1531pub(crate) fn publish_guest_protocol(
1532    name: &str,
1533    methods: HashMap<String, usize>,
1534    parents: Vec<String>,
1535    environment: &mut HashMap<String, Value>,
1536) -> Result<Value, String> {
1537    if name.contains('/') || name.is_empty() {
1538        return Err("defprotocol name must be an unqualified symbol".into());
1539    }
1540    if methods.keys().any(|method| method.contains('/')) {
1541        return Err("protocol method names must be unqualified symbols".into());
1542    }
1543    if methods
1544        .iter()
1545        .any(|(method, arity)| method.is_empty() || *arity == 0)
1546    {
1547        return Err("protocol methods must have a receiver and a non-empty name".into());
1548    }
1549    if parents.iter().any(|parent| parent.is_empty()) {
1550        return Err("protocol parent names must not be empty".into());
1551    }
1552    with_declaration_transaction(environment, |environment| {
1553        let registry = namespace_registry()?;
1554        let namespace = registry.current();
1555        let namespace_name = namespace.name().as_str().to_owned();
1556        let protocol_name = format!("{}.{}", namespace_name, name);
1557        ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1558            let registry = active.borrow();
1559            let registry = registry
1560                .as_ref()
1561                .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1562            if parents.iter().any(|parent| {
1563                parent == &protocol_name || registry.guest_protocol_reaches(parent, &protocol_name)
1564            }) {
1565                return Err(format!("protocol inheritance cycle: {protocol_name}"));
1566            }
1567            Ok(())
1568        })?;
1569        let previous_protocol = namespace
1570            .resolve(&Symbol::parse(name))
1571            .filter(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1572            .and_then(|var| match var.deref_value() {
1573                Value::Protocol(protocol) if protocol.name == protocol_name => Some(protocol),
1574                _ => None,
1575            });
1576
1577        for method in methods.keys() {
1578            for (local, var) in namespace.mappings() {
1579                if local.as_str() == name
1580                    || var.symbol().get_namespace() != Some(namespace_name.as_str())
1581                {
1582                    continue;
1583                }
1584                if let Value::Protocol(other) = var.deref_value() {
1585                    if other.methods.contains_key(method) {
1586                        return Err(format!(
1587                            "Protocol method Var already belongs to {}: {}/{}",
1588                            local.as_str(),
1589                            namespace_name,
1590                            method
1591                        ));
1592                    }
1593                }
1594            }
1595            let existing = namespace.resolve(&Symbol::parse(method));
1596            let same_protocol_reload = previous_protocol
1597                .as_ref()
1598                .is_some_and(|previous| previous.methods.contains_key(method));
1599            if existing
1600                .as_ref()
1601                .is_some_and(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1602                && !same_protocol_reload
1603            {
1604                return Err(format!(
1605                    "Protocol method Var already exists: {}/{}",
1606                    namespace_name,
1607                    method
1608                ));
1609            }
1610        }
1611
1612        if let Some(previous) = &previous_protocol {
1613            for old_method in previous.methods.keys() {
1614                if !methods.contains_key(old_method) {
1615                    let old = Symbol::parse(old_method);
1616                    if namespace.resolve(&old).is_some_and(|var| {
1617                        var.symbol().get_namespace() == Some(namespace_name.as_str())
1618                    }) {
1619                        namespace.unmap(&old);
1620                    }
1621                    environment.remove(old_method);
1622                    environment.remove(&format!("{}/{}", namespace_name, old_method));
1623                }
1624            }
1625        }
1626
1627        for method in methods.keys() {
1628            prepare_named_binding(&namespace, method);
1629        }
1630        prepare_named_binding(&namespace, name);
1631
1632        let protocol = Rc::new(GuestProtocol {
1633            name: protocol_name.clone(),
1634            methods,
1635            parents,
1636        });
1637        let protocol_value = Value::Protocol(protocol.clone());
1638        ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1639            let registry = active.borrow();
1640            let registry = registry
1641                .as_ref()
1642                .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1643            registry.replace_guest_protocol(protocol_name.clone());
1644            registry.register_guest_protocol(protocol.clone());
1645            for method in protocol.methods.keys() {
1646                registry.declare_guest(protocol_name.clone(), method.clone());
1647            }
1648            Ok(())
1649        })?;
1650
1651        let protocol_var = namespace.intern(name, protocol_value.clone());
1652        protocol_var.set_origin(definition_origin());
1653        environment.insert(name.to_owned(), Value::Var(protocol_var.clone()));
1654        environment.insert(
1655            format!("{}/{}", namespace_name, name),
1656            Value::Var(protocol_var),
1657        );
1658        for method in protocol.methods.keys() {
1659            let protocol_name = protocol_name.clone();
1660            let method_name = method.clone();
1661            let display_name = format!("{}/{}", namespace_name, method);
1662            let method_value = native_variadic_function(&display_name, move |arguments| {
1663                protocol_call(&protocol_name, &method_name, &arguments)
1664            });
1665            let method_var = namespace.intern(method, method_value);
1666            method_var.set_origin(definition_origin());
1667            environment.insert(method.clone(), Value::Var(method_var.clone()));
1668            environment.insert(
1669                format!("{}/{}", namespace_name, method),
1670                Value::Var(method_var),
1671            );
1672        }
1673        Ok(protocol_value)
1674    })
1675}
1676
1677/// Direct field access is reserved for mutable named values. Immutable
1678/// structs use ordinary associative lookup.
1679pub(crate) fn mutable_field_value(value: &Value, field: &str) -> Result<Value, String> {
1680    let Value::Mutable(value) = value else {
1681        return Err("field expects a mutable value".into());
1682    };
1683    value
1684        .get(field)
1685        .ok_or_else(|| format!("unknown mutable field: {field}"))
1686}
1687
1688/// Replaces one declared mutable field and returns the replacement value.
1689pub(crate) fn mutable_field_set(
1690    value: &Value,
1691    field: &str,
1692    replacement: Value,
1693) -> Result<Value, String> {
1694    let Value::Mutable(value) = value else {
1695        return Err("field expects a mutable value".into());
1696    };
1697    value.set(field, replacement)
1698}
1699
1700/// Named-value type identity check shared with the `instance?` special form.
1701pub(crate) fn named_instance_of(type_value: &Value, value: &Value) -> Result<Value, String> {
1702    let matches = match type_value {
1703        Value::StructType(ty) => {
1704            matches!(value, Value::Struct(value) if Rc::ptr_eq(ty, &value.ty))
1705        }
1706        Value::MutableType(ty) => {
1707            matches!(value, Value::Mutable(value) if Rc::ptr_eq(ty, &value.ty))
1708        }
1709        Value::NativeType(native) => native_type_instance(native, value)?,
1710        _ => return Err("instance? expects a struct or mutable type".into()),
1711    };
1712    Ok(Value::Bool(matches))
1713}
1714
1715pub(crate) fn namespace_registry() -> Result<NamespaceRegistry<Value>, String> {
1716    ACTIVE_NAMESPACES
1717        .with(|active| active.borrow().clone())
1718        .ok_or_else(|| "namespace runtime is unavailable".into())
1719}
1720
1721/// Returns a fresh evaluator environment for the registry's current
1722/// namespace, including its qualified and aliased bindings.
1723pub(crate) fn current_namespace_environment() -> Result<HashMap<String, Value>, String> {
1724    let registry = namespace_registry()?;
1725    let mut environment = registry
1726        .current()
1727        .mappings()
1728        .into_iter()
1729        .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1730        .collect();
1731    refresh_namespace_environment(&registry, &mut environment);
1732    Ok(environment)
1733}
1734
1735/// Saves all unqualified evaluator bindings into the registry current namespace.
1736pub fn save_namespace_environment(
1737    registry: &NamespaceRegistry<Value>,
1738    env: &mut HashMap<String, Value>,
1739) {
1740    let namespace = registry.current();
1741    let namespace_name = namespace.name().as_str().to_owned();
1742    let locals = env
1743        .iter()
1744        .filter(|(name, _)| !name.contains('/'))
1745        .map(|(name, value)| (name.clone(), value.clone()))
1746        .collect::<Vec<_>>();
1747    for (name, value) in locals {
1748        let path = format!("{namespace_name}/{name}");
1749        if matches!(&value, Value::Var(var) if
1750            (var.symbol().get_namespace().is_some()
1751                && var.symbol().get_namespace() != Some(namespace_name.as_str()))
1752                || var.symbol().as_str().starts_with("std.native.")
1753                || var.symbol().as_str().starts_with("std.protocol.")
1754        )
1755        {
1756            continue;
1757        }
1758        let var = match value {
1759            Value::Var(var) if var.symbol().as_str() == path => var,
1760            Value::Var(var) => var.requalify(&path),
1761            value => namespace.intern(&name, value),
1762        };
1763        namespace.map_var(crate::lang::data::Symbol::parse(&name), var.clone());
1764        env.insert(name, Value::Var(var));
1765    }
1766}
1767
1768/// Rebuilds qualified and aliased bindings without changing local bindings.
1769pub fn refresh_namespace_environment(
1770    registry: &NamespaceRegistry<Value>,
1771    env: &mut HashMap<String, Value>,
1772) {
1773    env.retain(|name, _| !name.contains('/'));
1774    for namespace in registry.all() {
1775        for (_, var) in namespace.mappings() {
1776            env.insert(var.symbol().as_str().to_owned(), Value::Var(var));
1777        }
1778    }
1779    for (alias, namespace) in registry.current().aliases() {
1780        for (local, var) in namespace.mappings() {
1781            env.insert(
1782                format!("{}/{}", alias.as_str(), local.as_str()),
1783                Value::Var(var),
1784            );
1785        }
1786    }
1787}
1788
1789/// Saves the current namespace, selects name, and loads its bindings.
1790pub fn select_namespace_environment(
1791    registry: &NamespaceRegistry<Value>,
1792    env: &mut HashMap<String, Value>,
1793    name: &str,
1794) {
1795    save_namespace_environment(registry, env);
1796    let namespace = registry.set_current(name);
1797    *env = namespace
1798        .mappings()
1799        .into_iter()
1800        .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1801        .collect();
1802    refresh_namespace_environment(registry, env);
1803}
1804
1805pub fn apply_global_aliases(registry: &NamespaceRegistry<Value>, namespace: &str) {
1806    let target = registry.find_or_create(namespace);
1807    for (alias, library) in registry.global_aliases() {
1808        if target.name() == &library {
1809            continue;
1810        }
1811        if let Some(source) = registry.find(library.as_str()) {
1812            target.alias(alias.as_str(), source);
1813        } else {
1814            target.lazy_alias(alias.as_str(), library.as_str());
1815        }
1816    }
1817}
1818
1819pub fn apply_global_imports(registry: &NamespaceRegistry<Value>, namespace: &str) {
1820    let target = registry.find_or_create(namespace);
1821    for (local, canonical) in registry.global_imports() {
1822        if target.resolve(&local).is_none() {
1823            if let Some(var) = registry.resolve(&canonical) {
1824                target.map_var(local, var);
1825            }
1826        }
1827    }
1828}
1829
1830/// Runs an evaluation with a registry available to protocol dispatch.
1831pub fn with_protocols<R>(registry: &ProtocolRegistry, operation: impl FnOnce() -> R) -> R {
1832    ACTIVE_PROTOCOLS.with(|active| {
1833        let previous = active.replace(Some(registry.clone()));
1834        let result = operation();
1835        active.replace(previous);
1836        result
1837    })
1838}
1839
1840pub fn with_package_catalog<R>(catalog: &PackageCatalog, operation: impl FnOnce() -> R) -> R {
1841    ACTIVE_PACKAGE_CATALOG.with(|active| {
1842        let previous = active.replace(Some(catalog.clone()));
1843        let result = operation();
1844        active.replace(previous);
1845        result
1846    })
1847}
1848
1849fn package_catalog() -> PackageCatalog {
1850    ACTIVE_PACKAGE_CATALOG.with(|active| active.borrow().clone().unwrap_or_default())
1851}
1852
1853/// Runs an evaluation through the selected runtime promise provider.
1854pub fn with_promise_provider<R>(
1855    provider: Rc<dyn PromiseProvider>,
1856    operation: impl FnOnce() -> R,
1857) -> R {
1858    ACTIVE_PROMISE_PROVIDER.with(|active| {
1859        let previous = active.replace(Some(provider));
1860        let result = operation();
1861        active.replace(previous);
1862        result
1863    })
1864}
1865
1866fn promise_provider() -> Rc<dyn PromiseProvider> {
1867    ACTIVE_PROMISE_PROVIDER.with(|active| {
1868        active
1869            .borrow()
1870            .clone()
1871            .unwrap_or_else(|| Rc::new(LocalPromiseProvider))
1872    })
1873}
1874/// Runs an evaluation through the selected runtime capability providers.
1875pub fn with_capability_providers<R>(
1876    file: Option<Rc<dyn FileProvider>>,
1877    socket: Option<Rc<dyn SocketProvider>>,
1878    process: bool,
1879    kernel: Option<Rc<KernelProvider>>,
1880    operation: impl FnOnce() -> R,
1881) -> R {
1882    ACTIVE_FILE_PROVIDER.with(|active_file| {
1883        ACTIVE_SOCKET_PROVIDER.with(|active_socket| {
1884            ACTIVE_KERNEL_PROVIDER.with(|active_kernel| {
1885                ACTIVE_PROCESS_ALLOWED.with(|active_process| {
1886                    let previous_file = active_file.replace(file);
1887                    let previous_socket = active_socket.replace(socket);
1888                    let previous_kernel = active_kernel.replace(kernel);
1889                    let previous_process = active_process.replace(process);
1890                    let result = operation();
1891                    active_file.replace(previous_file);
1892                    active_socket.replace(previous_socket);
1893                    active_kernel.replace(previous_kernel);
1894                    active_process.set(previous_process);
1895                    result
1896                })
1897            })
1898        })
1899    })
1900}
1901
1902pub type KernelProvider = dyn Fn(String, Vec<Value>) -> Result<Value, String>;
1903
1904fn kernel_provider(operation: &str) -> Result<Rc<KernelProvider>, String> {
1905    ACTIVE_KERNEL_PROVIDER.with(|active| {
1906        active
1907            .borrow()
1908            .clone()
1909            .ok_or_else(|| format!("std.native.Kernel/{operation} requires a kernel provider"))
1910    })
1911}
1912
1913fn file_provider(operation: &str) -> Result<Rc<dyn FileProvider>, String> {
1914    ACTIVE_FILE_PROVIDER.with(|active| {
1915        active
1916            .borrow()
1917            .clone()
1918            .ok_or_else(|| format!("{operation} is unsupported or file access is denied"))
1919    })
1920}
1921
1922fn socket_provider(operation: &str) -> Result<Rc<dyn SocketProvider>, String> {
1923    ACTIVE_SOCKET_PROVIDER.with(|active| {
1924        active
1925            .borrow()
1926            .clone()
1927            .ok_or_else(|| format!("{operation} is unsupported or network access is denied"))
1928    })
1929}
1930
1931pub(crate) fn native_capability_granted(capability: &str) -> bool {
1932    match capability {
1933        "kernel" | "sandbox" => ACTIVE_KERNEL_PROVIDER.with(|active| active.borrow().is_some()),
1934        "file" => ACTIVE_FILE_PROVIDER.with(|active| active.borrow().is_some()),
1935        "network" => ACTIVE_SOCKET_PROVIDER.with(|active| active.borrow().is_some()),
1936        "native-runtime" => ACTIVE_PROCESS_ALLOWED.get(),
1937        "host-call" => HOST_CALL_HANDLER.with(|active| active.borrow().is_some()),
1938        _ => false,
1939    }
1940}
1941
1942pub(crate) fn native_capability_error_value(
1943    native_type: &str,
1944    method: &str,
1945    capability: &str,
1946) -> Value {
1947    Value::ExceptionInfo(Rc::new(ExceptionInfo {
1948        message: format!(
1949            "std.native.{native_type}/{method} requires capability :{capability}"
1950        ),
1951        data: Box::new(Value::Map(
1952            [
1953                (
1954                    Value::Keyword("ex/code".into()),
1955                    Value::Keyword("native/capability-denied".into()),
1956                ),
1957                (
1958                    Value::Keyword("ex/class".into()),
1959                    Value::Keyword("ex.class/host".into()),
1960                ),
1961                (
1962                    Value::Keyword("native/type".into()),
1963                    Value::String(format!("std.native.{native_type}")),
1964                ),
1965                (
1966                    Value::Keyword("native/method".into()),
1967                    Value::String(method.into()),
1968                ),
1969                (
1970                    Value::Keyword("native/capability".into()),
1971                    Value::Keyword(capability.into()),
1972                ),
1973            ]
1974            .into_iter()
1975            .collect(),
1976        )),
1977        cause: None,
1978        provenance: Rc::new(RefCell::new(Default::default())),
1979    }))
1980}
1981
1982pub(crate) fn native_capability_denied(
1983    native_type: &str,
1984    method: &str,
1985    capability: &str,
1986) -> String {
1987    thrown_error(native_capability_error_value(native_type, method, capability))
1988}
1989
1990pub(crate) fn native_capability_denied_promise(
1991    native_type: &str,
1992    method: &str,
1993    capability: &str,
1994) -> Value {
1995    let promise = Promise::new();
1996    promise.reject_value(native_capability_error_value(native_type, method, capability));
1997    Value::Promise(promise)
1998}
1999
2000pub(crate) fn require_native_capability(
2001    native_type: &str,
2002    method: &str,
2003    capability: &str,
2004) -> Result<(), String> {
2005    native_capability_granted(capability)
2006        .then_some(())
2007        .ok_or_else(|| native_capability_denied(native_type, method, capability))
2008}
2009
2010fn require_process_access(operation: &str) -> Result<(), String> {
2011    ACTIVE_PROCESS_ALLOWED.with(|allowed| {
2012        allowed
2013            .get()
2014            .then_some(())
2015            .ok_or_else(|| {
2016                let method = operation
2017                    .strip_prefix("std.native.Process/")
2018                    .unwrap_or(operation);
2019                native_capability_denied("Process", method, "native-runtime")
2020            })
2021    })
2022}