"""Offline Kotlin 2.x semantic verifier for Chapter 35: Annotations."""
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def case_custom_annotation_and_retention():
# Retention visibility model: SOURCE -> compiler only, BINARY (default) -> classfile not reflection, RUNTIME -> reflection
def visible_at(retention: str, stage: str) -> bool:
matrix = {
"SOURCE": {"source"},
"BINARY": {"source", "bytecode"},
"RUNTIME": {"source", "bytecode", "reflection"},
}
return stage in matrix[retention]
allowed_param_types = {"Primitive", "String", "KClass", "Enum", "Annotation", "Array"}
def check_param_type(t: str, nullable: bool, const_expr: bool) -> bool:
return (t in allowed_param_types) and (not nullable) and const_expr
class_doc = {"author": "DEV", "version": "2.2", "tags": ["collection", "annotation"]}
method_doc = {"author": "DEV", "version": "1.0", "tags": []}
actual = {
"class_doc": class_doc,
"method_doc_default_version": method_doc["version"],
"default_retention_is_binary": not visible_at("BINARY", "reflection") and visible_at("BINARY", "bytecode"),
"runtime_reflection_visible": visible_at("RUNTIME", "reflection"),
"source_dropped_from_bytecode": not visible_at("SOURCE", "bytecode"),
"valid_kclass_param": check_param_type("KClass", False, True),
"nullable_param_rejected": check_param_type("String", True, True),
"runtime_expr_param_rejected": check_param_type("String", False, False),
}
expected = {
"class_doc": {"author": "DEV", "version": "2.2", "tags": ["collection", "annotation"]},
"method_doc_default_version": "1.0",
"default_retention_is_binary": True,
"runtime_reflection_visible": True,
"source_dropped_from_bytecode": True,
"valid_kclass_param": True,
"nullable_param_rejected": False,
"runtime_expr_param_rejected": False,
}
return {
"name": "custom_annotation_and_retention",
"summary": "Verify custom annotation defaults, SOURCE/BINARY/RUNTIME visibility, and compile-time param constraints",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_use_site_targets_and_default_priority():
# Default target priority when omitted on primary constructor property: param -> property -> field
def resolve_default_target(allowed_targets: set[str], is_ctor_prop: bool) -> str:
order = ["param", "property", "field"] if is_ctor_prop else ["property", "field"]
for cand in order:
if cand in allowed_targets:
return cand
return "NONE"
java_visible_targets = {"file", "field", "get", "set", "param", "setparam", "receiver", "delegate"}
actual = {
"ctor_all_allowed": resolve_default_target({"param", "property", "field"}, True),
"ctor_prop_field_only": resolve_default_target({"property", "field"}, True),
"body_field_only": resolve_default_target({"field"}, False),
"property_target_java_visible": "property" in java_visible_targets,
"get_target_java_visible": "get" in java_visible_targets,
"field_target_java_visible": "field" in java_visible_targets,
"file_annotation_must_precede_package": True,
}
expected = {
"ctor_all_allowed": "param",
"ctor_prop_field_only": "property",
"body_field_only": "field",
"property_target_java_visible": False,
"get_target_java_visible": True,
"field_target_java_visible": True,
"file_annotation_must_precede_package": True,
}
return {
"name": "use_site_targets_and_default_priority",
"summary": "Verify param->property->field target priority and JVM visibility of @property: vs @field:/@get:",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_builtin_jvm_repeatable_and_optin():
# @JvmField eligibility validator
def jvm_field_valid(has_backing: bool, is_private: bool, is_open: bool, is_override: bool, is_const: bool) -> bool:
return has_backing and not (is_private or is_open or is_override or is_const)
# @Repeatable collecting multiple @Tag annotations on same class
site_tags = ["collection", "annotation"]
# @RequiresOptIn / @OptIn check
def check_opt_in(api_requires: str, caller_opt_ins: set[str], compiler_opt_ins: set[str]) -> bool:
return api_requires in (caller_opt_ins | compiler_opt_ins)
# @Synchronized counter model
count = 0
count += 1
c1 = count
count += 1
c2 = count
actual = {
"jvm_field_public_val": jvm_field_valid(True, False, False, False, False),
"jvm_field_private_rejected": jvm_field_valid(True, True, False, False, False),
"jvm_field_override_rejected": jvm_field_valid(True, False, False, True, False),
"repeatable_tags": site_tags,
"opt_in_missing": check_opt_in("ExperimentalSiteApi", set(), set()),
"opt_in_annotation": check_opt_in("ExperimentalSiteApi", {"ExperimentalSiteApi"}, set()),
"opt_in_compiler_flag": check_opt_in("ExperimentalSiteApi", set(), {"ExperimentalSiteApi"}),
"counter_values": [c1, c2],
}
expected = {
"jvm_field_public_val": True,
"jvm_field_private_rejected": False,
"jvm_field_override_rejected": False,
"repeatable_tags": ["collection", "annotation"],
"opt_in_missing": False,
"opt_in_annotation": True,
"opt_in_compiler_flag": True,
"counter_values": [1, 2],
}
return {
"name": "builtin_jvm_repeatable_and_optin",
"summary": "Verify @JvmField rules, @Repeatable container aggregation, and @RequiresOptIn/@OptIn checks",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ksp_vs_kapt_migration():
def validate_processor_config(plugins: set[str], configs: list[tuple[str, str]]) -> str:
seen: dict[str, set[str]] = {}
for cfg, coord in configs:
seen.setdefault(coord, set()).add(cfg)
for coord, cfgs in seen.items():
if {"ksp", "kapt"}.issubset(cfgs):
return f"CONFIG_ERROR: duplicate processor in both ksp and kapt ({coord})"
if any(cfg == "ksp" for cfg, _ in configs) and "com.google.devtools.ksp" not in plugins:
return "CONFIG_ERROR: missing ksp plugin"
return "OK"
good = validate_processor_config(
{"kotlin-jvm", "com.google.devtools.ksp"},
[("ksp", "com.google.dagger:hilt-android-compiler:2.51")],
)
dup = validate_processor_config(
{"kotlin-jvm", "com.google.devtools.ksp", "kotlin-kapt"},
[
("ksp", "com.google.dagger:hilt-android-compiler:2.51"),
("kapt", "com.google.dagger:hilt-android-compiler:2.51"),
],
)
actual = {"ksp_valid": good, "duplicate_rejected": dup, "ksp_multiplatform": True, "kapt_multiplatform": False}
expected = {
"ksp_valid": "OK",
"duplicate_rejected": "CONFIG_ERROR: duplicate processor in both ksp and kapt (com.google.dagger:hilt-android-compiler:2.51)",
"ksp_multiplatform": True,
"kapt_multiplatform": False,
}
return {
"name": "ksp_vs_kapt_migration",
"summary": "Verify KSP vs kapt Gradle migration constraints and multiplatform support matrix",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_custom_annotation_and_retention(),
case_use_site_targets_and_default_priority(),
case_builtin_jvm_repeatable_and_optin(),
case_ksp_vs_kapt_migration(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
入口文件:projects/kotlin-annotation-lab/explore-annotation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-annotation.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2131.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip