"""Offline CPython 3.12.14 semantic verifier for Swift Value Semantics & Copy-on-Write (CH38)."""
import json
from dataclasses import dataclass
class ExclusiveAccessError(RuntimeError):
pass
@dataclass
class PointValue:
x: int
y: int
def copy(self) -> "PointValue":
return PointValue(self.x, self.y)
class PointReference:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
class RefCountedBuffer:
def __init__(self, value) -> None:
self.value = value
self.refcount = 1
class COWBox:
copy_allocations = 0
def __init__(self, value=None, _buf: RefCountedBuffer | None = None) -> None:
if _buf is not None:
_buf.refcount += 1
self._buf = _buf
else:
self._buf = RefCountedBuffer(value)
def copy_value(self) -> "COWBox":
return COWBox(_buf=self._buf)
def is_uniquely_referenced(self) -> bool:
return self._buf.refcount == 1
@property
def value(self):
return self._buf.value
@value.setter
def value(self, new_value) -> None:
if not self.is_uniquely_referenced():
self._buf.refcount -= 1
self._buf = RefCountedBuffer(new_value)
COWBox.copy_allocations += 1
else:
self._buf.value = new_value
class ScoreRef:
def __init__(self, point: int) -> None:
self.point = point
@dataclass
class StudentWithRef:
name: str
score: ScoreRef
def shallow_copy(self) -> "StudentWithRef":
return StudentWithRef(self.name, self.score)
class ExclusiveMemory:
def __init__(self, initial: int) -> None:
self._val = initial
self._write_locked = False
def read(self) -> int:
if self._write_locked:
raise ExclusiveAccessError("Simultaneous accesses to memory, but modification requires exclusive access.")
return self._val
def with_inout(self, fn):
if self._write_locked:
raise ExclusiveAccessError("inout arguments are not allowed to alias each other")
self._write_locked = True
try:
self._val = fn(self._val)
finally:
self._write_locked = False
def case_value_vs_reference():
p1 = PointValue(1, 2)
p2 = p1.copy()
p2.x = 100
q1 = PointReference(1, 2)
q2 = q1
q2.x = 100
# Function param passing
def move_val(pt: PointValue) -> PointValue:
c = pt.copy()
c.x += 1
return c
def move_ref(pt: PointReference) -> None:
pt.x += 1
v0 = PointValue(0, 0)
v_moved = move_val(v0)
r0 = PointReference(0, 0)
move_ref(r0)
# Immutable equivalence
im_c = PointReference(1, 2)
im_d = im_c
actual = {
"value_assign": [[p1.x, p1.y], [p2.x, p2.y]],
"ref_assign": [[q1.x, q1.y], [q2.x, q2.y]],
"param_value": [v0.x, v_moved.x],
"param_ref": r0.x,
"immutable_ref_same_identity": im_c is im_d,
}
expected = {
"value_assign": [[1, 2], [100, 2]],
"ref_assign": [[100, 2], [100, 2]],
"param_value": [0, 1],
"param_ref": 1,
"immutable_ref_same_identity": True,
}
return {
"name": "value_vs_reference_and_immutability",
"summary": "Verify struct copy isolation vs class shared reference on assignment/passing and observable equivalence when immutable.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cow_buffer():
COWBox.copy_allocations = 0
x = COWBox("example.com")
y = x.copy_value()
shared_before_write = x._buf is y._buf
allocs_after_assign = COWBox.copy_allocations
y.value = "SWIFT"
shared_after_first_write = x._buf is y._buf
allocs_after_first_write = COWBox.copy_allocations
# Second write on y is uniquely referenced -> in-place mutation, no extra copy!
y.value = "SWIFT-6"
allocs_after_second_write = COWBox.copy_allocations
# Standard array COW model
list1 = [1, 2, 3]
list2 = list(list1)
list2.append(4)
actual = {
"shared_before_write": shared_before_write,
"allocs_after_assign": allocs_after_assign,
"shared_after_first_write": shared_after_first_write,
"allocs_after_first_write": allocs_after_first_write,
"allocs_after_second_write": allocs_after_second_write,
"values": [x.value, y.value],
"cow_arrays": [list1, list2],
}
expected = {
"shared_before_write": True,
"allocs_after_assign": 0,
"shared_after_first_write": False,
"allocs_after_first_write": 1,
"allocs_after_second_write": 1,
"values": ["example.com", "SWIFT-6"],
"cow_arrays": [[1, 2, 3], [1, 2, 3, 4]],
}
return {
"name": "cow_buffer_and_uniquely_referenced",
"summary": "Verify Copy-on-Write buffer sharing on copy, single copy allocation when refcount > 1 on write, and in-place mutation when uniquely referenced.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_struct_with_reference_trap():
shared_score = ScoreRef(60)
a = StudentWithRef("小明", shared_score)
b = a.shallow_copy()
same_ref = a.score is b.score
b.name = "小红"
b.score.point = 100
actual = {
"same_score_instance": same_ref,
"student_a": [a.name, a.score.point],
"student_b": [b.name, b.score.point],
}
expected = {
"same_score_instance": True,
"student_a": ["小明", 100],
"student_b": ["小红", 100],
}
return {
"name": "struct_with_reference_trap_and_fixes",
"summary": "Verify struct containing class property shares mutable reference across copies unless immutable/COW/deep-copied.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_inout_and_exclusive_access():
score = ExclusiveMemory(60)
score.with_inout(lambda s: s + 10)
counter = ExclusiveMemory(0)
counter.with_inout(lambda c: c + 2)
p1 = ExclusiveMemory(42)
p2 = ExclusiveMemory(30)
total = p1.read() + p2.read()
p1.with_inout(lambda _: total // 2)
p2.with_inout(lambda _: total - total // 2)
# Overlapping read + write on stepSize traps
step_size = ExclusiveMemory(1)
overlap_trapped = False
try:
step_size.with_inout(lambda cur: cur + step_size.read())
except ExclusiveAccessError:
overlap_trapped = True
# Aliasing same variable as two inout parameters blocked
alias_blocked = False
try:
p1.with_inout(lambda _: p1.with_inout(lambda v: v))
except ExclusiveAccessError:
alias_blocked = True
actual = {
"score_after_bonus": score.read(),
"counter_after_twice": counter.read(),
"balanced_scores": [p1.read(), p2.read()],
"simultaneous_read_write_trapped": overlap_trapped,
"inout_aliasing_blocked": alias_blocked,
}
expected = {
"score_after_bonus": 70,
"counter_after_twice": 2,
"balanced_scores": [36, 36],
"simultaneous_read_write_trapped": True,
"inout_aliasing_blocked": True,
}
return {
"name": "inout_and_exclusive_access",
"summary": "Verify inout in-place modification, simultaneous read/write conflict trap, and inout argument aliasing error.",
"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_value_vs_reference(),
case_cow_buffer(),
case_struct_with_reference_trap(),
case_inout_and_exclusive_access(),
],
}
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-value-semantics-lab/explore-value-semantics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-value-semantics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2129.zip