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