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