Add host stdlib modules and unify view/run capabilities.
Ship fs/time/sys/json/net L1 libs (plus existing text/table), default-on host caps with soft exit under view, bilingual public/stdlib docs, and design notes for deferred math/foreign. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a5d30c00b3
commit
a53ebb65ee
66 files changed
+2703
-45
No files matched your search
@@ -22,6 +22,9 @@ pub fn is_reserved_keyword(name: &str) -> bool {
|
||||
/// Map a builtin callee (EN or ZH alias) to its English canonical name.
|
||||
/// Host primitives without ZH L0 aliases only match English.
|
||||
pub fn canonical_builtin(name: &str) -> Option<&'static str> {
|
||||
if let Some(h) = crate::host::HostFn::from_name(name) {
|
||||
return Some(h.name());
|
||||
}
|
||||
match name {
|
||||
"print" | "打印" => Some("print"),
|
||||
"input" | "输入" => Some("input"),
|
||||
|
||||
+2
-1
@@ -31,7 +31,7 @@ pub fn builtin_int(v: &Value) -> Result<i64, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `type`: type tag as text (`none` / `bool` / `int` / `text` / `list`).
|
||||
/// `type`: type tag as text (`none` / `bool` / `int` / `text` / `list` / `map`).
|
||||
pub fn builtin_type(v: &Value) -> Value {
|
||||
Value::Text(
|
||||
match v {
|
||||
@@ -40,6 +40,7 @@ pub fn builtin_type(v: &Value) -> Value {
|
||||
Value::Int(_) => "int",
|
||||
Value::Text(_) => "text",
|
||||
Value::List(_) => "list",
|
||||
Value::Map(_) => "map",
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
|
||||
@@ -427,6 +427,45 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
other if crate::host::HostFn::from_name(other).is_some() => {
|
||||
let hf = crate::host::HostFn::from_name(other).unwrap();
|
||||
let params = hf.all_params();
|
||||
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 = 0usize;
|
||||
let required_n = hf.required_params().len();
|
||||
for (i, p) in params.iter().enumerate() {
|
||||
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 if i < required_n {
|
||||
return Err(self.err(format!("{} requires `{p}`", hf.name())));
|
||||
} else {
|
||||
self.emit(Op::None_);
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
return Err(self.err(format!(
|
||||
"too many positional arguments ({} extra)",
|
||||
positionals.len() - pos_i
|
||||
)));
|
||||
}
|
||||
self.emit(Op::HostCall(hf.as_u16(), params.len() as u8));
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ pub enum Op {
|
||||
GetIndex,
|
||||
/// Call function by index; argc values are on the stack (param order).
|
||||
Call(u16, u8),
|
||||
/// Host primitive: pop `argc` args (param order), push result.
|
||||
HostCall(u16, u8),
|
||||
Return,
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,13 @@ use crate::builtin::{
|
||||
builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim,
|
||||
builtin_type,
|
||||
};
|
||||
use crate::host::{call_host, HostContext, HostFn};
|
||||
use crate::bytecode::{Op, Program};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::value::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct Vm {
|
||||
path: Option<PathBuf>,
|
||||
@@ -20,6 +22,7 @@ pub struct Vm {
|
||||
pub captured_stdout: String,
|
||||
input: InputFeed,
|
||||
trace: bool,
|
||||
host: HostContext,
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
@@ -36,6 +39,7 @@ impl Vm {
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(false, Vec::new()),
|
||||
trace: false,
|
||||
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +50,7 @@ impl Vm {
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(true, Vec::new()),
|
||||
trace: false,
|
||||
host: HostContext::for_capture(path, Default::default()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +64,11 @@ impl Vm {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_host(mut self, host: HostContext) -> Self {
|
||||
self.host = host;
|
||||
self
|
||||
}
|
||||
|
||||
fn emit_line(&mut self, text: &str) {
|
||||
if self.capture {
|
||||
self.captured_stdout.push_str(text);
|
||||
@@ -276,6 +286,35 @@ impl Vm {
|
||||
let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::HostCall(id, argc) => {
|
||||
let hf = HostFn::from_u16(id)
|
||||
.ok_or_else(|| self.err_at(span, format!("unknown host id {id}")))?;
|
||||
let argc = argc as usize;
|
||||
let params = hf.all_params();
|
||||
if params.len() != argc {
|
||||
return Err(self.err_at(span, "host call argc mismatch"));
|
||||
}
|
||||
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 mut bound = HashMap::new();
|
||||
for (p, v) in params.iter().zip(vals.into_iter()) {
|
||||
bound.insert((*p).to_string(), v);
|
||||
}
|
||||
for req in hf.required_params() {
|
||||
if !bound.contains_key(*req) {
|
||||
return Err(self.err_at(
|
||||
span,
|
||||
format!("{} requires `{req}`", hf.name()),
|
||||
));
|
||||
}
|
||||
}
|
||||
let result =
|
||||
call_host(&self.host, hf, &bound).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(result);
|
||||
}
|
||||
Op::Call(fid, argc) => {
|
||||
let fid = fid as usize;
|
||||
let argc = argc as usize;
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Host function registry and dispatch.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{fs, json, net, sys, time, HostContext};
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u16)]
|
||||
pub enum HostFn {
|
||||
ReadText = 1,
|
||||
WriteText = 2,
|
||||
AppendText = 3,
|
||||
Exists = 4,
|
||||
ListDir = 5,
|
||||
MakeDir = 6,
|
||||
Remove = 7,
|
||||
NowUnix = 8,
|
||||
NowMs = 9,
|
||||
FormatTime = 10,
|
||||
SleepMs = 11,
|
||||
ParseTime = 12,
|
||||
EnvGet = 13,
|
||||
EnvSet = 14,
|
||||
Args = 15,
|
||||
Cwd = 16,
|
||||
Exit = 17,
|
||||
Exec = 18,
|
||||
JsonParse = 19,
|
||||
JsonStringify = 20,
|
||||
JsonGet = 21,
|
||||
JsonKeys = 22,
|
||||
HttpGet = 23,
|
||||
HttpPost = 24,
|
||||
UrlEncode = 25,
|
||||
}
|
||||
|
||||
impl HostFn {
|
||||
pub fn from_u16(id: u16) -> Option<Self> {
|
||||
Some(match id {
|
||||
1 => Self::ReadText,
|
||||
2 => Self::WriteText,
|
||||
3 => Self::AppendText,
|
||||
4 => Self::Exists,
|
||||
5 => Self::ListDir,
|
||||
6 => Self::MakeDir,
|
||||
7 => Self::Remove,
|
||||
8 => Self::NowUnix,
|
||||
9 => Self::NowMs,
|
||||
10 => Self::FormatTime,
|
||||
11 => Self::SleepMs,
|
||||
12 => Self::ParseTime,
|
||||
13 => Self::EnvGet,
|
||||
14 => Self::EnvSet,
|
||||
15 => Self::Args,
|
||||
16 => Self::Cwd,
|
||||
17 => Self::Exit,
|
||||
18 => Self::Exec,
|
||||
19 => Self::JsonParse,
|
||||
20 => Self::JsonStringify,
|
||||
21 => Self::JsonGet,
|
||||
22 => Self::JsonKeys,
|
||||
23 => Self::HttpGet,
|
||||
24 => Self::HttpPost,
|
||||
25 => Self::UrlEncode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"host_read_text" => Self::ReadText,
|
||||
"host_write_text" => Self::WriteText,
|
||||
"host_append_text" => Self::AppendText,
|
||||
"host_exists" => Self::Exists,
|
||||
"host_list_dir" => Self::ListDir,
|
||||
"host_make_dir" => Self::MakeDir,
|
||||
"host_remove" => Self::Remove,
|
||||
"host_now_unix" => Self::NowUnix,
|
||||
"host_now_ms" => Self::NowMs,
|
||||
"host_format_time" => Self::FormatTime,
|
||||
"host_sleep_ms" => Self::SleepMs,
|
||||
"host_parse_time" => Self::ParseTime,
|
||||
"host_env_get" => Self::EnvGet,
|
||||
"host_env_set" => Self::EnvSet,
|
||||
"host_args" => Self::Args,
|
||||
"host_cwd" => Self::Cwd,
|
||||
"host_exit" => Self::Exit,
|
||||
"host_exec" => Self::Exec,
|
||||
"host_json_parse" => Self::JsonParse,
|
||||
"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,
|
||||
"host_url_encode" => Self::UrlEncode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_u16(self) -> u16 {
|
||||
self as u16
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::ReadText => "host_read_text",
|
||||
Self::WriteText => "host_write_text",
|
||||
Self::AppendText => "host_append_text",
|
||||
Self::Exists => "host_exists",
|
||||
Self::ListDir => "host_list_dir",
|
||||
Self::MakeDir => "host_make_dir",
|
||||
Self::Remove => "host_remove",
|
||||
Self::NowUnix => "host_now_unix",
|
||||
Self::NowMs => "host_now_ms",
|
||||
Self::FormatTime => "host_format_time",
|
||||
Self::SleepMs => "host_sleep_ms",
|
||||
Self::ParseTime => "host_parse_time",
|
||||
Self::EnvGet => "host_env_get",
|
||||
Self::EnvSet => "host_env_set",
|
||||
Self::Args => "host_args",
|
||||
Self::Cwd => "host_cwd",
|
||||
Self::Exit => "host_exit",
|
||||
Self::Exec => "host_exec",
|
||||
Self::JsonParse => "host_json_parse",
|
||||
Self::JsonStringify => "host_json_stringify",
|
||||
Self::JsonGet => "host_json_get",
|
||||
Self::JsonKeys => "host_json_keys",
|
||||
Self::HttpGet => "host_http_get",
|
||||
Self::HttpPost => "host_http_post",
|
||||
Self::UrlEncode => "host_url_encode",
|
||||
}
|
||||
}
|
||||
|
||||
/// Required params first; see `optional_params` for trailing optionals.
|
||||
pub fn required_params(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
|
||||
&["path"]
|
||||
}
|
||||
Self::WriteText | Self::AppendText => &["path", "text"],
|
||||
Self::NowUnix | Self::NowMs | Self::Args | Self::Cwd => &[],
|
||||
Self::FormatTime => &["unix", "pattern"],
|
||||
Self::ParseTime => &["text", "pattern"],
|
||||
Self::SleepMs => &["ms"],
|
||||
Self::EnvGet => &["name"],
|
||||
Self::EnvSet => &["name", "value"],
|
||||
Self::Exit => &["code"],
|
||||
Self::Exec => &["cmd"],
|
||||
Self::JsonParse | Self::UrlEncode => &["text"],
|
||||
Self::JsonStringify | Self::JsonKeys => &["value"],
|
||||
Self::JsonGet => &["value", "key"],
|
||||
Self::HttpGet => &["url"],
|
||||
Self::HttpPost => &["url", "body"],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn optional_params(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::JsonStringify => &["indent"],
|
||||
Self::HttpPost => &["content_type"],
|
||||
Self::Exec => &["args"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_params(self) -> Vec<&'static str> {
|
||||
let mut v = self.required_params().to_vec();
|
||||
v.extend_from_slice(self.optional_params());
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call_host(
|
||||
ctx: &HostContext,
|
||||
fn_id: HostFn,
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match fn_id {
|
||||
HostFn::ReadText => fs::read_text(ctx, require(bound, "path")?),
|
||||
HostFn::WriteText => {
|
||||
fs::write_text(ctx, require(bound, "path")?, require(bound, "text")?)
|
||||
}
|
||||
HostFn::AppendText => {
|
||||
fs::append_text(ctx, require(bound, "path")?, require(bound, "text")?)
|
||||
}
|
||||
HostFn::Exists => fs::exists(ctx, require(bound, "path")?),
|
||||
HostFn::ListDir => fs::list_dir(ctx, require(bound, "path")?),
|
||||
HostFn::MakeDir => fs::make_dir(ctx, require(bound, "path")?),
|
||||
HostFn::Remove => fs::remove(ctx, require(bound, "path")?),
|
||||
HostFn::NowUnix => time::now_unix(),
|
||||
HostFn::NowMs => time::now_ms(),
|
||||
HostFn::FormatTime => {
|
||||
time::format_time(require(bound, "unix")?, require(bound, "pattern")?)
|
||||
}
|
||||
HostFn::SleepMs => time::sleep_ms(ctx, require(bound, "ms")?),
|
||||
HostFn::ParseTime => {
|
||||
time::parse_time(require(bound, "text")?, require(bound, "pattern")?)
|
||||
}
|
||||
HostFn::EnvGet => sys::env_get(require(bound, "name")?),
|
||||
HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?),
|
||||
HostFn::Args => sys::args(ctx),
|
||||
HostFn::Cwd => sys::cwd(ctx),
|
||||
HostFn::Exit => sys::exit(ctx, require(bound, "code")?),
|
||||
HostFn::Exec => sys::exec(ctx, require(bound, "cmd")?, bound.get("args")),
|
||||
HostFn::JsonParse => json::parse(require(bound, "text")?),
|
||||
HostFn::JsonStringify => {
|
||||
json::stringify(require(bound, "value")?, bound.get("indent"))
|
||||
}
|
||||
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::HttpPost => net::http_post(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
),
|
||||
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
|
||||
}
|
||||
}
|
||||
|
||||
fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value, String> {
|
||||
bound
|
||||
.get(key)
|
||||
.ok_or_else(|| format!("host call missing `{key}`"))
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
//! Filesystem host primitives.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn path_under_root(path: &Path, root: &Path) -> bool {
|
||||
let mut cur = path.to_path_buf();
|
||||
loop {
|
||||
if cur == *root {
|
||||
return true;
|
||||
}
|
||||
if !cur.pop() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_path(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("path must be text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_body(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("text must be text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?;
|
||||
Ok(Value::Text(s))
|
||||
}
|
||||
|
||||
pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("write_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if let Some(parent) = p.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?;
|
||||
}
|
||||
fs::write(&p, text_body(text)?).map_err(|e| format!("write_text {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("append_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
use std::io::Write;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&p)
|
||||
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
|
||||
f.write_all(text_body(text)?.as_bytes())
|
||||
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
Ok(Value::Bool(p.exists()))
|
||||
}
|
||||
|
||||
pub fn list_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let mut names = Vec::new();
|
||||
let rd = fs::read_dir(&p).map_err(|e| format!("list_dir {}: {e}", p.display()))?;
|
||||
for ent in rd {
|
||||
let ent = ent.map_err(|e| format!("list_dir: {e}"))?;
|
||||
names.push(Value::Text(
|
||||
ent.file_name().to_string_lossy().into_owned(),
|
||||
));
|
||||
}
|
||||
names.sort_by(|a, b| a.as_display().cmp(&b.as_display()));
|
||||
Ok(Value::List(names))
|
||||
}
|
||||
|
||||
pub fn make_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("make_dir denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
fs::create_dir_all(&p).map_err(|e| format!("make_dir {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("remove denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if p.is_dir() {
|
||||
fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
|
||||
} else {
|
||||
fs::remove_file(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! JSON host primitives + Value↔JSON mapping.
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let s = match text {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json parse needs text".into()),
|
||||
};
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(s).map_err(|e| format!("json parse: {e}"))?;
|
||||
json_to_value(&v)
|
||||
}
|
||||
|
||||
pub fn stringify(value: &Value, indent: Option<&Value>) -> Result<Value, String> {
|
||||
let j = value_to_json(value)?;
|
||||
let pretty = match indent {
|
||||
None => false,
|
||||
Some(Value::Int(n)) => *n > 0,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::None) => false,
|
||||
Some(_) => return Err("json stringify indent must be int or bool".into()),
|
||||
};
|
||||
let s = if pretty {
|
||||
serde_json::to_string_pretty(&j).map_err(|e| format!("json stringify: {e}"))?
|
||||
} else {
|
||||
serde_json::to_string(&j).map_err(|e| format!("json stringify: {e}"))?
|
||||
};
|
||||
Ok(Value::Text(s))
|
||||
}
|
||||
|
||||
pub fn get(value: &Value, key: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json get key must be text".into()),
|
||||
};
|
||||
match value {
|
||||
Value::Map(entries) => Ok(entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None)),
|
||||
_ => Err("json get needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn keys(value: &Value) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::Map(entries) => Ok(Value::List(
|
||||
entries.iter().map(|(k, _)| Value::Text(k.clone())).collect(),
|
||||
)),
|
||||
_ => Err("json keys needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
|
||||
Ok(match v {
|
||||
serde_json::Value::Null => Value::None,
|
||||
serde_json::Value::Bool(b) => Value::Bool(*b),
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
Value::Int(i)
|
||||
} else {
|
||||
Value::Text(n.to_string())
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(s) => Value::Text(s.clone()),
|
||||
serde_json::Value::Array(xs) => {
|
||||
let mut out = Vec::with_capacity(xs.len());
|
||||
for x in xs {
|
||||
out.push(json_to_value(x)?);
|
||||
}
|
||||
Value::List(out)
|
||||
}
|
||||
serde_json::Value::Object(map) => {
|
||||
let mut entries = Vec::with_capacity(map.len());
|
||||
for (k, v) in map {
|
||||
entries.push((k.clone(), json_to_value(v)?));
|
||||
}
|
||||
Value::Map(entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
Ok(match v {
|
||||
Value::None => serde_json::Value::Null,
|
||||
Value::Bool(b) => serde_json::Value::Bool(*b),
|
||||
Value::Int(n) => serde_json::Value::Number((*n).into()),
|
||||
Value::Text(s) => serde_json::Value::String(s.clone()),
|
||||
Value::List(xs) => {
|
||||
let mut arr = Vec::with_capacity(xs.len());
|
||||
for x in xs {
|
||||
arr.push(value_to_json(x)?);
|
||||
}
|
||||
serde_json::Value::Array(arr)
|
||||
}
|
||||
Value::Map(entries) => {
|
||||
let mut map = serde_json::Map::new();
|
||||
for (k, v) in entries {
|
||||
map.insert(k.clone(), value_to_json(v)?);
|
||||
}
|
||||
serde_json::Value::Object(map)
|
||||
}
|
||||
})
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, …).
|
||||
//!
|
||||
//! User docs should import L1 wrappers; these `host_*` names are the Rust surface.
|
||||
//! Capabilities default **on** (importing a lib means you intend to use it).
|
||||
//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only.
|
||||
|
||||
mod dispatch;
|
||||
mod fs;
|
||||
mod json;
|
||||
mod net;
|
||||
mod sys;
|
||||
mod time;
|
||||
|
||||
pub use dispatch::{call_host, HostFn};
|
||||
pub use fs::path_under_root;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Host capability flags. Default: all enabled.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostCaps {
|
||||
pub fs_write: bool,
|
||||
pub exec: bool,
|
||||
pub net: bool,
|
||||
}
|
||||
|
||||
impl Default for HostCaps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fs_write: true,
|
||||
exec: true,
|
||||
net: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostContext {
|
||||
pub caps: HostCaps,
|
||||
pub fs_root: Option<PathBuf>,
|
||||
pub cwd: PathBuf,
|
||||
pub argv: Vec<String>,
|
||||
/// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export).
|
||||
pub soft_side_effects: bool,
|
||||
pub sleep_limit_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for HostContext {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
caps: HostCaps::default(),
|
||||
fs_root: None,
|
||||
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
argv: Vec::new(),
|
||||
soft_side_effects: false,
|
||||
sleep_limit_ms: Some(30_000),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HostContext {
|
||||
pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec<String>) -> Self {
|
||||
let mut ctx = Self::default();
|
||||
ctx.caps = caps;
|
||||
ctx.argv = argv;
|
||||
if let Some(p) = path {
|
||||
if let Some(parent) = p.parent() {
|
||||
let parent = if parent.as_os_str().is_empty() {
|
||||
PathBuf::from(".")
|
||||
} else {
|
||||
parent.to_path_buf()
|
||||
};
|
||||
ctx.cwd = parent.clone();
|
||||
ctx.fs_root = Some(parent);
|
||||
}
|
||||
}
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Capture stdout / view / export: soft exit + sleep clamp; same caps as CLI by default.
|
||||
pub fn for_capture(path: Option<&Path>, caps: HostCaps) -> Self {
|
||||
let mut ctx = Self::for_run(path, caps, Vec::new());
|
||||
ctx.soft_side_effects = true;
|
||||
ctx.sleep_limit_ms = Some(0);
|
||||
ctx
|
||||
}
|
||||
|
||||
pub fn allow_fs_write(&self) -> bool {
|
||||
self.caps.fs_write
|
||||
}
|
||||
|
||||
pub fn allow_exec(&self) -> bool {
|
||||
self.caps.exec
|
||||
}
|
||||
|
||||
pub fn allow_net(&self) -> bool {
|
||||
self.caps.net
|
||||
}
|
||||
|
||||
pub fn resolve_path(&self, rel: &str) -> Result<PathBuf, String> {
|
||||
let p = Path::new(rel);
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
self.cwd.join(p)
|
||||
};
|
||||
if let Some(root) = &self.fs_root {
|
||||
let root_canon = root.canonicalize().unwrap_or_else(|_| root.clone());
|
||||
let check = abs.canonicalize().unwrap_or_else(|_| abs.clone());
|
||||
if !path_under_root(&check, &root_canon) && !path_under_root(&abs, root) {
|
||||
if let Some(parent) = abs.parent() {
|
||||
let parent_ok = parent
|
||||
.canonicalize()
|
||||
.map(|p| path_under_root(&p, &root_canon))
|
||||
.unwrap_or_else(|_| path_under_root(parent, root));
|
||||
if !parent_ok {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
} else {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(abs)
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
//! Minimal HTTP host primitives (HTTP cleartext in v1; HTTPS deferred).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} must be text")),
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
};
|
||||
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());
|
||||
}
|
||||
Ok(UrlParts { host, port, path })
|
||||
}
|
||||
|
||||
fn http_exchange(
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<&str>,
|
||||
content_type: &str,
|
||||
) -> 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();
|
||||
|
||||
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()
|
||||
));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
if method == "POST" {
|
||||
req.push_str(body);
|
||||
}
|
||||
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 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> {
|
||||
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)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn http_post(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
body: &Value,
|
||||
content_type: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("http_post denied by host policy".into());
|
||||
}
|
||||
let url = as_text(url, "url")?;
|
||||
let body = as_text(body, "body")?;
|
||||
let ct = match content_type {
|
||||
Some(v) => as_text(v, "content_type")?,
|
||||
None => "text/plain; 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)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn url_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
Ok(Value::Text(
|
||||
s.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
(b as char).to_string()
|
||||
}
|
||||
b' ' => "+".into(),
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! System / process host primitives.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} must be text")),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn env_get(name: &Value) -> Result<Value, String> {
|
||||
let key = as_text(name, "name")?;
|
||||
Ok(match std::env::var(key) {
|
||||
Ok(v) => Value::Text(v),
|
||||
Err(_) => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
|
||||
let key = as_text(name, "name")?;
|
||||
let val = as_text(value, "value")?;
|
||||
std::env::set_var(key, val);
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn args(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(
|
||||
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn cwd(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::Text(ctx.cwd.display().to_string()))
|
||||
}
|
||||
|
||||
pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
|
||||
let c = as_i64(code, "code")?;
|
||||
if ctx.soft_side_effects {
|
||||
return Err(format!("exit {c} (soft mode does not terminate process)"));
|
||||
}
|
||||
std::process::exit(c as i32);
|
||||
}
|
||||
|
||||
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
|
||||
if !ctx.allow_exec() {
|
||||
return Err("exec denied by host policy".into());
|
||||
}
|
||||
let cmd = as_text(cmd, "cmd")?;
|
||||
let mut command = Command::new(cmd);
|
||||
command.current_dir(&ctx.cwd);
|
||||
if let Some(a) = args {
|
||||
match a {
|
||||
Value::List(xs) => {
|
||||
for x in xs {
|
||||
command.arg(x.as_display());
|
||||
}
|
||||
}
|
||||
Value::Text(s) => {
|
||||
command.arg(s);
|
||||
}
|
||||
_ => return Err("exec args must be list or text".into()),
|
||||
}
|
||||
}
|
||||
let status = command
|
||||
.status()
|
||||
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(1) as i64))
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Time host primitives.
|
||||
|
||||
use std::thread;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} must be text")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_time(unix: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
let pat = as_text(pattern, "pattern")?;
|
||||
let dt = DateTime::<Utc>::from_timestamp(secs, 0)
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
|
||||
Ok(Value::Text(dt.format(pat).to_string()))
|
||||
}
|
||||
|
||||
pub fn parse_time(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let pat = as_text(pattern, "pattern")?;
|
||||
let dt = NaiveDateTime::parse_from_str(t, pat).map_err(|e| format!("parse_time: {e}"))?;
|
||||
Ok(Value::Int(dt.and_utc().timestamp()))
|
||||
}
|
||||
|
||||
pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
|
||||
let n = as_i64(ms, "ms")?;
|
||||
if n < 0 {
|
||||
return Err("sleep_ms must be >= 0".into());
|
||||
}
|
||||
let n = n as u64;
|
||||
if let Some(lim) = ctx.sleep_limit_ms {
|
||||
if n > lim {
|
||||
return Err(format!("sleep_ms {n} exceeds limit {lim}"));
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
thread::sleep(Duration::from_millis(n));
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use crate::builtin::{
|
||||
};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::host::{call_host, HostContext, HostFn};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::value::Value;
|
||||
|
||||
@@ -23,6 +24,7 @@ pub struct Interpreter {
|
||||
pub captured_stdout: String,
|
||||
current_span: Span,
|
||||
input: InputFeed,
|
||||
host: HostContext,
|
||||
}
|
||||
|
||||
struct Env {
|
||||
@@ -59,6 +61,7 @@ impl Interpreter {
|
||||
captured_stdout: String::new(),
|
||||
current_span: Span::new(1, 1),
|
||||
input: InputFeed::new(false, Vec::new()),
|
||||
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +73,7 @@ impl Interpreter {
|
||||
captured_stdout: String::new(),
|
||||
current_span: Span::new(1, 1),
|
||||
input: InputFeed::new(true, Vec::new()),
|
||||
host: HostContext::for_capture(path, Default::default()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +82,11 @@ impl Interpreter {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_host(mut self, host: HostContext) -> Self {
|
||||
self.host = host;
|
||||
self
|
||||
}
|
||||
|
||||
fn err(&self, message: impl Into<String>) -> anyhow::Error {
|
||||
bail_at(self.path.as_deref(), self.current_span, message)
|
||||
}
|
||||
@@ -517,6 +526,21 @@ impl Interpreter {
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
return builtin_at(value, index).map_err(|m| self.err(m));
|
||||
}
|
||||
other if HostFn::from_name(other).is_some() => {
|
||||
let hf = HostFn::from_name(other).unwrap();
|
||||
let mut params: Vec<String> =
|
||||
hf.required_params().iter().map(|s| (*s).to_string()).collect();
|
||||
for p in hf.optional_params() {
|
||||
params.push((*p).to_string());
|
||||
}
|
||||
let bound = bind_args(¶ms, &ev_args, true).map_err(|m| self.err(m))?;
|
||||
for req in hf.required_params() {
|
||||
if !bound.contains_key(*req) {
|
||||
return Err(self.err(format!("{} requires `{req}`", hf.name())));
|
||||
}
|
||||
}
|
||||
return call_host(&self.host, hf, &bound).map_err(|m| self.err(m));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
|
||||
+70
-7
@@ -11,6 +11,7 @@ pub mod capture;
|
||||
pub mod catalog;
|
||||
pub mod debug;
|
||||
pub mod diagnostics;
|
||||
pub mod host;
|
||||
pub mod input_feed;
|
||||
pub mod interp;
|
||||
pub mod lex;
|
||||
@@ -23,6 +24,7 @@ use std::path::Path;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
use crate::host::{HostCaps, HostContext};
|
||||
use crate::ast::format_ast_dump;
|
||||
use crate::bytecode::{compile_module, Vm};
|
||||
use crate::capture::RunCapture;
|
||||
@@ -48,7 +50,7 @@ impl Backend {
|
||||
}
|
||||
|
||||
/// Options for a single `run` / dump invocation.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunOptions {
|
||||
pub dump_lines: bool,
|
||||
pub dump_tokens: bool,
|
||||
@@ -59,6 +61,36 @@ pub struct RunOptions {
|
||||
pub backend: Backend,
|
||||
/// Preset lines consumed by `input` (from `--stdin-file` or view).
|
||||
pub stdin_lines: Vec<String>,
|
||||
pub allow_fs_write: bool,
|
||||
pub allow_exec: bool,
|
||||
pub allow_net: bool,
|
||||
/// Exposed via `host_args` / `args`.
|
||||
pub argv: Vec<String>,
|
||||
/// Override filesystem sandbox root (default: source file's directory).
|
||||
pub fs_root: Option<std::path::PathBuf>,
|
||||
/// Sleep clamp when capturing (None = host default; view export uses `Some(0)`).
|
||||
pub sleep_limit_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for RunOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
dump_lines: false,
|
||||
dump_tokens: false,
|
||||
dump_ast: false,
|
||||
dump_sema: false,
|
||||
dump_bytecode: false,
|
||||
trace_eval: false,
|
||||
backend: Backend::default(),
|
||||
stdin_lines: Vec::new(),
|
||||
allow_fs_write: true,
|
||||
allow_exec: true,
|
||||
allow_net: true,
|
||||
argv: Vec::new(),
|
||||
fs_root: None,
|
||||
sleep_limit_ms: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RunOptions {
|
||||
@@ -70,8 +102,7 @@ impl RunOptions {
|
||||
dump_sema: true,
|
||||
dump_bytecode: true,
|
||||
trace_eval: true,
|
||||
backend: Backend::Tree,
|
||||
stdin_lines: Vec::new(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +114,14 @@ impl RunOptions {
|
||||
|| self.dump_bytecode
|
||||
|| self.trace_eval
|
||||
}
|
||||
|
||||
pub fn host_caps(&self) -> HostCaps {
|
||||
HostCaps {
|
||||
fs_write: self.allow_fs_write,
|
||||
exec: self.allow_exec,
|
||||
net: self.allow_net,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a `.mq.md` program (prints to real stdout).
|
||||
@@ -128,8 +167,10 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
let mut interp = Interpreter::new(Some(path), opts.trace_eval)
|
||||
.with_stdin(stdin_lines.clone());
|
||||
.with_stdin(stdin_lines.clone())
|
||||
.with_host(host);
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
@@ -143,9 +184,11 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.dump_bytecode {
|
||||
print!("{}", program.disassemble());
|
||||
}
|
||||
let host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
let mut vm = Vm::new(Some(path))
|
||||
.with_stdin(stdin_lines)
|
||||
.with_trace(opts.trace_eval);
|
||||
.with_trace(opts.trace_eval)
|
||||
.with_host(host);
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
@@ -173,7 +216,17 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
let module = load_module(path)?;
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut interp = Interpreter::with_capture(Some(path), false).with_stdin(stdin_lines);
|
||||
let mut host = HostContext::for_capture(Some(path), opts.host_caps());
|
||||
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(Some(path), false)
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = interp.run_module(&module)?;
|
||||
Ok(RunCapture {
|
||||
stdout: interp.captured_stdout,
|
||||
@@ -182,7 +235,17 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
}
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(Some(path), &module)?;
|
||||
let mut vm = Vm::with_capture(Some(path)).with_stdin(stdin_lines);
|
||||
let mut host = HostContext::for_capture(Some(path), opts.host_caps());
|
||||
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(Some(path))
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = vm.run(&program)?;
|
||||
Ok(RunCapture {
|
||||
stdout: vm.captured_stdout,
|
||||
|
||||
@@ -156,6 +156,7 @@ fn try_main() -> Result<i32> {
|
||||
trace_eval,
|
||||
backend: backend.into(),
|
||||
stdin_lines,
|
||||
..RunOptions::default()
|
||||
}
|
||||
};
|
||||
if dump_all {
|
||||
|
||||
@@ -10,6 +10,8 @@ pub enum Value {
|
||||
Text(String),
|
||||
/// Single-column table rows (v0); multi-column later.
|
||||
List(Vec<Value>),
|
||||
/// JSON object / string-keyed map (insertion order).
|
||||
Map(Vec<(String, Value)>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
@@ -20,6 +22,7 @@ impl Value {
|
||||
Value::Int(n) => *n != 0,
|
||||
Value::Text(s) => !s.is_empty(),
|
||||
Value::List(xs) => !xs.is_empty(),
|
||||
Value::Map(xs) => !xs.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +34,7 @@ impl Value {
|
||||
Value::Int(n) => n.to_string(),
|
||||
Value::Text(s) => s.clone(),
|
||||
Value::List(_) => "<list>".into(),
|
||||
Value::Map(_) => "<map>".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-6
@@ -130,7 +130,7 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
||||
if let Some(first) = root.files.first() {
|
||||
let rel = first.to_string_lossy().replace('\\', "/");
|
||||
let resolved = resolve_rel(root, &rel)?;
|
||||
let vm = build_file_view(&resolved, &rel, &[])?;
|
||||
let vm = build_file_view(root, &resolved, &rel, &[], true)?;
|
||||
let body = page_file(&root.files, &rel, &vm, &LinkMode::Live);
|
||||
respond_html(request, body)
|
||||
} else {
|
||||
@@ -143,7 +143,7 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
||||
let stdin_raw = query_param(query, "stdin").unwrap_or_default();
|
||||
let stdin_lines = split_stdin_text(&stdin_raw);
|
||||
let resolved = resolve_rel(root, &rel)?;
|
||||
let vm = build_file_view(&resolved, &rel, &stdin_lines)?;
|
||||
let vm = build_file_view(root, &resolved, &rel, &stdin_lines, true)?;
|
||||
let body = page_file(&root.files, &rel, &vm, &LinkMode::Live);
|
||||
respond_html(request, body)
|
||||
}
|
||||
@@ -160,9 +160,11 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
||||
}
|
||||
|
||||
pub(crate) fn build_file_view(
|
||||
root: &ViewRoot,
|
||||
abs: &Path,
|
||||
rel: &str,
|
||||
stdin_lines: &[String],
|
||||
live: bool,
|
||||
) -> Result<FileViewModel> {
|
||||
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
|
||||
let structure = match crate::load::load_module(abs) {
|
||||
@@ -173,10 +175,12 @@ pub(crate) fn build_file_view(
|
||||
),
|
||||
};
|
||||
let effective = effective_stdin(&source, stdin_lines);
|
||||
let opts = RunOptions {
|
||||
stdin_lines: effective.clone(),
|
||||
..RunOptions::default()
|
||||
};
|
||||
// Same host caps as `marqdo run`. Soft exit + sleep clamp only.
|
||||
let mut opts = RunOptions::default();
|
||||
opts.stdin_lines = effective.clone();
|
||||
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
|
||||
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
||||
opts.fs_root = Some(root.root.clone());
|
||||
let (stdout, stderr, ok) = match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => (cap.stdout, String::new(), true),
|
||||
Err(e) => (
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
|
||||
for rel_pb in &root.files {
|
||||
let rel = rel_pb.to_string_lossy().replace('\\', "/");
|
||||
let abs = resolve_abs(&root, &rel)?;
|
||||
let mut vm = build_file_view(&abs, &rel, &[])?;
|
||||
let mut vm = build_file_view(&root, &abs, &rel, &[], false)?;
|
||||
if opts.no_exec {
|
||||
vm.stdout.clear();
|
||||
vm.stderr = "execution skipped (--no-exec)".into();
|
||||
|
||||
Reference in new issue
Block a user