Example #1
0
    def verilogParse(self):

        with open(self.modelpath + self.fname, 'rt') as fh:
            code = fh.read()

        code = code.replace("wire", " ")
        code = code.replace("reg", " ")
        vlog_ex = vlog.VerilogExtractor()
        vlog_mods = vlog_ex.extract_objects_from_source(code)
        f = open(self.modelpath + "connection_info.txt", 'w')
        for m in vlog_mods:
            if m.name.lower() == self.fname.split('.')[0]:
                print(str(m.name) + " " + self.fname.split('.')[0])
                for p in m.ports:
                    print(p.data_type)
                    if str(p.data_type).find(':') == -1:
                        p.port_number = "1"
                    else:
                        x = p.data_type.split(":")
                        print(x)
                        y = x[0].split("[")
                        z = x[1].split("]")
                        z = int(y[1]) - int(z[0])
                        p.port_number = z + 1

        for m in vlog_mods:
            if m.name.lower() == self.fname.split('.')[0]:
                m.name = m.name.lower()
                print('Module "{}":'.format(m.name))
                for p in m.generics:
                    print('\t{:20}{:8}{}'.format(p.name, p.mode, p.data_type))
                print('  Ports:')
                for p in m.ports:
                    print(
                        '\t{:20}{:8}{}'.format(
                            p.name, p.mode, p.port_number))
                    f.write(
                        '\t{:20}{:8}{}\n'.format(
                            p.name, p.mode, p.port_number))
                break
        f.close()
        if m.name.lower() != self.fname.split(".")[0]:
            QtWidgets.QMessageBox.critical(
                None,
                "Error Message",
                "<b>Error: File name and module \
                name are not same. Please ensure that they are same</b>",
                QtWidgets.QMessageBox.Ok)

            self.obj_Appconfig.print_info(
                'NgVeri stopped due to file \
                name and module name not matching error')
            return "Error"
        modelname = str(m.name)
        schematicLib = createkicad.AutoSchematic()
        schematicLib.init(modelname, self.modelpath)
        error = schematicLib.createkicad()
        if error == "Error":
            return "Error"
        return "No Error"
Example #2
0
def parse_to_dict(fname):
    if os.path.exists(
            fname) and os.stat(fname).st_size != 0 and fname.endswith('.v'):
        vlog_ex = vlog.VerilogExtractor()
        with open(fname, 'r') as fh:
            code = fh.read()
        vlog_mods = vlog_ex.extract_objects_from_source(code)
        dict_ports = dict()
        for m in vlog_mods:
            for p in m.ports:
                dict_ports[p.name] = [p.mode, p.data_type]
        return dict_ports
    else:
        print("\nError in File: '%s'" % fname)
        sys.exit("File does not exist OR is empty OR wrong extension")
Example #3
0
def parse_verilog(filename):
    vlog_ex = vlog_parser.VerilogExtractor()
    vlog_mods = vlog_ex.extract_objects(filename)

    #for m in vlog_mods:
    #    print('Module "{}":'.format(m.name))
    #    print('  Parameters:')
    #    for p in m.generics:
    #        print('\t{:20}{:8}{:8}{:8}{} bits'.format(p.name, p.mode, p.data_type,
    #                                             p,range, p.size))
    #    print('  Ports:')
    #    for p in m.ports:
    #        print('\t{:20}{:8}{:6}{:8}{:8}{:4}{}'.format(p.name, p.mode, p.data_type, p.sign,
    #                                                      p.range, p.size, p.annotations if p.annotations else ''))
    #    print('  Sections:')
    #    for p, v in m.sections.items():
    #        print('\t{} {}'.format(p, v))

    return vlog_mods
