Refactor executable library handbooks and improve document reading
This commit is contained in:
1 parent
16c44588d5
commit
c50c515c4a
191 files changed
+29572
-7816
No files matched your search
+371
-227
@@ -26,10 +26,12 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
let special = index_special_assigns(module, source);
|
||||
let skip_body = special_body_lines(&special);
|
||||
let stmt_lines = index_stmt_lines(module);
|
||||
let occluded_lines = index_occluded_lines(module);
|
||||
let writebacks = writeback::writeback_map(source);
|
||||
let taken_arms = taken_arms_by_branch_line(annots);
|
||||
|
||||
let mut out = String::from(r#"<div class="document-surface">"#);
|
||||
out.push_str(&render_syntax_guide());
|
||||
|
||||
if !module.imports.is_empty() || !module.uses.is_empty() {
|
||||
out.push_str(r#"<div class="doc-imports">"#);
|
||||
@@ -62,10 +64,11 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
.map(|(_, t)| t.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
|
||||
para.clear();
|
||||
let md = comment_markdown_to_html(&text);
|
||||
out.push_str(&format!(
|
||||
r#"<div class="doc-block" data-line="{line}"><div class="doc-prose">{md}</div></div>"#,
|
||||
r#"<div class="doc-block" data-line="{line}" id="stmt-{line}">{source_anchors}<div class="doc-prose">{md}</div></div>"#,
|
||||
line = first_line,
|
||||
md = md
|
||||
));
|
||||
@@ -157,6 +160,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
special.get(&l.line_no),
|
||||
writebacks.get(&l.line_no),
|
||||
None,
|
||||
&occluded_lines,
|
||||
));
|
||||
} else if !trimmed.is_empty() {
|
||||
para.push((l.line_no, trimmed.to_string()));
|
||||
@@ -190,6 +194,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
&writebacks,
|
||||
&taken_arms,
|
||||
annots,
|
||||
&occluded_lines,
|
||||
);
|
||||
out.push_str(&html);
|
||||
i = next;
|
||||
@@ -205,6 +210,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
||||
special.get(&l.line_no),
|
||||
writebacks.get(&l.line_no),
|
||||
None,
|
||||
&occluded_lines,
|
||||
));
|
||||
i += 1;
|
||||
}
|
||||
@@ -295,7 +301,7 @@ fn render_table_block(
|
||||
}
|
||||
let first_line = rows[0].0;
|
||||
let mut html = format!(
|
||||
r#"<div class="doc-block doc-table-wrap" data-line="{line}"><table class="doc-table">"#,
|
||||
r#"<div class="doc-block doc-table-wrap" data-line="{line}" id="stmt-{line}"><table class="doc-table">"#,
|
||||
line = first_line
|
||||
);
|
||||
let mut header_done = false;
|
||||
@@ -370,6 +376,7 @@ fn render_list_block(
|
||||
writebacks: &HashMap<u32, String>,
|
||||
taken_arms: &HashMap<u32, usize>,
|
||||
all_annots: &[ViewAnnot],
|
||||
occluded_lines: &HashSet<u32>,
|
||||
) -> (String, usize) {
|
||||
let base_indent = indent_level(&lines[start].text);
|
||||
let tag = match kind {
|
||||
@@ -407,8 +414,7 @@ fn render_list_block(
|
||||
let frames: Vec<&ViewAnnot> = all_annots
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
a.kind == crate::view::annot::AnnotKind::LoopFrame
|
||||
&& a.anchor_line == branch_line
|
||||
a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line
|
||||
})
|
||||
.collect();
|
||||
if frames.len() >= 2 {
|
||||
@@ -483,7 +489,7 @@ fn render_list_block(
|
||||
_ => "",
|
||||
};
|
||||
html.push_str(&format!(
|
||||
r#"<li class="doc-list-item {arm_cls}" data-line="{line}" data-arm-index="{arm_idx}" style="--doc-indent:{indent}">"#,
|
||||
r#"<li class="doc-list-item {arm_cls}" data-line="{line}" id="stmt-{line}" data-arm-index="{arm_idx}" style="--doc-indent:{indent}">"#,
|
||||
arm_cls = arm_cls,
|
||||
line = lines[i].line_no,
|
||||
arm_idx = arm_index,
|
||||
@@ -491,7 +497,12 @@ fn render_list_block(
|
||||
));
|
||||
html.push_str(&format!(
|
||||
r#"<div class="doc-list-head">{}</div>"#,
|
||||
render_surface_line(lines[i].line_no, head, by_line)
|
||||
render_surface_line(
|
||||
lines[i].line_no,
|
||||
head,
|
||||
by_line,
|
||||
occluded_lines.contains(&lines[i].line_no)
|
||||
)
|
||||
));
|
||||
// Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS).
|
||||
let mut head_annots: Vec<ViewAnnot> = Vec::new();
|
||||
@@ -515,9 +526,12 @@ fn render_list_block(
|
||||
}
|
||||
}
|
||||
}
|
||||
if !head_annots.is_empty() {
|
||||
html.push_str(&render_annot_band(&head_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
let notes = if occluded_lines.contains(&lines[i].line_no) {
|
||||
render_logic_notes(lines[i].line_no, head, &[])
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
html.push_str(&render_document_band(&head_annots, ¬es));
|
||||
// Body: following lines with greater indent until next sibling.
|
||||
i += 1;
|
||||
html.push_str(r#"<div class="doc-list-body">"#);
|
||||
@@ -525,9 +539,7 @@ fn render_list_block(
|
||||
let t2 = lines[i].text.trim_end_matches(['\r', '\n']);
|
||||
if t2.trim().is_empty() {
|
||||
// allow blank inside body
|
||||
if i + 1 < lines.len()
|
||||
&& indent_level(&lines[i + 1].text) > base_indent
|
||||
{
|
||||
if i + 1 < lines.len() && indent_level(&lines[i + 1].text) > base_indent {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -550,6 +562,7 @@ fn render_list_block(
|
||||
writebacks,
|
||||
taken_arms,
|
||||
all_annots,
|
||||
occluded_lines,
|
||||
);
|
||||
html.push_str(&inner);
|
||||
i = next;
|
||||
@@ -573,6 +586,7 @@ fn render_list_block(
|
||||
special.get(&lines[i].line_no),
|
||||
writebacks.get(&lines[i].line_no),
|
||||
Some(ind2),
|
||||
occluded_lines,
|
||||
));
|
||||
i += 1;
|
||||
}
|
||||
@@ -593,23 +607,25 @@ fn render_surface_line(
|
||||
line_no: u32,
|
||||
head: &str,
|
||||
by_line: &HashMap<u32, Vec<&ViewAnnot>>,
|
||||
occluded: bool,
|
||||
) -> String {
|
||||
if occluded && !occlusion_spans(head).is_empty() {
|
||||
return format!(
|
||||
r#"<mark class="mq-anchor mq-control" data-line="{line_no}" data-byte-start="0" data-byte-end="{}" title="循环或条件:实际控制逻辑见侧注">{}</mark>"#,
|
||||
head.len(),
|
||||
render_occlusion_text(line_no, head, 0)
|
||||
);
|
||||
}
|
||||
let bits = scan_prose_line(head);
|
||||
if bits.is_empty() {
|
||||
// Else arm "*" or plain condition text.
|
||||
if head.trim() == "*" {
|
||||
return r#"<span class="mq-else">else</span>"#.into();
|
||||
}
|
||||
format!(
|
||||
r#"<span class="doc-cond">{}</span>"#,
|
||||
escape(head)
|
||||
)
|
||||
format!(r#"<span class="doc-cond">{}</span>"#, escape(head))
|
||||
} else {
|
||||
let annots = by_line
|
||||
.get(&line_no)
|
||||
.map(|v| v.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
render_prose_with_marks(line_no, head, &bits, annots)
|
||||
let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]);
|
||||
render_prose_with_marks(line_no, head, &bits, annots, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,7 +651,7 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
r##"<div class="doc-fun" id="fn-{line}" data-fn="{name}" data-fn-path="{name}" data-line="{line}">
|
||||
<div class="doc-fun-bar">
|
||||
<h3 class="doc-fun-title">{name}</h3>
|
||||
<a class="knowledge-explain" href="#knowledge-{name}" data-node="{name}">说明</a>"##,
|
||||
<a class="knowledge-explain" href="#knowledge-fn-{line}" data-node="{name}">说明</a>"##,
|
||||
line = fun.span.line,
|
||||
name = escape(&fun.name),
|
||||
);
|
||||
@@ -645,7 +661,9 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
.filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name)
|
||||
.collect();
|
||||
if call_labels.len() >= 2 {
|
||||
s.push_str(r#"<label class="call-picker-label">调用 <select class="call-picker" data-fn=""#);
|
||||
s.push_str(
|
||||
r#"<label class="call-picker-label">调用 <select class="call-picker" data-fn=""#,
|
||||
);
|
||||
s.push_str(&escape(&fun.name));
|
||||
s.push_str(r#"">"#);
|
||||
for (i, a) in call_labels.iter().enumerate() {
|
||||
@@ -678,11 +696,7 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
.unwrap_or_default();
|
||||
s.push_str(r#"<div class="params">"#);
|
||||
for p in &fun.params {
|
||||
let cls = if p.inferred {
|
||||
"chip inferred"
|
||||
} else {
|
||||
"chip"
|
||||
};
|
||||
let cls = if p.inferred { "chip inferred" } else { "chip" };
|
||||
let title = if p.inferred {
|
||||
"inferred from prose / body"
|
||||
} else {
|
||||
@@ -725,155 +739,173 @@ fn parse_args_brief(brief: &str) -> HashMap<String, String> {
|
||||
m
|
||||
}
|
||||
|
||||
/// Split a statement line holding one occlusion `[描述](实现)`.
|
||||
///
|
||||
/// Returns `(prefix, label, payload, suffix)`. Display-only: the parser already
|
||||
/// validated the real structure, this just decides how to paint it.
|
||||
fn split_occlusion(line: &str) -> Option<(String, String, String, String)> {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let mut i = 0usize;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
/// Display-only source spans. The AST decides whether this line contains an occlusion.
|
||||
/// Scan only executable fragments, preserving quoted links as literal data.
|
||||
struct OcclusionSpan<'a> { start: usize, end: usize, label: &'a str, payload: &'a str }
|
||||
fn occlusion_spans(text: &str) -> Vec<OcclusionSpan<'_>> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if matches!(bytes[i], b'"' | b'\'' | b'`') {
|
||||
let quote = bytes[i];
|
||||
i += 1;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'\\' {
|
||||
i += 2;
|
||||
} else if bytes[i] == quote {
|
||||
i += 1;
|
||||
break;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => in_bt = true,
|
||||
'"' => in_str = true,
|
||||
'[' if chars.get(i + 1) != Some(&'^') => {
|
||||
if let Some(close) = match_delim(&chars, i, '[', ']') {
|
||||
if chars.get(close + 1) == Some(&'(') {
|
||||
if let Some(paren) = match_delim(&chars, close + 1, '(', ')') {
|
||||
let mut prefix: String = chars[..i].iter().collect();
|
||||
let label: String = chars[i + 1..close].iter().collect();
|
||||
let payload: String = chars[close + 2..paren].iter().collect();
|
||||
let suffix: String = chars[paren + 1..].iter().collect();
|
||||
// `**名 = [..](..)**` reads as bold code: drop the
|
||||
// emphasis markers so the label reads as prose.
|
||||
if let Some(p) = prefix.strip_suffix("**") {
|
||||
prefix = p.to_string();
|
||||
}
|
||||
prefix = prefix.trim_end().to_string();
|
||||
if let Some(p) = prefix.strip_prefix("**") {
|
||||
prefix = p.to_string();
|
||||
}
|
||||
let suffix = suffix.strip_prefix("**").unwrap_or(&suffix).to_string();
|
||||
return Some((
|
||||
prefix,
|
||||
label.trim().to_string(),
|
||||
payload.trim().to_string(),
|
||||
suffix.trim().to_string(),
|
||||
));
|
||||
}
|
||||
let start = i;
|
||||
let mut j = i + 1;
|
||||
let mut depth = 1;
|
||||
while j < bytes.len() {
|
||||
match bytes[j] {
|
||||
b'\\' => {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
b'[' => depth += 1,
|
||||
b']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
j += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn match_delim(chars: &[char], start: usize, open: char, close: char) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
let mut i = start;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
if depth != 0 || bytes.get(j + 1) != Some(&b'(') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => in_bt = true,
|
||||
'"' => in_str = true,
|
||||
c if c == open => depth += 1,
|
||||
c if c == close => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
let label_end = j;
|
||||
j += 2;
|
||||
let payload_start = j;
|
||||
depth = 1;
|
||||
while j < bytes.len() {
|
||||
match bytes[j] {
|
||||
b'"' | b'\'' | b'`' => {
|
||||
let quote = bytes[j];
|
||||
j += 1;
|
||||
while j < bytes.len() {
|
||||
if bytes[j] == b'\\' {
|
||||
j += 2;
|
||||
} else if bytes[j] == quote {
|
||||
j += 1;
|
||||
break;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'(' => depth += 1,
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
j += 1;
|
||||
}
|
||||
if depth == 0 {
|
||||
out.push(OcclusionSpan {
|
||||
start,
|
||||
end: j + 1,
|
||||
label: &text[start + 1..label_end],
|
||||
payload: text[payload_start..j].trim(),
|
||||
});
|
||||
i = j + 1;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
out
|
||||
}
|
||||
|
||||
/// Render one occlusion line: description as prose, payload as a code chip,
|
||||
/// stubs get a badge. `<TAB>` M8
|
||||
fn render_occlusion_line(line_no: u32, line: &str) -> Option<String> {
|
||||
let (prefix, label, payload, suffix) = split_occlusion(line)?;
|
||||
let stub = payload.is_empty();
|
||||
// The rest of the view drops backticks (see the `mq-anchor` marks), so the
|
||||
// assignment head reads as `留存 =` rather than `` `留存` = ``.
|
||||
let head = prefix
|
||||
.trim_end()
|
||||
.trim_end_matches('=')
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_string();
|
||||
let mut html = format!(r#"<div class="doc-line doc-occl" data-line="{line_no}">"#);
|
||||
if !head.is_empty() {
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-pre">{} =</span>"#,
|
||||
escape(&head)
|
||||
));
|
||||
fn logic_id(line: u32, at: usize) -> String {
|
||||
format!("logic-{line}-{at}")
|
||||
}
|
||||
fn render_occlusion_text(line: u32, text: &str, base: usize) -> String {
|
||||
let mut html = String::new();
|
||||
let mut cursor = 0;
|
||||
for span in occlusion_spans(text) {
|
||||
html.push_str(&escape(&text[cursor..span.start]));
|
||||
let id = logic_id(line, base + span.start);
|
||||
let label = if span.label.is_empty() {
|
||||
"未命名动作"
|
||||
} else {
|
||||
span.label
|
||||
};
|
||||
html.push_str(&format!(r#"<button type="button" class="occl-label" id="{id}-source" data-logic-id="{id}" aria-controls="{id}-note" title="查看实际逻辑(阅读不会执行)">{}</button>"#,escape(label)));
|
||||
if span.payload.is_empty() {
|
||||
html.push_str(r#"<span class="occl-stub">待补充实际逻辑</span>"#);
|
||||
}
|
||||
cursor = span.end;
|
||||
}
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-label">{}</span>"#,
|
||||
escape(&label)
|
||||
));
|
||||
if stub {
|
||||
html.push_str(r#"<span class="occl-stub" title="空载荷:未接通或待补返回值">桩</span>"#);
|
||||
} else {
|
||||
html.push_str(&format!(
|
||||
r#"<code class="occl-code">{}</code>"#,
|
||||
escape(&payload)
|
||||
));
|
||||
html.push_str(&escape(&text[cursor..]));
|
||||
html
|
||||
}
|
||||
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit]) -> String {
|
||||
let mut notes = String::new();
|
||||
let fragments: Vec<(usize, usize, &str)> =
|
||||
if bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
|
||||
vec![(0, text.len(), text)]
|
||||
} else {
|
||||
bits.iter()
|
||||
.filter_map(|bit| match bit {
|
||||
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } => {
|
||||
Some((bit_at(bit), prose_bit_end(text, bit), inner.as_str()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for (start, end, fragment) in fragments {
|
||||
for span in occlusion_spans(fragment) {
|
||||
let id = logic_id(line, start + span.start);
|
||||
let payload = if span.payload.is_empty() {
|
||||
"待补充实际逻辑;当前空遮蔽返回 None。"
|
||||
} else {
|
||||
span.payload
|
||||
};
|
||||
notes.push_str(&format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label">实际逻辑 · {label}</summary><code class="annot-value occl-code">{payload}</code><small class="logic-hint">源码说明 · 不是运行结果</small></details>"#,label=escape(span.label),payload=escape(payload)));
|
||||
}
|
||||
}
|
||||
if !suffix.is_empty() {
|
||||
html.push_str(&format!(
|
||||
r#"<span class="occl-pre">{}</span>"#,
|
||||
escape(&suffix)
|
||||
));
|
||||
notes
|
||||
}
|
||||
fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String {
|
||||
let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS);
|
||||
if notes.is_empty() {
|
||||
return band;
|
||||
}
|
||||
html.push_str("</div>");
|
||||
Some(html)
|
||||
if band.is_empty() {
|
||||
return format!(
|
||||
r#"<div class="annot-band" data-annot-band><div class="annot-chips">{notes}</div></div>"#
|
||||
);
|
||||
}
|
||||
band.replacen(
|
||||
r#"<div class="annot-chips">"#,
|
||||
&format!(r#"<div class="annot-chips">{notes}"#),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
fn render_line_block(
|
||||
@@ -884,6 +916,7 @@ fn render_line_block(
|
||||
special: Option<&SpecialAssign>,
|
||||
writeback_body: Option<&String>,
|
||||
indent: Option<usize>,
|
||||
occluded_lines: &HashSet<u32>,
|
||||
) -> String {
|
||||
let indent_style = indent
|
||||
.map(|n| format!(r#" style="--doc-indent:{n}""#))
|
||||
@@ -900,37 +933,19 @@ fn render_line_block(
|
||||
s.push_str(&render_formula_assign_card(name, tex));
|
||||
}
|
||||
Some(SpecialAssign::Code {
|
||||
name,
|
||||
lang,
|
||||
source,
|
||||
..
|
||||
name, lang, source, ..
|
||||
}) => {
|
||||
s.push_str(&render_code_assign_card(name, lang, source));
|
||||
}
|
||||
None => {
|
||||
let trimmed = text.trim_start();
|
||||
// `<TAB>` M8: an occlusion line is painted as description + code chip
|
||||
// regardless of annotation bits (the annotator always emits spans).
|
||||
if let Some(html) = render_occlusion_line(line_no, trimmed) {
|
||||
s.push_str(&html);
|
||||
if let Some(body) = writeback_body {
|
||||
s.push_str(&crate::view::render::render_output_card(line_no, body));
|
||||
}
|
||||
// Must close `.doc-block` — an early return left the wrapper open and
|
||||
// nested the Functions/Variables outline under the document surface.
|
||||
let band_annots: Vec<ViewAnnot> = annots
|
||||
.iter()
|
||||
.filter(|a| !is_noisy_result_chip(a))
|
||||
.map(|a| (*a).clone())
|
||||
.collect();
|
||||
if !band_annots.is_empty() {
|
||||
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
return s;
|
||||
}
|
||||
if bits.is_empty() {
|
||||
if let Some(rest) = trimmed.strip_prefix("> ") {
|
||||
if bits.is_empty()
|
||||
|| (occluded_lines.contains(&line_no)
|
||||
&& bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })))
|
||||
{
|
||||
if occluded_lines.contains(&line_no) && !occlusion_spans(text).is_empty() {
|
||||
s.push_str(&format!(r#"<div class="doc-line doc-occl"><mark class="mq-anchor mq-code" data-line="{line_no}" data-byte-start="0" data-byte-end="{}">{}</mark></div>"#,text.len(),render_occlusion_text(line_no,text,0)));
|
||||
} else if let Some(rest) = trimmed.strip_prefix("> ") {
|
||||
let aid = match_annot_for_line(annots)
|
||||
.map(|a| a.id.as_str())
|
||||
.unwrap_or("");
|
||||
@@ -958,7 +973,13 @@ fn render_line_block(
|
||||
}
|
||||
} else {
|
||||
s.push_str(r#"<div class="doc-line doc-prose-line">"#);
|
||||
s.push_str(&render_prose_with_marks(line_no, text, bits, annots));
|
||||
s.push_str(&render_prose_with_marks(
|
||||
line_no,
|
||||
text,
|
||||
bits,
|
||||
annots,
|
||||
occluded_lines.contains(&line_no),
|
||||
));
|
||||
s.push_str("</div>");
|
||||
}
|
||||
}
|
||||
@@ -979,9 +1000,12 @@ fn render_line_block(
|
||||
.map(|a| (*a).clone())
|
||||
.collect()
|
||||
};
|
||||
if !band_annots.is_empty() {
|
||||
s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS));
|
||||
}
|
||||
let notes = if special.is_none() && occluded_lines.contains(&line_no) {
|
||||
render_logic_notes(line_no, text, bits)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
s.push_str(&render_document_band(&band_annots, ¬es));
|
||||
|
||||
s.push_str("</div>");
|
||||
s
|
||||
@@ -1040,12 +1064,37 @@ fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, us
|
||||
(html, j)
|
||||
}
|
||||
|
||||
/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML
|
||||
/// stays literal here, as it did in mixed executable prose before this renderer.
|
||||
fn render_narrative_inline(text: &str) -> String {
|
||||
let inner = text.trim();
|
||||
if inner.is_empty() {
|
||||
return escape(text);
|
||||
}
|
||||
let start = text.find(inner).unwrap();
|
||||
let end = start + inner.len();
|
||||
let parser = pulldown_cmark::Parser::new(inner).map(|event| match event {
|
||||
pulldown_cmark::Event::Html(html) => pulldown_cmark::Event::Text(html),
|
||||
other => other,
|
||||
});
|
||||
let mut html = String::new();
|
||||
pulldown_cmark::html::push_html(&mut html, parser);
|
||||
let Some(body) = html
|
||||
.strip_prefix("<p>")
|
||||
.and_then(|s| s.strip_suffix("</p>\n"))
|
||||
else {
|
||||
return escape(text);
|
||||
};
|
||||
format!("{}{}{}", escape(&text[..start]), body, escape(&text[end..]))
|
||||
}
|
||||
|
||||
/// Render prose with markers stripped; show surface inner text only.
|
||||
fn render_prose_with_marks(
|
||||
line_no: u32,
|
||||
text: &str,
|
||||
bits: &[ProseBit],
|
||||
annots: &[&ViewAnnot],
|
||||
occluded: bool,
|
||||
) -> String {
|
||||
let mut html = String::new();
|
||||
let mut cursor = 0usize;
|
||||
@@ -1053,7 +1102,7 @@ fn render_prose_with_marks(
|
||||
let start = bit_at(bit);
|
||||
let end = prose_bit_end(text, bit);
|
||||
if start > cursor {
|
||||
html.push_str(&escape(&text[cursor..start]));
|
||||
html.push_str(&render_narrative_inline(&text[cursor..start]));
|
||||
}
|
||||
if start < end && end <= text.len() {
|
||||
let (cls, display) = bit_display(bit);
|
||||
@@ -1061,19 +1110,20 @@ fn render_prose_with_marks(
|
||||
.map(|a| a.id.as_str())
|
||||
.unwrap_or("");
|
||||
html.push_str(&format!(
|
||||
r#"<mark class="mq-anchor mq-{cls}" data-line="{line}" data-byte-start="{start}" data-byte-end="{end}" data-annot-id="{aid}">{inner}</mark>"#,
|
||||
r#"<mark class="mq-anchor mq-{cls}" data-line="{line}" data-byte-start="{start}" data-byte-end="{end}" data-annot-id="{aid}" data-syntax="{cls}" title="{hint}" tabindex="0">{inner}</mark>"#,
|
||||
cls = cls,
|
||||
hint = match bit {ProseBit::Decl{..}=>"参数或变量声明",ProseBit::BoldCode{..}=>"语句:计算、赋值或调用",ProseBit::ItalicReturn{..}=>"返回:把结果交给调用方"},
|
||||
line = line_no,
|
||||
start = start,
|
||||
end = end,
|
||||
aid = escape(annot_id),
|
||||
inner = escape(&display),
|
||||
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,start)}else{escape(&display)},
|
||||
));
|
||||
}
|
||||
cursor = end.max(cursor);
|
||||
}
|
||||
if cursor < text.len() {
|
||||
html.push_str(&escape(&text[cursor..]));
|
||||
html.push_str(&render_narrative_inline(&text[cursor..]));
|
||||
}
|
||||
html
|
||||
}
|
||||
@@ -1164,6 +1214,46 @@ fn index_stmt_lines(module: &Module) -> HashSet<u32> {
|
||||
}
|
||||
|
||||
|
||||
fn index_occluded_lines(module: &Module) -> HashSet<u32> {
|
||||
use crate::ast::{Arg, Expr};
|
||||
fn expr(e: &Expr) -> bool {
|
||||
match e {
|
||||
Expr::Occluded { .. } => true,
|
||||
Expr::Unary { expr: e, .. } => expr(e),
|
||||
Expr::Binary { left, right, .. } => expr(left) || expr(right),
|
||||
Expr::Call(c) => c.args.iter().any(|a| match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e),
|
||||
}),
|
||||
Expr::List(xs) => xs.iter().any(expr),
|
||||
Expr::Map(xs) => xs.iter().any(|(_, e)| expr(e)),
|
||||
Expr::Index { base, .. } => expr(base),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let mut lines = HashSet::new();
|
||||
for f in &module.functions {
|
||||
crate::ast::walk_stmts(f, &mut |s| {
|
||||
let has = match s {
|
||||
Stmt::Assign { value, .. }
|
||||
| Stmt::Return { value, .. }
|
||||
| Stmt::Expr { value, .. } => expr(value),
|
||||
Stmt::Call { call, .. } => call.args.iter().any(|a| match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e),
|
||||
}),
|
||||
Stmt::ForEach { .. } => true,
|
||||
Stmt::While { condition, .. } => expr(condition),
|
||||
Stmt::Branch { arms, .. } => {
|
||||
arms.iter().any(|a| a.condition.as_ref().is_some_and(expr))
|
||||
}
|
||||
};
|
||||
if has {
|
||||
lines.insert(crate::ast::stmt_line(s));
|
||||
}
|
||||
});
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialAssign> {
|
||||
let src_lines: Vec<&str> = source.lines().collect();
|
||||
let mut m = HashMap::new();
|
||||
@@ -1602,47 +1692,101 @@ markup: occlusion
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Explain the existing core surface, including compatibility constructs, without executing it.
|
||||
fn render_syntax_guide() -> String {
|
||||
let mut html = String::from(
|
||||
r#"<details class="reader-syntax-guide" id="reader-syntax-guide"><summary>怎样读这份可执行文档</summary><p>正文说明意图,标记指出哪些片段会执行。遮蔽只在正文显示动作说明,实际逻辑放在侧注;阅读、展开与定位都不会运行代码。</p><div class="knowledge-table-wrap"><table><thead><tr><th>标记</th><th>阅读含义</th></tr></thead><tbody>"#,
|
||||
);
|
||||
for (id, surface) in crate::parse::CORE_CONSTRUCTS {
|
||||
let meaning=match *id {
|
||||
"narrative"=>"作者的解释,按普通 Markdown 阅读。", "blank"=>"分隔叙述与结构,不是计算步骤。",
|
||||
"heading-unit"=>"一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。",
|
||||
"call-line"=>"调用函数;实际执行结果另有标注。", "branch-list"=>"按条件选择分支,不是普通编号说明。",
|
||||
"loop-list"=>"重复或遍历结构;迭代选择器只切换已有运行记录。", "param"=>"兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。",
|
||||
"table"=>"未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。", "fence"=>"代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。",
|
||||
"hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。",
|
||||
"ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。",
|
||||
"italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。",
|
||||
"link-index"=>"默认模式是 [动作](实现) 遮蔽,正文只显示动作;空括号表示待补充实际逻辑。classic 模式才解释为旧链接取元。",
|
||||
"bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。",
|
||||
"soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。"
|
||||
};
|
||||
html.push_str(&format!(
|
||||
r#"<tr data-construct-id="{}"><td><code>{}</code></td><td>{}</td></tr>"#,
|
||||
escape(id),
|
||||
escape(surface),
|
||||
escape(meaning)
|
||||
));
|
||||
}
|
||||
html.push_str("</tbody></table></div></details>");
|
||||
html
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod occl_split_tests {
|
||||
use super::split_occlusion;
|
||||
|
||||
#[test]
|
||||
fn splits_bare_assignment_occlusion() {
|
||||
let (head, label, payload, rest) =
|
||||
split_occlusion("`留存` = [客户留存率,模拟数据](0.42)").unwrap();
|
||||
assert_eq!(head, "`留存` =");
|
||||
assert_eq!(label, "客户留存率,模拟数据");
|
||||
assert_eq!(payload, "0.42");
|
||||
assert_eq!(rest, "");
|
||||
mod readable_occlusion_tests {
|
||||
use super::*;
|
||||
fn render(source: &str) -> String {
|
||||
let module = crate::load::parse_source_auto(source).unwrap();
|
||||
render_module_document(&module, source, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_bold_assignment_occlusion_without_markers() {
|
||||
let (head, label, payload, _) =
|
||||
split_occlusion("**留存 = [客户留存率,模拟数据](0.42)**").unwrap();
|
||||
assert_eq!(head, "留存 =");
|
||||
assert_eq!(label, "客户留存率,模拟数据");
|
||||
assert_eq!(payload, "0.42");
|
||||
fn prose_keeps_multiple_actions_and_returns_without_exposing_payloads() {
|
||||
let html=render("# main\n\n先**a = [读取甲](1 + 2)**,接着**b = [读取乙](3 + 4)**,最后返回*[合计](a + b)*。\n");
|
||||
let line = html
|
||||
.split("doc-line doc-prose-line\"")
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.split("</div>")
|
||||
.next()
|
||||
.unwrap();
|
||||
for text in ["先", "读取甲", "接着", "读取乙", "最后返回", "合计"] {
|
||||
assert!(line.contains(text), "{line}");
|
||||
}
|
||||
for code in ["1 + 2", "3 + 4", "a + b", "[读取甲]"] {
|
||||
assert!(!line.contains(code), "payload leaked into prose: {line}");
|
||||
}
|
||||
assert_eq!(
|
||||
html.matches("class=\"annot-chip annot-implementation\"")
|
||||
.count(),
|
||||
3
|
||||
);
|
||||
assert!(html.contains("data-syntax=\"return\""));
|
||||
assert!(html.contains(">1 + 2</code>") && html.contains(">a + b</code>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_stub_and_nested_payload() {
|
||||
let (_, label, payload, _) =
|
||||
split_occlusion("`待接` = [搜索接入,待开发]()").unwrap();
|
||||
assert_eq!(label, "搜索接入,待开发");
|
||||
assert!(payload.is_empty());
|
||||
|
||||
let (_, label, payload, _) =
|
||||
split_occlusion("`取第一` = [第一颗](access(`篮子`, \"1\"))").unwrap();
|
||||
assert_eq!(label, "第一颗");
|
||||
assert_eq!(payload, "access(`篮子`, \"1\")");
|
||||
fn empty_logic_quotes_nested_parentheses_and_html_are_safe() {
|
||||
let html =
|
||||
render("# main\n\n得到**a = [括号](str(value=\") <tag>\"))**,再**b = [待接]()**。\n");
|
||||
assert!(html.contains("待补充实际逻辑"));
|
||||
assert!(html.contains("<tag>") && !html.contains("<tag>"));
|
||||
assert!(html.contains("str(value=") <tag>")"));
|
||||
assert!(html.contains("当前空遮蔽返回 None"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_index_and_plain_lines() {
|
||||
// Link-index (classic) and ordinary statements are not occlusions.
|
||||
assert!(split_occlusion("**v = [键](`表`)**").is_some()); // shape matches; parser decides meaning
|
||||
assert!(split_occlusion("**甲 = 加(1 2)**").is_none());
|
||||
assert!(split_occlusion("> print text=x").is_none());
|
||||
fn navigation_and_quoted_links_are_not_executable_occlusions() {
|
||||
let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n");
|
||||
assert!(html.contains("href=\"https://example.com/guide\""));
|
||||
assert!(html.contains("href=\"https://example.com/mixed\""));
|
||||
assert_eq!(
|
||||
html.matches("class=\"annot-chip annot-implementation\"")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(html.contains("[数据链接](should_stay_text)"));
|
||||
let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n");
|
||||
assert!(!classic.contains("class=\"annot-chip annot-implementation\""));
|
||||
}
|
||||
#[test]
|
||||
fn semantic_loop_labels_and_every_core_construct_are_explained() {
|
||||
let html=render("# main\n\n`items` =\n\n| n |\n|---|\n| 1 |\n| 2 |\n\n- [逐项处理](遍历 items 为 item)\n **out = item + 1**\n");
|
||||
assert!(html.contains("逐项处理</button>"));
|
||||
assert!(html.contains("遍历 items 为 item</code>"));
|
||||
for (id, _) in crate::parse::CORE_CONSTRUCTS {
|
||||
assert!(
|
||||
html.contains(&format!("data-construct-id=\"{id}\"")),
|
||||
"missing {id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2504,7 +2504,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
var root = scope || document.getElementById("structure") || document;
|
||||
root.querySelectorAll("[data-annot-band]").forEach(function (band) {{
|
||||
band.classList.remove("is-expanded");
|
||||
var chips = band.querySelectorAll(".annot-chip");
|
||||
var chips = band.querySelectorAll(".annot-chip:not(.annot-implementation)");
|
||||
var visible = [];
|
||||
chips.forEach(function (chip) {{
|
||||
chip.classList.remove("annot-chip-overflow");
|
||||
@@ -4210,7 +4210,7 @@ window.MARQDO_VIEW_PAGE_TOKEN = {page_token_js};
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
"<details class=\"block knowledge-block\"><summary>可执行知识(辅助)</summary>{}</details>",
|
||||
"<details class=\"block knowledge-block\" id=\"knowledge-section\"><summary>可执行知识 · 输入、返回与依据</summary>{}</details>",
|
||||
vm.knowledge_html
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Reader-facing projection of compiler facts; no evaluation or invented evidence.
|
||||
use crate::ast::{Function, Module};
|
||||
use crate::sema::{SemanticArtifact, SemanticProject};
|
||||
use crate::view::{html::escape, render::expr_display};
|
||||
|
||||
fn find_function(functions: &[Function], line: u32) -> Option<&Function> {
|
||||
functions.iter().find_map(|f| {
|
||||
if f.span.line == line {
|
||||
Some(f)
|
||||
} else {
|
||||
find_function(&f.children, line)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn state(value: &str) -> String {
|
||||
match value {
|
||||
"passed" => "检查通过".into(),
|
||||
"failed" => "检查失败".into(),
|
||||
"unchecked" => "尚未检查".into(),
|
||||
"not_run" => "分析未运行程序".into(),
|
||||
"unknown" => "没有可用记录".into(),
|
||||
"sourced" => "已关联来源,内容尚未核验".into(),
|
||||
"verified" => "证据已核验".into(),
|
||||
"unverified" => "尚无已核验证据".into(),
|
||||
"unreviewed" => "尚未进行领域审阅".into(),
|
||||
other => format!("原始状态:{other}"),
|
||||
}
|
||||
}
|
||||
fn effect(value: &str) -> &str {
|
||||
match value {
|
||||
"pure" => "无已知宿主副作用",
|
||||
"fs.read" => "读取文件",
|
||||
"fs.write" => "写入文件",
|
||||
"net.http" | "network" => "网络请求",
|
||||
"process.exec" => "启动进程",
|
||||
"plugin" => "加载原生插件",
|
||||
"environment.read" => "读取环境配置",
|
||||
"output.write" => "输出文本",
|
||||
"input.read" => "读取输入",
|
||||
"unknown" => "调用效应尚不能确定",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn kind(value: &str) -> &str {
|
||||
match value {
|
||||
"type" => "对象",
|
||||
"function" => "函数",
|
||||
"constant" => "常量",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn step_kind(value: &str) -> &str {
|
||||
match value {
|
||||
"derive" => "计算",
|
||||
"observe" => "观察",
|
||||
"iterate" => "遍历",
|
||||
"call" => "调用",
|
||||
"return" => "返回",
|
||||
"branch" => "条件",
|
||||
"narrate" | "reference" => "正文引用",
|
||||
_ => value,
|
||||
}
|
||||
}
|
||||
fn render_steps(
|
||||
project: &SemanticProject,
|
||||
steps: &[&crate::sema::ir::KnowledgeStep],
|
||||
title: &str,
|
||||
) -> String {
|
||||
if steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out=format!("<details class=\"knowledge-steps\"><summary>{}</summary><p class=\"knowledge-hint\">这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。</p><ol class=\"knowledge-step-list\">",escape(title));
|
||||
for step in steps {
|
||||
let label = project
|
||||
.refs
|
||||
.iter()
|
||||
.find(|r| r.id == step.reference)
|
||||
.map(|r| r.label.as_str())
|
||||
.unwrap_or("未命名步骤");
|
||||
out.push_str(&format!(r##"<li class="knowledge-step" data-step-kind="{kind}" data-line="{line}"><span class="knowledge-step-kind">{meaning}</span><a href="#stmt-{line}">{label}</a></li>"##,kind=escape(&step.kind),line=step.source.line,meaning=escape(step_kind(&step.kind)),label=escape(label)));
|
||||
}
|
||||
out.push_str("</ol></details>");
|
||||
out
|
||||
}
|
||||
fn technical(artifact: &SemanticArtifact) -> String {
|
||||
let v = &artifact.verification;
|
||||
format!(
|
||||
r##"<details class="knowledge-technical"><summary>技术详情:身份、摘要与原始状态</summary><dl><dt>目标标识</dt><dd><code>{target}</code></dd><dt>制品摘要(未检查锁定状态)</dt><dd><code>{digest}</code></dd><dt>依赖标识</dt><dd><code>{deps}</code></dd><dt>原始验证状态</dt><dd><code>parse: {parse}; resolve: {resolve}; contract: {contract}; execution: {execution}; tests: {tests}; evidence: {evidence}; domain: {domain}</code></dd></dl></details>"##,
|
||||
target = escape(
|
||||
artifact
|
||||
.symbol_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str())
|
||||
.unwrap_or(&artifact.artifact_id.0)
|
||||
),
|
||||
digest = escape(&artifact.hashes.artifact.0),
|
||||
deps = escape(
|
||||
&artifact
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|id| id.0.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
),
|
||||
parse = escape(&v.parse),
|
||||
resolve = escape(&v.resolve),
|
||||
contract = escape(&v.contract),
|
||||
execution = escape(&v.execution),
|
||||
tests = escape(&v.tests),
|
||||
evidence = escape(&v.evidence),
|
||||
domain = escape(&v.domain)
|
||||
)
|
||||
}
|
||||
/// Facts are grouped by exact source unit, with machine identities behind disclosure.
|
||||
pub(super) fn render(project: &SemanticProject, rel: &str, module: Option<&Module>) -> String {
|
||||
let mut artifacts: Vec<_> = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.source.file == rel && a.kind != "module")
|
||||
.collect();
|
||||
artifacts.sort_by_key(|a| a.source.line);
|
||||
let steps: Vec<_> = project
|
||||
.steps
|
||||
.iter()
|
||||
.filter(|s| s.source.file == rel)
|
||||
.collect();
|
||||
if artifacts.is_empty() && steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = format!(
|
||||
r##"<div class="knowledge-panel" aria-label="可执行知识"><div class="knowledge-intro"><h3>这份文档怎样成为可调用的知识</h3><p>{} 个知识单元 · {} 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。</p><p class="knowledge-hint">以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。</p></div>"##,
|
||||
artifacts.len(),
|
||||
steps.len()
|
||||
);
|
||||
let first = artifacts.first().map(|a| a.source.line).unwrap_or(u32::MAX);
|
||||
let introductory: Vec<_> = steps
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|s| s.source.line < first)
|
||||
.collect();
|
||||
out.push_str(&render_steps(project, &introductory, "正文中的引用与步骤"));
|
||||
for (index, a) in artifacts.iter().enumerate() {
|
||||
let line = a.source.line;
|
||||
let function = module.and_then(|m| find_function(&m.functions, line));
|
||||
let end = artifacts
|
||||
.get(index + 1)
|
||||
.map(|a| a.source.line)
|
||||
.unwrap_or(u32::MAX);
|
||||
out.push_str(&format!(r##"<details class="knowledge-card" id="knowledge-fn-{line}" data-source-line="{line}"><summary><span class="knowledge-unit-name">{name}</span><span class="knowledge-unit-kind">{kind}</span></summary><div class="knowledge-unit-body"><a class="knowledge-source-link" href="#fn-{line}">回到正文 · 第 {line} 行</a>"##,name=escape(&a.display_name),kind=escape(if function.is_some_and(|f|f.name=="main"&&f.level==1){"程序入口"}else{kind(&a.kind)})));
|
||||
if let Some(signature) = &a.signature {
|
||||
if signature.receiver == "instance" {
|
||||
out.push_str("<p class=\"knowledge-hint\">实例方法:先创建所属对象,再通过同一实例调用。</p>");
|
||||
}
|
||||
out.push_str("<h4>需要什么输入</h4>");
|
||||
if signature.params.is_empty() {
|
||||
out.push_str("<p>无需提供输入参数。</p>");
|
||||
} else {
|
||||
out.push_str("<div class=\"knowledge-table-wrap\"><table><thead><tr><th>参数</th><th>类型</th><th>提供方式</th><th>含义</th></tr></thead><tbody>");
|
||||
for param in &signature.params {
|
||||
let authored = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.params.iter().find(|p| p.name == param.name));
|
||||
let default = function
|
||||
.and_then(|f| f.params.iter().find(|p| p.name == param.name))
|
||||
.and_then(|p| p.default.as_ref())
|
||||
.map(expr_display);
|
||||
let supply = if param.required {
|
||||
"必填".into()
|
||||
} else {
|
||||
default
|
||||
.map(|v| format!("默认 {v}"))
|
||||
.unwrap_or("可省略;默认值见源码".into())
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"<tr><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
|
||||
escape(¶m.name),
|
||||
escape(¶m.ty),
|
||||
escape(&supply),
|
||||
escape(
|
||||
authored
|
||||
.map(|p| p.desc.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("源码未提供参数说明")
|
||||
)
|
||||
));
|
||||
}
|
||||
out.push_str("</tbody></table></div>");
|
||||
}
|
||||
let returns = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.returns.as_ref());
|
||||
out.push_str(&format!(
|
||||
"<h4>返回什么</h4><p><code>{}</code> · {}</p>",
|
||||
escape(&signature.returns),
|
||||
escape(
|
||||
returns
|
||||
.map(|r| r.desc.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("源码未提供返回值说明;请结合正文实现阅读。")
|
||||
)
|
||||
));
|
||||
} else {
|
||||
out.push_str("<p>这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。</p>");
|
||||
if let Some(returns) = function
|
||||
.and_then(|f| f.contract.as_ref())
|
||||
.and_then(|c| c.returns.as_ref())
|
||||
{
|
||||
out.push_str(&format!(
|
||||
"<h4>源码中的返回契约</h4><p><code>{}</code> · {}</p>",
|
||||
escape(&returns.ty.name()),
|
||||
escape(&returns.desc)
|
||||
));
|
||||
}
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"<h4>调用边界</h4><p>{}。权限由实际运行入口授予;静态副作用信息不等于运行许可。</p>",
|
||||
escape(
|
||||
&a.effects
|
||||
.values()
|
||||
.iter()
|
||||
.map(|s| effect(s))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、")
|
||||
)
|
||||
));
|
||||
if !a.dependencies.is_empty() {
|
||||
out.push_str("<h4>依赖哪些知识</h4><ul class=\"knowledge-dependencies\">");
|
||||
for dependency in &a.dependencies {
|
||||
if let Some(target) = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|other| other.artifact_id == *dependency)
|
||||
{
|
||||
if target.source.file == rel && target.kind != "module" {
|
||||
out.push_str(&format!(
|
||||
r##"<li><a href="#knowledge-fn-{}" data-knowledge-link>{}</a></li>"##,
|
||||
target.source.line,
|
||||
escape(&target.display_name)
|
||||
));
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
"<li>{} <span class=\"knowledge-hint\">{}</span></li>",
|
||||
escape(&target.display_name),
|
||||
escape(&target.source.file)
|
||||
));
|
||||
}
|
||||
} else {
|
||||
out.push_str("<li>依赖尚未解析;完整标识见技术详情。</li>");
|
||||
}
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
}
|
||||
let v = &a.verification;
|
||||
out.push_str(&format!("<h4>当前有哪些依据</h4><dl class=\"knowledge-status\"><dt>语法与引用</dt><dd>{};{}</dd><dt>契约检查</dt><dd>{}</dd><dt>测试记录</dt><dd>{}</dd><dt>内容来源</dt><dd>{}</dd><dt>领域审阅</dt><dd>{}</dd></dl>",escape(&state(&v.parse)),escape(&state(&v.resolve)),escape(&state(&v.contract)),escape(&state(&v.tests)),escape(&state(&v.evidence)),escape(&state(&v.domain))));
|
||||
let owned: Vec<_> = steps
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|s| s.source.line >= line && s.source.line < end)
|
||||
.collect();
|
||||
out.push_str(&render_steps(project, &owned, "查看本单元的结构步骤"));
|
||||
out.push_str(&technical(a));
|
||||
out.push_str("</div></details>");
|
||||
}
|
||||
out.push_str("</div>");
|
||||
out
|
||||
}
|
||||
+102
-90
@@ -7,6 +7,7 @@ mod debug_page;
|
||||
mod document;
|
||||
mod html;
|
||||
mod knowledge_present;
|
||||
mod knowledge_reading;
|
||||
mod notebook_api;
|
||||
mod output;
|
||||
mod render;
|
||||
@@ -410,30 +411,28 @@ pub(crate) fn build_file_view_with_exec(
|
||||
) -> Result<FileViewModel> {
|
||||
let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
|
||||
// Structure shows this file only — do not merge imported lib bodies into the tree.
|
||||
let (mut structure, mut module_opt, input_prompts) = match crate::load::parse_source_auto(&source) {
|
||||
Ok(module) => {
|
||||
let prompts = collect_input_prompts(&module);
|
||||
(
|
||||
render_module_structure(&module, &source),
|
||||
Some(module),
|
||||
prompts,
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
format!(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
|
||||
let (mut structure, mut module_opt, input_prompts) =
|
||||
match crate::load::parse_source_auto(&source) {
|
||||
Ok(module) => {
|
||||
let prompts = collect_input_prompts(&module);
|
||||
(
|
||||
render_module_structure(&module, &source),
|
||||
Some(module),
|
||||
prompts,
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
format!(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
|
||||
),
|
||||
None,
|
||||
Vec::new(),
|
||||
),
|
||||
None,
|
||||
Vec::new(),
|
||||
),
|
||||
};
|
||||
};
|
||||
let effective = effective_stdin(&source, stdin_lines);
|
||||
let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source);
|
||||
let show_stream = module_opt
|
||||
.as_ref()
|
||||
.map(uses_stream_panel)
|
||||
.unwrap_or(false);
|
||||
let show_stream = module_opt.as_ref().map(uses_stream_panel).unwrap_or(false);
|
||||
// Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`.
|
||||
let auto_stream = live
|
||||
&& show_stream
|
||||
@@ -447,41 +446,40 @@ pub(crate) fn build_file_view_with_exec(
|
||||
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
||||
opts.fs_root = Some(root.root.clone());
|
||||
let mut captured: Option<crate::capture::RunCapture> = None;
|
||||
let (stdout, stderr, ok, plots, mut bindings_html) =
|
||||
if !execute {
|
||||
(
|
||||
String::new(),
|
||||
"execution skipped (--no-exec)".into(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::from(r#"<p class="vars-skipped">skipped</p>"#),
|
||||
)
|
||||
} else if awaiting_input || auto_stream {
|
||||
(
|
||||
String::new(),
|
||||
String::new(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => {
|
||||
let stdout = cap.stdout.clone();
|
||||
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
|
||||
let bindings_html = render_bindings_html(&cap.bindings);
|
||||
captured = Some(cap);
|
||||
(stdout, String::new(), true, plots, bindings_html)
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
),
|
||||
let (stdout, stderr, ok, plots, mut bindings_html) = if !execute {
|
||||
(
|
||||
String::new(),
|
||||
"execution skipped (--no-exec)".into(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::from(r#"<p class="vars-skipped">skipped</p>"#),
|
||||
)
|
||||
} else if awaiting_input || auto_stream {
|
||||
(
|
||||
String::new(),
|
||||
String::new(),
|
||||
true,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => {
|
||||
let stdout = cap.stdout.clone();
|
||||
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
|
||||
let bindings_html = render_bindings_html(&cap.bindings);
|
||||
captured = Some(cap);
|
||||
(stdout, String::new(), true, plots, bindings_html)
|
||||
}
|
||||
};
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
String::new(),
|
||||
),
|
||||
}
|
||||
};
|
||||
// Re-read after run so writeback slots / workbook edits show in Structure.
|
||||
if execute && !awaiting_input && !auto_stream {
|
||||
if let Ok(next) = fs::read_to_string(abs) {
|
||||
@@ -514,46 +512,60 @@ pub(crate) fn build_file_view_with_exec(
|
||||
// Analysis is intentionally independent from capture/run. If a document
|
||||
// has side effects, its facts remain visible while its values stay absent.
|
||||
let title_guess = crate::view::title_from_source(&source, rel);
|
||||
let (knowledge_html, knowledge_error, page_token) =
|
||||
match crate::sema::compile_project(&crate::sema::CompileOptions {
|
||||
let analysis = if root.only_file.is_some() {
|
||||
crate::sema::compile_file_closure(abs)
|
||||
} else {
|
||||
crate::sema::compile_project(&crate::sema::CompileOptions {
|
||||
project_root: root.root.clone(),
|
||||
entry: Some(abs.to_path_buf()),
|
||||
lock_mode: crate::sema::LockMode::Off,
|
||||
}) {
|
||||
Ok(compilation) => {
|
||||
let html = render_knowledge_html(&compilation.semantics, rel);
|
||||
// V1: also materialize structured presentation (JSON available to page scripts).
|
||||
let mut presentation = crate::view::KnowledgePresentation::from_project(
|
||||
&compilation.semantics,
|
||||
rel,
|
||||
&title_guess,
|
||||
);
|
||||
presentation.page_token = crate::view::page_token_from_source(rel, &source);
|
||||
let json = presentation.to_json().to_string();
|
||||
let with_model = if html.is_empty() {
|
||||
format!(
|
||||
r#"<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
r#"{html}<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
html = html,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
};
|
||||
(
|
||||
with_model,
|
||||
String::new(),
|
||||
presentation.page_token.clone(),
|
||||
})
|
||||
};
|
||||
let (knowledge_html, knowledge_error, page_token) = match analysis {
|
||||
Ok(compilation) => {
|
||||
// Dependency closures may have a wider root than the reader's file directory.
|
||||
let semantic_rel = abs
|
||||
.strip_prefix(&compilation.semantics.root)
|
||||
.unwrap_or(abs)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let html = crate::view::knowledge_reading::render(
|
||||
&compilation.semantics,
|
||||
&semantic_rel,
|
||||
module_opt.as_ref(),
|
||||
);
|
||||
// V1: also materialize structured presentation (JSON available to page scripts).
|
||||
let mut presentation = crate::view::KnowledgePresentation::from_project(
|
||||
&compilation.semantics,
|
||||
&semantic_rel,
|
||||
&title_guess,
|
||||
);
|
||||
presentation.document_id = rel.to_string();
|
||||
presentation.page_token = crate::view::page_token_from_source(rel, &source);
|
||||
let json = presentation.to_json().to_string();
|
||||
let with_model = if html.is_empty() {
|
||||
format!(
|
||||
r#"<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
format!("知识关系暂不可用:{}", tidy_user_error(&format!("{e:#}"), abs, rel)),
|
||||
crate::view::page_token_from_source(rel, &source),
|
||||
} else {
|
||||
format!(
|
||||
r#"{html}<script type="application/json" id="mq-knowledge-presentation">{json}</script>"#,
|
||||
html = html,
|
||||
json = json.replace("</", "<\\/")
|
||||
)
|
||||
};
|
||||
(with_model, String::new(), presentation.page_token.clone())
|
||||
}
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
format!(
|
||||
"知识关系暂不可用:{}",
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel)
|
||||
),
|
||||
};
|
||||
crate::view::page_token_from_source(rel, &source),
|
||||
),
|
||||
};
|
||||
let page_token = if page_token.is_empty() {
|
||||
crate::view::page_token_from_source(rel, &source)
|
||||
} else {
|
||||
|
||||
@@ -169,3 +169,46 @@ body.reader-page .nav { visibility:hidden; }
|
||||
body.reader-page #nav-toggle:checked ~ .shell .nav { visibility:visible; }
|
||||
|
||||
@media print { body.reader-page .document-surface { padding-bottom:0; } }
|
||||
|
||||
/* Action text belongs to the sentence; its implementation belongs to a note. */
|
||||
body.reader-page .doc-line { font:19px/1.8 var(--serif); overflow-wrap:anywhere; }
|
||||
body.reader-page .mq-anchor:has(.occl-label) { background:transparent; border:0; padding:0; }
|
||||
body.reader-page button.occl-label { display:inline; appearance:none; font:inherit; color:var(--olive); background:transparent; border:0; border-bottom:1px dotted var(--gold); border-radius:0; padding:0 1px; cursor:pointer; text-align:inherit; }
|
||||
body.reader-page button.occl-label:hover { background:var(--fill); }
|
||||
body.reader-page .occl-stub { display:inline; font:11px/1.5 var(--sans); border:1px solid var(--gold); border-radius:5px; padding:2px 5px; margin-left:6px; color:var(--focus); white-space:normal; }
|
||||
body.reader-page details.annot-implementation { display:block; padding:8px 12px; border-radius:7px; border:1px solid var(--line); margin:5px 0; }
|
||||
body.reader-page .annot-implementation > summary { cursor:pointer; font:12px/1.6 var(--sans); color:var(--olive); }
|
||||
body.reader-page .annot-implementation .occl-code { display:block; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); padding:6px 0; border:0; border-radius:0; background:transparent; }
|
||||
body.reader-page details.annot-implementation.is-margin-note { padding:5px 0; border:0; margin:0; }
|
||||
body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5 var(--serif); }
|
||||
.logic-hint { display:block; color:var(--muted); font:10px/1.6 var(--sans); margin-top:5px; }
|
||||
.reader-syntax-guide { font:13px/1.7 var(--sans); border:1px solid var(--line); padding:12px 16px; border-radius:9px; margin:0 0 28px; color:var(--muted); }
|
||||
.reader-syntax-guide > summary { cursor:pointer; color:var(--olive); }
|
||||
.reader-syntax-guide p { margin:12px 0; }
|
||||
.knowledge-table-wrap { max-width:100%; overflow-x:auto; }
|
||||
.reader-syntax-guide table,.knowledge-panel table { width:100%; border-collapse:collapse; font:12px/1.65 var(--sans); }
|
||||
.reader-syntax-guide th,.reader-syntax-guide td,.knowledge-panel th,.knowledge-panel td { padding:9px 10px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
.reader-syntax-guide td:first-child { min-width:115px; }
|
||||
.reader-page .knowledge-block { border-top:1px solid var(--line); padding-top:22px; font:14px/1.7 var(--sans); }
|
||||
.reader-page .knowledge-block > summary { color:var(--olive); font:18px/1.6 var(--serif); }
|
||||
.knowledge-intro { margin:20px 0; }.knowledge-intro h3 { font:22px/1.5 var(--serif); margin:0 0 8px; }
|
||||
.knowledge-intro p { margin:7px 0; }
|
||||
.knowledge-card { margin:12px 0; border:1px solid var(--line); border-radius:10px; overflow:hidden; font:13px/1.75 var(--sans); }
|
||||
.knowledge-card > summary { display:flex; align-items:baseline; flex-wrap:wrap; gap:10px; padding:14px 18px; cursor:pointer; background:var(--fill); }
|
||||
.knowledge-card > summary::before { content:'›'; color:var(--gold); }.knowledge-card[open] > summary::before { content:'⌄'; }
|
||||
.knowledge-unit-name { font:18px/1.6 var(--serif); overflow-wrap:anywhere; }.knowledge-unit-kind { font:11px/1.5 var(--sans); color:var(--muted); }
|
||||
.knowledge-unit-body { padding:16px 18px; }.knowledge-unit-body h4 { margin:20px 0 8px; font:600 13px/1.6 var(--sans); color:var(--olive); }
|
||||
.knowledge-unit-body p { margin:6px 0; }.knowledge-source-link { color:var(--olive); border-bottom:1px dotted var(--gold); font-size:12px; }
|
||||
.knowledge-status { display:grid; grid-template-columns:100px minmax(0,1fr); gap:7px 12px; margin:8px 0; }.knowledge-status dt { color:var(--muted); }.knowledge-status dd { margin:0; }
|
||||
.knowledge-panel code { white-space:pre-wrap; overflow-wrap:anywhere; font:11px/1.65 var(--mono); }
|
||||
.knowledge-dependencies { padding-left:20px; }.knowledge-dependencies a { border-bottom:1px dotted var(--gold); }
|
||||
.knowledge-steps,.knowledge-technical { border-top:1px solid var(--line); margin-top:18px; padding-top:12px; }
|
||||
.knowledge-steps > summary,.knowledge-technical > summary { font:12px/1.7 var(--sans); cursor:pointer; color:var(--muted); }
|
||||
.knowledge-step { padding:5px 0; overflow-wrap:anywhere; }.knowledge-step-kind { display:inline-block; color:var(--olive); min-width:4em; margin-right:8px; }
|
||||
.knowledge-technical dl { font-size:11px; }.knowledge-technical dd { margin:4px 0 14px; overflow-wrap:anywhere; }
|
||||
.reader-dialog:has(.knowledge-panel) { width:min(850px,calc(100vw - 32px)); }
|
||||
@media(max-width:600px) { body.reader-page .doc-line { font-size:17px; }.knowledge-unit-body { padding:12px; }.knowledge-status { grid-template-columns:80px minmax(0,1fr); }.knowledge-card > summary { padding:12px; }.knowledge-table-wrap th,.knowledge-table-wrap td { min-width:65px; }.reader-syntax-guide { padding:10px; } }
|
||||
@media print { .annot-implementation { break-inside:avoid; }.reader-syntax-guide { display:none; }.knowledge-technical { overflow-wrap:anywhere; } }
|
||||
.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); }
|
||||
.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; }
|
||||
.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; }
|
||||
+47
-6
@@ -72,6 +72,8 @@
|
||||
if (name === 'close-dialog') { dialog.close(); return; }
|
||||
if (name === 'document') { if (dialog.open) dialog.close(); scrollTo(document.getElementById('document-section') || document.querySelector('main')); return; }
|
||||
if (name === 'search') { showSearch(); return; }
|
||||
if (name === 'knowledge') { openDialog('可执行知识', name); movePanel(document.querySelector('.knowledge-panel')); return; }
|
||||
if (name === 'syntax') { var guide=document.getElementById('reader-syntax-guide'); if(guide) {guide.open=true;scrollTo(guide);} return; }
|
||||
if (name === 'functions' || name === 'variables') {
|
||||
var panel = document.getElementById(name === 'functions' ? 'fn-outline' : 'vars-panel');
|
||||
openDialog(name === 'functions' ? '函数目录' : '文档变量', name); movePanel(panel); return;
|
||||
@@ -79,10 +81,27 @@
|
||||
if (name === 'memory') {
|
||||
openDialog('执行内存与调用轨迹', name);
|
||||
var hint = document.createElement('p'); hint.textContent = window.MARQDO_VIEW_LIVE ? '当前文档已捕获的绑定与调用轨迹;会话状态可在高级工具中查看。' : '以下为导出时保存的执行快照。'; content.appendChild(hint);
|
||||
var pre = document.createElement('pre');
|
||||
try { pre.textContent = JSON.stringify(JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'), null, 2); }
|
||||
catch (_) { pre.textContent = '当前没有可用执行快照。'; }
|
||||
content.appendChild(pre); return;
|
||||
var report;
|
||||
try { report=JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'); }
|
||||
catch (_) { report={}; }
|
||||
if(typeof report.ok!=='boolean') {
|
||||
var empty=document.createElement('p');empty.textContent='本页没有捕获执行记录;静态知识分析不会自动产生运行结果。';content.appendChild(empty);return;
|
||||
}
|
||||
var status=document.createElement('p');status.className='reader-run-summary';
|
||||
status.textContent=(report.ok?'这次运行成功':'这次运行失败')+' · '+(report.calls||[]).length+' 次调用 · '+(report.loops||[]).length+' 个循环记录';content.appendChild(status);
|
||||
function reportTable(title,headers,rows) {
|
||||
var heading=document.createElement('h3');heading.textContent=title;content.appendChild(heading);
|
||||
var wrap=document.createElement('div');wrap.className='knowledge-table-wrap';
|
||||
var table=document.createElement('table'),head=document.createElement('tr');
|
||||
headers.forEach(function(text){var cell=document.createElement('th');cell.textContent=text;head.appendChild(cell);});table.appendChild(head);
|
||||
rows.forEach(function(row){var tr=document.createElement('tr');row.forEach(function(text){var cell=document.createElement('td');cell.textContent=text;tr.appendChild(cell);});table.appendChild(tr);});
|
||||
wrap.appendChild(table);content.appendChild(wrap);
|
||||
}
|
||||
var bindings=report.bindings_final||{};
|
||||
reportTable('最终绑定',['名称','值'],Object.keys(bindings).map(function(key){return [key,String(bindings[key])];}));
|
||||
reportTable('调用记录',['函数','源码位置','输入'],(report.calls||[]).map(function(call){return [call.fn,'第 '+call.fn_line+' 行',call.args_brief||'无实参'];}));
|
||||
var details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='完整执行报告(技术详情)';details.appendChild(summary);
|
||||
var pre=document.createElement('pre');pre.textContent=JSON.stringify(report,null,2);details.appendChild(pre);content.appendChild(details);return;
|
||||
}
|
||||
if (name === 'execution') { scrollTo(document.getElementById('exec-block')); return; }
|
||||
if (name === 'run') {
|
||||
@@ -104,6 +123,8 @@
|
||||
}
|
||||
if (name === 'more') {
|
||||
openDialog('文档工具', name);
|
||||
option('可执行知识', function () { action('knowledge'); });
|
||||
option('语法与阅读说明', function () { dialog.close(); action('syntax'); });
|
||||
option('文件目录', function () { dialog.close(); action('files'); });
|
||||
option('查看完整源码', function () { var source = document.querySelector('.source-block'); if (source) { source.open = true; scrollTo(source); } });
|
||||
option('高级运行工具', function () { document.body.classList.toggle('reader-tools'); dialog.close(); scrollTo(document.getElementById('notebook-bar')); });
|
||||
@@ -170,6 +191,7 @@
|
||||
band.classList.remove('is-keyed');
|
||||
band.querySelectorAll('.annot-chip').forEach(function (chip) {
|
||||
chip.classList.remove('is-margin-note');
|
||||
if(chip.classList.contains('annot-implementation')) chip.open=false;
|
||||
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
|
||||
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
|
||||
});
|
||||
@@ -379,6 +401,7 @@
|
||||
var fragments = anchorFragments(item.anchor);
|
||||
var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58));
|
||||
item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px';
|
||||
if(item.chip.classList.contains('annot-implementation')) item.chip.open=true;
|
||||
var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4];
|
||||
var choices = nextY.map(function (y, side) {
|
||||
var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1];
|
||||
@@ -439,14 +462,32 @@
|
||||
dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content');
|
||||
dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); });
|
||||
document.addEventListener('click', function (ev) {
|
||||
var logic=ev.target.closest('[data-logic-id]');
|
||||
if(logic) {
|
||||
ev.preventDefault();
|
||||
var note=document.getElementById(logic.dataset.logicId+'-note');
|
||||
openDialog('实际逻辑 · '+logic.textContent,'logic');
|
||||
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码实现,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
|
||||
var code=document.createElement('pre');code.textContent=note ? note.querySelector('.annot-value').textContent : '此片段的逻辑详情暂不可用。';content.appendChild(code);return;
|
||||
}
|
||||
var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]');
|
||||
if(knowledge) {
|
||||
var target=document.getElementById((knowledge.getAttribute('href')||'').slice(1));
|
||||
if(target){ev.preventDefault();if(dialog.open)dialog.close();var parent=target;while(parent){if(parent.tagName==='DETAILS')parent.open=true;parent=parent.parentElement;}scrollTo(target);}return;
|
||||
}
|
||||
var sourceLink=ev.target.closest('.knowledge-source-link,.knowledge-step a');
|
||||
if(sourceLink && dialog.open) dialog.close();
|
||||
var button = ev.target.closest('[data-reader-action]'); if (button) action(button.dataset.readerAction);
|
||||
var chip = ev.target.closest('.annot-chip');
|
||||
if (chip) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); }
|
||||
if (chip && !chip.classList.contains('annot-implementation')) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); }
|
||||
if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); }
|
||||
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
|
||||
});
|
||||
function focusNote(ev, focus) {
|
||||
var chip = ev.target.closest('.annot-chip'); if (!chip || ev.relatedTarget && chip.contains(ev.relatedTarget)) return;
|
||||
var trigger=ev.target.closest('.annot-chip,[data-logic-id]');
|
||||
if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return;
|
||||
var chip=trigger.matches('.annot-chip') ? trigger : document.getElementById(trigger.dataset.logicId+'-note');
|
||||
if(!chip) return;
|
||||
var owner = noteOwner(chip.closest('[data-annot-band]'));
|
||||
var anchor = findAnchor(owner,chip); if (anchor) anchor.classList.toggle('is-focus', focus);
|
||||
chip.classList.toggle('is-focus',focus);
|
||||
|
||||
+3
-84
@@ -60,90 +60,9 @@ pub struct FileViewModel {
|
||||
/// View deliberately compiles semantics without running the target, so a page
|
||||
/// can show binding/effect/verification facts even in `--no-exec` exports.
|
||||
///
|
||||
/// V0: skip module/type container cards by default; rename lock digest accurately.
|
||||
/// The reader groups facts by source unit and folds raw identifiers into technical detail.
|
||||
pub fn render_knowledge_html(project: &crate::sema::SemanticProject, rel: &str) -> String {
|
||||
let artifacts: Vec<_> = project
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|artifact| {
|
||||
artifact.source.file == rel && artifact.kind != "module" && artifact.kind != "type"
|
||||
})
|
||||
.collect();
|
||||
let steps: Vec<_> = project.steps.iter().filter(|step| step.source.file == rel).collect();
|
||||
if artifacts.is_empty() && steps.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = String::from(r#"<div class="knowledge-panel" aria-label="Executable knowledge">"#);
|
||||
if !steps.is_empty() {
|
||||
out.push_str(r#"<article class="knowledge-card knowledge-steps"><h3>文档中的步骤</h3><p class="knowledge-hint">结构步骤(非实际执行时序)</p><ol class="knowledge-step-list">"#);
|
||||
for step in &steps {
|
||||
let label = project
|
||||
.refs
|
||||
.iter()
|
||||
.find(|r| r.id == step.reference)
|
||||
.map(|r| r.label.as_str())
|
||||
.unwrap_or(step.reference.as_str());
|
||||
let line = step.source.line;
|
||||
let target_ids = if step.calls.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
r#" <span class="knowledge-step-targets">→ {}</span>"#,
|
||||
escape(&step.calls.iter().map(|id| id.as_str()).collect::<Vec<_>>().join(", "))
|
||||
)
|
||||
};
|
||||
// Structure pane uses #stmt-{line}; jump there for source navigation.
|
||||
out.push_str(&format!(
|
||||
"<li class=\"knowledge-step\" data-step-kind=\"{0}\" data-line=\"{1}\"><a href=\"#stmt-{1}\"><code class=\"ks-kind\">{0}</code> {2}</a>{3}</li>",
|
||||
escape(&step.kind),
|
||||
line,
|
||||
escape(label),
|
||||
target_ids,
|
||||
));
|
||||
}
|
||||
out.push_str("</ol></article>");
|
||||
}
|
||||
for artifact in artifacts {
|
||||
let target = artifact.symbol_id.as_ref().map(|id| id.as_str()).unwrap_or(artifact.artifact_id.0.as_str());
|
||||
let signature = artifact.signature.as_ref().map(|sig| {
|
||||
let params = sig.params.iter().map(|param| format!("{}: {}{}", param.name, param.ty, if param.required { "" } else { "?" })).collect::<Vec<_>>().join(", ");
|
||||
format!("({params}) → {}", sig.returns)
|
||||
}).unwrap_or_else(|| "declaration".into());
|
||||
let effects = artifact.effects.values().join(", ");
|
||||
let deps = if artifact.dependencies.is_empty() { "none".to_string() } else { artifact.dependencies.iter().map(|id| id.0.as_str()).collect::<Vec<_>>().join(", ") };
|
||||
// Short digest for display; full value in title for copy.
|
||||
let digest = &artifact.hashes.artifact.0;
|
||||
let digest_short = if digest.len() > 20 {
|
||||
format!("{}…", &digest[..20])
|
||||
} else {
|
||||
digest.clone()
|
||||
};
|
||||
let evidence_note = match artifact.verification.evidence.as_str() {
|
||||
"sourced" => "已关联来源,内容尚未核验",
|
||||
"verified" => "证据已核验",
|
||||
"unverified" => "尚无来源记录",
|
||||
other => other,
|
||||
};
|
||||
out.push_str(&format!(
|
||||
r#"<article class="knowledge-card" id="knowledge-{name}"><h3>{name} <span class="ks-kind">{kind}</span></h3><dl><dt>Target</dt><dd><code>{target}</code></dd><dt>Signature</dt><dd><code>{sig}</code></dd><dt>Effects</dt><dd>{effects}</dd><dt>Verification</dt><dd>parse: {parse}; resolve: {resolve}; contract: {contract}; tests: {tests}; evidence: {evidence}({evidence_note})</dd><dt>制品摘要</dt><dd><code title="{digest}">{digest_short}</code> <span class="knowledge-hint">(未检查锁定状态)</span></dd><dt>Depends on</dt><dd><code>{deps}</code></dd><dt>Execution</dt><dd>尚无该知识的运行记录(知识预览不执行)。</dd></dl></article>"#,
|
||||
name = escape(&artifact.display_name),
|
||||
kind = escape(&artifact.kind),
|
||||
target = escape(target),
|
||||
sig = escape(&signature),
|
||||
effects = escape(&effects),
|
||||
parse = escape(&artifact.verification.parse),
|
||||
resolve = escape(&artifact.verification.resolve),
|
||||
contract = escape(&artifact.verification.contract),
|
||||
tests = escape(&artifact.verification.tests),
|
||||
evidence = escape(&artifact.verification.evidence),
|
||||
evidence_note = escape(evidence_note),
|
||||
digest = escape(digest),
|
||||
digest_short = escape(&digest_short),
|
||||
deps = escape(&deps),
|
||||
));
|
||||
}
|
||||
out.push_str("</div>");
|
||||
out
|
||||
crate::view::knowledge_reading::render(project, rel, None)
|
||||
}
|
||||
|
||||
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
|
||||
@@ -1336,7 +1255,7 @@ fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String
|
||||
escape(&expr_display(e))
|
||||
),
|
||||
None => String::from(
|
||||
"<span class=\"occl-stub\" title=\"空载荷:未接通或待补返回值\">桩</span>",
|
||||
"<span class=\"occl-stub\" title=\"空遮蔽当前返回 None\">待补充实际逻辑</span>",
|
||||
),
|
||||
};
|
||||
format!(
|
||||
|
||||
Reference in new issue
Block a user