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

运行离线 Python 校验:Rust 枚举变体解构、match 穷尽检查、Option<T> 与 if let

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-enum.py
explore-enum.py184 行
"""Offline Rust semantic verifier for Chapter 18: Enum (tagged unions, match exhaustiveness, Option, if let)."""
from dataclasses import dataclass
import json
from typing import Any, Callable


@dataclass(frozen=True)
class EnumVariant:
    enum_name: str
    tag: str
    payload: Any = None


def match_exhaustive(
    value: EnumVariant,
    all_tags: set[str],
    arms: dict[str, Callable[[Any], Any]],
    wildcard: Callable[[], Any] | None = None,
) -> Any:
    """Enforces Rust match exhaustiveness and uniform arm return types."""
    missing = all_tags - set(arms.keys())
    if missing and wildcard is None:
        raise TypeError(f"non-exhaustive patterns: missing {sorted(missing)}")
    if value.tag in arms:
        return arms[value.tag](value.payload)
    assert wildcard is not None
    return wildcard()


def run_cases() -> list[dict]:
    cases = []

    # Case 1: Unit, tuple, and struct-variant enums + match destructuring
    book_tags = {"Papery", "Electronic"}
    simple = EnumVariant("Book", "Papery")
    tuple_book = EnumVariant("Book", "Papery", (1001,))
    struct_book = EnumVariant("Book", "Papery", {"index": 1001})
    struct_ebook = EnumVariant("Book", "Electronic", {"url": "https://example.org/rust"})

    def describe_struct(b: EnumVariant) -> str:
        return match_exhaustive(
            b,
            book_tags,
            {
                "Papery": lambda f: f"Papery book {f['index']}",
                "Electronic": lambda f: f"E-book {f['url']}",
            },
        )

    def describe_tuple(b: EnumVariant) -> str:
        return match_exhaustive(
            b,
            book_tags,
            {
                "Papery": lambda t: str(t[0]),
                "Electronic": lambda f: f["url"],
            },
        )

    actual_1 = {
        "simple_debug": simple.tag,
        "struct_match_papery": describe_struct(struct_book),
        "struct_match_ebook": describe_struct(struct_ebook),
        "tuple_match": describe_tuple(tuple_book),
    }
    expected_1 = {
        "simple_debug": "Papery",
        "struct_match_papery": "Papery book 1001",
        "struct_match_ebook": "E-book https://example.org/rust",
        "tuple_match": "1001",
    }
    cases.append(dict(
        name="enum_variants_and_match_destructuring",
        summary="Verify unit, tuple, and struct enum variants destructured via exhaustive match",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: Exhaustiveness error + non-enum wildcard match
    non_exhaustive_caught = False
    try:
        match_exhaustive(struct_book, book_tags, {"Papery": lambda f: f["index"]})
    except TypeError:
        non_exhaustive_caught = True

    def match_str(val: str) -> str:
        match val:
            case "abc":
                return "Yes"
            case _:
                return ""

    actual_2 = {
        "non_exhaustive_rejected": non_exhaustive_caught,
        "str_match_abc": match_str("abc"),
        "str_match_other": match_str("xyz"),
    }
    expected_2 = {
        "non_exhaustive_rejected": True,
        "str_match_abc": "Yes",
        "str_match_other": "",
    }
    cases.append(dict(
        name="match_exhaustiveness_and_wildcard",
        summary="Verify missing enum arm is rejected and non-enum match uses _ catch-all arm",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: Option<T> Some/None and value-matching Some(64)
    opt_tags = {"Some", "None"}
    opt_hello = EnumVariant("Option", "Some", "Hello")
    opt_none = EnumVariant("Option", "None", None)
    opt_64 = EnumVariant("Option", "Some", 64)

    def handle_opt(opt: EnumVariant) -> str:
        return match_exhaustive(
            opt,
            opt_tags,
            {
                "Some": lambda v: str(v),
                "None": lambda _: "opt is nothing",
            },
        )

    val_match = "Yes" if (opt_64.tag == "Some" and opt_64.payload == 64) else "No"
    actual_3 = {
        "some_hello": handle_opt(opt_hello),
        "typed_none": handle_opt(opt_none),
        "some_64_match": val_match,
    }
    expected_3 = {
        "some_hello": "Hello",
        "typed_none": "opt is nothing",
        "some_64_match": "Yes",
    }
    cases.append(dict(
        name="option_some_none_matching",
        summary="Verify Option<T> replaces null via Some/None and supports nested literal matching",
        expected=expected_3,
        actual=actual_3,
        passed=actual_3 == expected_3,
    ))

    # Case 4: if let syntax sugar with else branch
    i = 0
    zero_msg = "zero" if i == 0 else "other"
    ebook_val = EnumVariant("Book", "Electronic", ("url",))
    if ebook_val.tag == "Papery":
        if_let_msg = f"Papery {ebook_val.payload[0]}"
    else:
        if_let_msg = "Not papery book"
    actual_4 = {
        "if_let_int": zero_msg,
        "if_let_enum_else": if_let_msg,
    }
    expected_4 = {
        "if_let_int": "zero",
        "if_let_enum_else": "Not papery book",
    }
    cases.append(dict(
        name="if_let_sugar_and_else",
        summary="Verify if let shortens two-branch match for both literals and enum variants",
        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-enum-lab/explore-enum.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-enum.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Rust

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

下载课程关联工程包:Rust

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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