feat(lang): implement RFC-LANG-0002 unified semantics (breaking)

One Markdown-to-program mapping, no version selector or legacy mapper.

Frontend/runtime:
- resolve @exec/@knowledge heading declarations with nearest-ancestor
  inheritance; only an Exec H2 is callable; add UnitKind::Knowledge and
  sem.* diagnostics (mode marker, unit name, exec-without-function,
  payload nesting/empty, syntax, control stack, params position,
  version directive, inferred-signature lint)
- extract Strong/Emph/inline Code as one-statement carriers, refuse
  nested carriers, and honour heading segment boundaries so an if/while
  cannot be closed across a heading
- lower if/else/while/end to the existing Branch/Loop/Return IR with a
  compile-time control stack; keep payload-relative source spans through
  expression parsing and rewrite them onto the file
- accept params(...) only as the first direct Exec H2 payload; keep the
  existing free-variable inference and named-only rule for inferred
  signatures; fix duplicate-mode/else/end and Knowledge-body inertness
- reject marqdo_semantics/syntax front matter directives

Data and tests:
- migrate stdlib/**/*.mq.md, regenerate stdlib.json digest
- migrate examples and the full semantics/negative/runtime corpus to
  the only current syntax; expected values/runtime codes preserved
- migrate Rust-embedded .mq.md fixtures, init template, CLI help and
  security-lane fixtures

Verified: cargo fmt --check, cargo clippy -D warnings and
cargo test --workspace --locked (green).
This commit is contained in:
cflmy committed 2026-11-21 12:26:46 +08:00
1 parent 49835424ee
commit e029853e32
375 files changed
+6591 -4790

No files matched your search

