Add object primitives, official ext/llm, and HTTPS/dotenv platform.

Introduce # objects with ## methods (handles + ` x.method `), ship OpenAI-compatible ext/llm, and upgrade net/sys for HTTPS headers and dotenv loading.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-06 11:53:14 +08:00
1 parent b974f10c6e
commit b00b018056
55 files changed
+1741 -291

No files matched your search

+14 -3
View File
@@ -13,6 +13,7 @@ pub struct Module {
#[derive(Debug, Clone)]
pub struct Function {
pub name: String,
/// Heading depth 1–6. Level 1 = object/type; level ≥ 2 = function/method.
pub level: u8,
pub span: Span,
pub params: Vec<String>,
@@ -20,6 +21,13 @@ pub struct Function {
pub children: Vec<Function>,
}
impl Function {
/// `# Name` — object / type (constructor body).
pub fn is_object(&self) -> bool {
self.level == 1
}
}
#[derive(Debug, Clone)]
pub enum Stmt {
Assign {
@@ -64,6 +72,8 @@ pub struct BranchArm {
#[derive(Debug, Clone)]
pub struct CallExpr {
pub callee: String,
/// When set, `` `recv`.callee `` method call; receiver is a variable name.
pub receiver: Option<String>,
pub args: Vec<Arg>,
}
@@ -148,8 +158,9 @@ pub fn format_ast_dump(path: &str, module: &Module) -> String {
fn dump_fun(out: &mut String, fun: &Function, depth: usize) {
let pad = " ".repeat(depth);
let kind = if fun.is_object() { "object" } else { "fun" };
out.push_str(&format!(
"{pad}(fun level={} {:?} params={:?} @{}\n",
"{pad}({kind} level={} {:?} params={:?} @{}\n",
fun.level, fun.name, fun.params, fun.span
));
for stmt in &fun.body {
@@ -179,8 +190,8 @@ fn dump_stmt(out: &mut String, stmt: &Stmt, depth: usize) {
}
Stmt::Call { call, span } => {
out.push_str(&format!(
"{pad}(call {:?} {:?} @{span})\n",
call.callee, call.args
"{pad}(call recv={:?} {:?} {:?} @{span}\n",
call.receiver, call.callee, call.args
));
}
Stmt::Branch { arms, span } => {
+113 -4
View File
@@ -13,6 +13,7 @@ use crate::value::Value;
struct FlatFun {
name: String,
level: u8,
parent: Option<usize>,
params: Vec<String>,
body: Vec<Stmt>,
@@ -33,10 +34,30 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
.iter()
.position(|f| f.name == "main" && f.parent.is_none())
.or_else(|| {
flat.iter()
.position(|f| f.parent.is_none() && f.params.is_empty())
let tops: Vec<usize> = flat
.iter()
.enumerate()
.filter(|(_, f)| f.parent.is_none() && f.level == 1 && f.params.is_empty())
.map(|(i, _)| i)
.collect();
if tops.len() == 1 {
Some(tops[0])
} else {
None
}
})
.ok_or_else(|| anyhow::anyhow!("bytecode: no entry function"))?;
.ok_or_else(|| anyhow::anyhow!("bytecode: no `# main` object"))?;
let mut objects = Vec::new();
let mut methods = Vec::new();
for (i, f) in flat.iter().enumerate() {
if f.parent.is_none() && f.level == 1 {
objects.push((f.name.clone(), i));
for &cid in &f.children {
methods.push((i, flat[cid].name.clone(), cid));
}
}
}
let path_buf = path.map(|p| p.to_path_buf());
let mut functions = Vec::new();
@@ -44,13 +65,19 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
functions.push(compile_function(i, &flat, path_buf.as_deref())?);
}
Ok(Program { functions, entry })
Ok(Program {
functions,
entry,
objects,
methods,
})
}
fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -> usize {
let id = flat.len();
flat.push(FlatFun {
name: fun.name.clone(),
level: fun.level,
parent,
params: fun.params.clone(),
body: fun.body.clone(),
@@ -80,6 +107,18 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu
for (i, p) in fun.params.iter().enumerate() {
locals.insert(p.clone(), i as u8);
}
let is_method = fun
.parent
.map(|pid| flat[pid].level == 1 && flat[pid].parent.is_none())
.unwrap_or(false);
if is_method {
for name in ["自", "self"] {
if !locals.contains_key(name) {
let s = locals.len() as u8;
locals.insert(name.to_string(), s);
}
}
}
let mut c = FnCompiler {
path,
flat,
@@ -324,6 +363,10 @@ impl<'a> FnCompiler<'a> {
call.callee =
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
if let Some(recv) = &call.receiver {
return self.compile_method_call(recv, &call, as_stmt);
}
match call.callee.as_str() {
"print" => {
let text_expr = call
@@ -499,6 +542,72 @@ impl<'a> FnCompiler<'a> {
)));
}
self.emit(Op::Call(fid as u16, params.len() as u8));
if self.flat[fid].parent.is_none() && self.flat[fid].level == 1 {
let ti = self.add_const(Value::Text(self.flat[fid].name.clone()));
self.emit(Op::TagInstance(ti));
}
if as_stmt {
self.emit(Op::Pop);
}
Ok(())
}
fn compile_method_call(&mut self, recv: &str, call: &CallExpr, as_stmt: bool) -> Result<()> {
// Resolve method among all object children by name (unique enough for compile);
// runtime still checks `_type`.
let mut method_fid = None;
for f in self.flat {
if f.parent.is_none() && f.level == 1 {
for &cid in &f.children {
if self.flat[cid].name == call.callee {
method_fid = Some(cid);
break;
}
}
}
if method_fid.is_some() {
break;
}
}
let fid = method_fid.ok_or_else(|| {
self.err(format!("unknown method `{}`", call.callee))
})?;
let params = self.flat[fid].params.clone();
let mut named: HashMap<String, &Expr> = HashMap::new();
let mut positionals = Vec::new();
for a in &call.args {
match a {
Arg::Positional(e) => positionals.push(e),
Arg::Named { name, value } => {
named.insert(name.clone(), value);
}
}
}
let mut pos_i = 0;
for p in &params {
if let Some(e) = named.get(p) {
self.compile_expr(e)?;
} else if pos_i < positionals.len() {
self.compile_expr(positionals[pos_i])?;
pos_i += 1;
} else {
return Err(self.err(format!("missing argument for parameter `{p}`")));
}
}
if pos_i < positionals.len() {
return Err(self.err(format!(
"too many positional arguments ({} extra)",
positionals.len() - pos_i
)));
}
let slot = self
.locals
.get(recv)
.copied()
.ok_or_else(|| self.err(format!("undefined variable `{recv}`")))?;
self.emit(Op::GetLocal(slot));
let name_i = self.add_const(Value::Text(call.callee.clone()));
self.emit(Op::MethodCall(name_i, params.len() as u8));
if as_stmt {
self.emit(Op::Pop);
}
+9
View File
@@ -54,6 +54,11 @@ pub enum Op {
GetIndex,
/// Call function by index; argc values are on the stack (param order).
Call(u16, u8),
/// After a constructor Call: tag top-of-stack map with `_type` = constants[idx].
TagInstance(u16),
/// Method call: stack has argc args (param order) then receiver on top.
/// constants[name_idx] is method name text; resolve via receiver `_type`.
MethodCall(u16, u8),
/// Host primitive: pop `argc` args (param order), push result.
HostCall(u16, u8),
Return,
@@ -75,6 +80,10 @@ pub struct FnChunk {
pub struct Program {
pub functions: Vec<FnChunk>,
pub entry: usize,
/// Top-level object name → function index (level-1).
pub objects: Vec<(String, usize)>,
/// (object_fn_idx, method_name) → method fn idx
pub methods: Vec<(usize, String, usize)>,
}
impl Program {
+93
View File
@@ -336,6 +336,69 @@ impl Vm {
slots,
});
}
Op::TagInstance(idx) => {
let type_name = match fun.constants.get(idx as usize) {
Some(Value::Text(s)) => s.clone(),
_ => {
return Err(self.err_at(span, "TagInstance needs type name constant"));
}
};
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
stack.push(tag_instance_value(&type_name, v));
}
Op::MethodCall(name_idx, argc) => {
let argc = argc as usize;
let method_name = match fun.constants.get(name_idx as usize) {
Some(Value::Text(s)) => s.clone(),
_ => {
return Err(self.err_at(span, "MethodCall needs method name constant"));
}
};
let recv = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let mut vals = Vec::with_capacity(argc);
for _ in 0..argc {
vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?);
}
vals.reverse();
let type_name = instance_type_name_bc(&recv).map_err(|m| self.err_at(span, m))?;
let obj_idx = program
.objects
.iter()
.find(|(n, _)| n == &type_name)
.map(|(_, i)| *i)
.ok_or_else(|| {
self.err_at(span, format!("unknown object type `{type_name}`"))
})?;
let method_fid = program
.methods
.iter()
.find(|(o, m, _)| *o == obj_idx && m == &method_name)
.map(|(_, _, i)| *i)
.ok_or_else(|| {
self.err_at(
span,
format!("unknown method `{type_name}.{method_name}`"),
)
})?;
let callee = &program.functions[method_fid];
if callee.params.len() != argc {
return Err(self.err_at(span, "method argument count mismatch"));
}
let mut slots = vec![Value::None; callee.locals.len().max(1)];
for (i, v) in vals.into_iter().enumerate() {
slots[i] = v;
}
for (i, name) in callee.locals.iter().enumerate() {
if name == "自" || name == "self" {
slots[i] = recv.clone();
}
}
frames.push(Frame {
fn_idx: method_fid,
ip: 0,
slots,
});
}
Op::Return => {
let ret = pop(&mut stack).unwrap_or(Value::None);
frames.pop();
@@ -397,3 +460,33 @@ fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Res
stack.push(Value::Bool(pred(ord)));
Ok(())
}
fn instance_type_name_bc(v: &Value) -> Result<String, String> {
match v {
Value::Map(entries) => entries
.iter()
.find(|(k, _)| k == "_type")
.and_then(|(_, v)| match v {
Value::Text(s) => Some(s.clone()),
_ => None,
})
.ok_or_else(|| "method receiver needs a map with `_type`".into()),
_ => Err("method receiver must be an object map".into()),
}
}
fn tag_instance_value(type_name: &str, value: Value) -> Value {
match value {
Value::Map(mut entries) => {
if !entries.iter().any(|(k, _)| k == "_type") {
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
}
Value::Map(entries)
}
Value::None => Value::Map(vec![("_type".into(), Value::Text(type_name.into()))]),
other => Value::Map(vec![
("_type".into(), Value::Text(type_name.into())),
("value".into(), other),
]),
}
}
+34 -5
View File
@@ -74,6 +74,9 @@ pub enum HostFn {
ForeignRun = 63,
ForeignRunLang = 64,
ForeignLangs = 65,
DotenvLoad = 66,
HttpRequest = 67,
JsonQuote = 68,
}
impl HostFn {
@@ -144,6 +147,9 @@ impl HostFn {
63 => Self::ForeignRun,
64 => Self::ForeignRunLang,
65 => Self::ForeignLangs,
66 => Self::DotenvLoad,
67 => Self::HttpRequest,
68 => Self::JsonQuote,
_ => return None,
})
}
@@ -172,8 +178,9 @@ impl HostFn {
"host_json_stringify" => Self::JsonStringify,
"host_json_get" => Self::JsonGet,
"host_json_keys" => Self::JsonKeys,
"host_http_get" => Self::HttpGet,
"host_http_post" => Self::HttpPost,
// Aliases so optional `headers` / `content_type` bind like plot.
"host_http_get" | "http_get" => Self::HttpGet,
"host_http_post" | "http_post" => Self::HttpPost,
"host_url_encode" => Self::UrlEncode,
"host_pi" => Self::Pi,
"host_e" => Self::EConst,
@@ -217,6 +224,9 @@ impl HostFn {
"host_foreign_run" => Self::ForeignRun,
"host_foreign_run_lang" => Self::ForeignRunLang,
"host_foreign_langs" => Self::ForeignLangs,
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
"host_http_request" | "http_request" => Self::HttpRequest,
"host_json_quote" | "quote" => Self::JsonQuote,
_ => return None,
})
}
@@ -292,6 +302,9 @@ impl HostFn {
Self::ForeignRun => "host_foreign_run",
Self::ForeignRunLang => "host_foreign_run_lang",
Self::ForeignLangs => "host_foreign_langs",
Self::DotenvLoad => "host_dotenv_load",
Self::HttpRequest => "host_http_request",
Self::JsonQuote => "host_json_quote",
}
}
@@ -309,11 +322,13 @@ impl HostFn {
Self::EnvSet => &["name", "value"],
Self::Exit => &["code"],
Self::Exec => &["cmd"],
Self::JsonParse | Self::UrlEncode => &["text"],
Self::JsonParse | Self::UrlEncode | Self::JsonQuote => &["text"],
Self::JsonStringify | Self::JsonKeys => &["value"],
Self::JsonGet => &["value", "key"],
Self::HttpGet => &["url"],
Self::HttpPost => &["url", "body"],
Self::HttpRequest => &["method", "url"],
Self::DotenvLoad => &[],
Self::Pi | Self::EConst | Self::Random => &[],
Self::Num | Self::MathNeg | Self::MathSin | Self::MathCos | Self::MathTan
| Self::MathAsin | Self::MathAcos | Self::MathAtan | Self::MathSqrt
@@ -338,7 +353,10 @@ impl HostFn {
pub fn optional_params(self) -> &'static [&'static str] {
match self {
Self::JsonStringify => &["indent"],
Self::HttpPost => &["content_type"],
Self::HttpGet => &["headers"],
Self::HttpPost => &["content_type", "headers"],
Self::HttpRequest => &["body", "content_type", "headers"],
Self::DotenvLoad => &["path"],
Self::Exec => &["args"],
Self::Solve => &["min", "max"],
Self::Plot => &["steps", "path", "derivative", "grid"],
@@ -385,6 +403,7 @@ pub fn call_host(
}
HostFn::EnvGet => sys::env_get(require(bound, "name")?),
HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?),
HostFn::DotenvLoad => sys::dotenv_load(ctx, bound.get("path")),
HostFn::Args => sys::args(ctx),
HostFn::Cwd => sys::cwd(ctx),
HostFn::Exit => sys::exit(ctx, require(bound, "code")?),
@@ -395,12 +414,22 @@ pub fn call_host(
}
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?),
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::HttpRequest => net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
),
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
+22
View File
@@ -53,6 +53,17 @@ pub fn keys(value: &Value) -> Result<Value, String> {
}
}
/// JSON-encode a text value including surrounding quotes (for building request bodies).
pub fn quote(text: &Value) -> Result<Value, String> {
let s = match text {
Value::Text(s) => s.as_str(),
_ => return Err("json quote needs text".into()),
};
serde_json::to_string(s)
.map(Value::Text)
.map_err(|e| format!("json quote: {e}"))
}
fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
Ok(match v {
serde_json::Value::Null => Value::None,
@@ -111,3 +122,14 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
Value::Code(c) => serde_json::Value::String(c.source.clone()),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quote_escapes_text() {
let q = quote(&Value::Text("a\"b".into())).unwrap();
assert_eq!(q, Value::Text("\"a\\\"b\"".into()));
}
}
+127 -87
View File
@@ -1,7 +1,5 @@
//! Minimal HTTP host primitives (HTTP cleartext in v1; HTTPS deferred).
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;
use crate::host::HostContext;
@@ -14,104 +12,96 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
}
}
struct UrlParts {
host: String,
port: u16,
path: String,
}
fn parse_http_url(url: &str) -> Result<UrlParts, String> {
let rest = url
.strip_prefix("http://")
.ok_or_else(|| {
if url.starts_with("https://") {
"https is not supported yet (use http:// or wait for TLS)".to_string()
} else {
"url must start with http://".into()
}
})?;
let (hostport, path) = match rest.split_once('/') {
Some((h, p)) => (h, format!("/{p}")),
None => (rest, "/".into()),
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
let Some(h) = headers else {
return Ok(Vec::new());
};
let (host, port) = if let Some((h, p)) = hostport.split_once(':') {
let port: u16 = p
.parse()
.map_err(|_| format!("invalid port in url: {p}"))?;
(h.to_string(), port)
} else {
(hostport.to_string(), 80)
};
if host.is_empty() {
return Err("url missing host".into());
match h {
Value::None => Ok(Vec::new()),
Value::Map(entries) => Ok(entries
.iter()
.map(|(k, v)| (k.clone(), v.as_display()))
.collect()),
_ => Err("headers must be a map (e.g. from json parse)".into()),
}
Ok(UrlParts { host, port, path })
}
fn http_exchange(
method: &str,
url: &str,
body: Option<&str>,
content_type: &str,
content_type: Option<&str>,
extra_headers: &[(String, String)],
) -> Result<(u16, String), String> {
let parts = parse_http_url(url)?;
let addr = format!("{}:{}", parts.host, parts.port);
let mut stream = TcpStream::connect(&addr).map_err(|e| format!("http connect {addr}: {e}"))?;
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.ok();
stream
.set_write_timeout(Some(Duration::from_secs(10)))
.ok();
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("url must start with http:// or https://".into());
}
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(15))
.timeout_read(Duration::from_secs(120))
.build();
let body = body.unwrap_or("");
let mut req = format!(
"{method} {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: marqdo\r\n",
path = parts.path,
host = parts.host,
);
if method == "POST" {
req.push_str(&format!(
"Content-Type: {content_type}\r\nContent-Length: {}\r\n",
body.len()
));
let mut req = match method {
"GET" => agent.get(url),
"POST" => agent.post(url),
"PUT" => agent.put(url),
"DELETE" => agent.request("DELETE", url),
other => return Err(format!("unsupported http method: {other}")),
};
req = req.set("User-Agent", "marqdo");
if let Some(ct) = content_type {
if !ct.is_empty() {
req = req.set("Content-Type", ct);
}
}
req.push_str("\r\n");
if method == "POST" {
req.push_str(body);
for (k, v) in extra_headers {
req = req.set(k, v);
}
stream
.write_all(req.as_bytes())
.map_err(|e| format!("http write: {e}"))?;
let mut buf = Vec::new();
stream
.read_to_end(&mut buf)
.map_err(|e| format!("http read: {e}"))?;
if buf.len() > 2 * 1024 * 1024 {
return Err("http response exceeds 2MiB limit".into());
let resp = if let Some(b) = body {
req.send_string(b)
} else {
req.call()
};
match resp {
Ok(r) => {
let status = r.status();
let text = r
.into_string()
.map_err(|e| format!("http read body: {e}"))?;
if text.len() > 8 * 1024 * 1024 {
return Err("http response exceeds 8MiB limit".into());
}
Ok((status, text))
}
Err(ureq::Error::Status(code, r)) => {
let text = r.into_string().unwrap_or_default();
Ok((code, text))
}
Err(e) => Err(format!("http {method} {url}: {e}")),
}
let text = String::from_utf8_lossy(&buf);
let (header, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_ref(), ""));
let status = header
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(0);
Ok((status, body.to_string()))
}
pub fn http_get(ctx: &HostContext, url: &Value) -> Result<Value, String> {
fn response_map(status: u16, body: String) -> Value {
Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(body)),
])
}
pub fn http_get(
ctx: &HostContext,
url: &Value,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_get denied by host policy".into());
}
let url = as_text(url, "url")?;
let (status, body) = http_exchange("GET", url, None, "")?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(body)),
]))
let hdrs = headers_from_value(headers)?;
let (status, body) = http_exchange("GET", url, None, None, &hdrs)?;
Ok(response_map(status, body))
}
pub fn http_post(
@@ -119,6 +109,7 @@ pub fn http_post(
url: &Value,
body: &Value,
content_type: Option<&Value>,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_post denied by host policy".into());
@@ -127,13 +118,44 @@ pub fn http_post(
let body = as_text(body, "body")?;
let ct = match content_type {
Some(v) => as_text(v, "content_type")?,
None => "text/plain; charset=utf-8",
None => "application/json; charset=utf-8",
};
let (status, resp) = http_exchange("POST", url, Some(body), ct)?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(resp)),
]))
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange("POST", url, Some(body), Some(ct), &hdrs)?;
Ok(response_map(status, resp))
}
/// Generic request: method + url + optional body / content_type / headers.
pub fn http_request(
ctx: &HostContext,
method: &Value,
url: &Value,
body: Option<&Value>,
content_type: Option<&Value>,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_request denied by host policy".into());
}
let method = as_text(method, "method")?.to_uppercase();
let url = as_text(url, "url")?;
let body_s = match body {
None | Some(Value::None) => None,
Some(v) => Some(as_text(v, "body")?),
};
let ct = match content_type {
None | Some(Value::None) => {
if body_s.is_some() && method == "POST" {
Some("application/json; charset=utf-8")
} else {
None
}
}
Some(v) => Some(as_text(v, "content_type")?),
};
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange(&method, url, body_s, ct, &hdrs)?;
Ok(response_map(status, resp))
}
pub fn url_encode(text: &Value) -> Result<Value, String> {
@@ -150,3 +172,21 @@ pub fn url_encode(text: &Value) -> Result<Value, String> {
.collect(),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn headers_from_map() {
let m = Value::Map(vec![
("Authorization".into(), Value::Text("Bearer x".into())),
("X-Test".into(), Value::Int(1)),
]);
let h = headers_from_value(Some(&m)).unwrap();
assert_eq!(h.len(), 2);
assert!(h
.iter()
.any(|(k, v)| k == "Authorization" && v == "Bearer x"));
}
}
+82
View File
@@ -34,6 +34,54 @@ pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
Ok(Value::None)
}
/// Load KEY=VALUE pairs from a `.env` file into the process environment.
/// Existing variables are **not** overridden. Default path: `.env` under host cwd.
pub fn dotenv_load(ctx: &HostContext, path: Option<&Value>) -> Result<Value, String> {
let rel = match path {
None | Some(Value::None) => ".env".to_string(),
Some(v) => as_text(v, "path")?.to_string(),
};
let file = if std::path::Path::new(&rel).is_absolute() {
std::path::PathBuf::from(&rel)
} else {
ctx.cwd.join(&rel)
};
let text = match std::fs::read_to_string(&file) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Int(0)),
Err(e) => {
return Err(format!("dotenv_load {}: {e}", file.display()));
}
};
let mut loaded = 0i64;
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim();
let Some((k, v)) = line.split_once('=') else {
continue;
};
let key = k.trim();
if key.is_empty() {
continue;
}
if std::env::var_os(key).is_some() {
continue;
}
let mut val = v.trim();
if (val.starts_with('"') && val.ends_with('"'))
|| (val.starts_with('\'') && val.ends_with('\''))
{
val = &val[1..val.len() - 1];
}
std::env::set_var(key, val);
loaded += 1;
}
Ok(Value::Int(loaded))
}
pub fn args(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
@@ -77,3 +125,37 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::host::HostContext;
use std::io::Write;
#[test]
fn dotenv_loads_without_override() {
let dir = std::env::temp_dir().join(format!("marqdo-dotenv-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("sample.env");
{
let mut f = std::fs::File::create(&path).unwrap();
writeln!(f, "# comment").unwrap();
writeln!(f, "MARQDO_DOTENV_A=one").unwrap();
writeln!(f, "export MARQDO_DOTENV_B=\"two\"").unwrap();
}
std::env::set_var("MARQDO_DOTENV_A", "keep");
std::env::remove_var("MARQDO_DOTENV_B");
let mut ctx = HostContext::default();
ctx.cwd = dir.clone();
let n = dotenv_load(&ctx, Some(&Value::Text("sample.env".into()))).unwrap();
assert_eq!(n, Value::Int(1));
assert_eq!(std::env::var("MARQDO_DOTENV_A").unwrap(), "keep");
assert_eq!(std::env::var("MARQDO_DOTENV_B").unwrap(), "two");
assert_eq!(
dotenv_load(&ctx, Some(&Value::Text("missing.env".into()))).unwrap(),
Value::Int(0)
);
let _ = std::fs::remove_dir_all(&dir);
}
}
+79 -10
View File
@@ -130,17 +130,16 @@ impl Interpreter {
if let Some(main) = find_top(module, "main") {
return self.run_function(module, main, Env::new(), &[]);
}
let tops: Vec<&Function> = module.functions.iter().filter(|f| f.level == 1).collect();
if tops.is_empty() {
bail!("no `# main` and no level-1 function to run");
// Document-as-entry: sole top-level `#` object with no params (e.g. `# Hello World`).
let entries: Vec<&Function> = module
.functions
.iter()
.filter(|f| f.is_object() && f.params.is_empty())
.collect();
if entries.len() == 1 {
return self.run_function(module, entries[0], Env::new(), &[]);
}
let mut last = Value::None;
for fun in tops {
if fun.params.is_empty() {
last = self.run_function(module, fun, Env::new(), &[])?;
}
}
Ok(last)
bail!("no `# main` object to run");
}
fn run_function(
@@ -443,6 +442,10 @@ impl Interpreter {
}
}
if let Some(recv_name) = &call.receiver {
return self.eval_method_call(module, env, recv_name, &call.callee, &ev_args);
}
match call.callee.as_str() {
"print" => {
let bound = bind_args(&["text".into()], &ev_args, false)
@@ -574,10 +577,76 @@ impl Interpreter {
call_env.set(k, v);
}
let result = self.run_function(module, target, call_env, &[])?;
if target.is_object() {
Ok(tag_instance(&target.name, result))
} else {
Ok(result)
}
}
fn eval_method_call(
&mut self,
module: &Module,
env: &mut Env,
recv_name: &str,
method: &str,
ev_args: &[EvArg],
) -> Result<Value> {
let recv = env
.get(recv_name)
.cloned()
.ok_or_else(|| self.err(format!("undefined variable `{recv_name}`")))?;
let type_name = instance_type_name(&recv).map_err(|m| self.err(m))?;
let obj = find_top(module, &type_name)
.filter(|f| f.is_object())
.ok_or_else(|| self.err(format!("unknown object type `{type_name}`")))?;
let target = obj
.children
.iter()
.find(|c| c.name == method)
.ok_or_else(|| self.err(format!("unknown method `{type_name}.{method}`")))?;
let bound = bind_args(&target.params, ev_args, false).map_err(|m| self.err(m))?;
let mut call_env = Env::new();
for (k, v) in bound {
call_env.set(k, v);
}
call_env.set("自".into(), recv.clone());
call_env.set("self".into(), recv);
self.run_function(module, target, call_env, &[])
}
}
fn instance_type_name(v: &Value) -> std::result::Result<String, String> {
match v {
Value::Map(entries) => entries
.iter()
.find(|(k, _)| k == "_type")
.and_then(|(_, v)| match v {
Value::Text(s) => Some(s.clone()),
_ => None,
})
.ok_or_else(|| "method receiver needs a map with `_type`".into()),
_ => Err("method receiver must be an object map".into()),
}
}
fn tag_instance(type_name: &str, value: Value) -> Value {
match value {
Value::Map(mut entries) => {
if !entries.iter().any(|(k, _)| k == "_type") {
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
}
Value::Map(entries)
}
Value::None => Value::Map(vec![("_type".into(), Value::Text(type_name.into()))]),
other => Value::Map(vec![
("_type".into(), Value::Text(type_name.into())),
("value".into(), other),
]),
}
}
/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path).
fn bind_args(
params: &[String],
+38 -2
View File
@@ -41,8 +41,8 @@ fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Modu
Ok(module)
}
/// Resolve an import path: relative to the importer first; `lib/…` and `std/…`
/// also search official library roots (`MARQDO_LIB`, `./lib`, near the binary).
/// Resolve an import path: relative to the importer first; `lib/…` / `std/…`
/// and `ext/…` also search official roots (`MARQDO_LIB` / `MARQDO_EXT`, cwd, near the binary).
pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
let rel = rel.replace('\\', "/");
let direct = from_dir.join(&rel);
@@ -72,6 +72,22 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
);
}
if let Some(remainder) = normalized.strip_prefix("ext/") {
for root in ext_search_roots() {
let as_ext_dir = root.join(remainder);
if as_ext_dir.is_file() {
return Ok(as_ext_dir);
}
let as_repo_root = root.join("ext").join(remainder);
if as_repo_root.is_file() {
return Ok(as_repo_root);
}
}
bail!(
"cannot resolve extension import `{rel}` (set MARQDO_EXT or keep an ext/ next to the project)"
);
}
Ok(direct)
}
@@ -95,6 +111,26 @@ fn lib_search_roots() -> Vec<PathBuf> {
roots
}
fn ext_search_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
if let Ok(h) = env::var("MARQDO_EXT") {
roots.push(PathBuf::from(h));
}
if let Ok(cwd) = env::current_dir() {
roots.push(cwd.join("ext"));
roots.push(cwd);
}
if let Ok(exe) = env::current_exe() {
if let Some(dir) = exe.parent() {
roots.push(dir.join("ext"));
roots.push(dir.join("../ext"));
roots.push(dir.join("../../ext"));
roots.push(dir.join("../../../ext"));
}
}
roots
}
fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
if let Some(d) = err.downcast_ref::<Diagnostic>() {
if d.path.is_none() {
+35 -4
View File
@@ -366,13 +366,14 @@ fn is_word_end(s: &str, len: usize) -> bool {
}
/// Parse `name key=val …` / positional args; returns call + bytes consumed.
/// Callee may be a bare name or method form `` `recv`.method ``.
pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
use crate::ast::Arg;
let s = s.trim_start();
let original_len = s.len();
let callee = {
let callee_tok = {
let mut parts = s.split_whitespace();
parts
.next()
@@ -380,9 +381,13 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
.to_string()
};
let (receiver, callee) = split_method_callee(&callee_tok)
.map(|(r, m)| (Some(r), m))
.unwrap_or((None, callee_tok.clone()));
let after_callee_offset = {
let idx = s.find(&callee).unwrap();
idx + callee.len()
let idx = s.find(&callee_tok).unwrap();
idx + callee_tok.len()
};
let mut args_str = s[after_callee_offset..].trim_start();
let mut args = Vec::new();
@@ -411,7 +416,33 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
}
}
Ok((CallExpr { callee, args }, original_len))
Ok((
CallExpr {
callee,
receiver,
args,
},
original_len,
))
}
/// `` `recv`.method `` → (recv, method).
fn split_method_callee(tok: &str) -> Option<(String, String)> {
if !tok.starts_with('`') {
return None;
}
let rest = &tok[1..];
let end = rest.find('`')?;
let recv = rest[..end].to_string();
if recv.is_empty() {
return None;
}
let after = &rest[end + 1..];
let method = after.strip_prefix('.')?;
if method.is_empty() || method.contains('`') || method.contains('.') {
return None;
}
Some((recv, method.to_string()))
}
/// If `s` begins with `ident=`, return (ident, rest_after_eq).
+1 -1
View File
@@ -31,7 +31,7 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
functions.push(cur.parse_function(1)?);
} else {
bail!(
"{}:1: expected function heading `# …`, got: {trimmed}",
"{}:1: expected heading (`#` object or `##` function), got: {trimmed}",
line.line_no
);
}
+8 -1
View File
@@ -573,7 +573,14 @@ fn stmt_shell(line: u32, inner: &str, mode: StructureMode) -> String {
}
fn call_display(call: &CallExpr) -> String {
let mut s = format!("> {}", call.callee);
let mut s = String::from("> ");
if let Some(recv) = &call.receiver {
s.push('`');
s.push_str(recv);
s.push('`');
s.push('.');
}
s.push_str(&call.callee);
for a in &call.args {
match a {
Arg::Positional(e) => {