#!/usr/bin/env python3
#
# This script reads and parses all top-level modules and generates a core block
# file containing instantiation of these modules. This generated file is included
# by core.vh
#
#-------------------------------------------------------------------------------
#  Copyright (C) 2016  Goran Devic
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
#
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
#-------------------------------------------------------------------------------
import os

# Define a set of module cross-connections. These are the chip's internal buses
# which we inject as connections as we generate a list of module instances
xconnections = [
    ['interrupts', 'db', 'db0[4:3]'],
    ['ir', 'db', 'db0[7:0]'],
    ['alu_control', 'db', 'db1[7:0]'],
    ['alu_control', 'op543', '{pla[104],pla[103],pla[102]}'],
    ['alu_flags', 'db', 'db1[7:0]'],
    ['alu', 'db', 'db2[7:0]'],
    ['alu', 'bsel', 'db0[5:3]'],
    ['reg_file', 'db_hi_ds', 'db2[7:0]'],
    ['reg_file', 'db_lo_ds', 'db1[7:0]'],
    ['reg_file', 'db_hi_as', 'db_hi_as[7:0]'],
    ['reg_file', 'db_lo_as', 'db_lo_as[7:0]'],
    ['address_latch', 'abus', '{db_hi_as[7:0], db_lo_as[7:0]}'],
    ['bus_control', 'db', 'db0[7:0]']
]

# Define a list of modules that are not used (but listed in 'top-level-files.txt' )
skip_modules = ['address_pins', 'data_pins', 'control_pins_n']

# For error-checking, make sure every xconnection entry has been utilized
xcount = len(xconnections)

def connect(module, wire):
    global xcount
    for xconnection in xconnections:
        m, w, xcon = xconnection
        if module==m and wire==w:
            print("Cross-connecting:", module, wire, "->", xcon)
            xcount -= 1
            return xcon
    return wire

def parse(wires, lines):
    while(len(lines)>0 and lines[0].startswith(');')==False):
        line = lines[0].strip()
        lines.pop(0)
        if len(line)==0 or line[0]=='(' or line[0]=='/':
            continue
        tokens = line.split()
        if len(tokens)>=3 and tokens[0] in ['input', 'output']:
            tokens.pop(0)
        if len(tokens)>=2 and tokens[0] in ['wire', 'reg']:
            tokens.pop(0)
        if len(tokens)>=2 and tokens[0].startswith('['):
            tokens.pop(0)
        if len(tokens)>=2 and tokens[0]=='`include':
            include_file = tokens[1].replace('"', '')
            with open('../control/' + include_file) as f:
                included_lines = f.read().splitlines()
            parse(wires, included_lines)
            continue
        name = tokens[0]
        if name.endswith(','):
            name = name[:-1]
        wires.append(name)

with open('../top-level-files.txt') as f:
    files = f.read().splitlines()

# Create a file that should be included in the top-level core source
with open('coremodules.vh', 'w') as file1:
    file1.write("// Automatically generated by gencoremodules.py\n")

# Read and parse each file from the list of input files
for infile in files:
    if not os.path.isfile('../' + infile):
        continue
    with open('../' + infile, "r") as f:
        lines = f.read().splitlines()

    # Find 'module' section; read and generate instantiation statement
    while(len(lines)>0 and lines[0].startswith('module ')==False):
        lines.pop(0)
    if len(lines)==0:
        continue

    module_name = lines[0].split()[1]
    lines.pop(0)
    if module_name.endswith('('):
        module_name = module_name[:-1]
    if module_name in skip_modules:
        continue

    # Read a list of input/output wires, one per line
    wires = []
    parse(wires, lines)

    # Print the names of all parsed signals in a module instantiation format
    with open('coremodules.vh', 'a') as file1:
        file1.write("\n" + module_name + " " + module_name + "_(\n")
        while(len(wires)>0):
            wire = wires.pop(0)
            terminator = ','
            if len(wires)==0:
                terminator = "\n);"
            file1.write("    ." + wire + " (" + connect(module_name, wire) + ")" + terminator + "\n")

assert(xcount==0)

# Touch files that include 'coremodules.vh' to ensure it will recompile correctly
os.utime("core.vh", None)
