Refactor executable library handbooks and improve document reading
This commit is contained in:
1 parent
16c44588d5
commit
c50c515c4a
191 files changed
+29572
-7816
No files matched your search
+1
-1
@@ -138,7 +138,7 @@ pub fn builtin_at(value: &Value, index: &Value) -> Result<Value, String> {
|
||||
Value::Int(n) => *n,
|
||||
_ => return Err("at needs int index".into()),
|
||||
};
|
||||
if i < 0 || (i as usize) >= xs.len() {
|
||||
if i < 0 || i >= xs.len() as i64 {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
Ok(xs[i as usize].clone())
|
||||
|
||||
+157
-69
@@ -19,62 +19,94 @@ use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject};
|
||||
use crate::value::Value;
|
||||
use crate::Backend;
|
||||
|
||||
/// Which host side effects `marqdo call` may perform.
|
||||
/// Explicit effect grants. Writes imply reads; unrelated effects stay denied.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum CallEffects {
|
||||
/// Refuse any non-pure artifact (historical default).
|
||||
#[default]
|
||||
None,
|
||||
/// Allow `plugin.call` (and accompanying `output.write` from load helpers).
|
||||
Plugin,
|
||||
}
|
||||
pub struct CallEffects(u32);
|
||||
|
||||
impl CallEffects {
|
||||
#[allow(non_upper_case_globals)]
|
||||
pub const None: Self = Self(0);
|
||||
#[allow(non_upper_case_globals)]
|
||||
pub const Plugin: Self = Self((1 << 2) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 11));
|
||||
const NAMES: &'static [&'static str] = &[
|
||||
"fs.read",
|
||||
"fs.write",
|
||||
"plugin.call",
|
||||
"network.read",
|
||||
"network.write",
|
||||
"process.exec",
|
||||
"output.write",
|
||||
"time.read",
|
||||
"random.read",
|
||||
"environment.read",
|
||||
"environment.write",
|
||||
"process.control",
|
||||
"user.input",
|
||||
];
|
||||
pub fn parse(s: &str) -> Result<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"none" | "" => Ok(Self::None),
|
||||
"plugin" => Ok(Self::Plugin),
|
||||
other => Err(call_diag(
|
||||
None,
|
||||
0,
|
||||
"call.bad_effects",
|
||||
format!("unknown --effects `{other}` (expected none|plugin)"),
|
||||
)),
|
||||
let mut out = Self::None;
|
||||
for name in s.split(',').map(str::trim) {
|
||||
match name {
|
||||
"none" | "" => {}
|
||||
"plugin" => out.0 |= Self::Plugin.0,
|
||||
"read" => out.0 |= 1,
|
||||
"write" => out.0 |= 3,
|
||||
_ => {
|
||||
let index = Self::NAMES.iter().position(|v| *v == name)
|
||||
.ok_or_else(|| call_diag(None, 0, "call.bad_effects",
|
||||
format!("unknown effect `{name}`; use none, plugin or comma-separated effect names")))?;
|
||||
out.0 |= 1 << index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "none",
|
||||
Self::Plugin => "plugin",
|
||||
if out.0 & (1 << 1) != 0 {
|
||||
out.0 |= 1;
|
||||
}
|
||||
if out.0 & (1 << 4) != 0 {
|
||||
out.0 |= 1 << 3;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
pub fn as_str(self) -> String {
|
||||
if self == Self::None {
|
||||
return "none".into();
|
||||
}
|
||||
if self == Self::Plugin {
|
||||
return "plugin".into();
|
||||
}
|
||||
Self::NAMES
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| self.0 & (1 << i) != 0)
|
||||
.map(|(_, name)| *name)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
/// File/network/process writes must never be repeated to rebuild a handle.
|
||||
pub(crate) fn needs_snapshot(self) -> bool {
|
||||
[
|
||||
"fs.write",
|
||||
"network.write",
|
||||
"process.exec",
|
||||
"environment.write",
|
||||
]
|
||||
.iter()
|
||||
.any(|effect| self.allows(effect))
|
||||
}
|
||||
|
||||
fn host_caps(self) -> HostCaps {
|
||||
match self {
|
||||
Self::None => HostCaps {
|
||||
fs_write: false,
|
||||
exec: false,
|
||||
net: false,
|
||||
plugin: false,
|
||||
},
|
||||
Self::Plugin => HostCaps {
|
||||
fs_write: false,
|
||||
exec: false,
|
||||
net: false,
|
||||
plugin: true,
|
||||
},
|
||||
HostCaps {
|
||||
fs_write: self.allows("fs.write"),
|
||||
exec: self.allows("process.exec"),
|
||||
net: self.allows("network.read") || self.allows("network.write"),
|
||||
plugin: self.allows("plugin.call"),
|
||||
}
|
||||
}
|
||||
|
||||
fn allows(self, effect: &str) -> bool {
|
||||
match self {
|
||||
Self::None => effect == "pure",
|
||||
Self::Plugin => matches!(
|
||||
effect,
|
||||
"pure" | "plugin.call" | "output.write" | "time.read" | "random.read"
|
||||
),
|
||||
}
|
||||
effect == "pure"
|
||||
|| Self::NAMES
|
||||
.iter()
|
||||
.position(|v| *v == effect)
|
||||
.is_some_and(|i| self.0 & (1 << i) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +114,7 @@ impl CallEffects {
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CallOptions {
|
||||
pub effects: CallEffects,
|
||||
pub fs_root: Option<std::path::PathBuf>,
|
||||
pub session: Option<String>,
|
||||
pub toget: Option<String>,
|
||||
}
|
||||
@@ -104,19 +137,16 @@ pub fn call_file_with(
|
||||
backend: Backend,
|
||||
opts: CallOptions,
|
||||
) -> Result<Value> {
|
||||
let path = path
|
||||
.canonicalize()
|
||||
.map_err(|e| {
|
||||
call_diag(
|
||||
None,
|
||||
1,
|
||||
"call.compile",
|
||||
format!("failed to read {}: {e}", path.display()),
|
||||
)
|
||||
})?;
|
||||
let path = path.canonicalize().map_err(|e| {
|
||||
call_diag(
|
||||
None,
|
||||
1,
|
||||
"call.compile",
|
||||
format!("failed to read {}: {e}", path.display()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args)
|
||||
{
|
||||
let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) {
|
||||
let id = opts
|
||||
.session
|
||||
.clone()
|
||||
@@ -135,7 +165,14 @@ pub fn call_file_with(
|
||||
// Record uses original arg texts (with $refs) so replay can re-resolve.
|
||||
let record_args = args.to_vec();
|
||||
|
||||
let value = call_file_raw(&path, function, &resolved, opts.effects, backend)?;
|
||||
let value = call_file_raw_with_root(
|
||||
&path,
|
||||
function,
|
||||
&resolved,
|
||||
opts.effects,
|
||||
backend,
|
||||
opts.fs_root.as_deref(),
|
||||
)?;
|
||||
|
||||
if let Some(ref mut sess) = session {
|
||||
crate::call_session::record_step(
|
||||
@@ -144,6 +181,7 @@ pub fn call_file_with(
|
||||
function,
|
||||
&record_args,
|
||||
opts.effects,
|
||||
opts.fs_root.as_deref(),
|
||||
opts.toget.as_deref(),
|
||||
&value,
|
||||
)?;
|
||||
@@ -160,6 +198,17 @@ pub fn call_file_raw(
|
||||
args: &[(String, Value)],
|
||||
effects: CallEffects,
|
||||
backend: Backend,
|
||||
) -> Result<Value> {
|
||||
call_file_raw_with_root(path, function, args, effects, backend, None)
|
||||
}
|
||||
|
||||
pub(crate) fn call_file_raw_with_root(
|
||||
path: &Path,
|
||||
function: &str,
|
||||
args: &[(String, Value)],
|
||||
effects: CallEffects,
|
||||
backend: Backend,
|
||||
fs_root: Option<&Path>,
|
||||
) -> Result<Value> {
|
||||
let path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
@@ -176,7 +225,7 @@ pub fn call_file_raw(
|
||||
let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?;
|
||||
let artifact = locate_artifact(&compilation.semantics, &path, function)?;
|
||||
deny_unsafe(&path, artifact, effects)?;
|
||||
execute_source_function(
|
||||
execute_source_function_with_root(
|
||||
&path,
|
||||
artifact.source.line,
|
||||
&artifact.display_name,
|
||||
@@ -184,14 +233,14 @@ pub fn call_file_raw(
|
||||
effects.host_caps(),
|
||||
backend,
|
||||
true,
|
||||
fs_root,
|
||||
)
|
||||
.map(|(value, _stdout)| value)
|
||||
}
|
||||
|
||||
fn args_need_session(args: &[(String, Value)]) -> bool {
|
||||
args.iter().any(|(_, v)| {
|
||||
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))
|
||||
})
|
||||
args.iter()
|
||||
.any(|(_, v)| matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')))
|
||||
}
|
||||
|
||||
/// Run the function declared at `line` in `path`.
|
||||
@@ -203,6 +252,28 @@ pub(crate) fn execute_source_function(
|
||||
caps: HostCaps,
|
||||
backend: Backend,
|
||||
strict_args: bool,
|
||||
) -> Result<(Value, String)> {
|
||||
execute_source_function_with_root(
|
||||
path,
|
||||
line,
|
||||
display_name,
|
||||
args,
|
||||
caps,
|
||||
backend,
|
||||
strict_args,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn execute_source_function_with_root(
|
||||
path: &Path,
|
||||
line: u32,
|
||||
display_name: &str,
|
||||
args: &[(String, Value)],
|
||||
caps: HostCaps,
|
||||
backend: Backend,
|
||||
strict_args: bool,
|
||||
fs_root: Option<&Path>,
|
||||
) -> Result<(Value, String)> {
|
||||
let module = load_module(path)?;
|
||||
let fun = find_function_at_line(&module.functions, line).ok_or_else(|| {
|
||||
@@ -225,8 +296,16 @@ pub(crate) fn execute_source_function(
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut interp = Interpreter::with_capture(Some(path), false)
|
||||
.with_host(HostContext::for_capture(Some(path), caps));
|
||||
let mut host = HostContext::for_capture(Some(path), caps);
|
||||
if let Some(root) = fs_root {
|
||||
let root = root.canonicalize()?;
|
||||
if !root.is_dir() {
|
||||
anyhow::bail!("call.fs_root: root must be a directory");
|
||||
}
|
||||
host.cwd = root.clone();
|
||||
host.fs_root = Some(root);
|
||||
}
|
||||
let mut interp = Interpreter::with_capture(Some(path), false).with_host(host);
|
||||
let bound;
|
||||
let invoke_args: &[(String, Value)] = if strict_args {
|
||||
bound = interp.bind_external_args(&module, fun, args)?;
|
||||
@@ -258,8 +337,13 @@ pub(crate) fn execute_source_function(
|
||||
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
|
||||
)
|
||||
})?;
|
||||
let mut vm =
|
||||
Vm::with_capture(Some(path)).with_host(HostContext::for_capture(Some(path), caps));
|
||||
let mut host = HostContext::for_capture(Some(path), caps);
|
||||
if let Some(root) = fs_root {
|
||||
let root = root.canonicalize()?;
|
||||
host.cwd = root.clone();
|
||||
host.fs_root = Some(root);
|
||||
}
|
||||
let mut vm = Vm::with_capture(Some(path)).with_host(host);
|
||||
let value = vm.call_function(&program, idx, invoke_args)?;
|
||||
Ok((value, vm.captured_stdout))
|
||||
}
|
||||
@@ -308,7 +392,12 @@ pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
|
||||
));
|
||||
}
|
||||
let value = parse_literal(raw).map_err(|message| {
|
||||
call_diag(None, 0, "call.bad_value", format!("参数 `{name}`: {message}"))
|
||||
call_diag(
|
||||
None,
|
||||
0,
|
||||
"call.bad_value",
|
||||
format!("参数 `{name}`: {message}"),
|
||||
)
|
||||
})?;
|
||||
out.push((name.to_string(), value));
|
||||
}
|
||||
@@ -356,8 +445,7 @@ fn locate_artifact<'a>(
|
||||
.copied()
|
||||
.filter(|artifact| {
|
||||
artifact.kind == "function"
|
||||
&& (artifact.display_name.ends_with(&suffix)
|
||||
|| artifact.display_name == query)
|
||||
&& (artifact.display_name.ends_with(&suffix) || artifact.display_name == query)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
+91
-22
@@ -35,6 +35,10 @@ pub struct CallStep {
|
||||
pub function: String,
|
||||
pub args: BTreeMap<String, serde_json::Value>,
|
||||
pub effects: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub result: Option<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fs_root: Option<PathBuf>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub toget: Option<String>,
|
||||
}
|
||||
@@ -97,18 +101,22 @@ pub fn resolve_args(
|
||||
live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?);
|
||||
}
|
||||
let needs_replay = args.iter().any(|(_, v)| {
|
||||
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))
|
||||
&& {
|
||||
let name = v_text_ref(v);
|
||||
session.journal_bindings.contains_key(name)
|
||||
|| (!session.bindings.contains_key(name)
|
||||
&& session.steps.iter().any(|s| s.toget.as_deref() == Some(name)))
|
||||
}
|
||||
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) && {
|
||||
let name = v_text_ref(v);
|
||||
session.journal_bindings.contains_key(name)
|
||||
|| (!session.bindings.contains_key(name)
|
||||
&& session
|
||||
.steps
|
||||
.iter()
|
||||
.any(|s| s.toget.as_deref() == Some(name)))
|
||||
}
|
||||
});
|
||||
if needs_replay || args.iter().any(|(_, v)| {
|
||||
matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@'))
|
||||
if needs_replay
|
||||
|| args.iter().any(|(_, v)| {
|
||||
matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@'))
|
||||
&& session.journal_bindings.contains_key(&t[1..]))
|
||||
}) {
|
||||
})
|
||||
{
|
||||
live = replay_live(session, backend)?;
|
||||
}
|
||||
let mut out = Vec::with_capacity(args.len());
|
||||
@@ -150,9 +158,12 @@ fn resolve_one(
|
||||
}
|
||||
// Last resort: full replay
|
||||
let live = replay_live(session, backend)?;
|
||||
live.get(key)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("call.session_unbound: `${key}` not in session {}", session.session))
|
||||
live.get(key).cloned().ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"call.session_unbound: `${key}` not in session {}",
|
||||
session.session
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn replay_live(session: &CallSession, backend: Backend) -> Result<BTreeMap<String, Value>> {
|
||||
@@ -179,13 +190,20 @@ fn replay_live(session: &CallSession, backend: Backend) -> Result<BTreeMap<Strin
|
||||
args.push((k.clone(), val));
|
||||
}
|
||||
let effects = CallEffects::parse(&step.effects)?;
|
||||
let value = call::call_file_raw(
|
||||
Path::new(&step.file),
|
||||
&step.function,
|
||||
&args,
|
||||
effects,
|
||||
backend,
|
||||
)?;
|
||||
let value = if effects.needs_snapshot() {
|
||||
let result = step.result.as_ref().ok_or_else(|| anyhow::anyhow!(
|
||||
"call.session_replay: effectful step has no durable result; refusing to repeat {}", step.effects))?;
|
||||
json_to_value(result).map_err(|e| anyhow::anyhow!(e))?
|
||||
} else {
|
||||
call::call_file_raw_with_root(
|
||||
Path::new(&step.file),
|
||||
&step.function,
|
||||
&args,
|
||||
effects,
|
||||
backend,
|
||||
step.fs_root.as_deref(),
|
||||
)?
|
||||
};
|
||||
if let Some(name) = &step.toget {
|
||||
live.insert(name.clone(), value);
|
||||
}
|
||||
@@ -199,6 +217,7 @@ pub fn record_step(
|
||||
function: &str,
|
||||
args: &[(String, Value)],
|
||||
effects: CallEffects,
|
||||
fs_root: Option<&Path>,
|
||||
toget: Option<&str>,
|
||||
result: &Value,
|
||||
) -> Result<()> {
|
||||
@@ -229,7 +248,13 @@ pub fn record_step(
|
||||
file: file_s,
|
||||
function: function.to_string(),
|
||||
args: arg_map,
|
||||
effects: effects.as_str().to_string(),
|
||||
effects: effects.as_str(),
|
||||
result: if is_json_friendly(result) {
|
||||
value_to_json(result).ok()
|
||||
} else {
|
||||
None
|
||||
},
|
||||
fs_root: fs_root.map(|p| p.canonicalize()).transpose()?,
|
||||
toget: toget.map(|s| s.to_string()),
|
||||
};
|
||||
session.steps.push(step);
|
||||
@@ -267,7 +292,8 @@ fn is_json_friendly(v: &Value) -> bool {
|
||||
|
||||
/// Dump journal steps as a minimal Marqdo script for later `marqdo run`.
|
||||
pub fn dump_replay_script(session: &CallSession) -> String {
|
||||
let mut out = String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n");
|
||||
let mut out =
|
||||
String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n");
|
||||
for (i, step) in session.steps.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"> print text=\"step {i}: call {} {} effects={}\"\n",
|
||||
@@ -284,3 +310,46 @@ pub fn dump_replay_script(session: &CallSession) -> String {
|
||||
pub fn default_session_id() -> String {
|
||||
std::env::var("MARQDO_CALL_SESSION").unwrap_or_else(|_| "default".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod write_snapshot_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn replay_uses_durable_write_results_instead_of_repeating_io() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-write-replay-{}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("log.txt"), "once").unwrap();
|
||||
for backend in [Backend::Tree, Backend::Bytecode] {
|
||||
let step = CallStep {
|
||||
file: Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("lib/fs.mq.md")
|
||||
.to_string_lossy()
|
||||
.into(),
|
||||
function: "append_text".into(),
|
||||
args: BTreeMap::from([
|
||||
("path".into(), serde_json::json!("log.txt")),
|
||||
("text".into(), serde_json::json!("once")),
|
||||
]),
|
||||
effects: "fs.write".into(),
|
||||
result: Some(serde_json::Value::Null),
|
||||
fs_root: Some(dir.clone()),
|
||||
toget: Some("written".into()),
|
||||
};
|
||||
let mut session = CallSession {
|
||||
steps: vec![step],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
replay_live(&session, backend).unwrap()["written"],
|
||||
Value::None
|
||||
);
|
||||
assert_eq!(fs::read_to_string(dir.join("log.txt")).unwrap(), "once");
|
||||
session.steps[0].result = None;
|
||||
assert!(replay_live(&session, backend)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("refusing to repeat"));
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
+29
-2
@@ -22,6 +22,9 @@ pub const CATALOG: &[ExtPackage] = &[
|
||||
id: "llm",
|
||||
description: "OpenAI-compatible chat object (ext/ai/llm)",
|
||||
mq_files: &[
|
||||
"ai/index.mq.md",
|
||||
"ai/索引.mq.md",
|
||||
"ai/llm/index.mq.md",
|
||||
"ai/llm.mq.md",
|
||||
"ai/大模型.mq.md",
|
||||
"ai/llm/openai.mq.md",
|
||||
@@ -32,13 +35,32 @@ pub const CATALOG: &[ExtPackage] = &[
|
||||
ExtPackage {
|
||||
id: "agent",
|
||||
description: "Agent development framework (ext/ai/agent)",
|
||||
mq_files: &["ai/agent.mq.md", "ai/智能体.mq.md"],
|
||||
mq_files: &[
|
||||
"ai/agent.mq.md",
|
||||
"ai/智能体.mq.md",
|
||||
"ai/sandbox.mq.md",
|
||||
"ai/沙盒.mq.md",
|
||||
"ai/policies/step-route.mq.md",
|
||||
],
|
||||
native_crate: Some("marqdo_plugin_agent"),
|
||||
},
|
||||
ExtPackage {
|
||||
id: "web",
|
||||
description: "Dynamic website toolkit (ext/web) — Document/Endpoint + layout skill",
|
||||
mq_files: &[
|
||||
"data/index.mq.md",
|
||||
"data/cache.mq.md",
|
||||
"data/db.mq.md",
|
||||
"data/form.mq.md",
|
||||
"data/storage.mq.md",
|
||||
"security/index.mq.md",
|
||||
"security/auth.mq.md",
|
||||
"security/rbac.mq.md",
|
||||
"security/oidc.mq.md",
|
||||
"net/index.mq.md",
|
||||
"net/http.mq.md",
|
||||
"net/url.mq.md",
|
||||
"net/websocket.mq.md",
|
||||
"web/index.mq.md",
|
||||
"web/web.mq.md",
|
||||
"web/网页.mq.md",
|
||||
@@ -86,7 +108,12 @@ pub const CATALOG: &[ExtPackage] = &[
|
||||
ExtPackage {
|
||||
id: "linalg",
|
||||
description: "Formula-first linear algebra (ext/linalg) — MatExpr simplify/display",
|
||||
mq_files: &["linalg/linalg.mq.md", "linalg/线性代数.mq.md"],
|
||||
mq_files: &[
|
||||
"linalg/index.mq.md",
|
||||
"linalg/索引.mq.md",
|
||||
"linalg/linalg.mq.md",
|
||||
"linalg/线性代数.mq.md",
|
||||
],
|
||||
native_crate: Some("marqdo_plugin_linalg"),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Optional ZIP tasks with preflight, expansion limits and no path traversal.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = operate(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("ZIP unavailable: build with net-host (native default)".into())
|
||||
};
|
||||
Ok(super::result::capture(
|
||||
if id == HostFn::ZipPack {
|
||||
"archive.pack"
|
||||
} else {
|
||||
"archive.unpack"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn operate(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("ZIP unavailable in CoW sandbox".into());
|
||||
}
|
||||
let src = ctx.resolve_path(super::as_text(arg(b, "src")?, "src")?)?;
|
||||
let dest = ctx.resolve_path(super::as_text(arg(b, "dest")?, "dest")?)?;
|
||||
let max = match arg(b, "max_bytes")? {
|
||||
Value::Int(n) if *n > 0 && *n <= 1024 * 1024 * 1024 => *n as u64,
|
||||
_ => return Err("max_bytes must be 1..1073741824".into()),
|
||||
};
|
||||
if dest.exists() {
|
||||
return Err("destination conflict: ZIP output must not exist".into());
|
||||
}
|
||||
if id == HostFn::ZipPack {
|
||||
if !src.is_dir() || dest.starts_with(&src) {
|
||||
return Err("pack src must be directory and dest outside src".into());
|
||||
}
|
||||
let mut args = HashMap::new();
|
||||
args.insert("path".into(), Value::Text(src.to_string_lossy().into()));
|
||||
args.insert("pattern".into(), Value::Text("**".into()));
|
||||
args.insert("exclude".into(), Value::None);
|
||||
args.insert("max_depth".into(), Value::Int(256));
|
||||
args.insert("kind".into(), Value::Text("file".into()));
|
||||
let Value::List(files) = super::fs_ops::call(ctx, HostFn::FsFind, &args)? else {
|
||||
unreachable!()
|
||||
};
|
||||
let total = files.iter().try_fold(0u64, |n, name| {
|
||||
let p = src.join(super::as_text(name, "name")?);
|
||||
let size = fs::metadata(p).map_err(|e| e.to_string())?.len();
|
||||
n.checked_add(size)
|
||||
.ok_or_else(|| "archive size overflow".to_string())
|
||||
})?;
|
||||
if total > max {
|
||||
return Err("archive source exceeds max_bytes".into());
|
||||
}
|
||||
let parent = dest.parent().ok_or("archive needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let temp = parent.join(format!(".mq-zip-{}", random_name()?));
|
||||
let file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let written = (|| {
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let mut buffer = [0u8; 65536];
|
||||
let mut seen = 0u64;
|
||||
for name in &files {
|
||||
let name = super::as_text(name, "name")?;
|
||||
writer
|
||||
.start_file(
|
||||
name,
|
||||
zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated),
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let p = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let mut file = fs::File::open(p).map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = file.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
seen += n as u64;
|
||||
if seen > max {
|
||||
return Err("archive source grew past max_bytes".into());
|
||||
}
|
||||
writer.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
writer
|
||||
.finish()
|
||||
.map_err(|e| e.to_string())?
|
||||
.sync_all()
|
||||
.map_err(|e| e.to_string())?;
|
||||
// hard_link is an atomic no-clobber publish on the same filesystem.
|
||||
fs::hard_link(&temp, &dest).map_err(|e| e.to_string())?;
|
||||
Ok(Value::Int(files.len() as i64))
|
||||
})();
|
||||
let _ = fs::remove_file(&temp);
|
||||
return written;
|
||||
}
|
||||
let file = fs::File::open(src).map_err(|e| e.to_string())?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
if zip.len() > 100000 {
|
||||
return Err("archive exceeds 100000 entries".into());
|
||||
}
|
||||
let mut names = HashSet::new();
|
||||
let mut total = 0u64;
|
||||
for i in 0..zip.len() {
|
||||
let entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let name = entry
|
||||
.enclosed_name()
|
||||
.ok_or("archive path escapes destination")?;
|
||||
if entry.name().contains('\\') || name == Path::new("") || !names.insert(name.to_path_buf())
|
||||
{
|
||||
return Err("invalid or duplicate archive path".into());
|
||||
}
|
||||
if entry
|
||||
.unix_mode()
|
||||
.is_some_and(|mode| mode & 0o170000 == 0o120000)
|
||||
{
|
||||
return Err("archive symlinks unsupported".into());
|
||||
}
|
||||
total = total
|
||||
.checked_add(entry.size())
|
||||
.ok_or("archive size overflow")?;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(dest.parent().ok_or("destination needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
fs::create_dir(&dest).map_err(|e| e.to_string())?;
|
||||
let extracted = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let path = ctx.resolve_path(
|
||||
dest.join(entry.enclosed_name().ok_or("invalid archive path")?)
|
||||
.to_str()
|
||||
.ok_or("non UTF-8 path")?,
|
||||
)?;
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(path).map_err(|e| e.to_string())?;
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(path.parent().ok_or("entry needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = entry.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Int(zip.len() as i64))
|
||||
})();
|
||||
if extracted.is_err() {
|
||||
let _ = fs::remove_dir_all(&dest);
|
||||
}
|
||||
extracted
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn random_name() -> Result<String, String> {
|
||||
let mut bytes = [0u8; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?;
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
+61
-17
@@ -16,7 +16,7 @@ fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
|
||||
if *n < 1 {
|
||||
return Err("put path index must be >= 1 (1-based)".into());
|
||||
}
|
||||
Ok(vec![PathSeg::Index1(*n as usize)])
|
||||
Ok(vec![PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)])
|
||||
}
|
||||
Value::List(xs) => {
|
||||
if xs.is_empty() {
|
||||
@@ -32,7 +32,7 @@ fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
|
||||
"put path segment {i}: index must be >= 1 (1-based)"
|
||||
));
|
||||
}
|
||||
out.push(PathSeg::Index1(*n as usize));
|
||||
out.push(PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
@@ -284,7 +284,7 @@ pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result<Value, Stri
|
||||
Value::None => vec![],
|
||||
_ => return Err("list_insert needs list".into()),
|
||||
};
|
||||
if index < 0 || index as usize > xs.len() {
|
||||
if index < 0 || index > xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_insert index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -298,7 +298,7 @@ pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result<Value, Stri
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_set_at needs list".into());
|
||||
};
|
||||
if index < 0 || index as usize >= xs.len() {
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_set_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -313,7 +313,7 @@ pub fn list_remove_at(list: &Value, index: i64) -> Result<Value, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_remove_at needs list".into());
|
||||
};
|
||||
if index < 0 || index as usize >= xs.len() {
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_remove_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -385,16 +385,33 @@ pub fn list_last(list: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
/// Total type order avoids cyclic comparisons between numeric and text keys.
|
||||
pub(super) fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering;
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => x.cmp(y),
|
||||
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Int(x), Value::Num(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Num(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal),
|
||||
(Value::Text(x), Value::Text(y)) => x.cmp(y),
|
||||
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
|
||||
_ => a.as_display().cmp(&b.as_display()),
|
||||
fn rank(v:&Value)->u8{match v{
|
||||
Value::Int(_)|Value::Num(_)=>0,Value::Text(_)=>1,Value::Bool(_)=>2,
|
||||
Value::None=>3,Value::List(_)=>4,Value::Map(_)=>5,Value::Formula(_)=>6,
|
||||
Value::Code(_)=>7,Value::Secret(_)=>8,Value::Handle(_)=>9,
|
||||
}}
|
||||
fn int_float(integer:i64,number:f64)->Ordering{
|
||||
if number.is_nan(){return Ordering::Less}
|
||||
if number >= -(i64::MIN as f64){return Ordering::Less}
|
||||
if number < i64::MIN as f64{return Ordering::Greater}
|
||||
let truncated=number as i64;
|
||||
match integer.cmp(&truncated){Ordering::Equal=>0.0f64.partial_cmp(&number.fract()).unwrap_or(Ordering::Equal),other=>other}
|
||||
}
|
||||
let order=rank(a).cmp(&rank(b));if !order.is_eq(){return order}
|
||||
match (a,b){
|
||||
(Value::Int(a),Value::Int(b))=>a.cmp(b),
|
||||
(Value::Num(a),Value::Num(b))=>match(a.is_nan(),b.is_nan()){
|
||||
(true,false)=>Ordering::Greater,(false,true)=>Ordering::Less,
|
||||
_=>a.partial_cmp(b).unwrap_or_else(||a.total_cmp(b)),
|
||||
},
|
||||
(Value::Int(a),Value::Num(b))=>int_float(*a,*b),
|
||||
(Value::Num(a),Value::Int(b))=>int_float(*b,*a).reverse(),
|
||||
(Value::Text(a),Value::Text(b))=>a.cmp(b),
|
||||
(Value::Bool(a),Value::Bool(b))=>a.cmp(b),
|
||||
_=>a.as_display().cmp(&b.as_display()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,9 +464,12 @@ pub fn list_sort_by(list: &Value, key: &Value) -> Result<Value, String> {
|
||||
pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut seen: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
|
||||
for x in xs {
|
||||
if !out.iter().any(|y| y == x) {
|
||||
let bucket = seen.entry(super::collection_ops::fingerprint(x)).or_default();
|
||||
if !bucket.iter().any(|i| out[*i] == *x) {
|
||||
bucket.push(out.len());
|
||||
out.push(x.clone());
|
||||
}
|
||||
}
|
||||
@@ -462,7 +482,7 @@ pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
|
||||
pub fn list_chunk(list: &Value, size: &Value) -> Result<Value, String> {
|
||||
let n = match size {
|
||||
Value::Int(i) if *i > 0 => *i as usize,
|
||||
Value::Int(i) if *i > 0 => usize::try_from(*i).unwrap_or(usize::MAX),
|
||||
Value::Int(_) => return Err("chunk size must be positive".into()),
|
||||
_ => return Err("chunk size needs int".into()),
|
||||
};
|
||||
@@ -570,3 +590,27 @@ mod tests {
|
||||
assert!(matches!(m, Value::Map(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod task_scale_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unique_preserves_signed_zero_nan_and_nested_equality(){
|
||||
let xs=Value::List(vec![Value::Num(-0.0),Value::Num(0.0),Value::Num(f64::NAN),Value::Num(f64::NAN),Value::Int(0),Value::List(vec![Value::Num(-0.0)]),Value::List(vec![Value::Num(0.0)])]);
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};
|
||||
assert_eq!(out.len(),5);assert_eq!(out[0],Value::Num(-0.0));assert_eq!(out[3],Value::Int(0));
|
||||
}
|
||||
#[test]
|
||||
fn mixed_order_is_transitive_and_exact_at_integer_float_boundary(){
|
||||
let values=[Value::Int(2),Value::Int(10),Value::Text("11".into()),Value::Int(i64::MAX),Value::Num(i64::MAX as f64),Value::Num(f64::NAN),Value::Num(-0.0),Value::Bool(false),Value::None];
|
||||
for a in &values{for b in &values{for c in &values{
|
||||
if cmp_value(a,b).is_le()&&cmp_value(b,c).is_le(){assert!(cmp_value(a,c).is_le(),"{a:?} {b:?} {c:?}");}
|
||||
}}}
|
||||
assert!(cmp_value(&Value::Int(i64::MAX),&Value::Num(i64::MAX as f64)).is_lt());
|
||||
}
|
||||
#[test]
|
||||
fn bulk_unique_handles_one_hundred_thousand_values(){
|
||||
let xs=Value::List((0..100_000).map(|n|Value::Int(n%50_000)).collect());
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};assert_eq!(out.len(),50_000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
//! Field-driven collection transforms. No string evaluation or callback language.
|
||||
use super::{as_text, collection::cmp_value};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn list(v: &Value) -> Result<&[Value], String> {
|
||||
match v {
|
||||
Value::List(xs) => Ok(xs),
|
||||
_ => Err("expected list".into()),
|
||||
}
|
||||
}
|
||||
fn record(v: &Value) -> Result<&[(String, Value)], String> {
|
||||
match v {
|
||||
Value::Map(m) => Ok(m),
|
||||
_ => Err("expected record map".into()),
|
||||
}
|
||||
}
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
record(v)?
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| format!("missing field {key}"))
|
||||
}
|
||||
fn strings(v: &Value) -> Result<Vec<String>, String> {
|
||||
list(v)?
|
||||
.iter()
|
||||
.map(|v| as_text(v, "key").map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
fn integer(v: &Value) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err("expected integer".into()),
|
||||
}
|
||||
}
|
||||
fn number(v: &Value) -> Result<f64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n as f64),
|
||||
Value::Num(n) if n.is_finite() => Ok(*n),
|
||||
_ => Err("expected finite number".into()),
|
||||
}
|
||||
}
|
||||
fn row(fields: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
// Structural equality is type-sensitive and map-order-sensitive, like Value::eq.
|
||||
// Fingerprints accelerate buckets; equality is still checked inside each bucket.
|
||||
pub(super) fn fingerprint(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Num(n) if *n == 0.0 => "Num(0)".into(),
|
||||
Value::List(xs) => format!("List{:?}", xs.iter().map(fingerprint).collect::<Vec<_>>()),
|
||||
Value::Map(xs) => format!(
|
||||
"Map{:?}",
|
||||
xs.iter()
|
||||
.map(|(k, v)| (k, fingerprint(v)))
|
||||
.collect::<Vec<_>>()
|
||||
),
|
||||
Value::Formula(formula) => format!("Formula{}", formula.as_display()),
|
||||
_ => format!("{v:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::ListRange => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let end = integer(arg(b, "end")?)?;
|
||||
let step = integer(arg(b, "step")?)?;
|
||||
if step == 0 {
|
||||
return Err("range step cannot be zero".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut n = start;
|
||||
while if step > 0 { n < end } else { n > end } {
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("range exceeds 1000000 items".into());
|
||||
}
|
||||
out.push(Value::Int(n));
|
||||
match n.checked_add(step) {
|
||||
Some(next) => n = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListEnumerate => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
let index = start
|
||||
.checked_add(i as i64)
|
||||
.ok_or("enumerate index overflow")?;
|
||||
Ok(row(vec![
|
||||
("index", Value::Int(index)),
|
||||
("value", v.clone()),
|
||||
]))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListPluck => {
|
||||
let key = text(b, "key")?;
|
||||
Ok(Value::List(
|
||||
list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| field(v, key).cloned())
|
||||
.collect::<Result<_, _>>()?,
|
||||
))
|
||||
}
|
||||
HostFn::ListProject => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
if keys.iter().collect::<HashSet<_>>().len() != keys.len() {
|
||||
return Err("project keys must be unique".into());
|
||||
}
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| {
|
||||
keys.iter()
|
||||
.map(|k| Ok((k.clone(), field(v, k)?.clone())))
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
.map(Value::Map)
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListWhere => {
|
||||
let key = text(b, "key")?;
|
||||
let op = text(b, "op")?;
|
||||
let wanted = arg(b, "value")?;
|
||||
if !matches!(
|
||||
op,
|
||||
"eq" | "ne" | "gt" | "ge" | "lt" | "le" | "contains" | "in"
|
||||
) {
|
||||
return Err(format!("unknown where operator {op}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let got = field(v, key)?;
|
||||
let yes = match op {
|
||||
"eq" => got == wanted,
|
||||
"ne" => got != wanted,
|
||||
"gt" | "ge" | "lt" | "le" => {
|
||||
let order = match (got, wanted) {
|
||||
(Value::Text(a), Value::Text(b)) => a.cmp(b),
|
||||
_ => number(got)?
|
||||
.partial_cmp(&number(wanted)?)
|
||||
.ok_or("unordered comparison")?,
|
||||
};
|
||||
match op {
|
||||
"gt" => order.is_gt(),
|
||||
"ge" => order.is_ge(),
|
||||
"lt" => order.is_lt(),
|
||||
_ => order.is_le(),
|
||||
}
|
||||
}
|
||||
"contains" => match got {
|
||||
Value::List(xs) => xs.contains(wanted),
|
||||
Value::Text(s) => s.contains(as_text(wanted, "value")?),
|
||||
_ => return Err("contains needs text or list".into()),
|
||||
},
|
||||
"in" => list(wanted)?.contains(got),
|
||||
_ => return Err(format!("unknown where operator {op}")),
|
||||
};
|
||||
if yes {
|
||||
out.push(v.clone())
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListGroupBy | HostFn::ListUniqueBy => {
|
||||
let key = text(b, "key")?;
|
||||
let mut groups: Vec<(Value, Vec<Value>)> = Vec::new();
|
||||
let mut index: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let k = field(v, key)?;
|
||||
let fp = fingerprint(k);
|
||||
let bucket = index.entry(fp).or_default();
|
||||
if let Some(i) = bucket.iter().find(|i| groups[**i].0 == *k) {
|
||||
groups[*i].1.push(v.clone());
|
||||
} else {
|
||||
bucket.push(groups.len());
|
||||
groups.push((k.clone(), vec![v.clone()]));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
groups
|
||||
.into_iter()
|
||||
.map(|(key, rows)| {
|
||||
if id == HostFn::ListUniqueBy {
|
||||
rows.into_iter().next().unwrap()
|
||||
} else {
|
||||
row(vec![
|
||||
("key", key),
|
||||
("count", Value::Int(rows.len() as i64)),
|
||||
("rows", Value::List(rows)),
|
||||
])
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListAggregate => {
|
||||
let xs = list(arg(b, "list")?)?;
|
||||
let op = text(b, "op")?;
|
||||
if op == "count" {
|
||||
return Ok(Value::Int(xs.len() as i64));
|
||||
}
|
||||
let key = arg(b, "key")?;
|
||||
let values = xs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
if matches!(key, Value::None) {
|
||||
Ok(v)
|
||||
} else {
|
||||
field(v, as_text(key, "key")?)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
if op == "sum" && values.iter().all(|v| matches!(v, Value::Int(_))) {
|
||||
let sum = values.into_iter().try_fold(0i64, |sum, v| {
|
||||
sum.checked_add(integer(v)?)
|
||||
.ok_or_else(|| "sum integer overflow".to_string())
|
||||
})?;
|
||||
return Ok(Value::Int(sum));
|
||||
}
|
||||
let nums = values
|
||||
.into_iter()
|
||||
.map(number)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let n = match op {
|
||||
"sum" => nums.iter().sum(),
|
||||
"mean" if !nums.is_empty() => nums.iter().sum::<f64>() / nums.len() as f64,
|
||||
"min" if !nums.is_empty() => nums.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
"max" if !nums.is_empty() => nums.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
_ => {
|
||||
return Err(
|
||||
"aggregate needs sum/count/min/max/mean; empty min/max/mean is invalid"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("aggregate overflow".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
HostFn::ListSortKeys => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
let descending = matches!(arg(b, "descending")?, Value::Bool(true));
|
||||
let mut xs = list(arg(b, "list")?)?.to_vec();
|
||||
for v in &xs {
|
||||
for k in &keys {
|
||||
field(v, k)?;
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| {
|
||||
let mut order = std::cmp::Ordering::Equal;
|
||||
for k in &keys {
|
||||
order = cmp_value(field(a, k).unwrap(), field(b, k).unwrap());
|
||||
if !order.is_eq() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if descending {
|
||||
order.reverse()
|
||||
} else {
|
||||
order
|
||||
}
|
||||
});
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
HostFn::ListRename => {
|
||||
let names = record(arg(b, "fields")?)?;
|
||||
for (_, v) in names {
|
||||
as_text(v, "new field name")?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let mut seen = HashSet::new();
|
||||
let mut fields = Vec::new();
|
||||
for (k, v) in record(v)? {
|
||||
let name = names
|
||||
.iter()
|
||||
.find(|(old, _)| old == k)
|
||||
.map(|(_, v)| as_text(v, "name").unwrap())
|
||||
.unwrap_or(k);
|
||||
if !seen.insert(name) {
|
||||
return Err(format!("rename conflict: {name}"));
|
||||
}
|
||||
fields.push((name.into(), v.clone()));
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableFromColumns => {
|
||||
let columns = record(arg(b, "columns")?)?;
|
||||
let n = columns
|
||||
.first()
|
||||
.map(|(_, v)| list(v).map(|xs| xs.len()))
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
for (_, v) in columns {
|
||||
if list(v)?.len() != n {
|
||||
return Err("column lengths differ".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
Value::Map(
|
||||
columns
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), list(v).unwrap()[i].clone()))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::TableToColumns => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
if rows.is_empty() {
|
||||
return Ok(Value::Map(vec![]));
|
||||
}
|
||||
let keys: Vec<_> = record(&rows[0])?.iter().map(|(k, _)| k.clone()).collect();
|
||||
for v in rows {
|
||||
let fields = record(v)?;
|
||||
if fields.len() != keys.len()
|
||||
|| keys.iter().any(|k| !fields.iter().any(|(f, _)| f == k))
|
||||
{
|
||||
return Err("rows have different fields".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(
|
||||
keys.into_iter()
|
||||
.map(|k| {
|
||||
let values = rows.iter().map(|v| field(v, &k).unwrap().clone()).collect();
|
||||
(k, Value::List(values))
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListJoin => {
|
||||
let a = list(arg(b, "a")?)?;
|
||||
let b_rows = list(arg(b, "b")?)?;
|
||||
let key = text(b, "key")?;
|
||||
let right_key = text(b, "right_key")?;
|
||||
let mode = text(b, "mode")?;
|
||||
if !matches!(mode, "inner" | "left") {
|
||||
return Err("join mode must be inner or left".into());
|
||||
}
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in b_rows {
|
||||
index
|
||||
.entry(fingerprint(field(v, right_key)?))
|
||||
.or_default()
|
||||
.push(v);
|
||||
}
|
||||
let right_fields: Vec<_> = b_rows
|
||||
.first()
|
||||
.map(|v| record(v).map(|m| m.iter().map(|(k, _)| k.clone()).collect()))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
for right in b_rows {
|
||||
let fields = record(right)?;
|
||||
if fields.len() != right_fields.len()
|
||||
|| right_fields
|
||||
.iter()
|
||||
.any(|key| !fields.iter().any(|(k, _)| k == key))
|
||||
{
|
||||
return Err("join right rows have different fields".into());
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for left in a {
|
||||
let left_key = field(left, key)?;
|
||||
let hits = index.get(&fingerprint(left_key));
|
||||
let matches: Vec<Option<&Value>> = match hits {
|
||||
Some(h) => {
|
||||
let values: Vec<_> = h
|
||||
.iter()
|
||||
.filter(|v| field(v, right_key).is_ok_and(|key| key == left_key))
|
||||
.map(|v| Some(*v))
|
||||
.collect();
|
||||
if values.is_empty() && mode == "left" {
|
||||
vec![None]
|
||||
} else {
|
||||
values
|
||||
}
|
||||
}
|
||||
None if mode == "left" => vec![None],
|
||||
_ => vec![],
|
||||
};
|
||||
for hit in matches {
|
||||
let mut fields = record(left)?.to_vec();
|
||||
let source = hit.map(record).transpose()?;
|
||||
for k in &right_fields {
|
||||
if k == right_key && key == right_key {
|
||||
continue;
|
||||
}
|
||||
let name = if fields.iter().any(|(f, _)| f == k) {
|
||||
format!("right_{k}")
|
||||
} else {
|
||||
k.clone()
|
||||
};
|
||||
if fields.iter().any(|(f, _)| f == &name) {
|
||||
return Err(format!("join field conflict: {name}"));
|
||||
}
|
||||
let value = source
|
||||
.and_then(|m| m.iter().find(|(f, _)| f == k))
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None);
|
||||
fields.push((name, value));
|
||||
}
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("join exceeds 1000000 rows".into());
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableCast => {
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut out = Vec::new();
|
||||
for (i, v) in list(arg(b, "rows")?)?.iter().enumerate() {
|
||||
let mut fields = record(v)?.to_vec();
|
||||
for (k, ty) in schema {
|
||||
let value = field(v, k)?;
|
||||
let ty = as_text(ty, "type")?;
|
||||
let cast = cast(value, ty).map_err(|e| format!("row {i} field {k}: {e}"))?;
|
||||
fields.iter_mut().find(|(name, _)| name == k).unwrap().1 = cast;
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableSummarize => {
|
||||
let groups = call(_ctx, HostFn::ListGroupBy, b)?;
|
||||
let field_name = text(b, "field")?;
|
||||
let op = text(b, "op")?;
|
||||
let mut out = Vec::new();
|
||||
for group in list(&groups)? {
|
||||
let rows = field(group, "rows")?;
|
||||
let mut args = HashMap::new();
|
||||
args.insert("list".into(), rows.clone());
|
||||
args.insert("key".into(), Value::Text(field_name.into()));
|
||||
args.insert("op".into(), Value::Text(op.into()));
|
||||
let value = call(_ctx, HostFn::ListAggregate, &args)?;
|
||||
out.push(row(vec![
|
||||
("key", field(group, "key")?.clone()),
|
||||
("count", field(group, "count")?.clone()),
|
||||
("value", value),
|
||||
]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableTryCast => {
|
||||
let answer =
|
||||
call(_ctx, HostFn::TableCast, b).map_err(|e| format!("validation_failed: {e}"));
|
||||
Ok(super::result::capture("table.cast", answer))
|
||||
}
|
||||
HostFn::TableValidate => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut errors = Vec::new();
|
||||
for (index, value) in rows.iter().enumerate() {
|
||||
let fields = record(value)?;
|
||||
for (key, ty) in schema {
|
||||
let name = as_text(ty, "type")?;
|
||||
let ty = crate::contract::Ty::parse(name);
|
||||
let got = fields.iter().find(|(k, _)| k == key).map(|(_, v)| v);
|
||||
if !got.is_some_and(|v| ty.matches_value(v)) {
|
||||
errors.push(row(vec![
|
||||
("row", Value::Int(index as i64)),
|
||||
("field", Value::Text(key.clone())),
|
||||
("expected", Value::Text(name.into())),
|
||||
(
|
||||
"actual",
|
||||
Value::Text(
|
||||
got.map(crate::contract::type_of)
|
||||
.unwrap_or("missing")
|
||||
.into(),
|
||||
),
|
||||
),
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(super::result::capture(
|
||||
"table.validate",
|
||||
Ok(arg(b, "rows")?.clone()),
|
||||
))
|
||||
} else {
|
||||
let mut result = super::result::capture(
|
||||
"table.validate",
|
||||
Err("validation_failed: records do not match schema".into()),
|
||||
);
|
||||
if let Value::Map(fields) = &mut result {
|
||||
if let Some((_, Value::Map(error))) =
|
||||
fields.iter_mut().find(|(k, _)| k == "error")
|
||||
{
|
||||
error.push(("details".into(), Value::List(errors)));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
HostFn::ListUnion | HostFn::ListIntersection | HostFn::ListDifference => {
|
||||
let left = list(arg(b, "a")?)?;
|
||||
let right = list(arg(b, "b")?)?;
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in right {
|
||||
index.entry(fingerprint(v)).or_default().push(v)
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
for v in left {
|
||||
let contains = index
|
||||
.get(&fingerprint(v))
|
||||
.is_some_and(|bucket| bucket.iter().any(|r| *r == v));
|
||||
if id == HostFn::ListUnion
|
||||
|| (id == HostFn::ListIntersection && contains)
|
||||
|| (id == HostFn::ListDifference && !contains)
|
||||
{
|
||||
values.push(v.clone())
|
||||
}
|
||||
}
|
||||
if id == HostFn::ListUnion {
|
||||
values.extend_from_slice(right)
|
||||
}
|
||||
super::collection::list_unique(&Value::List(values))
|
||||
}
|
||||
_ => Err("not a collection transform".into()),
|
||||
}
|
||||
}
|
||||
fn cast(v: &Value, ty: &str) -> Result<Value, String> {
|
||||
match ty {
|
||||
"text" => Ok(Value::Text(v.as_display())),
|
||||
"int" => match v {
|
||||
Value::Int(_) => Ok(v.clone()),
|
||||
Value::Text(s) => s
|
||||
.parse::<i64>()
|
||||
.map(Value::Int)
|
||||
.map_err(|_| "invalid integer".into()),
|
||||
_ => Err("int expects integer or text".into()),
|
||||
},
|
||||
"number" => {
|
||||
let n = match v {
|
||||
Value::Text(s) => s.parse::<f64>().map_err(|_| "invalid number")?,
|
||||
_ => number(v)?,
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("non-finite number".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
"bool" => match v {
|
||||
Value::Bool(_) => Ok(v.clone()),
|
||||
Value::Text(s) => match s.as_str() {
|
||||
"true" | "True" => Ok(Value::Bool(true)),
|
||||
"false" | "False" => Ok(Value::Bool(false)),
|
||||
_ => Err("invalid bool".into()),
|
||||
},
|
||||
_ => Err("bool expects bool or text".into()),
|
||||
},
|
||||
"any" => Ok(v.clone()),
|
||||
_ => Err(format!("unknown cast type {ty}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Recoverable parsing and timezone operations at the public data boundary.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
_ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::TomlStringify => super::toml_ops::stringify(arg(b, "value")?),
|
||||
HostFn::TomlTryParse => Ok(super::result::capture(
|
||||
"toml.parse",
|
||||
super::toml_ops::parse(arg(b, "text")?).map_err(|e| format!("invalid_toml: {e}")),
|
||||
)),
|
||||
HostFn::DatetimeLocal => Ok(super::result::capture(
|
||||
"datetime.parse_local",
|
||||
super::datetime::local(arg(b, "text")?, arg(b, "zone")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
HostFn::DatetimeCalendarAdd => Ok(super::result::capture(
|
||||
"datetime.add_calendar",
|
||||
super::datetime::calendar_add(arg(b, "dt")?, arg(b, "days")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
_ => Err("not a data operation".into()),
|
||||
}
|
||||
}
|
||||
+60
-20
@@ -1,10 +1,11 @@
|
||||
//! Calendar / timezone subset for Mid2 M7 (`lib/datetime`).
|
||||
//! Calendar moments with fixed offsets or embedded IANA timezone rules.
|
||||
//!
|
||||
//! Moments are plain maps: `{unix, zone, iso}`. Zone is a fixed offset (`+08:00`)
|
||||
//! or alias (`UTC`); a few fixed-offset IANA names are accepted. Full tzdb is out of scope.
|
||||
//! Moments retain `{unix, zone, iso}`; `zone` is the numeric offset.
|
||||
//! Named zones additionally retain `timezone`, so future instants and calendar
|
||||
//! arithmetic recompute offsets using embedded IANA/DST rules.
|
||||
|
||||
use crate::host::as_text;
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc, Offset, LocalResult};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
@@ -126,7 +127,11 @@ fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> {
|
||||
}
|
||||
}
|
||||
let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?;
|
||||
Ok((unix, zone_of_moment(entries)?))
|
||||
let offset = if let Some((_, Value::Text(zone))) = entries.iter().find(|(k,_)|k=="timezone") {
|
||||
let zone: chrono_tz::Tz = zone.parse().map_err(|_| format!("unknown IANA timezone {zone}"))?;
|
||||
zone.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.offset().fix()
|
||||
} else { zone_of_moment(entries)? };
|
||||
Ok((unix, offset))
|
||||
}
|
||||
Value::Text(s) => {
|
||||
// Treat bare ISO/RFC3339 text as a moment.
|
||||
@@ -151,11 +156,10 @@ pub fn now() -> Result<Value, String> {
|
||||
|
||||
pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
let off = match zone {
|
||||
None | Some(Value::None) => FixedOffset::east_opt(0).unwrap(),
|
||||
Some(z) => parse_zone(as_text(z, "zone")?)?,
|
||||
};
|
||||
moment(secs, off)
|
||||
match zone {
|
||||
None | Some(Value::None) => moment(secs, FixedOffset::east_opt(0).unwrap()),
|
||||
Some(zone) => moment_in_zone(secs, as_text(zone,"zone")?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_unix(dt: &Value) -> Result<Value, String> {
|
||||
@@ -241,20 +245,56 @@ pub fn add(
|
||||
let hours = optional_i64(hours, "hours")?;
|
||||
let minutes = optional_i64(minutes, "minutes")?;
|
||||
let seconds = optional_i64(seconds, "seconds")?;
|
||||
let delta = Duration::days(days)
|
||||
+ Duration::hours(hours)
|
||||
+ Duration::minutes(minutes)
|
||||
+ Duration::seconds(seconds);
|
||||
let new_secs = secs
|
||||
.checked_add(delta.num_seconds())
|
||||
.ok_or_else(|| "datetime.add overflow".to_string())?;
|
||||
moment(new_secs, zone)
|
||||
let delta = days.checked_mul(86400).and_then(|n|hours.checked_mul(3600).and_then(|h|n.checked_add(h)))
|
||||
.and_then(|n|minutes.checked_mul(60).and_then(|m|n.checked_add(m))).and_then(|n|n.checked_add(seconds))
|
||||
.ok_or("datetime.add overflow")?;
|
||||
let new_secs = secs.checked_add(delta).ok_or("datetime.add overflow")?;
|
||||
if let Some(zone) = named_zone(dt) { moment_in_zone(new_secs,zone) } else { moment(new_secs,zone) }
|
||||
}
|
||||
|
||||
pub fn in_zone(dt: &Value, zone: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
let off = parse_zone(as_text(zone, "zone")?)?;
|
||||
moment(secs, off)
|
||||
moment_in_zone(secs, as_text(zone,"zone")?)
|
||||
}
|
||||
|
||||
fn named_zone(dt:&Value)->Option<&str>{
|
||||
let Value::Map(fields)=dt else{return None};
|
||||
fields.iter().find_map(|(k,v)|if k=="timezone"{if let Value::Text(zone)=v{Some(zone.as_str())}else{None}}else{None})
|
||||
}
|
||||
fn moment_in_zone(unix:i64,zone:&str)->Result<Value,String>{
|
||||
if let Ok(tz)=zone.parse::<chrono_tz::Tz>(){
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?;
|
||||
let mut value=moment(unix,local.offset().fix())?;
|
||||
if let Value::Map(fields)=&mut value{fields.push(("timezone".into(),Value::Text(zone.into())));}
|
||||
Ok(value)
|
||||
}else{moment(unix,parse_zone(zone)?)}
|
||||
}
|
||||
fn choose_local(tz:chrono_tz::Tz,local:NaiveDateTime,ambiguity:&str)->Result<i64,String>{
|
||||
if !matches!(ambiguity,"reject"|"earliest"|"latest"){return Err("ambiguity must be reject/earliest/latest".into())}
|
||||
match tz.from_local_datetime(&local){
|
||||
LocalResult::Single(dt)=>Ok(dt.timestamp()),
|
||||
LocalResult::None=>Err("nonexistent_time: local time is in a DST gap".into()),
|
||||
LocalResult::Ambiguous(a,b)=>match ambiguity{
|
||||
"earliest"=>Ok(a.timestamp().min(b.timestamp())),
|
||||
"latest"=>Ok(a.timestamp().max(b.timestamp())),
|
||||
_=>Err("ambiguous_time: DST fold; select earliest or latest".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn local(text:&Value,zone:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let source=as_text(text,"text")?.replace('T'," ");
|
||||
let local=NaiveDateTime::parse_from_str(&source,"%Y-%m-%d %H:%M:%S").map_err(|e|format!("datetime.parse_local: {e}"))?;
|
||||
let zone=as_text(zone,"zone")?;let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
moment_in_zone(choose_local(tz,local,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
pub(super) fn calendar_add(dt:&Value,days:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let (unix,_)=unix_of_value(dt)?;let days=as_i64(days,"days")?;
|
||||
let Some(zone)=named_zone(dt) else{return add(dt,Some(&Value::Int(days)),None,None,None)};
|
||||
let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.naive_local();
|
||||
let duration=Duration::try_days(days).ok_or("calendar day overflow")?;
|
||||
let next=local.checked_add_signed(duration).ok_or("calendar date overflow")?;
|
||||
moment_in_zone(choose_local(tz,next,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -222,6 +222,74 @@ pub enum HostFn {
|
||||
Access = 212,
|
||||
OracleJournal = 213,
|
||||
OracleReplayCheck = 214,
|
||||
ListRange = 215,
|
||||
ListEnumerate = 216,
|
||||
ListPluck = 217,
|
||||
ListProject = 218,
|
||||
ListWhere = 219,
|
||||
ListGroupBy = 220,
|
||||
ListUniqueBy = 221,
|
||||
ListAggregate = 222,
|
||||
ListSortKeys = 223,
|
||||
ListRename = 224,
|
||||
TableFromColumns = 225,
|
||||
TableToColumns = 226,
|
||||
ListJoin = 227,
|
||||
TableCast = 228,
|
||||
FsTryReadText = 229,
|
||||
FsTryWriteText = 230,
|
||||
TryJsonParse = 231,
|
||||
TryCsvParse = 232,
|
||||
BytesFromText = 233,
|
||||
BytesFromBase64 = 234,
|
||||
BytesToText = 235,
|
||||
BytesToBase64 = 236,
|
||||
BytesLen = 237,
|
||||
BytesSlice = 238,
|
||||
FsReadBytes = 239,
|
||||
FsWriteBytes = 240,
|
||||
FsReadChunk = 241,
|
||||
FsAppendBytes = 242,
|
||||
FsAtomicWrite = 243,
|
||||
FsWriteChanged = 244,
|
||||
FsWriteChecked = 245,
|
||||
FsReadLines = 246,
|
||||
FsWriteLines = 247,
|
||||
FsRemoveFile = 248,
|
||||
FsRemoveEmptyDir = 249,
|
||||
FsTempDir = 250,
|
||||
FsFileHash = 251,
|
||||
FsFind = 252,
|
||||
FsCopyTree = 253,
|
||||
FsSyncTree = 254,
|
||||
FsRenameMany = 255,
|
||||
PathRelative = 256,
|
||||
PathWithExtension = 257,
|
||||
DocumentSections = 258,
|
||||
DocumentSection = 259,
|
||||
DocumentReplaceSection = 260,
|
||||
DocumentTables = 261,
|
||||
DocumentReplaceTable = 262,
|
||||
DocumentLinks = 263,
|
||||
DocumentCodeBlocks = 264,
|
||||
HttpRequestResult = 265,
|
||||
HttpDownload = 266,
|
||||
TomlStringify = 267,
|
||||
TomlTryParse = 268,
|
||||
DatetimeLocal = 269,
|
||||
DatetimeCalendarAdd = 270,
|
||||
SubtaskWaitTimeout = 271,
|
||||
SubtaskCancelAll = 272,
|
||||
SubtaskRunMany = 273,
|
||||
HttpGetResult = 274,
|
||||
ZipPack = 275,
|
||||
ZipUnpack = 276,
|
||||
TableTryCast = 277,
|
||||
TableValidate = 278,
|
||||
ListUnion = 279,
|
||||
ListIntersection = 280,
|
||||
ListDifference = 281,
|
||||
TableSummarize = 282,
|
||||
}
|
||||
|
||||
/// Single source of truth for every host function. `<TAB>` slimming
|
||||
@@ -442,6 +510,74 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[
|
||||
HostFnDef { id: 212, f: HostFn::Access, name: "host_access", required: &["value", "key"], optional: &[] },
|
||||
HostFnDef { id: 213, f: HostFn::OracleJournal, name: "host_oracle_journal", required: &[], optional: &[] },
|
||||
HostFnDef { id: 214, f: HostFn::OracleReplayCheck, name: "host_oracle_replay_check", required: &["expected", "observed"], optional: &[] },
|
||||
HostFnDef { id: 215, f: HostFn::ListRange, name: "host_table_range", required: &["start", "end"], optional: &["step"] },
|
||||
HostFnDef { id: 216, f: HostFn::ListEnumerate, name: "host_table_enumerate", required: &["list"], optional: &["start"] },
|
||||
HostFnDef { id: 217, f: HostFn::ListPluck, name: "host_table_pluck", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 218, f: HostFn::ListProject, name: "host_table_project", required: &["list", "keys"], optional: &[] },
|
||||
HostFnDef { id: 219, f: HostFn::ListWhere, name: "host_table_where", required: &["list", "key", "value"], optional: &["op"] },
|
||||
HostFnDef { id: 220, f: HostFn::ListGroupBy, name: "host_table_group_by", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 221, f: HostFn::ListUniqueBy, name: "host_table_unique_by", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 222, f: HostFn::ListAggregate, name: "host_table_aggregate", required: &["list"], optional: &["key", "op"] },
|
||||
HostFnDef { id: 223, f: HostFn::ListSortKeys, name: "host_table_sort_keys", required: &["list", "keys"], optional: &["descending"] },
|
||||
HostFnDef { id: 224, f: HostFn::ListRename, name: "host_table_rename", required: &["list", "fields"], optional: &[] },
|
||||
HostFnDef { id: 225, f: HostFn::TableFromColumns, name: "host_table_from_columns", required: &["columns"], optional: &[] },
|
||||
HostFnDef { id: 226, f: HostFn::TableToColumns, name: "host_table_to_columns", required: &["rows"], optional: &[] },
|
||||
HostFnDef { id: 227, f: HostFn::ListJoin, name: "host_table_join", required: &["a", "b", "key", "right_key"], optional: &["mode"] },
|
||||
HostFnDef { id: 228, f: HostFn::TableCast, name: "host_table_cast", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 229, f: HostFn::FsTryReadText, name: "host_fs_try_read_text", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 230, f: HostFn::FsTryWriteText, name: "host_fs_try_write_text", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 231, f: HostFn::TryJsonParse, name: "host_try_json_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 232, f: HostFn::TryCsvParse, name: "host_try_csv_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 233, f: HostFn::BytesFromText, name: "host_bytes_from_text", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 234, f: HostFn::BytesFromBase64, name: "host_bytes_from_base64", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 235, f: HostFn::BytesToText, name: "host_bytes_to_text", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 236, f: HostFn::BytesToBase64, name: "host_bytes_to_base64", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 237, f: HostFn::BytesLen, name: "host_bytes_len", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 238, f: HostFn::BytesSlice, name: "host_bytes_slice", required: &["data", "start", "end"], optional: &[] },
|
||||
HostFnDef { id: 239, f: HostFn::FsReadBytes, name: "host_fs_read_bytes", required: &["path"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 240, f: HostFn::FsWriteBytes, name: "host_fs_write_bytes", required: &["path", "data"], optional: &[] },
|
||||
HostFnDef { id: 241, f: HostFn::FsReadChunk, name: "host_fs_read_chunk", required: &["path"], optional: &["offset", "size"] },
|
||||
HostFnDef { id: 242, f: HostFn::FsAppendBytes, name: "host_fs_append_bytes", required: &["path", "data"], optional: &[] },
|
||||
HostFnDef { id: 243, f: HostFn::FsAtomicWrite, name: "host_fs_atomic_write", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 244, f: HostFn::FsWriteChanged, name: "host_fs_write_changed", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 245, f: HostFn::FsWriteChecked, name: "host_fs_write_checked", required: &["path", "text", "expected_sha256"], optional: &[] },
|
||||
HostFnDef { id: 246, f: HostFn::FsReadLines, name: "host_fs_read_lines", required: &["path"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 247, f: HostFn::FsWriteLines, name: "host_fs_write_lines", required: &["path", "lines"], optional: &[] },
|
||||
HostFnDef { id: 248, f: HostFn::FsRemoveFile, name: "host_fs_remove_file", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 249, f: HostFn::FsRemoveEmptyDir, name: "host_fs_remove_empty_dir", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 250, f: HostFn::FsTempDir, name: "host_fs_temp_dir", required: &[], optional: &["prefix"] },
|
||||
HostFnDef { id: 251, f: HostFn::FsFileHash, name: "host_fs_file_hash", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 252, f: HostFn::FsFind, name: "host_fs_find", required: &["path"], optional: &["pattern", "exclude", "max_depth", "kind"] },
|
||||
HostFnDef { id: 253, f: HostFn::FsCopyTree, name: "host_fs_copy_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] },
|
||||
HostFnDef { id: 254, f: HostFn::FsSyncTree, name: "host_fs_sync_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] },
|
||||
HostFnDef { id: 255, f: HostFn::FsRenameMany, name: "host_fs_rename_many", required: &["moves"], optional: &["dry_run"] },
|
||||
HostFnDef { id: 256, f: HostFn::PathRelative, name: "host_path_relative", required: &["path", "base"], optional: &[] },
|
||||
HostFnDef { id: 257, f: HostFn::PathWithExtension, name: "host_path_with_extension", required: &["path", "extension"], optional: &[] },
|
||||
HostFnDef { id: 258, f: HostFn::DocumentSections, name: "host_document_sections", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 259, f: HostFn::DocumentSection, name: "host_document_section", required: &["text", "title"], optional: &[] },
|
||||
HostFnDef { id: 260, f: HostFn::DocumentReplaceSection, name: "host_document_replace_section", required: &["text", "title", "body"], optional: &["expected_sha256"] },
|
||||
HostFnDef { id: 261, f: HostFn::DocumentTables, name: "host_document_tables", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 262, f: HostFn::DocumentReplaceTable, name: "host_document_replace_table", required: &["text", "index", "headers", "rows"], optional: &["expected_sha256"] },
|
||||
HostFnDef { id: 263, f: HostFn::DocumentLinks, name: "host_document_links", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 264, f: HostFn::DocumentCodeBlocks, name: "host_document_code_blocks", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 265, f: HostFn::HttpRequestResult, name: "host_http_request_result", required: &["method", "url"], optional: &["body", "headers", "timeout_ms", "max_bytes", "response"] },
|
||||
HostFnDef { id: 266, f: HostFn::HttpDownload, name: "host_http_download", required: &["url", "path"], optional: &["headers", "timeout_ms", "max_bytes"] },
|
||||
HostFnDef { id: 267, f: HostFn::TomlStringify, name: "host_toml_stringify", required: &["value"], optional: &[] },
|
||||
HostFnDef { id: 268, f: HostFn::TomlTryParse, name: "host_toml_try_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 269, f: HostFn::DatetimeLocal, name: "host_datetime_local", required: &["text", "zone"], optional: &["ambiguity"] },
|
||||
HostFnDef { id: 270, f: HostFn::DatetimeCalendarAdd, name: "host_datetime_calendar_add", required: &["dt", "days"], optional: &["ambiguity"] },
|
||||
HostFnDef { id: 271, f: HostFn::SubtaskWaitTimeout, name: "host_subtask_wait_timeout", required: &["id"], optional: &["timeout_ms", "cancel"] },
|
||||
HostFnDef { id: 272, f: HostFn::SubtaskCancelAll, name: "host_subtask_cancel_all", required: &[], optional: &[] },
|
||||
HostFnDef { id: 273, f: HostFn::SubtaskRunMany, name: "host_subtask_run_many", required: &["tasks"], optional: &["limit", "timeout_ms"] },
|
||||
HostFnDef { id: 274, f: HostFn::HttpGetResult, name: "host_http_get_result", required: &["url"], optional: &["headers", "timeout_ms", "max_bytes", "response"] },
|
||||
HostFnDef { id: 275, f: HostFn::ZipPack, name: "host_zip_pack", required: &["src", "dest"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 276, f: HostFn::ZipUnpack, name: "host_zip_unpack", required: &["src", "dest"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 277, f: HostFn::TableTryCast, name: "host_table_try_cast", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 278, f: HostFn::TableValidate, name: "host_table_validate", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 279, f: HostFn::ListUnion, name: "host_table_union", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] },
|
||||
];
|
||||
|
||||
|
||||
@@ -452,6 +588,74 @@ impl HostFn {
|
||||
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"host_table_summarize" => Self::TableSummarize,
|
||||
"host_table_difference" => Self::ListDifference,
|
||||
"host_table_intersection" => Self::ListIntersection,
|
||||
"host_table_union" => Self::ListUnion,
|
||||
"host_table_validate" => Self::TableValidate,
|
||||
"host_table_try_cast" => Self::TableTryCast,
|
||||
"host_zip_unpack" => Self::ZipUnpack,
|
||||
"host_zip_pack" => Self::ZipPack,
|
||||
"host_http_get_result" => Self::HttpGetResult,
|
||||
"host_subtask_run_many" => Self::SubtaskRunMany,
|
||||
"host_subtask_cancel_all" => Self::SubtaskCancelAll,
|
||||
"host_subtask_wait_timeout" => Self::SubtaskWaitTimeout,
|
||||
"host_datetime_calendar_add" => Self::DatetimeCalendarAdd,
|
||||
"host_datetime_local" => Self::DatetimeLocal,
|
||||
"host_toml_try_parse" => Self::TomlTryParse,
|
||||
"host_toml_stringify" => Self::TomlStringify,
|
||||
"host_http_download" => Self::HttpDownload,
|
||||
"host_http_request_result" => Self::HttpRequestResult,
|
||||
"host_document_code_blocks" => Self::DocumentCodeBlocks,
|
||||
"host_document_links" => Self::DocumentLinks,
|
||||
"host_document_replace_table" => Self::DocumentReplaceTable,
|
||||
"host_document_tables" => Self::DocumentTables,
|
||||
"host_document_replace_section" => Self::DocumentReplaceSection,
|
||||
"host_document_section" => Self::DocumentSection,
|
||||
"host_document_sections" => Self::DocumentSections,
|
||||
"host_path_with_extension" => Self::PathWithExtension,
|
||||
"host_path_relative" => Self::PathRelative,
|
||||
"host_fs_rename_many" => Self::FsRenameMany,
|
||||
"host_fs_sync_tree" => Self::FsSyncTree,
|
||||
"host_fs_copy_tree" => Self::FsCopyTree,
|
||||
"host_fs_find" => Self::FsFind,
|
||||
"host_fs_file_hash" => Self::FsFileHash,
|
||||
"host_fs_temp_dir" => Self::FsTempDir,
|
||||
"host_fs_remove_empty_dir" => Self::FsRemoveEmptyDir,
|
||||
"host_fs_remove_file" => Self::FsRemoveFile,
|
||||
"host_fs_write_lines" => Self::FsWriteLines,
|
||||
"host_fs_read_lines" => Self::FsReadLines,
|
||||
"host_fs_write_checked" => Self::FsWriteChecked,
|
||||
"host_fs_write_changed" => Self::FsWriteChanged,
|
||||
"host_fs_atomic_write" => Self::FsAtomicWrite,
|
||||
"host_fs_append_bytes" => Self::FsAppendBytes,
|
||||
"host_fs_read_chunk" => Self::FsReadChunk,
|
||||
"host_fs_write_bytes" => Self::FsWriteBytes,
|
||||
"host_fs_read_bytes" => Self::FsReadBytes,
|
||||
"host_bytes_slice" => Self::BytesSlice,
|
||||
"host_bytes_len" => Self::BytesLen,
|
||||
"host_bytes_to_base64" => Self::BytesToBase64,
|
||||
"host_bytes_to_text" => Self::BytesToText,
|
||||
"host_bytes_from_base64" => Self::BytesFromBase64,
|
||||
"host_bytes_from_text" => Self::BytesFromText,
|
||||
"host_try_csv_parse" => Self::TryCsvParse,
|
||||
"host_try_json_parse" => Self::TryJsonParse,
|
||||
"host_fs_try_write_text" => Self::FsTryWriteText,
|
||||
"host_fs_try_read_text" => Self::FsTryReadText,
|
||||
"host_table_cast" => Self::TableCast,
|
||||
"host_table_join" => Self::ListJoin,
|
||||
"host_table_to_columns" => Self::TableToColumns,
|
||||
"host_table_from_columns" => Self::TableFromColumns,
|
||||
"host_table_rename" => Self::ListRename,
|
||||
"host_table_sort_keys" => Self::ListSortKeys,
|
||||
"host_table_aggregate" => Self::ListAggregate,
|
||||
"host_table_unique_by" => Self::ListUniqueBy,
|
||||
"host_table_group_by" => Self::ListGroupBy,
|
||||
"host_table_where" => Self::ListWhere,
|
||||
"host_table_project" => Self::ListProject,
|
||||
"host_table_pluck" => Self::ListPluck,
|
||||
"host_table_enumerate" => Self::ListEnumerate,
|
||||
"host_table_range" => Self::ListRange,
|
||||
"host_read_text" => Self::ReadText,
|
||||
"host_write_text" => Self::WriteText,
|
||||
"host_append_text" => Self::AppendText,
|
||||
@@ -664,6 +868,281 @@ impl HostFn {
|
||||
})
|
||||
}
|
||||
|
||||
/// Effects belong to resolved host identities, never import spellings.
|
||||
/// Exhaustive match forces every new primitive to declare its effects.
|
||||
pub fn effects(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::TableSummarize => &["pure"],
|
||||
Self::DotenvLoad => &["fs.read", "environment.write"],
|
||||
Self::ForeignLoadConfig => &["fs.read"],
|
||||
Self::ExtNativePath => &["plugin.call"],
|
||||
Self::ListDifference => &["pure"],
|
||||
Self::ListIntersection => &["pure"],
|
||||
Self::ListUnion => &["pure"],
|
||||
Self::TableValidate => &["pure"],
|
||||
Self::TableTryCast => &["pure"],
|
||||
Self::ZipUnpack => &["fs.write"],
|
||||
Self::ZipPack => &["fs.write"],
|
||||
Self::HttpGetResult => &["network.read"],
|
||||
Self::SubtaskRunMany => &["process.exec"],
|
||||
Self::SubtaskCancelAll => &["process.exec"],
|
||||
Self::SubtaskWaitTimeout => &["process.exec"],
|
||||
Self::DatetimeCalendarAdd => &["pure"],
|
||||
Self::DatetimeLocal => &["pure"],
|
||||
Self::TomlTryParse => &["pure"],
|
||||
Self::TomlStringify => &["pure"],
|
||||
Self::HttpDownload => &["network.read", "fs.write"],
|
||||
Self::HttpRequestResult => &["network.write"],
|
||||
Self::DocumentCodeBlocks => &["pure"],
|
||||
Self::DocumentLinks => &["pure"],
|
||||
Self::DocumentReplaceTable => &["pure"],
|
||||
Self::DocumentTables => &["pure"],
|
||||
Self::DocumentReplaceSection => &["pure"],
|
||||
Self::DocumentSection => &["pure"],
|
||||
Self::DocumentSections => &["pure"],
|
||||
Self::PathWithExtension => &["pure"],
|
||||
Self::PathRelative => &["pure"],
|
||||
Self::FsRenameMany => &["fs.write"],
|
||||
Self::FsSyncTree => &["fs.write"],
|
||||
Self::FsCopyTree => &["fs.write"],
|
||||
Self::FsFind => &["fs.read"],
|
||||
Self::FsFileHash => &["fs.read"],
|
||||
Self::FsTempDir => &["fs.write"],
|
||||
Self::FsRemoveEmptyDir => &["fs.write"],
|
||||
Self::FsRemoveFile => &["fs.write"],
|
||||
Self::FsWriteLines => &["fs.write"],
|
||||
Self::FsReadLines => &["fs.read"],
|
||||
Self::FsWriteChecked => &["fs.write"],
|
||||
Self::FsWriteChanged => &["fs.write"],
|
||||
Self::FsAtomicWrite => &["fs.write"],
|
||||
Self::FsAppendBytes => &["fs.write"],
|
||||
Self::FsReadChunk => &["fs.read"],
|
||||
Self::FsWriteBytes => &["fs.write"],
|
||||
Self::FsReadBytes => &["fs.read"],
|
||||
Self::BytesSlice => &["pure"],
|
||||
Self::BytesLen => &["pure"],
|
||||
Self::BytesToBase64 => &["pure"],
|
||||
Self::BytesToText => &["pure"],
|
||||
Self::BytesFromBase64 => &["pure"],
|
||||
Self::BytesFromText => &["pure"],
|
||||
Self::TryCsvParse => &["pure"],
|
||||
Self::TryJsonParse => &["pure"],
|
||||
Self::FsTryWriteText => &["fs.write"],
|
||||
Self::FsTryReadText => &["fs.read"],
|
||||
Self::TableCast => &["pure"],
|
||||
Self::ListJoin => &["pure"],
|
||||
Self::TableToColumns => &["pure"],
|
||||
Self::TableFromColumns => &["pure"],
|
||||
Self::ListRename => &["pure"],
|
||||
Self::ListSortKeys => &["pure"],
|
||||
Self::ListAggregate => &["pure"],
|
||||
Self::ListUniqueBy => &["pure"],
|
||||
Self::ListGroupBy => &["pure"],
|
||||
Self::ListWhere => &["pure"],
|
||||
Self::ListProject => &["pure"],
|
||||
Self::ListPluck => &["pure"],
|
||||
Self::ListEnumerate => &["pure"],
|
||||
Self::ListRange => &["pure"],
|
||||
Self::ReadText
|
||||
| Self::Exists
|
||||
| Self::ListDir
|
||||
| Self::FsStat
|
||||
| Self::FsWalk
|
||||
| Self::WritebackGet
|
||||
| Self::WritebackList
|
||||
| Self::WritebackScanPath => &["fs.read"],
|
||||
Self::WriteText
|
||||
| Self::AppendText
|
||||
| Self::MakeDir
|
||||
| Self::Remove
|
||||
| Self::FsCopyFile
|
||||
| Self::FsMove
|
||||
| Self::FsMakeTemp
|
||||
| Self::FsMakeDirs
|
||||
| Self::FsRemoveTree
|
||||
| Self::TextPatch
|
||||
| Self::ApplyPatchBlocks
|
||||
| Self::WritebackRecord
|
||||
| Self::WritebackClear
|
||||
| Self::WritebackEnsure => &["fs.write"],
|
||||
Self::HttpGet => &["network.read"],
|
||||
Self::HttpRequest => &["network.write"],
|
||||
Self::HttpPost | Self::HttpPostSse => &["network.write"],
|
||||
Self::Exec
|
||||
| Self::SubtaskSpawn
|
||||
| Self::SubtaskPoll
|
||||
| Self::SubtaskJoin
|
||||
| Self::SubtaskKill
|
||||
| Self::SubtaskWaitAll
|
||||
| Self::ForeignRun
|
||||
| Self::ForeignRunLang
|
||||
| Self::ForeignInvoke
|
||||
| Self::ForeignProbe
|
||||
| Self::ForeignCall
|
||||
| Self::ForeignRunMany
|
||||
| Self::ForeignCallMany
|
||||
| Self::ForeignSessionOpen
|
||||
| Self::ForeignSessionEval
|
||||
| Self::ForeignSessionSet
|
||||
| Self::ForeignSessionGet
|
||||
| Self::ForeignSessionNames
|
||||
| Self::ForeignSessionClose
|
||||
| Self::ForeignSessionList
|
||||
| Self::ForeignSessionInterrupt => &["process.exec"],
|
||||
Self::PluginLoad | Self::PluginUnload => &["plugin.call"],
|
||||
Self::LogLine
|
||||
| Self::StreamPublish
|
||||
| Self::Plot
|
||||
| Self::PlotPoints
|
||||
| Self::PlotConic => &["output.write"],
|
||||
Self::NowUnix | Self::NowMs | Self::DatetimeNow => &["time.read"],
|
||||
Self::Random
|
||||
| Self::RandomInt
|
||||
| Self::SecretsTokenHex
|
||||
| Self::SecretsTokenUrlsafe
|
||||
| Self::UuidV4 => &["random.read"],
|
||||
Self::EnvGet => &["environment.read"],
|
||||
Self::EnvSet => &["environment.write"],
|
||||
Self::Exit | Self::SleepMs => &["process.control"],
|
||||
Self::FormatTime
|
||||
| Self::ParseTime
|
||||
| Self::Args
|
||||
| Self::Cwd
|
||||
| Self::JsonParse
|
||||
| Self::JsonStringify
|
||||
| Self::JsonGet
|
||||
| Self::JsonKeys
|
||||
| Self::UrlEncode
|
||||
| Self::Pi
|
||||
| Self::EConst
|
||||
| Self::Num
|
||||
| Self::MathAdd
|
||||
| Self::MathSub
|
||||
| Self::MathMul
|
||||
| Self::MathDiv
|
||||
| Self::MathPow
|
||||
| Self::MathNeg
|
||||
| Self::MathSin
|
||||
| Self::MathCos
|
||||
| Self::MathTan
|
||||
| Self::MathAsin
|
||||
| Self::MathAcos
|
||||
| Self::MathAtan
|
||||
| Self::MathSqrt
|
||||
| Self::MathAbs
|
||||
| Self::MathLn
|
||||
| Self::MathExp
|
||||
| Self::MathFloor
|
||||
| Self::MathCeil
|
||||
| Self::MathMin
|
||||
| Self::MathMax
|
||||
| Self::Seed
|
||||
| Self::Formula
|
||||
| Self::Simplify
|
||||
| Self::Expand
|
||||
| Self::Diff
|
||||
| Self::Subs
|
||||
| Self::Eval
|
||||
| Self::Solve
|
||||
| Self::ForeignSetCmd
|
||||
| Self::ForeignLangs
|
||||
| Self::JsonQuote
|
||||
| Self::PluginList
|
||||
| Self::MapSet
|
||||
| Self::ListAppend
|
||||
| Self::OuterCallLine
|
||||
| Self::OpenAiSseParse
|
||||
| Self::CollectionPut
|
||||
| Self::ListPrepend
|
||||
| Self::ListConcat
|
||||
| Self::ListInsert
|
||||
| Self::ListSetAt
|
||||
| Self::ListRemoveAt
|
||||
| Self::ListSlice
|
||||
| Self::ListContains
|
||||
| Self::ListIndexOf
|
||||
| Self::ListReverse
|
||||
| Self::ListFirst
|
||||
| Self::ListLast
|
||||
| Self::MapGet
|
||||
| Self::MapDelete
|
||||
| Self::MapHas
|
||||
| Self::MapKeys
|
||||
| Self::MapValues
|
||||
| Self::MapItems
|
||||
| Self::MapMerge
|
||||
| Self::MapSize
|
||||
| Self::CollectionClear
|
||||
| Self::CookieParse
|
||||
| Self::MultipartParse
|
||||
| Self::MarkdownParse
|
||||
| Self::ReIsMatch
|
||||
| Self::ReFind
|
||||
| Self::ReFindAll
|
||||
| Self::ReReplace
|
||||
| Self::ReSplit
|
||||
| Self::EncodingBase64Encode
|
||||
| Self::EncodingBase64Decode
|
||||
| Self::EncodingHexEncode
|
||||
| Self::EncodingHexDecode
|
||||
| Self::PathJoin
|
||||
| Self::PathSplit
|
||||
| Self::PathFileName
|
||||
| Self::PathParent
|
||||
| Self::PathExtension
|
||||
| Self::PathNormalize
|
||||
| Self::PathIsAbsolute
|
||||
| Self::HashSha256
|
||||
| Self::HashSha1
|
||||
| Self::HashMd5
|
||||
| Self::HashHmacSha256
|
||||
| Self::TextContains
|
||||
| Self::TextStartsWith
|
||||
| Self::TextEndsWith
|
||||
| Self::TextReplace
|
||||
| Self::TextToUpper
|
||||
| Self::TextToLower
|
||||
| Self::TextRepeat
|
||||
| Self::TextPad
|
||||
| Self::CsvParse
|
||||
| Self::CsvStringify
|
||||
| Self::ListSort
|
||||
| Self::ListSortBy
|
||||
| Self::ListUnique
|
||||
| Self::ListChunk
|
||||
| Self::ListZip
|
||||
| Self::ListFlatten
|
||||
| Self::CliParse
|
||||
| Self::LogSetLevel
|
||||
| Self::DatetimeFromUnix
|
||||
| Self::DatetimeToUnix
|
||||
| Self::DatetimeParse
|
||||
| Self::DatetimeFormat
|
||||
| Self::DatetimeAdd
|
||||
| Self::DatetimeInZone
|
||||
| Self::UrlParse
|
||||
| Self::UrlQueryParse
|
||||
| Self::UrlQueryStringify
|
||||
| Self::TomlParse
|
||||
| Self::HtmlEscape
|
||||
| Self::HtmlUnescape
|
||||
| Self::EncodingBase32Encode
|
||||
| Self::EncodingBase32Decode
|
||||
| Self::StatsMean
|
||||
| Self::StatsMedian
|
||||
| Self::StatsStdev
|
||||
| Self::Meta
|
||||
| Self::MetaGet
|
||||
| Self::ModuleSource
|
||||
| Self::ArtifactKind
|
||||
| Self::ForeignRegister
|
||||
| Self::ForeignUnset
|
||||
| Self::Access
|
||||
| Self::OracleJournal
|
||||
| Self::OracleReplayCheck => &["pure"],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_u16(self) -> u16 {
|
||||
self as u16
|
||||
}
|
||||
@@ -705,6 +1184,74 @@ pub fn call_host(
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match fn_id {
|
||||
HostFn::TableSummarize => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListDifference => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListIntersection => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListUnion => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableValidate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableTryCast => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ZipUnpack => super::archive::call(ctx, fn_id, bound),
|
||||
HostFn::ZipPack => super::archive::call(ctx, fn_id, bound),
|
||||
HostFn::HttpGetResult => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskRunMany => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskCancelAll => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskWaitTimeout => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DatetimeCalendarAdd => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DatetimeLocal => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TomlTryParse => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TomlStringify => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::HttpDownload => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::HttpRequestResult => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentCodeBlocks => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentTables => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentSection => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentSections => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::PathWithExtension => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::PathRelative => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRenameMany => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsSyncTree => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsCopyTree => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsFind => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsFileHash => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTempDir => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRemoveEmptyDir => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRemoveFile => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteLines => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadLines => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteChecked => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteChanged => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsAtomicWrite => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsAppendBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadChunk => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesSlice => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesLen => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesToBase64 => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesToText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesFromBase64 => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesFromText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TryCsvParse => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TryJsonParse => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTryWriteText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTryReadText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableCast => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListJoin => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableToColumns => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableFromColumns => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListRename => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListSortKeys => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListAggregate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListUniqueBy => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListGroupBy => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListWhere => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListProject => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListPluck => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListEnumerate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListRange => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::Access => {
|
||||
let base = require(bound, "value")?;
|
||||
let key = match require(bound, "key")? {
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Inert Markdown structure using the same pulldown-cmark parser as rendering.
|
||||
//! Byte ranges always refer to the original UTF-8 source; nothing is executed.
|
||||
use super::{as_text, result};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn map(values: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(values.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
fn string(v: impl Into<String>) -> Value {
|
||||
Value::Text(v.into())
|
||||
}
|
||||
fn num(v: usize) -> Value {
|
||||
Value::Int(v as i64)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Section {
|
||||
title: String,
|
||||
level: usize,
|
||||
start: usize,
|
||||
body: usize,
|
||||
end: usize,
|
||||
}
|
||||
fn sections(text: &str) -> Vec<Section> {
|
||||
let mut out: Vec<Section> = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Heading { level, .. }) => {
|
||||
let n = level as usize;
|
||||
for section in &mut out {
|
||||
if section.end == text.len() && section.level >= n {
|
||||
section.end = range.start
|
||||
}
|
||||
}
|
||||
out.push(Section {
|
||||
title: String::new(),
|
||||
level: n,
|
||||
start: range.start,
|
||||
body: range.end,
|
||||
end: text.len(),
|
||||
});
|
||||
active = Some(out.len() - 1);
|
||||
}
|
||||
Event::End(TagEnd::Heading(_)) => {
|
||||
if let Some(i) = active.take() {
|
||||
out[i].body = range.end
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push(' ')
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn unique_section<'a>(sections: &'a [Section], title: &str) -> Result<&'a Section, String> {
|
||||
let hits: Vec<_> = sections.iter().filter(|s| s.title == title).collect();
|
||||
match hits.as_slice() {
|
||||
[s] => Ok(s),
|
||||
[] => Err(format!("section not found: {title}")),
|
||||
_ => Err(format!("ambiguous section: {title}")),
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Table {
|
||||
start: usize,
|
||||
end: usize,
|
||||
headers: Vec<String>,
|
||||
rows: Vec<Vec<String>>,
|
||||
}
|
||||
fn tables(text: &str) -> Vec<Table> {
|
||||
let mut out = Vec::new();
|
||||
let mut table: Option<Table> = None;
|
||||
let mut header = false;
|
||||
let mut row = Vec::new();
|
||||
let mut cell: Option<String> = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Table(_)) => {
|
||||
table = Some(Table {
|
||||
start: range.start,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
Event::Start(Tag::TableHead) => {
|
||||
header = true;
|
||||
row.clear()
|
||||
}
|
||||
Event::End(TagEnd::TableHead) => {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.headers = std::mem::take(&mut row)
|
||||
}
|
||||
header = false
|
||||
}
|
||||
Event::Start(Tag::TableRow) => row.clear(),
|
||||
Event::End(TagEnd::TableRow) => {
|
||||
if !header {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.rows.push(std::mem::take(&mut row));
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Start(Tag::TableCell) => cell = Some(String::new()),
|
||||
Event::End(TagEnd::TableCell) => {
|
||||
if let Some(c) = cell.take() {
|
||||
row.push(c)
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push('\n')
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Table) => {
|
||||
if let Some(mut t) = table.take() {
|
||||
t.end = range.end;
|
||||
out.push(t)
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn check_digest(b: &Args, text: &str) -> Result<(), String> {
|
||||
if let Some(Value::Text(expected)) = b.get("expected_sha256") {
|
||||
if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected {
|
||||
return Err("conflict: document content changed".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let source = text(b, "text")?;
|
||||
match id {
|
||||
HostFn::DocumentSections => Ok(Value::List(
|
||||
sections(source)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
map(vec![
|
||||
("title", string(s.title)),
|
||||
("level", num(s.level)),
|
||||
("start", num(s.start)),
|
||||
("body_start", num(s.body)),
|
||||
("end", num(s.end)),
|
||||
("text", string(&source[s.body..s.end])),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentSection => {
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
Ok(string(&source[section.body..section.end]))
|
||||
}
|
||||
HostFn::DocumentReplaceSection => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
let mut out = source[..section.body].to_string();
|
||||
let body = text(b, "body")?;
|
||||
if !out.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push('\n');
|
||||
out.push_str(body);
|
||||
if !body.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push_str(&source[section.end..]);
|
||||
Ok(string(out))
|
||||
})();
|
||||
Ok(result::capture("document.replace_section", change))
|
||||
}
|
||||
HostFn::DocumentTables => Ok(Value::List(
|
||||
tables(source)
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
map(vec![
|
||||
("start", num(t.start)),
|
||||
("end", num(t.end)),
|
||||
(
|
||||
"headers",
|
||||
Value::List(t.headers.into_iter().map(string).collect()),
|
||||
),
|
||||
(
|
||||
"rows",
|
||||
Value::List(
|
||||
t.rows
|
||||
.into_iter()
|
||||
.map(|r| Value::List(r.into_iter().map(string).collect()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentReplaceTable => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let index = match arg(b, "index")? {
|
||||
Value::Int(n) if *n >= 0 => *n as usize,
|
||||
_ => return Err("table index is zero-based nonnegative integer".into()),
|
||||
};
|
||||
let tables = tables(source);
|
||||
let table = tables.get(index).ok_or("table index out of range")?;
|
||||
fn cells(v: &Value) -> Result<Vec<String>, String> {
|
||||
let Value::List(xs) = v else {
|
||||
return Err("cells must be list of text".into());
|
||||
};
|
||||
xs.iter()
|
||||
.map(|v| {
|
||||
as_text(v, "cell").map(|s| {
|
||||
s.replace('\\', "\\\\")
|
||||
.replace('|', "\\|")
|
||||
.replace('\n', "<br>")
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let headers = cells(arg(b, "headers")?)?;
|
||||
if headers.is_empty() {
|
||||
return Err("table needs headers".into());
|
||||
}
|
||||
let Value::List(rows) = arg(b, "rows")? else {
|
||||
return Err("rows must be list".into());
|
||||
};
|
||||
let mut rendered = format!(
|
||||
"| {} |\n| {} |\n",
|
||||
headers.join(" | "),
|
||||
vec!["---"; headers.len()].join(" | ")
|
||||
);
|
||||
for row in rows {
|
||||
let row = cells(row)?;
|
||||
if row.len() != headers.len() {
|
||||
return Err("table row length differs from header".into());
|
||||
}
|
||||
rendered.push_str(&format!("| {} |\n", row.join(" | ")))
|
||||
}
|
||||
Ok(string(format!(
|
||||
"{}{}{}",
|
||||
&source[..table.start],
|
||||
rendered,
|
||||
&source[table.end..]
|
||||
)))
|
||||
})();
|
||||
Ok(result::capture("document.replace_table", change))
|
||||
}
|
||||
HostFn::DocumentLinks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active: Vec<(String, String, usize)> = Vec::new();
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||
active.push((dest_url.into_string(), String::new(), range.start))
|
||||
}
|
||||
Event::Text(s) | Event::Code(s) => {
|
||||
if let Some((_, text, _)) = active.last_mut() {
|
||||
text.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Link) => {
|
||||
if let Some((url, text, start)) = active.pop() {
|
||||
out.push(map(vec![
|
||||
("label", string(text)),
|
||||
("target", string(url)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::DocumentCodeBlocks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::CodeBlock(kind)) => {
|
||||
let lang = match kind {
|
||||
CodeBlockKind::Fenced(s) => s.into_string(),
|
||||
CodeBlockKind::Indented => String::new(),
|
||||
};
|
||||
active = Some((lang, String::new(), range.start));
|
||||
}
|
||||
Event::Text(s) => {
|
||||
if let Some((_, body, _)) = active.as_mut() {
|
||||
body.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::CodeBlock) => {
|
||||
if let Some((lang, body, start)) = active.take() {
|
||||
out.push(map(vec![
|
||||
("language", string(lang)),
|
||||
("text", string(body)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
_ => Err("not a document operation".into()),
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ fn from_hex(b: u8) -> Result<u8, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_base64(input: &[u8]) -> String {
|
||||
pub(super) fn encode_base64(input: &[u8]) -> String {
|
||||
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= input.len() {
|
||||
@@ -153,7 +153,7 @@ fn encode_base64(input: &[u8]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
pub(super) fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
let raw = input.as_bytes();
|
||||
if raw.len() % 4 != 0 {
|
||||
return Err("base64_decode: length must be multiple of 4".into());
|
||||
|
||||
+52
-10
@@ -62,6 +62,17 @@ pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Valu
|
||||
return Err("append_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut current = match read_text(ctx,path) {
|
||||
Ok(Value::Text(text)) => text,
|
||||
Err(_) if !matches!(exists(ctx,path),Ok(Value::Bool(true))) => String::new(),
|
||||
Err(e) => return Err(e),
|
||||
_ => return Err("append_text needs UTF-8".into()),
|
||||
};
|
||||
current.push_str(text_body(text)?);
|
||||
crate::host::sandbox_fs::cow_write_text(ctx,&p,¤t)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
@@ -99,6 +110,7 @@ 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());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dir directory state in CoW sandbox".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)
|
||||
@@ -109,6 +121,7 @@ pub fn make_dirs(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("make_dirs denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dirs directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
fs::create_dir_all(&p).map_err(|e| format!("make_dirs {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
@@ -119,6 +132,9 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
return Err("remove denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() && p.is_dir() {
|
||||
return Err("unsupported: recursive directory removal in CoW sandbox".into());
|
||||
}
|
||||
if crate::host::sandbox_fs::cow_remove(ctx, &p)? {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
@@ -135,6 +151,7 @@ pub fn remove_tree(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("remove_tree denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: remove_tree directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if !p.exists() {
|
||||
return Err(format!("remove_tree: not found: {}", p.display()));
|
||||
@@ -210,6 +227,18 @@ pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value,
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Err("conflict: copy source equals destination".into()); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
use std::io::Read;
|
||||
let bytes = match crate::host::sandbox_fs::cow_read_bytes(ctx,&from)? {
|
||||
Some(bytes) => bytes,
|
||||
None => { let mut bytes=Vec::new();fs::File::open(&from).map_err(|e|e.to_string())?
|
||||
.take(64*1024*1024+1).read_to_end(&mut bytes).map_err(|e|e.to_string())?;bytes },
|
||||
};
|
||||
if bytes.len()>64*1024*1024 { return Err("resource_limit: CoW copy exceeds 64 MiB".into()); }
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&to,&bytes)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?;
|
||||
}
|
||||
@@ -223,6 +252,12 @@ pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value,
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Ok(Value::None); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
copy_file(ctx,src,dest)?;
|
||||
crate::host::sandbox_fs::cow_remove(ctx,&from)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("move mkdir: {e}"))?;
|
||||
}
|
||||
@@ -248,6 +283,13 @@ pub fn make_temp(ctx: &HostContext, prefix: Option<&Value>) -> Result<Value, Str
|
||||
.unwrap_or(0);
|
||||
let name = format!("{pref}-{stamp}");
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
if matches!(exists(ctx,&Value::Text(name.clone()))?,Value::Bool(true)) {
|
||||
return Err("conflict: temporary path exists".into());
|
||||
}
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&p,&[])?;
|
||||
return Ok(Value::Text(name));
|
||||
}
|
||||
if let Some(parent) = p.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("make_temp mkdir: {e}"))?;
|
||||
}
|
||||
@@ -264,28 +306,28 @@ pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("text_patch denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let display = text_path(path)?;
|
||||
let find = text_body(find)?;
|
||||
let replace = text_body(replace)?;
|
||||
if find.is_empty() {
|
||||
return Err("text_patch: find must be non-empty".into());
|
||||
}
|
||||
let src = fs::read_to_string(&p).map_err(|e| format!("text_patch {}: {e}", p.display()))?;
|
||||
let Value::Text(src) = read_text(ctx,path)? else { return Err("text_patch needs text".into()); };
|
||||
let count = src.matches(find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"text_patch: find not found in {}",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"text_patch: find matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
let next = src.replacen(find, replace, 1);
|
||||
fs::write(&p, next).map_err(|e| format!("text_patch write {}: {e}", p.display()))?;
|
||||
write_text(ctx,path,&Value::Text(next))?;
|
||||
Ok(Value::Int(1))
|
||||
}
|
||||
|
||||
@@ -362,8 +404,8 @@ fn apply_patch_blocks_inner(
|
||||
if blocks.is_empty() {
|
||||
return Ok(Value::Int(0));
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let mut src = fs::read_to_string(&p).map_err(|e| format!("apply_patch_blocks {}: {e}", p.display()))?;
|
||||
let display = text_path(path)?;
|
||||
let Value::Text(mut src) = read_text(ctx,path)? else { return Err("apply_patch_blocks needs text".into()); };
|
||||
let mut applied = 0i64;
|
||||
for (find, replace) in blocks {
|
||||
if find.is_empty() {
|
||||
@@ -379,19 +421,19 @@ fn apply_patch_blocks_inner(
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND not found in {}",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
src = src.replacen(&find, &replace, 1);
|
||||
applied += 1;
|
||||
}
|
||||
fs::write(&p, src).map_err(|e| format!("apply_patch_blocks write {}: {e}", p.display()))?;
|
||||
write_text(ctx,path,&Value::Text(src))?;
|
||||
Ok(Value::Int(applied))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,681 @@
|
||||
//! Bounded filesystem tasks. Public authors use lib/fs, lib/path and lib/bytes.
|
||||
use super::{as_text, encoding, fs as legacy, result, sandbox_fs};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
const MAX_READ: usize = 64 * 1024 * 1024;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn number(b: &Args, k: &str) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
fn flag(b: &Args, k: &str) -> bool {
|
||||
matches!(b.get(k), Some(Value::Bool(true)))
|
||||
}
|
||||
fn native(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.sandbox_session.is_some() {
|
||||
Err("operation unavailable in CoW sandbox; use write_text/remove_file".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn writable(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.allow_fs_write() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("filesystem write denied by host policy".into())
|
||||
}
|
||||
}
|
||||
fn path(ctx: &HostContext, b: &Args, k: &str) -> Result<PathBuf, String> {
|
||||
ctx.resolve_path(text(b, k)?)
|
||||
}
|
||||
fn ioerr(e: std::io::Error) -> String {
|
||||
let code = match e.kind() {
|
||||
std::io::ErrorKind::NotFound => "not_found",
|
||||
std::io::ErrorKind::PermissionDenied => "permission_denied",
|
||||
std::io::ErrorKind::AlreadyExists => "conflict",
|
||||
_ => "operation_failed",
|
||||
};
|
||||
format!("{code}: {e}")
|
||||
}
|
||||
fn limit(b: &Args, k: &str) -> Result<usize, String> {
|
||||
let n = number(b, k)?;
|
||||
if n == 0 || n > MAX_READ as u64 {
|
||||
return Err(format!("{k} must be 1..{MAX_READ}"));
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
pub(super) fn bytes_value(bytes: &[u8]) -> Value {
|
||||
Value::Map(vec![
|
||||
("_type".into(), Value::Text("bytes".into())),
|
||||
("base64".into(), Value::Text(encoding::encode_base64(bytes))),
|
||||
])
|
||||
}
|
||||
pub(super) fn bytes(v: &Value) -> Result<Vec<u8>, String> {
|
||||
let Value::Map(fields) = v else {
|
||||
return Err("expected bytes record from lib/bytes or fs.read_bytes".into());
|
||||
};
|
||||
if !fields
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_type" && v == &Value::Text("bytes".into()))
|
||||
{
|
||||
return Err("expected _type bytes".into());
|
||||
}
|
||||
let text = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == "base64")
|
||||
.ok_or("missing bytes.base64")?;
|
||||
encoding::decode_base64(as_text(&text.1, "base64")?)
|
||||
}
|
||||
fn read(ctx: &HostContext, p: &Path, max: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, p)? {
|
||||
if bytes.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
return Ok(bytes);
|
||||
}
|
||||
fs::File::open(p)
|
||||
.map_err(ioerr)?
|
||||
.take(max as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(ioerr)?;
|
||||
if out.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn atomic(ctx: &HostContext, p: &Path, body: &[u8]) -> Result<(), String> {
|
||||
writable(ctx)?;
|
||||
if sandbox_fs::cow_write_bytes(ctx, p, body)? {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = p.parent().ok_or("file needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
// create_new reserves the sibling name. Never truncate an existing temp file.
|
||||
let mut reserved = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = entropy
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-{name}.tmp"));
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
{
|
||||
Ok(file) => {
|
||||
reserved = Some((temp, file));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
let (temp, mut file) = reserved.ok_or("cannot reserve atomic write file")?;
|
||||
let result = (|| {
|
||||
file.write_all(body).map_err(ioerr)?;
|
||||
file.sync_all().map_err(ioerr)?;
|
||||
drop(file);
|
||||
fs::rename(&temp, p).map_err(ioerr)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let answer = match id {
|
||||
HostFn::FsTryReadText => {
|
||||
let answer = (|| {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, 8 * 1024 * 1024)?;
|
||||
String::from_utf8(data)
|
||||
.map(Value::Text)
|
||||
.map_err(|e| format!("invalid_encoding: {e}"))
|
||||
})();
|
||||
return Ok(result::capture("fs.read_text", answer));
|
||||
}
|
||||
HostFn::FsTryWriteText => {
|
||||
return Ok(result::capture(
|
||||
"fs.write_text",
|
||||
legacy::write_text(ctx, arg(b, "path")?, arg(b, "text")?),
|
||||
))
|
||||
}
|
||||
HostFn::TryJsonParse => {
|
||||
return Ok(result::capture(
|
||||
"json.parse",
|
||||
super::json::parse(arg(b, "text")?).map_err(|e| format!("invalid_json: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::TryCsvParse => {
|
||||
return Ok(result::capture(
|
||||
"csv.parse",
|
||||
super::csv::parse(arg(b, "text")?).map_err(|e| format!("invalid_csv: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::BytesFromText => bytes_value(text(b, "text")?.as_bytes()),
|
||||
HostFn::BytesFromBase64 => bytes_value(&encoding::decode_base64(text(b, "text")?)?),
|
||||
HostFn::BytesToText => Value::Text(
|
||||
String::from_utf8(bytes(arg(b, "data")?)?)
|
||||
.map_err(|e| format!("bytes are not UTF-8: {e}"))?,
|
||||
),
|
||||
HostFn::BytesToBase64 => Value::Text(encoding::encode_base64(&bytes(arg(b, "data")?)?)),
|
||||
HostFn::BytesLen => Value::Int(bytes(arg(b, "data")?)?.len() as i64),
|
||||
HostFn::BytesSlice => {
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
let start = usize::try_from(number(b, "start")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
let end = usize::try_from(number(b, "end")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
bytes_value(if start > end { &[] } else { &data[start..end] })
|
||||
}
|
||||
HostFn::FsReadBytes => {
|
||||
bytes_value(&read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?)
|
||||
}
|
||||
HostFn::FsWriteBytes => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
atomic(ctx, &p, &bytes(arg(b, "data")?)?)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsReadChunk => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let offset = number(b, "offset")?;
|
||||
let size = limit(b, "size")?;
|
||||
let mut data = vec![0u8; size];
|
||||
let (n, total) = if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
let start = usize::try_from(offset)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(bytes.len());
|
||||
let end = start.saturating_add(size).min(bytes.len());
|
||||
data[..end - start].copy_from_slice(&bytes[start..end]);
|
||||
(end - start, bytes.len() as u64)
|
||||
} else {
|
||||
let mut file = fs::File::open(&p).map_err(ioerr)?;
|
||||
let total = file.metadata().map_err(ioerr)?.len();
|
||||
file.seek(SeekFrom::Start(offset)).map_err(ioerr)?;
|
||||
let n = file.take(size as u64).read(&mut data).map_err(ioerr)?;
|
||||
(n, total)
|
||||
};
|
||||
data.truncate(n);
|
||||
let next = offset.checked_add(n as u64).ok_or("offset overflow")?;
|
||||
Value::Map(vec![
|
||||
("data".into(), bytes_value(&data)),
|
||||
("next_offset".into(), Value::Int(next as i64)),
|
||||
("eof".into(), Value::Bool(next >= total)),
|
||||
])
|
||||
}
|
||||
HostFn::FsAppendBytes => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut body = read(ctx, &p, MAX_READ).or_else(|e| {
|
||||
if matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(false))) {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})?;
|
||||
body.extend_from_slice(&data);
|
||||
sandbox_fs::cow_write_bytes(ctx, &p, &body)?;
|
||||
} else {
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&p)
|
||||
.map_err(ioerr)?;
|
||||
f.write_all(&data).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsAtomicWrite | HostFn::FsWriteChanged => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let body = text(b, "text")?.as_bytes();
|
||||
if id == HostFn::FsWriteChanged && read(ctx, &p, MAX_READ).ok().as_deref() == Some(body)
|
||||
{
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
atomic(ctx, &p, body)?;
|
||||
if id == HostFn::FsWriteChanged {
|
||||
Value::Bool(true)
|
||||
} else {
|
||||
Value::None
|
||||
}
|
||||
}
|
||||
HostFn::FsWriteChecked => {
|
||||
let change = (|| {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let expected = text(b, "expected_sha256")?;
|
||||
let current = read(ctx, &p, MAX_READ)?;
|
||||
let actual = format!("{:x}", Sha256::digest(¤t));
|
||||
if actual != expected {
|
||||
return Err("conflict: file content changed".into());
|
||||
}
|
||||
atomic(ctx, &p, text(b, "text")?.as_bytes()).map(|_| Value::None)
|
||||
})();
|
||||
return Ok(result::capture("fs.write_checked", change));
|
||||
}
|
||||
HostFn::FsReadLines => {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?;
|
||||
let text = String::from_utf8(data).map_err(|e| format!("file is not UTF-8: {e}"))?;
|
||||
Value::List(text.lines().map(|s| Value::Text(s.into())).collect())
|
||||
}
|
||||
HostFn::FsWriteLines => {
|
||||
let Value::List(lines) = arg(b, "lines")? else {
|
||||
return Err("lines must be list of text".into());
|
||||
};
|
||||
let lines = lines
|
||||
.iter()
|
||||
.map(|v| as_text(v, "line"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut body = lines.join("\n");
|
||||
if !lines.is_empty() {
|
||||
body.push('\n')
|
||||
};
|
||||
atomic(ctx, &path(ctx, b, "path")?, body.as_bytes())?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveFile => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
if p.is_dir() {
|
||||
return Err("remove_file refuses directory".into());
|
||||
}
|
||||
if !matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(true))) {
|
||||
return Err("not_found: remove_file target absent".into());
|
||||
}
|
||||
if !sandbox_fs::cow_remove(ctx, &p)? {
|
||||
fs::remove_file(p).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveEmptyDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
fs::remove_dir(path(ctx, b, "path")?).map_err(ioerr)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsTempDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let prefix = text(b, "prefix")?;
|
||||
if prefix.contains('/') || prefix.contains('\\') || prefix.contains("..") {
|
||||
return Err("temp prefix must be simple name".into());
|
||||
}
|
||||
let mut created = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = format!(
|
||||
"{prefix}-{}",
|
||||
entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>()
|
||||
);
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
match fs::create_dir(p) {
|
||||
Ok(()) => {
|
||||
created = Some(Value::Text(name));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
created.ok_or("unable to reserve temporary directory")?
|
||||
}
|
||||
HostFn::FsFileHash => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let mut hasher = Sha256::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
hasher.update(bytes)
|
||||
} else {
|
||||
let mut f = fs::File::open(p).map_err(ioerr)?;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = f.read(&mut buffer).map_err(ioerr)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..n]);
|
||||
}
|
||||
}
|
||||
Value::Text(format!("{:x}", hasher.finalize()))
|
||||
}
|
||||
HostFn::FsFind => {
|
||||
let root = path(ctx, b, "path")?;
|
||||
let pattern = glob(text(b, "pattern")?)?;
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let max_depth = number(b, "max_depth")? as usize;
|
||||
let kind = text(b, "kind")?;
|
||||
if !matches!(kind, "file" | "dir" | "all") {
|
||||
return Err("find kind must be file/dir/all".into());
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&root,
|
||||
Path::new(""),
|
||||
&pattern,
|
||||
&excluded,
|
||||
max_depth,
|
||||
kind,
|
||||
&mut files,
|
||||
)?;
|
||||
Value::List(files)
|
||||
}
|
||||
HostFn::FsCopyTree | HostFn::FsSyncTree => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let src = path(ctx, b, "src")?;
|
||||
let dest = path(ctx, b, "dest")?;
|
||||
if dest.starts_with(&src) || src.starts_with(&dest) {
|
||||
return Err("copy/sync trees must be disjoint".into());
|
||||
}
|
||||
if !src.is_dir() {
|
||||
return Err("src must be directory".into());
|
||||
}
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&src,
|
||||
Path::new(""),
|
||||
&glob("**")?,
|
||||
&excluded,
|
||||
256,
|
||||
"file",
|
||||
&mut files,
|
||||
)?;
|
||||
let mut jobs = Vec::new();
|
||||
for name in files {
|
||||
let name = as_text(&name, "name")?;
|
||||
let from = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let to = ctx.resolve_path(dest.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
if to.exists() {
|
||||
if id == HostFn::FsSyncTree && files_equal(&from, &to)? {
|
||||
continue;
|
||||
}
|
||||
if !flag(b, "overwrite") {
|
||||
return Err(format!("destination conflict: {}", to.display()));
|
||||
}
|
||||
}
|
||||
jobs.push((from, to, name.to_string()));
|
||||
}
|
||||
let dry = flag(b, "dry_run");
|
||||
let mut changed = Vec::new();
|
||||
for (from, to, name) in jobs {
|
||||
if !dry {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::copy(from, to).map_err(ioerr)?;
|
||||
}
|
||||
changed.push(Value::Text(name));
|
||||
}
|
||||
Value::List(changed)
|
||||
}
|
||||
HostFn::FsRenameMany => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let Value::List(rows) = arg(b, "moves")? else {
|
||||
return Err("moves must be record list".into());
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
let mut destinations = std::collections::HashSet::new();
|
||||
let mut sources = std::collections::HashSet::new();
|
||||
for row in rows {
|
||||
let Value::Map(fields) = row else {
|
||||
return Err("move needs src,dest".into());
|
||||
};
|
||||
let mut paths = Vec::new();
|
||||
for key in ["src", "dest"] {
|
||||
let value = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.ok_or("move needs src,dest")?;
|
||||
paths.push(ctx.resolve_path(as_text(&value.1, key)?)?);
|
||||
}
|
||||
if !paths[0].is_file() {
|
||||
return Err("rename_many source must be file".into());
|
||||
}
|
||||
if !sources.insert(paths[0].clone()) {
|
||||
return Err("conflict: repeated rename source".into());
|
||||
}
|
||||
if paths[1].exists() || !destinations.insert(paths[1].clone()) {
|
||||
return Err("rename_many destination conflict".into());
|
||||
}
|
||||
jobs.push((paths.remove(0), paths.remove(0)));
|
||||
}
|
||||
// Preflight all paths. Execution is ordered and deliberately not transactional.
|
||||
if !flag(b, "dry_run") {
|
||||
for (from, to) in &jobs {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::rename(from, to).map_err(ioerr)?;
|
||||
}
|
||||
}
|
||||
Value::Int(jobs.len() as i64)
|
||||
}
|
||||
HostFn::PathRelative => {
|
||||
let normalized = super::path::normalize(arg(b, "path")?)?;
|
||||
let normalized_base = super::path::normalize(arg(b, "base")?)?;
|
||||
let path = PathBuf::from(as_text(&normalized, "path")?);
|
||||
let base = PathBuf::from(as_text(&normalized_base, "base")?);
|
||||
if path.is_absolute() != base.is_absolute() {
|
||||
return Err("relative paths must share absolute/relative form".into());
|
||||
}
|
||||
let a: Vec<_> = path.components().collect();
|
||||
let b: Vec<_> = base.components().collect();
|
||||
if path.is_absolute() && a.first() != b.first() {
|
||||
return Err("relative paths have different roots".into());
|
||||
}
|
||||
let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
|
||||
let mut out = PathBuf::new();
|
||||
for _ in common..b.len() {
|
||||
out.push("..")
|
||||
}
|
||||
for c in &a[common..] {
|
||||
out.push(c.as_os_str())
|
||||
}
|
||||
Value::Text(if out.as_os_str().is_empty() {
|
||||
".".into()
|
||||
} else {
|
||||
out.to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
}
|
||||
HostFn::PathWithExtension => {
|
||||
let mut p = PathBuf::from(text(b, "path")?);
|
||||
let ext = text(b, "extension")?;
|
||||
if ext.contains('/') || ext.contains('\\') {
|
||||
return Err("extension cannot contain path separator".into());
|
||||
}
|
||||
p.set_extension(ext.trim_start_matches('.'));
|
||||
Value::Text(p.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
_ => return Err("not a filesystem task".into()),
|
||||
};
|
||||
Ok(answer)
|
||||
}
|
||||
fn patterns(v: &Value) -> Result<Vec<regex::Regex>, String> {
|
||||
if matches!(v, Value::None) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let Value::List(xs) = v else {
|
||||
return Err("exclude must be list of patterns".into());
|
||||
};
|
||||
xs.iter().map(|v| glob(as_text(v, "pattern")?)).collect()
|
||||
}
|
||||
fn glob(pattern: &str) -> Result<regex::Regex, String> {
|
||||
let mut out = String::from("^");
|
||||
let mut cs = pattern.chars().peekable();
|
||||
while let Some(c) = cs.next() {
|
||||
match c {
|
||||
'*' => {
|
||||
if cs.peek() == Some(&'*') {
|
||||
cs.next();
|
||||
if cs.peek() == Some(&'/') {
|
||||
cs.next();
|
||||
out.push_str("(?:.*/)?")
|
||||
} else {
|
||||
out.push_str(".*")
|
||||
}
|
||||
} else {
|
||||
out.push_str("[^/]*")
|
||||
}
|
||||
}
|
||||
'?' => out.push_str("[^/]"),
|
||||
_ => out.push_str(®ex::escape(&c.to_string())),
|
||||
}
|
||||
}
|
||||
out.push('$');
|
||||
regex::Regex::new(&out).map_err(|e| e.to_string())
|
||||
}
|
||||
fn find(
|
||||
ctx: &HostContext,
|
||||
root: &Path,
|
||||
rel: &Path,
|
||||
pattern: ®ex::Regex,
|
||||
exclude: &[regex::Regex],
|
||||
depth: usize,
|
||||
kind: &str,
|
||||
out: &mut Vec<Value>,
|
||||
) -> Result<(), String> {
|
||||
if depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let mut entries = fs::read_dir(root.join(rel))
|
||||
.map_err(ioerr)?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(ioerr)?;
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let child = rel.join(entry.file_name());
|
||||
let name = child.to_string_lossy().replace('\\', "/");
|
||||
let ty = entry.file_type().map_err(ioerr)?;
|
||||
if exclude
|
||||
.iter()
|
||||
.any(|r| r.is_match(&name) || r.is_match(&format!("{name}/")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// No symlink traversal. Reads returned by this finder still use resolve_path.
|
||||
if ty.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
ctx.resolve_path(entry.path().to_str().ok_or("non UTF-8 path")?)?;
|
||||
if pattern.is_match(&name)
|
||||
&& ((ty.is_file() && kind != "dir") || (ty.is_dir() && kind != "file"))
|
||||
{
|
||||
if out.len() >= 100_000 {
|
||||
return Err("find exceeds 100000 entries".into());
|
||||
}
|
||||
out.push(Value::Text(name))
|
||||
}
|
||||
if ty.is_dir() {
|
||||
find(ctx, root, &child, pattern, exclude, depth - 1, kind, out)?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn files_equal(a: &Path, b: &Path) -> Result<bool, String> {
|
||||
if fs::metadata(a).map_err(ioerr)?.len() != fs::metadata(b).map_err(ioerr)?.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut a = std::io::BufReader::new(fs::File::open(a).map_err(ioerr)?);
|
||||
let mut b = std::io::BufReader::new(fs::File::open(b).map_err(ioerr)?);
|
||||
use std::io::BufRead;
|
||||
loop {
|
||||
let left = a.fill_buf().map_err(ioerr)?;
|
||||
let right = b.fill_buf().map_err(ioerr)?;
|
||||
if left.is_empty() || right.is_empty() {
|
||||
return Ok(left.is_empty() && right.is_empty());
|
||||
}
|
||||
let n = left.len().min(right.len());
|
||||
if left[..n] != right[..n] {
|
||||
return Ok(false);
|
||||
}
|
||||
a.consume(n);
|
||||
b.consume(n);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod overlay_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn byte_append_copy_and_patch_stay_in_the_overlay_until_commit() {
|
||||
let root = std::env::temp_dir().join(format!("mq-byte-overlay-{}", std::process::id()));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::write(root.join("note.md"), "old text").unwrap();
|
||||
let mut ctx =
|
||||
HostContext::for_run(Some(&root.join("main.mq.md")), Default::default(), vec![]);
|
||||
let session = sandbox_fs::open(Some(root.to_str().unwrap()), &ctx).unwrap();
|
||||
let id = session["id"].as_str().unwrap().to_string();
|
||||
ctx.sandbox_session = Some(id.clone());
|
||||
legacy::text_patch(
|
||||
&ctx,
|
||||
&Value::Text("note.md".into()),
|
||||
&Value::Text("old".into()),
|
||||
&Value::Text("new".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("note.md")).unwrap(),
|
||||
"old text"
|
||||
);
|
||||
assert_eq!(
|
||||
legacy::read_text(&ctx, &Value::Text("note.md".into())).unwrap(),
|
||||
Value::Text("new text".into())
|
||||
);
|
||||
let mut args = Args::from([
|
||||
("path".into(), Value::Text("data.bin".into())),
|
||||
("data".into(), bytes_value(&[0, 255])),
|
||||
]);
|
||||
call(&mut ctx, HostFn::FsWriteBytes, &args).unwrap();
|
||||
args.insert("data".into(), bytes_value(&[128]));
|
||||
call(&mut ctx, HostFn::FsAppendBytes, &args).unwrap();
|
||||
legacy::copy_file(
|
||||
&ctx,
|
||||
&Value::Text("data.bin".into()),
|
||||
&Value::Text("copied.bin".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sandbox_fs::cow_read_bytes(&ctx, &root.join("copied.bin"))
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
[0, 255, 128]
|
||||
);
|
||||
assert!(!root.join("data.bin").exists());
|
||||
assert!(!root.join("copied.bin").exists());
|
||||
assert!(legacy::make_dirs(&ctx, &Value::Text("unsupported".into())).is_err());
|
||||
assert!(!root.join("unsupported").exists());
|
||||
sandbox_fs::discard(&id).unwrap();
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
+54
-13
@@ -276,21 +276,46 @@ impl HostContext {
|
||||
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()));
|
||||
let abs = if abs.is_absolute() { abs } else {
|
||||
std::env::current_dir().map_err(|e|e.to_string())?.join(abs)
|
||||
};
|
||||
let root = root.canonicalize().map_err(|e| format!("filesystem root: {e}"))?;
|
||||
// Normalize before checking, including destinations that do not exist yet.
|
||||
let mut lexical = PathBuf::new();
|
||||
for component in abs.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {},
|
||||
std::path::Component::ParentDir => { lexical.pop(); },
|
||||
component => lexical.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
if !lexical.is_absolute() {
|
||||
lexical = std::env::current_dir().map_err(|e| e.to_string())?.join(lexical);
|
||||
}
|
||||
if !lexical.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
// The nearest existing ancestor must also be inside root: a symlink
|
||||
// cannot authorize writes through a not-yet-existing descendant.
|
||||
let mut ancestor = lexical.as_path();
|
||||
loop {
|
||||
match ancestor.canonicalize() {
|
||||
Ok(real) => {
|
||||
if !real.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
if ancestor.symlink_metadata().is_ok() {
|
||||
return Err(format!("unresolvable symlink: {}", ancestor.display()));
|
||||
}
|
||||
ancestor = ancestor.parent().ok_or_else(|| "invalid file path".to_string())?;
|
||||
}
|
||||
Err(e) => return Err(format!("resolve path {}: {e}", abs.display())),
|
||||
}
|
||||
}
|
||||
return Ok(lexical);
|
||||
}
|
||||
Ok(abs)
|
||||
}
|
||||
@@ -320,3 +345,19 @@ pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> R
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod collection_ops;
|
||||
|
||||
mod result;
|
||||
|
||||
mod fs_ops;
|
||||
|
||||
mod document;
|
||||
|
||||
mod net_ops;
|
||||
|
||||
mod data_ops;
|
||||
|
||||
mod task_ops;
|
||||
|
||||
mod archive;
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Configurable bounded HTTP with one recoverable Result envelope.
|
||||
#[cfg(feature = "net-host")]
|
||||
use super::as_text;
|
||||
use super::result;
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
time::Duration,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = request(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("HTTP unavailable in this build".into())
|
||||
};
|
||||
Ok(result::capture(
|
||||
if id == HostFn::HttpDownload {
|
||||
"net.download"
|
||||
} else {
|
||||
"net.request"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn integer(b: &Args, k: &str, max: u64) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n > 0 && (*n as u64) <= max => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be 1..{max}")),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn request(ctx: &HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("network denied by host policy".into());
|
||||
}
|
||||
let url = as_text(arg(b, "url")?, "url")?;
|
||||
if !(url.starts_with("https://") || url.starts_with("http://")) {
|
||||
return Err("url must use http/https".into());
|
||||
}
|
||||
let timeout = Duration::from_millis(integer(b, "timeout_ms", 600000)?);
|
||||
let max = integer(b, "max_bytes", 1024 * 1024 * 1024)?;
|
||||
let method = if matches!(id, HostFn::HttpDownload | HostFn::HttpGetResult) {
|
||||
"GET"
|
||||
} else {
|
||||
as_text(arg(b, "method")?, "method")?
|
||||
};
|
||||
if !matches!(
|
||||
method,
|
||||
"GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"
|
||||
) {
|
||||
return Err("unsupported method".into());
|
||||
}
|
||||
// Reject invalid output settings and destinations before any HTTP exchange.
|
||||
let destination = if id == HostFn::HttpDownload {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("unsupported: stream download in CoW sandbox".into());
|
||||
}
|
||||
let path = ctx.resolve_path(as_text(arg(b, "path")?, "path")?)?;
|
||||
if path.is_dir() {
|
||||
return Err("invalid_argument: download destination is a directory".into());
|
||||
}
|
||||
Some(path)
|
||||
} else {
|
||||
if max > 64 * 1024 * 1024 {
|
||||
return Err(
|
||||
"resource_limit: in-memory response limit exceeds 64 MiB; use download".into(),
|
||||
);
|
||||
}
|
||||
if !matches!(as_text(arg(b, "response")?, "response")?, "text" | "bytes") {
|
||||
return Err("invalid_argument: response must be text or bytes".into());
|
||||
}
|
||||
None
|
||||
};
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(timeout)
|
||||
.timeout_connect(timeout)
|
||||
.timeout_read(timeout)
|
||||
.timeout_write(timeout)
|
||||
.build();
|
||||
let mut request = agent.request(method, url).set("User-Agent", "marqdo");
|
||||
if let Some(Value::Map(headers)) = b.get("headers") {
|
||||
for (k, v) in headers {
|
||||
request = request.set(k, as_text(v, "header value")?)
|
||||
}
|
||||
} else if !matches!(b.get("headers"), None | Some(Value::None)) {
|
||||
return Err("headers must be map or None".into());
|
||||
}
|
||||
let exchange = match b.get("body") {
|
||||
None | Some(Value::None) => request.call(),
|
||||
Some(Value::Text(text)) => request.send_bytes(text.as_bytes()),
|
||||
Some(v) => request.send_bytes(&super::fs_ops::bytes(v)?),
|
||||
};
|
||||
let response = match exchange {
|
||||
Ok(r) => r,
|
||||
Err(ureq::Error::Status(_, r)) => r,
|
||||
Err(e) => return Err(format!("transport_error: {e}")),
|
||||
};
|
||||
let status = response.status();
|
||||
let mut headers = Vec::new();
|
||||
for name in response.headers_names() {
|
||||
let values = response
|
||||
.all(&name)
|
||||
.into_iter()
|
||||
.map(|v| Value::Text(v.into()))
|
||||
.collect();
|
||||
headers.push(Value::Map(vec![
|
||||
("name".into(), Value::Text(name.to_ascii_lowercase())),
|
||||
("values".into(), Value::List(values)),
|
||||
]));
|
||||
}
|
||||
let mut reader = response.into_reader();
|
||||
if id == HostFn::HttpDownload {
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("http_status: {status}; destination unchanged"));
|
||||
}
|
||||
let path = destination.ok_or("missing validated download destination")?;
|
||||
let parent = path.parent().ok_or("destination needs parent")?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let token = entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-download-{token}"));
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let downloaded = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = reader.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
std::fs::rename(&temp, &path).map_err(|e| e.to_string())?;
|
||||
Ok(total)
|
||||
})();
|
||||
let total = match downloaded {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(temp);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
return Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("size".into(), Value::Int(total as i64)),
|
||||
("path".into(), arg(b, "path")?.clone()),
|
||||
]));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(max + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
let mode = as_text(arg(b, "response")?, "response")?;
|
||||
let body = match mode {
|
||||
"text" => Value::Text(String::from_utf8(bytes).map_err(|e| {
|
||||
format!("invalid_encoding: response is not UTF-8; request bytes instead: {e}")
|
||||
})?),
|
||||
"bytes" => super::fs_ops::bytes_value(&bytes),
|
||||
_ => return Err("response must be text or bytes".into()),
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("body".into(), body),
|
||||
]))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! A recoverable failure is data; permission errors remain explicit failures.
|
||||
use crate::value::Value;
|
||||
|
||||
pub(super) fn capture(operation: &str, result: Result<Value, String>) -> Value {
|
||||
let (ok, value, error) = match result {
|
||||
Ok(value) => (true, value, Value::None),
|
||||
Err(message) => {
|
||||
let tagged = message.split_once(':').map(|(code, _)| code);
|
||||
let code = match tagged {
|
||||
Some(
|
||||
code @ ("validation_failed" | "timed_out" | "permission_denied" | "not_found"
|
||||
| "conflict" | "invalid_encoding" | "invalid_json" | "invalid_csv"
|
||||
| "invalid_toml" | "transport_error" | "http_status" | "resource_limit"
|
||||
| "unsupported" | "invalid_argument" | "nonexistent_time"
|
||||
| "ambiguous_time"),
|
||||
) => code,
|
||||
_ if message.starts_with("path escapes sandbox root:")
|
||||
|| message.ends_with("denied by host policy") =>
|
||||
{
|
||||
"permission_denied"
|
||||
}
|
||||
_ => "operation_failed",
|
||||
};
|
||||
(
|
||||
false,
|
||||
Value::None,
|
||||
Value::Map(vec![
|
||||
("code".into(), Value::Text(code.into())),
|
||||
("message".into(), Value::Text(message)),
|
||||
("operation".into(), Value::Text(operation.into())),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
Value::Map(vec![
|
||||
("ok".into(), Value::Bool(ok)),
|
||||
("value".into(), value),
|
||||
("error".into(), error),
|
||||
])
|
||||
}
|
||||
@@ -277,6 +277,25 @@ pub fn inspect(id: &str) -> Result<serde_json::Value, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Byte-preserving overlay access shared by text and byte APIs.
|
||||
pub(super) fn cow_read_bytes(ctx: &HostContext, abs: &Path) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(None); };
|
||||
with_session(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
if session.whiteout.contains(&rel) { return Err(format!("not found (sandbox whiteout): {rel}")); }
|
||||
Ok(session.upper.get(&rel).cloned())
|
||||
})
|
||||
}
|
||||
pub(super) fn cow_write_bytes(ctx: &HostContext, abs: &Path, bytes: &[u8]) -> Result<bool, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(false); };
|
||||
with_session_mut(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
session.whiteout.remove(&rel);
|
||||
session.upper.insert(rel, bytes.to_vec());
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read file bytes through CoW for an active host sandbox session (lib/fs).
|
||||
pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result<Option<String>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
|
||||
+55
-10
@@ -302,6 +302,11 @@ fn spawn_file(
|
||||
));
|
||||
let mut cmd = Command::new(&exe);
|
||||
cmd.arg("run").arg(&file);
|
||||
if !ctx.caps.fs_write { cmd.arg("--deny-fs-write"); }
|
||||
if !ctx.caps.exec { cmd.arg("--deny-exec"); }
|
||||
if !ctx.caps.net { cmd.arg("--deny-net"); }
|
||||
if !ctx.caps.plugin { cmd.arg("--deny-plugin"); }
|
||||
if let Some(root) = &ctx.fs_root { cmd.arg("--fs-root").arg(root); }
|
||||
cmd.arg("--emit-result").arg(&result_path);
|
||||
cmd.current_dir(&ctx.cwd);
|
||||
cmd.stdin(Stdio::null());
|
||||
@@ -340,18 +345,10 @@ fn spawn_file(
|
||||
let mut stdout_pipe = child.stdout.take();
|
||||
let mut stderr_pipe = child.stderr.take();
|
||||
let stdout = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stdout_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
stdout_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
let stderr = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stderr_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
stderr_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
(Some(stdout), Some(stderr))
|
||||
} else {
|
||||
@@ -679,6 +676,54 @@ pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(results))
|
||||
}
|
||||
|
||||
fn capture_file_io(reader:&mut impl Read)->String {
|
||||
let mut kept=Vec::new(); let mut buffer=[0u8;8192];
|
||||
loop { match reader.read(&mut buffer) {
|
||||
Ok(0)|Err(_)=>break,
|
||||
Ok(n)=>{ let take=(FILE_IO_CAP+4-kept.len()).min(n);kept.extend_from_slice(&buffer[..take]); }
|
||||
}}
|
||||
clip_io(&String::from_utf8_lossy(&kept))
|
||||
}
|
||||
|
||||
/// Timeout leaves the handle available unless cancel=True. Process cancellation
|
||||
/// reaps the OS child; function-thread cancellation is logical, as in kill().
|
||||
pub(super) fn wait_timeout(ctx:&mut HostContext,id:&Value,timeout_ms:u64,cancel:bool)->Result<Value,String>{
|
||||
let start=std::time::Instant::now();
|
||||
loop{
|
||||
let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{return join(ctx,id)}
|
||||
if start.elapsed()>=Duration::from_millis(timeout_ms){if cancel{kill(ctx,id)?;}return Err("timed_out: subtask wait deadline exceeded".into())}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
pub(super) fn run_many(ctx:&mut HostContext,tasks:&Value,limit:usize,timeout_ms:u64)->Result<Value,String>{
|
||||
let Value::List(tasks)=tasks else{return Err("tasks must be record list".into())};
|
||||
if !(1..=64).contains(&limit){return Err("limit must be 1..64".into())}
|
||||
if tasks.len()>10000{return Err("batch exceeds 10000 tasks".into())}
|
||||
// Validate the entire batch before starting any process.
|
||||
let jobs=tasks.iter().map(|task|{let Value::Map(fields)=task else{return Err("task must contain path and optional args".to_string())};
|
||||
let mut job=HashMap::new();for (key,value) in fields{if !matches!(key.as_str(),"path"|"args"){return Err(format!("unsupported batch field {key}"))}job.insert(key.clone(),value.clone());}
|
||||
let path=job.get("path").ok_or("task missing path")?;ctx.resolve_path(as_text(path,"path")?)?;Ok(job)
|
||||
}).collect::<Result<Vec<_>,String>>()?;
|
||||
let mut active:Vec<(usize,Value,std::time::Instant)>=Vec::new();let mut next=0;let mut out=vec![Value::None;jobs.len()];
|
||||
while next<jobs.len()||!active.is_empty(){
|
||||
while next<jobs.len()&&active.len()<limit{
|
||||
match spawn(ctx,&jobs[next]){Ok(id)=>active.push((next,id,std::time::Instant::now())),Err(error)=>out[next]=super::result::capture("subtask.run_many",Err(error))};next+=1;
|
||||
}
|
||||
let mut i=0;
|
||||
while i<active.len(){
|
||||
let (_,id,start)=&active[i];let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{let(index,id,_)=active.remove(i);out[index]=super::result::capture("subtask.run_many",join(ctx,&id));}
|
||||
else if start.elapsed()>=Duration::from_millis(timeout_ms){let(index,id,_)=active.remove(i);let _=kill(ctx,&id);out[index]=super::result::capture("subtask.run_many",Err("timed_out: batch task deadline exceeded".into()));}
|
||||
else{i+=1;}
|
||||
}
|
||||
if !active.is_empty(){thread::sleep(Duration::from_millis(5));}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
fn clip_io(s: &str) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(FILE_IO_CAP).collect();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Bounded orchestration over existing subtask resources.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "exec-host")]
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
fn integer(b: &HashMap<String, Value>, key: &str) -> Result<u64, String> {
|
||||
match arg(b, key)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{key} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
match id {
|
||||
HostFn::SubtaskWaitTimeout => {
|
||||
let answer = super::subtask::wait_timeout(
|
||||
ctx,
|
||||
arg(b, "id")?,
|
||||
integer(b, "timeout_ms")?,
|
||||
matches!(b.get("cancel"), Some(Value::Bool(true))),
|
||||
);
|
||||
Ok(super::result::capture("subtask.wait_timeout", answer))
|
||||
}
|
||||
HostFn::SubtaskCancelAll => {
|
||||
let count = ctx.subtasks.len();
|
||||
super::subtask::kill_all(ctx);
|
||||
Ok(Value::Int(count as i64))
|
||||
}
|
||||
HostFn::SubtaskRunMany => super::subtask::run_many(
|
||||
ctx,
|
||||
arg(b, "tasks")?,
|
||||
integer(b, "limit")? as usize,
|
||||
integer(b, "timeout_ms")?,
|
||||
),
|
||||
_ => Err("not a task operation".into()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, id, b);
|
||||
Err("subtask unavailable in this build".into())
|
||||
}
|
||||
}
|
||||
+30
-297
@@ -1,305 +1,38 @@
|
||||
//! Minimal TOML → Marqdo Value for Mid2 M8 (`lib/toml`).
|
||||
//! Subset: comments, keys, strings, ints, floats, bools, arrays of scalars,
|
||||
//! `[table]` / dotted tables. No datetime, inline tables, or array-of-tables.
|
||||
//! Standards-based TOML; datetime scalars become explicit ISO text at Value boundary.
|
||||
use crate::{host::as_text,value::Value};
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::host::json::json_to_value;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let json = toml_to_json(raw)?;
|
||||
json_to_value(&json)
|
||||
pub fn parse(text: &Value) -> Result<Value,String> {
|
||||
let parsed: toml::Value = toml::from_str(as_text(text,"text")?).map_err(|e|format!("toml.parse: {e}"))?;
|
||||
fn convert(v: toml::Value) -> Result<Value,String> {
|
||||
Ok(match v {
|
||||
toml::Value::String(s) => Value::Text(s),
|
||||
toml::Value::Integer(n) => Value::Int(n),
|
||||
toml::Value::Float(n) if n.is_finite() => Value::Num(n),
|
||||
toml::Value::Float(_) => return Err("toml: non-finite numbers unsupported".into()),
|
||||
toml::Value::Boolean(b) => Value::Bool(b),
|
||||
toml::Value::Datetime(dt) => Value::Text(dt.to_string()),
|
||||
toml::Value::Array(xs) => Value::List(xs.into_iter().map(convert).collect::<Result<_,_>>()?),
|
||||
toml::Value::Table(fields) => Value::Map(fields.into_iter().map(|(k,v)|convert(v).map(|v|(k,v))).collect::<Result<_,_>>()?),
|
||||
})
|
||||
}
|
||||
convert(parsed)
|
||||
}
|
||||
|
||||
fn toml_to_json(src: &str) -> Result<serde_json::Value, String> {
|
||||
let mut root = serde_json::Map::new();
|
||||
let mut current_path: Vec<String> = Vec::new();
|
||||
for (lineno, line) in src.lines().enumerate() {
|
||||
let line_no = lineno + 1;
|
||||
let stripped = strip_comment(line);
|
||||
let t = stripped.trim();
|
||||
if t.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if t.starts_with('[') {
|
||||
if !t.ends_with(']') {
|
||||
return Err(format!("toml.parse:{line_no}: bad table header"));
|
||||
}
|
||||
if t.starts_with("[[") {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: array-of-tables [[...]] not supported"
|
||||
));
|
||||
}
|
||||
let inner = t[1..t.len() - 1].trim();
|
||||
current_path = split_dotted_keys(inner, line_no)?;
|
||||
ensure_table_path(&mut root, ¤t_path, line_no)?;
|
||||
continue;
|
||||
}
|
||||
let (key, val) = t
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("toml.parse:{line_no}: expected key = value"))?;
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty key"));
|
||||
}
|
||||
let key_parts = split_dotted_keys(key, line_no)?;
|
||||
let value = parse_value(val.trim(), line_no)?;
|
||||
let parent = table_at_path(&mut root, ¤t_path, line_no)?;
|
||||
insert_dotted(parent, &key_parts, value, line_no)?;
|
||||
pub fn stringify(value:&Value)->Result<Value,String>{
|
||||
fn convert(v:&Value)->Result<toml::Value,String>{
|
||||
Ok(match v {
|
||||
Value::Text(s)=>toml::Value::String(s.clone()),
|
||||
Value::Int(n)=>toml::Value::Integer(*n),
|
||||
Value::Num(n) if n.is_finite()=>toml::Value::Float(*n),
|
||||
Value::Bool(b)=>toml::Value::Boolean(*b),
|
||||
Value::List(xs)=>toml::Value::Array(xs.iter().map(convert).collect::<Result<_,_>>()?),
|
||||
Value::Map(fields)=>toml::Value::Table(fields.iter().map(|(k,v)|convert(v).map(|v|(k.clone(),v))).collect::<Result<_,_>>()?),
|
||||
_=>return Err("toml.stringify supports text/finite numbers/bool/list/map; None has no TOML representation".into()),
|
||||
})
|
||||
}
|
||||
Ok(serde_json::Value::Object(root))
|
||||
if !matches!(value,Value::Map(_)){return Err("toml root must be map".into())}
|
||||
toml::to_string_pretty(&convert(value)?).map(Value::Text).map_err(|e|format!("toml.stringify: {e}"))
|
||||
}
|
||||
|
||||
fn strip_comment(line: &str) -> String {
|
||||
// Strip unquoted `#` comments.
|
||||
let mut out = String::new();
|
||||
let mut in_str = false;
|
||||
let mut chars = line.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if !in_str && c == '#' {
|
||||
break;
|
||||
}
|
||||
if c == '"' {
|
||||
out.push(c);
|
||||
in_str = !in_str;
|
||||
continue;
|
||||
}
|
||||
if in_str && c == '\\' {
|
||||
out.push(c);
|
||||
if let Some(n) = chars.next() {
|
||||
out.push(n);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn split_dotted_keys(s: &str, line_no: usize) -> Result<Vec<String>, String> {
|
||||
let mut parts = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut in_quote = false;
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '"' {
|
||||
in_quote = !in_quote;
|
||||
continue;
|
||||
}
|
||||
if c == '.' && !in_quote {
|
||||
if cur.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty key segment"));
|
||||
}
|
||||
parts.push(std::mem::take(&mut cur));
|
||||
continue;
|
||||
}
|
||||
cur.push(c);
|
||||
}
|
||||
if in_quote {
|
||||
return Err(format!("toml.parse:{line_no}: unclosed quoted key"));
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
parts.push(cur);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty path"));
|
||||
}
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
fn ensure_table_path(
|
||||
root: &mut serde_json::Map<String, serde_json::Value>,
|
||||
path: &[String],
|
||||
line_no: usize,
|
||||
) -> Result<(), String> {
|
||||
let mut cur = root;
|
||||
for seg in path {
|
||||
if !cur.contains_key(seg) {
|
||||
cur.insert(seg.clone(), serde_json::Value::Object(serde_json::Map::new()));
|
||||
}
|
||||
cur = match cur.get_mut(seg) {
|
||||
Some(serde_json::Value::Object(m)) => m,
|
||||
Some(_) => {
|
||||
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
|
||||
}
|
||||
None => unreachable!(),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn table_at_path<'a>(
|
||||
root: &'a mut serde_json::Map<String, serde_json::Value>,
|
||||
path: &[String],
|
||||
line_no: usize,
|
||||
) -> Result<&'a mut serde_json::Map<String, serde_json::Value>, String> {
|
||||
let mut cur = root;
|
||||
for seg in path {
|
||||
cur = match cur.get_mut(seg) {
|
||||
Some(serde_json::Value::Object(m)) => m,
|
||||
Some(_) => {
|
||||
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
|
||||
}
|
||||
None => {
|
||||
return Err(format!("toml.parse:{line_no}: missing table {seg}"));
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(cur)
|
||||
}
|
||||
|
||||
fn insert_dotted(
|
||||
parent: &mut serde_json::Map<String, serde_json::Value>,
|
||||
parts: &[String],
|
||||
value: serde_json::Value,
|
||||
line_no: usize,
|
||||
) -> Result<(), String> {
|
||||
if parts.len() == 1 {
|
||||
if parent.contains_key(&parts[0]) {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: duplicate key {}",
|
||||
parts[0]
|
||||
));
|
||||
}
|
||||
parent.insert(parts[0].clone(), value);
|
||||
return Ok(());
|
||||
}
|
||||
let head = &parts[0];
|
||||
let entry = parent
|
||||
.entry(head.clone())
|
||||
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
|
||||
let obj = match entry {
|
||||
serde_json::Value::Object(m) => m,
|
||||
_ => {
|
||||
return Err(format!("toml.parse:{line_no}: {head} is not a table"));
|
||||
}
|
||||
};
|
||||
insert_dotted(obj, &parts[1..], value, line_no)
|
||||
}
|
||||
|
||||
fn parse_value(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
|
||||
if s.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty value"));
|
||||
}
|
||||
if s == "true" {
|
||||
return Ok(serde_json::Value::Bool(true));
|
||||
}
|
||||
if s == "false" {
|
||||
return Ok(serde_json::Value::Bool(false));
|
||||
}
|
||||
if s.starts_with('"') {
|
||||
return Ok(serde_json::Value::String(parse_basic_string(s, line_no)?));
|
||||
}
|
||||
if s.starts_with('\'') {
|
||||
return Ok(serde_json::Value::String(parse_literal_string(s, line_no)?));
|
||||
}
|
||||
if s.starts_with('[') {
|
||||
return parse_array(s, line_no);
|
||||
}
|
||||
if let Ok(i) = s.replace('_', "").parse::<i64>() {
|
||||
return Ok(serde_json::Value::Number(i.into()));
|
||||
}
|
||||
if let Ok(f) = s.replace('_', "").parse::<f64>() {
|
||||
if let Some(n) = serde_json::Number::from_f64(f) {
|
||||
return Ok(serde_json::Value::Number(n));
|
||||
}
|
||||
}
|
||||
Err(format!("toml.parse:{line_no}: unsupported value {s:?}"))
|
||||
}
|
||||
|
||||
fn parse_basic_string(s: &str, line_no: usize) -> Result<String, String> {
|
||||
if !s.ends_with('"') || s.len() < 2 {
|
||||
return Err(format!("toml.parse:{line_no}: bad string"));
|
||||
}
|
||||
let inner = &s[1..s.len() - 1];
|
||||
let mut out = String::new();
|
||||
let mut chars = inner.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
match chars.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some('\\') => out.push('\\'),
|
||||
Some('"') => out.push('"'),
|
||||
Some(other) => {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: bad escape \\{other}"
|
||||
));
|
||||
}
|
||||
None => return Err(format!("toml.parse:{line_no}: trailing escape")),
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn parse_literal_string(s: &str, line_no: usize) -> Result<String, String> {
|
||||
if !s.ends_with('\'') || s.len() < 2 {
|
||||
return Err(format!("toml.parse:{line_no}: bad literal string"));
|
||||
}
|
||||
Ok(s[1..s.len() - 1].to_string())
|
||||
}
|
||||
|
||||
fn parse_array(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
|
||||
if !s.ends_with(']') {
|
||||
return Err(format!("toml.parse:{line_no}: bad array"));
|
||||
}
|
||||
let inner = s[1..s.len() - 1].trim();
|
||||
if inner.is_empty() {
|
||||
return Ok(serde_json::Value::Array(vec![]));
|
||||
}
|
||||
let mut items = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut depth = 0i32;
|
||||
let mut in_str = false;
|
||||
let mut str_ch = '"';
|
||||
let mut chars = inner.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if in_str {
|
||||
cur.push(c);
|
||||
if c == '\\' {
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c == str_ch {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' | '\'' => {
|
||||
in_str = true;
|
||||
str_ch = c;
|
||||
cur.push(c);
|
||||
}
|
||||
'[' => {
|
||||
depth += 1;
|
||||
cur.push(c);
|
||||
}
|
||||
']' => {
|
||||
depth -= 1;
|
||||
cur.push(c);
|
||||
}
|
||||
',' if depth == 0 => {
|
||||
items.push(parse_value(cur.trim(), line_no)?);
|
||||
cur.clear();
|
||||
}
|
||||
_ => cur.push(c),
|
||||
}
|
||||
}
|
||||
if !cur.trim().is_empty() {
|
||||
items.push(parse_value(cur.trim(), line_no)?);
|
||||
}
|
||||
Ok(serde_json::Value::Array(items))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+74
-2
@@ -188,6 +188,24 @@ pub fn matching_bold_close_inline(trimmed: &str) -> Option<usize> {
|
||||
matching_bold_close_opts(trimmed, false)
|
||||
}
|
||||
|
||||
// An occlusion label is prose: stars, quotes and backticks inside it are not
|
||||
// statement/return delimiters. Payload nesting is tracked by the callers.
|
||||
fn occlusion_payload_start(bytes: &[u8], start: usize) -> Option<usize> {
|
||||
if bytes.get(start) != Some(&b'[') {
|
||||
return None;
|
||||
}
|
||||
let mut i = start + 1;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\\' => i += 2,
|
||||
b']' => return (bytes.get(i + 1) == Some(&b'(')).then_some(i + 1),
|
||||
b'\n' | b'\r' => return None,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option<usize> {
|
||||
let Some(rest) = trimmed.strip_prefix("**") else {
|
||||
return None;
|
||||
@@ -196,6 +214,7 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option<usize> {
|
||||
let mut i = 0usize;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
let mut nesting = Vec::new();
|
||||
while i + 1 < bytes.len() {
|
||||
let c = bytes[i];
|
||||
if in_str {
|
||||
@@ -216,7 +235,27 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option<usize> {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b'[' {
|
||||
if let Some(payload) = occlusion_payload_start(bytes, i) {
|
||||
i = payload;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match c {
|
||||
b'(' | b'[' | b'{' => {
|
||||
nesting.push(match c {
|
||||
b'(' => b')',
|
||||
b'[' => b']',
|
||||
_ => b'}',
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
b')' | b']' | b'}' => {
|
||||
if nesting.last() == Some(&c) {
|
||||
nesting.pop();
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
b'`' => {
|
||||
in_bt = true;
|
||||
i += 1;
|
||||
@@ -225,7 +264,7 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option<usize> {
|
||||
in_str = true;
|
||||
i += 1;
|
||||
}
|
||||
b'*' if bytes[i + 1] == b'*' => {
|
||||
b'*' if bytes[i + 1] == b'*' && nesting.is_empty() => {
|
||||
let after = i + 2;
|
||||
if !require_eol || rest[after..].trim().is_empty() {
|
||||
return Some(2 + i);
|
||||
@@ -260,6 +299,7 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option<usize>
|
||||
let mut i = 1usize; // skip opening *
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
let mut nesting = Vec::new();
|
||||
while i < bytes.len() {
|
||||
let c = bytes[i];
|
||||
if in_str {
|
||||
@@ -280,7 +320,27 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option<usize>
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b'[' {
|
||||
if let Some(payload) = occlusion_payload_start(bytes, i) {
|
||||
i = payload;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match c {
|
||||
b'(' | b'[' | b'{' => {
|
||||
nesting.push(match c {
|
||||
b'(' => b')',
|
||||
b'[' => b']',
|
||||
_ => b'}',
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
b')' | b']' | b'}' => {
|
||||
if nesting.last() == Some(&c) {
|
||||
nesting.pop();
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
b'`' => {
|
||||
in_bt = true;
|
||||
i += 1;
|
||||
@@ -289,7 +349,7 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option<usize>
|
||||
in_str = true;
|
||||
i += 1;
|
||||
}
|
||||
b'*' => {
|
||||
b'*' if nesting.is_empty() => {
|
||||
if !require_eol || trimmed[i + 1..].trim().is_empty() {
|
||||
return Some(i);
|
||||
}
|
||||
@@ -723,3 +783,15 @@ mod tests {
|
||||
assert_eq!(lines[4].kind, LineKind::Code, "assign recovers after bad line");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inline_occlusion_boundaries {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn prose_stars_and_payload_products_keep_the_real_return_boundary() {
|
||||
let source = r#"*[multiply x*y and keep "raw" text](2 * (3 + 1))* after the result"#;
|
||||
assert_eq!(matching_italic_close_inline(source), source.find("* after"));
|
||||
let source = r#"**answer = [render **literal** marker](helper(text="**", value=(2 * 3)))** then continue"#;
|
||||
assert_eq!(matching_bold_close_inline(source), source.find("** then"));
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -120,6 +120,19 @@ enum Commands {
|
||||
#[arg(long = "fs-root", value_name = "DIR")]
|
||||
fs_root: Option<PathBuf>,
|
||||
|
||||
/// Deny filesystem writes in this run and its file subtasks.
|
||||
#[arg(long)]
|
||||
deny_fs_write: bool,
|
||||
/// Deny process execution.
|
||||
#[arg(long)]
|
||||
deny_exec: bool,
|
||||
/// Deny network access.
|
||||
#[arg(long)]
|
||||
deny_net: bool,
|
||||
/// Deny native plugin loading.
|
||||
#[arg(long)]
|
||||
deny_plugin: bool,
|
||||
|
||||
/// Isolated worker: call `lib.member` on the site entry instead of `# main`.
|
||||
#[arg(long = "call-lib-path", value_name = "LIB.MEMBER")]
|
||||
call_lib_path: Option<String>,
|
||||
@@ -158,10 +171,14 @@ enum Commands {
|
||||
#[arg(long, value_enum, default_value_t = BackendCli::Tree)]
|
||||
backend: BackendCli,
|
||||
|
||||
/// Side effects this call may perform (`none` = pure only; `plugin` allows ABI plugins).
|
||||
/// Comma-separated effect grants: none, plugin, fs.read, fs.write, output.write, etc.
|
||||
#[arg(long, default_value = "none")]
|
||||
effects: String,
|
||||
|
||||
/// Directory available to file tools; defaults to the called file directory.
|
||||
#[arg(long)]
|
||||
fs_root: Option<PathBuf>,
|
||||
|
||||
/// Call-session id for `toget` / `$name` (default: env `MARQDO_CALL_SESSION` or `default`).
|
||||
#[arg(long)]
|
||||
session: Option<String>,
|
||||
@@ -769,6 +786,10 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
args_json,
|
||||
json: _,
|
||||
legacy_markup,
|
||||
deny_fs_write,
|
||||
deny_exec,
|
||||
deny_net,
|
||||
deny_plugin,
|
||||
} => {
|
||||
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
|
||||
let stdin_lines = match stdin_file {
|
||||
@@ -809,6 +830,10 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
..RunOptions::default()
|
||||
}
|
||||
};
|
||||
opts.allow_fs_write = !deny_fs_write;
|
||||
opts.allow_exec = !deny_exec;
|
||||
opts.allow_net = !deny_net;
|
||||
opts.allow_plugin = !deny_plugin;
|
||||
if dump_all {
|
||||
opts.backend = backend.into();
|
||||
}
|
||||
@@ -828,6 +853,7 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
json,
|
||||
backend,
|
||||
effects,
|
||||
fs_root,
|
||||
session,
|
||||
toget,
|
||||
} => {
|
||||
@@ -858,6 +884,7 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
backend.into(),
|
||||
marqdo::call::CallOptions {
|
||||
effects,
|
||||
fs_root,
|
||||
session,
|
||||
toget,
|
||||
},
|
||||
|
||||
+81
-21
@@ -94,44 +94,86 @@ fn collect_starts(fns: &[Function], out: &mut Vec<(String, u32, usize)>) {
|
||||
|
||||
/// Split a function unit's source into narrative vs code character counts.
|
||||
///
|
||||
/// Code: lines that are primarily executable markers (`>`, `**`, `*…*`, `+`, tables with `|`,
|
||||
/// fences, `#`/`##` headings themselves). Narrative: remaining prose (including formula fences
|
||||
/// content is counted as narrative — formulas are documentation).
|
||||
/// Count executable inline payloads separately from the sentences containing them.
|
||||
/// Occlusion labels and unbound contract/documentation tables are narration;
|
||||
/// bound data tables, expression payloads, code fences and structure markers are code.
|
||||
/// Display formulas retain the existing documentation treatment.
|
||||
pub fn split_narrative_code(chunk: &str) -> (usize, usize) {
|
||||
use crate::parse::{scan_md_links_in_line, scan_prose_line, ProseBit};
|
||||
let mut narrative = 0usize;
|
||||
let mut code = 0usize;
|
||||
let mut in_fence = false;
|
||||
let mut fence_is_formula = false;
|
||||
let mut pending_table = false;
|
||||
let mut data_table = false;
|
||||
for line in chunk.lines() {
|
||||
let trimmed = line.trim();
|
||||
let count = line.chars().count();
|
||||
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
|
||||
in_fence = !in_fence;
|
||||
fence_is_formula = trimmed.contains("$$") || trimmed == "$$";
|
||||
// Fence markers themselves are markup/code budget.
|
||||
code += line.chars().count();
|
||||
code += count;
|
||||
continue;
|
||||
}
|
||||
if in_fence {
|
||||
// Math/display fences count as narration; language fences as code.
|
||||
if fence_is_formula {
|
||||
narrative += line.chars().count();
|
||||
narrative += count;
|
||||
} else {
|
||||
code += line.chars().count();
|
||||
code += count;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if trimmed.is_empty() {
|
||||
data_table = false;
|
||||
continue;
|
||||
}
|
||||
// Standalone $$ formula blocks (Marqdo formula assignment bodies).
|
||||
if trimmed == "$$" || trimmed.starts_with("$$") {
|
||||
narrative += line.chars().count();
|
||||
if trimmed.starts_with('|') {
|
||||
if pending_table {
|
||||
data_table = true;
|
||||
pending_table = false;
|
||||
}
|
||||
if data_table {
|
||||
code += count;
|
||||
} else {
|
||||
narrative += count;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_code_line(trimmed) {
|
||||
code += line.chars().count();
|
||||
data_table = false;
|
||||
pending_table = (trimmed.starts_with('`') && trimmed.ends_with('='))
|
||||
|| (trimmed.starts_with("**")
|
||||
&& trimmed.ends_with("**")
|
||||
&& trimmed[2..trimmed.len() - 2].trim_end().ends_with('='));
|
||||
if trimmed.starts_with("$$") {
|
||||
narrative += count;
|
||||
continue;
|
||||
}
|
||||
let mut inline_code = 0;
|
||||
for bit in scan_prose_line(line) {
|
||||
let (inner, markers) = match bit {
|
||||
ProseBit::BoldCode { inner, .. } => (inner, 4),
|
||||
ProseBit::ItalicReturn { inner, .. } => (inner, 2),
|
||||
ProseBit::Decl { .. } => continue,
|
||||
};
|
||||
let labels: usize = scan_md_links_in_line(&inner, 0)
|
||||
.iter()
|
||||
.map(|link| link.label.chars().count())
|
||||
.sum();
|
||||
inline_code += (inner.chars().count() + markers).saturating_sub(labels);
|
||||
}
|
||||
if inline_code > 0 {
|
||||
let actual = inline_code.min(count);
|
||||
code += actual;
|
||||
narrative += count - actual;
|
||||
} else if is_code_line(trimmed) || pending_table {
|
||||
let labels: usize = scan_md_links_in_line(line, 0)
|
||||
.iter()
|
||||
.map(|link| link.label.chars().count())
|
||||
.sum();
|
||||
narrative += labels.min(count);
|
||||
code += count.saturating_sub(labels);
|
||||
} else {
|
||||
narrative += line.chars().count();
|
||||
narrative += count;
|
||||
}
|
||||
}
|
||||
(narrative, code)
|
||||
@@ -200,10 +242,7 @@ This paragraph keeps narration above half even with a small table.
|
||||
*None*
|
||||
"#;
|
||||
let (n, c) = split_narrative_code(chunk);
|
||||
assert!(
|
||||
(n as f64) / ((n + c) as f64) >= 0.5,
|
||||
"n={n} c={c}"
|
||||
);
|
||||
assert!((n as f64) / ((n + c) as f64) >= 0.5, "n={n} c={c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -214,9 +253,30 @@ This paragraph keeps narration above half even with a small table.
|
||||
*> quantum_h circuit=`self` qubit=`qubit`*
|
||||
"#;
|
||||
let (n, c) = split_narrative_code(chunk);
|
||||
assert!(
|
||||
(n as f64) / ((n + c) as f64) < 0.5,
|
||||
"n={n} c={c}"
|
||||
assert!((n as f64) / ((n + c) as f64) < 0.5, "n={n} c={c}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inline_measurement_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn inline_expressions_are_not_all_prose() {
|
||||
let (n, c) =
|
||||
split_narrative_code("Now **out = [Read the value](lookup(key=\"selected\"))**.");
|
||||
assert_eq!(
|
||||
n,
|
||||
"Now .".chars().count() + "Read the value".chars().count()
|
||||
);
|
||||
assert!(c > n);
|
||||
}
|
||||
#[test]
|
||||
fn bound_data_is_code_but_contracts_are_narration() {
|
||||
let table = "| field | value |\n|---|---|\n| example | item |";
|
||||
let (n, c) = split_narrative_code(table);
|
||||
assert!(n > 0 && c == 0);
|
||||
let (n, c) = split_narrative_code(&format!("`record` =\n\n{table}"));
|
||||
assert_eq!(n, 0);
|
||||
assert!(c > 0);
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -2470,7 +2470,34 @@ fn split_table_row(line: &str) -> Vec<String> {
|
||||
let t = line.trim();
|
||||
let t = t.strip_prefix('|').unwrap_or(t);
|
||||
let t = t.strip_suffix('|').unwrap_or(t);
|
||||
t.split('|').map(|c| c.trim().to_string()).collect()
|
||||
// GFM escaped pipes belong to a cell, including inside a quoted value.
|
||||
// Preserve other escapes for the expression parser (e.g. \n in text).
|
||||
let mut cells = Vec::new();
|
||||
let mut cell = String::new();
|
||||
let mut chars = t.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '\\' {
|
||||
match chars.peek().copied() {
|
||||
Some('|') => {
|
||||
chars.next();
|
||||
cell.push('|');
|
||||
}
|
||||
Some('\\') => {
|
||||
chars.next();
|
||||
cell.push('\\');
|
||||
cell.push('\\');
|
||||
}
|
||||
_ => cell.push(ch),
|
||||
}
|
||||
} else if ch == '|' {
|
||||
cells.push(cell.trim().to_string());
|
||||
cell.clear();
|
||||
} else {
|
||||
cell.push(ch);
|
||||
}
|
||||
}
|
||||
cells.push(cell.trim().to_string());
|
||||
cells
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2886,3 +2913,21 @@ pub const CORE_CONSTRUCTS: &[(&str, &str)] = &[
|
||||
("footnote-index", "集合[^键]"),
|
||||
("soft-emphasis", "*仅* / **说明**"),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod escaped_gfm_cell_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn escaped_pipes_do_not_create_columns() {
|
||||
assert_eq!(
|
||||
split_table_row(r#"| "source\|skill" | "line\n" |"#),
|
||||
[r#""source|skill""#, r#""line\n""#]
|
||||
);
|
||||
assert_eq!(split_table_row(r"| a\\| b |"), [r"a\\", "b"]);
|
||||
let module = parse_source(
|
||||
"## value\n\n`items` =\n\n| line |\n|---|\n| \"source\\|skill\" |\n\n*items*\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(format!("{:?}", module.functions[0].body).contains("source|skill"));
|
||||
}
|
||||
}
|
||||
+47
-6
@@ -290,12 +290,32 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> {
|
||||
let after_tick = start + 1 + end + 1;
|
||||
let after = line.get(after_tick..)?;
|
||||
if let Some(stripped) = after.strip_prefix('=') {
|
||||
let def_end = stripped
|
||||
.find(|c: char| {
|
||||
c.is_whitespace()
|
||||
|| matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`')
|
||||
})
|
||||
.unwrap_or(stripped.len());
|
||||
// Quoted defaults may contain prose delimiters, glob stars or spaces.
|
||||
// Keep the same quoted literal accepted by explicit parameter defaults.
|
||||
let def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() {
|
||||
let mut escaped = false;
|
||||
stripped
|
||||
.char_indices()
|
||||
.skip(1)
|
||||
.find_map(|(i, ch)| {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == quote {
|
||||
return Some(i + ch.len_utf8());
|
||||
}
|
||||
None
|
||||
})
|
||||
.unwrap_or(stripped.len())
|
||||
} else {
|
||||
stripped
|
||||
.find(|c: char| {
|
||||
c.is_whitespace()
|
||||
|| matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`')
|
||||
})
|
||||
.unwrap_or(stripped.len())
|
||||
};
|
||||
let default = stripped[..def_end].to_string();
|
||||
let next = after_tick + 1 + def_end;
|
||||
return Some((
|
||||
@@ -369,6 +389,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_defaults_keep_delimiters_and_escaped_quotes() {
|
||||
let line = r#"输入 `pattern`="**";`mime`="text/plain;charset=utf-8";`label`="a, b \"quoted\""。"#;
|
||||
let bits = scan_prose_line(line);
|
||||
let defaults: Vec<_> = bits
|
||||
.iter()
|
||||
.filter_map(|bit| match bit {
|
||||
ProseBit::Decl { name, default, .. } => Some((name.as_str(), default.as_deref())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
defaults,
|
||||
vec![
|
||||
("pattern", Some(r#""**""#)),
|
||||
("mime", Some(r#""text/plain;charset=utf-8""#)),
|
||||
("label", Some(r#""a, b \"quoted\"""#))
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_bold_emphasis_skipped() {
|
||||
let bits = scan_prose_line("本文件既是**说明**也是**程序**。");
|
||||
|
||||
+4
-1
@@ -41,7 +41,10 @@ pub fn lookup_local<'a>(module: &'a Module, current: &'a Function, name: &str) -
|
||||
super::resolution::lookup(&super::resolution::AstView::default(), &module, current, name)
|
||||
}
|
||||
pub fn resolve_for_exec<'a>(module: &'a Module, current: &'a Function, call: &CallExpr) -> ExecTarget<'a> {
|
||||
super::resolution::resolve(&super::resolution::AstView::default(), &module, current, call)
|
||||
match call.for_evaluation() {
|
||||
Ok(normalized) => super::resolution::resolve(&super::resolution::AstView::default(), &module, current, &normalized),
|
||||
Err(message) => ExecTarget::Unresolved { message, span_hint: None },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_static_bound(target: &ExecTarget<'_>) -> bool {
|
||||
|
||||
+71
-33
@@ -323,6 +323,24 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
||||
}
|
||||
}
|
||||
close_effect_dependencies(&mut artifacts);
|
||||
let resolved_effects: BTreeMap<_,_> = artifacts.iter()
|
||||
.map(|artifact|(artifact.artifact_id.clone(),artifact.effects.clone())).collect();
|
||||
for bound in &mut bound_calls {
|
||||
if let Some(effects) = resolved_effects.get(&ArtifactId(bound.target.as_str().into())) {
|
||||
bound.required_effects = effects.clone();
|
||||
}
|
||||
}
|
||||
let mut callsite_effects: BTreeMap<(String,u32),EffectSet> = BTreeMap::new();
|
||||
for bound in &bound_calls {
|
||||
callsite_effects.entry((bound.source.file.clone(),bound.source.line))
|
||||
.or_default().extend(&bound.required_effects);
|
||||
}
|
||||
for step in &mut steps {
|
||||
if let Some(effects) = callsite_effects.get(&(step.source.file.clone(),step.source.line)) {
|
||||
step.effects.extend(effects);
|
||||
}
|
||||
if step.effects.0.is_empty() { step.effects = EffectSet::pure(); }
|
||||
}
|
||||
close_closure_digests(&mut artifacts);
|
||||
artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0));
|
||||
refs.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
@@ -455,6 +473,10 @@ fn attach_project_imports(files: &mut BTreeMap<ModuleId, (PathBuf, String, Modul
|
||||
let key = path_key(&resolved);
|
||||
if let Some(dep) = by_path.get(&key) {
|
||||
import_modules.insert(imp.bind.clone(), dep.clone());
|
||||
} else if let Ok(dep) = crate::load::load_module(&resolved) {
|
||||
// External standard libraries are outside a project-only index,
|
||||
// but their resolved bodies still determine effects.
|
||||
import_modules.insert(imp.bind.clone(), dep);
|
||||
}
|
||||
}
|
||||
module.import_modules = import_modules;
|
||||
@@ -511,7 +533,7 @@ fn artifact_for_function(
|
||||
Vec<super::provenance::ProvenanceDiag>,
|
||||
) {
|
||||
let calls = collect_call_sites(function);
|
||||
let mut effects = direct_effects(&calls);
|
||||
let mut effects = direct_effects(index, ast_module, function, &calls);
|
||||
let mut dependencies = Vec::new();
|
||||
let mut bound_calls = Vec::new();
|
||||
let mut dynamic_calls = Vec::new();
|
||||
@@ -561,11 +583,10 @@ fn artifact_for_function(
|
||||
.unwrap_or_else(|| named.resolution.clone()),
|
||||
target: target.clone(),
|
||||
});
|
||||
let step_effects = named
|
||||
.call
|
||||
.as_ref()
|
||||
.map(effects_for_call)
|
||||
.unwrap_or_else(EffectSet::pure);
|
||||
let mut step_effects = EffectSet::default();
|
||||
for (_, call, line) in &calls {
|
||||
if *line == named.line { step_effects.extend(&effects_for_call(ast_module,function,call,Some(index))); }
|
||||
}
|
||||
steps.push(KnowledgeStep {
|
||||
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
|
||||
reference: ref_id,
|
||||
@@ -719,7 +740,7 @@ fn classify_call(
|
||||
};
|
||||
CallClass::Bound {
|
||||
target,
|
||||
effects: effects_for_call(call),
|
||||
effects: EffectSet::default(),
|
||||
}
|
||||
}
|
||||
ExecTarget::Import { bind, lib, fun, path } => {
|
||||
@@ -754,7 +775,7 @@ fn classify_call(
|
||||
};
|
||||
CallClass::Bound {
|
||||
target,
|
||||
effects: effects_for_call(call),
|
||||
effects: EffectSet::default(),
|
||||
}
|
||||
}
|
||||
ExecTarget::Builtin(_) | ExecTarget::Host(_) => CallClass::Other,
|
||||
@@ -1037,35 +1058,50 @@ fn call_name(call: &CallExpr) -> String {
|
||||
call_display(call)
|
||||
}
|
||||
|
||||
fn effects_for_call(call: &CallExpr) -> EffectSet {
|
||||
let name = call_name(call).to_ascii_lowercase();
|
||||
fn effects_for_call(module: &Module, current: &Function, call: &CallExpr, index: Option<&ProjectIndex>) -> EffectSet {
|
||||
let mut effects = EffectSet::default();
|
||||
let effect = if name.starts_with("fs.") || name.contains("writeback") { if name.contains("write") || name.contains("remove") || name.contains("move") || name.contains("mkdir") { "fs.write" } else { "fs.read" } }
|
||||
else if name.starts_with("http.") || name.starts_with("net.") { if name.contains("post") || name.contains("put") || name.contains("delete") { "network.write" } else { "network.read" } }
|
||||
else if name.starts_with("foreign.") || name.starts_with("subtask.") || name == "exec" { "process.exec" }
|
||||
else if name.starts_with("plugin.") { "plugin.call" }
|
||||
else if name.starts_with("llm.") || name.starts_with("openai.") { "llm.call" }
|
||||
else if name.starts_with("time.") || name.starts_with("datetime.") { "time.read" }
|
||||
else if name.starts_with("random.") || name.starts_with("uuid.") { "random.read" }
|
||||
else if name.starts_with("input") { "user.input" }
|
||||
else if name.starts_with("print") || name.starts_with("log.") { "output.write" }
|
||||
else if is_observe_call(call) {
|
||||
return EffectSet::pure();
|
||||
} else if call.path.is_some() || (call.path.is_none() && call.receiver.is_none()) {
|
||||
// Local bare name or import path: effects filled by BoundCall dependency
|
||||
// closure. Do not guess pure / unknown here.
|
||||
return EffectSet::default();
|
||||
} else {
|
||||
// Receiver / unresolved dynamic — unknown (G06).
|
||||
return EffectSet::unknown();
|
||||
};
|
||||
effects.add(effect);
|
||||
match resolve_for_exec(module, current, call) {
|
||||
ExecTarget::Host(host) => {
|
||||
for effect in host.effects() { effects.add(*effect); }
|
||||
}
|
||||
ExecTarget::Builtin("print") => effects.add("output.write"),
|
||||
ExecTarget::Builtin("input") => effects.add("user.input"),
|
||||
ExecTarget::Builtin(_) => return EffectSet::pure(),
|
||||
ExecTarget::Local(_) => {},
|
||||
ExecTarget::Import { lib, fun, .. } => {
|
||||
if index.is_some_and(|index| lib.source.path.as_ref().is_some_and(|path| index.module_id_for_path(path).is_some())) {
|
||||
// Project-indexed dependencies close by edges, not shallow AST clones.
|
||||
return EffectSet::default();
|
||||
}
|
||||
return imported_effects(lib, fun, &mut std::collections::HashSet::new());
|
||||
},
|
||||
ExecTarget::Dynamic { reason: DynamicReason::Plugin, .. } => effects.add("plugin.call"),
|
||||
ExecTarget::Dynamic { .. } | ExecTarget::Unresolved { .. } => return EffectSet::unknown(),
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
fn direct_effects(calls: &[(usize, CallExpr, u32)]) -> EffectSet {
|
||||
fn imported_effects(
|
||||
module: &Module, function: &Function,
|
||||
visiting: &mut std::collections::HashSet<(Option<PathBuf>, u32)>,
|
||||
) -> EffectSet {
|
||||
let identity = (module.source.path.clone(), function.span.line);
|
||||
if !visiting.insert(identity.clone()) { return EffectSet::default(); }
|
||||
let mut effects = EffectSet::default();
|
||||
for (_, call, _) in calls { effects.extend(&effects_for_call(call)); }
|
||||
for (_, call, _) in collect_call_sites(function) {
|
||||
match resolve_for_exec(module, function, &call) {
|
||||
ExecTarget::Local(fun) => effects.extend(&imported_effects(module, fun, visiting)),
|
||||
ExecTarget::Import { lib, fun, .. } => effects.extend(&imported_effects(lib, fun, visiting)),
|
||||
_ => effects.extend(&effects_for_call(module, function, &call, None)),
|
||||
}
|
||||
}
|
||||
visiting.remove(&identity);
|
||||
effects
|
||||
}
|
||||
|
||||
fn direct_effects(index: &ProjectIndex, module: &Module, current: &Function, calls: &[(usize, CallExpr, u32)]) -> EffectSet {
|
||||
let mut effects = EffectSet::default();
|
||||
for (_, call, _) in calls { effects.extend(&effects_for_call(module, current, call, Some(index))); }
|
||||
effects
|
||||
}
|
||||
|
||||
@@ -1516,7 +1552,7 @@ mod tests {
|
||||
#[test]
|
||||
fn compilation_is_deterministic_and_preserves_contract_effects() {
|
||||
let root = root();
|
||||
fs::write(root.join("main.mq.md"), "# main\n\n| 参数 | 类型 |\n| --- | --- |\n| path | text |\n\n## save\n\n> fs.write_text `path` ok\n\n*1*").unwrap();
|
||||
fs::write(root.join("main.mq.md"), "---\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n| 参数 | 类型 |\n| --- | --- |\n| path | text |\n\n## save\n\n> fs.write_text `path` ok\n\n*1*").unwrap();
|
||||
let options = CompileOptions::for_path(&root).unwrap();
|
||||
let first = compile_project(&options).unwrap();
|
||||
let second = compile_project(&options).unwrap();
|
||||
@@ -1545,6 +1581,8 @@ mod tests {
|
||||
root.join("main.mq.md"),
|
||||
r#"---
|
||||
markup: occlusion
|
||||
import:
|
||||
fs: lib/fs.mq.md
|
||||
---
|
||||
|
||||
## save
|
||||
|
||||
+2
-1
@@ -143,8 +143,9 @@ impl ProjectIndex {
|
||||
);
|
||||
}
|
||||
path_to_module.insert(file.clone(), module_id.clone());
|
||||
let module = crate::load::parse_source_auto(&source)
|
||||
let mut module = crate::load::parse_source_auto(&source)
|
||||
.with_context(|| format!("parse source {}", file.display()))?;
|
||||
module.source.path = Some(file.clone());
|
||||
for function in &module.functions {
|
||||
collect_symbols(
|
||||
&project_id,
|
||||
|
||||
+371
-227
@@ -26,10 +26,12 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
let special = index_special_assigns(module, source);
|
||||
let skip_body = special_body_lines(&special);
|
||||
let stmt_lines = index_stmt_lines(module);
|
||||
let occluded_lines = index_occluded_lines(module);
|
||||
let writebacks = writeback::writeback_map(source);
|
||||
let taken_arms = taken_arms_by_branch_line(annots);
|
||||
|
||||
let mut out = String::from(r#"<div class="document-surface">"#);
|
||||
out.push_str(&render_syntax_guide());
|
||||
|
||||
if !module.imports.is_empty() || !module.uses.is_empty() {
|
||||
out.push_str(r#"<div class="doc-imports">"#);
|
||||
@@ -62,10 +64,11 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
.map(|(_, t)| t.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
|
||||
para.clear();
|
||||
let md = comment_markdown_to_html(&text);
|
||||
out.push_str(&format!(
|
||||
r#"<div class="doc-block" data-line="{line}"><div class="doc-prose">{md}</div></div>"#,
|
||||
r#"<div class="doc-block" data-line="{line}" id="stmt-{line}">{source_anchors}<div class="doc-prose">{md}</div></div>"#,
|
||||
line = first_line,
|
||||
md = md
|
||||
));
|
||||
@@ -157,6 +160,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
special.get(&l.line_no),
|
||||
writebacks.get(&l.line_no),
|
||||
None,
|
||||
&occluded_lines,
|
||||
));
|
||||
} else if !trimmed.is_empty() {
|
||||
para.push((l.line_no, trimmed.to_string()));
|
||||
@@ -190,6 +194,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
&writebacks,
|
||||
&taken_arms,
|
||||
annots,
|
||||
&occluded_lines,
|
||||
);
|
||||
out.push_str(&html);
|
||||
i = next;
|
||||
@@ -205,6 +210,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
special.get(&l.line_no),
|
||||
writebacks.get(&l.line_no),
|
||||
None,
|
||||
&occluded_lines,
|
||||
));
|
||||
i += 1;
|
||||
}
|
||||
@@ -295,7 +301,7 @@ fn render_table_block(
|
||||
}
|
||||
let first_line = rows[0].0;
|
||||
let mut html = format!(
|
||||
r#"<div class="doc-block doc-table-wrap" data-line="{line}"><table class="doc-table">"#,
|
||||
r#"<div class="doc-block doc-table-wrap" data-line="{line}" id="stmt-{line}"><table class="doc-table">"#,
|
||||
line = first_line
|
||||
);
|
||||
let mut header_done = false;
|
||||
@@ -370,6 +376,7 @@ fn render_list_block(
|
||||
writebacks: &HashMap<u32, String>,
|
||||
taken_arms: &HashMap<u32, usize>,
|
||||
all_annots: &[ViewAnnot],
|
||||
occluded_lines: &HashSet<u32>,
|
||||
) -> (String, usize) {
|
||||
let base_indent = indent_level(&lines[start].text);
|
||||
let tag = match kind {
|
||||
@@ -407,8 +414,7 @@ fn render_list_block(
|
||||
let frames: Vec<&ViewAnnot> = all_annots
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
a.kind == crate::view::annot::AnnotKind::LoopFrame
|
||||
&& a.anchor_line == branch_line
|
||||
a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line
|
||||
})
|
||||
.collect();
|
||||
if frames.len() >= 2 {
|
||||
@@ -483,7 +489,7 @@ fn render_list_block(
|
||||
_ => "",
|
||||
};
|
||||
html.push_str(&format!(
|
||||
r#"<li class="doc-list-item {arm_cls}" data-line="{line}" data-arm-index="{arm_idx}" style="--doc-indent:{indent}">"#,
|
||||
r#"<li class="doc-list-item {arm_cls}" data-line="{line}" id="stmt-{line}" data-arm-index="{arm_idx}" style="--doc-indent:{indent}">"#,
|
||||
arm_cls = arm_cls,
|
||||
line = lines[i].line_no,
|
||||
arm_idx = arm_index,
|
||||
@@ -491,7 +497,12 @@ fn render_list_block(
|
||||
));
|
||||
html.push_str(&format!(
|
||||
r#"<div class="doc-list-head">{}</div>"#,
|
||||
render_surface_line(lines[i].line_no, head, by_line)
|
||||
render_surface_line(
|
||||
lines[i].line_no,
|
||||
head,
|
||||
by_line,
|
||||
occluded_lines.contains(&lines[i].line_no)
|
||||
)
|
||||
));
|
||||
// Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS).
|
||||
let mut head_annots: Vec<ViewAnnot> = Vec::new();
|
||||
@@ -515,9 +526,12 @@ fn render_list_block(
|
||||
}
|
||||
}
|
||||
}
|
||||
if !head_annots.is_empty() {
|
||||
html.push_str(&render_annot_band(&head_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
let notes = if occluded_lines.contains(&lines[i].line_no) {
|
||||
render_logic_notes(lines[i].line_no, head, &[])
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
html.push_str(&render_document_band(&head_annots, ¬es));
|
||||
// Body: following lines with greater indent until next sibling.
|
||||
i += 1;
|
||||
html.push_str(r#"<div class="doc-list-body">"#);
|
||||
@@ -525,9 +539,7 @@ fn render_list_block(
|
||||
let t2 = lines[i].text.trim_end_matches(['\r', '\n']);
|
||||
if t2.trim().is_empty() {
|
||||
// allow blank inside body
|
||||
if i + 1 < lines.len()
|
||||
&& indent_level(&lines[i + 1].text) > base_indent
|
||||
{
|
||||
if i + 1 < lines.len() && indent_level(&lines[i + 1].text) > base_indent {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -550,6 +562,7 @@ fn render_list_block(
|
||||
writebacks,
|
||||
taken_arms,
|
||||
all_annots,
|
||||
occluded_lines,
|
||||
);
|
||||
html.push_str(&inner);
|
||||
i = next;
|
||||
@@ -573,6 +586,7 @@ fn render_list_block(
|
||||
special.get(&lines[i].line_no),
|
||||
writebacks.get(&lines[i].line_no),
|
||||
Some(ind2),
|
||||
occluded_lines,
|
||||
));
|
||||
i += 1;
|
||||
}
|
||||
@@ -593,23 +607,25 @@ fn render_surface_line(
|
||||
line_no: u32,
|
||||
head: &str,
|
||||
by_line: &HashMap<u32, Vec<&ViewAnnot>>,
|
||||
occluded: bool,
|
||||
) -> String {
|
||||
if occluded && !occlusion_spans(head).is_empty() {
|
||||
return format!(
|
||||
r#"<mark class="mq-anchor mq-control" data-line="{line_no}" data-byte-start="0" data-byte-end="{}" title="循环或条件:实际控制逻辑见侧注">{}</mark>"#,
|
||||
head.len(),
|
||||
render_occlusion_text(line_no, head, 0)
|
||||
);
|
||||
}
|
||||
let bits = scan_prose_line(head);
|
||||
if bits.is_empty() {
|
||||
// Else arm "*" or plain condition text.
|
||||
if head.trim() == "*" {
|
||||
return r#"<span class="mq-else">else</span>"#.into();
|
||||
}
|
||||
format!(
|
||||
r#"<span class="doc-cond">{}</span>"#,
|
||||
escape(head)
|
||||
)
|
||||
format!(r#"<span class="doc-cond">{}</span>"#, escape(head))
|
||||
} else {
|
||||
let annots = by_line
|
||||
.get(&line_no)
|
||||
.map(|v| v.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
render_prose_with_marks(line_no, head, &bits, annots)
|
||||
let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]);
|
||||
render_prose_with_marks(line_no, head, &bits, annots, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,7 +651,7 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
r##"<div class="doc-fun" id="fn-{line}" data-fn="{name}" data-fn-path="{name}" data-line="{line}">
|
||||
<div class="doc-fun-bar">
|
||||
<h3 class="doc-fun-title">{name}</h3>
|
||||
<a class="knowledge-explain" href="#knowledge-{name}" data-node="{name}">说明</a>"##,
|
||||
<a class="knowledge-explain" href="#knowledge-fn-{line}" data-node="{name}">说明</a>"##,
|
||||
line = fun.span.line,
|
||||
name = escape(&fun.name),
|
||||
);
|
||||
@@ -645,7 +661,9 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
.filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name)
|
||||
.collect();
|
||||
if call_labels.len() >= 2 {
|
||||
s.push_str(r#"<label class="call-picker-label">调用 <select class="call-picker" data-fn=""#);
|
||||
s.push_str(
|
||||
r#"<label class="call-picker-label">调用 <select class="call-picker" data-fn=""#,
|
||||
);
|
||||
s.push_str(&escape(&fun.name));
|
||||
s.push_str(r#"">"#);
|
||||
for (i, a) in call_labels.iter().enumerate() {
|
||||
@@ -678,11 +696,7 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
.unwrap_or_default();
|
||||
s.push_str(r#"<div class="params">"#);
|
||||
for p in &fun.params {
|
||||
let cls = if p.inferred {
|
||||
"chip inferred"
|
||||
} else {
|
||||
"chip"
|
||||
};
|
||||
let cls = if p.inferred { "chip inferred" } else { "chip" };
|
||||
let title = if p.inferred {
|
||||
"inferred from prose / body"
|
||||
} else {
|
||||
@@ -725,155 +739,173 @@ fn parse_args_brief(brief: &str) -> HashMap<String, String> {
|
||||
m
|
||||
}
|
||||
|
||||
/// Split a statement line holding one occlusion `[描述](实现)`.
|
||||
///
|
||||
/// Returns `(prefix, label, payload, suffix)`. Display-only: the parser already
|
||||
/// validated the real structure, this just decides how to paint it.
|
||||
fn split_occlusion(line: &str) -> Option<(String, String, String, String)> {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let mut i = 0usize;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
/// Display-only source spans. The AST decides whether this line contains an occlusion.
|
||||
/// Scan only executable fragments, preserving quoted links as literal data.
|
||||
struct OcclusionSpan<'a> { start: usize, end: usize, label: &'a str, payload: &'a str }
|
||||
fn occlusion_spans(text: &str) -> Vec<OcclusionSpan<'_>> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if matches!(bytes[i], b'"' | b'\'' | b'`') {
|
||||
let quote = bytes[i];
|
||||
i += 1;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'\\' {
|
||||
i += 2;
|
||||
} else if bytes[i] == quote {
|
||||
i += 1;
|
||||
break;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => in_bt = true,
|
||||
'"' => in_str = true,
|
||||
'[' if chars.get(i + 1) != Some(&'^') => {
|
||||
if let Some(close) = match_delim(&chars, i, '[', ']') {
|
||||
if chars.get(close + 1) == Some(&'(') {
|
||||
if let Some(paren) = match_delim(&chars, close + 1, '(', ')') {
|
||||
let mut prefix: String = chars[..i].iter().collect();
|
||||
let label: String = chars[i + 1..close].iter().collect();
|
||||
let payload: String = chars[close + 2..paren].iter().collect();
|
||||
let suffix: String = chars[paren + 1..].iter().collect();
|
||||
// `**名 = [..](..)**` reads as bold code: drop the
|
||||
// emphasis markers so the label reads as prose.
|
||||
if let Some(p) = prefix.strip_suffix("**") {
|
||||
prefix = p.to_string();
|
||||
}
|
||||
prefix = prefix.trim_end().to_string();
|
||||
if let Some(p) = prefix.strip_prefix("**") {
|
||||
prefix = p.to_string();
|
||||
}
|
||||
let suffix = suffix.strip_prefix("**").unwrap_or(&suffix).to_string();
|
||||
return Some((
|
||||
prefix,
|
||||
label.trim().to_string(),
|
||||
payload.trim().to_string(),
|
||||
suffix.trim().to_string(),
|
||||
));
|
||||
}
|
||||
let start = i;
|
||||
let mut j = i + 1;
|
||||
let mut depth = 1;
|
||||
while j < bytes.len() {
|
||||
match bytes[j] {
|
||||
b'\\' => {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
b'[' => depth += 1,
|
||||
b']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
j += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn match_delim(chars: &[char], start: usize, open: char, close: char) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
let mut i = start;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
if depth != 0 || bytes.get(j + 1) != Some(&b'(') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => in_bt = true,
|
||||
'"' => in_str = true,
|
||||
c if c == open => depth += 1,
|
||||
c if c == close => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
let label_end = j;
|
||||
j += 2;
|
||||
let payload_start = j;
|
||||
depth = 1;
|
||||
while j < bytes.len() {
|
||||
match bytes[j] {
|
||||
b'"' | b'\'' | b'`' => {
|
||||
let quote = bytes[j];
|
||||
j += 1;
|
||||
while j < bytes.len() {
|
||||
if bytes[j] == b'\\' {
|
||||
j += 2;
|
||||
} else if bytes[j] == quote {
|
||||
j += 1;
|
||||
break;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'(' => depth += 1,
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
j += 1;
|
||||
}
|
||||
if depth == 0 {
|
||||
out.push(OcclusionSpan {
|
||||
start,
|
||||
end: j + 1,
|
||||
label: &text[start + 1..label_end],
|
||||
payload: text[payload_start..j].trim(),
|
||||
});
|
||||
i = j + 1;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
out
|
||||
}
|
||||
|
||||
/// Render one occlusion line: description as prose, payload as a code chip,
|
||||
/// stubs get a badge. `<TAB>` M8
|
||||
fn render_occlusion_line(line_no: u32, line: &str) -> Option<String> {
|
||||
let (prefix, label, payload, suffix) = split_occlusion(line)?;
|
||||
let stub = payload.is_empty();
|
||||
// The rest of the view drops backticks (see the `mq-anchor` marks), so the
|
||||
// assignment head reads as `留存 =` rather than `` `留存` = ``.
|
||||
let head = prefix
|
||||
.trim_end()
|
||||
.trim_end_matches('=')
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_string();
|
||||
let mut html = format!(r#"<div class="doc-line doc-occl" data-line="{line_no}">"#);
|
||||
if !head.is_empty() {
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-pre">{} =</span>"#,
|
||||
escape(&head)
|
||||
));
|
||||
fn logic_id(line: u32, at: usize) -> String {
|
||||
format!("logic-{line}-{at}")
|
||||
}
|
||||
fn render_occlusion_text(line: u32, text: &str, base: usize) -> String {
|
||||
let mut html = String::new();
|
||||
let mut cursor = 0;
|
||||
for span in occlusion_spans(text) {
|
||||
html.push_str(&escape(&text[cursor..span.start]));
|
||||
let id = logic_id(line, base + span.start);
|
||||
let label = if span.label.is_empty() {
|
||||
"未命名动作"
|
||||
} else {
|
||||
span.label
|
||||
};
|
||||
html.push_str(&format!(r#"<button type="button" class="occl-label" id="{id}-source" data-logic-id="{id}" aria-controls="{id}-note" title="查看实际逻辑(阅读不会执行)">{}</button>"#,escape(label)));
|
||||
if span.payload.is_empty() {
|
||||
html.push_str(r#"<span class="occl-stub">待补充实际逻辑</span>"#);
|
||||
}
|
||||
cursor = span.end;
|
||||
}
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-label">{}</span>"#,
|
||||
escape(&label)
|
||||
));
|
||||
if stub {
|
||||
html.push_str(r#"<span class="occl-stub" title="空载荷:未接通或待补返回值">桩</span>"#);
|
||||
} else {
|
||||
html.push_str(&format!(
|
||||
r#"<code class="occl-code">{}</code>"#,
|
||||
escape(&payload)
|
||||
));
|
||||
html.push_str(&escape(&text[cursor..]));
|
||||
html
|
||||
}
|
||||
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit]) -> String {
|
||||
let mut notes = String::new();
|
||||
let fragments: Vec<(usize, usize, &str)> =
|
||||
if bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
|
||||
vec![(0, text.len(), text)]
|
||||
} else {
|
||||
bits.iter()
|
||||
.filter_map(|bit| match bit {
|
||||
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } => {
|
||||
Some((bit_at(bit), prose_bit_end(text, bit), inner.as_str()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for (start, end, fragment) in fragments {
|
||||
for span in occlusion_spans(fragment) {
|
||||
let id = logic_id(line, start + span.start);
|
||||
let payload = if span.payload.is_empty() {
|
||||
"待补充实际逻辑;当前空遮蔽返回 None。"
|
||||
} else {
|
||||
span.payload
|
||||
};
|
||||
notes.push_str(&format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label">实际逻辑 · {label}</summary><code class="annot-value occl-code">{payload}</code><small class="logic-hint">源码说明 · 不是运行结果</small></details>"#,label=escape(span.label),payload=escape(payload)));
|
||||
}
|
||||
}
|
||||
if !suffix.is_empty() {
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-pre">{}</span>"#,
|
||||
escape(&suffix)
|
||||
));
|
||||
notes
|
||||
}
|
||||
fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String {
|
||||
let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS);
|
||||
if notes.is_empty() {
|
||||
return band;
|
||||
}
|
||||
html.push_str("</div>");
|
||||
Some(html)
|
||||
if band.is_empty() {
|
||||
return format!(
|
||||
r#"<div class="annot-band" data-annot-band><div class="annot-chips">{notes}</div></div>"#
|
||||
);
|
||||
}
|
||||
band.replacen(
|
||||
r#"<div class="annot-chips">"#,
|
||||
&format!(r#"<div class="annot-chips">{notes}"#),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
fn render_line_block(
|
||||
@@ -884,6 +916,7 @@ fn render_line_block(
|
||||
special: Option<&SpecialAssign>,
|
||||
writeback_body: Option<&String>,
|
||||
indent: Option<usize>,
|
||||
occluded_lines: &HashSet<u32>,
|
||||
) -> String {
|
||||
let indent_style = indent
|
||||
.map(|n| format!(r#" style="--doc-indent:{n}""#))
|
||||
@@ -900,37 +933,19 @@ fn render_line_block(
|
||||
s.push_str(&render_formula_assign_card(name, tex));
|
||||
}
|
||||
Some(SpecialAssign::Code {
|
||||
name,
|
||||
lang,
|
||||
source,
|
||||
..
|
||||
name, lang, source, ..
|
||||
}) => {
|
||||
s.push_str(&render_code_assign_card(name, lang, source));
|
||||
}
|
||||
None => {
|
||||
let trimmed = text.trim_start();
|
||||
// `<TAB>` M8: an occlusion line is painted as description + code chip
|
||||
// regardless of annotation bits (the annotator always emits spans).
|
||||
if let Some(html) = render_occlusion_line(line_no, trimmed) {
|
||||
s.push_str(&html);
|
||||
if let Some(body) = writeback_body {
|
||||
s.push_str(&crate::view::render::render_output_card(line_no, body));
|
||||
}
|
||||
// Must close `.doc-block` — an early return left the wrapper open and
|
||||
// nested the Functions/Variables outline under the document surface.
|
||||
let band_annots: Vec<ViewAnnot> = annots
|
||||
.iter()
|
||||
.filter(|a| !is_noisy_result_chip(a))
|
||||
.map(|a| (*a).clone())
|
||||
.collect();
|
||||
if !band_annots.is_empty() {
|
||||
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
return s;
|
||||
}
|
||||
if bits.is_empty() {
|
||||
if let Some(rest) = trimmed.strip_prefix("> ") {
|
||||
if bits.is_empty()
|
||||
|| (occluded_lines.contains(&line_no)
|
||||
&& bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })))
|
||||
{
|
||||
if occluded_lines.contains(&line_no) && !occlusion_spans(text).is_empty() {
|
||||
s.push_str(&format!(r#"<div class="doc-line doc-occl"><mark class="mq-anchor mq-code" data-line="{line_no}" data-byte-start="0" data-byte-end="{}">{}</mark></div>"#,text.len(),render_occlusion_text(line_no,text,0)));
|
||||
} else if let Some(rest) = trimmed.strip_prefix("> ") {
|
||||
let aid = match_annot_for_line(annots)
|
||||
.map(|a| a.id.as_str())
|
||||
.unwrap_or("");
|
||||
@@ -958,7 +973,13 @@ fn render_line_block(
|
||||
}
|
||||
} else {
|
||||
s.push_str(r#"<div class="doc-line doc-prose-line">"#);
|
||||
s.push_str(&render_prose_with_marks(line_no, text, bits, annots));
|
||||
s.push_str(&render_prose_with_marks(
|
||||
line_no,
|
||||
text,
|
||||
bits,
|
||||
annots,
|
||||
occluded_lines.contains(&line_no),
|
||||
));
|
||||
s.push_str("</div>");
|
||||
}
|
||||
}
|
||||
@@ -979,9 +1000,12 @@ fn render_line_block(
|
||||
.map(|a| (*a).clone())
|
||||
.collect()
|
||||
};
|
||||
if !band_annots.is_empty() {
|
||||
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
let notes = if special.is_none() && occluded_lines.contains(&line_no) {
|
||||
render_logic_notes(line_no, text, bits)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
s.push_str(&render_document_band(&band_annots, ¬es));
|
||||
|
||||
s.push_str("</div>");
|
||||
s
|
||||
@@ -1040,12 +1064,37 @@ fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, us
|
||||
(html, j)
|
||||
}
|
||||
|
||||
/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML
|
||||
/// stays literal here, as it did in mixed executable prose before this renderer.
|
||||
fn render_narrative_inline(text: &str) -> String {
|
||||
let inner = text.trim();
|
||||
if inner.is_empty() {
|
||||
return escape(text);
|
||||
}
|
||||
let start = text.find(inner).unwrap();
|
||||
let end = start + inner.len();
|
||||
let parser = pulldown_cmark::Parser::new(inner).map(|event| match event {
|
||||
pulldown_cmark::Event::Html(html) => pulldown_cmark::Event::Text(html),
|
||||
other => other,
|
||||
});
|
||||
let mut html = String::new();
|
||||
pulldown_cmark::html::push_html(&mut html, parser);
|
||||
let Some(body) = html
|
||||
.strip_prefix("<p>")
|
||||
.and_then(|s| s.strip_suffix("</p>\n"))
|
||||
else {
|
||||
return escape(text);
|
||||
};
|
||||
format!("{}{}{}", escape(&text[..start]), body, escape(&text[end..]))
|
||||
}
|
||||
|
||||
/// Render prose with markers stripped; show surface inner text only.
|
||||
fn render_prose_with_marks(
|
||||
line_no: u32,
|
||||
text: &str,
|
||||
bits: &[ProseBit],
|
||||
annots: &[&ViewAnnot],
|
||||
occluded: bool,
|
||||
) -> String {
|
||||
let mut html = String::new();
|
||||
let mut cursor = 0usize;
|
||||
@@ -1053,7 +1102,7 @@ fn render_prose_with_marks(
|
||||
let start = bit_at(bit);
|
||||
let end = prose_bit_end(text, bit);
|
||||
if start > cursor {
|
||||
html.push_str(&escape(&text[cursor..start]));
|
||||
html.push_str(&render_narrative_inline(&text[cursor..start]));
|
||||
}
|
||||
if start < end && end <= text.len() {
|
||||
let (cls, display) = bit_display(bit);
|
||||
@@ -1061,19 +1110,20 @@ fn render_prose_with_marks(
|
||||
.map(|a| a.id.as_str())
|
||||
.unwrap_or("");
|
||||
html.push_str(&format!(
|
||||
r#"<mark class="mq-anchor mq-{cls}" data-line="{line}" data-byte-start="{start}" data-byte-end="{end}" data-annot-id="{aid}">{inner}</mark>"#,
|
||||
r#"<mark class="mq-anchor mq-{cls}" data-line="{line}" data-byte-start="{start}" data-byte-end="{end}" data-annot-id="{aid}" data-syntax="{cls}" title="{hint}" tabindex="0">{inner}</mark>"#,
|
||||
cls = cls,
|
||||
hint = match bit {ProseBit::Decl{..}=>"参数或变量声明",ProseBit::BoldCode{..}=>"语句:计算、赋值或调用",ProseBit::ItalicReturn{..}=>"返回:把结果交给调用方"},
|
||||
line = line_no,
|
||||
start = start,
|
||||
end = end,
|
||||
aid = escape(annot_id),
|
||||
inner = escape(&display),
|
||||
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,start)}else{escape(&display)},
|
||||
));
|
||||
}
|
||||
cursor = end.max(cursor);
|
||||
}
|
||||
if cursor < text.len() {
|
||||
html.push_str(&escape(&text[cursor..]));
|
||||
html.push_str(&render_narrative_inline(&text[cursor..]));
|
||||
}
|
||||
html
|
||||
}
|
||||
@@ -1164,6 +1214,46 @@ fn index_stmt_lines(module: &Module) -> HashSet<u32> {
|
||||
}
|
||||
|
||||
|
||||
fn index_occluded_lines(module: &Module) -> HashSet<u32> {
|
||||
use crate::ast::{Arg, Expr};
|
||||
fn expr(e: &Expr) -> bool {
|
||||
match e {
|
||||
Expr::Occluded { .. } => true,
|
||||
Expr::Unary { expr: e, .. } => expr(e),
|
||||
Expr::Binary { left, right, .. } => expr(left) || expr(right),
|
||||
Expr::Call(c) => c.args.iter().any(|a| match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e),
|
||||
}),
|
||||
Expr::List(xs) => xs.iter().any(expr),
|
||||
Expr::Map(xs) => xs.iter().any(|(_, e)| expr(e)),
|
||||
Expr::Index { base, .. } => expr(base),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let mut lines = HashSet::new();
|
||||
for f in &module.functions {
|
||||
crate::ast::walk_stmts(f, &mut |s| {
|
||||
let has = match s {
|
||||
Stmt::Assign { value, .. }
|
||||
| Stmt::Return { value, .. }
|
||||
| Stmt::Expr { value, .. } => expr(value),
|
||||
Stmt::Call { call, .. } => call.args.iter().any(|a| match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e),
|
||||
}),
|
||||
Stmt::ForEach { .. } => true,
|
||||
Stmt::While { condition, .. } => expr(condition),
|
||||
Stmt::Branch { arms, .. } => {
|
||||
arms.iter().any(|a| a.condition.as_ref().is_some_and(expr))
|
||||
}
|
||||
};
|
||||
if has {
|
||||
lines.insert(crate::ast::stmt_line(s));
|
||||
}
|
||||
});
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialAssign> {
|
||||
let src_lines: Vec<&str> = source.lines().collect();
|
||||
let mut m = HashMap::new();
|
||||
@@ -1602,47 +1692,101 @@ markup: occlusion
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Explain the existing core surface, including compatibility constructs, without executing it.
|
||||
fn render_syntax_guide() -> String {
|
||||
let mut html = String::from(
|
||||
r#"<details class="reader-syntax-guide" id="reader-syntax-guide"><summary>怎样读这份可执行文档</summary><p>正文说明意图,标记指出哪些片段会执行。遮蔽只在正文显示动作说明,实际逻辑放在侧注;阅读、展开与定位都不会运行代码。</p><div class="knowledge-table-wrap"><table><thead><tr><th>标记</th><th>阅读含义</th></tr></thead><tbody>"#,
|
||||
);
|
||||
for (id, surface) in crate::parse::CORE_CONSTRUCTS {
|
||||
let meaning=match *id {
|
||||
"narrative"=>"作者的解释,按普通 Markdown 阅读。", "blank"=>"分隔叙述与结构,不是计算步骤。",
|
||||
"heading-unit"=>"一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。",
|
||||
"call-line"=>"调用函数;实际执行结果另有标注。", "branch-list"=>"按条件选择分支,不是普通编号说明。",
|
||||
"loop-list"=>"重复或遍历结构;迭代选择器只切换已有运行记录。", "param"=>"兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。",
|
||||
"table"=>"未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。", "fence"=>"代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。",
|
||||
"hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。",
|
||||
"ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。",
|
||||
"italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。",
|
||||
"link-index"=>"默认模式是 [动作](实现) 遮蔽,正文只显示动作;空括号表示待补充实际逻辑。classic 模式才解释为旧链接取元。",
|
||||
"bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。",
|
||||
"soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。"
|
||||
};
|
||||
html.push_str(&format!(
|
||||
r#"<tr data-construct-id="{}"><td><code>{}</code></td><td>{}</td></tr>"#,
|
||||
escape(id),
|
||||
escape(surface),
|
||||
escape(meaning)
|
||||
));
|
||||
}
|
||||
html.push_str("</tbody></table></div></details>");
|
||||
html
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod occl_split_tests {
|
||||
use super::split_occlusion;
|
||||
|
||||
#[test]
|
||||
fn splits_bare_assignment_occlusion() {
|
||||
let (head, label, payload, rest) =
|
||||
split_occlusion("`留存` = [客户留存率,模拟数据](0.42)").unwrap();
|
||||
assert_eq!(head, "`留存` =");
|
||||
assert_eq!(label, "客户留存率,模拟数据");
|
||||
assert_eq!(payload, "0.42");
|
||||
assert_eq!(rest, "");
|
||||
mod readable_occlusion_tests {
|
||||
use super::*;
|
||||
fn render(source: &str) -> String {
|
||||
let module = crate::load::parse_source_auto(source).unwrap();
|
||||
render_module_document(&module, source, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_bold_assignment_occlusion_without_markers() {
|
||||
let (head, label, payload, _) =
|
||||
split_occlusion("**留存 = [客户留存率,模拟数据](0.42)**").unwrap();
|
||||
assert_eq!(head, "留存 =");
|
||||
assert_eq!(label, "客户留存率,模拟数据");
|
||||
assert_eq!(payload, "0.42");
|
||||
fn prose_keeps_multiple_actions_and_returns_without_exposing_payloads() {
|
||||
let html=render("# main\n\n先**a = [读取甲](1 + 2)**,接着**b = [读取乙](3 + 4)**,最后返回*[合计](a + b)*。\n");
|
||||
let line = html
|
||||
.split("doc-line doc-prose-line\"")
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.split("</div>")
|
||||
.next()
|
||||
.unwrap();
|
||||
for text in ["先", "读取甲", "接着", "读取乙", "最后返回", "合计"] {
|
||||
assert!(line.contains(text), "{line}");
|
||||
}
|
||||
for code in ["1 + 2", "3 + 4", "a + b", "[读取甲]"] {
|
||||
assert!(!line.contains(code), "payload leaked into prose: {line}");
|
||||
}
|
||||
assert_eq!(
|
||||
html.matches("class=\"annot-chip annot-implementation\"")
|
||||
.count(),
|
||||
3
|
||||
);
|
||||
assert!(html.contains("data-syntax=\"return\""));
|
||||
assert!(html.contains(">1 + 2</code>") && html.contains(">a + b</code>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_stub_and_nested_payload() {
|
||||
let (_, label, payload, _) =
|
||||
split_occlusion("`待接` = [搜索接入,待开发]()").unwrap();
|
||||
assert_eq!(label, "搜索接入,待开发");
|
||||
assert!(payload.is_empty());
|
||||
|
||||
let (_, label, payload, _) =
|
||||
split_occlusion("`取第一` = [第一颗](access(`篮子`, \"1\"))").unwrap();
|
||||
assert_eq!(label, "第一颗");
|
||||
assert_eq!(payload, "access(`篮子`, \"1\")");
|
||||
fn empty_logic_quotes_nested_parentheses_and_html_are_safe() {
|
||||
let html =
|
||||
render("# main\n\n得到**a = [括号](str(value=\") <tag>\"))**,再**b = [待接]()**。\n");
|
||||
assert!(html.contains("待补充实际逻辑"));
|
||||
assert!(html.contains("<tag>") && !html.contains("<tag>"));
|
||||
assert!(html.contains("str(value=") <tag>")"));
|
||||
assert!(html.contains("当前空遮蔽返回 None"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_index_and_plain_lines() {
|
||||
// Link-index (classic) and ordinary statements are not occlusions.
|
||||
assert!(split_occlusion("**v = [键](`表`)**").is_some()); // shape matches; parser decides meaning
|
||||
assert!(split_occlusion("**甲 = 加(1 2)**").is_none());
|
||||
assert!(split_occlusion("> print text=x").is_none());
|
||||
fn navigation_and_quoted_links_are_not_executable_occlusions() {
|
||||
let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n");
|
||||
assert!(html.contains("href=\"https://example.com/guide\""));
|
||||
assert!(html.contains("href=\"https://example.com/mixed\""));
|
||||
assert_eq!(
|
||||
html.matches("class=\"annot-chip annot-implementation\"")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(html.contains("[数据链接](should_stay_text)"));
|
||||
let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n");
|
||||
assert!(!classic.contains("class=\"annot-chip annot-implementation\""));
|
||||
}
|
||||
#[test]
|
||||
fn semantic_loop_labels_and_every_core_construct_are_explained() {
|
||||
let html=render("# main\n\n`items` =\n\n| n |\n|---|\n| 1 |\n| 2 |\n\n- [逐项处理](遍历 items 为 item)\n **out = item + 1**\n");
|
||||
assert!(html.contains("逐项处理</button>"));
|
||||
assert!(html.contains("遍历 items 为 item</code>"));
|
||||
for (id, _) in crate::parse::CORE_CONSTRUCTS {
|
||||
assert!(
|
||||
html.contains(&format!("data-construct-id=\"{id}\"")),
|
||||
"missing {id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2504,7 +2504,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
var root = scope || document.getElementById("structure") || document;
|
||||
root.querySelectorAll("[data-annot-band]").forEach(function (band) {{
|
||||
band.classList.remove("is-expanded");
|
||||
var chips = band.querySelectorAll(".annot-chip");
|
||||
var chips = band.querySelectorAll(".annot-chip:not(.annot-implementation)");
|
||||
var visible = [];
|
||||
chips.forEach(function (chip) {{
|
||||
chip.classList.remove("annot-chip-overflow");
|
||||
@@ -4210,7 +4210,7 @@ window.MARQDO_VIEW_PAGE_TOKEN = {page_token_js};
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
"<details class=\"block knowledge-block\"><summary>可执行知识(辅助)</summary>{}</details>",
|
||||
"<details class=\"block knowledge-block\" id=\"knowledge-section\"><summary>可执行知识 · 输入、返回与依据</summary>{}</details>",
|
||||
vm.knowledge_html
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Reader-facing projection of compiler facts; no evaluation or invented evidence.
|
||||
use crate::ast::{Function, Module};
|
||||
use crate::sema::{SemanticArtifact, SemanticProject};
|
||||
use crate::view::{html::escape, render::expr_display};
|
||||
|
||||
fn find_function(functions: &[Function], line: u32) -> Option<&Function> {
|
||||
functions.iter().find_map(|f| {
|
||||
if f.span.line == line {
|
||||
Some(f)
|
||||
} else {
|
||||
find_function(&f.children, line)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn state(value: &str) -> String {
|
||||
match value {
|
||||
"passed" => "检查通过".into(),
|
||||
"failed" => "检查失败".into(),
|
||||
"unchecked" => "尚未检查".into(),
|
||||
"not_run" => "分析未运行程序".into(),
|
||||
"unknown" => "没有可用记录".into(),
|
||||
"sourced" => "已关联来源,内容尚未核验".into(),
|
||||
"verified" => "证据已核验".into(),
|
||||
"unverified" => "尚无已核验证据".into(),
|
||||
"unreviewed" => "尚未进行领域审阅".into(),
|
||||
other => format!("原始状态:{other}"),
|
||||
}
|
||||
}
|
||||
fn effect(value: &str) -> &str {
|
||||
match value {
|
||||
"pure" => "无已知宿主副作用",
|
||||
"fs.read" => "读取文件",
|
||||
"fs.write" => "写入文件",
|
||||
"net.http" | "network" => "网络请求",
|
||||
"process.exec" => "启动进程",
|
||||
"plugin" => "加载原生插件",
|
||||
"environment.read" => "读取环境配置",
|
||||
"output.write" => "输出文本",
|
||||
"input.read" => "读取输入",
|
||||
"unknown" => "调用效应尚不能确定",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn kind(value: &str) -> &str {
|
||||
match value {
|
||||
"type" => "对象",
|
||||
"function" => "函数",
|
||||
"constant" => "常量",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn step_kind(value: &str) -> &str {
|
||||
match value {
|
||||
"derive" => "计算",
|
||||
"observe" => "观察",
|
||||
"iterate" => "遍历",
|
||||
"call" => "调用",
|
||||
"return" => "返回",
|
||||
"branch" => "条件",
|
||||
"narrate" | "reference" => "正文引用",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn render_steps(
|
||||
project: &SemanticProject,
|
||||
steps: &[&crate::sema::ir::KnowledgeStep],
|
||||
title: &str,
|
||||
) -> String {
|
||||
if steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out=format!("<details class=\"knowledge-steps\"><summary>{}</summary><p class=\"knowledge-hint\">这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。</p><ol class=\"knowledge-step-list\">",escape(title));
|
||||
for step in steps {
|
||||
let label = project
|
||||
.refs
|
||||
.iter()
|
||||
.find(|r| r.id == step.reference)
|
||||
.map(|r| r.label.as_str())
|
||||
.unwrap_or("未命名步骤");
|
||||
out.push_str(&format!(r##"<li class="knowledge-step" data-step-kind="{kind}" data-line="{line}"><span class="knowledge-step-kind">{meaning}</span><a href="#stmt-{line}">{label}</a></li>"##,kind=escape(&step.kind),line=step.source.line,meaning=escape(step_kind(&step.kind)),label=escape(label)));
|
||||
}
|
||||
out.push_str("</ol></details>");
|
||||
out
|
||||
}
|
||||
fn technical(artifact: &SemanticArtifact) -> String {
|
||||
let v = &artifact.verification;
|
||||
format!(
|
||||
r##"<details class="knowledge-technical"><summary>技术详情:身份、摘要与原始状态</summary><dl><dt>目标标识</dt><dd><code>{target}</code></dd><dt>制品摘要(未检查锁定状态)</dt><dd><code>{digest}</code></dd><dt>依赖标识</dt><dd><code>{deps}</code></dd><dt>原始验证状态</dt><dd><code>parse: {parse}; resolve: {resolve}; contract: {contract}; execution: {execution}; tests: {tests}; evidence: {evidence}; domain: {domain}</code></dd></dl></details>"##,
|
||||
target = escape(
|
||||
artifact
|
||||
.symbol_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str())
|
||||
.unwrap_or(&artifact.artifact_id.0)
|
||||
),
|
||||
digest = escape(&artifact.hashes.artifact.0),
|
||||
deps = escape(
|
||||
&artifact
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|id| id.0.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
),
|
||||
parse = escape(&v.parse),
|
||||
resolve = escape(&v.resolve),
|
||||
contract = escape(&v.contract),
|
||||
execution = escape(&v.execution),
|
||||
tests = escape(&v.tests),
|
||||
evidence = escape(&v.evidence),
|
||||
domain = escape(&v.domain)
|
||||
)
|
||||
}
|
||||
/// Facts are grouped by exact source unit, with machine identities behind disclosure.
|
||||
pub(super) fn render(project: &SemanticProject, rel: &str, module: Option<&Module>) -> String {
|
||||
let mut artifacts: Vec<_> = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.source.file == rel && a.kind != "module")
|
||||
.collect();
|
||||
artifacts.sort_by_key(|a| a.source.line);
|
||||
let steps: Vec<_> = project
|
||||
.steps
|
||||
.iter()
|
||||
.filter(|s| s.source.file == rel)
|
||||
.collect();
|
||||
if artifacts.is_empty() && steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = format!(
|
||||
r##"<div class="knowledge-panel" aria-label="可执行知识"><div class="knowledge-intro"><h3>这份文档怎样成为可调用的知识</h3><p>{} 个知识单元 · {} 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。</p><p class="knowledge-hint">以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。</p></div>"##,
|
||||
artifacts.len(),
|
||||
steps.len()
|
||||
);
|
||||
let first = artifacts.first().map(|a| a.source.line).unwrap_or(u32::MAX);
|
||||
let introductory: Vec<_> = steps
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|s| s.source.line < first)
|
||||
.collect();
|
||||
out.push_str(&render_steps(project, &introductory, "正文中的引用与步骤"));
|
||||
for (index, a) in artifacts.iter().enumerate() {
|
||||
let line = a.source.line;
|
||||
let function = module.and_then(|m| find_function(&m.functions, line));
|
||||
let end = artifacts
|
||||
.get(index + 1)
|
||||
.map(|a| a.source.line)
|
||||
.unwrap_or(u32::MAX);
|
||||
out.push_str(&format!(r##"<details class="knowledge-card" id="knowledge-fn-{line}" data-source-line="{line}"><summary><span class="knowledge-unit-name">{name}</span><span class="knowledge-unit-kind">{kind}</span></summary><div class="knowledge-unit-body"><a class="knowledge-source-link" href="#fn-{line}">回到正文 · 第 {line} 行</a>"##,name=escape(&a.display_name),kind=escape(if function.is_some_and(|f|f.name=="main"&&f.level==1){"程序入口"}else{kind(&a.kind)})));
|
||||
if let Some(signature) = &a.signature {
|
||||
if signature.receiver == "instance" {
|
||||
out.push_str("<p class=\"knowledge-hint\">实例方法:先创建所属对象,再通过同一实例调用。</p>");
|
||||
}
|
||||
out.push_str("<h4>需要什么输入</h4>");
|
||||
if signature.params.is_empty() {
|
||||
out.push_str("<p>无需提供输入参数。</p>");
|
||||
} else {
|
||||
out.push_str("<div class=\"knowledge-table-wrap\"><table><thead><tr><th>参数</th><th>类型</th><th>提供方式</th><th>含义</th></tr></thead><tbody>");
|
||||
for param in &signature.params {
|
||||
let authored = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.params.iter().find(|p| p.name == param.name));
|
||||
let default = function
|
||||
.and_then(|f| f.params.iter().find(|p| p.name == param.name))
|
||||
.and_then(|p| p.default.as_ref())
|
||||
.map(expr_display);
|
||||
let supply = if param.required {
|
||||
"必填".into()
|
||||
} else {
|
||||
default
|
||||
.map(|v| format!("默认 {v}"))
|
||||
.unwrap_or("可省略;默认值见源码".into())
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"<tr><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
|
||||
escape(¶m.name),
|
||||
escape(¶m.ty),
|
||||
escape(&supply),
|
||||
escape(
|
||||
authored
|
||||
.map(|p| p.desc.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("源码未提供参数说明")
|
||||
)
|
||||
));
|
||||
}
|
||||
out.push_str("</tbody></table></div>");
|
||||
}
|
||||
let returns = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.returns.as_ref());
|
||||
out.push_str(&format!(
|
||||
"<h4>返回什么</h4><p><code>{}</code> · {}</p>",
|
||||
escape(&signature.returns),
|
||||
escape(
|
||||
returns
|
||||
.map(|r| r.desc.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("源码未提供返回值说明;请结合正文实现阅读。")
|
||||
)
|
||||
));
|
||||
} else {
|
||||
out.push_str("<p>这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。</p>");
|
||||
if let Some(returns) = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.returns.as_ref())
|
||||
{
|
||||
out.push_str(&format!(
|
||||
"<h4>源码中的返回契约</h4><p><code>{}</code> · {}</p>",
|
||||
escape(&returns.ty.name()),
|
||||
escape(&returns.desc)
|
||||
));
|
||||
}
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"<h4>调用边界</h4><p>{}。权限由实际运行入口授予;静态副作用信息不等于运行许可。</p>",
|
||||
escape(
|
||||
&a.effects
|
||||
.values()
|
||||
.iter()
|
||||
.map(|s| effect(s))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、")
|
||||
)
|
||||
));
|
||||
if !a.dependencies.is_empty() {
|
||||
out.push_str("<h4>依赖哪些知识</h4><ul class=\"knowledge-dependencies\">");
|
||||
for dependency in &a.dependencies {
|
||||
if let Some(target) = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|other| other.artifact_id == *dependency)
|
||||
{
|
||||
if target.source.file == rel && target.kind != "module" {
|
||||
out.push_str(&format!(
|
||||
r##"<li><a href="#knowledge-fn-{}" data-knowledge-link>{}</a></li>"##,
|
||||
target.source.line,
|
||||
escape(&target.display_name)
|
||||
));
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
"<li>{} <span class=\"knowledge-hint\">{}</span></li>",
|
||||
escape(&target.display_name),
|
||||
escape(&target.source.file)
|
||||
));
|
||||
}
|
||||
} else {
|
||||
out.push_str("<li>依赖尚未解析;完整标识见技术详情。</li>");
|
||||
}
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
}
|
||||
let v = &a.verification;
|
||||
out.push_str(&format!("<h4>当前有哪些依据</h4><dl class=\"knowledge-status\"><dt>语法与引用</dt><dd>{};{}</dd><dt>契约检查</dt><dd>{}</dd><dt>测试记录</dt><dd>{}</dd><dt>内容来源</dt><dd>{}</dd><dt>领域审阅</dt><dd>{}</dd></dl>",escape(&state(&v.parse)),escape(&state(&v.resolve)),escape(&state(&v.contract)),escape(&state(&v.tests)),escape(&state(&v.evidence)),escape(&state(&v.domain))));
|
||||
let owned: Vec<_> = steps
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|s| s.source.line >= line && s.source.line < end)
|
||||
.collect();
|
||||
out.push_str(&render_steps(project, &owned, "查看本单元的结构步骤"));
|
||||
out.push_str(&technical(a));
|
||||
out.push_str("</div></details>");
|
||||
}
|
||||
out.push_str("</div>");
|
||||
out
|
||||
}
|
||||
+102
-90
@@ -7,6 +7,7 @@ mod debug_page;
|
||||
mod document;
|
||||
mod html;
|
||||
mod knowledge_present;
|
||||
mod knowledge_reading;
|
||||
mod notebook_api;
|
||||
mod output;
|
||||
mod render;
|
||||
@@ -410,30 +411,28 @@ pub(crate) fn build_file_view_with_exec(
|
||||
) -> Result<FileViewModel> {
|
||||
let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
|
||||
// Structure shows this file only — do not merge imported lib bodies into the tree.
|
||||
let (mut structure, mut module_opt, input_prompts) = match crate::load::parse_source_auto(&source) {
|
||||
Ok(module) => {
|
||||
let prompts = collect_input_prompts(&module);
|
||||
(
|
||||
render_module_structure(&module, &source),
|
||||
Some(module),
|
||||
prompts,
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
format!(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
|
||||
let (mut structure, mut module_opt, input_prompts) =
|
||||
match crate::load::parse_source_auto(&source) {
|
||||
Ok(module) => {
|
||||
let prompts = collect_input_prompts(&module);
|
||||
(
|
||||
render_module_structure(&module, &source),
|
||||
Some(module),
|
||||
prompts,
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
format!(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
|
||||
),
|
||||
None,
|
||||
Vec::new(),
|
||||
),
|
||||
None,
|
||||
Vec::new(),
|
||||
),
|
||||
};
|
||||
};
|
||||
let effective = effective_stdin(&source, stdin_lines);
|
||||
let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source);
|
||||
let show_stream = module_opt
|
||||
.as_ref()
|
||||
.map(uses_stream_panel)
|
||||
.unwrap_or(false);
|
||||
let show_stream = module_opt.as_ref().map(uses_stream_panel).unwrap_or(false);
|
||||
// Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`.
|
||||
let auto_stream = live
|
||||
&& show_stream
|
||||
@@ -447,41 +446,40 @@ pub(crate) fn build_file_view_with_exec(
|
||||
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
||||
opts.fs_root = Some(root.root.clone());
|
||||
let mut captured: Option<crate::capture::RunCapture> = None;
|
||||
let (stdout, stderr, ok, plots, mut bindings_html) =
|
||||
if !execute {
|
||||
(
|
||||
String::new(),
|
||||
"execution skipped (--no-exec)".into(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::from(r#"<p class="vars-skipped">skipped</p>"#),
|
||||
)
|
||||
} else if awaiting_input || auto_stream {
|
||||
(
|
||||
String::new(),
|
||||
String::new(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => {
|
||||
let stdout = cap.stdout.clone();
|
||||
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
|
||||
let bindings_html = render_bindings_html(&cap.bindings);
|
||||
captured = Some(cap);
|
||||
(stdout, String::new(), true, plots, bindings_html)
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
),
|
||||
let (stdout, stderr, ok, plots, mut bindings_html) = if !execute {
|
||||
(
|
||||
String::new(),
|
||||
"execution skipped (--no-exec)".into(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::from(r#"<p class="vars-skipped">skipped</p>"#),
|
||||
)
|
||||
} else if awaiting_input || auto_stream {
|
||||
(
|
||||
String::new(),
|
||||
String::new(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => {
|
||||
let stdout = cap.stdout.clone();
|
||||
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
|
||||
let bindings_html = render_bindings_html(&cap.bindings);
|
||||
captured = Some(cap);
|
||||
(stdout, String::new(), true, plots, bindings_html)
|
||||
}
|
||||
};
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
),
|
||||
}
|
||||
};
|
||||
// Re-read after run so writeback slots / workbook edits show in Structure.
|
||||
if execute && !awaiting_input && !auto_stream {
|
||||
if let Ok(next) = fs::read_to_string(abs) {
|
||||
@@ -514,46 +512,60 @@ pub(crate) fn build_file_view_with_exec(
|
||||
// Analysis is intentionally independent from capture/run. If a document
|
||||
// has side effects, its facts remain visible while its values stay absent.
|
||||
let title_guess = crate::view::title_from_source(&source, rel);
|
||||
let (knowledge_html, knowledge_error, page_token) =
|
||||
match crate::sema::compile_project(&crate::sema::CompileOptions {
|
||||
let analysis = if root.only_file.is_some() {
|
||||
crate::sema::compile_file_closure(abs)
|
||||
} else {
|
||||
crate::sema::compile_project(&crate::sema::CompileOptions {
|
||||
project_root: root.root.clone(),
|
||||
entry: Some(abs.to_path_buf()),
|
||||
lock_mode: crate::sema::LockMode::Off,
|
||||
}) {
|
||||
Ok(compilation) => {
|
||||
let html = render_knowledge_html(&compilation.semantics, rel);
|
||||
// V1: also materialize structured presentation (JSON available to page scripts).
|
||||
let mut presentation = crate::view::KnowledgePresentation::from_project(
|
||||
&compilation.semantics,
|
||||
rel,
|
||||
&title_guess,
|
||||
);
|
||||
presentation.page_token = crate::view::page_token_from_source(rel, &source);
|
||||
let json = presentation.to_json().to_string();
|
||||
let with_model = if html.is_empty() {
|
||||
format!(
|
||||
r#"<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
r#"{html}<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
html = html,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
};
|
||||
(
|
||||
with_model,
|
||||
String::new(),
|
||||
presentation.page_token.clone(),
|
||||
})
|
||||
};
|
||||
let (knowledge_html, knowledge_error, page_token) = match analysis {
|
||||
Ok(compilation) => {
|
||||
// Dependency closures may have a wider root than the reader's file directory.
|
||||
let semantic_rel = abs
|
||||
.strip_prefix(&compilation.semantics.root)
|
||||
.unwrap_or(abs)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let html = crate::view::knowledge_reading::render(
|
||||
&compilation.semantics,
|
||||
&semantic_rel,
|
||||
module_opt.as_ref(),
|
||||
);
|
||||
// V1: also materialize structured presentation (JSON available to page scripts).
|
||||
let mut presentation = crate::view::KnowledgePresentation::from_project(
|
||||
&compilation.semantics,
|
||||
&semantic_rel,
|
||||
&title_guess,
|
||||
);
|
||||
presentation.document_id = rel.to_string();
|
||||
presentation.page_token = crate::view::page_token_from_source(rel, &source);
|
||||
let json = presentation.to_json().to_string();
|
||||
let with_model = if html.is_empty() {
|
||||
format!(
|
||||
r#"<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
format!("知识关系暂不可用:{}", tidy_user_error(&format!("{e:#}"), abs, rel)),
|
||||
crate::view::page_token_from_source(rel, &source),
|
||||
} else {
|
||||
format!(
|
||||
r#"{html}<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
html = html,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
};
|
||||
(with_model, String::new(), presentation.page_token.clone())
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
format!(
|
||||
"知识关系暂不可用:{}",
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel)
|
||||
),
|
||||
};
|
||||
crate::view::page_token_from_source(rel, &source),
|
||||
),
|
||||
};
|
||||
let page_token = if page_token.is_empty() {
|
||||
crate::view::page_token_from_source(rel, &source)
|
||||
} else {
|
||||
|
||||
@@ -169,3 +169,46 @@ body.reader-page .nav { visibility:hidden; }
|
||||
body.reader-page #nav-toggle:checked ~ .shell .nav { visibility:visible; }
|
||||
|
||||
@media print { body.reader-page .document-surface { padding-bottom:0; } }
|
||||
|
||||
/* Action text belongs to the sentence; its implementation belongs to a note. */
|
||||
body.reader-page .doc-line { font:19px/1.8 var(--serif); overflow-wrap:anywhere; }
|
||||
body.reader-page .mq-anchor:has(.occl-label) { background:transparent; border:0; padding:0; }
|
||||
body.reader-page button.occl-label { display:inline; appearance:none; font:inherit; color:var(--olive); background:transparent; border:0; border-bottom:1px dotted var(--gold); border-radius:0; padding:0 1px; cursor:pointer; text-align:inherit; }
|
||||
body.reader-page button.occl-label:hover { background:var(--fill); }
|
||||
body.reader-page .occl-stub { display:inline; font:11px/1.5 var(--sans); border:1px solid var(--gold); border-radius:5px; padding:2px 5px; margin-left:6px; color:var(--focus); white-space:normal; }
|
||||
body.reader-page details.annot-implementation { display:block; padding:8px 12px; border-radius:7px; border:1px solid var(--line); margin:5px 0; }
|
||||
body.reader-page .annot-implementation > summary { cursor:pointer; font:12px/1.6 var(--sans); color:var(--olive); }
|
||||
body.reader-page .annot-implementation .occl-code { display:block; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); padding:6px 0; border:0; border-radius:0; background:transparent; }
|
||||
body.reader-page details.annot-implementation.is-margin-note { padding:5px 0; border:0; margin:0; }
|
||||
body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5 var(--serif); }
|
||||
.logic-hint { display:block; color:var(--muted); font:10px/1.6 var(--sans); margin-top:5px; }
|
||||
.reader-syntax-guide { font:13px/1.7 var(--sans); border:1px solid var(--line); padding:12px 16px; border-radius:9px; margin:0 0 28px; color:var(--muted); }
|
||||
.reader-syntax-guide > summary { cursor:pointer; color:var(--olive); }
|
||||
.reader-syntax-guide p { margin:12px 0; }
|
||||
.knowledge-table-wrap { max-width:100%; overflow-x:auto; }
|
||||
.reader-syntax-guide table,.knowledge-panel table { width:100%; border-collapse:collapse; font:12px/1.65 var(--sans); }
|
||||
.reader-syntax-guide th,.reader-syntax-guide td,.knowledge-panel th,.knowledge-panel td { padding:9px 10px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
.reader-syntax-guide td:first-child { min-width:115px; }
|
||||
.reader-page .knowledge-block { border-top:1px solid var(--line); padding-top:22px; font:14px/1.7 var(--sans); }
|
||||
.reader-page .knowledge-block > summary { color:var(--olive); font:18px/1.6 var(--serif); }
|
||||
.knowledge-intro { margin:20px 0; }.knowledge-intro h3 { font:22px/1.5 var(--serif); margin:0 0 8px; }
|
||||
.knowledge-intro p { margin:7px 0; }
|
||||
.knowledge-card { margin:12px 0; border:1px solid var(--line); border-radius:10px; overflow:hidden; font:13px/1.75 var(--sans); }
|
||||
.knowledge-card > summary { display:flex; align-items:baseline; flex-wrap:wrap; gap:10px; padding:14px 18px; cursor:pointer; background:var(--fill); }
|
||||
.knowledge-card > summary::before { content:'›'; color:var(--gold); }.knowledge-card[open] > summary::before { content:'⌄'; }
|
||||
.knowledge-unit-name { font:18px/1.6 var(--serif); overflow-wrap:anywhere; }.knowledge-unit-kind { font:11px/1.5 var(--sans); color:var(--muted); }
|
||||
.knowledge-unit-body { padding:16px 18px; }.knowledge-unit-body h4 { margin:20px 0 8px; font:600 13px/1.6 var(--sans); color:var(--olive); }
|
||||
.knowledge-unit-body p { margin:6px 0; }.knowledge-source-link { color:var(--olive); border-bottom:1px dotted var(--gold); font-size:12px; }
|
||||
.knowledge-status { display:grid; grid-template-columns:100px minmax(0,1fr); gap:7px 12px; margin:8px 0; }.knowledge-status dt { color:var(--muted); }.knowledge-status dd { margin:0; }
|
||||
.knowledge-panel code { white-space:pre-wrap; overflow-wrap:anywhere; font:11px/1.65 var(--mono); }
|
||||
.knowledge-dependencies { padding-left:20px; }.knowledge-dependencies a { border-bottom:1px dotted var(--gold); }
|
||||
.knowledge-steps,.knowledge-technical { border-top:1px solid var(--line); margin-top:18px; padding-top:12px; }
|
||||
.knowledge-steps > summary,.knowledge-technical > summary { font:12px/1.7 var(--sans); cursor:pointer; color:var(--muted); }
|
||||
.knowledge-step { padding:5px 0; overflow-wrap:anywhere; }.knowledge-step-kind { display:inline-block; color:var(--olive); min-width:4em; margin-right:8px; }
|
||||
.knowledge-technical dl { font-size:11px; }.knowledge-technical dd { margin:4px 0 14px; overflow-wrap:anywhere; }
|
||||
.reader-dialog:has(.knowledge-panel) { width:min(850px,calc(100vw - 32px)); }
|
||||
@media(max-width:600px) { body.reader-page .doc-line { font-size:17px; }.knowledge-unit-body { padding:12px; }.knowledge-status { grid-template-columns:80px minmax(0,1fr); }.knowledge-card > summary { padding:12px; }.knowledge-table-wrap th,.knowledge-table-wrap td { min-width:65px; }.reader-syntax-guide { padding:10px; } }
|
||||
@media print { .annot-implementation { break-inside:avoid; }.reader-syntax-guide { display:none; }.knowledge-technical { overflow-wrap:anywhere; } }
|
||||
.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); }
|
||||
.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; }
|
||||
.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; }
|
||||
+47
-6
@@ -72,6 +72,8 @@
|
||||
if (name === 'close-dialog') { dialog.close(); return; }
|
||||
if (name === 'document') { if (dialog.open) dialog.close(); scrollTo(document.getElementById('document-section') || document.querySelector('main')); return; }
|
||||
if (name === 'search') { showSearch(); return; }
|
||||
if (name === 'knowledge') { openDialog('可执行知识', name); movePanel(document.querySelector('.knowledge-panel')); return; }
|
||||
if (name === 'syntax') { var guide=document.getElementById('reader-syntax-guide'); if(guide) {guide.open=true;scrollTo(guide);} return; }
|
||||
if (name === 'functions' || name === 'variables') {
|
||||
var panel = document.getElementById(name === 'functions' ? 'fn-outline' : 'vars-panel');
|
||||
openDialog(name === 'functions' ? '函数目录' : '文档变量', name); movePanel(panel); return;
|
||||
@@ -79,10 +81,27 @@
|
||||
if (name === 'memory') {
|
||||
openDialog('执行内存与调用轨迹', name);
|
||||
var hint = document.createElement('p'); hint.textContent = window.MARQDO_VIEW_LIVE ? '当前文档已捕获的绑定与调用轨迹;会话状态可在高级工具中查看。' : '以下为导出时保存的执行快照。'; content.appendChild(hint);
|
||||
var pre = document.createElement('pre');
|
||||
try { pre.textContent = JSON.stringify(JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'), null, 2); }
|
||||
catch (_) { pre.textContent = '当前没有可用执行快照。'; }
|
||||
content.appendChild(pre); return;
|
||||
var report;
|
||||
try { report=JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'); }
|
||||
catch (_) { report={}; }
|
||||
if(typeof report.ok!=='boolean') {
|
||||
var empty=document.createElement('p');empty.textContent='本页没有捕获执行记录;静态知识分析不会自动产生运行结果。';content.appendChild(empty);return;
|
||||
}
|
||||
var status=document.createElement('p');status.className='reader-run-summary';
|
||||
status.textContent=(report.ok?'这次运行成功':'这次运行失败')+' · '+(report.calls||[]).length+' 次调用 · '+(report.loops||[]).length+' 个循环记录';content.appendChild(status);
|
||||
function reportTable(title,headers,rows) {
|
||||
var heading=document.createElement('h3');heading.textContent=title;content.appendChild(heading);
|
||||
var wrap=document.createElement('div');wrap.className='knowledge-table-wrap';
|
||||
var table=document.createElement('table'),head=document.createElement('tr');
|
||||
headers.forEach(function(text){var cell=document.createElement('th');cell.textContent=text;head.appendChild(cell);});table.appendChild(head);
|
||||
rows.forEach(function(row){var tr=document.createElement('tr');row.forEach(function(text){var cell=document.createElement('td');cell.textContent=text;tr.appendChild(cell);});table.appendChild(tr);});
|
||||
wrap.appendChild(table);content.appendChild(wrap);
|
||||
}
|
||||
var bindings=report.bindings_final||{};
|
||||
reportTable('最终绑定',['名称','值'],Object.keys(bindings).map(function(key){return [key,String(bindings[key])];}));
|
||||
reportTable('调用记录',['函数','源码位置','输入'],(report.calls||[]).map(function(call){return [call.fn,'第 '+call.fn_line+' 行',call.args_brief||'无实参'];}));
|
||||
var details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='完整执行报告(技术详情)';details.appendChild(summary);
|
||||
var pre=document.createElement('pre');pre.textContent=JSON.stringify(report,null,2);details.appendChild(pre);content.appendChild(details);return;
|
||||
}
|
||||
if (name === 'execution') { scrollTo(document.getElementById('exec-block')); return; }
|
||||
if (name === 'run') {
|
||||
@@ -104,6 +123,8 @@
|
||||
}
|
||||
if (name === 'more') {
|
||||
openDialog('文档工具', name);
|
||||
option('可执行知识', function () { action('knowledge'); });
|
||||
option('语法与阅读说明', function () { dialog.close(); action('syntax'); });
|
||||
option('文件目录', function () { dialog.close(); action('files'); });
|
||||
option('查看完整源码', function () { var source = document.querySelector('.source-block'); if (source) { source.open = true; scrollTo(source); } });
|
||||
option('高级运行工具', function () { document.body.classList.toggle('reader-tools'); dialog.close(); scrollTo(document.getElementById('notebook-bar')); });
|
||||
@@ -170,6 +191,7 @@
|
||||
band.classList.remove('is-keyed');
|
||||
band.querySelectorAll('.annot-chip').forEach(function (chip) {
|
||||
chip.classList.remove('is-margin-note');
|
||||
if(chip.classList.contains('annot-implementation')) chip.open=false;
|
||||
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
|
||||
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
|
||||
});
|
||||
@@ -379,6 +401,7 @@
|
||||
var fragments = anchorFragments(item.anchor);
|
||||
var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58));
|
||||
item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px';
|
||||
if(item.chip.classList.contains('annot-implementation')) item.chip.open=true;
|
||||
var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4];
|
||||
var choices = nextY.map(function (y, side) {
|
||||
var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1];
|
||||
@@ -439,14 +462,32 @@
|
||||
dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content');
|
||||
dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); });
|
||||
document.addEventListener('click', function (ev) {
|
||||
var logic=ev.target.closest('[data-logic-id]');
|
||||
if(logic) {
|
||||
ev.preventDefault();
|
||||
var note=document.getElementById(logic.dataset.logicId+'-note');
|
||||
openDialog('实际逻辑 · '+logic.textContent,'logic');
|
||||
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码实现,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
|
||||
var code=document.createElement('pre');code.textContent=note ? note.querySelector('.annot-value').textContent : '此片段的逻辑详情暂不可用。';content.appendChild(code);return;
|
||||
}
|
||||
var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]');
|
||||
if(knowledge) {
|
||||
var target=document.getElementById((knowledge.getAttribute('href')||'').slice(1));
|
||||
if(target){ev.preventDefault();if(dialog.open)dialog.close();var parent=target;while(parent){if(parent.tagName==='DETAILS')parent.open=true;parent=parent.parentElement;}scrollTo(target);}return;
|
||||
}
|
||||
var sourceLink=ev.target.closest('.knowledge-source-link,.knowledge-step a');
|
||||
if(sourceLink && dialog.open) dialog.close();
|
||||
var button = ev.target.closest('[data-reader-action]'); if (button) action(button.dataset.readerAction);
|
||||
var chip = ev.target.closest('.annot-chip');
|
||||
if (chip) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); }
|
||||
if (chip && !chip.classList.contains('annot-implementation')) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); }
|
||||
if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); }
|
||||
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
|
||||
});
|
||||
function focusNote(ev, focus) {
|
||||
var chip = ev.target.closest('.annot-chip'); if (!chip || ev.relatedTarget && chip.contains(ev.relatedTarget)) return;
|
||||
var trigger=ev.target.closest('.annot-chip,[data-logic-id]');
|
||||
if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return;
|
||||
var chip=trigger.matches('.annot-chip') ? trigger : document.getElementById(trigger.dataset.logicId+'-note');
|
||||
if(!chip) return;
|
||||
var owner = noteOwner(chip.closest('[data-annot-band]'));
|
||||
var anchor = findAnchor(owner,chip); if (anchor) anchor.classList.toggle('is-focus', focus);
|
||||
chip.classList.toggle('is-focus',focus);
|
||||
|
||||
+3
-84
@@ -60,90 +60,9 @@ pub struct FileViewModel {
|
||||
/// View deliberately compiles semantics without running the target, so a page
|
||||
/// can show binding/effect/verification facts even in `--no-exec` exports.
|
||||
///
|
||||
/// V0: skip module/type container cards by default; rename lock digest accurately.
|
||||
/// The reader groups facts by source unit and folds raw identifiers into technical detail.
|
||||
pub fn render_knowledge_html(project: &crate::sema::SemanticProject, rel: &str) -> String {
|
||||
let artifacts: Vec<_> = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|artifact| {
|
||||
artifact.source.file == rel && artifact.kind != "module" && artifact.kind != "type"
|
||||
})
|
||||
.collect();
|
||||
let steps: Vec<_> = project.steps.iter().filter(|step| step.source.file == rel).collect();
|
||||
if artifacts.is_empty() && steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = String::from(r#"<div class="knowledge-panel" aria-label="Executable knowledge">"#);
|
||||
if !steps.is_empty() {
|
||||
out.push_str(r#"<article class="knowledge-card knowledge-steps"><h3>文档中的步骤</h3><p class="knowledge-hint">结构步骤(非实际执行时序)</p><ol class="knowledge-step-list">"#);
|
||||
for step in &steps {
|
||||
let label = project
|
||||
.refs
|
||||
.iter()
|
||||
.find(|r| r.id == step.reference)
|
||||
.map(|r| r.label.as_str())
|
||||
.unwrap_or(step.reference.as_str());
|
||||
let line = step.source.line;
|
||||
let target_ids = if step.calls.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
r#" <span class="knowledge-step-targets">→ {}</span>"#,
|
||||
escape(&step.calls.iter().map(|id| id.as_str()).collect::<Vec<_>>().join(", "))
|
||||
)
|
||||
};
|
||||
// Structure pane uses #stmt-{line}; jump there for source navigation.
|
||||
out.push_str(&format!(
|
||||
"<li class=\"knowledge-step\" data-step-kind=\"{0}\" data-line=\"{1}\"><a href=\"#stmt-{1}\"><code class=\"ks-kind\">{0}</code> {2}</a>{3}</li>",
|
||||
escape(&step.kind),
|
||||
line,
|
||||
escape(label),
|
||||
target_ids,
|
||||
));
|
||||
}
|
||||
out.push_str("</ol></article>");
|
||||
}
|
||||
for artifact in artifacts {
|
||||
let target = artifact.symbol_id.as_ref().map(|id| id.as_str()).unwrap_or(artifact.artifact_id.0.as_str());
|
||||
let signature = artifact.signature.as_ref().map(|sig| {
|
||||
let params = sig.params.iter().map(|param| format!("{}: {}{}", param.name, param.ty, if param.required { "" } else { "?" })).collect::<Vec<_>>().join(", ");
|
||||
format!("({params}) → {}", sig.returns)
|
||||
}).unwrap_or_else(|| "declaration".into());
|
||||
let effects = artifact.effects.values().join(", ");
|
||||
let deps = if artifact.dependencies.is_empty() { "none".to_string() } else { artifact.dependencies.iter().map(|id| id.0.as_str()).collect::<Vec<_>>().join(", ") };
|
||||
// Short digest for display; full value in title for copy.
|
||||
let digest = &artifact.hashes.artifact.0;
|
||||
let digest_short = if digest.len() > 20 {
|
||||
format!("{}…", &digest[..20])
|
||||
} else {
|
||||
digest.clone()
|
||||
};
|
||||
let evidence_note = match artifact.verification.evidence.as_str() {
|
||||
"sourced" => "已关联来源,内容尚未核验",
|
||||
"verified" => "证据已核验",
|
||||
"unverified" => "尚无来源记录",
|
||||
other => other,
|
||||
};
|
||||
out.push_str(&format!(
|
||||
r#"<article class="knowledge-card" id="knowledge-{name}"><h3>{name} <span class="ks-kind">{kind}</span></h3><dl><dt>Target</dt><dd><code>{target}</code></dd><dt>Signature</dt><dd><code>{sig}</code></dd><dt>Effects</dt><dd>{effects}</dd><dt>Verification</dt><dd>parse: {parse}; resolve: {resolve}; contract: {contract}; tests: {tests}; evidence: {evidence}({evidence_note})</dd><dt>制品摘要</dt><dd><code title="{digest}">{digest_short}</code> <span class="knowledge-hint">(未检查锁定状态)</span></dd><dt>Depends on</dt><dd><code>{deps}</code></dd><dt>Execution</dt><dd>尚无该知识的运行记录(知识预览不执行)。</dd></dl></article>"#,
|
||||
name = escape(&artifact.display_name),
|
||||
kind = escape(&artifact.kind),
|
||||
target = escape(target),
|
||||
sig = escape(&signature),
|
||||
effects = escape(&effects),
|
||||
parse = escape(&artifact.verification.parse),
|
||||
resolve = escape(&artifact.verification.resolve),
|
||||
contract = escape(&artifact.verification.contract),
|
||||
tests = escape(&artifact.verification.tests),
|
||||
evidence = escape(&artifact.verification.evidence),
|
||||
evidence_note = escape(evidence_note),
|
||||
digest = escape(digest),
|
||||
digest_short = escape(&digest_short),
|
||||
deps = escape(&deps),
|
||||
));
|
||||
}
|
||||
out.push_str("</div>");
|
||||
out
|
||||
crate::view::knowledge_reading::render(project, rel, None)
|
||||
}
|
||||
|
||||
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
|
||||
@@ -1336,7 +1255,7 @@ fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String
|
||||
escape(&expr_display(e))
|
||||
),
|
||||
None => String::from(
|
||||
"<span class=\"occl-stub\" title=\"空载荷:未接通或待补返回值\">桩</span>",
|
||||
"<span class=\"occl-stub\" title=\"空遮蔽当前返回 None\">待补充实际逻辑</span>",
|
||||
),
|
||||
};
|
||||
format!(
|
||||
|
||||
Reference in new issue
Block a user