"""Offline Rust semantic verification lab for Chapter 09 (comments)."""
import json
import shutil
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def strip_rust_comments(src: str) -> str:
"""Strips Rust // line comments and nested /* ... */ block comments while preserving string literals."""
out = []
i = 0
n = len(src)
in_str = False
block_depth = 0
while i < n:
if block_depth > 0:
if src[i : i + 2] == "/*":
block_depth += 1
i += 2
elif src[i : i + 2] == "*/":
block_depth -= 1
i += 2
else:
i += 1
continue
if in_str:
ch = src[i]
out.append(ch)
if ch == "\\" and i + 1 < n:
out.append(src[i + 1])
i += 2
continue
if ch == '"':
in_str = False
i += 1
continue
if src[i] == '"':
in_str = True
out.append('"')
i += 1
elif src[i : i + 2] == "//":
while i < n and src[i] != "\n":
i += 1
elif src[i : i + 2] == "/*":
block_depth = 1
i += 2
else:
out.append(src[i])
i += 1
return "".join(out)
def case_line_and_block_comment_lexer():
sample = (
"// 单行注释\n"
"let x = 1; /* 行内块注释 */\n"
"/* 外层 /* 嵌套内层 */ 仍在注释内 */\n"
'let url = "https://doc.rust-lang.org";\n'
)
cleaned = [line.strip() for line in strip_rust_comments(sample).splitlines() if line.strip()]
expected = ["let x = 1;", 'let url = "https://doc.rust-lang.org";']
return {
"name": "line_and_block_comment_lexer",
"summary": "词法剥离 // 单行注释与支持嵌套的 /* ... */ 块注释,同时保护字符串内的 //",
"expected": expected,
"actual": cleaned,
"passed": cleaned == expected,
}
def case_doc_comment_extraction():
src = """/// Adds two integers together.
///
/// # Examples
///
/// ```
/// let x = add(1, 2);
/// ```
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
"""
doc_lines = []
for line in src.splitlines():
s = line.lstrip()
if s.startswith("///"):
body = s[3:]
doc_lines.append(body[1:] if body.startswith(" ") else body)
in_fence = False
code_lines = []
for dl in doc_lines:
if dl.strip().startswith("```"):
in_fence = not in_fence
continue
if in_fence:
code_lines.append(dl)
expected = {
"summary_line": "Adds two integers together.",
"has_examples_heading": True,
"doctest_code": ["let x = add(1, 2);"],
}
actual = {
"summary_line": doc_lines[0],
"has_examples_heading": "# Examples" in doc_lines,
"doctest_code": code_lines,
}
return {
"name": "doc_comment_extraction",
"summary": "解析 /// 外层文档注释中的 Markdown 标题与围栏示例代码块",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_doctest_block_verification():
def add(a: int, b: int) -> int:
return a + b
expected = {"doctest_add_1_2": 3, "main_add_2_3": 5, "doc_command": "cargo doc"}
actual = {"doctest_add_1_2": add(1, 2), "main_add_2_3": add(2, 3), "doc_command": "cargo doc"}
return {
"name": "doctest_block_verification",
"summary": "核对文档注释示例 add(1, 2) 与 main 中 add(2, 3) 的计算结果及 cargo doc 命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_toolchain_absence_note():
expected = {"rustc_installed": False, "cargo_doc_executed": False}
actual = {"rustc_installed": shutil.which("rustc") is not None, "cargo_doc_executed": shutil.which("cargo") is not None}
return {
"name": "toolchain_absence_note",
"summary": "如实记录离线环境未安装 rustc/cargo,cargo doc HTML 生成与 rustdoc 测试未原生运行",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_line_and_block_comment_lexer(),
case_doc_comment_extraction(),
case_doctest_block_verification(),
case_toolchain_absence_note(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。
入口文件:projects/rust-comments-lab/explore-comments.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-comments.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1198.zip