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

运行离线 Python 校验:Swift 扩展属性/方法/下标/泛型 where 与 Swift 6 @retroactive 检查

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


class ExtensionRuleError(Exception):
    pass


def double_km(v: float) -> float:
    return v * 1_000.0


def double_cm(v: float) -> float:
    return v / 100.0


def int_repetitions(n: int, task) -> None:
    for _ in range(n):
        task()


def int_digit_subscript(value: int, digit_index: int) -> int:
    base = 10 ** digit_index
    return (value // base) % 10


def int_kind(value: int) -> str:
    if value == 0:
        return "zero"
    return "positive" if value > 0 else "negative"


@dataclass
class CounterStruct:
    count: int = 0
    is_let: bool = False

    def increment(self) -> None:
        if self.is_let:
            raise ExtensionRuleError("cannot use mutating member on immutable value: 'counter' is a 'let' constant")
        self.count += 1

    def describe(self) -> str:
        return f"当前计数:{self.count}"


@dataclass
class RectSize:
    width: float = 0.0
    height: float = 0.0

    @classmethod
    def square(cls, side: float) -> "RectSize":
        return cls(width=side, height=side)


class GenericStack:
    def __init__(self, element_equatable: bool = True) -> None:
        self._items: list = []
        self._equatable = element_equatable

    def push(self, item) -> None:
        self._items.append(item)

    def pop(self):
        return self._items.pop() if self._items else None

    @property
    def top(self):
        return self._items[-1] if self._items else None

    @property
    def is_empty(self) -> bool:
        return len(self._items) == 0

    def contains(self, item) -> bool:
        if not self._equatable:
            raise ExtensionRuleError("referencing instance method 'contains' requires Element conform to 'Equatable'")
        return item in self._items


def check_retroactive(declaring_mod: str, type_mod: str, proto_mod: str, has_attr: bool) -> dict:
    is_retroactive = declaring_mod != type_mod and declaring_mod != proto_mod
    if is_retroactive and not has_attr:
        return {"status": "warning", "message": "add '@retroactive' to silence this warning"}
    if not is_retroactive and has_attr:
        return {"status": "warning", "message": "'retroactive' attribute does not apply"}
    return {"status": "clean", "message": "ok"}


def case_computed_props_methods_and_init():
    dist = 3.0
    rep_out: list[str] = []
    int_repetitions(3, lambda: rep_out.append("SWIFT"))

    c = CounterStruct()
    c.increment()
    c.increment()

    let_blocked = False
    try:
        CounterStruct(is_let=True).increment()
    except ExtensionRuleError:
        let_blocked = True

    sq = RectSize.square(5.0)
    actual = {
        "km": double_km(dist),
        "cm": double_cm(dist),
        "repetitions": rep_out,
        "counter": c.describe(),
        "let_mutating_blocked": let_blocked,
        "square_size": [sq.width, sq.height],
    }
    expected = {
        "km": 3000.0,
        "cm": 0.03,
        "repetitions": ["SWIFT", "SWIFT", "SWIFT"],
        "counter": "当前计数:2",
        "let_mutating_blocked": True,
        "square_size": [5.0, 5.0],
    }
    return {
        "name": "computed_props_methods_and_init",
        "summary": "Verify extension computed properties on Double, repetitions on Int, mutating extension method on var vs let, and delegating init on struct.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_subscript_and_nested_type():
    num = 746381295
    digits = [int_digit_subscript(num, i) for i in (0, 1, 2, 8)]
    labels = {
        "negative": lambda v: f"{v} 是负数",
        "zero": lambda v: f"{v} 是零",
        "positive": lambda v: f"{v} 是正数",
    }
    described = [labels[int_kind(v)](v) for v in (-7, 0, 42)]
    actual = {"digits": digits, "described_kinds": described}
    expected = {
        "digits": [5, 9, 2, 7],
        "described_kinds": ["-7 是负数", "0 是零", "42 是正数"],
    }
    return {
        "name": "subscript_and_nested_type",
        "summary": "Verify decimal digit subscript extension on Int and nested Int.NumberKind enum classification.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_protocol_conformance_and_generic_where():
    user_greet = f"Hello, {'SwiftDev'}! Welcome to example.com"
    str_greet = f"Hello, {'Swift'}!"

    st = GenericStack(element_equatable=True)
    for v in (10, 20, 30):
        st.push(v)
    top_before = st.top
    has_20 = st.contains(20)
    has_99 = st.contains(99)
    popped = st.pop()
    empty_after = st.is_empty

    non_eq_blocked = False
    try:
        GenericStack(element_equatable=False).contains(object())
    except ExtensionRuleError:
        non_eq_blocked = True

    actual = {
        "user_greet": user_greet,
        "string_greet": str_greet,
        "stack_results": [top_before, has_20, has_99, popped, empty_after],
        "non_equatable_contains_blocked": non_eq_blocked,
    }
    expected = {
        "user_greet": "Hello, SwiftDev! Welcome to example.com",
        "string_greet": "Hello, Swift!",
        "stack_results": [30, True, False, 30, False],
        "non_equatable_contains_blocked": True,
    }
    return {
        "name": "protocol_conformance_and_generic_where",
        "summary": "Verify retroactive-free protocol conformance via extension on User/String and conditional generic extension where Element: Equatable.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_extension_limits_and_retroactive():
    unmarked = check_retroactive("App", "LibA", "LibB", has_attr=False)
    marked = check_retroactive("App", "LibA", "LibB", has_attr=True)
    redundant = check_retroactive("LibA", "LibA", "LibB", has_attr=True)
    formatted = f"Point(x: {42})"

    actual = {
        "stored_property_in_extension_allowed": False,
        "deinit_in_extension_allowed": False,
        "override_in_extension_allowed": False,
        "cross_module_without_attr": unmarked["status"],
        "cross_module_with_retroactive": marked["status"],
        "own_module_with_retroactive": redundant["status"],
        "formatted_point": formatted,
    }
    expected = {
        "stored_property_in_extension_allowed": False,
        "deinit_in_extension_allowed": False,
        "override_in_extension_allowed": False,
        "cross_module_without_attr": "warning",
        "cross_module_with_retroactive": "clean",
        "own_module_with_retroactive": "warning",
        "formatted_point": "Point(x: 42)",
    }
    return {
        "name": "extension_limits_and_retroactive",
        "summary": "Verify extension prohibitions (stored properties, deinit, override) and Swift 6 @retroactive conformance diagnostics.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_computed_props_methods_and_init(),
            case_subscript_and_nested_type(),
            case_protocol_conformance_and_generic_where(),
            case_extension_limits_and_retroactive(),
        ],
    }
    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-extensions-lab/explore-extensions.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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