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

运行离线 Python 校验:Rust macro_rules! 展开、vec! 重复匹配与派生过程宏生成

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-macros.py
explore-macros.py130 行
"""Offline Rust semantic verifier for Chapter 27: Macros (macro_rules! pattern matching, repetition expansion, proc macros)."""
import json
import re


def expand_greet(token_arg: str) -> str:
    """Expands macro_rules! greet { ($name:expr) => { println!(\"Hello, {}!\", $name); }; }."""
    arg = token_arg.strip()
    if not arg:
        raise SyntaxError("expected expression for $name:expr")
    return f'println!("Hello, {{}}!", {arg});'


def expand_vec(raw_tokens: str) -> tuple[str, list[int]]:
    """Expands macro_rules! vec { () => { Vec::new() }; ($($element:expr),+ $(,)?) => { ... }; }."""
    body = raw_tokens.strip()
    if body == "":
        return "Vec::new()", []
    # Strip optional trailing comma handled by $(,)?
    if body.endswith(","):
        body = body[:-1].strip()
    parts = [p.strip() for p in body.split(",") if p.strip()]
    if not parts:
        raise SyntaxError("unexpected lone comma in vec! invocation")
    lines = ["{", "    let mut temp_vec = Vec::new();"]
    values: list[int] = []
    for p in parts:
        if not re.fullmatch(r"-?\d+", p):
            raise SyntaxError(f"unsupported literal expression `{p}` in offline evaluator")
        lines.append(f"    temp_vec.push({p});")
        values.append(int(p))
    lines.append("    temp_vec")
    lines.append("}")
    return "\n".join(lines), values


def expand_derive_debug(struct_name: str, fields: list[str]) -> str:
    """Models a derive procedural macro generating an impl fmt::Debug skeleton from TokenStream metadata."""
    field_calls = "".join(f'.field("{f}", &self.{f})' for f in fields)
    return (
        f"impl std::fmt::Debug for {struct_name} {{ "
        f'fn fmt(&self, f: &mut std::fmt::Formatter<\'_>) -> std::fmt::Result {{ '
        f'f.debug_struct("{struct_name}"){field_calls}.finish() }} }}'
    )


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

    # Case 1: Simple declarative macro_rules! greet!($name:expr)
    expanded_greet = expand_greet('"World"')
    actual_1 = {
        "expanded_code": expanded_greet,
        "simulated_output": "Hello, World!",
    }
    expected_1 = {
        "expanded_code": 'println!("Hello, {}!", "World");',
        "simulated_output": "Hello, World!",
    }
    cases.append(dict(
        name="macro_rules_simple_greet",
        summary="Verify macro_rules! greet!($name:expr) captures expression token and expands println!",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: Variadic repetition vec![] / vec![1, 2, 3] / trailing comma vec![1, 2, 3,]
    empty_code, empty_val = expand_vec("")
    three_code, three_val = expand_vec("1, 2, 3")
    trailing_code, trailing_val = expand_vec("1, 2, 3,")
    actual_2 = {
        "empty_arm": [empty_code, empty_val],
        "three_val": three_val,
        "push_count": three_code.count("temp_vec.push("),
        "trailing_comma_matches_identical": (three_code == trailing_code and three_val == trailing_val),
    }
    expected_2 = {
        "empty_arm": ["Vec::new()", []],
        "three_val": [1, 2, 3],
        "push_count": 3,
        "trailing_comma_matches_identical": True,
    }
    cases.append(dict(
        name="macro_rules_vec_repetition_and_trailing_comma",
        summary="Verify vec! empty arm, $($element:expr),+ repetition, and $(,)? optional trailing comma",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: Procedural macro categories (Derive / Attribute / Function-like) & TokenStream expansion
    derive_code = expand_derive_debug("Point", ["x", "y"])
    proc_macro_kinds = {
        "derive": "#[derive(Copy, Debug)]",
        "attribute": "#[route(GET, \"/\")]",
        "function_like": "sql!(SELECT * FROM users)",
    }
    actual_3 = {
        "derive_impl_has_debug_struct": 'f.debug_struct("Point").field("x", &self.x).field("y", &self.y).finish()' in derive_code,
        "proc_macro_kind_count": len(proc_macro_kinds),
        "derive_is_derive_macro": proc_macro_kinds["derive"].startswith("#[derive("),
    }
    expected_3 = {
        "derive_impl_has_debug_struct": True,
        "proc_macro_kind_count": 3,
        "derive_is_derive_macro": True,
    }
    cases.append(dict(
        name="procedural_macro_derive_and_kinds",
        summary="Verify procedural macro TokenStream-style #[derive(Debug)] code generation and macro categories",
        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-macros-lab/explore-macros.py

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

下载课程关联工程包:Rust

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

下载课程关联工程包:Rust

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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