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