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