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