"""Offline Rust semantic verification lab for Chapter 10 (function)."""
import json
import re
import shutil
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def case_function_definition_and_hoisting():
# In Rust, items in the same module can be defined after main() and still be called.
items = {}
def main_fn():
return ["Hello, world!", items["another_function"]()]
items["main"] = main_fn
items["another_function"] = lambda: "Hello, Rust!"
snake_ok = bool(re.fullmatch(r"[a-z][a-z0-9_]*", "another_function"))
expected = {
"snake_case_valid": True,
"call_output": ["Hello, world!", "Hello, Rust!"],
"rustc_installed": False,
}
actual = {
"snake_case_valid": snake_ok,
"call_output": items["main"](),
"rustc_installed": shutil.which("rustc") is not None,
}
return {
"name": "function_definition_and_hoisting",
"summary": "验证函数 snake_case 命名规范以及 main 调用后置定义函数的顺序无关性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_typed_parameters_and_arity():
def another_function(x: int, y: int) -> list[str]:
if not (isinstance(x, int) and isinstance(y, int)):
raise TypeError("expected i32")
return [f"x 的值为 : {x}", f"y 的值为 : {y}"]
expected = ["x 的值为 : 5", "y 的值为 : 6"]
actual = another_function(5, 6)
return {
"name": "typed_parameters_and_arity",
"summary": "验证带显式类型标注的双参数函数 another_function(5, 6) 的输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_statements_vs_expressions():
# Statement: `let a = 6;` does not produce a value -> `let a = (let b = 2);` is a syntax/semantic error.
let_in_expr_allowed = False
# In Rust, assignment `a = 7` is an expression that evaluates to unit `()`.
assign_expr_value = ()
a, b, c = 7, 3, 2
expr1 = b + 2
expr2 = c * (a + b)
expected = {
"let_as_rhs_allowed": False,
"assign_expr_value": [],
"b_plus_2": 5,
"c_mul_a_plus_b": 20,
}
actual = {
"let_as_rhs_allowed": let_in_expr_allowed,
"assign_expr_value": list(assign_expr_value),
"b_plus_2": expr1,
"c_mul_a_plus_b": expr2,
}
return {
"name": "statements_vs_expressions",
"summary": "区分无返回值语句(拒绝 let a = (let b = 2))、赋值表达式返回 () 与算术求值表达式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_block_expression_and_semicolon_trap():
x = 5
def eval_block(with_trailing_semicolon: bool):
inner_x = 3
val = inner_x + 1
return () if with_trailing_semicolon else val
y = eval_block(with_trailing_semicolon=False)
y_with_semi = eval_block(with_trailing_semicolon=True)
expected = {"outer_x": 5, "block_y": 4, "block_with_semicolon": []}
actual = {"outer_x": x, "block_y": y, "block_with_semicolon": list(y_with_semi)}
return {
"name": "block_expression_and_semicolon_trap",
"summary": "验证块表达式 { let x = 3; x + 1 } 求值为 4 且不改外层 x,加分号则退化为 ()",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nested_fn_and_explicit_return():
def outer():
def five() -> int:
return 5
def add(a: int, b: int) -> int:
return a + b
return five(), add(7, 8)
five_val, sum_val = outer()
# Missing -> ReturnType defaults to () and rejects returning i32
missing_arrow_error = "E0308: expected `()`, found integer"
expected = {"five": 5, "add_7_8": 15, "unannotated_return_err": "E0308"}
actual = {"five": five_val, "add_7_8": sum_val, "unannotated_return_err": missing_arrow_error[:5]}
return {
"name": "nested_fn_and_explicit_return",
"summary": "验证嵌套函数 fn five() -> i32、显式 return a + b; 以及缺失 -> 返回类型标注时的 E0308 限制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_function_definition_and_hoisting(),
case_typed_parameters_and_arity(),
case_statements_vs_expressions(),
case_block_expression_and_semicolon_trap(),
case_nested_fn_and_explicit_return(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。
入口文件:projects/rust-function-lab/explore-function.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-function.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1205.zip