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