"""Offline Rust semantic verification lab for Chapter 05 (println)."""
import json
import shutil
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def rust_format(template: str, *args) -> str:
"""Minimal Rust format_args! evaluator supporting {}, {n}, {{ and }}."""
out = []
i = 0
auto_idx = 0
n = len(template)
while i < n:
ch = template[i]
if ch == "{":
if i + 1 < n and template[i + 1] == "{":
out.append("{")
i += 2
continue
end = template.find("}", i + 1)
if end == -1:
raise ValueError("unclosed '{' in format string")
spec = template[i + 1 : end]
if spec == "":
if auto_idx >= len(args):
raise IndexError("not enough positional arguments")
out.append(str(args[auto_idx]))
auto_idx += 1
elif spec.isdigit():
idx = int(spec)
if idx >= len(args):
raise IndexError(f"argument index {idx} out of range")
out.append(str(args[idx]))
else:
raise ValueError(f"unsupported placeholder spec: {spec!r}")
i = end + 1
elif ch == "}":
if i + 1 < n and template[i + 1] == "}":
out.append("}")
i += 2
continue
raise ValueError("unmatched '}' in format string")
else:
out.append(ch)
i += 1
return "".join(out)
def case_print_vs_println_newline():
p1 = rust_format("a is {}", 12)
p2 = p1 + "\n"
expected = {
"print_output": "a is 12",
"println_output": "a is 12\n",
"println_ends_with_lf": True,
"rustc_installed": False,
}
actual = {
"print_output": p1,
"println_output": p2,
"println_ends_with_lf": p2.endswith("\n") and not p1.endswith("\n"),
"rustc_installed": shutil.which("rustc") is not None,
}
return {
"name": "print_vs_println_newline",
"summary": "对比 print! 与 println! 宏在末尾换行符上的差异及单占位符格式化结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_positional_and_repeated_placeholders():
seq_form = rust_format("a is {}, a again is {}", 12, 12)
idx_form = rust_format("a is {0}, a again is {0}", 12)
reordered = rust_format("{1}-{0}-{1}", "A", "B")
expected = {
"sequential": "a is 12, a again is 12",
"indexed": "a is 12, a again is 12",
"reordered": "B-A-B",
}
actual = {"sequential": seq_form, "indexed": idx_form, "reordered": reordered}
return {
"name": "positional_and_repeated_placeholders",
"summary": "验证顺序 {} 与 0 基下标 {0}、{1} 重复引用可变参数的等价输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_brace_and_backslash_escapes():
braces = rust_format("{{}}")
mixed = rust_format("{{{0}}}", 42)
backslash_text = rust_format("line1\n\t\"{}\"", "ok")
expected = {
"escaped_empty_braces": "{}",
"wrapped_value": "{42}",
"escaped_newline_tab_quote": 'line1\n\t"ok"',
}
actual = {
"escaped_empty_braces": braces,
"wrapped_value": mixed,
"escaped_newline_tab_quote": backslash_text,
}
return {
"name": "brace_and_backslash_escapes",
"summary": "验证 {{ 与 }} 转义输出花括号字面量以及 \\n、\\t、\\\" 反斜杠转义行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_format_argument_validation():
errors = {}
for label, tpl, args in [
("missing_arg", "{} {}", (1,)),
("oob_index", "{2}", (10, 20)),
("unclosed_brace", "{", ()),
("unmatched_close", "}", ()),
]:
try:
rust_format(tpl, *args)
errors[label] = "unexpected_ok"
except (IndexError, ValueError) as exc:
errors[label] = type(exc).__name__
expected = {
"missing_arg": "IndexError",
"oob_index": "IndexError",
"unclosed_brace": "ValueError",
"unmatched_close": "ValueError",
}
return {
"name": "format_argument_validation",
"summary": "验证格式字符串占位符数量不足、越界索引及未闭合花括号在解析期即被拒绝",
"expected": expected,
"actual": errors,
"passed": errors == expected,
}
def main():
cases = [
case_print_vs_println_newline(),
case_positional_and_repeated_placeholders(),
case_brace_and_backslash_escapes(),
case_format_argument_validation(),
]
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-println-lab/explore-println.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-println.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1215.zip