"""Offline Scala semantic verification lab for Chapter 05 (data-types)."""
import json
import struct
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_numeric_and_char_bit_ranges():
ranges = {
"Byte": (-(1 << 7), (1 << 7) - 1),
"Short": (-(1 << 15), (1 << 15) - 1),
"Int": (-(1 << 31), (1 << 31) - 1),
"Long": (-(1 << 63), (1 << 63) - 1),
"Char": (0, (1 << 16) - 1),
}
f32 = struct.unpack(">f", struct.pack(">f", 3.14))[0]
expected = {
"byte_max": 127,
"short_max": 32767,
"int_max": 2147483647,
"long_max": 9223372036854775807,
"char_max_hex": "0xffff",
"float32_approx": 3.14,
}
actual = {
"byte_max": ranges["Byte"][1],
"short_max": ranges["Short"][1],
"int_max": ranges["Int"][1],
"long_max": ranges["Long"][1],
"char_max_hex": hex(ranges["Char"][1]),
"float32_approx": round(f32, 2),
}
return {
"name": "numeric_and_char_bit_ranges",
"summary": "验证 Byte/Short/Int/Long 有符号位宽边界、Char 无符号区间与 IEEE 754 单精度浮点数",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_unified_type_hierarchy_anyval_anyref():
parents = {
"Byte": "AnyVal", "Short": "AnyVal", "Int": "AnyVal", "Long": "AnyVal",
"Float": "AnyVal", "Double": "AnyVal", "Char": "AnyVal", "Boolean": "AnyVal", "Unit": "AnyVal",
"String": "AnyRef", "List": "AnyRef", "Null": "String",
"AnyVal": "Any", "AnyRef": "Any",
}
def conforms(sub, sup):
if sub == "Nothing":
return True
cur = sub
while cur is not None:
if cur == sup:
return True
cur = parents.get(cur)
return False
expected = {
"int_is_anyval": True,
"int_is_any": True,
"string_is_anyref": True,
"null_is_string": True,
"null_is_int": False,
"nothing_is_int": True,
"nothing_is_string": True,
}
actual = {
"int_is_anyval": conforms("Int", "AnyVal"),
"int_is_any": conforms("Int", "Any"),
"string_is_anyref": conforms("String", "AnyRef"),
"null_is_string": conforms("Null", "String"),
"null_is_int": conforms("Null", "Int"),
"nothing_is_int": conforms("Nothing", "Int"),
"nothing_is_string": conforms("Nothing", "String"),
}
return {
"name": "unified_type_hierarchy_anyval_anyref",
"summary": "校验 Scala 统一类型层次中 Any/AnyVal/AnyRef/Null/Nothing 的子类型关系",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_collection_and_effect_containers():
list_val = (1, 2, 3)
set_val = frozenset({"Scala", "Java", "Python"})
map_val = {"one": 1, "two": 2, "three": 3}
array_val = [4, 5, 6]
tuple_val = (42, "Answer", True)
option_val = ("Some", "I am here")
either_val = ("Right", 42)
try_val = ("Success", 10 // 2)
expected = {
"list_len": 3,
"set_has_scala": True,
"map_two": 2,
"array_joined": "4, 5, 6",
"tuple_second": "Answer",
"option_tag": "Some",
"either_tag": "Right",
"try_result": ("Success", 5),
}
actual = {
"list_len": len(list_val),
"set_has_scala": "Scala" in set_val,
"map_two": map_val["two"],
"array_joined": ", ".join(str(x) for x in array_val),
"tuple_second": tuple_val[1],
"option_tag": option_val[0],
"either_tag": either_val[0],
"try_result": try_val,
}
return {
"name": "collection_and_effect_containers",
"summary": "验证 List/Set/Map/Array/Tuple/Option/Either/Try 八类集合与容器语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_unit_null_nothing_execution_trap():
# Evaluating `throw new RuntimeException(...)` aborts subsequent statements unless deferred/caught
printed_before_throw = []
def simulate_unguarded():
printed_before_throw.append("init")
raise RuntimeError("Nothing value")
caught_msg = ""
try:
simulate_unguarded()
printed_before_throw.append("unreachable")
except RuntimeError as exc:
caught_msg = str(exc)
expected = {
"unit_repr": "()",
"null_repr": "null",
"caught_exception": "Nothing value",
"unreachable_skipped": True,
}
actual = {
"unit_repr": "()",
"null_repr": "null",
"caught_exception": caught_msg,
"unreachable_skipped": "unreachable" not in printed_before_throw,
}
return {
"name": "unit_null_nothing_execution_trap",
"summary": "验证 Unit、Null 与 Nothing 异常中断行为,说明源码示例中直接求值 throw 会阻断后续打印",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_numeric_and_char_bit_ranges(),
case_unified_type_hierarchy_anyval_anyref(),
case_collection_and_effect_containers(),
case_unit_null_nothing_execution_trap(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
入口文件:projects/scala-data-types-lab/explore-data-types.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-data-types.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2414.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip