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