//! Browse Structure as a prose-preserving document surface + annotation bands.
//!
//! See `doc/design/view-document-annotations.md` · `doc/design/view-execution-trace.md`.
use std::collections::{HashMap, HashSet};
use crate::ast::{Function, Module, Stmt};
use crate::host::writeback;
use crate::lex::{classify_source, ClassifiedLine, LineKind};
use crate::parse::{scan_prose_line, ProseBit};
use crate::view::annot::{
annots_by_line, bit_at, bit_kind_class, prose_bit_end, render_annot_band, ViewAnnot,
};
use crate::view::html::escape;
use crate::view::render::{
comment_markdown_to_html, render_code_assign_card, render_formula_assign_card,
};
const MAX_VISIBLE_ANNOTS: usize = 4;
/// Render Browse Structure: narration kept, executable spans marked, annot bands attached.
pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot]) -> String {
let lines = classify_source(source);
let by_line = annots_by_line(annots);
let fun_by_line = index_functions(module);
let special = index_special_assigns(module, source);
let skip_body = special_body_lines(&special);
let stmt_lines = index_stmt_lines(module);
let writebacks = writeback::writeback_map(source);
let taken_arms = taken_arms_by_branch_line(annots);
let mut out = String::from(r#"
"#);
if !module.imports.is_empty() || !module.uses.is_empty() {
out.push_str(r#"
"#);
for imp in &module.imports {
out.push_str(&format!(
r#"{}:{}"#,
escape(&imp.bind),
escape(&imp.path)
));
}
for u in &module.uses {
out.push_str(&format!(
r#"{}:{}"#,
escape(&u.bind),
escape(&u.path.join("."))
));
}
out.push_str("
");
}
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
let mut para: Vec<(u32, String)> = Vec::new();
let flush_para = |para: &mut Vec<(u32, String)>, out: &mut String| {
if para.is_empty() {
return;
}
let first_line = para[0].0;
let text = para
.iter()
.map(|(_, t)| t.as_str())
.collect::>()
.join(" ");
para.clear();
let md = comment_markdown_to_html(&text);
out.push_str(&format!(
r#"
{md}
"#,
line = first_line,
md = md
));
};
let mut i = 0usize;
while i < lines.len() {
let l = &lines[i];
if l.line_no < body_start {
i += 1;
continue;
}
// Body lines of $$ / ``` already folded into formula/code cards.
if skip_body.contains(&l.line_no) {
flush_para(&mut para, &mut out);
i += 1;
continue;
}
// GFM table block (may be Comment or Code classified).
if looks_like_table_row(l.text.trim()) {
flush_para(&mut para, &mut out);
let (html, next) = render_table_block(&lines, i, &by_line, &writebacks);
out.push_str(&html);
i = next;
continue;
}
match l.kind {
LineKind::Blank => {
flush_para(&mut para, &mut out);
i += 1;
}
LineKind::Writeback => {
flush_para(&mut para, &mut out);
let start_line = l.line_no;
let mut block = String::new();
while i < lines.len() && matches!(lines[i].kind, LineKind::Writeback) {
if !block.is_empty() {
block.push('\n');
}
block.push_str(lines[i].text.trim_end_matches(['\r', '\n']));
i += 1;
}
out.push_str(&crate::view::render::render_writeback_source_line(
start_line, &block,
));
}
LineKind::Comment => {
let text = l.text.trim_end_matches(['\r', '\n']);
let trimmed = text.trim();
// Unbound ```lang fences stay Comment in lex — render as code cards
// (same chrome as bound foreign), never join into a prose blob.
if crate::foreign::is_fence_opener(trimmed)
|| (trimmed.starts_with("```") && !crate::foreign::is_fence_closer(trimmed))
{
flush_para(&mut para, &mut out);
let (html, next) = render_narrative_fence(&lines, i);
out.push_str(&html);
i = next;
continue;
}
if crate::foreign::is_fence_closer(trimmed) {
// Orphan closer — skip.
flush_para(&mut para, &mut out);
i += 1;
continue;
}
let bits = scan_prose_line(text);
let is_stmt = stmt_lines.contains(&l.line_no);
let has_annots = by_line
.get(&l.line_no)
.map(|v| !v.is_empty())
.unwrap_or(false);
// Decl alone stays in Markdown prose (keep links). Open a marked
// line block when there is executable prose, a stmt, or chips.
let needs_annot = is_stmt
|| has_annots
|| bits.iter().any(|b| {
matches!(b, ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. })
});
if needs_annot {
flush_para(&mut para, &mut out);
out.push_str(&render_line_block(
l.line_no,
text,
&bits,
by_line.get(&l.line_no).map(|v| v.as_slice()).unwrap_or(&[]),
special.get(&l.line_no),
writebacks.get(&l.line_no),
None,
));
} else if !trimmed.is_empty() {
para.push((l.line_no, trimmed.to_string()));
}
i += 1;
}
LineKind::Code => {
flush_para(&mut para, &mut out);
let text = l.text.trim_end_matches(['\r', '\n']);
if let Some(fun) = fun_by_line.get(&l.line_no) {
out.push_str(&render_fun_heading(fun, annots));
if let Some(list) = by_line.get(&l.line_no) {
if !list.is_empty() {
let owned: Vec = list.iter().map(|a| (*a).clone()).collect();
out.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS));
}
}
i += 1;
continue;
}
let trimmed = text.trim_start();
if let Some((kind, marker_len)) = list_marker(trimmed) {
let (html, next) = render_list_block(
&lines,
i,
kind,
marker_len,
&by_line,
&special,
&writebacks,
&taken_arms,
annots,
);
out.push_str(&html);
i = next;
continue;
}
let bits = scan_prose_line(text);
out.push_str(&render_line_block(
l.line_no,
text,
&bits,
by_line.get(&l.line_no).map(|v| v.as_slice()).unwrap_or(&[]),
special.get(&l.line_no),
writebacks.get(&l.line_no),
None,
));
i += 1;
}
}
}
flush_para(&mut para, &mut out);
out.push_str("
");
out
}
#[derive(Clone, Copy)]
enum ListKind {
Ul,
Ol,
}
fn list_marker(trimmed: &str) -> Option<(ListKind, usize)> {
if let Some(rest) = trimmed.strip_prefix("- ") {
let _ = rest;
return Some((ListKind::Ul, 2));
}
if trimmed.starts_with("-") && trimmed.len() > 1 && trimmed.as_bytes()[1].is_ascii_whitespace() {
return Some((ListKind::Ul, 2));
}
// N. or N. *
let bytes = trimmed.as_bytes();
let mut i = 0;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
if i > 0 && i < bytes.len() && bytes[i] == b'.' {
let after = i + 1;
if after < bytes.len() && bytes[after].is_ascii_whitespace() {
return Some((ListKind::Ol, after + 1));
}
if after < bytes.len() && bytes[after] == b'*' {
// "3.*" else — marker through '*'
return Some((ListKind::Ol, after + 1));
}
}
None
}
fn looks_like_table_row(trimmed: &str) -> bool {
trimmed.starts_with('|') && trimmed.matches('|').count() >= 2
}
fn looks_like_table_sep(trimmed: &str) -> bool {
if !trimmed.starts_with('|') {
return false;
}
trimmed
.chars()
.all(|c| c == '|' || c == '-' || c == ':' || c.is_whitespace())
}
fn indent_level(text: &str) -> usize {
let mut n = 0usize;
for c in text.chars() {
match c {
' ' => n += 1,
'\t' => n += 4,
_ => break,
}
}
n / 2 // 2 spaces per visual level
}
fn render_table_block(
lines: &[ClassifiedLine],
start: usize,
by_line: &HashMap>,
writebacks: &HashMap,
) -> (String, usize) {
let mut rows: Vec<(u32, String)> = Vec::new();
let mut i = start;
while i < lines.len() {
let t = lines[i].text.trim_end_matches(['\r', '\n']);
let trimmed = t.trim();
if !looks_like_table_row(trimmed) {
break;
}
rows.push((lines[i].line_no, trimmed.to_string()));
i += 1;
}
if rows.is_empty() {
return (String::new(), start + 1);
}
let first_line = rows[0].0;
let mut html = format!(
r#"
"#,
line = first_line
);
let mut header_done = false;
for (idx, (_ln, row)) in rows.iter().enumerate() {
if looks_like_table_sep(row) {
continue;
}
let cells: Vec<&str> = row
.trim()
.trim_matches('|')
.split('|')
.map(|c| c.trim())
.collect();
if !header_done {
html.push_str("
");
for c in &cells {
html.push_str(&format!("
{}
", escape(c)));
}
html.push_str("
");
header_done = true;
// If next is sep, skip handled above; if only one data row treated as header+body empty ok
if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) {
continue;
}
// Single-row table without sep: also emit as body
if rows.len() == 1 {
html.push_str("
");
for c in &cells {
html.push_str(&format!("
{}
", escape(c)));
}
html.push_str("
");
}
continue;
}
html.push_str("
");
for c in &cells {
html.push_str(&format!("
{}
", escape(c)));
}
html.push_str("
");
}
if header_done {
html.push_str("");
}
html.push_str("
");
// Annots on first table line (bind of collection).
if let Some(list) = by_line.get(&first_line) {
// A table is already its own readable value; a call chip would collapse
// the whole collection into an ellipsis. Keep only non-call chips.
let owned: Vec = list
.iter()
.filter(|a| a.kind != crate::view::annot::AnnotKind::Call)
.map(|a| (*a).clone())
.collect();
if !owned.is_empty() {
html.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS));
}
}
if let Some(body) = writebacks.get(&first_line) {
html.push_str(&crate::view::render::render_output_card(first_line, body));
}
html.push_str("
");
(html, i)
}
fn render_list_block(
lines: &[ClassifiedLine],
start: usize,
kind: ListKind,
_marker_len: usize,
by_line: &HashMap>,
special: &HashMap,
writebacks: &HashMap,
taken_arms: &HashMap,
all_annots: &[ViewAnnot],
) -> (String, usize) {
let base_indent = indent_level(&lines[start].text);
let tag = match kind {
ListKind::Ul => "ul",
ListKind::Ol => "ol",
};
let cls = match kind {
ListKind::Ul => "doc-loop",
ListKind::Ol => "doc-branch",
};
// Branch stmt line = list head line for taken-arm lookup.
let branch_line = lines[start].line_no;
let taken = taken_arms.get(&branch_line).copied();
let loop_id = all_annots
.iter()
.find(|a| {
a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line
})
.and_then(|a| a.loop_id);
let mut html = format!(
r#"<{tag} class="{cls}" data-line="{line}"{loop_attr} style="--doc-indent:{indent}">"#,
tag = tag,
cls = cls,
line = branch_line,
loop_attr = loop_id
.map(|id| format!(r#" data-loop-id="{id}""#))
.unwrap_or_default(),
indent = base_indent.max(1),
);
// Loop iteration picker (default = last).
if matches!(kind, ListKind::Ul) {
let frames: Vec<&ViewAnnot> = all_annots
.iter()
.filter(|a| {
a.kind == crate::view::annot::AnnotKind::LoopFrame
&& a.anchor_line == branch_line
})
.collect();
if frames.len() >= 2 {
html.push_str(r#"");
}
}
let mut i = start;
let mut arm_index = 0usize;
while i < lines.len() {
let text = lines[i].text.trim_end_matches(['\r', '\n']);
let trimmed = text.trim_start();
let ind = indent_level(text);
if lines[i].kind == LineKind::Blank {
// Blank inside list: peek ahead — if next is deeper/same list continue, else break.
if i + 1 < lines.len() {
let n = &lines[i + 1];
let nt = n.text.trim_end_matches(['\r', '\n']);
if nt.trim().is_empty() {
i += 1;
continue;
}
let nind = indent_level(nt);
if nind > base_indent
|| (nind == base_indent && list_marker(nt.trim_start()).is_some())
{
i += 1;
continue;
}
}
break;
}
if ind < base_indent {
break;
}
if ind == base_indent {
if let Some((k, mlen)) = list_marker(trimmed) {
if !matches!(
(k, kind),
(ListKind::Ul, ListKind::Ul) | (ListKind::Ol, ListKind::Ol)
) {
break;
}
let head = trimmed[mlen..].trim();
let arm_cls = match (kind, taken) {
(ListKind::Ol, Some(t)) if t == arm_index => "arm-taken",
(ListKind::Ol, Some(_)) => "arm-miss",
(ListKind::Ol, None) => "",
_ => "",
};
html.push_str(&format!(
r#"
"#,
render_surface_line(lines[i].line_no, head, by_line)
));
// Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS).
let mut head_annots: Vec = Vec::new();
if let Some(list) = by_line.get(&lines[i].line_no) {
for a in list {
if a.kind == crate::view::annot::AnnotKind::Branch {
continue;
}
head_annots.push((*a).clone());
}
}
if matches!(kind, ListKind::Ol) {
// Branch annots are keyed to the list's first line, not each arm head.
if let Some(list) = by_line.get(&branch_line) {
for a in list {
if a.kind == crate::view::annot::AnnotKind::Branch
&& a.arm_index == Some(arm_index)
{
head_annots.push((*a).clone());
}
}
}
}
if !head_annots.is_empty() {
html.push_str(&render_annot_band(&head_annots, MAX_VISIBLE_ANNOTS));
}
// Body: following lines with greater indent until next sibling.
i += 1;
html.push_str(r#"
"#);
while i < lines.len() {
let t2 = lines[i].text.trim_end_matches(['\r', '\n']);
if t2.trim().is_empty() {
// allow blank inside body
if i + 1 < lines.len()
&& indent_level(&lines[i + 1].text) > base_indent
{
i += 1;
continue;
}
break;
}
let ind2 = indent_level(t2);
if ind2 <= base_indent {
break;
}
// Nested list at deeper indent.
let tr2 = t2.trim_start();
if let Some((nk, _)) = list_marker(tr2) {
let (inner, next) = render_list_block(
lines,
i,
nk,
0,
by_line,
special,
writebacks,
taken_arms,
all_annots,
);
html.push_str(&inner);
i = next;
continue;
}
if looks_like_table_row(tr2) {
let (th, next) = render_table_block(lines, i, by_line, writebacks);
html.push_str(&th);
i = next;
continue;
}
let bits = scan_prose_line(t2);
html.push_str(&render_line_block(
lines[i].line_no,
t2,
&bits,
by_line
.get(&lines[i].line_no)
.map(|v| v.as_slice())
.unwrap_or(&[]),
special.get(&lines[i].line_no),
writebacks.get(&lines[i].line_no),
Some(ind2),
));
i += 1;
}
html.push_str("
");
arm_index += 1;
continue;
}
break;
}
// Deeper than base but not under an open item — shouldn't happen; stop.
break;
}
html.push_str(&format!("{tag}>", tag = tag));
(html, i)
}
fn render_surface_line(
line_no: u32,
head: &str,
by_line: &HashMap>,
) -> String {
let bits = scan_prose_line(head);
if bits.is_empty() {
// Else arm "*" or plain condition text.
if head.trim() == "*" {
return r#"else"#.into();
}
format!(
r#"{}"#,
escape(head)
)
} else {
let annots = by_line
.get(&line_no)
.map(|v| v.as_slice())
.unwrap_or(&[]);
render_prose_with_marks(line_no, head, &bits, annots)
}
}
/// SSR default: taken arm for the highest `call_id` per branch line (matches last-call picker).
fn taken_arms_by_branch_line(annots: &[ViewAnnot]) -> HashMap {
let mut best: HashMap = HashMap::new();
for a in annots {
if a.kind != crate::view::annot::AnnotKind::Branch {
continue;
}
let Some(idx) = a.arm_index else { continue };
let cid = a.call_id.unwrap_or(0);
let entry = best.entry(a.anchor_line).or_insert((cid, idx));
if cid >= entry.0 {
*entry = (cid, idx);
}
}
best.into_iter().map(|(line, (_, arm))| (line, arm)).collect()
}
fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
let mut s = format!(
r##"
{name}
说明"##,
line = fun.span.line,
name = escape(&fun.name),
);
// Call picker placeholder: filled when ≥2 call frames exist for this fn.
let call_labels: Vec<&ViewAnnot> = annots
.iter()
.filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name)
.collect();
if call_labels.len() >= 2 {
s.push_str(r#"");
}
s.push_str("
");
if !fun.params.is_empty() {
// Default SSR values = last call frame (matches picker default = last option).
let default_args = call_labels
.last()
.map(|a| parse_args_brief(&a.value))
.unwrap_or_default();
s.push_str(r#"
"#);
for p in &fun.params {
let cls = if p.inferred {
"chip inferred"
} else {
"chip"
};
let title = if p.inferred {
"inferred from prose / body"
} else {
"explicit + param"
};
let val = default_args
.get(p.name.as_str())
.filter(|v| !v.is_empty())
.map(|v| format!("={}", escape(v)))
.unwrap_or_default();
// Always emit chip-val so call-picker JS can refresh per frame.
s.push_str(&format!(
r#"{name}{val}"#,
cls = cls,
title = title,
name = escape(&p.name),
fn = escape(&fun.name),
val = val,
));
}
s.push_str("
");
}
s.push_str("
");
s
}
/// Parse `args_brief` (`谁=marqdo, n=37`) into name → value.
fn parse_args_brief(brief: &str) -> HashMap {
let mut m = HashMap::new();
if brief.trim().is_empty() {
return m;
}
for part in brief.split(", ") {
if let Some((k, v)) = part.split_once('=') {
if !k.is_empty() {
m.insert(k.to_string(), v.to_string());
}
}
}
m
}
/// Split a statement line holding one occlusion `[描述](实现)`.
///
/// Returns `(prefix, label, payload, suffix)`. Display-only: the parser already
/// validated the real structure, this just decides how to paint it.
fn split_occlusion(line: &str) -> Option<(String, String, String, String)> {
let chars: Vec = line.chars().collect();
let mut i = 0usize;
let mut in_bt = false;
let mut in_str = false;
while i < chars.len() {
let c = chars[i];
if in_str {
if c == '\\' {
i += 2;
continue;
}
if c == '"' {
in_str = false;
}
i += 1;
continue;
}
if in_bt {
if c == '`' {
in_bt = false;
}
i += 1;
continue;
}
match c {
'`' => in_bt = true,
'"' => in_str = true,
'[' if chars.get(i + 1) != Some(&'^') => {
if let Some(close) = match_delim(&chars, i, '[', ']') {
if chars.get(close + 1) == Some(&'(') {
if let Some(paren) = match_delim(&chars, close + 1, '(', ')') {
let mut prefix: String = chars[..i].iter().collect();
let label: String = chars[i + 1..close].iter().collect();
let payload: String = chars[close + 2..paren].iter().collect();
let suffix: String = chars[paren + 1..].iter().collect();
// `**名 = [..](..)**` reads as bold code: drop the
// emphasis markers so the label reads as prose.
if let Some(p) = prefix.strip_suffix("**") {
prefix = p.to_string();
}
prefix = prefix.trim_end().to_string();
if let Some(p) = prefix.strip_prefix("**") {
prefix = p.to_string();
}
let suffix = suffix.strip_prefix("**").unwrap_or(&suffix).to_string();
return Some((
prefix,
label.trim().to_string(),
payload.trim().to_string(),
suffix.trim().to_string(),
));
}
}
}
}
_ => {}
}
i += 1;
}
None
}
fn match_delim(chars: &[char], start: usize, open: char, close: char) -> Option {
let mut depth = 0i32;
let mut i = start;
let mut in_bt = false;
let mut in_str = false;
while i < chars.len() {
let c = chars[i];
if in_str {
if c == '\\' {
i += 2;
continue;
}
if c == '"' {
in_str = false;
}
i += 1;
continue;
}
if in_bt {
if c == '`' {
in_bt = false;
}
i += 1;
continue;
}
match c {
'`' => in_bt = true,
'"' => in_str = true,
c if c == open => depth += 1,
c if c == close => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}
/// Render one occlusion line: description as prose, payload as a code chip,
/// stubs get a badge. `` M8
fn render_occlusion_line(line_no: u32, line: &str) -> Option {
let (prefix, label, payload, suffix) = split_occlusion(line)?;
let stub = payload.is_empty();
// The rest of the view drops backticks (see the `mq-anchor` marks), so the
// assignment head reads as `留存 =` rather than `` `留存` = ``.
let head = prefix
.trim_end()
.trim_end_matches('=')
.trim()
.trim_matches('`')
.to_string();
let mut html = format!(r#"
");
Some(html)
}
fn render_line_block(
line_no: u32,
text: &str,
bits: &[ProseBit],
annots: &[&ViewAnnot],
special: Option<&SpecialAssign>,
writeback_body: Option<&String>,
indent: Option,
) -> String {
let indent_style = indent
.map(|n| format!(r#" style="--doc-indent:{n}""#))
.unwrap_or_default();
// Source structure always visible — do not stamp data-call-ids (frame filter is chips-only).
let mut s = format!(
r#"
"#,
line = line_no,
indent = indent_style,
);
match special {
Some(SpecialAssign::Formula { name, tex, .. }) => {
s.push_str(&render_formula_assign_card(name, tex));
}
Some(SpecialAssign::Code {
name,
lang,
source,
..
}) => {
s.push_str(&render_code_assign_card(name, lang, source));
}
None => {
let trimmed = text.trim_start();
// `` M8: an occlusion line is painted as description + code chip
// regardless of annotation bits (the annotator always emits spans).
if let Some(html) = render_occlusion_line(line_no, trimmed) {
s.push_str(&html);
if let Some(body) = writeback_body {
s.push_str(&crate::view::render::render_output_card(line_no, body));
}
// Must close `.doc-block` — an early return left the wrapper open and
// nested the Functions/Variables outline under the document surface.
let band_annots: Vec = annots
.iter()
.filter(|a| !is_noisy_result_chip(a))
.map(|a| (*a).clone())
.collect();
if !band_annots.is_empty() {
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
}
s.push_str("
");
return s;
}
if bits.is_empty() {
if let Some(rest) = trimmed.strip_prefix("> ") {
let aid = match_annot_for_line(annots)
.map(|a| a.id.as_str())
.unwrap_or("");
s.push_str(&format!(
r#"
> {rest}
"#,
line = line_no,
aid = escape(aid),
rest = escape(rest),
));
} else if let Some(rest) = trimmed.strip_prefix('>') {
let aid = match_annot_for_line(annots)
.map(|a| a.id.as_str())
.unwrap_or("");
s.push_str(&format!(
r#"
> {rest}
"#,
line = line_no,
aid = escape(aid),
rest = escape(rest.trim_start()),
));
} else {
s.push_str(&format!(
r#"
");
}
}
}
if let Some(body) = writeback_body {
s.push_str(&crate::view::render::render_output_card(line_no, body));
}
// Formula/code cards are the single visual truth — do not stack Bind chips
// (or fence/SVG dumps) underneath. Variables rail still has final values.
let band_annots: Vec = if special.is_some() {
Vec::new()
} else {
annots
.iter()
.filter(|a| !is_noisy_result_chip(a))
.map(|a| (*a).clone())
.collect()
};
if !band_annots.is_empty() {
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
}
s.push_str("");
s
}
/// Huge SVG / fenced code dumps — prefer abbreviated chips from annot builder;
/// only drop if detail is still an unreadable dump.
fn is_noisy_result_chip(a: &ViewAnnot) -> bool {
if a.kind != crate::view::annot::AnnotKind::Bind {
return false;
}
let v = a.detail.as_str();
v.contains("