蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Swift 版本规则、三大安全基石、COW 模型与字符串插值

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。explore-intro.py
explore-intro.py145 行
"""Offline Swift 5/6 semantic verification lab for Chapter 02 (intro)."""
import json
import re

VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"


def case_version_milestones_and_swift3_cleanup():
    milestones = [
        (2014, "1.0"), (2015, "2.0"), (2016, "3.0"), (2017, "4.0"),
        (2019, "5.0"), (2021, "5.5"), (2022, "5.7"), (2023, "5.9"), (2024, "6.0"),
    ]
    legacy_snippets = ["println(\"hi\")", "i++", "for var i = 0; i < 3; i += 1 {}"]
    legacy_patterns = [r"\bprintln\s*\(", r"\+\+", r"\bfor\s+var\b"]
    rejected = [any(re.search(p, s) for p in legacy_patterns) for s in legacy_snippets]
    expected = {"milestone_count": 9, "monotonic_years": True, "all_swift2_legacy_rejected": True}
    actual = {
        "milestone_count": len(milestones),
        "monotonic_years": all(a[0] < b[0] for a, b in zip(milestones, milestones[1:])),
        "all_swift2_legacy_rejected": all(rejected),
    }
    return {
        "name": "version_milestones_and_swift3_cleanup",
        "summary": "核对 Swift 1.0 至 6.0 九个里程碑版本时间顺序,并拦截 Swift 2 时代已废弃语法",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_safety_pillars_type_optional_overflow():
    # 1. Explicit conversion required between Int and Double
    def checked_add(lhs_type, lhs_val, rhs_type, rhs_val):
        if lhs_type != rhs_type:
            return {"ok": False, "error": f"cannot convert '{lhs_type}' to '{rhs_type}'"}
        return {"ok": True, "value": lhs_val + rhs_val}

    # 2. Optional safe unwrap
    def safe_unwrap(opt, fallback):
        return fallback if opt is None else opt

    # 3. Checked Int8 overflow trap
    def checked_int8_add(a, b):
        res = a + b
        if res < -128 or res > 127:
            return {"trapped": True, "value": None}
        return {"trapped": False, "value": res}

    mixed = checked_add("Int", 3, "Double", 1.5)
    explicit = checked_add("Double", float(3), "Double", 1.5)
    overflow = checked_int8_add(127, 1)
    expected = {
        "mixed_int_double_blocked": True,
        "explicit_double_sum": 4.5,
        "optional_nil_fallback": "guest",
        "int8_overflow_trapped": True,
    }
    actual = {
        "mixed_int_double_blocked": not mixed["ok"],
        "explicit_double_sum": explicit["value"],
        "optional_nil_fallback": safe_unwrap(None, "guest"),
        "int8_overflow_trapped": overflow["trapped"],
    }
    return {
        "name": "safety_pillars_type_optional_overflow",
        "summary": "模拟 Swift 强类型禁止隐式混算、Optional 空值保护与有符号整数溢出陷阱三项安全基石",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cow_value_semantics_and_domains():
    # Simulate Copy-On-Write buffer sharing between two value handles
    buf = {"id": 1, "refcount": 1, "data": [10, 20, 30]}
    a = {"buf": buf}
    b = {"buf": a["buf"]}
    b["buf"]["refcount"] += 1
    shared_before_write = a["buf"]["id"] == b["buf"]["id"]
    # Mutating b triggers copy when refcount > 1
    if b["buf"]["refcount"] > 1:
        b["buf"]["refcount"] -= 1
        b["buf"] = {"id": 2, "refcount": 1, "data": list(b["buf"]["data"])}
    b["buf"]["data"].append(40)
    domains = ["Apple 平台应用", "服务端开发", "系统与命令行工具", "机器学习", "嵌入式"]
    expected = {
        "shared_before_write": True,
        "isolated_after_write": True,
        "a_data": [10, 20, 30],
        "b_data": [10, 20, 30, 40],
        "domain_count": 5,
    }
    actual = {
        "shared_before_write": shared_before_write,
        "isolated_after_write": a["buf"]["id"] != b["buf"]["id"],
        "a_data": a["buf"]["data"],
        "b_data": b["buf"]["data"],
        "domain_count": len(domains),
    }
    return {
        "name": "cow_value_semantics_and_domains",
        "summary": "验证值语义写时复制(COW)的共享与按需拷贝机制及五大应用领域清单",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_top_level_print_and_interpolation():
    env = {"site": "BlueSky", "year": 2024}
    template = r"欢迎来到 \(site),当前教程年份 \(year)"
    rendered = re.sub(r"\\\((\w+)\)", lambda m: str(env[m.group(1)]), template)
    expected = {
        "hello_line": "Hello, World!\n",
        "interpolated": "欢迎来到 BlueSky,当前教程年份 2024",
        "inferred_types": {"site": "String", "year": "Int"},
    }
    actual = {
        "hello_line": "Hello, World!" + "\n",
        "interpolated": rendered,
        "inferred_types": {"site": "String" if isinstance(env["site"], str) else "Other",
                           "year": "Int" if isinstance(env["year"], int) else "Other"},
    }
    return {
        "name": "top_level_print_and_interpolation",
        "summary": "验证顶层脚本免 main 函数执行、print 自动换行与 \\(...) 字符串插值求值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_version_milestones_and_swift3_cleanup(),
        case_safety_pillars_type_optional_overflow(),
        case_cow_value_semantics_and_domains(),
        case_top_level_print_and_interpolation(),
    ]
    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-intro-lab/explore-intro.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-intro.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Swift

课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip

下载课程关联工程包:Swift

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2107.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习