"""Offline CPython 3.12.14 semantic verifier for Swift API Design Guidelines & Style (CH46)."""
import json
import re
from dataclasses import dataclass
@dataclass
class GridPoint:
x: int
y: int
def scaled(self, by: int) -> "GridPoint":
return GridPoint(self.x * by, self.y * by)
def move(from_pt: GridPoint, to_pt: GridPoint) -> GridPoint:
return GridPoint(to_pt.x - from_pt.x, to_pt.y - from_pt.y)
@dataclass
class Article:
title: str
view_count: int
is_published: bool
has_cover: bool
@dataclass
class User:
name: str
email: str | None
age: int
def lint_swift_snippet(lines: list[str], expected_spaces: int = 2) -> list[str]:
warnings = []
for idx, line in enumerate(lines, 1):
m_type = re.match(r"^\s*(?:struct|class|enum|protocol)\s+([a-z]\w*)", line)
if m_type:
warnings.append(f"L{idx}:TypeNamesShouldBeCapitalized:{m_type.group(1)}")
leading = len(line) - len(line.lstrip(" "))
if leading > 0 and leading != expected_spaces:
warnings.append(f"L{idx}:Indentation:{leading}->{expected_spaces}")
if re.search(r":[^\s]", line) and not re.search(r"https?:", line):
warnings.append(f"L{idx}:SpacingAfterColon")
return warnings
def case_api_design_and_naming():
delta = move(GridPoint(1, 1), GridPoint(4, 5))
scaled = GridPoint(2, 3).scaled(by=4)
articles = [
Article("Swift 入门", 320, True, True),
Article("Swift 进阶", 180, False, False),
Article("Swift 并发", 520, True, True),
]
drafts = [a.title for a in articles if not a.is_published]
by_views = [a.title for a in sorted(articles, key=lambda a: a.view_count, reverse=True)]
bool_names = ["isPublished", "hasCover", "canUndo", "shouldShowAlert"]
bool_prefixes_ok = all(
n.startswith(("is", "has", "can", "should")) and n[len(next(p for p in ("is", "has", "can", "should") if n.startswith(p)))].isupper()
for n in bool_names
)
actual = {
"move_delta": [delta.x, delta.y],
"scaled_point": [scaled.x, scaled.y],
"draft_titles": drafts,
"sorted_by_views": by_views,
"boolean_prefixes_valid": bool_prefixes_ok,
"se0046_first_param_has_default_label": True,
}
expected = {
"move_delta": [3, 4],
"scaled_point": [8, 12],
"draft_titles": ["Swift 进阶"],
"sorted_by_views": ["Swift 并发", "Swift 入门", "Swift 进阶"],
"boolean_prefixes_valid": True,
"se0046_first_param_has_default_label": True,
}
return {
"name": "api_design_guidelines_and_naming",
"summary": "Verify API Design Guidelines naming (fluent labels, -ed non-mutating sorted, boolean prefixes) and SE-0046 default label rule.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_swift_format_lint():
bad_code = [
"struct gridPoint {",
" var x:Int",
" var y:Int",
"}",
]
diags = lint_swift_snippet(bad_code, expected_spaces=2)
cfg = json.loads('{"indentation": {"spaces": 4}, "lineLength": 100}')
actual = {
"lint_warnings": diags,
"config_indent_spaces": cfg["indentation"]["spaces"],
"config_line_length": cfg["lineLength"],
}
expected = {
"lint_warnings": [
"L1:TypeNamesShouldBeCapitalized:gridPoint",
"L2:Indentation:4->2",
"L2:SpacingAfterColon",
"L3:Indentation:4->2",
"L3:SpacingAfterColon",
],
"config_indent_spaces": 4,
"config_line_length": 100,
}
return {
"name": "swift_format_lint_and_config",
"summary": "Verify swift-format lint rule detection (UpperCamelCase, indentation, colon spacing) and .swift-format JSON parsing.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_swift_idioms():
def welcome_nested(u: User) -> str:
if u.age >= 18:
if u.email is not None:
if u.email != "":
return f"欢迎,{u.name}({u.email})"
return "邮箱为空"
return "缺少邮箱"
return "未成年"
def welcome_guard(u: User) -> str:
if u.age < 18:
return "未成年"
if not u.email:
return "邮箱无效"
return f"欢迎,{u.name}({u.email})"
u = User("Alice", "dev@example.com", 20)
raw = ["Swift", "", "example.com", " ", "CONCURRENCY"]
valid_items = [s for s in raw if s.strip()]
def show_url(url: str | None) -> str:
if url is None:
return "无链接"
return f"链接:{url}"
# Value type copy isolation
a = GridPoint(1, 2)
b = GridPoint(a.x, a.y)
b.x = 100
# Protocol extension shared greeting
greetings = [f"你好,{n}" for n in ("Swift", "example.com")]
actual = {
"guard_matches_nested": welcome_nested(u) == welcome_guard(u),
"welcome_message": welcome_guard(u),
"guard_continue_filtered": valid_items,
"shorthand_optional": [show_url("https://example.com"), show_url(None)],
"value_type_isolation": [a.x, b.x],
"protocol_ext_greetings": greetings,
}
expected = {
"guard_matches_nested": True,
"welcome_message": "欢迎,Alice(dev@example.com)",
"guard_continue_filtered": ["Swift", "example.com", "CONCURRENCY"],
"shorthand_optional": ["链接:https://example.com", "无链接"],
"value_type_isolation": [1, 100],
"protocol_ext_greetings": ["你好,Swift", "你好,example.com"],
}
return {
"name": "swift_idioms_guard_shorthand_value_pop",
"summary": "Verify guard early-exit equivalence, loop guard-continue, SE-0345 if-let/guard-let shorthand, value semantics, and protocol extension reuse.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_anti_patterns_audit():
pairs = {
"mutability": ("var", "let"),
"precondition": ("nested if", "guard"),
"optional_binding": ("if let x = x", "if let x"),
"modeling": ("class", "struct/enum"),
"reuse": ("copy-paste", "protocol extension"),
"unwrap": ("!", "if let / guard let / ??"),
"naming": ("d", "dayCount"),
"boolean": ("published", "isPublished"),
"interpolation": ("\"你好,\" + name", "\"你好,\\(name)\""),
"nil_fallback": ("x != nil ? x! : y", "x ?? y"),
}
actual = {"checked_anti_pattern_count": len(pairs), "all_distinct_upgrades": all(a != b for a, b in pairs.values())}
expected = {"checked_anti_pattern_count": 10, "all_distinct_upgrades": True}
return {
"name": "anti_patterns_audit",
"summary": "Verify all 10 idiomatic Swift anti-pattern to recommended-pattern transformations.",
"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_api_design_and_naming(),
case_swift_format_lint(),
case_swift_idioms(),
case_anti_patterns_audit(),
],
}
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-style-lab/explore-style.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-style.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2125.zip