"""Offline Verilog RTL verification lab for Chapter 27 (testbench)."""
import json
VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"
def sim_data_consolidation(din_stream):
"""Cycle-accurate model of data_consolidation (2-bit -> 8-bit packer) and self-check."""
state_cnt = 0
data_r = 0
dout_en_r = 0
ref_shift = 0
outputs = []
err_cnt = 0
for din_en, din in din_stream:
# Next-state computation (non-blocking)
if din_en:
next_cnt = (state_cnt + 1) & 0x3
next_data = ((data_r << 2) | (din & 0x3)) & 0xFF
next_dout_en = 1 if state_cnt == 3 else 0
ref_shift = ((ref_shift << 2) | (din & 0x3)) & 0xFF
else:
next_cnt = 0
next_data = data_r
next_dout_en = 0
state_cnt, data_r, dout_en_r = next_cnt, next_data, next_dout_en
if dout_en_r:
outputs.append(data_r)
if data_r != ref_shift:
err_cnt += 1
return outputs, err_cnt
def case_data_consolidation_self_check():
"""Verify 2-bit to 8-bit shift packing and testbench err_cnt == 0 self-checking."""
# Pack [3, 1, 2, 0] -> 11_01_10_00 = 0xD8, and [2, 2, 1, 3] -> 10_10_01_11 = 0xA7
stream = [(1, v) for v in (3, 1, 2, 0, 2, 2, 1, 3)] + [(0, 0)]
outputs, err_cnt = sim_data_consolidation(stream)
expected = {"packed_hex": ["0xd8", "0xa7"], "err_cnt": 0}
actual = {"packed_hex": [f"0x{x:02x}" for x in outputs], "err_cnt": err_cnt}
return {
"name": "data_consolidation_self_check",
"summary": "仿真 2-bit 拼 8-bit 模块 data_consolidation 并验证自校验计数 err_cnt=0",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fread_ascii_vs_readmemh_parsing():
"""Verify $fread 16-bit ASCII+'\\n' extraction read_temp[9:8] matches $readmemh hex lines."""
lines = ["3\n", "1\n", "2\n", "0\n"]
# $fread reads 2 bytes big-endian into 16-bit reg: '3' (0x33) in [15:8], '\n' (0x0A) in [7:0]
fread_vals = []
for line in lines:
raw = line.encode("ascii")
read_temp = (raw[0] << 8) | raw[1]
fread_vals.append((read_temp >> 8) & 0x3) # read_temp[9:8]
readmemh_vals = [int(line.strip(), 16) & 0x3 for line in lines]
first_word_hex = f"0x{((ord('3') << 8) | ord('\n')):04x}"
expected = {
"first_ascii_word": "0x330a",
"fread_extracted": [3, 1, 2, 0],
"readmemh_loaded": [3, 1, 2, 0],
"match": True,
}
actual = {
"first_ascii_word": first_word_hex,
"fread_extracted": fread_vals,
"readmemh_loaded": readmemh_vals,
"match": fread_vals == readmemh_vals,
}
return {
"name": "fread_ascii_vs_readmemh_parsing",
"summary": "校验 $fread 二进制读取 ASCII 字符 0x330a 截取 [9:8] 与 $readmemh 按行加载结果一致",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_clock_real_vs_integer_parameter_period():
"""Verify why real CYCLE=5.0 gives 2.5ns half-period while integer truncation shifts 200MHz clock."""
real_half = 5.0 / 2.0
int_half = 5 // 2
expected = {
"real_half_ns": 2.5,
"real_period_ns": 5.0,
"int_truncated_period_ns": 4,
"needs_finer_timeprecision": True,
}
actual = {
"real_half_ns": real_half,
"real_period_ns": real_half * 2,
"int_truncated_period_ns": int_half * 2,
"needs_finer_timeprecision": True,
}
return {
"name": "clock_real_vs_integer_parameter_period",
"summary": "验证浮点时钟周期用 real 声明与高精度 timescale 的必要性(避免整型截断成 4ns)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fopen_file_modes_audit():
"""Verify all 12 Verilog $fopen file access modes (text/binary x r/w/a/r+/w+/a+)."""
modes = ["r", "w", "a", "rb", "wb", "ab", "r+", "w+", "a+", "rb+", "wb+", "ab+"]
binary_modes = [m for m in modes if "b" in m]
rw_modes = [m for m in modes if "+" in m]
expected = {"total_modes": 12, "binary_count": 6, "read_write_count": 6}
actual = {
"total_modes": len(modes),
"binary_count": len(binary_modes),
"read_write_count": len(rw_modes),
}
return {
"name": "fopen_file_modes_audit",
"summary": "核对 $fopen 全部 12 种文本与二进制文件打开模式(只读/只写/追加/读写)分类属性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_data_consolidation_self_check(),
case_fread_ascii_vs_readmemh_parsing(),
case_clock_real_vs_integer_parameter_period(),
case_fopen_file_modes_audit(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。
入口文件:projects/verilog-testbench-lab/explore-testbench.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-testbench.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a2580.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2612.zip