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

离线校验 Verilog 四值逻辑上下拉、定宽/不定宽进制解析、负数补码与 ASCII 打包

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

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


def parse_verilog_int(literal):
    s = literal.strip()
    neg = False
    if s.startswith("-"):
        neg = True
        s = s[1:].strip()
    if "'" not in s:
        if not re.fullmatch(r"[0-9][0-9_]*", s):
            raise ValueError(f"Illegal integer literal: {literal}")
        val = int(s.replace("_", ""), 10)
        width = 32
    else:
        size_part, rest = s.split("'", 1)
        if not rest or rest[0] not in "bBdDhHoO":
            raise ValueError(f"Illegal radix in literal: {literal}")
        radix_ch = rest[0].lower()
        digits = rest[1:].replace("_", "")
        if not digits or digits.startswith("-"):
            raise ValueError(f"Illegal sign placement or empty digits: {literal}")
        base = {"b": 2, "o": 8, "d": 10, "h": 16}[radix_ch]
        val = int(digits, base)
        width = int(size_part) if size_part else 32
    mask = (1 << width) - 1
    bits_val = ((-val) & mask) if neg else (val & mask)
    return width, bits_val, format(bits_val, f"0{width}b")


def case_four_value_logic_and_pull_resolution():
    raw_states = ["0", "1", "x", "X", "z", "Z"]
    normalized = sorted({s.lower() for s in raw_states})

    def resolve_pad(driver, pull):
        if driver in ("0", "1", "x"):
            return driver
        # driver == 'z' (high impedance)
        return {"pullup": "1", "pulldown": "0", "none": "z"}[pull]

    expected = {
        "four_states": ["0", "1", "x", "z"],
        "z_pullup": "1",
        "z_pulldown": "0",
        "z_floating": "z",
        "driven_0_overrides_pullup": "0",
    }
    actual = {
        "four_states": normalized,
        "z_pullup": resolve_pad("z", "pullup"),
        "z_pulldown": resolve_pad("z", "pulldown"),
        "z_floating": resolve_pad("z", "none"),
        "driven_0_overrides_pullup": resolve_pad("0", "pullup"),
    }
    return {
        "name": "four_value_logic_and_pull_resolution",
        "summary": "校验四值逻辑 0/1/x/z 大小写归一化以及高阻态 z 在上拉、下拉与强驱动下的引脚电平解析",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sized_unsized_radix_literal_parser():
    w1, v1, b1 = parse_verilog_int("4'b1011")
    w2, v2, _ = parse_verilog_int("32'h3022_c0de")
    _, v_d100, _ = parse_verilog_int("'d100")
    _, v_100, _ = parse_verilog_int("100")
    _, v_h64, _ = parse_verilog_int("32'h64")
    _, v_oct, _ = parse_verilog_int("8'o377")
    expected = {
        "4b1011": [4, 11, "1011"],
        "32h3022_c0de_hex": "0x3022c0de",
        "100_forms_equal": True,
        "8o377_dec": 255,
    }
    actual = {
        "4b1011": [w1, v1, b1],
        "32h3022_c0de_hex": hex(v2),
        "100_forms_equal": (v_d100 == v_100 == v_h64 == 100),
        "8o377_dec": v_oct,
    }
    return {
        "name": "sized_unsized_radix_literal_parser",
        "summary": "解析指明位宽与未指明位宽的二/八/十/十六进制整数常数及下划线分隔符等价性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_negative_twos_complement_and_syntax_guard():
    _, _, neg15_5b = parse_verilog_int("-5'd15")
    _, _, neg15_6b = parse_verilog_int("-6'd15")
    illegal_caught = False
    try:
        parse_verilog_int("4'd-2")
    except ValueError:
        illegal_caught = True
    expected = {
        "neg15_5bit": "10001",
        "neg15_6bit": "110001",
        "illegal_4d_minus_2_rejected": True,
    }
    actual = {
        "neg15_5bit": neg15_5b,
        "neg15_6bit": neg15_6b,
        "illegal_4d_minus_2_rejected": illegal_caught,
    }
    return {
        "name": "negative_twos_complement_and_syntax_guard",
        "summary": "验证负数二进制补码表示(-15 的 5bit/6bit 编码)并拦截非法写法 4'd-2",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_real_scientific_and_ascii_string_packing():
    dec_reals = [float(x) for x in ("30.123", "6.0", "3.0", "0.001")]
    sci_reals = [float(x.replace("_", "")) for x in ("1.2e4", "1_0001e4", "1E-3")]

    def pack_ascii(text, width_bytes):
        raw = text.encode("ascii")
        if len(raw) < width_bytes:
            raw = b"\x00" * (width_bytes - len(raw)) + raw
        elif len(raw) > width_bytes:
            raw = raw[-width_bytes:]
        return raw

    sample = "docs.mbsky.com"  # 14 ASCII chars -> 14 * 8 = 112 bits
    exact_packed = pack_ascii(sample, 14)
    padded_packed = pack_ascii("HDL", 5)
    trunc_packed = pack_ascii("Verilog", 4)
    expected = {
        "dec_reals": [30.123, 6.0, 3.0, 0.001],
        "sci_reals": [12000.0, 100010000.0, 0.001],
        "sample_bit_width": 112,
        "padded_hex": "000048444c",
        "truncated_ascii": "ilog",
    }
    actual = {
        "dec_reals": dec_reals,
        "sci_reals": sci_reals,
        "sample_bit_width": len(exact_packed) * 8,
        "padded_hex": padded_packed.hex(),
        "truncated_ascii": trunc_packed.decode("ascii"),
    }
    return {
        "name": "real_scientific_and_ascii_string_packing",
        "summary": "校验十进制与科学计数法实数解析及单字节 ASCII 字符串的寄存器打包、左补零与左截断规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_four_value_logic_and_pull_resolution(),
        case_sized_unsized_radix_literal_parser(),
        case_negative_twos_complement_and_syntax_guard(),
        case_real_scientific_and_ascii_string_packing(),
    ]
    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-number-lab/explore-number.py

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

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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