2.1 Verilog 基础语法
讲解 Verilog 的大小写敏感性、自由书写格式与分号结束规则、单行与多行注释写法,以及标识符命名规范与全小写关键字约束。
学完这一章,你能够
- 讲解 Verilog 的大小写敏感性、自由书写格式与分号结束规则、单行与多行注释写法,以及标识符命名规范与全小写关键字约束。
代码格式、空白符与分号规则
Verilog 严格区分大小写,且采用自由格式语法:既可将多条语句压缩在同一行内书写,也可以按缩进跨越多行排版。每条语句必须以英文分号 `;` 结尾,而空格、制表符(Tab)与换行符等空白符仅作为词法分隔,在编译阶段会被忽略,不会改变语义。
例如声明 `wire [1:0] results;` 并以嵌套三目条件运算符赋值时,单行紧凑写法与多行对齐写法在词法与综合结果上完全等价,但工程实践强烈推荐采用多行分层缩进以提升可读性与审阅效率;同时务必确保冒号 `:` 与分号 `;` 均为半角 ASCII 标点,避免误输入全角字符引发编译报错。
单行注释与多行块注释
Verilog 提供与 C/C++ 一致的两种注释语法:使用 `//` 发起单行注释(从 `//` 起至行尾均被编译器忽略,例如 `reg [3:0] counter; // counter register`);使用 `/*` 与 `*/` 包裹跨行块注释,适合编写模块头说明或临时屏蔽多行代码(标准 Verilog 中块注释不支持嵌套)。
标识符命名规则与关键字
用户自定义的标识符(Identifier)可由英文字母、数字、美元符号 `$` 与下划线 `_` 组成,但首字符必须是字母或下划线,严禁以数字或 `$` 开头(`$` 开头预留给 `$display`、`$finish` 等系统任务与系统函数)。标识符严格区分大小写,因此 `clk` 与 `CLK` 代表两个完全独立的信号;关键字(如 `reg`、`wire`、`input`、`assign`、`module`)均为全小写预留词,不可直接用作普通标识符。
离线校验 Verilog 自由格式词法等价、注释剥离、标识符规则与标点检查
"""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()
- 在 CPython 3.12.14 离线脚本中验证单行与多行代码分词等价及三目真值、单行/块注释剥离、标识符正则与大小写区分(clk != CLK)及全角冒号检测全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。
当前源码 SHA256:400284a7619b5c7622439d14a109cb5599a1e8bb7add4ee7c580f14191187531
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。
ZIP SHA256:a1e35935ff9510b2d94985a1a7d10fa1854499fae47114d5827c294998533c69
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Verilog 标识符不能以 `$` 开头?`CLK` 与 `clk` 能否在同一个模块中同时声明?
展开参考解答
以 `$` 开头的标识符在 Verilog 中专门保留给系统任务与系统函数(如 `$time`、`$finish`),用户信号名不能以 `$` 或数字开头;由于 Verilog 区分大小写,`CLK` 与 `clk` 在语法上是两个不同的标识符(尽管工程规范中应避免仅靠大小写区分信号以防误读)。