Add usable table/map stdlib with put, and show run bindings in view.

Authors can update nested collections via table.put/表.改 instead of json.set chains; view’s right rail adds collapsible Variables from the entry env.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 11:49:48 +08:00
1 parent 91d51f3f0a
commit 25b7be6739
26 files changed
+1577 -123

No files matched your search

+2
View File
@@ -8,4 +8,6 @@ pub struct RunCapture {
pub stdout: String,
pub value: Value,
pub plots: Vec<PlotArtifact>,
/// Entry-function bindings after a successful tree-backend run (empty for bytecode).
pub bindings: std::collections::HashMap<String, Value>,
}
+2 -26
View File
@@ -125,35 +125,11 @@ fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
}
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.clone(),
_ => return Err("map_set key must be text".into()),
};
match map {
Value::Map(entries) => {
let mut out = entries.clone();
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) {
*slot = value.clone();
} else {
out.push((k, value.clone()));
}
Ok(Value::Map(out))
}
Value::None => Ok(Value::Map(vec![(k, value.clone())])),
_ => Err("map_set needs map".into()),
}
crate::host::collection::map_set(map, key, value)
}
pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => {
let mut out = xs.clone();
out.push(item.clone());
Ok(Value::List(out))
}
Value::None => Ok(Value::List(vec![item.clone()])),
_ => Err("list_append needs list".into()),
}
crate::host::collection::list_append(list, item)
}
#[cfg(test)]
+442
View File
@@ -0,0 +1,442 @@
//! List / map collection primitives for `lib/table` (and json compat aliases).
use crate::value::Value;
#[derive(Clone)]
enum PathSeg {
Key(String),
/// 1-based list index (aligned with footnote `[^1]`).
Index1(usize),
}
fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
match at {
Value::Text(s) => Ok(vec![PathSeg::Key(s.clone())]),
Value::Int(n) => {
if *n < 1 {
return Err("put path index must be >= 1 (1-based)".into());
}
Ok(vec![PathSeg::Index1(*n as usize)])
}
Value::List(xs) => {
if xs.is_empty() {
return Err("put path must not be empty".into());
}
let mut out = Vec::with_capacity(xs.len());
for (i, seg) in xs.iter().enumerate() {
match seg {
Value::Text(s) => out.push(PathSeg::Key(s.clone())),
Value::Int(n) => {
if *n < 1 {
return Err(format!(
"put path segment {i}: index must be >= 1 (1-based)"
));
}
out.push(PathSeg::Index1(*n as usize));
}
_ => {
return Err(format!(
"put path segment {i}: need text key or int index"
));
}
}
}
Ok(out)
}
_ => Err("put at= needs text, int, or list path".into()),
}
}
/// Deep put: `in` collection, `at` path (1-based ints), `value` leaf.
/// `in=None` + single text key → new one-entry map.
pub fn collection_put(input: &Value, at: &Value, value: &Value) -> Result<Value, String> {
let path = path_segments(at)?;
if matches!(input, Value::None) {
if path.len() == 1 {
if let PathSeg::Key(k) = &path[0] {
return Ok(Value::Map(vec![(k.clone(), value.clone())]));
}
}
return Err("put in=None only allowed with a single text key".into());
}
put_rec(input, &path, value)
}
fn put_rec(cur: &Value, path: &[PathSeg], value: &Value) -> Result<Value, String> {
let Some((head, rest)) = path.split_first() else {
return Ok(value.clone());
};
if rest.is_empty() {
return put_leaf(cur, head, value);
}
match head {
PathSeg::Key(k) => {
let Value::Map(entries) = cur else {
return Err(format!("put: expected map at key `{k}`"));
};
let child = entries
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
.ok_or_else(|| format!("put: missing key `{k}` on path"))?;
let new_child = put_rec(&child, rest, value)?;
map_set(cur, &Value::Text(k.clone()), &new_child)
}
PathSeg::Index1(i1) => {
let Value::List(xs) = cur else {
return Err(format!("put: expected list at index {i1}"));
};
let i0 = i1 - 1;
if i0 >= xs.len() {
return Err(format!("put: list index {i1} out of range (len {})", xs.len()));
}
let new_child = put_rec(&xs[i0], rest, value)?;
list_set_at(cur, i0 as i64, &new_child)
}
}
}
fn put_leaf(cur: &Value, head: &PathSeg, value: &Value) -> Result<Value, String> {
match head {
PathSeg::Key(k) => map_set(cur, &Value::Text(k.clone()), value),
PathSeg::Index1(i1) => {
let i0 = (*i1 as i64) - 1;
list_set_at(cur, i0, value)
}
}
}
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.clone(),
_ => return Err("map_set key must be text".into()),
};
match map {
Value::Map(entries) => {
let mut out = entries.clone();
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) {
*slot = value.clone();
} else {
out.push((k, value.clone()));
}
Ok(Value::Map(out))
}
Value::None => Ok(Value::Map(vec![(k, value.clone())])),
_ => Err("map_set needs map".into()),
}
}
pub fn map_get(map: &Value, key: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.as_str(),
_ => return Err("map_get key must be text".into()),
};
match map {
Value::Map(entries) => Ok(entries
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
.unwrap_or(Value::None)),
Value::None => Ok(Value::None),
_ => Err("map_get needs map".into()),
}
}
pub fn map_delete(map: &Value, key: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.as_str(),
_ => return Err("map_delete key must be text".into()),
};
match map {
Value::Map(entries) => {
let out: Vec<_> = entries.iter().filter(|(kk, _)| kk != k).cloned().collect();
Ok(Value::Map(out))
}
Value::None => Ok(Value::Map(vec![])),
_ => Err("map_delete needs map".into()),
}
}
pub fn map_has(map: &Value, key: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.as_str(),
_ => return Err("map_has key must be text".into()),
};
match map {
Value::Map(entries) => Ok(Value::Bool(entries.iter().any(|(kk, _)| kk == k))),
Value::None => Ok(Value::Bool(false)),
_ => Err("map_has needs map".into()),
}
}
pub fn map_keys(map: &Value) -> Result<Value, String> {
match map {
Value::Map(entries) => Ok(Value::List(
entries
.iter()
.map(|(k, _)| Value::Text(k.clone()))
.collect(),
)),
Value::None => Ok(Value::List(vec![])),
_ => Err("map_keys needs map".into()),
}
}
pub fn map_values(map: &Value) -> Result<Value, String> {
match map {
Value::Map(entries) => Ok(Value::List(entries.iter().map(|(_, v)| v.clone()).collect())),
Value::None => Ok(Value::List(vec![])),
_ => Err("map_values needs map".into()),
}
}
pub fn map_items(map: &Value) -> Result<Value, String> {
match map {
Value::Map(entries) => {
let rows: Vec<Value> = entries
.iter()
.map(|(k, v)| {
Value::Map(vec![
("key".into(), Value::Text(k.clone())),
("value".into(), v.clone()),
])
})
.collect();
Ok(Value::List(rows))
}
Value::None => Ok(Value::List(vec![])),
_ => Err("map_items needs map".into()),
}
}
pub fn map_merge(left: &Value, right: &Value) -> Result<Value, String> {
let mut out = match left {
Value::Map(e) => e.clone(),
Value::None => vec![],
_ => return Err("map_merge left needs map".into()),
};
let right_entries = match right {
Value::Map(e) => e,
Value::None => return Ok(Value::Map(out)),
_ => return Err("map_merge right needs map".into()),
};
for (k, v) in right_entries {
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| kk == k) {
*slot = v.clone();
} else {
out.push((k.clone(), v.clone()));
}
}
Ok(Value::Map(out))
}
pub fn map_size(map: &Value) -> Result<Value, String> {
match map {
Value::Map(entries) => Ok(Value::Int(entries.len() as i64)),
Value::None => Ok(Value::Int(0)),
_ => Err("map_size needs map".into()),
}
}
pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => {
let mut out = xs.clone();
out.push(item.clone());
Ok(Value::List(out))
}
Value::None => Ok(Value::List(vec![item.clone()])),
_ => Err("list_append needs list".into()),
}
}
pub fn list_prepend(list: &Value, item: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => {
let mut out = vec![item.clone()];
out.extend(xs.iter().cloned());
Ok(Value::List(out))
}
Value::None => Ok(Value::List(vec![item.clone()])),
_ => Err("list_prepend needs list".into()),
}
}
pub fn list_concat(a: &Value, b: &Value) -> Result<Value, String> {
let left = match a {
Value::List(xs) => xs.clone(),
Value::None => vec![],
_ => return Err("list_concat left needs list".into()),
};
let right = match b {
Value::List(xs) => xs,
Value::None => return Ok(Value::List(left)),
_ => return Err("list_concat right needs list".into()),
};
let mut out = left;
out.extend(right.iter().cloned());
Ok(Value::List(out))
}
pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result<Value, String> {
let mut xs = match list {
Value::List(xs) => xs.clone(),
Value::None => vec![],
_ => return Err("list_insert needs list".into()),
};
if index < 0 || index as usize > xs.len() {
return Err(format!(
"list_insert index {index} out of range (len {})",
xs.len()
));
}
xs.insert(index as usize, item.clone());
Ok(Value::List(xs))
}
pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result<Value, String> {
let Value::List(xs) = list else {
return Err("list_set_at needs list".into());
};
if index < 0 || index as usize >= xs.len() {
return Err(format!(
"list_set_at index {index} out of range (len {})",
xs.len()
));
}
let mut out = xs.clone();
out[index as usize] = item.clone();
Ok(Value::List(out))
}
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() {
return Err(format!(
"list_remove_at index {index} out of range (len {})",
xs.len()
));
}
let mut out = xs.clone();
out.remove(index as usize);
Ok(Value::List(out))
}
pub fn list_slice(list: &Value, start: i64, end: Option<i64>) -> Result<Value, String> {
let Value::List(xs) = list else {
return Err("list_slice needs list".into());
};
let n = xs.len() as i64;
let s = start.clamp(0, n) as usize;
let e = end.unwrap_or(n).clamp(0, n) as usize;
if e < s {
return Ok(Value::List(vec![]));
}
Ok(Value::List(xs[s..e].to_vec()))
}
pub fn list_contains(list: &Value, item: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => Ok(Value::Bool(xs.iter().any(|x| x == item))),
Value::None => Ok(Value::Bool(false)),
_ => Err("list_contains needs list".into()),
}
}
pub fn list_index_of(list: &Value, item: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => Ok(xs
.iter()
.position(|x| x == item)
.map(|i| Value::Int(i as i64))
.unwrap_or(Value::None)),
Value::None => Ok(Value::None),
_ => Err("list_index_of needs list".into()),
}
}
pub fn list_reverse(list: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => {
let mut out = xs.clone();
out.reverse();
Ok(Value::List(out))
}
Value::None => Ok(Value::List(vec![])),
_ => Err("list_reverse needs list".into()),
}
}
pub fn list_first(list: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => Ok(xs.first().cloned().unwrap_or(Value::None)),
Value::None => Ok(Value::None),
_ => Err("list_first needs list".into()),
}
}
pub fn list_last(list: &Value) -> Result<Value, String> {
match list {
Value::List(xs) => Ok(xs.last().cloned().unwrap_or(Value::None)),
Value::None => Ok(Value::None),
_ => Err("list_last needs list".into()),
}
}
pub fn collection_clear(value: &Value) -> Result<Value, String> {
match value {
Value::List(_) | Value::None => Ok(Value::List(vec![])),
Value::Map(_) => Ok(Value::Map(vec![])),
_ => Err("clear needs list or map".into()),
}
}
fn require_i64(v: &Value, name: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!("{name} must be int")),
}
}
/// Bind helper used by dispatch for optional end=.
pub fn list_slice_bound(list: &Value, start: &Value, end: Option<&Value>) -> Result<Value, String> {
let s = require_i64(start, "start")?;
let e = match end {
None | Some(Value::None) => None,
Some(v) => Some(require_i64(v, "end")?),
};
list_slice(list, s, e)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn put_map_key_and_nested() {
let m = Value::Map(vec![("a".into(), Value::Int(1))]);
let m2 = collection_put(&m, &Value::Text("b".into()), &Value::Int(2)).unwrap();
assert!(matches!(map_get(&m2, &Value::Text("b".into())).unwrap(), Value::Int(2)));
let rows = Value::List(vec![Value::Map(vec![("qty".into(), Value::Int(1))])]);
let path = Value::List(vec![Value::Int(1), Value::Text("qty".into())]);
let rows2 = collection_put(&rows, &path, &Value::Int(9)).unwrap();
let row = match &rows2 {
Value::List(xs) => &xs[0],
_ => panic!(),
};
assert!(matches!(
map_get(row, &Value::Text("qty".into())).unwrap(),
Value::Int(9)
));
}
#[test]
fn put_none_single_key() {
let m = collection_put(&Value::None, &Value::Text("k".into()), &Value::Text("v".into()))
.unwrap();
assert!(matches!(m, Value::Map(_)));
}
}
+158 -3
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -100,8 +100,30 @@ pub enum HostFn {
HttpPostSse = 98,
OpenAiSseParse = 99,
StreamPublish = 100,
CollectionPut = 101,
ListPrepend = 102,
ListConcat = 103,
ListInsert = 104,
ListSetAt = 105,
ListRemoveAt = 106,
ListSlice = 107,
ListContains = 108,
ListIndexOf = 109,
ListReverse = 110,
ListFirst = 111,
ListLast = 112,
MapGet = 113,
MapDelete = 114,
MapHas = 115,
MapKeys = 116,
MapValues = 117,
MapItems = 118,
MapMerge = 119,
MapSize = 120,
CollectionClear = 121,
}
impl HostFn {
pub fn from_u16(id: u16) -> Option<Self> {
Some(match id {
@@ -196,6 +218,27 @@ impl HostFn {
98 => Self::HttpPostSse,
99 => Self::OpenAiSseParse,
100 => Self::StreamPublish,
101 => Self::CollectionPut,
102 => Self::ListPrepend,
103 => Self::ListConcat,
104 => Self::ListInsert,
105 => Self::ListSetAt,
106 => Self::ListRemoveAt,
107 => Self::ListSlice,
108 => Self::ListContains,
109 => Self::ListIndexOf,
110 => Self::ListReverse,
111 => Self::ListFirst,
112 => Self::ListLast,
113 => Self::MapGet,
114 => Self::MapDelete,
115 => Self::MapHas,
116 => Self::MapKeys,
117 => Self::MapValues,
118 => Self::MapItems,
119 => Self::MapMerge,
120 => Self::MapSize,
121 => Self::CollectionClear,
_ => return None,
})
}
@@ -296,6 +339,27 @@ impl HostFn {
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
"host_subtask_kill" | "subtask_kill" => Self::SubtaskKill,
"host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll,
"host_collection_put" | "collection_put" => Self::CollectionPut,
"host_list_prepend" | "list_prepend" => Self::ListPrepend,
"host_list_concat" | "list_concat" => Self::ListConcat,
"host_list_insert" | "list_insert" => Self::ListInsert,
"host_list_set_at" | "list_set_at" => Self::ListSetAt,
"host_list_remove_at" | "list_remove_at" => Self::ListRemoveAt,
"host_list_slice" | "list_slice" => Self::ListSlice,
"host_list_contains" | "list_contains" => Self::ListContains,
"host_list_index_of" | "list_index_of" => Self::ListIndexOf,
"host_list_reverse" | "list_reverse" => Self::ListReverse,
"host_list_first" | "list_first" => Self::ListFirst,
"host_list_last" | "list_last" => Self::ListLast,
"host_map_get" | "map_get" => Self::MapGet,
"host_map_delete" | "map_delete" => Self::MapDelete,
"host_map_has" | "map_has" => Self::MapHas,
"host_map_keys" | "map_keys" => Self::MapKeys,
"host_map_values" | "map_values" => Self::MapValues,
"host_map_items" | "map_items" => Self::MapItems,
"host_map_merge" | "map_merge" => Self::MapMerge,
"host_map_size" | "map_size" => Self::MapSize,
"host_collection_clear" | "collection_clear" => Self::CollectionClear,
_ => return None,
})
}
@@ -383,6 +447,27 @@ impl HostFn {
Self::ExtNativePath => "host_ext_native_path",
Self::MapSet => "host_map_set",
Self::ListAppend => "host_list_append",
Self::CollectionPut => "host_collection_put",
Self::ListPrepend => "host_list_prepend",
Self::ListConcat => "host_list_concat",
Self::ListInsert => "host_list_insert",
Self::ListSetAt => "host_list_set_at",
Self::ListRemoveAt => "host_list_remove_at",
Self::ListSlice => "host_list_slice",
Self::ListContains => "host_list_contains",
Self::ListIndexOf => "host_list_index_of",
Self::ListReverse => "host_list_reverse",
Self::ListFirst => "host_list_first",
Self::ListLast => "host_list_last",
Self::MapGet => "host_map_get",
Self::MapDelete => "host_map_delete",
Self::MapHas => "host_map_has",
Self::MapKeys => "host_map_keys",
Self::MapValues => "host_map_values",
Self::MapItems => "host_map_items",
Self::MapMerge => "host_map_merge",
Self::MapSize => "host_map_size",
Self::CollectionClear => "host_collection_clear",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -451,6 +536,20 @@ impl HostFn {
Self::WritebackScanPath => &["path"],
Self::MapSet => &["map", "key", "value"],
Self::ListAppend => &["list", "item"],
Self::CollectionPut => &["in", "at", "value"],
Self::ListPrepend => &["list", "item"],
Self::ListConcat => &["a", "b"],
Self::ListInsert => &["list", "index", "item"],
Self::ListSetAt => &["list", "index", "item"],
Self::ListRemoveAt => &["list", "index"],
Self::ListSlice => &["list", "start"],
Self::ListContains => &["list", "item"],
Self::ListIndexOf => &["list", "item"],
Self::ListReverse | Self::ListFirst | Self::ListLast => &["list"],
Self::MapGet | Self::MapDelete | Self::MapHas => &["map", "key"],
Self::MapKeys | Self::MapValues | Self::MapItems | Self::MapSize => &["map"],
Self::MapMerge => &["a", "b"],
Self::CollectionClear => &["value"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -482,6 +581,7 @@ impl HostFn {
}
Self::WritebackEnsure => &["placeholder", "line"],
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
Self::ListSlice => &["end"],
_ => &[],
}
}
@@ -670,11 +770,66 @@ pub fn call_host(
})
}
HostFn::MapSet => {
agent_rt::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
}
HostFn::ListAppend => {
agent_rt::list_append(require(bound, "list")?, require(bound, "item")?)
super::collection::list_append(require(bound, "list")?, require(bound, "item")?)
}
HostFn::CollectionPut => super::collection::collection_put(
require(bound, "in")?,
require(bound, "at")?,
require(bound, "value")?,
),
HostFn::ListPrepend => {
super::collection::list_prepend(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListConcat => {
super::collection::list_concat(require(bound, "a")?, require(bound, "b")?)
}
HostFn::ListInsert => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_insert(require(bound, "list")?, idx, require(bound, "item")?)
}
HostFn::ListSetAt => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_set_at(require(bound, "list")?, idx, require(bound, "item")?)
}
HostFn::ListRemoveAt => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_remove_at(require(bound, "list")?, idx)
}
HostFn::ListSlice => super::collection::list_slice_bound(
require(bound, "list")?,
require(bound, "start")?,
bound.get("end"),
),
HostFn::ListContains => {
super::collection::list_contains(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListIndexOf => {
super::collection::list_index_of(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListReverse => super::collection::list_reverse(require(bound, "list")?),
HostFn::ListFirst => super::collection::list_first(require(bound, "list")?),
HostFn::ListLast => super::collection::list_last(require(bound, "list")?),
HostFn::MapGet => super::collection::map_get(require(bound, "map")?, require(bound, "key")?),
HostFn::MapDelete => super::collection::map_delete(require(bound, "map")?, require(bound, "key")?),
HostFn::MapHas => super::collection::map_has(require(bound, "map")?, require(bound, "key")?),
HostFn::MapKeys => super::collection::map_keys(require(bound, "map")?),
HostFn::MapValues => super::collection::map_values(require(bound, "map")?),
HostFn::MapItems => super::collection::map_items(require(bound, "map")?),
HostFn::MapMerge => super::collection::map_merge(require(bound, "a")?, require(bound, "b")?),
HostFn::MapSize => super::collection::map_size(require(bound, "map")?),
HostFn::CollectionClear => super::collection::collection_clear(require(bound, "value")?),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
+1
View File
@@ -5,6 +5,7 @@
//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only.
pub mod agent_rt;
pub mod collection;
mod dispatch;
pub mod event_bus;
pub mod foreign;
+19 -7
View File
@@ -24,6 +24,8 @@ pub struct Interpreter {
pub trace: bool,
capture: bool,
pub captured_stdout: String,
/// Bindings in the entry (`# main` / sole object) env after it finishes.
pub entry_bindings: HashMap<String, Value>,
current_span: Span,
input: InputFeed,
host: HostContext,
@@ -50,6 +52,10 @@ impl Env {
fn set(&mut self, name: String, value: Value) {
self.vars.insert(name, value);
}
fn vars_clone(&self) -> HashMap<String, Value> {
self.vars.clone()
}
}
pub(crate) enum EvArg {
@@ -64,6 +70,7 @@ impl Interpreter {
trace,
capture: false,
captured_stdout: String::new(),
entry_bindings: HashMap::new(),
current_span: Span::new(1, 1),
input: InputFeed::new(false, Vec::new()),
host: HostContext::for_run(path, Default::default(), Vec::new()),
@@ -78,6 +85,7 @@ impl Interpreter {
trace,
capture: true,
captured_stdout: String::new(),
entry_bindings: HashMap::new(),
current_span: Span::new(1, 1),
input: InputFeed::new(true, Vec::new()),
host: HostContext::for_capture(path, Default::default()),
@@ -140,7 +148,7 @@ impl Interpreter {
) -> Result<Value> {
let fun = find_function_anywhere(module, name)
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
self.run_function(module, fun, Env::new(), args)
self.run_function(module, fun, Env::new(), args, false)
}
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
@@ -148,7 +156,7 @@ impl Interpreter {
self.site_module = Some(module as *const Module);
let result = (|| {
if let Some(main) = find_top(module, "main") {
return self.run_function(module, main, Env::new(), &[]);
return self.run_function(module, main, Env::new(), &[], true);
}
// Document-as-entry: sole top-level `#` object with no params (e.g. `# Hello World`).
let entries: Vec<&Function> = module
@@ -157,7 +165,7 @@ impl Interpreter {
.filter(|f| f.is_object() && f.params.is_empty())
.collect();
if entries.len() == 1 {
return self.run_function(module, entries[0], Env::new(), &[]);
return self.run_function(module, entries[0], Env::new(), &[], true);
}
bail!("no `# main` object to run");
})();
@@ -216,6 +224,7 @@ impl Interpreter {
fun: &Function,
mut env: Env,
args: &[(String, Value)],
capture_entry_env: bool,
) -> Result<Value> {
if self.trace {
emit_trace(
@@ -246,6 +255,9 @@ impl Interpreter {
})();
self.host.pop_call_frame();
let ret = body_result?;
if capture_entry_env {
self.entry_bindings = env.vars_clone();
}
if self.trace {
let display = ret.as_display();
emit_trace(
@@ -669,7 +681,7 @@ impl Interpreter {
"call_fn: `{name}` must have no parameters"
)));
}
return self.run_function(module, target, Env::new(), &[]);
return self.run_function(module, target, Env::new(), &[], false);
}
other if HostFn::from_name(other).is_some() => {
let hf = HostFn::from_name(other).unwrap();
@@ -707,7 +719,7 @@ impl Interpreter {
}
self.host.push_call_site_line(self.host.current_line);
let result = self.run_function(module, target, call_env, &[]);
let result = self.run_function(module, target, call_env, &[], false);
self.host.pop_call_site_line();
let result = result?;
if target.is_object() {
@@ -774,7 +786,7 @@ impl Interpreter {
}
self.host.push_call_site_line(self.host.current_line);
let result = self.run_function(lib, node, call_env, &[]);
let result = self.run_function(lib, node, call_env, &[], false);
self.host.pop_call_site_line();
let result = result?;
if node.is_object() {
@@ -821,7 +833,7 @@ impl Interpreter {
call_env.set("自".into(), recv.clone());
call_env.set("self".into(), recv);
self.host.push_call_site_line(self.host.current_line);
let result = self.run_function(owner, target, call_env, &[]);
let result = self.run_function(owner, target, call_env, &[], false);
self.host.pop_call_site_line();
result
}
+2
View File
@@ -265,6 +265,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
stdout: interp.captured_stdout,
value,
plots,
bindings: interp.entry_bindings,
})
}
Backend::Bytecode => {
@@ -287,6 +288,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
stdout: vm.captured_stdout,
value,
plots,
bindings: Default::default(),
})
}
}
+82 -3
View File
@@ -391,17 +391,89 @@ section.block > h2 {
}
@media (max-width: 960px) {
.struct-wrap { grid-template-columns: 1fr; }
.outline-panel { position: static; }
.outline-rail, .outline-panel { position: static; }
}
.outline-panel {
.outline-rail {
position: sticky;
top: 1rem;
display: flex;
flex-direction: column;
gap: 0.55rem;
min-width: 0;
}
.outline-section {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.55rem 0.6rem 0.65rem;
padding: 0.35rem 0.55rem 0.55rem;
box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}
.outline-summary {
cursor: pointer;
font: 600 0.72rem/1.3 var(--sans);
color: var(--muted);
letter-spacing: 0.02em;
text-transform: uppercase;
list-style: none;
padding: 0.2rem 0 0.35rem;
}
.outline-summary::-webkit-details-marker { display: none; }
.outline-panel {
position: static;
background: transparent;
border: none;
border-radius: 0;
padding: 0;
box-shadow: none;
}
.vars-panel {
max-height: min(50vh, 28rem);
overflow: auto;
font: 0.72rem/1.35 var(--mono);
}
.vars-list {
list-style: none;
margin: 0;
padding: 0;
}
.vars-item {
margin: 0 0 0.55rem;
padding-bottom: 0.45rem;
border-bottom: 1px solid var(--line);
}
.vars-item:last-child {
margin-bottom: 0;
padding-bottom: 0;
border-bottom: none;
}
.vars-name {
font-weight: 600;
color: var(--ink);
margin-bottom: 0.2rem;
word-break: break-all;
}
.vars-table {
width: 100%;
border-collapse: collapse;
font: inherit;
}
.vars-table th,
.vars-table td {
border: 1px solid var(--line);
padding: 0.15rem 0.3rem;
text-align: left;
vertical-align: top;
word-break: break-word;
}
.vars-table th {
background: #f5f5f7;
font-weight: 600;
color: var(--muted);
}
.vars-idx, .vars-key { color: var(--muted); white-space: nowrap; }
.vars-scalar { white-space: pre-wrap; }
.vars-empty, .vars-skipped { color: var(--muted); margin: 0.2rem 0; }
.vars-nested > summary { cursor: pointer; color: var(--muted); }
.fn-search {
width: 100%;
box-sizing: border-box;
@@ -1423,6 +1495,13 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
scrollIfPinned();
}}
if (thinkingEl && (answerNode && answerNode.data)) thinkingEl.open = false;
if (typeof ev.bindings_html === "string") {{
var vp = document.getElementById("vars-panel");
if (vp) {{
vp.innerHTML = ev.bindings_html
|| "<p class=\\"vars-empty\\">No bindings</p>";
}}
}}
}}
}}
}}
+39 -12
View File
@@ -23,7 +23,10 @@ use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text};
use crate::view::debug_page::{build_debug_model, page_debug};
use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel};
use crate::view::render::{
collect_input_prompts, render_bindings_html, render_module_structure, render_right_rail,
FileViewModel,
};
use crate::{run_file_capture, RunOptions};
pub struct ViewOptions {
@@ -306,18 +309,21 @@ pub(crate) fn build_file_view(
) -> 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 outline, input_prompts) = match crate::parse::parse_source(&source) {
Ok(module) => (
render_module_structure(&module, &source),
crate::view::render::render_function_outline(&module),
collect_input_prompts(&module),
),
let (mut structure, mut module_opt, input_prompts) = match crate::parse::parse_source(&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))
),
String::new(),
None,
Vec::new(),
),
};
@@ -332,8 +338,14 @@ pub(crate) fn build_file_view(
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
// Optional: sandbox to the whole view tree so sibling folders are reachable.
opts.fs_root = Some(root.root.clone());
let (stdout, stderr, ok, plots) = if awaiting_input || auto_stream {
(String::new(), String::new(), true, Vec::new())
let (stdout, stderr, ok, plots, mut bindings_html) = if awaiting_input || auto_stream {
(
String::new(),
String::new(),
true,
Vec::new(),
String::new(),
)
} else {
match run_file_capture(abs, &opts) {
Ok(cap) => (
@@ -341,12 +353,14 @@ pub(crate) fn build_file_view(
String::new(),
true,
cap.plots.into_iter().map(|p| p.svg).collect(),
render_bindings_html(&cap.bindings),
),
Err(e) => (
String::new(),
tidy_user_error(&format!("{e:#}"), abs, rel),
false,
Vec::new(),
String::new(),
),
}
};
@@ -356,11 +370,21 @@ pub(crate) fn build_file_view(
source = next;
if let Ok(module) = crate::parse::parse_source(&source) {
structure = render_module_structure(&module, &source);
outline = crate::view::render::render_function_outline(&module);
module_opt = Some(module);
}
}
}
outline.push_str(&crate::view::render::render_writeback_outline(&source));
let wb = crate::view::render::render_writeback_outline(&source);
let outline = match &module_opt {
Some(module) => render_right_rail(module, &bindings_html, &wb),
None => {
if bindings_html.is_empty() && wb.is_empty() {
String::new()
} else {
render_right_rail(&crate::ast::Module::default(), &bindings_html, &wb)
}
}
};
Ok(FileViewModel {
rel_path: rel.to_string(),
source,
@@ -374,6 +398,7 @@ pub(crate) fn build_file_view(
awaiting_input,
auto_stream,
plots,
bindings_html: std::mem::take(&mut bindings_html),
})
}
@@ -607,12 +632,14 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
Ok(cap) => {
// Keep the terminal frame small — tokens already streamed via bus.
let preview: String = cap.stdout.chars().take(500).collect();
let bindings_html = render_bindings_html(&cap.bindings);
let done = serde_json::json!({
"type": "done",
"run_id": run_id,
"path": rel_clone,
"ok": true,
"result": preview,
"bindings_html": bindings_html,
});
crate::host::event_bus::EventBus::global().publish_json(&done.to_string());
}
+7
View File
@@ -31,6 +31,13 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
vm.stderr = "execution skipped (--no-exec)".into();
vm.ok = true;
vm.plots.clear();
vm.bindings_html = String::from(r#"<p class="vars-skipped">skipped</p>"#);
// Rebuild outline so Variables shows skipped.
if let Ok(module) = crate::parse::parse_source(&vm.source) {
let wb = crate::view::render::render_writeback_outline(&vm.source);
vm.outline_html =
crate::view::render::render_right_rail(&module, &vm.bindings_html, &wb);
}
}
let links = LinkMode::Static {
from: Some(rel.clone()),
+201
View File
@@ -41,6 +41,8 @@ pub struct FileViewModel {
pub auto_stream: bool,
/// SVG plots from math lib (embedded in Execution).
pub plots: Vec<String>,
/// HTML for Variables panel (entry bindings after run).
pub bindings_html: String,
}
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
@@ -237,6 +239,184 @@ pub fn render_function_outline(module: &Module) -> String {
out
}
/// Right rail: collapsible Functions + Variables (+ optional writeback HTML appended by caller).
pub fn render_right_rail(module: &Module, bindings_html: &str, writeback_html: &str) -> String {
let fn_inner = if module.functions.is_empty() {
r#"<p class="vars-empty">No functions</p>"#.to_string()
} else {
let mut tree = String::from(
r#"<input type="search" id="fn-search" class="fn-search" placeholder="Search functions…" autocomplete="off" spellcheck="false"/>
<ul class="outline-tree">"#,
);
for fun in &module.functions {
tree.push_str(&outline_fun(fun, ""));
}
tree.push_str("</ul>");
tree
};
let vars = if bindings_html.is_empty() {
r#"<p class="vars-empty">No bindings</p>"#
} else {
bindings_html
};
format!(
r#"<div class="outline-rail" id="outline-rail">
<details class="outline-section" open>
<summary class="outline-summary">Functions</summary>
<div class="outline-panel" id="fn-outline">{fn_inner}</div>
</details>
<details class="outline-section" open>
<summary class="outline-summary">Variables</summary>
<div class="vars-panel" id="vars-panel">{vars}</div>
</details>
{wb}
</div>"#,
fn_inner = fn_inner,
vars = vars,
wb = writeback_html,
)
}
/// Render entry bindings as HTML tables (List / Map / records).
pub fn render_bindings_html(bindings: &HashMap<String, crate::value::Value>) -> String {
if bindings.is_empty() {
return String::new();
}
let mut names: Vec<&String> = bindings.keys().collect();
names.sort();
let mut out = String::from(r#"<ul class="vars-list">"#);
for name in names {
let Some(val) = bindings.get(name) else {
continue;
};
out.push_str(&format!(
r#"<li class="vars-item"><div class="vars-name">{}</div><div class="vars-value">{}</div></li>"#,
escape(name),
render_value_html(val, 0)
));
}
out.push_str("</ul>");
out
}
const BIND_MAX_DEPTH: usize = 2;
fn render_value_html(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(xs) => {
if let Some(keys) = record_keys(xs) {
return render_records_table(xs, &keys, depth);
}
let mut s = String::from(r#"<table class="vars-table"><thead><tr><th>#</th><th>value</th></tr></thead><tbody>"#);
for (i, item) in xs.iter().enumerate() {
s.push_str(&format!(
"<tr><td class=\"vars-idx\">{}</td><td>{}</td></tr>",
i + 1,
cell_html(item, depth)
));
}
if xs.is_empty() {
s.push_str(r#"<tr><td colspan="2" class="vars-empty">∅</td></tr>"#);
}
s.push_str("</tbody></table>");
s
}
Value::Map(pairs) => {
let mut s = String::from(
r#"<table class="vars-table"><thead><tr><th>key</th><th>value</th></tr></thead><tbody>"#,
);
for (k, val) in pairs {
s.push_str(&format!(
"<tr><td class=\"vars-key\">{}</td><td>{}</td></tr>",
escape(k),
cell_html(val, depth)
));
}
if pairs.is_empty() {
s.push_str(r#"<tr><td colspan="2" class="vars-empty">∅</td></tr>"#);
}
s.push_str("</tbody></table>");
s
}
other => format!(r#"<span class="vars-scalar">{}</span>"#, escape(&other.as_display())),
}
}
fn cell_html(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(_) | Value::Map(_) if depth >= BIND_MAX_DEPTH => {
format!(
r#"<details class="vars-nested"><summary>{}</summary><span class="vars-scalar">{}</span></details>"#,
escape(&brief_type(v)),
escape(&v.as_display())
)
}
Value::List(_) | Value::Map(_) => render_value_html(v, depth + 1),
other => escape(&other.as_display()),
}
}
fn brief_type(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::List(xs) => format!("List({})", xs.len()),
Value::Map(xs) => format!("Map({})", xs.len()),
_ => "…".into(),
}
}
fn record_keys(xs: &[crate::value::Value]) -> Option<Vec<String>> {
use crate::value::Value;
if xs.is_empty() {
return None;
}
let mut keys: Vec<String> = Vec::new();
for (i, item) in xs.iter().enumerate() {
let Value::Map(pairs) = item else {
return None;
};
if i == 0 {
keys = pairs.iter().map(|(k, _)| k.clone()).collect();
if keys.is_empty() {
return None;
}
}
}
Some(keys)
}
fn render_records_table(
xs: &[crate::value::Value],
keys: &[String],
depth: usize,
) -> String {
use crate::value::Value;
let mut s = String::from(r#"<table class="vars-table"><thead><tr><th>#</th>"#);
for k in keys {
s.push_str(&format!("<th>{}</th>", escape(k)));
}
s.push_str("</tr></thead><tbody>");
for (i, item) in xs.iter().enumerate() {
let Value::Map(pairs) = item else {
continue;
};
s.push_str(&format!(r#"<tr><td class="vars-idx">{}</td>"#, i + 1));
for k in keys {
let cell = pairs
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| cell_html(v, depth))
.unwrap_or_else(|| String::from(""));
s.push_str(&format!("<td>{cell}</td>"));
}
s.push_str("</tr>");
}
s.push_str("</tbody></table>");
s
}
fn outline_fun(fun: &Function, parent_path: &str) -> String {
let fn_path = fn_path(parent_path, &fun.name);
let mut s = format!(
@@ -998,4 +1178,25 @@ mod tests {
assert!(outline.contains("href=\"#fn-"), "{outline}");
assert!(outline.contains("ol-meta\">h"), "{outline}");
}
#[test]
fn right_rail_has_functions_and_variables() {
let src = include_str!("../../tests/structure/hello.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let mut bind = HashMap::new();
bind.insert(
"xs".into(),
crate::value::Value::List(vec![
crate::value::Value::Text("a".into()),
crate::value::Value::Text("b".into()),
]),
);
let html = render_right_rail(&module, &render_bindings_html(&bind), "");
assert!(html.contains("outline-rail"), "{html}");
assert!(html.contains("Functions"), "{html}");
assert!(html.contains("Variables"), "{html}");
assert!(html.contains("vars-panel"), "{html}");
assert!(html.contains("vars-table"), "{html}");
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
}
}