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

离线运行 Rust 所有权与借用检查模拟器,校验 Drop 顺序、Move/Copy/Clone 与借用互斥

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

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


class OwnershipBorrowChecker:
    """Mini Rust ownership, drop-order, and borrow-checker simulator."""

    def __init__(self):
        self.next_alloc = 1
        self.scopes: list[list[str]] = [[]]
        self.vars: dict[str, dict] = {}
        self.dropped_order: list[str] = []

    def enter_scope(self):
        self.scopes.append([])

    def exit_scope(self):
        frame = self.scopes.pop()
        for name in reversed(frame):
            v = self.vars.pop(name, None)
            if v and v["alive"] and not v["is_copy"]:
                self.dropped_order.append(f"{name}#alloc{v['alloc_id']}")

    def bind(self, name: str, value, is_copy: bool, mutable: bool = False):
        alloc_id = None if is_copy else self.next_alloc
        if not is_copy:
            self.next_alloc += 1
        self.vars[name] = {
            "value": value,
            "is_copy": is_copy,
            "mut": mutable,
            "alive": True,
            "alloc_id": alloc_id,
            "shared_borrows": 0,
            "mut_borrow": False,
        }
        self.scopes[-1].append(name)

    def move_or_copy(self, src: str, dst: str, mutable: bool = False):
        v = self.vars[src]
        if not v["alive"]:
            return ("Err", f"E0382: use of moved value `{src}`")
        if v["shared_borrows"] > 0 or v["mut_borrow"]:
            return ("Err", f"E0505: cannot move out of `{src}` because it is borrowed")
        if v["is_copy"]:
            self.bind(dst, v["value"], is_copy=True, mutable=mutable)
            return ("Ok", "copied")
        v["alive"] = False
        self.vars[dst] = {
            "value": v["value"],
            "is_copy": False,
            "mut": mutable,
            "alive": True,
            "alloc_id": v["alloc_id"],
            "shared_borrows": 0,
            "mut_borrow": False,
        }
        self.scopes[-1].append(dst)
        return ("Ok", "moved")

    def clone_var(self, src: str, dst: str):
        v = self.vars[src]
        if not v["alive"]:
            return ("Err", f"E0382: use of moved value `{src}`")
        self.bind(dst, v["value"], is_copy=False, mutable=False)
        return ("Ok", self.vars[dst]["alloc_id"])

    def read(self, name: str):
        v = self.vars.get(name)
        if not v or not v["alive"]:
            return ("Err", f"E0382: borrow of moved value `{name}`")
        return ("Ok", v["value"])

    def borrow_shared(self, name: str):
        v = self.vars[name]
        if not v["alive"]:
            return ("Err", f"E0382: borrow of moved value `{name}`")
        if v["mut_borrow"]:
            return ("Err", f"E0502: cannot borrow `{name}` as immutable because it is also borrowed as mutable")
        v["shared_borrows"] += 1
        return ("Ok", v["value"])

    def release_shared(self, name: str):
        self.vars[name]["shared_borrows"] -= 1

    def borrow_mut(self, name: str):
        v = self.vars[name]
        if not v["alive"]:
            return ("Err", f"E0382: borrow of moved value `{name}`")
        if not v["mut"]:
            return ("Err", f"E0596: cannot borrow `{name}` as mutable, as it is not declared as mutable")
        if v["mut_borrow"]:
            return ("Err", f"E0499: cannot borrow `{name}` as mutable more than once at a time")
        if v["shared_borrows"] > 0:
            return ("Err", f"E0502: cannot borrow `{name}` as mutable because it is also borrowed as immutable")
        v["mut_borrow"] = True
        return ("Ok", v["value"])

    def release_mut(self, name: str):
        self.vars[name]["mut_borrow"] = False


