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