summaryrefslogtreecommitdiff
path: root/projects/scripts/nands.py
diff options
context:
space:
mode:
authorFrederick Yin <fkfd@fkfd.me>2022-08-18 19:54:09 +0800
committerFrederick Yin <fkfd@fkfd.me>2022-08-18 19:54:09 +0800
commitc80e03e74121d1cc321f94d7764288a4347e4e1e (patch)
treec539412a700b75cfa057381ee9eb4f7f3860563b /projects/scripts/nands.py
parent05cdd93b973587dd123b58ad0944c0e51088638e (diff)
Add nands.py script
Diffstat (limited to 'projects/scripts/nands.py')
-rw-r--r--projects/scripts/nands.py60
1 files changed, 60 insertions, 0 deletions
diff --git a/projects/scripts/nands.py b/projects/scripts/nands.py
new file mode 100644
index 0000000..fe6dada
--- /dev/null
+++ b/projects/scripts/nands.py
@@ -0,0 +1,60 @@
+"""Count how many NANDs are there in a given HDL file."""
+
+from sys import stderr
+from argparse import ArgumentParser
+
+HDL_PROJECTS = ["01", "02", "03/a", "03/b", "05"]
+
+CHIPS = {
+ "Nand": 1,
+ "DFF": 6, # https://commons.wikimedia.org/wiki/File:Edge_triggered_D_flip_flop.svg
+ "ARegister": 224, # the same as Register
+ "DRegister": 224,
+}
+
+
+def count_nands(project_path, chip):
+ # figure out where the HDL is
+ f = None
+ for dir in HDL_PROJECTS:
+ try:
+ f = open(project_path + dir + f"/{chip}.hdl")
+ break
+ except FileNotFoundError:
+ continue
+
+ if f is None:
+ print(f"Chip not found: {chip}", file=stderr)
+ return 0
+
+ while f.readline().strip() != "PARTS:":
+ continue
+
+ nands = 0
+ line = f.readline() # e.g. " Not (in=in, out=out); // comment"
+ while line:
+ code = line.split("//")[0].strip() # e.g. "Not (in=in, out=out);"
+ if "(" not in code:
+ line = f.readline()
+ continue
+ subchip = code.split("(")[0].strip() # e.g. "Not"
+ if subchip not in CHIPS:
+ CHIPS[subchip] = count_nands(project_path, subchip)
+ print(f"{subchip}\t{CHIPS[subchip]}")
+
+ nands += CHIPS[subchip]
+ line = f.readline()
+
+ f.close()
+ return nands
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser("nands")
+ parser.add_argument(
+ "path",
+ help="Path to directory that contains the projects",
+ )
+ parser.add_argument("chip", help="Name of chip in which to count NANDs")
+ args = parser.parse_args()
+ print(f"There are {count_nands(args.path, args.chip)} NAND gates in {args.chip}")