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

离线校验嵌套注释剥离、标识符规范、print/readLine 与 #if/#available 分支

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

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


def strip_nested_swift_comments(src: str) -> str:
    out = []
    i = 0
    depth = 0
    n = len(src)
    while i < n:
        if depth == 0 and src[i:i + 2] == "//":
            nl = src.find("\n", i)
            i = n if nl == -1 else nl
            continue
        if src[i:i + 2] == "/*":
            depth += 1
            i += 2
            continue
        if depth > 0 and src[i:i + 2] == "*/":
            depth -= 1
            i += 2
            continue
        if depth == 0:
            out.append(src[i])
        i += 1
    if depth != 0:
        raise ValueError("unterminated nested block comment")
    return "".join(out)


def case_foundation_date_and_semicolons():
    epoch = datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc).strftime("%Y-%m-%d")
    # Single-line statements without semicolons vs same-line statements separated by ';'
    a, b = 1, 2
    c, d = 3, 4
    expected = {
        "utc_epoch": "1970-01-01",
        "sum_ab": 3,
        "sum_cd": 7,
        "import_forms": 4,
    }
    actual = {
        "utc_epoch": epoch,
        "sum_ab": a + b,
        "sum_cd": c + d,
        "import_forms": len(["import Foundation", "import func Foundation.sqrt", "import struct Foundation.Date", "@testable import SkyKit"]),
    }
    return {
        "name": "foundation_date_and_semicolons",
        "summary": "验证 Foundation UTC 纪元日期格式化、四类 import 语法以及单行分号分隔规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nested_comments_and_identifiers():
    snippet = '/* 外层开始 /* 内层嵌套 */ 外层结束 */\nlet 课程名称 = "Swift 教程" // 行尾注释\nlet π = 3.14159\nlet `class` = "Swift 6"\n'
    cleaned = strip_nested_swift_comments(snippet).strip()
    decls = re.findall(r"let\s+(`?\w+`?)\s*=\s*(.+)", cleaned)
    expected = {
        "nested_comment_stripped": True,
        "identifiers": ["课程名称", "π", "`class`"],
        "case_sensitive": True,
    }
    actual = {
        "nested_comment_stripped": "/*" not in cleaned and "*/" not in cleaned and "//" not in cleaned,
        "identifiers": [name for name, _ in decls],
        "case_sensitive": ("siteName" != "SiteName"),
    }
    return {
        "name": "nested_comments_and_identifiers",
        "summary": "通过嵌套多行注释词法剥离器验证 /* /* */ */ 合法性以及 Unicode 与反引号转义标识符",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_keywords_special_literals_and_io():
    # print(_ items: Any..., separator: String = " ", terminator: String = "\n")
    def swift_print(*items, separator=" ", terminator="\n"):
        return separator.join(str(x) for x in items) + terminator

    def simulate_readline(line):
        if line is None:
            return "EOF"
        return f"你输入的是:{line}"

    special_literals = ["#file", "#fileID", "#line", "#column", "#function", "#dsohandle"]
    expected = {
        "default_print": "BlueSky Swift 6\n",
        "custom_print": "BlueSky - 教程!\n",
        "readline_some": "你输入的是:BlueSky",
        "readline_eof": "EOF",
        "expr_statement_total": 30,
        "special_literal_count": 6,
    }
    total = (1 + 2) * 10
    actual = {
        "default_print": swift_print("BlueSky", "Swift", "6"),
        "custom_print": swift_print("BlueSky", "教程", separator=" - ", terminator="!\n"),
        "readline_some": simulate_readline("BlueSky"),
        "readline_eof": simulate_readline(None),
        "expr_statement_total": total,
        "special_literal_count": len(special_literals),
    }
    return {
        "name": "keywords_special_literals_and_io",
        "summary": "校验 print 默认/自定义分隔与终止符、readLine() 可选返回、语句与表达式区别及 # 特殊字面量",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_conditional_compilation_and_availability():
    def eval_compile_flags(os_name, arch_name, compiler_ver, lang_mode):
        out = []
        out.append("macOS" if os_name == "macOS" else ("Linux" if os_name == "Linux" else "Other"))
        if arch_name in ("arm64", "x86_64"):
            out.append(arch_name)
        if compiler_ver >= (6, 0):
            out.append("compiler>=6.0")
        out.append("swift>=6.0" if lang_mode >= (6, 0) else "swift<6.0")
        return out

    def runtime_available(os_name, version, min_macos=(11, 0)):
        if os_name == "macOS":
            return version >= min_macos
        return True  # '*' wildcard covers other platforms

    expected = {
        "xcode16_default_mode": ["macOS", "arm64", "compiler>=6.0", "swift<6.0"],
        "swift6_mode": ["macOS", "arm64", "compiler>=6.0", "swift>=6.0"],
        "macos_14_available": True,
        "macos_10_15_available": False,
        "linux_wildcard_available": True,
    }
    actual = {
        "xcode16_default_mode": eval_compile_flags("macOS", "arm64", (6, 3), (5, 0)),
        "swift6_mode": eval_compile_flags("macOS", "arm64", (6, 3), (6, 0)),
        "macos_14_available": runtime_available("macOS", (14, 0)),
        "macos_10_15_available": runtime_available("macOS", (10, 15)),
        "linux_wildcard_available": runtime_available("Linux", (6, 0)),
    }
    return {
        "name": "conditional_compilation_and_availability",
        "summary": "对比编译期 #if (os/arch/compiler/swift) 与运行期 #available(macOS 11.0, *) 语义差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_foundation_date_and_semicolons(),
        case_nested_comments_and_identifiers(),
        case_keywords_special_literals_and_io(),
        case_conditional_compilation_and_availability(),
    ]
    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-basic-syntax-lab/explore-basic-syntax.py

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

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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