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.idereftimeout.IDerefTimeout",
706            "deref-timeout",
707            protocol_deref_timeout,
708        );
709        registry.register("std.protocol.ireset.IReset", "reset", protocol_reset);
710        registry.register("std.protocol.icas.ICas", "cas", protocol_cas);
711        registry.register("std.protocol.ireduce.IReduce", "reduce", protocol_reduce);
712        registry.register(
713            "std.protocol.itomutable.IToMutable",
714            "to-mutable",
715            protocol_to_mutable,
716        );
717        registry.register(
718            "std.protocol.itopersistent.IToPersistent",
719            "to-persistent",
720            protocol_to_persistent,
721        );
722        registry.register(
723            "std.protocol.ipromise.IPromise",
724            "state",
725            protocol_promise_state,
726        );
727        registry.register(
728            "std.protocol.ipromise.IPromise",
729            "value",
730            protocol_promise_value,
731        );
732        registry.register("std.protocol.ipromise.IPromise", "then", |arguments| {
733            protocol_promise_chain("promise/then", arguments)
734        });
735        registry.register("std.protocol.ipromise.IPromise", "catch", |arguments| {
736            protocol_promise_chain("promise/catch", arguments)
737        });
738        registry.register("std.protocol.ipromise.IPromise", "finally", |arguments| {
739            protocol_promise_chain("promise/finally", arguments)
740        });
741        registry.register(
742            "std.protocol.ipromise.IPromise",
743            "cancel",
744            protocol_promise_cancel,
745        );
746        registry.register(
747            "std.protocol.icoroutine.ICoroutine",
748            "status",
749            protocol_coroutine_status,
750        );
751        registry.register(
752            "std.protocol.icoroutine.ICoroutine",
753            "resume",
754            protocol_coroutine_resume,
755        );
756        registry.register(
757            "std.protocol.istream.IStream",
758            "next",
759            |arguments| match arguments {
760                [Value::Stream(stream)] => Ok(stream_next(stream)),
761                [_] => Err("IStream/next expects a stream".into()),
762                _ => Err("IStream/next expects one argument".into()),
763            },
764        );
765        registry.register(
766            "std.protocol.istreamwrite.IStreamWrite",
767            "write",
768            |arguments| match arguments {
769                [_target, _value] => Err("IStreamWrite/write expects a writable stream".into()),
770                _ => Err("IStreamWrite/write expects two arguments".into()),
771            },
772        );
773        registry.register(
774            "std.protocol.iabort.IAbort",
775            "abort",
776            |arguments| match arguments {
777                [_target, _error] => Err("IAbort/abort expects an abortable stream".into()),
778                _ => Err("IAbort/abort expects two arguments".into()),
779            },
780        );
781        registry.register(
782            "std.protocol.iwatch.IWatch",
783            "watch-add",
784            protocol_watch_add,
785        );
786        registry.register(
787            "std.protocol.iwatch.IWatch",
788            "watch-remove",
789            protocol_watch_remove,
790        );
791        registry.register(
792            "std.protocol.iwatch.IWatch",
793            "watch-list",
794            protocol_watch_list,
795        );
796        registry
797    }
798}
799
800thread_local! {
801    static ACTIVE_PROTOCOLS: RefCell<Option<ProtocolRegistry>> = const { RefCell::new(None) };
802    static ACTIVE_NAMESPACES: RefCell<Option<NamespaceRegistry<Value>>> = const { RefCell::new(None) };
803    static ACTIVE_DEFINITION_ORIGIN: Cell<VarOrigin> = const { Cell::new(VarOrigin::Source) };
804    static ACTIVE_PROMISE_PROVIDER: RefCell<Option<Rc<dyn PromiseProvider>>> = const { RefCell::new(None) };
805    static ACTIVE_FILE_PROVIDER: RefCell<Option<Rc<dyn FileProvider>>> = const { RefCell::new(None) };
806    static ACTIVE_SOCKET_PROVIDER: RefCell<Option<Rc<dyn SocketProvider>>> = const { RefCell::new(None) };
807    static ACTIVE_KERNEL_PROVIDER: RefCell<Option<Rc<KernelProvider>>> = const { RefCell::new(None) };
808    static ACTIVE_PACKAGE_CATALOG: RefCell<Option<PackageCatalog>> = const { RefCell::new(None) };
809    static ACTIVE_PROCESS_ALLOWED: Cell<bool> = const { Cell::new(false) };
810    static ACTIVE_TEST_RUNNER: RefCell<String> = RefCell::new("code.test".into());
811    static HOST_CALL_HANDLER: RefCell<Option<Rc<dyn Fn(String, String, Vec<Value>) -> Result<Value, String>>>> = const { RefCell::new(None) };
812    static NAMESPACE_SOURCE_PROVIDER: RefCell<Option<Rc<dyn Fn(&str) -> Option<NamespaceResource>>>> = const { RefCell::new(None) };
813    static ACTIVE_THROWN_VALUE: RefCell<Option<(String, Value)>> = const { RefCell::new(None) };
814    static ACTIVE_MULTIMETHODS: RefCell<HashMap<String, Rc<RefCell<MultiMethod>>>> = RefCell::new(HashMap::new());
815    #[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
816    static ACTIVE_DIRECT_NATIVE_NAMESPACE_LOADER: RefCell<Option<Rc<dyn Fn(&str, NamespaceResource, &mut HashMap<String, Value>) -> Result<(), String>>>> = const { RefCell::new(None) };
817    #[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
818    static ACTIVE_DIRECT_NATIVE_EXECUTION: Cell<bool> = const { Cell::new(false) };
819}
820
821#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
822pub(crate) type MultiMethodRegistry =
823    Rc<RefCell<HashMap<String, Rc<RefCell<MultiMethod>>>>>;
824
825#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
826#[derive(Clone)]
827pub(crate) struct DirectNativeContext {
828    pub(crate) namespaces: NamespaceRegistry<Value>,
829    /// The namespace in which the frame was compiled. Namespace registries
830    /// share their mutable current pointer, so a suspended child must restore
831    /// this selection explicitly when it resumes instead of inheriting a
832    /// caller which happened to run in the meantime.
833    pub(crate) namespace: String,
834    pub(crate) protocols: ProtocolRegistry,
835    pub(crate) promise_provider: Rc<dyn PromiseProvider>,
836    pub(crate) file_provider: Option<Rc<dyn FileProvider>>,
837    pub(crate) socket_provider: Option<Rc<dyn SocketProvider>>,
838    pub(crate) process_allowed: bool,
839    pub(crate) kernel_provider: Option<Rc<KernelProvider>>,
840    pub(crate) package_catalog: PackageCatalog,
841    pub(crate) macros: Rc<RefCell<HashMap<(String, String), Rc<Function>>>>,
842    pub(crate) namespace_source:
843        Option<Rc<dyn Fn(&str) -> Option<NamespaceResource>>>,
844    pub(crate) host_handler:
845        Option<Rc<dyn Fn(String, String, Vec<Value>) -> Result<Value, String>>>,
846    pub(crate) test_runner: String,
847    pub(crate) definition_origin: VarOrigin,
848    pub(crate) multimethods: MultiMethodRegistry,
849    pub(crate) native_namespace_loader: Option<
850        Rc<dyn Fn(
851            &str,
852            NamespaceResource,
853            &mut HashMap<String, Value>,
854        ) -> Result<(), String>>,
855    >,
856    pub(crate) work_context: Option<crate::work::WorkContext>,
857}
858
859#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
860impl DirectNativeContext {
861    pub(crate) fn capture() -> Self {
862        let multimethods = Rc::new(RefCell::new(
863            ACTIVE_MULTIMETHODS.with(|active| active.borrow().clone()),
864        ));
865        Self::capture_with_multimethods(multimethods)
866    }
867
868    pub(crate) fn capture_with_multimethods(multimethods: MultiMethodRegistry) -> Self {
869        let namespaces = namespace_registry()
870            .unwrap_or_else(|_| NamespaceRegistry::new("user"));
871        let namespace = namespaces.current().name().as_str().to_owned();
872        let protocols = ACTIVE_PROTOCOLS
873            .with(|active| active.borrow().clone())
874            .unwrap_or_else(ProtocolRegistry::core);
875        let promise_provider = ACTIVE_PROMISE_PROVIDER
876            .with(|active| active.borrow().clone())
877            .unwrap_or_else(|| Rc::new(LocalPromiseProvider));
878        let file_provider = ACTIVE_FILE_PROVIDER.with(|active| active.borrow().clone());
879        let socket_provider = ACTIVE_SOCKET_PROVIDER.with(|active| active.borrow().clone());
880        let process_allowed = ACTIVE_PROCESS_ALLOWED.get();
881        let kernel_provider = ACTIVE_KERNEL_PROVIDER.with(|active| active.borrow().clone());
882        let package_catalog = ACTIVE_PACKAGE_CATALOG
883            .with(|active| active.borrow().clone())
884            .unwrap_or_default();
885        let macros = ACTIVE_MACROS.with(|active| {
886            active
887                .borrow()
888                .clone()
889                .unwrap_or_else(|| Rc::new(RefCell::new(HashMap::new())))
890        });
891        let namespace_source = NAMESPACE_SOURCE_PROVIDER
892            .with(|active| active.borrow().clone());
893        let host_handler = HOST_CALL_HANDLER.with(|active| active.borrow().clone());
894        let test_runner = ACTIVE_TEST_RUNNER.with(|active| active.borrow().clone());
895        let definition_origin = ACTIVE_DEFINITION_ORIGIN.with(Cell::get);
896        let native_namespace_loader = ACTIVE_DIRECT_NATIVE_NAMESPACE_LOADER
897            .with(|active| active.borrow().clone());
898        let work_context = crate::work::current_work_context();
899        Self {
900            namespaces,
901            namespace,
902            protocols,
903            promise_provider,
904            file_provider,
905            socket_provider,
906            process_allowed,
907            kernel_provider,
908            package_catalog,
909            macros,
910            namespace_source,
911            host_handler,
912            test_runner,
913            definition_origin,
914            multimethods,
915            native_namespace_loader,
916            work_context,
917        }
918    }
919
920    pub(crate) fn with<R>(&self, operation: impl FnOnce() -> R) -> R {
921        let namespaces = self.namespaces.clone();
922        let namespace = self.namespace.clone();
923        let run = || {
924            let previous = namespaces.current().name().as_str().to_owned();
925            namespaces.set_current(&namespace);
926            let result = with_test_runner(&self.test_runner, || {
927                with_capability_providers(
928                    self.file_provider.clone(),
929                    self.socket_provider.clone(),
930                    self.process_allowed,
931                    self.kernel_provider.clone(),
932                    || {
933                        with_package_catalog(&self.package_catalog, || {
934                            with_promise_provider(self.promise_provider.clone(), || {
935                                with_macros(self.macros.clone(), || {
936                                    with_namespace_registry(&self.namespaces, || {
937                                        with_definition_origin(self.definition_origin, || {
938                                            with_protocols(&self.protocols, || {
939                                                with_direct_native_context_values(self, operation)
940                                            })
941                                        })
942                                    })
943                                })
944                            })
945                        })
946                    },
947                )
948            });
949            namespaces.set_current(&previous);
950            result
951        };
952        if let Some(context) = self.work_context.clone() {
953            crate::work::with_current_work_context(context, run)
954        } else {
955            run()
956        }
957    }
958}
959
960#[cfg(all(feature = "direct-native", not(target_arch = "wasm32")))]
961fn with_direct_native_context_values<R>(
962    context: &DirectNativeContext,
963    operation: impl FnOnce() -> R,
964) -> R {
965    let run_with_multimethods = || {
966        ACTIVE_MULTIMETHODS.with(|active| {
967            let previous = std::mem::replace(
968                &mut *active.borrow_mut(),
969                context.multimethods.borrow().clone(),
970            );
971            let result = operation();
972            *context.multimethods.borrow_mut() = active.borrow().clone();
973            *active.borrow_mut() = previous;
974            result
975        })
976    };
977    let run_with_loader = || {
978        if let Some(loader) = context.native_namespace_loader.clone() {
979            with_direct_native_namespace_loader(loader, run_with_multimethods)
980        } else {
981            run_with_multimethods()
982        }
983    };
984    let run_with_source = || {
985        if let Some(provider) = context.namespace_source.clone() {
986            with_namespace_source(provider, run_with_loader)
987        } else {
988            run_with_loader()
989        }
990    };
991    if let Some(handler) = context.host_handler.clone() {
992        with_host_calls(handler, run_with_source)
993    } else {
994        run_with_source()
995    }
996}
997
998pub(crate) fn with_test_runner<R>(runner: &str, f: impl FnOnce() -> R) -> R {
999    ACTIVE_TEST_RUNNER.with(|active| {
1000        let previous = active.replace(runner.into());
1001        let result = f();
1002        active.replace(previous);
1003        result
1004    })
1005}
1006
1007pub(crate) fn snapshot_multimethods() -> HashMap<String, MultiMethod> {
1008    ACTIVE_MULTIMETHODS.with(|active| {
1009        active
1010            .borrow()
1011            .iter()
1012            .map(|(name, state)| (name.clone(), state.borrow().clone()))
1013            .collect()
1014    })
1015}
1016
1017pub(crate) fn restore_multimethods(snapshot: HashMap<String, MultiMethod>) {
1018    ACTIVE_MULTIMETHODS.with(|active| {
1019        *active.borrow_mut() = snapshot
1020            .into_iter()
1021            .map(|(name, state)| (name, Rc::new(RefCell::new(state))))
1022            .collect();
1023    });
1024}
1025
1026pub(crate) fn register_multimethod(name: String, state: Rc<RefCell<MultiMethod>>) {
1027    ACTIVE_MULTIMETHODS.with(|active| {
1028        active.borrow_mut().insert(name, state);
1029    });
1030}
1031
1032pub(crate) fn multimethod_state(name: &str) -> Option<Rc<RefCell<MultiMethod>>> {
1033    ACTIVE_MULTIMETHODS.with(|active| active.borrow().get(name).cloned())
1034}
1035
1036pub(crate) fn active_protocol_registry() -> Result<ProtocolRegistry, String> {
1037    ACTIVE_PROTOCOLS
1038        .with(|active| active.borrow().clone())
1039        .ok_or_else(|| "protocol registry is unavailable".into())
1040}
1041
1042#[derive(Clone)]
1043pub enum NamespaceResource {
1044    Source(String),
1045    /// A native host source whose contents are read only when the namespace
1046    /// crosses the require boundary.
1047    #[cfg(not(target_arch = "wasm32"))]
1048    SourcePath(std::path::PathBuf),
1049    #[cfg(feature = "bytecode-vm")]
1050    Bytecode {
1051        namespace_form: String,
1052        artifact: Vec<u8>,
1053    },
1054}
1055
1056#[cfg(not(target_arch = "wasm32"))]
1057pub(crate) fn read_source_resource(
1058    resource: &NamespaceResource,
1059    namespace: &str,
1060) -> Result<String, String> {
1061    match resource {
1062        NamespaceResource::Source(source) => Ok(source.clone()),
1063        NamespaceResource::SourcePath(path) => std::fs::read_to_string(path)
1064            .map_err(|error| format!("{namespace}: cannot read {}: {error}", path.display())),
1065        #[cfg(feature = "bytecode-vm")]
1066        NamespaceResource::Bytecode { .. } => {
1067            Err(format!("{namespace}: bytecode resource is not source text"))
1068        }
1069    }
1070}
1071
1072pub(crate) fn thrown_error(value: Value) -> String {
1073    thrown_error_at(value, current_exception_site())
1074}
1075
1076pub(crate) fn thrown_error_at(value: Value, site: Option<ExceptionSite>) -> String {
1077    record_exception_throw(&value, site);
1078    record_trace_failure();
1079    let error = format!("thrown: {}", value.display());
1080    ACTIVE_THROWN_VALUE.with(|active| {
1081        *active.borrow_mut() = Some((error.clone(), value));
1082    });
1083    error
1084}
1085
1086/// Captures the uncaught exception value from one evaluator boundary without
1087/// changing the string error API used by the runtime.  The previous dynamic
1088/// value is restored so a diagnostic request cannot leak exception state into
1089/// a later evaluation in the same broker session.
1090pub fn with_thrown_value_capture<R>(operation: impl FnOnce() -> R) -> (R, Option<Value>) {
1091    ACTIVE_THROWN_VALUE.with(|active| {
1092        let previous = active.replace(None);
1093        let result = operation();
1094        let captured = active.take().map(|(_, value)| value);
1095        active.replace(previous);
1096        (result, captured)
1097    })
1098}
1099
1100pub(crate) fn promise_rejection_error(error: PromiseRejection) -> String {
1101    match error {
1102        PromiseRejection::Message(message) => message,
1103        PromiseRejection::Value(value) | PromiseRejection::Cancelled(value) => thrown_error(value),
1104    }
1105}
1106
1107pub(crate) fn caught_error(error: &str) -> Value {
1108    ACTIVE_THROWN_VALUE.with(|active| {
1109        let mut active = active.borrow_mut();
1110        if active
1111            .as_ref()
1112            .is_some_and(|(thrown_error, _)| error.starts_with(thrown_error))
1113        {
1114            return active.take().unwrap().1;
1115        }
1116        Value::String(error.to_owned())
1117    })
1118}
1119
1120pub(crate) fn catch_matches(error: &str, class: &str) -> bool {
1121    if class == "Exception" || class == "Throwable" {
1122        return true;
1123    }
1124    if let Some(selectors) = class
1125        .strip_prefix('[')
1126        .and_then(|value| value.strip_suffix(']'))
1127    {
1128        return selectors
1129            .split(',')
1130            .any(|selector| catch_matches(error, selector));
1131    }
1132    if let Some(selector) = class.strip_prefix(':') {
1133        return ACTIVE_THROWN_VALUE.with(|active| {
1134            active.borrow().as_ref().is_some_and(|(message, value)| {
1135                error.starts_with(message)
1136                    && matches!(value, Value::ExceptionInfo(info)
1137                        if map_entries(&info.data).is_some_and(|entries| entries.iter().any(|(key, value)| {
1138                            matches!(key, Value::Keyword(name) if name.as_str() == "ex/code")
1139                                && matches!(value, Value::Keyword(code) if code.as_str() == selector)
1140                        })))
1141            })
1142        });
1143    }
1144    ACTIVE_THROWN_VALUE.with(|active| {
1145        active.borrow().as_ref().is_some_and(|(message, value)| {
1146            error.starts_with(message)
1147                && match value {
1148                    Value::Struct(value) => {
1149                        value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1150                    }
1151                    Value::Mutable(value) => {
1152                        value.ty.name == class || value.ty.name.ends_with(&format!("/{class}"))
1153                    }
1154                    _ => false,
1155                }
1156        })
1157    })
1158}
1159
1160/// Runs an evaluation with a namespace registry available to namespace builtins.
1161pub fn with_namespace_registry<R>(
1162    registry: &NamespaceRegistry<Value>,
1163    operation: impl FnOnce() -> R,
1164) -> R {
1165    ACTIVE_NAMESPACES.with(|active| {
1166        let previous = active.replace(Some(registry.clone()));
1167        let result = operation();
1168        active.replace(previous);
1169        result
1170    })
1171}
1172
1173pub fn with_definition_origin<R>(origin: VarOrigin, operation: impl FnOnce() -> R) -> R {
1174    ACTIVE_DEFINITION_ORIGIN.with(|active| {
1175        let previous = active.replace(origin);
1176        let result = operation();
1177        active.set(previous);
1178        result
1179    })
1180}
1181
1182pub(crate) fn definition_origin() -> VarOrigin {
1183    ACTIVE_DEFINITION_ORIGIN.with(Cell::get)
1184}
1185
1186pub(crate) fn binding_is_local(var: &KernelVar<Value>) -> bool {
1187    namespace_registry()
1188        .map(|registry| {
1189            var.symbol().get_namespace().is_none()
1190                || var.symbol().get_namespace() == Some(registry.current().name().as_str())
1191        })
1192        .unwrap_or(true)
1193}
1194
1195/// Names a fresh local var cell: qualified to the current namespace when
1196/// a registry is active, bare otherwise. Qualifying matters: an
1197/// unqualified cell fails `binding_is_local`, so redefining the name in
1198/// the same eval used to shadow with a fresh cell instead of resetting
1199/// the existing one — the answer then depended on whether the name had
1200/// survived a previous eval's namespace save-back (which qualifies
1201/// cells). The JVM runtime always resets the same cell; qualifying at
1202/// creation makes the tree evaluator agree on both first and later
1203/// evals (issue #223).
1204pub(crate) fn local_var_name(name: &str) -> String {
1205    match namespace_registry() {
1206        Ok(registry) => format!("{}/{}", registry.current().name().as_str(), name),
1207        Err(_) => name.to_string(),
1208    }
1209}
1210
1211fn prepare_owned_definition(env: &mut HashMap<String, Value>, name: &str) -> Result<(), String> {
1212    if let Some(Value::Var(var)) = env.get(name) {
1213        if !binding_is_local(var) {
1214            if let Ok(registry) = namespace_registry() {
1215                registry.current().unmap(&Symbol::parse(name));
1216            }
1217            env.remove(name);
1218        }
1219    }
1220    Ok(())
1221}
1222
1223/// Defines or updates a global var in the current namespace, mirroring
1224/// the evaluator's `def` arm (`core.rs` special forms) without the flat
1225/// env bridge: an existing var local to the current namespace is reused
1226/// (identity preserved), a referred or missing name gets a fresh cell.
1227/// Used by the bytecode VM's `DefGlobal` (issue #223).
1228pub(crate) fn vm_def_global(
1229    name: &str,
1230    value: Value,
1231    metadata: Option<Rc<Metadata>>,
1232) -> Result<KernelVar<Value>, String> {
1233    let registry = namespace_registry()?;
1234    let current = registry.current();
1235    let local = Symbol::create(None, name);
1236    if let Some(existing) = current.resolve(&local) {
1237        if binding_is_local(&existing) {
1238            existing.reset_value(value);
1239            if metadata.is_some() {
1240                existing.set_hara_metadata(metadata);
1241            }
1242            existing.set_origin(definition_origin());
1243            refresh_schema_contract(&existing)?;
1244            return Ok(existing);
1245        }
1246        current.unmap(&local);
1247    }
1248    let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), value);
1249    var.set_hara_metadata(metadata);
1250    var.set_origin(definition_origin());
1251    current.map_var(local, var.clone());
1252    refresh_schema_contract(&var)?;
1253    Ok(var)
1254}
1255
1256pub(crate) fn vm_def_macro(
1257    name: &str,
1258    value: Value,
1259    metadata: Option<Rc<Metadata>>,
1260) -> Result<KernelVar<Value>, String> {
1261    let Value::Function(function) = &value else {
1262        return Err("defmacro expects a function value".into());
1263    };
1264    let function = function.clone();
1265    let namespace = namespace_registry()?.current().name().as_str().to_owned();
1266    let var = vm_def_global(name, value, metadata)?;
1267    register_macro(&namespace, name, function)?;
1268    Ok(var)
1269}
1270
1271/// Declares a global var without assigning it, mirroring the evaluator's
1272/// `declare` arm: an existing local var is kept (value untouched), a
1273/// missing name gets a fresh nil cell. Used by the VM (issue #223).
1274pub(crate) fn vm_declare_global(name: &str) -> Result<KernelVar<Value>, String> {
1275    let registry = namespace_registry()?;
1276    let current = registry.current();
1277    let local = Symbol::create(None, name);
1278    if let Some(existing) = current.resolve(&local) {
1279        if binding_is_local(&existing) {
1280            existing.set_origin(definition_origin());
1281            return Ok(existing);
1282        }
1283        // An explicit `declare` is the source-level ownership boundary.  It
1284        // authorizes the following definition to replace a referred Var in
1285        // this namespace; a direct definition still goes through the
1286        // compiler's ownership check and remains protected.
1287        current.unmap(&local);
1288    }
1289    let var = KernelVar::new(format!("{}/{}", current.name().as_str(), name), Value::Nil);
1290    var.set_origin(definition_origin());
1291    current.map_var(local, var.clone());
1292    Ok(var)
1293}
1294
1295/// Resolves a global var by (possibly qualified) name through the
1296/// registry: current-namespace mappings, aliases, and qualified names.
1297pub(crate) fn vm_resolve_global(name: &str) -> Result<KernelVar<Value>, String> {
1298    let registry = namespace_registry()?;
1299    if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1300        return Ok(var);
1301    }
1302    if let Some((namespace, _)) = name.rsplit_once('/') {
1303        if NAMESPACE_SOURCE_PROVIDER.with(|active| {
1304            active
1305                .borrow()
1306                .as_ref()
1307                .is_some_and(|provider| provider(namespace).is_some())
1308        }) {
1309            require_namespace(&registry, &mut HashMap::new(), namespace)?;
1310            if let Some(var) = registry.resolve(&Symbol::parse(name)) {
1311                return Ok(var);
1312            }
1313        }
1314    }
1315    Err(format!("unbound symbol: {name}"))
1316}
1317
1318/// Resolves a bare namespace symbol as the evaluator does. Namespace aliases
1319/// are values (and therefore callable through their `run` Var), but they are
1320/// not Vars themselves and cannot be represented by `vm_resolve_global`.
1321/// Lazy aliases are materialized at execution time so compiled programs keep
1322/// the same load boundary as interpreted forms.
1323pub(crate) fn vm_resolve_namespace_value(name: &str) -> Result<Value, String> {
1324    let registry = namespace_registry()?;
1325    if let Some(namespace) = registry
1326        .current()
1327        .aliases()
1328        .into_iter()
1329        .find_map(|(alias, namespace)| (alias.as_str() == name).then_some(namespace))
1330    {
1331        return Ok(Value::Namespace(Rc::new(namespace)));
1332    }
1333    if let Some(target) = registry.current().lazy_target(name) {
1334        require_namespace(&registry, &mut HashMap::new(), target.as_str())?;
1335        let namespace = registry
1336            .find(target.as_str())
1337            .ok_or_else(|| format!("Cannot require missing namespace: {target}"))?;
1338        registry.current().alias(name, namespace.clone());
1339        return Ok(Value::Namespace(Rc::new(namespace)));
1340    }
1341    registry
1342        .find(name)
1343        .map(|namespace| Value::Namespace(Rc::new(namespace)))
1344        .ok_or_else(|| format!("unbound symbol: {name}"))
1345}
1346
1347fn validate_named_definition(kind: &str, name: &str, fields: &[NamedField]) -> Result<(), String> {
1348    if name.contains('/') {
1349        return Err(format!("{kind} name must be an unqualified symbol"));
1350    }
1351    if fields
1352        .iter()
1353        .any(|field| field.name.is_empty() || field.name.contains('/'))
1354    {
1355        return Err(format!("{kind} field names must be unqualified symbols"));
1356    }
1357    if fields
1358        .iter()
1359        .map(|field| &field.name)
1360        .collect::<HashSet<_>>()
1361        .len()
1362        != fields.len()
1363    {
1364        return Err(format!("Duplicate {kind} field"));
1365    }
1366    Ok(())
1367}
1368
1369/// Runs a source declaration as one registry operation.
1370///
1371/// Declarations touch the namespace registry, the active protocol dispatch
1372/// registry, and the flat evaluator environment. Restore all three views when
1373/// validation or a later inline extension fails.
1374pub(crate) fn with_declaration_transaction<R>(
1375    environment: &mut HashMap<String, Value>,
1376    operation: impl FnOnce(&mut HashMap<String, Value>) -> Result<R, String>,
1377) -> Result<R, String> {
1378    let registry = namespace_registry()?;
1379    let registry_snapshot = registry.snapshot();
1380    let environment_snapshot = environment.clone();
1381    let protocol_snapshot = ACTIVE_PROTOCOLS.with(|active| {
1382        active
1383            .borrow()
1384            .as_ref()
1385            .map(ProtocolRegistry::snapshot)
1386    });
1387    let multimethod_snapshot = snapshot_multimethods();
1388
1389    let result = operation(environment);
1390    if result.is_err() {
1391        registry.restore(registry_snapshot);
1392        *environment = environment_snapshot;
1393        if let Some(snapshot) = protocol_snapshot {
1394            ACTIVE_PROTOCOLS.with(|active| {
1395                if let Some(registry) = active.borrow().as_ref() {
1396                    registry.restore(snapshot);
1397                }
1398            });
1399        }
1400        restore_multimethods(multimethod_snapshot);
1401    }
1402    result
1403}
1404
1405fn prepare_named_binding(namespace: &crate::kernel::Namespace<Value>, name: &str) {
1406    let symbol = Symbol::parse(name);
1407    if let Some(existing) = namespace.resolve(&symbol) {
1408        if existing.symbol().get_namespace() != Some(namespace.name().as_str()) {
1409            namespace.unmap(&symbol);
1410        }
1411    }
1412}
1413
1414/// Publishes the type Var and its positional and map constructors for a
1415/// defstruct or defmutable declaration. `Base/struct` and `Base/mutable`
1416/// use this path after Foundation macro expansion.
1417pub(crate) fn publish_named_value(
1418    kind: &str,
1419    name: &str,
1420    fields: Vec<NamedField>,
1421    environment: &mut HashMap<String, Value>,
1422    metadata: Option<Rc<Metadata>>,
1423) -> Result<Value, String> {
1424    validate_named_definition(kind, name, &fields)?;
1425    let mutable = kind == "defmutable";
1426    let schema_form = named_value_schema_form(
1427        &format!("{}/{}", namespace_registry()?.current().name().as_str(), name),
1428        mutable,
1429        &fields,
1430    );
1431    let metadata = assoc_metadata(metadata, "schema", metadata_value(&schema_form)?)
1432        .ok_or_else(|| "named value schema metadata could not be created".to_string())?;
1433    let field_names = fields
1434        .iter()
1435        .map(|field| field.name.clone())
1436        .collect::<Vec<_>>();
1437    with_declaration_transaction(environment, |environment| {
1438        let registry = namespace_registry()?;
1439        let namespace = registry.current();
1440        let namespace_name = namespace.name().as_str().to_owned();
1441        let type_name = format!("{}/{}", namespace_name, name);
1442        let declaration = Rc::new(NamedDeclaration::new(
1443            type_name.clone(),
1444            mutable,
1445            fields.clone(),
1446            schema_form.clone(),
1447        ));
1448
1449        let (type_value, map_constructor) = if mutable {
1450            let ty = Rc::new(MutableType {
1451                name: type_name.clone(),
1452                fields: field_names.clone(),
1453                declaration: Some(declaration.clone()),
1454            });
1455            let map_type = ty.clone();
1456            let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1457                let source = values.first().expect("native arity is checked");
1458                let values = map_type
1459                    .fields
1460                    .iter()
1461                    .map(|field| {
1462                        map_value(source, &named_field_key(field))
1463                            .cloned()
1464                            .unwrap_or(Value::Nil)
1465                    })
1466                    .collect();
1467                Ok(Value::Mutable(Rc::new(MutableValue::from_values(
1468                    map_type.clone(),
1469                    values,
1470                    None,
1471                )?)))
1472            });
1473            (Value::MutableType(ty), constructor)
1474        } else {
1475            let ty = Rc::new(StructType {
1476                name: type_name.clone(),
1477                fields: field_names,
1478                declaration: Some(declaration),
1479            });
1480            let map_type = ty.clone();
1481            let constructor = native_function(&format!("map->{}", name), 1, move |values| {
1482                let source = values.first().expect("native arity is checked");
1483                let values = map_type
1484                    .fields
1485                    .iter()
1486                    .map(|field| {
1487                        map_value(source, &named_field_key(field))
1488                            .cloned()
1489                            .unwrap_or(Value::Nil)
1490                    })
1491                    .collect();
1492                Ok(Value::Struct(Rc::new(StructValue::from_values(
1493                    map_type.clone(),
1494                    values,
1495                    None,
1496                )?)))
1497            });
1498            (Value::StructType(ty), constructor)
1499        };
1500
1501        let bindings = [
1502            (name.to_owned(), type_value.clone()),
1503            (format!("->{}", name), type_value),
1504            (format!("map->{}", name), map_constructor),
1505        ];
1506        for (binding, value) in bindings {
1507            prepare_named_binding(&namespace, &binding);
1508            let var = namespace.intern(&binding, value);
1509            var.set_origin(definition_origin());
1510            if binding == name {
1511                var.set_hara_metadata(Some(metadata.clone()));
1512                refresh_schema_contract(&var)?;
1513            }
1514            environment.insert(binding.clone(), Value::Var(var.clone()));
1515            environment.insert(
1516                format!("{}/{}", namespace_name, binding),
1517                Value::Var(var),
1518            );
1519        }
1520        Ok(Value::Nil)
1521    })
1522}
1523
1524/// Publishes a guest protocol and all of its method Vars through one
1525/// namespace/dispatch transaction.
1526pub(crate) fn publish_guest_protocol(
1527    name: &str,
1528    methods: HashMap<String, usize>,
1529    parents: Vec<String>,
1530    environment: &mut HashMap<String, Value>,
1531) -> Result<Value, String> {
1532    if name.contains('/') || name.is_empty() {
1533        return Err("defprotocol name must be an unqualified symbol".into());
1534    }
1535    if methods.keys().any(|method| method.contains('/')) {
1536        return Err("protocol method names must be unqualified symbols".into());
1537    }
1538    if methods
1539        .iter()
1540        .any(|(method, arity)| method.is_empty() || *arity == 0)
1541    {
1542        return Err("protocol methods must have a receiver and a non-empty name".into());
1543    }
1544    if parents.iter().any(|parent| parent.is_empty()) {
1545        return Err("protocol parent names must not be empty".into());
1546    }
1547    with_declaration_transaction(environment, |environment| {
1548        let registry = namespace_registry()?;
1549        let namespace = registry.current();
1550        let namespace_name = namespace.name().as_str().to_owned();
1551        let protocol_name = format!("{}.{}", namespace_name, name);
1552        ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1553            let registry = active.borrow();
1554            let registry = registry
1555                .as_ref()
1556                .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1557            if parents.iter().any(|parent| {
1558                parent == &protocol_name || registry.guest_protocol_reaches(parent, &protocol_name)
1559            }) {
1560                return Err(format!("protocol inheritance cycle: {protocol_name}"));
1561            }
1562            Ok(())
1563        })?;
1564        let previous_protocol = namespace
1565            .resolve(&Symbol::parse(name))
1566            .filter(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1567            .and_then(|var| match var.deref_value() {
1568                Value::Protocol(protocol) if protocol.name == protocol_name => Some(protocol),
1569                _ => None,
1570            });
1571
1572        for method in methods.keys() {
1573            for (local, var) in namespace.mappings() {
1574                if local.as_str() == name
1575                    || var.symbol().get_namespace() != Some(namespace_name.as_str())
1576                {
1577                    continue;
1578                }
1579                if let Value::Protocol(other) = var.deref_value() {
1580                    if other.methods.contains_key(method) {
1581                        return Err(format!(
1582                            "Protocol method Var already belongs to {}: {}/{}",
1583                            local.as_str(),
1584                            namespace_name,
1585                            method
1586                        ));
1587                    }
1588                }
1589            }
1590            let existing = namespace.resolve(&Symbol::parse(method));
1591            let same_protocol_reload = previous_protocol
1592                .as_ref()
1593                .is_some_and(|previous| previous.methods.contains_key(method));
1594            if existing
1595                .as_ref()
1596                .is_some_and(|var| var.symbol().get_namespace() == Some(namespace_name.as_str()))
1597                && !same_protocol_reload
1598            {
1599                return Err(format!(
1600                    "Protocol method Var already exists: {}/{}",
1601                    namespace_name,
1602                    method
1603                ));
1604            }
1605        }
1606
1607        if let Some(previous) = &previous_protocol {
1608            for old_method in previous.methods.keys() {
1609                if !methods.contains_key(old_method) {
1610                    let old = Symbol::parse(old_method);
1611                    if namespace.resolve(&old).is_some_and(|var| {
1612                        var.symbol().get_namespace() == Some(namespace_name.as_str())
1613                    }) {
1614                        namespace.unmap(&old);
1615                    }
1616                    environment.remove(old_method);
1617                    environment.remove(&format!("{}/{}", namespace_name, old_method));
1618                }
1619            }
1620        }
1621
1622        for method in methods.keys() {
1623            prepare_named_binding(&namespace, method);
1624        }
1625        prepare_named_binding(&namespace, name);
1626
1627        let protocol = Rc::new(GuestProtocol {
1628            name: protocol_name.clone(),
1629            methods,
1630            parents,
1631        });
1632        let protocol_value = Value::Protocol(protocol.clone());
1633        ACTIVE_PROTOCOLS.with(|active| -> Result<(), String> {
1634            let registry = active.borrow();
1635            let registry = registry
1636                .as_ref()
1637                .ok_or_else(|| "protocol registry is unavailable".to_string())?;
1638            registry.replace_guest_protocol(protocol_name.clone());
1639            registry.register_guest_protocol(protocol.clone());
1640            for method in protocol.methods.keys() {
1641                registry.declare_guest(protocol_name.clone(), method.clone());
1642            }
1643            Ok(())
1644        })?;
1645
1646        let protocol_var = namespace.intern(name, protocol_value.clone());
1647        protocol_var.set_origin(definition_origin());
1648        environment.insert(name.to_owned(), Value::Var(protocol_var.clone()));
1649        environment.insert(
1650            format!("{}/{}", namespace_name, name),
1651            Value::Var(protocol_var),
1652        );
1653        for method in protocol.methods.keys() {
1654            let protocol_name = protocol_name.clone();
1655            let method_name = method.clone();
1656            let display_name = format!("{}/{}", namespace_name, method);
1657            let method_value = native_variadic_function(&display_name, move |arguments| {
1658                protocol_call(&protocol_name, &method_name, &arguments)
1659            });
1660            let method_var = namespace.intern(method, method_value);
1661            method_var.set_origin(definition_origin());
1662            environment.insert(method.clone(), Value::Var(method_var.clone()));
1663            environment.insert(
1664                format!("{}/{}", namespace_name, method),
1665                Value::Var(method_var),
1666            );
1667        }
1668        Ok(protocol_value)
1669    })
1670}
1671
1672/// Direct field access is reserved for mutable named values. Immutable
1673/// structs use ordinary associative lookup.
1674pub(crate) fn mutable_field_value(value: &Value, field: &str) -> Result<Value, String> {
1675    let Value::Mutable(value) = value else {
1676        return Err("field expects a mutable value".into());
1677    };
1678    value
1679        .get(field)
1680        .ok_or_else(|| format!("unknown mutable field: {field}"))
1681}
1682
1683/// Replaces one declared mutable field and returns the replacement value.
1684pub(crate) fn mutable_field_set(
1685    value: &Value,
1686    field: &str,
1687    replacement: Value,
1688) -> Result<Value, String> {
1689    let Value::Mutable(value) = value else {
1690        return Err("field expects a mutable value".into());
1691    };
1692    value.set(field, replacement)
1693}
1694
1695/// Named-value type identity check shared with the `instance?` special form.
1696pub(crate) fn named_instance_of(type_value: &Value, value: &Value) -> Result<Value, String> {
1697    let matches = match type_value {
1698        Value::StructType(ty) => {
1699            matches!(value, Value::Struct(value) if Rc::ptr_eq(ty, &value.ty))
1700        }
1701        Value::MutableType(ty) => {
1702            matches!(value, Value::Mutable(value) if Rc::ptr_eq(ty, &value.ty))
1703        }
1704        Value::NativeType(native) => native_type_instance(native, value)?,
1705        _ => return Err("instance? expects a struct or mutable type".into()),
1706    };
1707    Ok(Value::Bool(matches))
1708}
1709
1710pub(crate) fn namespace_registry() -> Result<NamespaceRegistry<Value>, String> {
1711    ACTIVE_NAMESPACES
1712        .with(|active| active.borrow().clone())
1713        .ok_or_else(|| "namespace runtime is unavailable".into())
1714}
1715
1716/// Returns a fresh evaluator environment for the registry's current
1717/// namespace, including its qualified and aliased bindings.
1718pub(crate) fn current_namespace_environment() -> Result<HashMap<String, Value>, String> {
1719    let registry = namespace_registry()?;
1720    let mut environment = registry
1721        .current()
1722        .mappings()
1723        .into_iter()
1724        .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1725        .collect();
1726    refresh_namespace_environment(&registry, &mut environment);
1727    Ok(environment)
1728}
1729
1730/// Saves all unqualified evaluator bindings into the registry current namespace.
1731pub fn save_namespace_environment(
1732    registry: &NamespaceRegistry<Value>,
1733    env: &mut HashMap<String, Value>,
1734) {
1735    let namespace = registry.current();
1736    let namespace_name = namespace.name().as_str().to_owned();
1737    let locals = env
1738        .iter()
1739        .filter(|(name, _)| !name.contains('/'))
1740        .map(|(name, value)| (name.clone(), value.clone()))
1741        .collect::<Vec<_>>();
1742    for (name, value) in locals {
1743        let path = format!("{namespace_name}/{name}");
1744        if matches!(&value, Value::Var(var) if
1745            (var.symbol().get_namespace().is_some()
1746                && var.symbol().get_namespace() != Some(namespace_name.as_str()))
1747                || var.symbol().as_str().starts_with("std.native.")
1748                || var.symbol().as_str().starts_with("std.protocol.")
1749        )
1750        {
1751            continue;
1752        }
1753        let var = match value {
1754            Value::Var(var) if var.symbol().as_str() == path => var,
1755            Value::Var(var) => var.requalify(&path),
1756            value => namespace.intern(&name, value),
1757        };
1758        namespace.map_var(crate::lang::data::Symbol::parse(&name), var.clone());
1759        env.insert(name, Value::Var(var));
1760    }
1761}
1762
1763/// Rebuilds qualified and aliased bindings without changing local bindings.
1764pub fn refresh_namespace_environment(
1765    registry: &NamespaceRegistry<Value>,
1766    env: &mut HashMap<String, Value>,
1767) {
1768    env.retain(|name, _| !name.contains('/'));
1769    for namespace in registry.all() {
1770        for (_, var) in namespace.mappings() {
1771            env.insert(var.symbol().as_str().to_owned(), Value::Var(var));
1772        }
1773    }
1774    for (alias, namespace) in registry.current().aliases() {
1775        for (local, var) in namespace.mappings() {
1776            env.insert(
1777                format!("{}/{}", alias.as_str(), local.as_str()),
1778                Value::Var(var),
1779            );
1780        }
1781    }
1782}
1783
1784/// Saves the current namespace, selects name, and loads its bindings.
1785pub fn select_namespace_environment(
1786    registry: &NamespaceRegistry<Value>,
1787    env: &mut HashMap<String, Value>,
1788    name: &str,
1789) {
1790    save_namespace_environment(registry, env);
1791    let namespace = registry.set_current(name);
1792    *env = namespace
1793        .mappings()
1794        .into_iter()
1795        .map(|(name, var)| (name.as_str().to_owned(), Value::Var(var)))
1796        .collect();
1797    refresh_namespace_environment(registry, env);
1798}
1799
1800pub fn apply_global_aliases(registry: &NamespaceRegistry<Value>, namespace: &str) {
1801    let target = registry.find_or_create(namespace);
1802    for (alias, library) in registry.global_aliases() {
1803        if target.name() == &library {
1804            continue;
1805        }
1806        if let Some(source) = registry.find(library.as_str()) {
1807            target.alias(alias.as_str(), source);
1808        } else {
1809            target.lazy_alias(alias.as_str(), library.as_str());
1810        }
1811    }
1812}
1813
1814pub fn apply_global_imports(registry: &NamespaceRegistry<Value>, namespace: &str) {
1815    let target = registry.find_or_create(namespace);
1816    for (local, canonical) in registry.global_imports() {
1817        if target.resolve(&local).is_none() {
1818            if let Some(var) = registry.resolve(&canonical) {
1819                target.map_var(local, var);
1820            }
1821        }
1822    }
1823}
1824
1825/// Runs an evaluation with a registry available to protocol dispatch.
1826pub fn with_protocols<R>(registry: &ProtocolRegistry, operation: impl FnOnce() -> R) -> R {
1827    ACTIVE_PROTOCOLS.with(|active| {
1828        let previous = active.replace(Some(registry.clone()));
1829        let result = operation();
1830        active.replace(previous);
1831        result
1832    })
1833}
1834
1835pub fn with_package_catalog<R>(catalog: &PackageCatalog, operation: impl FnOnce() -> R) -> R {
1836    ACTIVE_PACKAGE_CATALOG.with(|active| {
1837        let previous = active.replace(Some(catalog.clone()));
1838        let result = operation();
1839        active.replace(previous);
1840        result
1841    })
1842}
1843
1844fn package_catalog() -> PackageCatalog {
1845    ACTIVE_PACKAGE_CATALOG.with(|active| active.borrow().clone().unwrap_or_default())
1846}
1847
1848/// Runs an evaluation through the selected runtime promise provider.
1849pub fn with_promise_provider<R>(
1850    provider: Rc<dyn PromiseProvider>,
1851    operation: impl FnOnce() -> R,
1852) -> R {
1853    ACTIVE_PROMISE_PROVIDER.with(|active| {
1854        let previous = active.replace(Some(provider));
1855        let result = operation();
1856        active.replace(previous);
1857        result
1858    })
1859}
1860
1861fn promise_provider() -> Rc<dyn PromiseProvider> {
1862    ACTIVE_PROMISE_PROVIDER.with(|active| {
1863        active
1864            .borrow()
1865            .clone()
1866            .unwrap_or_else(|| Rc::new(LocalPromiseProvider))
1867    })
1868}
1869/// Runs an evaluation through the selected runtime capability providers.
1870pub fn with_capability_providers<R>(
1871    file: Option<Rc<dyn FileProvider>>,
1872    socket: Option<Rc<dyn SocketProvider>>,
1873    process: bool,
1874    kernel: Option<Rc<KernelProvider>>,
1875    operation: impl FnOnce() -> R,
1876) -> R {
1877    ACTIVE_FILE_PROVIDER.with(|active_file| {
1878        ACTIVE_SOCKET_PROVIDER.with(|active_socket| {
1879            ACTIVE_KERNEL_PROVIDER.with(|active_kernel| {
1880                ACTIVE_PROCESS_ALLOWED.with(|active_process| {
1881                    let previous_file = active_file.replace(file);
1882                    let previous_socket = active_socket.replace(socket);
1883                    let previous_kernel = active_kernel.replace(kernel);
1884                    let previous_process = active_process.replace(process);
1885                    let result = operation();
1886                    active_file.replace(previous_file);
1887                    active_socket.replace(previous_socket);
1888                    active_kernel.replace(previous_kernel);
1889                    active_process.set(previous_process);
1890                    result
1891                })
1892            })
1893        })
1894    })
1895}
1896
1897pub type KernelProvider = dyn Fn(String, Vec<Value>) -> Result<Value, String>;
1898
1899fn kernel_provider(operation: &str) -> Result<Rc<KernelProvider>, String> {
1900    ACTIVE_KERNEL_PROVIDER.with(|active| {
1901        active
1902            .borrow()
1903            .clone()
1904            .ok_or_else(|| format!("std.native.Kernel/{operation} requires a kernel provider"))
1905    })
1906}
1907
1908fn file_provider(operation: &str) -> Result<Rc<dyn FileProvider>, String> {
1909    ACTIVE_FILE_PROVIDER.with(|active| {
1910        active
1911            .borrow()
1912            .clone()
1913            .ok_or_else(|| format!("{operation} is unsupported or file access is denied"))
1914    })
1915}
1916
1917fn socket_provider(operation: &str) -> Result<Rc<dyn SocketProvider>, String> {
1918    ACTIVE_SOCKET_PROVIDER.with(|active| {
1919        active
1920            .borrow()
1921            .clone()
1922            .ok_or_else(|| format!("{operation} is unsupported or network access is denied"))
1923    })
1924}
1925
1926pub(crate) fn native_capability_granted(capability: &str) -> bool {
1927    match capability {
1928        "kernel" | "sandbox" => ACTIVE_KERNEL_PROVIDER.with(|active| active.borrow().is_some()),
1929        "file" => ACTIVE_FILE_PROVIDER.with(|active| active.borrow().is_some()),
1930        "network" => ACTIVE_SOCKET_PROVIDER.with(|active| active.borrow().is_some()),
1931        "native-runtime" => ACTIVE_PROCESS_ALLOWED.get(),
1932        "host-call" => HOST_CALL_HANDLER.with(|active| active.borrow().is_some()),
1933        _ => false,
1934    }
1935}
1936
1937pub(crate) fn native_capability_error_value(
1938    native_type: &str,
1939    method: &str,
1940    capability: &str,
1941) -> Value {
1942    Value::ExceptionInfo(Rc::new(ExceptionInfo {
1943        message: format!(
1944            "std.native.{native_type}/{method} requires capability :{capability}"
1945        ),
1946        data: Box::new(Value::Map(
1947            [
1948                (
1949                    Value::Keyword("ex/code".into()),
1950                    Value::Keyword("native/capability-denied".into()),
1951                ),
1952                (
1953                    Value::Keyword("ex/class".into()),
1954                    Value::Keyword("ex.class/host".into()),
1955                ),
1956                (
1957                    Value::Keyword("native/type".into()),
1958                    Value::String(format!("std.native.{native_type}")),
1959                ),
1960                (
1961                    Value::Keyword("native/method".into()),
1962                    Value::String(method.into()),
1963                ),
1964                (
1965                    Value::Keyword("native/capability".into()),
1966                    Value::Keyword(capability.into()),
1967                ),
1968            ]
1969            .into_iter()
1970            .collect(),
1971        )),
1972        cause: None,
1973        provenance: Rc::new(RefCell::new(Default::default())),
1974    }))
1975}
1976
1977pub(crate) fn native_capability_denied(
1978    native_type: &str,
1979    method: &str,
1980    capability: &str,
1981) -> String {
1982    thrown_error(native_capability_error_value(native_type, method, capability))
1983}
1984
1985pub(crate) fn native_capability_denied_promise(
1986    native_type: &str,
1987    method: &str,
1988    capability: &str,
1989) -> Value {
1990    let promise = Promise::new();
1991    promise.reject_value(native_capability_error_value(native_type, method, capability));
1992    Value::Promise(promise)
1993}
1994
1995pub(crate) fn require_native_capability(
1996    native_type: &str,
1997    method: &str,
1998    capability: &str,
1999) -> Result<(), String> {
2000    native_capability_granted(capability)
2001        .then_some(())
2002        .ok_or_else(|| native_capability_denied(native_type, method, capability))
2003}
2004
2005fn require_process_access(operation: &str) -> Result<(), String> {
2006    ACTIVE_PROCESS_ALLOWED.with(|allowed| {
2007        allowed
2008            .get()
2009            .then_some(())
2010            .ok_or_else(|| {
2011                let method = operation
2012                    .strip_prefix("std.native.Process/")
2013                    .unwrap_or(operation);
2014                native_capability_denied("Process", method, "native-runtime")
2015            })
2016    })
2017}
2018
2019#[cfg(test)]
2020mod capability_profile_tests {
2021    use super::*;
2022    use std::collections::BTreeSet;
2023
2024    #[derive(Debug)]
2025    struct Profile {
2026        id: String,
2027        grants: BTreeSet<String>,
2028    }
2029
2030    fn profile_corpus() -> (Vec<String>, Vec<Profile>) {
2031        let source = include_str!("../../assets/native-capability-profiles-v1.edn");
2032        let root = read_edn(source).expect("capability profile corpus must parse");
2033        let format = field(&root, "format");
2034        assert_eq!(
2035            format,
2036            Value::String("hara.native/capability-profiles/v1".into())
2037        );
2038        let capabilities = keywords(field(&root, "capabilities"), "capabilities");
2039        let profiles = values(field(&root, "profiles"), "profiles")
2040            .into_iter()
2041            .map(|value| {
2042                let id = match field(&value, "id") {
2043                    Value::Keyword(id) => id,
2044                    _ => panic!("capability profile ids must be keywords"),
2045                };
2046                let grants = keywords(field(&value, "grants"), "profile grants")
2047                    .into_iter()
2048                    .collect();
2049                Profile {
2050                    id: id.as_str().to_owned(),
2051                    grants,
2052                }
2053            })
2054            .collect::<Vec<_>>();
2055        (capabilities, profiles)
2056    }
2057
2058    fn field(value: &Value, name: &str) -> Value {
2059        map_entries(value)
2060            .expect("capability profile records must be maps")
2061            .into_iter()
2062            .find_map(|(key, value)| {
2063                matches!(key, Value::Keyword(ref keyword) if keyword.as_str() == name)
2064                    .then_some(value)
2065            })
2066            .unwrap_or_else(|| panic!("capability profile record is missing :{name}"))
2067    }
2068
2069    fn values(value: Value, field: &str) -> Vec<Value> {
2070        match value {
2071            Value::Vector(values) => values.iter().cloned().collect(),
2072            Value::Tuple(values) => values.iter().cloned().collect(),
2073            _ => panic!("{field} must be a vector"),
2074        }
2075    }
2076
2077    fn keywords(value: Value, field: &str) -> Vec<String> {
2078        values(value, field)
2079            .into_iter()
2080            .map(|value| match value {
2081                Value::Keyword(keyword) => keyword.as_str().to_owned(),
2082                _ => panic!("{field} entries must be keywords"),
2083            })
2084            .collect()
2085    }
2086
2087    fn with_profile<R>(grants: &BTreeSet<String>, operation: impl FnOnce() -> R) -> R {
2088        let file = grants
2089            .contains("file")
2090            .then(|| Rc::new(NativeFileProvider::new(".")) as Rc<dyn FileProvider>);
2091        let socket = grants
2092            .contains("network")
2093            .then(|| Rc::new(NativeSocketProvider::default()) as Rc<dyn SocketProvider>);
2094        let kernel = grants
2095            .contains("kernel")
2096            .then(|| Rc::new(|_, _| Ok(Value::Nil)) as Rc<KernelProvider>);
2097        with_capability_providers(
2098            file,
2099            socket,
2100            grants.contains("native-runtime"),
2101            kernel,
2102            || {
2103                if grants.contains("host-call") {
2104                    with_host_calls(Rc::new(|_, _, _| Ok(Value::Nil)), operation)
2105                } else {
2106                    operation()
2107                }
2108            },
2109        )
2110    }
2111
2112    #[test]
2113    fn native_capability_profiles_are_shared_and_exact() {
2114        let (capabilities, profiles) = profile_corpus();
2115        assert_eq!(
2116            capabilities,
2117            [
2118                "kernel",
2119                "sandbox",
2120                "file",
2121                "network",
2122                "native-runtime",
2123                "host-call",
2124            ]
2125        );
2126        assert_eq!(
2127            profiles
2128                .iter()
2129                .map(|profile| profile.id.as_str())
2130                .collect::<Vec<_>>(),
2131            [
2132                "zero",
2133                "kernel-sandbox",
2134                "file",
2135                "network",
2136                "native-runtime",
2137                "host-call",
2138                "all"
2139            ]
2140        );
2141
2142        for profile in profiles {
2143            assert!(profile
2144                .grants
2145                .iter()
2146                .all(|grant| capabilities.contains(grant)));
2147            let observed = with_profile(&profile.grants, || {
2148                capabilities
2149                    .iter()
2150                    .filter(|capability| native_capability_granted(capability))
2151                    .cloned()
2152                    .collect::<BTreeSet<_>>()
2153            });
2154            assert_eq!(observed, profile.grants, "profile {}", profile.id);
2155
2156            with_profile(&profile.grants, || {
2157                for capability in &capabilities {
2158                    if profile.grants.contains(capability) {
2159                        require_native_capability("Profile", "probe", capability).unwrap();
2160                    } else {
2161                        let error =
2162                            require_native_capability("Profile", "probe", capability).unwrap_err();
2163                        assert!(error.contains("std.native.Profile/probe requires capability"));
2164                        assert!(error.contains(":native/capability-denied"));
2165                    }
2166                }
2167            });
2168        }
2169    }
2170}