"""Offline Kotlin 2.x semantic verifier for Chapter 05 (command-line)."""
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def parse_kotlinc_args(argv: list[str]) -> dict:
"""Deterministic CLI flag parser modeling kotlinc options."""
result = {
"version": False,
"output": None,
"output_kind": None,
"include_runtime": False,
"classpath": None,
"jvm_target": None,
"script": None,
"nowarn": False,
"werror": False,
"sources": [],
}
i = 0
while i < len(argv):
tok = argv[i]
if tok == "-version":
result["version"] = True
elif tok == "-include-runtime":
result["include_runtime"] = True
elif tok == "-nowarn":
result["nowarn"] = True
elif tok == "-Werror":
result["werror"] = True
elif tok == "-d":
i += 1
out = argv[i]
result["output"] = out
result["output_kind"] = "jar" if out.endswith(".jar") else "directory"
elif tok in ("-classpath", "-cp"):
i += 1
result["classpath"] = argv[i]
elif tok == "-jvm-target":
i += 1
result["jvm_target"] = argv[i]
elif tok == "-script":
i += 1
result["script"] = argv[i]
else:
result["sources"].append(tok)
i += 1
return result
def file_to_facade(package: str | None, filename: str) -> str:
stem = filename[:-3] if filename.endswith(".kt") else filename
cls = stem[0].upper() + stem[1:] + "Kt"
return f"{package}.{cls}" if package else cls
def simulate_jar_run(include_runtime: bool, manual_stdlib_cp: bool) -> dict:
if include_runtime or manual_stdlib_cp:
return {"ok": True, "error": None}
return {"ok": False, "error": "NoClassDefFoundError: kotlin/jvm/internal/Intrinsics"}
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Installation methods & -version flag
install_methods = {
"SDKMAN!": "sdk install kotlin",
"Homebrew": "brew install kotlin",
"MacPorts": "sudo port install kotlin",
"手动下载": "GitHub Releases zip + PATH",
}
parsed_ver = parse_kotlinc_args(["-version"])
actual_1 = {
"install_method_count": len(install_methods),
"version_flag": parsed_ver["version"],
"min_jdk": 8,
}
expected_1 = {
"install_method_count": 4,
"version_flag": True,
"min_jdk": 8,
}
cases.append({
"name": "kotlinc_install_and_version_flag",
"summary": "Verify four kotlinc install channels, -version flag parsing, and JDK 8+ prerequisite.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: -d (jar vs directory), -include-runtime, facade class naming, and classpath separator
fat_jar = parse_kotlinc_args(["hello.kt", "-include-runtime", "-d", "hello.jar"])
class_dir = parse_kotlinc_args(["hello.kt", "-d", "out"])
lib_jar = parse_kotlinc_args(["Site.kt", "-d", "site.jar"])
actual_2 = {
"fat_jar_kind": fat_jar["output_kind"],
"fat_jar_run": simulate_jar_run(fat_jar["include_runtime"], False),
"missing_runtime_run": simulate_jar_run(False, False),
"manual_cp_run": simulate_jar_run(False, True),
"dir_output_kind": class_dir["output_kind"],
"hello_facade": file_to_facade(None, "hello.kt"),
"site_facade": file_to_facade("com.mbsky", "Site.kt"),
"lib_has_runtime": lib_jar["include_runtime"],
"cp_separators": {"windows": ";", "posix": ":"},
}
expected_2 = {
"fat_jar_kind": "jar",
"fat_jar_run": {"ok": True, "error": None},
"missing_runtime_run": {"ok": False, "error": "NoClassDefFoundError: kotlin/jvm/internal/Intrinsics"},
"manual_cp_run": {"ok": True, "error": None},
"dir_output_kind": "directory",
"hello_facade": "HelloKt",
"site_facade": "com.mbsky.SiteKt",
"lib_has_runtime": False,
"cp_separators": {"windows": ";", "posix": ":"},
}
cases.append({
"name": "kotlinc_jar_dir_runtime_and_facade",
"summary": "Model -d directory/jar outputs, -include-runtime behavior, Intrinsics error, and FileKt facade naming.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: REPL stateful session & .kts script execution with args
repl_env: dict[str, str] = {}
repl_env["siteName"] = "蓝色天空网"
repl_out_1 = f"欢迎访问 {repl_env['siteName']}"
repl_out_2 = "网址:www.mbsky.com".upper()
script_parsed = parse_kotlinc_args(["-script", "greet.kts", "蓝色天空网"])
args = script_parsed["sources"]
greet_name = args[0] if args else "Kotlin"
actual_3 = {
"repl_lines": [repl_out_1, repl_out_2],
"repl_exit_cmd": ":quit",
"script_file": script_parsed["script"],
"script_greeting": f"你好,{greet_name}!欢迎访问 www.mbsky.com",
"default_greeting": "你好,Kotlin!欢迎访问 www.mbsky.com",
}
expected_3 = {
"repl_lines": ["欢迎访问 蓝色天空网", "网址:WWW.MBSKY.COM"],
"repl_exit_cmd": ":quit",
"script_file": "greet.kts",
"script_greeting": "你好,蓝色天空网!欢迎访问 www.mbsky.com",
"default_greeting": "你好,Kotlin!欢迎访问 www.mbsky.com",
}
cases.append({
"name": "repl_session_and_kts_script_args",
"summary": "Simulate persistent REPL variable binding and .kts script argument passing.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Full common option flags (-cp, -jvm-target, -nowarn, -Werror)
ci_cmd = parse_kotlinc_args(["main.kt", "-cp", "libs/util.jar", "-jvm-target", "17", "-Werror", "-d", "out"])
quiet_cmd = parse_kotlinc_args(["hello.kt", "-nowarn", "-d", "out"])
actual_4 = {
"cp": ci_cmd["classpath"],
"jvm_target": ci_cmd["jvm_target"],
"werror": ci_cmd["werror"],
"nowarn": quiet_cmd["nowarn"],
}
expected_4 = {
"cp": "libs/util.jar",
"jvm_target": "17",
"werror": True,
"nowarn": True,
}
cases.append({
"name": "kotlinc_common_flags_verification",
"summary": "Verify -cp/-classpath, -jvm-target, -nowarn, and -Werror flag semantics.",
"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-command-line-lab/explore-command-line.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-command-line.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2138.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip