"""Offline Kotlin 2.x semantic verifier for Chapter 15 (inline-function)."""
import json
import sys
from typing import Any, Callable, Type
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class _NonLocalReturn(Exception):
pass
class Site:
def __init__(self, name: str) -> None:
self.name = name
class SiteValidator:
"""Models @PublishedApi internal member accessed from a public inline function."""
def __init__(self) -> None:
self._published_api_members = {"check_name"}
def check_name(self, name: str) -> bool:
return len(name) > 0
def validate_inline(self, name: str, *, published_api: bool = True) -> bool:
if not published_api:
raise PermissionError("Public-API inline function cannot access non-public-API internal member")
return self.check_name(name)
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Inline vs normal HOF object-allocation model & non-local return
alloc_normal = 0
alloc_inline = 0
normal_log: list[str] = []
inline_log: list[str] = []
def run_task_normal(action: Callable[[], None]) -> None:
nonlocal alloc_normal
alloc_normal += 1 # Function0 instance allocated per call
action()
def run_task_inline(action: Callable[[], None]) -> None:
# Inlined at call site: zero Function0 allocations
action()
for _ in range(5):
run_task_normal(lambda: normal_log.append("ok"))
run_task_inline(lambda: inline_log.append("ok"))
nl_seen: list[int] = []
after_foreach_executed = False
try:
for el in [1, 2, 3, 4, 5]:
if el == 3:
raise _NonLocalReturn()
nl_seen.append(el)
after_foreach_executed = True
except _NonLocalReturn:
pass
actual_1 = {
"normal_allocations": alloc_normal,
"inline_allocations": alloc_inline,
"identical_runtime_output": normal_log == inline_log,
"non_local_return_output": nl_seen,
"after_foreach_executed": after_foreach_executed,
"non_inline_allows_non_local_return": False,
}
expected_1 = {
"normal_allocations": 5,
"inline_allocations": 0,
"identical_runtime_output": True,
"non_local_return_output": [1, 2],
"after_foreach_executed": False,
"non_inline_allows_non_local_return": False,
}
cases.append({
"name": "inline_allocation_and_non_local_return",
"summary": "Model Function0 allocation elimination via inline and non-local return exiting the enclosing function.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: noinline (store as value) & crossinline (indirect Runnable context, no non-local return)
events: list[str] = []
def run_with_noinline(on_finish: Callable[[], None], action: Callable[[], None]) -> Callable[[], None]:
action()
saved_handler = on_finish # allowed because noinline
saved_handler()
return saved_handler
stored = run_with_noinline(
on_finish=lambda: events.append("finish:MBSKY"),
action=lambda: events.append("run:www.mbsky.com"),
)
def run_crossinline(block: Callable[[], None], *, allow_non_local_return: bool = False) -> str:
if allow_non_local_return:
raise SyntaxError("'return' is not allowed in crossinline lambda")
task = lambda: block() # wrapped in another execution context (Runnable)
task()
return "ran_in_runnable"
cross_log: list[str] = []
cross_res = run_crossinline(lambda: cross_log.append("crossinline:MBSKY"))
cross_nl_rejected = False
try:
run_crossinline(lambda: None, allow_non_local_return=True)
except SyntaxError:
cross_nl_rejected = True
actual_2 = {
"noinline_events": events,
"noinline_storable": callable(stored),
"crossinline_result": cross_res,
"crossinline_log": cross_log,
"crossinline_forbids_non_local_return": cross_nl_rejected,
}
expected_2 = {
"noinline_events": ["run:www.mbsky.com", "finish:MBSKY"],
"noinline_storable": True,
"crossinline_result": "ran_in_runnable",
"crossinline_log": ["crossinline:MBSKY"],
"crossinline_forbids_non_local_return": True,
}
cases.append({
"name": "noinline_and_crossinline_modifiers",
"summary": "Verify noinline storable lambda semantics and crossinline indirect context with forbidden non-local return.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: reified type parameters (is T, T::class.simpleName, filterIsInstance)
kotlin_type_names = {str: "String", int: "Int", Site: "Site"}
def is_instance_of(val: Any, reified_type: Type[Any]) -> bool:
return isinstance(val, reified_type) and not (reified_type is int and isinstance(val, bool))
def type_name(reified_type: Type[Any]) -> str:
return kotlin_type_names.get(reified_type, reified_type.__name__)
def filter_is_instance(items: list[Any], reified_type: Type[Any]) -> list[Any]:
return [x for x in items if is_instance_of(x, reified_type)]
mixed: list[Any] = [1, "Mbsky", 2, "MBSKY", 3.14]
actual_3 = {
"is_string": is_instance_of("MBSKY", str),
"is_int": is_instance_of("MBSKY", int),
"type_names": [type_name(str), type_name(int), type_name(Site)],
"filtered_strings": filter_is_instance(mixed, str),
"reified_requires_inline": True,
"can_call_T_constructor_directly": False,
}
expected_3 = {
"is_string": True,
"is_int": False,
"type_names": ["String", "Int", "Site"],
"filtered_strings": ["Mbsky", "MBSKY"],
"reified_requires_inline": True,
"can_call_T_constructor_directly": False,
}
cases.append({
"name": "reified_type_checks_and_filter_is_instance",
"summary": "Verify inline reified is T checks, T::class.simpleName, filterIsInstance, and T() restriction.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: @PublishedApi visibility check & inline trade-off criteria
validator = SiteValidator()
without_annotation_blocked = False
try:
validator.validate_inline("Mbsky", published_api=False)
except PermissionError:
without_annotation_blocked = True
actual_4 = {
"with_published_api_valid": [validator.validate_inline("Mbsky"), validator.validate_inline("")],
"without_published_api_blocked": without_annotation_blocked,
"inline_recommended_when_no_lambda_no_reified": False,
}
expected_4 = {
"with_published_api_valid": [True, False],
"without_published_api_blocked": True,
"inline_recommended_when_no_lambda_no_reified": False,
}
cases.append({
"name": "published_api_and_inline_guidelines",
"summary": "Verify @PublishedApi access enforcement from public inline functions and inline applicability 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-inline-function-lab/explore-inline-function.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-inline-function.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2151.zip