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