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