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

运行离线 Python 校验:Swift 六级访问矩阵、private(set)、package/open 边界与构造器可见性

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。explore-access-control.py
explore-access-control.py210 行
"""Offline CPython 3.12.14 semantic verifier for Swift Access Control (CH34)."""
import json
from dataclasses import dataclass


@dataclass(frozen=True)
class SiteContext:
    package: str
    module: str
    file: str
    scope: str
    is_extension_of_same_type: bool = False


@dataclass(frozen=True)
class DeclContext:
    level: str  # private, fileprivate, internal, package, public, open
    package: str
    module: str
    file: str
    scope: str
    is_class_or_member: bool = True


def can_access(decl: DeclContext, caller: SiteContext) -> bool:
    lvl = decl.level
    if lvl == "private":
        return caller.file == decl.file and (
            caller.scope == decl.scope or caller.is_extension_of_same_type
        )
    if lvl == "fileprivate":
        return caller.file == decl.file
    if lvl == "internal":
        return caller.module == decl.module
    if lvl == "package":
        return caller.package == decl.package
    if lvl in ("public", "open"):
        return True
    raise ValueError(f"Unknown level {lvl}")


def can_subclass_or_override(decl: DeclContext, caller: SiteContext) -> bool:
    if not decl.is_class_or_member:
        return False
    if caller.module == decl.module:
        return can_access(decl, caller)
    return decl.level == "open"


