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