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

运行离线 Python 校验:Swift 协议扩展默认实现、条件符合与见证表静态/动态派发

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。explore-protocol-extensions.py
explore-protocol-extensions.py199 行
"""Offline CPython 3.12.14 semantic verifier for Swift Protocol Extensions & POP (CH36)."""
import json
from dataclasses import dataclass


class ConformanceError(TypeError):
    pass


# --- Default implementation via protocol extension ---
class GreetableDefault:
    def greet(self) -> str:
        return f"你好,我是 {self.name}"


@dataclass
class Guest(GreetableDefault):
    name: str


@dataclass
class Vip(GreetableDefault):
    name: str

    def greet(self) -> str:
        return f"贵宾 {self.name},欢迎回来"


# --- Conditional conformance ---
@dataclass
class Order:
    amount: float

    def summary(self) -> str:
        return f"订单 {self.amount:.1f} 元"


def payable_array_summary(items: list) -> str:
    if not all(isinstance(x, Order) for x in items):
        raise ConformanceError("Array<Int> does not conditionally conform to Payable")
    total = sum(x.amount for x in items)
    return f"共 {len(items)} 笔,合计 {total:.1f} 元"


@dataclass
class Player:
    name: str
    score: int

    def is_better_than(self, other: "Player") -> bool:
        return self.score > other.score


def collection_first_or_nil(seq: list):
    return seq[0] if seq else None


# --- Protocol Witness Table (PWT) model for Static vs Dynamic Dispatch ---
class ExistentialBox:
    def __init__(self, value, protocol_requirements: set[str], ext_methods: dict) -> None:
        self._value = value
        self._reqs = protocol_requirements
        self._ext = ext_methods

    def call(self, method_name: str):
        # Dynamic dispatch ONLY if method is declared in protocol body (in witness table)
        if method_name in self._reqs:
            return getattr(self._value, method_name)()
        # Extension-only methods are statically dispatched to the protocol extension implementation
        return self._ext[method_name](self._value)


@dataclass
class Athlete:
    name: str

    def run(self) -> str:
        return f"{self.name} 在冲刺"


def case_default_implementation():
    g = Guest("访客")
    v = Vip("小明")
    actual = {"guest": g.greet(), "vip": v.greet()}
    expected = {"guest": "你好,我是 访客", "vip": "贵宾 小明,欢迎回来"}
    return {
        "name": "protocol_extension_default_impl",
        "summary": "Verify Guest inherits protocol extension default greet() while Vip overrides it.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_conditional_conformance():
    orders = [Order(19.5), Order(30.5)]
    order_summary = payable_array_summary(orders)
    int_array_rejected = False
    try:
        payable_array_summary([1, 2, 3])
    except ConformanceError:
        int_array_rejected = True

    a = Player("小明", 90)
    b = Player("小红", 85)
    actual = {
        "orders_summary": order_summary,
        "int_array_rejected": int_array_rejected,
        "player_better": a.is_better_than(b),
        "first_or_nil_non_empty": collection_first_or_nil([10, 20, 30]) or 0,
        "first_or_nil_empty": collection_first_or_nil([]) or 0,
    }
    expected = {
        "orders_summary": "共 2 笔,合计 50.0 元",
        "int_array_rejected": True,
        "player_better": True,
        "first_or_nil_non_empty": 10,
        "first_or_nil_empty": 0,
    }
    return {
        "name": "conditional_conformance_and_self_constraint",
        "summary": "Verify conditional Array: Payable where Element: Payable, where Self: Equatable, and Collection extension.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_static_vs_dynamic_dispatch():
    ext_run = {"run": lambda self: f"{self.name} 在慢跑"}

    # Protocol 1: run() is NOT in protocol requirements -> static dispatch on existential
    athlete = Athlete("小明")
    concrete_call = athlete.run()
    existential_ext_only = ExistentialBox(athlete, protocol_requirements=set(), ext_methods=ext_run)
    static_dispatch_call = existential_ext_only.call("run")

    # Protocol 2: run() IS in protocol requirements -> dynamic dispatch via witness table
    sprinter = Athlete("小红")
    existential_req = ExistentialBox(sprinter, protocol_requirements={"run"}, ext_methods=ext_run)
    dynamic_dispatch_call = existential_req.call("run")

    actual = {
        "concrete_type_call": concrete_call,
        "existential_extension_only_static": static_dispatch_call,
        "existential_requirement_dynamic": dynamic_dispatch_call,
    }
    expected = {
        "concrete_type_call": "小明 在冲刺",
        "existential_extension_only_static": "小明 在慢跑",
        "existential_requirement_dynamic": "小红 在冲刺",
    }
    return {
        "name": "static_vs_dynamic_dispatch_witness_table",
        "summary": "Verify protocol witness table dispatch: extension-only members statically dispatch while protocol requirements dynamically dispatch.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pop_tradeoffs():
    rules = {
        "protocol_extension_stored_properties_allowed": False,
        "structs_and_enums_can_share_impl": True,
        "requirement_member_prefers_conformer": True,
        "extension_only_member_via_existential_uses_extension": True,
    }
    expected = {
        "protocol_extension_stored_properties_allowed": False,
        "structs_and_enums_can_share_impl": True,
        "requirement_member_prefers_conformer": True,
        "extension_only_member_via_existential_uses_extension": True,
    }
    return {
        "name": "pop_tradeoffs_and_constraints",
        "summary": "Verify protocol-oriented programming rules: no stored properties in extensions and dispatch precedence.",
        "expected": expected,
        "actual": rules,
        "passed": rules == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_default_implementation(),
            case_conditional_conformance(),
            case_static_vs_dynamic_dispatch(),
            case_pop_tradeoffs(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

入口文件:projects/swift-protocol-extensions-lab/explore-protocol-extensions.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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