def case_six_level_visibility_matrix():
    decl_base = dict(package="PkgA", module="CoreKit", file="Core.swift", scope="User")
    callers = {
        "same_scope": SiteContext("PkgA", "CoreKit", "Core.swift", "User"),
        "same_file_ext": SiteContext("PkgA", "CoreKit", "Core.swift", "UserExt", is_extension_of_same_type=True),
        "same_file_other": SiteContext("PkgA", "CoreKit", "Core.swift", "Logger"),
        "same_module": SiteContext("PkgA", "CoreKit", "Other.swift", "Service"),
        "same_pkg_other_mod": SiteContext("PkgA", "AppCLI", "main.swift", "Main"),
        "external_pkg": SiteContext("PkgB", "ThirdParty", "ext.swift", "Client"),
    }
    levels = ["private", "fileprivate", "internal", "package", "public", "open"]
    access_matrix = {}
    override_ext = {}
    for lv in levels:
        d = DeclContext(level=lv, **decl_base)
        access_matrix[lv] = [can_access(d, callers[k]) for k in callers]
        override_ext[lv] = can_subclass_or_override(d, callers["same_pkg_other_mod"])

    actual = {"access_matrix": access_matrix, "cross_module_override": override_ext}
    expected = {
        "access_matrix": {
            "private":     [True,  True,  False, False, False, False],
            "fileprivate": [True,  True,  True,  False, False, False],
            "internal":    [True,  True,  True,  True,  False, False],
            "package":     [True,  True,  True,  True,  True,  False],
            "public":      [True,  True,  True,  True,  True,  True],
            "open":        [True,  True,  True,  True,  True,  True],
        },
        "cross_module_override": {
            "private": False,
            "fileprivate": False,
            "internal": False,
            "package": False,
            "public": False,
            "open": True,
        },
    }
    return {
        "name": "six_level_visibility_matrix",
        "summary": "Verify Swift 6-level access control matrix across scope, same-file extension, file, module, package, and external package.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_private_set_and_extension_visibility():
    getter_decl = DeclContext("internal", "PkgA", "CoreKit", "User.swift", "User")
    setter_decl = DeclContext("private", "PkgA", "CoreKit", "User.swift", "User")
    inside = SiteContext("PkgA", "CoreKit", "User.swift", "User")
    outside_same_mod = SiteContext("PkgA", "CoreKit", "Other.swift", "Caller")

    same_file_ext = SiteContext("PkgA", "CoreKit", "User.swift", "UserExt2", is_extension_of_same_type=True)
    other_file_ext = SiteContext("PkgA", "CoreKit", "UserExtra.swift", "UserExt3", is_extension_of_same_type=True)

    token = "SWIFT-SECRET"
    masked = token[:3] + "****"
    visit_count = 0
    if can_access(setter_decl, inside):
        visit_count += 1
        visit_count += 1

    actual = {
        "external_can_read_visit_count": can_access(getter_decl, outside_same_mod),
        "external_can_write_visit_count": can_access(setter_decl, outside_same_mod),
        "internal_visit_count": visit_count,
        "masked_token_in_same_file_ext": masked if can_access(setter_decl, same_file_ext) else None,
        "other_file_ext_can_access_private": can_access(setter_decl, other_file_ext),
    }
    expected = {
        "external_can_read_visit_count": True,
        "external_can_write_visit_count": False,
        "internal_visit_count": 2,
        "masked_token_in_same_file_ext": "SWI****",
        "other_file_ext_can_access_private": False,
    }
    return {
        "name": "private_set_and_extension_visibility",
        "summary": "Verify private(set) allows external reads while restricting writes, and Swift 4+ private shares across same-file extensions only.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_package_public_open_cross_module():
    app = SiteContext("PkgA", "AppCLI", "main.swift", "Main")
    ext = SiteContext("PkgB", "External", "main.swift", "Main")

    open_cls = DeclContext("open", "PkgA", "CoreKit", "Kit.swift", "Base")
    pub_cls = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "Helper")
    pub_member_on_open = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "Base.helperMethod")
    pkg_fn = DeclContext("package", "PkgA", "CoreKit", "Kit.swift", "internalName", is_class_or_member=False)

    actual = {
        "app_can_subclass_open": can_subclass_or_override(open_cls, app),
        "app_can_subclass_public": can_subclass_or_override(pub_cls, app),
        "app_can_override_public_in_open_class": can_subclass_or_override(pub_member_on_open, app),
        "app_can_call_package_fn": can_access(pkg_fn, app),
        "ext_pkg_can_call_package_fn": can_access(pkg_fn, ext),
    }
    expected = {
        "app_can_subclass_open": True,
        "app_can_subclass_public": False,
        "app_can_override_public_in_open_class": False,
        "app_can_call_package_fn": True,
        "ext_pkg_can_call_package_fn": False,
    }
    return {
        "name": "package_public_open_cross_module",
        "summary": "Verify cross-module open subclassing, public non-subclassable boundary, and package-level intra-package sharing.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_initializer_visibility_and_singleton():
    app = SiteContext("PkgA", "AppCLI", "main.swift", "Main")
    implicit_memberwise_init = DeclContext("internal", "PkgA", "CoreKit", "Kit.swift", "PublicStruct.init", is_class_or_member=False)
    explicit_public_init = DeclContext("public", "PkgA", "CoreKit", "Kit.swift", "PublicStruct.init", is_class_or_member=False)
    singleton_init = DeclContext("private", "PkgA", "CoreKit", "Config.swift", "AppConfig.init", is_class_or_member=False)
    singleton_shared = DeclContext("public", "PkgA", "CoreKit", "Config.swift", "AppConfig.shared", is_class_or_member=False)

    actual = {
        "implicit_struct_init_cross_module": can_access(implicit_memberwise_init, app),
        "explicit_public_init_cross_module": can_access(explicit_public_init, app),
        "singleton_direct_init_external": can_access(singleton_init, app),
        "singleton_shared_accessible": can_access(singleton_shared, app),
    }
    expected = {
        "implicit_struct_init_cross_module": False,
        "explicit_public_init_cross_module": True,
        "singleton_direct_init_external": False,
        "singleton_shared_accessible": True,
    }
    return {
        "name": "initializer_visibility_and_singleton",
        "summary": "Verify synthesized public struct memberwise init stays internal cross-module and private init enforces singleton access.",
        "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_six_level_visibility_matrix(),
            case_private_set_and_extension_visibility(),
            case_package_public_open_cross_module(),
            case_initializer_visibility_and_singleton(),
        ],
    }
    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-access-control-lab/explore-access-control.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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