"""Offline Rust semantic verifier for Chapter 22: Lifetimes (borrow scope checker, elision rules, 'static)."""
from dataclasses import dataclass
import json
@dataclass(frozen=True)
class ScopeInterval:
name: str
start_line: int
end_line: int
def outlives(self, other: "ScopeInterval") -> bool:
return self.start_line <= other.start_line and self.end_line >= other.end_line
def check_borrow(owner_scope: ScopeInterval, ref_use_scope: ScopeInterval) -> tuple[bool, str]:
if owner_scope.outlives(ref_use_scope):
return True, "ok"
return False, f"`{owner_scope.name}` does not live long enough for `{ref_use_scope.name}`"
def elide_fn_lifetimes(param_refs: list[str], has_self_ref: bool, output_ref: bool) -> tuple[bool, str]:
"""Implements Rust's three lifetime elision rules."""
if not output_ref:
return True, "no_output_ref"
if has_self_ref:
return True, "elided_to_self_lifetime"
if len(param_refs) == 1:
return True, f"elided_to_{param_refs[0]}"
return False, "missing_lifetime_specifier_ambiguous_inputs"
def longer(s1: str, s2: str) -> str:
return s2 if len(s2) > len(s1) else s1
def longest_with_announcement(x: str, y: str, ann: str) -> tuple[str, str]:
msg = f"Announcement! {ann}"
res = x if len(x) > len(y) else y
return msg, res
def run_cases() -> list[dict]:
cases = []
# Case 1: Dangling reference detection ('a outlives 'b -> rejected)
r_scope = ScopeInterval("r('a)", start_line=2, end_line=9)
x_scope = ScopeInterval("x('b)", start_line=4, end_line=6)
ok_dangle, msg_dangle = check_borrow(x_scope, r_scope)
inner_use = ScopeInterval("r_inner", start_line=5, end_line=6)
ok_valid, _ = check_borrow(x_scope, inner_use)
actual_1 = {
"dangling_rejected": not ok_dangle,
"error_mentions_lifetime": "does not live long enough" in msg_dangle,
"inner_scope_accepted": ok_valid,
}
expected_1 = {
"dangling_rejected": True,
"error_mentions_lifetime": True,
"inner_scope_accepted": True,
}
cases.append(dict(
name="dangling_reference_scope_check",
summary="Verify outer borrow 'a outliving inner value 'b is rejected while inner-scope use succeeds",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Function lifetime annotation and elision rules
unannotated_ok, unannotated_reason = elide_fn_lifetimes(["s1", "s2"], has_self_ref=False, output_ref=True)
# With explicit <'a>, returned lifetime is intersection min(s1, s2)
s1_scope = ScopeInterval("s1", 1, 10)
s2_scope = ScopeInterval("s2", 3, 6)
min_scope = ScopeInterval("min(s1,s2)", max(s1_scope.start_line, s2_scope.start_line), min(s1_scope.end_line, s2_scope.end_line))
use_inside_ok, _ = check_borrow(min_scope, ScopeInterval("print_inside", 4, 5))
use_outside_ok, _ = check_borrow(min_scope, ScopeInterval("print_outside", 4, 8))
actual_2 = {
"unannotated_longer_rejected": not unannotated_ok,
"unannotated_reason": unannotated_reason,
"longer_value": longer("rust", "ecmascript"),
"use_inside_accepted": use_inside_ok,
"use_outside_rejected": not use_outside_ok,
}
expected_2 = {
"unannotated_longer_rejected": True,
"unannotated_reason": "missing_lifetime_specifier_ambiguous_inputs",
"longer_value": "ecmascript",
"use_inside_accepted": True,
"use_outside_rejected": True,
}
cases.append(dict(
name="longer_fn_annotation_and_intersection",
summary="Verify two-&str input elision ambiguity, longer<'a> result, and shortest-input intersection check",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Struct<'a> with &str field, method elision rule 3, 'static, and generics+trait+lifetime
method_ok, method_rule = elide_fn_lifetimes(["&self"], has_self_ref=True, output_ref=True)
static_scope = ScopeInterval("'static", 0, 10**9)
struct_scope = ScopeInterval("Str<'a>", 10, 50)
static_ok, _ = check_borrow(static_scope, struct_scope)
ann_msg, ann_longest = longest_with_announcement("rust", "ecmascript", "compare lengths")
actual_3 = {
"struct_content": "s.content = string_slice",
"method_elision": [method_ok, method_rule],
"static_outlives_struct": static_ok,
"combined_announcement": [ann_msg, ann_longest],
}
expected_3 = {
"struct_content": "s.content = string_slice",
"method_elision": [True, "elided_to_self_lifetime"],
"static_outlives_struct": True,
"combined_announcement": ["Announcement! compare lengths", "ecmascript"],
}
cases.append(dict(
name="struct_elision_static_and_combined_fn",
summary="Verify Str<'a> holding &'static str, &self method elision rule 3, and longest_with_an_announcement",
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-lifetime-lab/explore-lifetime.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-lifetime.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1209.zip