Example #4
0
def main():
    '''Run symbolator'''
    args = parse_args()

    style = DrawStyle()
    style.line_color = (0, 0, 0)

    vhdl_ex = vhdl.VhdlExtractor()
    vlog_ex = vlog.VerilogExtractor()

    if os.path.isfile(args.lib_dirs[0]):
        # This is a file containing previously parsed array type names
        vhdl_ex.load_array_types(args.lib_dirs[0])

    else:  # args.lib_dirs is a path
        # Find all library files
        flist = []
        for lib in args.lib_dirs:
            print('Scanning library:', lib)
            flist.extend(
                file_search(lib,
                            extensions=('.vhdl', '.vhd', '.vlog',
                                        '.v')))  # Get VHDL and Verilog files
        if args.input and os.path.isfile(args.input):
            flist.append(args.input)

        # Find all of the array types
        vhdl_ex.register_array_types_from_sources(flist)

        #print('## ARRAYS:', vhdl_ex.array_types)

    if args.save_lib:
        print('Saving type defs to "{}".'.format(args.save_lib))
        vhdl_ex.save_array_types(args.save_lib)

    if args.input is None:
        print("Error: Please provide a proper input file")
        sys.exit(0)

    if args.input == '-':  # Read from stdin
        code = ''.join(list(sys.stdin))
        if is_verilog_code(code):
            all_components = {
                '<stdin>': [(c, vlog_ex)
                            for c in vlog_ex.extract_objects_from_source(code)]
            }
        else:
            all_components = {
                '<stdin>': [(c, vhdl_ex)
                            for c in vhdl_ex.extract_objects_from_source(
                                code, VhdlComponent)]
            }
        # Output is a named file

    elif os.path.isfile(args.input):
        if vhdl.is_vhdl(args.input):
            all_components = {
                args.input:
                [(c, vhdl_ex)
                 for c in vhdl_ex.extract_objects(args.input, VhdlComponent)]
            }
        else:
            all_components = {
                args.input:
                [(c, vlog_ex) for c in vlog_ex.extract_objects(args.input)]
            }
        # Output is a directory

    elif os.path.isdir(args.input):
        flist = set(
            file_search(args.input,
                        extensions=('.vhdl', '.vhd', '.vlog', '.v', '.sv')))

        # Separate file by extension
        vhdl_files = set(f for f in flist if vhdl.is_vhdl(f))
        vlog_files = flist - vhdl_files

        all_components = {
            f:
            [(c, vhdl_ex) for c in vhdl_ex.extract_objects(f, VhdlComponent)]
            for f in vhdl_files
        }

        vlog_components = {
            f: [(c, vlog_ex) for c in vlog_ex.extract_objects(f)]
            for f in vlog_files
        }
        all_components.update(vlog_components)
        # Output is a directory

    else:
        print('Error: Invalid input source')
        sys.exit(1)

    if args.output:
        create_directories(args.output)

    if not args.markdown_only:
        nc = NuCanvas(None)

        # Set markers for all shapes
        nc.add_marker(
            'arrow_fwd',
            PathShape(((0, -4), (2, -1, 2, 1, 0, 4), (8, 0), 'z'),
                      fill=(0, 0, 0),
                      weight=0), (3.2, 0), 'auto', None)

        nc.add_marker(
            'arrow_back',
            PathShape(((0, -4), (-2, -1, -2, 1, 0, 4), (-8, 0), 'z'),
                      fill=(0, 0, 0),
                      weight=0), (-3.2, 0), 'auto', None)

        nc.add_marker('bubble',
                      OvalShape(-3, -3, 3, 3, fill=(255, 255, 255), weight=1),
                      (0, 0), 'auto', None)

        nc.add_marker(
            'clock',
            PathShape(((0, -7), (0, 7), (7, 0), 'z'),
                      fill=(255, 255, 255),
                      weight=1), (0, 0), 'auto', None)

    # read default signal & params desc from file
    if args.markdown_dict:
        with open(args.markdown_dict, 'r') as stream:
            global default_desc_dict
            default_desc_dict = yaml.safe_load(stream)

    # Render every component from every file into an image
    for source, components in all_components.items():
        for comp, extractor in components:
            comp.name = comp.name.strip('_')

            if args.component != "" and args.component != comp.name:
                continue

            reformat_array_params(comp)
            if source == '<stdin>' or args.output_as_filename:
                fname = args.output
            else:
                fname = '{}{}.{}'.format(
                    args.libname + "__" if args.libname is not None
                    or args.libname != "" else "", comp.name, args.format)
                if args.output:
                    fname = os.path.join(args.output, fname)

            # image output
            if not args.markdown_only:
                print('Creating symbol for {} "{}"\n\t-> {}'.format(
                    source, comp.name, fname))
                if args.format == 'svg':
                    surf = SvgSurface(fname,
                                      style,
                                      padding=5,
                                      scale=args.scale)
                else:
                    surf = CairoSurface(fname,
                                        style,
                                        padding=5,
                                        scale=args.scale)

                nc.set_surface(surf)
                nc.clear_shapes()

                sym = make_symbol(comp, extractor, args.title, args.libname,
                                  args.no_type)
                sym.draw(0, 0, nc)

                nc.render(args.transparent)

            # doc (markdown) output
            if args.markdown or args.markdown_only:
                if args.output_as_filename or args.markdown_only:
                    fname_md = args.output
                    fname_img = re.sub('md$', args.format,
                                       os.path.basename(fname_md))
                else:
                    fname_md = re.sub(args.format + '$', 'md', fname)
                    fname_img = os.path.basename(fname)
                print('Creating markdown for {} "{}"\n\t-> {}'.format(
                    source, comp.name, fname_md))

                env = Environment(loader=PackageLoader("symbolator_templates",
                                                       ''),
                                  autoescape=select_autoescape())
                template = env.get_template("template.md.jinjja2")
                doc_txt = template.render(module=comp,
                                          fname=fname_img,
                                          get_description=get_description)

                with open(fname_md, 'w') as doc_file:
                    doc_file.write(doc_txt)
