Support footnote indexing inside interpolated call args and strings

Parse `` `var`[^key] `` in `` *…* `` segments and quoted strings as an
Index part (chained `` [^a][^b] `` folds into one part) in both the
tree-walk interpreter and the bytecode compiler, and render it back in
`view`. Also make bytecode `_type` stamping always overwrite like the
interpreter does, so child constructors yield the most specific type.

Adds gold/unit tests for interp footnote indexing and a bytecode
inherit-explicit-super case.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-24 14:45:56 +08:00
1 parent d7924ea8c7
commit b84e82eb56
10 files changed
+247 -6

No files matched your search

+1
View File
@@ -32,6 +32,7 @@ positional ::= value_token
- `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。
- `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。
- 实参值中 `` `变量` `` 后**紧跟** `[^…]` 时按**脚注取元**解析(可链式),而非文本:`> print text=苹果单价:`水果价格`[^苹果]`、`> print text=`订单`[^2][^品名]`。
- **独立 `>` 调用**:裸词 = 文本字面量。
- **`*…*` / `**…**` 段内的调用**(如 `*x = > text.split value=src sep=","*`):裸词 = **变量**(Python 统一命名空间),文本字面量必须加引号(`value="a,b"`);`` `名` `` 变量形式仍合法。
- 内置 `print` / `打印` 形参:`text` ≡ `内容`。
+1
View File
@@ -302,6 +302,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
- **List**:标签须为纯数字(1-based);`[^0]` / 越界 → 报错。
- **Map**:标签为键文本(含 `"00"` 这类数字串键);缺键 → 报错。同一外形按接收值类型分派,不把 map 上的 `[^1]` 当成「第 1 个条目」。
- 基名:`` `名`[^键] `` 与 `` 名[^键] `` 等价;无 `` [^ `` 时裸词仍是**文本字面量**(不是变量)。
- **插值中的取元**:在调用实参值 / 引号字符串里,`` `变量` `` 后**紧跟**(无空白)`` [^…] `` 时按取元解析,而不是字面文本:`> print text=苹果单价:`水果价格`[^苹果]`;链式 `` `货架`[^苹果][^1] `` 同理。`` `变量` [^…] ``(有空白)则 `` [^…] `` 仍是文本。
- 文末 `[^1]: …` 定义块仍是注释,与取元无关。
- foreach:`List` 遍历元素;`Map` 遍历**键**(值用脚注取)。
+3
View File
@@ -159,6 +159,9 @@ pub enum Expr {
pub enum InterpPart {
Lit(String),
Var(String),
/// `` `base`[^label] `` — variable followed by footnote index inside interpolated
/// text (chained labels fold into one part, e.g. `` `x`[^a][^b] `` → two labels).
Index { base: String, labels: Vec<String> },
}
#[derive(Debug, Clone)]
+13
View File
@@ -830,6 +830,19 @@ impl<'a> FnCompiler<'a> {
.ok_or_else(|| self.err(format!("undefined variable `{n}`")))?;
self.emit(Op::GetLocal(slot));
}
InterpPart::Index { base, labels } => {
let slot = self
.locals
.get(base)
.copied()
.ok_or_else(|| self.err(format!("undefined variable `{base}`")))?;
self.emit(Op::GetLocal(slot));
for label in labels {
let li = self.add_const(Value::Text(label.clone()));
self.emit(Op::Constant(li));
self.emit(Op::FootnoteGet);
}
}
}
if idx > 0 {
self.emit(Op::Add);
+4 -3
View File
@@ -658,9 +658,10 @@ fn instance_type_name_bc(v: &Value) -> Result<String, String> {
fn tag_instance_value(type_name: &str, value: Value) -> Value {
match value {
Value::Map(mut entries) => {
if !entries.iter().any(|(k, _)| k == "_type") {
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
}
// Always stamp the constructed type so an explicit `` `self` = > Parent ``
// inside a child constructor still yields the most specific `_type`.
entries.retain(|(k, _)| k != "_type");
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
Value::Map(entries)
}
Value::None => Value::Map(vec![("_type".into(), Value::Text(type_name.into()))]),
+9
View File
@@ -449,6 +449,15 @@ impl Interpreter {
.ok_or_else(|| self.err(format!("undefined variable `{n}`")))?;
s.push_str(&v.as_display());
}
InterpPart::Index { base, labels } => {
let mut v = env.get(base).cloned().ok_or_else(|| {
self.err(format!("undefined variable `{base}`"))
})?;
for label in labels {
v = builtin_footnote_get(&v, label).map_err(|m| self.err(m))?;
}
s.push_str(&v.as_display());
}
}
}
Ok(Value::Text(s))
+138 -3
View File
@@ -169,8 +169,14 @@ pub fn parse_interp(s: &str) -> Expr {
let after = &rest[start + 1..];
if let Some(end) = after.find('`') {
let name = after[..end].to_string();
parts.push(InterpPart::Var(name));
rest = &after[end + 1..];
let mut tail = &after[end + 1..];
// `` `name`[^a][^b] `` → Index part (chained labels fold).
if let Some(labels) = take_index_chain(&mut tail) {
parts.push(InterpPart::Index { base: name, labels });
} else {
parts.push(InterpPart::Var(name));
}
rest = tail;
} else {
parts.push(InterpPart::Lit(format!("`{after}")));
break;
@@ -184,11 +190,46 @@ pub fn parse_interp(s: &str) -> Expr {
match &parts[0] {
InterpPart::Lit(t) => return Expr::Literal(Literal::Text(t.clone())),
InterpPart::Var(n) => return Expr::Var(n.clone()),
InterpPart::Index { base, labels } => {
let mut e = Expr::Var(base.clone());
for label in labels {
e = Expr::Index {
base: Box::new(e),
label: label.clone(),
};
}
return e;
}
}
}
Expr::Interp(parts)
}
/// If `s` starts with one or more `[^label]` (no whitespace), consume them.
fn take_index_chain(s: &mut &str) -> Option<Vec<String>> {
let mut labels = Vec::new();
loop {
if !s.starts_with("[^") {
break;
}
let after_open = &s[2..];
let Some(close) = after_open.find(']') else {
break;
};
let label = after_open[..close].trim().to_string();
if label.is_empty() {
break;
}
labels.push(label);
*s = &after_open[close + 1..];
}
if labels.is_empty() {
None
} else {
Some(labels)
}
}
struct Parser<'a> {
src: &'a str,
i: usize,
@@ -568,7 +609,12 @@ impl<'a> Parser<'a> {
if !self.eat("`") {
bail!("unterminated `name` in string");
}
parts.push(InterpPart::Var(name));
// `` `name`[^a][^b] `` inside a quoted string → footnote index parts.
if let Some(labels) = self.take_index_chain_in_string()? {
parts.push(InterpPart::Index { base: name, labels });
} else {
parts.push(InterpPart::Var(name));
}
continue;
}
lit.push(c);
@@ -584,11 +630,56 @@ impl<'a> Parser<'a> {
return Ok(match parts.remove(0) {
InterpPart::Lit(t) => Expr::Literal(Literal::Text(t)),
InterpPart::Var(n) => Expr::Var(n),
InterpPart::Index { base, labels } => {
let mut e = Expr::Var(base);
for label in labels {
e = Expr::Index {
base: Box::new(e),
label,
};
}
e
}
});
}
Ok(Expr::Interp(parts))
}
/// In quoted strings, consume `[^label]` chains following `` `var` ``.
fn take_index_chain_in_string(&mut self) -> Result<Option<Vec<String>>> {
let mut labels = Vec::new();
loop {
if !self.starts_with("[^") {
break;
}
self.bump_char();
self.bump_char(); // consume `[^`
let start = self.i;
while let Some(ch) = self.peek_char() {
if ch == ']' {
break;
}
if ch == '\n' || ch == '\r' {
bail!("unterminated footnote index [^…] in string");
}
self.bump_char();
}
let label = self.src[start..self.i].trim().to_string();
if !self.eat("]") {
bail!("unterminated footnote index [^…] in string");
}
if label.is_empty() {
bail!("empty footnote index `[^]` in string");
}
labels.push(label);
}
if labels.is_empty() {
Ok(None)
} else {
Ok(Some(labels))
}
}
/// Parse `[^label]` after a value; label is text until `]`.
fn parse_footnote_label(&mut self) -> Result<String> {
if !self.eat("[^") {
@@ -972,6 +1063,50 @@ mod tests {
Expr::Literal(Literal::None)
));
}
#[test]
fn interp_footnote_index_after_var() {
// `前缀`x`[^key]` → Interp([Lit, Index])
let e = parse_interp("前缀`m`[^苹果]");
match &e {
Expr::Interp(parts) => {
assert!(matches!(&parts[0], InterpPart::Lit(t) if t == "前缀"));
assert!(matches!(
&parts[1],
InterpPart::Index { base, labels } if base == "m" && labels == &["苹果".to_string()]
));
}
other => panic!("expected Interp, got {other:?}"),
}
// Bare `m`[^key] with no prefix → Expr::Index
let e = parse_interp("`m`[^苹果]");
assert!(matches!(e, Expr::Index { label, .. } if label == "苹果"));
// Chained labels fold into one Index part with multiple labels.
let e = parse_interp("`m`[^a][^b]");
match &e {
Expr::Index { base, label } => {
assert!(matches!(base.as_ref(), Expr::Index { label: l, .. } if l == "a"));
assert_eq!(label, "b");
}
other => panic!("expected chained Index, got {other:?}"),
}
// `x`[^key] with plain Var text when no `[^` follows.
let e = parse_interp("`m` 和 `n`");
assert!(matches!(e, Expr::Interp(_)));
}
#[test]
fn interp_footnote_index_keeps_text_between() {
// `x` followed by whitespace then [^...] → [^...] stays literal text.
let e = parse_interp("`m` [^苹果]");
match &e {
Expr::Interp(parts) => {
assert!(matches!(&parts[0], InterpPart::Var(n) if n == "m"));
assert!(matches!(&parts[1], InterpPart::Lit(t) if t == " [^苹果]"));
}
other => panic!("expected Interp, got {other:?}"),
}
}
}
+10
View File
@@ -1296,6 +1296,16 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
s.push_str(n);
s.push('`');
}
InterpPart::Index { base, labels } => {
s.push('`');
s.push_str(base);
s.push('`');
for label in labels {
s.push_str("[^");
s.push_str(label);
s.push(']');
}
}
}
}
s
+34
View File
@@ -95,6 +95,17 @@ Ada",
);
}
#[test]
fn bytecode_inherit_explicit_super() {
assert_out_backend(
"tests/structure/inherit-explicit-super.mq.md",
"bytecode",
"Child
child
Ada",
);
}
#[test]
fn structure_nested_call() {
assert_out("tests/structure/nested-call.mq.md", "Hello World!");
@@ -207,6 +218,29 @@ other",
);
}
#[test]
fn structure_interp_footnote_index() {
assert_out(
"tests/structure/interp-footnote-index.mq.md",
"苹果单价:5
第一种:红富士 结尾
引号内:\"价 3 元\"
梨 × 3",
);
}
#[test]
fn bytecode_interp_footnote_index() {
assert_out_backend(
"tests/structure/interp-footnote-index.mq.md",
"bytecode",
"苹果单价:5
第一种:红富士 结尾
引号内:\"价 3 元\"
梨 × 3",
);
}
#[test]
fn structure_collection_records() {
assert_out(
@@ -0,0 +1,34 @@
---
title: 插值中脚注取元(前缀 + `var`[^key])
description: 独立 > 调用实参与引号字符串内,`前缀`var`[^key]` 的取元应生效。
---
# main
`水果价格` =
| 苹果 | 香蕉 |
|------|------|
| 5 | 3 |
> print text=苹果单价:`水果价格`[^苹果]
`货架` =
| 苹果 | 黄瓜 |
|------|------|
| 红富士 | 青瓜 |
| 嘎啦 | 黄瓜条 |
> print text=第一种:`货架`[^苹果][^1] 结尾
> print text=引号内:"价 `水果价格`[^香蕉] 元"
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
| 2 | 梨 | 3 |
> print text=`订单`[^2][^品名] × `订单`[^2][^数量]