5d08f54db01d1ebbadf9cf9d0cbd160572a5d7c8
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
5 # All rights reserved.
6 #
7 # $Id$
8 #
9 # Author: Lorenzo Berni <duplo@develer.com>
10 #
11
12 import os
13 import fnmatch
14 import glob
15 import re
16 import shutil
17 # Use custom copytree function
18 import copytree
19 import pickle
20
21 import const
22 import plugins
23 import DefineException
24
25 def isBertosDir(directory):
26    return os.path.exists(directory + "/VERSION")
27
28 def bertosVersion(directory):
29    return open(directory + "/VERSION").readline().strip()
30
31 def createBertosProject(project_info):
32     directory = project_info.info("PROJECT_PATH")
33     sources_dir = project_info.info("SOURCES_PATH")
34     if not os.path.isdir(directory):
35         os.mkdir(directory)
36     f = open(directory + "/project.bertos", "w")
37     f.write(pickle.dumps(project_info))
38     f.close()
39     # Destination source dir
40     srcdir = directory + "/bertos"
41     shutil.rmtree(srcdir, True)
42     copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
43     # Destination makefile
44     makefile = directory + "/Makefile"
45     if os.path.exists(makefile):
46         os.remove(makefile)
47     makefile = open("mktemplates/Makefile").read()
48     makefile = makefileGenerator(project_info, makefile)
49     open(directory + "/Makefile", "w").write(makefile)
50     # Destination project dir
51     prjdir = directory + "/" + os.path.basename(directory)
52     shutil.rmtree(prjdir, True)
53     os.mkdir(prjdir)
54     # Destination hw files
55     hwdir = prjdir + "/hw"
56     shutil.rmtree(hwdir, True)
57     os.mkdir(hwdir)
58     # Copy all the hw files
59     for module, information in project_info.info("MODULES").items():
60         for hwfile in information["hw"]:
61             string = open(sources_dir + "/" + hwfile, "r").read()
62             open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
63     # Destination configurations files
64     cfgdir = prjdir + "/cfg"
65     shutil.rmtree(cfgdir, True)
66     os.mkdir(cfgdir)
67     # Set to 1 the autoenabled for enabled modules
68     for module, information in project_info.info("MODULES").items():
69         if information["enabled"] and "configuration" in information and information["configuration"] != "":
70             configurations = project_info.info("CONFIGURATIONS")
71             configuration = configurations[information["configuration"]]
72             for start, parameter in configuration["paramlist"]:
73                 if "type" in configuration[parameter] and configuration[parameter]["type"] == "autoenabled":
74                     configuration[parameter]["value"] = "1"
75             project_info.setInfo("CONFIGURATIONS", configurations)
76     # Copy all the configuration files
77     for configuration, information in project_info.info("CONFIGURATIONS").items():
78         string = open(sources_dir + "/" + configuration, "r").read()
79         for start, parameter in information["paramlist"]:
80             infos = information[parameter]
81             value = infos["value"]
82             if "unsigned" in infos["informations"] and infos["informations"]["unsigned"]:
83                 value += "U"
84             if "long" in infos["informations"] and infos["informations"]["long"]:
85                 value += "L"
86             string = sub(string, parameter, value)
87         f = open(cfgdir + "/" + os.path.basename(configuration), "w")
88         f.write(string)
89         f.close()
90     # Destinatio mk file
91     makefile = open("mktemplates/template.mk", "r").read()
92     makefile = mkGenerator(project_info, makefile)
93     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
94     # Destination main.c file
95     main = open("srctemplates/main.c", "r").read()
96     open(prjdir + "/main.c", "w").write(main)
97     # Files for selected plugins
98     for plugin in project_info.info("OUTPUT"):
99         module = getattr(__import__("plugins", {}, {}, [plugin]), plugin)
100         module.createProject(project_info)
101
102 def mkGenerator(project_info, makefile):
103     """
104     Generates the mk file for the current project.
105     """
106     mk_data = {}
107     mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
108     mk_data["$cpuflag"] = project_info.info("CPU_INFOS")["CPU_FLAG_NAME"]
109     mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
110     mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
111     mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
112     mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
113     mk_data["$cppflags"] = " ".join(project_info.info("CPU_INFOS")["CPP_FLAGS"])
114     mk_data["$cppaflags"] = " ".join(project_info.info("CPU_INFOS")["CPPA_FLAGS"])
115     mk_data["$cxxflags"] = " ".join(project_info.info("CPU_INFOS")["CXX_FLAGS"])
116     mk_data["$asflags"] = " ".join(project_info.info("CPU_INFOS")["AS_FLAGS"])
117     mk_data["$arflags"] = " ".join(project_info.info("CPU_INFOS")["AR_FLAGS"])
118     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
119     mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
120     mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
121     mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
122     for key in mk_data:
123         while makefile.find(key) != -1:
124             makefile = makefile.replace(key, mk_data[key])
125     return makefile
126
127 def makefileGenerator(project_info, makefile):
128     """
129     Generate the Makefile for the current project.
130     """
131     # TODO write a general function that works for both the mk file and the Makefile
132     while makefile.find("project_name") != -1:
133         makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
134     return makefile
135
136 def csrcGenerator(project_info):
137     modules = project_info.info("MODULES")
138     files = project_info.info("FILES")
139     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
140         harvard = True
141     else:
142         harvard = False
143     # file to be included in CSRC variable
144     csrc = []
145     # file to be included in PCSRC variable
146     pcsrc = []
147     # files to be included in CPPASRC variable
148     cppasrc = []
149     # files to be included in CXXSRC variable
150     cxxsrc = []
151     # files to be included in ASRC variable
152     asrc = []
153     # constants to be included at the beginning of the makefile
154     constants = {}
155     for module, information in modules.items():
156         module_files = set([])
157         dependency_files = set([])
158         # assembly sources
159         asm_files = set([])
160         hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw" 
161         if information["enabled"]:
162             if "constants" in information:
163                 constants.update(information["constants"])
164             cfiles, sfiles = findModuleFiles(module, project_info)
165             module_files |= set(cfiles)
166             asm_files |= set(sfiles)
167             for file in information["hw"]:
168                 if file.endswith(".c"):
169                     module_files |= set([hwdir + "/" + os.path.basename(file)])
170             for file_dependency in information["depends"]:
171                 if file_dependency in files:
172                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
173                     dependency_files |= set(dependencyCFiles)
174                     asm_files |= set(dependencySFiles)
175             for file in module_files:
176                 if not harvard or information.get("harvard", "both") == "both":
177                     csrc.append(file)
178                 if harvard and "harvard" in information:
179                     pcsrc.append(file)
180             for file in dependency_files:
181                 csrc.append(file)
182             for file in project_info.info("CPU_INFOS")["C_SRC"]:
183                 csrc.append(file)
184             for file in project_info.info("CPU_INFOS")["PC_SRC"]:
185                 pcsrc.append(file)
186             for file in asm_files:
187                 cppasrc.append(file)
188     for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
189         cppasrc.append(file)
190     for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
191         cxxsrc.append(file)
192     for file in project_info.info("CPU_INFOS")["ASRC"]:
193         asrc.append(file)
194     csrc = " \\\n\t".join(csrc) + " \\"
195     pcsrc = " \\\n\t".join(pcsrc) + " \\"
196     cppasrc = " \\\n\t".join(cppasrc) + " \\"
197     cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
198     asrc = " \\\n\t".join(asrc) + " \\"
199     constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
200     return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
201
202 def findModuleFiles(module, project_info):
203     # Find the files related to the selected module
204     cfiles = []
205     sfiles = []
206     # .c files related to the module and the cpu architecture
207     for filename, path in findDefinitions(module + ".c", project_info) + \
208             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
209         path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
210         path = replaceSeparators(path)
211         cfiles.append(path + "/" + filename)
212     # .s files related to the module and the cpu architecture
213     for filename, path in findDefinitions(module + ".s", project_info) + \
214             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
215             findDefinitions(module + ".S", project_info) + \
216             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
217         path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
218         path = replaceSeparators(path)
219         sfiles.append(path + "/" + filename)
220     # .c and .s files related to the module and the cpu tags
221     for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
222         for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
223             path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
224             if os.sep != "/":
225                 path = replaceSeparators(path)
226             cfiles.append(path + "/" + filename)
227         for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
228                 findDefinitions(module + "_" + tag + ".S", project_info):
229             path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
230             path = replaceSeparators(path)
231             sfiles.append(path + "/" + filename)
232     return cfiles, sfiles
233
234 def replaceSeparators(path):
235     """
236     Replace the separators in the given path with unix standard separator.
237     """
238     if os.sep != "/":
239         while path.find(os.sep) != -1:
240             path = path.replace(os.sep, "/")
241     return path
242
243 def getSystemPath():
244     path = os.environ["PATH"]
245     if os.name == "nt":
246         path = path.split(";")
247     else:
248         path = path.split(":")
249     return path
250
251 def findToolchains(path_list):
252     toolchains = []
253     for element in path_list:
254         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
255             toolchains.append(toolchain)
256     return list(set(toolchains))
257
258 def getToolchainInfo(output):
259     info = {}
260     expr = re.compile("Target: .*")
261     target = expr.findall(output)
262     if len(target) == 1:
263         info["target"] = target[0].split("Target: ")[1]
264     expr = re.compile("gcc version [0-9,.]*")
265     version = expr.findall(output)
266     if len(version) == 1:
267         info["version"] = version[0].split("gcc version ")[1]
268     expr = re.compile("gcc version [0-9,.]* \(.*\)")
269     build = expr.findall(output)
270     if len(build) == 1:
271         build = build[0].split("gcc version ")[1]
272         build = build[build.find("(") + 1 : build.find(")")]
273         info["build"] = build
274     expr = re.compile("Configured with: .*")
275     configured = expr.findall(output)
276     if len(configured) == 1:
277         info["configured"] = configured[0].split("Configured with: ")[1]
278     expr = re.compile("Thread model: .*")
279     thread = expr.findall(output)
280     if len(thread) == 1:
281         info["thread"] = thread[0].split("Thread model: ")[1]
282     return info
283
284 def loadSourceTree(project):
285     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
286     project.setInfo("FILE_LIST", fileList)
287
288 def findDefinitions(ftype, project):
289     L = project.info("FILE_LIST")
290     definitions = []
291     for element in L:
292         for filename in element[2]:
293             if fnmatch.fnmatch(filename, ftype):
294                 definitions.append((filename, element[0]))
295     return definitions
296
297 def loadCpuInfos(project):
298     cpuInfos = []
299     for definition in findDefinitions(const.CPU_DEFINITION, project):
300         cpuInfos.append(getInfos(definition))
301     return cpuInfos
302
303 def getTagSet(cpu_info):
304     tag_set = set([])
305     for cpu in cpu_info:
306         tag_set |= set([cpu["CPU_NAME"]])
307         tag_set |= set(cpu["CPU_TAGS"])
308         tag_set |= set([cpu["CORE_CPU"]])
309         tag_set |= set([cpu["TOOLCHAIN"]])
310     return tag_set
311         
312
313 def getInfos(definition):
314     D = {}
315     D.update(const.CPU_DEF)
316     def include(filename, dict = D, directory=definition[1]):
317         execfile(directory + "/" + filename, {}, D)
318     D["include"] = include
319     include(definition[0], D)
320     D["CPU_NAME"] = definition[0].split(".")[0]
321     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
322     del D["include"]
323     return D
324
325 def getCommentList(string):
326     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
327     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
328     return comment_list
329
330 def loadModuleDefinition(first_comment):
331     to_be_parsed = False
332     module_definition = {}
333     for num, line in enumerate(first_comment):
334         index = line.find("$WIZ$")
335         if index != -1:
336             to_be_parsed = True
337             try:
338                 exec line[index + len("$WIZ$ "):] in {}, module_definition
339             except:
340                 raise ParseError(num, line[index:])
341         elif line.find("\\brief") != -1:
342             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
343     module_dict = {}
344     if "module_name" in module_definition:
345         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
346         del module_definition[const.MODULE_DEFINITION["module_name"]]
347         module_dict[module_name] = {}
348         if const.MODULE_DEFINITION["module_depends"] in module_definition:
349             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
350             del module_definition[const.MODULE_DEFINITION["module_depends"]]
351             if type(depends) == str:
352                 depends = (depends,)
353             module_dict[module_name]["depends"] = depends
354         else:
355             module_dict[module_name]["depends"] = ()
356         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
357             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
358             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
359         else:
360             module_dict[module_name]["configuration"] = ""
361         if "module_description" in module_definition:
362             module_dict[module_name]["description"] = module_definition["module_description"]
363             del module_definition["module_description"]
364         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
365             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
366             if harvard == "both" or harvard == "pgm_memory":
367                 module_dict[module_name]["harvard"] = harvard
368             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
369         if const.MODULE_DEFINITION["module_hw"] in module_definition:
370             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
371             del module_definition[const.MODULE_DEFINITION["module_hw"]]
372             if type(hw) == str:
373                 hw = (hw, )
374             module_dict[module_name]["hw"] = hw
375         else:
376             module_dict[module_name]["hw"] = ()
377         if const.MODULE_DEFINITION["module_supports"] in module_definition:
378             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
379             del module_definition[const.MODULE_DEFINITION["module_supports"]]
380             module_dict[module_name]["supports"] = supports
381         module_dict[module_name]["constants"] = module_definition
382         module_dict[module_name]["enabled"] = False
383     return to_be_parsed, module_dict
384
385 def isSupported(project, module=None, property_id=None):
386     if not module and property_id:
387         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
388     else:
389         item = project.info("MODULES")[module]
390     tag_dict = project.info("ALL_CPU_TAGS")
391     if "supports" in item:
392         support_string = item["supports"]
393         supported = {}
394         try:
395             exec "supported = " + support_string in tag_dict, supported
396         except:
397             raise SupportedException(support_string)
398         return supported["supported"]
399     else:
400         return True
401
402 def loadDefineLists(comment_list):
403     define_list = {}
404     for comment in comment_list:
405         for num, line in enumerate(comment):
406             index = line.find("$WIZ$")
407             if index != -1:
408                 try:
409                     exec line[index + len("$WIZ$ "):] in {}, define_list
410                 except:
411                     raise ParseError(num, line[index:])
412     for key, value in define_list.items():
413         if type(value) == str:
414             define_list[key] = (value,)
415     return define_list
416
417 def getDescriptionInformations(comment):
418     """
419     Take the doxygen comment and strip the wizard informations, returning the tuple
420     (comment, wizard_information)
421     """
422     brief = ""
423     description = ""
424     information = {}
425     for num, line in enumerate(comment):
426         index = line.find("$WIZ$")
427         if index != -1:
428             if len(brief) == 0:
429                 brief += line[:index].strip()
430             else:
431                 description += " " + line[:index]
432             try:
433                 exec line[index + len("$WIZ$ "):] in {}, information
434             except:
435                 raise ParseError(num, line[index:])
436         else:
437             if len(brief) == 0:
438                 brief += line.strip()
439             else:
440                 description += " " + line
441                 description = description.strip()
442     return brief.strip(), description.strip(), information
443
444 def getDefinitionBlocks(text):
445     """
446     Take a text and return a list of tuple (description, name-value).
447     """
448     block = []
449     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
450     for match in block_tmp:
451         # Only the first element is needed
452         comment = match.group(1)
453         define = match.group(2)
454         start = match.start()
455         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
456     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
457         comment = match.group(1)
458         define = match.group(2)
459         start = match.start()
460         block.append(([comment], define, start))
461     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
462         comment = match.group(2)
463         define = match.group(1)
464         start = match.start()
465         block.append(([comment], define, start))
466     return block
467
468 def loadModuleData(project):
469     module_info_dict = {}
470     list_info_dict = {}
471     configuration_info_dict = {}
472     file_dict = {}
473     for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
474         comment_list = getCommentList(open(path + "/" + filename, "r").read())
475         if len(comment_list) > 0:
476             module_info = {}
477             configuration_info = {}
478             try:
479                 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
480             except ParseError, err:
481                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
482             for module, information in module_dict.items():
483                 if "depends" not in information:
484                     information["depends"] = ()
485                 information["depends"] += (filename.split(".")[0],)
486                 information["category"] = os.path.basename(path)
487                 if "configuration" in information and len(information["configuration"]):
488                     configuration = module_dict[module]["configuration"]
489                     try:
490                         configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
491                     except ParseError, err:
492                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
493             module_info_dict.update(module_dict)
494             configuration_info_dict.update(configuration_info)
495             if to_be_parsed:
496                 try:
497                     list_dict = loadDefineLists(comment_list[1:])
498                     list_info_dict.update(list_dict)
499                 except ParseError, err:
500                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
501     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
502         comment_list = getCommentList(open(path + "/" + filename, "r").read())
503         list_info_dict.update(loadDefineLists(comment_list))
504     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
505         for filename, path in findDefinitions("*_" + tag + ".h", project):
506             comment_list = getCommentList(open(path + "/" + filename, "r").read())
507             list_info_dict.update(loadDefineLists(comment_list))
508     project.setInfo("MODULES", module_info_dict)
509     project.setInfo("LISTS", list_info_dict)
510     project.setInfo("CONFIGURATIONS", configuration_info_dict)
511     project.setInfo("FILES", file_dict)
512
513 def formatParamNameValue(text):
514     """
515     Take the given string and return a tuple with the name of the parameter in the first position
516     and the value in the second.
517     """
518     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
519     return block[0]
520
521 def loadConfigurationInfos(path):
522     """
523     Return the module configurations found in the given file as a dict with the
524     parameter name as key and a dict containig the fields above as value:
525         "value": the value of the parameter
526         "description": the description of the parameter
527         "informations": a dict containig optional informations:
528             "type": "int" | "boolean" | "enum"
529             "min": the minimum value for integer parameters
530             "max": the maximum value for integer parameters
531             "long": boolean indicating if the num is a long
532             "unsigned": boolean indicating if the num is an unsigned
533             "value_list": the name of the enum for enum parameters
534     """
535     configuration_infos = {}
536     configuration_infos["paramlist"] = []
537     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
538         name, value = formatParamNameValue(define)
539         brief, description, informations = getDescriptionInformations(comment)
540         configuration_infos["paramlist"].append((start, name))
541         configuration_infos[name] = {}
542         configuration_infos[name]["value"] = value
543         configuration_infos[name]["informations"] = informations
544         if not "type" in configuration_infos[name]["informations"]:
545             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
546         if ("type" in configuration_infos[name]["informations"] and
547                 configuration_infos[name]["informations"]["type"] == "int" and
548                 configuration_infos[name]["value"].find("L") != -1):
549             configuration_infos[name]["informations"]["long"] = True
550             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
551         if ("type" in configuration_infos[name]["informations"] and
552                 configuration_infos[name]["informations"]["type"] == "int" and
553                 configuration_infos[name]["value"].find("U") != -1):
554             configuration_infos[name]["informations"]["unsigned"] = True
555             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
556         configuration_infos[name]["description"] = description
557         configuration_infos[name]["brief"] = brief
558     return configuration_infos
559
560 def findParameterType(parameter):
561     if "value_list" in parameter["informations"]:
562         return "enum"
563     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
564         return "int"
565
566 def sub(string, parameter, value):
567     """
568     Substitute the given value at the given parameter define in the given string
569     """
570     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
571
572 def isInt(informations):
573     """
574     Return True if the value is a simple int.
575     """
576     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
577         return True
578     else:
579         return False
580
581 def isLong(informations):
582     """
583     Return True if the value is a long.
584     """
585     if "long" in informations and informations["long"] and "unsigned" not in informations:
586         return True
587     else:
588         return False
589
590 def isUnsigned(informations):
591     """
592     Return True if the value is an unsigned.
593     """
594     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
595         return True
596     else:
597         return False
598
599 def isUnsignedLong(informations):
600     """
601     Return True if the value is an unsigned long.
602     """
603     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
604         return True
605     else:
606         return False
607
608 class ParseError(Exception):
609     def __init__(self, line_number, line):
610         Exception.__init__(self)
611         self.line_number = line_number
612         self.line = line
613
614 class SupportedException(Exception):
615     def __init__(self, support_string):
616         Exception.__init__(self)
617         self.support_string = support_string