fix(parse): D9 未闭合引号不再静默吞行(分类层 + 解析层双层修复)

缺陷:`**s = "abc`(引号未闭合)被静默当成叙述丢弃,退出码 0,
没有输出也没有报错,该行凭空消失。对「文档即程序」来说这是最危险的一类
错误——文档看起来完整、能跑、check 通过,实际少了一节。

根因在**分类层**而不是解析层:
parse_quoted_string 里 `unterminated " string` 的报错一直都在,
但 matching_bold_close 扫描时遇到未闭合的 '"' 后一直处于 in_str 状态,
再也找不到收尾 '**',于是 is_marqdo_star_line 返回 false,
该行被判为 LineKind::Comment 成为叙述,解析器根本看不到它。
解析层精心准备的报错不可达。

修复(两层,缺一不可):
1. src/lex/mod.rs
   - 新增 pub fn has_unterminated_string:统计未被 \ 转义的 '"',奇数即「开了没收」
   - is_marqdo_star_line:粗体起始且找不到收尾时,若引号未闭合则仍判 Code
     (判 Comment 会静默丢行;判 Code 才能让解析器说话)
2. src/parse/mod.rs
   - parse_simple_stmt 紧跟既有粗体分支之后,对「粗体起始 + 引号未闭合」
     给出精确报错,而不是笼统的 unrecognized statement

影响面(改前量化,避免凭直觉改核心解析):
- 全仓库 845 个 .mq.md、620 个含代码行文件
- 引号计数为奇数的代码行:**0**
- 结论:不改变任何现有文件的解析结果,只作用于畸形输入

测试(TDD,先写测试确认失败再修):
- 新增 4 个单测:未闭合→Code、闭合→Code、叙述含引号→Comment、
  叙述含孤立引号→Comment
- 修复前 unterminated_quote_inside_bold_is_code_not_comment 如期失败
- 修复后 lex 14/14;cargo test --lib 237 passed 0 failed(基线 233 + 新增 4)
- cargo test --test gold 276 passed 8 failed;git stash 验证基线同样 8 failed,
  失败全部是 ext_web_*(依赖 Go 插件 libweb,本机环境不具备),与本次无关

文档:
- doc/design/parser-diagnostics-d8-d9.md  设计依据、根因链路、候选方案评判、影响面
- doc/design/change-d9-unterminated-string.md  变更记录(现象/根因/改法/测试/边界)
- doc/design/spaced-function-names-d8.md  D8 方案评估(待审阅,未改代码)

已知边界:单引号 '...' 未闭合仍是旧行为,留作后续评估
(单引号兼作英文撇号,误判风险高于双引号)。
This commit is contained in:
cflmy committed 2026-10-22 11:52:27 +08:00
1 parent ecd7d5e433
commit b6629e5450
5 files changed
+685 -2

No files matched your search

+65 -1
View File
@@ -138,7 +138,14 @@ fn is_marqdo_star_line(trimmed: &str) -> bool {
if trimmed.trim() == "** **" {
return true;
}
return matching_bold_close(trimmed).is_some();
if matching_bold_close(trimmed).is_some() {
return true;
}
// D9: a bold-starting line whose string literal is never closed has no
// findable closing `**` -- the scanner stays "inside the string" forever.
// Classifying it as Comment would silently drop the line; treat it as
// Code so the parser can report `unterminated " string`.
return has_unterminated_string(trimmed);
}
if !trimmed.starts_with('*') || trimmed.len() < 2 {
return false;
@@ -146,6 +153,29 @@ fn is_marqdo_star_line(trimmed: &str) -> bool {
matching_italic_close(trimmed).is_some()
}
/// True when `line` contains an odd number of unescaped double quotes,
/// i.e. a string literal that is opened but never closed.
///
/// Used only by [`is_marqdo_star_line`] to keep a malformed bold line in the
/// Code class so the parser surfaces the error (D9). Prose lines never reach
/// here -- they do not start with `**`.
pub fn has_unterminated_string(line: &str) -> bool {
let bytes = line.as_bytes();
let mut i = 0usize;
let mut count = 0usize;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => {
count += 1;
i += 1;
}
_ => i += 1,
}
}
count % 2 == 1
}
/// Closing `**` for a bold segment, skipping strings and backticks.
/// Returns the index within `trimmed` of the first `*` of the closing `**`.
/// When `require_eol`, the closing `**` must be the last non-ws on the line (whole-line code).
@@ -605,6 +635,40 @@ mod tests {
assert!(lines.iter().any(|l| l.kind == LineKind::Code));
}
#[test]
fn unterminated_quote_inside_bold_is_code_not_comment() {
// D9: "**s = \"abc" has an unclosed string. Classification must keep it
// as Code so the parser reports "unterminated \" string" instead of
// silently demoting the line to narration.
let lines = classify_source("**s = \"abc\n");
let code = lines.iter().find(|l| l.text.contains("abc"));
assert!(
matches!(code.map(|l| l.kind), Some(LineKind::Code)),
"expected Code (so parser reports the error), got {lines:?}"
);
}
#[test]
fn balanced_quote_inside_bold_still_code() {
let lines = classify_source("**s = \"abc\"**\n");
let code = lines.iter().find(|l| l.text.contains("abc"));
assert!(matches!(code.map(|l| l.kind), Some(LineKind::Code)));
}
#[test]
fn prose_with_quotes_stays_comment() {
// Narration that merely mentions quotes must stay narration.
let lines = classify_source("他说 \"你好\",然后走了。\n");
assert!(matches!(lines.first().map(|l| l.kind), Some(LineKind::Comment)));
}
#[test]
fn prose_bold_emphasis_with_quote_stays_comment() {
// **强调** with a stray quote in surrounding prose is still narration.
let lines = classify_source("这一句有 \" 引号但不是代码。\n");
assert!(matches!(lines.first().map(|l| l.kind), Some(LineKind::Comment)));
}
#[test]
fn math_fence_body_stays_code() {
let lines = classify_source("`f` =\n$$\nx^2 - 2\n$$\n");
+12 -1
View File
@@ -15,7 +15,7 @@ use crate::ast::{
BranchArm, Expr, Function, Import, IndexKey, Literal, Module, Param, Stmt, Use,
};
use crate::diagnostics::{bail_at, Diagnostic, Span};
use crate::lex::{classify_source, ClassifiedLine, LineKind};
use crate::lex::{ClassifiedLine, LineKind, classify_source, has_unterminated_string};
use crate::parse::expr::parse_call_after_gt as call_after_gt;
use crate::parse::expr::parse_call_tail;
use crate::parse::expr::parse_expr as parse_expr_str;
@@ -433,6 +433,17 @@ impl<'a> Cursor<'a> {
return self.stmt_from_bold_inner(inner, span);
}
// D9: bold code whose string literal is never closed. The line reaches
// this point (classifier keeps it Code) but has no closing `**`, so the
// generic "unrecognized statement" would hide the real cause.
if trimmed.starts_with("**") && has_unterminated_string(trimmed) {
bail!(
"{span}: unterminated string: this line starts bold code but \
contains an odd number of `\"` -- close the string and the \
trailing `**` (line: {trimmed})"
);
}
// v0.3: *…* = return
if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") {
let inner = &trimmed[1..trimmed.len() - 1];