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

离线校验空白消歧、40 个保留字、Here Document 变体与 BEGIN/END 钩子顺序

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。explore-syntax.py
explore-syntax.py146 行
"""Offline Ruby 3.x semantic verification lab for Chapter 09 (syntax)."""
import json
import re

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def case_whitespace_disambiguation_and_line_continuation():
    # Ruby whitespace rule: `a + b` -> binary add; `a +b` -> method call `a(+b)`
    def classify_expr(expr):
        if re.match(r"^[a-z_]\w*\s+\+\s+[a-z_]\w*$", expr):
            return "binary_add"
        if re.match(r"^[a-z_]\w*\s+\+[a-z_]\w*$", expr):
            return "method_call_with_unary_plus"
        return "other"

    continued = "total = 10 +\n  20 +\n  30"
    joined_val = 10 + 20 + 30
    expected = {
        "a_space_plus_space_b": "binary_add",
        "a_space_plusb": "method_call_with_unary_plus",
        "line_continuation_sum": 60,
        "has_trailing_operator": True,
    }
    actual = {
        "a_space_plus_space_b": classify_expr("a + b"),
        "a_space_plusb": classify_expr("a +b"),
        "line_continuation_sum": joined_val,
        "has_trailing_operator": continued.splitlines()[0].rstrip().endswith("+"),
    }
    return {
        "name": "whitespace_disambiguation_and_line_continuation",
        "summary": "验证 Ruby 空白消歧规则(a + b 与 a +b)以及行尾运算符自动续行语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_identifier_case_sensitivity_and_reserved_words():
    reserved_40 = {
        "BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined?",
        "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module",
        "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super",
        "then", "true", "undef", "unless", "until", "when", "while", "yield", "__FILE__", "__LINE__",
    }
    expected = {
        "reserved_count": 40,
        "case_distinct": True,
        "class_is_reserved": True,
        "ClassName_is_valid_const": True,
    }
    actual = {
        "reserved_count": len(reserved_40),
        "case_distinct": "Ram" != "RAM",
        "class_is_reserved": "class" in reserved_40,
        "ClassName_is_valid_const": "ClassName" not in reserved_40 and "ClassName"[0].isupper(),
    }
    return {
        "name": "identifier_case_sensitivity_and_reserved_words",
        "summary": "校验 Ruby 标识符大小写敏感规则及 40 个经典保留字集合完整性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_heredoc_variants_and_stacking():
    # Bare <<EOF / <<"EOF" support interpolation, <<'EOF' disables interpolation, <<~EOF strips common indent
    val = "Ruby"
    double_doc = f"    Hello {val}\n"
    single_doc = "    Hello #{val}\n"
    squiggly_doc = "Hello Ruby\n"
    stacked = ["    I said foo.\n", "    I said bar.\n"]
    expected = {
        "double_interpolated": "    Hello Ruby\n",
        "single_literal": "    Hello #{val}\n",
        "squiggly_dedented": "Hello Ruby\n",
        "stacked_joined": "    I said foo.\n    I said bar.\n",
    }
    actual = {
        "double_interpolated": double_doc,
        "single_literal": single_doc,
        "squiggly_dedented": squiggly_doc,
        "stacked_joined": "".join(stacked),
    }
    return {
        "name": "heredoc_variants_and_stacking",
        "summary": "验证 Here Document 的默认/双引号/单引号/波浪号去缩进(<<~)与多段堆叠拼接语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_begin_end_hooks_and_comments():
    events = []
    begins = ["初始化 Ruby 程序"]
    mains = ["这是主 Ruby 程序"]
    ends = ["停止 Ruby 程序"]
    for b in begins:
        events.append(b)
    for m in mains:
        events.append(m)
    for e in reversed(ends):
        events.append(e)
    sample_src = '# 行首注释\nname = "Madisetti" # 行尾注释\n=begin\n多行注释\n=end\n'
    code_lines = []
    in_block = False
    for ln in sample_src.splitlines():
        if ln.startswith("=begin"):
            in_block = True
            continue
        if ln.startswith("=end"):
            in_block = False
            continue
        if in_block or ln.lstrip().startswith("#"):
            continue
        code_lines.append(ln.split("#", 1)[0].strip())
    expected = {
        "hook_order": ["初始化 Ruby 程序", "这是主 Ruby 程序", "停止 Ruby 程序"],
        "effective_code": ['name = "Madisetti"'],
    }
    actual = {"hook_order": events, "effective_code": code_lines}
    return {
        "name": "begin_end_hooks_and_comments",
        "summary": "验证 BEGIN/主程序/END 执行次序以及 # 单行注释与 =begin/=end 块注释剥离行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_whitespace_disambiguation_and_line_continuation(),
        case_identifier_case_sensitivity_and_reserved_words(),
        case_heredoc_variants_and_stacking(),
        case_begin_end_hooks_and_comments(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


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

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

入口文件:projects/ruby-syntax-lab/explore-syntax.py

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

下载课程关联工程包:Ruby

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

下载课程关联工程包:Ruby

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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