+74 -38
View File
@@ -57,25 +57,45 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
)
.with_hint("front matter must be valid YAML between `---` delimiters"),
),
Ok(_) => match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
Ok(_) => {
for key in ["marqdo_semantics", "syntax"] {
if frontmatter.has_key(key) {
diagnostics.push(
Diagnostic::error(
codes::SEM_UNSUPPORTED_VERSION_DIRECTIVE,
Some(frontmatter.yaml_span),
format!(
"`{key}` is not a syntax selector; there is one current syntax"
),
)
.with_hint(
"remove the directive and migrate the source to RFC-LANG-0002 syntax",
),
);
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint("imports are an explicit mapping: `import: { alias: \"@module\" }`"),
),
},
match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint(
"imports are an explicit mapping: `import: { alias: \"@module\" }`",
),
),
}
}
}
}
@@ -92,7 +112,7 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
let signature = signature::detect(&document, &blocks);
let explicit = signature.as_ref().map(|(_, sig)| sig);
let mut mapped = map::map_function(&document, &units, &imports, scope);
let mut mapped = map::map_function(&document, &units, scope);
diagnostics.append(&mut mapped.diagnostics);
let mut params: Vec<Param> = Vec::new();
@@ -104,7 +124,12 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
}
let inference = infer::infer(&mapped.stmts, explicit, &import_names);
diagnostics.extend(inference.diagnostics);
if kind == SignatureKind::Inferred {
if kind == SignatureKind::Inferred && !inference.params.is_empty() {
diagnostics.push(Diagnostic::warning(
codes::SEM_INFERRED_SIGNATURE,
Some(scope.heading_span),
"function signature was inferred; declare it with `params(...)`",
));
params = inference
.params
.into_iter()
@@ -157,19 +182,25 @@ mod tests {
#[test]
fn maps_recursive_factorial() {
let source = r#"# 数学
let source = r#"# @knowledge 数学
## 阶乘
## @exec 阶乘
1. `n <= 1`
`if n <= 1`
*1*
`return 1`
2. `n > 1`
`else`
**结果 = n * 阶乘(n=n-1)**
`if n > 1`
*结果*
`结果 = n * 阶乘(n=n-1)`
`return 结果`
`end`
`end`
"#;
let result = analyze(source);
assert!(
@@ -186,17 +217,19 @@ mod tests {
#[test]
fn maps_countdown_loop() {
let source = r#"## 倒计时
let source = r#"## @exec 倒计时
**n = 3**
`n = 3`
- `n > 0`
`while n > 0`
> 打印(n)
`打印(n)`
**n = n - 1**
`n = n - 1`
*n*
`end`
`return n`
"#;
let result = analyze(source);
assert!(!result.has_errors(), "{:#?}", result.diagnostics);
@@ -207,22 +240,24 @@ mod tests {
#[test]
fn invalid_strong_payload_is_a_hard_error() {
let result = analyze("## f\n\n**a *b* c**\n");
let result = analyze("## @exec f\n\n**a *b* c**\n");
assert!(result.has_errors());
assert!(result
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
.any(|d| d.code == "sem.payload_nested"));
}
#[test]
fn invalid_list_header_is_a_hard_error() {
let result = analyze("## f\n\n1. 没有条件\n");
// RFC-LANG-0002: a plain list is inert Markdown; the v2 negative is an
// unclosed control frame inside the owning Exec H2.
let result = analyze("## @exec f\n\n`if 1`\n");
assert!(result.has_errors());
assert!(result
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
.any(|d| d.code == "sem.unclosed_control"));
}
/// Strip source spans so that pure narrative edits (which shift byte
@@ -252,8 +287,9 @@ mod tests {
#[test]
fn prose_changes_do_not_change_ir() {
let base = "## f\n\n说明文字。\n\n**x = 1**\n\n更多说明。\n\n*x*\n";
let edited = "## f\n\n另一段完全不同的叙述。\n\n**x = 1**\n\n继续叙述。\n\n*x*\n";
let base = "## @exec f\n\n说明文字。\n\n`x = 1`\n\n更多说明。\n\n`return x`\n";
let edited =
"## @exec f\n\n另一段完全不同的叙述。\n\n`x = 1`\n\n继续叙述。\n\n`return x`\n";
let a = analyze(base);
let b = analyze(edited);
let a_ir = serde_json::to_value(&a.module.functions).unwrap();
+418 -458
View File
@@ -5,10 +5,8 @@
//! parsed only after the role is known. Invalid executable shapes produce hard
//! diagnostics and never fall back to prose.
use marqdo_expression::{
parse_arguments, parse_expression, parse_statement, Arg, AssignTarget, Expr, StatementKind,
};
use marqdo_ir::{CallSite, CallTarget, ImportDecl, PlaceTarget, Stmt};
use marqdo_expression::{parse_expression, parse_statement, AssignTarget, Expr, StatementKind};
use marqdo_ir::{PlaceTarget, Stmt};
use marqdo_markdown::{normalize_name, MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
@@ -29,30 +27,74 @@ pub struct MappedBody {
pub fn map_function(
doc: &MarkdownDocument,
index: &UnitIndex,
imports: &[ImportDecl],
scope: &FunctionScope,
) -> MappedBody {
let mut mapper = Mapper {
index,
imports,
diagnostics: Vec::new(),
saw_params: None,
};
let blocks = &doc.root.children[scope.body_start..scope.body_end];
let stmts = mapper.blocks(blocks);
let mut stmts = Vec::new();
let mut segment = Vec::new();
let mut mode = crate::units::SemanticMode::Exec;
for (node_index, block) in doc.root.children.iter().enumerate() {
if node_index < scope.body_start || node_index >= scope.body_end {
continue;
}
if let MdKind::Heading { .. } = block.kind {
if mode == crate::units::SemanticMode::Exec {
stmts.extend(mapper.blocks(&segment));
}
segment.clear();
if let Some(heading) = index.headings.iter().find(|h| h.node_index == node_index) {
mode = heading.mode;
}
continue;
}
if mode == crate::units::SemanticMode::Exec {
segment.push(block.clone());
}
}
if mode == crate::units::SemanticMode::Exec {
stmts.extend(mapper.blocks(&segment));
}
MappedBody {
stmts,
diagnostics: mapper.diagnostics,
}
}
struct Mapper<'a> {
index: &'a UnitIndex,
#[allow(dead_code)]
imports: &'a [ImportDecl],
struct Mapper {
diagnostics: Vec<Diagnostic>,
saw_params: Option<Span>,
}
impl<'a> Mapper<'a> {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stop {
End,
Else,
Eof,
}
enum Payload {
If(Expr),
Else,
While(Expr),
End,
Return(Expr),
Params,
Statement(marqdo_expression::Statement),
}
struct RawPayload {
payload: Payload,
span: Span,
segments: PayloadSegments,
/// True only for a carrier in the heading's direct body, not inside a
/// list or block quote (`params` is legal only there).
direct: bool,
}
impl Mapper {
fn error(&mut self, code: &str, span: Option<Span>, message: impl Into<String>) {
self.diagnostics
.push(Diagnostic::error(code, span, message));
@@ -70,468 +112,386 @@ impl<'a> Mapper<'a> {
}
fn blocks(&mut self, blocks: &[MdNode]) -> Vec<Stmt> {
let mut stmts = Vec::new();
let mut raw = Vec::new();
for block in blocks {
stmts.extend(self.block(block));
self.extract(block, &mut raw, true);
}
let mut position = 0;
let (stmts, stop) = self.sequence(&raw, &mut position, false, false);
if stop != Stop::Eof {
self.error(
codes::SEM_UNMATCHED_END,
raw.get(position.saturating_sub(1)).map(|node| node.span),
"control frame ends outside its owning function segment",
);
}
stmts
}
fn block(&mut self, block: &MdNode) -> Vec<Stmt> {
match &block.kind {
MdKind::Paragraph => self.paragraph(block),
MdKind::List { ordered, .. } => self.list(block, *ordered),
MdKind::BlockQuote => self.quote(block),
// Level>=3 headings and inert document values stay out of the IR.
_ => Vec::new(),
}
}
fn paragraph(&mut self, paragraph: &MdNode) -> Vec<Stmt> {
let mut stmts = Vec::new();
for child in &paragraph.children {
match &child.kind {
MdKind::Strong => {
if let Some(stmt) = self.exec_statement(child) {
stmts.push(stmt);
fn extract(&mut self, node: &MdNode, out: &mut Vec<RawPayload>, direct: bool) {
match &node.kind {
MdKind::Paragraph => {
for child in &node.children {
self.extract(child, out, direct);
}
}
MdKind::BlockQuote | MdKind::Item { .. } | MdKind::List { .. } => {
for child in &node.children {
self.extract(child, out, false);
}
}
MdKind::Strong | MdKind::Emph => {
let (text, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error(
codes::SEM_PAYLOAD_NESTED,
Some(error.span),
format!("invalid payload carrier: {}", error.reason),
);
return;
}
}
MdKind::Emph => {
if let Some(stmt) = self.return_statement(child) {
stmts.push(stmt);
}
}
// Lazy/inert inline structures: never recurse into them.
MdKind::Link { .. }
| MdKind::Image { .. }
| MdKind::Strikethrough
| MdKind::Code { .. }
| MdKind::Math { .. }
| MdKind::Text
| MdKind::SoftBreak
| MdKind::LineBreak
| MdKind::HtmlInline
| MdKind::FootnoteReference { .. } => {}
_ => {}
};
self.push(text, node.span, segments, out, direct);
}
MdKind::Code { ticks } => {
let literal = node.literal.as_deref().unwrap_or_default();
let inner = Span::new(
node.span.start.saturating_add(*ticks),
node.span.end.saturating_sub(*ticks),
);
self.push(
literal.to_string(),
node.span,
PayloadSegments::single(literal, inner),
out,
direct,
);
}
MdKind::Heading { .. } => {}
_ => {}
}
stmts
}
fn exec_statement(&mut self, node: &MdNode) -> Option<Stmt> {
let (payload, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"keep the executable payload as plain text or a single code span",
);
return None;
}
};
if payload.trim().is_empty() {
fn push(
&mut self,
text: String,
span: Span,
segments: PayloadSegments,
out: &mut Vec<RawPayload>,
direct: bool,
) {
if text.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(node.span),
"execution statement has an empty payload",
codes::SEM_EMPTY_PAYLOAD,
Some(span),
"executable payload is empty",
);
return None;
return;
}
match parse_statement(&payload) {
Ok(mut statement) => {
segments.rewrite_statement(&mut statement);
Some(match statement.kind {
StatementKind::Assign { target, value } => Stmt::Assign {
target: match target {
AssignTarget::Local { name, name_span } => {
PlaceTarget::Local { name, name_span }
}
AssignTarget::Index {
base,
index,
span: target_span,
} => PlaceTarget::Index {
base: *base,
index: *index,
span: target_span,
},
},
value,
span: node.span,
},
StatementKind::Expr(expr) => Stmt::Eval {
expr,
span: node.span,
},
})
if let Some(mut payload) = self.parse_payload(&text, span, &segments) {
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload {
segments.rewrite_expr(expr);
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid execution statement: {}", error.message),
"statements are `name = expression` or an expression; put the payload in a code span when Markdown emphasis conflicts",
);
None
}
}
}
fn return_statement(&mut self, node: &MdNode) -> Option<Stmt> {
let (payload, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"a return payload must be plain text or a single code span",
);
return None;
}
};
if payload.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(node.span),
"return statement has an empty payload",
);
return None;
}
match parse_expression(&payload) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
Some(Stmt::Return {
value: expr,
span: node.span,
})
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid return expression: {}", error.message),
"`*表达式*` returns the value of the expression",
);
None
}
}
}
fn list(&mut self, list: &MdNode, ordered: bool) -> Vec<Stmt> {
if list.children.is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(list.span),
"list in an executable position has no items",
);
return Vec::new();
}
let mut arms = Vec::new();
let mut loops = Vec::new();
for item in &list.children {
let Some((condition, condition_span, body_blocks)) = self.condition_of(item) else {
continue;
};
let body = self.blocks(body_blocks);
if ordered {
arms.push(marqdo_ir::BranchArm {
condition,
condition_span,
body,
span: item.span,
});
} else {
loops.push(Stmt::Loop {
condition,
condition_span,
body,
span: item.span,
});
}
}
if ordered {
if arms.is_empty() {
return Vec::new();
}
vec![Stmt::Branch {
arms,
span: list.span,
}]
} else {
loops
}
}
/// Extract the condition header of a list item and its remaining blocks.
fn condition_of<'b>(&mut self, item: &'b MdNode) -> Option<(Expr, Span, &'b [MdNode])> {
let Some(first) = item.children.first() else {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(item.span),
"list item in an executable position must start with a condition code span",
"write the condition first: `` `n > 0` ``",
);
return None;
};
if !matches!(first.kind, MdKind::Paragraph) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(first.span),
"list item must start with a paragraph containing the condition code span",
"put the condition on the first line of the item",
);
return None;
}
let Some(condition_node) = first.children.first() else {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(first.span),
"list item paragraph is empty; a condition code span is required",
);
return None;
};
if !matches!(condition_node.kind, MdKind::Code { .. }) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(condition_node.span),
"list item must start with a condition inside an inline code span",
"the condition is a `Code` span: `` `n > 0` ``; other text is description",
);
return None;
}
// The remainder of the condition paragraph is description only. The
// semantic mapper does not descend into it, so an executable `Strong`
// or `Emph` there would otherwise be silently swallowed. Reject it as
// a hard shape error instead of guessing the author's intent.
for tail in first.children.iter().skip(1) {
if matches!(tail.kind, MdKind::Strong | MdKind::Emph) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(tail.span),
format!(
"`{}` inside a list-item condition paragraph is not executed and cannot be silently ignored",
tail.kind.tag()
),
"put executable statements in their own paragraph after the condition line",
);
return None;
}
}
let literal = condition_node.literal.clone().unwrap_or_default();
// `condition_node.span` includes the backtick delimiters. The payload
// map must start at the first literal byte so parse diagnostics and
// expression spans point at the expression, not at a delimiter.
let ticks = match condition_node.kind {
MdKind::Code { ticks } => ticks,
_ => 0,
};
let literal_span = Span::new(
condition_node.span.start.saturating_add(ticks),
condition_node.span.end.saturating_sub(ticks),
);
let segments = PayloadSegments::single(&literal, literal_span);
match parse_expression(&literal) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
Some((expr, condition_node.span, &item.children[1..]))
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid condition expression: {}", error.message),
"conditions are Boolean expressions, e.g. `n > 0`",
);
None
}
}
}
fn quote(&mut self, quote: &MdNode) -> Vec<Stmt> {
if quote.children.len() != 1 || quote.children[0].kind != MdKind::Paragraph {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"a block quote invocation must contain exactly one paragraph",
"use one block quote per call; prose belongs in normal paragraphs",
);
return Vec::new();
}
let paragraph = &quote.children[0];
self.call_paragraph(quote, paragraph)
}
fn call_paragraph(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
let first = paragraph.children.first();
let is_link_form = first
.map(|node| matches!(node.kind, MdKind::Link { .. }))
.unwrap_or(false);
if is_link_form {
return self.link_call(quote, paragraph);
}
let (payload, segments) = match PayloadSegments::of(paragraph) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"a block quote call payload must be plain text or one code span",
);
return Vec::new();
}
};
if payload.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"block quote invocation has an empty payload",
);
return Vec::new();
}
match parse_expression(&payload) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
if !matches!(expr, Expr::Call { .. }) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(segments.map_span(expr_span(&expr))),
"a block quote must be a complete function call",
"write `> 函数(参数)`; use a `**strong**` statement to bind a result",
);
return Vec::new();
}
vec![Stmt::Eval {
expr,
span: quote.span,
}]
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid call expression: {}", error.message),
"block quotes call functions explicitly: `> 函数(参数)`",
);
Vec::new()
}
}
}
fn link_call(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
let link = &paragraph.children[0];
let (url, link_span) = match &link.kind {
MdKind::Link { url, .. } => (url.clone(), link.span),
_ => unreachable!("link form checked by caller"),
};
let target = self.resolve_link_target(&url, link_span);
let rest = &paragraph.children[1..];
let (suffix, segments) = match PayloadSegments::from_children(rest) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"link call arguments must follow the link as plain text or code spans",
);
return Vec::new();
}
};
if suffix.trim().is_empty() {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"link-form call requires an explicit argument list",
"write `> [函数](#函数)()` even for zero arguments",
);
return Vec::new();
}
let mut args: Vec<Arg> = match parse_arguments(&suffix) {
Ok(args) => args,
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid call arguments: {}", error.message),
"arguments are `name = value` or positional values",
);
return Vec::new();
}
};
segments.rewrite_args(&mut args);
let Some(target) = target else {
return Vec::new();
};
vec![Stmt::Call {
call: CallSite {
target,
args,
span: quote.span,
},
span: quote.span,
}]
}
fn resolve_link_target(&mut self, url: &str, span: Span) -> Option<CallTarget> {
if let Some(fragment) = url.strip_prefix('#') {
let unit_id = self.index.anchors.get(fragment).cloned().or_else(|| {
self.index
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| unit.id.clone())
out.push(RawPayload {
payload,
span,
segments,
direct,
});
let Some(unit_id) = unit_id else {
self.error(
codes::REF_UNRESOLVED,
Some(span),
format!("no heading matches call target `{url}`"),
);
return None;
};
let Some(scope) = self
.index
.functions
.iter()
.find(|scope| scope.unit == unit_id)
else {
self.error(
codes::REF_UNRESOLVED,
Some(span),
format!("call target `{url}` is not a function"),
);
return None;
};
Some(CallTarget::Resolved {
module: unit_id.module.clone(),
function: scope.id.name.clone(),
})
} else if url.starts_with("http://") || url.starts_with("https://") {
self.error_with_hint(
codes::REF_UNRESOLVED,
Some(span),
"external links cannot be called",
"link targets used as calls must resolve to a Marqdo function",
);
None
} else {
self.error_with_hint(
codes::MODULE_UNRESOLVED,
Some(span),
format!("cannot resolve cross-module call target `{url}`"),
"import the module explicitly in front matter and call it through the alias",
);
None
}
}
}
fn expr_span(expr: &Expr) -> Span {
marqdo_expression::Expr::span(expr)
fn parse_payload(
&mut self,
text: &str,
span: Span,
segments: &PayloadSegments,
) -> Option<Payload> {
let map = |span: Span| segments.map_span(span);
let text = text.trim();
if text.starts_with("params(") {
// Signature syntax and diagnostics are owned by `signature::parse`;
// the mapper only recognizes the declaration payload.
return Some(Payload::Params);
}
if text == "params" || text.starts_with("params ") {
self.error(
codes::SEM_SYNTAX,
Some(span),
"malformed params declaration; write `params(name: Type, ...)`",
);
return None;
}
let (word, rest) = match text.split_once(char::is_whitespace) {
Some((word, rest)) => (word, rest.trim()),
None => (text, ""),
};
// Parse control expressions with the keyword replaced by spaces so the
// expression AST keeps payload-relative (not rest-relative) spans.
let expression_at = |rest: &str| {
let offset = text.len().saturating_sub(rest.len());
parse_expression(&format!("{}{}", " ".repeat(offset), rest))
};
match word {
"if" => {
if rest.is_empty() {
self.error(codes::SEM_SYNTAX, Some(span), "`if` requires a condition");
return None;
}
match expression_at(rest) {
Ok(expr) => Some(Payload::If(expr)),
Err(error) => {
self.error(
codes::SEM_SYNTAX,
Some(map(error.span)),
format!("invalid if condition: {}", error.message),
);
None
}
}
}
"else" if rest.is_empty() => Some(Payload::Else),
"else" => {
self.error(codes::SEM_SYNTAX, Some(span), "`else` takes no expression");
None
}
"while" => {
if rest.is_empty() {
self.error(
codes::SEM_SYNTAX,
Some(span),
"`while` requires a condition",
);
return None;
}
match expression_at(rest) {
Ok(expr) => Some(Payload::While(expr)),
Err(error) => {
self.error(
codes::SEM_SYNTAX,
Some(map(error.span)),
format!("invalid while condition: {}", error.message),
);
None
}
}
}
"end" if rest.is_empty() => Some(Payload::End),
"end" => {
self.error(codes::SEM_SYNTAX, Some(span), "`end` takes no expression");
None
}
"return" => {
if rest.is_empty() {
self.error(
codes::SEM_SYNTAX,
Some(span),
"`return` requires an expression",
);
return None;
}
match expression_at(rest) {
Ok(expr) => Some(Payload::Return(expr)),
Err(error) => {
self.error(
codes::SEM_SYNTAX,
Some(map(error.span)),
format!("invalid return expression: {}", error.message),
);
None
}
}
}
"params" => {
if text.starts_with("params(") && text.ends_with(')') {
Some(Payload::Params)
} else {
self.error(
codes::SEM_SYNTAX,
Some(span),
"malformed params declaration",
);
None
}
}
"ifdef" | "returning" | "paramsx" => self.statement_payload(text, span),
_ => self.statement_payload(text, span),
}
}
fn statement_payload(&mut self, text: &str, span: Span) -> Option<Payload> {
match parse_statement(text) {
Ok(statement) => Some(Payload::Statement(statement)),
Err(error) => {
self.error_with_hint(
codes::SEM_SYNTAX,
Some(span),
format!("invalid execution payload: {}", error.message),
"one payload is exactly one statement; put control keywords in their own carriers",
);
None
}
}
}
fn sequence(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
stop_on_else: bool,
in_else_body: bool,
) -> (Vec<Stmt>, Stop) {
let mut out = Vec::new();
while *position < nodes.len() {
let raw = &nodes[*position];
match &raw.payload {
Payload::Else => {
if stop_on_else {
return (out, Stop::Else);
}
self.error(
if in_else_body {
codes::SEM_DUPLICATE_ELSE
} else {
codes::SEM_UNMATCHED_ELSE
},
Some(raw.span),
if in_else_body {
"`if` has more than one `else`"
} else {
"`else` has no open `if`"
},
);
*position += 1;
}
Payload::End => {
return (out, Stop::End);
}
Payload::If(condition) => {
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (then_body, stop) = self.sequence(nodes, position, true, false);
let mut else_body = Vec::new();
let finish = match stop {
Stop::Else => {
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, true);
else_body = body;
stop
}
other => other,
};
if finish != Stop::End {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`if` is not closed by `end`",
);
} else {
*position += 1;
}
let mut arms = vec![marqdo_ir::BranchArm {
condition,
condition_span: span,
body: then_body,
span,
}];
if !else_body.is_empty() {
arms.push(marqdo_ir::BranchArm {
condition: Expr::Bool(true),
condition_span: span,
body: else_body,
span,
});
}
out.push(Stmt::Branch { arms, span });
}
Payload::While(condition) => {
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, false);
if stop != Stop::End {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`while` is not closed by `end`",
);
} else {
*position += 1;
}
out.push(Stmt::Loop {
condition,
condition_span: span,
body,
span,
});
}
Payload::Return(value) => {
out.push(Stmt::Return {
value: value.clone(),
span: raw.span,
});
*position += 1;
}
Payload::Params => {
let duplicate = self.saw_params.is_some();
if !raw.direct {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` must be a direct payload, not inside a list or block quote",
);
} else if *position != 0 {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` must be the first payload of an Exec H2",
);
} else if duplicate {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` may be declared only once per function",
);
} else {
self.saw_params = Some(raw.span);
}
*position += 1;
}
Payload::Statement(statement) => {
let mut statement = statement.clone();
raw.segments.rewrite_statement(&mut statement);
let span = raw.span;
match statement.kind {
StatementKind::Assign { target, value } => out.push(Stmt::Assign {
target: match target {
AssignTarget::Local { name, name_span } => {
PlaceTarget::Local { name, name_span }
}
AssignTarget::Index {
base,
index,
span: target_span,
} => PlaceTarget::Index {
base: *base,
index: *index,
span: target_span,
},
},
value,
span,
}),
StatementKind::Expr(expr) => out.push(Stmt::Eval { expr, span }),
}
*position += 1;
}
}
}
(out, Stop::Eof)
}
}
/// Normalise a heading name (re-exported for callers that resolve link targets).
+21 -16
View File
@@ -311,40 +311,42 @@ mod extra_span_tests {
#[test]
fn condition_literal_span_excludes_backticks_for_one_and_two_ticks() {
for source in ["## f\n\n1. `n ** 2 ==`\n", "## f\n\n1. ``n ** 2 ==``\n"] {
for source in [
"## @exec f\n\n`if n ** 2 ==`\n",
"## @exec f\n\n``if n ** 2 ==``\n",
] {
let result = crate::analyze_source("index.mq.md", source);
let diagnostic = result
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == marqdo_value::codes::EXPR_PARSE)
.unwrap_or_else(|| panic!("no expr.parse diagnostic for {source:?}"));
.find(|diagnostic| diagnostic.code == marqdo_value::codes::SEM_SYNTAX)
.unwrap_or_else(|| panic!("no sem.syntax diagnostic for {source:?}"));
let span = diagnostic
.span
.expect("condition parse error has a source span");
assert_eq!(
source.as_bytes()[span.start],
b'`',
"span must stop before the closing backtick: {span:?} in {source:?}"
);
assert_eq!(
&source[span.start.saturating_sub(2)..span.start],
"==",
"span must point at the missing operand"
let condition = source.find("n ** 2 ==").expect("condition text");
let closing = source.rfind('`').expect("closing backtick");
assert!(
span.start >= condition && span.end <= closing,
"span must point inside the carrier payload, before the closing backtick: {span:?} in {source:?}"
);
}
}
#[test]
fn condition_description_rejects_executable_roles() {
// RFC-LANG-0002 no longer rejects Strong/Emph next to a code span:
// every carrier is an independent statement. The preserved intent is
// that a malformed control sequence after `if` is a hard error; it is
// repurposed as an unclosed-control negative.
for tail in ["**print(1)**", "*1*"] {
let source = format!("## f\n\n1. `n > 0` {tail}\n\n > print(1)\n");
let source = format!("## @exec f\n\n`if n > 0` {tail}\n");
let result = crate::analyze_source("index.mq.md", &source);
assert!(
result
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code
== marqdo_value::codes::MARKDOWN_INVALID_CONSTRUCT),
.any(|diagnostic| diagnostic.code == "sem.unclosed_control"),
"executable tail `{tail}` was not rejected: {:#?}",
result.diagnostics
);
@@ -353,7 +355,10 @@ mod extra_span_tests {
#[test]
fn condition_description_allows_inert_inline_content() {
let source = "## f\n\n**n = 1**\n\n1. `n > 0` 普通说明、`惰性代码` 与 [链接](#f)。\n\n > print(1)\n";
// Inline code spans are payload carriers in Exec scope, so the old inert
// `惰性代码` example is now a statement; prose, a link and a carrier-free
// block quote remain inert and must not be rejected.
let source = "## @exec f\n\n`n = 1`\n\n1. `n > 0` 普通说明与 [链接](#f)。\n\n > print(1)\n\n`return n`\n";
let result = crate::analyze_source("index.mq.md", source);
assert!(
!result.has_errors(),
+1 -1
View File
@@ -121,7 +121,7 @@ mod tests {
#[test]
fn formulas_and_code_are_attributed_to_functions() {
let resources = resources_of(
"# ns\n\n## f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## g\n\n$$B = 1$$\n",
"# @knowledge ns\n\n## @exec f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## @exec g\n\n$$B = 1$$\n",
);
assert_eq!(resources.len(), 3);
let Resource::Formula { unit, latex, .. } = &resources[0] else {
+60 -36
View File
@@ -42,37 +42,41 @@ pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Sig
match &block.kind {
MdKind::Heading { level, .. } if *level >= 3 => continue,
MdKind::Paragraph => {
let is_candidate = block.children.len() == 1
&& matches!(block.children[0].kind, MdKind::Code { .. })
&& block.children[0]
.literal
.as_deref()
.map(|text| text.trim_start().starts_with('('))
.unwrap_or(false);
if !is_candidate {
if block.children.len() != 1 {
continue;
}
let carrier = &block.children[0];
let (source, span, segments) = match &carrier.kind {
MdKind::Code { ticks } => {
let literal = carrier.literal.clone().unwrap_or_default();
let inner = Span::new(
carrier.span.start.saturating_add(*ticks),
carrier.span.end.saturating_sub(*ticks),
);
(
literal.clone(),
carrier.span,
PayloadSegments::single(&literal, inner),
)
}
MdKind::Strong | MdKind::Emph => match PayloadSegments::of(carrier) {
Ok((source, segments)) => (source, carrier.span, segments),
Err(_) => continue,
},
_ => continue,
};
if !source.trim_start().starts_with("params(") {
return None;
}
let code = &block.children[0];
let source = code.literal.clone().unwrap_or_default();
let mut signature = parse(&source, code.span);
// Rewrite parameter default expression spans onto the file.
let segments = PayloadSegments::of(&MdNode {
kind: MdKind::Strong,
span: code.span,
literal: None,
children: vec![code.clone()],
})
.ok()
.map(|(_, segments)| segments);
if let Some(segments) = segments {
for param in &mut signature.params {
if let Some(default) = &mut param.default {
segments.rewrite_expr(default);
}
let mut signature = parse(&source, span);
for param in &mut signature.params {
if let Some(default) = &mut param.default {
segments.rewrite_expr(default);
}
}
return Some((index, signature));
}
MdKind::List { .. } | MdKind::BlockQuote | MdKind::Item { .. } => continue,
_ => return None,
}
}
@@ -83,13 +87,33 @@ pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Sig
pub fn parse(source: &str, span: Span) -> Signature {
let mut diagnostics = Vec::new();
let trimmed = source.trim();
let inner = if let Some(rest) = trimmed.strip_prefix('(') {
let is_params = trimmed.starts_with("params(");
let syntax_code = if is_params {
codes::SEM_SYNTAX
} else {
codes::EXPR_PARSE
};
let inner = if let Some(rest) = trimmed.strip_prefix("params(") {
match rest.strip_suffix(')') {
Some(inner) => inner,
None => {
diagnostics.push(Diagnostic::error(
codes::SEM_SYNTAX,
Some(span),
"function signature must be closed by `)`",
));
rest
}
}
} else if let Some(rest) = trimmed.strip_prefix('(') {
// Plugin/ABI descriptors keep their existing parenthesised signature
// spelling; language payloads are detected only as `params(...)`.
rest.strip_suffix(')').unwrap_or(rest)
} else {
diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
"function signature must be parenthesised, e.g. `(r: Number)`",
"function signature must be `params(...)`, e.g. `params(r: Number)`",
));
trimmed
};
@@ -102,7 +126,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
if entry.trim().is_empty() {
if !inner.trim().is_empty() {
diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
"empty parameter in function signature",
));
@@ -129,7 +153,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
}
}
Err(message) => diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
format!("invalid function signature: {message}"),
)),
@@ -293,7 +317,7 @@ mod tests {
#[test]
fn parses_typed_signature_with_default() {
let signature = parse("(r: Number, precision: Int = 2)", Span::new(0, 38));
let signature = parse("params(r: Number, precision: Int = 2)", Span::new(0, 38));
assert!(!signature.has_errors(), "{:?}", signature.diagnostics);
assert_eq!(signature.params.len(), 2);
assert_eq!(signature.params[0].name, "r");
@@ -307,20 +331,20 @@ mod tests {
#[test]
fn parses_untyped_and_empty() {
let signature = parse("()", Span::new(0, 2));
let signature = parse("params()", Span::new(0, 8));
assert!(signature.params.is_empty());
assert!(!signature.has_errors());
let signature = parse("(n)", Span::new(0, 3));
let signature = parse("params(n)", Span::new(0, 9));
assert_eq!(signature.params[0].name, "n");
}
#[test]
fn rejects_duplicates_and_bad_defaults() {
let duplicate = parse("(a, a)", Span::new(0, 6));
let duplicate = parse("params(a, a)", Span::new(0, 12));
assert!(duplicate.has_errors());
let bad_default = parse("(a = f())", Span::new(0, 10));
let bad_default = parse("params(a = f())", Span::new(0, 16));
assert!(bad_default.has_errors());
let bad_name = parse("(1x)", Span::new(0, 4));
let bad_name = parse("params(1x)", Span::new(0, 10));
assert!(bad_name.has_errors());
}
+200 -101
View File
@@ -16,7 +16,7 @@
use std::collections::BTreeMap;
use marqdo_ir::{FunctionId, ModuleId, UnitId, UnitInfo, UnitKind};
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind};
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
@@ -35,6 +35,8 @@ pub struct HeadingInfo {
pub path: Vec<String>,
/// Role derived from level and position.
pub kind: UnitKind,
/// Semantic mode declared or inherited by this heading.
pub mode: SemanticMode,
}
/// A function range mapped from a level-2 heading.
@@ -93,6 +95,91 @@ impl UnitIndex {
}
}
fn has_payload(node: &MdNode) -> bool {
match &node.kind {
MdKind::Strong | MdKind::Emph | MdKind::Code { .. } => true,
MdKind::Paragraph | MdKind::List { .. } | MdKind::Item { .. } | MdKind::BlockQuote => {
node.children.iter().any(has_payload)
}
_ => false,
}
}
/// Build the heading/function index for a parsed document.
/// Semantic mode declared or inherited by a heading (RFC-LANG-0002).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemanticMode {
/// Document/knowledge region; no executable statements.
Knowledge,
/// Executable region; only an Exec H2 is callable.
Exec,
}
fn heading_declaration(
node: &MdNode,
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
let Some(first) = node.children.first() else {
return (None, None, None);
};
let MdKind::Text = first.kind else {
return (None, None, None);
};
let literal = first.literal.as_deref().unwrap_or_default();
let (mode, rest) = if let Some(rest) = literal.strip_prefix("@exec") {
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return (None, None, None);
}
(SemanticMode::Exec, rest)
} else if let Some(rest) = literal.strip_prefix("@knowledge") {
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return (None, None, None);
}
(SemanticMode::Knowledge, rest)
} else if literal.starts_with('@')
&& literal
.trim_start_matches('@')
.chars()
.next()
.is_some_and(char::is_alphabetic)
{
return (
None,
None,
Some(Diagnostic::error(
codes::SEM_INVALID_MODE_MARKER,
Some(first.span),
"unknown heading mode marker; use exactly `@exec` or `@knowledge`",
)),
);
} else {
return (None, None, None);
};
let title = rest.trim();
if title.is_empty() {
return (
Some(mode),
None,
Some(Diagnostic::error(
codes::SEM_EMPTY_UNIT_NAME,
Some(node.span),
"mode declaration has an empty heading name",
)),
);
}
if title.starts_with("@exec") || title.starts_with("@knowledge") {
return (
Some(mode),
None,
Some(Diagnostic::error(
codes::SEM_INVALID_MODE_MARKER,
Some(node.span),
"a heading may declare only one semantic mode",
)),
);
}
(Some(mode), Some(title.to_string()), None)
}
/// Build the heading/function index for a parsed document.
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let mut index = UnitIndex::default();
@@ -108,8 +195,8 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
function: None,
});
// Stack of (level, path) for ancestor headings with smaller level.
let mut stack: Vec<(u8, Vec<String>)> = Vec::new();
// Stack of (level, path, mode) for ancestors.
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new();
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
let mut current_namespace: Option<String> = None;
let mut current_function: Option<FunctionId> = None;
@@ -120,11 +207,26 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
continue;
};
let level = *level;
let raw_name = normalize_name(&plain_text(child));
let Some(name) = raw_name else {
let (declared, declared_name, declaration_error) = heading_declaration(child);
if let Some(error) = declaration_error {
index.diagnostics.push(error);
if declared_name.is_none() {
continue;
}
}
let inherited = stack
.last()
.map(|(_, _, mode)| *mode)
.unwrap_or(SemanticMode::Knowledge);
let mode = declared.unwrap_or(inherited);
let raw_name = match declared_name {
Some(name) => name,
None => plain_text(child),
};
let Some(name) = normalize_name(&raw_name) else {
index.diagnostics.push(
Diagnostic::error(
codes::MARKDOWN_INVALID_CONSTRUCT,
codes::SEM_EMPTY_UNIT_NAME,
Some(child.span),
"heading name must not be empty",
)
@@ -133,7 +235,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
continue;
};
while let Some((parent_level, _)) = stack.last() {
while let Some((parent_level, _, _)) = stack.last() {
if *parent_level >= level {
stack.pop();
} else {
@@ -142,7 +244,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
}
let parent_path = stack
.last()
.map(|(_, path)| path.clone())
.map(|(_, path, _)| path.clone())
.unwrap_or_default();
let path = {
let mut path = parent_path.clone();
@@ -150,14 +252,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
path
};
// Duplicate canonical names in the same scope are a hard error; never
// silently rename with -1/-2 suffixes.
let key = (parent_path.clone(), name.clone());
if let Some(previous) = seen.get(&key) {
let previous = *previous;
index.diagnostics.push(
Diagnostic::error(
codes::MARKDOWN_INVALID_CONSTRUCT,
codes::SEM_DUPLICATE_UNIT_NAME,
Some(child.span),
format!("duplicate heading name `{name}` in the same scope"),
)
@@ -170,14 +270,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let kind = match level {
1 => UnitKind::Namespace,
2 => UnitKind::Function,
2 if mode == SemanticMode::Exec => UnitKind::Function,
2 => UnitKind::Knowledge,
_ => UnitKind::Section,
};
if level == 1 {
current_namespace = Some(name.clone());
current_function = None;
}
let function = if level == 2 {
if level >= 3 && mode == SemanticMode::Exec && current_function.is_none() {
index.diagnostics.push(
Diagnostic::error(
codes::SEM_EXEC_WITHOUT_FUNCTION,
Some(child.span),
"executable section has no owning Exec H2 function",
)
.with_hint("put the section under an Exec H2, or mark it @knowledge"),
);
}
let function = if level == 2 && mode == SemanticMode::Exec {
let local = name.clone();
let qualified = match &current_namespace {
Some(namespace) => format!("{namespace}.{local}"),
@@ -189,9 +300,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
};
current_function = Some(id.clone());
Some(id)
} else if level >= 3 {
} else if level >= 3 && mode == SemanticMode::Exec {
current_function.clone()
} else {
if level <= 2 {
current_function = None;
}
None
};
@@ -202,6 +316,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
span: child.span,
path: path.clone(),
kind,
mode,
};
let unit_id = UnitId {
module: module.clone(),
@@ -215,12 +330,40 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
kind,
function,
});
if level == 1 && mode == SemanticMode::Exec {
// H1 Exec: direct-body carriers before the next heading have no
// owning H2 function. A Knowledge H2 body is inert (inline code
// there is documentation), and Exec H3 sections are checked above.
let mut scan = node_index + 1;
while scan < doc.root.children.len() {
if let MdKind::Heading { .. } = doc.root.children[scan].kind {
break;
}
if has_payload(&doc.root.children[scan]) {
index.diagnostics.push(Diagnostic::error(
codes::SEM_EXEC_WITHOUT_FUNCTION,
Some(doc.root.children[scan].span),
"executable payload has no owning Exec H2 function",
));
break;
}
scan += 1;
}
}
heading_infos.push(info.clone());
stack.push((level, info.path.clone()));
stack.push((level, info.path.clone(), mode));
}
// Function body ranges and spans.
for heading in heading_infos.iter().filter(|h| h.level == 2) {
// A Knowledge H2 has no function range.
if !index
.units
.iter()
.any(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
{
continue;
}
let body_start = heading.node_index + 1;
let body_end = doc.root.children[body_start..]
.iter()
@@ -239,33 +382,23 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
} else {
heading.span
};
let local_name = heading.name.clone();
let namespace = match heading.path.len() {
0 => None,
_ if heading.path.len() == 1 => None,
_ => Some(heading.path[0].clone()),
};
let namespace = namespace.filter(|_| {
index
.units
.iter()
.any(|unit| unit.kind == UnitKind::Namespace && unit.name == heading.path[0])
});
let qualified = match &namespace {
Some(namespace) => format!("{namespace}.{local_name}"),
None => local_name.clone(),
let unit = index
.units
.iter()
.find(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
.expect("function unit exists");
let FunctionId { name, .. } = unit.function.clone().expect("function id");
let local_name = name.rsplit('.').next().unwrap_or(&name).to_string();
let namespace = if name.contains('.') {
Some(name.rsplit_once('.').unwrap().0.to_string())
} else {
None
};
index.functions.push(FunctionScope {
id: FunctionId {
module: module.clone(),
name: qualified,
},
id: unit.function.clone().unwrap(),
local_name,
namespace,
unit: UnitId {
module: module.clone(),
path: heading.path.clone(),
},
unit: unit.id.clone(),
heading_span: heading.span,
body_start,
body_end,
@@ -273,67 +406,34 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
});
}
// Warnings for would-be execution nodes outside every function body.
for (node_index, child) in doc.root.children.iter().enumerate() {
if index.function_containing_block(node_index).is_some() {
for heading in &heading_infos {
let Some(unit) = index.units.iter().find(|unit| unit.id.path == heading.path) else {
continue;
};
let slug = github_slug(&heading.name);
if slug.is_empty() {
continue;
}
let mut warn = |span: Span, what: &str| {
index.diagnostics.push(
Diagnostic::warning(
codes::MARKDOWN_INERT_EXECUTABLE,
Some(span),
format!("{what} outside a function body is inert document content"),
)
.with_hint("move it under a level-2 heading (`## 函数名`) to execute it"),
);
};
match &child.kind {
MdKind::BlockQuote => warn(child.span, "a block quote invocation"),
MdKind::List { .. } => warn(child.span, "a list control structure"),
MdKind::Paragraph => {
let mut found: Option<(Span, &'static str)> = None;
child.walk(&mut |node| {
if found.is_none() {
match node.kind {
MdKind::Strong => found = Some((node.span, "an execution statement")),
MdKind::Emph => found = Some((node.span, "a return statement")),
_ => {}
}
}
});
if let Some((span, what)) = found {
warn(span, what);
let mut count = index.anchors.keys().filter(|key| *key == &slug).count();
let key = if count == 0 {
slug.clone()
} else {
loop {
count += 1;
let candidate = format!("{slug}-{count}");
if !index.anchors.contains_key(&candidate) {
break candidate;
}
}
_ => {}
}
}
// Derive GitHub-style anchors for navigation and `ref("#...")`. Anchors are
// not identity: they may collide and receive -1/-2 suffixes exactly like
// GitHub's slugger, while internal ids stay canonical.
let mut slug_counts: BTreeMap<String, usize> = BTreeMap::new();
for unit in &index.units {
if unit.level == 0 {
continue;
}
let base = github_slug(&unit.name);
if base.is_empty() {
continue;
}
let count = slug_counts.entry(base.clone()).or_insert(0);
let slug = if *count == 0 {
base
} else {
format!("{base}-{count}")
};
*count += 1;
index.anchors.insert(slug, unit.id.clone());
index.anchors.insert(key, unit.id.clone());
}
index.headings = heading_infos;
index
.diagnostics
.dedup_by(|a, b| a.code == b.code && a.span == b.span && a.message == b.message);
index
}
/// GitHub-style heading slug, kept in a separate namespace from canonical
@@ -366,7 +466,7 @@ mod tests {
#[test]
fn builds_function_ranges() {
let index = index_of(
"# 命名空间\n\n## 阶乘\n\n**x = 1**\n\n### 小节\n\n正文\n\n## 下一个\n\n*y*\n",
"# @knowledge 命名空间\n\n## @exec 阶乘\n\n`x = 1`\n\n### 小节\n\n正文\n\n## @exec 下一个\n\n`return y`\n",
);
assert_eq!(index.functions.len(), 2);
assert_eq!(index.functions[0].local_name, "阶乘");
@@ -380,7 +480,7 @@ mod tests {
#[test]
fn root_level_function_without_namespace() {
let index = index_of("## main\n\n> 打印(1)\n");
let index = index_of("## @exec main\n\n`打印(1)`\n");
assert_eq!(index.functions.len(), 1);
assert_eq!(index.functions[0].id.name, "main");
assert!(index.functions[0].namespace.is_none());
@@ -389,16 +489,16 @@ mod tests {
#[test]
fn empty_heading_is_an_error() {
let index = index_of("## \n\n正文\n");
let index = index_of("## @exec\n\n正文\n");
assert!(index
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT && d.message.contains("empty")));
.any(|d| d.code == "sem.empty_unit_name" && d.message.contains("empty")));
}
#[test]
fn duplicate_function_names_are_errors() {
let index = index_of("## f\n\n## f\n");
let index = index_of("## @exec f\n\n## @exec f\n");
let errors = index
.diagnostics
.iter()
@@ -409,7 +509,7 @@ mod tests {
#[test]
fn same_name_in_different_namespaces_is_allowed() {
let index = index_of("# a\n\n## f\n\n# b\n\n## f\n");
let index = index_of("# @knowledge a\n\n## @exec f\n\n# @knowledge b\n\n## @exec f\n");
let duplicates = index
.diagnostics
.iter()
@@ -423,11 +523,10 @@ mod tests {
#[test]
fn executable_outside_function_warns_but_does_not_execute() {
let index = index_of("**x = 1**\n\n## f\n\n*y*\n");
assert!(index
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INERT_EXECUTABLE));
// RFC-LANG-0002: a Strong at the Knowledge root is inert prose with no
// diagnostic; only an Exec H2 is a callable function.
let index = index_of("**x = 1**\n\n## @exec f\n\n`return y`\n");
assert!(index.diagnostics.is_empty());
assert_eq!(index.functions.len(), 1);
}
}