蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线模拟 Rust 闭包类型锁定、三种捕获、Fn/FnMut/FnOnce 体系与生命周期逃逸检查

PYTHONWindows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。explore-closure.py
explore-closure.py269 行
"""Offline Rust semantic verification lab for Chapter 14 (closure)."""
import json
import shutil

VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"


def case_closure_syntax_and_inference():
    add_one = lambda x: x + 1
    multiply = lambda a, b: a * b

    def greet(name: str) -> str:
        greeting = f"Hello, {name}!"
        return greeting

    # Simulate Rust's single concrete type lock-in on first inferred call
    inferred_param_type = None

    def typed_identity(val):
        nonlocal inferred_param_type
        tname = type(val).__name__
        if inferred_param_type is None:
            inferred_param_type = tname
            return ("Ok", val)
        if inferred_param_type != tname:
            return ("Err", f"E0308: expected {inferred_param_type}, found {tname}")
        return ("Ok", val)

    c1 = typed_identity(4)
    c2 = typed_identity("text")
    expected = {
        "add_one_4": 5,
        "multiply_3_7": 21,
        "greet_rust": "Hello, Rust!",
        "first_call_ok": ["Ok", 4],
        "second_diff_type_rejected": "E0308",
        "rustc_installed": False,
    }
    actual = {
        "add_one_4": add_one(4),
        "multiply_3_7": multiply(3, 7),
        "greet_rust": greet("Rust"),
        "first_call_ok": list(c1),
        "second_diff_type_rejected": c2[1][:5],
        "rustc_installed": shutil.which("rustc") is not None,
    }
    return {
        "name": "closure_syntax_and_inference",
        "summary": "验证闭包省略/显式类型注解、多行大括号块以及首次调用锁定推导类型的语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_capture_modes_borrow_mut_move():
    # 1. Immutable borrow (&T): outer remains usable
    text = "rust-lang"
    print_text = lambda: f"text = {text}"
    borrow_out = print_text()
    outer_still_usable = text

    # 2. Mutable borrow (&mut T): requires mut closure
    counter = [0]

    def inc():
        counter[0] += 1

    inc()
    inc()

    # 3. Move capture: String moved (outer invalidated), i32 copied (outer remains valid)
    env = {"owned_string": "RUST", "copy_num": 42}
    moved_val = env.pop("owned_string")
    copied_val = env["copy_num"]
    take_owned = lambda: f"owned = {moved_val}"

    expected = {
        "borrow_out": "text = rust-lang",
        "outer_text_valid": "rust-lang",
        "mut_counter": 2,
        "move_out": "owned = RUST",
        "outer_string_invalidated": True,
        "outer_copy_int_still_valid": True,
        "copied_num": 42,
    }
    actual = {
        "borrow_out": borrow_out,
        "outer_text_valid": outer_still_usable,
        "mut_counter": counter[0],
        "move_out": take_owned(),
        "outer_string_invalidated": "owned_string" not in env,
        "outer_copy_int_still_valid": "copy_num" in env,
        "copied_num": copied_val,
    }
    return {
        "name": "capture_modes_borrow_mut_move",
        "summary": "验证不可变借用、可变借用与 move 按值捕获(对比非 Copy 的 String 与 Copy 的 i32)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_fn_fnmut_fnonce_hierarchy():
    class SimClosure:
        def __init__(self, trait_level: str, fn):
            self.trait_level = trait_level  # "Fn", "FnMut", "FnOnce"
            self.fn = fn
            self.consumed = False

        def implements(self, req: str) -> bool:
            order = {"Fn": {"Fn", "FnMut", "FnOnce"}, "FnMut": {"FnMut", "FnOnce"}, "FnOnce": {"FnOnce"}}
            return req in order[self.trait_level]

        def call(self):
            if self.consumed:
                return ("Err", "E0382: use of moved value (FnOnce already called)")
            res = self.fn()
            if self.trait_level == "FnOnce":
                self.consumed = True
            return ("Ok", res)

    # move closure that only reads captured data still implements Fn!
    moved_label = "Rust"
    move_but_fn = SimClosure("Fn", lambda: f"Hello, {moved_label}!")
    cnt = [0]
    fn_mut = SimClosure("FnMut", lambda: (cnt.__setitem__(0, cnt[0] + 1) or cnt[0]))
    fn_once = SimClosure("FnOnce", lambda: "consumed")

    expected = {
        "fn_impls_all_three": True,
        "move_read_only_called_twice": [["Ok", "Hello, Rust!"], ["Ok", "Hello, Rust!"]],
        "fn_mut_calls": [["Ok", 1], ["Ok", 2]],
        "fn_once_first_ok": ["Ok", "consumed"],
        "fn_once_second_rejected": "E0382",
    }
    actual = {
        "fn_impls_all_three": all(move_but_fn.implements(t) for t in ("Fn", "FnMut", "FnOnce")),
        "move_read_only_called_twice": [list(move_but_fn.call()), list(move_but_fn.call())],
        "fn_mut_calls": [list(fn_mut.call()), list(fn_mut.call())],
        "fn_once_first_ok": list(fn_once.call()),
        "fn_once_second_rejected": fn_once.call()[1][:5],
    }
    return {
        "name": "fn_fnmut_fnonce_hierarchy",
        "summary": "验证 Fn:FnMut:FnOnce 继承关系、move 只读闭包仍实现 Fn 以及 FnOnce 二次调用被拒",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_higher_order_params_and_returns():
    def apply(val: int, f) -> int:
        return f(val)

    def make_adder_impl_fn(x: int):
        # Static dispatch equivalent (stack)
        return ("impl_Fn_stack", lambda y: x + y)

    def make_adder_box_dyn(x: int, negate: bool = False):
        # Dynamic dispatch equivalent (heap)
        if negate:
            return ("Box_dyn_Fn_heap", lambda y: y - x)
        return ("Box_dyn_Fn_heap", lambda y: x + y)

    tag_s, add_five = make_adder_impl_fn(5)
    tag_d, add_ten = make_adder_box_dyn(10, negate=False)
    expected = {
        "apply_double_5": 10,
        "apply_add100_3": 103,
        "square_5": 25,
        "cube_5": 125,
        "impl_fn_5_plus_3": ["impl_Fn_stack", 8],
        "box_dyn_10_plus_2": ["Box_dyn_Fn_heap", 12],
    }
    actual = {
        "apply_double_5": apply(5, lambda x: x * 2),
        "apply_add100_3": apply(3, lambda x: x + 100),
        "square_5": apply(5, lambda x: x * x),
        "cube_5": apply(5, lambda x: x * x * x),
        "impl_fn_5_plus_3": [tag_s, add_five(3)],
        "box_dyn_10_plus_2": [tag_d, add_ten(2)],
    }
    return {
        "name": "higher_order_params_and_returns",
        "summary": "验证闭包作为泛型 Fn 参数(apply/square/cube)与 impl Fn / Box<dyn Fn> 返回模式",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_iterator_thread_and_result_closures():
    nums = [1, 2, 3, 4, 5]
    squared = [x * x for x in nums]
    evens = [x for x in nums if x % 2 == 0]
    total = sum(nums)
    # Simulated thread::spawn(move || num * 2) join order
    thread_results = [n * 2 for n in nums]
    # Closure + find + Result mapping
    signed = [3, -1, 4, -5, 9]
    first_pos = next((x for x in signed if x > 0), None)
    mapped_res = [("Ok", n * 10) if n > 0 else ("Err", "负数无法处理") for n in signed]

    expected = {
        "squared": [1, 4, 9, 16, 25],
        "evens": [2, 4],
        "fold_sum": 15,
        "thread_doubles": [2, 4, 6, 8, 10],
        "first_positive": 3,
        "result_statuses": [["Ok", 30], ["Err", "负数无法处理"], ["Ok", 40], ["Err", "负数无法处理"], ["Ok", 90]],
    }
    actual = {
        "squared": squared,
        "evens": evens,
        "fold_sum": total,
        "thread_doubles": thread_results,
        "first_positive": first_pos,
        "result_statuses": [list(r) for r in mapped_res],
    }
    return {
        "name": "iterator_thread_and_result_closures",
        "summary": "验证闭包在迭代器流水线、move 多线程计算与 Option/Result 错误处理中的行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_closure_lifetime_escape_check():
    def check_return_closure(captures_local_by_ref: bool, uses_move: bool):
        if captures_local_by_ref and not uses_move:
            return ("Err", "E0373: closure may outlive the current function, add `move`")
        return ("Ok", "closure owns captured value safely")

    expected = {
        "ref_escape_rejected": "E0373",
        "move_escape_allowed": "Ok",
    }
    actual = {
        "ref_escape_rejected": check_return_closure(True, False)[1][:5],
        "move_escape_allowed": check_return_closure(True, True)[0],
    }
    return {
        "name": "closure_lifetime_escape_check",
        "summary": "验证借用检查器拦截返回引用局部变量的闭包(E0373),改用 move 转移所有权后合法",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_closure_syntax_and_inference(),
        case_capture_modes_borrow_mut_move(),
        case_fn_fnmut_fnonce_hierarchy(),
        case_higher_order_params_and_returns(),
        case_iterator_thread_and_result_closures(),
        case_closure_lifetime_escape_check(),
    ]
    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-closure-lab/explore-closure.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-closure.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Rust

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1196.zip

下载课程关联工程包:Rust

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习