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