");
out
}
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
pub fn collect_input_prompts(module: &Module) -> Vec {
let mut out = Vec::new();
for fun in &module.functions {
collect_input_prompts_fun(fun, &mut out);
}
out
}
/// Stream panel is for LLM/agent token streaming — only when those ext packages are imported.
pub fn uses_stream_panel(module: &Module) -> bool {
module.imports.iter().any(|imp| import_enables_stream(&imp.path))
}
fn import_enables_stream(path: &str) -> bool {
let norm = path.replace('\\', "/");
let lower = norm.to_ascii_lowercase();
lower.contains("ext/ai/llm")
|| lower.contains("/llm.mq.md")
|| lower.ends_with("llm.mq.md")
|| lower.contains("ext/llm")
|| norm.contains("ext/ai/大模型")
|| norm.contains("大模型.mq.md")
|| lower.contains("ext/ai/agent")
|| lower.contains("/agent.mq.md")
|| lower.ends_with("agent.mq.md")
|| lower.contains("ext/agent")
|| norm.contains("ext/ai/智能体")
|| norm.contains("智能体.mq.md")
}
fn collect_input_prompts_fun(fun: &Function, out: &mut Vec) {
for stmt in &fun.body {
collect_input_prompts_stmt(stmt, out);
}
for child in &fun.children {
collect_input_prompts_fun(child, out);
}
}
fn collect_input_prompts_stmt(stmt: &Stmt, out: &mut Vec) {
match stmt {
Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => {
collect_input_prompts_expr(value, out);
}
Stmt::Call { call, .. } => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Stmt::Branch { arms, .. } => {
for arm in arms {
if let Some(c) = &arm.condition {
collect_input_prompts_expr(c, out);
}
for s in &arm.body {
collect_input_prompts_stmt(s, out);
}
}
}
Stmt::While {
condition, body, ..
} => {
collect_input_prompts_expr(condition, out);
for s in body {
collect_input_prompts_stmt(s, out);
}
}
Stmt::ForEach { body, .. } => {
for s in body {
collect_input_prompts_stmt(s, out);
}
}
}
}
fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec) {
match expr {
Expr::Occluded { payload, .. } => {
if let Some(inner) = payload {
collect_input_prompts_expr(inner, out);
}
}
Expr::Call(call) => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Expr::Unary { expr, .. } => collect_input_prompts_expr(expr, out),
Expr::Binary { left, right, .. } => {
collect_input_prompts_expr(left, out);
collect_input_prompts_expr(right, out);
}
Expr::List(items) => {
for e in items {
collect_input_prompts_expr(e, out);
}
}
Expr::Map(pairs) => {
for (_, e) in pairs {
collect_input_prompts_expr(e, out);
}
}
Expr::Index { base, .. } => collect_input_prompts_expr(base, out),
Expr::Literal(_) | Expr::Var(_) | Expr::Interp(_) | Expr::Formula(_) | Expr::Code(_) => {}
}
}
fn push_input_prompt(call: &CallExpr, out: &mut Vec) {
if crate::aliases::canonical_builtin(&call.callee) != Some("input") {
return;
}
for a in &call.args {
if let Arg::Named { name, value } = a {
if crate::aliases::canonical_param("input", name) == "prompt" {
out.push(prompt_expr_text(value));
return;
}
}
}
if let Some(Arg::Positional(value)) = call.args.first() {
out.push(prompt_expr_text(value));
return;
}
out.push(String::new());
}
fn prompt_expr_text(expr: &Expr) -> String {
match expr {
Expr::Literal(Literal::Text(t)) => t.clone(),
Expr::Literal(lit) => lit_display(lit),
other => expr_display(other),
}
}
/// Browse Structure without run annotations (empty callouts).
pub fn render_module_structure(module: &Module, source: &str) -> String {
render_module_structure_mode(module, source, StructureMode::Browse)
}
/// Browse Structure: document surface with optional result annotations.
pub fn render_module_structure_with_annots(
module: &Module,
source: &str,
annots: &[crate::view::annot::ViewAnnot],
) -> String {
crate::view::document::render_module_document(module, source, annots)
}
pub fn render_module_structure_mode(
module: &Module,
source: &str,
mode: StructureMode,
) -> String {
match mode {
StructureMode::Browse => render_module_structure_with_annots(module, source, &[]),
StructureMode::Debug => render_module_structure_cards(module, source, mode),
}
}
/// Legacy AST-card Structure (debug + tests that need card markup).
pub fn render_module_structure_cards(
module: &Module,
source: &str,
mode: StructureMode,
) -> String {
let lines = classify_source(source);
let writebacks = writeback::writeback_map(source);
let mut out = String::new();
if !module.imports.is_empty() || !module.uses.is_empty() {
out.push_str("
import");
for imp in &module.imports {
let label = format!("{}:{}", imp.bind, imp.path);
out.push_str(&format!("{}", escape(&label)));
}
for u in &module.uses {
let label = format!("{}:{}", u.bind, u.path.join("."));
out.push_str(&format!("{}", escape(&label)));
}
out.push_str("
");
}
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
let mut cursor = body_start;
if module.functions.is_empty() {
out.push_str(&emit_comments(&lines, cursor, u32::MAX));
if out.is_empty() {
out.push_str("
(empty module)
");
}
return out;
}
// Leading comments before first function
let first = module.functions[0].span.line;
out.push_str(&emit_comments(&lines, cursor, first));
cursor = first;
for (i, fun) in module.functions.iter().enumerate() {
if i > 0 {
out.push_str(&emit_comments(&lines, cursor, fun.span.line));
}
let (html, next) = render_fun(fun, &lines, 0, "", mode, &writebacks);
out.push_str(&html);
cursor = next;
}
// Trailing comments after last function tree
out.push_str(&emit_comments(&lines, cursor, u32::MAX));
out
}
pub fn render_function_outline(module: &Module) -> String {
if module.functions.is_empty() {
return String::new();
}
let mut out = String::from(
r#"
"#,
);
for fun in &module.functions {
out.push_str(&outline_fun(fun, ""));
}
out.push_str("
");
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#"
No functions
"#.to_string()
} else {
let mut tree = String::from(
r#"
"#,
);
for fun in &module.functions {
tree.push_str(&outline_fun(fun, ""));
}
tree.push_str("
");
tree
};
let vars = if bindings_html.is_empty() {
r#"
No bindings
"#
} else {
bindings_html
};
format!(
r#"
Functions
{fn_inner}
Variables
{vars}
{wb}
"#,
fn_inner = fn_inner,
vars = vars,
wb = writeback_html,
)
}
/// Render entry bindings: visible preview in the rail; click card → inspect dialog.
pub fn render_bindings_html(bindings: &HashMap) -> String {
if bindings.is_empty() {
return String::new();
}
let mut names: Vec<&String> = bindings.keys().collect();
names.sort();
let mut out = String::from(r#"
"#);
for (i, name) in names.into_iter().enumerate() {
let Some(val) = bindings.get(name) else {
continue;
};
let kind = value_kind_label(val);
let preview = render_value_preview_html(val);
let full = render_value_rich(val, 0);
out.push_str(&format!(
r#"
{name}{kind}
{preview}
{full}
"#,
name = escape(name),
kind = escape(&kind),
preview = preview,
id = i,
full = full,
));
}
out.push_str("
");
out
}
/// Compact inline preview (may truncate visually via CSS).
fn render_value_preview_html(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"
$${}$$
"#, tex)
}
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
render_value_html(v, 0)
}
Value::Map(pairs) => {
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((_, _, complex)) = detect_matrix(rows) {
return render_matrix_grid(rows, complex);
}
}
// Prefer a short key/value peek for objects.
let mut s = String::from(r#"
"#);
for (k, val) in pairs.iter().take(6) {
if k == "matrix" || k == "矩阵" || k == "ops" {
s.push_str(&format!(
"
");
s
}
other => format!(
r#"{}"#,
escape(&other.as_display())
),
}
}
fn brief_preview_cell(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()),
Value::Formula(_) => "formula".into(),
other => {
let s = other.as_display();
if s.chars().count() > 36 {
format!("{}…", s.chars().take(36).collect::())
} else {
s
}
}
}
}
fn value_kind_label(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::None => "none".into(),
Value::Bool(_) => "bool".into(),
Value::Int(_) => "int".into(),
Value::Num(_) => "num".into(),
Value::Text(_) => "text".into(),
Value::Secret(_) => "secret".into(),
Value::Formula(crate::formula::Expr::Matrix { rows, .. }) => {
format!("formula · {}×{}", rows.len(), rows.first().map(|r| r.len()).unwrap_or(0))
}
Value::Formula(_) => "formula".into(),
Value::Code(c) => format!("code · {}", c.lang),
Value::List(xs) => {
if let Some((r, c, _)) = detect_matrix(xs) {
format!("matrix · {r}×{c}")
} else {
format!("list · {}", xs.len())
}
}
Value::Map(pairs) => {
if let Some(t) = pairs.iter().find(|(k, _)| k == "_type").and_then(|(_, v)| match v {
Value::Text(s) => Some(s.as_str()),
_ => None,
}) {
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((r, c, _)) = detect_matrix(rows) {
return format!("{t} · {r}×{c}");
}
}
t.to_string()
} else {
format!("map · {}", pairs.len())
}
}
}
}
/// Complex or real matrix: rows × cols, and whether cells are complex maps.
fn detect_matrix(xs: &[crate::value::Value]) -> Option<(usize, usize, bool)> {
use crate::value::Value;
if xs.is_empty() {
return None;
}
let mut cols = None;
let mut complex = false;
for row in xs {
let Value::List(cells) = row else {
return None;
};
if cells.is_empty() {
return None;
}
match cols {
None => cols = Some(cells.len()),
Some(c) if c != cells.len() => return None,
_ => {}
}
for c in cells {
match c {
Value::Num(_) | Value::Int(_) => {}
Value::Map(m)
if m.iter().any(|(k, _)| k == "re")
&& m.iter().any(|(k, _)| k == "im") =>
{
complex = true;
}
_ => return None,
}
}
}
Some((xs.len(), cols.unwrap_or(0), complex))
}
fn format_complex_cell(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::Num(n) => format_matrix_num(*n),
Value::Int(i) => i.to_string(),
Value::Map(m) => {
let re = m
.iter()
.find(|(k, _)| k == "re")
.and_then(|(_, v)| match v {
Value::Num(n) => Some(*n),
Value::Int(i) => Some(*i as f64),
_ => None,
})
.unwrap_or(0.0);
let im = m
.iter()
.find(|(k, _)| k == "im")
.and_then(|(_, v)| match v {
Value::Num(n) => Some(*n),
Value::Int(i) => Some(*i as f64),
_ => None,
})
.unwrap_or(0.0);
if im.abs() < 1e-12 {
format_matrix_num(re)
} else if re.abs() < 1e-12 {
format!("{}i", format_matrix_num(im))
} else {
format!("{}{:+}i", format_matrix_num(re), im)
}
}
other => other.as_display(),
}
}
fn format_matrix_num(n: f64) -> String {
if n.fract().abs() < 1e-12 && n.abs() < 1e15 {
format!("{}", n as i64)
} else {
let s = format!("{n:.6}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
}
fn render_matrix_grid(xs: &[crate::value::Value], complex: bool) -> String {
let mut s = String::from(r#"
"#);
if complex {
s.push_str(r#"
complex amplitudes
"#);
}
s.push_str("");
for row in xs {
let crate::value::Value::List(cells) = row else {
continue;
};
s.push_str("
");
for c in cells {
let label = escape(&format_complex_cell(c));
let mag = match c {
crate::value::Value::Num(n) => n.abs(),
crate::value::Value::Int(i) => (*i as f64).abs(),
crate::value::Value::Map(m) => {
let re = m
.iter()
.find(|(k, _)| k == "re")
.and_then(|(_, v)| match v {
crate::value::Value::Num(n) => Some(*n),
_ => None,
})
.unwrap_or(0.0);
let im = m
.iter()
.find(|(k, _)| k == "im")
.and_then(|(_, v)| match v {
crate::value::Value::Num(n) => Some(*n),
_ => None,
})
.unwrap_or(0.0);
(re * re + im * im).sqrt()
}
_ => 0.0,
};
let heat = mag.clamp(0.0, 1.0);
let bg = format!(
"rgba(74, 111, 165, {:.3})",
0.06 + heat * 0.42
);
s.push_str(&format!(
r#"
{label}
"#
));
}
s.push_str("
");
}
s.push_str("
");
s
}
const BIND_MAX_DEPTH: usize = 3;
/// Full rich HTML for the inspect dialog (matrices get a dedicated grid).
fn render_value_rich(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
if let Some(keys) = record_keys(xs) {
return render_records_table(xs, &keys, depth);
}
render_value_html(v, depth)
}
Value::Map(pairs) => {
// Prefer pretty matrix when object carries `matrix` / `矩阵`.
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((_, _, complex)) = detect_matrix(rows) {
let mut s = String::from(r#"
"#);
if let Some(Value::Text(t)) =
pairs.iter().find(|(k, _)| k == "_type").map(|(_, v)| v)
{
s.push_str(&format!(
r#"
{}"#,
escape(t)
));
if let Some(Value::Text(n)) =
pairs.iter().find(|(k, _)| k == "name" || k == "名").map(|(_, v)| v)
{
s.push_str(&format!(
r#" {}"#,
escape(n)
));
}
s.push_str("
");
}
s.push_str(&render_matrix_grid(rows, complex));
// Other keys (skip matrix / _type / name noise)
let rest: Vec<_> = pairs
.iter()
.filter(|(k, _)| {
k != "matrix"
&& k != "矩阵"
&& k != "_type"
&& k != "name"
&& k != "名"
&& k != "custom"
})
.collect();
if !rest.is_empty() {
s.push_str(r#"Other fields"#);
s.push_str(r#"
"#);
for (k, val) in rest {
s.push_str(&format!(
"
");
return s;
}
}
render_value_html(v, depth)
}
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(
r#"
$${}$$
"#,
tex
)
}
other => render_value_html(other, depth),
}
}
fn render_value_html(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
if let Some(keys) = record_keys(xs) {
return render_records_table(xs, &keys, depth);
}
let mut s = String::from(r#"
#
value
"#);
for (i, item) in xs.iter().enumerate() {
s.push_str(&format!(
"
{}
{}
",
i + 1,
cell_html(item, depth)
));
}
if xs.is_empty() {
s.push_str(r#"
∅
"#);
}
s.push_str("
");
s
}
Value::Map(pairs) => {
let mut s = String::from(
r#"
key
value
"#,
);
for (k, val) in pairs {
s.push_str(&format!(
"
{}
{}
",
escape(k),
cell_html(val, depth)
));
}
if pairs.is_empty() {
s.push_str(r#"
∅
"#);
}
s.push_str("
");
s
}
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"
$${}$$
"#, tex)
}
other => format!(r#"{}"#, 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#"{}{}"#,
escape(&brief_type(v)),
escape(&v.as_display())
)
}
Value::List(_) | Value::Map(_) => render_value_html(v, depth + 1),
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"
$${}$$
"#, tex)
}
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> {
use crate::value::Value;
if xs.is_empty() {
return None;
}
let mut keys: Vec = 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#"
#
"#);
for k in keys {
s.push_str(&format!("
{}
", escape(k)));
}
s.push_str("
");
for (i, item) in xs.iter().enumerate() {
let Value::Map(pairs) = item else {
continue;
};
s.push_str(&format!(r#"
{}
"#, 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!("
{cell}
"));
}
s.push_str("
");
}
s.push_str("
");
s
}
fn outline_fun(fun: &Function, parent_path: &str) -> String {
let fn_path = fn_path(parent_path, &fun.name);
let mut s = format!(
"
\
{}h{}",
escape(&fun.name),
escape(&fn_path),
fun.span.line,
escape(&fun.name),
fun.level,
);
if !fun.params.is_empty() {
s.push_str(" ");
for (i, p) in fun.params.iter().enumerate() {
if i > 0 {
s.push(' ');
}
if p.inferred {
s.push_str(&format!(
"{}",
escape(&p.name)
));
} else {
s.push_str(&format!(
"{}",
escape(&p.name)
));
}
}
s.push_str("");
}
if !fun.children.is_empty() {
s.push_str("
");
for child in &fun.children {
s.push_str(&outline_fun(child, &fn_path));
}
s.push_str("
");
}
s.push_str("
");
s
}
fn fn_path(parent_path: &str, name: &str) -> String {
if parent_path.is_empty() {
name.to_string()
} else {
format!("{parent_path}/{name}")
}
}
/// Line after closing frontmatter `---`, or 1 if none.
fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option {
let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?;
if first_code.text.trim() != "---" {
return Some(1);
}
for l in lines.iter().skip_while(|l| l.line_no <= first_code.line_no) {
if l.kind == LineKind::Code && l.text.trim() == "---" {
return Some(l.line_no + 1);
}
}
Some(1)
}
fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) -> String {
let mut s = String::new();
let mut paragraph: Vec = Vec::new();
let flush = |paragraph: &mut Vec, s: &mut String| {
if paragraph.is_empty() {
return;
}
// Soft-wrapped source lines → one Markdown paragraph (spaces between).
let text = paragraph.join(" ");
paragraph.clear();
s.push_str(&format!(
"
comment
{}
",
comment_markdown_to_html(&text)
));
};
for l in lines {
if l.line_no < from_line {
continue;
}
if l.line_no >= before_line {
break;
}
match l.kind {
LineKind::Comment => {
let text = l.text.trim();
if !text.is_empty() {
paragraph.push(text.to_string());
}
}
LineKind::Blank | LineKind::Writeback | LineKind::Code => flush(&mut paragraph, &mut s),
}
}
flush(&mut paragraph, &mut s);
s
}
/// Render narrative comments as Markdown (links, emphasis, code, lists, …).
pub(crate) fn comment_markdown_to_html(md: &str) -> String {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_TABLES);
opts.insert(Options::ENABLE_TASKLISTS);
let parser = Parser::new_ext(md, opts);
let mut out = String::new();
html::push_html(&mut out, parser);
out
}
fn render_fun(
fun: &Function,
lines: &[ClassifiedLine],
depth: usize,
parent_path: &str,
mode: StructureMode,
writebacks: &HashMap,
) -> (String, u32) {
let fn_path = fn_path(parent_path, &fun.name);
let mut s = String::new();
let nest = if depth > 0 { " nested" } else { "" };
s.push_str(&format!(
"
",
fun.level,
escape(&fun.name)
));
if !fun.params.is_empty() {
s.push_str("
");
for p in &fun.params {
let (cls, title) = if p.inferred {
("chip inferred", "inferred from prose / body")
} else {
("chip", "explicit + param")
};
s.push_str(&format!(
"{name}",
cls = cls,
title = title,
name = escape(&p.name),
fn = escape(&fun.name),
));
}
s.push_str("
");
}
let mut cursor = fun.span.line + 1;
// Comments / gap before first body stmt or child
let first_body = fun.body.first().map(stmt_start);
let first_child = fun.children.first().map(|c| c.span.line);
let first_content = match (first_body, first_child) {
(Some(a), Some(b)) => Some(a.min(b)),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => None,
};
if let Some(fc) = first_content {
s.push_str(&emit_comments(lines, cursor, fc));
cursor = fc;
}
// Interleave body stmts and nested functions by source line
let mut bi = 0usize;
let mut ci = 0usize;
while bi < fun.body.len() || ci < fun.children.len() {
let stmt_line = fun.body.get(bi).map(stmt_start);
let child_line = fun.children.get(ci).map(|c| c.span.line);
let take_stmt = match (stmt_line, child_line) {
(Some(sl), Some(cl)) => sl <= cl,
(Some(_), None) => true,
(None, Some(_)) => false,
(None, None) => break,
};
if take_stmt {
let stmt = &fun.body[bi];
let start = stmt_start(stmt);
s.push_str(&emit_comments(lines, cursor, start));
let (html, end) = render_stmt(stmt, lines, mode, writebacks);
s.push_str(&html);
cursor = end;
bi += 1;
} else {
let child = &fun.children[ci];
s.push_str(&emit_comments(lines, cursor, child.span.line));
let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode, writebacks);
s.push_str(&format!("
{html}
"));
cursor = end;
ci += 1;
}
}
s.push_str("
");
(s, cursor)
}
fn stmt_start(stmt: &Stmt) -> u32 {
match stmt {
Stmt::Assign { span, .. }
| Stmt::Return { span, .. }
| Stmt::Call { span, .. }
| Stmt::Expr { span, .. }
| Stmt::Branch { span, .. }
| Stmt::While { span, .. }
| Stmt::ForEach { span, .. } => span.line,
}
}
fn stmt_end_line(stmt: &Stmt) -> u32 {
match stmt {
Stmt::Assign { end_line, .. } => end_line + 1,
Stmt::Return { span, .. } | Stmt::Call { span, .. } | Stmt::Expr { span, .. } => {
span.line + 1
}
Stmt::Branch { arms, span, .. } => {
let mut end = span.line + 1;
for arm in arms {
for st in &arm.body {
end = end.max(stmt_end_line(st));
}
}
end
}
Stmt::While { body, span, .. } | Stmt::ForEach { body, span, .. } => {
let mut end = span.line + 1;
for st in body {
end = end.max(stmt_end_line(st));
}
end
}
}
}
fn output_card(line: u32, writebacks: &HashMap) -> String {
match writebacks.get(&line) {
Some(body) => render_output_card(line, body),
None => String::new(),
}
}
/// Live view + static site: text `
` and/or `` for image writebacks.
pub fn render_output_card(line: u32, combined: &str) -> String {
if combined.trim().is_empty() {
return String::new();
}
let badges = writeback_badges(combined);
let mut body_html = String::new();
let mut buf_text = String::new();
let flush_text = |buf: &mut String, out: &mut String| {
if buf.is_empty() {
return;
}
out.push_str(&format!(
r#"
{}
"#,
escape(buf.trim_end())
));
buf.clear();
};
for line_s in combined.lines() {
let t = line_s.trim();
if let Some(url) = extract_md_image_url(t) {
flush_text(&mut buf_text, &mut body_html);
body_html.push_str(&format!(
r#"{cap}"#,
src = escape(&url),
cap = escape(&url),
));
} else {
if !buf_text.is_empty() {
buf_text.push('\n');
}
buf_text.push_str(line_s);
}
}
flush_text(&mut buf_text, &mut body_html);
let has_img = body_html.contains("wb-image");
format!(
r#"
{badges}
{body}
"#,
line = line,
img_cls = if has_img { " output-card-image" } else { "" },
badges = badges,
body = body_html,
)
}
fn extract_md_image_url(line: &str) -> Option {
let t = line.trim();
let rest = t.strip_prefix("?;
let after = &rest[alt_end + 2..];
let url_end = after.rfind(')')?;
let url = after[..url_end].trim();
if url.is_empty() {
None
} else {
Some(url.to_string())
}
}
/// Document-surface marker for a writeback source line (comment or image).
pub fn render_writeback_source_line(line_no: u32, text: &str) -> String {
let trimmed = text.trim();
let is_image = trimmed.starts_with("![") && trimmed.contains("marqdo-out");
let kind = if is_image { "image" } else { "comment" };
let label = if is_image {
"writeback · image"
} else {
"writeback"
};
format!(
r#"
{label}{text}
"#,
line = line_no,
kind = kind,
label = label,
text = escape(trimmed),
)
}
fn writeback_badges(body: &str) -> String {
let mut keys = Vec::new();
for line in body.lines() {
if let Some(rest) = line.strip_prefix('[') {
if let Some(end) = rest.find(']') {
let k = &rest[..end];
if !k.is_empty() && !keys.iter().any(|x| x == k) {
keys.push(k.to_string());
}
}
}
}
if keys.is_empty() {
return r#"output"#.into();
}
keys.into_iter()
.map(|k| {
let cls = match k.as_str() {
"ok" => "wb-ok",
"error" => "wb-error",
"trace" => "wb-trace",
_ => "wb-other",
};
format!(r#"{k}"#, k = escape(&k))
})
.collect::>()
.join(" ")
}
/// Outline links to writeback cards (`#wb-{line}`).
pub fn render_writeback_outline(source: &str) -> String {
let map = writeback::writeback_map(source);
if map.is_empty() {
return String::new();
}
let mut lines: Vec = map.keys().copied().filter(|l| *l > 0).collect();
lines.sort_unstable();
if lines.is_empty() {
return String::new();
}
let mut out = String::from(
r#"
Writebacks
"#,
);
for line in lines {
let body = map.get(&line).map(|s| s.as_str()).unwrap_or("");
let label = if body.contains("[error]") {
"error"
} else if body.contains("[ok]") {
"ok"
} else if body.contains("[trace]") {
"trace"
} else {
"output"
};
out.push_str(&format!(
r##"
"##,
line = line,
label = label,
));
}
out.push_str("
");
out
}
/// `` M8: occlusion card — the description reads as prose, the payload as a
/// code chip, stubs get a badge. Shared by bind / expr / return statements.
fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String {
let pre = match name {
Some(n) => format!(
"`{}` =",
escape(n)
),
None => String::new(),
};
let val = match payload {
Some(e) => format!(
"{}",
escape(&expr_display(e))
),
None => String::from(
"桩",
),
};
format!(
"
",
escape(&expr_display(value))
),
Stmt::Branch { arms, .. } => {
let mut body =
String::from("
branch");
let mut arm_cursor = stmt_start(stmt) + 1;
for arm in arms {
let label = match &arm.condition {
None => "else".to_string(),
Some(c) => expr_display(c),
};
// comments before first stmt in arm (approx: between arms hard; use body starts)
let arm_first = arm.body.first().map(stmt_start);
body.push_str(&format!(
"
arm{}",
escape(&label)
));
if let Some(af) = arm_first {
body.push_str(&emit_comments(lines, arm_cursor, af));
arm_cursor = af;
}
body.push_str("
");
for st in &arm.body {
let start = stmt_start(st);
body.push_str(&emit_comments(lines, arm_cursor, start));
let (h, e) = render_stmt(st, lines, mode, writebacks);
body.push_str(&h);
arm_cursor = e;
}
body.push_str("
");
}
body.push_str("
");
body
}
Stmt::While {
condition, body, ..
} => {
let mut body_html = format!(
"
while{}
",
escape(&expr_display(condition))
);
let mut cursor = stmt_start(stmt) + 1;
for st in body {
let start = stmt_start(st);
body_html.push_str(&emit_comments(lines, cursor, start));
let (h, e) = render_stmt(st, lines, mode, writebacks);
body_html.push_str(&h);
cursor = e;
}
body_html.push_str("
"#,
line = line,
inner = inner,
),
}
}
fn call_display(call: &CallExpr) -> String {
let mut s = String::new();
let bracket = call.bracket_marked || !call.pre_modifiers.is_empty();
if bracket {
for m in &call.pre_modifiers {
s.push_str(m);
s.push(' ');
}
s.push('[');
if let Some(recv) = &call.receiver {
s.push('`');
s.push_str(recv);
s.push('`');
s.push('.');
s.push_str(&call.callee);
} else if let Some(path) = &call.path {
s.push_str(&path.join("."));
} else {
s.push_str(&call.callee);
}
s.push(']');
} else {
s.push_str("> ");
if let Some(recv) = &call.receiver {
s.push('`');
s.push_str(recv);
s.push('`');
s.push('.');
s.push_str(&call.callee);
} else if let Some(path) = &call.path {
s.push_str(&path.join("."));
} else {
s.push_str(&call.callee);
}
}
for a in &call.args {
match a {
Arg::Positional(e) => {
s.push(' ');
s.push_str(&expr_display(e));
}
Arg::Named { name, value } => {
s.push(' ');
s.push_str(name);
s.push('=');
s.push_str(&expr_display(value));
}
}
}
s
}
/// Surface-syntax preview for view (not Debug).
pub fn expr_display(expr: &Expr) -> String {
expr_prec(expr, 0)
}
fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
match expr {
// `` M2: show the occlusion surface (label + payload).
Expr::Occluded { label, payload } => match payload {
Some(inner) => format!("[{}]({})", label, expr_prec(inner, 0)),
None => format!("[{}]()", label),
},
Expr::Literal(lit) => lit_display(lit),
Expr::Var(name) => format!("`{name}`"),
Expr::Interp(parts) => {
let mut s = String::new();
for p in parts {
match p {
InterpPart::Lit(t) => s.push_str(t),
InterpPart::Var(n) => {
s.push('`');
s.push_str(n);
s.push('`');
}
InterpPart::Index { base, labels } => {
// Preferred surface: nested `[key](base)` (legacy footnote still parses).
let mut inner = format!("`{base}`");
for label in labels {
inner = format!("[{label}]({inner})");
}
s.push_str(&inner);
}
}
}
s
}
Expr::Unary { op, expr } => {
let prec = 5;
let inner = match op {
UnaryOp::Not => format!("not {}", expr_prec(expr, prec)),
UnaryOp::Neg => format!("-{}", expr_prec(expr, prec)),
};
wrap(inner, prec, parent_prec)
}
Expr::Binary { op, left, right } => {
let (sym, prec) = bin_sym_prec(*op);
let inner = format!(
"{} {} {}",
expr_prec(left, prec),
sym,
expr_prec(right, prec + 1) // left-assoc bias
);
wrap(inner, prec, parent_prec)
}
Expr::Call(call) => call_display(call),
Expr::List(items) => {
let parts: Vec = items.iter().map(|e| expr_prec(e, 0)).collect();
format!("[{}]", parts.join(", "))
}
Expr::Map(pairs) => {
let parts: Vec = pairs
.iter()
.map(|(k, e)| format!("{}: {}", k, expr_prec(e, 0)))
.collect();
format!("{{{}}}", parts.join(", "))
}
Expr::Index { base, label } => {
let key = match label {
crate::ast::IndexKey::Lit(s) => s.clone(),
crate::ast::IndexKey::Var(n) => format!("`{n}`"),
};
// Preferred surface: GFM link shape (legacy footnote still accepted by parser).
format!("[{}]({})", key, expr_prec(base, 0))
}
Expr::Formula(e) => format!("$$ {} $$", e.as_display()),
Expr::Code(c) => format!("```{} …```", c.lang),
}
}
/// Best-effort ASCII formula → TeX for KaTeX in view Structure.
pub(crate) fn formula_ascii_to_tex_pub(ascii: &str) -> String {
formula_ascii_to_tex(ascii)
}
/// Formula assign card for document surface embedding (single visual layer).
pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String {
format!(
r#"
formula{name}
$${tex}$$
"#,
name = escape(name),
tex = escape(tex),
)
}
/// Foreign code assign card for document surface embedding (single visual layer).
/// Head → body → foot(actions) so the source is never collapsed under the Run row.
pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String {
let placeholder = escape(&crate::foreign::default_cmd_display(lang));
format!(
r#"
code{name}{lang}
{src}
"#,
lang = escape(lang),
name = escape(name),
placeholder = placeholder,
src = escape(source),
)
}
fn formula_ascii_to_tex(ascii: &str) -> String {
let mut out = String::new();
let chars: Vec = ascii.chars().collect();
let mut i = 0usize;
while i < chars.len() {
let c = chars[i];
if c == '*' {
// multiplication: a*b → a \cdot b
out.push_str(r" \cdot ");
i += 1;
continue;
}
if c == '^' {
out.push('^');
i += 1;
if i < chars.len() && chars[i] == '(' {
out.push('{');
i += 1;
let start = i;
let mut depth = 1i32;
while i < chars.len() && depth > 0 {
match chars[i] {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
if depth > 0 {
i += 1;
}
}
out.push_str(&chars[start..i].iter().collect::());
if i < chars.len() && chars[i] == ')' {
i += 1;
}
out.push('}');
} else if i < chars.len() {
out.push('{');
out.push(chars[i]);
out.push('}');
i += 1;
}
continue;
}
// TeX specials that may appear in identifiers rarely
match c {
'{' | '}' | '%' | '&' | '#' | '$' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
i += 1;
}
out
}
fn wrap(inner: String, prec: u8, parent_prec: u8) -> String {
if prec < parent_prec {
format!("({inner})")
} else {
inner
}
}
fn bin_sym_prec(op: BinaryOp) -> (&'static str, u8) {
match op {
BinaryOp::Or => ("or", 1),
BinaryOp::And => ("and", 2),
BinaryOp::Eq => ("==", 3),
BinaryOp::Ne => ("!=", 3),
BinaryOp::Lt => ("<", 3),
BinaryOp::Le => ("<=", 3),
BinaryOp::Gt => (">", 3),
BinaryOp::Ge => (">=", 3),
BinaryOp::Add => ("+", 4),
BinaryOp::Sub => ("-", 4),
BinaryOp::Mul => ("*", 5),
BinaryOp::Div => ("/", 5),
}
}
fn lit_display(lit: &Literal) -> String {
match lit {
Literal::None => "None".into(),
Literal::Bool(true) => "True".into(),
Literal::Bool(false) => "False".into(),
Literal::Int(n) => n.to_string(),
Literal::Num(n) => crate::formula::format_num(*n),
Literal::Text(t) => t.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::{Arg, BinaryOp, CallExpr, Expr, Literal};
#[test]
fn expr_gt_is_surface() {
let e = Expr::Binary {
op: BinaryOp::Gt,
left: Box::new(Expr::Var("x".into())),
right: Box::new(Expr::Literal(Literal::Int(0))),
};
assert_eq!(expr_display(&e), "`x` > 0");
assert!(!expr_display(&e).contains("Binary"));
}
#[test]
fn structure_keeps_comments_and_surface_expr() {
let src = include_str!("../../tests/structure/nested-call.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("doc-prose") || html.contains("打印一句问候"), "{html}");
assert!(html.contains("print"));
assert!(!html.contains("Binary {"));
assert!(!html.contains("Literal(Int"));
}
#[test]
fn comments_render_as_paragraphs() {
let src = "段首说明\n续行仍属同段\n\n下一段\n\n# main\n\n> print text=x\n";
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
let blocks = html.matches("doc-prose").count();
assert!(blocks >= 2, "blank line should split comment paragraphs: {html}");
assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明
") || html.contains("段首说明"));
assert!(html.contains("下一段"));
}
#[test]
fn comments_render_markdown_links() {
let src = "见[仓库](https://github.com/cflmy/marqdo)与 `code`\n\n# main\n\n> print text=x\n";
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(
html.contains("仓库"),
"{html}"
);
assert!(html.contains("code"), "{html}");
assert!(!html.contains("[仓库](https://github.com/cflmy/marqdo)"));
}
#[test]
fn collect_input_prompts_from_fixture() {
let src = include_str!("../../tests/keywords/input.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let prompts = collect_input_prompts(&module);
assert_eq!(prompts, vec!["Name:".to_string()]);
}
#[test]
fn collect_input_prompts_absent_without_input() {
let src = include_str!("../../tests/structure/hello.mq.md");
let module = crate::parse::parse_source(src).unwrap();
assert!(collect_input_prompts(&module).is_empty());
}
#[test]
fn structure_omits_imported_lib_bodies() {
let src = "---\ntitle: t\nimport:\n text: lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
let local = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&local, src);
assert!(html.contains("doc-imports") || html.contains("lib/text.mq.md"), "{html}");
assert!(html.contains("lib/text.mq.md"), "{html}");
assert!(html.contains("main"), "{html}");
assert!(!html.contains("trim"), "{html}");
assert!(html.contains("data-line="), "{html}");
assert_eq!(local.functions.len(), 1);
assert_eq!(local.functions[0].name, "main");
}
#[test]
fn structure_formula_assign_not_comment() {
let src = include_str!("../../tests/lib/math-formula.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("badge\">formula"), "{html}");
assert!(html.contains("math-block"), "{html}");
assert!(html.contains("$$"), "{html}");
assert!(
!html.contains("comment-text\">x^2 - 2")
&& !html.contains("comment-text\">
x^2 - 2"),
"formula fence leaked into comments: {html}"
);
}
#[test]
fn structure_code_card() {
let src = include_str!("../../tests/lib/foreign-python.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("code-card"), "{html}");
assert!(html.contains("code-run"), "{html}");
assert!(html.contains("hello-from-python"), "{html}");
assert!(!html.contains("python name=hi"), "{html}");
}
#[test]
fn formula_ascii_to_tex_pow_and_mul() {
assert_eq!(formula_ascii_to_tex("x^2 - 2"), "x^{2} - 2");
assert_eq!(formula_ascii_to_tex("2*x"), r"2 \cdot x");
}
#[test]
fn structure_mode_browse_vs_debug() {
let src = include_str!("../../tests/structure/nested-call.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let browse = render_module_structure_mode(&module, src, StructureMode::Browse);
let debug = render_module_structure_mode(&module, src, StructureMode::Debug);
assert!(browse.contains("id=\"fn-"), "{browse}");
assert!(browse.contains("document-surface"), "{browse}");
assert!(!browse.contains("bp-gutter"), "{browse}");
assert!(debug.contains("bp-gutter"), "{debug}");
assert!(debug.contains("id=\"stmt-"), "{debug}");
assert!(debug.contains("card"), "{debug}");
}
#[test]
fn browse_preserves_prose_unified_line() {
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("对于输入变量"), "{html}");
assert!(html.contains("mq-anchor"), "{html}");
assert!(!html.contains("badge\">bind"), "{html}");
}
#[test]
fn function_outline_lists_nested_names() {
let src = include_str!("../../tests/structure/nested-call.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let outline = render_function_outline(&module);
assert!(outline.contains("outline-item"), "{outline}");
assert!(outline.contains("data-fn=\"main\""), "{outline}");
assert!(outline.contains("data-fn=\"问候\""), "{outline}");
assert!(outline.contains("data-fn-path=\"main/问候\""), "{outline}");
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-card"), "{html}");
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
}
#[test]
fn output_card_renders_image_writeback() {
let html = render_output_card(3, "[ok]\n");
assert!(html.contains("output-card-image"), "{html}");
assert!(html.contains(r#"src="plots/a.svg""#), "{html}");
assert!(html.contains("wb-ok") || html.contains(">ok<"), "{html}");
let text = render_output_card(1, "plain-42");
assert!(text.contains("output-body"), "{text}");
assert!(!text.contains("wb-image"), "{text}");
let src = render_writeback_source_line(4, "");
assert!(src.contains(r#"data-wb-kind="image""#), "{src}");
assert!(src.contains("writeback · image"), "{src}");
}
#[test]
fn structure_marks_inferred_params() {
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let add = module
.functions
.iter()
.find(|f| f.name == "加一函数")
.expect("加一函数");
assert!(add.params.iter().any(|p| p.name == "n" && p.inferred));
let html = render_module_structure(&module, src);
assert!(
html.contains("chip inferred")
&& (html.contains(">n<") || html.contains(r#"data-param-name="n""#)),
"expected inferred chip for n: {html}"
);
let outline = render_function_outline(&module);
assert!(
outline.contains("ol-param inferred") && outline.contains(">n<"),
"expected outline inferred param: {outline}"
);
}
#[test]
fn stream_panel_gated_on_llm_or_agent_import() {
let hello = crate::parse::parse_source(include_str!("../../tests/structure/hello.mq.md"))
.unwrap();
assert!(!uses_stream_panel(&hello));
let llm = crate::parse::parse_source(include_str!("../../tests/ext/llm-import.mq.md")).unwrap();
assert!(uses_stream_panel(&llm));
}
#[test]
fn call_display_bracket_without_modifiers() {
let call = CallExpr {
callee: "parse".into(),
path: Some(vec!["json".into(), "parse".into()]),
receiver: None,
args: vec![Arg::Named {
name: "text".into(),
value: Expr::Literal(Literal::Text("{}".into())),
}],
pre_modifiers: vec![],
bracket_marked: true,
};
let d = call_display(&call);
assert!(d.starts_with("[json.parse]"), "{d}");
assert!(!d.starts_with("> "), "{d}");
}
#[test]
fn call_display_gt_when_not_bracket() {
let call = CallExpr {
callee: "print".into(),
path: None,
receiver: None,
args: vec![Arg::Named {
name: "text".into(),
value: Expr::Literal(Literal::Text("hi".into())),
}],
pre_modifiers: vec![],
bracket_marked: false,
};
let d = call_display(&call);
assert!(d.starts_with("> print"), "{d}");
}
}