Avoid recursion on string.replace()
[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         while makefile.find(key) != -1:
165             makefile = makefile.replace(key, mk_data[key])
166     open(destination, "w").write(makefile)
167
168 def mkGenerator(project_info):
169     """
170     Generates the mk file for the current project.
171     """
172     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
173     destination = os.path.join(project_info.prjdir, os.path.basename(project_info.prjdir) + ".mk")
174     mk_data = {}
175     mk_data["$pname"] = project_info.info("PROJECT_NAME")
176     mk_data["$ppath"] = relpath.relpath(project_info.info("PROJECT_SRC_PATH"), project_info.info("PROJECT_PATH"))
177     mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
178     cpu_mk_parameters = []
179     for key, value in project_info.info("CPU_INFOS").items():
180         if key.startswith(const.MK_PARAM_ID):
181             cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
182     mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
183     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
184     mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
185     mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
186     for key in mk_data:
187         while makefile.find(key) != -1:
188             makefile = makefile.replace(key, mk_data[key])
189     open(destination, "w").write(makefile)
190
191 def makefileGenerator(project_info):
192     """
193     Generate the Makefile for the current project.
194     """
195     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), "r").read()
196     destination = os.path.join(project_info.maindir, "Makefile")
197     # TODO write a general function that works for both the mk file and the Makefile
198     mk_data = {}
199     mk_data["$pname"] = project_info.info("PROJECT_NAME")
200     mk_data["$ppath"] = os.path.basename(project_info.info("PROJECT_SRC_PATH"))
201     for key in mk_data:
202         while makefile.find(key) != -1:
203             makefile = makefile.replace(key, mk_data[key])
204     open(destination, "w").write(makefile)
205
206 def csrcGenerator(project_info):
207     modules = project_info.info("MODULES")
208     files = project_info.info("FILES")
209     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
210         harvard = True
211     else:
212         harvard = False
213     # file to be included in CSRC variable
214     csrc = []
215     # file to be included in PCSRC variable
216     pcsrc = []
217     # files to be included in CPPASRC variable
218     cppasrc = []
219     # files to be included in CXXSRC variable
220     cxxsrc = []
221     # files to be included in ASRC variable
222     asrc = []
223     # constants to be included at the beginning of the makefile
224     constants = {}
225     for module, information in modules.items():
226         module_files = set([])
227         dependency_files = set([])
228         # assembly sources
229         asm_files = set([])
230         hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw" 
231         if information["enabled"]:
232             if "constants" in information:
233                 constants.update(information["constants"])
234             cfiles, sfiles = findModuleFiles(module, project_info)
235             module_files |= set(cfiles)
236             asm_files |= set(sfiles)
237             for file in information["hw"]:
238                 if file.endswith(".c"):
239                     module_files |= set([hwdir + "/" + os.path.basename(file)])
240             for file_dependency in information["depends"] + tuple(files.keys()):
241                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
242                     dependency_files |= set(dependencyCFiles)
243                     asm_files |= set(dependencySFiles)
244             for file in module_files:
245                 if not harvard or information.get("harvard", "both") == "both":
246                     csrc.append(file)
247                 if harvard and "harvard" in information:
248                     pcsrc.append(file)
249             for file in dependency_files:
250                 csrc.append(file)
251             for file in project_info.info("CPU_INFOS")["C_SRC"]:
252                 csrc.append(file)
253             for file in project_info.info("CPU_INFOS")["PC_SRC"]:
254                 pcsrc.append(file)
255             for file in asm_files:
256                 cppasrc.append(file)
257     for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
258         cppasrc.append(file)
259     for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
260         cxxsrc.append(file)
261     for file in project_info.info("CPU_INFOS")["ASRC"]:
262         asrc.append(file)
263     csrc = set(csrc)
264     csrc = " \\\n\t".join(csrc) + " \\"
265     pcsrc = set(pcsrc)
266     pcsrc = " \\\n\t".join(pcsrc) + " \\"
267     cppasrc = set(cppasrc)
268     cppasrc = " \\\n\t".join(cppasrc) + " \\"
269     cxxsrc = set(cxxsrc)
270     cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
271     asrc = set(asrc)
272     asrc = " \\\n\t".join(asrc) + " \\"
273     constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
274     return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
275
276 def findModuleFiles(module, project_info):
277     # Find the files related to the selected module
278     cfiles = []
279     sfiles = []
280     # .c files related to the module and the cpu architecture
281     for filename, path in project_info.searchFiles(module + ".c"):
282         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
283         path = replaceSeparators(path)
284         cfiles.append(path + "/" + filename)
285     # .s files related to the module and the cpu architecture
286     for filename, path in project_info.searchFiles(module + ".s") + \
287             project_info.searchFiles(module + ".S"):
288         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
289         path = replaceSeparators(path)
290         sfiles.append(path + "/" + filename)
291     # .c and .s files related to the module and the cpu tags
292     tags = project_info.info("CPU_INFOS")["CPU_TAGS"]
293
294     # Awful, but secure check for version
295     # TODO: split me in a method/function
296     try:
297         version_string = bertosVersion(project_info.info("BERTOS_PATH"))
298         version_list = [int(i) for i in version_string.split()[-1].split('.')]
299     except ValueError:
300         # If the version file hasn't a valid version number assume it's an older
301         # project.
302         version_list = [0, 0]
303     if version_list < [2, 5]:
304         # For older versions of BeRTOS add the toolchain to the tags
305         tags.append(project_info.info("CPU_INFOS")["TOOLCHAIN"])
306
307     for tag in tags:
308         for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
309             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
310             if os.sep != "/":
311                 path = replaceSeparators(path)
312             cfiles.append(path + "/" + filename)
313         for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
314                 project_info.searchFiles(module + "_" + tag + ".S"):
315             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
316             path = replaceSeparators(path)
317             sfiles.append(path + "/" + filename)
318     return cfiles, sfiles
319
320 def replaceSeparators(path):
321     """
322     Replace the separators in the given path with unix standard separator.
323     """
324     if os.sep != "/":
325         while path.find(os.sep) != -1:
326             path = path.replace(os.sep, "/")
327     return path
328
329 def getSystemPath():
330     path = os.environ["PATH"]
331     if os.name == "nt":
332         path = path.split(";")
333     else:
334         path = path.split(":")
335     return path
336
337 def findToolchains(path_list):
338     toolchains = []
339     for element in path_list:
340         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
341             toolchains.append(toolchain)
342     return list(set(toolchains))
343
344 def getToolchainInfo(output):
345     info = {}
346     expr = re.compile("Target: .*")
347     target = expr.findall(output)
348     if len(target) == 1:
349         info["target"] = target[0].split("Target: ")[1]
350     expr = re.compile("gcc version [0-9,.]*")
351     version = expr.findall(output)
352     if len(version) == 1:
353         info["version"] = version[0].split("gcc version ")[1]
354     expr = re.compile("gcc version [0-9,.]* \(.*\)")
355     build = expr.findall(output)
356     if len(build) == 1:
357         build = build[0].split("gcc version ")[1]
358         build = build[build.find("(") + 1 : build.find(")")]
359         info["build"] = build
360     expr = re.compile("Configured with: .*")
361     configured = expr.findall(output)
362     if len(configured) == 1:
363         info["configured"] = configured[0].split("Configured with: ")[1]
364     expr = re.compile("Thread model: .*")
365     thread = expr.findall(output)
366     if len(thread) == 1:
367         info["thread"] = thread[0].split("Thread model: ")[1]
368     return info
369
370 def getToolchainName(toolchain_info):
371     name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
372     return name
373
374 def getTagSet(cpu_info):
375     tag_set = set([])
376     for cpu in cpu_info:
377         tag_set |= set([cpu["CPU_NAME"]])
378         tag_set |= set(cpu["CPU_TAGS"])
379         tag_set |= set([cpu["TOOLCHAIN"]])
380     return tag_set
381         
382
383 def getInfos(definition):
384     D = {}
385     D.update(const.CPU_DEF)
386     def include(filename, dict = D, directory=definition[1]):
387         execfile(directory + "/" + filename, {}, D)
388     D["include"] = include
389     include(definition[0], D)
390     D["CPU_NAME"] = definition[0].split(".")[0]
391     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
392     del D["include"]
393     return D
394
395 def getCommentList(string):
396     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
397     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
398     return comment_list
399
400 def loadModuleDefinition(first_comment):
401     to_be_parsed = False
402     module_definition = {}
403     for num, line in enumerate(first_comment):
404         index = line.find("$WIZ$")
405         if index != -1:
406             to_be_parsed = True
407             try:
408                 exec line[index + len("$WIZ$ "):] in {}, module_definition
409             except:
410                 raise ParseError(num, line[index:])
411         elif line.find("\\brief") != -1:
412             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
413     module_dict = {}
414     if "module_name" in module_definition:
415         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
416         del module_definition[const.MODULE_DEFINITION["module_name"]]
417         module_dict[module_name] = {}
418         if const.MODULE_DEFINITION["module_depends"] in module_definition:
419             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
420             del module_definition[const.MODULE_DEFINITION["module_depends"]]
421             if type(depends) == str:
422                 depends = (depends,)
423             module_dict[module_name]["depends"] = depends
424         else:
425             module_dict[module_name]["depends"] = ()
426         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
427             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
428             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
429         else:
430             module_dict[module_name]["configuration"] = ""
431         if "module_description" in module_definition:
432             module_dict[module_name]["description"] = module_definition["module_description"]
433             del module_definition["module_description"]
434         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
435             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
436             module_dict[module_name]["harvard"] = harvard
437             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
438         if const.MODULE_DEFINITION["module_hw"] in module_definition:
439             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
440             del module_definition[const.MODULE_DEFINITION["module_hw"]]
441             if type(hw) == str:
442                 hw = (hw, )
443             module_dict[module_name]["hw"] = hw
444         else:
445             module_dict[module_name]["hw"] = ()
446         if const.MODULE_DEFINITION["module_supports"] in module_definition:
447             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
448             del module_definition[const.MODULE_DEFINITION["module_supports"]]
449             module_dict[module_name]["supports"] = supports
450         module_dict[module_name]["constants"] = module_definition
451         module_dict[module_name]["enabled"] = False
452     return to_be_parsed, module_dict
453
454 def isSupported(project, module=None, property_id=None):
455     if not module and property_id:
456         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
457     else:
458         item = project.info("MODULES")[module]
459     tag_dict = project.info("ALL_CPU_TAGS")
460     if "supports" in item:
461         support_string = item["supports"]
462         supported = {}
463         try:
464             exec "supported = " + support_string in tag_dict, supported
465         except:
466             raise SupportedException(support_string)
467         return supported["supported"]
468     else:
469         return True
470
471 def loadDefineLists(comment_list):
472     define_list = {}
473     for comment in comment_list:
474         for num, line in enumerate(comment):
475             index = line.find("$WIZ$")
476             if index != -1:
477                 try:
478                     exec line[index + len("$WIZ$ "):] in {}, define_list
479                 except:
480                     raise ParseError(num, line[index:])
481     for key, value in define_list.items():
482         if type(value) == str:
483             define_list[key] = (value,)
484     return define_list
485
486 def getDescriptionInformations(comment):
487     """
488     Take the doxygen comment and strip the wizard informations, returning the tuple
489     (comment, wizard_information)
490     """
491     brief = ""
492     description = ""
493     information = {}
494     for num, line in enumerate(comment):
495         index = line.find("$WIZ$")
496         if index != -1:
497             if len(brief) == 0:
498                 brief += line[:index].strip()
499             else:
500                 description += " " + line[:index]
501             try:
502                 exec line[index + len("$WIZ$ "):] in {}, information
503             except:
504                 raise ParseError(num, line[index:])
505         else:
506             if len(brief) == 0:
507                 brief += line.strip()
508             else:
509                 description += " " + line
510                 description = description.strip()
511     return brief.strip(), description.strip(), information
512
513 def getDefinitionBlocks(text):
514     """
515     Take a text and return a list of tuple (description, name-value).
516     """
517     block = []
518     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
519     for match in block_tmp:
520         # Only the first element is needed
521         comment = match.group(1)
522         define = match.group(2)
523         start = match.start()
524         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
525     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
526         comment = match.group(1)
527         define = match.group(2)
528         start = match.start()
529         block.append(([comment], define, start))
530     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
531         comment = match.group(2)
532         define = match.group(1)
533         start = match.start()
534         block.append(([comment], define, start))
535     return block
536
537 def formatParamNameValue(text):
538     """
539     Take the given string and return a tuple with the name of the parameter in the first position
540     and the value in the second.
541     """
542     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
543     return block[0]
544
545 def loadConfigurationInfos(path):
546     """
547     Return the module configurations found in the given file as a dict with the
548     parameter name as key and a dict containig the fields above as value:
549         "value": the value of the parameter
550         "description": the description of the parameter
551         "informations": a dict containig optional informations:
552             "type": "int" | "boolean" | "enum"
553             "min": the minimum value for integer parameters
554             "max": the maximum value for integer parameters
555             "long": boolean indicating if the num is a long
556             "unsigned": boolean indicating if the num is an unsigned
557             "value_list": the name of the enum for enum parameters
558             "conditional_deps": the list of conditional dependencies for boolean parameters
559     """
560     configuration_infos = {}
561     configuration_infos["paramlist"] = []
562     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
563         name, value = formatParamNameValue(define)
564         brief, description, informations = getDescriptionInformations(comment)
565         configuration_infos["paramlist"].append((start, name))
566         configuration_infos[name] = {}
567         configuration_infos[name]["value"] = value
568         configuration_infos[name]["informations"] = informations
569         if not "type" in configuration_infos[name]["informations"]:
570             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
571         if ("type" in configuration_infos[name]["informations"] and
572                 configuration_infos[name]["informations"]["type"] == "int" and
573                 configuration_infos[name]["value"].find("L") != -1):
574             configuration_infos[name]["informations"]["long"] = True
575             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
576         if ("type" in configuration_infos[name]["informations"] and
577                 configuration_infos[name]["informations"]["type"] == "int" and
578                 configuration_infos[name]["value"].find("U") != -1):
579             configuration_infos[name]["informations"]["unsigned"] = True
580             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
581         if "conditional_deps" in configuration_infos[name]["informations"]:
582             if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
583                     type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
584                 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
585             elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
586                 pass
587             else:
588                 configuration_infos[name]["informations"]["conditional_deps"] = ()
589         configuration_infos[name]["description"] = description
590         configuration_infos[name]["brief"] = brief
591     return configuration_infos
592
593 def updateConfigurationValues(def_conf, user_conf):
594     for param in def_conf["paramlist"]:
595         if param[1] in user_conf and "value" in user_conf[param[1]]:
596             def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
597     return def_conf
598
599 def findParameterType(parameter):
600     if "value_list" in parameter["informations"]:
601         return "enum"
602     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
603         return "int"
604
605 def sub(string, parameter, value):
606     """
607     Substitute the given value at the given parameter define in the given string
608     """
609     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
610
611 def isInt(informations):
612     """
613     Return True if the value is a simple int.
614     """
615     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
616         return True
617     else:
618         return False
619
620 def isLong(informations):
621     """
622     Return True if the value is a long.
623     """
624     if "long" in informations and informations["long"] and "unsigned" not in informations:
625         return True
626     else:
627         return False
628
629 def isUnsigned(informations):
630     """
631     Return True if the value is an unsigned.
632     """
633     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
634         return True
635     else:
636         return False
637
638 def isUnsignedLong(informations):
639     """
640     Return True if the value is an unsigned long.
641     """
642     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
643         return True
644     else:
645         return False
646
647 class ParseError(Exception):
648     def __init__(self, line_number, line):
649         Exception.__init__(self)
650         self.line_number = line_number
651         self.line = line
652
653 class SupportedException(Exception):
654     def __init__(self, support_string):
655         Exception.__init__(self)
656         self.support_string = support_string