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