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