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

离线校验任务与函数对比、3ns 延时异或任务、时钟生成对比与 automatic 隔离

PYTHONWindows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。explore-task.py
explore-task.py164 行
"""Offline Verilog RTL verification lab for Chapter 23 (task)."""
import json

VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"


def case_task_vs_function_rules():
    """Verify the 7 comparison dimensions between Verilog function and task."""
    matrix = {
        "输入": {"function_min_inputs": 1, "function_inout": False, "task_min_inputs": 0, "task_inout": True},
        "输出": {"function_outputs": 0, "task_outputs": "0_or_more"},
        "返回值": {"function_returns": 1, "task_returns": 0},
        "仿真时刻": {"function_zero_time": True, "task_nonzero_time": True},
        "时序逻辑": {"function_timing_ctrl": False, "task_delay_event": True, "task_always": False},
        "调用": {"function_calls_task": False, "task_calls_both": True},
        "书写规范": {"function_standalone_stmt": False, "task_standalone_stmt": True},
    }
    expected = {
        "dimensions_checked": 7,
        "task_allows_timing_not_always": True,
        "function_rhs_only": True,
    }
    actual = {
        "dimensions_checked": len(matrix),
        "task_allows_timing_not_always": matrix["时序逻辑"]["task_delay_event"] and not matrix["时序逻辑"]["task_always"],
        "function_rhs_only": not matrix["书写规范"]["function_standalone_stmt"],
    }
    return {
        "name": "task_vs_function_rules",
        "summary": "校验 Verilog 函数与任务在输入/输出/返回值/仿真时刻/时序逻辑/调用/书写规范 7 项对比规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_delayed_xor_task_pipeline():
    """Simulate xor_oper with 3ns delayed task xor_oper_iner and clock-registered output."""
    stimuli = [
        (0b1111, 0b1001),
        (0b0110, 0b1001),
        (0b1000, 0b1001),
    ]
    events = []
    t = 13  # first posedge clk after rstn=1 at #8 (clk toggles every 5ns -> posedge at 13,23,33,43)
    co_t = 0
    co_r = 0
    for a, b in stimuli:
        # At posedge clk, co_r latches previous co_t; sig_input updates a,b -> co_t updates at t+3ns
        co_r = co_t
        co_t = a ^ b
        events.append({"t_ns": t, "a": f"{a:04b}", "b": f"{b:04b}", "co_t_at_t_plus_3ns": f"{co_t:04b}", "co_r": f"{co_r:04b}"})
        t += 10
    # Final cycle latch
    co_r_final = co_t
    expected = {
        "xor_outputs": ["0110", "1111", "0001"],
        "delay_ns": 3,
        "final_latched_co": "0001",
    }
    actual = {
        "xor_outputs": [e["co_t_at_t_plus_3ns"] for e in events],
        "delay_ns": 3,
        "final_latched_co": f"{co_r_final:04b}",
    }
    return {
        "name": "delayed_xor_task_pipeline",
        "summary": "仿真带 #3 时延的 xor_oper_iner 任务与时钟寄存缓存输出 co_r 的流水行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_task_output_port_vs_global_clk():
    """Demonstrate why task output-port copy-out cannot toggle a clock while global reg access can."""
    # Way 1: output argument only copies out final value when task returns at #10
    clk_test1_samples = []
    for _ in range(3):
        internal = 0
        # t + 5ns: internal = 0 (not visible externally)
        clk_test1_samples.append(1 if clk_test1_samples else "x")
        internal = 1
        # t + 10ns: task ends, copy out internal -> clk_test1
        clk_test1_samples.append(internal)
    # Way 2: global module reg updated directly at #5 and #10
    clk_test2_samples = []
    for _ in range(3):
        clk_test2_samples.append(0)
        clk_test2_samples.append(1)
    expected = {
        "way1_toggles": False,
        "way1_steady_val": 1,
        "way2_sequence": [0, 1, 0, 1, 0, 1],
    }
    actual = {
        "way1_toggles": len(set(clk_test1_samples[1:])) > 1,
        "way1_steady_val": clk_test1_samples[-1],
        "way2_sequence": clk_test2_samples,
    }
    return {
        "name": "task_output_port_vs_global_clk",
        "summary": "验证任务 output 端口仅在任务结束时回写(无法产生时钟)与操作模块内全局寄存器产生时钟的差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_static_vs_automatic_concurrent_task():
    """Simulate concurrent task calls: static shared cnto clobbering vs automatic independent frames."""
    # Static task: shared cnto register persists across calls
    static_shared_cnto = "x"
    static_trace = []
    auto_trace = []
    for en_cnt, cnt_temp in [(1, 0), (1, 1), (0, 2), (0, 3)]:
        # Static call 1: test_flag(2, en_cnt, cnt1)
        if en_cnt:
            static_shared_cnto = 2
        c1_s = static_shared_cnto
        # Static call 2: test_flag(cnt_temp, !en_cnt, cnt2)
        if not en_cnt:
            static_shared_cnto = cnt_temp
        c2_s = static_shared_cnto
        static_trace.append((c1_s, c2_s))

        # Automatic calls: each call gets fresh uninitialized local cnto='x'
        c1_a = 2 if en_cnt else "x"
        c2_a = cnt_temp if (not en_cnt) else "x"
        auto_trace.append((c1_a, c2_a))

    expected = {
        "static_cross_talk": [(2, 2), (2, 2), (2, 2), (3, 3)],
        "automatic_isolated": [(2, "x"), (2, "x"), ("x", 2), ("x", 3)],
    }
    # Note on static step 3: when en_cnt=0, call1 reads previous static_shared_cnto (2), then call2 writes cnt_temp=2;
    # at step 4, call1 reads 2 (from step 3) and call2 writes 3 -> let's trace exact order!
    expected["static_cross_talk"] = [(2, 2), (2, 2), (2, 2), (2, 3)]
    actual = {
        "static_cross_talk": static_trace,
        "automatic_isolated": auto_trace,
    }
    return {
        "name": "static_vs_automatic_concurrent_task",
        "summary": "对比静态 task 并发调用共享存储导致的信号串扰与 task automatic 动态隔离效果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_task_vs_function_rules(),
        case_delayed_xor_task_pipeline(),
        case_task_output_port_vs_global_clk(),
        case_static_vs_automatic_concurrent_task(),
    ]
    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-task-lab/explore-task.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-task.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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