"""Offline Rust semantic verification lab for Chapter 02 (intro)."""
import json
import shutil
import threading
import tomllib
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def case_ownership_move_and_borrow():
heap = {"s1": "Hello, Rust!"}
# Move s1 -> s2
heap["s2"] = heap.pop("s1")
s1_moved = "s1" not in heap
# Copy i32
x = 42
y = x
# Multiple shared borrows
readers = [heap["s2"], heap["s2"]]
# Exclusive mutable borrow
data = ["rust"]
data.append("!")
mutated = "".join(data)
expected = {
"s1_invalidated": True,
"s2_value": "Hello, Rust!",
"copy_pair": [42, 42],
"shared_readers": ["Hello, Rust!", "Hello, Rust!"],
"mutated_value": "rust!",
}
actual = {
"s1_invalidated": s1_moved,
"s2_value": heap["s2"],
"copy_pair": [x, y],
"shared_readers": readers,
"mutated_value": mutated,
}
return {
"name": "ownership_move_and_borrow",
"summary": "模拟 String 移动失效、i32 复制、多重不可变借用与独占可变借用修改",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pattern_matching_exhaustiveness():
def grade(score: int) -> str:
if 90 <= score <= 100:
return "A"
if 60 <= score <= 89:
return "B"
if 0 <= score <= 59:
return "C"
return "无效分数"
def describe_pair(pair: tuple[int, int]) -> str:
match pair:
case (0, y):
return f"first_zero:{y}"
case (x, 0):
return f"second_zero:{x}"
case (x, y):
return f"both:{x},{y}"
expected = {"score_85": "B", "score_105": "无效分数", "pair_3_7": "both:3,7", "pair_0_9": "first_zero:9"}
actual = {
"score_85": grade(85),
"score_105": grade(105),
"pair_3_7": describe_pair((3, 7)),
"pair_0_9": describe_pair((0, 9)),
}
return {
"name": "pattern_matching_exhaustiveness",
"summary": "验证 match 闭区间范围匹配、通配分支与元组解构模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_option_and_result_semantics():
numbers = [10, 20, 30]
def vec_get(vec, idx):
return ("Some", vec[idx]) if 0 <= idx < len(vec) else ("None", None)
def read_virtual_file(name: str, fs_map: dict[str, str]):
if name in fs_map:
return ("Ok", fs_map[name])
return ("Err", f"NotFound:{name}")
expected = {
"first": ["Some", 10],
"missing": ["None", None],
"missing_file": ["Err", "NotFound:config.txt"],
"present_file": ["Ok", "mode=release"],
}
actual = {
"first": list(vec_get(numbers, 0)),
"missing": list(vec_get(numbers, 5)),
"missing_file": list(read_virtual_file("config.txt", {"app.toml": "mode=release"})),
"present_file": list(read_virtual_file("app.toml", {"app.toml": "mode=release"})),
}
return {
"name": "option_and_result_semantics",
"summary": "验证 Option<T> 替代空指针与 Result<T, E> 替代异常的显式分支处理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_zero_cost_iterator_pipeline():
data = list(range(1, 11))
result = [x * x for x in data if x % 2 == 0]
expected = [4, 16, 36, 64, 100]
return {
"name": "zero_cost_iterator_pipeline",
"summary": "验证 1..=10 链式 filter(偶数) + map(平方) + collect 的精确结果",
"expected": expected,
"actual": result,
"passed": result == expected,
}
def case_fearless_concurrency_arc_mutex():
lock = threading.Lock()
state = {"counter": 0}
def worker():
with lock:
state["counter"] += 1
threads = [threading.Thread(target=worker) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
expected = {"threads": 10, "final_count": 10}
actual = {"threads": len(threads), "final_count": state["counter"]}
return {
"name": "fearless_concurrency_arc_mutex",
"summary": "以多线程互斥锁模拟 Arc<Mutex<i32>> 10 线程累加,核验最终计数无数据竞争",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cargo_toml_and_project_layout():
toml_text = """
[package]
name = "hello_rust"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
walkdir = "2"
"""
parsed = tomllib.loads(toml_text)
expected = {
"name": "hello_rust",
"version": "0.1.0",
"edition": "2024",
"tokio_features": ["full"],
"dep_count": 5,
"rustc_installed": False,
}
actual = {
"name": parsed["package"]["name"],
"version": parsed["package"]["version"],
"edition": parsed["package"]["edition"],
"tokio_features": parsed["dependencies"]["tokio"]["features"],
"dep_count": len(parsed["dependencies"]),
"rustc_installed": shutil.which("rustc") is not None,
}
return {
"name": "cargo_toml_and_project_layout",
"summary": "使用 Python 3.12 tomllib 真实解析 Cargo.toml 元数据与异步/CLI 依赖项",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_syntax_control_fn_struct():
# Shadowing: 5 -> 6 -> 12
x = 5
x = x + 1
x = x * 2
# if expression + loop expression
score = 75
grade = "A" if score >= 90 else ("B" if score >= 60 else "C")
count = 0
while True:
count += 1
if count == 5:
loop_val = count * 2
break
# Functions
def divide(a: float, b: float):
return (0.0, "错误:除数不能为零") if b == 0.0 else (a / b, "OK")
# Struct User
user = {"name": "rustacean", "email": "dev@example.com", "active": True, "login_count": 0}
user["login_count"] += 1
user["login_count"] += 1
# String &str coercion
s = "Hello" + ", world!"
expected = {
"shadowed_x": 12,
"grade": "B",
"loop_val": 10,
"add_10_20": 30,
"divide_ok": [5.0, "OK"],
"divide_zero": [0.0, "错误:除数不能为零"],
"largest": 9,
"login_count": 2,
"greet_from_string": "你好,Hello, world!!",
}
actual = {
"shadowed_x": x,
"grade": grade,
"loop_val": loop_val,
"add_10_20": 10 + 20,
"divide_ok": list(divide(10.0, 2.0)),
"divide_zero": list(divide(10.0, 0.0)),
"largest": max([3, 7, 2, 9, 5]),
"login_count": user["login_count"],
"greet_from_string": f"你好,{s}!",
}
return {
"name": "syntax_control_fn_struct",
"summary": "验证变量遮蔽、if/loop 表达式、多返回元组函数、泛型最大值与结构体方法逻辑",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cli_axum_and_walkdir_simulation():
def axum_hello(name: str | None):
target = name if name is not None else "Guest"
return {
"code": 200,
"message": f"你好,{target}!欢迎访问 Rust HTTP 服务",
"data": {"name": target},
}
# Simulated directory files for extension stats
files = [
("src/main.rs", 40, 1200),
("src/lib.rs", 25, 800),
("Cargo.toml", 15, 420),
("README", 8, 210),
]
stats: dict[str, list[int]] = {}
for path, lines, size in files:
ext = path.rsplit(".", 1)[1].lower() if "." in path else "(无扩展名)"
cur = stats.setdefault(ext, [0, 0, 0])
cur[0] += 1
cur[1] += lines
cur[2] += size
ordered = sorted(stats.items(), key=lambda kv: (-kv[1][0], kv[0]))
expected = {
"api_with_name": {"code": 200, "message": "你好,Rust开发者!欢迎访问 Rust HTTP 服务", "data": {"name": "Rust开发者"}},
"api_default": {"code": 200, "message": "你好,Guest!欢迎访问 Rust HTTP 服务", "data": {"name": "Guest"}},
"walkdir_summary": [["rs", [2, 65, 2000]], ["(无扩展名)", [1, 8, 210]], ["toml", [1, 15, 420]]],
}
actual = {
"api_with_name": axum_hello("Rust开发者"),
"api_default": axum_hello(None),
"walkdir_summary": [[k, v] for k, v in ordered],
}
return {
"name": "cli_axum_and_walkdir_simulation",
"summary": "模拟 Axum GET /hello JSON 响应与 WalkDir 按扩展名聚合统计排序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ownership_move_and_borrow(),
case_pattern_matching_exhaustiveness(),
case_option_and_result_semantics(),
case_zero_cost_iterator_pipeline(),
case_fearless_concurrency_arc_mutex(),
case_cargo_toml_and_project_layout(),
case_syntax_control_fn_struct(),
case_cli_axum_and_walkdir_simulation(),
]
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-intro-lab/explore-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1207.zip