Example #5
0
    def runmakerchip(self):
        init_path = '../../'
        if os.name == 'nt':
            init_path = ''
        try:
            if not makerchipTOSAccepted(True):
                return

            print("Running Makerchip IDE...........................")
            # self.file = open(self.verilogfile,"w")
            # self.file.write(self.entry_var[1].toPlainText())
            # self.file.close()
            filename = self.verilogfile
            if self.verilogfile.split('.')[-1] != "tlv":
                reply = QtWidgets.QMessageBox.warning(
                    None, "Do you want to automate the top module? ",
                    "<b>Click on YES button if you want the top module \
                    to be added automatically. A .tlv file will be created \
                    in the directory of current verilog file \
                    and the Makerchip IDE will be running on \
                    this file. Otherwise click on NO button. \
                    To not open Makerchip IDE, click on CANCEL button. </b>\
                    <br><br> NOTE: Makerchip IDE requires an active \
                    internet connection and a browser.",
                    QtWidgets.QMessageBox.Yes
                    | QtWidgets.QMessageBox.No
                    | QtWidgets.QMessageBox.Cancel)
                if reply == QtWidgets.QMessageBox.Cancel:
                    return
                if reply == QtWidgets.QMessageBox.Yes:
                    code = open(self.verilogfile).read()
                    text = code
                    filename = '.'.join(
                        self.verilogfile.split('.')[:-1]) + ".tlv"
                    file = os.path.basename('.'.join(
                        self.verilogfile.split('.')[:-1]))
                    f = open(filename, 'w')
                    code = code.replace(" wire ", " ")
                    code = code.replace(" reg ", " ")
                    vlog_ex = vlog.VerilogExtractor()
                    vlog_mods = vlog_ex.extract_objects_from_source(code)
                    lint_off = open(init_path +
                                    "library/tlv/lint_off.txt").readlines()
                    string = '''\\TLV_version 1d: tl-x.org\n\\SV\n'''
                    for item in lint_off:
                        string += "/* verilator lint_off " + \
                            item.strip("\n") + "*/  "
                    string += '''\n\n//Your Verilog/System \
Verilog Code Starts Here:\n''' + \
                        text + '''\n\n//Top Module Code \
Starts here:\n\tmodule top(input \
logic clk, input logic reset, input logic [31:0] cyc_cnt, \
output logic passed, output logic failed);\n'''
                    print(file)
                    for m in vlog_mods:
                        if m.name.lower() == file.lower():
                            for p in m.ports:
                                if str(p.name) != "clk" and str(
                                        p.name) != "reset" and str(
                                            p.name) != "cyc_cnt" and str(
                                                p.name) != "passed" and str(
                                                    p.name) != "failed":
                                    string += '\t\tlogic ' + p.data_type\
                                     + " " + p.name + ";//" + p.mode + "\n"
                    if m.name.lower() != file.lower():
                        QtWidgets.QMessageBox.critical(
                            None, "Error Message",
                            "<b>Error: File name and module \
                            name are not same. Please \
                            ensure that they are same.</b>",
                            QtWidgets.QMessageBox.Ok)

                        self.obj_Appconfig.print_info(
                            'NgVeri stopped due to file \
name and module name not matching error')
                        return
                    string += "//The $random() can be replaced \
if user wants to assign values\n"

                    for m in vlog_mods:
                        if m.name.lower() == file.lower():
                            for p in m.ports:
                                if str(p.mode) == "input" or str(
                                        p.mode) == "inout":
                                    if str(p.name) != "clk" and str(
                                            p.name) != "reset" and str(
                                                p.name) != "cyc_cnt" and str(
                                                    p.name
                                                ) != "passed" and str(
                                                    p.name) != "failed":
                                        string += '\t\tassign ' + p.name\
                                         + " = " + "$random();\n"

                    for m in vlog_mods:
                        if m.name.lower() == file.lower():
                            string += '\t\t' + m.name + " " + m.name + '('
                            i = 0
                            for p in m.ports:
                                i = i + 1
                                string += "." + p.name + "(" + p.name + ")"
                                if i == len(m.ports):
                                    string += ");\n\t\n\\TLV\n//\
Add \\TLV here if desired\
                                     \n\\SV\nendmodule\n\n"

                                else:
                                    string += ", "
                    f.write(string)

            self.process = QtCore.QProcess(self)
            cmd = 'makerchip ' + filename
            print("File: " + filename)
            self.process.start(cmd)
            print("Makerchip IDE command process pid ---------->",
                  self.process.pid())
        except BaseException as e:
            print(e)
            self.msg = QtWidgets.QErrorMessage(self)
            self.msg.setModal(True)
            self.msg.setWindowTitle("Error Message")
            self.msg.showMessage("Error in running Makerchip IDE. \
Please check if verilog file is chosen.")
            self.msg.exec_()
            print("Error in running Makerchip IDE. \
Please check if verilog file is chosen.")
Example #6
0
import os.path
import re
import sys
import hdlparse.verilog_parser as vlog

# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', required=True, help='Verilog input file')
parser.add_argument('-i',
                    '--iceblock',
                    action='store_true',
                    help='Help with Icestudio code block generation')
parser.add_argument('-n', '--name', help='Instance Name')
args = parser.parse_args()

vlog_ex = vlog.VerilogExtractor()
vlog_mods = vlog_ex.extract_objects(args.file)

input = lambda p: p.mode == "input"
output = lambda p: p.mode == "output"


def lpad(str, n):
    return (str + " " * n)[0:n]


def rpad(str, n):
    return (" " * n + str)[-n:]


def instanciate():
Example #7
0
def main():
    '''Run symbolator'''
    args = parse_args()

    style = DrawStyle()
    style.line_color = (0, 0, 0)

    vhdl_ex = vhdl.VhdlExtractor()
    vlog_ex = vlog.VerilogExtractor()

    if args.input is None:
        sys.exit(0)

    if args.input == '-':  # Read from stdin
        code = ''.join(list(sys.stdin))
        if is_verilog_code(code):
            all_components = {
                '<stdin>': [(c, vlog_ex)
                            for c in vlog_ex.extract_objects_from_source(code)]
            }
        else:
            all_components = {
                '<stdin>': [(c, vhdl_ex)
                            for c in vhdl_ex.extract_objects_from_source(
                                code, VhdlComponent)]
            }
        # Output is a named file

    elif os.path.isfile(args.input):
        if vhdl.is_vhdl(args.input):
            all_components = {
                args.input:
                [(c, vhdl_ex)
                 for c in vhdl_ex.extract_objects(args.input, VhdlComponent)]
            }
        else:
            all_components = {
                args.input:
                [(c, vlog_ex) for c in vlog_ex.extract_objects(args.input)]
            }
        # Output is a directory

    else:
        print('ERROR: Invalid input source')
        sys.exit(1)

    if args.output:
        create_directories(args.output)

    nc = NuCanvas(None)

    # Set markers for all shapes
    nc.add_marker(
        'arrow_fwd',
        PathShape(((0, -4), (2, -1, 2, 1, 0, 4), (8, 0), 'z'),
                  fill=(0, 0, 0),
                  weight=0), (3.2, 0), 'auto', None)

    nc.add_marker(
        'arrow_back',
        PathShape(((0, -4), (-2, -1, -2, 1, 0, 4), (-8, 0), 'z'),
                  fill=(0, 0, 0),
                  weight=0), (-3.2, 0), 'auto', None)

    nc.add_marker('bubble',
                  OvalShape(-3, -3, 3, 3, fill=(255, 255, 255), weight=1),
                  (0, 0), 'auto', None)

    nc.add_marker(
        'clock',
        PathShape(((0, -7), (0, 7), (7, 0), 'z'),
                  fill=(255, 255, 255),
                  weight=1), (0, 0), 'auto', None)

    # Render every component from every file into an image
    for source, components in all_components.items():
        for comp, extractor in components:
            comp.name = comp.name.strip('_')
            reformat_array_params(comp)
            if source == '<stdin>':
                fname = args.output
            else:
                fname = args.input.rsplit('.', 1)[0] + '.' + args.format
                if args.output:
                    fname = os.path.join(args.output, fname)
            assert not os.path.exists(fname), fname
            print('Creating symbol for {} "{}" -> {}'.format(
                source, comp.name, fname))
            if args.format == 'svg':
                surf = SvgSurface(fname, style, padding=5, scale=args.scale)
            else:
                surf = CairoSurface(fname, style, padding=5, scale=args.scale)

            nc.set_surface(surf)
            nc.clear_shapes()

            sym = make_symbol(comp, extractor, args.title, args.libname,
                              args.no_type)
            sym.draw(0, 0, nc)

            nc.render()
