4 # This file is part of BeRTOS.
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.
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.
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
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.
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
33 # Author: Lorenzo Berni <duplo@develer.com>
41 # Use custom copytree function
47 import DefineException
50 from _wizard_version import WIZARD_VERSION
52 from LoadException import VersionException, ToolchainException
54 def isBertosDir(directory):
55 return os.path.exists(directory + "/VERSION")
57 def bertosVersion(directory):
58 return open(directory + "/VERSION").readline().strip()
60 def loadBertosProject(project_file, info_dict):
61 project_dir = os.path.dirname(project_file)
62 project_data = pickle.loads(open(project_file, "r").read())
63 project_info = BProject.BProject()
64 project_info.setInfo("PROJECT_PATH", os.path.dirname(project_file))
65 # Check for the Wizard version
66 wizard_version = project_data.get("WIZARD_VERSION", 0)
67 if not wizard_version:
68 project_data["SOURCES_PATH"] = project_dir
69 if "SOURCES_PATH" in info_dict:
70 project_data["SOURCES_PATH"] = info_dict["SOURCES_PATH"]
71 if os.path.exists(project_data["SOURCES_PATH"]):
72 project_info.setInfo("SOURCES_PATH", project_data["SOURCES_PATH"])
74 raise VersionException(project_info)
75 if not isBertosDir(os.path.dirname(project_file)):
76 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
77 open(os.path.join(project_dir, "VERSION"), "w").write(version_file.replace("$version", "").strip())
78 loadSourceTree(project_info)
79 cpu_name = project_data["CPU_NAME"]
80 project_info.setInfo("CPU_NAME", cpu_name)
81 cpu_info = loadCpuInfos(project_info)
83 if cpu["CPU_NAME"] == cpu_name:
84 project_info.setInfo("CPU_INFOS", cpu)
86 tag_list = getTagSet(cpu_info)
87 # Create, fill and store the dict with the tags
89 for element in tag_list:
90 tag_dict[element] = False
91 infos = project_info.info("CPU_INFOS")
93 if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
97 project_info.setInfo("ALL_CPU_TAGS", tag_dict)
98 if "TOOLCHAIN" in info_dict:
99 project_data["TOOLCHAIN"] = info_dict["TOOLCHAIN"]
100 if os.path.exists(project_data["TOOLCHAIN"]["path"]):
101 project_info.setInfo("TOOLCHAIN", project_data["TOOLCHAIN"])
103 raise ToolchainException(project_info)
104 project_info.setInfo("SELECTED_FREQ", project_data["SELECTED_FREQ"])
105 project_info.setInfo("OUTPUT", project_data["OUTPUT"])
106 loadModuleData(project_info, True)
107 setEnabledModules(project_info, project_data["ENABLED_MODULES"])
110 def setEnabledModules(project_info, enabled_modules):
111 modules = project_info.info("MODULES")
113 for module, information in modules.items():
114 information["enabled"] = module in enabled_modules
115 for dependency in information["depends"]:
116 if not dependency in modules:
117 if dependency in files:
118 files[dependency] += 1
120 files[dependency] = 1
121 project_info.setInfo("MODULES", modules)
122 project_info.setInfo("FILES", files)
124 def enabledModules(project_info):
126 for name, module in project_info.info("MODULES").items():
127 if module["enabled"]:
128 enabled_modules.append(name)
129 return enabled_modules
131 def mergeSources(srcdir, new_sources, old_sources):
132 # The current mergeSources function provide only a raw copy of the sources in the
135 # TODO: implement the three way merge algorithm
137 shutil.rmtree(srcdir, True)
138 copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
140 def projectFileGenerator(project_info):
141 directory = project_info.info("PROJECT_PATH")
144 for module, information in project_info.info("MODULES").items():
145 if information["enabled"]:
146 enabled_modules.append(module)
147 project_data["ENABLED_MODULES"] = enabled_modules
148 # Use the local BeRTOS version instead of the original one
149 # project_data["SOURCES_PATH"] = project_info.info("SOURCES_PATH")
150 project_data["SOURCES_PATH"] = directory
151 project_data["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
152 project_data["CPU_NAME"] = project_info.info("CPU_NAME")
153 project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
154 project_data["OUTPUT"] = project_info.info("OUTPUT")
155 project_data["WIZARD_VERSION"] = WIZARD_VERSION
156 return pickle.dumps(project_data)
158 def createBertosProject(project_info, edit=False):
159 directory = project_info.info("PROJECT_PATH")
160 sources_dir = project_info.info("SOURCES_PATH")
161 old_sources_dir = project_info.info("OLD_SOURCES_PATH")
163 if os.path.isdir(directory):
164 shutil.rmtree(directory, True)
165 os.makedirs(directory)
166 # Write the project file
167 f = open(directory + "/project.bertos", "w")
168 f.write(projectFileGenerator(project_info))
171 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
172 open(directory + "/VERSION", "w").write(versionFileGenerator(project_info, version_file))
173 # Destination source dir
174 srcdir = directory + "/bertos"
176 # If not in editing mode it copies all the bertos sources in the /bertos subdirectory of the project
177 shutil.rmtree(srcdir, True)
178 copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
179 elif old_sources_dir:
180 # If in editing mode it merges the current bertos sources with the selected ones
181 # TODO: implement the three way merge algotihm
183 mergeSources(srcdir, sources_dir, old_sources_dir)
184 # Destination makefile
185 makefile = directory + "/Makefile"
186 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), 'r').read()
187 makefile = makefileGenerator(project_info, makefile)
188 open(directory + "/Makefile", "w").write(makefile)
189 # Destination project dir
190 prjdir = directory + "/" + os.path.basename(directory)
192 shutil.rmtree(prjdir, True)
194 # Destination hw files
195 hwdir = prjdir + "/hw"
197 shutil.rmtree(hwdir, True)
199 # Copy all the hw files
200 for module, information in project_info.info("MODULES").items():
201 for hwfile in information["hw"]:
202 string = open(sources_dir + "/" + hwfile, "r").read()
203 hwfile_path = hwdir + "/" + os.path.basename(hwfile)
204 if not edit or not os.path.exists(hwfile_path):
205 # If not in editing mode it copies all the hw files. If in
206 # editing mode it copies only the files that don't exist yet
207 open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
208 # Destination configurations files
209 cfgdir = prjdir + "/cfg"
211 shutil.rmtree(cfgdir, True)
213 # Set properly the autoenabled parameters
214 for module, information in project_info.info("MODULES").items():
215 if "configuration" in information and information["configuration"] != "":
216 configurations = project_info.info("CONFIGURATIONS")
217 configuration = configurations[information["configuration"]]
218 for start, parameter in configuration["paramlist"]:
219 if "type" in configuration[parameter]["informations"] and configuration[parameter]["informations"]["type"] == "autoenabled":
220 configuration[parameter]["value"] = "1" if information["enabled"] else "0"
221 project_info.setInfo("CONFIGURATIONS", configurations)
222 # Copy all the configuration files
223 for configuration, information in project_info.info("CONFIGURATIONS").items():
224 string = open(sources_dir + "/" + configuration, "r").read()
225 for start, parameter in information["paramlist"]:
226 infos = information[parameter]
227 value = infos["value"]
228 if "unsigned" in infos["informations"] and infos["informations"]["unsigned"]:
230 if "long" in infos["informations"] and infos["informations"]["long"]:
232 string = sub(string, parameter, value)
233 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
237 # Destination user mk file (only on project creation)
238 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
239 # Deadly performances loss was here :(
240 makefile = userMkGenerator(project_info, makefile)
241 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
242 # Destination wizard mk file
243 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template_wiz.mk"), "r").read()
244 makefile = mkGenerator(project_info, makefile)
245 open(prjdir + "/" + os.path.basename(prjdir) + "_wiz.mk", "w").write(makefile)
246 # Destination main.c file
248 main = open(os.path.join(const.DATA_DIR, "srctemplates/main.c"), "r").read()
249 open(prjdir + "/main.c", "w").write(main)
250 # Files for selected plugins
252 for plugin in project_info.info("OUTPUT"):
253 module = loadPlugin(plugin)
254 relevants_files[plugin] = module.createProject(project_info)
255 project_info.setInfo("RELEVANT_FILES", relevants_files)
257 def loadPlugin(plugin):
259 Returns the given plugin module.
261 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
263 def versionFileGenerator(project_info, version_file):
264 version = bertosVersion(project_info.info("SOURCES_PATH"))
265 return version_file.replace('$version', version)
267 def userMkGenerator(project_info, makefile):
269 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
270 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
272 while makefile.find(key) != -1:
273 makefile = makefile.replace(key, mk_data[key])
276 def mkGenerator(project_info, makefile):
278 Generates the mk file for the current project.
281 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
282 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
283 cpu_mk_parameters = []
284 for key, value in project_info.info("CPU_INFOS").items():
285 if key.startswith(const.MK_PARAM_ID):
286 cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
287 mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
288 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
289 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
290 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
291 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
293 while makefile.find(key) != -1:
294 makefile = makefile.replace(key, mk_data[key])
297 def makefileGenerator(project_info, makefile):
299 Generate the Makefile for the current project.
301 # TODO write a general function that works for both the mk file and the Makefile
302 while makefile.find("$pname") != -1:
303 makefile = makefile.replace("$pname", os.path.basename(project_info.info("PROJECT_PATH")))
306 def csrcGenerator(project_info):
307 modules = project_info.info("MODULES")
308 files = project_info.info("FILES")
309 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
313 # file to be included in CSRC variable
315 # file to be included in PCSRC variable
317 # files to be included in CPPASRC variable
319 # files to be included in CXXSRC variable
321 # files to be included in ASRC variable
323 # constants to be included at the beginning of the makefile
325 for module, information in modules.items():
326 module_files = set([])
327 dependency_files = set([])
330 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
331 if information["enabled"]:
332 if "constants" in information:
333 constants.update(information["constants"])
334 cfiles, sfiles = findModuleFiles(module, project_info)
335 module_files |= set(cfiles)
336 asm_files |= set(sfiles)
337 for file in information["hw"]:
338 if file.endswith(".c"):
339 module_files |= set([hwdir + "/" + os.path.basename(file)])
340 for file_dependency in information["depends"] + tuple(files.keys()):
341 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
342 dependency_files |= set(dependencyCFiles)
343 asm_files |= set(dependencySFiles)
344 for file in module_files:
345 if not harvard or information.get("harvard", "both") == "both":
347 if harvard and "harvard" in information:
349 for file in dependency_files:
351 for file in project_info.info("CPU_INFOS")["C_SRC"]:
353 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
355 for file in asm_files:
357 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
359 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
361 for file in project_info.info("CPU_INFOS")["ASRC"]:
364 csrc = " \\\n\t".join(csrc) + " \\"
366 pcsrc = " \\\n\t".join(pcsrc) + " \\"
367 cppasrc = set(cppasrc)
368 cppasrc = " \\\n\t".join(cppasrc) + " \\"
370 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
372 asrc = " \\\n\t".join(asrc) + " \\"
373 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
374 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
376 def findModuleFiles(module, project_info):
377 # Find the files related to the selected module
380 # .c files related to the module and the cpu architecture
381 for filename, path in findDefinitions(module + ".c", project_info) + \
382 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
383 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
384 path = replaceSeparators(path)
385 cfiles.append(path + "/" + filename)
386 # .s files related to the module and the cpu architecture
387 for filename, path in findDefinitions(module + ".s", project_info) + \
388 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
389 findDefinitions(module + ".S", project_info) + \
390 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
391 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
392 path = replaceSeparators(path)
393 sfiles.append(path + "/" + filename)
394 # .c and .s files related to the module and the cpu tags
395 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
396 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
397 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
399 path = replaceSeparators(path)
400 cfiles.append(path + "/" + filename)
401 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
402 findDefinitions(module + "_" + tag + ".S", project_info):
403 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
404 path = replaceSeparators(path)
405 sfiles.append(path + "/" + filename)
406 return cfiles, sfiles
408 def replaceSeparators(path):
410 Replace the separators in the given path with unix standard separator.
413 while path.find(os.sep) != -1:
414 path = path.replace(os.sep, "/")
418 path = os.environ["PATH"]
420 path = path.split(";")
422 path = path.split(":")
425 def findToolchains(path_list):
427 for element in path_list:
428 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
429 toolchains.append(toolchain)
430 return list(set(toolchains))
432 def getToolchainInfo(output):
434 expr = re.compile("Target: .*")
435 target = expr.findall(output)
437 info["target"] = target[0].split("Target: ")[1]
438 expr = re.compile("gcc version [0-9,.]*")
439 version = expr.findall(output)
440 if len(version) == 1:
441 info["version"] = version[0].split("gcc version ")[1]
442 expr = re.compile("gcc version [0-9,.]* \(.*\)")
443 build = expr.findall(output)
445 build = build[0].split("gcc version ")[1]
446 build = build[build.find("(") + 1 : build.find(")")]
447 info["build"] = build
448 expr = re.compile("Configured with: .*")
449 configured = expr.findall(output)
450 if len(configured) == 1:
451 info["configured"] = configured[0].split("Configured with: ")[1]
452 expr = re.compile("Thread model: .*")
453 thread = expr.findall(output)
455 info["thread"] = thread[0].split("Thread model: ")[1]
458 def getToolchainName(toolchain_info):
459 name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
462 def loadSourceTree(project):
463 # Index only the SOURCES_PATH/bertos content
464 bertos_sources_dir = os.path.join(project.info("SOURCES_PATH"), 'bertos')
465 if os.path.exists(bertos_sources_dir):
466 fileList = [f for f in os.walk(bertos_sources_dir)]
469 project.setInfo("FILE_LIST", fileList)
473 def findDefinitions(ftype, project):
474 definitions = _cached_queries.get(ftype, None)
475 if definitions is not None:
477 L = project.info("FILE_LIST")
480 for filename in element[2]:
481 if fnmatch.fnmatch(filename, ftype):
482 definitions.append((filename, element[0]))
483 _cached_queries[ftype] = definitions
486 def loadCpuInfos(project):
488 for definition in findDefinitions(const.CPU_DEFINITION, project):
489 cpuInfos.append(getInfos(definition))
492 def getTagSet(cpu_info):
495 tag_set |= set([cpu["CPU_NAME"]])
496 tag_set |= set(cpu["CPU_TAGS"])
497 tag_set |= set([cpu["TOOLCHAIN"]])
501 def getInfos(definition):
503 D.update(const.CPU_DEF)
504 def include(filename, dict = D, directory=definition[1]):
505 execfile(directory + "/" + filename, {}, D)
506 D["include"] = include
507 include(definition[0], D)
508 D["CPU_NAME"] = definition[0].split(".")[0]
509 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
513 def getCommentList(string):
514 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
515 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
518 def loadModuleDefinition(first_comment):
520 module_definition = {}
521 for num, line in enumerate(first_comment):
522 index = line.find("$WIZ$")
526 exec line[index + len("$WIZ$ "):] in {}, module_definition
528 raise ParseError(num, line[index:])
529 elif line.find("\\brief") != -1:
530 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
532 if "module_name" in module_definition:
533 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
534 del module_definition[const.MODULE_DEFINITION["module_name"]]
535 module_dict[module_name] = {}
536 if const.MODULE_DEFINITION["module_depends"] in module_definition:
537 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
538 del module_definition[const.MODULE_DEFINITION["module_depends"]]
539 if type(depends) == str:
541 module_dict[module_name]["depends"] = depends
543 module_dict[module_name]["depends"] = ()
544 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
545 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
546 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
548 module_dict[module_name]["configuration"] = ""
549 if "module_description" in module_definition:
550 module_dict[module_name]["description"] = module_definition["module_description"]
551 del module_definition["module_description"]
552 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
553 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
554 module_dict[module_name]["harvard"] = harvard
555 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
556 if const.MODULE_DEFINITION["module_hw"] in module_definition:
557 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
558 del module_definition[const.MODULE_DEFINITION["module_hw"]]
561 module_dict[module_name]["hw"] = hw
563 module_dict[module_name]["hw"] = ()
564 if const.MODULE_DEFINITION["module_supports"] in module_definition:
565 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
566 del module_definition[const.MODULE_DEFINITION["module_supports"]]
567 module_dict[module_name]["supports"] = supports
568 module_dict[module_name]["constants"] = module_definition
569 module_dict[module_name]["enabled"] = False
570 return to_be_parsed, module_dict
572 def isSupported(project, module=None, property_id=None):
573 if not module and property_id:
574 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
576 item = project.info("MODULES")[module]
577 tag_dict = project.info("ALL_CPU_TAGS")
578 if "supports" in item:
579 support_string = item["supports"]
582 exec "supported = " + support_string in tag_dict, supported
584 raise SupportedException(support_string)
585 return supported["supported"]
589 def loadDefineLists(comment_list):
591 for comment in comment_list:
592 for num, line in enumerate(comment):
593 index = line.find("$WIZ$")
596 exec line[index + len("$WIZ$ "):] in {}, define_list
598 raise ParseError(num, line[index:])
599 for key, value in define_list.items():
600 if type(value) == str:
601 define_list[key] = (value,)
604 def getDescriptionInformations(comment):
606 Take the doxygen comment and strip the wizard informations, returning the tuple
607 (comment, wizard_information)
612 for num, line in enumerate(comment):
613 index = line.find("$WIZ$")
616 brief += line[:index].strip()
618 description += " " + line[:index]
620 exec line[index + len("$WIZ$ "):] in {}, information
622 raise ParseError(num, line[index:])
625 brief += line.strip()
627 description += " " + line
628 description = description.strip()
629 return brief.strip(), description.strip(), information
631 def getDefinitionBlocks(text):
633 Take a text and return a list of tuple (description, name-value).
636 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
637 for match in block_tmp:
638 # Only the first element is needed
639 comment = match.group(1)
640 define = match.group(2)
641 start = match.start()
642 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
643 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
644 comment = match.group(1)
645 define = match.group(2)
646 start = match.start()
647 block.append(([comment], define, start))
648 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
649 comment = match.group(2)
650 define = match.group(1)
651 start = match.start()
652 block.append(([comment], define, start))
655 def loadModuleData(project, edit=False):
656 module_info_dict = {}
658 configuration_info_dict = {}
660 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
661 comment_list = getCommentList(open(path + "/" + filename, "r").read())
662 if len(comment_list) > 0:
664 configuration_info = {}
666 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
667 except ParseError, err:
668 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
669 for module, information in module_dict.items():
670 if "depends" not in information:
671 information["depends"] = ()
672 information["depends"] += (filename.split(".")[0],)
673 information["category"] = os.path.basename(path)
674 if "configuration" in information and len(information["configuration"]):
675 configuration = module_dict[module]["configuration"]
677 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
678 except ParseError, err:
679 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
682 path = os.path.basename(project.info("PROJECT_PATH"))
683 directory = project.info("PROJECT_PATH")
684 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
685 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
686 except ParseError, err:
687 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
688 module_info_dict.update(module_dict)
689 configuration_info_dict.update(configuration_info)
692 list_dict = loadDefineLists(comment_list[1:])
693 list_info_dict.update(list_dict)
694 except ParseError, err:
695 raise DefineException.EnumDefineException(path, err.line_number, err.line)
696 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
697 comment_list = getCommentList(open(path + "/" + filename, "r").read())
698 list_info_dict.update(loadDefineLists(comment_list))
699 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
700 for filename, path in findDefinitions("*_" + tag + ".h", project):
701 comment_list = getCommentList(open(path + "/" + filename, "r").read())
702 list_info_dict.update(loadDefineLists(comment_list))
703 project.setInfo("MODULES", module_info_dict)
704 project.setInfo("LISTS", list_info_dict)
705 project.setInfo("CONFIGURATIONS", configuration_info_dict)
706 project.setInfo("FILES", file_dict)
708 def formatParamNameValue(text):
710 Take the given string and return a tuple with the name of the parameter in the first position
711 and the value in the second.
713 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
716 def loadConfigurationInfos(path):
718 Return the module configurations found in the given file as a dict with the
719 parameter name as key and a dict containig the fields above as value:
720 "value": the value of the parameter
721 "description": the description of the parameter
722 "informations": a dict containig optional informations:
723 "type": "int" | "boolean" | "enum"
724 "min": the minimum value for integer parameters
725 "max": the maximum value for integer parameters
726 "long": boolean indicating if the num is a long
727 "unsigned": boolean indicating if the num is an unsigned
728 "value_list": the name of the enum for enum parameters
729 "conditional_deps": the list of conditional dependencies for boolean parameters
731 configuration_infos = {}
732 configuration_infos["paramlist"] = []
733 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
734 name, value = formatParamNameValue(define)
735 brief, description, informations = getDescriptionInformations(comment)
736 configuration_infos["paramlist"].append((start, name))
737 configuration_infos[name] = {}
738 configuration_infos[name]["value"] = value
739 configuration_infos[name]["informations"] = informations
740 if not "type" in configuration_infos[name]["informations"]:
741 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
742 if ("type" in configuration_infos[name]["informations"] and
743 configuration_infos[name]["informations"]["type"] == "int" and
744 configuration_infos[name]["value"].find("L") != -1):
745 configuration_infos[name]["informations"]["long"] = True
746 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
747 if ("type" in configuration_infos[name]["informations"] and
748 configuration_infos[name]["informations"]["type"] == "int" and
749 configuration_infos[name]["value"].find("U") != -1):
750 configuration_infos[name]["informations"]["unsigned"] = True
751 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
752 if "conditional_deps" in configuration_infos[name]["informations"]:
753 if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
754 type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
755 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
756 elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
759 configuration_infos[name]["informations"]["conditional_deps"] = ()
760 configuration_infos[name]["description"] = description
761 configuration_infos[name]["brief"] = brief
762 return configuration_infos
764 def updateConfigurationValues(def_conf, user_conf):
765 for param in def_conf["paramlist"]:
766 if param[1] in user_conf and "value" in user_conf[param[1]]:
767 def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
770 def findParameterType(parameter):
771 if "value_list" in parameter["informations"]:
773 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
776 def sub(string, parameter, value):
778 Substitute the given value at the given parameter define in the given string
780 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
782 def isInt(informations):
784 Return True if the value is a simple int.
786 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
791 def isLong(informations):
793 Return True if the value is a long.
795 if "long" in informations and informations["long"] and "unsigned" not in informations:
800 def isUnsigned(informations):
802 Return True if the value is an unsigned.
804 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
809 def isUnsignedLong(informations):
811 Return True if the value is an unsigned long.
813 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
818 class ParseError(Exception):
819 def __init__(self, line_number, line):
820 Exception.__init__(self)
821 self.line_number = line_number
824 class SupportedException(Exception):
825 def __init__(self, support_string):
826 Exception.__init__(self)
827 self.support_string = support_string