"""Offline Kotlin 2.x semantic verifier for Chapter 12 (loop-control)."""
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class _BreakOuter(Exception):
pass
class _ContinueOuter(Exception):
pass
class _NonLocalReturn(Exception):
def __init__(self, value: object = None) -> None:
self.value = value
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: for loop over collections, arrays, ranges, indices, withIndex, Map destructuring
sites = ["Mbsky", "www.mbsky.com", "MBSKY"]
numbers = [10, 20, 30]
info = {"name": "Mbsky", "site": "www.mbsky.com"}
actual_1 = {
"for_list": [s for s in sites],
"for_int_array": [f"当前元素:{n}" for n in numbers],
"closed_1_3": list(range(1, 4)),
"until_1_3": list(range(1, 3)),
"downTo_3_1": list(range(3, 0, -1)),
"step_1_6_2": list(range(1, 7, 2)),
"open_end_1_3": list(range(1, 3)),
"indices": [f"{i}->{sites[i]}" for i in range(len(sites))],
"with_index": [f"{i}: {v}" for i, v in enumerate(sites)],
"map_destructure": [f"{k} = {v}" for k, v in info.items()],
}
expected_1 = {
"for_list": ["Mbsky", "www.mbsky.com", "MBSKY"],
"for_int_array": ["当前元素:10", "当前元素:20", "当前元素:30"],
"closed_1_3": [1, 2, 3],
"until_1_3": [1, 2],
"downTo_3_1": [3, 2, 1],
"step_1_6_2": [1, 3, 5],
"open_end_1_3": [1, 2],
"indices": ["0->Mbsky", "1->www.mbsky.com", "2->MBSKY"],
"with_index": ["0: Mbsky", "1: www.mbsky.com", "2: MBSKY"],
"map_destructure": ["name = Mbsky", "site = www.mbsky.com"],
}
cases.append({
"name": "for_ranges_indices_and_destructuring",
"summary": "Verify for loops over lists/arrays/ranges, indices, withIndex(), and Map destructuring.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: while (0+ iterations) vs do...while (1+ iterations)
countdown: list[int] = []
c = 3
while c > 0:
countdown.append(c)
c -= 1
zero_while_runs = 0
c0 = 0
while c0 > 0:
zero_while_runs += 1
c0 -= 1
do_while_log: list[int] = []
cd = 0
while True:
do_while_log.append(cd)
cd += 1
if not (cd < 0):
break
actual_2 = {
"while_countdown": countdown,
"while_false_initial_runs": zero_while_runs,
"do_while_runs_once": do_while_log,
"do_while_final_count": cd,
}
expected_2 = {
"while_countdown": [3, 2, 1],
"while_false_initial_runs": 0,
"do_while_runs_once": [0],
"do_while_final_count": 1,
}
cases.append({
"name": "while_and_do_while_execution",
"summary": "Verify while pre-check (0 iterations when false) vs do...while post-check (at least 1 iteration).",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: break, continue, labeled break@loop / continue@loop, and labeled lambda return@check
basic_jump: list[int] = []
for i in range(1, 11):
if i == 3:
continue
if i > 5:
break
basic_jump.append(i)
labeled_pairs: list[str] = []
try:
for i in range(1, 4):
try:
for j in range(1, 4):
if j == 2:
raise _ContinueOuter()
if i == 3:
raise _BreakOuter()
labeled_pairs.append(f"i={i},j={j}")
except _ContinueOuter:
continue
except _BreakOuter:
pass
def labeled_lambda_check(value: int) -> str:
if value < 0:
return "负数" # return@check
return "非负数"
actual_3 = {
"basic_break_continue": basic_jump,
"labeled_loop_pairs": labeled_pairs,
"labeled_lambda": [labeled_lambda_check(5), labeled_lambda_check(-1)],
}
expected_3 = {
"basic_break_continue": [1, 2, 4, 5],
"labeled_loop_pairs": ["i=1,j=1", "i=2,j=1"],
"labeled_lambda": ["非负数", "负数"],
}
cases.append({
"name": "break_continue_and_labeled_jumps",
"summary": "Verify break/continue, labeled continue@loop & break@loop, and labeled lambda return@check.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Kotlin 2.2 non-local break/continue in inline lambda & return@forEach vs non-local return
def inline_run(fn):
return fn()
nl_continue_out: list[str] = []
for num in [1, None, 3, None, 5]:
try:
if num is None:
def _on_null():
nl_continue_out.append("skip_null")
raise _ContinueOuter()
inline_run(_on_null)
val = num
nl_continue_out.append(f"val={val}")
except _ContinueOuter:
continue
nl_break_out: list[int] = []
try:
for num in [1, 2, 3, 4, 5]:
def _check_break(n=num):
if n == 4:
raise _BreakOuter()
inline_run(_check_break)
nl_break_out.append(num)
except _BreakOuter:
pass
foreach_labeled: list[int] = []
for item in [1, 2, 0, 4]:
# return@forEach skips only current invocation
if item == 0:
continue
foreach_labeled.append(item)
foreach_nonlocal: list[int] = []
try:
for item in [1, 2, 0, 4]:
if item == 0:
raise _NonLocalReturn()
foreach_nonlocal.append(item)
except _NonLocalReturn:
pass
actual_4 = {
"non_local_continue_2_2": nl_continue_out,
"non_local_break_2_2": nl_break_out,
"return_at_forEach": foreach_labeled,
"non_local_return_exits_enclosing": foreach_nonlocal,
"non_local_break_continue_stable": "2.2",
}
expected_4 = {
"non_local_continue_2_2": ["val=1", "skip_null", "val=3", "skip_null", "val=5"],
"non_local_break_2_2": [1, 2, 3],
"return_at_forEach": [1, 2, 4],
"non_local_return_exits_enclosing": [1, 2],
"non_local_break_continue_stable": "2.2",
}
cases.append({
"name": "non_local_jumps_and_return_at_foreach",
"summary": "Verify Kotlin 2.2 non-local continue/break inside inline lambdas and return@forEach vs non-local return.",
"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-loop-control-lab/explore-loop-control.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-loop-control.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2156.zip