def copy_files(self, build_type, lib_names=None):
     """Copy all source directories and source files listed at the <tool_name>_copy_files key. The build_type selects the <tool_name>_copy_files key using the
        tool_name_<build_type> key value from the hdltool_<toolset>.cfg.
        The <tool_name>_copy_files key expects a source and a destination pair per listed directory or file:
        
        - The sources need to be specified with absolute path or relative to the HDL library source directory where the hdllib.cfg is stored
        - The destinations need to be specified with absolute path or relative to HDL library build directory where the project file (e.g. mpf, qpf) gets stored
        
        Arguments:
        - lib_names      : one or more HDL libraries
     """
     if lib_names==None: lib_names=self.lib_names
     lib_dicts = self.libs.get_dicts(key='hdl_lib_name', values=lib_names)
     tool_name_key = 'tool_name_' + build_type
     tool_name_value = self.tool_dict[tool_name_key]
     tool_name_copy_key = tool_name_value + '_copy_files'
     for lib_dict in cm.listify(lib_dicts):
         if tool_name_copy_key in lib_dict:
             lib_path = self.libs.get_filePath(lib_dict)
             build_dir_path = self.get_lib_build_dirs(build_type, lib_dicts=lib_dict)
             cm.mkdir(build_dir_path)
             key_values = lib_dict[tool_name_copy_key].split()
             sources = key_values[0::2]
             destinations = key_values[1::2]
             file_io = zip(sources, destinations)
             for fpn_io in file_io:
                 sourcePathName = cm.expand_file_path_name(fpn_io[0], lib_path)
                 destinationPath = cm.expand_file_path_name(fpn_io[1], build_dir_path)
                 if os.path.isfile(sourcePathName):
                     shutil.copy(sourcePathName, destinationPath)     # copy file
                 else:
                     copy_tree(sourcePathName, destinationPath)       # copy directory tree (will create new destinationPath directory)
    def create_quartus_settings_file(self, lib_names=None):
        """Create the Quartus settings file (QSF) for all HDL libraries that have a toplevel entity key synth_top_level_entity.
        
           Note:
           . No support for revisions, so only one qsf per qpf
           
           Arguments:
           - lib_names      : one or more HDL libraries
        """
        if lib_names == None: lib_names = self.lib_names
        lib_dicts = self.libs.get_dicts(key='hdl_lib_name', values=lib_names)
        syn_dicts = self.libs.get_dicts(key='synth_top_level_entity',
                                        values=None,
                                        dicts=lib_dicts)
        for syn_dict in cm.listify(syn_dicts):
            # Open qsf for each HDL library that has a synth_top_level_entity
            lib_name = syn_dict['hdl_lib_name']
            lib_path = self.libs.get_filePath(syn_dict)
            top_level_entity = syn_dict['synth_top_level_entity']
            if top_level_entity == '':
                top_level_entity = lib_name
            qsf_path = self.get_lib_build_dirs('synth', lib_dicts=syn_dict)
            cm.mkdir(qsf_path)

            # One qsf per lib_name
            qsf_name = lib_name + '.qsf'
            qsfPathName = cm.expand_file_path_name(qsf_name, qsf_path)
            with open(qsfPathName, 'w') as fp:
                fp.write('# synth_top_level_entity\n')
                fp.write('set_global_assignment -name TOP_LEVEL_ENTITY %s\n' %
                         top_level_entity)

                fp.write('\n')
                fp.write('# quartus_qsf_files\n')
                quartus_qsf_files = syn_dict['quartus_qsf_files'].split()
                for fn in quartus_qsf_files:
                    filePathName = cm.expand_file_path_name(fn, lib_path)
                    fp.write(
                        'set_global_assignment -name SOURCE_TCL_SCRIPT_FILE %s\n'
                        % filePathName)

                fp.write('\n')
                fp.write(
                    '# All used HDL library *_lib.qip files in order with top level last\n'
                )
                use_lib_order = self.derive_lib_order('synth', lib_name)
                #use_lib_dicts = self.libs.get_dicts('hdl_lib_name', values=use_lib_order)    # uses original libs.dicts order, but
                use_lib_dicts = self.get_lib_dicts_from_lib_names(
                    lib_names=use_lib_order
                )  # must preserve use_lib_order order to ensure that top level design qip with sdc file is include last in qsf
                for lib_dict in cm.listify(use_lib_dicts):
                    qip_path = self.get_lib_build_dirs('synth',
                                                       lib_dicts=lib_dict)
                    qip_name = lib_dict['hdl_lib_name'] + '_lib.qip'
                    qipPathName = cm.expand_file_path_name(qip_name, qip_path)
                    fp.write('set_global_assignment -name QIP_FILE %s\n' %
                             qipPathName)
 def create_quartus_project_file(self, lib_names=None):
     """Create the Quartus project file (QPF) for all HDL libraries that have a toplevel entity key synth_top_level_entity.
     
        Note:
        . Default if the synth_top_level_entity key is defined but left empty then the top level entity has the same name as the lib_name in hdl_lib_name.
          Otherwise synth_top_level_entity can specify another top level entity name in the library. Each HDL library can only have one Quartus project
          file
        . The project revision has the same name as the lib_name and will result in a <lib_name>.sof FPGA image file. 
        . For each additional revision a subdirectory can be used. 
          This subdirectory can be named 'revisions/' and lists a number of revisions as subdirectories. Each revision will have a separate hdllib.cfg file and a 
          .vhd file with the toplevel entity. The toplevel .vhd file specifies the <g_design_name> for the revision in the generics. 
     
        Arguments:
        - lib_names      : one or more HDL libraries
     """
     if lib_names == None: lib_names = self.lib_names
     lib_dicts = self.libs.get_dicts(key='hdl_lib_name', values=lib_names)
     syn_dicts = self.libs.get_dicts(key='synth_top_level_entity',
                                     values=None,
                                     dicts=lib_dicts)
     for syn_dict in cm.listify(syn_dicts):
         # Open qpf for each HDL library that has a synth_top_level_entity
         lib_name = syn_dict['hdl_lib_name']
         qpf_name = lib_name + '.qpf'
         qpf_path = self.get_lib_build_dirs('synth', lib_dicts=syn_dict)
         cm.mkdir(qpf_path)
         qpfPathName = cm.expand_file_path_name(qpf_name, qpf_path)
         with open(qpfPathName, 'w') as fp:
             fp.write('PROJECT_REVISION = "%s"\n' % lib_name)
 def create_quartus_project_file(self, lib_names=None):
     """Create the Quartus project file (QPF) for all HDL libraries that have a toplevel entity key synth_top_level_entity.
     
        Note:
        . Default if the synth_top_level_entity key is defined but left empty then the top level entity has the same name as the lib_name in hdl_lib_name.
          Otherwise synth_top_level_entity can specify another top level entity name in the library. Each HDL library can only have one Quartus project
          file
        . The project revision has the same name as the lib_name and will result in a <lib_name>.sof FPGA image file. 
        . For each additional revision a subdirectory can be used. 
          This subdirectory can be named 'revisions/' and lists a number of revisions as subdirectories. Each revision will have a separate hdllib.cfg file and a 
          .vhd file with the toplevel entity. The toplevel .vhd file specifies the <g_design_name> for the revision in the generics. 
     
        Arguments:
        - lib_names      : one or more HDL libraries
     """
     if lib_names==None: lib_names=self.lib_names
     lib_dicts = self.libs.get_dicts(key='hdl_lib_name', values=lib_names)
     syn_dicts = self.libs.get_dicts(key='synth_top_level_entity', values=None, dicts=lib_dicts)
     for syn_dict in cm.listify(syn_dicts):
         # Open qpf for each HDL library that has a synth_top_level_entity
         lib_name = syn_dict['hdl_lib_name']
         qpf_name = lib_name + '.qpf'
         qpf_path = self.get_lib_build_dirs('synth', lib_dicts=syn_dict)
         cm.mkdir(qpf_path)
         qpfPathName = cm.expand_file_path_name(qpf_name, qpf_path)
         with open(qpfPathName, 'w') as fp:
             fp.write('PROJECT_REVISION = "%s"\n' % lib_name)
    def create_quartus_settings_file(self, lib_names=None):
        """Create the Quartus settings file (QSF) for all HDL libraries that have a toplevel entity key synth_top_level_entity.
        
           Note:
           . No support for revisions, so only one qsf per qpf
           
           Arguments:
           - lib_names      : one or more HDL libraries
        """
        if lib_names==None: lib_names=self.lib_names
        lib_dicts = self.libs.get_dicts(key='hdl_lib_name', values=lib_names)
        syn_dicts = self.libs.get_dicts(key='synth_top_level_entity', values=None, dicts=lib_dicts)
        for syn_dict in cm.listify(syn_dicts):
            # Open qsf for each HDL library that has a synth_top_level_entity
            lib_name = syn_dict['hdl_lib_name']
            lib_path = self.libs.get_filePath(syn_dict)
            top_level_entity = syn_dict['synth_top_level_entity']
            if top_level_entity=='':
                top_level_entity = lib_name
            qsf_path = self.get_lib_build_dirs('synth', lib_dicts=syn_dict)
            cm.mkdir(qsf_path)

            # One qsf per lib_name
            qsf_name = lib_name + '.qsf'
            qsfPathName = cm.expand_file_path_name(qsf_name, qsf_path)
            with open(qsfPathName, 'w') as fp:
                fp.write('# synth_top_level_entity\n')
                fp.write('set_global_assignment -name TOP_LEVEL_ENTITY %s\n' % top_level_entity)

                fp.write('\n')
                fp.write('# quartus_qsf_files\n')
                quartus_qsf_files = syn_dict['quartus_qsf_files'].split()
                for fn in quartus_qsf_files:
                    filePathName = cm.expand_file_path_name(fn, lib_path)
                    fp.write('set_global_assignment -name SOURCE_TCL_SCRIPT_FILE %s\n' % filePathName)

                fp.write('\n')
                fp.write('# All used HDL library *_lib.qip files in order with top level last\n')
                use_lib_names = self.derive_all_use_libs('synth', lib_name)
                use_lib_order = self.derive_lib_order('synth', use_lib_names)
                #use_lib_dicts = self.libs.get_dicts('hdl_lib_name', values=use_lib_order)    # uses original libs.dicts order, but
                use_lib_dicts = self.get_lib_dicts_from_lib_names(lib_names=use_lib_order)    # must preserve use_lib_order order to ensure that top level design qip with sdc file is include last in qsf
                for lib_dict in cm.listify(use_lib_dicts):
                    qip_path = self.get_lib_build_dirs('synth', lib_dicts=lib_dict)
                    qip_name = lib_dict['hdl_lib_name'] + '_lib.qip'
                    qipPathName = cm.expand_file_path_name(qip_name, qip_path)
                    fp.write('set_global_assignment -name QIP_FILE %s\n' % qipPathName)
    def __init__(self, mmmRootDir = os.environ['RADIOHDL'], mmmFileName='', mmmLibraryName=''):
        """
        """
        self.mmmRootDir         = mmmRootDir
        self.mmmFileName        = mmmFileName
        self.mmmLibraryName     = mmmLibraryName
        self.peripherals        = []
        self.input_clks         = []
        self.board_select       = 'unb1' 
        self.designName         = ''
        self.mmmName            = ''
        self.VhdlOutputPath     = ''
        self.VhdlFileName       = ''
        self.QsysName           = ''
        self.QsysFileName       = ''
        self.custom_peripherals = []  
        self.board_peripherals  = []
        
        # mmm config from files
        if self.mmmFileName != '':
            self.mmm = common_dict_file.CommonDictFile(mmmRootDir, mmmFileName)        # library dict files
            if self.mmm.nof_dicts==0: sys.exit('Error : No mmm config file found')
            if self.mmmLibraryName=='': sys.exit('Error: No mmmLibraryName specified');
            
            for d in self.mmm.dicts:
                name = self.mmm.get_key_value('mmm_name', d)
                if name == mmmLibraryName:
                    self.mmm.remove_all_but_the_dict_from_list(d)     
                    
            self.designName              = self.mmm.get_key_values('mmm_name')
            self.mmmName                 = "mmm_" + self.mmm.get_key_values('mmm_name')
            self.VhdlOutputPath          = cm.expand_file_path_name(self.mmm.get_key_values('vhdl_output_path'), self.mmm.filePaths[0])
            self.VhdlFileName            = self.mmmName + '.vhd'
            self.QsysName                = "qsys_" + self.designName
            self.QsysFileName            = self.QsysName + '.vhd'
            self.input_clks              = self.mmm.get_key_values('input_clks') 
            self.custom_peripherals_temp = self.mmm.get_key_values('custom_peripherals').split() 
            self.custom_peripherals      = self.chunks(self.custom_peripherals_temp, 3)
            self.board_select            = self.mmm.get_key_values('board_select')    

            if self.board_select == 'unb1':
                self.board_peripherals_path = mmmRootDir + "/boards/uniboard1/libraries/unb1_board/unb1_board_peripherals.cfg"
            elif self.board_select == 'unb2':
                self.board_peripherals_path = mmmRootDir + "/boards/uniboard2/libraries/unb2_board/unb2_board_peripherals.cfg"
            
            self.board_peripherals_dict = self.mmm.read_dict_file(self.board_peripherals_path , ' ')
            self.board_peripherals      = self.chunks(self.mmm.get_key_values('board_peripherals', dicts=self.board_peripherals_dict).split(), 3)
            
        self.peripherals            = self.board_peripherals + self.custom_peripherals
    def create_modelsim_project_file(self, lib_names=None):
        """Create the Modelsim project file for all technology libraries and RTL HDL libraries.

           Arguments:
           - lib_names       : one or more HDL libraries

           Library mapping:
           - Technology libraries that are available, but not used are mapped to work.
           - Unavailable libraries are also mapped to work. The default library clause name is <lib_name> with postfix '_lib'. This is a best
             effort guess, because it is impossible to know the library clause name for an unavailable library. If the best effort guess is
             not suitable, then the workaround is to create a place holder directory with hdllib.cfg that defines the actual library clause
             name as it appears in the VHDL for the unavailable HDL library. unavailable library names occur when e.g. a technology IP library
             is not available in the toolRootDir because it is not needed, or it may indicate a spelling error.
        """
        if lib_names == None: lib_names = self.lib_names
        lib_dicts = self.libs.get_dicts('hdl_lib_name', lib_names)
        for lib_dict in cm.listify(lib_dicts):
            # Open mpf
            lib_name = lib_dict['hdl_lib_name']
            mpf_name = lib_name + '.mpf'
            mpf_path = self.get_lib_build_dirs('sim', lib_dicts=lib_dict)
            cm.mkdir(mpf_path)
            mpfPathName = os.path.normpath(os.path.join(mpf_path, mpf_name))
            with open(mpfPathName, 'w') as fp:
                # Write [Library] section for all used libraries
                fp.write('[Library]\n')

                # . map used vendor technology libs to their target directory
                for technologyName in self.technologyNames:
                    tech_dict = self.read_hdl_libraries_technology_file(
                        technologyName, 'tool_name_sim')

                    for lib_clause, lib_work in tech_dict.items():
                        if type(lib_work) is str:
                            lib_work = cm.expand_file_path_name(lib_work)

                        fp.write('%s = %s\n' % (lib_clause, lib_work))
                # . not used vendor technology libs are not compiled but are mapped to work to avoid compile error when mentioned in the LIBRARY clause


