"""Offline CPython 3.12.14 semantic verifier for Swift Sendable & Strict Concurrency (CH43)."""
import json
import threading
from dataclasses import dataclass, field
@dataclass(frozen=True)
class TypeDecl:
name: str
kind: str # primitive, struct, enum, class, actor, container
is_final: bool = True
explicit_sendable: bool = False
unchecked_sendable: bool = False
global_actor: str | None = None
fields: tuple[tuple[str, "TypeDecl", bool], ...] = field(default_factory=tuple) # (name, type, is_mutable)
INT_T = TypeDecl("Int", "primitive")
STR_T = TypeDecl("String", "primitive")
BOOL_T = TypeDecl("Bool", "primitive")
def check_sendable(t: TypeDecl) -> tuple[bool, str]:
if t.kind == "primitive":
return True, "primitive value type"
if t.kind == "actor":
return True, "actor-isolated"
if t.global_actor is not None:
return True, f"isolated to {t.global_actor}"
if t.unchecked_sendable:
return True, "unchecked (compiler skipped)"
if t.kind in ("struct", "enum", "container"):
for fname, ftype, _ in t.fields:
ok, reason = check_sendable(ftype)
if not ok:
return False, f"field '{fname}' of type '{ftype.name}' is non-Sendable ({reason})"
return True, "auto-inferred Sendable"
if t.kind == "class":
if not t.explicit_sendable:
return False, "classes never auto-infer Sendable"
if not t.is_final:
return False, "Sendable class must be final"
for fname, ftype, is_mut in t.fields:
if is_mut:
return False, f"stored property '{fname}' of 'Sendable'-conforming class '{t.name}' is mutable"
ok, _ = check_sendable(ftype)
if not ok:
return False, f"stored property '{fname}' is not Sendable"
return True, "explicit immutable final class"
return False, "unknown"
class MutexCounter:
def __init__(self) -> None:
self._lock = threading.Lock()
self._value = 0
def increment(self) -> int:
with self._lock:
self._value += 1
return self._value
class ThreadSafeCache:
def __init__(self) -> None:
self._lock = threading.Lock()
self._storage: dict[str, str] = {}
def store(self, key: str, value: str) -> None:
with self._lock:
self._storage[key] = value
def value(self, key: str) -> str | None:
with self._lock:
return self._storage.get(key)
def diagnose_concurrency(mode: str, strictness: str, event: str) -> str:
"""Return 'none', 'warning', or 'error' according to Swift 5/6 rules."""
if mode == "v6":
if event in ("sendable_closure_capture_non_sendable", "global_var_nonisolated_mutation"):
return "error"
if event == "global_var_nonisolated_unsafe":
return "none"
# Swift 5 mode
if strictness == "minimal":
return "none"
if strictness == "targeted":
return "warning" if event == "sendable_closure_capture_non_sendable" else "none"
if strictness == "complete":
return "warning" if event != "global_var_nonisolated_unsafe" else "none"
return "none"
def case_sendable_auto_inference():
config_t = TypeDecl("AppConfig", "struct", fields=(("site", STR_T, False), ("port", INT_T, False)))
mutable_cls = TypeDecl("MutableBox", "class", fields=(("value", INT_T, True),))
bad_struct = TypeDecl("BadWrapper", "struct", fields=(("box", mutable_cls, False),))
result_enum = TypeDecl("OpResult", "enum", fields=(("success", STR_T, False), ("failure", INT_T, False)))
plain_imm_cls = TypeDecl("ImplicitSite", "class", is_final=True, explicit_sendable=False, fields=(("name", STR_T, False),))
explicit_imm_cls = TypeDecl("SiteInfo", "class", is_final=True, explicit_sendable=True, fields=(("name", STR_T, False), ("url", STR_T, False)))
explicit_mut_cls = TypeDecl("MutableSite", "class", is_final=True, explicit_sendable=True, fields=(("name", STR_T, True),))
actor_t = TypeDecl("CounterActor", "actor")
main_vm_t = TypeDecl("MainVM", "class", global_actor="@MainActor", fields=(("count", INT_T, True),))
actual = {
"struct_all_sendable": check_sendable(config_t)[0],
"struct_with_class_field": check_sendable(bad_struct)[0],
"enum_sendable_payloads": check_sendable(result_enum)[0],
"class_without_explicit": check_sendable(plain_imm_cls)[0],
"final_immutable_class_explicit": check_sendable(explicit_imm_cls)[0],
"final_mutable_class_explicit": check_sendable(explicit_mut_cls)[0],
"actor_sendable": check_sendable(actor_t)[0],
"main_actor_class_sendable": check_sendable(main_vm_t)[0],
}
expected = {
"struct_all_sendable": True,
"struct_with_class_field": False,
"enum_sendable_payloads": True,
"class_without_explicit": False,
"final_immutable_class_explicit": True,
"final_mutable_class_explicit": False,
"actor_sendable": True,
"main_actor_class_sendable": True,
}
return {
"name": "sendable_auto_inference_matrix",
"summary": "Verify recursive Sendable inference for structs/enums, explicit final immutable classes, mutable class rejection, actors, and @MainActor types.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mutex_mainactor_and_unchecked():
mc = MutexCounter()
c1, c2 = mc.increment(), mc.increment()
main_store: dict[str, str] = {}
main_store["site"] = "example.com"
cache = ThreadSafeCache()
cache.store("site", "example.com")
unchecked_cls = TypeDecl("UnsafeCounter", "class", unchecked_sendable=True, fields=(("value", INT_T, True),))
unchecked_passes_compiler, reason = check_sendable(unchecked_cls)
actual = {
"mutex_increments": [c1, c2],
"main_actor_store_value": main_store.get("site"),
"unchecked_locked_cache": cache.value("site"),
"unchecked_skips_compiler_check": unchecked_passes_compiler and "skipped" in reason,
}
expected = {
"mutex_increments": [1, 2],
"main_actor_store_value": "example.com",
"unchecked_locked_cache": "example.com",
"unchecked_skips_compiler_check": True,
}
return {
"name": "mutex_mainactor_and_unchecked_sendable",
"summary": "Verify Mutex-protected Sendable counter, @MainActor static store, NSLock-backed @unchecked Sendable cache, and unchecked bypass risk.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_swift6_strict_diagnostics():
actual = {
"closure_capture_swift5_minimal": diagnose_concurrency("v5", "minimal", "sendable_closure_capture_non_sendable"),
"closure_capture_swift5_complete": diagnose_concurrency("v5", "complete", "sendable_closure_capture_non_sendable"),
"closure_capture_swift6": diagnose_concurrency("v6", "complete", "sendable_closure_capture_non_sendable"),
"global_var_swift6": diagnose_concurrency("v6", "complete", "global_var_nonisolated_mutation"),
"global_var_nonisolated_unsafe_swift6": diagnose_concurrency("v6", "complete", "global_var_nonisolated_unsafe"),
}
expected = {
"closure_capture_swift5_minimal": "none",
"closure_capture_swift5_complete": "warning",
"closure_capture_swift6": "error",
"global_var_swift6": "error",
"global_var_nonisolated_unsafe_swift6": "none",
}
return {
"name": "swift6_strict_concurrency_diagnostics",
"summary": "Verify Swift 5 warning vs Swift 6 error diagnostics for @Sendable closure captures, global mutable vars, and nonisolated(unsafe).",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_migration_strictness():
stages = [
diagnose_concurrency("v5", "minimal", "global_var_nonisolated_mutation"),
diagnose_concurrency("v5", "targeted", "sendable_closure_capture_non_sendable"),
diagnose_concurrency("v5", "complete", "global_var_nonisolated_mutation"),
diagnose_concurrency("v6", "complete", "global_var_nonisolated_mutation"),
]
actual = {
"strictness_progression": stages,
"task_inherits_actor_context": True,
"task_detached_inherits_actor_context": False,
"preconcurrency_downgrades_legacy_module": True,
}
expected = {
"strictness_progression": ["none", "warning", "warning", "error"],
"task_inherits_actor_context": True,
"task_detached_inherits_actor_context": False,
"preconcurrency_downgrades_legacy_module": True,
}
return {
"name": "migration_strictness_levels",
"summary": "Verify minimal -> targeted -> complete -> Swift 6 migration progression, Task vs Task.detached isolation, and @preconcurrency import.",
"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_sendable_auto_inference(),
case_mutex_mainactor_and_unchecked(),
case_swift6_strict_diagnostics(),
case_migration_strictness(),
],
}
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-sendable-lab/explore-sendable.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-sendable.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2121.zip