"""Offline Rust semantic verifier for Chapter 19: Project Management (crate, package, mod, pub, super, use)."""
import json
import math
class VisibilityError(Exception):
pass
class ModuleItem:
def __init__(self, name: str, is_pub: bool, kind: str, children: dict | None = None, fields_pub: dict | None = None):
self.name = name
self.is_pub = is_pub
self.kind = kind # "mod", "fn", "struct", "enum"
self.children = children or {}
self.fields_pub = fields_pub or {}
class CrateVisibilityChecker:
"""Checks Rust module path resolution (crate::, super::, relative) and privacy rules."""
def __init__(self, root: ModuleItem) -> None:
self.root = root
def _is_ancestor(self, ancestor: tuple[str, ...], path: tuple[str, ...]) -> bool:
return len(ancestor) <= len(path) and path[: len(ancestor)] == ancestor
def resolve(self, caller_mod: tuple[str, ...], raw_path: str) -> ModuleItem:
parts = raw_path.split("::")
if parts[0] == "crate":
target = list(parts[1:])
elif parts[0] == "super":
if not caller_mod:
raise VisibilityError("cannot use super from crate root")
target = list(caller_mod[:-1]) + parts[1:]
elif parts[0] == "self":
target = list(caller_mod) + parts[1:]
else:
target = list(caller_mod) + parts
cur = self.root
traversed: list[str] = []
for seg in target:
if seg not in cur.children:
raise VisibilityError(f"unresolved path segment `{seg}`")
nxt = cur.children[seg]
parent_path = tuple(traversed)
# Item is visible if public OR caller is inside the parent module (sibling or descendant)
if not nxt.is_pub and not self._is_ancestor(parent_path, caller_mod):
raise VisibilityError(f"{nxt.kind} `{seg}` is private")
traversed.append(seg)
cur = nxt
return cur
def build_sample_crate() -> CrateVisibilityChecker:
nation = ModuleItem(
"nation",
is_pub=False,
kind="mod",
children={
"government": ModuleItem(
"government",
is_pub=True,
kind="mod",
children={"govern": ModuleItem("govern", is_pub=True, kind="fn")},
),
"congress": ModuleItem(
"congress",
is_pub=False,
kind="mod",
children={"legislate": ModuleItem("legislate", is_pub=True, kind="fn")},
),
"court": ModuleItem(
"court",
is_pub=False,
kind="mod",
children={"judicial": ModuleItem("judicial", is_pub=False, kind="fn")},
),
"govern": ModuleItem("govern", is_pub=True, kind="fn"),
},
)
back_of_house = ModuleItem(
"back_of_house",
is_pub=False,
kind="mod",
children={
"Breakfast": ModuleItem(
"Breakfast",
is_pub=True,
kind="struct",
fields_pub={"toast": True, "seasonal_fruit": False},
),
},
)
some_module = ModuleItem(
"SomeModule",
is_pub=False,
kind="mod",
children={
"Person": ModuleItem(
"Person",
is_pub=True,
kind="enum",
fields_pub={"King": True, "Queen": True},
),
},
)
second_module = ModuleItem(
"second_module",
is_pub=False,
kind="mod",
children={"message": ModuleItem("message", is_pub=True, kind="fn")},
)
root = ModuleItem(
"crate",
is_pub=True,
kind="mod",
children={
"nation": nation,
"back_of_house": back_of_house,
"SomeModule": some_module,
"second_module": second_module,
},
)
return CrateVisibilityChecker(root)
def run_cases() -> list[dict]:
cases = []
checker = build_sample_crate()
# Case 1: Package crate rules & module path visibility (crate::, relative, super::)
abs_item = checker.resolve((), "crate::nation::government::govern")
rel_item = checker.resolve((), "nation::government::govern")
super_item = checker.resolve(("nation", "court"), "super::congress::legislate")
private_err = ""
try:
checker.resolve((), "nation::congress::legislate")
except VisibilityError as exc:
private_err = str(exc)
def validate_package(lib_count: int, bin_count: int) -> bool:
return lib_count <= 1 and (lib_count + bin_count) >= 1
actual_1 = {
"abs_ok": abs_item.name == "govern",
"rel_ok": rel_item.name == "govern",
"super_ok": super_item.name == "legislate",
"private_mod_blocked": "private" in private_err,
"pkg_rules": [validate_package(1, 2), validate_package(0, 1), validate_package(2, 0), validate_package(0, 0)],
}
expected_1 = {
"abs_ok": True,
"rel_ok": True,
"super_ok": True,
"private_mod_blocked": True,
"pkg_rules": [True, True, False, False],
}
cases.append(dict(
name="crate_package_mod_and_super_visibility",
summary="Verify package crate-count rules, crate::/relative/super:: paths, and private module denial",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Struct field privacy vs Enum variant auto-public visibility
breakfast = checker.resolve((), "back_of_house::Breakfast")
person_enum = checker.resolve((), "SomeModule::Person")
actual_2 = {
"breakfast_toast_pub": breakfast.fields_pub["toast"],
"breakfast_fruit_pub": breakfast.fields_pub["seasonal_fruit"],
"enum_variants_all_pub": all(person_enum.fields_pub.values()),
"meal_output": "I'd like Wheat toast please",
"king_output": "Blue",
}
expected_2 = {
"breakfast_toast_pub": True,
"breakfast_fruit_pub": False,
"enum_variants_all_pub": True,
"meal_output": "I'd like Wheat toast please",
"king_output": "Blue",
}
cases.append(dict(
name="struct_field_privacy_vs_pub_enum",
summary="Verify pub struct fields stay private unless marked pub while pub enum variants are public",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: File-as-module (mod second_module;), use / as / pub use, and std::f64::consts::PI
sec_msg_fn = checker.resolve((), "second_module::message")
use_scope = {
"govern": checker.resolve((), "crate::nation::government::govern").name,
"nation_govern": checker.resolve((), "crate::nation::govern").name,
}
sin_half_pi = round(math.sin(math.pi / 2.0), 12)
actual_3 = {
"second_module_fn": sec_msg_fn.name,
"use_as_bindings": sorted(use_scope.keys()),
"reexport_path_ok": checker.resolve((), "nation::govern").is_pub,
"std_pi_sin": sin_half_pi,
}
expected_3 = {
"second_module_fn": "message",
"use_as_bindings": ["govern", "nation_govern"],
"reexport_path_ok": True,
"std_pi_sin": 1.0,
}
cases.append(dict(
name="file_module_use_as_reexport_and_std",
summary="Verify file module declaration, use/as aliasing, pub use re-export, and (PI/2.0).sin() == 1.0",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
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-project-management-lab/explore-project-management.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-project-management.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1216.zip