feat: block formula meta bind and control-flow prose

Support $$ % marqdo: var= binding, arm/loop narrative (fix comment-paragraph
swallow of branch arms), foreach ZH/EN sugar, and condition-line narrative.
Welcome pages and gold samples updated; view skips meta formula fence bodies.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-15 15:28:46 +08:00
1 parent f99d552d87
commit 9cf98a98b5
17 files changed
+706 -58

No files matched your search

+3 -1
View File
@@ -114,7 +114,9 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `` ```lang `` | Foreign code block (via `lib/foreign`); bind with `` `name` = `` then fence |
| `$$` + `% marqdo: var=name` | Block formula bind (TeX comment; prefer over empty RHS) |
| `- [item](coll)` | Foreach (**preferred**, nestable). Sugar: `- 对`coll`的每一项`item`` / `- for each `item` in `coll`` |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment |
@@ -0,0 +1,60 @@
# 块公式元数据绑定 · 控制流叙述统一
| | |
|---|---|
| 状态 | Active |
| 日期 | 2026-10-15 |
| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 块公式 `% marqdo: var=`
在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体):
```markdown
$$
% marqdo: var=f
x^2 - 2
$$
```
- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。
- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。
- **保留**旧空 RHS + 后随 `$$`。
- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。
- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。
无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。
---
## 2. 臂 / 循环体叙述(与函数体同权)
`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。
斜体返回结束**当前臂或当前循环体**,不结束外层函数。
---
## 3. 循环头
| 面 | 写法 | 说明 |
|----|------|------|
| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 |
| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 |
| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` |
糖与链接头语义相同,可混用嵌套。
---
## 4. 分支条件行叙述
结构行仍以 `1.` / `2.` 开头。条件提取顺序:
1. 整段可解析为表达式(现状);
2. 行内粗体代码条件 `**`n` > 0**`;
3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。
else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。
禁止无标记自然语言整句当条件。
+3 -1
View File
@@ -215,7 +215,9 @@ v0.3:
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
| ` ```lang ` | 外联(不变) |
| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) |
| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) |
| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` |
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
+14 -4
View File
@@ -34,7 +34,16 @@
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)):
````markdown
$$
% marqdo: var=f
sin(x) + x
$$
````
**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致):
````markdown
# main
@@ -52,13 +61,14 @@ $$
也支持:
- 单行围栏:下一行 `$$x^2 - 2$$`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面)
- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ ``
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。
### 2.3 从文本构造
+2 -2
View File
@@ -19,10 +19,10 @@ Want a quick hello? Calls only run when they sit in the entry `# main` — `##`
Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention.
Bind a formula to `f` like this:
Write a math block and bind it with a TeX comment:
`f` =
$$
% marqdo: var=f
x^2 - 2
$$
+2 -2
View File
@@ -19,10 +19,10 @@ English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English
除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。
比方说,先给公式起个名字`f`:
比方说,直接写一块公式,并用 TeX 注释标上变量名:
`f` =
$$
% marqdo: var=f
x^2 - 2
$$
+50 -1
View File
@@ -279,7 +279,36 @@ fn breaks_comment_paragraph(trimmed: &str) -> bool {
if trimmed.starts_with('#') || trimmed.starts_with('>') {
return true;
}
is_marqdo_star_line(trimmed)
if is_marqdo_star_line(trimmed) {
return true;
}
// Branch arms / loops / params must not be swallowed after prose in an arm body.
if looks_like_ordered_list_item(trimmed) {
return true;
}
if trimmed.starts_with("- ") || trimmed.starts_with("-\t") || trimmed == "-" {
return true;
}
if trimmed.starts_with('+') {
return true;
}
false
}
fn looks_like_ordered_list_item(trimmed: &str) -> bool {
let mut chars = trimmed.chars();
let mut saw_digit = false;
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
saw_digit = true;
continue;
}
if c == '.' && saw_digit {
return true;
}
return false;
}
false
}
/// Classify a single logical line (no trailing newline required).
@@ -439,6 +468,26 @@ pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String {
mod tests {
use super::*;
#[test]
fn ordered_arm_breaks_prose_paragraph() {
let src = "\
# main\n\
\n\
1. `n` > 0\n\
此时我们 **打印 内容=\"正\"**\n\
2. *\n\
否则 **打印 内容=\"非正\"**\n\
";
let lines = classify_source(src);
let l12 = lines.iter().find(|l| l.text.trim() == "2. *").expect("2. *");
assert_eq!(
l12.kind,
LineKind::Code,
"else arm must stay Code after prose, got dump:\n{}",
format_lines_dump("t", &lines)
);
}
#[test]
fn blank_and_comment_and_code() {
assert_eq!(classify_line(""), LineKind::Blank);
+411 -30
View File
@@ -358,6 +358,13 @@ impl<'a> Cursor<'a> {
continue;
}
if self.peek_is_formula_fence() {
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
fun.body.push(stmt);
continue;
}
}
if is_ordered_branch(trimmed) {
fun.body.push(self.parse_branch()?);
continue;
@@ -405,9 +412,10 @@ impl<'a> Cursor<'a> {
}
if trimmed.starts_with("$$") {
// Standalone meta formulas are handled before parse_simple_stmt.
bail!(
"{span}: formula fence must follow an empty assignment (`name` =); \
`$$:name` binding was removed"
"{span}: formula fence must follow an empty assignment (`name` =) \
or include `% marqdo: var=name` inside the block"
);
}
@@ -503,7 +511,7 @@ impl<'a> Cursor<'a> {
if crate::aliases::is_reserved_keyword(&name) {
bail!("{span}: `{name}` is a reserved keyword");
}
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
return Ok(Stmt::Assign {
name,
value,
@@ -544,7 +552,7 @@ impl<'a> Cursor<'a> {
if crate::aliases::is_reserved_keyword(&name) {
bail!("{span}: `{name}` is a reserved keyword");
}
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
Ok(Stmt::Assign {
name,
value,
@@ -570,7 +578,7 @@ impl<'a> Cursor<'a> {
return Ok(None);
}
let rhs = after[1..].trim().to_string();
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, false)?;
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, false)?;
Ok(Some(Stmt::Assign {
name,
value,
@@ -584,6 +592,7 @@ impl<'a> Cursor<'a> {
/// `prefer_var`: italic RHS uses variable-preferring expression syntax.
fn resolve_assign_rhs(
&mut self,
assign_name: &str,
rhs: &str,
span: Span,
prefer_var: bool,
@@ -592,7 +601,9 @@ impl<'a> Cursor<'a> {
if rhs.is_empty() {
self.skip_blanks();
if self.peek_is_formula_fence() {
return self.consume_formula_fence(span);
let (expr, end_line, meta_var) = self.consume_formula_fence(span)?;
check_formula_meta_var(assign_name, meta_var.as_deref(), span)?;
return Ok((expr, end_line));
}
if self.peek_is_code_fence() {
return self.consume_code_fence(span);
@@ -698,7 +709,8 @@ impl<'a> Cursor<'a> {
))
}
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32)> {
/// Consume `$$…$$`. Returns `(expr, end_line, optional var from % marqdo: var=)`.
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32, Option<String>)> {
let open = self
.bump()
.ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?;
@@ -707,7 +719,7 @@ impl<'a> Cursor<'a> {
if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") {
bail!(
"{open_line}:1: `$$:name` / `$$ name=` binding was removed; \
use `name` = then a `$$…$$` fence"
use `% marqdo: var=name` inside `$$…$$` or `name` = then a fence"
);
}
// Single-line: $$body$$
@@ -716,15 +728,21 @@ impl<'a> Cursor<'a> {
if body.is_empty() {
bail!("{open_line}:1: empty formula");
}
let (meta_var, tex) = strip_formula_marqdo_meta(body)
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
if tex.is_empty() {
bail!("{open_line}:1: empty formula");
}
return Ok((
formula_fence_to_expr(body)
formula_fence_to_expr(&tex)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?,
open_line,
meta_var,
));
}
if trimmed != "$$" {
bail!(
"{open_line}:1: expected `$$` fence opener after empty assignment, got: {trimmed}"
"{open_line}:1: expected `$$` fence opener, got: {trimmed}"
);
}
let mut body_lines: Vec<String> = Vec::new();
@@ -743,13 +761,45 @@ impl<'a> Cursor<'a> {
if !closed {
bail!("{open_line}:1: unclosed formula fence `$$`");
}
let text = body_lines.join("\n").trim().to_string();
if text.is_empty() {
let raw = body_lines.join("\n");
let (meta_var, tex) = strip_formula_marqdo_meta(&raw)
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
if tex.is_empty() {
bail!("{open_line}:1: empty formula");
}
let expr = formula_fence_to_expr(&text)
let expr = formula_fence_to_expr(&tex)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
Ok((expr, end_line))
Ok((expr, end_line, meta_var))
}
/// Standalone `$$` with `% marqdo: var=` → Assign (no empty RHS required).
fn try_parse_meta_formula_assign(&mut self) -> Result<Option<Stmt>> {
if !self.peek_is_formula_fence() {
return Ok(None);
}
let Some(l) = self.peek() else {
return Ok(None);
};
let span = Span {
line: l.line_no,
col: 1,
};
let (value, end_line, meta_var) = self.consume_formula_fence(span)?;
let Some(name) = meta_var else {
bail!(
"{span}: formula fence must follow an empty assignment (`name` =) \
or include `% marqdo: var=name` inside the block"
);
};
if crate::aliases::is_reserved_keyword(&name) {
bail!("{span}: `{name}` is a reserved keyword");
}
Ok(Some(Stmt::Assign {
name,
value,
span,
end_line,
}))
}
/// GFM table after empty RHS:
@@ -878,11 +928,7 @@ impl<'a> Cursor<'a> {
let cond_src = strip_ordered(trimmed).unwrap();
self.bump();
let condition = if cond_src == "*" || cond_src.is_empty() {
None
} else {
Some(parse_expr_str(cond_src)?)
};
let condition = parse_branch_condition(cond_src)?;
let body = self.parse_indented_body(base_indent)?;
arms.push(BranchArm { condition, body });
@@ -904,8 +950,10 @@ impl<'a> Cursor<'a> {
let trimmed = line.text.trim();
let rest = trimmed.strip_prefix('-').unwrap().trim();
// foreach: [item](collection)
if let Some((item, coll)) = parse_foreach_header(rest) {
// foreach: [item](collection) or narrative sugar
if let Some((item, coll)) = parse_foreach_header(rest)
.or_else(|| parse_foreach_narrative(rest))
{
let body = self.parse_indented_body(base_indent)?;
return Ok(Stmt::ForEach {
item,
@@ -931,7 +979,7 @@ impl<'a> Cursor<'a> {
let Some(l) = self.peek() else { break };
let ind = indent_of(&l.text);
if ind <= parent_indent {
// Same-indent `+`/`-` ends body (next arm / sibling).
// Same-indent `2.` / `-` ends body (next arm / sibling).
break;
}
let trimmed = l.text.trim();
@@ -951,6 +999,39 @@ impl<'a> Cursor<'a> {
body.push(self.parse_loop_or_err()?);
continue;
}
// Same prose rights as function body (fixes arm/loop narrative escape).
if self.peek_is_prose() {
let line = self.bump().unwrap();
let span = Span {
line: line.line_no,
col: 1,
};
let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n']));
let mut end_arm = false;
for bit in bits {
match bit {
ProseBit::Decl { .. } => {}
ProseBit::BoldCode { inner, .. } => {
body.push(self.stmt_from_bold_inner(&inner, span.clone())?);
}
ProseBit::ItalicReturn { inner, .. } => {
body.push(stmt_from_italic_return(&inner, span.clone())?);
end_arm = true;
break;
}
}
}
if end_arm {
break;
}
continue;
}
if self.peek_is_formula_fence() {
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
body.push(stmt);
continue;
}
}
let stmt = self.parse_simple_stmt()?;
let end_arm = matches!(stmt, Stmt::Return { .. });
body.push(stmt);
@@ -998,26 +1079,101 @@ fn is_bare_assign_ident(s: &str) -> bool {
true
}
/// Same-line `$$body$$` → Formula or numeric matrix List; otherwise None.
/// Same-line `$$body$$` or `$body$` → Formula; otherwise None.
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
let rhs = rhs.trim();
if !rhs.starts_with("$$") {
return Ok(None);
}
if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") {
bail!(
"`$$:name` / `$$ name=` binding was removed; use `name` = then a `$$…$$` fence"
"`$$:name` / `$$ name=` binding was removed; use `% marqdo: var=name` \
inside `$$…$$` or `name` = then a fence"
);
}
if rhs.ends_with("$$") && rhs.len() > 4 {
let body = rhs[2..rhs.len() - 2].trim();
if rhs.starts_with("$$") {
if rhs.ends_with("$$") && rhs.len() > 4 {
let body = rhs[2..rhs.len() - 2].trim();
if body.is_empty() {
bail!("empty formula");
}
let (_meta, tex) = strip_formula_marqdo_meta(body)
.map_err(|e| anyhow::anyhow!("{e}"))?;
if tex.is_empty() {
bail!("empty formula");
}
let expr = formula_fence_to_expr(&tex).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
return Ok(Some(expr));
}
bail!("incomplete inline formula (expected `$$…$$` on one line)");
}
// Traditional inline: $…$ (not $$)
if rhs.starts_with('$') && rhs.ends_with('$') && rhs.len() > 2 && !rhs.starts_with("$$") {
let body = rhs[1..rhs.len() - 1].trim();
if body.is_empty() {
bail!("empty formula");
}
if body.contains('%') && body.to_lowercase().contains("marqdo:") {
bail!(
"inline `$…$` must not use `% marqdo:` (breaks Markdown/TeX); \
bind with `name` = $…$ or use a `$$` block with `% marqdo: var=`"
);
}
let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
return Ok(Some(expr));
}
bail!("incomplete inline formula (expected `$$…$$` on one line)");
Ok(None)
}
/// Strip `% marqdo: var=name` directive lines from formula fence body.
/// Returns `(optional var name, remaining TeX)`.
fn strip_formula_marqdo_meta(body: &str) -> Result<(Option<String>, String), String> {
let mut meta_var: Option<String> = None;
let mut out: Vec<&str> = Vec::new();
for line in body.lines() {
let t = line.trim();
if let Some(rest) = t.strip_prefix('%') {
let rest = rest.trim_start();
if rest.to_ascii_lowercase().starts_with("marqdo:") {
let after = rest["marqdo:".len()..].trim_start();
let mut got_var = false;
for part in after.split_whitespace() {
if let Some(v) = part.strip_prefix("var=") {
if v.is_empty() {
return Err("% marqdo: var= requires a name".into());
}
if !is_bare_assign_ident(v) {
return Err(format!("invalid marqdo var name `{v}`"));
}
if meta_var.as_deref() == Some(v) || meta_var.is_none() {
meta_var = Some(v.to_string());
} else {
return Err(format!(
"conflicting % marqdo: var= ({} vs {v})",
meta_var.as_deref().unwrap_or("")
));
}
got_var = true;
} else {
return Err(format!("unknown marqdo key `{part}` (only var= is supported)"));
}
}
if !got_var {
return Err("% marqdo: requires var=<name>".into());
}
continue; // strip directive line
}
}
out.push(line);
}
Ok((meta_var, out.join("\n").trim().to_string()))
}
fn check_formula_meta_var(assign_name: &str, meta: Option<&str>, span: Span) -> Result<()> {
match meta {
None => Ok(()),
Some(v) if v == assign_name => Ok(()),
Some(v) => bail!(
"{span}: formula `% marqdo: var={v}` conflicts with assignment `{assign_name}`"
),
}
}
fn formula_fence_to_expr(body: &str) -> Result<Expr, String> {
@@ -1112,6 +1268,148 @@ fn parse_foreach_header(rest: &str) -> Option<(String, String)> {
Some((item, coll))
}
/// Narrative foreach sugar (recommended remains `- [item](coll)`).
/// - ZH: `对`xs`的每一项`项`` optional `遍历`
/// - EN: `for each `item` in `xs``
fn parse_foreach_narrative(rest: &str) -> Option<(String, String)> {
let rest = rest.trim();
if let Some(after) = rest.strip_prefix('对') {
let (coll, after) = take_backtick_token(after.trim_start())?;
let after = after.trim_start().strip_prefix("的每一项")?;
let (item, after) = take_backtick_token(after.trim_start())?;
let after = after
.trim()
.trim_end_matches('。')
.trim();
let after = after.strip_prefix("遍历").unwrap_or(after).trim();
if after.is_empty() {
return Some((item, coll));
}
return None;
}
let lower = rest.to_ascii_lowercase();
let Some(idx) = lower.find("for each ") else {
return None;
};
if idx != 0 {
return None;
}
let after = rest["for each ".len()..].trim_start();
let (item, after) = take_backtick_token(after)?;
let after = after.trim_start();
let after_l = after.to_ascii_lowercase();
if !after_l.starts_with("in ") && !after_l.starts_with("in\t") {
// require ` in `
let Some(in_at) = after_l.find("in ") else {
return None;
};
if in_at != 0 {
return None;
}
}
let after = after["in ".len()..].trim_start();
let (coll, after) = take_backtick_token(after)?;
if after.trim().is_empty() {
return Some((item, coll));
}
None
}
fn take_backtick_token(s: &str) -> Option<(String, &str)> {
let s = s.trim_start();
if !s.starts_with('`') {
return None;
}
let end = s[1..].find('`')?;
let name = s[1..1 + end].to_string();
if name.is_empty() {
return None;
}
Some((name, &s[1 + end + 1..]))
}
/// Branch arm condition: expr, bold code, narrative (当`n`大于 0 时), or else `*`.
fn parse_branch_condition(cond_src: &str) -> Result<Option<Expr>> {
let t = cond_src.trim();
if t.is_empty() || t == "*" {
return Ok(None);
}
// "否则 *" / "else *"
if let Some(before) = t.strip_suffix('*') {
let before = before.trim();
if before.is_empty()
|| before == "否则"
|| before == "其它"
|| before == "其他"
|| before.eq_ignore_ascii_case("else")
|| before.eq_ignore_ascii_case("otherwise")
{
return Ok(None);
}
}
if let Ok(e) = parse_expr_str(t) {
return Ok(Some(e));
}
if let Some(inner) = extract_first_bold_inner(t) {
if let Ok(e) = parse_expr_str(inner.trim()) {
return Ok(Some(e));
}
}
if let Some(e) = try_narrative_condition(t) {
return Ok(Some(e));
}
bail!(
"branch condition: cannot parse `{t}` \
(use an expression, **`n` > 0**, or 当`n`大于 0 时)"
)
}
fn extract_first_bold_inner(s: &str) -> Option<&str> {
let start = s.find("**")?;
let rest = &s[start + 2..];
let end = rest.find("**")?;
Some(&rest[..end])
}
fn try_narrative_condition(s: &str) -> Option<Expr> {
let mut s = s.trim();
for p in ["当且仅当", "当", "若", "如果"] {
if let Some(r) = s.strip_prefix(p) {
s = r.trim_start();
break;
}
}
let lower = s.to_ascii_lowercase();
if let Some(r) = lower.strip_prefix("when ") {
let _ = r;
s = s[5..].trim_start();
} else if let Some(r) = lower.strip_prefix("if ") {
let _ = r;
s = s[3..].trim_start();
}
for suf in ["的话", "时", "则"] {
if let Some(r) = s.strip_suffix(suf) {
s = r.trim_end();
}
}
let mut mapped = s.to_string();
let replacements = [
("大于等于", ">="),
("小于等于", "<="),
("不等于", "!="),
("等于", "=="),
("大于", ">"),
("小于", "<"),
];
for (zh, op) in replacements {
if mapped.contains(zh) {
mapped = mapped.replace(zh, op);
break;
}
}
parse_expr_str(mapped.trim()).ok()
}
fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
if !trimmed.starts_with('#') {
return None;
@@ -1882,6 +2180,89 @@ mod tests {
use super::*;
use crate::ast::Stmt;
#[test]
fn parse_formula_meta_var_standalone() {
let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n";
let m = parse_source(src).unwrap();
match &m.functions[0].body[0] {
Stmt::Assign { name, value, .. } => {
assert_eq!(name, "f");
assert!(matches!(value, Expr::Formula(_)));
}
other => panic!("expected formula assign, got {other:?}"),
}
}
#[test]
fn parse_formula_meta_conflicts_with_assign() {
let src = "# main\n\n`f` =\n$$\n% marqdo: var=g\nx\n$$\n";
let err = parse_source(src).unwrap_err().to_string();
assert!(
err.contains("conflicts") || err.contains("var=g"),
"{err}"
);
}
#[test]
fn parse_foreach_narrative_zh_en() {
let src = "# main\n\n- 对`xs`的每一项`项`\n > print text=`项`\n\n- for each `item` in `ys`\n > print text=`item`\n";
let m = parse_source(src).unwrap();
match &m.functions[0].body[0] {
Stmt::ForEach { item, collection, .. } => {
assert_eq!(item, "项");
assert_eq!(collection, "xs");
}
other => panic!("zh foreach: {other:?}"),
}
match &m.functions[0].body[1] {
Stmt::ForEach { item, collection, .. } => {
assert_eq!(item, "item");
assert_eq!(collection, "ys");
}
other => panic!("en foreach: {other:?}"),
}
}
#[test]
fn branch_arm_prose_stays_inside_arm() {
let src = include_str!("../../tests/markup-v03/branch-arm-prose.mq.md");
let m = parse_source(src).unwrap();
let main = &m.functions[0];
let branches: Vec<_> = main
.body
.iter()
.filter(|s| matches!(s, Stmt::Branch { .. }))
.collect();
assert_eq!(
branches.len(),
1,
"expected one Branch, body={:?}",
main.body
);
match &main.body[1] {
Stmt::Branch { arms, .. } => {
assert_eq!(arms.len(), 2, "arms={arms:?}");
assert!(
!arms[0].body.is_empty(),
"then arm must contain prose stmts: {:?}",
arms[0].body
);
assert!(
!arms[1].body.is_empty(),
"else arm must contain prose stmts: {:?}",
arms[1].body
);
}
other => panic!("expected Branch as body[1] after assign, got {other:?}"),
}
// No Call/Assign print siblings after the branch
assert!(
!main.body.iter().skip(2).any(|s| matches!(s, Stmt::Call { .. } | Stmt::Assign { .. })),
"prose escaped branch: {:?}",
main.body
);
}
#[test]
fn parse_hello() {
let src = include_str!("../../tests/structure/hello.mq.md");
+22 -17
View File
@@ -974,13 +974,14 @@ fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialA
name,
value: crate::ast::Expr::Formula(e),
span,
end_line,
..
} => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => source.clone(),
_ => crate::view::render::formula_ascii_to_tex_pub(&e.as_display()),
};
let end_line = fence_block_end(src_lines, span.line, "$$");
let end_line = (*end_line).max(fence_block_end(src_lines, span.line, "$$"));
m.insert(
span.line,
SpecialAssign::Formula {
@@ -994,9 +995,10 @@ fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialA
name,
value: crate::ast::Expr::Code(c),
span,
end_line,
..
} => {
let end_line = fence_block_end(src_lines, span.line, "```");
let end_line = (*end_line).max(fence_block_end(src_lines, span.line, "```"));
m.insert(
span.line,
SpecialAssign::Code {
@@ -1018,16 +1020,25 @@ fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialA
/// Inclusive end line of a `$$` / ` ``` ` block starting on or after `assign_line`.
fn fence_block_end(src_lines: &[&str], assign_line: u32, fence: &str) -> u32 {
let start = assign_line as usize; // 1-based → index of next line candidate
if start == 0 || start > src_lines.len() {
if assign_line == 0 || assign_line as usize > src_lines.len() {
return assign_line;
}
let mut i = start; // 0-based index of line after assign (assign_line is 1-based)
// Allow fence on the assign line itself after `=`.
let assign = src_lines.get(assign_line as usize - 1).copied().unwrap_or("");
if assign.contains(fence) && fence == "$$" {
// rare one-liner
let assign = src_lines[assign_line as usize - 1].trim();
// Meta formula: assign span is the opening `$$` line itself.
if fence == "$$" && assign == "$$" {
let mut i = assign_line as usize; // 0-based next line
while i < src_lines.len() {
if src_lines[i].trim() == "$$" {
return (i + 1) as u32;
}
i += 1;
}
return assign_line;
}
if fence == "$$" && assign.starts_with("$$") && assign.ends_with("$$") && assign.len() > 4 {
return assign_line;
}
let mut i = assign_line as usize; // 0-based index of line after assign
let mut seen_open = false;
while i < src_lines.len() {
let t = src_lines[i].trim();
@@ -1036,18 +1047,13 @@ fn fence_block_end(src_lines: &[&str], assign_line: u32, fence: &str) -> u32 {
if t.starts_with(fence) {
seen_open = true;
if fence == "```" && t == "```" {
// closing without open — stop
return line_no;
}
// opening ```lang or $$
if fence == "$$" && t == "$$" {
// look for closing $$
i += 1;
while i < src_lines.len() {
let t2 = src_lines[i].trim();
let ln = (i + 1) as u32;
if t2 == "$$" {
return ln;
if src_lines[i].trim() == "$$" {
return (i + 1) as u32;
}
i += 1;
}
@@ -1057,7 +1063,6 @@ fn fence_block_end(src_lines: &[&str], assign_line: u32, fence: &str) -> u32 {
i += 1;
continue;
} else {
// no fence body
return assign_line;
}
} else if fence == "```" && t.starts_with("```") {
+30
View File
@@ -3365,3 +3365,33 @@ fn markup_v03_decl_ident_only() {
fn markup_v03_bold_expr() {
assert_out_v03("tests/markup-v03/bold-expr.mq.md", "42");
}
#[test]
fn markup_v03_formula_meta_var() {
assert_out_v03("tests/markup-v03/formula-meta-var.mq.md", "x^2 - 2");
}
#[test]
fn markup_v03_inline_dollar_formula() {
assert_out_v03("tests/markup-v03/inline-dollar-formula.mq.md", "x + 1");
}
#[test]
fn markup_v03_branch_arm_prose() {
assert_out_v03("tests/markup-v03/branch-arm-prose.mq.md", "正");
}
#[test]
fn markup_v03_branch_cond_narrative() {
assert_out_v03("tests/markup-v03/branch-cond-narrative.mq.md", "正");
}
#[test]
fn markup_v03_foreach_narrative() {
assert_out_v03("tests/markup-v03/foreach-narrative.mq.md", "a\nb\n1\n2");
}
#[test]
fn markup_v03_foreach_nested_link() {
assert_out_v03("tests/markup-v03/foreach-nested-link.mq.md", "x\ny");
}
+2
View File
@@ -17,6 +17,8 @@
代码即文档叙述面(G1–G4):`module-hr` / `soft-emphasis` / `float-discount` / `dynamic-footnote` —— 设计见 [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。
块公式 meta / 控制流叙述:`formula-meta-var` / `inline-dollar-formula` / `branch-arm-prose` / `branch-cond-narrative` / `foreach-narrative` / `foreach-nested-link` —— 见 [fence-meta-and-control-prose.md](../../doc/design/fence-meta-and-control-prose.md)。
```bash
cargo test --test gold markup_v03
marqdo run tests/markup-v03/inc-prose.mq.md
+15
View File
@@ -0,0 +1,15 @@
---
title: v0.3 分支臂内叙述
description: 臂内 prose 不得逃逸;n>0 时仅 then
---
# main
**n = 1**
1. `n` > 0
此时`n`为正,我们 **打印 内容="正"**
2. *
否则 **打印 内容="非正"**
*None*
@@ -0,0 +1,15 @@
---
title: v0.3 条件行夹叙述
description: 当`n`大于 0 时 / 否则 *
---
# main
**n = 1**
1. 当`n`大于 0 时
我们 **打印 内容="正"**
2. 否则 *
我们 **打印 内容="非正"**
*None*
+28
View File
@@ -0,0 +1,28 @@
---
title: v0.3 循环头叙述糖
description: 对`xs`的每一项`项` / for each `item` in `ys`
---
# main
`xs` =
| v |
|---|
| a |
| b |
- 对`xs`的每一项`项`
**打印 内容=`项`**
`ys` =
| v |
|---|
| 1 |
| 2 |
- for each `item` in `ys`
**print text=`item`**
*None*
@@ -0,0 +1,25 @@
---
title: v0.3 推荐循环头嵌套
description: `- [o](外层)` 内再 `- [i](内层)`
---
# main
`外层` =
| a |
|---|
| x |
| y |
`内层` =
| b |
|---|
| 1 |
- [o](外层)
- [i](内层)
**print text=`o`**
*None*
+14
View File
@@ -0,0 +1,14 @@
---
title: v0.3 块公式 % marqdo: var=
description: 无空 RHS;块内 TeX 注释绑定 formula
import math:lib/math.mq.md
---
# main
$$
% marqdo: var=f
x^2 - 2
$$
**print text=`f`**
@@ -0,0 +1,10 @@
---
title: v0.3 行内 $ 传统绑定
description: `g` = $x+1$ → formula(无 % marqdo)
---
# main
`g` = $x + 1$
**print text=`g`**