Example #8
0
def main():
  '''Run symbolator'''
  args = parse_args()

  style = DrawStyle()
  style.line_color = (0,0,0)

  vhdl_ex = vhdl.VhdlExtractor()
  vlog_ex = vlog.VerilogExtractor()

  if os.path.isfile(args.lib_dirs[0]):
    # This is a file containing previously parsed array type names
    vhdl_ex.load_array_types(args.lib_dirs[0])

  else: # args.lib_dirs is a path
    # Find all library files
    flist = []
    for lib in args.lib_dirs:
      print('Scanning library:', lib)
      flist.extend(file_search(lib, extensions=('.vhdl', '.vhd', '.vlog', '.v'))) # Get VHDL and Verilog files
    if args.input and os.path.isfile(args.input):
      flist.append(args.input)

    # Find all of the array types
    vhdl_ex.register_array_types_from_sources(flist)

    #print('## ARRAYS:', vhdl_ex.array_types)

  if args.save_lib:
    print('Saving type defs to "{}".'.format(args.save_lib))
    vhdl_ex.save_array_types(args.save_lib)


  if args.input is None:
    print("Error: Please provide a proper input file")
    sys.exit(0)

  if args.input == '-': # Read from stdin
    code = ''.join(list(sys.stdin))
    if is_verilog_code(code):
      all_components = {'<stdin>': [(c, vlog_ex) for c in vlog_ex.extract_objects_from_source(code)]}
    else:
      all_components = {'<stdin>': [(c, vhdl_ex) for c in vhdl_ex.extract_objects_from_source(code, VhdlComponent)]}
      all_components['<stdin>'].extend((c, vhdl_ex) for c in vhdl_ex.extract_objects_from_source(code, VhdlEntity))
    # Output is a named file

  elif os.path.isfile(args.input):
    if vhdl.is_vhdl(args.input):
      all_components = {args.input: [(c, vhdl_ex) for c in vhdl_ex.extract_objects(args.input, VhdlComponent)]}
      all_components[args.input].extend((c, vhdl_ex) for c in vhdl_ex.extract_objects(args.input, VhdlEntity))
    else:
      all_components = {args.input: [(c, vlog_ex) for c in vlog_ex.extract_objects(args.input)]}
    # Output is a directory

  elif os.path.isdir(args.input):
    flist = set(file_search(args.input, extensions=('.vhdl', '.vhd', '.vlog', '.v')))

    # Separate file by extension
    vhdl_files = set(f for f in flist if vhdl.is_vhdl(f))
    vlog_files = flist - vhdl_files

    all_components = {f: [(c, vhdl_ex) for c in vhdl_ex.extract_objects(f, objtype)] for objtype in [VhdlComponent, VhdlEntity] for f in vhdl_files}

    vlog_components = {f: [(c, vlog_ex) for c in vlog_ex.extract_objects(f)] for f in vlog_files}
    all_components.update(vlog_components)
    # Output is a directory

  else:
    print('Error: Invalid input source')
    sys.exit(1)

  if args.output:
    create_directories(args.output)

  nc = NuCanvas(None)

  # Set markers for all shapes
  nc.add_marker('arrow_fwd',
    PathShape(((0,-4), (2,-1, 2,1, 0,4), (8,0), 'z'), fill=(0,0,0), weight=0),
    (3.2,0), 'auto', None)

  nc.add_marker('arrow_back',
    PathShape(((0,-4), (-2,-1, -2,1, 0,4), (-8,0), 'z'), fill=(0,0,0), weight=0),
    (-3.2,0), 'auto', None)

  nc.add_marker('bubble',
    OvalShape(-3,-3, 3,3, fill=(255,255,255), weight=1),
    (0,0), 'auto', None)

  nc.add_marker('clock',
    PathShape(((0,-7), (0,7), (7,0), 'z'), fill=(255,255,255), weight=1),
    (0,0), 'auto', None)

  # Render every component from every file into an image
  for source, components in all_components.items():
    for comp, extractor in components:
      comp.name = comp.name.strip('_')
      reformat_array_params(comp)
      if source == '<stdin>' or args.output_as_filename:
        fname = args.output
      else:
        fname = '{}{}.{}'.format(
            args.libname + "__" if args.libname is not None or args.libname != "" else "",
            comp.name,
            args.format)
        if args.output:
          fname = os.path.join(args.output, fname)
      print('Creating symbol for {} "{}"\n\t-> {}'.format(source, comp.name, fname))
      if args.format == 'svg':
        surf = SvgSurface(fname, style, padding=5, scale=args.scale)
      else:
        surf = CairoSurface(fname, style, padding=5, scale=args.scale)

      nc.set_surface(surf)
      nc.clear_shapes()

      sym = make_symbol(comp, extractor, args.title, args.libname, args.no_type)
      sym.draw(0,0, nc)

      nc.render(args.transparent)