"""Offline Swift 5/6 semantic verification lab for Chapter 10 (operators)."""
import json
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def swift_trunc_div(a: int, b: int) -> int:
# Swift integer division truncates toward zero
q = abs(a) // abs(b)
return -q if (a < 0) ^ (b < 0) else q
def swift_rem(a: int, b: int) -> int:
# Remainder keeps the sign of the dividend (a == b * (a/b) + a%b)
return a - swift_trunc_div(a, b) * b
def wrap_signed(val: int, bits: int) -> int:
mask = (1 << bits) - 1
u = val & mask
return u - (1 << bits) if u >= (1 << (bits - 1)) else u
def case_arithmetic_truncation_and_overflow_operators():
a, b = 10, 20
int64_max = (1 << 63) - 1
int64_min = -(1 << 63)
# Checked Int8 + traps on 127 + 1
checked_int8_trap = (127 + 1) > 127
expected = {
"basic_ops": [30, -10, 200, 2, 0],
"trunc_div_and_rem": [3, -3, 1, -1, 3.5],
"checked_int8_trapped": True,
"wrap_int64_max_plus_1": int64_min,
"wrap_int64_min_minus_1": int64_max,
"wrap_int8_100_mul_2": -56,
}
actual = {
"basic_ops": [a + b, a - b, a * b, swift_trunc_div(b, a), swift_rem(b, a)],
"trunc_div_and_rem": [swift_trunc_div(7, 2), swift_trunc_div(-7, 2), swift_rem(7, 3), swift_rem(-7, 3), 7.0 / 2],
"checked_int8_trapped": checked_int8_trap,
"wrap_int64_max_plus_1": wrap_signed(int64_max + 1, 64),
"wrap_int64_min_minus_1": wrap_signed(int64_min - 1, 64),
"wrap_int8_100_mul_2": wrap_signed(100 * 2, 8),
}
return {
"name": "arithmetic_truncation_and_overflow_operators",
"summary": "验证算术运算、向零截断除法与被除数同号求余、默认溢出陷阱及 &+/&-/&* 补码环绕",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_comparison_logic_and_bitwise_shifts():
a, b = 10, 20
# Short-circuit tracking
rhs_eval_count = 0
def rhs_probe():
nonlocal rhs_eval_count
rhs_eval_count += 1
return True
short_and = False and rhs_probe()
short_or = True or rhs_probe()
p, q = 60, 13
int8_lshift = wrap_signed(127 << 1, 8) # 0111_1111 &<< 1 = 1111_1110 = -2
int8_rshift = -128 >> 1 # arithmetic right shift preserves sign bit -> -64
expected = {
"cmp": [False, True, False, True, False, True],
"logic": [False, True, False, True],
"short_circuit_rhs_calls": 0,
"bitwise": [12, 61, 49, -61, 240, 15],
"masking_shifts": [-2, -64],
}
actual = {
"cmp": [a == b, a != b, a > b, a < b, a >= b, a <= b],
"logic": [short_and, short_or, not True, not False],
"short_circuit_rhs_calls": rhs_eval_count,
"bitwise": [p & q, p | q, p ^ q, ~p, p << 2, p >> 2],
"masking_shifts": [int8_lshift, int8_rshift],
}
return {
"name": "comparison_logic_and_bitwise_shifts",
"summary": "验证比较运算、&&/|| 短路求值、按位逻辑与补码取反以及 &<</&>> 掩码移位语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ranges_nil_coalescing_and_ternary():
closed = list(range(1, 4)) # 1...3
half_open = list(range(1, 3)) # 1..<3
names = ["Alpha", "Beta", "Gamma", "Swift"]
prefix_slice = names[:2] # names[...1]
suffix_slice = names[2:] # names[2...]
info = {"name": "BlueSky"}
opt_nil = None
opt_val = "www.bluesky.org"
expected = {
"closed_1_3": [1, 2, 3],
"half_open_1_3": [1, 2],
"one_sided_slices": [["Alpha", "Beta"], ["Gamma", "Swift"]],
"contains_3_and_6": [True, False],
"nil_coalesce": ["BlueSky", "www.bluesky.org", "BlueSky", "未知"],
"ternary": ["及格", 1],
}
actual = {
"closed_1_3": closed,
"half_open_1_3": half_open,
"one_sided_slices": [prefix_slice, suffix_slice],
"contains_3_and_6": [3 in range(1, 6), 6 in range(1, 6)],
"nil_coalesce": [
opt_nil if opt_nil is not None else "BlueSky",
opt_val if opt_val is not None else "BlueSky",
info.get("name", "未知"),
info.get("site", "未知"),
],
"ternary": ["及格" if 85 >= 60 else "不及格", 1 if True else 2],
}
return {
"name": "ranges_nil_coalescing_and_ternary",
"summary": "验证闭区间 ...、半开区间 ..<、单侧区间切片、空合运算符 ?? 与三元表达式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_swift_precedence_groups():
# Swift standard library precedence order (high -> low):
# BitwiseShift > Multiplication (* / % &* &) > Addition (+ - &+ &- | ^) > Range > Casting > NilCoalescing > Comparison > && > || > Ternary > Assignment
# In Swift, (a & b == c) parses as ((a & b) == c) because '&' is in MultiplicationPrecedence > ComparisonPrecedence!
a, b, c = 6, 3, 2
swift_bitwise_before_cmp = (a & b) == c # (6 & 3) == 2 -> 2 == 2 -> True
expr_default = 2 + ((3 * 4) % 5) # 2 + 12 % 5 = 4
expr_grouped = ((2 + 3) * 4) % 5 # 20 % 5 = 0
groups = [
"BitwiseShiftPrecedence", "MultiplicationPrecedence", "AdditionPrecedence",
"RangeFormationPrecedence", "CastingPrecedence", "NilCoalescingPrecedence",
"ComparisonPrecedence", "LogicalConjunctionPrecedence", "LogicalDisjunctionPrecedence",
"TernaryPrecedence", "AssignmentPrecedence",
]
expected = {
"expr_default": 4,
"expr_grouped": 0,
"swift_and_higher_than_eq": True,
"precedence_group_count": 11,
}
actual = {
"expr_default": expr_default,
"expr_grouped": expr_grouped,
"swift_and_higher_than_eq": swift_bitwise_before_cmp,
"precedence_group_count": len(groups),
}
return {
"name": "swift_precedence_groups",
"summary": "核对 Swift 11 个标准优先级组、& 高于 == 的 C 语言差异以及括号改写求值顺序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_arithmetic_truncation_and_overflow_operators(),
case_comparison_logic_and_bitwise_shifts(),
case_ranges_nil_coalescing_and_ternary(),
case_swift_precedence_groups(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
入口文件:projects/swift-operators-lab/explore-operators.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-operators.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2113.zip