Move loadSourceTree and findDefinitions function into BProject class (to avoid useles...
[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     project_info.loadSourceTree()
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 project_info.findDefinitions(module + ".c") + \
385             project_info.findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c"):
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 project_info.findDefinitions(module + ".s") + \
391             project_info.findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s") + \
392             project_info.findDefinitions(module + ".S") + \
393             project_info.findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S"):
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 project_info.findDefinitions(module + "_" + tag + ".c"):
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 project_info.findDefinitions(module + "_" + tag + ".s") + \
405                 project_info.findDefinitions(module + "_" + tag + ".S"):
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 loadCpuInfos(project_info):
466     cpuInfos = []
467     for definition in project_info.findDefinitions(const.CPU_DEFINITION):
468         cpuInfos.append(getInfos(definition))
469     return cpuInfos
470
471 def getTagSet(cpu_info):
472     tag_set = set([])
473     for cpu in cpu_info:
474         tag_set |= set([cpu["CPU_NAME"]])
475         tag_set |= set(cpu["CPU_TAGS"])
476         tag_set |= set([cpu["TOOLCHAIN"]])
477     return tag_set
478         
479
480 def getInfos(definition):
481     D = {}
482     D.update(const.CPU_DEF)
483     def include(filename, dict = D, directory=definition[1]):
484         execfile(directory + "/" + filename, {}, D)
485     D["include"] = include
486     include(definition[0], D)
487     D["CPU_NAME"] = definition[0].split(".")[0]
488     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
489     del D["include"]
490     return D
491
492 def getCommentList(string):
493     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
494     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
495     return comment_list
496
497 def loadModuleDefinition(first_comment):
498     to_be_parsed = False
499     module_definition = {}
500     for num, line in enumerate(first_comment):
501         index = line.find("$WIZ$")
502         if index != -1:
503             to_be_parsed = True
504             try:
505                 exec line[index + len("$WIZ$ "):] in {}, module_definition
506             except:
507                 raise ParseError(num, line[index:])
508         elif line.find("\\brief") != -1:
509             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
510     module_dict = {}
511     if "module_name" in module_definition:
512         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
513         del module_definition[const.MODULE_DEFINITION["module_name"]]
514         module_dict[module_name] = {}
515         if const.MODULE_DEFINITION["module_depends"] in module_definition:
516             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
517             del module_definition[const.MODULE_DEFINITION["module_depends"]]
518             if type(depends) == str:
519                 depends = (depends,)
520             module_dict[module_name]["depends"] = depends
521         else:
522             module_dict[module_name]["depends"] = ()
523         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
524             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
525             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
526         else:
527             module_dict[module_name]["configuration"] = ""
528         if "module_description" in module_definition:
529             module_dict[module_name]["description"] = module_definition["module_description"]
530             del module_definition["module_description"]
531         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
532             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
533             module_dict[module_name]["harvard"] = harvard
534             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
535         if const.MODULE_DEFINITION["module_hw"] in module_definition:
536             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
537             del module_definition[const.MODULE_DEFINITION["module_hw"]]
538             if type(hw) == str:
539                 hw = (hw, )
540             module_dict[module_name]["hw"] = hw
541         else:
542             module_dict[module_name]["hw"] = ()
543         if const.MODULE_DEFINITION["module_supports"] in module_definition:
544             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
545             del module_definition[const.MODULE_DEFINITION["module_supports"]]
546             module_dict[module_name]["supports"] = supports
547         module_dict[module_name]["constants"] = module_definition
548         module_dict[module_name]["enabled"] = False
549     return to_be_parsed, module_dict
550
551 def isSupported(project, module=None, property_id=None):
552     if not module and property_id:
553         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
554     else:
555         item = project.info("MODULES")[module]
556     tag_dict = project.info("ALL_CPU_TAGS")
557     if "supports" in item:
558         support_string = item["supports"]
559         supported = {}
560         try:
561             exec "supported = " + support_string in tag_dict, supported
562         except:
563             raise SupportedException(support_string)
564         return supported["supported"]
565     else:
566         return True
567
568 def loadDefineLists(comment_list):
569     define_list = {}
570     for comment in comment_list:
571         for num, line in enumerate(comment):
572             index = line.find("$WIZ$")
573             if index != -1:
574                 try:
575                     exec line[index + len("$WIZ$ "):] in {}, define_list
576                 except:
577                     raise ParseError(num, line[index:])
578     for key, value in define_list.items():
579         if type(value) == str:
580             define_list[key] = (value,)
581     return define_list
582
583 def getDescriptionInformations(comment):
584     """
585     Take the doxygen comment and strip the wizard informations, returning the tuple
586     (comment, wizard_information)
587     """
588     brief = ""
589     description = ""
590     information = {}
591     for num, line in enumerate(comment):
592         index = line.find("$WIZ$")
593         if index != -1:
594             if len(brief) == 0:
595                 brief += line[:index].strip()
596             else:
597                 description += " " + line[:index]
598             try:
599                 exec line[index + len("$WIZ$ "):] in {}, information
600             except:
601                 raise ParseError(num, line[index:])
602         else:
603             if len(brief) == 0:
604                 brief += line.strip()
605             else:
606                 description += " " + line
607                 description = description.strip()
608     return brief.strip(), description.strip(), information
609
610 def getDefinitionBlocks(text):
611     """
612     Take a text and return a list of tuple (description, name-value).
613     """
614     block = []
615     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
616     for match in block_tmp:
617         # Only the first element is needed
618         comment = match.group(1)
619         define = match.group(2)
620         start = match.start()
621         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
622     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
623         comment = match.group(1)
624         define = match.group(2)
625         start = match.start()
626         block.append(([comment], define, start))
627     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
628         comment = match.group(2)
629         define = match.group(1)
630         start = match.start()
631         block.append(([comment], define, start))
632     return block
633
634 def loadModuleData(project_info, edit=False):
635     module_info_dict = {}
636     list_info_dict = {}
637     configuration_info_dict = {}
638     file_dict = {}
639     for filename, path in project_info.findDefinitions("*.h") + project_info.findDefinitions("*.c") + project_info.findDefinitions("*.s") + project_info.findDefinitions("*.S"):
640         comment_list = getCommentList(open(path + "/" + filename, "r").read())
641         if len(comment_list) > 0:
642             module_info = {}
643             configuration_info = {}
644             try:
645                 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
646             except ParseError, err:
647                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
648             for module, information in module_dict.items():
649                 if "depends" not in information:
650                     information["depends"] = ()
651                 information["depends"] += (filename.split(".")[0],)
652                 information["category"] = os.path.basename(path)
653                 if "configuration" in information and len(information["configuration"]):
654                     configuration = module_dict[module]["configuration"]
655                     try:
656                         configuration_info[configuration] = loadConfigurationInfos(project_info.info("SOURCES_PATH") + "/" + configuration)
657                     except ParseError, err:
658                         raise DefineException.ConfigurationDefineException(project_info.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
659                     if edit:
660                         try:
661                             path = project_info.info("PROJECT_NAME")
662                             directory = project_info.info("PROJECT_PATH")
663                             user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
664                             configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
665                         except ParseError, err:
666                             raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
667             module_info_dict.update(module_dict)
668             configuration_info_dict.update(configuration_info)
669             if to_be_parsed:
670                 try:
671                     list_dict = loadDefineLists(comment_list[1:])
672                     list_info_dict.update(list_dict)
673                 except ParseError, err:
674                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
675     for filename, path in project_info.findDefinitions("*_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".h"):
676         comment_list = getCommentList(open(path + "/" + filename, "r").read())
677         list_info_dict.update(loadDefineLists(comment_list))
678     for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
679         for filename, path in project_info.findDefinitions("*_" + tag + ".h"):
680             comment_list = getCommentList(open(path + "/" + filename, "r").read())
681             list_info_dict.update(loadDefineLists(comment_list))
682     project_info.setInfo("MODULES", module_info_dict)
683     project_info.setInfo("LISTS", list_info_dict)
684     project_info.setInfo("CONFIGURATIONS", configuration_info_dict)
685     project_info.setInfo("FILES", file_dict)
686
687 def formatParamNameValue(text):
688     """
689     Take the given string and return a tuple with the name of the parameter in the first position
690     and the value in the second.
691     """
692     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
693     return block[0]
694
695 def loadConfigurationInfos(path):
696     """
697     Return the module configurations found in the given file as a dict with the
698     parameter name as key and a dict containig the fields above as value:
699         "value": the value of the parameter
700         "description": the description of the parameter
701         "informations": a dict containig optional informations:
702             "type": "int" | "boolean" | "enum"
703             "min": the minimum value for integer parameters
704             "max": the maximum value for integer parameters
705             "long": boolean indicating if the num is a long
706             "unsigned": boolean indicating if the num is an unsigned
707             "value_list": the name of the enum for enum parameters
708             "conditional_deps": the list of conditional dependencies for boolean parameters
709     """
710     configuration_infos = {}
711     configuration_infos["paramlist"] = []
712     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
713         name, value = formatParamNameValue(define)
714         brief, description, informations = getDescriptionInformations(comment)
715         configuration_infos["paramlist"].append((start, name))
716         configuration_infos[name] = {}
717         configuration_infos[name]["value"] = value
718         configuration_infos[name]["informations"] = informations
719         if not "type" in configuration_infos[name]["informations"]:
720             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
721         if ("type" in configuration_infos[name]["informations"] and
722                 configuration_infos[name]["informations"]["type"] == "int" and
723                 configuration_infos[name]["value"].find("L") != -1):
724             configuration_infos[name]["informations"]["long"] = True
725             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
726         if ("type" in configuration_infos[name]["informations"] and
727                 configuration_infos[name]["informations"]["type"] == "int" and
728                 configuration_infos[name]["value"].find("U") != -1):
729             configuration_infos[name]["informations"]["unsigned"] = True
730             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
731         if "conditional_deps" in configuration_infos[name]["informations"]:
732             if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
733                     type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
734                 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
735             elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
736                 pass
737             else:
738                 configuration_infos[name]["informations"]["conditional_deps"] = ()
739         configuration_infos[name]["description"] = description
740         configuration_infos[name]["brief"] = brief
741     return configuration_infos
742
743 def updateConfigurationValues(def_conf, user_conf):
744     for param in def_conf["paramlist"]:
745         if param[1] in user_conf and "value" in user_conf[param[1]]:
746             def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
747     return def_conf
748
749 def findParameterType(parameter):
750     if "value_list" in parameter["informations"]:
751         return "enum"
752     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
753         return "int"
754
755 def sub(string, parameter, value):
756     """
757     Substitute the given value at the given parameter define in the given string
758     """
759     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
760
761 def isInt(informations):
762     """
763     Return True if the value is a simple int.
764     """
765     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
766         return True
767     else:
768         return False
769
770 def isLong(informations):
771     """
772     Return True if the value is a long.
773     """
774     if "long" in informations and informations["long"] and "unsigned" not in informations:
775         return True
776     else:
777         return False
778
779 def isUnsigned(informations):
780     """
781     Return True if the value is an unsigned.
782     """
783     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
784         return True
785     else:
786         return False
787
788 def isUnsignedLong(informations):
789     """
790     Return True if the value is an unsigned long.
791     """
792     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
793         return True
794     else:
795         return False
796
797 class ParseError(Exception):
798     def __init__(self, line_number, line):
799         Exception.__init__(self)
800         self.line_number = line_number
801         self.line = line
802
803 class SupportedException(Exception):
804     def __init__(self, support_string):
805         Exception.__init__(self)
806         self.support_string = support_string