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

离线校验 Verilog 自由格式词法等价、注释剥离、标识符规则与标点检查

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

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

TOKEN_RE = re.compile(r"\d+'[bBdDhHoO][0-9a-fA-FxXzZ_]+|[A-Za-z_][A-Za-z0-9_$]*|==|!=|<=|>=|[;:\?\[\]\(\)=]")


def tokenize_verilog(src):
    return TOKEN_RE.findall(src)


def case_free_format_and_whitespace_equivalence():
    one_line = "wire [1:0] results ;assign results = (a == 1'b0) ? 2'b01 : (b == 1'b0) ? 2'b10 : 2'b11 ;"
    multi_line = (
        "wire [1:0] results ;\n"
        "assign     results = (a == 1'b0) ? 2'b01 :\n"
        "                     (b == 1'b0) ? 2'b10 :\n"
        "                                   2'b11 ;\n"
    )
    toks_one = tokenize_verilog(one_line)
    toks_multi = tokenize_verilog(multi_line)

    def eval_results(a, b):
        return "2'b01" if a == 0 else ("2'b10" if b == 0 else "2'b11")

    truth = {f"{a}{b}": eval_results(a, b) for a in (0, 1) for b in (0, 1)}
    expected = {
        "tokens_identical": True,
        "semicolon_count": 2,
        "truth_map": {"00": "2'b01", "01": "2'b01", "10": "2'b10", "11": "2'b11"},
    }
    actual = {
        "tokens_identical": toks_one == toks_multi,
        "semicolon_count": toks_one.count(";"),
        "truth_map": truth,
    }
    return {
        "name": "free_format_and_whitespace_equivalence",
        "summary": "验证单行与多行自由格式代码词法等价、分号语句结束符及嵌套条件赋值真值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_comment_stripping_single_and_block():
    single_src = "reg [3:0] counter ; // A definition of counter register\n"
    block_src = (
        "wire [11:0] addr ;\n"
        "/*\n"
        "Next are notes with multiple lines.\n"
        "Codes here cannot be compiled.\n"
        "*/\n"
        "assign addr = 12'b0 ;\n"
    )

    def strip_comments(text):
        no_block = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
        no_line = re.sub(r"//[^\n]*", "", no_block)
        return " ".join(no_line.split())

    expected = {
        "single_cleaned": "reg [3:0] counter ;",
        "block_cleaned": "wire [11:0] addr ; assign addr = 12'b0 ;",
        "block_comment_excluded": True,
    }
    cleaned_single = strip_comments(single_src)
    cleaned_block = strip_comments(block_src)
    actual = {
        "single_cleaned": cleaned_single,
        "block_cleaned": cleaned_block,
        "block_comment_excluded": "cannot be compiled" not in cleaned_block,
    }
    return {
        "name": "comment_stripping_single_and_block",
        "summary": "验证单行注释 // 与多行块注释 /* ... */ 在编译预处理阶段被完整忽略",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_identifier_and_case_sensitivity():
    ident_re = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$")
    keywords = {"module", "endmodule", "wire", "reg", "input", "output", "assign", "always", "initial"}

    def classify(name):
        if name in keywords:
            return "keyword"
        if ident_re.match(name):
            return "identifier"
        return "invalid"

    samples = {
        "reg": classify("reg"),
        "counter": classify("counter"),
        "clk": classify("clk"),
        "CLK": classify("CLK"),
        "_bus$0": classify("_bus$0"),
        "1data": classify("1data"),
        "$finish": classify("$finish"),
    }
    symbol_table = {"clk": "low_freq_clock", "CLK": "high_freq_clock"}
    expected = {
        "samples": {
            "reg": "keyword",
            "counter": "identifier",
            "clk": "identifier",
            "CLK": "identifier",
            "_bus$0": "identifier",
            "1data": "invalid",
            "$finish": "invalid",
        },
        "all_keywords_lowercase": True,
        "distinct_clk_CLK": True,
    }
    actual = {
        "samples": samples,
        "all_keywords_lowercase": all(k == k.lower() for k in keywords),
        "distinct_clk_CLK": symbol_table["clk"] != symbol_table["CLK"],
    }
    return {
        "name": "identifier_and_case_sensitivity",
        "summary": "校验 Verilog 标识符首字符与字符集规则、大小写敏感性(clk 与 CLK 区分)及关键字全小写约定",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ascii_punctuation_lint_check():
    bad_expr = "assign y = a ? 1'b1 : 1'b0 ;"
    good_expr = "assign y = a ? 1'b1 : 1'b0 ;"

    def has_non_ascii_punct(s):
        return any(ord(c) > 127 for c in s)

    expected = {
        "fullwidth_colon_flagged": True,
        "ascii_colon_clean": True,
    }
    actual = {
        "fullwidth_colon_flagged": has_non_ascii_punct(bad_expr),
        "ascii_colon_clean": not has_non_ascii_punct(good_expr),
    }
    return {
        "name": "ascii_punctuation_lint_check",
        "summary": "检测条件表达式中误用全角中文冒号等非 ASCII 标点导致的语法错误",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_free_format_and_whitespace_equivalence(),
        case_comment_stripping_single_and_block(),
        case_identifier_and_case_sensitivity(),
        case_ascii_punctuation_lint_check(),
    ]
    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-basic-syntax-lab/explore-basic-syntax.py

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

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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