"""Offline CPython 3.12.14 semantic verifier for Swift Generics (CH33)."""
import json
class GenericConstraintError(TypeError):
pass
def swap_pair(a, b):
if type(a) is not type(b):
raise GenericConstraintError("Generic swap requires both arguments to share type T")
return b, a
def find_index(value, array: list) -> int | None:
for idx, item in enumerate(array):
if item == value:
return idx
return None
class Stack:
def __init__(self, element_type: type) -> None:
self.element_type = element_type
self._items: list = []
def push(self, item) -> None:
if not isinstance(item, self.element_type):
raise GenericConstraintError(f"Expected {self.element_type.__name__}, got {type(item).__name__}")
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:
return item in self._items
def max_element(self):
return max(self._items) if self._items else None
def joined_strings(self, sep: str = " - ") -> str:
if self.element_type is not str:
raise GenericConstraintError("where Element == String constraint not satisfied")
return sep.join(self._items)
class Box:
def __init__(self, value) -> None:
self.value = value
self.value_type = type(value).__name__
class BaseEntity:
pass
class SubEntity(BaseEntity):
pass
def generic_max(a, b):
return a if a > b else b
def hashable_desc(value) -> str:
hash(value) # verifies Hashable
return f"值:{value},描述:{value}"
def check_subclass(item) -> str:
if not isinstance(item, BaseEntity):
raise GenericConstraintError("T must inherit from BaseEntity")
return f"类型是 {type(item).__name__}"
def common_pairs(a: list, b: list) -> int:
if a and b and type(a[0]) is not type(b[0]):
raise GenericConstraintError("where C1.Element == C2.Element violated")
return sum(1 for x in a if x in b)
class IntList:
item_type = "Int"
def __init__(self) -> None:
self._items: list[int] = []
def append(self, item: int) -> None:
self._items.append(item)
@property
def count(self) -> int:
return len(self._items)
def __getitem__(self, i: int) -> int:
return self._items[i]
class StringList:
item_type = "String"
def __init__(self) -> None:
self._items: list[str] = []
def append(self, item: str) -> None:
self._items.append(item)
@property
def count(self) -> int:
return len(self._items)
def __getitem__(self, i: int) -> str:
return self._items[i]
def case_generic_swap_and_index():
s1, s2 = swap_pair("example.com", "SWIFT")
x, y = swap_pair(10, 99)
idx = find_index("swift", ["rust", "swift", "kotlin"])
mismatch_blocked = False
try:
swap_pair(10, "ten")
except GenericConstraintError:
mismatch_blocked = True
actual = {
"swapped_str": f"{s1} / {s2}",
"swapped_int": [x, y],
"found_index": idx,
"type_mismatch_blocked": mismatch_blocked,
}
expected = {
"swapped_str": "SWIFT / example.com",
"swapped_int": [99, 10],
"found_index": 1,
"type_mismatch_blocked": True,
}
return {
"name": "generic_swap_and_equatable_index",
"summary": "Verify generic swap<T> type inference & homogeneity check plus Equatable index search.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_generic_stack_and_box():
int_stack = Stack(int)
for n in (1, 2, 3):
int_stack.push(n)
str_stack = Stack(str)
str_stack.push("alpha")
str_stack.push("beta")
top1 = str_stack.top
popped = str_stack.pop()
top2 = str_stack.top
box = Box("Swift 泛型")
cross_push_blocked = False
try:
int_stack.push("not-an-int")
except GenericConstraintError:
cross_push_blocked = True
actual = {
"int_top": int_stack.top,
"str_trace": [top1, popped, top2],
"box_value": box.value,
"box_type": box.value_type,
"cross_type_blocked": cross_push_blocked,
}
expected = {
"int_top": 3,
"str_trace": ["beta", "beta", "alpha"],
"box_value": "Swift 泛型",
"box_type": "str",
"cross_type_blocked": True,
}
return {
"name": "generic_stack_and_box_types",
"summary": "Verify generic Stack<Int> and Stack<String> enforce element type specialization and Box<Value> type inference.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_constraints_and_where():
st = Stack(int)
for n in (30, 10, 20):
st.push(n)
pairs = common_pairs([1, 2, 3, 4], [2, 4, 6])
diff_elem_blocked = False
try:
common_pairs([1, 2], ["1", "2"])
except GenericConstraintError:
diff_elem_blocked = True
actual = {
"max_int": generic_max(3, 9),
"max_str": generic_max("apple", "swift"),
"hashable_info": hashable_desc("SWIFT"),
"class_constraint": check_subclass(SubEntity()),
"where_contains_10": st.contains(10),
"where_max": st.max_element(),
"where_common_pairs": pairs,
"where_same_element_enforced": diff_elem_blocked,
}
expected = {
"max_int": 9,
"max_str": "swift",
"hashable_info": "值:SWIFT,描述:SWIFT",
"class_constraint": "类型是 SubEntity",
"where_contains_10": True,
"where_max": 30,
"where_common_pairs": 2,
"where_same_element_enforced": True,
}
return {
"name": "type_constraints_and_where_clause",
"summary": "Verify Comparable/Hashable/class constraints and where-clause C1.Element == C2.Element matching.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_associatedtype_and_extension():
ints = IntList()
for v in (100, 200, 300):
ints.append(v)
strs = StringList()
strs.append("Swift")
strs.append("Generics")
str_stack = Stack(str)
for s in ("Swift", "TypeSafe", "example.com"):
str_stack.push(s)
int_stack_join_blocked = False
try:
Stack(int).joined_strings()
except GenericConstraintError:
int_stack_join_blocked = True
actual = {
"int_list": [ints.count, ints[0], ints.item_type],
"string_list": [strs.count, strs[1], strs.item_type],
"joined_string_stack": str_stack.joined_strings(),
"where_element_eq_string_enforced": int_stack_join_blocked,
}
expected = {
"int_list": [3, 100, "Int"],
"string_list": [2, "Generics", "String"],
"joined_string_stack": "Swift - TypeSafe - example.com",
"where_element_eq_string_enforced": True,
}
return {
"name": "associatedtype_and_generic_extension",
"summary": "Verify Container associatedtype Item inference/typealias and exact-type conditional extension where Element == String.",
"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_generic_swap_and_index(),
case_generic_stack_and_box(),
case_constraints_and_where(),
case_associatedtype_and_extension(),
],
}
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-generics-lab/explore-generics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-generics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2103.zip