"""Offline Kotlin 2.x semantic verifier for Chapter 07 (basic-syntax)."""
import json
import math
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def strip_nested_block_comments(src: str) -> str:
"""Kotlin supports nested /* ... /* ... */ ... */ block comments unlike Java."""
out: list[str] = []
i = 0
depth = 0
n = len(src)
while i < n:
if i + 1 < n and src[i : i + 2] == "/*":
depth += 1
i += 2
elif depth > 0 and i + 1 < n and src[i : i + 2] == "*/":
depth -= 1
i += 2
elif depth == 0:
out.append(src[i])
i += 1
else:
i += 1
if depth != 0:
raise ValueError("Unclosed block comment")
return "".join(out)
def infer_kotlin_type(val: object) -> str:
if isinstance(val, bool):
return "Boolean"
if isinstance(val, int):
return "Int"
if isinstance(val, float):
return "Double"
if isinstance(val, str):
return "String"
raise TypeError(type(val))
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: package, import, import alias (as), wildcard (*), and 10 default imports
pi_value = math.pi
area_r2 = pi_value * 2.0 * 2.0
recovered_r = math.sqrt(area_r2 / pi_value)
default_common = [
"kotlin.*", "kotlin.annotation.*", "kotlin.collections.*",
"kotlin.comparisons.*", "kotlin.io.*", "kotlin.ranges.*",
"kotlin.sequences.*", "kotlin.text.*",
]
default_jvm_only = ["java.lang.*", "kotlin.jvm.*"]
actual_1 = {
"recovered_radius": recovered_r,
"pi_alias_approx": round(pi_value, 6),
"wildcard_max_abs": [max(3, 7), abs(-5)],
"default_imports_total": len(default_common) + len(default_jvm_only),
"jvm_only_imports": default_jvm_only,
}
expected_1 = {
"recovered_radius": 2.0,
"pi_alias_approx": 3.141593,
"wildcard_max_abs": [7, 5],
"default_imports_total": 10,
"jvm_only_imports": ["java.lang.*", "kotlin.jvm.*"],
}
cases.append({
"name": "package_import_and_default_packages",
"summary": "Verify package/import/as/wildcard semantics and the 10 default-imported packages (8 common + 2 JVM-only).",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: main(), main(args: Array<String>), suspend fun main()
def run_args_main(args: list[str]) -> list[str]:
name = args[0] if args else "Kotlin"
return [f"参数个数:{len(args)}", f"欢迎访问 {name}"]
actual_2 = {
"empty_args": run_args_main([]),
"one_arg": run_args_main(["蓝色天空网"]),
"suspend_main_since": "1.3",
"both_main_and_suspend_main_in_same_file_allowed": False,
}
expected_2 = {
"empty_args": ["参数个数:0", "欢迎访问 Kotlin"],
"one_arg": ["参数个数:1", "欢迎访问 蓝色天空网"],
"suspend_main_since": "1.3",
"both_main_and_suspend_main_in_same_file_allowed": False,
}
cases.append({
"name": "main_entry_variants_and_suspend_main",
"summary": "Model parameterless main, args: Array<String> fallback, and suspend fun main() rules.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: val vs var, reassignment check, type inference, explicit type
class Scope:
def __init__(self) -> None:
self._vals: dict[str, tuple[str, object]] = {}
self._vars: dict[str, tuple[str, object | None]] = {}
def decl_val(self, name: str, value: object) -> None:
self._vals[name] = (infer_kotlin_type(value), value)
def decl_var(self, name: str, typ: str | None = None, value: object | None = None) -> None:
if value is None and typ is None:
raise SyntaxError("Type annotation required when uninitialized")
inferred = typ if typ is not None else infer_kotlin_type(value)
self._vars[name] = (inferred, value)
def assign(self, name: str, value: object) -> None:
if name in self._vals:
raise TypeError("Val cannot be reassigned")
t, _ = self._vars[name]
self._vars[name] = (t, value)
sc = Scope()
sc.decl_val("siteName", "蓝色天空网")
sc.decl_var("count", value=1)
sc.assign("count", 2)
val_error = ""
try:
sc.assign("siteName", "Other")
except TypeError as exc:
val_error = str(exc)
sc.decl_var("age", typ="Int", value=None)
sc.assign("age", 25)
untyped_error = False
try:
sc.decl_var("bad")
except SyntaxError:
untyped_error = True
actual_3 = {
"count_after_inc": sc._vars["count"][1],
"val_reassign_error": val_error,
"inferred_types": [infer_kotlin_type("mbsky"), infer_kotlin_type(25), infer_kotlin_type(9.9), infer_kotlin_type(True)],
"explicit_deferred_age": sc._vars["age"][1],
"uninitialized_without_type_rejected": untyped_error,
}
expected_3 = {
"count_after_inc": 2,
"val_reassign_error": "Val cannot be reassigned",
"inferred_types": ["String", "Int", "Double", "Boolean"],
"explicit_deferred_age": 25,
"uninitialized_without_type_rejected": True,
}
cases.append({
"name": "val_var_and_type_inference",
"summary": "Verify val immutability, var reassignment, literal type inference, and explicit type requirement when uninitialized.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Nestable block comments, string templates, semicolon & line-break split
nested_src = '/* outer /* inner */ still outer */fun main() = println("ok")'
stripped = strip_nested_block_comments(nested_src)
site_name = "蓝色天空网"
url = "www.mbsky.com"
x_multiline = 1 + 2 # trailing operator continues line
y_split = 10 # leading `- 3` on next line becomes separate unary expression
actual_4 = {
"nested_comment_stripped": stripped,
"template_lines": [
f"欢迎访问 {site_name}",
f"网址:{url.upper()}",
f"名称长度:{len(site_name)}",
f"差值:{2026 - 2010}",
"价格是 $9.9",
],
"semicolon_sums": [1 + 2, 3 + 4],
"multiline_x": x_multiline,
"split_y": y_split,
}
expected_4 = {
"nested_comment_stripped": 'fun main() = println("ok")',
"template_lines": [
"欢迎访问 蓝色天空网",
"网址:WWW.MBSKY.COM",
"名称长度:5",
"差值:16",
"价格是 $9.9",
],
"semicolon_sums": [3, 7],
"multiline_x": 3,
"split_y": 10,
}
cases.append({
"name": "nested_comments_templates_and_linebreaks",
"summary": "Verify Kotlin nestable block comments, string templates with escaped $, optional semicolons, and newline statement splitting.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: Null safety intro (String vs String?, ?., ?:)
not_null: str = "Kotlin"
maybe_null: str | None = None
safe_len = len(maybe_null) if maybe_null is not None else None
elvis_len = safe_len if safe_len is not None else 0
actual_5 = {
"not_null_len": len(not_null),
"safe_call_on_null": safe_len,
"elvis_default": elvis_len,
}
expected_5 = {
"not_null_len": 6,
"safe_call_on_null": None,
"elvis_default": 0,
}
cases.append({
"name": "null_safety_safe_call_and_elvis",
"summary": "Model non-null String vs nullable String?, safe call ?. returning null, and Elvis ?: fallback.",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
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-basic-syntax-lab/explore-basic-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-basic-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2133.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip