"""Offline Rust semantic verifier for Chapter 20: Error Handling (panic!, Result, ?, ErrorKind, custom AppError, Option)."""
from dataclasses import dataclass
import json
from pathlib import Path
import tempfile
from typing import Any
class RustPanic(Exception):
pass
@dataclass(frozen=True)
class Ok:
value: Any
def is_ok(self) -> bool:
return True
def unwrap(self) -> Any:
return self.value
def expect(self, _msg: str) -> Any:
return self.value
def ok(self) -> tuple[str, Any]:
return ("Some", self.value)
@dataclass(frozen=True)
class Err:
error: Any
def is_ok(self) -> bool:
return False
def unwrap(self) -> Any:
raise RustPanic(f"called `Result::unwrap()` on an `Err` value: {self.error}")
def expect(self, msg: str) -> Any:
raise RustPanic(f"{msg}: {self.error}")
def ok(self) -> tuple[str, Any]:
return ("None", None)
@dataclass(frozen=True)
class IoError:
kind: str
message: str
def __str__(self) -> str:
return f"{self.kind}: {self.message}"
@dataclass(frozen=True)
class AppError:
variant: str
detail: str
def display(self) -> str:
prefixes = {"IoError": "IO 错误", "ParseError": "解析错误", "CustomError": "业务错误"}
return f"{prefixes[self.variant]}: {self.detail}"
@classmethod
def from_io(cls, err: IoError) -> "AppError":
return cls("IoError", str(err))
@classmethod
def from_parse(cls, detail: str) -> "AppError":
return cls("ParseError", detail)
def open_and_read(path: Path) -> Ok | Err:
try:
return Ok(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return Err(IoError("NotFound", str(path.name)))
except PermissionError:
return Err(IoError("PermissionDenied", str(path.name)))
def process_config(path: Path) -> Ok | Err:
# Emulates `?` operator with From<io::Error> and From<ParseIntError> -> AppError
res = open_and_read(path)
if isinstance(res, Err):
return Err(AppError.from_io(res.error))
raw = res.value.strip()
try:
val = int(raw)
except ValueError:
return Err(AppError.from_parse(f"invalid digit found in string `{raw}`"))
if val < 0:
return Err(AppError("CustomError", "配置值不能为负数"))
return Ok(val)
def find_user(uid: int) -> tuple[str, Any]:
return {1: ("Some", "Alice"), 2: ("Some", "Bob")}.get(uid, ("None", None))
def opt_ok_or(opt: tuple[str, Any], err: Any) -> Ok | Err:
return Ok(opt[1]) if opt[0] == "Some" else Err(err)
def run_cases() -> list[dict]:
cases = []
# Case 1: panic!, unwrap(), and expect() failure messages
unwrap_msg = ""
expect_msg = ""
err_res = Err(IoError("NotFound", "hello.txt"))
try:
err_res.unwrap()
except RustPanic as exc:
unwrap_msg = str(exc)
try:
err_res.expect("无法打开配置文件")
except RustPanic as exc:
expect_msg = str(exc)
actual_1 = {
"unwrap_has_default": "called `Result::unwrap()` on an `Err` value" in unwrap_msg,
"expect_has_custom": expect_msg.startswith("无法打开配置文件:"),
"ok_unwrap": Ok(42).unwrap(),
}
expected_1 = {
"unwrap_has_default": True,
"expect_has_custom": True,
"ok_unwrap": 42,
}
cases.append(dict(
name="panic_unwrap_and_expect_behavior",
summary="Verify Ok::unwrap returns value while Err::unwrap/expect panic with default vs custom messages",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Result match, if let, and io::ErrorKind dispatch
with tempfile.TemporaryDirectory() as tmp:
tp = Path(tmp)
existing = tp / "hello.txt"
existing.write_text("rust-ok", encoding="utf-8")
missing = tp / "missing.txt"
r_ok = open_and_read(existing)
r_missing = open_and_read(missing)
def classify_kind(kind: str) -> str:
return {
"NotFound": "文件不存在,请检查路径",
"PermissionDenied": "没有权限读取该文件",
"AlreadyExists": "文件已存在(创建时)",
"ConnectionRefused": "连接被拒绝",
"TimedOut": "操作超时",
"InvalidInput": "参数无效",
}.get(kind, "其他错误")
actual_2 = {
"existing_ok": r_ok.is_ok() and r_ok.unwrap() == "rust-ok",
"missing_kind": r_missing.error.kind if isinstance(r_missing, Err) else None,
"not_found_msg": classify_kind(r_missing.error.kind) if isinstance(r_missing, Err) else "",
"all_six_kinds_mapped": all(
classify_kind(k) != "其他错误"
for k in ("NotFound", "PermissionDenied", "AlreadyExists", "ConnectionRefused", "TimedOut", "InvalidInput")
),
}
expected_2 = {
"existing_ok": True,
"missing_kind": "NotFound",
"not_found_msg": "文件不存在,请检查路径",
"all_six_kinds_mapped": True,
}
cases.append(dict(
name="result_match_and_error_kind_dispatch",
summary="Verify Result Ok/Err matching on real temp files and io::ErrorKind classification",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: ? propagation + From trait conversion into custom AppError
good_cfg = tp / "good.txt"
good_cfg.write_text(" 2026\n", encoding="utf-8")
bad_parse = tp / "bad_parse.txt"
bad_parse.write_text("abc", encoding="utf-8")
neg_cfg = tp / "neg.txt"
neg_cfg.write_text("-7", encoding="utf-8")
res_good = process_config(good_cfg)
res_io = process_config(missing)
res_parse = process_config(bad_parse)
res_neg = process_config(neg_cfg)
actual_3 = {
"good": res_good.unwrap() if isinstance(res_good, Ok) else None,
"io_variant": res_io.error.variant if isinstance(res_io, Err) else None,
"parse_variant": res_parse.error.variant if isinstance(res_parse, Err) else None,
"custom_display": res_neg.error.display() if isinstance(res_neg, Err) else "",
}
expected_3 = {
"good": 2026,
"io_variant": "IoError",
"parse_variant": "ParseError",
"custom_display": "业务错误: 配置值不能为负数",
}
cases.append(dict(
name="question_mark_and_custom_app_error",
summary="Verify ? early-return propagation and From conversion across IoError, ParseError, and CustomError",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
# Case 4: Option<T> vs Result<T, E> and ok_or / ok conversions
u1 = find_user(1)
u99 = find_user(99)
name_default = u99[1] if u99[0] == "Some" else "匿名用户"
first_char = ("Some", "hello"[0]) if "hello" else ("None", None)
converted_res = opt_ok_or(u99, "missing_user")
converted_opt = Ok("Alice").ok()
actual_4 = {
"u1": list(u1),
"u99_unwrap_or": name_default,
"first_char": list(first_char),
"ok_or_is_err": isinstance(converted_res, Err) and converted_res.error == "missing_user",
"result_ok_to_option": list(converted_opt),
}
expected_4 = {
"u1": ["Some", "Alice"],
"u99_unwrap_or": "匿名用户",
"first_char": ["Some", "h"],
"ok_or_is_err": True,
"result_ok_to_option": ["Some", "Alice"],
}
cases.append(dict(
name="option_and_result_interconversion",
summary="Verify Option<T> lookup, unwrap_or default, chars().next(), ok_or(), and Result::ok()",
expected=expected_4,
actual=actual_4,
passed=actual_4 == expected_4,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/rust-error-handle-lab/explore-error-handle.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-error-handle.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1203.zip