#                for tech_dict in self.removed_dicts:
#                    fp.write('%s = work\n' % tech_dict['hdl_library_clause_name'])
# . unavailable used libs are not compiled but are mapped to work to avoid compile error when mentioned in the LIBRARY clause
                for unavailable_use_name in self.unavailable_use_libs:
                    # if the unavailable library is not in the dictionary of disclosed unavailable library clause names, then assume that the library clause
                    # name has the default postfix '_lib'.
                    if unavailable_use_name in self.disclosed_library_clause_names:
                        fp.write('%s = work\n' %
                                 self.disclosed_library_clause_names[
                                     unavailable_use_name])
                    else:
                        fp.write('%s_lib = work\n' % unavailable_use_name)
                # . all used libs for this lib_name
                use_lib_names = self.derive_all_use_libs('sim', lib_name)
                use_lib_dicts = self.libs.get_dicts('hdl_lib_name',
                                                    use_lib_names)
                use_lib_build_sim_dirs = self.get_lib_build_dirs(
                    'sim', lib_dicts=use_lib_dicts)
                use_lib_clause_names = self.libs.get_key_values(
                    'hdl_library_clause_name', use_lib_dicts)
                for lib_clause, lib_dir in zip(
                        cm.listify(use_lib_clause_names),
                        cm.listify(use_lib_build_sim_dirs)):
                    lib_work = os.path.normpath(os.path.join(lib_dir, 'work'))
                    fp.write('%s = %s\n' % (lib_clause, lib_work))
                # . work
                fp.write('work = work\n')
                # . others modelsim default libs
                model_tech_dir = os.path.expandvars(
                    self.tool_dict['model_tech_dir'])
                fp.write('others = %s\n' % os.path.normpath(
                    os.path.join(model_tech_dir, 'modelsim.ini')))

                # Write [Project] section for all used libraries
                fp.write('[Project]\n')
                fp.write('Project_Version = 6\n')  # must be >= 6 to fit all
                fp.write('Project_DefaultLib = work\n')
                fp.write('Project_SortMethod = unused\n')

                # - project files
                try:
                    synth_files = lib_dict['synth_files'].split()
                except KeyError:
                    synth_files = []

                try:
                    test_bench_files = lib_dict['test_bench_files'].split()
                except KeyError:
                    test_bench_files = []

                project_files = synth_files + test_bench_files
                if 'modelsim_compile_ip_files' in lib_dict:
                    compile_ip_files = lib_dict[
                        'modelsim_compile_ip_files'].split()
                    project_files += compile_ip_files
                fp.write('Project_Files_Count = %d\n' % len(project_files))
                lib_path = self.libs.get_filePath(lib_dict)

                project_file_p_defaults_hdl = 'vhdl_novitalcheck 0 group_id 0 cover_nofec 0 vhdl_nodebug 0 vhdl_1164 1 vhdl_noload 0 vhdl_synth 0 vhdl_enable0In 0 vlog_1995compat 0 last_compile 0 vhdl_disableopt 0 cover_excludedefault 0 vhdl_vital 0 vhdl_warn1 1 vhdl_warn2 1 vhdl_explicit 1 vhdl_showsource 0 cover_covercells 0 vhdl_0InOptions {} vhdl_warn3 1 vlog_vopt {} cover_optlevel 3 voptflow 1 vhdl_options {} vhdl_warn4 1 toggle - ood 0 vhdl_warn5 1 cover_noshort 0 compile_to work cover_nosub 0 dont_compile 0 vhdl_use93 2008 cover_stmt 1'
                project_file_p_defaults_vhdl = 'file_type vhdl'
                project_file_p_defaults_verilog = 'file_type verilog'
                project_file_p_defaults_systemverilog = 'file_type systemverilog'
                project_file_p_defaults_tcl = 'last_compile 0 compile_order -1 file_type tcl group_id 0 dont_compile 1 ood 1'

                project_folders = []
                offset = 0

                nof_synth_files = len(synth_files)

                #                for i, fn in enumerate(project_files):
                #                    filePathName = cm.expand_file_path_name(fn, lib_path)
                #                    fp.write('Project_File_%d = %s\n' % (i, filePathName))

                if nof_synth_files > 0:
                    project_folders.append('synth_files')
                    for i in range(nof_synth_files):

                        # Add file type specific settings
                        file_ext = synth_files[i].split('.')[-1]
                        if file_ext == 'vhd' or file_ext == 'vhdl':
                            project_file_p_defaults_file_specific = project_file_p_defaults_vhdl
                        elif file_ext == 'v':
                            project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        elif file_ext == 'vh':
                            project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        elif file_ext == 'sv':
                            project_file_p_defaults_file_specific = project_file_p_defaults_systemverilog
                        else:
                            print(
                                "\nERROR - Undefined file extension in synth_files:",
                                lib_name, synth_files[i])
                            sys.exit()

                        # Prepend the library path if a relative path
                        if synth_files[i].find(":") == -1:
                            filePathName = cm.expand_file_path_name(
                                synth_files[i], lib_path)
                        else:
                            filePathName = synth_files[i]
                        fp.write('Project_File_%d = %s\n' % (i, filePathName))
                        fp.write(
                            'Project_File_P_%d = folder %s compile_order %d %s\n'
                            % (offset + i, project_folders[-1], offset + i,
                               project_file_p_defaults_hdl + ' ' +
                               project_file_p_defaults_file_specific))

                offset = nof_synth_files

                nof_test_bench_files = len(test_bench_files)
                if nof_test_bench_files > 0:
                    project_folders.append('test_bench_files')
                    for i in range(nof_test_bench_files):

                        # Add file type specific settings
                        file_ext = test_bench_files[i].split('.')[-1]
                        if file_ext == 'vhd' or file_ext == 'vho' or file_ext == 'vhdl':
                            project_file_p_defaults_file_specific = project_file_p_defaults_vhdl
                        elif file_ext == 'v':
                            project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        elif file_ext == 'vh':
                            project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        elif file_ext == 'sv':
                            project_file_p_defaults_file_specific = project_file_p_defaults_systemverilog
                        else:
                            print(
                                "\nERROR - Undefined file extension in test_bench_files:",
                                lib_name, test_bench_files[i])
                            sys.exit()

                        filePathName = cm.expand_file_path_name(
                            test_bench_files[i], lib_path)
                        fp.write('Project_File_%d = %s\n' %
                                 (offset + i, filePathName))
                        fp.write(
                            'Project_File_P_%d = folder %s compile_order %d %s\n'
                            % (offset + i, project_folders[-1], offset + i,
                               project_file_p_defaults_hdl + ' ' +
                               project_file_p_defaults_file_specific))
                offset += nof_test_bench_files

                if 'modelsim_compile_ip_files' in lib_dict:
                    nof_compile_ip_files = len(compile_ip_files)
                    if nof_compile_ip_files > 0:
                        project_folders.append('compile_ip_files')
                        for i in range(nof_compile_ip_files):
                            filePathName = cm.expand_file_path_name(
                                compile_ip_files[i], lib_path)
                            fp.write('Project_File_%d = %s\n' %
                                     (offset + i, filePathName))
                            fp.write(
                                'Project_File_P_%d = folder %s compile_order %d %s\n'
                                % (offset + i, project_folders[-1], offset + i,
                                   project_file_p_defaults_tcl))
                    offset += nof_compile_ip_files

                # - project folders
                fp.write('Project_Folder_Count = %d\n' % len(project_folders))
                for i, fd in enumerate(project_folders):
                    fp.write('Project_Folder_%d = %s\n' % (i, fd))
                    fp.write('Project_Folder_P_%d = folder {Top Level}\n' % i)

                # - simulation configurations
                fp.write('Project_Sim_Count = %d\n' % len(test_bench_files))
                project_sim_p_defaults, project_sim_p_search_libraries, project_sim_p_otherargs, project_sim_p_optimization = self.simulation_configuration(
                )
                for i, fn in enumerate(test_bench_files):
                    fName = os.path.basename(fn)
                    tbName = os.path.splitext(fName)[0]
                    fp.write('Project_Sim_%d = %s\n' % (i, tbName))
                for i, fn in enumerate(test_bench_files):
                    fName = os.path.basename(fn)
                    tbName = os.path.splitext(fName)[0]

                    #if project_sim_p_search_libraries.find("xpm") != -1: tbName += " xpm.glbl"

                    fp.write(
                        'Project_Sim_P_%d = folder {Top Level} additional_dus { work.%s } %s %s %s %s\n'
                        %
                        (i, tbName, project_sim_p_defaults,
                         project_sim_p_search_libraries,
                         project_sim_p_otherargs, project_sim_p_optimization))

                # Write [vsim] section
                fp.write('[vsim]\n')
                fp.write('RunLength = 0 ps\n')
                fp.write('resolution = 1fs\n')
                fp.write(
                    'IterationLimit = 5000\n'
                )  # According to 'verror 3601' the default is 5000, typically 100 is enough, but e.g. the ip_stratixiv_phy_xaui_0 requires more.
                fp.write('DefaultRadix = hexadecimal\n')
                fp.write('NumericStdNoWarnings = 1\n')
                fp.write('StdArithNoWarnings = 1\n')
    def create_modelsim_project_file(self, lib_names=None):
        """Create the Modelsim project file for all technology libraries and RTL HDL libraries.
        
           Arguments:
           - lib_names       : one or more HDL libraries
        """
        if lib_names==None: lib_names=self.lib_names
        lib_dicts = self.libs.get_dicts('hdl_lib_name', lib_names)
        for lib_dict in cm.listify(lib_dicts):
            # Open mpf
            lib_name = lib_dict['hdl_lib_name']
            mpf_name = lib_name + '.mpf'
            mpf_path = self.get_lib_build_dirs('sim', lib_dicts=lib_dict)
            cm.mkdir(mpf_path)
            mpfPathName = os.path.join(mpf_path, mpf_name)
            with open(mpfPathName, 'w') as fp:
                # Write [Library] section for all used libraries
                fp.write('[Library]\n')
                # . map used vendor technology libs to their target directory
                for technologyName in cm.listify(self.technologyNames):
                    tech_dict = self.read_hdl_libraries_technology_file(technologyName)
                    for lib_clause, lib_work in tech_dict.iteritems():
                        fp.write('%s = %s\n' % (lib_clause, lib_work))
                # . not used vendor technology libs are not compiled but are mapped to work to avoid compile error when mentioned in the LIBRARY clause
                for tech_dict in self.removed_dicts:
                    fp.write('%s = work\n' % tech_dict['hdl_library_clause_name'])
                # . all used libs for this lib_name
                use_lib_names = self.derive_all_use_libs('sim', lib_name)
                use_lib_dicts = self.libs.get_dicts('hdl_lib_name', use_lib_names)
                use_lib_build_sim_dirs = self.get_lib_build_dirs('sim', lib_dicts=use_lib_dicts)
                use_lib_clause_names = self.libs.get_key_values('hdl_library_clause_name', use_lib_dicts)
                for lib_clause, lib_dir in zip(cm.listify(use_lib_clause_names), cm.listify(use_lib_build_sim_dirs)):
                    lib_work = os.path.join(lib_dir, 'work')
                    fp.write('%s = %s\n' % (lib_clause, lib_work))
                # . work
                fp.write('work = work\n')
                # . others modelsim default libs
                model_tech_dir = os.path.expandvars(self.tool_dict['model_tech_dir'])
                fp.write('others = %s\n' % os.path.join(model_tech_dir, 'modelsim.ini'))
                
                # Write [Project] section for all used libraries
                fp.write('[Project]\n')
                fp.write('Project_Version = 6\n')  # must be >= 6 to fit all
                fp.write('Project_DefaultLib = work\n')
                fp.write('Project_SortMethod = unused\n')
                
                # - project files
                synth_files = lib_dict['synth_files'].split()
                test_bench_files = lib_dict['test_bench_files'].split()
                project_files = synth_files + test_bench_files
                if 'modelsim_compile_ip_files' in lib_dict:
                    compile_ip_files = lib_dict['modelsim_compile_ip_files'].split()
                    project_files += compile_ip_files
                fp.write('Project_Files_Count = %d\n' % len(project_files))
                lib_path = self.libs.get_filePath(lib_dict)
                for i, fn in enumerate(project_files):
                    filePathName = cm.expand_file_path_name(fn, lib_path)
                    fp.write('Project_File_%d = %s\n' % (i, filePathName))

                project_file_p_defaults_hdl     = 'vhdl_novitalcheck 0 group_id 0 cover_nofec 0 vhdl_nodebug 0 vhdl_1164 1 vhdl_noload 0 vhdl_synth 0 vhdl_enable0In 0 vlog_1995compat 0 last_compile 0 vhdl_disableopt 0 cover_excludedefault 0 vhdl_vital 0 vhdl_warn1 1 vhdl_warn2 1 vhdl_explicit 1 vhdl_showsource 0 cover_covercells 0 vhdl_0InOptions {} vhdl_warn3 1 vlog_vopt {} cover_optlevel 3 voptflow 1 vhdl_options {} vhdl_warn4 1 toggle - ood 0 vhdl_warn5 1 cover_noshort 0 compile_to work cover_nosub 0 dont_compile 0 vhdl_use93 2002 cover_stmt 1'
                project_file_p_defaults_vhdl    = 'file_type vhdl'
                project_file_p_defaults_verilog = 'file_type verilog'
                project_file_p_defaults_tcl     = 'last_compile 0 compile_order -1 file_type tcl group_id 0 dont_compile 1 ood 1'

                project_folders = []
                offset = 0

                nof_synth_files = len(synth_files)
                if nof_synth_files>0:
                    project_folders.append('synth_files')
                    for i in range(nof_synth_files):  

                        # Add file type specific settings
                        file_ext = synth_files[i].split('.')[-1]
                        if file_ext=='vhd' or file_ext=='vhdl':
                            project_file_p_defaults_file_specific = project_file_p_defaults_vhdl
                        elif file_ext=='v':
                             project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        else:
                             print '\nERROR - Undefined file extension in synth_files:', synth_files[i]
                             sys.exit()

                        fp.write('Project_File_P_%d = folder %s compile_order %d %s\n' % (offset+i, project_folders[-1], offset+i, project_file_p_defaults_hdl+' '+project_file_p_defaults_file_specific))
                offset = nof_synth_files

                nof_test_bench_files = len(test_bench_files)
                if nof_test_bench_files>0:
                    project_folders.append('test_bench_files')
                    for i in range(nof_test_bench_files):

                        # Add file type specific settings
                        file_ext = test_bench_files[i].split('.')[-1]
                        if file_ext=='vhd' or file_ext=='vho' or file_ext=='vhdl':
                            project_file_p_defaults_file_specific = project_file_p_defaults_vhdl
                        elif file_ext=='v':
                             project_file_p_defaults_file_specific = project_file_p_defaults_verilog
                        else:
                             print '\nERROR - Undefined file extension in test_bench_files:', test_bench_files[i]
                             sys.exit()

                        fp.write('Project_File_P_%d = folder %s compile_order %d %s\n' % (offset+i, project_folders[-1], offset+i, project_file_p_defaults_hdl+' '+project_file_p_defaults_file_specific))
                offset += nof_test_bench_files

                if 'modelsim_compile_ip_files' in lib_dict:
                    nof_compile_ip_files = len(compile_ip_files)
                    if nof_compile_ip_files>0:
                        project_folders.append('compile_ip_files')
                        for i in range(nof_compile_ip_files):
                            fp.write('Project_File_P_%d = folder %s compile_order %d %s\n' % (offset+i, project_folders[-1], offset+i, project_file_p_defaults_tcl))
                    offset += nof_compile_ip_files
                        
                # - project folders
                fp.write('Project_Folder_Count = %d\n' % len(project_folders))
                for i, fd in enumerate(project_folders):
                    fp.write('Project_Folder_%d = %s\n' % (i, fd))
                    fp.write('Project_Folder_P_%d = folder {Top Level}\n' % i)
                    
                # - simulation configurations
                fp.write('Project_Sim_Count = %d\n' % len(test_bench_files))
                project_sim_p_defaults = 'Generics {} timing default -std_output {} -nopsl 0 +notimingchecks 0 selected_du {} -hazards 0 -sdf {} ok 1 -0in 0 -nosva 0 +pulse_r {} -absentisempty 0 -multisource_delay {} +pulse_e {} vopt_env 1 -coverage 0 -sdfnoerror 0 +plusarg {} -vital2.2b 0 -t default -memprof 0 is_vopt_flow 0 -noglitch 0 -nofileshare 0 -wlf {} -assertdebug 0 +no_pulse_msg 0 -0in_options {} -assertfile {} -sdfnowarn 0 -Lf {} -std_input {}'
                project_sim_p_search_libraries = '-L {}'
                if 'modelsim_search_libraries' in self.tool_dict:
                    project_sim_p_search_libraries = '-L {'
                    for sl in self.tool_dict['modelsim_search_libraries'].split():
                        project_sim_p_search_libraries += sl
                        project_sim_p_search_libraries += ' '
                    project_sim_p_search_libraries += '}'
                project_sim_p_otherargs = 'OtherArgs {}'
                project_sim_p_otherargs = 'OtherArgs {+nowarn8684 +nowarn8683 -quiet}'
                project_sim_p_otherargs = 'OtherArgs {+nowarn8684 +nowarn8683}'
                project_sim_p_otherargs = 'OtherArgs {+nowarn8684 +nowarn8683 +nowarnTFMPC +nowarnPCDPC}'  # nowarn on verilog IP connection mismatch warnings
                project_sim_p_optimization = 'is_vopt_opt_used 2'  # = when 'Enable optimization' is not selected in GUI
                project_sim_p_optimization = 'is_vopt_opt_used 1 voptargs {OtherVoptArgs {} timing default VoptOutFile {} -vopt_keep_delta 0 -0in 0 -fvopt {} VoptOptimize:method 1 -vopt_00 2 +vopt_notimingcheck 0 -Lfvopt {} VoptOptimize:list .vopt_opt.nb.canvas.notebook.cs.page1.cs.g.spec.listbox -Lvopt {} +vopt_acc {} VoptOptimize .vopt_opt.nb.canvas.notebook.cs.page1.cs -vopt_hazards 0 VoptOptimize:Buttons .vopt_opt.nb.canvas.notebook.cs.page1.cs.g.spec.bf 0InOptionsWgt .vopt_opt.nb.canvas.notebook.cs.page3.cs.zf.ze -0in_options {}}' # = when 'Enable optimization' is selected in GUI for full visibility
                for i, fn in enumerate(test_bench_files):
                    fName = os.path.basename(fn)
                    tbName = os.path.splitext(fName)[0]
                    fp.write('Project_Sim_%d = %s\n' % (i, tbName))
                for i, fn in enumerate(test_bench_files):
                    fName = os.path.basename(fn)
                    tbName = os.path.splitext(fName)[0]
                    fp.write('Project_Sim_P_%d = folder {Top Level} additional_dus work.%s %s %s %s %s\n' % (i, tbName, project_sim_p_defaults, project_sim_p_search_libraries, project_sim_p_otherargs, project_sim_p_optimization))
                    
                # Write [vsim] section
                fp.write('[vsim]\n')
                fp.write('RunLength = 0 ps\n')
                fp.write('resolution = 1fs\n')
                fp.write('IterationLimit = 5000\n')       # According to 'verror 3601' the default is 5000, typically 100 is enough, but e.g. the ip_stratixiv_phy_xaui_0 requires more.
                fp.write('DefaultRadix = decimal\n')
    def create_quartus_ip_lib_file(self, lib_names=None):
        """Create the Quartus IP file <hdl_lib_name>_lib.qip for all HDL libraries. The <hdl_lib_name>.qip file contains the list of files that are given
           by the synth_files key and the quartus_*_file keys.
           
           Note:
           . Use post fix '_lib' in QIP file name *_lib.qip to avoid potential conflict with *.qip that may come with the IP.
           . The HDL library *_lib.qip files contain all files that are listed by the synth_files key. Hence when these qip files are included then
             the Quartus project will analyse all files even if there entity is not instantiated in the design. This is fine, it is unnecessary
             to parse the hierarchy of the synth_top_level_entity VHDL file to find and include only the source files that are actually used.
        
           Arguments:
           - lib_names      : one or more HDL libraries
        """
        if lib_names == None: lib_names = self.lib_names
        lib_dicts = self.libs.get_dicts('hdl_lib_name', values=lib_names)
        for lib_dict in cm.listify(lib_dicts):
            # Open qip
            lib_name = lib_dict['hdl_lib_name']
            lib_path = self.libs.get_filePath(lib_dict)
            qip_name = lib_name + '_lib.qip'
            qip_path = self.get_lib_build_dirs('synth', lib_dicts=lib_dict)
            cm.mkdir(qip_path)
            qipPathName = cm.expand_file_path_name(qip_name, qip_path)
            with open(qipPathName, 'w') as fp:
                if 'synth_files' in lib_dict:
                    fp.write('# synth_files\n')
                    synth_files = lib_dict['synth_files'].split()
                    for fn in synth_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)

                        file_ext = fn.split('.')[-1]
                        if file_ext == 'vhd' or file_ext == 'vhdl':
                            file_type = 'VHDL_FILE'
                        elif file_ext == 'v':
                            file_type = 'VERILOG_FILE'
                        else:
                            print '\nERROR - Undefined file extension in synth_files:', fn
                            sys.exit()

                        fp.write(
                            'set_global_assignment -name %s %s -library %s\n' %
                            (file_type, filePathName, lib_name + '_lib'))

                if 'quartus_vhdl_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_vhdl_files\n')
                    quartus_vhdl_files = lib_dict['quartus_vhdl_files'].split()
                    for fn in quartus_vhdl_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)

                        file_ext = fn.split('.')[-1]
                        if file_ext == 'vhd' or file_ext == 'vhdl':
                            file_type = 'VHDL_FILE'
                        elif file_ext == 'v':
                            file_type = 'VERILOG_FILE'
                        else:
                            print '\nERROR - Undefined file extension in quartus_vhdl_files:', fn
                            sys.exit()

                        fp.write(
                            'set_global_assignment -name VHDL_FILE %s -library %s\n'
                            % (filePathName, lib_name + '_lib'))

                if 'quartus_qip_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_qip_files\n')
                    quartus_qip_files = lib_dict['quartus_qip_files'].split()
                    for fn in quartus_qip_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write('set_global_assignment -name QIP_FILE %s\n' %
                                 filePathName)

                if 'quartus_tcl_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_tcl_files\n')
                    quartus_tcl_files = lib_dict['quartus_tcl_files'].split()
                    for fn in quartus_tcl_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write(
                            'set_global_assignment -name SOURCE_TCL_SCRIPT_FILE %s\n'
                            % filePathName)

                if 'quartus_sdc_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_sdc_files\n')
                    quartus_sdc_files = lib_dict['quartus_sdc_files'].split()
                    for fn in quartus_sdc_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write('set_global_assignment -name SDC_FILE %s\n' %
                                 filePathName)
    def create_quartus_ip_lib_file(self, lib_names=None):
        """Create the Quartus IP file <hdl_lib_name>_lib.qip for all HDL libraries. The <hdl_lib_name>.qip file contains the list of files that are given
           by the synth_files key and the quartus_*_file keys.
           
           Note:
           . Use post fix '_lib' in QIP file name *_lib.qip to avoid potential conflict with *.qip that may come with the IP.
           . The HDL library *_lib.qip files contain all files that are listed by the synth_files key. Hence when these qip files are included then
             the Quartus project will analyse all files even if there entity is not instantiated in the design. This is fine, it is unnecessary
             to parse the hierarchy of the synth_top_level_entity VHDL file to find and include only the source files that are actually used.
        
           Arguments:
           - lib_names      : one or more HDL libraries
        """
        if lib_names==None: lib_names=self.lib_names
        lib_dicts = self.libs.get_dicts('hdl_lib_name', values=lib_names)
        for lib_dict in cm.listify(lib_dicts):
            # Open qip
            lib_name = lib_dict['hdl_lib_name']
            lib_path = self.libs.get_filePath(lib_dict)
            qip_name = lib_name + '_lib.qip'
            qip_path = self.get_lib_build_dirs('synth', lib_dicts=lib_dict)
            cm.mkdir(qip_path)
            qipPathName = cm.expand_file_path_name(qip_name, qip_path)
            with open(qipPathName, 'w') as fp:
                if 'synth_files' in lib_dict:
                    fp.write('# synth_files\n')
                    synth_files = lib_dict['synth_files'].split()
                    for fn in synth_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)

                        file_ext = fn.split('.')[-1]
                        if file_ext=='vhd' or file_ext=='vhdl':
                            file_type = 'VHDL_FILE'                         
                        elif file_ext=='v':
                            file_type = 'VERILOG_FILE'                              
                        else:
                             print '\nERROR - Undefined file extension in synth_files:', fn
                             sys.exit()

                        fp.write('set_global_assignment -name %s %s -library %s\n' % (file_type, filePathName, lib_name + '_lib'))
    
                if 'quartus_vhdl_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_vhdl_files\n')
                    quartus_vhdl_files = lib_dict['quartus_vhdl_files'].split()
                    for fn in quartus_vhdl_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)

                        file_ext = fn.split('.')[-1]
                        if file_ext=='vhd' or file_ext=='vhdl':
                            file_type = 'VHDL_FILE'                         
                        elif file_ext=='v':
                            file_type = 'VERILOG_FILE'                              
                        else:
                             print '\nERROR - Undefined file extension in quartus_vhdl_files:', fn
                             sys.exit()

                        fp.write('set_global_assignment -name VHDL_FILE %s -library %s\n' % (filePathName, lib_name + '_lib'))
                    
                if 'quartus_qip_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_qip_files\n')
                    quartus_qip_files = lib_dict['quartus_qip_files'].split()
                    for fn in quartus_qip_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write('set_global_assignment -name QIP_FILE %s\n' % filePathName)

                if 'quartus_tcl_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_tcl_files\n')
                    quartus_tcl_files = lib_dict['quartus_tcl_files'].split()
                    for fn in quartus_tcl_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write('set_global_assignment -name SOURCE_TCL_SCRIPT_FILE %s\n' % filePathName)
                    
                if 'quartus_sdc_files' in lib_dict:
                    fp.write('\n')
                    fp.write('# quartus_sdc_files\n')
                    quartus_sdc_files = lib_dict['quartus_sdc_files'].split()
                    for fn in quartus_sdc_files:
                        filePathName = cm.expand_file_path_name(fn, lib_path)
                        fp.write('set_global_assignment -name SDC_FILE %s\n' % filePathName)