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