"""Offline CPython 3.12.14 semantic verifier for Swift Opaque (some) vs Existential (any) Types (CH37)."""
import json
import math
from dataclasses import dataclass
class OpaqueTypeError(TypeError):
pass
@dataclass
class Circle:
radius: float
def area(self) -> float:
return math.pi * self.radius * self.radius
@dataclass
class Square:
side: float
def area(self) -> float:
return self.side * self.side
def check_opaque_return_types(return_branch_types: list[str]) -> str:
unique = set(return_branch_types)
if len(unique) != 1:
raise OpaqueTypeError(
f"function declares an opaque return type 'some Shape', but return statements have mismatched underlying types: {sorted(unique)}"
)
return next(iter(unique))
class ExistentialShape:
def __init__(self, boxed) -> None:
self._boxed = boxed
def area(self) -> float:
return self._boxed.area()
def downcast(self, cls):
return self._boxed if isinstance(self._boxed, cls) else None
@dataclass
class TypedContainer:
item_type: str
count: int
def count_int_container(container: TypedContainer) -> int:
if container.item_type != "Int":
raise OpaqueTypeError(f"Primary associated type mismatch: expected Int, got {container.item_type}")
return container.count
def case_opaque_some():
underlying = check_opaque_return_types(["Circle"])
c = Circle(2.0)
mismatch_rejected = False
try:
check_opaque_return_types(["Circle", "Square"])
except OpaqueTypeError:
mismatch_rejected = True
actual = {
"circle_area": f"{c.area():.4f}",
"runtime_type": type(c).__name__,
"single_underlying_type": underlying,
"mixed_branches_rejected": mismatch_rejected,
}
expected = {
"circle_area": "12.5664",
"runtime_type": "Circle",
"single_underlying_type": "Circle",
"mixed_branches_rejected": True,
}
return {
"name": "opaque_some_single_underlying_type",
"summary": "Verify 'some Shape' fixes a single static underlying type while preserving runtime identity and rejecting heterogeneous branches.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_existential_any():
shape = ExistentialShape(Circle(1.0))
first_area = f"{shape.area():.4f}"
shape = ExistentialShape(Square(3.0))
second_area = f"{shape.area():.4f}"
shapes = [
ExistentialShape(Circle(1.0)),
ExistentialShape(Square(2.0)),
ExistentialShape(Circle(3.0)),
]
total = sum(s.area() for s in shapes)
unboxed_sq = shapes[1].downcast(Square)
actual = {
"reassigned_areas": [first_area, second_area],
"total_area": f"{total:.4f}",
"count": len(shapes),
"downcast_square_side": unboxed_sq.side if unboxed_sq else None,
}
expected = {
"reassigned_areas": ["3.1416", "9.0000"],
"total_area": "35.4159",
"count": 3,
"downcast_square_side": 2.0,
}
return {
"name": "existential_any_heterogeneous_box",
"summary": "Verify 'any Shape' existential box supports variable reassignment, heterogeneous arrays, and as? downcasting.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_primary_associated_types():
first_int = [10, 20, 30][0]
opaque_nums = [1, 2, 3, 4, 5]
any_col_list = [1, 2, 3]
any_col_set = {1, 1, 2, 3}
int_box = TypedContainer("Int", 7)
str_box = TypedContainer("String", 3)
wrong_assoc_rejected = False
try:
count_int_container(str_box)
except OpaqueTypeError:
wrong_assoc_rejected = True
actual = {
"first_int": first_int,
"some_collection": [len(opaque_nums), opaque_nums[0]],
"any_collection_counts": [len(any_col_list), len(any_col_set)],
"custom_primary_assoc_count": count_int_container(int_box),
"mismatched_primary_assoc_rejected": wrong_assoc_rejected,
}
expected = {
"first_int": 10,
"some_collection": [5, 1],
"any_collection_counts": [3, 3],
"custom_primary_assoc_count": 7,
"mismatched_primary_assoc_rejected": True,
}
return {
"name": "primary_associated_types",
"summary": "Verify SE-0346 primary associated type constraints (Collection<Int> and custom Container<Item>).",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_some_vs_any_rules():
actual = {
"some_allowed_on_computed_property": True,
"some_allowed_on_stored_property": False,
"some_dispatch": "static",
"any_dispatch": "dynamic_existential_box",
}
expected = {
"some_allowed_on_computed_property": True,
"some_allowed_on_stored_property": False,
"some_dispatch": "static",
"any_dispatch": "dynamic_existential_box",
}
return {
"name": "some_vs_any_vs_generics_matrix",
"summary": "Verify property placement rules (computed allowed, stored disallowed for some P) and dispatch models.",
"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_opaque_some(),
case_existential_any(),
case_primary_associated_types(),
case_some_vs_any_rules(),
],
}
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-opaque-types-lab/explore-opaque-types.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-opaque-types.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2112.zip