蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 var/final/const 语义、数值与字符串方法、空安全操作符及显式类型转换

PYTHONWindows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。explore-variables-and-types.py
explore-variables-and-types.py237 行
"""Offline Dart 3.x semantic verification lab for Chapter 06 (variables-and-types)."""
import json
import math
import random

VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"


def case_var_final_const_binding_semantics():
    class Binding:
        def __init__(self, kind: str, static_type: str, assigned: bool = False, value=None):
            self.kind = kind
            self.static_type = static_type
            self.assigned = assigned
            self.value = value

        def set_val(self, val, val_type: str, compile_time: bool = False) -> tuple[bool, str]:
            if val_type != self.static_type:
                return False, "type_mismatch"
            if self.kind == "const":
                if not compile_time:
                    return False, "non_const_initializer"
                if self.assigned:
                    return False, "const_reassign"
            if self.kind == "final" and self.assigned:
                return False, "final_reassign"
            self.value = val
            self.assigned = True
            return True, "ok"

    v = Binding("var", "String", True, "BlueSky")
    var_wrong_type = v.set_val(123, "int")

    f = Binding("final", "String", False)
    final_first = f.set_val("Hello, BlueSky!", "String", compile_time=False)
    final_second = f.set_val("Again", "String", compile_time=False)

    c_ok = Binding("const", "int", False)
    const_ok = c_ok.set_val(100, "int", compile_time=True)
    c_bad = Binding("const", "DateTime", False)
    const_runtime = c_bad.set_val("2026-06-12", "DateTime", compile_time=False)

    expected = {
        "var_wrong_type": [False, "type_mismatch"],
        "final_first": [True, "ok"],
        "final_second": [False, "final_reassign"],
        "const_ok": [True, "ok"],
        "const_runtime_rejected": [False, "non_const_initializer"],
    }
    actual = {
        "var_wrong_type": list(var_wrong_type),
        "final_first": list(final_first),
        "final_second": list(final_second),
        "const_ok": list(const_ok),
        "const_runtime_rejected": list(const_runtime),
    }
    return {
        "name": "var_final_const_binding_semantics",
        "summary": "验证 var 静态类型锁定、final 单次运行时延迟赋值及 const 编译期常量限制",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_numbers_strings_and_booleans():
    a = -10
    b = 3.7
    rng = random.Random(2026)
    rand_sample = rng.randrange(100)

    text = "  Hello, BlueSky!  "
    csv = "Dart,Flutter,Google"

    def dart_if_condition(cond):
        if not isinstance(cond, bool):
            raise TypeError("Conditions must have a static type of 'bool'")
        return cond

    rejected_zero = False
    try:
        dart_if_condition(0)
    except TypeError:
        rejected_zero = True

    rejected_empty_str = False
    try:
        dart_if_condition("")
    except TypeError:
        rejected_empty_str = True

    expected = {
        "num_ops": {"abs": 10, "round": 4, "floor": 3, "ceil": 4, "parsed_int": 42, "parsed_double": 3.14, "rand_in_range": True},
        "str_ops": {
            "trim": "Hello, BlueSky!",
            "contains": True,
            "starts_space": True,
            "ends_bang": True,
            "replaced": "  Hello, DART!  ",
            "split": ["Dart", "Flutter", "Google"],
        },
        "strict_bool": {"and_result": False, "not_result": False, "reject_zero": True, "reject_empty_str": True},
    }
    actual = {
        "num_ops": {
            "abs": abs(a),
            "round": int(math.floor(b + 0.5)),
            "floor": math.floor(b),
            "ceil": math.ceil(b),
            "parsed_int": int("42"),
            "parsed_double": float("3.14"),
            "rand_in_range": 0 <= rand_sample < 100,
        },
        "str_ops": {
            "trim": text.strip(),
            "contains": "BlueSky" in text,
            "starts_space": text.startswith(" "),
            "ends_bang": text.strip().endswith("!"),
            "replaced": text.replace("BlueSky", "DART"),
            "split": csv.split(","),
        },
        "strict_bool": {
            "and_result": True and False,
            "not_result": not True,
            "reject_zero": rejected_zero,
            "reject_empty_str": rejected_empty_str,
        },
    }
    return {
        "name": "numbers_strings_and_booleans",
        "summary": "校验 int/double 数值方法、String 常用文本方法及 Dart 严格 bool 条件检查",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sound_null_safety_operators():
    def null_assert(val):
        if val is None:
            raise RuntimeError("Null check operator used on a null value")
        return val

    username: str | None = None
    display_name = username if username is not None else "BlueSky 访客"
    if username is None:
        username = "新用户"
    # Second ??= does not overwrite non-null
    if username is None:
        username = "被忽略"

    maybe_null: str | None = None
    len_when_null = len(maybe_null) if maybe_null is not None else None
    maybe_null = "Hello"
    len_when_set = len(maybe_null) if maybe_null is not None else None

    bang_ok = len(null_assert("BlueSky"))
    bang_failed = False
    try:
        null_assert(None)
    except RuntimeError:
        bang_failed = True

    expected = {
        "coalesce_default": "BlueSky 访客",
        "coalesce_assign_once": "新用户",
        "safe_access_null": None,
        "safe_access_non_null": 5,
        "bang_non_null_len": 7,
        "bang_on_null_throws": True,
    }
    actual = {
        "coalesce_default": display_name,
        "coalesce_assign_once": username,
        "safe_access_null": len_when_null,
        "safe_access_non_null": len_when_set,
        "bang_non_null_len": bang_ok,
        "bang_on_null_throws": bang_failed,
    }
    return {
        "name": "sound_null_safety_operators",
        "summary": "验证 Dart 空安全操作 ??、??=、?. 及 ! 断言在非空与 null 上的行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_explicit_type_conversions():
    count_str = str(42)
    price = float("19.99")
    as_double = float(10)
    pi_trunc = int(3.14)
    neg_trunc = int(-3.9)
    bool_str = "true" if True else "false"
    parsed_bool = "true" == "true"

    expected = {
        "int_to_str": "42",
        "str_to_double": 19.99,
        "int_to_double": 10.0,
        "double_to_int_pos": 3,
        "double_to_int_neg": -3,
        "bool_to_str": "true",
        "str_to_bool": True,
    }
    actual = {
        "int_to_str": count_str,
        "str_to_double": price,
        "int_to_double": as_double,
        "double_to_int_pos": pi_trunc,
        "double_to_int_neg": neg_trunc,
        "bool_to_str": bool_str,
        "str_to_bool": parsed_bool,
    }
    return {
        "name": "explicit_type_conversions",
        "summary": "校验数字/字符串/布尔值之间的显式转换及 double.toInt() 向零截断语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_var_final_const_binding_semantics(),
        case_numbers_strings_and_booleans(),
        case_sound_null_safety_operators(),
        case_explicit_type_conversions(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。

入口文件:projects/dart-variables-and-types-lab/explore-variables-and-types.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-variables-and-types.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Dart

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip

下载课程关联工程包:Dart

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2554.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习