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

离线校验 Rust 六大类运算符、向零整除、补码按位取反与 ? / 范围语义

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

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


def rust_trunc_div(a: int, b: int) -> int:
    # Rust integer division truncates toward zero
    q = abs(a) // abs(b)
    return -q if (a < 0) ^ (b < 0) else q


def rust_trunc_rem(a: int, b: int) -> int:
    return a - rust_trunc_div(a, b) * b


def case_arithmetic_and_pow_ops():
    a, b = 10, 3
    expected = {
        "sample_5_2": {"add": 7, "sub": 3, "mul": 10, "div": 2, "rem": 1},
        "sample_10_3": {"add": 13, "sub": 7, "mul": 30, "div": 3, "rem": 1},
        "neg_trunc_div": -2,
        "neg_trunc_rem": -1,
        "int_pow": 8,
        "float_powf": round(math.pow(2.0, 2.5), 12),
        "rustc_installed": False,
    }
    actual = {
        "sample_5_2": {"add": 5 + 2, "sub": 5 - 2, "mul": 5 * 2, "div": rust_trunc_div(5, 2), "rem": rust_trunc_rem(5, 2)},
        "sample_10_3": {"add": a + b, "sub": a - b, "mul": a * b, "div": rust_trunc_div(a, b), "rem": rust_trunc_rem(a, b)},
        "neg_trunc_div": rust_trunc_div(-5, 2),
        "neg_trunc_rem": rust_trunc_rem(-5, 2),
        "int_pow": 2**3,
        "float_powf": round(2.0**2.5, 12),
        "rustc_installed": shutil.which("rustc") is not None,
    }
    return {
        "name": "arithmetic_and_pow_ops",
        "summary": "验证算术五则运算、向零截断整除与取余以及 pow/powf 乘方(区分 ^ 按位异或)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_relational_comparison_ops():
    x, y = 5, 10
    expected = {
        "table_checks": [True, True, True, False, True, True],
        "x5_y10": [False, True, False, True, False, True],
    }
    actual = {
        "table_checks": [5 == 5, 5 != 2, 5 > 2, 5 < 2, 5 >= 5, 2 <= 5],
        "x5_y10": [x == y, x != y, x > y, x < y, x >= y, x <= y],
    }
    return {
        "name": "relational_comparison_ops",
        "summary": "验证六种关系比较运算符 ==、!=、>、<、>=、<= 的布尔返回结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_logical_short_circuit_ops():
    rhs_calls = []

    def rhs(val: bool) -> bool:
        rhs_calls.append(val)
        return val

    and_short = False and rhs(True)
    or_short = True or rhs(False)
    a, b = True, False
    expected = {
        "a_and_b": False,
        "a_or_b": True,
        "not_a": False,
        "short_circuit_skipped_rhs": True,
    }
    actual = {
        "a_and_b": a and b,
        "a_or_b": a or b,
        "not_a": not a,
        "short_circuit_skipped_rhs": (not and_short) and or_short and (len(rhs_calls) == 0),
    }
    return {
        "name": "logical_short_circuit_ops",
        "summary": "验证 &&、||、! 真值表以及逻辑与/逻辑或短路求值不触发右侧副作用",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bitwise_twos_complement_ops():
    # Signed i32: !5 == ~5 == -6
    signed_ops = {
        "and": 5 & 3,
        "or": 5 | 3,
        "xor": 5 ^ 3,
        "not_i32": ~5,
        "shl": 5 << 1,
        "shr": 5 >> 1,
    }
    # Unsigned u8: x=0b1010 (10), y=0b1100 (12)
    x, y = 0b1010, 0b1100
    u8_bin = {
        "and": format(x & y, "b"),
        "or": format(x | y, "b"),
        "xor": format(x ^ y, "b"),
        "not_u8": format((~x) & 0xFF, "b"),
        "shl_1": format((x << 1) & 0xFF, "b"),
        "shr_1": format(x >> 1, "b"),
    }
    expected = {
        "signed_i32": {"and": 1, "or": 7, "xor": 6, "not_i32": -6, "shl": 10, "shr": 2},
        "u8_binary": {"and": "1000", "or": "1110", "xor": "110", "not_u8": "11110101", "shl_1": "10100", "shr_1": "101"},
    }
    actual = {"signed_i32": signed_ops, "u8_binary": u8_bin}
    return {
        "name": "bitwise_twos_complement_ops",
        "summary": "验证有符号 i32 按位取反 !5 == -6 与无符号 u8 按位运算二进制输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_compound_assignment_ops():
    n = 5
    trace = []
    n += 3
    trace.append(n)
    n *= 2
    trace.append(n)
    n >>= 1
    trace.append(n)
    x = 5
    x -= 2  # 3
    x = rust_trunc_div(x * 4, 2)  # 6
    x = rust_trunc_rem(x, 4)  # 2
    x &= 3  # 2
    x |= 1  # 3
    x ^= 2  # 1
    x <<= 2  # 4
    expected = {"demo_trace": [8, 16, 8], "full_chain_final": 4}
    actual = {"demo_trace": trace, "full_chain_final": x}
    return {
        "name": "compound_assignment_ops",
        "summary": "验证基本赋值与算术/位运算复合赋值(+=、*=、>>=、&=、|=、^=、<<=)状态轨迹",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_range_cast_try_ref_deref():
    half_open = list(range(1, 4))  # 1..4
    inclusive = list(range(1, 4))  # 1..=3
    r_0_5 = list(range(0, 5))  # 0..5
    r_0_eq_5 = list(range(0, 6))  # 0..=5
    cast_f64 = float(5)

    # Simulate ? operator propagation on Result
    def try_double(res: tuple[str, object]):
        tag, val = res
        if tag == "Err":
            return res
        return ("Ok", val * 2)

    # Simulate &x / *b / ref y
    a_cell = [10]
    deref_b = a_cell[0]
    ref_y = a_cell[0]

    expected = {
        "range_1_to_4": [1, 2, 3],
        "range_1_eq_3": [1, 2, 3],
        "range_0_to_5": [0, 1, 2, 3, 4],
        "range_0_eq_5": [0, 1, 2, 3, 4, 5],
        "cast_5_as_f64": 5.0,
        "try_ok": ["Ok", 14],
        "try_err": ["Err", "io_error"],
        "deref_and_ref": [10, 10],
    }
    actual = {
        "range_1_to_4": half_open,
        "range_1_eq_3": inclusive,
        "range_0_to_5": r_0_5,
        "range_0_eq_5": r_0_eq_5,
        "cast_5_as_f64": cast_f64,
        "try_ok": list(try_double(("Ok", 7))),
        "try_err": list(try_double(("Err", "io_error"))),
        "deref_and_ref": [deref_b, ref_y],
    }
    return {
        "name": "range_cast_try_ref_deref",
        "summary": "验证 .. / ..= 区间、as 显式转型、? 错误传播以及 &、* 与 ref 引用语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_arithmetic_and_pow_ops(),
        case_relational_comparison_ops(),
        case_logical_short_circuit_ops(),
        case_bitwise_twos_complement_ops(),
        case_compound_assignment_ops(),
        case_range_cast_try_ref_deref(),
    ]
    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-operators-lab/explore-operators.py

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

下载课程关联工程包:Rust

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

下载课程关联工程包:Rust

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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