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

离线校验首程序语法拆解、var 推断与插值、三元条件及五大新手报错诊断

PYTHONWindows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。explore-first-program.py
explore-first-program.py219 行
"""Offline Dart 3.x semantic verification lab for Chapter 04 (first-program)."""
import json
import re

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


def case_entry_structure_quotes_and_comments():
    single_q = "Hello, Dart!"
    double_q = "Hello, Dart!"
    with_apostrophe = "It's a beautiful day!"
    with_quotes = '他说:"你好"'

    sample = (
        "/// 文档注释\n"
        "void main() {\n"
        "  // 单行注释\n"
        "  /* 多行\n注释 */\n"
        "  print('Hello, Dart!'); // 行尾注释\n"
        "}\n"
    )
    stripped = re.sub(r"/\*.*?\*/", "", sample, flags=re.S)
    stripped = re.sub(r"//.*", "", stripped)
    code_lines = [line.strip() for line in stripped.splitlines() if line.strip()]

    expected = {
        "quotes_equivalent": True,
        "apostrophe_text": "It's a beautiful day!",
        "inner_double_quote": '他说:"你好"',
        "executable_lines": ["void main() {", "print('Hello, Dart!');", "}"],
    }
    actual = {
        "quotes_equivalent": single_q == double_q,
        "apostrophe_text": with_apostrophe,
        "inner_double_quote": with_quotes,
        "executable_lines": code_lines,
    }
    return {
        "name": "entry_structure_quotes_and_comments",
        "summary": "校验 void main() 结构、单双引号等价与嵌套策略及三类注释剥离后的可执行语句",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_variables_inference_and_interpolation():
    def infer_dart_type(val):
        if isinstance(val, bool):
            return "bool"
        if isinstance(val, int):
            return "int"
        if isinstance(val, float):
            return "double"
        if isinstance(val, str):
            return "String"
        return "Object"

    env = {
        "name": ("String", "BlueSky"),
        "age": ("int", 25),
        "height": ("double", 1.68),
        "isStudent": ("bool", True),
    }
    inferred = {k: infer_dart_type(v) for k, (_, v) in env.items()}

    def assign(var_name, new_val):
        declared_type, _ = env[var_name]
        if infer_dart_type(new_val) != declared_type:
            return False
        env[var_name] = (declared_type, new_val)
        return True

    ok_str = assign("name", "Bob")
    bad_int = assign("name", 123)

    name_val = "BlueSky"
    age_val = 25
    line1 = f"我叫 {name_val},今年 {age_val} 岁。"
    line2 = f"明年我将 {age_val + 1} 岁。"
    upper_expr = name_val.upper()

    expected = {
        "inferred": {"name": "String", "age": "int", "height": "double", "isStudent": "bool"},
        "reassign_same_type": True,
        "reassign_wrong_type": False,
        "interpolated": ["我叫 BlueSky,今年 25 岁。", "明年我将 26 岁。", "BLUESKY"],
    }
    actual = {
        "inferred": inferred,
        "reassign_same_type": ok_str,
        "reassign_wrong_type": bad_int,
        "interpolated": [line1, line2, upper_expr],
    }
    return {
        "name": "variables_inference_and_interpolation",
        "summary": "校验 String/int/double/bool 显式与 var 静态推断、跨类型赋值拒绝及 $var/${expr} 插值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_profile_generator_and_ternary():
    name = "BlueSky"
    age = 25
    city = "上海"
    is_student = False
    hobby = "Dart 编程"

    ternary_val = "学生" if is_student else "职场人"
    if is_student:
        ifelse_val = "学生"
    else:
        ifelse_val = "职场人"

    summary_lines = [
        f"姓名:{name}",
        f"年龄:{age} 岁",
        f"城市:{city}",
        f"身份:{ternary_val}",
        f"爱好:{hobby}",
    ]
    expected = {
        "ternary_equals_ifelse": True,
        "occupation_false": "职场人",
        "occupation_true": "学生",
        "summary_lines": [
            "姓名:BlueSky",
            "年龄:25 岁",
            "城市:上海",
            "身份:职场人",
            "爱好:Dart 编程",
        ],
    }
    actual = {
        "ternary_equals_ifelse": ternary_val == ifelse_val,
        "occupation_false": ternary_val,
        "occupation_true": "学生" if True else "职场人",
        "summary_lines": summary_lines,
    }
    return {
        "name": "profile_generator_and_ternary",
        "summary": "验证自我介绍小程序与三元运算符和 if/else 分支的等价性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_style_rules_and_beginner_errors():
    lower_camel = re.compile(r"^[a-z][a-zA-Z0-9]*$")
    upper_camel = re.compile(r"^[A-Z][a-zA-Z0-9]*$")

    style_checks = {
        "var_firstName": bool(lower_camel.match("firstName")),
        "const_maxRetries": bool(lower_camel.match("maxRetries")),
        "class_UserProfile": bool(upper_camel.match("UserProfile")),
        "reject_snake_var": not bool(lower_camel.match("first_name")),
        "reject_shouty_const": not bool(lower_camel.match("MAX_RETRIES")),
    }

    def diagnose(code: str) -> str:
        if "void Main(" in code and "void main(" not in code:
            return "No 'main' method found."
        if re.search(r"print\('[^\n']*\"\)", code):
            return "Unterminated string literal."
        if code.count("(") != code.count(")"):
            return "Expected ')' before this."
        if re.search(r"print\([^)]*\)\s*$", code, re.M):
            return "Expected ';' after this."
        if re.search(r"String\s+(\w+);\s*print\(\1\);", code):
            return "Non-nullable variable must be assigned before it can be used."
        return "OK"

    diagnostics = {
        "missing_semicolon": diagnose("void main() {\n  print('Hello, Dart!')\n}"),
        "unmatched_paren": diagnose("void main() {\n  print('Hello, Dart!'\n}"),
        "mismatched_quote": diagnose("void main() {\n  print('Hello, Dart!\");\n}"),
        "capital_main": diagnose("void Main() {\n  print('Hello, Dart!');\n}"),
        "unassigned_non_null": diagnose("void main() {\n  String name; print(name);\n}"),
    }

    expected = {
        "style_all_pass": True,
        "diagnostics": {
            "missing_semicolon": "Expected ';' after this.",
            "unmatched_paren": "Expected ')' before this.",
            "mismatched_quote": "Unterminated string literal.",
            "capital_main": "No 'main' method found.",
            "unassigned_non_null": "Non-nullable variable must be assigned before it can be used.",
        },
    }
    actual = {
        "style_all_pass": all(style_checks.values()),
        "diagnostics": diagnostics,
    }
    return {
        "name": "style_rules_and_beginner_errors",
        "summary": "校验 Dart 小驼峰/大驼峰代码风格规范及 5 类常见新手编译与空安全错误诊断",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_entry_structure_quotes_and_comments(),
        case_variables_inference_and_interpolation(),
        case_profile_generator_and_ternary(),
        case_style_rules_and_beginner_errors(),
    ]
    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-first-program-lab/explore-first-program.py

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

下载课程关联工程包:Dart

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

下载课程关联工程包:Dart

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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