"""Offline Kotlin 2.x semantic verifier for Chapter 39: Multiplatform, JS & Native."""
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def case_four_backends_and_native_closed_world():
backends = {
"Kotlin/JVM": {"artifact": ".class/.jar", "full_reflection": True, "dynamic_classload": True},
"Kotlin/JS": {"artifact": ".mjs/.js", "ir_only_since": "1.9", "export_annotation": "@JsExport"},
"Kotlin/Native": {
"artifact": "native binary/framework",
"full_reflection": False,
"dynamic_classload": False,
"new_mm_default_since": "1.7.20",
"old_mm_removed_in": "1.9.20",
},
"Kotlin/Wasm": {"artifact": ".wasm", "targets": ["wasmJs", "wasmWasi"], "status": "Beta"},
}
# @JsExport only exports public declarations under IR backend
def js_exported(is_ir: bool, has_annotation: bool, is_public: bool) -> bool:
return is_ir and has_annotation and is_public
# Parse cinterop .def file
def_content = "headers = demo.h\npackage = demo\n"
def_parsed = dict(line.split("=", 1) for line in def_content.strip().splitlines())
def_parsed = {k.strip(): v.strip() for k, v in def_parsed.items()}
# Emulate C binding add(3, 4)
c_add_result = 3 + 4
actual = {
"backend_count": len(backends),
"native_closed_world_no_forName": not backends["Kotlin/Native"]["dynamic_classload"],
"js_export_public": js_exported(True, True, True),
"js_export_private_blocked": js_exported(True, True, False),
"cinterop_def": def_parsed,
"cinterop_add": c_add_result,
"wasm_targets": backends["Kotlin/Wasm"]["targets"],
}
expected = {
"backend_count": 4,
"native_closed_world_no_forName": True,
"js_export_public": True,
"js_export_private_blocked": False,
"cinterop_def": {"headers": "demo.h", "package": "demo"},
"cinterop_add": 7,
"wasm_targets": ["wasmJs", "wasmWasi"],
}
return {
"name": "four_backends_and_native_closed_world",
"summary": "Verify four Kotlin compiler backends, Native closed-world model, @JsExport visibility, and cinterop .def",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_expect_actual_signature_matcher():
expects = {
"platformName": ("fun", "() -> String"),
"isDesktop": ("val", "Boolean"),
}
target_actuals = {
"jvmMain": {
"platformName": ("fun", "() -> String", "Kotlin/JVM"),
"isDesktop": ("val", "Boolean", True),
},
"jsMain": {
"platformName": ("fun", "() -> String", "Kotlin/JS"),
"isDesktop": ("val", "Boolean", False),
},
"brokenTarget": {
"platformName": ("fun", "() -> Int", 123),
},
}
def check_target(target_name: str) -> list[str]:
errs = []
actuals = target_actuals[target_name]
for sym, (ekind, esig) in expects.items():
if sym not in actuals:
errs.append(f"missing actual for {sym}")
else:
akind, asig, _ = actuals[sym]
if (akind, asig) != (ekind, esig):
errs.append(f"signature mismatch for {sym}: expected {(ekind, esig)}, got {(akind, asig)}")
return errs
jvm_greeting = f"欢迎使用 Kotlin 多平台,当前平台:{target_actuals['jvmMain']['platformName'][2]}"
js_greeting = f"欢迎使用 Kotlin 多平台,当前平台:{target_actuals['jsMain']['platformName'][2]}"
actual = {
"jvm_errors": check_target("jvmMain"),
"js_errors": check_target("jsMain"),
"broken_errors": check_target("brokenTarget"),
"jvm_greeting": jvm_greeting,
"js_greeting": js_greeting,
}
expected = {
"jvm_errors": [],
"js_errors": [],
"broken_errors": [
"signature mismatch for platformName: expected ('fun', '() -> String'), got ('fun', '() -> Int')",
"missing actual for isDesktop",
],
"jvm_greeting": "欢迎使用 Kotlin 多平台,当前平台:Kotlin/JVM",
"js_greeting": "欢迎使用 Kotlin 多平台,当前平台:Kotlin/JS",
}
return {
"name": "expect_actual_signature_matcher",
"summary": "Verify expect/actual exact signature matching across jvmMain, jsMain, and mismatched targets",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_kmp_source_set_hierarchy():
# Default hierarchy template (Kotlin 1.9.20+)
parents = {
"commonMain": [],
"jvmMain": ["commonMain"],
"jsMain": ["commonMain"],
"wasmJsMain": ["commonMain"],
"nativeMain": ["commonMain"],
"appleMain": ["nativeMain"],
"iosMain": ["appleMain"],
}
def ancestors(ss: str) -> list[str]:
chain = []
cur = ss
while parents[cur]:
cur = parents[cur][0]
chain.append(cur)
return chain
def import_allowed(source_set: str, pkg: str) -> bool:
if pkg.startswith("java.") and source_set != "jvmMain":
return False
return True
actual = {
"iosMain_ancestors": ancestors("iosMain"),
"jvmMain_ancestors": ancestors("jvmMain"),
"java_util_in_commonMain": import_allowed("commonMain", "java.util.Date"),
"java_util_in_jvmMain": import_allowed("jvmMain", "java.util.Date"),
"kotlinx_datetime_in_commonMain": import_allowed("commonMain", "kotlinx.datetime.Clock"),
}
expected = {
"iosMain_ancestors": ["appleMain", "nativeMain", "commonMain"],
"jvmMain_ancestors": ["commonMain"],
"java_util_in_commonMain": False,
"java_util_in_jvmMain": True,
"kotlinx_datetime_in_commonMain": True,
}
return {
"name": "kmp_source_set_hierarchy",
"summary": "Verify KMP default hierarchy template ancestry and platform-specific import isolation in commonMain",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_four_backends_and_native_closed_world(),
case_expect_actual_signature_matcher(),
case_kmp_source_set_hierarchy(),
]
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-multiplatform-lab/explore-multiplatform.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-multiplatform.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2157.zip