"""Offline Ruby 3.x semantic verification lab for Chapter 06 (encoding)."""
import json
import re
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
MAGIC_RE = re.compile(r"coding\s*[:=]\s*([A-Za-z0-9_-]+)", re.IGNORECASE)
def detect_ruby_source_encoding(raw_bytes: bytes, ruby_major: int = 3) -> str:
lines = raw_bytes.splitlines()[:2]
check_lines = lines[:2] if (lines and lines[0].startswith(b"#!")) else lines[:1]
for ln in check_lines:
if ln.lstrip().startswith(b"#"):
m = MAGIC_RE.search(ln.decode("ascii", errors="ignore"))
if m:
return m.group(1).upper()
return "UTF-8" if ruby_major >= 2 else "US-ASCII"
def case_us_ascii_multibyte_syntax_error_legacy():
src = '#!/usr/bin/ruby -w\n\nputs "你好,世界!";\n'.encode("utf-8")
enc_19 = detect_ruby_source_encoding(src, ruby_major=1)
try:
src.decode("ascii")
err = None
except UnicodeDecodeError:
err = "invalid multibyte char (US-ASCII)"
expected = {"ruby19_default": "US-ASCII", "error": "invalid multibyte char (US-ASCII)"}
actual = {"ruby19_default": enc_19, "error": err}
return {
"name": "us_ascii_multibyte_syntax_error_legacy",
"summary": "复现 Ruby 1.9 默认 US-ASCII 源码编码下读取 UTF-8 中文字符触发 invalid multibyte char 报错的机理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_magic_encoding_comment_parser():
samples = [
b"#!/usr/bin/ruby -w\n# -*- coding: UTF-8 -*-\nputs 'hi'\n",
b"# coding=utf-8\nputs 'hi'\n",
b"# encoding: UTF-8\nputs 'hi'\n",
]
detected = [detect_ruby_source_encoding(s, ruby_major=1) for s in samples]
expected = {"detected": ["UTF-8", "UTF-8", "UTF-8"]}
actual = {"detected": detected}
return {
"name": "magic_encoding_comment_parser",
"summary": "解析 Emacs 风格与简写编码魔术注释(允许紧跟 shebang 位于第 2 行)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_utf8_default_and_frozen_string_literal():
src = '#!/usr/bin/ruby -w\n# frozen_string_literal: true\nputs "你好,世界!"\n'.encode("utf-8")
enc_3 = detect_ruby_source_encoding(src, ruby_major=3)
frozen = b"frozen_string_literal: true" in src
expected = {"ruby3_default": "UTF-8", "frozen_enabled": True, "decoded_text": "你好,世界!"}
actual = {
"ruby3_default": enc_3,
"frozen_enabled": frozen,
"decoded_text": src.decode("utf-8").split('"')[1],
}
return {
"name": "utf8_default_and_frozen_string_literal",
"summary": "验证 Ruby 2.0+/3.x 默认 UTF-8 源码编码及 frozen_string_literal 魔术注释共存",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_encoding_consistency_check():
text = "你好,世界!"
utf8_bytes = text.encode("utf-8")
gbk_bytes = text.encode("gbk")
utf8_ok = utf8_bytes.decode("utf-8") == text
try:
gbk_bytes.decode("utf-8")
mismatch_error = False
except UnicodeDecodeError:
mismatch_error = True
expected = {"utf8_roundtrip_ok": True, "gbk_under_utf8_fails": True, "utf8_byte_len": 18}
actual = {"utf8_roundtrip_ok": utf8_ok, "gbk_under_utf8_fails": mismatch_error, "utf8_byte_len": len(utf8_bytes)}
return {
"name": "file_encoding_consistency_check",
"summary": "校验文件声明编码与编辑器实际保存编码一致的重要性(GBK 字节按 UTF-8 解析将解码失败)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_us_ascii_multibyte_syntax_error_legacy(),
case_magic_encoding_comment_parser(),
case_utf8_default_and_frozen_string_literal(),
case_file_encoding_consistency_check(),
]
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-encoding-lab/explore-encoding.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-encoding.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2449.zip