"""Offline Ruby 3.x semantic verification lab for Chapter 15 (comment)."""
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def strip_ruby_comments(source: str):
lines = []
in_embedded = False
for raw in source.splitlines():
if not in_embedded and raw.startswith("=begin") and (len(raw) == 6 or raw[6].isspace()):
in_embedded = True
continue
if in_embedded:
if raw.startswith("=end") and (len(raw) == 4 or raw[4].isspace()):
in_embedded = False
continue
# Preserve shebang / magic comment separately in another case; here strip # outside quotes
in_str = None
buf = []
i = 0
while i < len(raw):
ch = raw[i]
if in_str:
buf.append(ch)
if ch == "\\" and i + 1 < len(raw):
i += 1
buf.append(raw[i])
elif ch == in_str:
in_str = None
else:
if ch in ("'", '"'):
in_str = ch
buf.append(ch)
elif ch == "#":
break
else:
buf.append(ch)
i += 1
cleaned = "".join(buf).strip()
if cleaned:
lines.append(cleaned)
return lines
def case_single_line_hash_comment_stripping():
src = '#!/usr/bin/ruby -w\n\n# 这是一个单行注释。\n\nputs "Hello, Ruby!"\nputs "not # a comment"\n'
cleaned = strip_ruby_comments(src)
expected = ['puts "Hello, Ruby!"', 'puts "not # a comment"']
return {
"name": "single_line_hash_comment_stripping",
"summary": "验证 # 单行注释从 # 到行尾全部忽略,同时保留字符串字面量内部的 # 字符",
"expected": expected,
"actual": cleaned,
"passed": cleaned == expected,
}
def case_embedded_begin_end_block_comment_rules():
valid_src = 'puts "Hello, Ruby!"\n=begin\n多行注释内容\n=end\nputs "After"\n'
# Indented ` =begin` is NOT a valid embedded doc comment in Ruby (must start at column 0)
indented_line = " =begin"
valid_col0 = valid_src.splitlines()[1].startswith("=begin")
indented_is_col0 = indented_line.startswith("=begin")
expected = {
"effective_lines": ['puts "Hello, Ruby!"', 'puts "After"'],
"col0_required": True,
"indented_rejected": True,
}
actual = {
"effective_lines": strip_ruby_comments(valid_src),
"col0_required": valid_col0,
"indented_rejected": not indented_is_col0,
}
return {
"name": "embedded_begin_end_block_comment_rules",
"summary": "验证 =begin/=end 块注释必须顶格(第 0 列)书写且不可缩进的词法规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_trailing_comment_alignment_style():
lines = [
"@counter # 跟踪页面被点击的次数",
"@siteCounter # 跟踪所有页面被点击的次数",
]
cols = [ln.index("#") for ln in lines]
gaps = [ln.index("#") - len(ln[: ln.index("#")].rstrip()) for ln in lines]
expected = {"aligned": True, "comment_col": 14, "min_gap_at_least_2": True}
actual = {"aligned": len(set(cols)) == 1, "comment_col": cols[0], "min_gap_at_least_2": min(gaps) >= 2}
return {
"name": "trailing_comment_alignment_style",
"summary": "校验多条行尾注释的列对齐与代码间距规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_shebang_and_magic_comment_preservation():
header = ["#!/usr/bin/ruby -w", "# -*- coding: UTF-8 -*-", "# frozen_string_literal: true"]
expected = {
"has_shebang": True,
"has_encoding_directive": True,
"has_frozen_directive": True,
}
actual = {
"has_shebang": header[0].startswith("#!"),
"has_encoding_directive": "coding:" in header[1],
"has_frozen_directive": "frozen_string_literal:" in header[2],
}
return {
"name": "shebang_and_magic_comment_preservation",
"summary": "区分普通 # 注释与具有解释器语义的 shebang 及魔术注释",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_single_line_hash_comment_stripping(),
case_embedded_begin_end_block_comment_rules(),
case_trailing_comment_alignment_style(),
case_shebang_and_magic_comment_preservation(),
]
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-comment-lab/explore-comment.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-comment.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2443.zip