文章目录
介绍
在 上一篇文章 中,我们使用 Python 构建了一个简单的硬件仿真框架。这一篇文章中,会基于它,构建更加便捷的仿真框架。
目标:实现这样的语法:
from hardware_sim_simpleS import * # 为了表示不同,在模块名结尾加上 S
class Xor(Module):
a: Input # 表示 a 是一个输入,位宽是 1
b: Input
out: Output # 表示 out 是一个输出,位宽是 1
def build(self):
... # 与上次相同
class XorTest(Testbench[Xor]): # 测试类的基类是 Testbench,带 [] 可以自动生成测试
pass
if __name__ == '__main__':
XorTest.run()
产生输出是 Markdown 格式的真值表(而且格式化过):
| a | b | out |
|-----|-----|-----|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
实现
Module 类
首先实现 Module 类。只需继承自上一篇文章中的 Module 类,并实现 __init_subclass__
方法就可以了。
上一篇文章的 Module 类需要 inputs 和 outputs 类变量。__init_subclass__
需要找到类中的 Input 和 Output 类型注解,并转换成 inputs 和 outputs。 Input 和 Output 两个类可以什么都不做。只用来标注输入和输出。
获取类的类型注解和函数一样,使用 .__annotations__
属性访问。
可以写出:
from typing import Generic, TypeVar
from hardware_sim_simple import Module as _Module, Wire, Nand, all_wires
size = TypeVar('size')
class Module(_Module):
def build(self):
raise NotImplementedError
def __init_subclass__(cls, **kwargs):
inputs = []
outputs = []
for attr, t in cls.__annotations__.items():
if t is Input:
inputs.append((attr, 1))
elif t is Output:
outputs