def case_scope_and_automatic_drop():
    chk = OwnershipBorrowChecker()
    chk.enter_scope()
    chk.bind("outer_s", "alpha", is_copy=False)
    chk.enter_scope()
    chk.bind("inner_s", "beta", is_copy=False)
    chk.exit_scope()
    dropped_after_inner = list(chk.dropped_order)
    chk.exit_scope()
    expected = {
        "after_inner_scope": ["inner_s#alloc2"],
        "after_outer_scope": ["inner_s#alloc2", "outer_s#alloc1"],
        "rustc_installed": False,
    }
    actual = {
        "after_inner_scope": dropped_after_inner,
        "after_outer_scope": chk.dropped_order,
        "rustc_installed": shutil.which("rustc") is not None,
    }
    return {
        "name": "scope_and_automatic_drop",
        "summary": "验证词法作用域结束时自动按 LIFO 顺序 drop 堆资源,无需手动 free 或 GC",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_copy_vs_move_and_clone():
    chk = OwnershipBorrowChecker()
    # Stack Copy types
    chk.bind("x", 5, is_copy=True)
    c_res = chk.move_or_copy("x", "y")
    copy_both_ok = chk.read("x")[0] == "Ok" and chk.read("y")[0] == "Ok"
    # Heap String move
    chk.bind("s1", "hello", is_copy=False)
    m_res = chk.move_or_copy("s1", "s2")
    s1_read_err = chk.read("s1")[1][:5]
    # Clone produces independent allocation
    cl_res = chk.clone_var("s2", "s3")
    distinct_allocs = chk.vars["s2"]["alloc_id"] != chk.vars["s3"]["alloc_id"]
    chk.exit_scope()
    expected = {
        "copy_mode": "copied",
        "copy_both_valid": True,
        "move_mode": "moved",
        "use_after_move_err": "E0382",
        "clone_distinct_alloc": True,
        "dropped_without_double_free": ["s3#alloc2", "s2#alloc1"],
    }
    actual = {
        "copy_mode": c_res[1],
        "copy_both_valid": copy_both_ok,
        "move_mode": m_res[1],
        "use_after_move_err": s1_read_err,
        "clone_distinct_alloc": distinct_allocs and cl_res[0] == "Ok",
        "dropped_without_double_free": chk.dropped_order,
    }
    return {
        "name": "copy_vs_move_and_clone",
        "summary": "验证 Copy 类型直接复制、String 移动后原变量触发 E0382、clone 深拷贝避免二次释放",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_function_param_and_return_ownership():
    chk = OwnershipBorrowChecker()
    # takes_ownership(s) + makes_copy(x)
    chk.bind("s", "hello", is_copy=False)
    chk.bind("x", 5, is_copy=True)
    chk.enter_scope()
    chk.move_or_copy("s", "some_string")
    chk.move_or_copy("x", "some_integer")
    chk.exit_scope()  # drops some_string
    s_after_call = chk.read("s")[1][:5]
    x_after_call = chk.read("x")[1]

    # gives_ownership() & takes_and_gives_back(s2) -> s3
    chk.bind("s1", "hello", is_copy=False)
    chk.bind("s2", "hello", is_copy=False)
    chk.move_or_copy("s2", "s3")
    s2_after_roundtrip = chk.read("s2")[1][:5]
    s3_val = chk.read("s3")[1]
    expected = {
        "s_after_takes_ownership": "E0382",
        "x_after_makes_copy": 5,
        "s2_moved_into_fn": "E0382",
        "s3_received_back": "hello",
        "dropped_in_callee": ["some_string#alloc1"],
    }
    actual = {
        "s_after_takes_ownership": s_after_call,
        "x_after_makes_copy": x_after_call,
        "s2_moved_into_fn": s2_after_roundtrip,
        "s3_received_back": s3_val,
        "dropped_in_callee": chk.dropped_order,
    }
    return {
        "name": "function_param_and_return_ownership",
        "summary": "追踪函数传参移动(String)与复制(i32)以及返回值将所有权移出函数的完整生命周期",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_shared_borrowing_and_reborrow():
    chk = OwnershipBorrowChecker()
    chk.bind("s1", "hello", is_copy=False)
    b1 = chk.borrow_shared("s1")
    length = len(b1[1])
    # Moving s1 while s2 borrows it is rejected (E0505)
    move_while_borrowed = chk.move_or_copy("s1", "s3")
    # Release s2 borrow, move s1 -> s3, then reborrow from s3
    chk.release_shared("s1")
    move_after_release = chk.move_or_copy("s1", "s3")
    reborrowed = chk.borrow_shared("s3")
    expected = {
        "calculated_len": 5,
        "move_while_borrowed_err": "E0505",
        "move_after_release": "moved",
        "reborrow_s3_val": "hello",
    }
    actual = {
        "calculated_len": length,
        "move_while_borrowed_err": move_while_borrowed[1][:5],
        "move_after_release": move_after_release[1],
        "reborrow_s3_val": reborrowed[1],
    }
    return {
        "name": "shared_borrowing_and_reborrow",
        "summary": "验证不可变借用求长度不夺取所有权、借用期间移动被 E0505 拒绝以及释放后重新借用",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mutable_borrow_and_aliasing_rules():
    chk = OwnershipBorrowChecker()
    # Immutable variable cannot be mutably borrowed
    chk.bind("immut_s", "rust", is_copy=False, mutable=False)
    immut_mut_err = chk.borrow_mut("immut_s")[1][:5]

    # Mutable variable allows single &mut, rejects double &mut (E0499) and & + &mut (E0502)
    chk.bind("s", "rust", is_copy=False, mutable=True)
    r1 = chk.borrow_mut("s")
    chk.vars["s"]["value"] += "-lang"
    double_mut_err = chk.borrow_mut("s")[1][:5]
    shared_during_mut_err = chk.borrow_shared("s")[1][:5]
    chk.release_mut("s")
    # Multiple shared borrows allowed once &mut ends
    sh1 = chk.borrow_shared("s")
    sh2 = chk.borrow_shared("s")

    expected = {
        "mutate_immutable_err": "E0596",
        "mutated_value": "rust-lang",
        "double_mut_err": "E0499",
        "shared_plus_mut_err": "E0502",
        "multiple_shared_allowed": ["rust-lang", "rust-lang"],
    }
    actual = {
        "mutate_immutable_err": immut_mut_err,
        "mutated_value": chk.vars["s"]["value"],
        "double_mut_err": double_mut_err,
        "shared_plus_mut_err": shared_during_mut_err,
        "multiple_shared_allowed": [sh1[1], sh2[1]],
    }
    return {
        "name": "mutable_borrow_and_aliasing_rules",
        "summary": "验证不可变借用禁写(E0596)、独占可变借用修改及读写互斥(E0499/E0502)防数据竞争规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_dangling_reference_rejection():
    def check_return_ref(returns_ref_to_local: bool):
        if returns_ref_to_local:
            return ("Err", "E0106/E0515: cannot return reference to local variable `s` dropped at end of function")
        return ("Ok", "String ownership moved out safely")

    expected = {
        "dangle_ref_rejected": "E0106",
        "return_owned_string_ok": "Ok",
    }
    actual = {
        "dangle_ref_rejected": check_return_ref(True)[1][:5],
        "return_owned_string_ok": check_return_ref(False)[0],
    }
    return {
        "name": "dangling_reference_rejection",
        "summary": "验证返回局部变量引用 dangle() -> &String 在编译期被拦截,改为直接返回所有权 String 方可安全通过",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_scope_and_automatic_drop(),
        case_copy_vs_move_and_clone(),
        case_function_param_and_return_ownership(),
        case_shared_borrowing_and_reborrow(),
        case_mutable_borrow_and_aliasing_rules(),
        case_dangling_reference_rejection(),
    ]
    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-ownership-lab/explore-ownership.py

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

下载课程关联工程包:Rust

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

下载课程关联工程包:Rust

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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