"""Offline Kotlin 2.x semantic verifier for Chapter 20 (visibility)."""
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
VIS_RANK = {"private": 0, "protected": 1, "internal": 1, "public": 2}
def check_top_level_access(modifier: str, *, same_file: bool, same_module: bool, friend_test: bool = False) -> bool:
if modifier == "protected":
raise SyntaxError("Modifier 'protected' is not applicable to top-level declarations")
if modifier == "public":
return True
if modifier == "internal":
return same_module or friend_test
if modifier == "private":
return same_file
raise ValueError(modifier)
def check_member_access(modifier: str, *, same_class: bool, is_subclass: bool, same_module: bool, same_file: bool) -> bool:
if modifier == "public":
return True
if modifier == "internal":
return same_module
if modifier == "protected":
return same_class or is_subclass # NOT same_file or same_package!
if modifier == "private":
return same_class
raise ValueError(modifier)
def check_override_visibility(parent_mod: str, child_mod: str | None) -> tuple[bool, str]:
effective = parent_mod if child_mod is None else child_mod
if parent_mod == "public" and effective != "public":
return False, "weaker access privilege"
if parent_mod == "protected" and effective not in ("protected", "public"):
return False, "weaker access privilege"
if parent_mod == "internal" and effective not in ("internal", "public"):
return False, "weaker access privilege"
return True, effective
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Top-level visibility (public, internal, private; protected forbidden)
prot_top_error = False
try:
check_top_level_access("protected", same_file=True, same_module=True)
except SyntaxError:
prot_top_error = True
actual_1 = {
"top_private_same_file": check_top_level_access("private", same_file=True, same_module=True),
"top_private_other_file_same_pkg": check_top_level_access("private", same_file=False, same_module=True),
"top_internal_same_module": check_top_level_access("internal", same_file=False, same_module=True),
"top_internal_gradle_test_friend": check_top_level_access("internal", same_file=False, same_module=False, friend_test=True),
"top_internal_other_module": check_top_level_access("internal", same_file=False, same_module=False),
"top_protected_rejected": prot_top_error,
"has_package_private_like_java": False,
}
expected_1 = {
"top_private_same_file": True,
"top_private_other_file_same_pkg": False,
"top_internal_same_module": True,
"top_internal_gradle_test_friend": True,
"top_internal_other_module": False,
"top_protected_rejected": True,
"has_package_private_like_java": False,
}
cases.append({
"name": "top_level_visibility_and_modules",
"summary": "Verify top-level public/internal/private access, Gradle main->test friend module, and top-level protected prohibition.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Class member visibility (private class-only, protected class+subclass only, NOT same-file/package)
actual_2 = {
"member_private_same_class": check_member_access("private", same_class=True, is_subclass=False, same_module=True, same_file=True),
"member_private_subclass": check_member_access("private", same_class=False, is_subclass=True, same_module=True, same_file=True),
"member_protected_subclass": check_member_access("protected", same_class=False, is_subclass=True, same_module=True, same_file=False),
"member_protected_same_file_outside": check_member_access("protected", same_class=False, is_subclass=False, same_module=True, same_file=True),
"member_internal_same_module": check_member_access("internal", same_class=False, is_subclass=False, same_module=True, same_file=False),
"member_public_anywhere": check_member_access("public", same_class=False, is_subclass=False, same_module=False, same_file=False),
}
expected_2 = {
"member_private_same_class": True,
"member_private_subclass": False,
"member_protected_subclass": True,
"member_protected_same_file_outside": False,
"member_internal_same_module": True,
"member_public_anywhere": True,
}
cases.append({
"name": "class_member_visibility_matrix",
"summary": "Verify member visibility rules distinguishing Kotlin protected from Java package+subclass protected.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Constructor visibility (private singleton, internal config) & `private set` property
class UserWithPrivateSet:
def __init__(self) -> None:
self._name = "mbsky"
@property
def name(self) -> str:
return self._name
def rename(self, new_name: str) -> None:
self._name = new_name
u = UserWithPrivateSet()
ext_write_blocked = False
try:
u.name = "hack" # type: ignore[misc]
except AttributeError:
ext_write_blocked = True
before = u.name
u.rename("MBSKY")
after = u.name
actual_3 = {
"private_set_initial": before,
"private_set_after_internal_rename": after,
"private_set_external_write_blocked": ext_write_blocked,
"primary_ctor_with_visibility_requires_constructor_kw": True,
}
expected_3 = {
"private_set_initial": "mbsky",
"private_set_after_internal_rename": "MBSKY",
"private_set_external_write_blocked": True,
"primary_ctor_with_visibility_requires_constructor_kw": True,
}
cases.append({
"name": "constructor_and_private_set_visibility",
"summary": "Verify private/internal constructor rules and private set external read-only semantics.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Override visibility rules, JVM internal name mangling, public API exposure & local var rules
widen_ok, widen_eff = check_override_visibility("protected", "public")
inherit_ok, inherit_eff = check_override_visibility("protected", None)
narrow_ok, narrow_reason = check_override_visibility("public", "private")
mangled_jvm_name = "log$app_main"
actual_4 = {
"widen_protected_to_public": [widen_ok, widen_eff],
"inherit_protected_default": [inherit_ok, inherit_eff],
"narrow_public_to_private": [narrow_ok, narrow_reason],
"internal_jvm_mangled_example": mangled_jvm_name,
"public_fun_expose_internal_return_allowed": False,
"local_var_allows_visibility_modifier": False,
}
expected_4 = {
"widen_protected_to_public": [True, "public"],
"inherit_protected_default": [True, "protected"],
"narrow_public_to_private": [False, "weaker access privilege"],
"internal_jvm_mangled_example": "log$app_main",
"public_fun_expose_internal_return_allowed": False,
"local_var_allows_visibility_modifier": False,
}
cases.append({
"name": "override_visibility_mangling_and_constraints",
"summary": "Verify override widening/non-narrowing, JVM internal name mangling, and public-exposes-internal / local-var rules.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
入口文件:projects/kotlin-visibility-lab/explore-visibility.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-visibility.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2174.zip