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

离线校验 let 不可变绑定、值/引用类型差异、延迟单次赋值与命名规范

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

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


class LetBinding:
    """Models Swift let immutability for value types vs reference types."""

    def __init__(self, name: str, is_reference: bool, value=None, initialized: bool = True):
        self.name = name
        self.is_reference = is_reference
        self._value = value
        self._initialized = initialized

    def init_once(self, value):
        if self._initialized:
            raise TypeError(f"immutable value '{self.name}' may only be initialized once")
        self._value = value
        self._initialized = True

    def reassign(self, new_value):
        raise TypeError(f"cannot assign to value: '{self.name}' is a 'let' constant")

    def mutate_property(self, prop: str, new_val):
        if not self._initialized:
            raise RuntimeError(f"constant '{self.name}' used before being initialized")
        if not self.is_reference:
            raise TypeError(f"cannot assign to property: '{self.name}' is a 'let' constant")
        self._value[prop] = new_val

    def read(self):
        if not self._initialized:
            raise RuntimeError(f"constant '{self.name}' used before being initialized")
        return self._value


def case_let_immutability_and_reassign_rejection():
    site = LetBinding("site", is_reference=False, value="www.bluesky.org")
    reassign_err = ""
    try:
        site.reassign("BlueSky")
    except TypeError as exc:
        reassign_err = str(exc)
    expected = {
        "site": "www.bluesky.org",
        "reassign_rejected": True,
        "error_mentions_let_constant": True,
    }
    actual = {
        "site": site.read(),
        "reassign_rejected": bool(reassign_err),
        "error_mentions_let_constant": "'let' constant" in reassign_err,
    }
    return {
        "name": "let_immutability_and_reassign_rejection",
        "summary": "验证 let 常量初始化后禁止二次赋值并在编译期模型中报告 let 常量错误",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_let_binding_vs_reference_and_value_types():
    counter_ref = LetBinding("counter", is_reference=True, value={"value": 0})
    counter_ref.mutate_property("value", 10)
    ref_rebind_blocked = False
    try:
        counter_ref.reassign({"value": 20})
    except TypeError:
        ref_rebind_blocked = True

    site_struct = LetBinding("site", is_reference=False, value={"name": "BlueSky"})
    struct_prop_blocked = False
    try:
        site_struct.mutate_property("name", "SkyLab")
    except TypeError:
        struct_prop_blocked = True

    fixed_array = LetBinding("fixed", is_reference=False, value=["BlueSky"])
    array_mutate_blocked = False
    try:
        fixed_array.mutate_property("append", "Swift")
    except TypeError:
        array_mutate_blocked = True

    expected = {
        "class_prop_mutated": 10,
        "class_rebind_blocked": True,
        "struct_prop_blocked": True,
        "let_array_append_blocked": True,
    }
    actual = {
        "class_prop_mutated": counter_ref.read()["value"],
        "class_rebind_blocked": ref_rebind_blocked,
        "struct_prop_blocked": struct_prop_blocked,
        "let_array_append_blocked": array_mutate_blocked,
    }
    return {
        "name": "let_binding_vs_reference_and_value_types",
        "summary": "对比 let 修饰类实例(可改内部 var 属性但不可改绑)与修饰结构体/数组(整体不可变)的差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_deferred_let_initialization_branches():
    def compute_score(input_val: int) -> int:
        score = LetBinding("score", is_reference=False, initialized=False)
        if input_val >= 60:
            score.init_once(input_val)
        else:
            score.init_once(0)
        return score.read()

    # Second init attempt rejected
    s = LetBinding("score", is_reference=False, initialized=False)
    s.init_once(85)
    double_init_blocked = False
    try:
        s.init_once(90)
    except TypeError:
        double_init_blocked = True

    # Missing branch leaves uninitialized -> read blocked
    missing_branch = LetBinding("incomplete", is_reference=False, initialized=False)
    uninit_read_blocked = False
    try:
        missing_branch.read()
    except RuntimeError:
        uninit_read_blocked = True

    expected = {
        "pass_score": 85,
        "fail_score": 0,
        "double_init_blocked": True,
        "missing_branch_blocked": True,
    }
    actual = {
        "pass_score": compute_score(85),
        "fail_score": compute_score(42),
        "double_init_blocked": double_init_blocked,
        "missing_branch_blocked": uninit_read_blocked,
    }
    return {
        "name": "deferred_let_initialization_branches",
        "summary": "验证 let 延迟初始化在所有分支单次赋值规则,拦截重复赋值与漏分支读取",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_camel_case_naming_and_let_first_policy():
    def is_lower_camel_constant(name: str) -> bool:
        return bool(name) and name[0].islower() and "_" not in name and not name.isupper()

    recommended = ["maxRetryCount", "defaultTimeout", "isDebugEnabled", "className"]
    discouraged = ["MaxRetryCount", "MAX_RETRY_COUNT", "_timeout"]
    retry_count = 0
    retry_count += 1
    expected = {
        "recommended_all_lower_camel": True,
        "discouraged_all_rejected": True,
        "retry_summary": "BlueSky:已重试 1 次,上限 3 次",
    }
    actual = {
        "recommended_all_lower_camel": all(is_lower_camel_constant(n) for n in recommended),
        "discouraged_all_rejected": all(not is_lower_camel_constant(n) for n in discouraged),
        "retry_summary": f"BlueSky:已重试 {retry_count} 次,上限 {3} 次",
    }
    return {
        "name": "camel_case_naming_and_let_first_policy",
        "summary": "核对 Swift 常量小驼峰命名规范与“默认 let、按需改为 var”的选择准则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_let_immutability_and_reassign_rejection(),
        case_let_binding_vs_reference_and_value_types(),
        case_deferred_let_initialization_branches(),
        case_camel_case_naming_and_let_first_policy(),
    ]
    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-constants-lab/explore-constants.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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