Remove useless while loops
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # This file is part of BeRTOS.
5 #
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19 #
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction.  Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License.  This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
28 #
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
30 #
31 # $Id$
32 #
33 # Author: Lorenzo Berni <duplo@develer.com>
34 #
35
36 import os
37 import fnmatch
38 import glob
39 import re
40 import shutil
41 # Use custom copytree function
42 import copytree
43 import relpath
44 import pickle
45
46 import const
47 import plugins
48 import DefineException
49
50 from _wizard_version import WIZARD_VERSION
51
52 from LoadException import VersionException, ToolchainException
53
54 def isBertosDir(directory):
55    return os.path.exists(directory + "/VERSION")
56
57 def bertosVersion(directory):
58    return open(directory + "/VERSION").readline().strip()
59
60 def enabledModules(project_info):
61     enabled_modules = []
62     for name, module in project_info.info("MODULES").items():
63         if module["enabled"]:
64             enabled_modules.append(name)
65     return enabled_modules
66
67 def presetList(directory):
68     """
69     Return the list of the preset found in the selected BeRTOS Version.
70     """
71     abspath = os.path.join(directory, const.PREDEFINED_BOARDS_DIR)
72     preset_list = dict([
73         (os.path.join(abspath, preset_dir), presetInfo(os.path.join(abspath, preset_dir)))
74         for preset_dir in os.listdir(os.path.join(directory, const.PREDEFINED_BOARDS_DIR))
75     ])
76     return preset_list
77
78 def presetInfo(preset_dir):
79     """
80     Return the preset-relevant info contined into the project_file.
81     """
82     preset_info = pickle.loads(open(os.path.join(preset_dir, "project.bertos"), "r").read())
83     try:
84         description = open(os.path.join(preset_dir, "description"), "r").read()
85     except IOError:
86         # No description file found.
87         description = ""
88     relevant_info = {
89         "CPU_NAME": preset_info.get("CPU_NAME"),
90         "SELECTED_FREQ": preset_info.get("SELECTED_FREQ"),
91         "WIZARD_VERSION": preset_info.get("WIZARD_VERSION", None),
92         "PRESET_NAME": preset_info.get("PROJECT_NAME"),
93         "PRESET_DESCRIPTION": description.decode("utf-8"),
94     }
95     return relevant_info
96
97 def mergeSources(srcdir, new_sources, old_sources):
98     # The current mergeSources function provide only a raw copy of the sources in the
99     # created project.
100     #
101     # TODO: implement the three way merge algorithm
102     #
103     shutil.rmtree(srcdir, True)
104     copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
105
106 def projectFileGenerator(project_info):
107     directory = project_info.info("PROJECT_PATH")
108     project_data = {}
109     enabled_modules = []
110     for module, information in project_info.info("MODULES").items():
111         if information["enabled"]:
112             enabled_modules.append(module)
113     project_data["ENABLED_MODULES"] = enabled_modules
114     if project_info.info("PRESET"):
115         # For presets save again the BERTOS_PATH into project file
116         project_data["PRESET"] = True
117         project_data["BERTOS_PATH"] = project_info.info("BERTOS_PATH")
118     else:
119         # Use the local BeRTOS version instead of the original one
120         # project_data["BERTOS_PATH"] = project_info.info("BERTOS_PATH")
121         project_data["BERTOS_PATH"] = directory
122     project_data["PROJECT_NAME"] = project_info.info("PROJECT_NAME", os.path.basename(directory))
123     project_src_relpath = relpath.relpath(project_info.info("PROJECT_SRC_PATH"), directory)
124     project_data["PROJECT_SRC_PATH"] = project_src_relpath
125     project_data["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
126     project_data["CPU_NAME"] = project_info.info("CPU_NAME")
127     project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
128     project_data["OUTPUT"] = project_info.info("OUTPUT")
129     project_data["WIZARD_VERSION"] = WIZARD_VERSION
130     project_data["PRESET"] = project_info.info("PRESET")
131     return pickle.dumps(project_data)
132
133 def loadPlugin(plugin):
134     """
135     Returns the given plugin module.
136     """
137     return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
138
139 def versionFileGenerator(project_info, version_file):
140     version = bertosVersion(project_info.info("BERTOS_PATH"))
141     return version_file.replace('$version', version)
142
143 def userMkGeneratorFromPreset(project_info):
144     project_name = project_info.info("PROJECT_NAME")
145     preset_path = project_info.info("PRESET_PATH")
146     preset_name = project_info.info("PRESET_NAME")
147     preset_src_dir = project_info.info("PRESET_SRC_PATH")
148     makefile = open(os.path.join(preset_path, preset_src_dir, "%s_user.mk" %preset_name), 'r').read()
149     destination = os.path.join(project_info.prjdir, "%s_user.mk" %project_info.info("PROJECT_NAME"))
150     # Temporary code.
151     # TODO: write it using regular expressions to secure this function
152     makefile = makefile.replace(preset_name + "_", project_name + "_")
153     open(destination, "w").write(makefile)
154
155 def userMkGenerator(project_info):
156     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template_user.mk"), "r").read()
157     destination = os.path.join(project_info.prjdir, os.path.basename(project_info.prjdir) + "_user.mk")
158     # Deadly performances loss was here :(
159     mk_data = {}
160     mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
161     mk_data["$ppath"] = relpath.relpath(project_info.info("PROJECT_SRC_PATH"), project_info.info("PROJECT_PATH"))
162     mk_data["$main"] = os.path.join("$(%s_SRC_PATH)" %project_info.info("PROJECT_NAME"), "main.c")
163     for key in mk_data:
164         makefile = makefile.replace(key, mk_data[key])
165     open(destination, "w").write(makefile)
166
167 def mkGenerator(project_info):
168     """
169     Generates the mk file for the current project.
170     """
171     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
172     destination = os.path.join(project_info.prjdir, os.path.basename(project_info.prjdir) + ".mk")
173     mk_data = {}
174     mk_data["$pname"] = project_info.info("PROJECT_NAME")
175     mk_data["$ppath"] = relpath.relpath(project_info.info("PROJECT_SRC_PATH"), project_info.info("PROJECT_PATH"))
176     mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
177     cpu_mk_parameters = []
178     for key, value in project_info.info("CPU_INFOS").items():
179         if key.startswith(const.MK_PARAM_ID):
180             cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
181     mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
182     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
183     mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
184     mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
185     for key in mk_data:
186         makefile = makefile.replace(key, mk_data[key])
187     open(destination, "w").write(makefile)
188
189 def makefileGenerator(project_info):
190     """
191     Generate the Makefile for the current project.
192     """
193     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), "r").read()
194     destination = os.path.join(project_info.maindir, "Makefile")
195     # TODO write a general function that works for both the mk file and the Makefile
196     mk_data = {}
197     mk_data["$pname"] = project_info.info("PROJECT_NAME")
198     mk_data["$ppath"] = os.path.basename(project_info.info("PROJECT_SRC_PATH"))
199     for key in mk_data:
200         makefile = makefile.replace(key, mk_data[key])
201     open(destination, "w").write(makefile)
202
203 def csrcGenerator(project_info):
204     modules = project_info.info("MODULES")
205     files = project_info.info("FILES")
206     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
207         harvard = True
208     else:
209         harvard = False
210     # file to be included in CSRC variable
211     csrc = []
212     # file to be included in PCSRC variable
213     pcsrc = []
214     # files to be included in CPPASRC variable
215     cppasrc = []
216     # files to be included in CXXSRC variable
217     cxxsrc = []
218     # files to be included in ASRC variable
219     asrc = []
220     # constants to be included at the beginning of the makefile
221     constants = {}
222     for module, information in modules.items():
223         module_files = set([])
224         dependency_files = set([])
225         # assembly sources
226         asm_files = set([])
227         hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw" 
228         if information["enabled"]:
229             if "constants" in information:
230                 constants.update(information["constants"])
231             cfiles, sfiles = findModuleFiles(module, project_info)
232             module_files |= set(cfiles)
233             asm_files |= set(sfiles)
234             for file in information["hw"]:
235                 if file.endswith(".c"):
236                     module_files |= set([hwdir + "/" + os.path.basename(file)])
237             for file_dependency in information["depends"] + tuple(files.keys()):
238                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
239                     dependency_files |= set(dependencyCFiles)
240                     asm_files |= set(dependencySFiles)
241             for file in module_files:
242                 if not harvard or information.get("harvard", "both") == "both":
243                     csrc.append(file)
244                 if harvard and "harvard" in information:
245                     pcsrc.append(file)
246             for file in dependency_files:
247                 csrc.append(file)
248             for file in project_info.info("CPU_INFOS")["C_SRC"]:
249                 csrc.append(file)
250             for file in project_info.info("CPU_INFOS")["PC_SRC"]:
251                 pcsrc.append(file)
252             for file in asm_files:
253                 cppasrc.append(file)
254     for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
255         cppasrc.append(file)
256     for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
257         cxxsrc.append(file)
258     for file in project_info.info("CPU_INFOS")["ASRC"]:
259         asrc.append(file)
260     csrc = set(csrc)
261     csrc = " \\\n\t".join(csrc) + " \\"
262     pcsrc = set(pcsrc)
263     pcsrc = " \\\n\t".join(pcsrc) + " \\"
264     cppasrc = set(cppasrc)
265     cppasrc = " \\\n\t".join(cppasrc) + " \\"
266     cxxsrc = set(cxxsrc)
267     cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
268     asrc = set(asrc)
269     asrc = " \\\n\t".join(asrc) + " \\"
270     constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
271     return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
272
273 def findModuleFiles(module, project_info):
274     # Find the files related to the selected module
275     cfiles = []
276     sfiles = []
277     # .c files related to the module and the cpu architecture
278     for filename, path in project_info.searchFiles(module + ".c"):
279         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
280         path = replaceSeparators(path)
281         cfiles.append(path + "/" + filename)
282     # .s files related to the module and the cpu architecture
283     for filename, path in project_info.searchFiles(module + ".s") + \
284             project_info.searchFiles(module + ".S"):
285         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
286         path = replaceSeparators(path)
287         sfiles.append(path + "/" + filename)
288     # .c and .s files related to the module and the cpu tags
289     tags = project_info.info("CPU_INFOS")["CPU_TAGS"]
290
291     # Awful, but secure check for version
292     # TODO: split me in a method/function
293     try:
294         version_string = bertosVersion(project_info.info("BERTOS_PATH"))
295         version_list = [int(i) for i in version_string.split()[-1].split('.')]
296     except ValueError:
297         # If the version file hasn't a valid version number assume it's an older
298         # project.
299         version_list = [0, 0]
300     if version_list < [2, 5]:
301         # For older versions of BeRTOS add the toolchain to the tags
302         tags.append(project_info.info("CPU_INFOS")["TOOLCHAIN"])
303
304     for tag in tags:
305         for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
306             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
307             if os.sep != "/":
308                 path = replaceSeparators(path)
309             cfiles.append(path + "/" + filename)
310         for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
311                 project_info.searchFiles(module + "_" + tag + ".S"):
312             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
313             path = replaceSeparators(path)
314             sfiles.append(path + "/" + filename)
315     return cfiles, sfiles
316
317 def replaceSeparators(path):
318     """
319     Replace the separators in the given path with unix standard separator.
320     """
321     if os.sep != "/":
322         path = path.replace(os.sep, "/")
323     return path
324
325 def getSystemPath():
326     path = os.environ["PATH"]
327     if os.name == "nt":
328         path = path.split(";")
329     else:
330         path = path.split(":")
331     return path
332
333 def findToolchains(path_list):
334     toolchains = []
335     for element in path_list:
336         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
337             toolchains.append(toolchain)
338     return list(set(toolchains))
339
340 def getToolchainInfo(output):
341     info = {}
342     expr = re.compile("Target: .*")
343     target = expr.findall(output)
344     if len(target) == 1:
345         info["target"] = target[0].split("Target: ")[1]
346     expr = re.compile("gcc version [0-9,.]*")
347     version = expr.findall(output)
348     if len(version) == 1:
349         info["version"] = version[0].split("gcc version ")[1]
350     expr = re.compile("gcc version [0-9,.]* \(.*\)")
351     build = expr.findall(output)
352     if len(build) == 1:
353         build = build[0].split("gcc version ")[1]
354         build = build[build.find("(") + 1 : build.find(")")]
355         info["build"] = build
356     expr = re.compile("Configured with: .*")
357     configured = expr.findall(output)
358     if len(configured) == 1:
359         info["configured"] = configured[0].split("Configured with: ")[1]
360     expr = re.compile("Thread model: .*")
361     thread = expr.findall(output)
362     if len(thread) == 1:
363         info["thread"] = thread[0].split("Thread model: ")[1]
364     return info
365
366 def getToolchainName(toolchain_info):
367     name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
368     return name
369
370 def getTagSet(cpu_info):
371     tag_set = set([])
372     for cpu in cpu_info:
373         tag_set |= set([cpu["CPU_NAME"]])
374         tag_set |= set(cpu["CPU_TAGS"])
375         tag_set |= set([cpu["TOOLCHAIN"]])
376     return tag_set
377         
378
379 def getInfos(definition):
380     D = {}
381     D.update(const.CPU_DEF)
382     def include(filename, dict = D, directory=definition[1]):
383         execfile(directory + "/" + filename, {}, D)
384     D["include"] = include
385     include(definition[0], D)
386     D["CPU_NAME"] = definition[0].split(".")[0]
387     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
388     del D["include"]
389     return D
390
391 def getCommentList(string):
392     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
393     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
394     return comment_list
395
396 def loadModuleDefinition(first_comment):
397     to_be_parsed = False
398     module_definition = {}
399     for num, line in enumerate(first_comment):
400         index = line.find("$WIZ$")
401         if index != -1:
402             to_be_parsed = True
403             try:
404                 exec line[index + len("$WIZ$ "):] in {}, module_definition
405             except:
406                 raise ParseError(num, line[index:])
407         elif line.find("\\brief") != -1:
408             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
409     module_dict = {}
410     if "module_name" in module_definition:
411         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
412         del module_definition[const.MODULE_DEFINITION["module_name"]]
413         module_dict[module_name] = {}
414         if const.MODULE_DEFINITION["module_depends"] in module_definition:
415             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
416             del module_definition[const.MODULE_DEFINITION["module_depends"]]
417             if type(depends) == str:
418                 depends = (depends,)
419             module_dict[module_name]["depends"] = depends
420         else:
421             module_dict[module_name]["depends"] = ()
422         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
423             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
424             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
425         else:
426             module_dict[module_name]["configuration"] = ""
427         if "module_description" in module_definition:
428             module_dict[module_name]["description"] = module_definition["module_description"]
429             del module_definition["module_description"]
430         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
431             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
432             module_dict[module_name]["harvard"] = harvard
433             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
434         if const.MODULE_DEFINITION["module_hw"] in module_definition:
435             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
436             del module_definition[const.MODULE_DEFINITION["module_hw"]]
437             if type(hw) == str:
438                 hw = (hw, )
439             module_dict[module_name]["hw"] = hw
440         else:
441             module_dict[module_name]["hw"] = ()
442         if const.MODULE_DEFINITION["module_supports"] in module_definition:
443             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
444             del module_definition[const.MODULE_DEFINITION["module_supports"]]
445             module_dict[module_name]["supports"] = supports
446         module_dict[module_name]["constants"] = module_definition
447         module_dict[module_name]["enabled"] = False
448     return to_be_parsed, module_dict
449
450 def isSupported(project, module=None, property_id=None):
451     if not module and property_id:
452         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
453     else:
454         item = project.info("MODULES")[module]
455     tag_dict = project.info("ALL_CPU_TAGS")
456     if "supports" in item:
457         support_string = item["supports"]
458         supported = {}
459         try:
460             exec "supported = " + support_string in tag_dict, supported
461         except:
462             raise SupportedException(support_string)
463         return supported["supported"]
464     else:
465         return True
466
467 def loadDefineLists(comment_list):
468     define_list = {}
469     for comment in comment_list:
470         for num, line in enumerate(comment):
471             index = line.find("$WIZ$")
472             if index != -1:
473                 try:
474                     exec line[index + len("$WIZ$ "):] in {}, define_list
475                 except:
476                     raise ParseError(num, line[index:])
477     for key, value in define_list.items():
478         if type(value) == str:
479             define_list[key] = (value,)
480     return define_list
481
482 def getDescriptionInformations(comment):
483     """
484     Take the doxygen comment and strip the wizard informations, returning the tuple
485     (comment, wizard_information)
486     """
487     brief = ""
488     description = ""
489     information = {}
490     for num, line in enumerate(comment):
491         index = line.find("$WIZ$")
492         if index != -1:
493             if len(brief) == 0:
494                 brief += line[:index].strip()
495             else:
496                 description += " " + line[:index]
497             try:
498                 exec line[index + len("$WIZ$ "):] in {}, information
499             except:
500                 raise ParseError(num, line[index:])
501         else:
502             if len(brief) == 0:
503                 brief += line.strip()
504             else:
505                 description += " " + line
506                 description = description.strip()
507     return brief.strip(), description.strip(), information
508
509 def getDefinitionBlocks(text):
510     """
511     Take a text and return a list of tuple (description, name-value).
512     """
513     block = []
514     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
515     for match in block_tmp:
516         # Only the first element is needed
517         comment = match.group(1)
518         define = match.group(2)
519         start = match.start()
520         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
521     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
522         comment = match.group(1)
523         define = match.group(2)
524         start = match.start()
525         block.append(([comment], define, start))
526     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
527         comment = match.group(2)
528         define = match.group(1)
529         start = match.start()
530         block.append(([comment], define, start))
531     return block
532
533 def formatParamNameValue(text):
534     """
535     Take the given string and return a tuple with the name of the parameter in the first position
536     and the value in the second.
537     """
538     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
539     return block[0]
540
541 def loadConfigurationInfos(path):
542     """
543     Return the module configurations found in the given file as a dict with the
544     parameter name as key and a dict containig the fields above as value:
545         "value": the value of the parameter
546         "description": the description of the parameter
547         "informations": a dict containig optional informations:
548             "type": "int" | "boolean" | "enum"
549             "min": the minimum value for integer parameters
550             "max": the maximum value for integer parameters
551             "long": boolean indicating if the num is a long
552             "unsigned": boolean indicating if the num is an unsigned
553             "value_list": the name of the enum for enum parameters
554             "conditional_deps": the list of conditional dependencies for boolean parameters
555     """
556     configuration_infos = {}
557     configuration_infos["paramlist"] = []
558     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
559         name, value = formatParamNameValue(define)
560         brief, description, informations = getDescriptionInformations(comment)
561         configuration_infos["paramlist"].append((start, name))
562         configuration_infos[name] = {}
563         configuration_infos[name]["value"] = value
564         configuration_infos[name]["informations"] = informations
565         if not "type" in configuration_infos[name]["informations"]:
566             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
567         if ("type" in configuration_infos[name]["informations"] and
568                 configuration_infos[name]["informations"]["type"] == "int" and
569                 configuration_infos[name]["value"].find("L") != -1):
570             configuration_infos[name]["informations"]["long"] = True
571             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
572         if ("type" in configuration_infos[name]["informations"] and
573                 configuration_infos[name]["informations"]["type"] == "int" and
574                 configuration_infos[name]["value"].find("U") != -1):
575             configuration_infos[name]["informations"]["unsigned"] = True
576             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
577         if "conditional_deps" in configuration_infos[name]["informations"]:
578             if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
579                     type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
580                 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
581             elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
582                 pass
583             else:
584                 configuration_infos[name]["informations"]["conditional_deps"] = ()
585         configuration_infos[name]["description"] = description
586         configuration_infos[name]["brief"] = brief
587     return configuration_infos
588
589 def updateConfigurationValues(def_conf, user_conf):
590     for param in def_conf["paramlist"]:
591         if param[1] in user_conf and "value" in user_conf[param[1]]:
592             def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
593     return def_conf
594
595 def findParameterType(parameter):
596     if "value_list" in parameter["informations"]:
597         return "enum"
598     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
599         return "int"
600
601 def sub(string, parameter, value):
602     """
603     Substitute the given value at the given parameter define in the given string
604     """
605     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
606
607 def isInt(informations):
608     """
609     Return True if the value is a simple int.
610     """
611     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
612         return True
613     else:
614         return False
615
616 def isLong(informations):
617     """
618     Return True if the value is a long.
619     """
620     if "long" in informations and informations["long"] and "unsigned" not in informations:
621         return True
622     else:
623         return False
624
625 def isUnsigned(informations):
626     """
627     Return True if the value is an unsigned.
628     """
629     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
630         return True
631     else:
632         return False
633
634 def isUnsignedLong(informations):
635     """
636     Return True if the value is an unsigned long.
637     """
638     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
639         return True
640     else:
641         return False
642
643 class ParseError(Exception):
644     def __init__(self, line_number, line):
645         Exception.__init__(self)
646         self.line_number = line_number
647         self.line = line
648
649 class SupportedException(Exception):
650     def __init__(self, support_string):
651         Exception.__init__(self)
652         self.support_string = support_string