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

离线校验 var 类型锁定、推断与标注规则、确定性初始化与插值

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

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


class SwiftVarEnv:
    def __init__(self):
        self.slots = {}

    def declare(self, name, typ=None, value=None, has_value=False):
        if typ is None and not has_value:
            raise TypeError(f"type annotation missing in pattern for '{name}'")
        if typ is None:
            typ = self.infer(value)
        self.slots[name] = {"type": typ, "init": has_value, "value": value if has_value else None}

    @staticmethod
    def infer(val):
        if isinstance(val, bool):
            return "Bool"
        if isinstance(val, int):
            return "Int"
        if isinstance(val, float):
            return "Double"
        if isinstance(val, str):
            return "String"
        if isinstance(val, list) and len(val) == 0:
            raise TypeError("empty collection literal requires an explicit type")
        return "Any"

    def assign(self, name, value, val_type=None):
        slot = self.slots[name]
        vtype = val_type or self.infer(value)
        if vtype != slot["type"]:
            raise TypeError(f"cannot assign value of type '{vtype}' to type '{slot['type']}'")
        slot["value"] = value
        slot["init"] = True

    def read(self, name):
        slot = self.slots[name]
        if not slot["init"]:
            raise RuntimeError(f"variable '{name}' used before being initialized")
        return slot["value"]


def case_var_reassignment_and_type_lock():
    env = SwiftVarEnv()
    env.declare("site", value="www.bluesky.org", has_value=True)
    first = env.read("site")
    env.assign("site", "BlueSky")
    second = env.read("site")
    env.declare("visits", value=100, has_value=True)
    env.assign("visits", env.read("visits") + 50)
    mismatch_blocked = False
    try:
        env.assign("visits", "not-an-int")
    except TypeError:
        mismatch_blocked = True
    expected = {"first": "www.bluesky.org", "second": "BlueSky", "visits": 150, "type_mismatch_blocked": True}
    actual = {"first": first, "second": second, "visits": env.read("visits"), "type_mismatch_blocked": mismatch_blocked}
    return {
        "name": "var_reassignment_and_type_lock",
        "summary": "验证 var 变量可反复覆盖赋值、基于旧值更新且编译期锁定静态类型",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_type_annotation_inference_and_multi_decl():
    env = SwiftVarEnv()
    env.declare("count", value=43, has_value=True)
    env.declare("ratio", typ="Float", value=0.5, has_value=True)
    env.declare("small", typ="Int8", value=10, has_value=True)
    env.declare("names", typ="[String]", value=[], has_value=True)
    env.slots["names"]["value"].append("BlueSky")

    empty_no_type_err = False
    try:
        env.declare("badEmpty", value=[], has_value=True)
    except TypeError:
        empty_no_type_err = True

    missing_pattern_err = False
    try:
        env.declare("y", typ=None, has_value=False)
    except TypeError:
        missing_pattern_err = True

    expected = {
        "inferred_count": "Int",
        "explicit_ratio": "Float",
        "explicit_small": "Int8",
        "names": ["BlueSky"],
        "empty_array_needs_type": True,
        "multi_decl_missing_type_blocked": True,
    }
    actual = {
        "inferred_count": env.slots["count"]["type"],
        "explicit_ratio": env.slots["ratio"]["type"],
        "explicit_small": env.slots["small"]["type"],
        "names": env.read("names"),
        "empty_array_needs_type": empty_no_type_err,
        "multi_decl_missing_type_blocked": missing_pattern_err,
    }
    return {
        "name": "type_annotation_inference_and_multi_decl",
        "summary": "验证类型推断默认规则、必须显式标注的四种场景以及单行多变量声明约束",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_definite_initialization_check():
    env = SwiftVarEnv()
    env.declare("site", typ="String", has_value=False)
    read_before_init_blocked = False
    try:
        env.read("site")
    except RuntimeError:
        read_before_init_blocked = True
    env.assign("site", "www.bluesky.org")
    status = 0
    status = 1
    status = 2
    expected = {"read_before_init_blocked": True, "after_init": "www.bluesky.org", "final_status": 2}
    actual = {"read_before_init_blocked": read_before_init_blocked, "after_init": env.read("site"), "final_status": status}
    return {
        "name": "definite_initialization_check",
        "summary": "模拟确定性初始化(Definite Initialization):禁止读取未初始化变量,赋值后正常读取",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_naming_rules_and_string_interpolation():
    def is_valid_swift_ident(ident: str) -> bool:
        if ident.startswith("`") and ident.endswith("`") and len(ident) > 2:
            return True
        if not ident or ident[0].isdigit():
            return False
        if any(ch in ident for ch in (" ", "-", "+", "*")):
            return False
        if ident in {"class", "struct", "var", "let", "func"}:
            return False
        return True

    interp_a = f"欢迎访问 {'www.bluesky.org'},{'BlueSky'} 教程更新于 {2024} 年"
    interp_b = f"{3} + {4} = {3 + 4}"
    expected = {
        "valid_idents": [True, True, True, True],
        "invalid_idents": [False, False, False],
        "interp_a": "欢迎访问 www.bluesky.org,BlueSky 教程更新于 2024 年",
        "interp_b": "3 + 4 = 7",
    }
    actual = {
        "valid_idents": [is_valid_swift_ident(x) for x in ("课程名称", "π", "siteName", "`class`")],
        "invalid_idents": [is_valid_swift_ident(x) for x in ("2site", "site-name", "class")],
        "interp_a": interp_a,
        "interp_b": interp_b,
    }
    return {
        "name": "naming_rules_and_string_interpolation",
        "summary": "校验 Unicode/小驼峰/反引号标识符规则与 \\(表达式) 字符串插值求值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_var_reassignment_and_type_lock(),
        case_type_annotation_inference_and_multi_decl(),
        case_definite_initialization_check(),
        case_naming_rules_and_string_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-variables-lab/explore-variables.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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