"""Offline Rust semantic verifier for Chapter 21: Generics & Traits (bounds, monomorphization, default impl, where)."""
from dataclasses import dataclass
import json
from typing import Any, Generic, Protocol, TypeVar
T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
W = TypeVar("W")
class Comparable(Protocol):
def compare(self, other: Any) -> int: ...
@dataclass(frozen=True)
class Point(Generic[T, U]):
x: T
y: U
def get_x(self) -> T:
return self.x
def mixup(self, other: "Point[V, W]") -> "Point[T, W]":
return Point(self.x, other.y)
class Descriptive:
"""Models a Rust trait with a default method implementation."""
def describe(self) -> str:
return "[Object]"
@dataclass
class Person(Descriptive):
name: str
age: int
def describe(self) -> str:
return f"{self.name} {self.age}"
@dataclass
class DefaultItem(Descriptive):
label: str
@dataclass(frozen=True)
class FloatVal:
v: float
def compare(self, other: "FloatVal") -> int:
if self.v > other.v:
return 1
if self.v == other.v:
return 0
return -1
def generic_max(arr: list[Comparable]) -> Comparable:
"""Models fn max<T: Comparable>(array: &[T]) -> &T."""
max_idx = 0
for i in range(1, len(arr)):
if arr[i].compare(arr[max_idx]) > 0:
max_idx = i
return arr[max_idx]
def check_trait_bounds(type_traits: dict[str, set[str]], type_name: str, required: set[str]) -> bool:
return required.issubset(type_traits.get(type_name, set()))
def run_cases() -> list[dict]:
cases = []
# Case 1: Generic struct Point<T> type consistency + Point<T, U>::mixup
p_int = Point(1, 2)
p_float = Point(1.0, 2.0)
mixed = Point(5, 10.4).mixup(Point("Hello", "c"))
same_type_check_ok = type(p_int.x) is type(p_int.y)
mismatch_rejected = type(1) is not type(2.0)
actual_1 = {
"p_int_x": p_int.get_x(),
"p_float_x": p_float.get_x(),
"same_type_ok": same_type_check_ok,
"mismatch_rejected": mismatch_rejected,
"mixup_result": [mixed.x, mixed.y],
}
expected_1 = {
"p_int_x": 1,
"p_float_x": 1.0,
"same_type_ok": True,
"mismatch_rejected": True,
"mixup_result": [5, "c"],
}
cases.append(dict(
name="generic_struct_and_mixup",
summary="Verify Point<T> homogeneous type check, concrete f64 method, and Point<T, U>::mixup<V, W>",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Trait override vs default trait method
cali = Person(name="Cali", age=24)
fallback = DefaultItem(label="anon")
actual_2 = {
"overridden_describe": cali.describe(),
"default_describe": fallback.describe(),
}
expected_2 = {
"overridden_describe": "Cali 24",
"default_describe": "[Object]",
}
cases.append(dict(
name="trait_impl_and_default_method",
summary="Verify custom impl Descriptive overrides default [Object] while empty impl inherits default",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Comparable trait bound + monomorphized max on &[i32] and &[f64]
int_arr = [2, 4, 6, 3, 1]
float_arr = [FloatVal(x) for x in (1.0, 3.0, 5.0, 4.0, 2.0)]
best_float = generic_max(float_arr)
actual_3 = {
"i32_max": max(int_arr),
"f64_comparable_max": best_float.v,
}
expected_3 = {
"i32_max": 6,
"f64_comparable_max": 5.0,
}
cases.append(dict(
name="trait_bound_comparable_max",
summary="Verify max(&[i32]) == 6 and generic max<T: Comparable>(&[f64]) == 5.0",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
# Case 4: Multi-trait bounds (+ / where), impl Trait return uniformity, conditional impl<T: B + C>
registry = {
"Person": {"Descriptive", "Display", "Clone"},
"StructA": {"Descriptive", "B", "C"},
"StructB": {"Descriptive", "B"},
}
def check_impl_return_uniform(branch_types: list[str]) -> bool:
return len(set(branch_types)) == 1
actual_4 = {
"where_bound_person_ok": check_trait_bounds(registry, "Person", {"Display", "Clone"}),
"impl_return_single_type_ok": check_impl_return_uniform(["Person", "Person"]),
"impl_return_two_types_rejected": not check_impl_return_uniform(["StructA", "StructB"]),
"conditional_impl_A_ok": check_trait_bounds(registry, "StructA", {"B", "C"}),
"conditional_impl_B_blocked": not check_trait_bounds(registry, "StructB", {"B", "C"}),
}
expected_4 = {
"where_bound_person_ok": True,
"impl_return_single_type_ok": True,
"impl_return_two_types_rejected": True,
"conditional_impl_A_ok": True,
"conditional_impl_B_blocked": True,
}
cases.append(dict(
name="trait_bounds_return_and_conditional_impl",
summary="Verify +/where multi-bounds, single concrete type rule for impl Trait return, and impl<T: B + C>",
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-generics-lab/explore-generics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-generics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1206.zip