Add menu in order to configure toolchain
[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 loadSourceTree(project):
362     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
363     project.setInfo("FILE_LIST", fileList)
364
365 def findDefinitions(ftype, project):
366     L = project.info("FILE_LIST")
367     definitions = []
368     for element in L:
369         for filename in element[2]:
370             if fnmatch.fnmatch(filename, ftype):
371                 definitions.append((filename, element[0]))
372     return definitions
373
374 def loadCpuInfos(project):
375     cpuInfos = []
376     for definition in findDefinitions(const.CPU_DEFINITION, project):
377         cpuInfos.append(getInfos(definition))
378     return cpuInfos
379
380 def getTagSet(cpu_info):
381     tag_set = set([])
382     for cpu in cpu_info:
383         tag_set |= set([cpu["CPU_NAME"]])
384         tag_set |= set(cpu["CPU_TAGS"])
385         tag_set |= set([cpu["CORE_CPU"]])
386         tag_set |= set([cpu["TOOLCHAIN"]])
387     return tag_set
388         
389
390 def getInfos(definition):
391     D = {}
392     D.update(const.CPU_DEF)
393     def include(filename, dict = D, directory=definition[1]):
394         execfile(directory + "/" + filename, {}, D)
395     D["include"] = include
396     include(definition[0], D)
397     D["CPU_NAME"] = definition[0].split(".")[0]
398     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
399     del D["include"]
400     return D
401
402 def getCommentList(string):
403     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
404     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
405     return comment_list
406
407 def loadModuleDefinition(first_comment):
408     to_be_parsed = False
409     module_definition = {}
410     for num, line in enumerate(first_comment):
411         index = line.find("$WIZ$")
412         if index != -1:
413             to_be_parsed = True
414             try:
415                 exec line[index + len("$WIZ$ "):] in {}, module_definition
416             except:
417                 raise ParseError(num, line[index:])
418         elif line.find("\\brief") != -1:
419             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
420     module_dict = {}
421     if "module_name" in module_definition:
422         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
423         del module_definition[const.MODULE_DEFINITION["module_name"]]
424         module_dict[module_name] = {}
425         if const.MODULE_DEFINITION["module_depends"] in module_definition:
426             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
427             del module_definition[const.MODULE_DEFINITION["module_depends"]]
428             if type(depends) == str:
429                 depends = (depends,)
430             module_dict[module_name]["depends"] = depends
431         else:
432             module_dict[module_name]["depends"] = ()
433         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
434             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
435             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
436         else:
437             module_dict[module_name]["configuration"] = ""
438         if "module_description" in module_definition:
439             module_dict[module_name]["description"] = module_definition["module_description"]
440             del module_definition["module_description"]
441         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
442             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
443             module_dict[module_name]["harvard"] = harvard
444             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
445         if const.MODULE_DEFINITION["module_hw"] in module_definition:
446             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
447             del module_definition[const.MODULE_DEFINITION["module_hw"]]
448             if type(hw) == str:
449                 hw = (hw, )
450             module_dict[module_name]["hw"] = hw
451         else:
452             module_dict[module_name]["hw"] = ()
453         if const.MODULE_DEFINITION["module_supports"] in module_definition:
454             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
455             del module_definition[const.MODULE_DEFINITION["module_supports"]]
456             module_dict[module_name]["supports"] = supports
457         module_dict[module_name]["constants"] = module_definition
458         module_dict[module_name]["enabled"] = False
459     return to_be_parsed, module_dict
460
461 def isSupported(project, module=None, property_id=None):
462     if not module and property_id:
463         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
464     else:
465         item = project.info("MODULES")[module]
466     tag_dict = project.info("ALL_CPU_TAGS")
467     if "supports" in item:
468         support_string = item["supports"]
469         supported = {}
470         try:
471             exec "supported = " + support_string in tag_dict, supported
472         except:
473             raise SupportedException(support_string)
474         return supported["supported"]
475     else:
476         return True
477
478 def loadDefineLists(comment_list):
479     define_list = {}
480     for comment in comment_list:
481         for num, line in enumerate(comment):
482             index = line.find("$WIZ$")
483             if index != -1:
484                 try:
485                     exec line[index + len("$WIZ$ "):] in {}, define_list
486                 except:
487                     raise ParseError(num, line[index:])
488     for key, value in define_list.items():
489         if type(value) == str:
490             define_list[key] = (value,)
491     return define_list
492
493 def getDescriptionInformations(comment):
494     """
495     Take the doxygen comment and strip the wizard informations, returning the tuple
496     (comment, wizard_information)
497     """
498     brief = ""
499     description = ""
500     information = {}
501     for num, line in enumerate(comment):
502         index = line.find("$WIZ$")
503         if index != -1:
504             if len(brief) == 0:
505                 brief += line[:index].strip()
506             else:
507                 description += " " + line[:index]
508             try:
509                 exec line[index + len("$WIZ$ "):] in {}, information
510             except:
511                 raise ParseError(num, line[index:])
512         else:
513             if len(brief) == 0:
514                 brief += line.strip()
515             else:
516                 description += " " + line
517                 description = description.strip()
518     return brief.strip(), description.strip(), information
519
520 def getDefinitionBlocks(text):
521     """
522     Take a text and return a list of tuple (description, name-value).
523     """
524     block = []
525     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
526     for match in block_tmp:
527         # Only the first element is needed
528         comment = match.group(1)
529         define = match.group(2)
530         start = match.start()
531         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
532     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
533         comment = match.group(1)
534         define = match.group(2)
535         start = match.start()
536         block.append(([comment], define, start))
537     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
538         comment = match.group(2)
539         define = match.group(1)
540         start = match.start()
541         block.append(([comment], define, start))
542     return block
543
544 def loadModuleData(project, edit=False):
545     module_info_dict = {}
546     list_info_dict = {}
547     configuration_info_dict = {}
548     file_dict = {}
549     for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
550         comment_list = getCommentList(open(path + "/" + filename, "r").read())
551         if len(comment_list) > 0:
552             module_info = {}
553             configuration_info = {}
554             try:
555                 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
556             except ParseError, err:
557                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
558             for module, information in module_dict.items():
559                 if "depends" not in information:
560                     information["depends"] = ()
561                 information["depends"] += (filename.split(".")[0],)
562                 information["category"] = os.path.basename(path)
563                 if "configuration" in information and len(information["configuration"]):
564                     configuration = module_dict[module]["configuration"]
565                     try:
566                         configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
567                     except ParseError, err:
568                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
569                     if edit:
570                         try:
571                             path = os.path.basename(project.info("PROJECT_PATH"))
572                             directory = project.info("PROJECT_PATH")
573                             user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
574                             configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
575                         except ParseError, err:
576                             raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
577             module_info_dict.update(module_dict)
578             configuration_info_dict.update(configuration_info)
579             if to_be_parsed:
580                 try:
581                     list_dict = loadDefineLists(comment_list[1:])
582                     list_info_dict.update(list_dict)
583                 except ParseError, err:
584                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
585     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
586         comment_list = getCommentList(open(path + "/" + filename, "r").read())
587         list_info_dict.update(loadDefineLists(comment_list))
588     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
589         for filename, path in findDefinitions("*_" + tag + ".h", project):
590             comment_list = getCommentList(open(path + "/" + filename, "r").read())
591             list_info_dict.update(loadDefineLists(comment_list))
592     project.setInfo("MODULES", module_info_dict)
593     project.setInfo("LISTS", list_info_dict)
594     project.setInfo("CONFIGURATIONS", configuration_info_dict)
595     project.setInfo("FILES", file_dict)
596
597 def formatParamNameValue(text):
598     """
599     Take the given string and return a tuple with the name of the parameter in the first position
600     and the value in the second.
601     """
602     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
603     return block[0]
604
605 def loadConfigurationInfos(path):
606     """
607     Return the module configurations found in the given file as a dict with the
608     parameter name as key and a dict containig the fields above as value:
609         "value": the value of the parameter
610         "description": the description of the parameter
611         "informations": a dict containig optional informations:
612             "type": "int" | "boolean" | "enum"
613             "min": the minimum value for integer parameters
614             "max": the maximum value for integer parameters
615             "long": boolean indicating if the num is a long
616             "unsigned": boolean indicating if the num is an unsigned
617             "value_list": the name of the enum for enum parameters
618     """
619     configuration_infos = {}
620     configuration_infos["paramlist"] = []
621     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
622         name, value = formatParamNameValue(define)
623         brief, description, informations = getDescriptionInformations(comment)
624         configuration_infos["paramlist"].append((start, name))
625         configuration_infos[name] = {}
626         configuration_infos[name]["value"] = value
627         configuration_infos[name]["informations"] = informations
628         if not "type" in configuration_infos[name]["informations"]:
629             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
630         if ("type" in configuration_infos[name]["informations"] and
631                 configuration_infos[name]["informations"]["type"] == "int" and
632                 configuration_infos[name]["value"].find("L") != -1):
633             configuration_infos[name]["informations"]["long"] = True
634             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
635         if ("type" in configuration_infos[name]["informations"] and
636                 configuration_infos[name]["informations"]["type"] == "int" and
637                 configuration_infos[name]["value"].find("U") != -1):
638             configuration_infos[name]["informations"]["unsigned"] = True
639             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
640         configuration_infos[name]["description"] = description
641         configuration_infos[name]["brief"] = brief
642     return configuration_infos
643
644 def updateConfigurationValues(def_conf, user_conf):
645     for param in def_conf["paramlist"]:
646         def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
647     return def_conf
648
649 def findParameterType(parameter):
650     if "value_list" in parameter["informations"]:
651         return "enum"
652     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
653         return "int"
654
655 def sub(string, parameter, value):
656     """
657     Substitute the given value at the given parameter define in the given string
658     """
659     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
660
661 def isInt(informations):
662     """
663     Return True if the value is a simple int.
664     """
665     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
666         return True
667     else:
668         return False
669
670 def isLong(informations):
671     """
672     Return True if the value is a long.
673     """
674     if "long" in informations and informations["long"] and "unsigned" not in informations:
675         return True
676     else:
677         return False
678
679 def isUnsigned(informations):
680     """
681     Return True if the value is an unsigned.
682     """
683     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
684         return True
685     else:
686         return False
687
688 def isUnsignedLong(informations):
689     """
690     Return True if the value is an unsigned long.
691     """
692     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
693         return True
694     else:
695         return False
696
697 class ParseError(Exception):
698     def __init__(self, line_number, line):
699         Exception.__init__(self)
700         self.line_number = line_number
701         self.line = line
702
703 class SupportedException(Exception):
704     def __init__(self, support_string):
705         Exception.__init__(self)
706         self.support_string = support_string