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