Skip to main content

hara_wasm/
lib.rs

1#![allow(clippy::too_many_lines)] // Temporary compatibility facade during Java-port split.
2#[cfg(not(target_arch = "wasm32"))]
3pub mod asset;
4#[cfg(not(target_arch = "wasm32"))]
5pub mod cli_app;
6// Public embedding surface used by native hosts such as Hoplite. The module's
7// value, protocol, promise, and host-call types form the runtime integration ABI.
8pub mod core;
9pub mod extension;
10#[cfg(not(target_arch = "wasm32"))]
11pub mod extension_tool;
12pub mod hta;
13#[cfg(not(target_arch = "wasm32"))]
14pub mod identity_tool;
15#[cfg(feature = "evaluation-journal")]
16pub mod journal;
17mod json;
18pub mod kernel;
19pub mod lang;
20#[cfg(not(target_arch = "wasm32"))]
21pub mod native_cli;
22#[cfg(not(target_arch = "wasm32"))]
23mod native_extension;
24#[cfg(not(target_arch = "wasm32"))]
25pub mod native_link;
26#[cfg(not(target_arch = "wasm32"))]
27mod native_process;
28#[cfg(not(target_arch = "wasm32"))]
29pub mod package;
30#[cfg(not(target_arch = "wasm32"))]
31mod process_extension;
32#[cfg(not(target_arch = "wasm32"))]
33pub mod project;
34#[cfg(not(target_arch = "wasm32"))]
35pub mod resp;
36pub mod snapshot;
37#[cfg(not(target_arch = "wasm32"))]
38pub mod snapshot_tool;
39#[cfg(not(target_arch = "wasm32"))]
40pub mod tap;
41pub mod task;
42// Experimental staged bytecode VM (issue #195). Non-default feature; the
43// default evaluator is untouched.
44#[cfg(feature = "tracing-jit")]
45pub mod jit;
46#[cfg(feature = "bytecode-vm")]
47pub mod vm;
48#[cfg(not(target_arch = "wasm32"))]
49pub mod wasmtime_provider;
50#[cfg(feature = "whole-wasm")]
51pub mod whole_wasm;
52use crate::kernel::Form;
53use crate::lang::protocol::INamespaced;
54use std::cell::RefCell;
55use std::collections::{HashMap, HashSet};
56use std::rc::Rc;
57
58/// Builds the core namespace registry used by native embedding hosts.
59///
60/// Hosts receive the same primitive values and protocol wiring as Hara's core
61/// runtime without depending on crate-private bootstrap helpers.
62pub fn embedding_namespace_registry() -> kernel::NamespaceRegistry<core::Value> {
63    let namespaces = kernel::NamespaceRegistry::new("user");
64    let foundation = namespaces.find_or_create("std.foundation");
65    for (name, value) in core::exception_function_values() {
66        foundation.intern(name, value);
67    }
68    for (name, protocol) in core::foundation_protocol_values() {
69        foundation.intern(&name, protocol.clone());
70        namespaces
71            .find_or_create(core::builtin_protocol_namespace(&name))
72            .intern(name, protocol);
73    }
74    for (namespace, name, method) in core::builtin_protocol_method_values() {
75        namespaces.find_or_create(namespace).intern(name, method);
76    }
77    for (name, descriptor) in core::native_type_values() {
78        let canonical_name = format!("std.native.{name}");
79        let var = foundation.intern(&canonical_name, descriptor);
80        foundation.map_var(lang::data::Symbol::parse(&name), var);
81        namespaces.find_or_create(canonical_name);
82    }
83    core::refer_startup_defaults(&namespaces, "user");
84    namespaces
85}
86use wasm_bindgen::prelude::*;
87
88include!(concat!(env!("OUT_DIR"), "/embedded_hal.rs"));
89
90const EAGER_HAL_RESOURCES: &[&str] = &[
91    "std.foundation.string",
92    "std.foundation.promise",
93    "std.foundation.bytes",
94    "std.foundation.coroutine",
95    "std.foundation.file",
96    "std.foundation.host",
97    "std.foundation.socket",
98    "std.foundation.os",
99    "std.foundation.edn",
100    "std.foundation.json",
101];
102
103fn ignore_socket_event(_event: core::SocketEvent) {}
104
105#[wasm_bindgen(start)]
106pub fn init_wasm() {
107    #[cfg(target_arch = "wasm32")]
108    console_error_panic_hook::set_once();
109}
110
111#[wasm_bindgen]
112pub struct PromiseHandle {
113    promise: core::Promise,
114}
115
116#[wasm_bindgen]
117impl PromiseHandle {
118    fn from_promise(promise: core::Promise) -> PromiseHandle {
119        PromiseHandle { promise }
120    }
121
122    #[wasm_bindgen(constructor)]
123    pub fn new() -> PromiseHandle {
124        PromiseHandle {
125            promise: core::Promise::new(),
126        }
127    }
128
129    pub fn state(&self) -> String {
130        match self.promise.state() {
131            core::PromiseState::Pending => "pending".into(),
132            core::PromiseState::Fulfilled(_) => "fulfilled".into(),
133            core::PromiseState::Rejected(_) => "rejected".into(),
134        }
135    }
136
137    pub fn resolve(&self, value: &str) -> bool {
138        self.promise.resolve(core::Value::String(value.into()))
139    }
140
141    pub fn reject(&self, error: &str) -> bool {
142        self.promise.reject(error)
143    }
144
145    pub fn adopt(&self, other: &PromiseHandle) -> bool {
146        self.promise.adopt(&other.promise)
147    }
148
149    pub fn value(&self) -> Result<String, JsValue> {
150        match self.promise.state() {
151            core::PromiseState::Pending => Err(JsValue::from_str("promise is pending")),
152            core::PromiseState::Fulfilled(value) => Ok(value.display()),
153            core::PromiseState::Rejected(error) => Err(JsValue::from_str(&error.message())),
154        }
155    }
156}
157
158#[wasm_bindgen]
159pub struct Runtime {
160    env: HashMap<String, core::Value>,
161    protocols: core::ProtocolRegistry,
162    extensions: core::ExtensionRegistry,
163    wasm_extensions: HashMap<String, extension::WasmExtension>,
164    providers: core::ProviderRegistry,
165    resources: HashMap<String, String>,
166    loaded_resources: HashSet<String>,
167    halc_schema_definitions: HashMap<String, Form>,
168    halc_function_schemas: HashMap<String, Form>,
169    halc_schema_types: HashMap<String, kernel::SchemaType>,
170    halc_function_types: HashMap<String, kernel::SchemaType>,
171    halc_inferred_function_types: HashMap<String, kernel::SchemaType>,
172    namespace_registry: kernel::NamespaceRegistry<core::Value>,
173    macros: Rc<RefCell<HashMap<(String, String), Rc<core::Function>>>>,
174    generated_configs: HashMap<String, kernel::GeneratedNamespaceConfig>,
175    #[cfg(feature = "evaluation-journal")]
176    next_journal_id: u64,
177    #[cfg(target_arch = "wasm32")]
178    host_handler: Option<js_sys::Function>,
179    #[cfg(not(target_arch = "wasm32"))]
180    native_host_handler:
181        Option<Rc<dyn Fn(String, String, Vec<core::Value>) -> Result<core::Value, String>>>,
182    #[cfg(not(target_arch = "wasm32"))]
183    extension_roots: Vec<std::path::PathBuf>,
184}
185
186/// A process-local kernel that multiplexes isolated evaluator sessions.
187///
188/// Raw HTA exposes the same lifecycle over its wire targets; this native
189/// facade keeps embedding hosts from treating a `Runtime` as the process
190/// boundary when several independent sessions can share one kernel.
191pub struct SessionKernel {
192    sessions: HashMap<String, Session>,
193    resources: HashMap<String, String>,
194    mounts: HashMap<u64, FilesystemMount>,
195    session_mounts: HashMap<String, u64>,
196    next_mount_id: u64,
197}
198
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub struct SessionMetadata {
201    pub name: String,
202    pub namespace: String,
203    pub state: &'static str,
204    pub filesystem: Option<u64>,
205}
206
207/// An isolated, named execution context owned by a [`SessionKernel`].
208pub struct Session {
209    name: String,
210    runtime: Runtime,
211    active: bool,
212    filesystem: Option<u64>,
213}
214
215impl Session {
216    fn new(name: &str, runtime: Runtime) -> Self {
217        Self {
218            name: name.into(),
219            runtime,
220            active: true,
221            filesystem: None,
222        }
223    }
224
225    fn ensure_active(&self) -> Result<(), String> {
226        if self.active {
227            Ok(())
228        } else {
229            Err(format!("SESSION_CLOSED {}", self.name))
230        }
231    }
232
233    pub fn eval(&mut self, source: &str) -> Result<String, String> {
234        self.ensure_active()?;
235        self.runtime.eval_transfer_text(source)
236    }
237
238    pub fn current_namespace(&self) -> String {
239        self.runtime.current_namespace()
240    }
241
242    #[cfg(not(target_arch = "wasm32"))]
243    pub fn install_native_socket_provider(&mut self) {
244        self.runtime.install_native_socket_provider();
245    }
246
247    #[cfg(not(target_arch = "wasm32"))]
248    pub fn install_native_process_provider(&mut self) {
249        self.runtime.install_native_process_provider();
250    }
251}
252
253impl crate::lang::protocol::IContext<&str> for Session {
254    type Output = Result<String, String>;
255
256    fn call(&mut self, source: &str) -> Self::Output {
257        self.eval(source)
258    }
259}
260
261impl crate::lang::protocol::IComponent for Session {
262    type Metadata = SessionMetadata;
263
264    fn props(&self) -> Self::Metadata {
265        SessionMetadata {
266            name: self.name.clone(),
267            namespace: self.current_namespace(),
268            state: if self.active { "idle" } else { "closed" },
269            filesystem: self.filesystem,
270        }
271    }
272
273    fn status(&self) -> Self::Metadata {
274        self.props()
275    }
276
277    fn started(&self) -> bool {
278        self.active
279    }
280
281    fn stopped(&self) -> bool {
282        !self.active
283    }
284
285    fn start(&mut self) {
286        assert!(self.active, "cannot restart closed session {}", self.name);
287    }
288
289    fn stop(&mut self) {
290        self.active = false;
291        self.filesystem = None;
292        self.runtime.providers.set_file(None);
293    }
294}
295
296impl<'a> crate::lang::protocol::IApplicable<Session, &'a str> for Session {
297    type Output = Result<String, String>;
298
299    fn apply_in(&self, runtime: &mut Session, source: &'a str) -> Self::Output {
300        self.ensure_active()?;
301        crate::lang::protocol::IContext::call(runtime, source)
302    }
303
304    fn apply_default(&mut self) -> &mut Session {
305        self
306    }
307
308    fn transform_in(&self, _runtime: &Session, source: &'a str) -> &'a str {
309        source
310    }
311
312    fn transform_out(
313        &self,
314        _runtime: &Session,
315        _source: &'a str,
316        value: Self::Output,
317    ) -> Self::Output {
318        value
319    }
320}
321
322impl<'a> crate::lang::protocol::IInvokeIn<Session, &'a str> for Session {
323    type Output = Result<String, String>;
324
325    fn invoke_in(&self, context: &mut Session, source: &'a str) -> Self::Output {
326        self.ensure_active()?;
327        crate::lang::protocol::IContext::call(context, source)
328    }
329}
330
331struct FilesystemMount {
332    provider: Rc<dyn core::FileProvider>,
333    kind: &'static str,
334    key: String,
335    attachments: usize,
336}
337
338impl Default for SessionKernel {
339    fn default() -> Self {
340        Self::new()
341    }
342}
343
344impl SessionKernel {
345    pub fn new() -> Self {
346        Self {
347            sessions: HashMap::from([("ROOT".into(), Session::new("ROOT", Runtime::new()))]),
348            resources: HashMap::new(),
349            mounts: HashMap::new(),
350            session_mounts: HashMap::new(),
351            next_mount_id: 1,
352        }
353    }
354
355    pub fn create_session(&mut self, name: &str) -> Result<(), String> {
356        validate_session_name(name)?;
357        if self.sessions.contains_key(name) {
358            return Err(format!("SESSION_EXISTS {name}"));
359        }
360        let mut runtime = Runtime::new();
361        for (resource, source) in &self.resources {
362            runtime.register_resource(resource, source);
363        }
364        self.sessions
365            .insert(name.into(), Session::new(name, runtime));
366        Ok(())
367    }
368
369    pub fn session_names(&self) -> Vec<String> {
370        let mut names = self.sessions.keys().cloned().collect::<Vec<_>>();
371        names.sort();
372        names
373    }
374
375    pub fn session(&self, name: &str) -> Result<&Session, String> {
376        self.sessions
377            .get(name)
378            .ok_or_else(|| format!("NO_SESSION {name}"))
379    }
380
381    pub fn session_mut(&mut self, name: &str) -> Result<&mut Session, String> {
382        self.sessions
383            .get_mut(name)
384            .ok_or_else(|| format!("NO_SESSION {name}"))
385    }
386
387    pub fn session_namespace(&self, session: &str) -> Result<String, String> {
388        self.sessions
389            .get(session)
390            .map(Session::current_namespace)
391            .ok_or_else(|| format!("NO_SESSION {session}"))
392    }
393
394    pub fn eval(&mut self, session: &str, source: &str) -> Result<String, String> {
395        self.sessions
396            .get_mut(session)
397            .ok_or_else(|| format!("NO_SESSION {session}"))?
398            .eval(source)
399    }
400
401    pub fn register_resource(&mut self, name: &str, source: &str) {
402        self.resources.insert(name.into(), source.into());
403        for session in self.sessions.values_mut() {
404            session.runtime.register_resource(name, source);
405        }
406    }
407
408    pub fn create_memory_filesystem(&mut self, root: &str) -> u64 {
409        self.create_filesystem(Rc::new(core::MemoryFileProvider::new(root)), "memory", root)
410    }
411
412    #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
413    pub fn create_native_filesystem(&mut self, root: &str) -> u64 {
414        self.create_filesystem(Rc::new(core::NativeFileProvider::new(root)), "native", root)
415    }
416
417    fn create_filesystem(
418        &mut self,
419        provider: Rc<dyn core::FileProvider>,
420        kind: &'static str,
421        key: &str,
422    ) -> u64 {
423        let id = self.next_mount_id;
424        self.next_mount_id = self
425            .next_mount_id
426            .checked_add(1)
427            .expect("filesystem mount identifiers exhausted");
428        self.mounts.insert(
429            id,
430            FilesystemMount {
431                provider,
432                kind,
433                key: key.into(),
434                attachments: 0,
435            },
436        );
437        id
438    }
439
440    pub fn attach_filesystem(&mut self, session: &str, mount_id: u64) -> Result<(), String> {
441        if !self.sessions.contains_key(session) {
442            return Err(format!("NO_SESSION {session}"));
443        }
444        let provider = self
445            .mounts
446            .get(&mount_id)
447            .ok_or_else(|| format!("NO_FILESYSTEM {mount_id}"))?
448            .provider
449            .clone();
450        if self.session_mounts.get(session) == Some(&mount_id) {
451            return Ok(());
452        }
453        self.detach_filesystem(session)?;
454        self.mounts.get_mut(&mount_id).unwrap().attachments += 1;
455        self.session_mounts.insert(session.into(), mount_id);
456        let session = self.sessions.get_mut(session).unwrap();
457        session.runtime.providers.set_file(Some(provider));
458        session.filesystem = Some(mount_id);
459        Ok(())
460    }
461
462    pub fn detach_filesystem(&mut self, session: &str) -> Result<(), String> {
463        let runtime = self
464            .sessions
465            .get_mut(session)
466            .ok_or_else(|| format!("NO_SESSION {session}"))?;
467        runtime.runtime.providers.set_file(None);
468        runtime.filesystem = None;
469        if let Some(mount_id) = self.session_mounts.remove(session) {
470            if let Some(mount) = self.mounts.get_mut(&mount_id) {
471                mount.attachments = mount.attachments.saturating_sub(1);
472            }
473        }
474        Ok(())
475    }
476
477    pub fn filesystem(&self, session: &str) -> Option<u64> {
478        self.session_mounts.get(session).copied()
479    }
480
481    pub fn filesystem_info(&self, mount_id: u64) -> Result<(&str, &str, usize), String> {
482        self.mounts
483            .get(&mount_id)
484            .map(|mount| (mount.kind, mount.key.as_str(), mount.attachments))
485            .ok_or_else(|| format!("NO_FILESYSTEM {mount_id}"))
486    }
487
488    pub fn close_filesystem(&mut self, mount_id: u64) -> Result<(), String> {
489        let mount = self
490            .mounts
491            .get(&mount_id)
492            .ok_or_else(|| format!("NO_FILESYSTEM {mount_id}"))?;
493        if mount.attachments != 0 {
494            return Err(format!("FILESYSTEM_ATTACHED {mount_id}"));
495        }
496        self.mounts.remove(&mount_id);
497        Ok(())
498    }
499
500    pub fn close_session(&mut self, name: &str) -> Result<(), String> {
501        validate_session_name(name)?;
502        if name == "ROOT" {
503            return Err("ROOT_CANNOT_CLOSE".into());
504        }
505        if !self.sessions.contains_key(name) {
506            return Err(format!("NO_SESSION {name}"));
507        }
508        self.detach_filesystem(name)?;
509        if let Some(mut session) = self.sessions.remove(name) {
510            crate::lang::protocol::IComponent::stop(&mut session);
511        }
512        Ok(())
513    }
514}
515
516fn validate_session_name(name: &str) -> Result<(), String> {
517    if name.is_empty()
518        || !name
519            .bytes()
520            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
521    {
522        return Err("INVALID_SESSION_NAME".into());
523    }
524    Ok(())
525}
526
527/// The root Foundation surface deliberately contains only the iterator core.
528/// Native iterator mechanics must enter through the `Iter/*` type alias, so
529/// reject legacy unqualified call heads before namespace rewriting canonicalizes
530/// an alias to its backing method name.
531fn reject_legacy_iterator_calls(form: &Form) -> Result<(), String> {
532    const LEGACY: &[&str] = &[
533        "iter-has?",
534        "iter-finite?",
535        "iter-materialize",
536        "iter-close",
537        "iter-map",
538        "iter-filter",
539        "iter-take-while",
540        "iter-drop-while",
541        "iter-mapcat",
542        "iter-keep",
543        "iter-interpose",
544        "iter-interleave",
545        "iter-every?",
546        "iter-any?",
547        "iter-take",
548        "iter-drop",
549        "iter-zip",
550        "iter-cycle",
551        "iter-partition-pair",
552        "iter-partition-all",
553        "iter-partition",
554        "iter-range",
555        "iter-constantly",
556        "iter-repeatedly",
557        "iter-iterate",
558    ];
559    match form {
560        Form::List(values) => {
561            if let Some(Form::Symbol(name)) = values.first() {
562                if LEGACY.contains(&name.as_str()) {
563                    return Err(format!("unbound symbol: {name}"));
564                }
565                if name == "quote" {
566                    return Ok(());
567                }
568            }
569            for value in values {
570                reject_legacy_iterator_calls(value)?;
571            }
572        }
573        Form::Vector(values) | Form::Set(values) => {
574            for value in values {
575                reject_legacy_iterator_calls(value)?;
576            }
577        }
578        Form::Map(entries) => {
579            for (key, value) in entries {
580                reject_legacy_iterator_calls(key)?;
581                reject_legacy_iterator_calls(value)?;
582            }
583        }
584        Form::Tagged(_, value) | Form::Metadata(_, value) => reject_legacy_iterator_calls(value)?,
585        _ => {}
586    }
587    Ok(())
588}
589
590#[wasm_bindgen]
591impl Runtime {
592    fn empty() -> Runtime {
593        let namespace_registry = kernel::NamespaceRegistry::new("user");
594        let foundation = namespace_registry.find_or_create("std.foundation");
595        foundation.intern_with_origin(
596            "list",
597            core::native_variadic_function("list", |values| Ok(core::Value::List(values.into()))),
598            kernel::VarOrigin::RustLibrary,
599        );
600        for (name, value) in core::exception_function_values() {
601            foundation.intern_with_origin(name, value, kernel::VarOrigin::RustLibrary);
602        }
603        for (name, value) in core::basic_function_values() {
604            foundation.intern_with_origin(name, value, kernel::VarOrigin::RustLibrary);
605        }
606        for (name, protocol) in core::foundation_protocol_values() {
607            foundation.intern(&name, protocol.clone());
608            let namespace =
609                namespace_registry.find_or_create(core::builtin_protocol_namespace(&name));
610            namespace.intern(name, protocol);
611        }
612        for (namespace, name, method) in core::builtin_protocol_method_values() {
613            namespace_registry
614                .find_or_create(namespace)
615                .intern(name, method);
616        }
617        let native = namespace_registry.find_or_create("std.native");
618        for (name, descriptor) in core::native_type_values() {
619            let canonical_name = format!("std.native.{name}");
620            let var = foundation.intern(&canonical_name, descriptor);
621            foundation.map_var(crate::lang::data::Symbol::parse(&name), var.clone());
622            native.map_var(crate::lang::data::Symbol::parse(&name), var);
623            namespace_registry.find_or_create(canonical_name);
624        }
625        for (native_type, methods) in core::NATIVE_TYPES {
626            let namespace_name = format!("std.native.{native_type}");
627            let namespace = namespace_registry.find_or_create(&namespace_name);
628            for method in *methods {
629                let dispatch_name = match *native_type {
630                    "Iter" => (*method).to_owned(),
631                    "String" => format!("str/{method}"),
632                    _ => format!("{namespace_name}/{method}"),
633                };
634                namespace.intern_with_origin(
635                    *method,
636                    core::structural_function_value(dispatch_name),
637                    kernel::VarOrigin::RuntimePrimitive,
638                );
639            }
640        }
641        Runtime {
642            env: HashMap::new(),
643            protocols: core::ProtocolRegistry::core(),
644            extensions: core::ExtensionRegistry::new(),
645            wasm_extensions: HashMap::new(),
646            providers: core::ProviderRegistry::new(),
647            resources: HashMap::new(),
648            loaded_resources: HashSet::new(),
649            halc_schema_definitions: HashMap::new(),
650            halc_function_schemas: HashMap::new(),
651            halc_schema_types: HashMap::new(),
652            halc_function_types: HashMap::new(),
653            halc_inferred_function_types: HashMap::new(),
654            namespace_registry,
655            macros: Rc::new(RefCell::new(HashMap::new())),
656            generated_configs: HashMap::from([(
657                "user".into(),
658                kernel::GeneratedNamespaceConfig::defaults(),
659            )]),
660            #[cfg(feature = "evaluation-journal")]
661            next_journal_id: 1,
662            #[cfg(target_arch = "wasm32")]
663            host_handler: None,
664            #[cfg(not(target_arch = "wasm32"))]
665            native_host_handler: None,
666            #[cfg(not(target_arch = "wasm32"))]
667            extension_roots: native_extension::configured_roots(),
668        }
669    }
670
671    #[wasm_bindgen(constructor)]
672    pub fn new() -> Runtime {
673        let mut runtime = Runtime::empty();
674        runtime
675            .bootstrap_foundation()
676            .expect("embedded std.foundation fallback must be valid");
677        runtime
678    }
679
680    /// Creates the portable L0 evaluator without loading the language-level
681    /// foundation. This is useful for small embedded surfaces whose commands
682    /// only require core forms and should become interactive immediately.
683    pub fn core() -> Runtime {
684        let mut runtime = Runtime::empty();
685        runtime.refer_foundation_into("user");
686        runtime.use_namespace("user");
687        runtime
688    }
689
690    #[cfg(feature = "bytecode-vm")]
691    pub(crate) fn prepare_foundation_bytecode(&mut self) {
692        let foundation = self.namespace_registry.find_or_create("std.foundation");
693        for name in core::bytecode_callable_names() {
694            let symbol = crate::lang::data::Symbol::parse(name);
695            if foundation.resolve(&symbol).is_none() {
696                foundation.intern_with_origin(
697                    name,
698                    core::structural_function_value(name),
699                    kernel::VarOrigin::RuntimePrimitive,
700                );
701            }
702        }
703    }
704
705    #[cfg(not(feature = "bytecode-vm"))]
706    fn install_structural_primitives(&mut self) {
707        self.install_structural_primitives_into("std.foundation");
708    }
709
710    fn install_structural_primitives_into(&mut self, namespace: &str) {
711        let target = self.namespace_registry.find_or_create(namespace);
712        for name in core::structural_callable_names() {
713            let symbol = crate::lang::data::Symbol::parse(name);
714            if target.resolve(&symbol).is_none() {
715                target.intern_with_origin(
716                    name,
717                    core::structural_function_value(name),
718                    kernel::VarOrigin::RuntimePrimitive,
719                );
720            }
721        }
722    }
723
724    fn refer_native_types_into(&mut self, namespace: &str) {
725        let target = self.namespace_registry.find_or_create(namespace);
726        for (protocol, _) in core::FOUNDATION_PROTOCOLS {
727            let protocol_namespace = core::builtin_protocol_namespace(protocol);
728            if let Some(source) = self.namespace_registry.find(&protocol_namespace) {
729                target.alias(protocol, source);
730            }
731        }
732        for (native_type, _) in core::NATIVE_TYPES {
733            let native_namespace = format!("std.native.{native_type}");
734            if let Some(source) = self.namespace_registry.find(&native_namespace) {
735                target.alias(*native_type, source);
736            }
737        }
738        if let Some(native) = self.namespace_registry.find("std.native") {
739            for (name, var) in native.mappings() {
740                if target.resolve(&name).is_none() {
741                    target.map_var(name.clone(), var.clone());
742                }
743                let canonical =
744                    crate::lang::data::Symbol::parse(&format!("std.native.{}", name.as_str()));
745                if target.resolve(&canonical).is_none() {
746                    target.map_var(canonical, var);
747                }
748            }
749        }
750    }
751
752    fn refer_foundation_into(&mut self, namespace: &str) {
753        self.refer_native_types_into(namespace);
754        let target = self.namespace_registry.find_or_create(namespace);
755        if namespace == "std.foundation" {
756            return;
757        }
758        let Some(foundation) = self.namespace_registry.find("std.foundation") else {
759            return;
760        };
761        for (name, var) in foundation.mappings() {
762            if target.resolve(&name).is_none() {
763                target.map_var(name, var);
764            }
765        }
766    }
767
768    fn bootstrap_foundation(&mut self) -> Result<(), String> {
769        for &(name, _, source) in EMBEDDED_HAL_RESOURCES {
770            self.register_resource(name, source);
771        }
772        #[cfg(feature = "bytecode-vm")]
773        {
774            vm::eval_bytecode_bundle(self, include_bytes!("../assets/std.foundation.hbb"))?;
775            self.loaded_resources.insert("std.foundation".into());
776            for &name in EAGER_HAL_RESOURCES {
777                self.loaded_resources.insert(name.into());
778            }
779        }
780        #[cfg(not(feature = "bytecode-vm"))]
781        {
782            let foundation = self
783                .resources
784                .get("std.foundation")
785                .cloned()
786                .ok_or_else(|| "embedded HAL catalog is missing std.foundation".to_owned())?;
787            core::with_definition_origin(kernel::VarOrigin::HalFallback, || {
788                self.eval_text(&foundation)
789            })?;
790            self.install_structural_primitives();
791            self.loaded_resources.insert("std.foundation".into());
792        }
793        let json = self.namespace_registry.find_or_create("std.native.Json");
794        json.intern(
795            "read",
796            core::native_function("std.native.Json/read", 1, |arguments| {
797                match arguments.as_slice() {
798                    [core::Value::String(source)] => json::read(source),
799                    _ => Err("json/read expects a string".into()),
800                }
801            }),
802        );
803        json.intern(
804            "write",
805            core::native_function("std.native.Json/write", 1, |arguments| {
806                json::write(&arguments[0]).map(core::Value::String)
807            }),
808        );
809        json.intern(
810            "pretty",
811            core::native_function("std.native.Json/pretty", 2, |arguments| {
812                if core::map_entries(&arguments[1]).is_none() {
813                    return Err("json/pretty expects an options map".into());
814                }
815                json::write_pretty(&arguments[0]).map(core::Value::String)
816            }),
817        );
818        #[cfg(not(feature = "bytecode-vm"))]
819        for &name in EAGER_HAL_RESOURCES {
820            let source = self
821                .resources
822                .get(name)
823                .cloned()
824                .ok_or_else(|| format!("embedded HAL catalog is missing {name}"))?;
825            core::with_definition_origin(kernel::VarOrigin::HalFallback, || {
826                self.eval_text(&source)
827            })?;
828            self.loaded_resources.insert(name.into());
829        }
830        self.use_namespace("std.foundation");
831        self.refer_foundation_into("user");
832        self.use_namespace("user");
833        Ok(())
834    }
835
836    fn eval_text_mode(&mut self, source: &str, traced: bool) -> Result<String, String> {
837        self.eval_value_mode(source, traced)
838            .map(|result| result.display())
839    }
840
841    fn eval_value_mode(&mut self, source: &str, traced: bool) -> Result<core::Value, String> {
842        self.refresh_qualified_bindings();
843        let forms = kernel::parse_forms(source)?;
844        let result = self.eval_forms(forms, traced)?;
845        self.save_namespace();
846        self.refresh_qualified_bindings();
847        Ok(result)
848    }
849
850    fn eval_transfer_text(&mut self, source: &str) -> Result<String, String> {
851        self.refresh_qualified_bindings();
852        let forms = kernel::parse_forms(source)?;
853        let result = self.eval_forms(forms, false)?;
854        self.save_namespace();
855        self.refresh_qualified_bindings();
856        if !core::session_transferable(&result) {
857            return Err(format!(
858                "SESSION_TRANSFER_REJECTED {}",
859                core::portable_type_name(&result)
860            ));
861        }
862        Ok(result.display())
863    }
864
865    pub fn eval_halc(&mut self, bytes: &[u8]) -> Result<String, String> {
866        self.refresh_qualified_bindings();
867        let module = kernel::halc::decode_halc(bytes)?;
868        let schemas = module.schemas;
869        let result = self.eval_forms(module.forms, false)?;
870        self.halc_schema_definitions.extend(schemas.definitions);
871        self.halc_function_schemas.extend(schemas.functions);
872        self.halc_schema_types.extend(schemas.definition_types);
873        self.halc_function_types.extend(schemas.function_types);
874        self.save_namespace();
875        self.refresh_qualified_bindings();
876        Ok(result.display())
877    }
878
879    fn eval_forms(&mut self, forms: Vec<Form>, traced: bool) -> Result<core::Value, String> {
880        let mut result = core::Value::Nil;
881        for form in forms {
882            if let Form::List(values) = &form {
883                if matches!(values.first(), Some(Form::Symbol(name)) if name == "ns") {
884                    let name = match values.get(1) {
885                        Some(Form::Symbol(name)) if !name.contains('/') => name.clone(),
886                        _ => return Err("ns expects an unqualified namespace symbol".into()),
887                    };
888                    #[cfg(not(target_arch = "wasm32"))]
889                    let roots = self.extension_roots.clone();
890                    let config =
891                        kernel::GeneratedNamespaceConfig::configure_with(&values[2..], |target| {
892                            if self.namespace_registry.find(target).is_some()
893                                || self.resources.contains_key(target)
894                                || self.wasm_extensions.contains_key(target)
895                            {
896                                return true;
897                            }
898                            #[cfg(not(target_arch = "wasm32"))]
899                            {
900                                return native_extension::package_exists(target, &roots);
901                            }
902                            #[cfg(target_arch = "wasm32")]
903                            false
904                        })?;
905                    for target in config.required_namespaces() {
906                        if self.resources.contains_key(target)
907                            || self.loaded_resources.contains(target)
908                        {
909                            continue;
910                        }
911                        if target == "std.foundation"
912                            || target.starts_with("std.lib.")
913                            || target.starts_with("std.foundation.")
914                        {
915                            continue;
916                        }
917                        #[cfg(not(target_arch = "wasm32"))]
918                        self.install_discovered_extension(target)?;
919                        self.load_wasm_extension_namespace(target)?;
920                    }
921
922                    let registry_before = self.namespace_registry.snapshot();
923                    let environment_before = self.env.clone();
924                    let macros_before = self.macros.borrow().clone();
925                    let configs_before = self.generated_configs.clone();
926                    let loaded_before = self.loaded_resources.clone();
927                    self.generated_configs.insert(name.clone(), config);
928                    self.use_namespace(&name);
929                    let foundation_bootstrap_child = name.starts_with("std.foundation.");
930                    let require_specs = values[2..]
931                        .iter()
932                        .flat_map(|clause| match clause {
933                            Form::List(items)
934                                if matches!(items.first(), Some(Form::Keyword(key)) if key == "require") =>
935                            {
936                                items[1..].to_vec()
937                            }
938                            Form::List(items)
939                                if matches!(items.first(), Some(Form::Keyword(key)) if key == "use") =>
940                            {
941                                items[1..]
942                                    .iter()
943                                    .cloned()
944                                    .map(|target| Form::Vector(vec![target]))
945                                    .collect()
946                            }
947                            _ => Vec::new(),
948                        })
949                        // std.foundation is the host bootstrap namespace. Its
950                        // child HAL libraries are rewritten against the
951                        // catalog while it is still being assembled, so they
952                        // must not recursively require the partially-built
953                        // namespace through the ordinary module loader.
954                        .filter(|spec| {
955                            !foundation_bootstrap_child
956                                || !matches!(spec,
957                                Form::Vector(items)
958                                    if matches!(items.first(), Some(Form::Symbol(target)) if target == "std.foundation"))
959                        })
960                        .collect::<Vec<_>>();
961                    if !require_specs.is_empty() {
962                        let require_form = Form::List(
963                            std::iter::once(Form::Symbol("require".into()))
964                                .chain(require_specs)
965                                .collect(),
966                        );
967                        if let Err(error) = self.eval_form(require_form, traced) {
968                            self.namespace_registry.restore(registry_before);
969                            self.env = environment_before;
970                            *self.macros.borrow_mut() = macros_before;
971                            self.generated_configs = configs_before;
972                            self.loaded_resources = loaded_before;
973                            return Err(error);
974                        }
975                        let config = self
976                            .generated_configs
977                            .get(&name)
978                            .expect("ns config was installed");
979                        self.sync_generated_aliases(config);
980                    }
981                    result = core::Value::Nil;
982                    continue;
983                }
984            }
985            if let Form::List(values) = &form {
986                if matches!(values.first(), Some(Form::Symbol(name)) if name == "require") {
987                    let current = self.current_namespace();
988                    let mut config = self
989                        .generated_configs
990                        .get(&current)
991                        .cloned()
992                        .unwrap_or_else(kernel::GeneratedNamespaceConfig::defaults);
993                    {
994                        #[cfg(not(target_arch = "wasm32"))]
995                        let roots = self.extension_roots.clone();
996                        let available = |target: &str| {
997                            if self.namespace_registry.find(target).is_some()
998                                || self.resources.contains_key(target)
999                                || self.wasm_extensions.contains_key(target)
1000                            {
1001                                return true;
1002                            }
1003                            #[cfg(not(target_arch = "wasm32"))]
1004                            {
1005                                return native_extension::package_exists(target, &roots);
1006                            }
1007                            #[cfg(target_arch = "wasm32")]
1008                            false
1009                        };
1010                        for spec in &values[1..] {
1011                            config.apply_require(spec, &available)?;
1012                        }
1013                    }
1014                    self.sync_generated_aliases(&config);
1015                    self.generated_configs.insert(current, config);
1016                }
1017            }
1018            let config = self
1019                .generated_configs
1020                .get(&self.current_namespace())
1021                .cloned()
1022                .unwrap_or_else(kernel::GeneratedNamespaceConfig::defaults);
1023            reject_legacy_iterator_calls(&form)?;
1024            let resolved = config.rewrite(form);
1025            result = self.eval_form(resolved, traced)?;
1026            if matches!(result, core::Value::Recur(_)) {
1027                return Err("recur must be inside loop".into());
1028            }
1029            self.save_namespace();
1030            self.refresh_qualified_bindings();
1031        }
1032        self.save_namespace();
1033        self.refresh_qualified_bindings();
1034        Ok(result)
1035    }
1036
1037    fn eval_text(&mut self, source: &str) -> Result<String, String> {
1038        self.eval_text_mode(source, false)
1039    }
1040
1041    fn eval_form(&mut self, form: Form, traced: bool) -> Result<core::Value, String> {
1042        let namespace_source = self.namespace_source();
1043        if traced {
1044            return core::with_capability_providers(
1045                self.providers.file(),
1046                self.providers.socket(),
1047                self.providers.process(),
1048                || {
1049                    core::with_promise_provider(self.providers.promise(), || {
1050                        core::with_macros(self.macros.clone(), || {
1051                            core::with_namespace_registry(&self.namespace_registry, || {
1052                                core::with_namespace_source(namespace_source, || {
1053                                    core::with_protocols(&self.protocols, || {
1054                                        #[cfg(target_arch = "wasm32")]
1055                                        if let Some(handler) = &self.host_handler {
1056                                            let handler = handler.clone();
1057                                            return core::with_host_calls(
1058                                                host_call_bridge(handler),
1059                                                || core::eval_traced(&form, &mut self.env),
1060                                            );
1061                                        }
1062                                        #[cfg(not(target_arch = "wasm32"))]
1063                                        if let Some(handler) = &self.native_host_handler {
1064                                            return core::with_host_calls(handler.clone(), || {
1065                                                core::eval_traced(&form, &mut self.env)
1066                                            });
1067                                        }
1068                                        core::eval_traced(&form, &mut self.env)
1069                                    })
1070                                })
1071                            })
1072                        })
1073                    })
1074                },
1075            );
1076        }
1077        let env = self.env.clone();
1078        let (result, fiber) = core::with_capability_providers(
1079            self.providers.file(),
1080            self.providers.socket(),
1081            self.providers.process(),
1082            || {
1083                core::with_promise_provider(self.providers.promise(), || {
1084                    core::with_macros(self.macros.clone(), || {
1085                        core::with_namespace_registry(&self.namespace_registry, || {
1086                            core::with_namespace_source(namespace_source, || {
1087                                core::with_protocols(&self.protocols, || -> Result<(Result<core::Value, String>, core::EvalFiber), String> {
1088                                    let mut fiber =
1089                                        core::EvalFiber::start_forms(vec![form], env)?;
1090                                    #[cfg(target_arch = "wasm32")]
1091                                    if let Some(handler) = &self.host_handler {
1092                                        let handler = handler.clone();
1093                                        let result = core::with_host_calls(
1094                                            host_call_bridge(handler),
1095                                            || fiber.drive_sync(),
1096                                        );
1097                                        return Ok((result, fiber));
1098                                    }
1099                                    #[cfg(not(target_arch = "wasm32"))]
1100                                    if let Some(handler) = &self.native_host_handler {
1101                                        let result = core::with_host_calls(handler.clone(), || {
1102                                            fiber.drive_sync()
1103                                        });
1104                                        return Ok((result, fiber));
1105                                    }
1106                                    Ok((fiber.drive_sync(), fiber))
1107                                })
1108                            })
1109                        })
1110                    })
1111                })
1112            },
1113        )?;
1114        self.env = fiber.environment();
1115        result
1116    }
1117
1118    fn refresh_qualified_bindings(&mut self) {
1119        core::refresh_namespace_environment(&self.namespace_registry, &mut self.env);
1120    }
1121
1122    fn save_namespace(&mut self) {
1123        core::save_namespace_environment(&self.namespace_registry, &mut self.env);
1124    }
1125
1126    pub fn create_namespace(&mut self, name: &str) -> bool {
1127        if name.is_empty() || self.namespace_registry.find(name).is_some() {
1128            return false;
1129        }
1130        self.namespace_registry.find_or_create(name);
1131        true
1132    }
1133
1134    pub fn use_namespace(&mut self, name: &str) -> bool {
1135        if name.is_empty() {
1136            return false;
1137        }
1138        let config = self
1139            .generated_configs
1140            .get(name)
1141            .cloned()
1142            .unwrap_or_else(kernel::GeneratedNamespaceConfig::defaults);
1143        if config.blank() {
1144            let target = self.namespace_registry.find_or_create(name);
1145            for (local, var) in target.mappings() {
1146                if var.symbol().get_namespace() != Some(name) {
1147                    target.unmap(&local);
1148                }
1149            }
1150            self.refer_native_types_into(name);
1151            #[cfg(feature = "bytecode-vm")]
1152            self.install_structural_primitives_into(name);
1153        } else {
1154            self.refer_foundation_into(name);
1155            let target = self.namespace_registry.find_or_create(name);
1156            for excluded in config.excluded_foundation() {
1157                let local = crate::lang::data::Symbol::parse(excluded);
1158                if target
1159                    .resolve(&local)
1160                    .is_some_and(|var| var.symbol().get_namespace() == Some("std.foundation"))
1161                {
1162                    target.unmap(&local);
1163                    self.env.remove(excluded);
1164                }
1165                self.macros
1166                    .borrow_mut()
1167                    .remove(&(name.to_owned(), excluded.clone()));
1168            }
1169        }
1170        core::select_namespace_environment(&self.namespace_registry, &mut self.env, name);
1171        self.sync_generated_aliases(&config);
1172        self.refresh_qualified_bindings();
1173        true
1174    }
1175
1176    fn sync_generated_aliases(&self, config: &kernel::GeneratedNamespaceConfig) {
1177        let target = self.namespace_registry.current();
1178        for (alias, namespace) in config.aliases() {
1179            if let Some(source) = self.namespace_registry.find(&namespace) {
1180                target.alias(alias, source);
1181            }
1182        }
1183        for namespace in config.used_namespaces() {
1184            if let Some(source) = self.namespace_registry.find(namespace) {
1185                for (symbol, var) in source.mappings() {
1186                    if !config.used_symbol_excluded(namespace, symbol.as_str()) {
1187                        target.map_var(symbol, var);
1188                    }
1189                }
1190                let source_name = source.name().as_str().to_owned();
1191                let target_name = target.name().as_str().to_owned();
1192                let referred = self
1193                    .macros
1194                    .borrow()
1195                    .iter()
1196                    .filter_map(|((namespace, name), function)| {
1197                        (namespace == &source_name).then(|| (name.clone(), function.clone()))
1198                    })
1199                    .collect::<Vec<_>>();
1200                let mut macros = self.macros.borrow_mut();
1201                for (name, function) in referred {
1202                    if !config.used_symbol_excluded(namespace, &name) {
1203                        macros.insert((target_name.clone(), name), function);
1204                    }
1205                }
1206            }
1207        }
1208    }
1209
1210    pub fn visible_symbols(&self) -> Vec<String> {
1211        self.namespace_registry.visible_symbol_names()
1212    }
1213
1214    pub fn current_namespace(&self) -> String {
1215        self.namespace_registry.current().name().as_str().to_owned()
1216    }
1217
1218    pub fn alias_namespace(&mut self, alias: &str, target: &str) -> bool {
1219        if alias.is_empty() || alias == "-" || target.is_empty() {
1220            return false;
1221        }
1222        let Some(target) = self.namespace_registry.find(target) else {
1223            return false;
1224        };
1225        self.namespace_registry.current().alias(alias, target);
1226        self.refresh_qualified_bindings();
1227        true
1228    }
1229
1230    pub fn resolve_namespace(&self, name: &str) -> String {
1231        self.namespace_registry
1232            .current()
1233            .aliases()
1234            .into_iter()
1235            .find(|(alias, _)| alias.as_str() == name)
1236            .map(|(_, namespace)| namespace.name().as_str().to_owned())
1237            .unwrap_or_else(|| name.into())
1238    }
1239
1240    /// Evaluates source after selecting a namespace.
1241    pub fn eval_in_namespace(&mut self, name: &str, source: &str) -> Result<String, JsValue> {
1242        let name = self.resolve_namespace(name);
1243        self.use_namespace(&name);
1244        self.eval_text(source)
1245            .map_err(|error| JsValue::from_str(&error))
1246    }
1247
1248    pub fn require_resource_in_namespace(
1249        &mut self,
1250        resource: &str,
1251        namespace: &str,
1252    ) -> Result<String, JsValue> {
1253        let namespace = self.resolve_namespace(namespace);
1254        self.use_namespace(&namespace);
1255        self.require_resource(resource)
1256    }
1257
1258    pub fn install_memory_file_provider(&mut self, root: &str) {
1259        self.providers
1260            .install_file(core::MemoryFileProvider::new(root));
1261    }
1262
1263    #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
1264    pub fn install_native_file_provider(&mut self, root: &str) {
1265        self.providers
1266            .install_file(core::NativeFileProvider::new(root));
1267    }
1268
1269    #[cfg(not(target_arch = "wasm32"))]
1270    pub fn install_native_socket_provider(&mut self) {
1271        self.providers
1272            .install_socket(core::NativeSocketProvider::default());
1273    }
1274
1275    #[cfg(not(target_arch = "wasm32"))]
1276    pub fn install_native_process_provider(&mut self) {
1277        self.providers.install_process();
1278    }
1279
1280    pub fn install_loopback_socket_provider(&mut self) {
1281        self.providers
1282            .install_socket(core::LoopbackSocketProvider::default());
1283    }
1284
1285    /// Installs the JS host handler that backs `std.native.Host/call`.
1286    #[cfg(target_arch = "wasm32")]
1287    pub fn install_host_handler(&mut self, handler: js_sys::Function) {
1288        self.host_handler = Some(handler);
1289    }
1290
1291    pub fn file_resolve(&self, root: &str, path: &str) -> Result<String, JsValue> {
1292        let provider = self
1293            .providers
1294            .file()
1295            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1296        provider
1297            .resolve(root, path)
1298            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1299    }
1300
1301    pub fn file_read(&self, path: &str) -> Result<PromiseHandle, JsValue> {
1302        let provider = self
1303            .providers
1304            .file()
1305            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1306        provider
1307            .read(path)
1308            .map(PromiseHandle::from_promise)
1309            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1310    }
1311
1312    pub fn file_write(&self, path: &str, bytes: Vec<u8>) -> Result<PromiseHandle, JsValue> {
1313        let provider = self
1314            .providers
1315            .file()
1316            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1317        provider
1318            .write(path, bytes)
1319            .map(PromiseHandle::from_promise)
1320            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1321    }
1322
1323    pub fn file_exists(&self, path: &str) -> Result<PromiseHandle, JsValue> {
1324        let provider = self
1325            .providers
1326            .file()
1327            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1328        provider
1329            .exists(path)
1330            .map(PromiseHandle::from_promise)
1331            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1332    }
1333
1334    pub fn file_list(&self, path: &str) -> Result<PromiseHandle, JsValue> {
1335        let provider = self
1336            .providers
1337            .file()
1338            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1339        provider
1340            .list(path)
1341            .map(PromiseHandle::from_promise)
1342            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1343    }
1344
1345    pub fn file_mkdir(&self, path: &str) -> Result<PromiseHandle, JsValue> {
1346        let provider = self
1347            .providers
1348            .file()
1349            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1350        provider
1351            .mkdir(path)
1352            .map(PromiseHandle::from_promise)
1353            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1354    }
1355
1356    pub fn file_delete(&self, path: &str) -> Result<PromiseHandle, JsValue> {
1357        let provider = self
1358            .providers
1359            .file()
1360            .ok_or_else(|| JsValue::from_str("file/unsupported"))?;
1361        provider
1362            .delete(path)
1363            .map(PromiseHandle::from_promise)
1364            .map_err(|error| JsValue::from_str(&format!("file/{}", error.code())))
1365    }
1366
1367    pub fn extension_available(&self, name: &str) -> bool {
1368        self.extensions.contains(name) || self.wasm_extensions.contains_key(name)
1369    }
1370
1371    pub fn require_extension(&mut self, name: &str) -> Result<String, JsValue> {
1372        if self.wasm_extensions.contains_key(name) {
1373            return self
1374                .load_wasm_extension_namespace(name)
1375                .map_err(|error| JsValue::from_str(&error));
1376        }
1377        self.extensions
1378            .require(name, &mut self.protocols)
1379            .map_err(|error| JsValue::from_str(&error))
1380    }
1381
1382    /// Registers a host-supplied Hara resource. Resources are source text, not executable host code.
1383    pub fn register_resource(&mut self, name: &str, source: &str) {
1384        let changed = self
1385            .resources
1386            .get(name)
1387            .is_some_and(|existing| existing != source);
1388        self.resources.insert(name.into(), source.into());
1389        if changed {
1390            self.loaded_resources.remove(name);
1391        }
1392    }
1393
1394    /// Evaluates a registered resource in the current lexical namespace.
1395    pub fn load_resource(&mut self, name: &str) -> Result<String, JsValue> {
1396        let source = self
1397            .resources
1398            .get(name)
1399            .cloned()
1400            .ok_or_else(|| JsValue::from_str("module/not-found"))?;
1401        self.eval_text(&source)
1402            .map_err(|error| JsValue::from_str(&error))
1403    }
1404
1405    /// Loads a resource once; subsequent requires return the current loaded marker.
1406    pub fn require_resource(&mut self, name: &str) -> Result<String, JsValue> {
1407        if self.loaded_resources.contains(name) {
1408            return Ok(":loaded".into());
1409        }
1410        if self.resources.contains_key(name) {
1411            let result = self.load_resource(name)?;
1412            self.loaded_resources.insert(name.into());
1413            return Ok(result);
1414        }
1415        if self.extensions.contains(name) {
1416            let result = self.require_extension(name)?;
1417            self.loaded_resources.insert(name.into());
1418            return Ok(result);
1419        }
1420        if self.wasm_extensions.contains_key(name) {
1421            let result = self
1422                .load_wasm_extension_namespace(name)
1423                .map_err(|error| JsValue::from_str(&error))?;
1424            self.loaded_resources.insert(name.into());
1425            return Ok(result);
1426        }
1427        Err(JsValue::from_str("module/not-found"))
1428    }
1429
1430    pub fn file_supported(&self) -> bool {
1431        self.providers.capabilities().file
1432    }
1433
1434    pub fn socket_supported(&self) -> bool {
1435        self.providers.capabilities().socket
1436    }
1437
1438    /// Opens a callback-based socket and returns its provider-owned handle.
1439    pub fn socket_connect(&self, host: &str, port: u16) -> Result<u64, JsValue> {
1440        let provider = self
1441            .providers
1442            .socket()
1443            .ok_or_else(|| JsValue::from_str("socket/unsupported"))?;
1444        provider
1445            .connect(host, port, Rc::new(ignore_socket_event))
1446            .map_err(|error| JsValue::from_str(&format!("socket/{}", error.code())))
1447    }
1448
1449    pub fn socket_send(&self, socket: u64, bytes: Vec<u8>) -> Result<usize, JsValue> {
1450        let provider = self
1451            .providers
1452            .socket()
1453            .ok_or_else(|| JsValue::from_str("socket/unsupported"))?;
1454        provider
1455            .send(socket, &bytes)
1456            .map_err(|error| JsValue::from_str(&format!("socket/{}", error.code())))
1457    }
1458
1459    pub fn socket_close(&self, socket: u64) -> Result<(), JsValue> {
1460        let provider = self
1461            .providers
1462            .socket()
1463            .ok_or_else(|| JsValue::from_str("socket/unsupported"))?;
1464        provider
1465            .close(socket)
1466            .map_err(|error| JsValue::from_str(&format!("socket/{}", error.code())))
1467    }
1468
1469    /// Returns whether a protocol method is registered in this runtime context.
1470    pub fn has_protocol_method(&self, protocol: &str, method: &str) -> bool {
1471        self.protocols.contains(protocol, method)
1472    }
1473
1474    pub fn eval(&mut self, source: &str) -> Result<String, JsValue> {
1475        self.eval_text(source)
1476            .map_err(|error| JsValue::from_str(&error))
1477    }
1478
1479    pub fn eval_traced(&mut self, source: &str) -> Result<String, JsValue> {
1480        self.eval_text_mode(source, true)
1481            .map_err(|error| JsValue::from_str(&error))
1482    }
1483
1484    #[cfg(feature = "bytecode-vm")]
1485    #[wasm_bindgen(js_name = compileBytecodeArtifact)]
1486    pub fn compile_bytecode_artifact_js(&self, source: &str) -> Result<Vec<u8>, JsValue> {
1487        self.compile_bytecode_artifact(source)
1488            .map_err(|error| JsValue::from_str(&error))
1489    }
1490
1491    /// Compiles source into an HNW1 artifact whose generated module can be
1492    /// instantiated by either Wasmtime or a browser WebAssembly engine.
1493    #[cfg(feature = "whole-wasm")]
1494    #[wasm_bindgen(js_name = compileWholeWasmArtifact)]
1495    pub fn compile_whole_wasm_artifact_js(&self, source: &str) -> Result<Vec<u8>, JsValue> {
1496        let program = self
1497            .compile_bytecode(source)
1498            .map_err(|error| JsValue::from_str(&error))?;
1499        whole_wasm::compile_artifact(program.as_ref()).map_err(|error| JsValue::from_str(&error))
1500    }
1501
1502    #[cfg(feature = "bytecode-vm")]
1503    #[wasm_bindgen(js_name = evalBytecodeArtifact)]
1504    pub fn eval_bytecode_artifact_js(&mut self, bytes: &[u8]) -> Result<String, JsValue> {
1505        self.eval_bytecode_artifact(bytes)
1506            .map_err(|error| JsValue::from_str(&error))
1507    }
1508
1509    #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
1510    pub fn eval_native(&mut self, source: &str) -> Result<String, String> {
1511        #[cfg(not(target_arch = "wasm32"))]
1512        if let Some(handler) = self.native_host_handler.clone() {
1513            return core::with_host_calls(handler, || self.eval_text(source));
1514        }
1515        self.eval_text(source)
1516    }
1517
1518    #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
1519    pub fn eval_native_traced(&mut self, source: &str) -> Result<String, String> {
1520        self.eval_text_mode(source, true)
1521    }
1522}
1523
1524/// Experimental bytecode VM entry points (issue #195), gated behind the
1525/// non-default `bytecode-vm` feature. These accept only closed,
1526/// namespace-independent forms in the supported synchronous subset;
1527/// anything else fails as a typed compile error. There is no fallback to
1528/// the default evaluator, and `Runtime::eval_native` is unaffected.
1529///
1530/// Programs are returned inside `Rc` because compiled closures share the
1531/// program with their executing machines; `Rc::clone` is the cheap way to
1532/// pass one around.
1533#[cfg(feature = "bytecode-vm")]
1534pub fn compile_bytecode(source: &str) -> Result<std::rc::Rc<vm::Program>, String> {
1535    vm::compile_source(source)
1536        .map(std::rc::Rc::new)
1537        .map_err(|error| error.to_string())
1538}
1539
1540/// Executes a previously compiled and validated program.
1541#[cfg(feature = "bytecode-vm")]
1542pub fn execute_bytecode(program: &std::rc::Rc<vm::Program>) -> Result<String, String> {
1543    vm::execute_program(program.clone())
1544        .map(|value| value.display())
1545        .map_err(|error| error.to_string())
1546}
1547
1548/// Returns tracing-JIT counters retained for a compiled bytecode program.
1549/// `None` means this build has no tracing-JIT feature enabled.
1550#[cfg(all(feature = "bytecode-vm", feature = "tracing-jit"))]
1551pub fn bytecode_jit_telemetry(program: &std::rc::Rc<vm::Program>) -> jit::JitTelemetry {
1552    vm::machine::cached_jit_telemetry(program)
1553}
1554
1555/// Compiles source into a checksummed, versioned bytecode artifact.
1556#[cfg(feature = "bytecode-vm")]
1557pub fn compile_bytecode_artifact(source: &str) -> Result<Vec<u8>, String> {
1558    let program = compile_bytecode(source)?;
1559    vm::encode_program(program.as_ref())
1560}
1561
1562/// Decodes, validates, and executes a bytecode artifact.
1563#[cfg(feature = "bytecode-vm")]
1564pub fn execute_bytecode_artifact(bytes: &[u8]) -> Result<String, String> {
1565    let program = std::rc::Rc::new(vm::decode_program(bytes)?);
1566    execute_bytecode(&program)
1567}
1568
1569/// Compiles and executes a source string through the experimental VM.
1570#[cfg(feature = "bytecode-vm")]
1571pub fn eval_bytecode_native(source: &str) -> Result<String, String> {
1572    execute_bytecode(&compile_bytecode(source)?)
1573}
1574
1575#[cfg(feature = "bytecode-vm")]
1576impl Runtime {
1577    /// Installs the native host service handler used by `std.native.Host/call`.
1578    /// Embedders can expose process-local services without converting values
1579    /// through JavaScript or textual serialization.
1580    #[cfg(not(target_arch = "wasm32"))]
1581    pub fn install_native_host_handler(
1582        &mut self,
1583        handler: Rc<dyn Fn(String, String, Vec<core::Value>) -> Result<core::Value, String>>,
1584    ) {
1585        self.native_host_handler = Some(handler);
1586    }
1587
1588    /// Compiles source against this runtime's namespace registry:
1589    /// std.foundation vars and anything already interned are visible to
1590    /// the compiler's two-phase global check (issue #223). The program
1591    /// is validated but not executed; globals intern only at execution.
1592    pub fn compile_bytecode(&self, source: &str) -> Result<std::rc::Rc<vm::Program>, String> {
1593        core::with_macros(self.macros.clone(), || {
1594            vm::compile_source_with(source, &self.namespace_registry)
1595                .map(std::rc::Rc::new)
1596                .map_err(|error| error.to_string())
1597        })
1598    }
1599
1600    /// Executes an already compiled program against this runtime's namespace
1601    /// registry. Embedding hosts use this for prepare-once/call-many paths
1602    /// without decoding an artifact or rebuilding the program on every call.
1603    pub fn execute_compiled_bytecode(
1604        &mut self,
1605        program: std::rc::Rc<vm::Program>,
1606    ) -> Result<String, String> {
1607        self.execute_compiled_bytecode_value(program)
1608            .map(|value| value.display())
1609    }
1610
1611    /// Executes an already compiled program and returns its immutable runtime
1612    /// value directly. This avoids display serialization and lets native hosts
1613    /// inspect persistent results through their shared representation.
1614    pub fn execute_compiled_bytecode_value(
1615        &mut self,
1616        program: std::rc::Rc<vm::Program>,
1617    ) -> Result<core::Value, String> {
1618        let result = self.execute_compiled_bytecode_registry_value(program);
1619        let current = self.namespace_registry.current().name().as_str().to_owned();
1620        core::select_namespace_environment(&self.namespace_registry, &mut self.env, &current);
1621        result
1622    }
1623
1624    /// Executes a prepared program directly against the namespace registry,
1625    /// without copying bindings into the compatibility environment per call.
1626    pub fn execute_compiled_bytecode_registry_value(
1627        &mut self,
1628        program: std::rc::Rc<vm::Program>,
1629    ) -> Result<core::Value, String> {
1630        core::with_macros(self.macros.clone(), || {
1631            vm::execute_program_with_globals(program, &self.namespace_registry)
1632                .map_err(|error| error.to_string())
1633        })
1634    }
1635
1636    /// Compiles and executes through the experimental VM against this
1637    /// runtime's registry, then syncs the flat env so later `eval_native`
1638    /// calls see the vars the program interned. No fallback: unsupported
1639    /// forms fail as compile errors. `eval_native` is unaffected.
1640    pub fn eval_bytecode_native(&mut self, source: &str) -> Result<String, String> {
1641        let program = self.compile_bytecode(source)?;
1642        self.execute_compiled_bytecode(program)
1643    }
1644
1645    /// Compiles against this runtime's namespaces and persists the validated
1646    /// program for later native or browser execution.
1647    pub fn compile_bytecode_artifact(&self, source: &str) -> Result<Vec<u8>, String> {
1648        let program = self.compile_bytecode(source)?;
1649        vm::encode_program(program.as_ref())
1650    }
1651
1652    /// Lowers a HALC module directly to persistent bytecode. No source text is
1653    /// reconstructed, and the module's normalized schema graph is embedded in
1654    /// the HBC artifact for later inference and specialization tiers.
1655    pub fn compile_halc_bytecode_artifact(&mut self, bytes: &[u8]) -> Result<Vec<u8>, String> {
1656        let module = kernel::halc::decode_halc(bytes)?;
1657        // HALC retains the source namespace declaration as structured data.
1658        // Apply it through the ordinary module loader before lowering so
1659        // aliases, refers, intrinsics, and required resources are identical
1660        // to interpreted HALC. Only the declaration is evaluated here; the
1661        // remaining forms go directly to the bytecode compiler below.
1662        if let Some(namespace_form) = module.forms.iter().find(|form| {
1663            matches!(
1664                core::form_without_metadata(form),
1665                Form::List(items)
1666                    if matches!(items.first(), Some(Form::Symbol(operator)) if operator == "ns")
1667            )
1668        }) {
1669            self.eval_forms(vec![namespace_form.clone()], false)?;
1670        } else {
1671            self.use_namespace(&module.namespace);
1672        }
1673        let program = vm::compile_halc_module(&module, &self.namespace_registry)
1674            .map_err(|error| error.to_string())?;
1675        vm::encode_program(&program)
1676    }
1677
1678    /// Executes a persisted artifact against this runtime's namespaces.
1679    pub fn eval_bytecode_artifact(&mut self, bytes: &[u8]) -> Result<String, String> {
1680        let program = std::rc::Rc::new(vm::decode_program(bytes)?);
1681        if let Some(namespace) = &program.namespace {
1682            self.namespace_registry.set_current(namespace);
1683        }
1684        let schema_types = program.schema_types.clone();
1685        let function_types = program.function_types.clone();
1686        let inferred_function_types = program.inferred_function_types.clone();
1687        let result = core::with_macros(self.macros.clone(), || {
1688            vm::execute_program_with_globals(program, &self.namespace_registry)
1689                .map(|value| value.display())
1690                .map_err(|error| error.to_string())
1691        });
1692        if result.is_ok() {
1693            self.halc_schema_types.extend(schema_types);
1694            self.halc_function_types.extend(function_types);
1695            self.halc_inferred_function_types
1696                .extend(inferred_function_types);
1697        }
1698        let current = self.namespace_registry.current().name().as_str().to_owned();
1699        core::select_namespace_environment(&self.namespace_registry, &mut self.env, &current);
1700        result
1701    }
1702}
1703
1704impl Runtime {
1705    /// Returns the canonical schema value loaded from HALC for a named schema Var.
1706    pub fn halc_schema(&self, qualified_var: &str) -> Option<&Form> {
1707        self.halc_schema_definitions.get(qualified_var)
1708    }
1709
1710    /// Returns the canonical schema annotation loaded from HALC for a function Var.
1711    pub fn halc_function_schema(&self, qualified_var: &str) -> Option<&Form> {
1712        self.halc_function_schemas.get(qualified_var)
1713    }
1714
1715    /// Returns the normalized compiler type for a named schema Var.
1716    pub fn halc_schema_type(&self, qualified_var: &str) -> Option<&kernel::SchemaType> {
1717        self.halc_schema_types.get(qualified_var)
1718    }
1719
1720    /// Returns a conservative body-derived function signature, when the
1721    /// compiler could prove one independently of the declared contract.
1722    pub fn halc_inferred_function_type(&self, qualified_var: &str) -> Option<&kernel::SchemaType> {
1723        self.halc_inferred_function_types.get(qualified_var)
1724    }
1725
1726    /// Returns a function's normalized annotation, resolving one named edge.
1727    pub fn halc_function_type(&self, qualified_var: &str) -> Option<&kernel::SchemaType> {
1728        let schema = self.halc_function_types.get(qualified_var)?;
1729        match schema {
1730            kernel::SchemaType::Reference(name) => {
1731                self.halc_schema_types.get(name).or(Some(schema))
1732            }
1733            _ => Some(schema),
1734        }
1735    }
1736
1737    /// Evaluates native Hara source and returns its runtime value without a
1738    /// display round trip. Embedding hosts use this to inspect declarative
1739    /// values containing Vars, functions, bytes, and persistent collections.
1740    #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
1741    pub fn eval_native_value(&mut self, source: &str) -> Result<core::Value, String> {
1742        #[cfg(not(target_arch = "wasm32"))]
1743        if let Some(handler) = self.native_host_handler.clone() {
1744            return core::with_host_calls(handler, || self.eval_value_mode(source, false));
1745        }
1746        self.eval_value_mode(source, false)
1747    }
1748
1749    /// Evaluates once through the existing evaluator and returns a portable
1750    /// bounded Evaluation Journal.
1751    #[cfg(feature = "evaluation-journal")]
1752    pub fn eval_native_journal(&mut self, source: &str) -> journal::Journal {
1753        let journal_id = journal::JournalId(self.next_journal_id);
1754        self.next_journal_id += 1;
1755        let (_, journal) = core::with_evaluation_journal(
1756            journal_id,
1757            journal::JournalLimits::default(),
1758            || {
1759                self.refresh_qualified_bindings();
1760                let forms = kernel::parse_forms(source)?;
1761                let result = self.eval_forms(forms, true)?;
1762                self.save_namespace();
1763                self.refresh_qualified_bindings();
1764                Ok(result)
1765            },
1766            |value, collector| {
1767                collector.preview_value(core::portable_type_name(value), value.display())
1768            },
1769        );
1770        journal
1771    }
1772
1773    #[cfg(feature = "evaluation-journal")]
1774    #[deprecated(note = "use eval_native_journal")]
1775    pub fn eval_native_trace(&mut self, source: &str) -> Result<journal::Journal, String> {
1776        let journal = self.eval_native_journal(source);
1777        match journal.status {
1778            journal::JournalStatus::Error => Err(journal.error.clone().unwrap_or_default()),
1779            _ => Ok(journal),
1780        }
1781    }
1782
1783    #[cfg(not(target_arch = "wasm32"))]
1784    pub fn add_extension_root(&mut self, root: impl Into<std::path::PathBuf>) {
1785        self.extension_roots.push(root.into());
1786    }
1787
1788    #[cfg(not(target_arch = "wasm32"))]
1789    fn install_discovered_extension(&mut self, namespace: &str) -> Result<(), String> {
1790        if self.wasm_extensions.contains_key(namespace) {
1791            return Ok(());
1792        }
1793        let package =
1794            native_extension::ExtensionPackage::discover(namespace, &self.extension_roots)?
1795                .ok_or_else(|| format!("extension/not-found: {namespace}"))?;
1796        if package.manifest.provider == "hta" {
1797            let target = package
1798                .manifest
1799                .targets
1800                .get("node")
1801                .ok_or_else(|| format!("extension/target-unsupported: node for {namespace}"))?;
1802            if target.runtime != "process" {
1803                return Err(format!(
1804                    "extension/target-unsupported: node for {namespace}"
1805                ));
1806            }
1807            let module = package.resolve(&target.module)?;
1808            let provider = process_extension::ProcessExtensionProvider::new(module);
1809            return self.install_wasm_extension(
1810                &package.source,
1811                &package.descriptor.display().to_string(),
1812                provider,
1813            );
1814        }
1815        if package.manifest.provider != "wasm" {
1816            return Err(format!(
1817                "extension/provider-unsupported: {} for {namespace}",
1818                package.manifest.provider
1819            ));
1820        }
1821        let bytes = package.module_bytes()?;
1822        let provider = wasmtime_provider::WasmtimeExtensionProvider::compile(&bytes)?;
1823        self.install_wasm_extension(
1824            &package.source,
1825            &package.descriptor.display().to_string(),
1826            provider,
1827        )
1828    }
1829
1830    pub fn install_wasm_extension<P: extension::WasmExtensionProvider + 'static>(
1831        &mut self,
1832        manifest_source: &str,
1833        origin: &str,
1834        provider: P,
1835    ) -> Result<(), String> {
1836        let manifest = extension::ExtensionManifest::parse(manifest_source, origin)?;
1837        let namespace = manifest.namespace.clone();
1838        if self.wasm_extensions.contains_key(&namespace)
1839            || self.extensions.contains(&namespace)
1840            || self.resources.contains_key(&namespace)
1841        {
1842            return Err(format!(
1843                "extension/ambiguous: namespace already registered: {namespace}"
1844            ));
1845        }
1846        let extension = extension::WasmExtension::new(manifest, provider)?;
1847        self.wasm_extensions.insert(namespace, extension);
1848        Ok(())
1849    }
1850
1851    pub fn cancel_wasm_extension(&self, name: &str, request: u64) -> Result<(), String> {
1852        self.wasm_extensions
1853            .get(name)
1854            .ok_or_else(|| format!("extension/not-found: {name}"))?
1855            .cancel(request)
1856    }
1857
1858    /// Invokes an installed WASM extension without routing the call through
1859    /// source text. Service hosts use this binary-safe boundary for HTA1
1860    /// arguments and results.
1861    pub fn invoke_wasm_extension(
1862        &mut self,
1863        namespace: &str,
1864        export: &str,
1865        arguments: &[extension::Value],
1866    ) -> Result<extension::Value, String> {
1867        let binding = self
1868            .wasm_extensions
1869            .get_mut(namespace)
1870            .ok_or_else(|| format!("extension/not-found: {namespace}"))?
1871            .require()?
1872            .into_iter()
1873            .find(|binding| binding.name == export)
1874            .ok_or_else(|| format!("extension/export-missing: {namespace}/{export}"))?;
1875        binding.invoke(arguments)
1876    }
1877
1878    fn namespace_source(&self) -> Rc<dyn Fn(&str) -> Option<String>> {
1879        let resources = self.resources.clone();
1880        Rc::new(move |name: &str| resources.get(name).cloned())
1881    }
1882
1883    fn load_wasm_extension_namespace(&mut self, name: &str) -> Result<String, String> {
1884        let bindings = self
1885            .wasm_extensions
1886            .get_mut(name)
1887            .ok_or_else(|| format!("extension/not-found: {name}"))?
1888            .require()?;
1889        let namespace = self.namespace_registry.find_or_create(name);
1890        for binding in bindings {
1891            let arity = binding.specification.arguments.len();
1892            let function_name = format!("{name}/{}", binding.name);
1893            let binding_name = binding.name.clone();
1894            namespace.intern(
1895                &binding_name,
1896                core::native_function(&function_name, arity, move |arguments| {
1897                    binding.invoke(&arguments)
1898                }),
1899            );
1900        }
1901        self.refresh_qualified_bindings();
1902        Ok(":loaded".into())
1903    }
1904}
1905
1906#[cfg(target_arch = "wasm32")]
1907fn js_error_string(error: JsValue) -> String {
1908    if let Some(message) = error.as_string() {
1909        return message;
1910    }
1911    js_sys::Reflect::get(&error, &JsValue::from_str("message"))
1912        .ok()
1913        .and_then(|message| message.as_string())
1914        .unwrap_or_else(|| format!("{error:?}"))
1915}
1916
1917#[cfg(target_arch = "wasm32")]
1918fn host_key_to_string(key: &core::Value) -> String {
1919    match key {
1920        core::Value::String(text) => text.clone(),
1921        core::Value::Keyword(keyword) => keyword.as_str().to_owned(),
1922        core::Value::Symbol(symbol) => symbol.as_str().to_owned(),
1923        other => other.display(),
1924    }
1925}
1926
1927#[cfg(target_arch = "wasm32")]
1928fn host_seq_to_js<'a>(values: impl Iterator<Item = &'a core::Value>) -> Result<JsValue, String> {
1929    let array = js_sys::Array::new();
1930    for value in values {
1931        array.push(&value_to_js(value)?);
1932    }
1933    Ok(array.into())
1934}
1935
1936#[cfg(target_arch = "wasm32")]
1937fn value_to_js(value: &core::Value) -> Result<JsValue, String> {
1938    match value {
1939        core::Value::Nil => Ok(JsValue::NULL),
1940        core::Value::Bool(flag) => Ok(JsValue::from_bool(*flag)),
1941        core::Value::Number(number)
1942            if (*number as i128).abs() <= js_sys::Number::MAX_SAFE_INTEGER as i128 =>
1943        {
1944            Ok(JsValue::from_f64(*number as f64))
1945        }
1946        core::Value::Number(number) => Ok(js_sys::BigInt::from(*number).into()),
1947        core::Value::Float(number) => Ok(JsValue::from_f64(*number)),
1948        core::Value::String(text) => Ok(JsValue::from_str(text)),
1949        core::Value::Keyword(keyword) => Ok(JsValue::from_str(keyword.as_str())),
1950        core::Value::Symbol(symbol) => Ok(JsValue::from_str(symbol.as_str())),
1951        core::Value::Bytes(bytes) => Ok(js_sys::Uint8Array::from(&bytes[..]).into()),
1952        core::Value::Vector(values) => host_seq_to_js(values.iter()),
1953        core::Value::List(values) => host_seq_to_js(values.iter()),
1954        core::Value::Set(values) => host_seq_to_js(values.iter()),
1955        core::Value::OrderedSet(values) => host_seq_to_js(values.iter()),
1956        core::Value::Map(values) => {
1957            let object = js_sys::Object::new();
1958            for (key, value) in values.iter() {
1959                js_sys::Reflect::set(
1960                    &object,
1961                    &JsValue::from_str(&host_key_to_string(key)),
1962                    &value_to_js(value)?,
1963                )
1964                .map_err(js_error_string)?;
1965            }
1966            Ok(object.into())
1967        }
1968        core::Value::OrderedMap(values) => {
1969            let object = js_sys::Object::new();
1970            for entry in values.iter() {
1971                js_sys::Reflect::set(
1972                    &object,
1973                    &JsValue::from_str(&host_key_to_string(&entry.0)),
1974                    &value_to_js(&entry.1)?,
1975                )
1976                .map_err(js_error_string)?;
1977            }
1978            Ok(object.into())
1979        }
1980        other => Err(format!(
1981            "std.native.Host/call type-not-transportable: {}",
1982            other.display()
1983        )),
1984    }
1985}
1986
1987#[cfg(target_arch = "wasm32")]
1988fn js_to_value(value: &JsValue) -> Result<core::Value, String> {
1989    use crate::lang::data::{OrderedMap as POrderedMap, Vector as PVector};
1990    use wasm_bindgen::JsCast;
1991
1992    if value.is_null() || value.is_undefined() {
1993        return Ok(core::Value::Nil);
1994    }
1995    if let Some(flag) = value.as_bool() {
1996        return Ok(core::Value::Bool(flag));
1997    }
1998    if value.is_bigint() {
1999        let integer: js_sys::BigInt = value.clone().unchecked_into();
2000        return i64::try_from(integer)
2001            .map(core::Value::Number)
2002            .map_err(|_| "std.native.Host/call bigint is outside the signed 64-bit range".into());
2003    }
2004    if let Some(number) = value.as_f64() {
2005        if number.fract() == 0.0
2006            && number >= js_sys::Number::MIN_SAFE_INTEGER
2007            && number <= js_sys::Number::MAX_SAFE_INTEGER
2008        {
2009            return Ok(core::Value::Number(number as i64));
2010        }
2011        return Ok(core::Value::Float(number));
2012    }
2013    if let Some(text) = value.as_string() {
2014        return Ok(core::Value::String(text));
2015    }
2016    if value.is_instance_of::<js_sys::Uint8Array>() {
2017        return Ok(core::Value::Bytes(js_sys::Uint8Array::new(value).to_vec()));
2018    }
2019    if js_sys::Array::is_array(value) {
2020        let array = js_sys::Array::from(value);
2021        let mut items = Vec::with_capacity(array.length() as usize);
2022        for index in 0..array.length() {
2023            items.push(js_to_value(&array.get(index))?);
2024        }
2025        return Ok(core::Value::Vector(PVector::from_iter(items)));
2026    }
2027    if value.is_object() {
2028        let entries = js_sys::Object::entries(value.unchecked_ref::<js_sys::Object>());
2029        let mut items = Vec::with_capacity(entries.length() as usize);
2030        for index in 0..entries.length() {
2031            let entry = js_sys::Array::from(&entries.get(index));
2032            let key = entry.get(0).as_string().unwrap_or_default();
2033            let item = js_to_value(&entry.get(1))?;
2034            items.push((core::Value::String(key), item));
2035        }
2036        return Ok(core::Value::OrderedMap(Box::new(POrderedMap::from_iter(
2037            items,
2038        ))));
2039    }
2040    Err("std.native.Host/call type-not-transportable: unsupported JS result".into())
2041}
2042
2043#[cfg(target_arch = "wasm32")]
2044fn host_call_bridge(
2045    handler: js_sys::Function,
2046) -> Rc<dyn Fn(String, String, Vec<core::Value>) -> Result<core::Value, String>> {
2047    Rc::new(move |service, method, args| {
2048        let js_args = js_sys::Array::new();
2049        for value in &args {
2050            js_args.push(&value_to_js(value)?);
2051        }
2052        let result = handler
2053            .call3(
2054                &JsValue::NULL,
2055                &JsValue::from(service),
2056                &JsValue::from(method),
2057                js_args.as_ref(),
2058            )
2059            .map_err(js_error_string)?;
2060        js_to_value(&result)
2061    })
2062}
2063
2064#[wasm_bindgen]
2065pub fn target_profile() -> String {
2066    if cfg!(target_os = "wasi") {
2067        "wasi".into()
2068    } else if cfg!(target_arch = "wasm32") {
2069        "wasm".into()
2070    } else {
2071        "native".into()
2072    }
2073}
2074
2075#[wasm_bindgen]
2076pub fn version() -> String {
2077    "hara-wasm/0.1 L0 slice".to_string()
2078}
2079
2080#[cfg(test)]
2081mod tests {
2082    use super::*;
2083
2084    fn repo_text(relative: &str) -> Option<String> {
2085        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2086            .join("..")
2087            .join(relative);
2088        match std::fs::read_to_string(&path) {
2089            Ok(content) => Some(content),
2090            Err(_) => {
2091                eprintln!(
2092                    "skipping: {} is unavailable (specs/docs submodule not initialized)",
2093                    path.display()
2094                );
2095                None
2096            }
2097        }
2098    }
2099
2100    fn module_case(id: &str) -> Vec<(Form, Form)> {
2101        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
2102            entries
2103                .iter()
2104                .find_map(|(candidate, value)| match candidate {
2105                    Form::Keyword(name) if name == key => Some(value),
2106                    _ => None,
2107                })
2108        }
2109
2110        let corpus = repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn")
2111            .expect("specs submodule must be initialized for module conformance tests");
2112        let manifest = kernel::parse_forms(&corpus)
2113            .expect("module conformance corpus must parse")
2114            .remove(0);
2115        let Form::Map(manifest) = manifest else {
2116            panic!("module conformance corpus must be a map")
2117        };
2118        let Some(Form::Vector(cases)) = entry(&manifest, "cases") else {
2119            panic!("module conformance :cases must be a vector")
2120        };
2121        cases
2122            .iter()
2123            .find_map(|case| {
2124                let Form::Map(case) = case else {
2125                    return None;
2126                };
2127                matches!(entry(case, "id"), Some(Form::Keyword(candidate)) if candidate == id)
2128                    .then(|| case.clone())
2129            })
2130            .unwrap_or_else(|| panic!("missing module conformance case :{id}"))
2131    }
2132
2133    fn module_expect(id: &str, key: &str) -> Form {
2134        let case = module_case(id);
2135        let expect = case.iter().find_map(|(candidate, value)| match candidate {
2136            Form::Keyword(name) if name == "expect" => Some(value),
2137            _ => None,
2138        });
2139        let Some(Form::Map(expect)) = expect else {
2140            panic!("module conformance case :{id} must have an :expect map")
2141        };
2142        expect
2143            .iter()
2144            .find_map(|(candidate, value)| {
2145                matches!(candidate, Form::Keyword(name) if name == key).then(|| value.clone())
2146            })
2147            .unwrap_or_else(|| panic!("module conformance case :{id} is missing :expect :{key}"))
2148    }
2149
2150    fn module_runtime_profile(runtime: &str, key: &str) -> Form {
2151        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
2152            entries
2153                .iter()
2154                .find_map(|(candidate, value)| match candidate {
2155                    Form::Keyword(name) if name == key => Some(value),
2156                    _ => None,
2157                })
2158        }
2159
2160        let corpus = repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn")
2161            .expect("specs submodule must be initialized for module conformance tests");
2162        let manifest = kernel::parse_forms(&corpus)
2163            .expect("module conformance corpus must parse")
2164            .remove(0);
2165        let Form::Map(manifest) = manifest else {
2166            panic!("module conformance corpus must be a map")
2167        };
2168        let Some(Form::Map(profiles)) = entry(&manifest, "runtime/profiles") else {
2169            panic!("module conformance corpus must declare :runtime/profiles")
2170        };
2171        let Some(Form::Map(profile)) = entry(profiles, runtime) else {
2172            panic!("module conformance corpus has no :{runtime} profile")
2173        };
2174        entry(profile, key)
2175            .cloned()
2176            .unwrap_or_else(|| panic!("module runtime profile :{runtime} has no :{key}"))
2177    }
2178
2179    fn host_conformance_case(id: &str) -> Vec<(Form, Form)> {
2180        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
2181            entries
2182                .iter()
2183                .find_map(|(candidate, value)| match candidate {
2184                    Form::Keyword(name) if name == key => Some(value),
2185                    _ => None,
2186                })
2187        }
2188
2189        let document_source = repo_text("specs/00-unsorted/runtime/draft/host-runtime.edn")
2190            .expect("specs submodule must be initialized for host runtime conformance tests");
2191        let document = kernel::parse_forms(&document_source)
2192            .expect("Host runtime specification must parse")
2193            .remove(0);
2194        let Form::Map(document) = document else {
2195            panic!("Host runtime specification must be a map")
2196        };
2197        let Some(Form::Vector(cases)) = entry(&document, "host/conformance") else {
2198            panic!("Host runtime specification must declare :host/conformance")
2199        };
2200        cases
2201            .iter()
2202            .find_map(|case| {
2203                let Form::Map(case) = case else {
2204                    return None;
2205                };
2206                matches!(entry(case, "id"), Some(Form::Keyword(candidate)) if candidate == id)
2207                    .then(|| case.clone())
2208            })
2209            .unwrap_or_else(|| panic!("missing Host conformance case :{id}"))
2210    }
2211
2212    #[test]
2213    fn session_kernel_mounts_preserve_state_and_enforce_lifetime() {
2214        let mut kernel = SessionKernel::new();
2215        kernel.create_session("alpha").unwrap();
2216        kernel.create_session("beta").unwrap();
2217        assert_eq!(
2218            kernel.eval("alpha", "(def answer 41) answer").unwrap(),
2219            "41"
2220        );
2221        assert_eq!(kernel.eval("beta", "(def answer 6) answer").unwrap(), "6");
2222        let mount = kernel.create_memory_filesystem("/workspace");
2223        kernel.attach_filesystem("alpha", mount).unwrap();
2224        kernel.attach_filesystem("beta", mount).unwrap();
2225        assert_eq!(kernel.filesystem("alpha"), Some(mount));
2226        assert_eq!(kernel.eval("alpha", "answer").unwrap(), "41");
2227        assert_eq!(
2228            kernel
2229                .eval(
2230                    "alpha",
2231                    "(do (require [std.foundation.file :as file]) \
2232                     (deref (file/write \"/workspace/shared.bin\" (bytes 7 8))))",
2233                )
2234                .unwrap(),
2235            "nil"
2236        );
2237        assert_eq!(
2238            kernel
2239                .eval(
2240                    "beta",
2241                    "(do (require [std.foundation.file :as file]) \
2242                     (deref (file/exists? \"/workspace/shared.bin\")))",
2243                )
2244                .unwrap(),
2245            "true"
2246        );
2247        assert_eq!(
2248            kernel
2249                .eval(
2250                    "alpha",
2251                    "(do (require [std.foundation.file :as file]) \
2252                     (deref (file/write \"/workspace/source.hal\" \
2253                       (str/encode-utf8 \"(+ 19 23)\"))))",
2254                )
2255                .unwrap(),
2256            "nil"
2257        );
2258        assert_eq!(
2259            kernel
2260                .eval(
2261                    "beta",
2262                    "(do (require [std.foundation.file :as file]) \
2263                     (str/decode-utf8 \
2264                       (deref (file/read \"/workspace/source.hal\"))))",
2265                )
2266                .unwrap(),
2267            "\"(+ 19 23)\""
2268        );
2269        assert_eq!(
2270            kernel.close_filesystem(mount).unwrap_err(),
2271            format!("FILESYSTEM_ATTACHED {mount}")
2272        );
2273        kernel.detach_filesystem("alpha").unwrap();
2274        kernel.detach_filesystem("beta").unwrap();
2275        kernel.close_filesystem(mount).unwrap();
2276        assert_eq!(
2277            kernel.session_names(),
2278            vec!["ROOT".to_string(), "alpha".to_string(), "beta".to_string()]
2279        );
2280    }
2281
2282    #[test]
2283    fn named_sessions_conform_to_context_component_and_applicative_protocols() {
2284        use crate::lang::protocol::{IApplicable, IComponent, IContext, IInvokeIn};
2285
2286        let mut alpha = Session::new("alpha", Runtime::new());
2287        let mut beta = Session::new("beta", Runtime::new());
2288
2289        assert!(alpha.started());
2290        assert_eq!(alpha.props().namespace, "user");
2291        assert_eq!(
2292            alpha.call("(do (ns alpha.core) (def answer 41) answer)"),
2293            Ok("41".into())
2294        );
2295        assert_eq!(alpha.props().namespace, "alpha.core");
2296        assert_eq!(beta.current_namespace(), "user");
2297
2298        assert_eq!(alpha.apply_in(&mut beta, "(+ 20 22)"), Ok("42".into()));
2299        assert_eq!(alpha.invoke_in(&mut beta, "(+ 40 2)"), Ok("42".into()));
2300        assert_eq!(alpha.transform_in(&beta, "answer"), "answer");
2301        assert_eq!(
2302            alpha.transform_out(&beta, "answer", Ok("41".into())),
2303            Ok("41".into())
2304        );
2305        assert_eq!(alpha.apply_default().current_namespace(), "alpha.core");
2306
2307        alpha.stop();
2308        assert!(alpha.stopped());
2309        assert_eq!(alpha.call("answer"), Err("SESSION_CLOSED alpha".into()));
2310    }
2311
2312    fn ignore_socket_event(_event: core::SocketEvent) {}
2313
2314    static SOCKET_EVENTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2315
2316    fn count_socket_event(_event: core::SocketEvent) {
2317        SOCKET_EVENTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2318    }
2319
2320    #[cfg(not(target_arch = "wasm32"))]
2321    #[test]
2322    fn native_socket_provider_sends_callbacks_and_bytes() {
2323        use crate::core::SocketProvider;
2324        use std::io::Read;
2325        use std::net::TcpListener;
2326        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
2327        let port = listener.local_addr().unwrap().port();
2328        let server = std::thread::spawn(move || {
2329            let (mut stream, _) = listener.accept().unwrap();
2330            let mut bytes = [0u8; 3];
2331            stream.read_exact(&mut bytes).unwrap();
2332            bytes
2333        });
2334        SOCKET_EVENTS.store(0, std::sync::atomic::Ordering::SeqCst);
2335        let sockets = core::NativeSocketProvider::default();
2336        let handle = sockets
2337            .connect("127.0.0.1", port, Rc::new(count_socket_event))
2338            .unwrap();
2339        assert_eq!(sockets.send(handle, &[7, 8, 9]).unwrap(), 3);
2340        sockets.close(handle).unwrap();
2341        assert_eq!(server.join().unwrap(), [7, 8, 9]);
2342        assert_eq!(SOCKET_EVENTS.load(std::sync::atomic::Ordering::SeqCst), 3);
2343    }
2344
2345    #[cfg(not(target_arch = "wasm32"))]
2346    #[test]
2347    fn native_socket_server_streams_real_tcp_events() {
2348        use crate::core::{PromiseState, SocketProvider};
2349        use std::io::Write;
2350        let sockets = core::NativeSocketProvider::default();
2351        let server = sockets.listen("127.0.0.1", 0, Rc::new(|_| {})).unwrap();
2352        let (host, port) = sockets.endpoint(server).unwrap();
2353        let stream = sockets.events(server).unwrap();
2354        let mut client = std::net::TcpStream::connect((host.as_str(), port)).unwrap();
2355        let open = sockets.next(stream).unwrap().wait_state();
2356        assert!(
2357            matches!(open, PromiseState::Fulfilled(value) if value.display().contains(":open"))
2358        );
2359        client.write_all(b"ping").unwrap();
2360        let data = sockets.next(stream).unwrap().wait_state();
2361        assert!(
2362            matches!(data, PromiseState::Fulfilled(value) if value.display().contains(":data") && value.display().contains("112 105 110 103"))
2363        );
2364        sockets.close(server).unwrap();
2365    }
2366
2367    #[cfg(not(target_arch = "wasm32"))]
2368    #[test]
2369    fn native_file_provider_round_trips_bytes() {
2370        use crate::core::FileProvider;
2371        let path = std::env::temp_dir().join(format!("hara-wasm-test-{}", std::process::id()));
2372        std::fs::create_dir_all(&path).unwrap();
2373        let provider = core::NativeFileProvider::new(&path);
2374        let resolved = provider
2375            .resolve(path.to_str().unwrap(), "data.bin")
2376            .unwrap();
2377        assert_eq!(
2378            provider.write(&resolved, vec![4, 5, 6]).unwrap().state(),
2379            core::PromiseState::Fulfilled(core::Value::Nil)
2380        );
2381        assert_eq!(
2382            provider.read(&resolved).unwrap().state(),
2383            core::PromiseState::Fulfilled(core::Value::Bytes(vec![4, 5, 6]))
2384        );
2385        std::fs::remove_file(resolved).unwrap();
2386        std::fs::remove_dir(path).unwrap();
2387    }
2388
2389    #[test]
2390    fn extension_provider_values_load_and_iterate_through_protocols() {
2391        let mut runtime = Runtime::new();
2392        runtime.extensions.install(RangeExtension);
2393        assert!(runtime.extension_available("range"));
2394        assert_eq!(runtime.require_resource("range").unwrap(), ":loaded");
2395        let value = runtime
2396            .extensions
2397            .construct("range", "range", &[core::Value::Number(3)])
2398            .unwrap();
2399        assert_eq!(core::receiver_category(&value), "extension");
2400        runtime.env.insert("r".into(), value);
2401        assert_eq!(runtime.eval_text("(iter-next (iter r))").unwrap(), "0");
2402        assert_eq!(runtime.eval_text("(iter-next (iter r))").unwrap(), "0");
2403        assert_eq!(runtime.require_resource("range").unwrap(), ":loaded");
2404    }
2405
2406    #[test]
2407    fn runtime_routes_file_operations_through_provider_registry() {
2408        let mut runtime = Runtime::new();
2409        assert!(!runtime.file_supported());
2410        runtime.install_memory_file_provider("/sandbox");
2411        assert!(runtime.file_supported());
2412        let path = runtime.file_resolve("/sandbox", "data.bin").unwrap();
2413        assert_eq!(
2414            runtime
2415                .file_write(&path, vec![1, 2, 3])
2416                .unwrap()
2417                .value()
2418                .unwrap(),
2419            "nil"
2420        );
2421        assert_eq!(
2422            runtime.file_read(&path).unwrap().value().unwrap(),
2423            "#bytes[1 2 3]"
2424        );
2425        runtime.install_loopback_socket_provider();
2426        assert!(runtime.socket_supported());
2427    }
2428
2429    #[test]
2430    fn runtime_core_evaluates_embedded_commands() {
2431        let mut runtime = Runtime::core();
2432        assert_eq!(runtime.eval_text("(+ 19 23)").unwrap(), "42");
2433        assert_eq!(runtime.eval_text("(let (x 7) (* x 6))").unwrap(), "42");
2434        assert_eq!(runtime.eval_text("(if true 1 0)").unwrap(), "1");
2435    }
2436
2437    #[test]
2438    fn foundation_boolean_and_not_equal_are_portable() {
2439        let mut runtime = Runtime::new();
2440        assert_eq!(runtime.eval_text("(boolean :present)").unwrap(), "true");
2441        assert_eq!(runtime.eval_text("(boolean nil)").unwrap(), "false");
2442        assert_eq!(runtime.eval_text("(not= 1 2)").unwrap(), "true");
2443        assert_eq!(runtime.eval_text("(not= 1 1 2)").unwrap(), "true");
2444        assert_eq!(runtime.eval_text("(not= 1 1)").unwrap(), "false");
2445    }
2446
2447    #[test]
2448    fn portable_pretty_renderer_groups_and_breaks_documents() {
2449        let mut runtime = Runtime::new();
2450        runtime.require_resource("std.foundation.pretty").unwrap();
2451        assert_eq!(
2452            runtime
2453                .eval_text("(std.foundation.pretty/render \"abc\")")
2454                .unwrap(),
2455            "\"abc\""
2456        );
2457        let document = "[:group \"(\" [:nest 2 [:line] \"alpha\" [:line] \"beta\"] \")\"]";
2458        assert_eq!(
2459            runtime
2460                .eval_text(&format!(
2461                    "(std.foundation.pretty/render {document} {{:width 80}})"
2462                ))
2463                .unwrap(),
2464            "\"( alpha beta)\""
2465        );
2466        assert_eq!(
2467            runtime
2468                .eval_text(&format!(
2469                    "(std.foundation.pretty/render {document} {{:width 8}})"
2470                ))
2471                .unwrap(),
2472            "\"(\\n  alpha\\n  beta)\""
2473        );
2474    }
2475
2476    #[test]
2477    fn threading_macros_expand_finite_iterator_clauses() {
2478        let mut runtime = Runtime::new();
2479        assert_eq!(runtime.eval_text("(cond-> 1 (= 1 1) inc)").unwrap(), "2");
2480        assert_eq!(runtime.eval_text("(cond-> 1 (= 1 2) inc)").unwrap(), "1");
2481        assert_eq!(runtime.eval_text("(cond->> 1 (= 1 1) inc)").unwrap(), "2");
2482        assert_eq!(runtime.eval_text("(cond->> 1 (= 1 2) inc)").unwrap(), "1");
2483        assert_eq!(
2484            runtime.eval_text("(vec (drop 2 [1 2 3 4]))").unwrap(),
2485            "[3 4]"
2486        );
2487    }
2488
2489    #[test]
2490    fn hara_file_operations_use_capability_providers() {
2491        let mut runtime = Runtime::new();
2492        assert!(runtime
2493            .eval_text("(file/read \"/sandbox/data.bin\")")
2494            .unwrap_err()
2495            .contains("unsupported or file access is denied"));
2496
2497        runtime.install_memory_file_provider("/sandbox");
2498        assert_eq!(
2499            runtime
2500                .eval_text("(file/resolve \"/sandbox\" \"data.bin\")")
2501                .unwrap(),
2502            "\"/sandbox/data.bin\""
2503        );
2504        assert_eq!(
2505            runtime
2506                .eval_text("(deref (file/write \"/sandbox/data.bin\" (bytes 0 127 255)))")
2507                .unwrap(),
2508            "nil"
2509        );
2510        assert_eq!(
2511            runtime
2512                .eval_text("(deref (file/read \"/sandbox/data.bin\"))")
2513                .unwrap(),
2514            "#bytes[0 127 -1]"
2515        );
2516        assert!(runtime
2517            .eval_text("(file/resolve \"/sandbox\" \"../escape\")")
2518            .unwrap_err()
2519            .contains("file/denied"));
2520        assert_eq!(
2521            runtime
2522                .eval_text("(deref (file/exists? \"/sandbox/data.bin\"))")
2523                .unwrap(),
2524            "true"
2525        );
2526        assert_eq!(
2527            runtime
2528                .eval_text("(deref (file/exists? \"/sandbox/missing.bin\"))")
2529                .unwrap(),
2530            "false"
2531        );
2532        assert_eq!(
2533            runtime
2534                .eval_text("(deref (file/write \"/sandbox/list/a.bin\" (bytes 1)))")
2535                .unwrap(),
2536            "nil"
2537        );
2538        assert_eq!(
2539            runtime
2540                .eval_text("(deref (file/write \"/sandbox/list/b.bin\" (bytes 2)))")
2541                .unwrap(),
2542            "nil"
2543        );
2544        assert_eq!(
2545            runtime
2546                .eval_text("(count (deref (file/list \"/sandbox/list\")))")
2547                .unwrap(),
2548            "2"
2549        );
2550        assert_eq!(
2551            runtime
2552                .eval_text("(deref (file/delete \"/sandbox/data.bin\"))")
2553                .unwrap(),
2554            "nil"
2555        );
2556        assert_eq!(
2557            runtime
2558                .eval_text("(deref (file/exists? \"/sandbox/data.bin\"))")
2559                .unwrap(),
2560            "false"
2561        );
2562    }
2563
2564    #[test]
2565    fn hara_socket_operations_use_callback_providers() {
2566        let mut runtime = Runtime::new();
2567        assert!(runtime
2568            .eval_text("(socket/connect \"localhost\" 8080 {} (fn [error socket] socket))")
2569            .unwrap_err()
2570            .contains("unsupported or network access is denied"));
2571
2572        runtime.install_loopback_socket_provider();
2573        assert_eq!(
2574            runtime
2575                .eval_text("(def socket-handle (socket/connect \"localhost\" 8080 {} (fn [error socket] socket)))")
2576                .unwrap(),
2577            "1"
2578        );
2579        assert_eq!(
2580            runtime
2581                .eval_text("(socket/send socket-handle (bytes 0 127 255))")
2582                .unwrap(),
2583            "3"
2584        );
2585        assert_eq!(
2586            runtime.eval_text("(socket/close socket-handle)").unwrap(),
2587            "nil"
2588        );
2589        assert!(runtime
2590            .eval_text("(socket/send socket-handle (bytes 1))")
2591            .unwrap_err()
2592            .contains("socket/invalid"));
2593    }
2594
2595    #[test]
2596    fn provider_registry_reports_installed_capabilities() {
2597        let mut registry = core::ProviderRegistry::new();
2598        assert_eq!(
2599            registry.capabilities(),
2600            core::ProviderCapabilities {
2601                file: false,
2602                socket: false,
2603                process: false
2604            }
2605        );
2606        registry.install_file(core::MemoryFileProvider::new("/sandbox"));
2607        registry.install_socket(core::LoopbackSocketProvider::default());
2608        registry.install_process();
2609        assert_eq!(
2610            registry.capabilities(),
2611            core::ProviderCapabilities {
2612                file: true,
2613                socket: true,
2614                process: true
2615            }
2616        );
2617        assert!(registry.file().is_some());
2618        assert!(registry.socket().is_some());
2619        assert!(registry.process());
2620    }
2621
2622    #[test]
2623    fn runtime_routes_socket_handles_through_callback_provider() {
2624        let mut runtime = Runtime::new();
2625        runtime.install_loopback_socket_provider();
2626        let socket = runtime.socket_connect("localhost", 8080).unwrap();
2627        assert_eq!(runtime.socket_send(socket, vec![1, 2, 3]).unwrap(), 3);
2628        runtime.socket_close(socket).unwrap();
2629    }
2630
2631    #[test]
2632    fn loopback_socket_is_callback_based_and_counts_bytes() {
2633        use crate::core::SocketProvider;
2634        SOCKET_EVENTS.store(0, std::sync::atomic::Ordering::SeqCst);
2635        let sockets = core::LoopbackSocketProvider::default();
2636        let handle = sockets
2637            .connect("localhost", 8080, Rc::new(count_socket_event))
2638            .unwrap();
2639        assert_eq!(sockets.send(handle, &[1, 2, 3]).unwrap(), 3);
2640        sockets.close(handle).unwrap();
2641        assert_eq!(SOCKET_EVENTS.load(std::sync::atomic::Ordering::SeqCst), 3);
2642        assert_eq!(
2643            sockets.send(handle, &[9]).unwrap_err(),
2644            core::SocketError::Invalid("unknown socket".into())
2645        );
2646    }
2647
2648    #[test]
2649    fn memory_file_provider_enforces_root_and_preserves_bytes() {
2650        use crate::core::FileProvider;
2651        let files = core::MemoryFileProvider::new("/sandbox");
2652        assert_eq!(
2653            files.resolve("/sandbox", "docs/../secret").unwrap_err(),
2654            core::FileError::Denied
2655        );
2656        let path = files.resolve("/sandbox", "data.bin").unwrap();
2657        let write = files.write(&path, vec![0, 127, 255]).unwrap();
2658        assert_eq!(
2659            write.state(),
2660            core::PromiseState::Fulfilled(core::Value::Nil)
2661        );
2662        let read = files.read(&path).unwrap();
2663        assert_eq!(
2664            read.state(),
2665            core::PromiseState::Fulfilled(core::Value::Bytes(vec![0, 127, 255]))
2666        );
2667        assert_eq!(
2668            files.read("/outside/data.bin").unwrap_err(),
2669            core::FileError::Denied
2670        );
2671    }
2672
2673    #[test]
2674    fn unsupported_capabilities_fail_stably() {
2675        use crate::core::{FileProvider, SocketProvider};
2676        let files = core::UnsupportedFileProvider;
2677        assert_eq!(
2678            files.resolve("/root", "data.bin").unwrap_err(),
2679            core::FileError::Unsupported
2680        );
2681        assert_eq!(
2682            files.read("data.bin").unwrap_err(),
2683            core::FileError::Unsupported
2684        );
2685        let sockets = core::UnsupportedSocketProvider;
2686        assert_eq!(
2687            sockets
2688                .connect("localhost", 80, Rc::new(ignore_socket_event))
2689                .unwrap_err(),
2690            core::SocketError::Unsupported
2691        );
2692        assert_eq!(
2693            sockets.send(1, &[1, 2]).unwrap_err(),
2694            core::SocketError::Unsupported
2695        );
2696        assert_eq!(
2697            sockets.close(1).unwrap_err(),
2698            core::SocketError::Unsupported
2699        );
2700    }
2701
2702    #[test]
2703    fn namespace_aliases_route_evaluation_and_resources() {
2704        let mut runtime = Runtime::new();
2705        assert!(runtime.create_namespace("hara.math"));
2706        assert!(runtime.alias_namespace("math", "hara.math"));
2707        assert_eq!(runtime.resolve_namespace("math"), "hara.math");
2708        assert_eq!(
2709            runtime
2710                .eval_in_namespace("math", "(defn answer [] 42) (answer)")
2711                .unwrap(),
2712            "42"
2713        );
2714        runtime.register_resource("helpers", "(defn helper [] 7) (helper)");
2715        assert_eq!(
2716            runtime
2717                .require_resource_in_namespace("helpers", "math")
2718                .unwrap(),
2719            "7"
2720        );
2721        assert_eq!(runtime.eval_text("(helper)").unwrap(), "7");
2722    }
2723
2724    #[test]
2725    fn foundation_host_routes_calls_to_the_native_host_type() {
2726        let mut runtime = Runtime::new();
2727        let error = runtime
2728            .eval_text(
2729                "(ns user (:require [std.foundation.host :as host])) (deref (host/call \"browser.dom\" \"set-text\" \"#sel\" \"hi\"))",
2730            )
2731            .unwrap_err();
2732        assert!(
2733            error.contains("host/unavailable"),
2734            "unexpected error: {error}"
2735        );
2736    }
2737
2738    #[test]
2739    fn host_modules_route_through_the_foundation_wrapper() {
2740        let mut runtime = Runtime::new();
2741        runtime.register_resource(
2742            "host.browser.dom",
2743            "(ns host.browser.dom (:require [std.foundation.host :as host])) (defn set-text [selector text] (host/call \"browser.dom\" \"set-text\" selector text))",
2744        );
2745        let error = runtime
2746            .eval_text(
2747                "(ns user (:require [host.browser.dom :as dom])) (deref (dom/set-text \"#sel\" \"hi\"))",
2748            )
2749            .unwrap_err();
2750        assert!(
2751            error.contains("host/unavailable"),
2752            "unexpected error: {error}"
2753        );
2754    }
2755
2756    #[test]
2757    fn namespace_registry_owns_qualified_vars_without_changing_identity() {
2758        let mut runtime = Runtime::new();
2759        runtime.use_namespace("alpha");
2760        runtime
2761            .eval_text("(def ^{:dynamic true} answer 41)")
2762            .unwrap();
2763        let local = match runtime.env.get("answer").unwrap() {
2764            core::Value::Var(var) => var.clone(),
2765            _ => panic!("definition must be a Var"),
2766        };
2767        assert_eq!(local.symbol().as_str(), "alpha/answer");
2768        let qualified = match runtime.env.get("alpha/answer").unwrap() {
2769            core::Value::Var(var) => var.clone(),
2770            _ => panic!("qualified definition must be a Var"),
2771        };
2772        assert!(local.same_identity(&qualified));
2773        assert!(qualified.is_dynamic());
2774        runtime.use_namespace("user");
2775        runtime.alias_namespace("a", "alpha");
2776        let alias = match runtime.env.get("a/answer").unwrap() {
2777            core::Value::Var(var) => var.clone(),
2778            _ => panic!("alias must resolve to a Var"),
2779        };
2780        assert!(local.same_identity(&alias));
2781    }
2782
2783    #[test]
2784    fn qualified_namespace_symbols_resolve_shared_vars_and_aliases() {
2785        let mut runtime = Runtime::new();
2786        assert!(runtime.create_namespace("alpha"));
2787        assert_eq!(
2788            runtime
2789                .eval_in_namespace("alpha", "(def answer 41)")
2790                .unwrap(),
2791            "41"
2792        );
2793        runtime.use_namespace("user");
2794        assert_eq!(runtime.eval_text("alpha/answer").unwrap(), "41");
2795        assert!(runtime.alias_namespace("a", "alpha"));
2796        assert_eq!(runtime.eval_text("a/answer").unwrap(), "41");
2797        assert_eq!(
2798            runtime
2799                .eval_text("(do (set! alpha/answer 42) alpha/answer)")
2800                .unwrap(),
2801            "42"
2802        );
2803        runtime.use_namespace("alpha");
2804        assert_eq!(runtime.eval_text("answer").unwrap(), "42");
2805    }
2806
2807    #[test]
2808    fn dash_qualifier_resolves_values_and_vars_in_the_current_namespace() {
2809        let mut runtime = Runtime::new();
2810        runtime.use_namespace("example.current");
2811        assert_eq!(
2812            runtime
2813                .eval_text("(def answer 42) [answer -/answer (= #'answer #'-/answer)]")
2814                .unwrap(),
2815            "[42 42 true]"
2816        );
2817        assert_eq!(runtime.eval_text("(quote -/answer)").unwrap(), "-/answer");
2818        assert!(runtime
2819            .eval_text("-/missing")
2820            .unwrap_err()
2821            .contains("unbound symbol"));
2822    }
2823
2824    #[test]
2825    fn defn_schema_var_references_must_resolve() {
2826        let mut runtime = Runtime::new();
2827        assert_eq!(
2828            runtime
2829                .eval_text(
2830                    "(def Customer [:map [:id :int]]) \
2831                     (defn ^{:schema #'-/Customer} customer-id [customer] (get customer :id)) \
2832                     (customer-id {:id 42})",
2833                )
2834                .unwrap(),
2835            "42"
2836        );
2837        assert!(runtime
2838            .eval_text("(defn ^{:schema #'MissingSchema} invalid [value] value)")
2839            .unwrap_err()
2840            .contains("schema Var does not exist: MissingSchema"));
2841    }
2842
2843    #[cfg(feature = "bytecode-vm")]
2844    #[test]
2845    fn bytecode_vm_canonicalizes_the_current_namespace_qualifier() {
2846        let mut runtime = Runtime::new();
2847        runtime.use_namespace("example.bytecode-current");
2848        assert_eq!(
2849            runtime
2850                .eval_bytecode_native("(def answer 42) [answer -/answer (= #'answer #'-/answer)]")
2851                .unwrap(),
2852            "[42 42 true]"
2853        );
2854    }
2855
2856    #[cfg(feature = "bytecode-vm")]
2857    #[test]
2858    fn bytecode_compiler_checks_named_schema_vars() {
2859        let mut runtime = Runtime::new();
2860        assert_eq!(
2861            runtime
2862                .eval_bytecode_native(
2863                    "(defn ^{:schema #'-/Customer} customer-id [customer] (get customer :id)) \
2864                     (def Customer [:map [:id :int]]) \
2865                     (customer-id {:id 42})",
2866                )
2867                .unwrap(),
2868            "42"
2869        );
2870        assert!(runtime
2871            .compile_bytecode("(defn ^{:schema #'MissingSchema} invalid [value] value)")
2872            .unwrap_err()
2873            .contains("schema Var does not exist: MissingSchema"));
2874    }
2875
2876    #[test]
2877    fn requiring_resolve_loads_a_qualified_resource_and_returns_its_var() {
2878        let mut runtime = Runtime::new();
2879        runtime.register_resource("demo.required", "(ns demo.required) (def answer 42)");
2880        assert_eq!(
2881            runtime
2882                .eval_text("(deref (requiring-resolve 'demo.required/answer))")
2883                .unwrap(),
2884            "42"
2885        );
2886    }
2887
2888    #[test]
2889    fn namespaces_isolate_bindings_and_can_be_selected() {
2890        let mut runtime = Runtime::new();
2891        assert_eq!(runtime.current_namespace(), "user");
2892        assert!(runtime.create_namespace("math"));
2893        runtime.eval_text("(defn answer [] 42)").unwrap();
2894        runtime.use_namespace("math");
2895        assert_eq!(
2896            runtime.eval_text("(defn answer [] 7) (answer)").unwrap(),
2897            "7"
2898        );
2899        runtime.use_namespace("user");
2900        assert_eq!(runtime.eval_text("(answer)").unwrap(), "42");
2901        runtime.use_namespace("math");
2902        assert_eq!(runtime.eval_text("(answer)").unwrap(), "7");
2903    }
2904
2905    #[test]
2906    fn generated_namespaces_configure_aliases_refers_and_intrinsics_without_sources() {
2907        let mut runtime = Runtime::new();
2908        assert_eq!(
2909            runtime.eval_text("(str/trim \"  hara  \")").unwrap(),
2910            "\"hara\""
2911        );
2912        assert_eq!(
2913            runtime
2914                .eval_text(
2915                    "(ns app (:intrinsics {:exclude [bytes] :aliases {string text}})                       (:require [hara.lib.string :as s :refer [trim]]))                       (trim (s/trim (text/upper \" x \")))"
2916                )
2917                .unwrap(),
2918            "\"X\""
2919        );
2920        assert!(runtime
2921            .eval_text("(bytes/count (bytes 1))")
2922            .unwrap_err()
2923            .contains("bytes/count"));
2924        assert_eq!(
2925            runtime
2926                .eval_text("(ns core-user (:require [hara.lib.core :as core])) (core/bit-not 0)")
2927                .unwrap(),
2928            "-1"
2929        );
2930    }
2931
2932    #[test]
2933    fn generated_namespace_require_never_falls_back_to_registered_source() {
2934        let mut runtime = Runtime::new();
2935        runtime.register_resource("std.foundation.string", "(def poisoned 42)");
2936        assert_eq!(
2937            runtime
2938                .eval_text("(ns app (:require [hara.lib.string :as text])) (text/trim \" x \")")
2939                .unwrap(),
2940            "\"x\""
2941        );
2942        assert!(runtime
2943            .eval_text("poisoned")
2944            .unwrap_err()
2945            .contains("unbound symbol"));
2946    }
2947
2948    #[test]
2949    fn strict_json_and_pretty_libraries_match_the_portable_contract() {
2950        let mut runtime = Runtime::new();
2951        assert_eq!(
2952            runtime
2953                .eval_text(
2954                    "(std.foundation.json/read \"[null,true,-2,\\\"x\\\",[3],{\\\"a\\\":4}]\")"
2955                )
2956                .unwrap(),
2957            "[nil true -2 \"x\" [3] {\"a\" 4}]"
2958        );
2959        assert_eq!(
2960            runtime
2961                .eval_text("(std.foundation.json/write {\"a\" 1 \"b\" [true nil]})")
2962                .unwrap(),
2963            "\"{\\\"a\\\":1,\\\"b\\\":[true,null]}\""
2964        );
2965        assert_eq!(
2966            runtime.eval_text("(Json/write {\"a\" 1})").unwrap(),
2967            "\"{\\\"a\\\":1}\""
2968        );
2969        assert_eq!(
2970            runtime
2971                .eval_text("(std.foundation.json/pretty {\"a\" 1} {})")
2972                .unwrap(),
2973            "\"{\\n  \\\"a\\\": 1\\n}\""
2974        );
2975        assert!(runtime
2976            .eval_text("(std.foundation.json/pretty {\"a\" 1} nil)")
2977            .unwrap_err()
2978            .contains("options map"));
2979        assert!(runtime
2980            .eval_text("(std.foundation.json/read \"1.5\")")
2981            .unwrap_err()
2982            .contains("signed 64-bit integers"));
2983        assert_eq!(
2984            runtime
2985                .eval_text("(do (require 'std.pretty) (std.pretty/pprint-str {:a [1 2]}))")
2986                .unwrap(),
2987            "\"{:a [1 2]}\""
2988        );
2989    }
2990
2991    #[test]
2992    fn restricted_edn_library_reads_and_writes_without_evaluation() {
2993        let mut runtime = Runtime::new();
2994        assert_eq!(
2995            runtime
2996                .eval_text(
2997                    "(do (require 'std.foundation.edn) \
2998                     (std.foundation.edn/read \"{:a [1 2] :b #{:x}}\"))"
2999                )
3000                .unwrap(),
3001            "{:a [1 2] :b #{:x}}"
3002        );
3003        assert_eq!(
3004            runtime
3005                .eval_text(
3006                    "(do (require 'std.foundation.edn) \
3007                     [(std.foundation.edn/write {:a [1 2]}) \
3008                      (std.foundation.edn/pretty [:a 1] {})])"
3009                )
3010                .unwrap(),
3011            "[\"{:a [1 2]}\" \"[:a 1]\"]"
3012        );
3013        assert!(runtime
3014            .eval_text(
3015                "(do (require 'std.foundation.edn) \
3016                 (std.foundation.edn/pretty [:a 1] nil))"
3017            )
3018            .unwrap_err()
3019            .contains("options map"));
3020        assert_eq!(
3021            runtime
3022                .eval_text(
3023                    "(do (require 'std.foundation.edn) \
3024                     (std.foundation.edn/read \"(+ 1 2)\"))"
3025                )
3026                .unwrap(),
3027            "(+ 1 2)"
3028        );
3029        assert_eq!(
3030            runtime
3031                .eval_text(
3032                    "(try \
3033                       (throw (ex-info \"bad input\" {:kind :invalid})) \
3034                       (catch Throwable error \
3035                         [(ex-message error) (ex-data error)]))"
3036                )
3037                .unwrap(),
3038            "[\"bad input\" {:kind :invalid}]"
3039        );
3040        assert_eq!(
3041            runtime
3042                .eval_text(
3043                    "(IExInfo/data \
3044                       (ex-info \"bad input\" {:kind :invalid}))"
3045                )
3046                .unwrap(),
3047            "{:kind :invalid}"
3048        );
3049        for source in ["1/2", "1 2"] {
3050            let escaped = source.replace('\\', "\\\\").replace('"', "\\\"");
3051            assert!(runtime
3052                .eval_text(&format!(
3053                    "(do (require 'std.foundation.edn) \
3054                     (std.foundation.edn/read \"{escaped}\"))"
3055                ))
3056                .is_err());
3057        }
3058    }
3059
3060    #[test]
3061    fn resource_sources_accept_namespace_declarations() {
3062        let mut runtime = Runtime::new();
3063        runtime.register_resource(
3064            "module",
3065            "(ns demo (:require [core])) (defn answer [] 42) (answer)",
3066        );
3067        assert_eq!(runtime.load_resource("module").unwrap(), "42");
3068    }
3069
3070    #[test]
3071    fn substrate_protocol_resource_loads_in_the_native_runtime() {
3072        let mut runtime = Runtime::new();
3073        assert_eq!(
3074            runtime
3075                .eval_text("(require 'std.lib.substrate.protocol) :loaded")
3076                .unwrap(),
3077            ":loaded"
3078        );
3079    }
3080
3081    #[test]
3082    fn guest_struct_protocols_dispatch_like_truffle() {
3083        let mut runtime = Runtime::new();
3084        assert_eq!(
3085            runtime
3086                .eval_text(
3087                    "(do (defstruct Box [value]) \
3088                     (defprotocol BoxOps (read [self]) (add [self amount])) \
3089                     (extend-type Box BoxOps \
3090                       (read [self] (field self :value)) \
3091                       (add [self amount] (+ (field self :value) amount))) \
3092                     [(read (Box 40)) \
3093                      (add (map->Box {:value 40}) 2) \
3094                      (user/read (Box 41)) \
3095                      (instance? Box (Box 1))])",
3096                )
3097                .unwrap(),
3098            "[40 42 41 true]"
3099        );
3100        assert!(runtime
3101            .eval_text(
3102                "(do (ns protocol-probe (:config {:blank true}) (:require [std.foundation :refer :all :exclude [get]])) (defstruct Missing []) (defprotocol Needed (get [self])) \
3103                     (get (Missing)))",
3104            )
3105            .unwrap_err()
3106            .contains("missing protocol implementation: protocol-probe/Needed/get"));
3107    }
3108
3109    #[test]
3110    fn guest_protocol_methods_reload_and_reject_collisions_atomically() {
3111        let mut runtime = Runtime::new();
3112        assert_eq!(
3113            runtime
3114                .eval_text(
3115                    "(do (defstruct Box [value]) \
3116                     (defprotocol BoxOps (read [self])) \
3117                     (extend-type Box BoxOps (read [self] (field self :value))) \
3118                     [(read (Box 41)) (user/read (Box 42))])",
3119                )
3120                .unwrap(),
3121            "[41 42]"
3122        );
3123        assert_eq!(
3124            runtime
3125                .eval_text("(defprotocol BoxOps (read [self]))")
3126                .unwrap(),
3127            "#protocol[user/BoxOps]"
3128        );
3129        let collision = runtime
3130            .eval_text(
3131                "(do (def ordinary 1) \
3132                 (defprotocol Broken (fresh [self]) (ordinary [self])))",
3133            )
3134            .unwrap_err();
3135        assert!(collision.contains("Protocol method Var already exists"));
3136        assert_eq!(runtime.eval_text("ordinary").unwrap(), "1");
3137        assert!(runtime.eval_text("fresh").is_err());
3138        assert!(runtime.eval_text("Broken").is_err());
3139        assert!(runtime
3140            .eval_text("(protocol-call BoxOps read (Box 1))")
3141            .is_err());
3142        assert!(runtime.eval_text("(BoxOps/read (Box 1))").is_err());
3143    }
3144
3145    #[test]
3146    fn required_guest_protocol_methods_are_called_through_namespace_aliases() {
3147        let mut runtime = Runtime::new();
3148        runtime.register_resource(
3149            "acme.box",
3150            "(ns acme.box) \
3151             (defstruct Box [value]) \
3152             (defprotocol BoxOps (read [self])) \
3153             (extend-type Box BoxOps (read [self] (field self :value)))",
3154        );
3155        assert_eq!(
3156            runtime
3157                .eval_text(
3158                    "(ns consumer (:require [acme.box :as box])) \
3159                     (box/read (acme.box/Box 42))"
3160                )
3161                .unwrap(),
3162            "42"
3163        );
3164    }
3165
3166    #[test]
3167    fn foundation_protocols_are_canonical_and_method_names_reject_bangs() {
3168        let mut runtime = Runtime::new();
3169        let Some(contract) =
3170            repo_text("specs/00-unsorted/platform-language/draft/conformance/protocols.edn")
3171        else {
3172            return;
3173        };
3174        let fixture =
3175            include_str!("../hal-test-fixtures/std/foundation/protocol_conformance.hal");
3176        assert_eq!(core::FOUNDATION_PROTOCOLS.len(), 53);
3177        assert_eq!(
3178            core::FOUNDATION_PROTOCOLS
3179                .iter()
3180                .map(|(_, methods)| methods.len())
3181                .sum::<usize>(),
3182            103
3183        );
3184        let foundation = runtime
3185            .namespace_registry
3186            .find("std.foundation")
3187            .expect("std.foundation namespace");
3188        for (name, methods) in core::FOUNDATION_PROTOCOLS {
3189            assert!(
3190                contract.contains(&format!(":name {name}")),
3191                "shared contract is missing {name}"
3192            );
3193            let namespace_name = core::builtin_protocol_namespace(name);
3194            let namespace = runtime
3195                .namespace_registry
3196                .find(&namespace_name)
3197                .unwrap_or_else(|| panic!("missing {namespace_name} namespace"));
3198            let protocol = namespace
3199                .resolve(&lang::data::Symbol::parse(name))
3200                .unwrap_or_else(|| panic!("missing {namespace_name}/{name}"))
3201                .deref_value();
3202            let core::Value::Protocol(descriptor) = &protocol else {
3203                panic!("{namespace_name}/{name} is not a protocol");
3204            };
3205            assert_eq!(descriptor.name, core::builtin_protocol_name(name));
3206            assert_eq!(descriptor.methods.len(), methods.len());
3207            assert!(descriptor
3208                .methods
3209                .keys()
3210                .all(|method| !method.ends_with('!')));
3211            assert_eq!(
3212                foundation
3213                    .resolve(&lang::data::Symbol::parse(name))
3214                    .unwrap_or_else(|| panic!("missing std.foundation/{name} alias"))
3215                    .deref_value(),
3216                protocol
3217            );
3218            for (method, _) in *methods {
3219                let canonical_method = namespace
3220                    .resolve(&lang::data::Symbol::parse(method))
3221                    .unwrap_or_else(|| panic!("missing {namespace_name}/{method}"))
3222                    .deref_value();
3223                let aliased_method = foundation
3224                    .resolve(&lang::data::Symbol::parse(&format!("{name}/{method}")))
3225                    .unwrap_or_else(|| panic!("missing global alias {name}/{method}"))
3226                    .deref_value();
3227                assert_eq!(aliased_method, canonical_method);
3228                assert!(
3229                    fixture.contains(&format!("({namespace_name}/{method} fixture")),
3230                    "shared fixture does not directly call {namespace_name}/{method}"
3231                );
3232            }
3233        }
3234        for protocol in [
3235            "IColl",
3236            "IMetadata",
3237            "IHasRuntime",
3238            "IRanged",
3239            "IValidate",
3240            "IComponentOptions",
3241            "IComponentProps",
3242            "IComponentQuery",
3243            "IComponentTrack",
3244        ] {
3245            let namespace = core::builtin_protocol_namespace(protocol);
3246            assert!(
3247                runtime
3248                    .eval_text(&format!("{namespace}/{protocol}"))
3249                    .unwrap_err()
3250                    .contains("unbound symbol"),
3251                "{namespace}/{protocol} must not be guest-visible"
3252            );
3253            assert!(
3254                runtime
3255                    .eval_text(&format!("std.foundation/{protocol}"))
3256                    .unwrap_err()
3257                    .contains("unbound symbol"),
3258                "std.foundation/{protocol} must not be guest-visible"
3259            );
3260        }
3261        assert_eq!(
3262            runtime
3263                .eval_text("(std.protocol.icount/count [1 2 3])")
3264                .unwrap(),
3265            "3"
3266        );
3267        assert_eq!(
3268            runtime
3269                .eval_text("(std.protocol.icas/cas (atom 1) 1 2)")
3270                .unwrap(),
3271            "true"
3272        );
3273        assert_eq!(
3274            runtime
3275                .eval_text(
3276                    "(std.protocol.ireduce/reduce \
3277                       [1 2 3] (fn [left right] (+ left right)) 0)",
3278                )
3279                .unwrap(),
3280            "6"
3281        );
3282        assert_eq!(
3283            runtime
3284                .eval_text("(std.protocol.ipromise/state (std.foundation.promise/from 7))")
3285                .unwrap(),
3286            ":fulfilled"
3287        );
3288        assert_eq!(
3289            runtime
3290                .eval_text("(require 'std.protocol.ifind) :loaded")
3291                .unwrap(),
3292            ":loaded"
3293        );
3294        assert_eq!(
3295            runtime
3296                .eval_text("(defprotocol PredicateProtocol (ready? [self]))")
3297                .unwrap(),
3298            "#protocol[user/PredicateProtocol]"
3299        );
3300        assert!(runtime
3301            .eval_text("(defprotocol MutatingProtocol (mutate! [self]))")
3302            .unwrap_err()
3303            .contains("protocol method names must not end with !"));
3304    }
3305
3306    #[test]
3307    fn shared_foundation_protocol_conformance_fixture_runs_in_the_native_runtime() {
3308        let mut runtime = Runtime::new();
3309        let result = runtime
3310            .eval_text(include_str!(
3311                "../../lib/test-fixtures/std/foundation/protocol_conformance.hal"
3312            ))
3313            .unwrap();
3314        assert!(!result.contains(":pass false"), "{result}");
3315        assert_eq!(result.matches(":pass true").count(), 53, "{result}");
3316    }
3317
3318    #[test]
3319    fn shared_foundation_protocol_functionality_fixture_runs_in_the_native_runtime() {
3320        let source =
3321            include_str!("../hal-test-fixtures/std/foundation/protocol_functionality.hal");
3322        let Some(catalog) = repo_text(
3323            "specs/00-unsorted/platform-language/draft/conformance/protocol-method-cases.edn",
3324        ) else {
3325            return;
3326        };
3327        assert_eq!(catalog.matches("{:protocol ").count(), 88);
3328        let mut runtime = Runtime::new();
3329        let result = runtime.eval_text(source).unwrap();
3330        assert!(!result.contains(":pass false"), "{result}");
3331        assert_eq!(result.matches(":pass true").count(), 88, "{result}");
3332
3333        let method_vars = source
3334            .lines()
3335            .filter_map(|line| {
3336                let line = line.trim();
3337                let start = line.find("(protocol-case ")?;
3338                line[(start + "(protocol-case ".len())..]
3339                    .split_whitespace()
3340                    .nth(2)
3341            })
3342            .collect::<Vec<_>>();
3343        assert_eq!(method_vars.len(), 88);
3344        for method_var in method_vars {
3345            let mut segments = method_var.split(['.', '/']);
3346            let protocol_namespace = segments.nth(2).expect("protocol namespace");
3347            let method = segments.next().expect("protocol method");
3348            assert!(
3349                catalog.contains(&format!(":method {method} ")),
3350                "case catalog is missing {protocol_namespace}/{method}"
3351            );
3352            let error = runtime.eval_text(&format!("({method_var})")).unwrap_err();
3353            assert!(
3354                error.contains("protocol/arity"),
3355                "{method_var} returned an uncategorized arity error: {error}"
3356            );
3357        }
3358
3359        let failure_forms = source
3360            .lines()
3361            .filter_map(|line| {
3362                let line = line.trim();
3363                let start = line.find("'(std.protocol.")? + 1;
3364                let form = &line[start..];
3365                let mut depth = 0_usize;
3366                for (index, character) in form.char_indices() {
3367                    match character {
3368                        '(' => depth += 1,
3369                        ')' => {
3370                            depth -= 1;
3371                            if depth == 0 {
3372                                return Some(form[..=index].to_owned());
3373                            }
3374                        }
3375                        _ => {}
3376                    }
3377                }
3378                None
3379            })
3380            .collect::<Vec<_>>();
3381        assert_eq!(failure_forms.len(), 88);
3382        for failure_form in failure_forms {
3383            let call = failure_form.replacen("unsupported", "(UnsupportedUseCase)", 1);
3384            let error = runtime.eval_text(&call).unwrap_err();
3385            assert!(
3386                error.contains("protocol/unsupported-receiver"),
3387                "{call} returned an uncategorized dispatch error: {error}"
3388            );
3389        }
3390
3391        assert_eq!(
3392            runtime
3393                .eval_text(
3394                    "(try (std.protocol.icount/count) false \
3395                       (catch Throwable error true))"
3396                )
3397                .unwrap(),
3398            "true"
3399        );
3400    }
3401
3402    #[test]
3403    fn foundation_iterator_protocols_traverse_and_close_native_iterators() {
3404        let mut runtime = Runtime::new();
3405        assert_eq!(
3406            runtime
3407                .eval_text(
3408                    "(let [it (IIter/iter [1 2])] \
3409                       [(IIterator/iter-next? it) \
3410                        (IIterator/iter-next it) \
3411                        (IIterator/iter-next it) \
3412                        (IIterator/iter-next? it) \
3413                        (IClose/close it)])"
3414                )
3415                .unwrap(),
3416            "[true 1 2 false nil]"
3417        );
3418    }
3419
3420    #[test]
3421    fn foundation_state_protocols_dispatch_and_watch_keys_come_first() {
3422        let mut runtime = Runtime::new();
3423        assert_eq!(
3424            runtime
3425                .eval_text(
3426                    "(let [a (atom 1) seen (atom nil)] \
3427                       (IWatch/watch-add a :log \
3428                         (fn [key ref old new] \
3429                           (IReset/reset seen [key old new]))) \
3430                       (IReset/reset a 2) \
3431                       [(IDeref/deref a) \
3432                        (IDeref/deref seen)])"
3433                )
3434                .unwrap(),
3435            "[2 [:log 1 2]]"
3436        );
3437    }
3438
3439    #[test]
3440    fn shared_protocol_conformance_fixture_runs_in_the_native_runtime() {
3441        let mut runtime = Runtime::new();
3442        assert_eq!(
3443            runtime
3444                .eval_text(include_str!(
3445                    "../../lib/test-fixtures/std/lib/substrate/protocol_conformance.hal"
3446                ))
3447                .unwrap(),
3448            "[40 42]"
3449        );
3450    }
3451
3452    #[test]
3453    fn shared_substrate_frame_conformance_fixture_runs_in_the_native_runtime() {
3454        let mut runtime = Runtime::new();
3455        assert_eq!(
3456            runtime
3457                .eval_text(include_str!(
3458                    "../../lib/test-fixtures/std/lib/substrate/frame_conformance.hal"
3459                ))
3460                .unwrap(),
3461            "\"{\\\"version\\\":\\\"substrate.v1\\\",\\\"kind\\\":\\\"request\\\",\\\"id\\\":\\\"req-1\\\",\\\"source\\\":\\\"client/a\\\",\\\"target\\\":\\\"server/b\\\",\\\"space\\\":\\\"workspace/main\\\",\\\"meta\\\":{\\\"trace\\\":\\\"trace-1\\\"},\\\"action\\\":\\\"math/add\\\",\\\"args\\\":[19,23],\\\"reply_to\\\":null,\\\"status\\\":null,\\\"data\\\":null,\\\"error\\\":null,\\\"signal\\\":null,\\\"cause\\\":null}\""
3462        );
3463        assert!(runtime
3464            .eval_text(
3465                "(do (require 'std.lib.substrate.frame) \\
3466                     (std.lib.substrate.frame/normalize-frame {:kind :unknown :id \"evt-1\"}))",
3467            )
3468            .is_err());
3469    }
3470
3471    #[test]
3472    fn shared_substrate_node_lifecycle_fixture_runs_in_the_native_runtime() {
3473        let mut runtime = Runtime::new();
3474        assert_eq!(
3475            runtime
3476                .eval_text(include_str!(
3477                    "../../lib/test-fixtures/std/lib/substrate/node_lifecycle_conformance.hal"
3478                ))
3479                .unwrap(),
3480            "[84 42 :rejected]"
3481        );
3482    }
3483
3484    #[test]
3485    fn atom_backed_substrate_capabilities_work_in_the_native_runtime() {
3486        let mut runtime = Runtime::new();
3487        assert_eq!(
3488            runtime
3489                .eval_text(
3490                    "(require 'std.lib.substrate) \
3491                     (def node (std.lib.substrate/node-create \"node-1\")) \
3492                     [(std.lib.substrate.protocol/set-service node \"cache\" 42) \
3493                      (std.lib.substrate.protocol/get-service node \"cache\") \
3494                      (std.lib.substrate.protocol/set-space-state node \"main\" {:count 1}) \
3495                      (std.lib.substrate.protocol/get-space-state node \"main\") \
3496                      (def subscription (std.lib.substrate.protocol/subscribe node \"main\" \"changed\" \"sub-1\" {})) \
3497                      (std.lib.substrate.protocol/receive-frame node subscription {:transport-id \"peer-a\"}) \
3498                      (std.lib.substrate.protocol/list-subscriptions node \"main\" \"changed\")]",
3499                )
3500                .unwrap(),
3501            "[42 42 {:count 1} {:count 1} #std.lib.substrate/SubstrateFrame{:id \"sub-1\" :kind :subscribe :space \"main\" :meta {} :action nil :args [] :reply-to nil :status nil :data nil :error nil :signal \"changed\" :cause nil} {\"peer-a\" {:id \"sub-1\" :meta {}}} [\"peer-a\"]]"
3502        );
3503    }
3504
3505    #[test]
3506    fn substrate_routes_streams_and_settles_transport_requests() {
3507        let mut runtime = Runtime::new();
3508        assert_eq!(
3509            runtime
3510                .eval_text(
3511                    "(require 'std.lib.substrate) \
3512                     (def node (std.lib.substrate/node-create \"node-1\")) \
3513                     (std.lib.substrate.protocol/attach-transport node \"peer-a\" \
3514                       (fn [frame] \
3515                         (std.lib.substrate.protocol/set-service node \"sent\" \
3516                           (std.lib.substrate.protocol/frame-data frame)))) \
3517                     (def subscription (std.lib.substrate.protocol/subscribe node \"main\" \"changed\" \"sub-1\" {})) \
3518                     (std.lib.substrate.protocol/receive-frame node subscription {:transport-id \"peer-a\"}) \
3519                     (std.lib.substrate.protocol/publish node \"main\" \"changed\" 42 {:id \"evt-1\"}) \
3520                     (std.lib.substrate.protocol/get-service node \"sent\")",
3521                )
3522                .unwrap(),
3523            "42"
3524        );
3525
3526        assert_eq!(
3527            runtime
3528                .eval_text(
3529                    "(def requester (std.lib.substrate/node-create \"node-2\")) \
3530                     (std.lib.substrate.protocol/attach-transport requester \"peer-b\" \
3531                       (fn [frame] \
3532                         (std.lib.substrate.protocol/receive-frame requester \
3533                           (std.lib.substrate/node-frame :response \"res-1\" \"main\" {} nil [] \
3534                             (std.lib.substrate.protocol/frame-id frame) :ok 84 nil nil nil) \
3535                           {:transport-id \"peer-b\"}))) \
3536                     (def reply (std.lib.substrate.protocol/request requester \"main\" \"sum\" [] \
3537                                  {:id \"req-1\" :transport-id \"peer-b\"})) \
3538                     (promise/value reply)",
3539                )
3540                .unwrap(),
3541            "84"
3542        );
3543    }
3544
3545    #[test]
3546    fn substrate_cancellation_and_rejection_settle_pending_promises() {
3547        let mut runtime = Runtime::new();
3548        assert_eq!(
3549            runtime
3550                .eval_text(
3551                    "(require 'std.lib.substrate) \
3552                     (def node (std.lib.substrate/node-create \"node-1\")) \
3553                     (std.lib.substrate.protocol/attach-transport node \"peer-a\" (fn [frame] nil)) \
3554                     (def cancelled (std.lib.substrate.protocol/request node \"main\" \"wait\" [] \
3555                                      {:id \"req-cancel\" :transport-id \"peer-a\"})) \
3556                     (std.lib.substrate.protocol/cancel-request node \"req-cancel\" :cancelled) \
3557                     (promise/state cancelled)",
3558                )
3559                .unwrap(),
3560            ":rejected"
3561        );
3562    }
3563
3564    #[test]
3565    fn registered_resources_load_into_the_runtime_environment() {
3566        let mut runtime = Runtime::new();
3567        runtime.register_resource("demo", "(defn answer [] 42) (answer)");
3568        assert_eq!(runtime.load_resource("demo").unwrap(), "42");
3569        assert_eq!(runtime.eval_text("(answer)").unwrap(), "42");
3570        assert_eq!(runtime.require_resource("demo").unwrap(), "42");
3571        assert_eq!(runtime.require_resource("demo").unwrap(), ":loaded");
3572    }
3573
3574    #[test]
3575    fn vector_literals_are_values() {
3576        let mut runtime = Runtime::new();
3577        assert_eq!(runtime.eval_text("[1 2 3]").unwrap(), "[1 2 3]");
3578    }
3579
3580    #[test]
3581    fn set_literals_reject_duplicate_items() {
3582        let mut runtime = Runtime::new();
3583        assert!(runtime
3584            .eval_text("#{1 (+ 1 1) 1}")
3585            .unwrap_err()
3586            .contains("Duplicate item"));
3587        assert!(runtime
3588            .eval_text("(count #{1 2 2})")
3589            .unwrap_err()
3590            .contains("Duplicate item"));
3591        assert_eq!(runtime.eval_text("(has? #{1 2} 2)").unwrap(), "true");
3592        assert_eq!(runtime.eval_text("(conj #{1} 2)").unwrap(), "#{1 2}");
3593        assert_eq!(runtime.eval_text("(= (set 1 2 1) #{1 2})").unwrap(), "true");
3594        assert_eq!(runtime.eval_text("(= #{1 2} #{2 1})").unwrap(), "true");
3595        assert_eq!(runtime.eval_text("(get #{1 2} 2 :missing)").unwrap(), "2");
3596    }
3597
3598    #[test]
3599    fn syntax_quote_matches_java_expansion_semantics() {
3600        let mut runtime = Runtime::new();
3601        assert_eq!(runtime.eval_text("`foo").unwrap(), "foo");
3602        assert_eq!(
3603            runtime.eval_text("`(a ~(+ 1 2) ~@[4 5])").unwrap(),
3604            "(a 3 4 5)"
3605        );
3606        assert_eq!(runtime.eval_text("`[a ~(+ 1 2)]").unwrap(), "[a 3]");
3607        assert_eq!(runtime.eval_text("`{:a ~(+ 1 2)}").unwrap(), "{:a 3}");
3608        assert_eq!(
3609            runtime.eval_text("`(a (unquote))").unwrap_err(),
3610            "unquote expects one argument"
3611        );
3612        assert_eq!(
3613            runtime.eval_text("`(a ~@1)").unwrap_err(),
3614            "iter expects a collection, got 1"
3615        );
3616    }
3617
3618    #[test]
3619    fn deref_of_a_global_atom_targets_the_atom_value_not_its_namespace_var() {
3620        let mut runtime = Runtime::new();
3621        assert_eq!(
3622            runtime
3623                .eval_text("(do (def state (atom [1])) (deref state))")
3624                .unwrap(),
3625            "[1]"
3626        );
3627        assert_eq!(
3628            runtime
3629                .eval_text("(do (swap! state conj 2) (deref state))")
3630                .unwrap(),
3631            "[1 2]"
3632        );
3633    }
3634
3635    #[test]
3636    fn fn_star_and_eval_forms_execute_while_hash_dispatch_extensions_are_rejected() {
3637        let mut runtime = Runtime::new();
3638        assert_eq!(runtime.eval_text("((fn* [x] (+ x 1)) 4)").unwrap(), "5");
3639        assert!(runtime
3640            .eval_text("#=(+ 2 3)")
3641            .unwrap_err()
3642            .contains("No dispatch macro for: ="));
3643        assert!(runtime
3644            .eval_text("#[(def x 4) (+ x 2)]")
3645            .unwrap_err()
3646            .contains("No dispatch macro for: ["));
3647        assert!(runtime
3648            .eval_text("(eval)")
3649            .unwrap_err()
3650            .contains("one form"));
3651    }
3652
3653    #[test]
3654    fn runtime_readable_strings_escape_and_round_trip() {
3655        let mut runtime = Runtime::new();
3656        let sources = [
3657            r#""quote: \" slash: \\ newline: \n tab: \t""#,
3658            r#"{:text "line\nvalue" :nested ["a\tb" "c\\d"]}"#,
3659            r#"["\u0000" "unicode λ"]"#,
3660            r#"#"a\"b""#,
3661        ];
3662        for source in sources {
3663            let readable = runtime.eval_text(source).unwrap();
3664            assert_eq!(
3665                kernel::parse(&readable).unwrap(),
3666                kernel::parse(source).unwrap()
3667            );
3668        }
3669    }
3670
3671    #[test]
3672    fn reader_literals_are_first_class_runtime_values() {
3673        let mut runtime = Runtime::new();
3674        let cases = [
3675            ("1.5", "1.5"),
3676            ("\\newline", "\\newline"),
3677            ("#\"a+\"", "#\"a+\""),
3678            ("#demo {:a 1}", "#demo{:a 1}"),
3679            ("##Inf", "##Inf"),
3680            ("##-Inf", "##-Inf"),
3681            ("##NaN", "##NaN"),
3682        ];
3683        for (source, expected) in cases {
3684            assert_eq!(runtime.eval_text(source).unwrap(), expected, "{source}");
3685        }
3686        for source in ["123N", "1.20M"] {
3687            assert!(runtime.eval_text(source).is_err(), "{source}");
3688        }
3689        for unsupported in ["9223372036854775808"] {
3690            assert!(runtime.eval_text(unsupported).is_err(), "{unsupported}");
3691        }
3692        assert_eq!(runtime.eval_text("(= ##NaN ##NaN)").unwrap(), "true");
3693        assert_eq!(runtime.eval_text("'#demo [1 2]").unwrap(), "#demo[1 2]");
3694        assert_eq!(runtime.eval_text("()").unwrap(), "()");
3695        assert_eq!(runtime.eval_text("(list? ())").unwrap(), "true");
3696        assert_eq!(runtime.eval_text("(char? \\x)").unwrap(), "true");
3697        assert_eq!(runtime.eval_text("(char? \"x\")").unwrap(), "false");
3698        assert_eq!(runtime.eval_text("(nth [1 nil 3] 1)").unwrap(), "nil");
3699        assert_eq!(runtime.eval_text("(nth '(1 nil 3) 1)").unwrap(), "nil");
3700    }
3701
3702    #[test]
3703    fn basic_math_has_the_portable_root_surface_and_explicit_numeric_boundary() {
3704        let mut runtime = Runtime::new();
3705        assert_eq!(
3706            runtime
3707                .eval_text(
3708                    "[(= E 2.718281828459045) (= PI 3.141592653589793) \
3709                     (sin 0) (cos 0) (tan 0) (asin 0) (acos 1) (atan 0) \
3710                     (atan2 0 1) (sinh 0) (cosh 0) (tanh 0) \
3711                     (asinh 0) (acosh 1) (atanh 0) \
3712                     (floor 1.75) (ceil 1.25) (pow 2 3) (abs -3) \
3713                     (exp 0) (sqrt 9)]"
3714                )
3715                .unwrap(),
3716            "[true true 0 1 0 0 0 0 0 0 1 0 0 0 0 1 2 8 3 1 3]"
3717        );
3718        assert_eq!(runtime.eval_text("(= (sqrt -1) ##NaN)").unwrap(), "true");
3719        assert_eq!(runtime.eval_text("(sqrt (long 9.9))").unwrap(), "3");
3720        assert_eq!(runtime.eval_text("(sqrt (double 9))").unwrap(), "3");
3721        assert!(runtime
3722            .eval_text("(abs -9223372036854775808)")
3723            .unwrap_err()
3724            .contains("overflow"));
3725        assert_eq!(
3726            runtime
3727                .eval_text("[(= (asinh 1.0e300) ##Inf) (= (acosh 1.0e300) ##Inf)]")
3728                .unwrap(),
3729            "[false false]"
3730        );
3731        for source in ["(sin)", "(pow 2)", "(sqrt \"9\")"] {
3732            assert!(runtime.eval_text(source).is_err(), "{source}");
3733        }
3734    }
3735
3736    #[test]
3737    fn closed_native_method_inventory_is_classified_and_callable() {
3738        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> &'a Form {
3739            entries
3740                .iter()
3741                .find_map(|(candidate, value)| match candidate {
3742                    Form::Keyword(name) if name == key => Some(value),
3743                    _ => None,
3744                })
3745                .unwrap_or_else(|| panic!("missing :{key}"))
3746        }
3747        fn symbols(value: &Form, label: &str) -> Vec<String> {
3748            let Form::Vector(values) = value else {
3749                panic!("{label} must be a vector")
3750            };
3751            values
3752                .iter()
3753                .map(|value| match value {
3754                    Form::Symbol(name) => name.clone(),
3755                    _ => panic!("{label} must contain symbols"),
3756                })
3757                .collect()
3758        }
3759        fn classified(value: Option<&Form>, all: &[String], label: &str) -> Vec<String> {
3760            match value {
3761                None => Vec::new(),
3762                Some(Form::Keyword(marker)) if marker == "all" => all.to_vec(),
3763                Some(value) => symbols(value, label),
3764            }
3765        }
3766        fn wrapper_source(path: &str) -> &'static str {
3767            EMBEDDED_HAL_RESOURCES
3768                .iter()
3769                .find_map(|(_, resource_path, source)| (*resource_path == path).then_some(*source))
3770                .unwrap_or_else(|| panic!("unknown wrapper source: {path}"))
3771        }
3772
3773        let Some(contract_source) =
3774            repo_text("specs/00-unsorted/platform-language/draft/conformance/native.edn")
3775        else {
3776            return;
3777        };
3778        let contract = kernel::parse_forms(&contract_source).unwrap().remove(0);
3779        let Form::Map(contract) = contract else {
3780            panic!("native contract must be a map")
3781        };
3782        let Form::Map(inventory) = entry(&contract, "inventory") else {
3783            panic!(":inventory must be a map")
3784        };
3785        assert!(matches!(entry(inventory, "closed"), Form::Bool(true)));
3786        let Form::Vector(types) = entry(&contract, "types") else {
3787            panic!(":types must be a vector")
3788        };
3789        assert_eq!(
3790            entry(inventory, "type-count"),
3791            &Form::Number(types.len() as i64)
3792        );
3793
3794        let mut specified = Vec::new();
3795        let mut direct_cases = Vec::new();
3796        for value in types {
3797            let Form::Map(native_type) = value else {
3798                panic!("native type entries must be maps")
3799            };
3800            let Form::Symbol(name) = entry(native_type, "name") else {
3801                panic!("native :name must be a symbol")
3802            };
3803            let methods = symbols(entry(native_type, "methods"), ":methods");
3804            let Form::Keyword(availability) = entry(native_type, "availability") else {
3805                panic!("native :availability must be a keyword")
3806            };
3807            assert!(
3808                ["implemented", "capability-gated"].contains(&availability.as_str()),
3809                "unsupported availability: {availability}"
3810            );
3811            let Form::Map(classification) = entry(native_type, "method-classification") else {
3812                panic!(":method-classification must be a map")
3813            };
3814            let hal_wrappers = classified(
3815                classification.iter().find_map(|(key, value)| {
3816                    matches!(key, Form::Keyword(name) if name == "hal-wrapper").then_some(value)
3817                }),
3818                &methods,
3819                ":hal-wrapper",
3820            );
3821            let primitives = classified(
3822                classification.iter().find_map(|(key, value)| {
3823                    matches!(key, Form::Keyword(name) if name == "foundation-primitive")
3824                        .then_some(value)
3825                }),
3826                &methods,
3827                ":foundation-primitive",
3828            );
3829            let native_only = classified(
3830                classification.iter().find_map(|(key, value)| {
3831                    matches!(key, Form::Keyword(name) if name == "native-only").then_some(value)
3832                }),
3833                &methods,
3834                ":native-only",
3835            );
3836            let mut exposed = hal_wrappers.clone();
3837            exposed.extend(primitives);
3838            exposed.extend(native_only);
3839            assert_eq!(
3840                exposed
3841                    .iter()
3842                    .collect::<std::collections::HashSet<_>>()
3843                    .len(),
3844                methods.len(),
3845                "{name} methods must have one Foundation exposure"
3846            );
3847            assert_eq!(
3848                methods.iter().collect::<std::collections::HashSet<_>>(),
3849                exposed.iter().collect::<std::collections::HashSet<_>>(),
3850                "{name} method classifications are incomplete"
3851            );
3852            if !hal_wrappers.is_empty() {
3853                let Form::String(path) = entry(native_type, "wrapper-source") else {
3854                    panic!("{name} HAL wrappers require :wrapper-source")
3855                };
3856                let source = wrapper_source(path);
3857                for method in &hal_wrappers {
3858                    assert!(
3859                        source.contains(&format!("{name}/{method}")),
3860                        "missing HAL wrapper for {name}/{method}"
3861                    );
3862                }
3863            }
3864            let mut type_cases = Vec::new();
3865            for method in &methods {
3866                let symbol = format!("{name}/{method}");
3867                type_cases.push(format!(
3868                    "(native-method-result '{symbol} \
3869                     (fn [] ({symbol} nil nil nil nil nil nil nil nil nil)))"
3870                ));
3871            }
3872            direct_cases.push((name.clone(), type_cases));
3873            specified.push((name.clone(), methods));
3874        }
3875
3876        let runtime_inventory = core::NATIVE_TYPES
3877            .iter()
3878            .map(|(name, methods)| {
3879                (
3880                    (*name).to_owned(),
3881                    methods.iter().map(|method| (*method).to_owned()).collect(),
3882                )
3883            })
3884            .collect::<Vec<(String, Vec<String>)>>();
3885        assert_eq!(specified, runtime_inventory);
3886        assert_eq!(
3887            entry(inventory, "method-count"),
3888            &Form::Number(
3889                specified
3890                    .iter()
3891                    .map(|(_, methods)| methods.len())
3892                    .sum::<usize>() as i64
3893            )
3894        );
3895
3896        for (type_name, type_cases) in &direct_cases {
3897            let mut runtime = Runtime::new();
3898            runtime
3899                .eval_text(include_str!(
3900                    "../../lib/test-fixtures/std/foundation/native_method_conformance.hal"
3901                ))
3902                .unwrap();
3903            for direct_case in type_cases {
3904                let result = runtime.eval_text(direct_case).unwrap();
3905                assert!(
3906                    result.contains(":pass true"),
3907                    "{direct_case} returned {result}"
3908                );
3909            }
3910            assert!(
3911                !type_cases.is_empty(),
3912                "{type_name} has no conformance cases"
3913            );
3914        }
3915        assert_eq!(
3916            direct_cases
3917                .iter()
3918                .map(|(_, type_cases)| type_cases.len())
3919                .sum::<usize>(),
3920            specified
3921                .iter()
3922                .map(|(_, methods)| methods.len())
3923                .sum::<usize>()
3924        );
3925        let mut runtime = Runtime::new();
3926        assert_eq!(
3927            runtime
3928                .eval_text(
3929                    "[(Error/message \
3930                        (Error/new \"native failure\" {})) \
3931                      (string? (Error/class \
3932                        (Error/new \"native failure\" {}))) \
3933                      (Runtime/load-string \"(+ 19 23)\")]"
3934                )
3935                .unwrap(),
3936            "[\"native failure\" true 42]"
3937        );
3938    }
3939
3940    #[test]
3941    fn native_types_are_descriptors_and_foundation_libraries_are_hal_wrappers() {
3942        let mut runtime = Runtime::new();
3943        assert_eq!(
3944            runtime
3945                .eval_text(
3946                    "[(str std.native.Maths) \
3947                      (INamespaced/name std.native.Maths) \
3948                      (INamespaced/namespace std.native.Maths) \
3949                      (= std.native.Maths (with-meta std.native.Maths {:doc \"math\"})) \
3950                      (Maths/sin 0) \
3951                      (String/upper \"hara\") \
3952                      (str/upper \"hara\") \
3953                      (Bytes/u8 -1) \
3954                      (bytes/u8 -1)]"
3955                )
3956                .unwrap(),
3957            "[\"#<native-type std.native.Maths>\" \"Maths\" \"std.native\" true 0 \"HARA\" \"HARA\" 255 255]"
3958        );
3959        assert!(runtime.eval_text("(std.native.Maths 1)").is_err());
3960        assert_eq!(
3961            runtime
3962                .eval_text("(ns legacy.activation (:config {:builtins [inc]}))")
3963                .unwrap(),
3964            "nil"
3965        );
3966    }
3967
3968    #[test]
3969    fn startup_defaults_expose_edn_native_types_and_protocols() {
3970        let mut runtime = Runtime::new();
3971        assert_eq!(
3972            runtime
3973                .eval_text(
3974                    "(ns startup.defaults) \
3975                     [(edn/write {:a 1}) \
3976                      (= Maths std.native.Maths std.foundation/Maths) \
3977                      (= Edn std.native.Edn std.foundation/Edn) \
3978                      (= Json std.native.Json std.foundation/Json) \
3979                      (= Host std.native.Host std.foundation/Host) \
3980                      (= Arr std.native.Arr std.foundation/Arr) \
3981                      (= Obj std.native.Obj std.foundation/Obj) \
3982                      (let [arr (Arr/new 1 2)] \
3983                        (Arr/set-index arr 1 7) \
3984                        (Arr/get-index arr 1)) \
3985                      (let [obj (Obj/new \"a\" 1)] \
3986                        (Obj/set-key obj \"a\" 9) \
3987                        (Obj/get-key obj \"a\")) \
3988                      (ICount/count [1 2 3])]"
3989                )
3990                .unwrap(),
3991            "[\"{:a 1}\" true true true true true true 7 9 3]"
3992        );
3993        assert_eq!(
3994            runtime
3995                .eval_text(
3996                    "(ns blank.native (:config {:blank true})) \
3997                     [(= Iter std.native.Iter) \
3998                      (Iter/iter-next (Iter/iter-map (fn [value] value) [1]))]"
3999                )
4000                .unwrap(),
4001            "[true 1]"
4002        );
4003        let symbols = runtime.visible_symbols();
4004        assert!(symbols.iter().any(|symbol| symbol == "edn/pretty"));
4005        for native_type in [
4006            "Maths",
4007            "Numbers",
4008            "Bits",
4009            "String",
4010            "Bytes",
4011            "File",
4012            "Socket",
4013            "Promise",
4014            "Coroutine",
4015            "Arr",
4016            "Obj",
4017            "Runtime",
4018            "Printer",
4019            "Edn",
4020            "Json",
4021            "Host",
4022            "Regex",
4023            "UUID",
4024            "Error",
4025            "Iter",
4026            "Kernel",
4027        ] {
4028            assert!(
4029                symbols.iter().any(|symbol| symbol == native_type),
4030                "{native_type}"
4031            );
4032        }
4033    }
4034
4035    #[test]
4036    fn strings_and_maps_are_values() {
4037        let mut runtime = Runtime::new();
4038        assert_eq!(runtime.eval_text("\"hello\"").unwrap(), "\"hello\"");
4039        assert_eq!(runtime.eval_text("{\"a\" 1}").unwrap(), "{\"a\" 1}");
4040    }
4041
4042    #[test]
4043    fn application_and_pair_helpers_support_bootstrap_code() {
4044        let mut runtime = Runtime::new();
4045        assert_eq!(runtime.eval_text("(identity 42)").unwrap(), "42");
4046        assert_eq!(runtime.eval_text("(apply + [19 23])").unwrap(), "42");
4047        assert_eq!(runtime.eval_text("(apply + 19 [23])").unwrap(), "42");
4048        assert_eq!(runtime.eval_text("(key [1 2])").unwrap(), "1");
4049        assert_eq!(runtime.eval_text("(val [1 2])").unwrap(), "2");
4050        assert_eq!(runtime.eval_text("(reverse [1 2 3])").unwrap(), "(3 2 1)");
4051    }
4052
4053    #[test]
4054    fn structural_hashes_are_stable_and_order_independent_for_maps_and_sets() {
4055        let mut runtime = Runtime::new();
4056        let _ = &mut runtime;
4057        let map_a = core::Value::Map(
4058            vec![
4059                (core::Value::Keyword("a".into()), core::Value::Number(1)),
4060                (core::Value::Keyword("b".into()), core::Value::Number(2)),
4061            ]
4062            .into_iter()
4063            .collect(),
4064        );
4065        let map_b = core::Value::Map(
4066            vec![
4067                (core::Value::Keyword("b".into()), core::Value::Number(2)),
4068                (core::Value::Keyword("a".into()), core::Value::Number(1)),
4069            ]
4070            .into_iter()
4071            .collect(),
4072        );
4073        let set_a = core::Value::Set(
4074            vec![
4075                core::Value::Number(1),
4076                core::Value::Number(2),
4077                core::Value::Number(3),
4078            ]
4079            .into(),
4080        );
4081        let set_b = core::Value::Set(
4082            vec![
4083                core::Value::Number(3),
4084                core::Value::Number(1),
4085                core::Value::Number(2),
4086            ]
4087            .into(),
4088        );
4089        assert_eq!(map_a.stable_hash(), map_b.stable_hash());
4090        assert_eq!(set_a.stable_hash(), set_b.stable_hash());
4091    }
4092
4093    #[test]
4094    fn sequential_representations_share_java_equality_and_hash_semantics() {
4095        let values = vec![core::Value::Number(1), core::Value::Number(2)];
4096        let list = core::Value::List(values.clone().into());
4097        let tuple = core::Value::Tuple(Box::new(
4098            crate::lang::data::Tuple::from_values(values.clone()).unwrap(),
4099        ));
4100        let vector = core::Value::Vector(values.into());
4101
4102        assert_eq!(list, tuple);
4103        assert_eq!(tuple, vector);
4104        assert_eq!(list.stable_hash(), tuple.stable_hash());
4105        assert_eq!(tuple.stable_hash(), vector.stable_hash());
4106
4107        let mut runtime = Runtime::new();
4108        assert_eq!(runtime.eval_text("(= [1 2] '(1 2))").unwrap(), "true");
4109        assert_eq!(runtime.eval_text("(= [1 2] (list 1 2))").unwrap(), "true");
4110        assert_eq!(runtime.eval_text("(conj (list 2) 1)").unwrap(), "(1 2)");
4111        assert_eq!(runtime.eval_text("(pair 1 2)").unwrap(), "[1 2]");
4112        assert_eq!(runtime.eval_text("(key (pair 1 2))").unwrap(), "1");
4113        assert_eq!(runtime.eval_text("(val (pair 1 2))").unwrap(), "2");
4114        assert_eq!(runtime.eval_text("(tup 1 2 3 4 5)").unwrap(), "[1 2 3 4 5]");
4115        assert!(runtime
4116            .eval_text("(tup 1 2 3 4 5 6)")
4117            .unwrap_err()
4118            .contains("at most 5"));
4119        assert_eq!(runtime.eval_text("(= [1 2] [1 2 3])").unwrap(), "false");
4120        assert_eq!(
4121            runtime.eval_text("(get {[1 2] :found} '(1 2))").unwrap(),
4122            ":found"
4123        );
4124        assert_eq!(
4125            runtime.eval_text("(get #{[1 2]} '(1 2) :missing)").unwrap(),
4126            "[1 2]"
4127        );
4128    }
4129
4130    #[test]
4131    fn java_collection_families_are_first_class_runtime_values() {
4132        let mut runtime = Runtime::new();
4133        for source in [
4134            "(= (hash-map :a 1 :b 2) (ordered-map :b 2 :a 1))",
4135            "(= (hash-map :a 1 :b 2) (sorted-map :b 2 :a 1))",
4136            "(= (hash-set 1 2) (ordered-set 2 1))",
4137            "(= (hash-set 1 2) (sorted-set 2 1))",
4138            "(= (queue 1 2) [1 2])",
4139        ] {
4140            assert_eq!(runtime.eval_text(source).unwrap(), "true", "{source}");
4141        }
4142        assert_eq!(runtime.eval_text("(get (hash-map :a 1) :a)").unwrap(), "1");
4143        assert_eq!(
4144            runtime.eval_text("(get (ordered-map :a 1) :a)").unwrap(),
4145            "1"
4146        );
4147        assert_eq!(
4148            runtime.eval_text("(get (sorted-map :a 1) :a)").unwrap(),
4149            "1"
4150        );
4151        assert_eq!(
4152            runtime
4153                .eval_text("(get (trie \"alpha\" 7) \"alpha\")")
4154                .unwrap(),
4155            "7"
4156        );
4157        assert_eq!(
4158            runtime.eval_text("(keys (sorted-map :b 2 :a 1))").unwrap(),
4159            "[:a :b]"
4160        );
4161        assert_eq!(runtime.eval_text("(nth (queue 4 5 6) 1)").unwrap(), "5");
4162        assert_eq!(
4163            runtime.eval_text("(last (conj (queue 4 5) 6))").unwrap(),
4164            "6"
4165        );
4166        assert_eq!(
4167            runtime
4168                .eval_text("(count (dissoc (ordered-set 1 2) 1))")
4169                .unwrap(),
4170            "1"
4171        );
4172        assert_eq!(
4173            runtime
4174                .eval_text("(get (assoc (trie) \"x\" 9) \"x\")")
4175                .unwrap(),
4176            "9"
4177        );
4178        assert!(runtime
4179            .eval_text("(hash-map :a)")
4180            .unwrap_err()
4181            .contains("even number"));
4182        assert!(runtime
4183            .eval_text("(trie :a 1)")
4184            .unwrap_err()
4185            .contains("string keys"));
4186    }
4187
4188    #[test]
4189    fn map_membership_keys_and_values_are_portable() {
4190        let mut runtime = Runtime::new();
4191        assert_eq!(runtime.eval_text(r#"(has? {"a" 1} "a")"#).unwrap(), "true");
4192        assert_eq!(runtime.eval_text("(has? [1 2] 1)").unwrap(), "true");
4193        assert_eq!(runtime.eval_text("(has? [1 2] 2)").unwrap(), "false");
4194        assert_eq!(
4195            runtime.eval_text(r#"(has? {"a" nil} "a")"#).unwrap(),
4196            "true"
4197        );
4198        assert_eq!(
4199            runtime.eval_text(r#"(keys {"a" 1 "b" 2})"#).unwrap(),
4200            "[\"a\" \"b\"]"
4201        );
4202        assert_eq!(
4203            runtime.eval_text(r#"(vals {"a" 1 "b" 2})"#).unwrap(),
4204            "[1 2]"
4205        );
4206    }
4207
4208    #[test]
4209    fn core_collection_navigation_and_predicates_are_host_neutral() {
4210        let mut runtime = Runtime::new();
4211        assert_eq!(runtime.eval_text("(first [1 2 3])").unwrap(), "1");
4212        assert_eq!(
4213            runtime
4214                .eval_text("[(seq? (rest [1 2 3])) (vec (rest [1 2 3]))]")
4215                .unwrap(),
4216            "[true [2 3]]"
4217        );
4218        assert_eq!(runtime.eval_text("(last [1 2 3])").unwrap(), "3");
4219        assert_eq!(runtime.eval_text("(empty? [])").unwrap(), "true");
4220        assert_eq!(runtime.eval_text("(not false)").unwrap(), "true");
4221        assert_eq!(runtime.eval_text("(< 1 2 3)").unwrap(), "true");
4222        assert_eq!(runtime.eval_text("(>= 3 3)").unwrap(), "true");
4223        assert_eq!(runtime.eval_text("(mod 7 3)").unwrap(), "1");
4224    }
4225
4226    #[test]
4227    fn atoms_match_java_identity_and_mutation_semantics() {
4228        let mut runtime = Runtime::new();
4229        assert_eq!(runtime.eval_text("(let [a (atom 1)] @a)").unwrap(), "1");
4230        assert_eq!(
4231            runtime
4232                .eval_text("(do (def deref-test-values (atom [10 18])) (deref deref-test-values))")
4233                .unwrap(),
4234            "[10 18]"
4235        );
4236        assert_eq!(
4237            runtime
4238                .eval_text("(let [a (atom 1)] (do (reset! a 2) @a))")
4239                .unwrap(),
4240            "2"
4241        );
4242        assert_eq!(
4243            runtime
4244                .eval_text("(let [a (atom 1)] (do (swap! a (fn [x y] (+ x y)) 4) @a))")
4245                .unwrap(),
4246            "5"
4247        );
4248        assert_eq!(
4249            runtime
4250                .eval_text("(let [a (atom 1)] [(cas! a 1 2) @a])")
4251                .unwrap(),
4252            "[true 2]"
4253        );
4254        assert_eq!(
4255            runtime
4256                .eval_text("(let [a (atom 1)] [(cas! a 0 2) @a])")
4257                .unwrap(),
4258            "[false 1]"
4259        );
4260        assert_eq!(
4261            runtime.eval_text("(let [a (atom 1) b a] (= a b))").unwrap(),
4262            "true"
4263        );
4264        assert_eq!(runtime.eval_text("(= (atom 1) (atom 1))").unwrap(), "false");
4265        assert_eq!(
4266            runtime.eval_text("(let [a (atom 1) seen (atom nil)] (do (watch-add a :log (fn [key ref old new] (reset! seen [key @ref old new]))) (reset! a 2) @seen))").unwrap(),
4267            "[:log 2 1 2]"
4268        );
4269        assert_eq!(
4270            runtime.eval_text("(let [a (atom 1)] (do (watch-add a :log (fn [key ref old new] new)) (watch-add a :log (fn [key ref old new] old)) (count (watch-list a))))").unwrap(),
4271            "1"
4272        );
4273        assert_eq!(
4274            runtime.eval_text("(let [a (atom 1) seen (atom nil)] (do (watch-add a :log (fn [key ref old new] (reset! seen new))) (watch-remove a :log) (reset! a 2) @seen))").unwrap(),
4275            "nil"
4276        );
4277        assert!(runtime
4278            .eval_text("(watch-add (atom:basic 1) :log (fn [key ref old new] new))")
4279            .unwrap_err()
4280            .contains("watch-add"));
4281        assert!(runtime
4282            .eval_text("(reset! 1 2)")
4283            .unwrap_err()
4284            .contains("IReset/reset"));
4285        assert!(runtime
4286            .eval_text("(swap! (atom 1) 2)")
4287            .unwrap_err()
4288            .contains("expects a function"));
4289        for legacy in [
4290            "compare:set!",
4291            "compare-and-set!",
4292            "add-watch",
4293            "remove-watch",
4294            "get-watches",
4295        ] {
4296            assert!(
4297                runtime.eval_text(legacy).unwrap_err().contains("unbound"),
4298                "{legacy} should not remain public"
4299            );
4300        }
4301    }
4302
4303    #[test]
4304    fn keywords_maps_and_sets_match_java_callable_semantics() {
4305        let mut runtime = Runtime::new();
4306        assert_eq!(runtime.eval_text("(:answer {:answer 42})").unwrap(), "42");
4307        assert_eq!(runtime.eval_text("(:missing {:answer 42})").unwrap(), "nil");
4308        assert_eq!(runtime.eval_text("(:missing nil 7)").unwrap(), "7");
4309        assert_eq!(runtime.eval_text("({:answer 42} :answer)").unwrap(), "42");
4310        assert_eq!(runtime.eval_text("({:answer 42} :missing 7)").unwrap(), "7");
4311        assert_eq!(
4312            runtime.eval_text("(#{:answer} :answer)").unwrap(),
4313            ":answer"
4314        );
4315        assert_eq!(runtime.eval_text("(#{:answer} :missing 7)").unwrap(), "7");
4316        assert_eq!(
4317            runtime.eval_text("(:answer)").unwrap_err(),
4318            "keyword invocation expects one or two arguments"
4319        );
4320        assert_eq!(
4321            runtime.eval_text("({} :a :b :c)").unwrap_err(),
4322            "map invocation expects one or two arguments"
4323        );
4324    }
4325
4326    #[test]
4327    fn foundation_fallback_is_eager_canonical_and_shadowable() {
4328        let mut runtime = Runtime::new();
4329        let foundation = runtime
4330            .namespace_registry
4331            .find("std.foundation")
4332            .expect("foundation is bootstrapped");
4333        let canonical = foundation
4334            .resolve(&crate::lang::data::Symbol::parse("identity"))
4335            .expect("identity fallback is installed");
4336        assert_eq!(canonical.origin(), kernel::VarOrigin::HalFallback);
4337        let referred = runtime
4338            .namespace_registry
4339            .find("user")
4340            .unwrap()
4341            .resolve(&crate::lang::data::Symbol::parse("identity"))
4342            .unwrap();
4343        assert!(canonical.same_identity(&referred));
4344        assert_eq!(runtime.eval_text("(identity 42)").unwrap(), "42");
4345        assert_eq!(runtime.eval_text("(first (range 3))").unwrap(), "0");
4346        assert_eq!(runtime.eval_text("(first (range 2 5))").unwrap(), "2");
4347
4348        assert_eq!(
4349            runtime
4350                .eval_text("(ns project.app (:config {:blank true}) (:require [std.foundation :refer :all :exclude [identity]])) (def identity (fn [value] 7)) (identity 42)")
4351                .unwrap(),
4352            "7"
4353        );
4354        let local = runtime
4355            .namespace_registry
4356            .find("project.app")
4357            .unwrap()
4358            .resolve(&crate::lang::data::Symbol::parse("identity"))
4359            .unwrap();
4360        assert!(!canonical.same_identity(&local));
4361        assert_eq!(
4362            runtime.eval_text("(std.foundation/identity 42)").unwrap(),
4363            "42"
4364        );
4365    }
4366
4367    #[test]
4368    fn blank_namespace_collision_controls_preserve_the_canonical_cache() {
4369        let mut runtime = Runtime::new();
4370        let foundation = runtime
4371            .namespace_registry
4372            .find("std.foundation")
4373            .expect("foundation is bootstrapped");
4374        let canonical_identity = foundation
4375            .resolve(&crate::lang::data::Symbol::parse("identity"))
4376            .expect("foundation identity is installed");
4377
4378        runtime.register_resource(
4379            "xt.collision-probe",
4380            concat!(
4381                "(ns xt.collision-probe ",
4382                "(:config {:blank true}) ",
4383                "(:require [std.foundation :refer :all ",
4384                ":exclude [/ do if fn quote try]])) ",
4385                "(defmacro do [value] (list 'quote value)) ",
4386                "(defmacro if [value] (list 'quote value)) ",
4387                "(defmacro fn [value] (list 'quote value)) ",
4388                "(defmacro quote [value] (list 'quote value)) ",
4389                "(defmacro try [value] (list 'quote value))"
4390            ),
4391        );
4392
4393        runtime
4394            .eval_text("(require [xt.collision-probe :as probe])")
4395            .unwrap();
4396        runtime
4397            .eval_text("(require [xt.collision-probe :as probe-again])")
4398            .unwrap();
4399
4400        assert_eq!(
4401            runtime
4402                .eval_text("(module-revision 'xt.collision-probe)")
4403                .unwrap(),
4404            "1"
4405        );
4406        assert_eq!(runtime.eval_text("(probe/do 42)").unwrap(), "42");
4407        assert_eq!(runtime.eval_text("(probe-again/try 7)").unwrap(), "7");
4408
4409        let cached_identity = runtime
4410            .namespace_registry
4411            .find("std.foundation")
4412            .unwrap()
4413            .resolve(&crate::lang::data::Symbol::parse("identity"))
4414            .unwrap();
4415        assert!(canonical_identity.same_identity(&cached_identity));
4416    }
4417
4418    #[test]
4419    fn fallback_definitions_never_replace_rust_library_vars() {
4420        let mut runtime = Runtime::new();
4421        let foundation = runtime.namespace_registry.find_or_create("std.foundation");
4422        let native = foundation.intern_with_origin(
4423            "optimized",
4424            core::Value::Number(7),
4425            kernel::VarOrigin::RustLibrary,
4426        );
4427        let identity = native.identity_address();
4428        core::with_definition_origin(kernel::VarOrigin::HalFallback, || {
4429            runtime.eval_text(concat!(
4430                "(ns std.foundation)",
4431                " (defn ^{:schema [:fn [:int] :int]} optimized",
4432                " \"Documents the native implementation.\" [value] 9)"
4433            ))
4434        })
4435        .unwrap();
4436        let refreshed = foundation
4437            .resolve(&crate::lang::data::Symbol::parse("optimized"))
4438            .unwrap();
4439        assert_eq!(refreshed.identity_address(), identity);
4440        assert_eq!(refreshed.origin(), kernel::VarOrigin::RustLibrary);
4441        assert_eq!(refreshed.deref_value().display(), "7");
4442        assert_eq!(
4443            refreshed
4444                .hara_metadata()
4445                .and_then(|metadata| metadata.doc().map(str::to_owned)),
4446            Some("Documents the native implementation.".into())
4447        );
4448        let metadata = refreshed.hara_metadata().expect("fallback metadata");
4449        assert_eq!(
4450            metadata.get_keyword("arglists"),
4451            Some(&crate::lang::data::MetadataValue::Vector(vec![
4452                crate::lang::data::MetadataValue::Vector(vec![
4453                    crate::lang::data::MetadataValue::Symbol(crate::lang::data::Symbol::from(
4454                        "value"
4455                    ))
4456                ])
4457            ]))
4458        );
4459        assert_eq!(
4460            metadata.get_keyword("schema"),
4461            Some(&crate::lang::data::MetadataValue::Vector(vec![
4462                crate::lang::data::MetadataValue::Keyword(crate::lang::data::Keyword::from("fn")),
4463                crate::lang::data::MetadataValue::Vector(vec![
4464                    crate::lang::data::MetadataValue::Keyword(crate::lang::data::Keyword::from(
4465                        "int"
4466                    ))
4467                ]),
4468                crate::lang::data::MetadataValue::Keyword(crate::lang::data::Keyword::from("int"))
4469            ]))
4470        );
4471    }
4472
4473    #[test]
4474    fn function_metadata_is_visible_through_meta_and_var_literals() {
4475        let mut runtime = Runtime::new();
4476        assert_eq!(
4477            runtime
4478                .eval_text(concat!(
4479                    "(defn ^{:schema [:fn [:int] :int]} documented",
4480                    " \"Returns its argument.\" [value] value)",
4481                    " (let [m (meta #'documented)]",
4482                    " [(get m :doc) (get m :arglists) (get m :schema)])"
4483                ))
4484                .unwrap(),
4485            "[\"Returns its argument.\" [[value]] [:fn [:int] :int]]"
4486        );
4487        assert_eq!(
4488            runtime
4489                .eval_text(concat!(
4490                    "(let [m (meta #'std.foundation.string/length)]",
4491                    " [(get m :doc) (get m :arglists) (get m :schema)])"
4492                ))
4493                .unwrap(),
4494            concat!(
4495                "[\"Returns the portable character count of value.\"",
4496                " [[value]] [:fn [:str] :int]]"
4497            )
4498        );
4499    }
4500
4501    #[test]
4502    fn definitions_accept_source_metadata_around_hir_syntax() {
4503        let mut runtime = Runtime::new();
4504        runtime
4505            .eval_text(concat!(
4506                "(defn wrapped ^{:line 1} [value] value)",
4507                " (defn wrapped-many",
4508                " ^{:line 2} ([value] value)",
4509                " ^{:line 3} ([left right] (+ left right)))"
4510            ))
4511            .unwrap();
4512        assert_eq!(
4513            runtime
4514                .eval_text(concat!(
4515                    "[(wrapped 42)",
4516                    " (wrapped-many 42)",
4517                    " (wrapped-many 19 23)]"
4518                ))
4519                .unwrap(),
4520            "[42 42 42]"
4521        );
4522    }
4523
4524    #[test]
4525    fn namespace_values_and_operations_match_java_registry_semantics() {
4526        let mut runtime = Runtime::new();
4527        let initial_namespace_count = runtime.namespace_registry.all().len();
4528        assert_eq!(
4529            runtime
4530                .eval_text("(ns:name (ns:create (quote example.lib)))")
4531                .unwrap(),
4532            "example.lib"
4533        );
4534        assert_eq!(
4535            runtime
4536                .eval_text("(= (ns:create (quote example.lib)) (ns:create (quote example.lib)))")
4537                .unwrap(),
4538            "true"
4539        );
4540        assert_eq!(
4541            runtime
4542                .eval_text("(ns example.lib) (def answer 42) (ns user) (deref (get (ns:map (ns:find (quote example.lib))) (quote answer)))")
4543                .unwrap(),
4544            "42"
4545        );
4546        assert_eq!(
4547            runtime.eval_text("(count (ns:list))").unwrap(),
4548            (initial_namespace_count + 1).to_string()
4549        );
4550        assert_eq!(
4551            runtime.eval_text("(ns:find (quote missing.lib))").unwrap(),
4552            "nil"
4553        );
4554        runtime.alias_namespace("lib", "example.lib");
4555        assert_eq!(
4556            runtime
4557                .eval_text("(= (get (ns:aliases (ns:find (quote user))) (quote lib)) (ns:find (quote example.lib)))")
4558                .unwrap(),
4559            "true"
4560        );
4561        assert!(runtime
4562            .eval_text("(ns:create (quote bad/name))")
4563            .unwrap_err()
4564            .contains("unqualified symbol"));
4565    }
4566
4567    #[test]
4568    fn namespace_use_refers_portable_test_vars_and_macros() {
4569        let mut runtime = Runtime::new();
4570        assert_eq!(
4571            runtime
4572                .eval_text(concat!(
4573                    "(ns code.test-rust-probe (:use code.test))",
4574                    " (def lifecycle (atom []))",
4575                    " (fact \"promise assertion\"",
4576                    "   {:before (fn []",
4577                    "              (swap! lifecycle",
4578                    "                     (fn [events] (conj events :before))))",
4579                    "    :after (fn []",
4580                    "             (swap! lifecycle",
4581                    "                    (fn [events] (conj events :after))))}",
4582                    "   (promise/from 42) => 42",
4583                    "   (+ 1 1) => 2)",
4584                    " (let [summary (run {:namespace \"code.test-rust-probe\"})",
4585                    "       timer (function-timer",
4586                    "              (fn [promise milliseconds]",
4587                    "                {:promise (promise/from {:test/status :timeout})",
4588                    "                 :timeout milliseconds})",
4589                    "              (fn [timeout] timeout))",
4590                    "       timed (check (fn [] (promise/from 42)) 42",
4591                    "                    {:timer timer :timeout 25})",
4592                    "       positional (run '[code])",
4593                    "       cancelled",
4594                    "       (run {:namespace \"code.test-rust-probe\"",
4595                    "             :control (function-control (fn [fact] true))})]",
4596                    " [(:status summary)",
4597                    "  (:passed (:counts summary))",
4598                    "  (count (:checks (first (:results summary))))",
4599                    "  (:status timed)",
4600                    "  (:timeout timed)",
4601                    "  (:facts positional)",
4602                    "  (:cancelled (:counts cancelled))])"
4603                ))
4604                .unwrap(),
4605            "[:passed 1 2 :timeout 25 1 1]"
4606        );
4607    }
4608
4609    #[test]
4610    fn foundation_code_test_compatibility_namespaces_are_embedded() {
4611        let mut runtime = Runtime::new();
4612        assert_eq!(
4613            runtime
4614                .eval_text(
4615                    "(ns code-test-compat-rust-probe \
4616                       (:require [code.test :as test] \
4617                                 [code.test.checker.common :as common] \
4618                                 [code.test.checker.collection :as collection] \
4619                                 [code.test.checker.logic :as logic] \
4620                                 [code.test.base.runtime :as runtime] \
4621                                 [code.test.compile.types :as types] \
4622                                 [code.test.task :as task])) \
4623                     (let [fact (types/Fact :core 'id 'probe nil nil \
4624                                            \"portable\" 1 1 nil nil \
4625                                            (fn [] 42) {})] \
4626                       [(common/succeeded? \
4627                         (common/verify (common/exactly 1) 1)) \
4628                        (:pass (test/check \
4629                                (fn [] {:a 1 :b 2}) \
4630                                (collection/contains-map {:a 1}))) \
4631                        (:pass (test/check \
4632                                (fn [] 3) \
4633                                (logic/all (fn [value] (number? value)) \
4634                                           (fn [value] (= 1 (mod value 2)))))) \
4635                        (types/fact? fact) \
4636                        (fact) \
4637                        (task/process-test-args \
4638                         [\":only\" \"std\" \"code\"])])"
4639                )
4640                .unwrap(),
4641            "[true true true true 42 {:ns [std code]}]"
4642        );
4643    }
4644
4645    #[test]
4646    fn canonical_component_and_context_libraries_load_without_old_aliases() {
4647        let mut runtime = Runtime::new();
4648        assert_eq!(
4649            runtime
4650                .eval_text(
4651                    "(ns std-lib-context-rust-probe \
4652                       (:require [std.lib.component :as component] \
4653                                 [std.lib.context :as context])) \
4654                     (let [runtime (context/runtime-null)] \
4655                       [(component/started? runtime) \
4656                        (context/call runtime :a :b)])"
4657                )
4658                .unwrap(),
4659            "[true [:a :b]]"
4660        );
4661        assert!(runtime
4662            .eval_text("(require [std.foundation.component :as old])")
4663            .unwrap_err()
4664            .contains("missing"));
4665    }
4666
4667    #[test]
4668    fn portable_task_bulk_execution_is_data_first() {
4669        let mut runtime = Runtime::new();
4670        assert_eq!(
4671            runtime
4672                .eval_text(
4673                    "(ns std-task-rust-probe \
4674                       (:require [std.lib.task :as task] \
4675                                 [std.lib.task.bulk :as bulk])) \
4676                     (task/deftask double-task \
4677                       {:template :default \
4678                        :main {:fn (fn [value] (* 2 value))}}) \
4679                     (task/deftask selected-task \
4680                       {:template :default \
4681                        :main {:fn (fn [value suffix] (str value suffix))} \
4682                        :item {:list (fn [lookup env] \
4683                                      ['code.alpha 'code.beta 'std.gamma])}}) \
4684                     (task/deftask aggregate-task \
4685                       {:template :default \
4686                        :main {:fn (fn [value] {:score value})} \
4687                        :result {:ignore (fn [data] \
4688                                           (= 0 (get data :score))) \
4689                                 :output (fn [data] (get data :score))} \
4690                        :summary {:aggregate \
4691                                  {:score-total \
4692                                   [(fn [data] (get data :score)) \
4693                                    (fn [total score] (+ total score)) 0]}}}) \
4694                     (task/deftask constructed-task \
4695                       {:template :default \
4696                        :main {:argcount 4 \
4697                               :fn (fn [input params lookup env] \
4698                                     [input (get params :flag) \
4699                                      (get lookup :input) \
4700                                      (get env :environment)])} \
4701                        :construct \
4702                        {:input (fn [task] 7) \
4703                         :env (fn [options] {:environment :ready}) \
4704                         :lookup (fn [task options] \
4705                                   {:input (get options :environment)})} \
4706                        :params {:flag true}}) \
4707                     (let [reporter (bulk/event-reporter) \
4708                           output (task/invoke double-task [1 2 3] \
4709                                               {:reporter reporter :return :all \
4710                                                :package :records}) \
4711                           aggregate-output \
4712                           (task/invoke aggregate-task [0 2 3] \
4713                                        {:return :all})] \
4714                       [(get output :summary) \
4715                        (vec (map (fn [result] (get result :data)) \
4716                                  (get output :results))) \
4717                        (count (bulk/reporter-events reporter)) \
4718                        (task/invoke double-task 4) \
4719                        (vec (map (fn [result] (get result :data)) \
4720                                  (task/invoke selected-task 'code \
4721                                               {:package :records} \
4722                                               :args \"!\"))) \
4723                        (get aggregate-output :results) \
4724                        (get (get aggregate-output :summary) \
4725                             :score-total) \
4726                        (task/invoke constructed-task)])"
4727                )
4728                .unwrap(),
4729            "[{:items 3 :results 3 :warnings 0 :errors 0 :cumulative 0 :elapsed 0} [2 4 6] 8 8 [\"code.alpha!\" \"code.beta!\"] {2 2 3 3} 5 [7 true :ready :ready]]"
4730        );
4731    }
4732
4733    #[test]
4734    fn portable_block_preserves_source_value_and_structure() {
4735        let mut runtime = Runtime::new();
4736        assert_eq!(
4737            runtime
4738                .eval_text(
4739                    "(ns std-block-rust-probe \
4740                       (:require [std.lib.block :as block] \
4741                                 [std.lib.block.grid :as grid] \
4742                                 [std.lib.block.reader :as reader])) \
4743                     (let [parsed (block/parse-string \"[1 2 3]\") \
4744                           first-block (block/parse-first \"[1 2 3]\") \
4745                           spaces (block/spaces 3) \
4746                           wrapped (block/layout '(if ready [1 2] [3 4]) \
4747                                                 {:width 10}) \
4748                           gridded (grid/grid \
4749                                    (block/parse-first \"(if\\nready\\ndone)\") \
4750                                    0 {:rules {'if {:indent 1}}}) \
4751                           modified (block/parse-first \"[1 #_2 3]\") \
4752                           original (block/block [1 2]) \
4753                           input-reader (reader/create \"ab\\ncd\") \
4754                           first-two (reader/read-times input-reader \
4755                                                        reader/read-char 2) \
4756                           newline (reader/read-char input-reader) \
4757                           edited (std.lib.zip/result \
4758                                   (std.lib.zip/replace-right \
4759                                    (std.lib.zip/step-right \
4760                                     (std.lib.zip/step-right \
4761                                     (std.lib.zip/step-inside \
4762                                      (block/block-zip original)))) \
4763                                    (block/block 3)))] \
4764                       [(block/string parsed) \
4765                        (block/value parsed) \
4766                        (block/type first-block) \
4767                        (block/tag first-block) \
4768                        (vec (map block/value \
4769                                  (filter block/code? \
4770                                          (block/children first-block)))) \
4771                        (block/string spaces) \
4772                        (block/space? spaces) \
4773                        (block/string wrapped) \
4774                        (block/string gridded) \
4775                        (block/value modified) \
4776                        (block/child-values modified) \
4777                        (block/string original) \
4778                        (block/string edited) \
4779                        first-two \
4780                        (reader/reader-position input-reader) \
4781                        (reader/read-to-boundary input-reader) \
4782                        (block/value (block/parse-string \"[4 5]\"))])"
4783                )
4784                .unwrap(),
4785            "[\"[1 2 3]\" [1 2 3] :container :vector [1 2 3] \"   \" true \"(if\\n  ready\\n  [1 2]\\n  [3 4]\\n)\" \"(if\\n  ready\\n  done)\" [1 3] [1 3] \"[1 2]\" \"[1 3]\" [\"a\" \"b\"] [2 1] \"cd\" [4 5]]"
4786        );
4787    }
4788
4789    #[test]
4790    fn portable_zip_is_embedded_and_preserves_original_values() {
4791        let mut runtime = Runtime::new();
4792        assert_eq!(
4793            runtime
4794                .eval_text(
4795                    "(ns std-lib-zip-rust-probe \
4796                       (:require [std.lib.zip :as zip])) \
4797                     (let [root [1 2 3] \
4798                           location (zip/step-right \
4799                                     (zip/step-inside (zip/vector-zip root))) \
4800                           edited (zip/replace-right \
4801                                   (zip/insert-left location 9) 8)] \
4802                       [(zip/result edited) root])"
4803                )
4804                .unwrap(),
4805            "[[1 9 8 3] [1 2 3]]"
4806        );
4807    }
4808
4809    #[test]
4810    fn portable_collection_execution_preserves_hal_semantics_and_errors() {
4811        let mut runtime = Runtime::new();
4812        assert_eq!(
4813            runtime
4814                .eval_text(
4815                    "[(reduce (fn [total value] (+ total value)) 0 [1 2 3 4]) \
4816                      (let [answer 41] (+ answer 1) (+ answer 2))]"
4817                )
4818                .unwrap(),
4819            "[10 43]"
4820        );
4821        assert!(runtime
4822            .eval_text("(vec (map (fn [value] (/ 1 value)) [1 0]))")
4823            .unwrap_err()
4824            .contains("division by zero"));
4825    }
4826
4827    #[test]
4828    fn named_values_expose_java_basic_object_operations() {
4829        let mut runtime = Runtime::new();
4830        assert_eq!(runtime.eval_text("(compare :a :b)").unwrap(), "-1");
4831        assert_eq!(
4832            runtime
4833                .eval_text("(compare (symbol \"a\") (symbol \"a\"))")
4834                .unwrap(),
4835            "0"
4836        );
4837        assert_eq!(
4838            runtime
4839                .eval_text("(= (hash [1 2]) (hash (list 1 2)))")
4840                .unwrap(),
4841            "true"
4842        );
4843        assert_eq!(runtime.eval_text("(meta :answer)").unwrap(), "nil");
4844        assert_eq!(
4845            runtime
4846                .eval_text("(with-meta :answer {:doc \"ignored\"})")
4847                .unwrap(),
4848            ":answer"
4849        );
4850        assert_eq!(
4851            runtime
4852                .eval_text("(get (meta (with-meta (symbol \"answer\") {:doc \"named\"})) :doc)")
4853                .unwrap(),
4854            "\"named\""
4855        );
4856        assert_eq!(
4857            runtime
4858                .eval_text("(get (meta (with-meta [1] {:doc \"vector\"})) :doc)")
4859                .unwrap(),
4860            "\"vector\""
4861        );
4862        assert_eq!(
4863            runtime
4864                .eval_text("(meta (with-meta (with-meta [1] {:doc \"vector\"}) nil))")
4865                .unwrap(),
4866            "nil"
4867        );
4868        assert_eq!(
4869            runtime.eval_text("(hash)").unwrap_err(),
4870            "hash expects one value"
4871        );
4872    }
4873
4874    #[test]
4875    fn cons_pointer_and_tagged_literals_are_first_class_runtime_values() {
4876        let mut runtime = Runtime::new();
4877        assert_eq!(runtime.eval_text("(cons 0 [1 2])").unwrap(), "(0 1 2)");
4878        assert_eq!(
4879            runtime.eval_text("(type (cons 0 [1 2]))").unwrap(),
4880            ":hara.type/cons"
4881        );
4882        assert_eq!(runtime.eval_text("(count (cons 0 [1 2]))").unwrap(), "3");
4883        assert_eq!(runtime.eval_text("(get (cons 0 [1 2]) 2)").unwrap(), "2");
4884        assert_eq!(
4885            runtime
4886                .eval_text("(pointer \"hara.core\" \"value\")")
4887                .unwrap(),
4888            "#\x27hara.core/value"
4889        );
4890        assert_eq!(
4891            runtime
4892                .eval_text("(type (pointer \"hara.core/value\"))")
4893                .unwrap(),
4894            ":hara.type/pointer"
4895        );
4896        assert_eq!(
4897            runtime.eval_text("(type #sample [1 2])").unwrap(),
4898            ":hara.type/tagged-literal"
4899        );
4900        assert_eq!(runtime.eval_text("(ILookup/lookup (IObjType/meta (IObjType/with-meta (cons 0 [1]) {:doc \"cons\"})) :doc)").unwrap(), "\"cons\"");
4901    }
4902
4903    #[test]
4904    fn keyword_symbol_constructors_and_namespaced_protocol_match_java() {
4905        let mut runtime = Runtime::new();
4906        assert_eq!(
4907            runtime.eval_text("(keyword \"answer\")").unwrap(),
4908            ":answer"
4909        );
4910        assert_eq!(
4911            runtime.eval_text("(keyword \"core\" \"answer\")").unwrap(),
4912            ":core/answer"
4913        );
4914        assert_eq!(runtime.eval_text("(symbol \"answer\")").unwrap(), "answer");
4915        assert_eq!(
4916            runtime.eval_text("(symbol \"core\" \"answer\")").unwrap(),
4917            "core/answer"
4918        );
4919        assert_eq!(
4920            runtime
4921                .eval_text("(INamespaced/name :core/answer)")
4922                .unwrap(),
4923            "\"answer\""
4924        );
4925        assert_eq!(
4926            runtime
4927                .eval_text("(INamespaced/namespace (symbol \"core\" \"answer\"))")
4928                .unwrap(),
4929            "\"core\""
4930        );
4931        assert_eq!(
4932            runtime
4933                .eval_text("(INamespaced/namespace :answer)")
4934                .unwrap(),
4935            "nil"
4936        );
4937        assert_eq!(
4938            runtime.eval_text("(namespace :core/answer)").unwrap(),
4939            "\"core\""
4940        );
4941        assert_eq!(
4942            runtime.eval_text("(name :core/answer)").unwrap(),
4943            "\"answer\""
4944        );
4945        assert_eq!(
4946            runtime
4947                .eval_text("(name (symbol \"core\" \"answer\"))")
4948                .unwrap(),
4949            "\"answer\""
4950        );
4951        assert!(runtime
4952            .eval_text("(keyword \"a/b/c\")")
4953            .unwrap_err()
4954            .contains("one slash"));
4955        assert!(runtime
4956            .eval_text("(symbol 1)")
4957            .unwrap_err()
4958            .contains("string arguments"));
4959    }
4960
4961    #[test]
4962    fn foundation_compiler_support_functions_are_available_at_root() {
4963        let mut runtime = Runtime::new();
4964        assert_eq!(
4965            runtime
4966                .eval_text(
4967                    "(reduce-kv (fn [out key value] (assoc out key (+ value 1))) {} {:a 1 :b 2})"
4968                )
4969                .unwrap(),
4970            "{:a 2 :b 3}"
4971        );
4972        assert_eq!(
4973            runtime
4974                .eval_text("(select-keys {:a 1 :b 2} [:b :missing])")
4975                .unwrap(),
4976            "{:b 2}"
4977        );
4978        assert_eq!(
4979            runtime.eval_text("(fn? (deref (resolve 'inc)))").unwrap(),
4980            "true"
4981        );
4982        assert_eq!(
4983            runtime.eval_text("(nil? (resolve 'missing))").unwrap(),
4984            "true"
4985        );
4986        assert_eq!(
4987            runtime
4988                .eval_text("(ex-class (ex-info \"broken\" {:phase :test}))")
4989                .unwrap(),
4990            "\"ExceptionInfo\""
4991        );
4992    }
4993
4994    #[test]
4995    fn reader_vectors_use_java_tuple_arity_selection() {
4996        let mut env = HashMap::new();
4997        let small = core::eval(&kernel::parse("[1 2 3]").unwrap(), &mut env).unwrap();
4998        let large = core::eval(&kernel::parse("[1 2 3 4 5 6]").unwrap(), &mut env).unwrap();
4999        assert!(matches!(small, core::Value::Tuple(_)));
5000        assert!(matches!(large, core::Value::Vector(_)));
5001
5002        let mut runtime = Runtime::new();
5003        assert_eq!(runtime.eval_text("(nth [1 2 3] 1)").unwrap(), "2");
5004        assert_eq!(runtime.eval_text("(conj [1 2 3] 4)").unwrap(), "[1 2 3 4]");
5005        assert_eq!(
5006            runtime
5007                .eval_text(
5008                    "(loop [values [] n 0]
5009                       (if (< n 32)
5010                         (recur (conj values n) (+ n 1))
5011                         [(count values) (first values) (nth values 31)]))"
5012                )
5013                .unwrap(),
5014            "[32 0 31]"
5015        );
5016        let promoted = core::eval(
5017            &kernel::parse("(conj (conj (conj (conj [0 1 2 3 4] 5) 6) 7) 8)").unwrap(),
5018            &mut env,
5019        )
5020        .unwrap();
5021        assert!(matches!(promoted, core::Value::Vector(values) if values.len() == 9));
5022        assert_eq!(
5023            runtime
5024                .eval_text("(ILookup/lookup (IObjType/meta (IObjType/with-meta [1] {:doc \"tuple\"})) :doc)")
5025                .unwrap(),
5026            "\"tuple\""
5027        );
5028    }
5029
5030    #[test]
5031    fn reader_maps_and_sets_preserve_java_hash_order() {
5032        let mut runtime = Runtime::new();
5033        assert_eq!(runtime.eval_text("{:b 2 :a 1}").unwrap(), "{:b 2 :a 1}");
5034        assert_eq!(runtime.eval_text("(keys {:b 2 :a 1})").unwrap(), "[:b :a]");
5035        assert_eq!(runtime.eval_text("#{:b :a}").unwrap(), "#{:b :a}");
5036        assert_eq!(
5037            runtime
5038                .eval_text("(conj (dissoc {:a 1 :b 2} :a) [:a 3])")
5039                .unwrap(),
5040            "{:b 2 :a 3}"
5041        );
5042    }
5043
5044    #[test]
5045    fn collection_operations_are_values() {
5046        let mut runtime = Runtime::new();
5047        assert_eq!(runtime.eval_text("(count [1 2 3])").unwrap(), "3");
5048        assert_eq!(runtime.eval_text("(get {\"a\" 9} \"a\")").unwrap(), "9");
5049        assert_eq!(runtime.eval_text("(nth (conj [1] 2) 1)").unwrap(), "2");
5050        assert_eq!(
5051            runtime.eval_text(r#"(conj {"a" 1} ["b" 2])"#).unwrap(),
5052            r#"{"a" 1 "b" 2}"#
5053        );
5054        assert_eq!(
5055            runtime
5056                .eval_text(r#"(get (conj {"a" 1} ["a" 9]) "a")"#)
5057                .unwrap(),
5058            "9"
5059        );
5060        assert_eq!(
5061            runtime.eval_text(r#"(dissoc {"a" 1 "b" 2} "a")"#).unwrap(),
5062            r#"{"b" 2}"#
5063        );
5064        assert_eq!(
5065            runtime
5066                .eval_text(r#"(dissoc {"a" 1 "b" 2} "a" "b")"#)
5067                .unwrap(),
5068            "{}"
5069        );
5070        assert_eq!(runtime.eval_text("(cons 0 [1 2])").unwrap(), "(0 1 2)");
5071        assert_eq!(runtime.eval_text("(= :ready :ready)").unwrap(), "true");
5072    }
5073
5074    #[test]
5075    fn persistent_vectors_and_lists_keep_previous_values() {
5076        let mut runtime = Runtime::new();
5077        assert_eq!(
5078            runtime
5079                .eval_text("(let (source [1 2]) (get (conj source 3) 2))")
5080                .unwrap(),
5081            "3"
5082        );
5083        assert_eq!(
5084            runtime
5085                .eval_text("(let (source [1 2]) (count source))")
5086                .unwrap(),
5087            "2"
5088        );
5089        assert!(runtime
5090            .eval_text("(conj (rest [1 2]) 2)")
5091            .unwrap_err()
5092            .contains("IConj/conj expects a collection"));
5093        assert_eq!(
5094            runtime.eval_text("(vec (cons 0 (rest [1 2])))").unwrap(),
5095            "[0 2]"
5096        );
5097        assert_eq!(
5098            runtime
5099                .eval_text("(let (source (rest [1 2])) (count source))")
5100                .unwrap(),
5101            "1"
5102        );
5103    }
5104
5105    struct RangeExtension;
5106
5107    impl core::ExtensionProvider for RangeExtension {
5108        fn name(&self) -> &str {
5109            "range"
5110        }
5111
5112        fn install(&self, protocols: &mut core::ProtocolRegistry) {
5113            protocols.register("IIter", "iter", |arguments| match arguments.first() {
5114                Some(core::Value::Extension(value))
5115                    if value.provider == "range" && value.type_name == "range" =>
5116                {
5117                    Ok(core::iterator_from_values(
5118                        (0..value.handle)
5119                            .map(|index| core::Value::Number(index as i64))
5120                            .collect(),
5121                    ))
5122                }
5123                _ => Err("range/IIter does not accept this value".into()),
5124            });
5125        }
5126
5127        fn construct(
5128            &self,
5129            type_name: &str,
5130            arguments: &[core::Value],
5131        ) -> Result<core::Value, String> {
5132            if type_name != "range" {
5133                return Err("range/type-not-found".into());
5134            }
5135            let count = match arguments.first() {
5136                Some(core::Value::Number(count)) if *count >= 0 => *count as u64,
5137                _ => return Err("range expects a non-negative count".into()),
5138            };
5139            Ok(core::Value::Extension(core::ExtensionValue {
5140                provider: "range".into(),
5141                type_name: "range".into(),
5142                handle: count,
5143            }))
5144        }
5145    }
5146
5147    fn protocol_identity(arguments: &[core::Value]) -> Result<core::Value, String> {
5148        arguments
5149            .first()
5150            .cloned()
5151            .ok_or_else(|| "missing receiver".into())
5152    }
5153
5154    fn protocol_custom_iterator(_arguments: &[core::Value]) -> Result<core::Value, String> {
5155        Ok(core::iterator_from_values(vec![
5156            core::Value::Number(7),
5157            core::Value::Number(8),
5158        ]))
5159    }
5160
5161    #[test]
5162    fn promise_constructors_and_composition() {
5163        let mut runtime = Runtime::new();
5164        assert_eq!(
5165            runtime
5166                .eval_text("(deref (promise/new (fn [resolve reject] (resolve 42))))")
5167                .unwrap(),
5168            "42"
5169        );
5170        assert_eq!(
5171            runtime.eval_text("(deref (promise (fn [] 40)))").unwrap(),
5172            "40"
5173        );
5174        assert_eq!(
5175            runtime.eval_text("(deref (promise/from 42))").unwrap(),
5176            "42"
5177        );
5178        assert_eq!(
5179            runtime.eval_text("(promise? (promise/from 1))").unwrap(),
5180            "true"
5181        );
5182        assert_eq!(runtime.eval_text("(promise? 1)").unwrap(), "false");
5183        assert_eq!(
5184            runtime
5185                .eval_text("(deref (promise/then (promise (fn [] 40)) (fn [x] (+ x 2))))")
5186                .unwrap(),
5187            "42"
5188        );
5189        assert_eq!(
5190            runtime
5191                .eval_text("(deref (promise/catch (promise (fn [] (throw :bad))) (fn [error] 7)))")
5192                .unwrap(),
5193            "7"
5194        );
5195        assert_eq!(
5196            runtime
5197                .eval_text("(deref (promise/finally (promise (fn [] 4)) (fn [] 99)))")
5198                .unwrap(),
5199            "4"
5200        );
5201        assert_eq!(
5202            runtime
5203                .eval_text(
5204                    "(. (deref (promise/all [(promise (fn [] 1)) 2 (promise (fn [] 3))])) (get 1))"
5205                )
5206                .unwrap(),
5207            "2"
5208        );
5209        assert_eq!(
5210            runtime
5211                .eval_text("(deref (promise (fn [] (promise (fn [] 9)))))")
5212                .unwrap(),
5213            "9"
5214        );
5215        assert_eq!(
5216            runtime
5217                .eval_text("(deref (promise/delay 0 (fn [] 5)))")
5218                .unwrap(),
5219            "5"
5220        );
5221        assert!(runtime
5222            .eval_text("(promise/delay -1 (fn [] 1))")
5223            .unwrap_err()
5224            .contains("non-negative"));
5225        assert!(runtime
5226            .eval_text("(promise/new 1)")
5227            .unwrap_err()
5228            .contains("expects a function"));
5229    }
5230    #[test]
5231    fn promise_continuations_preserve_registration_order_and_late_delivery() {
5232        let promise = core::Promise::new();
5233        let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
5234        let first = events.clone();
5235        promise.on_settle(std::rc::Rc::new(move |_| first.borrow_mut().push(1)));
5236        let second = events.clone();
5237        promise.on_settle(std::rc::Rc::new(move |_| second.borrow_mut().push(2)));
5238        assert!(promise.resolve(core::Value::Number(7)));
5239        assert_eq!(*events.borrow(), vec![1, 2]);
5240        let late = events.clone();
5241        promise.on_settle(std::rc::Rc::new(move |_| late.borrow_mut().push(3)));
5242        assert_eq!(*events.borrow(), vec![1, 2, 3]);
5243        assert!(!promise.reject("late"));
5244    }
5245
5246    #[test]
5247    fn promises_settle_once_and_adopt() {
5248        let pending = core::Promise::new();
5249        let adopted = core::Promise::new();
5250        assert_eq!(pending.state(), core::PromiseState::Pending);
5251        assert!(adopted.adopt(&pending));
5252        assert!(pending.resolve(core::Value::Number(7)));
5253        assert!(!pending.reject("late"));
5254        assert_eq!(
5255            adopted.state(),
5256            core::PromiseState::Fulfilled(core::Value::Number(7))
5257        );
5258    }
5259
5260    #[test]
5261    fn marker_mutation_methods_cover_array_and_object_boundaries() {
5262        let mut runtime = Runtime::new();
5263        assert_eq!(runtime.eval_text("(let (a (array 2)) (do (. a (push-first 1)) (. a (push-last 3)) (. a (insert 1 9)) (. a (get 1))))").unwrap(), "9");
5264        assert_eq!(
5265            runtime
5266                .eval_text(
5267                    "(let (a (array 1 2)) (do (. a (pop-first)) (. a (pop-last)) (count a)))"
5268                )
5269                .unwrap(),
5270            "0"
5271        );
5272        assert_eq!(
5273            runtime
5274                .eval_text(r#"(. (object "a" 1 "b" 2) (keys))"#)
5275                .unwrap(),
5276            r#"(array "a" "b")"#
5277        );
5278        assert_eq!(
5279            runtime
5280                .eval_text(r#"(. (object "a" 1 "b" 2) (vals))"#)
5281                .unwrap(),
5282            "(array 1 2)"
5283        );
5284        assert_eq!(
5285            runtime
5286                .eval_text(
5287                    r#"(let (o (object "a" 1)) (do (. o (assign (object "b" 2))) (. o (get "b"))))"#
5288                )
5289                .unwrap(),
5290            "2"
5291        );
5292    }
5293
5294    #[test]
5295    fn marker_dot_contract_covers_results_identity_callbacks_and_rejections() {
5296        let mut runtime = Runtime::new();
5297        let cases = [
5298            ("(. (. (array 1 2 3) (map (fn [x] (* x 2)))) (get 2))", "6"),
5299            (
5300                "(. (. (array 1 2 3 4) (filter (fn [x] (> x 2)))) (get 0))",
5301                "3",
5302            ),
5303            ("(. (. (array 1 2 3) (slice 1)) (get 1))", "3"),
5304            (
5305                "(. (array 1 2 3) (fold-left (fn [out x] (- out x)) 0))",
5306                "-6",
5307            ),
5308            (
5309                "(. (array 1 2 3) (fold-right (fn [x out] (- x out)) 0))",
5310                "2",
5311            ),
5312            ("(let [a (array 1)] (= a (. a (push-last 2))))", "true"),
5313            ("(let [a (array 1)] (= a (. a (set 0 2))))", "true"),
5314            ("(let [a (array 1)] (= a (. a (insert 1 2))))", "true"),
5315            ("(let [a (array 1)] (= a (. a (clone))))", "false"),
5316            (
5317                r#"(let [o (object "a" 1)] (= o (. o (set "a" 2))))"#,
5318                "true",
5319            ),
5320            (r#"(. (object "a" 1) (delete "a"))"#, "1"),
5321            (r#"(. (object "a" 1) (delete "missing"))"#, "nil"),
5322            (r#"(. (. (object "a" 1) (keys)) (get 0))"#, r#""a""#),
5323            (r#"(. (. (. (object "a" 1) (pairs)) (get 0)) (get 1))"#, "1"),
5324            ("(iter-next (iter (array 7 8)))", "7"),
5325            (r#"(second (iter-next (iter (object "a" 7))))"#, "7"),
5326        ];
5327        for (source, expected) in cases {
5328            assert_eq!(runtime.eval_text(source).unwrap(), expected, "{source}");
5329        }
5330
5331        let invalid = [
5332            ("(. [1 2] (get 0))", "array or object marker"),
5333            ("(. {} (get \"a\"))", "array or object marker"),
5334            ("(. 1 (get 0))", "array or object marker"),
5335            ("(. (array 1) (unknown))", "unsupported array method"),
5336            (
5337                r#"(. (object "a" 1) (unknown))"#,
5338                "unsupported object method",
5339            ),
5340            ("(. (array 1) (set 0))", "expects an index and value"),
5341            ("(. (array 1) (clone 1))", "expects no arguments"),
5342            (r#"(. (object "a" 1) (clone 1))"#, "expects no arguments"),
5343            (
5344                "(. (array 1) (map (fn [x y] x)))",
5345                "function expects 2 arguments",
5346            ),
5347            ("(x:array 1)", "unbound symbol: x:array"),
5348            ("(x:object)", "unbound symbol: x:object"),
5349            ("(x:get nil 0)", "unbound symbol: x:get"),
5350            ("(x:set nil 0 1)", "unbound symbol: x:set"),
5351            (
5352                r#"(host-symbol "java.lang.String")"#,
5353                "unbound symbol: host-symbol",
5354            ),
5355            (r#"(host-get nil "value")"#, "unbound symbol: host-get"),
5356            (r#"(host-call nil "run")"#, "unbound symbol: host-call"),
5357        ];
5358        for (source, message) in invalid {
5359            assert!(
5360                runtime.eval_text(source).unwrap_err().contains(message),
5361                "{source}"
5362            );
5363        }
5364    }
5365    #[test]
5366    fn marker_arrays_and_objects_use_restricted_dot_calls() {
5367        let mut runtime = Runtime::new();
5368        assert_eq!(runtime.eval_text("(count (array 1 2 3))").unwrap(), "3");
5369        assert_eq!(runtime.eval_text("(. (array 1 2) (get 1))").unwrap(), "2");
5370        assert_eq!(
5371            runtime
5372                .eval_text("(let (a (array 1 2)) (do (. a (set 1 7)) (. a (get 1))))")
5373                .unwrap(),
5374            "7"
5375        );
5376        assert_eq!(
5377            runtime
5378                .eval_text("(let (a (array 1)) (do (. a (push-last 2)) (count a)))")
5379                .unwrap(),
5380            "2"
5381        );
5382        assert_eq!(
5383            runtime
5384                .eval_text(r#"(. (object "answer" 41) (get "answer"))"#)
5385                .unwrap(),
5386            "41"
5387        );
5388        assert_eq!(
5389            runtime
5390                .eval_text(
5391                    r#"(let (o (object)) (do (. o (set "answer" 42)) (. o (get "answer"))))"#
5392                )
5393                .unwrap(),
5394            "42"
5395        );
5396        assert_eq!(
5397            runtime
5398                .eval_text(r#"(. (object "answer" 41) (has? "answer"))"#)
5399                .unwrap(),
5400            "true"
5401        );
5402    }
5403
5404    #[test]
5405    fn strings_and_bytes_support_utf8_copy_and_slice() {
5406        let mut runtime = Runtime::new();
5407        assert_eq!(
5408            runtime.eval_text(r#"(str "hello" " " "world")"#).unwrap(),
5409            "\"hello world\""
5410        );
5411        assert_eq!(runtime.eval_text(r#"(str/length "a😀b")"#).unwrap(), "3");
5412        assert_eq!(
5413            runtime.eval_text(r#"(str/char-at "a😀b" 1)"#).unwrap(),
5414            "\"😀\""
5415        );
5416        assert_eq!(
5417            runtime.eval_text(r#"(str/slice "a😀b" 1 2)"#).unwrap(),
5418            "\"😀\""
5419        );
5420        assert_eq!(
5421            runtime.eval_text(r#"(str/index-of "a😀b" "b")"#).unwrap(),
5422            "2"
5423        );
5424        assert_eq!(
5425            runtime
5426                .eval_text(r#"(str/last-index-of "😀a😀" "😀")"#)
5427                .unwrap(),
5428            "2"
5429        );
5430        assert_eq!(
5431            runtime.eval_text(r#"(str/pad-left "x" 3 "😀")"#).unwrap(),
5432            "\"😀😀x\""
5433        );
5434        assert_eq!(
5435            runtime.eval_text(r#"(str/trim "  hara  ")"#).unwrap(),
5436            "\"hara\""
5437        );
5438        assert_eq!(
5439            runtime
5440                .eval_text(r#"(str/decode-utf8 (str/encode-utf8 "hé"))"#)
5441                .unwrap(),
5442            "\"hé\""
5443        );
5444        assert_eq!(
5445            runtime
5446                .eval_text("(bytes/slice (bytes 1 2 3) 1 3)")
5447                .unwrap(),
5448            "(bytes 2 3)"
5449        );
5450        assert_eq!(runtime.eval_text("(let (source (bytes 1 2)) (let (copy (bytes/copy source)) (do (bytes/set copy 0 9) (bytes/get source 0))))").unwrap(), "1");
5451    }
5452
5453    #[test]
5454    fn byte_buffers_preserve_signed_storage_and_unsigned_reads() {
5455        let mut runtime = Runtime::new();
5456        assert_eq!(
5457            runtime.eval_text("(bytes 1 2 -3)").unwrap(),
5458            "(bytes 1 2 -3)"
5459        );
5460        assert_eq!(
5461            runtime.eval_text("(bytes/get (bytes 1 2 -3) 2)").unwrap(),
5462            "253"
5463        );
5464        assert_eq!(runtime.eval_text("(bytes/u8 -1)").unwrap(), "255");
5465        assert_eq!(runtime.eval_text("(bytes/s8 255)").unwrap(), "-1");
5466        assert_eq!(
5467            runtime
5468                .eval_text("(let (b (bytes 1 2)) (do (bytes/set b 0 9) (bytes/get b 0)))")
5469                .unwrap(),
5470            "9"
5471        );
5472        assert_eq!(runtime.eval_text("(bytes/get (bytes 1) 4 7)").unwrap(), "7");
5473        assert_eq!(
5474            runtime.eval_text("(bytes/count (bytes 1 2 -3))").unwrap(),
5475            "3"
5476        );
5477    }
5478
5479    #[test]
5480    fn bytes_and_bits_cover_conversion_copy_and_overflow_boundaries() {
5481        let mut runtime = Runtime::new();
5482        let cases = [
5483            ("(bytes/u8 -128)", "128"),
5484            ("(bytes/u8 255)", "255"),
5485            ("(bytes/s8 -128)", "-128"),
5486            ("(bytes/s8 128)", "-128"),
5487            ("(bytes/s8 255)", "-1"),
5488            ("(bytes/get (bytes -128 0 127 255) 0)", "128"),
5489            ("(bytes/get (bytes -128 0 127 255) 3)", "255"),
5490            ("(bytes/slice (bytes 1 2 3) 1)", "(bytes 2 3)"),
5491            ("(bytes/slice (bytes 1 2 3) 1 1)", "(bytes)"),
5492            (
5493                "(let [b (bytes 0)] (count [(bytes/set b 0 255) (bytes/get b 0)]))",
5494                "2",
5495            ),
5496            ("(bit-not -2147483648)", "2147483647"),
5497            ("(bit-not 2147483647)", "-2147483648"),
5498            ("(bit-and -2147483648 2147483647)", "0"),
5499            ("(bit-or -2147483648 1)", "-2147483647"),
5500            ("(bit-xor -1 2147483647)", "-2147483648"),
5501            ("(bit-shift-left 1 0)", "1"),
5502            ("(bit-shift-left 1 31)", "-2147483648"),
5503            ("(bit-shift-left 2147483647 1)", "-2"),
5504            ("(bit-shift-right -2147483648 31)", "-1"),
5505            ("(bit-shift-right 2147483647 31)", "0"),
5506            ("(bit-shift-left 2147483648 0)", "-2147483648"),
5507        ];
5508        for (source, expected) in cases {
5509            assert_eq!(runtime.eval_text(source).unwrap(), expected, "{source}");
5510        }
5511
5512        let invalid = [
5513            ("(bytes -129)", "range -128..255"),
5514            ("(bytes 256)", "range -128..255"),
5515            ("(bytes/u8 -129)", "range -128..255"),
5516            ("(bytes/s8 256)", "range -128..255"),
5517            ("(bytes/get (bytes 1) 1)", "out of bounds"),
5518            ("(bytes/set (bytes 1) 1 0)", "out of bounds"),
5519            ("(bytes/slice (bytes 1 2) 2 1)", "out of bounds"),
5520            ("(bytes/slice (bytes 1 2) 0 3)", "out of bounds"),
5521            ("(str/decode-utf8 (bytes 255))", "invalid UTF-8"),
5522            ("(bit-shift-left 1 -1)", "range 0..31"),
5523            ("(bit-shift-right 1 32)", "range 0..31"),
5524        ];
5525        for (source, message) in invalid {
5526            assert!(
5527                runtime.eval_text(source).unwrap_err().contains(message),
5528                "{source}"
5529            );
5530        }
5531
5532        assert_eq!(
5533            runtime
5534                .eval_text("(let [source (bytes 1 2 3) copy (bytes/copy source)] (do (bytes/set copy 0 9) (bytes/get source 0)))")
5535                .unwrap(),
5536            "1"
5537        );
5538        assert_eq!(
5539            runtime
5540                .eval_text("(let [source (bytes 1 2 3) part (bytes/slice source 0 2)] (do (bytes/set part 0 9) (bytes/get source 0)))")
5541                .unwrap(),
5542            "1"
5543        );
5544    }
5545    #[test]
5546    fn iterator_aliases_and_combinators_match_core_shapes() {
5547        let mut runtime = Runtime::new();
5548        assert_eq!(
5549            runtime
5550                .eval_text("(nth (map (fn [x] (* x 2)) [1 2]) 0)")
5551                .unwrap(),
5552            "2"
5553        );
5554        assert_eq!(
5555            runtime
5556                .eval_text("(nth (filter (fn [x] (= x 2)) [1 2 3]) 0)")
5557                .unwrap(),
5558            "2"
5559        );
5560        assert_eq!(
5561            runtime
5562                .eval_text("(nth (take 1 (drop 1 [1 2 3])) 0)")
5563                .unwrap(),
5564            "2"
5565        );
5566        assert_eq!(
5567            runtime.eval_text("(nth (nth (zip [1] [2]) 0) 1)").unwrap(),
5568            "2"
5569        );
5570        assert_eq!(
5571            runtime
5572                .eval_text(
5573                    "(let (it (cycle [1 2])) (do (iter-next it) (iter-next it) (iter-next it)))"
5574                )
5575                .unwrap(),
5576            "1"
5577        );
5578        assert_eq!(
5579            runtime.eval_text("(iter-next (concat [1] [2]))").unwrap(),
5580            "1"
5581        );
5582    }
5583
5584    #[test]
5585    fn seq_boundaries_and_source_aware_transforms_match_design() {
5586        let mut runtime = Runtime::new();
5587        assert_eq!(
5588            runtime.eval_text("(vector? (map inc [1 2 3]))").unwrap(),
5589            "true"
5590        );
5591        assert_eq!(runtime.eval_text("(first (map inc [1 2 3]))").unwrap(), "2");
5592        assert_eq!(
5593            runtime.eval_text("(first ((map inc) [1 2 3]))").unwrap(),
5594            "2"
5595        );
5596        assert_eq!(
5597            runtime
5598                .eval_text("(first ((map inc) (seq [1 2 3])))")
5599                .unwrap(),
5600            "2"
5601        );
5602        assert_eq!(
5603            runtime
5604                .eval_text("(first (seq (map inc) [1 2 3]))")
5605                .unwrap(),
5606            "2"
5607        );
5608        assert_eq!(
5609            runtime
5610                .eval_text("(first ((comp (map inc) (map inc)) [1 2 3]))")
5611                .unwrap(),
5612            "3"
5613        );
5614        assert_eq!(
5615            runtime
5616                .eval_text("(first (seq (comp (map inc) (map inc)) [1 2 3]))")
5617                .unwrap(),
5618            "3"
5619        );
5620    }
5621
5622    #[test]
5623    fn issue_200_nil_terminates_sequences_and_iterator_lookahead_is_exact() {
5624        let mut runtime = Runtime::new();
5625        assert_eq!(
5626            runtime
5627                .eval_text(
5628                    "[(nil? (seq nil)) \
5629                      (nil? (seq [])) \
5630                      (nil? (rest nil)) \
5631                      (nil? (rest [])) \
5632                      (nil? (rest [1])) \
5633                      (seq? (rest [1 2])) \
5634                      (vec (rest [1])) \
5635                      (vec (rest [1 2]))]"
5636                )
5637                .unwrap(),
5638            "[true true true true true true [] [2]]"
5639        );
5640        assert_eq!(
5641            runtime
5642                .eval_text(
5643                    "(let [it (Iter/iter-drop 1 [1])] \
5644                       [(iter-next? it) (iter-next? it) (nil? (seq it))])"
5645                )
5646                .unwrap(),
5647            "[false false true]"
5648        );
5649        assert_eq!(
5650            runtime
5651                .eval_text(
5652                    "(let [it (Iter/iter-map inc [1])] \
5653                       [(iter-next? it) (iter-next? it) (iter-next it) (iter-next? it)])"
5654                )
5655                .unwrap(),
5656            "[true true 2 false]"
5657        );
5658    }
5659
5660    #[test]
5661    fn issue_200_finite_generated_iterators_materialize_and_failures_propagate() {
5662        let mut runtime = Runtime::new();
5663        assert_eq!(
5664            runtime
5665                .eval_text(
5666                    "[(last (Iter/iter-take 2 [1 2 3])) \
5667                      (vec (reverse (Iter/iter-take 2 [1 2 3]))) \
5668                      (vec (Iter/iter-zip [1] (repeat 0))) \
5669                      (vec (Iter/iter-interleave [1] (repeat 0)))]"
5670                )
5671                .unwrap(),
5672            "[2 [2 1] [[1 0]] [1 0]]"
5673        );
5674        assert!(runtime
5675            .eval_text("(count (Iter/iter-map (fn [x] (throw \"boom\")) [1]))")
5676            .unwrap_err()
5677            .contains("boom"));
5678        assert!(runtime
5679            .eval_text("(count (Iter/iter-map (fn [x] (throw \"weekend\")) [1]))")
5680            .unwrap_err()
5681            .contains("weekend"));
5682        assert_eq!(
5683            runtime
5684                .eval_text(
5685                    "[(seq? (seq [1])) \
5686                      (iter? (seq [1])) \
5687                      (vec (cons 0 (rest [1 2]))) \
5688                      (vec (Iter/iter-take 4 (cons 0 (repeat 1))))]"
5689                )
5690                .unwrap(),
5691            "[true true [0 2] [0 1 1 1]]"
5692        );
5693        assert!(runtime
5694            .eval_text("(cycle [])")
5695            .unwrap_err()
5696            .contains("cycle expects a non-empty source"));
5697    }
5698
5699    #[test]
5700    fn iterators_are_closeable_and_support_map_filter() {
5701        let mut runtime = Runtime::new();
5702        assert_eq!(
5703            runtime
5704                .eval_text("(let (it (iter [1 2])) (iter-next it))")
5705                .unwrap(),
5706            "1"
5707        );
5708        assert_eq!(
5709            runtime
5710                .eval_text("(let (it (iter [1 2])) (do (iter-next it) (iter-next it)))")
5711                .unwrap(),
5712            "2"
5713        );
5714        assert_eq!(
5715            runtime.eval_text("(iter-next? (iter [1]))").unwrap(),
5716            "true"
5717        );
5718        assert_eq!(
5719            runtime
5720                .eval_text("(let (it (iter [1])) (do (Iter/iter-close it) (iter-next? it)))")
5721                .unwrap(),
5722            "false"
5723        );
5724        assert_eq!(
5725            runtime
5726                .eval_text("(let (it (Iter/iter-cycle [1 2])) (do (iter-next it) (Iter/iter-close it) (iter-next? it)))")
5727                .unwrap(),
5728            "false"
5729        );
5730        assert_eq!(
5731            runtime
5732                .eval_text("(let (it (Iter/iter-zip [1 2] [3 4])) (do (Iter/iter-close it) (iter-next? it)))")
5733                .unwrap(),
5734            "false"
5735        );
5736        assert_eq!(
5737            runtime
5738                .eval_text("(iter-next (Iter/iter-map (fn [x] (* x 2)) [1 2]))")
5739                .unwrap(),
5740            "2"
5741        );
5742        assert_eq!(
5743            runtime
5744                .eval_text("(iter-next (Iter/iter-filter (fn [x] (= x 2)) [1 2 3]))")
5745                .unwrap(),
5746            "2"
5747        );
5748        assert_eq!(
5749            runtime
5750                .eval_text("(receiver-category (iter [1]))")
5751                .unwrap_err(),
5752            "unbound symbol: receiver-category"
5753        );
5754    }
5755
5756    #[test]
5757    fn evaluator_protocol_calls_cover_collections_and_bytes() {
5758        let mut runtime = Runtime::new();
5759        assert_eq!(runtime.eval_text("(ICount/count [1 2 3])").unwrap(), "3");
5760        assert_eq!(
5761            runtime.eval_text("(INth/nth (bytes 1 -3) 1)").unwrap(),
5762            "-3"
5763        );
5764        assert_eq!(
5765            runtime
5766                .eval_text(r#"(ILookup/lookup {"a" 9} "a")"#)
5767                .unwrap(),
5768            "9"
5769        );
5770        assert_eq!(
5771            runtime.eval_text(r#"(has? {"a" nil} "a")"#).unwrap(),
5772            "true"
5773        );
5774        assert_eq!(runtime.eval_text("(has? [10 20] 1)").unwrap(), "true");
5775        assert_eq!(runtime.eval_text("(has? [10 20] 10)").unwrap(), "false");
5776        assert_eq!(
5777            runtime
5778                .eval_text(r#"(IAssoc/assoc {"a" 9} "b" 10)"#)
5779                .unwrap(),
5780            r#"{"a" 9 "b" 10}"#
5781        );
5782        assert_eq!(runtime.eval_text(r#"(IConj/conj [1] 2)"#).unwrap(), "[1 2]");
5783        assert_eq!(
5784            runtime
5785                .eval_text(r#"(IDissoc/dissoc {"a" 9 "b" 10} "a")"#)
5786                .unwrap(),
5787            r#"{"b" 10}"#
5788        );
5789        runtime
5790            .protocols
5791            .register("IIter", "iter", protocol_custom_iterator);
5792        assert_eq!(runtime.eval_text("(iter-next (iter 99))").unwrap(), "7");
5793        assert!(runtime.has_protocol_method("IAssoc", "assoc"));
5794        assert!(runtime
5795            .eval_text("(ICount/count 1)")
5796            .unwrap_err()
5797            .contains("protocol/unsupported-receiver"));
5798    }
5799
5800    #[test]
5801    fn portable_type_descriptors_cover_named_and_collection_values() {
5802        let mut runtime = Runtime::new();
5803        for (source, expected) in [
5804            ("nil", ":hara.type/nil"),
5805            (":key", ":hara.type/keyword"),
5806            ("(symbol \"hara/name\")", ":hara.type/symbol"),
5807            ("[]", ":hara.type/tuple"),
5808            ("(list)", ":hara.type/list"),
5809            ("(queue)", ":hara.type/queue"),
5810            ("(vector)", ":hara.type/vector"),
5811            ("(hash-map)", ":hara.type/hash-map"),
5812            ("{}", ":hara.type/ordered-map"),
5813            ("(sorted-map)", ":hara.type/sorted-map"),
5814            ("(trie)", ":hara.type/trie"),
5815            ("(hash-set)", ":hara.type/hash-set"),
5816            ("#{}", ":hara.type/ordered-set"),
5817            ("(sorted-set)", ":hara.type/sorted-set"),
5818            ("(bytes)", ":hara.type/byte-buffer"),
5819            ("(array)", ":hara.type/array"),
5820            ("(object)", ":hara.type/object"),
5821            ("(atom 0)", ":hara.type/atom"),
5822            ("(ns:create (quote example))", ":hara.type/namespace"),
5823        ] {
5824            assert_eq!(
5825                runtime.eval_text(&format!("(type {source})")).unwrap(),
5826                expected
5827            );
5828        }
5829        assert_eq!(
5830            runtime.eval_text("(type (type []))").unwrap(),
5831            ":hara.type/keyword"
5832        );
5833        assert!(runtime
5834            .eval_text("(type)")
5835            .unwrap_err()
5836            .contains("one value"));
5837    }
5838
5839    #[test]
5840    fn protocol_registry_dispatches_by_protocol_and_method() {
5841        let mut registry = core::ProtocolRegistry::new();
5842        registry.register("IIdentity", "identity", protocol_identity);
5843        assert!(core::ProtocolRegistry::core().contains("IAssoc", "assoc"));
5844        assert!(registry.contains("IIdentity", "identity"));
5845        assert_eq!(
5846            registry
5847                .invoke("IIdentity", "identity", &[core::Value::Number(7)])
5848                .unwrap(),
5849            core::Value::Number(7)
5850        );
5851        assert!(registry
5852            .invoke("IIdentity", "missing", &[])
5853            .unwrap_err()
5854            .contains("missing protocol method"));
5855        assert_eq!(
5856            core::receiver_category(&core::Value::Vector(Default::default())),
5857            "vector"
5858        );
5859    }
5860
5861    #[test]
5862    fn functions_support_variadic_rest_parameters() {
5863        let mut runtime = Runtime::new();
5864        assert_eq!(
5865            runtime
5866                .eval_text("((fn [x & rest] (+ x (count rest))) 40 1 2)")
5867                .unwrap(),
5868            "42"
5869        );
5870        assert_eq!(
5871            runtime
5872                .eval_text("(do (defn collect [x & rest] (count rest)) (collect 1 2 3 4))")
5873                .unwrap(),
5874            "3"
5875        );
5876        assert!(runtime
5877            .eval_text("((fn [x & rest] x))")
5878            .unwrap_err()
5879            .contains("at least 1"));
5880    }
5881
5882    #[test]
5883    fn issue_133_cases_run_from_the_shared_l0_conformance_corpus() {
5884        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> &'a Form {
5885            entries
5886                .iter()
5887                .find_map(|(candidate, value)| match candidate {
5888                    Form::Keyword(name) if name == key => Some(value),
5889                    _ => None,
5890                })
5891                .unwrap_or_else(|| panic!("missing :{key}"))
5892        }
5893
5894        let Some(corpus) =
5895            repo_text("specs/00-unsorted/platform-language/draft/conformance/l0.edn")
5896        else {
5897            return;
5898        };
5899        let manifest = kernel::parse_forms(&corpus).unwrap().remove(0);
5900        let Form::Map(manifest) = manifest else {
5901            panic!("L0 conformance corpus must be a map")
5902        };
5903        let Form::Vector(cases) = entry(&manifest, "cases") else {
5904            panic!("L0 conformance :cases must be a vector")
5905        };
5906        let ids = [
5907            "function/closure-capture",
5908            "function/fixed-arity",
5909            "function/variadic-arity",
5910            "function/multiple-arities",
5911            "function/arity-error",
5912            "binding/let-sequential",
5913            "binding/sequential-destructuring",
5914            "binding/map-destructuring",
5915            "binding/missing-destructuring",
5916            "binding/nil-map-default",
5917            "definition/doc-metadata",
5918            "definition/schema-metadata",
5919            "definition/arglists-metadata",
5920            "sequence/empty-is-nil",
5921            "sequence/non-empty-rest",
5922            "sequence/is-iterator",
5923            "sequence/lazy-cons",
5924            "sequence/reject-conj",
5925            "iterator/exact-lookahead",
5926            "iterator/generated-exhaustion",
5927            "iterator/shortest-source-finite",
5928            "iterator/nil-requires-conversion",
5929            "iterator/native-combinator-qualified",
5930            "iterator/root-combinator-unbound",
5931            "iterator/empty-cycle-rejected",
5932            "runtime/recur-outside-target",
5933            "runtime/recur-arity",
5934            "error/catch-guest-value",
5935            "error/catch-order",
5936            "error/unmatched-catch",
5937            "error/finally-normal",
5938            "error/finally-unwind",
5939        ];
5940
5941        for id in ids {
5942            let case = cases
5943                .iter()
5944                .find(|case| {
5945                    matches!(
5946                        case,
5947                        Form::Map(entries)
5948                            if matches!(entry(entries, "id"), Form::Keyword(name) if name == id)
5949                    )
5950                })
5951                .unwrap_or_else(|| panic!("missing conformance case :{id}"));
5952            let Form::Map(case) = case else {
5953                unreachable!()
5954            };
5955            let Form::String(source) = entry(case, "source") else {
5956                panic!(":{id} source must be a string")
5957            };
5958            let Form::Map(expect) = entry(case, "expect") else {
5959                panic!(":{id} expect must be a map")
5960            };
5961            let mut runtime = Runtime::new();
5962            if expect
5963                .iter()
5964                .any(|(key, _)| matches!(key, Form::Keyword(name) if name == "error"))
5965            {
5966                assert!(runtime.eval_text(source).is_err(), ":{id} should fail");
5967            } else {
5968                let expected = match entry(expect, "value") {
5969                    Form::Number(value) => value.to_string(),
5970                    Form::String(value) => format!("{value:?}"),
5971                    Form::Bool(value) => value.to_string(),
5972                    Form::Nil => "nil".to_owned(),
5973                    value => panic!(":{id} has unsupported expected value {value:?}"),
5974                };
5975                let actual = runtime
5976                    .eval_text(source)
5977                    .unwrap_or_else(|error| panic!(":{id} unexpectedly failed: {error}"));
5978                assert_eq!(actual, expected, ":{id}");
5979            }
5980        }
5981    }
5982
5983    #[test]
5984    fn issue_134_module_scenarios_have_machine_readable_acceptance_data() {
5985        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
5986            entries
5987                .iter()
5988                .find_map(|(candidate, value)| match candidate {
5989                    Form::Keyword(name) if name == key => Some(value),
5990                    _ => None,
5991                })
5992        }
5993
5994        let Some(corpus) =
5995            repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn")
5996        else {
5997            return;
5998        };
5999        let manifest = kernel::parse_forms(&corpus).unwrap().remove(0);
6000        let Form::Map(manifest) = manifest else {
6001            panic!("module conformance corpus must be a map")
6002        };
6003        let Some(Form::Vector(cases)) = entry(&manifest, "cases") else {
6004            panic!("module conformance :cases must be a vector")
6005        };
6006        assert!(cases.len() >= 20);
6007        let mut ids = HashSet::new();
6008        for case in cases {
6009            let Form::Map(case) = case else {
6010                panic!("module conformance cases must be maps")
6011            };
6012            let Some(Form::Keyword(id)) = entry(case, "id") else {
6013                panic!("module conformance case is missing :id")
6014            };
6015            assert!(ids.insert(id.clone()), "duplicate module case :{id}");
6016            assert!(
6017                matches!(entry(case, "area"), Some(Form::Keyword(_))),
6018                ":{id}"
6019            );
6020            assert!(
6021                matches!(entry(case, "scenario"), Some(Form::Keyword(_))),
6022                ":{id}"
6023            );
6024            assert!(matches!(entry(case, "expect"), Some(Form::Map(_))), ":{id}");
6025        }
6026    }
6027
6028    #[test]
6029    fn module_ns_require_reload_executes_shared_spec_fixture() {
6030        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
6031            entries.iter().find_map(|(candidate, value)| {
6032                matches!(candidate, Form::Keyword(name) if name == key).then_some(value)
6033            })
6034        }
6035
6036        let case = module_case("module/ns-require-reload");
6037        let Some(Form::Map(fixture)) = entry(&case, "fixture") else {
6038            panic!(":module/ns-require-reload must declare :fixture")
6039        };
6040        let Some(Form::Map(resource)) = entry(fixture, "resource") else {
6041            panic!("reload fixture must declare :resource")
6042        };
6043        let Some(Form::String(namespace)) = entry(resource, "namespace") else {
6044            panic!("reload resource must declare string :namespace")
6045        };
6046        let Some(Form::Map(revisions)) = entry(resource, "revisions") else {
6047            panic!("reload resource must declare :revisions")
6048        };
6049        let Some(Form::Vector(steps)) = entry(fixture, "steps") else {
6050            panic!("reload fixture must declare :steps")
6051        };
6052
6053        let mut runtime = Runtime::new();
6054        for step in steps {
6055            let Form::Map(step) = step else {
6056                panic!("reload fixture steps must be maps")
6057            };
6058            let Some(Form::Keyword(operation)) = entry(step, "op") else {
6059                panic!("reload fixture step must declare :op")
6060            };
6061            match operation.as_str() {
6062                "resource/use" => {
6063                    let Some(Form::Keyword(revision)) = entry(step, "revision") else {
6064                        panic!(":resource/use must declare :revision")
6065                    };
6066                    let Some(Form::String(source)) = entry(revisions, revision) else {
6067                        panic!("missing reload resource revision :{revision}")
6068                    };
6069                    runtime.register_resource(namespace, source);
6070                }
6071                "eval" => {
6072                    let Some(Form::String(source)) = entry(step, "source") else {
6073                        panic!(":eval must declare string :source")
6074                    };
6075                    let Some(Form::Map(expect)) = entry(step, "expect") else {
6076                        panic!(":eval must declare :expect")
6077                    };
6078                    if let Some(Form::String(expected)) = entry(expect, "display") {
6079                        assert_eq!(
6080                            runtime.eval_text(source).unwrap_or_else(|error| {
6081                                panic!("shared reload eval failed for {source}: {error}")
6082                            }),
6083                            *expected
6084                        );
6085                    } else if matches!(entry(expect, "error"), Some(Form::Bool(true))) {
6086                        runtime
6087                            .eval_text(source)
6088                            .expect_err("shared reload eval must fail");
6089                    } else if let Some(Form::String(marker)) = entry(expect, "error-contains") {
6090                        let error = runtime
6091                            .eval_text(source)
6092                            .expect_err("shared reload eval must fail");
6093                        assert!(error.contains(marker), "{error}");
6094                    } else {
6095                        panic!("unsupported shared reload expectation")
6096                    }
6097                }
6098                "assert/revision" => {
6099                    let Some(Form::Number(expected)) = entry(step, "expect") else {
6100                        panic!(":assert/revision must declare numeric :expect")
6101                    };
6102                    assert_eq!(
6103                        runtime
6104                            .eval_text(&format!("(module-revision '{namespace})"))
6105                            .unwrap(),
6106                        expected.to_string()
6107                    );
6108                }
6109                other => panic!("unsupported shared reload operation :{other}"),
6110            }
6111        }
6112    }
6113
6114    #[test]
6115    fn callable_var_scenarios_execute_from_shared_spec() {
6116        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> Option<&'a Form> {
6117            entries.iter().find_map(|(candidate, value)| {
6118                matches!(candidate, Form::Keyword(name) if name == key).then_some(value)
6119            })
6120        }
6121
6122        for id in [
6123            "namespace/callable-var-precedence",
6124            "namespace/callable-var-lexical-shadow",
6125            "namespace/callable-var-late-binding",
6126            "namespace/referred-var-protected",
6127        ] {
6128            let case = module_case(id);
6129            let Some(Form::String(setup)) = entry(&case, "setup") else {
6130                panic!(":{id} must declare string :setup")
6131            };
6132            let Some(Form::String(source)) = entry(&case, "source") else {
6133                panic!(":{id} must declare string :source")
6134            };
6135            let Some(Form::Map(expect)) = entry(&case, "expect") else {
6136                panic!(":{id} must declare :expect")
6137            };
6138            let mut runtime = Runtime::new();
6139            runtime
6140                .eval_text(setup)
6141                .unwrap_or_else(|error| panic!(":{id} setup failed: {error}"));
6142            if let Some(Form::String(expected)) = entry(expect, "display") {
6143                assert_eq!(
6144                    runtime
6145                        .eval_text(source)
6146                        .unwrap_or_else(|error| panic!(":{id} failed: {error}")),
6147                    *expected,
6148                    ":{id}"
6149                );
6150            } else if let Some(Form::String(marker)) = entry(expect, "error-contains") {
6151                let error = runtime
6152                    .eval_text(source)
6153                    .expect_err(&format!(":{id} must fail"));
6154                assert!(error.contains(marker), ":{id}: {error}");
6155            } else {
6156                panic!(":{id} has unsupported expectation")
6157            }
6158        }
6159    }
6160
6161    #[test]
6162    fn issue_134_lazy_namespace_state_is_non_forcing_and_failure_is_sticky() {
6163        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6164        {
6165            return;
6166        }
6167        assert_eq!(
6168            module_expect("lazy/non-forcing", "state"),
6169            Form::Keyword("unloaded".into())
6170        );
6171        assert_eq!(
6172            module_expect("lazy/non-forcing", "target-evaluated"),
6173            Form::Bool(false)
6174        );
6175        assert_eq!(
6176            module_expect("lazy/qualified-force", "target-evaluations"),
6177            Form::Number(1)
6178        );
6179        assert_eq!(
6180            module_expect("lazy/failure-state", "state"),
6181            Form::Keyword("failed".into())
6182        );
6183        assert_eq!(
6184            module_expect("lazy/failure-state", "partial-state"),
6185            Form::Bool(false)
6186        );
6187        assert_eq!(
6188            module_expect("lazy/explicit-retry", "ordinary-force-retries"),
6189            Form::Bool(false)
6190        );
6191        assert_eq!(
6192            module_expect("lazy/explicit-retry", "reload-retries"),
6193            Form::Bool(true)
6194        );
6195        assert_eq!(
6196            module_expect("module/reload-revision", "revision-increment"),
6197            Form::Number(1)
6198        );
6199        assert_eq!(
6200            module_expect("module/reload-rollback", "previous-revision-preserved"),
6201            Form::Bool(true)
6202        );
6203        assert_eq!(
6204            module_expect("namespace/loading-state", "non-forcing"),
6205            Form::Bool(true)
6206        );
6207        assert_eq!(
6208            module_expect("namespace/cross-namespace-alias-state", "owner-explicit"),
6209            Form::Bool(true)
6210        );
6211
6212        let mut runtime = Runtime::new();
6213        runtime.register_resource(
6214            "example.lazy",
6215            "(ns example.lazy) (def observed-state (ns-state 'example.lazy)) (def answer 42)",
6216        );
6217
6218        assert_eq!(
6219            runtime
6220                .eval_text("(require [example.lazy :as lazy :lazy true])")
6221                .unwrap(),
6222            "nil"
6223        );
6224        assert_eq!(
6225            runtime.eval_text("(ns-state 'example.lazy)").unwrap(),
6226            ":unloaded"
6227        );
6228        assert_eq!(
6229            runtime
6230                .eval_text("(get (ns-alias-state 'lazy) :state)")
6231                .unwrap(),
6232            ":unloaded"
6233        );
6234        assert_eq!(runtime.eval_text("lazy/answer").unwrap(), "42");
6235        assert_eq!(
6236            runtime.eval_text("lazy/observed-state").unwrap(),
6237            ":loading"
6238        );
6239        assert_eq!(
6240            runtime.eval_text("(ns-state 'example.lazy)").unwrap(),
6241            ":loaded"
6242        );
6243        assert_eq!(
6244            runtime
6245                .eval_text("(module-revision 'example.lazy)")
6246                .unwrap(),
6247            "1"
6248        );
6249
6250        runtime.register_resource("example.lazy", "(ns example.lazy) (def answer 43)");
6251        runtime
6252            .eval_text("(require [example.lazy :as lazy :reload true])")
6253            .unwrap();
6254        assert_eq!(runtime.eval_text("lazy/answer").unwrap(), "43");
6255        assert_eq!(
6256            runtime
6257                .eval_text("(module-revision 'example.lazy)")
6258                .unwrap(),
6259            "2"
6260        );
6261
6262        runtime.register_resource(
6263            "example.lazy",
6264            "(ns example.lazy) (def answer 99) (def reload-leaked-134 1) (throw :reload-failed)",
6265        );
6266        assert!(runtime
6267            .eval_text("(require [example.lazy :as lazy :reload true])")
6268            .is_err());
6269        assert_eq!(runtime.eval_text("lazy/answer").unwrap(), "43");
6270        assert_eq!(
6271            runtime
6272                .eval_text("(module-revision 'example.lazy)")
6273                .unwrap(),
6274            "2"
6275        );
6276        assert_eq!(
6277            runtime.eval_text("(ns-state 'example.lazy)").unwrap(),
6278            ":loaded"
6279        );
6280        assert!(runtime
6281            .namespace_registry
6282            .find("example.lazy")
6283            .unwrap()
6284            .resolve(&crate::lang::data::Symbol::parse("reload-leaked-134"))
6285            .is_none());
6286
6287        runtime.register_resource(
6288            "example.broken",
6289            "(ns example.broken) (def leaked 1) (throw :broken)",
6290        );
6291        runtime
6292            .eval_text("(require [example.broken :as broken :lazy true])")
6293            .unwrap();
6294        assert!(runtime.eval_text("broken/leaked").is_err());
6295        assert_eq!(
6296            runtime.eval_text("(ns-state 'example.broken)").unwrap(),
6297            ":failed"
6298        );
6299        assert_eq!(
6300            runtime
6301                .eval_text("(get (ns-alias-state 'broken) :state)")
6302                .unwrap(),
6303            ":failed"
6304        );
6305        assert!(runtime.namespace_registry.find("example.broken").is_none());
6306        assert_eq!(runtime.current_namespace(), "user");
6307        assert_eq!(
6308            runtime
6309                .namespace_registry
6310                .current()
6311                .lazy_target("broken")
6312                .map(|name| name.as_str().to_owned()),
6313            Some("example.broken".into())
6314        );
6315
6316        runtime.register_resource("example.broken", "(ns example.broken) (def answer 42)");
6317        let sticky_error = runtime.eval_text("broken/answer").unwrap_err();
6318        assert!(
6319            sticky_error.contains("explicit reload"),
6320            "unexpected sticky lazy-load error: {sticky_error}"
6321        );
6322        assert!(
6323            sticky_error.contains("initial failure"),
6324            "sticky error should retain the initial failure detail: {sticky_error}"
6325        );
6326        runtime
6327            .eval_text("(require [example.broken :as broken :reload true])")
6328            .unwrap();
6329        assert_eq!(runtime.eval_text("broken/answer").unwrap(), "42");
6330        assert_eq!(
6331            runtime.eval_text("(ns-state 'example.broken)").unwrap(),
6332            ":loaded"
6333        );
6334
6335        runtime.eval_text("(ns observer)").unwrap();
6336        assert_eq!(
6337            runtime
6338                .eval_text("(get (ns-alias-state 'user 'broken) :state)")
6339                .unwrap(),
6340            ":loaded"
6341        );
6342
6343        let mut isolated = Runtime::new();
6344        assert_eq!(
6345            isolated.eval_text("(ns-state 'example.lazy)").unwrap(),
6346            ":unknown"
6347        );
6348    }
6349
6350    #[test]
6351    fn issue_134_dependency_order_cycles_and_canonical_cache_are_transactional() {
6352        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6353        {
6354            return;
6355        }
6356        assert_eq!(
6357            module_expect("module/canonical-cache", "duplicate-evaluation"),
6358            Form::Bool(false)
6359        );
6360        assert_eq!(
6361            module_expect("module/dependency-order", "order"),
6362            Form::Keyword("dependency-first-source-order".into())
6363        );
6364        assert_eq!(
6365            module_expect("module/cycle-rollback", "partial-state"),
6366            Form::Bool(false)
6367        );
6368        assert_eq!(
6369            module_expect("module/failure-rollback", "revision-increment"),
6370            Form::Bool(false)
6371        );
6372
6373        let mut runtime = Runtime::new();
6374        runtime.register_resource("graph.dependency", "(ns graph.dependency) (def value 41)");
6375        runtime.register_resource(
6376            "graph.root",
6377            concat!(
6378                "(ns graph.root) ",
6379                "(require [graph.dependency :as dependency]) ",
6380                "(def answer (+ dependency/value 1))"
6381            ),
6382        );
6383
6384        runtime
6385            .eval_text("(require [graph.root :as graph])")
6386            .unwrap();
6387        assert_eq!(runtime.eval_text("graph/answer").unwrap(), "42");
6388        assert_eq!(
6389            runtime
6390                .eval_text("(module-revision 'graph.dependency)")
6391                .unwrap(),
6392            "1"
6393        );
6394        assert_eq!(
6395            runtime.eval_text("(module-revision 'graph.root)").unwrap(),
6396            "1"
6397        );
6398        assert_eq!(
6399            runtime
6400                .namespace_registry
6401                .module_dependencies("graph.root")
6402                .iter()
6403                .map(|name| name.as_str().to_owned())
6404                .collect::<Vec<_>>(),
6405            vec!["graph.dependency"]
6406        );
6407
6408        runtime
6409            .eval_text("(require [graph.root :as graph])")
6410            .unwrap();
6411        assert_eq!(
6412            runtime.eval_text("(module-revision 'graph.root)").unwrap(),
6413            "1"
6414        );
6415
6416        runtime.register_resource(
6417            "cycle.first",
6418            concat!(
6419                "(ns cycle.first) ",
6420                "(def leaked-first 1) ",
6421                "(require [cycle.second :as second])"
6422            ),
6423        );
6424        runtime.register_resource(
6425            "cycle.second",
6426            concat!(
6427                "(ns cycle.second) ",
6428                "(def leaked-second 2) ",
6429                "(require [cycle.first :as first])"
6430            ),
6431        );
6432
6433        let cycle = runtime
6434            .eval_text("(require [cycle.first :as cycle])")
6435            .unwrap_err();
6436        assert!(cycle.contains("Cyclic namespace require"), "{cycle}");
6437        assert!(runtime.namespace_registry.find("cycle.first").is_none());
6438        assert!(runtime.namespace_registry.find("cycle.second").is_none());
6439        assert_eq!(
6440            runtime.eval_text("(module-revision 'cycle.first)").unwrap(),
6441            "0"
6442        );
6443        assert_eq!(
6444            runtime
6445                .eval_text("(module-revision 'cycle.second)")
6446                .unwrap(),
6447            "0"
6448        );
6449        assert!(runtime
6450            .namespace_registry
6451            .module_dependencies("cycle.first")
6452            .is_empty());
6453        assert!(runtime
6454            .namespace_registry
6455            .module_dependencies("cycle.second")
6456            .is_empty());
6457
6458        runtime.register_resource(
6459            "failure.root",
6460            concat!(
6461                "(ns failure.root) ",
6462                "(require [graph.dependency :as dependency]) ",
6463                "(def leaked dependency/value) ",
6464                "(throw :failure)"
6465            ),
6466        );
6467        assert!(runtime
6468            .eval_text("(require [failure.root :as failure])")
6469            .is_err());
6470        assert!(runtime.namespace_registry.find("failure.root").is_none());
6471        assert!(runtime
6472            .namespace_registry
6473            .module_dependencies("failure.root")
6474            .is_empty());
6475    }
6476
6477    #[test]
6478    fn issue_134_with_ns_uses_target_globals_and_restores_the_caller() {
6479        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6480        {
6481            return;
6482        }
6483        assert_eq!(
6484            module_expect("namespace/with-ns-success", "caller-restored"),
6485            Form::Bool(true)
6486        );
6487        assert_eq!(
6488            module_expect("namespace/with-ns-failure", "caller-restored"),
6489            Form::Bool(true)
6490        );
6491        assert_eq!(
6492            module_expect(
6493                "namespace/with-ns-lexical-isolation",
6494                "caller-locals-visible"
6495            ),
6496            Form::Bool(false)
6497        );
6498
6499        let mut runtime = Runtime::new();
6500        runtime
6501            .eval_text("(ns target) (def answer 41) (ns user)")
6502            .unwrap();
6503        assert_eq!(
6504            runtime
6505                .eval_text("(with-ns 'target (def answer 42) answer)")
6506                .unwrap(),
6507            "42"
6508        );
6509        assert_eq!(runtime.current_namespace(), "user");
6510        assert_eq!(runtime.eval_text("target/answer").unwrap(), "42");
6511
6512        assert!(runtime
6513            .eval_text("(with-ns 'target (throw :with-ns-failed))")
6514            .is_err());
6515        assert_eq!(runtime.current_namespace(), "user");
6516
6517        assert!(runtime
6518            .eval_text("(let [caller-local 42] (with-ns 'target caller-local))")
6519            .is_err());
6520        assert_eq!(runtime.current_namespace(), "user");
6521    }
6522
6523    #[test]
6524    fn issue_134_facade_vars_copy_roots_and_metadata_without_sharing_identity() {
6525        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6526        {
6527            return;
6528        }
6529        assert_eq!(
6530            module_expect("namespace/facade-var-copy", "same-var"),
6531            Form::Bool(false)
6532        );
6533        assert_eq!(
6534            module_expect("namespace/facade-var-copy", "copied-root"),
6535            Form::Bool(true)
6536        );
6537        assert_eq!(
6538            module_expect("namespace/facade-var-copy", "copied-metadata"),
6539            Form::Bool(true)
6540        );
6541
6542        let mut runtime = Runtime::new();
6543        runtime
6544            .eval_text("(ns source) (def ^{:doc \"copied\"} answer 41)")
6545            .unwrap();
6546        runtime.eval_text("(ns target)").unwrap();
6547        assert_eq!(
6548            runtime.eval_text("(deref (var source/answer))").unwrap(),
6549            "41"
6550        );
6551        runtime
6552            .eval_text("(intern-var 'target 'answer (var source/answer))")
6553            .unwrap();
6554        let source = runtime
6555            .namespace_registry
6556            .find("source")
6557            .unwrap()
6558            .resolve(&crate::lang::data::Symbol::parse("answer"))
6559            .unwrap();
6560        let target = runtime
6561            .namespace_registry
6562            .find("target")
6563            .unwrap()
6564            .resolve(&crate::lang::data::Symbol::parse("answer"))
6565            .unwrap();
6566
6567        assert!(!source.same_identity(&target));
6568        assert_eq!(source.deref_value(), target.deref_value());
6569        assert_eq!(source.metadata(), target.metadata());
6570    }
6571
6572    #[test]
6573    fn issue_134_aliases_and_refers_share_live_var_identity() {
6574        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6575        {
6576            return;
6577        }
6578        assert_eq!(
6579            module_expect("namespace/alias-var-identity", "same-var"),
6580            Form::Bool(true)
6581        );
6582        assert_eq!(
6583            module_expect("namespace/alias-var-identity", "live-root"),
6584            Form::Bool(true)
6585        );
6586        assert_eq!(
6587            module_expect("namespace/refer-var-identity", "same-var"),
6588            Form::Bool(true)
6589        );
6590        assert_eq!(
6591            module_expect("namespace/refer-var-identity", "live-root"),
6592            Form::Bool(true)
6593        );
6594
6595        let mut runtime = Runtime::new();
6596        runtime.register_resource("identity.source", "(ns identity.source) (def answer 41)");
6597        runtime
6598            .eval_text("(require [identity.source :as source :refer [answer]])")
6599            .unwrap();
6600        let source = runtime
6601            .namespace_registry
6602            .find("identity.source")
6603            .unwrap()
6604            .resolve(&crate::lang::data::Symbol::parse("answer"))
6605            .unwrap();
6606        let alias = runtime
6607            .namespace_registry
6608            .resolve(&crate::lang::data::Symbol::parse("source/answer"))
6609            .unwrap();
6610        let referred = runtime
6611            .namespace_registry
6612            .find("user")
6613            .unwrap()
6614            .resolve(&crate::lang::data::Symbol::parse("answer"))
6615            .unwrap();
6616        assert!(source.same_identity(&alias));
6617        assert!(source.same_identity(&referred));
6618        source.reset_value(core::Value::Number(42));
6619        assert_eq!(runtime.eval_text("source/answer").unwrap(), "42");
6620        assert_eq!(runtime.eval_text("answer").unwrap(), "42");
6621    }
6622
6623    #[test]
6624    fn issue_134_macro_reload_only_changes_new_compilations() {
6625        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6626        {
6627            return;
6628        }
6629        assert_eq!(
6630            module_expect("macro/reload-new-compilation", "existing-call-target"),
6631            Form::Keyword("unchanged".into())
6632        );
6633        assert_eq!(
6634            module_expect("macro/reload-new-compilation", "new-compilation"),
6635            Form::Keyword("new-expansion".into())
6636        );
6637
6638        let mut runtime = Runtime::new();
6639        runtime.register_resource(
6640            "reload.macros",
6641            "(ns reload.macros) (defmacro answer [] 41)",
6642        );
6643        runtime
6644            .eval_text(
6645                "(require [reload.macros :refer-macros [answer]]) \
6646                 (def compiled-before (macroexpand '(answer)))",
6647            )
6648            .unwrap();
6649        assert_eq!(runtime.eval_text("compiled-before").unwrap(), "41");
6650
6651        runtime.register_resource(
6652            "reload.macros",
6653            "(ns reload.macros) (defmacro answer [] 42)",
6654        );
6655        runtime
6656            .eval_text("(require [reload.macros :reload true :refer-macros [answer]])")
6657            .unwrap();
6658        assert_eq!(runtime.eval_text("compiled-before").unwrap(), "41");
6659        assert_eq!(runtime.eval_text("(answer)").unwrap(), "42");
6660    }
6661
6662    #[test]
6663    fn issue_134_session_namespace_module_and_macro_state_is_isolated() {
6664        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6665        {
6666            return;
6667        }
6668        assert_eq!(
6669            module_expect("session/namespace-isolation", "vars-shared"),
6670            Form::Bool(false)
6671        );
6672        assert_eq!(
6673            module_expect("session/namespace-isolation", "modules-shared"),
6674            Form::Bool(false)
6675        );
6676        assert_eq!(
6677            module_expect("session/namespace-isolation", "macros-shared"),
6678            Form::Bool(false)
6679        );
6680
6681        let mut kernel = SessionKernel::new();
6682        kernel.register_resource(
6683            "session.module",
6684            "(ns session.module) (defmacro chosen [] 41) (def answer 41)",
6685        );
6686        kernel.create_session("alpha").unwrap();
6687        kernel.create_session("beta").unwrap();
6688        kernel
6689            .eval(
6690                "alpha",
6691                "(do (require [session.module :as module :refer-macros [chosen]]) \
6692                     (def local-answer (chosen)) nil)",
6693            )
6694            .unwrap();
6695        assert_eq!(kernel.eval("alpha", "local-answer").unwrap(), "41");
6696        assert!(kernel.eval("beta", "local-answer").is_err());
6697        assert_eq!(
6698            kernel
6699                .eval("alpha", "(module-revision 'session.module)")
6700                .unwrap(),
6701            "1"
6702        );
6703        assert_eq!(
6704            kernel
6705                .eval("beta", "(module-revision 'session.module)")
6706                .unwrap(),
6707            "0"
6708        );
6709        assert!(kernel.eval("beta", "(chosen)").is_err());
6710    }
6711
6712    #[test]
6713    fn issue_134_source_and_hir_have_value_metadata_and_error_parity() {
6714        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6715        {
6716            return;
6717        }
6718        assert_eq!(
6719            module_expect("module/source-hir-parity", "same-value"),
6720            Form::Bool(true)
6721        );
6722        assert_eq!(
6723            module_expect("module/source-hir-parity", "same-var-metadata"),
6724            Form::Bool(true)
6725        );
6726        assert_eq!(
6727            module_expect("module/source-hir-parity", "same-error-category"),
6728            Form::Bool(true)
6729        );
6730
6731        use crate::kernel::halc::encode_halc_module;
6732
6733        let source = "(ns parity.demo) (defn value \"answer\" [] 42) (value)";
6734        let forms = kernel::parse_forms(source).unwrap();
6735        let artifact = encode_halc_module("parity.demo", "parity/demo.hal", source, forms).unwrap();
6736
6737        let mut source_runtime = Runtime::new();
6738        let mut hir_runtime = Runtime::new();
6739        assert_eq!(source_runtime.eval_text(source).unwrap(), "42");
6740        assert_eq!(hir_runtime.eval_halc(&artifact).unwrap(), "42");
6741
6742        let source_var = source_runtime
6743            .namespace_registry
6744            .find("parity.demo")
6745            .unwrap()
6746            .resolve(&crate::lang::data::Symbol::parse("value"))
6747            .unwrap();
6748        let hir_var = hir_runtime
6749            .namespace_registry
6750            .find("parity.demo")
6751            .unwrap()
6752            .resolve(&crate::lang::data::Symbol::parse("value"))
6753            .unwrap();
6754        assert_eq!(source_var.metadata(), hir_var.metadata());
6755
6756        let failing_source = "(throw :parity-failed)";
6757        let failing_artifact = encode_halc_module(
6758            "parity.failure",
6759            "parity/failure.hal",
6760            failing_source,
6761            kernel::parse_forms(failing_source).unwrap(),
6762        )
6763        .unwrap();
6764        let source_error = source_runtime.eval_text(failing_source).unwrap_err();
6765        let hir_error = hir_runtime.eval_halc(&failing_artifact).unwrap_err();
6766        assert!(source_error.contains("thrown: :parity-failed"));
6767        assert!(hir_error.contains("thrown: :parity-failed"));
6768    }
6769
6770    #[test]
6771    fn issue_134_runtime_profile_declares_deterministic_resource_precedence() {
6772        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6773        {
6774            return;
6775        }
6776        assert_eq!(
6777            module_expect("module/resource-precedence", "deterministic"),
6778            Form::Bool(true)
6779        );
6780        assert_eq!(
6781            module_expect("module/resource-precedence", "declared-by-runtime-profile"),
6782            Form::Bool(true)
6783        );
6784        assert_eq!(
6785            module_runtime_profile("rust", "resource-order"),
6786            Form::Vector(vec![
6787                Form::Keyword("loaded-native-namespace".into()),
6788                Form::Keyword("registered-resource".into()),
6789                Form::Keyword("registered-extension".into()),
6790            ])
6791        );
6792
6793        let mut runtime = Runtime::new();
6794        runtime.extensions.install(RangeExtension);
6795        runtime.register_resource(
6796            "range",
6797            "(def resource-precedence-marker 42) resource-precedence-marker",
6798        );
6799        assert_eq!(runtime.require_resource("range").unwrap(), "42");
6800        assert_eq!(runtime.require_resource("range").unwrap(), ":loaded");
6801        assert_eq!(
6802            runtime.eval_text("resource-precedence-marker").unwrap(),
6803            "42"
6804        );
6805    }
6806
6807    #[test]
6808    fn issue_134_sessions_unwind_bindings_and_transfer_only_immutable_data() {
6809        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6810        {
6811            return;
6812        }
6813        assert_eq!(
6814            module_expect("session/dynamic-unwind", "binding-session-local"),
6815            Form::Bool(true)
6816        );
6817        assert_eq!(
6818            module_expect("session/dynamic-unwind", "restored-after-error"),
6819            Form::Bool(true)
6820        );
6821        assert_eq!(
6822            module_expect("session/immutable-transfer", "immutable-data"),
6823            Form::Bool(true)
6824        );
6825        for kind in [
6826            "functions",
6827            "vars",
6828            "mutable-references",
6829            "streams",
6830            "sockets",
6831            "host-handles",
6832        ] {
6833            assert_eq!(
6834                module_expect("session/reject-live-transfer", kind),
6835                Form::Bool(false)
6836            );
6837        }
6838
6839        let mut kernel = SessionKernel::new();
6840        kernel.create_session("alpha").unwrap();
6841        kernel.create_session("beta").unwrap();
6842        assert_eq!(
6843            kernel
6844                .eval("alpha", "(do (def ^:dynamic *answer* 1) nil)")
6845                .unwrap(),
6846            "nil"
6847        );
6848        assert_eq!(
6849            kernel
6850                .eval("beta", "(do (def ^:dynamic *answer* 10) nil)")
6851                .unwrap(),
6852            "nil"
6853        );
6854        assert!(kernel
6855            .eval("alpha", "(binding [*answer* 2] (throw :binding-failed))")
6856            .is_err());
6857        assert_eq!(kernel.eval("alpha", "*answer*").unwrap(), "1");
6858        assert_eq!(kernel.eval("beta", "*answer*").unwrap(), "10");
6859
6860        assert_eq!(
6861            kernel
6862                .eval("alpha", "{:answer [1 2 {:nested #{:immutable}}]}")
6863                .unwrap(),
6864            "{:answer [1 2 {:nested #{:immutable}}]}"
6865        );
6866        for source in [
6867            "(fn [value] value)",
6868            "(var *answer*)",
6869            "(atom 1)",
6870            "(iter [1 2 3])",
6871        ] {
6872            let error = kernel.eval("alpha", source).unwrap_err();
6873            assert!(
6874                error.contains("SESSION_TRANSFER_REJECTED"),
6875                "{source} unexpectedly produced {error}"
6876            );
6877        }
6878        assert!(!core::session_transferable(&core::Value::Extension(
6879            core::ExtensionValue {
6880                provider: "socket".into(),
6881                type_name: "Socket".into(),
6882                handle: 1,
6883            }
6884        )));
6885    }
6886
6887    #[test]
6888    fn issue_134_retained_repl_state_survives_errors_and_multiline_forms() {
6889        if repo_text("specs/00-unsorted/platform-language/draft/conformance/modules.edn").is_none()
6890        {
6891            return;
6892        }
6893        assert_eq!(
6894            module_expect("repl/retained-state", "namespace-retained"),
6895            Form::Bool(true)
6896        );
6897        assert_eq!(
6898            module_expect("repl/retained-state", "multiline"),
6899            Form::Bool(true)
6900        );
6901        assert_eq!(
6902            module_expect("repl/error-recovery", "session-survives"),
6903            Form::Bool(true)
6904        );
6905        assert_eq!(
6906            module_expect("repl/error-recovery", "namespace-restored"),
6907            Form::Bool(true)
6908        );
6909
6910        let mut kernel = SessionKernel::new();
6911        kernel.create_session("repl").unwrap();
6912        assert_eq!(
6913            kernel
6914                .eval(
6915                    "repl",
6916                    "(ns retained.repl)\n(def answer\n  (+ 40\n     2))\nnil"
6917                )
6918                .unwrap(),
6919            "nil"
6920        );
6921        assert!(kernel.eval("repl", "missing-symbol").is_err());
6922        assert_eq!(kernel.session_namespace("repl").unwrap(), "retained.repl");
6923        assert_eq!(kernel.eval("repl", "answer").unwrap(), "42");
6924    }
6925
6926    #[test]
6927    fn issue_134_host_facades_are_loaded_session_local_and_non_transferable() {
6928        if repo_text("specs/00-unsorted/runtime/draft/host-runtime.edn").is_none() {
6929            return;
6930        }
6931        for id in [
6932            "host/type-identity",
6933            "host/session-local-facade",
6934            "host/namespace-loaded",
6935            "host/no-live-transfer",
6936            "host/rejected-ex-info",
6937        ] {
6938            assert!(!host_conformance_case(id).is_empty());
6939        }
6940
6941        let mut first = Runtime::new();
6942        let second = Runtime::new();
6943        assert_eq!(
6944            first
6945                .eval_text("(= Host std.native.Host std.foundation/Host)")
6946                .unwrap(),
6947            "true"
6948        );
6949        assert_eq!(
6950            first.eval_text("(ns-state 'std.native)").unwrap(),
6951            ":loaded"
6952        );
6953        assert_eq!(
6954            first.eval_text("(ns-state 'std.native.Host)").unwrap(),
6955            ":loaded"
6956        );
6957
6958        let first_host = first
6959            .namespace_registry
6960            .find("std.native")
6961            .unwrap()
6962            .resolve(&crate::lang::data::Symbol::parse("Host"))
6963            .unwrap()
6964            .deref_value();
6965        let second_host = second
6966            .namespace_registry
6967            .find("std.native")
6968            .unwrap()
6969            .resolve(&crate::lang::data::Symbol::parse("Host"))
6970            .unwrap()
6971            .deref_value();
6972        let (core::Value::NativeType(first_host), core::Value::NativeType(second_host)) =
6973            (first_host, second_host)
6974        else {
6975            panic!("Host must be a native façade descriptor")
6976        };
6977        assert!(!Rc::ptr_eq(&first_host, &second_host));
6978
6979        let mut kernel = SessionKernel::new();
6980        kernel.create_session("host-transfer").unwrap();
6981        let error = kernel.eval("host-transfer", "Host").unwrap_err();
6982        assert!(error.contains("SESSION_TRANSFER_REJECTED"), "{error}");
6983
6984        assert_eq!(
6985            first
6986                .eval_text(
6987                    "(try
6988                       (deref (Host/call \"missing\" \"missing\" []))
6989                       (catch error
6990                         [(ex-message error)
6991                          (get (ex-data error) :error/code)]))"
6992                )
6993                .unwrap(),
6994            "[\"Host capability provider is unavailable\" :host/unavailable]"
6995        );
6996        assert_eq!(
6997            first
6998                .eval_text(
6999                    "(deref
7000                       (promise/catch
7001                         (Host/call \"missing\" \"missing\" [])
7002                         (fn [error]
7003                           (get (ex-data error) :error/code))))"
7004                )
7005                .unwrap(),
7006            ":host/unavailable"
7007        );
7008        assert_eq!(
7009            kernel
7010                .eval(
7011                    "host-transfer",
7012                    "(try
7013                       (deref (Host/call \"missing\" \"missing\" []))
7014                       (catch error
7015                         (get (ex-data error) :error/code)))"
7016                )
7017                .unwrap(),
7018            ":host/unavailable"
7019        );
7020    }
7021
7022    #[test]
7023    fn throw_and_try_catch_finally_are_host_neutral() {
7024        let mut runtime = Runtime::new();
7025        assert_eq!(
7026            runtime
7027                .eval_text("(try (throw :failed) (catch error error))")
7028                .unwrap(),
7029            ":failed"
7030        );
7031        assert_eq!(runtime.eval_text("(try 42 (finally 0))").unwrap(), "42");
7032        assert_eq!(
7033            runtime
7034                .eval_text("(try (throw :failed) (catch error (str error :handled)))")
7035                .unwrap(),
7036            "\":failed:handled\""
7037        );
7038        assert!(runtime
7039            .eval_text("(throw :failed)")
7040            .unwrap_err()
7041            .contains("thrown: :failed"));
7042    }
7043
7044    #[test]
7045    fn def_binds_values_in_the_current_environment() {
7046        let mut runtime = Runtime::new();
7047        assert_eq!(
7048            runtime
7049                .eval_text("(do (def answer 41) (+ answer 1))")
7050                .unwrap(),
7051            "42"
7052        );
7053        assert_eq!(
7054            runtime
7055                .eval_text("(do (def answer 42) (deref (var answer)))")
7056                .unwrap(),
7057            "42"
7058        );
7059        assert!(runtime
7060            .eval_text("(deref 42)")
7061            .unwrap_err()
7062            .contains("deref expects a var"));
7063        assert_eq!(
7064            runtime
7065                .eval_text("(do (def answer 1) (def answer 42) answer)")
7066                .unwrap(),
7067            "42"
7068        );
7069        assert!(runtime
7070            .eval_text("(def 1 2)")
7071            .unwrap_err()
7072            .contains("def name must be a symbol"));
7073    }
7074
7075    #[test]
7076    fn vars_preserve_identity_and_support_root_mutation() {
7077        let mut runtime = Runtime::new();
7078        assert_eq!(
7079            runtime
7080                .eval_text("(do (def answer 1) (= (var answer) (var answer)))")
7081                .unwrap(),
7082            "true"
7083        );
7084        assert_eq!(
7085            runtime
7086                .eval_text("(do (def answer 1) (set! answer 42) (deref (var answer)))")
7087                .unwrap(),
7088            "42"
7089        );
7090        assert_eq!(
7091            runtime
7092                .eval_text(
7093                    "(do (def answer 1) (let (v (var answer)) (do (set! answer 7) (deref v))))"
7094                )
7095                .unwrap(),
7096            "7"
7097        );
7098        assert_eq!(runtime.eval_text("(do (def answer 1) (defn add [x y] (+ x y)) (alter-var-root (var answer) add 40) answer)").unwrap(), "41");
7099        assert_eq!(
7100            runtime.eval_text("(assoc [1 2 3] 0 :x)").unwrap(),
7101            "[:x 2 3]"
7102        );
7103        assert_eq!(
7104            runtime.eval_text("(assoc [1 2 3] 3 :x)").unwrap(),
7105            "[1 2 3 :x]"
7106        );
7107        assert_eq!(
7108            runtime.eval_text("(assoc [1 2 3] 5 :x)").unwrap_err(),
7109            "assoc index out of bounds"
7110        );
7111        assert_eq!(
7112            runtime.eval_text("(set! missing 1)").unwrap_err(),
7113            "unbound var: missing"
7114        );
7115    }
7116
7117    #[test]
7118    fn functions_capture_lexical_values_and_support_defn() {
7119        let mut runtime = Runtime::new();
7120        assert_eq!(runtime.eval_text("((fn [x] (+ x 1)) 41)").unwrap(), "42");
7121        assert_eq!(
7122            runtime
7123                .eval_text("(let (inc (fn [x] (+ x 1))) (inc 41))")
7124                .unwrap(),
7125            "42"
7126        );
7127        assert_eq!(
7128            runtime
7129                .eval_text("(do (defn add1 [x] (+ x 1)) (add1 41))")
7130                .unwrap(),
7131            "42"
7132        );
7133        assert_eq!(runtime.eval_text("(do (defn factorial [n] (if (<= n 1) 1 (* n (factorial (dec n))))) (factorial 5))").unwrap(), "120");
7134        assert_eq!(
7135            runtime
7136                .eval_text("(let (x 40) (let (f (fn [y] (+ x y))) (f 2)))")
7137                .unwrap(),
7138            "42"
7139        );
7140    }
7141
7142    #[test]
7143    fn quote_lists_and_do_match_core_shapes() {
7144        let mut runtime = Runtime::new();
7145        assert_eq!(runtime.eval_text("'(1 2)").unwrap(), "(1 2)");
7146        assert_eq!(runtime.eval_text("(count '(1 2 3))").unwrap(), "3");
7147        assert_eq!(runtime.eval_text("(nth (cons 0 '(1 2)) 0)").unwrap(), "0");
7148        assert_eq!(runtime.eval_text("(do 1 2 3)").unwrap(), "3");
7149    }
7150
7151    #[test]
7152    fn signed_32_bit_operations_match_core_contract() {
7153        let mut runtime = Runtime::new();
7154        assert_eq!(runtime.eval_text("(bit-and 6 3)").unwrap(), "2");
7155        assert_eq!(runtime.eval_text("(bit-or 1 2)").unwrap(), "3");
7156        assert_eq!(runtime.eval_text("(bit-xor 7 3)").unwrap(), "4");
7157        assert_eq!(runtime.eval_text("(bit-not 0)").unwrap(), "-1");
7158        assert_eq!(runtime.eval_text("(bit-shift-right -4 1)").unwrap(), "-2");
7159        assert_eq!(
7160            runtime.eval_text("(bit-shift-left 1 31)").unwrap(),
7161            "-2147483648"
7162        );
7163        assert!(runtime
7164            .eval_text("(bit-shift-left 1 -1)")
7165            .unwrap_err()
7166            .contains("distance must be in the range 0..31"));
7167    }
7168
7169    #[test]
7170    fn l0_numeric_and_truth_predicates_are_available() {
7171        let mut runtime = Runtime::new();
7172        assert_eq!(runtime.eval_text("(inc 41)").unwrap(), "42");
7173        assert_eq!(runtime.eval_text("(dec 43)").unwrap(), "42");
7174        assert_eq!(runtime.eval_text("(zero? 0)").unwrap(), "true");
7175        assert_eq!(runtime.eval_text("(pos? 1)").unwrap(), "true");
7176        assert_eq!(runtime.eval_text("(neg? -1)").unwrap(), "true");
7177        assert_eq!(runtime.eval_text("(even? 4)").unwrap(), "true");
7178        assert_eq!(runtime.eval_text("(odd? 3)").unwrap(), "true");
7179        assert_eq!(runtime.eval_text("(nil? nil)").unwrap(), "true");
7180        assert_eq!(runtime.eval_text("(true? true)").unwrap(), "true");
7181        assert_eq!(runtime.eval_text("(false? false)").unwrap(), "true");
7182    }
7183
7184    #[test]
7185    fn core_sequence_navigation_ranges_and_quantifiers() {
7186        let mut runtime = Runtime::new();
7187        assert_eq!(runtime.eval_text("(second [10 20 30])").unwrap(), "20");
7188        assert_eq!(runtime.eval_text("(not-empty [])").unwrap(), "nil");
7189        assert_eq!(runtime.eval_text("(not-empty [1])").unwrap(), "[1]");
7190        assert_eq!(runtime.eval_text("(range 3)").unwrap(), "<seq>");
7191        assert_eq!(
7192            runtime
7193                .eval_text("(vector? (map (fn [x] (+ x 1)) [1 2 3]))")
7194                .unwrap(),
7195            "true"
7196        );
7197        assert_eq!(
7198            runtime
7199                .eval_text("(first (map (fn [x] (+ x 1)) [1 2 3]))")
7200                .unwrap(),
7201            "2"
7202        );
7203        assert_eq!(runtime.eval_text("(count (range 2 5))").unwrap(), "3");
7204        assert_eq!(runtime.eval_text("(count (repeat 4 :x))").unwrap(), "4");
7205        assert_eq!(
7206            runtime
7207                .eval_text("(every? (fn [x] (pos? x)) [1 2 3])")
7208                .unwrap(),
7209            "true"
7210        );
7211        assert_eq!(
7212            runtime
7213                .eval_text("(any? (fn [x] (= x 2)) [1 2 3])")
7214                .unwrap(),
7215            "true"
7216        );
7217    }
7218
7219    #[test]
7220    fn map_and_zip_support_multiple_collections() {
7221        let mut runtime = Runtime::new();
7222        assert_eq!(
7223            runtime
7224                .eval_text("(nth (map (fn [x y] (+ x y)) [1 2] [10 20]) 1)")
7225                .unwrap(),
7226            "22"
7227        );
7228        assert_eq!(
7229            runtime
7230                .eval_text("(count (map (fn [x y z] (+ x (+ y z))) [1 2] [10 20] [100 200]))")
7231                .unwrap(),
7232            "2"
7233        );
7234        assert_eq!(
7235            runtime
7236                .eval_text("(nth (zip [1 2] [:a :b] [true false]) 0)")
7237                .unwrap(),
7238            "[1 :a true]"
7239        );
7240        assert_eq!(
7241            runtime.eval_text("(count (zip [1 2 3] [:a :b]))").unwrap(),
7242            "2"
7243        );
7244    }
7245
7246    #[test]
7247    fn lazy_iterator_generators_are_bounded_by_consumers() {
7248        let mut runtime = Runtime::new();
7249        assert_eq!(
7250            runtime.eval_text("(count ((take 4) (repeat :x)))").unwrap(),
7251            "4"
7252        );
7253        assert_eq!(
7254            runtime.eval_text("(first ((drop 3) (repeat :x)))").unwrap(),
7255            ":x"
7256        );
7257        assert_eq!(
7258            runtime
7259                .eval_text("(Iter/iter-finite? (repeat :x))")
7260                .unwrap(),
7261            "false"
7262        );
7263        assert_eq!(
7264            runtime
7265                .eval_text("(count ((take 3) (repeatedly (constantly 7))))")
7266                .unwrap(),
7267            "3"
7268        );
7269        assert_eq!(
7270            runtime
7271                .eval_text("(count ((take 5) (iterate (fn [x] (+ x 2)) 0)))")
7272                .unwrap(),
7273            "5"
7274        );
7275        assert_eq!(
7276            runtime
7277                .eval_text(
7278                    "(count ((take 3) ((take-while (fn [x] (< x 10))) (iterate (fn [x] (+ x 2)) 0))))"
7279                )
7280                .unwrap(),
7281            "3"
7282        );
7283        assert_eq!(
7284            runtime
7285                .eval_text(
7286                    "(first ((take 2) ((drop-while (fn [x] (< x 4))) (iterate (fn [x] (+ x 2)) 0))))"
7287                )
7288                .unwrap(),
7289            "4"
7290        );
7291        assert_eq!(
7292            runtime
7293                .eval_text(
7294                    "(nth ((take 4) ((map (fn [x] (* x 2))) (iterate (fn [x] (+ x 1)) 0))) 3)"
7295                )
7296                .unwrap(),
7297            "6"
7298        );
7299        assert_eq!(
7300            runtime
7301                .eval_text(
7302                    "(first ((take 2) ((filter (fn [x] (even? x))) (iterate (fn [x] (+ x 1)) 0))))"
7303                )
7304                .unwrap(),
7305            "0"
7306        );
7307        assert_eq!(
7308            runtime
7309                .eval_text(
7310                    "(nth ((take 4) ((mapcat (fn [x] [x x])) (iterate (fn [x] (+ x 1)) 0))) 3)"
7311                )
7312                .unwrap(),
7313            "1"
7314        );
7315        assert_eq!(runtime.eval_text("(first ((take 2) ((keep (fn [x] (if (even? x) (* x 10) nil))) (iterate (fn [x] (+ x 1)) 0))))").unwrap(), "0");
7316        assert_eq!(
7317            runtime
7318                .eval_text(
7319                    "(nth ((take 3) (Iter/iter-zip (iterate (fn [x] (+ x 1)) 0) (repeat :x))) 2)"
7320                )
7321                .unwrap(),
7322            "[2 :x]"
7323        );
7324        assert_eq!(
7325            runtime
7326                .eval_text("(nth ((take 4) (Iter/iter-interleave (iterate (fn [x] (+ x 1)) 0) (repeat :x))) 3)")
7327                .unwrap(),
7328            ":x"
7329        );
7330        assert_eq!(
7331            runtime
7332                .eval_text("(nth ((take 3) ((partition-all 2) (iterate (fn [x] (+ x 1)) 0))) 2)")
7333                .unwrap(),
7334            "[4 5]"
7335        );
7336        assert_eq!(
7337            runtime
7338                .eval_text("(nth ((take 2) ((partition 2) (iterate (fn [x] (+ x 1)) 0))) 1)")
7339                .unwrap(),
7340            "[2 3]"
7341        );
7342        assert_eq!(
7343            runtime
7344                .eval_text("(first ((take 4) (iterate (fn [x] (+ x 2)) 0)))")
7345                .unwrap(),
7346            "0"
7347        );
7348        assert_eq!(runtime.eval_text("(second (repeat :x))").unwrap(), ":x");
7349        assert_eq!(
7350            runtime
7351                .eval_text("(first (rest (iterate (fn [x] (+ x 1)) 0)))")
7352                .unwrap(),
7353            "1"
7354        );
7355        assert_eq!(
7356            runtime
7357                .eval_text("(nth (take 4 (iterate (fn [x] (+ x 2)) 0)) 3)")
7358                .unwrap(),
7359            "6"
7360        );
7361    }
7362
7363    #[test]
7364    fn function_combinators_capture_values_and_functions() {
7365        let mut runtime = Runtime::new();
7366        assert_eq!(runtime.eval_text("((constantly 42) 1 2 3)").unwrap(), "42");
7367        assert_eq!(
7368            runtime
7369                .eval_text("((complement (fn [x] (> x 2))) 1)")
7370                .unwrap(),
7371            "true"
7372        );
7373        assert_eq!(
7374            runtime
7375                .eval_text("((comp (fn [x] (+ x 1)) (fn [x] (* x 2))) 20)")
7376                .unwrap(),
7377            "41"
7378        );
7379        assert_eq!(
7380            runtime
7381                .eval_text("((comp (fn [x] (+ x 1)) (fn [x] (+ x 1)) (fn [x] (+ x 1))) 39)")
7382                .unwrap(),
7383            "42"
7384        );
7385        assert_eq!(
7386            runtime.eval_text("((comp inc inc inc inc) 38)").unwrap(),
7387            "42"
7388        );
7389    }
7390
7391    #[test]
7392    fn public_map_doto_and_set_helpers_are_portable() {
7393        let mut runtime = Runtime::new();
7394        assert_eq!(
7395            runtime
7396                .eval_text(
7397                    "[(map-keys (fn [x] (+ x 1)) {1 :a 2 :b}) \
7398                     (map-vals (fn [x] (+ x 1)) {:a 1 :b 2}) \
7399                     (let [calls (atom 0) \
7400                           value (doto \
7401                                   (do (swap! calls (fn [x] (+ x 1))) (atom [])) \
7402                                   (swap! (fn [values item] (conj values item)) 1) \
7403                                   (swap! (fn [values item] (conj values item)) 2))] \
7404                       [(deref calls) (deref value)])]"
7405                )
7406                .unwrap(),
7407            "[{2 :a 3 :b} {:a 2 :b 3} [1 [1 2]]]"
7408        );
7409        assert_eq!(
7410            runtime
7411                .eval_text(
7412                    "(do \
7413                       (require [std.foundation.set :as set]) \
7414                       [(set/union #{1 2} #{2 3}) \
7415                        (set/intersection #{1 2 3} #{2 3 4} #{3 5}) \
7416                        (set/difference #{1 2 3} #{2} #{3}) \
7417                        (set/subset? #{1 2} #{1 2 3}) \
7418                        (set/superset? #{1 2 3} #{1 2}) \
7419                        (set/select odd? #{1 2 3 4})])"
7420                )
7421                .unwrap(),
7422            "[#{1 2 3} #{3} #{1} true true #{1 3}]"
7423        );
7424    }
7425
7426    #[test]
7427    fn nested_associative_helpers_match_l0_shapes() {
7428        let mut runtime = Runtime::new();
7429        assert_eq!(
7430            runtime.eval_text("(get-in {:a {:b 42}} [:a :b])").unwrap(),
7431            "42"
7432        );
7433        assert_eq!(
7434            runtime
7435                .eval_text("(get-in (object :a (object :b 42)) [:a :b])")
7436                .unwrap(),
7437            "42"
7438        );
7439        assert_eq!(runtime.eval_text("(get (object :a 7) :a)").unwrap(), "7");
7440        assert_eq!(
7441            runtime
7442                .eval_text("(get-in {:a {:b 42}} [:a :missing])")
7443                .unwrap(),
7444            "nil"
7445        );
7446        assert_eq!(
7447            runtime
7448                .eval_text("(get-in (assoc-in {} [:a :b] 42) [:a :b])")
7449                .unwrap(),
7450            "42"
7451        );
7452        assert_eq!(runtime.eval_text("(get {:a 3} :a)").unwrap(), "3");
7453        assert_eq!(
7454            runtime
7455                .eval_text("(get (update {:a 3} :a (fn [x] (+ x 2))) :a)")
7456                .unwrap(),
7457            "5"
7458        );
7459        assert_eq!(
7460            runtime
7461                .eval_text("(get-in (update-in {:a {:b 3}} [:a :b] (fn [x y] (+ x y)) 4) [:a :b])")
7462                .unwrap(),
7463            "7"
7464        );
7465        assert_eq!(
7466            runtime.eval_text("(get (assoc {} :a 1 :b 2) :b)").unwrap(),
7467            "2"
7468        );
7469    }
7470
7471    #[test]
7472    fn opaque_extensions_use_compact_tagged_display() {
7473        let value = core::Value::Extension(core::ExtensionValue {
7474            provider: "math.tensor".into(),
7475            type_name: "tensor".into(),
7476            handle: 42,
7477        });
7478        assert_eq!(value.display(), "#ht[:handle 42]");
7479    }
7480    #[test]
7481    fn iterator_combinators_cover_core_shapes() {
7482        let mut runtime = Runtime::new();
7483        assert_eq!(
7484            runtime
7485                .eval_text("(count (take-while (fn [x] (< x 3)) (range 5)))")
7486                .unwrap(),
7487            "3"
7488        );
7489        assert_eq!(
7490            runtime
7491                .eval_text("(count (drop-while (fn [x] (< x 3)) (range 5)))")
7492                .unwrap(),
7493            "2"
7494        );
7495        assert_eq!(
7496            runtime
7497                .eval_text("(count (mapcat (fn [x] [x x]) [1 2]))")
7498                .unwrap(),
7499            "4"
7500        );
7501        assert_eq!(
7502            runtime
7503                .eval_text("(count (keep (fn [x] (if (even? x) (* x 10) nil)) [1 2 3 4]))")
7504                .unwrap(),
7505            "2"
7506        );
7507        assert_eq!(
7508            runtime
7509                .eval_text("(count (partition-all 2 [1 2 3]))")
7510                .unwrap(),
7511            "2"
7512        );
7513        assert_eq!(
7514            runtime.eval_text("(count (partition 2 [1 2 3]))").unwrap(),
7515            "1"
7516        );
7517        assert_eq!(
7518            runtime.eval_text("(count (interpose :x [1 2 3]))").unwrap(),
7519            "5"
7520        );
7521        assert_eq!(
7522            runtime
7523                .eval_text("(count (interleave [1 2] [:a :b]))")
7524                .unwrap(),
7525            "4"
7526        );
7527        assert_eq!(
7528            runtime
7529                .eval_text("(count (partition-pair [1 2 3]))")
7530                .unwrap(),
7531            "1"
7532        );
7533    }
7534
7535    #[test]
7536    fn arithmetic() {
7537        let mut runtime = Runtime::new();
7538        assert_eq!(runtime.eval_text("(+ 19 23)").unwrap(), "42");
7539    }
7540
7541    #[test]
7542    fn declare_noop() {
7543        let mut runtime = Runtime::new();
7544        assert_eq!(runtime.eval_text("(declare x)").unwrap(), "nil");
7545    }
7546
7547    #[test]
7548    fn recur_cannot_escape_loop_or_function_boundaries() {
7549        let mut runtime = Runtime::new();
7550        assert_eq!(
7551            runtime.eval_text("(recur 1)").unwrap_err(),
7552            "recur must be inside loop"
7553        );
7554        assert_eq!(
7555            runtime.eval_text("((fn [] (recur 1)))").unwrap_err(),
7556            "recur must be inside loop"
7557        );
7558    }
7559
7560    #[test]
7561    fn loop_supports_binding_vectors_and_multiple_recur_values() {
7562        let mut runtime = Runtime::new();
7563        assert_eq!(
7564            runtime
7565                .eval_text("(loop [x 0 y 1] (if (< x 4) (recur (+ x 1) (+ y x)) y))")
7566                .unwrap(),
7567            "7"
7568        );
7569        assert!(runtime
7570            .eval_text("(loop [x 0 y 1] (recur 2))")
7571            .unwrap_err()
7572            .contains("loop recur arity mismatch"));
7573    }
7574
7575    #[test]
7576    fn loop_and_recur_support_tail_recursive_bootstrap_forms() {
7577        let mut runtime = Runtime::new();
7578        assert_eq!(
7579            runtime
7580                .eval_text("(loop (x 0) (if (< x 5) (recur (+ x 1)) x))")
7581                .unwrap(),
7582            "5"
7583        );
7584        assert_eq!(
7585            runtime
7586                .eval_text("(loop (x 1) (do (if (< x 3) (recur (* x 2)) x)))")
7587                .unwrap(),
7588            "4"
7589        );
7590    }
7591
7592    #[test]
7593    fn let_accepts_binding_vectors_and_multiple_sequential_pairs() {
7594        let mut runtime = Runtime::new();
7595        assert_eq!(
7596            runtime.eval_text("(let [x 19 y 23] (+ x y))").unwrap(),
7597            "42"
7598        );
7599        assert_eq!(
7600            runtime.eval_text("(let (x 19 y (+ x 23)) y)").unwrap(),
7601            "42"
7602        );
7603        assert!(runtime
7604            .eval_text("(let [x 1 y] y)")
7605            .unwrap_err()
7606            .contains("name/value pairs"));
7607    }
7608
7609    #[test]
7610    fn letfn_supports_local_recursion_mutual_recursion_and_scope_restoration() {
7611        let mut runtime = Runtime::new();
7612        assert_eq!(
7613            runtime
7614                .eval_text(
7615                    "(letfn [(sum [n acc] (if (= n 0) acc (sum (- n 1) (+ acc n))))] (sum 5 0))",
7616                )
7617                .unwrap(),
7618            "15"
7619        );
7620        assert_eq!(
7621            runtime
7622                .eval_text(
7623                    "(letfn [(even-local? [n] (if (= n 0) true (odd-local? (- n 1)))) (odd-local? [n] (if (= n 0) false (even-local? (- n 1))))] [(even-local? 8) (odd-local? 7)])",
7624                )
7625                .unwrap(),
7626            "[true true]"
7627        );
7628        assert!(runtime.eval_text("even-local?").is_err());
7629        assert!(runtime
7630            .eval_text("(letfn [(f [x] x) (f [x] x)] (f 1))")
7631            .unwrap_err()
7632            .contains("Duplicate letfn name"));
7633    }
7634
7635    #[test]
7636    fn read_forms_uses_the_capability_gated_file_provider() {
7637        let mut runtime = Runtime::new();
7638        runtime.install_memory_file_provider("/typed");
7639        runtime
7640            .eval_text(
7641                "(deref (file/write \"/typed/sample.hal\" (bytes 40 110 115 32 116 121 112 101 100 46 115 97 109 112 108 101 41 10 40 100 101 102 32 118 97 108 117 101 32 52 50 41)))",
7642            )
7643            .unwrap();
7644        assert_eq!(
7645            runtime
7646                .eval_text("(count (read-forms \"/typed/sample.hal\"))")
7647                .unwrap(),
7648            "2"
7649        );
7650        assert!(runtime
7651            .eval_text("(read-forms \"typed/sample.clj\")")
7652            .unwrap_err()
7653            .contains(".hal or .hrl"));
7654    }
7655
7656    #[test]
7657    fn conditional_and_let() {
7658        let mut runtime = Runtime::new();
7659        // Var display is namespace-qualified, matching the JVM runtime
7660        // (issue #223).
7661        assert_eq!(
7662            runtime.eval_text("(defn rank [score] score)").unwrap(),
7663            "#'user/rank"
7664        );
7665        assert_eq!(
7666            runtime
7667                .eval_text("(let (x 19) (if true (+ x 23) 0))")
7668                .unwrap(),
7669            "42"
7670        );
7671        assert_eq!(
7672            runtime
7673                .eval_text("(cond false \"gold\" (>= 70 50) \"silver\" :else \"bronze\")")
7674                .unwrap(),
7675            "\"silver\""
7676        );
7677        assert_eq!(runtime.eval_text("(cond false 1)").unwrap(), "nil");
7678        assert!(runtime
7679            .eval_text("(cond true 1 false)")
7680            .unwrap_err()
7681            .contains("test/expression pairs"));
7682    }
7683
7684    #[test]
7685    fn lesson_definition_cases_run_from_the_l0_conformance_corpus() {
7686        fn entry<'a>(entries: &'a [(Form, Form)], key: &str) -> &'a Form {
7687            entries
7688                .iter()
7689                .find_map(|(candidate, value)| match candidate {
7690                    Form::Keyword(name) if name == key => Some(value),
7691                    _ => None,
7692                })
7693                .unwrap_or_else(|| panic!("missing :{key}"))
7694        }
7695
7696        let Some(corpus) = repo_text("docs/docs/reference/l0-conformance.edn") else {
7697            return;
7698        };
7699        let manifest = kernel::parse_forms(&corpus).unwrap().remove(0);
7700        let Form::Map(manifest) = manifest else {
7701            panic!("conformance corpus must be a map")
7702        };
7703        let Form::Vector(cases) = entry(&manifest, "cases") else {
7704            panic!("conformance :cases must be a vector")
7705        };
7706        let mut runtime = Runtime::new();
7707
7708        for id in ["compiler/defn-var", "runtime/cond-defined-function"] {
7709            let case = cases
7710                .iter()
7711                .find(|case| {
7712                    matches!(
7713                        case,
7714                        Form::Map(entries)
7715                            if matches!(entry(entries, "id"), Form::Keyword(name) if name == id)
7716                    )
7717                })
7718                .unwrap_or_else(|| panic!("missing conformance case :{id}"));
7719            let Form::Map(case) = case else {
7720                unreachable!()
7721            };
7722            let Form::String(source) = entry(case, "source") else {
7723                panic!(":{id} source must be a string")
7724            };
7725            let Form::Map(expect) = entry(case, "expect") else {
7726                panic!(":{id} expect must be a map")
7727            };
7728            let Form::String(expected) = entry(expect, "value") else {
7729                panic!(":{id} expected value must be a string")
7730            };
7731            let Form::Keyword(expected_type) = entry(expect, "type") else {
7732                panic!(":{id} expected type must be a keyword")
7733            };
7734            let expected = if expected_type == "string" {
7735                format!("{expected:?}")
7736            } else {
7737                expected.clone()
7738            };
7739            assert_eq!(runtime.eval_text(source).unwrap(), expected, ":{id}");
7740        }
7741    }
7742
7743    #[test]
7744    fn errors_are_stable() {
7745        let mut runtime = Runtime::new();
7746        assert_eq!(
7747            runtime.eval_text("unknown").unwrap_err(),
7748            "unbound symbol: unknown"
7749        );
7750    }
7751
7752    #[test]
7753    fn mutable_collections_build_in_place_and_freeze_once() {
7754        let mut runtime = Runtime::new();
7755        let source = "(let [m (to-mutable {})]
7756                        (do
7757                          (loop [i 0]
7758                            (if (< i 500)
7759                              (do (assoc m i (+ i 1)) (recur (+ i 1)))
7760                              nil))
7761                          (let [p (to-persistent m)]
7762                            (+ (count p) (get p 499)))))";
7763        assert_eq!(runtime.eval_text(source).unwrap(), "1000");
7764        assert_eq!(
7765            runtime
7766                .eval_text("(let [m (to-mutable {:a 1})] (do (assoc m :b 2) (get m :b)))")
7767                .unwrap(),
7768            "2"
7769        );
7770        assert!(runtime
7771            .eval_text("(let [m (to-mutable {}) p (to-persistent m)] (do p (assoc m :late 1)))")
7772            .unwrap_err()
7773            .contains("mutable collection used after to-persistent"));
7774    }
7775
7776    #[cfg(not(target_arch = "wasm32"))]
7777    #[test]
7778    fn native_embedding_can_receive_values_without_display_serialization() {
7779        let mut runtime = Runtime::new();
7780        let value = runtime
7781            .eval_native_value("(do (def answer 42) {:answer #'answer})")
7782            .unwrap();
7783        let entries = core::map_entries(&value).expect("expected map");
7784        assert!(entries.iter().any(|(key, value)| matches!(
7785            (key, value),
7786            (core::Value::Keyword(name), core::Value::Var(var))
7787                if name.as_str() == "answer" && var.deref_value() == core::Value::Number(42)
7788        )));
7789    }
7790
7791    #[cfg(not(target_arch = "wasm32"))]
7792    #[test]
7793    fn native_error_traces_are_opt_in_and_nested() {
7794        let mut runtime = Runtime::new();
7795        assert_eq!(runtime.eval_native("(+ 19 23)").unwrap(), "42");
7796        assert_eq!(
7797            runtime.eval_native("unknown").unwrap_err(),
7798            "unbound symbol: unknown"
7799        );
7800        let error = runtime
7801            .eval_native_traced("(do (defn inner [] (/ 1 0)) (defn outer [] (inner)) (outer))")
7802            .unwrap_err();
7803        assert!(error.contains("[hara stack]"));
7804        assert!(error.contains("at inner"));
7805        assert!(error.contains("at outer"));
7806        assert_eq!(error.matches("[hara stack]").count(), 1);
7807    }
7808    #[test]
7809    fn runtime_metadata_round_trips_through_protocols_and_reader_literals() {
7810        let mut runtime = Runtime::new();
7811        assert_eq!(
7812            runtime.eval_text("(ILookup/lookup (IObjType/meta (IObjType/with-meta [1] {:doc \"vector\"})) :doc)").unwrap(),
7813            "\"vector\""
7814        );
7815        assert_eq!(
7816            runtime
7817                .eval_text("(ILookup/lookup (IObjType/meta (quote ^{:doc \"quoted\"} [1])) :doc)")
7818                .unwrap(),
7819            "\"quoted\""
7820        );
7821    }
7822    #[test]
7823    fn typed_vars_preserve_definition_metadata_and_dynamic_binding_scope() {
7824        let mut runtime = Runtime::new();
7825        assert_eq!(runtime.eval_text("(do (def ^:dynamic *answer* 1) (binding [*answer* 42] (binding [*answer* 43] *answer*)))").unwrap(), "43");
7826        assert_eq!(runtime.eval_text("*answer*").unwrap(), "1");
7827        assert_eq!(
7828            runtime
7829                .eval_text("(ILookup/lookup (IObjType/meta (var *answer*)) :dynamic)")
7830                .unwrap(),
7831            "true"
7832        );
7833        assert_eq!(runtime.eval_text("(do (def ^{:doc \"answer doc\"} answer 42) (ILookup/lookup (IObjType/meta (var answer)) :doc))").unwrap(), "\"answer doc\"");
7834        assert!(runtime
7835            .eval_text("(do (def plain 1) (binding [plain 2] plain))")
7836            .unwrap_err()
7837            .contains("dynamic Var"));
7838        let err = runtime
7839            .eval_text("(do (def ^:dynamic *left* 1) (binding [*left* 2 plain 3] *left*))")
7840            .unwrap_err();
7841        eprintln!("ERROR: {err}");
7842        assert!(err.contains("dynamic Var") || err.contains("name must be"));
7843        assert_eq!(runtime.eval_text("*left*").unwrap(), "1");
7844    }
7845    #[test]
7846    fn coroutine_introspection_works_in_cli_path() {
7847        let mut runtime = Runtime::new();
7848        assert_eq!(
7849            runtime
7850                .eval_text(
7851                    "(std.foundation.coroutine/status (std.foundation.coroutine/create (fn [x] x)))"
7852                )
7853                .unwrap(),
7854            ":suspended"
7855        );
7856        assert_eq!(
7857            runtime.eval_text("(std.foundation.coroutine/coroutine? (std.foundation.coroutine/create (fn [] 1)))").unwrap(),
7858            "true"
7859        );
7860        assert_eq!(
7861            runtime
7862                .eval_text("(std.foundation.coroutine/coroutine? 42)")
7863                .unwrap(),
7864            "false"
7865        );
7866        let mut runtime = Runtime::new();
7867        assert_eq!(
7868            runtime.eval_text("(def c (std.foundation.coroutine/create (fn [] 1))) (std.foundation.coroutine/status (std.foundation.coroutine/close c))").unwrap(),
7869            ":dead"
7870        );
7871        assert!(runtime
7872            .eval_text("(std.foundation.coroutine/resume c)")
7873            .unwrap_err()
7874            .contains("cannot resume a dead coroutine"));
7875        assert!(runtime
7876            .eval_text("(std.foundation.coroutine/yield 1)")
7877            .unwrap_err()
7878            .contains("coroutine/yield used outside of a coroutine"));
7879        assert_eq!(
7880            runtime
7881                .eval_text("(std.foundation.coroutine/await (promise/run (fn [] 1)))")
7882                .unwrap(),
7883            "1"
7884        );
7885    }
7886    #[cfg(not(target_arch = "wasm32"))]
7887    #[test]
7888    fn coroutine_suspending_forms_error_in_traced_path() {
7889        let mut runtime = Runtime::new();
7890        assert!(runtime
7891            .eval_native_traced("(def c (std.foundation.coroutine/create (fn [] 1))) (std.foundation.coroutine/resume c)")
7892            .unwrap_err()
7893            .contains("fiber evaluator"));
7894        assert!(runtime
7895            .eval_native_traced("(std.foundation.coroutine/yield 1)")
7896            .unwrap_err()
7897            .contains("fiber evaluator"));
7898        assert!(runtime
7899            .eval_native_traced("(std.foundation.coroutine/await (promise (fn [] 1)))")
7900            .unwrap_err()
7901            .contains("fiber evaluator"));
7902    }
7903    #[test]
7904    fn fiber_cli_path_evaluates_coroutine_resume_and_yield() {
7905        let mut runtime = Runtime::new();
7906        runtime
7907            .eval_text("(require [std.foundation.coroutine :as c])")
7908            .unwrap();
7909        assert_eq!(
7910            runtime.eval_text("(do (def co (c/create (fn [x] (let [y (c/yield (* x 2))] (+ y 1))))) (c/resume co 21))").unwrap(),
7911            "42"
7912        );
7913        assert_eq!(runtime.eval_text("(c/resume co 20)").unwrap(), "21");
7914    }
7915    #[test]
7916    fn binding_forms_evaluate_multiple_body_expressions() {
7917        let mut runtime = Runtime::new();
7918        assert_eq!(
7919            runtime
7920                .eval_text("(let [a (array 1 2 3)] (. a (push-last 4)) (. a (get 3)))")
7921                .unwrap(),
7922            "4"
7923        );
7924        assert_eq!(
7925            runtime
7926                .eval_text("(loop [n 0] (+ n 1) (if (< n 2) (recur (+ n 1)) n))")
7927                .unwrap(),
7928            "2"
7929        );
7930    }
7931    #[test]
7932    fn fiber_cli_path_awaits_promise_inside_coroutine() {
7933        let mut runtime = Runtime::new();
7934        runtime
7935            .eval_text("(require [std.foundation.coroutine :as c])")
7936            .unwrap();
7937        assert_eq!(
7938            runtime
7939                .eval_text(
7940                    "(def co (c/create (fn [] (c/await (promise/run (fn [] 42)))))) (c/resume co)"
7941                )
7942                .unwrap(),
7943            "42"
7944        );
7945    }
7946    #[test]
7947    fn coroutine_namespace_can_be_required_and_aliased() {
7948        let mut runtime = Runtime::new();
7949        assert_eq!(
7950            runtime
7951                .eval_text("(require 'std.foundation.coroutine) :loaded")
7952                .unwrap(),
7953            ":loaded"
7954        );
7955        assert_eq!(
7956            runtime
7957                .eval_text("(coroutine/status (coroutine/create (fn [x] x)))")
7958                .unwrap(),
7959            ":suspended"
7960        );
7961        assert_eq!(
7962            runtime.eval_text("(require [std.foundation.coroutine :as co]) (co/coroutine? (co/create (fn [] 1)))").unwrap(),
7963            "true"
7964        );
7965    }
7966    #[test]
7967    fn coroutine_default_alias_is_co() {
7968        let mut runtime = Runtime::new();
7969        assert_eq!(
7970            runtime
7971                .eval_text("(require 'std.foundation.coroutine) (co/status (co/create (fn [] 1)))")
7972                .unwrap(),
7973            ":suspended"
7974        );
7975    }
7976    #[test]
7977    fn eval_halc_runs_encoded_library() {
7978        use crate::kernel::halc::encode_halc_module;
7979
7980        let source = "(ns demo)\n\
7981                      (def Address [:map [:street :str]])\n\
7982                      (def Customer [:map [:address #'Address]])\n\
7983                      (defn ^{:schema #'Customer} identity-customer [customer] customer)\n\
7984                      (identity-customer 42)";
7985        let forms = kernel::parse_forms(source).unwrap();
7986        let artifact = encode_halc_module("demo", "demo.hal", source, forms).unwrap();
7987        let mut runtime = Runtime::new();
7988        assert_eq!(runtime.eval_halc(&artifact).unwrap(), "42");
7989        assert!(runtime.halc_schema("demo/Address").is_some());
7990        assert!(runtime.halc_schema("demo/Customer").is_some());
7991        assert!(matches!(
7992            runtime.halc_function_type("demo/identity-customer"),
7993            Some(kernel::SchemaType::Map(fields)) if fields.len() == 1
7994        ));
7995        assert_eq!(
7996            runtime
7997                .halc_function_schema("demo/identity-customer")
7998                .unwrap()
7999                .to_string(),
8000            "(var demo/Customer)"
8001        );
8002    }
8003
8004    #[cfg(feature = "bytecode-vm")]
8005    #[test]
8006    fn halc_lowers_to_typed_bytecode_without_source_reconstruction() {
8007        use crate::kernel::halc::encode_halc_module;
8008
8009        let source = "(ns typed.demo)\n\
8010                      (def Customer [:map [:id :int]])\n\
8011                      (def IdentityCustomer [:fn [#'Customer] #'Customer])\n\
8012                      (defn ^{:schema #'IdentityCustomer} identity-customer [customer] customer)\n\
8013                      (identity-customer 42)";
8014        let halc = encode_halc_module(
8015            "typed.demo",
8016            "typed/demo.hal",
8017            source,
8018            kernel::parse_forms(source).unwrap(),
8019        )
8020        .unwrap();
8021        let mut runtime = Runtime::new();
8022        let bytecode = runtime.compile_halc_bytecode_artifact(&halc).unwrap();
8023        let program = vm::decode_program(&bytecode).unwrap();
8024        assert!(matches!(
8025            program.function_types.get("typed.demo/identity-customer"),
8026            Some(kernel::SchemaType::Reference(name)) if name == "typed.demo/IdentityCustomer"
8027        ));
8028        assert!(matches!(
8029            program.schema_types.get("typed.demo/IdentityCustomer"),
8030            Some(kernel::SchemaType::Function(arities)) if arities.len() == 1
8031        ));
8032        assert!(matches!(
8033            program
8034                .inferred_function_types
8035                .get("typed.demo/identity-customer"),
8036            Some(kernel::SchemaType::Function(arities))
8037                if *arities[0].output == kernel::SchemaType::Reference("typed.demo/Customer".into())
8038        ));
8039        let identity_prototype = program
8040            .functions
8041            .iter()
8042            .position(|prototype| prototype.name.as_deref() == Some("identity-customer"))
8043            .unwrap() as u16;
8044        assert!(matches!(
8045            program.function_schema(identity_prototype),
8046            Some(kernel::SchemaType::Function(arities)) if arities.len() == 1
8047        ));
8048        assert_eq!(runtime.eval_bytecode_artifact(&bytecode).unwrap(), "42");
8049        assert!(runtime
8050            .halc_inferred_function_type("typed.demo/identity-customer")
8051            .is_some());
8052
8053        let mismatch_source = "(ns typed.bad)\n\
8054                               (def Unary [:fn [:int] :int])\n\
8055                               (defn ^{:schema #'Unary} wrong [left right] left)";
8056        let mismatch_halc = encode_halc_module(
8057            "typed.bad",
8058            "typed/bad.hal",
8059            mismatch_source,
8060            kernel::parse_forms(mismatch_source).unwrap(),
8061        )
8062        .unwrap();
8063        assert!(runtime
8064            .compile_halc_bytecode_artifact(&mismatch_halc)
8065            .unwrap_err()
8066            .contains("function schema for wrong has no 2-argument arity"));
8067    }
8068
8069    #[cfg(feature = "bytecode-vm")]
8070    #[test]
8071    fn halc_bytecode_lowering_applies_namespace_requires_before_compilation() {
8072        use crate::kernel::halc::encode_halc_module;
8073
8074        let source = "(ns typed.consumer (:require [typed.dependency :refer [answer]]))\n\
8075                      (defn read-answer [] answer)\n\
8076                      (read-answer)";
8077        let halc = encode_halc_module(
8078            "typed.consumer",
8079            "typed/consumer.hal",
8080            source,
8081            kernel::parse_forms(source).unwrap(),
8082        )
8083        .unwrap();
8084        let mut runtime = Runtime::new();
8085        runtime.register_resource("typed.dependency", "(ns typed.dependency) (def answer 42)");
8086
8087        let bytecode = runtime.compile_halc_bytecode_artifact(&halc).unwrap();
8088        assert_eq!(runtime.eval_bytecode_artifact(&bytecode).unwrap(), "42");
8089    }
8090
8091    #[test]
8092    #[ignore = "requires a Truffle-compiled foundation HALC artifact"]
8093    fn truffle_compiled_foundation_halc_loads_with_foundation_semantics() {
8094        let artifact = std::env::var("HARA_TRUFFLE_FOUNDATION_HALC")
8095            .or_else(|_| std::env::var("HARA_TRUFFLE_FOUNDATION_HIR"))
8096            .expect("HARA_TRUFFLE_FOUNDATION_HALC must point to the compiled artifact");
8097        let bytes = std::fs::read(&artifact).expect("read Truffle-compiled foundation HALC");
8098        let mut runtime = Runtime::new();
8099
8100        assert_eq!(runtime.eval_halc(&bytes).unwrap(), "<fn>");
8101        assert_eq!(runtime.eval_native("((comp inc inc) 40)").unwrap(), "42");
8102    }
8103
8104    #[cfg(feature = "evaluation-journal")]
8105    #[test]
8106    fn evaluation_journal_uses_the_real_macro_and_invocation_paths() {
8107        let mut runtime = Runtime::new();
8108        let trace =
8109            runtime.eval_native_journal("(defn observed [x] x) (if-not false (observed 5))");
8110
8111        assert_eq!(trace.schema, crate::journal::SCHEMA);
8112        assert_eq!(trace.result.as_ref().unwrap().display, "5");
8113        assert!(trace.events.iter().any(|event| {
8114            event.kind == crate::journal::JournalEventKind::MacroExpand
8115                && event.function.as_deref() == Some("if-not")
8116        }));
8117        assert!(trace.events.iter().any(|event| {
8118            event.kind == crate::journal::JournalEventKind::OperationEnter
8119                && event.function.as_deref() == Some("observed")
8120                && event
8121                    .values
8122                    .first()
8123                    .is_some_and(|value| value.display == "5")
8124        }));
8125        assert!(trace.events.iter().any(|event| {
8126            event.kind == crate::journal::JournalEventKind::OperationReturn
8127                && event.function.as_deref() == Some("observed")
8128                && event
8129                    .values
8130                    .first()
8131                    .is_some_and(|value| value.display == "5")
8132        }));
8133    }
8134}