feat(wasm): C0/C1 browser Marqdo interpreter on wasm32

Feature-gate host/CLI deps for wasm-core, add run_source, and ship
crates/marqdo-wasm with a raw mq_run ABI plus examples/browser-hello.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-01 10:37:44 +08:00
1 parent f2fd4fb34e
commit a75b7a1c87
22 files changed
+904 -151

No files matched your search

+223 -51
View File
@@ -2,7 +2,11 @@
use std::collections::HashMap;
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
use crate::host::plugin;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -648,22 +652,52 @@ pub fn call_host(
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::JsonQuote => json::quote(require(bound, "text")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?, bound.get("headers")),
HostFn::HttpPost => net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpPostSse => net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
),
HostFn::HttpGet => {
#[cfg(feature = "net-host")]
{
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_get unavailable in browser wasm".into())
}
}
HostFn::HttpPost => {
#[cfg(feature = "net-host")]
{
net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post unavailable in browser wasm".into())
}
}
HostFn::HttpPostSse => {
#[cfg(feature = "net-host")]
{
net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post_sse unavailable in browser wasm".into())
}
}
HostFn::OpenAiSseParse => {
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
}
@@ -671,14 +705,24 @@ pub fn call_host(
crate::host::event_bus::publish(require(bound, "event")?);
Ok(Value::Bool(true))
}
HostFn::HttpRequest => net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpRequest => {
#[cfg(feature = "net-host")]
{
net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_request unavailable in browser wasm".into())
}
}
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
HostFn::EConst => math::e_const(),
@@ -756,33 +800,111 @@ pub fn call_host(
bound.get("path"),
bound.get("grid"),
),
HostFn::ForeignSetCmd => foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
),
HostFn::ForeignRun => foreign::run(ctx, require(bound, "code")?, bound.get("stdin")),
HostFn::ForeignRunLang => foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
),
HostFn::ForeignLangs => foreign::langs(ctx),
HostFn::PluginLoad => plugin::load(ctx, require(bound, "path")?),
HostFn::PluginUnload => plugin::unload(ctx),
HostFn::PluginList => plugin::list(ctx),
HostFn::ForeignSetCmd => {
#[cfg(feature = "exec-host")]
{
foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRun => {
#[cfg(feature = "exec-host")]
{
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRunLang => {
#[cfg(feature = "exec-host")]
{
foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignLangs => {
#[cfg(feature = "exec-host")]
{
foreign::langs(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::PluginLoad => {
#[cfg(feature = "plugin-host")]
{
plugin::load(ctx, require(bound, "path")?)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = (ctx, bound);
Err("plugin.load unavailable in browser wasm".into())
}
}
HostFn::PluginUnload => {
#[cfg(feature = "plugin-host")]
{
plugin::unload(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Err("plugin.unload unavailable in browser wasm".into())
}
}
HostFn::PluginList => {
#[cfg(feature = "plugin-host")]
{
plugin::list(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::ExtNativePath => {
let name = require(bound, "name")?;
let s = match name {
Value::Text(t) => t.as_str(),
_ => return Err("name must be text".into()),
};
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
#[cfg(feature = "cli")]
{
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
}
#[cfg(not(feature = "cli"))]
{
let _ = s;
Ok(Value::None)
}
}
HostFn::MapSet => {
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
@@ -899,11 +1021,61 @@ pub fn call_host(
bound.get("line"),
)
}
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
HostFn::SubtaskSpawn => {
#[cfg(feature = "exec-host")]
{
subtask::spawn(ctx, bound)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskPoll => {
#[cfg(feature = "exec-host")]
{
subtask::poll(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskJoin => {
#[cfg(feature = "exec-host")]
{
subtask::join(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskKill => {
#[cfg(feature = "exec-host")]
{
subtask::kill(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskWaitAll => {
#[cfg(feature = "exec-host")]
{
subtask::wait_all(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Err("subtask unavailable in browser wasm".into())
}
}
}
}
+10
View File
@@ -8,12 +8,21 @@ pub mod agent_rt;
pub mod collection;
mod dispatch;
pub mod event_bus;
#[cfg(feature = "exec-host")]
pub mod foreign;
mod fs;
pub(crate) mod json;
pub mod math;
mod net;
#[cfg(feature = "plugin-host")]
pub mod plugin;
#[cfg(not(feature = "plugin-host"))]
#[path = "plugin_stub.rs"]
pub mod plugin;
#[cfg(feature = "exec-host")]
pub mod subtask;
#[cfg(not(feature = "exec-host"))]
#[path = "subtask_stub.rs"]
pub mod subtask;
mod sys;
mod time;
@@ -80,6 +89,7 @@ pub struct HostContext {
/// Entry-file line of each active user call (for writeback anchoring).
pub call_site_lines: Vec<u32>,
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
pub subtask_seq: u64,
}
+14 -2
View File
@@ -1,10 +1,14 @@
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::{BufRead, BufReader, Write};
use std::io::Write;
#[cfg(feature = "net-host")]
use std::io::{BufRead, BufReader};
#[cfg(feature = "net-host")]
use std::time::Duration;
use crate::host::HostContext;
use crate::value::Value;
#[cfg(feature = "net-host")]
use crate::host::HostContext;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
@@ -13,6 +17,7 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
}
}
#[cfg(feature = "net-host")]
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
let Some(h) = headers else {
return Ok(Vec::new());
@@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
}
}
#[cfg(feature = "net-host")]
fn http_exchange(
method: &str,
url: &str,
@@ -84,6 +90,7 @@ fn http_exchange(
}
}
#[cfg(feature = "net-host")]
fn response_map(status: u16, body: String) -> Value {
Value::Map(vec![
("status".into(), Value::Int(status as i64)),
@@ -91,6 +98,7 @@ fn response_map(status: u16, body: String) -> Value {
])
}
#[cfg(feature = "net-host")]
pub fn http_get(
ctx: &HostContext,
url: &Value,
@@ -105,6 +113,7 @@ pub fn http_get(
Ok(response_map(status, body))
}
#[cfg(feature = "net-host")]
pub fn http_post(
ctx: &HostContext,
url: &Value,
@@ -127,6 +136,7 @@ pub fn http_post(
}
/// Generic request: method + url + optional body / content_type / headers.
#[cfg(feature = "net-host")]
pub fn http_request(
ctx: &HostContext,
method: &Value,
@@ -630,6 +640,7 @@ pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result<Value, Str
Ok(Value::List(openai_chat_sse_events(text, echo)?))
}
#[cfg(feature = "net-host")]
fn read_sse_body_to_events<R: BufRead>(
mut reader: R,
echo: bool,
@@ -755,6 +766,7 @@ fn read_sse_body_to_events<R: BufRead>(
}
/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps.
#[cfg(feature = "net-host")]
pub fn http_post_sse(
ctx: &HostContext,
url: &Value,
+57
View File
@@ -0,0 +1,57 @@
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
use std::collections::HashMap;
use crate::host::HostContext;
use crate::value::Value;
pub const ABI_VERSION: u32 = 2;
pub const ABI_VERSION_MIN: u32 = 1;
/// Hook: resolve bare `lib.member` (unused without native plugins).
pub struct LibPathCall {
pub call: fn(*mut (), &str) -> Result<Value, String>,
pub data: *mut (),
}
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
body()
}
#[derive(Clone)]
pub struct RegisteredFn {
pub params: Vec<String>,
}
#[derive(Debug, Default, Clone)]
pub struct PluginState;
impl PluginState {
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
None
}
pub fn list_names(&self) -> Vec<String> {
Vec::new()
}
}
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
Err("plugin.load unavailable in browser wasm".into())
}
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
Err("plugin.unload unavailable in browser wasm".into())
}
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(Vec::new()))
}
pub fn call_registered(
_ctx: &mut HostContext,
name: &str,
_bound: &HashMap<String, Value>,
) -> Result<Value, String> {
Err(format!("plugin `{name}` unavailable in browser wasm"))
}
+9
View File
@@ -0,0 +1,9 @@
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
use crate::host::HostContext;
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
#[derive(Debug)]
pub(crate) struct Handle;
pub fn kill_all(_ctx: &mut HostContext) {}
+17 -1
View File
@@ -1,5 +1,6 @@
//! System / process host primitives.
#[cfg(feature = "exec-host")]
use std::process::Command;
use crate::host::HostContext;
@@ -97,10 +98,24 @@ pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
if ctx.soft_side_effects {
return Err(format!("exit {c} (soft mode does not terminate process)"));
}
std::process::exit(c as i32);
#[cfg(target_arch = "wasm32")]
{
return Err(format!("exit {c} unavailable in browser wasm"));
}
#[cfg(not(target_arch = "wasm32"))]
{
std::process::exit(c as i32);
}
}
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, cmd, args);
return Err("exec unavailable in browser wasm".into());
}
#[cfg(feature = "exec-host")]
{
if !ctx.allow_exec() {
return Err("exec denied by host policy".into());
}
@@ -123,6 +138,7 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
.status()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
}
#[cfg(test)]
+37 -13
View File
@@ -1,7 +1,8 @@
//! Time host primitives.
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{SystemTime, UNIX_EPOCH};
use chrono::{DateTime, NaiveDateTime, Utc};
@@ -9,19 +10,34 @@ use crate::host::HostContext;
use crate::value::Value;
pub fn now_unix() -> Result<Value, String> {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
#[cfg(target_arch = "wasm32")]
{
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
}
}
pub fn now_ms() -> Result<Value, String> {
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
#[cfg(target_arch = "wasm32")]
{
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
}
}
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
@@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
}
}
if n > 0 {
thread::sleep(Duration::from_millis(n));
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::sleep(Duration::from_millis(n));
}
#[cfg(target_arch = "wasm32")]
{
let _ = Duration::from_millis(n);
// Browser wasm has no blocking sleep; ignore (C0/C1).
}
}
Ok(Value::None)
}
+11 -8
View File
@@ -3,7 +3,9 @@
use std::collections::VecDeque;
use std::fs;
use std::io::{self, BufRead, Read, Write};
use std::io::{self, BufRead, Write};
#[cfg(all(unix, feature = "tty"))]
use std::io::Read;
use std::path::Path;
use anyhow::{Context, Result};
@@ -146,11 +148,11 @@ fn strip_block_indent(line: &str) -> String {
}
pub fn stdin_is_tty() -> bool {
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
{
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
#[cfg(not(unix))]
#[cfg(not(all(unix, feature = "tty")))]
{
false
}
@@ -181,13 +183,13 @@ fn normalize_prompt(prompt: &str) -> String {
}
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
struct TermGuard {
fd: i32,
original: libc::termios,
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
impl TermGuard {
fn enter_cbreak() -> Result<Self> {
let fd = libc::STDIN_FILENO;
@@ -206,7 +208,7 @@ impl TermGuard {
}
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
impl Drop for TermGuard {
fn drop(&mut self) {
unsafe {
@@ -215,6 +217,7 @@ impl Drop for TermGuard {
}
}
#[cfg(all(unix, feature = "tty"))]
fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
let mut out = io::stdout().lock();
// CR + clear whole line, then reprint (fixes CJK backspace display desync).
@@ -224,7 +227,7 @@ fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
}
/// Interactive line editor: UTF-8 char backspace + full-line redraw.
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
let _guard = TermGuard::enter_cbreak()?;
@@ -290,7 +293,7 @@ fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
}
}
#[cfg(not(unix))]
#[cfg(not(all(unix, feature = "tty")))]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
print!("{prompt}");
+73 -1
View File
@@ -8,10 +8,12 @@ pub mod ast;
pub mod builtin;
pub mod bytecode;
pub mod capture;
#[cfg(feature = "cli")]
pub mod catalog;
pub mod debug;
pub mod diagnostics;
pub mod embedded_lib;
#[cfg(feature = "cli")]
pub mod ext_cli;
pub mod foreign;
pub mod formula;
@@ -23,7 +25,9 @@ pub mod lex;
pub mod load;
pub mod parse;
pub mod value;
#[cfg(feature = "net-host")]
pub mod version_check;
#[cfg(feature = "view")]
pub mod view;
use std::path::Path;
@@ -36,7 +40,7 @@ use crate::bytecode::{compile_module, Vm};
use crate::capture::RunCapture;
use crate::interp::Interpreter;
use crate::lex::{classify_source, format_lines_dump};
use crate::load::load_module;
use crate::load::{load_module, load_module_from_source};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Backend {
@@ -293,3 +297,71 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
}
}
}
/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only.
pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
if source.trim().is_empty() {
bail!("source is empty");
}
let stdin_lines = crate::input_feed::effective_stdin(source, &opts.stdin_lines);
let module = load_module_from_source(source)?;
match opts.backend {
Backend::Tree => {
let mut host = HostContext::for_capture(None, opts.host_caps());
host.set_entry_source(None, source);
host.argv = opts.argv.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
}
let mut interp = Interpreter::with_capture(None, false)
.with_stdin(stdin_lines)
.with_host(host);
let value = interp.run_module(&module)?;
let plots = interp.take_plots();
Ok(RunCapture {
stdout: interp.captured_stdout,
value,
plots,
bindings: interp.entry_bindings,
})
}
Backend::Bytecode => {
let program = compile_module(None, &module)?;
let mut host = HostContext::for_capture(None, opts.host_caps());
host.set_entry_source(None, source);
host.argv = opts.argv.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
}
let mut vm = Vm::with_capture(None)
.with_stdin(stdin_lines)
.with_host(host);
let value = vm.run(&program)?;
let plots = vm.take_plots();
Ok(RunCapture {
stdout: vm.captured_stdout,
value,
plots,
bindings: Default::default(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_source_hello() {
let cap = run_source("# main\n\n> print text=Hello World!\n", &RunOptions::default())
.expect("run_source");
assert_eq!(cap.stdout, "Hello World!\n");
}
}
+57 -8
View File
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use crate::ast::{Function, Module};
use crate::ast::Module;
use crate::diagnostics::Diagnostic;
use crate::embedded_lib;
use crate::parse::parse_source;
@@ -212,14 +212,63 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
}
}
/// Kept for tests / tooling that expect a flat list (local tops only).
#[allow(dead_code)]
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
*existing = fun;
} else {
into.push(fun);
/// Load a module from source text. Imports may only resolve to the embedded
/// `lib/…` stdlib (no filesystem / `ext/` for this MVP path).
pub fn load_module_from_source(source: &str) -> Result<Module> {
let mut visited = HashSet::new();
load_module_from_source_inner(source, "<memory>", &mut visited)
}
fn load_module_from_source_inner(
source: &str,
label: &str,
visited: &mut HashSet<PathBuf>,
) -> Result<Module> {
let key = PathBuf::from(label);
if !visited.insert(key.clone()) {
bail!("circular import involving {label}");
}
let result = (|| {
let mut module = parse_source(source).map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
let imports = module.imports.clone();
let mut import_modules = HashMap::new();
for imp in imports {
let dep = load_embedded_import(&imp.path, visited)?;
if import_modules.contains_key(&imp.bind) {
bail!("duplicate import bind `{}` while loading {label}", imp.bind);
}
import_modules.insert(imp.bind, dep);
}
module.import_modules = import_modules;
crate::inherit::validate_inheritance(&module)
.map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
Ok(module)
})();
visited.remove(&key);
result
}
fn load_embedded_import(rel: &str, visited: &mut HashSet<PathBuf>) -> Result<Module> {
let rel = rel.replace('\\', "/");
let rest = if let Some(r) = rel.strip_prefix("lib/") {
r.to_string()
} else if let Some(r) = rel.strip_prefix("std/") {
r.to_string()
} else if embedded_lib::read_file(&rel).is_some() {
rel.clone()
} else {
bail!(
"import `{rel}` is not an embedded lib/ path — \
run_source only resolves embedded stdlib (lib/…); filesystem and ext/ imports are unsupported"
);
};
let Some(dep_source) = embedded_lib::read_file(&rest) else {
bail!("embedded lib not found: lib/{rest}");
};
let label = format!("lib/{rest}");
load_module_from_source_inner(&dep_source, &label, visited)
}
#[cfg(test)]