summaryrefslogtreecommitdiff
path: root/projects/scripts/nands.py
blob: fe6dadab2cbdbdb3382eae0c59fd5ff102db7f0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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}")