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

离线校验 Verilog 预处理器宏替换、多模块 timescale 换算与 default_nettype 检查

PYTHONWindows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。explore-compile-instruction.py
explore-compile-instruction.py243 行
"""Offline Verilog semantic verification lab for Chapter 08 (compile-instruction)."""
import json
import re
from pathlib import PurePosixPath

VERSION = "CPython 3.12.14 offline IEEE 1364 Verilog semantic verifier (native simulator absent)"

UNIT_FS = {
    "s": 10**15,
    "ms": 10**12,
    "us": 10**9,
    "ns": 10**6,
    "ps": 10**3,
    "fs": 1,
}


def parse_time_token(tok):
    m = re.fullmatch(r"(1|10|100)(s|ms|us|ns|ps|fs)", tok.strip())
    if not m:
        raise ValueError(f"Invalid timescale token: {tok}")
    return int(m.group(1)) * UNIT_FS[m.group(2)]


def case_define_undef_and_conditional_compile():
    def preprocess(macros_init):
        macros = dict(macros_init)
        # `define DATA_DW 32, `define S $stop;, `define WORD_DEF reg [31:0]
        macros["DATA_DW"] = "32"
        macros["S"] = "$stop;"
        macros["WORD_DEF"] = "reg [31:0]"
        expanded_decl = f"{macros['WORD_DEF']} data_in;"
        expanded_width = f"reg [{macros['DATA_DW']}-1:0] data_in;"
        # `undef DATA_DW
        del macros["DATA_DW"]
        after_undef = "DATA_DW" in macros

        # `ifdef MCU51 ... `elsif WINDOW ... `else ... `endif
        if "MCU51" in macros:
            ifdef_dw = 8
        elif "WINDOW" in macros:
            ifdef_dw = 64
        else:
            ifdef_dw = 32

        # `ifndef WINDOW -> 32 else 64
        ifndef_dw = 32 if "WINDOW" not in macros else 64
        return expanded_decl, expanded_width, after_undef, ifdef_dw, ifndef_dw

    d0 = preprocess({})
    d_mcu = preprocess({"MCU51": "1"})
    d_win = preprocess({"WINDOW": "1"})
    expected = {
        "expanded_decl": "reg [31:0] data_in;",
        "expanded_width": "reg [32-1:0] data_in;",
        "data_dw_present_after_undef": False,
        "ifdef_none": 32,
        "ifdef_mcu51": 8,
        "ifdef_window": 64,
        "ifndef_none": 32,
        "ifndef_window": 64,
    }
    actual = {
        "expanded_decl": d0[0],
        "expanded_width": d0[1],
        "data_dw_present_after_undef": d0[2],
        "ifdef_none": d0[3],
        "ifdef_mcu51": d_mcu[3],
        "ifdef_window": d_win[3],
        "ifndef_none": d0[4],
        "ifndef_window": d_win[4],
    }
    return {
        "name": "define_undef_and_conditional_compile",
        "summary": "验证 `define/`undef 文本宏替换与 `ifdef/`ifndef/`elsif/`else/`endif 条件编译分支",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_include_resolution_model():
    vfs = {
        "/proj/param.v": "`define BUS_W 16\n",
        "/proj/rtl/core/header.v": "localparam DEPTH = 256;\n",
    }
    cur_dir = PurePosixPath("/proj/rtl/core")

    def resolve_include(inc_path):
        p = PurePosixPath(inc_path)
        full = p if p.is_absolute() else PurePosixPath(
            "/" + "/".join(
                part for part in (cur_dir / p).parts
                if part != "/"
            )
        )
        # normalize ..
        stack = []
        for part in full.parts:
            if part == "/":
                continue
            if part == "..":
                stack.pop()
            elif part != ".":
                stack.append(part)
        norm = "/" + "/".join(stack)
        return norm, vfs[norm].strip()

    p1, c1 = resolve_include("../../param.v")
    p2, c2 = resolve_include("header.v")
    expected = {
        "rel_parent_path": "/proj/param.v",
        "rel_parent_content": "`define BUS_W 16",
        "rel_local_path": "/proj/rtl/core/header.v",
        "rel_local_content": "localparam DEPTH = 256;",
    }
    actual = {
        "rel_parent_path": p1,
        "rel_parent_content": c1,
        "rel_local_path": p2,
        "rel_local_content": c2,
    }
    return {
        "name": "include_resolution_model",
        "summary": "验证 `include 相对路径与同目录头文件展开及宏定义跨文件可见性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_timescale_rounding_and_multi_module_precision():
    def validate_timescale(unit_s, prec_s):
        u_fs = parse_time_token(unit_s)
        p_fs = parse_time_token(prec_s)
        return u_fs >= p_fs, u_fs, p_fs

    def scale_delay_fs(delay_val, u_fs, p_fs):
        # IEEE 1364 rounds delay to module's own precision first
        steps = int(delay_val * (u_fs / p_fs) + 0.5)
        return steps * p_fs

    ok_and, u_and, p_and = validate_timescale("1ns", "100ps")
    ok_and_10ps, u_and_10ps, p_and_10ps = validate_timescale("1ns", "10ps")
    ok_bad, _, _ = validate_timescale("100ps", "1ns")
    ok_test, u_test, p_test = validate_timescale("10ns", "1ns")
    ok_or, u_or, p_or = validate_timescale("10ns", "1ns")

    and_delay_100ps_fs = scale_delay_fs(5.207, u_and, p_and)         # 5.2ns = 52 * 100ps
    and_delay_10ps_fs = scale_delay_fs(5.207, u_and_10ps, p_and_10ps) # 5.21ns = 521 * 10ps
    test_d1_fs = scale_delay_fs(1.28, u_test, p_test)                 # 13ns = 13_000_000 fs
    test_d2_fs = scale_delay_fs(3.1, u_test, p_test)                  # 31ns = 31_000_000 fs
    or_delay_fs = scale_delay_fs(5.207, u_or, p_or)                   # 52ns = 52_000_000 fs

    global_prec_fs = min(p_and, p_test, p_or)  # 100ps = 100_000 fs
    expected = {
        "valid_1ns_100ps": True,
        "illegal_100ps_1ns_rejected": True,
        "andfunc_5_207_at_100ps_ns": 5.2,
        "andfunc_5_207_at_10ps_ns": 5.21,
        "test_1_28_ns": 13.0,
        "test_3_1_ns": 31.0,
        "global_precision_ps": 100,
        "test_13ns_in_global_ticks": 130,
        "test_31ns_in_global_ticks": 310,
        "sibling_orfunc_5_207_ns": 52.0,
    }
    actual = {
        "valid_1ns_100ps": ok_and and ok_and_10ps and ok_test and ok_or,
        "illegal_100ps_1ns_rejected": not ok_bad,
        "andfunc_5_207_at_100ps_ns": and_delay_100ps_fs / UNIT_FS["ns"],
        "andfunc_5_207_at_10ps_ns": and_delay_10ps_fs / UNIT_FS["ns"],
        "test_1_28_ns": test_d1_fs / UNIT_FS["ns"],
        "test_3_1_ns": test_d2_fs / UNIT_FS["ns"],
        "global_precision_ps": global_prec_fs // UNIT_FS["ps"],
        "test_13ns_in_global_ticks": test_d1_fs // global_prec_fs,
        "test_31ns_in_global_ticks": test_d2_fs // global_prec_fs,
        "sibling_orfunc_5_207_ns": or_delay_fs / UNIT_FS["ns"],
    }
    return {
        "name": "timescale_rounding_and_multi_module_precision",
        "summary": "验证 `timescale 合法性、单模块舍入、跨模块最小全局精度换算及并行子模块独立性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_default_nettype_resetall_and_cell_directives():
    def check_undeclared_lhs(default_nettype, declared_ports, lhs):
        if lhs in declared_ports:
            return ("ok", "declared")
        if default_nettype == "none":
            return ("error", "undeclared_identifier")
        return ("warning", f"implicit_{default_nettype}")

    r_default = check_undeclared_lhs("wire", {"A", "B", "Z"}, "Z1")
    r_wand = check_undeclared_lhs("wand", {"A", "B", "Z"}, "Z1")
    r_none = check_undeclared_lhs("none", {"A", "B", "Z"}, "Z1")
    # `resetall restores default_nettype -> wire and clears timescale inheritance
    after_resetall_nettype = "wire"
    r_after_reset = check_undeclared_lhs(after_resetall_nettype, {"A", "B", "Z"}, "Z1")

    cell_tagged = True  # `celldefine ... `endcelldefine
    unconnected_states = {"pull1": "1", "pull0": "0", "nounconnected_drive": "z"}
    expected = {
        "default_wire_result": ["warning", "implicit_wire"],
        "wand_result": ["warning", "implicit_wand"],
        "none_result": ["error", "undeclared_identifier"],
        "after_resetall_result": ["warning", "implicit_wire"],
        "celldefine_marked": True,
        "unconnected_drive_map": {"pull1": "1", "pull0": "0", "nounconnected_drive": "z"},
    }
    actual = {
        "default_wire_result": list(r_default),
        "wand_result": list(r_wand),
        "none_result": list(r_none),
        "after_resetall_result": list(r_after_reset),
        "celldefine_marked": cell_tagged,
        "unconnected_drive_map": unconnected_states,
    }
    return {
        "name": "default_nettype_resetall_and_cell_directives",
        "summary": "校验 `default_nettype (wire/wand/none)、`resetall 复位、`celldefine 及 `unconnected_drive 语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_define_undef_and_conditional_compile(),
        case_include_resolution_model(),
        case_timescale_rounding_and_multi_module_precision(),
        case_default_nettype_resetall_and_cell_directives(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。

入口文件:projects/verilog-compile-instruction-lab/explore-compile-instruction.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-compile-instruction.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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