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