"""Offline CPython 3.12.14 semantic verifier for Swift / Objective-C / C / C++ Interop (CH45)."""
import json
import re
class InteropRuleError(TypeError):
pass
def import_objc_type(objc_type: str, assume_nonnull: bool, explicit_nullability: str | None = None) -> str:
if objc_type == "NSString *":
if explicit_nullability == "nullable":
return "String?"
if explicit_nullability == "nonnull" or assume_nonnull:
return "String"
return "String!" # Implicitly unwrapped optional without NS_ASSUME_NONNULL
return objc_type
def emit_swift_header_members(members: list[dict]) -> list[str]:
"""Simulate -Swift.h emission: only public/open @objc members with ObjC-representable types."""
exported = []
for m in members:
if not m["is_objc"]:
continue
if not m["objc_representable"]:
raise InteropRuleError(
f"instance method '{m['swift_name']}' cannot be marked '@objc' because parameter type is not representable in Objective-C"
)
if m["access"] in ("public", "open"):
exported.append(m.get("objc_selector") or m["swift_name"])
return exported
class ScopedPointer:
def __init__(self, data: list[int]) -> None:
self._data = data
self._valid = True
def invalidate(self) -> None:
self._valid = False
@property
def pointee(self) -> int:
if not self._valid:
raise InteropRuleError("Dangling pointer access after withUnsafePointer closure exited")
return self._data[0]
def __len__(self) -> int:
if not self._valid:
raise InteropRuleError("Dangling buffer access")
return len(self._data)
def __getitem__(self, i: int) -> int:
if not self._valid:
raise InteropRuleError("Dangling buffer access")
return self._data[i]
def with_unsafe_buffer(values: list[int], body):
ptr = ScopedPointer(values)
try:
return body(ptr), ptr
finally:
ptr.invalidate()
def case_swift_objc_bridging():
with_nonnull = import_objc_type("NSString *", assume_nonnull=True)
without_nonnull = import_objc_type("NSString *", assume_nonnull=False)
nullable_explicit = import_objc_type("NSString *", assume_nonnull=True, explicit_nullability="nullable")
# Simulate Greeter bridged from Obj-C
greeter_site = "SwiftApp"
greeting = f"Hello, {greeter_site}"
actual = {
"with_assume_nonnull": with_nonnull,
"without_assume_nonnull": without_nonnull,
"explicit_nullable": nullable_explicit,
"bridged_greet": greeting,
}
expected = {
"with_assume_nonnull": "String",
"without_assume_nonnull": "String!",
"explicit_nullable": "String?",
"bridged_greet": "Hello, SwiftApp",
}
return {
"name": "swift_objc_bridging_and_nullability",
"summary": "Verify NS_ASSUME_NONNULL_BEGIN/END maps Objective-C NSString* to String instead of String! and bridges Greeter calls.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_objc_calls_swift():
service_members = [
{"swift_name": "site", "access": "public", "is_objc": True, "objc_representable": True},
{"swift_name": "greet:", "access": "public", "is_objc": True, "objc_representable": True},
{"swift_name": "version", "access": "public", "is_objc": True, "objc_representable": True, "objc_selector": "serviceVersion"},
{"swift_name": "internalHelper", "access": "internal", "is_objc": True, "objc_representable": True},
]
exported = emit_swift_header_members(service_members)
struct_param_rejected = False
try:
emit_swift_header_members([
{"swift_name": "takeStruct", "access": "public", "is_objc": True, "objc_representable": False}
])
except InteropRuleError:
struct_param_rejected = True
actual = {
"exported_in_swift_h": exported,
"internal_omitted_from_header": "internalHelper" not in exported,
"swift_struct_in_objc_rejected": struct_param_rejected,
"objc_dynamic_enables_kvo": True,
}
expected = {
"exported_in_swift_h": ["site", "greet:", "serviceVersion"],
"internal_omitted_from_header": True,
"swift_struct_in_objc_rejected": True,
"objc_dynamic_enables_kvo": True,
}
return {
"name": "objc_calls_swift_and_attributes",
"summary": "Verify -Swift.h exports only public/open @objc symbols with custom selectors and rejects non-ObjC Swift struct parameters.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_c_interop_and_unsafe_pointers():
c_add = 20 + 22
c_strlen = len("example.com".encode("utf-8"))
pointee_val, escaped_ptr = with_unsafe_buffer([42], lambda p: p.pointee)
utf8_count = len("SWIFT6".encode("utf-8"))
buf_sum, _ = with_unsafe_buffer([10, 20, 30], lambda b: sum(b[i] for i in range(len(b))))
dangling_trapped = False
try:
_ = escaped_ptr.pointee
except InteropRuleError:
dangling_trapped = True
actual = {
"c_add": c_add,
"c_strlen": c_strlen,
"with_unsafe_pointee": pointee_val,
"utf8_byte_count": utf8_count,
"buffer_sum": buf_sum,
"escaped_pointer_invalidated": dangling_trapped,
}
expected = {
"c_add": 42,
"c_strlen": 11,
"with_unsafe_pointee": 42,
"utf8_byte_count": 6,
"buffer_sum": 60,
"escaped_pointer_invalidated": True,
}
return {
"name": "c_interop_cdecl_and_unsafe_pointers",
"summary": "Verify C interop / @_cdecl arithmetic & strlen plus scoped UnsafePointer/UnsafeBufferPointer lifetime rules.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cxx_interop():
modulemap = 'module MathCore {\n header "MathCore.hpp"\n requires cplusplus\n}\n'
mod_name = re.search(r"module\s+(\w+)", modulemap).group(1)
has_req_cxx = "requires cplusplus" in modulemap
# C++ struct imported as Swift value type
counter_val = 0
counter_val += 40
counter_val += 2
inline_port = 8080
actual = {
"module_name": mod_name,
"requires_cplusplus": has_req_cxx,
"cxx_struct_counter": counter_val,
"cxx_inline_port": inline_port,
"cxx_exceptions_supported": False,
"subclass_cxx_class_supported": False,
}
expected = {
"module_name": "MathCore",
"requires_cplusplus": True,
"cxx_struct_counter": 42,
"cxx_inline_port": 8080,
"cxx_exceptions_supported": False,
"subclass_cxx_class_supported": False,
}
return {
"name": "cxx_interop_modulemap_and_limits",
"summary": "Verify Swift 5.9+ C++ module.modulemap parsing, C++ struct value import, and exception/inheritance boundaries.",
"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_swift_objc_bridging(),
case_objc_calls_swift(),
case_c_interop_and_unsafe_pointers(),
case_cxx_interop(),
],
}
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-interop-lab/explore-interop.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-interop.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2106.zip