//! Render Marqdo AST as HTML fragments for `view`.
//!
//! Comments are not in the AST; they are interleaved from classified source lines.
//! Expressions are shown in surface syntax, never Rust `Debug`.
use std::collections::HashMap;
use crate::ast::{
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
};
use crate::host::writeback;
use crate::lex::{classify_source, ClassifiedLine, LineKind};
use crate::view::html::escape;
use pulldown_cmark::{html, Options, Parser};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StructureMode {
/// Documentation browse: fun anchors, no breakpoint gutters
Browse,
/// Debugger: breakpoint gutters on statements
Debug,
}
pub struct FileViewModel {
#[allow(dead_code)]
pub rel_path: String,
pub source: String,
pub structure_html: String,
pub outline_html: String,
pub stdout: String,
pub stderr: String,
pub ok: bool,
/// Text shown in the live-view preset stdin box.
pub preset_stdin: String,
/// One entry per `input` / `输入` call (prompt text; may be empty).
/// Empty vec → page does not use input; hide the preset form.
pub input_prompts: Vec,
/// Live view: program uses `input` but no stdin yet — execution deferred until form submit.
pub awaiting_input: bool,
/// Live view: stdin present — skip blocking page-load run; client auto-starts Stream SSE.
pub auto_stream: bool,
/// Show the LLM/agent Stream panel (live view only; gated on ext llm/agent import).
pub show_stream: bool,
/// SVG plots from math lib (embedded in Execution).
pub plots: Vec,
/// HTML for Variables panel (entry bindings after run).
pub bindings_html: String,
}
/// 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, .. } => {
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::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),
}
}
pub fn render_module_structure(module: &Module, source: &str) -> String {
render_module_structure_mode(module, source, StructureMode::Browse)
}
pub fn render_module_structure_mode(
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::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, …).
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),
));
}
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::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, .. } => 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) => {
let badges = writeback_badges(body);
format!(
r#"
{badges}
{}
"#,
escape(body)
)
}
None => String::new(),
}
}
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##"
",
escape(&call_display(call))
),
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("