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

离线校验 Verilog 操作符优先级、四值算术/比较/按位真值表、移位与拼接复制

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

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


def bit_and(a, b):
    if a == "0" or b == "0":
        return "0"
    if a == "1" and b == "1":
        return "1"
    return "x"


def bit_or(a, b):
    if a == "1" or b == "1":
        return "1"
    if a == "0" and b == "0":
        return "0"
    return "x"


def bit_xor(a, b):
    if a in ("0", "1") and b in ("0", "1"):
        return "1" if a != b else "0"
    return "x"


def bit_xnor(a, b):
    r = bit_xor(a, b)
    return "x" if r == "x" else ("1" if r == "0" else "0")


def bit_not(a):
    return {"0": "1", "1": "0"}.get(a, "x")


def vec_op(va, vb, fn):
    w = max(len(va), len(vb))
    pa = va.rjust(w, "0")
    pb = vb.rjust(w, "0")
    return "".join(fn(x, y) for x, y in zip(pa, pb))


def case_precedence_associativity_and_operands():
    # Procedural LHS check: reg legal, wire illegal inside always @*
    def can_assign_in_always(var_type):
        return var_type in ("reg", "integer", "real", "time")

    # Left-associative arithmetic vs right-associative ternary
    A, B, C, D, F = 0, 1, 1, 2, 3
    arith_eq = (10 + 5 - 3) == ((10 + 5) - 3)
    # Right-associative: A ? B : (C ? D : F) -> A=0 => C?D:F => D=2
    ternary_right = B if A else (D if C else F)
    # Left-grouped: (A ? B : C) ? D : F -> (0?1:1)=1 => D=2; test with A=1, B=0, C=1, D=2, F=3
    A2, B2, C2, D2, F2 = 1, 0, 1, 2, 3
    right_val = B2 if A2 else (D2 if C2 else F2)     # 0
    left_val = D2 if (B2 if A2 else C2) else F2      # (1?0:1)=0 => F2=3

    precedence_levels = [
        "unary(+ - ! ~)", "mul_div_mod(* / %)", "add_sub(+ -)", "shift(<< >> <<< >>>)",
        "relational(< <= > >=)", "equality(== != === !==)",
        "bitwise_and(& ~&)", "bitwise_xor(^ ~^)", "bitwise_or(| ~|)",
        "logical_and(&&)", "logical_or(||)", "conditional(?:)",
    ]
    expected = {
        "reg_legal_in_always": True,
        "wire_illegal_in_always": True,
        "arith_left_assoc": True,
        "ternary_right_val": 0,
        "ternary_left_grouped_val": 3,
        "precedence_level_count": 12,
        "ternary_lowest": True,
    }
    actual = {
        "reg_legal_in_always": can_assign_in_always("reg"),
        "wire_illegal_in_always": not can_assign_in_always("wire"),
        "arith_left_assoc": arith_eq and ternary_right == 2,
        "ternary_right_val": right_val,
        "ternary_left_grouped_val": left_val,
        "precedence_level_count": len(precedence_levels),
        "ternary_lowest": precedence_levels[-1] == "conditional(?:)",
    }
    return {
        "name": "precedence_associativity_and_operands",
        "summary": "校验操作数合法性(wire 不可在 always 中赋值)、12 级优先级顺序及条件运算符右结合性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_arithmetic_x_propagation_and_width():
    def arith_add(va, vb, width):
        if any(c in "xz" for c in va + vb):
            return "x" * width
        val = (int(va, 2) + int(vb, 2)) & ((1 << width) - 1)
        return format(val, f"0{width}b")

    a, b = "0010", "1001"  # 2, 9
    c_add = arith_add(a, b, 5)       # 5'b01011 = 11
    c_div = int(b, 2) // int(a, 2)   # 4
    c_x = arith_add(a, "100x", 5)    # 5'bxxxxx

    # Unsigned multiply width: 4-bit (0xE=14) * 2-bit (0x3=3) = 42 = 6'h2a
    mul_res = 0xE * 0x3
    # Signed negative width: -4'd4 in 6-bit context -> -4 * 2 = -8 -> 6'b111000 = 6'h38
    signed_mul_6b = ((-4) * 2) & 0x3F
    # Unsized negative literal (-'d4) in 32-bit unsigned context -> (2**32 - 4)
    unsized_neg4 = (-4) & 0xFFFFFFFF
    expected = {
        "add_5b": "01011",
        "div_int": 4,
        "x_propagates_all_bits": "xxxxx",
        "mul_6b_hex": "0x2a",
        "signed_neg4_times_2_6b_hex": "0x38",
        "unsized_neg4_u32_hex": "0xfffffffc",
    }
    actual = {
        "add_5b": c_add,
        "div_int": c_div,
        "x_propagates_all_bits": c_x,
        "mul_6b_hex": hex(mul_res),
        "signed_neg4_times_2_6b_hex": hex(signed_mul_6b),
        "unsized_neg4_u32_hex": hex(unsized_neg4),
    }
    return {
        "name": "arithmetic_x_propagation_and_width",
        "summary": "验证算术运算位宽扩展、整数除法截断、x 全位污染及有符号/未定宽负数补码陷阱",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_relational_equality_logical_and_bitwise_tables():
    def rel_cmp(va, vb, op):
        if any(c in "xz" for c in va + vb):
            return "x"
        ia, ib = int(va, 2), int(vb, 2)
        res = {"gt": ia > ib, "le": ia <= ib, "ge": ia >= ib}[op]
        return "1" if res else "0"

    def eq_logical(va, vb):
        if any(c in "xz" for c in va + vb):
            return "x"
        return "1" if int(va, 2) == int(vb, 2) else "0"

    def eq_case(va, vb):
        w = max(len(va), len(vb))
        return "1" if va.rjust(w, "0") == vb.rjust(w, "0") else "0"

    def to_bool4(v):
        if "1" in v:
            return "1"
        if any(c in "xz" for c in v):
            return "x"
        return "0"

    def log_and(va, vb):
        return bit_and(to_bool4(va), to_bool4(vb))

    def log_or(va, vb):
        return bit_or(to_bool4(va), to_bool4(vb))

    def log_not(va):
        return bit_not(to_bool4(va))

    # Verify full 3x3 bitwise tables for &, |, ^, ~^
    vals = ("0", "1", "x")
    tbl_and = [[bit_and(r, c) for c in vals] for r in vals]
    tbl_or = [[bit_or(r, c) for c in vals] for r in vals]
    tbl_xor = [[bit_xor(r, c) for c in vals] for r in vals]
    tbl_xnor = [[bit_xnor(r, c) for c in vals] for r in vals]

    A_bw, B_bw, C_bw = "0101", "1001", "x010"
    expected = {
        "rel_4_gt_3": "1",
        "rel_4_le_3": "0",
        "rel_with_x": "x",
        "eq_4_vs_8h04": "1",
        "eq_4_vs_xxxx": "x",
        "case_eq_4_vs_xxxx": "0",
        "case_eq_xxxx_vs_4hx": "1",
        "log_3_and_1x": "1",  # Note: IEEE 1364: 2'b1x has a '1' bit so nonzero -> true! Wait: check 2'b0x too
        "log_3_and_0x": "x",
        "log_3_or_0x": "1",
        "log_not_0": "1",
        "bw_not_A": "1010",
        "bw_B_or_C": "1011",
        "bw_B_and_C": "x000",
        "tbl_and": [["0", "0", "0"], ["0", "1", "x"], ["0", "x", "x"]],
        "tbl_or": [["0", "1", "x"], ["1", "1", "1"], ["x", "1", "x"]],
        "tbl_xor": [["0", "1", "x"], ["1", "0", "x"], ["x", "x", "x"]],
        "tbl_xnor": [["1", "0", "x"], ["0", "1", "x"], ["x", "x", "x"]],
    }
    actual = {
        "rel_4_gt_3": rel_cmp("100", "011", "gt"),
        "rel_4_le_3": rel_cmp("100", "011", "le"),
        "rel_with_x": rel_cmp("100", "1xx", "ge"),
        "eq_4_vs_8h04": eq_logical("0100", "00000100"),
        "eq_4_vs_xxxx": eq_logical("0100", "xxxx"),
        "case_eq_4_vs_xxxx": eq_case("0100", "xxxx"),
        "case_eq_xxxx_vs_4hx": eq_case("xxxx", "xxxx"),
        "log_3_and_1x": log_and("11", "1x"),
        "log_3_and_0x": log_and("11", "0x"),
        "log_3_or_0x": log_or("11", "0x"),
        "log_not_0": log_not("0"),
        "bw_not_A": "".join(bit_not(c) for c in A_bw),
        "bw_B_or_C": vec_op(B_bw, C_bw, bit_or),
        "bw_B_and_C": vec_op(B_bw, C_bw, bit_and),
        "tbl_and": tbl_and,
        "tbl_or": tbl_or,
        "tbl_xor": tbl_xor,
        "tbl_xnor": tbl_xnor,
    }
    return {
        "name": "relational_equality_logical_and_bitwise_tables",
        "summary": "校验关系、逻辑相等 == 与全等 ===、逻辑短路与四值按位真值表(&、|、^、~^)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_reduction_shift_concat_and_conditional():
    # Reduction on 4'b1010
    A_bits = "1010"
    red_and = A_bits[0]
    red_or = A_bits[0]
    red_xor = A_bits[0]
    for ch in A_bits[1:]:
        red_and = bit_and(red_and, ch)
        red_or = bit_or(red_or, ch)
        red_xor = bit_xor(red_xor, ch)
    red_nor = bit_not(red_or)

    # Shift: logical vs signed arithmetic right shift
    a_val = 0b1100  # 12 unsigned, -4 in 4-bit signed
    lshr = (a_val >> 2) & 0xF     # 4'b0011 = 3
    lshl = (a_val << 1) & 0xF     # 4'b1000 = 8
    # Arithmetic right shift on signed 4'b1100 (-4) >>> 2 = -1 = 4'b1111
    a_signed = -4
    ashr_4b = (a_signed >> 2) & 0xF  # 4'b1111
    c_val = (0b0010 + ashr_4b) & 0xF # 2 + (-1) mod 16 = 1 = 4'b0001

    # Concatenation and replication
    A = "1010"  # [3]=1,[2]=0,[1]=1,[0]=0
    B = "1"
    y1 = B + A[0:2] + A[3] + "0011"      # 1_10_0_0011 = 11000011
    y2 = (B * 4) + "100"                 # 1111_100 = 1111100
    y3 = "0" * 32

    # 4-way nested conditional mux
    def mux4(addr_hi):
        return "p1" if addr_hi == 0 else ("p2" if addr_hi == 1 else ("p3" if addr_hi == 2 else "p4"))

    expected = {
        "red_and": "0",
        "red_nor": "0",
        "red_xor": "0",
        "lshr_4b": "0011",
        "lshl_4b": "1000",
        "ashr_signed_4b": "1111",
        "b_plus_ashr_4b": "0001",
        "y1": "11000011",
        "y2": "1111100",
        "y3_zero_width": 32,
        "mux4_outputs": ["p1", "p2", "p3", "p4"],
    }
    actual = {
        "red_and": red_and,
        "red_nor": red_nor,
        "red_xor": red_xor,
        "lshr_4b": format(lshr, "04b"),
        "lshl_4b": format(lshl, "04b"),
        "ashr_signed_4b": format(ashr_4b, "04b"),
        "b_plus_ashr_4b": format(c_val, "04b"),
        "y1": y1,
        "y2": y2,
        "y3_zero_width": len(y3),
        "mux4_outputs": [mux4(i) for i in range(4)],
    }
    return {
        "name": "reduction_shift_concat_and_conditional",
        "summary": "验证归约运算、逻辑移位与有符号算术右移 >>>、位拼接/复制及嵌套条件运算符多路选择",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_precedence_associativity_and_operands(),
        case_arithmetic_x_propagation_and_width(),
        case_relational_equality_logical_and_bitwise_tables(),
        case_reduction_shift_concat_and_conditional(),
    ]
    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-expression-lab/explore-expression.py

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

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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