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 # If PROJECT_NAME is not defined it use the directory name as PROJECT_NAME
65 # NOTE: this can throw an Exception if the user has changed the directory containing the project
66 project_info.setInfo("PROJECT_NAME", project_data.get("PROJECT_NAME", os.path.basename(project_dir)))
67 project_info.setInfo("PROJECT_PATH", os.path.dirname(project_file))
68 # Check for the Wizard version
69 wizard_version = project_data.get("WIZARD_VERSION", 0)
70 # Ignore the SOURCES_PATH inside the project file
71 project_data["SOURCES_PATH"] = project_dir
72 if "SOURCES_PATH" in info_dict:
73 project_data["SOURCES_PATH"] = info_dict["SOURCES_PATH"]
74 if os.path.exists(project_data["SOURCES_PATH"]):
75 project_info.setInfo("SOURCES_PATH", project_data["SOURCES_PATH"])
77 raise VersionException(project_info)
78 if not isBertosDir(project_dir):
79 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
80 open(os.path.join(project_dir, "VERSION"), "w").write(version_file.replace("$version", "").strip())
81 project_info.loadSourceTree()
82 cpu_name = project_data["CPU_NAME"]
83 project_info.setInfo("CPU_NAME", cpu_name)
84 cpu_info = loadCpuInfos(project_info)
86 if cpu["CPU_NAME"] == cpu_name:
87 project_info.setInfo("CPU_INFOS", cpu)
89 tag_list = getTagSet(cpu_info)
90 # Create, fill and store the dict with the tags
92 for element in tag_list:
93 tag_dict[element] = False
94 infos = project_info.info("CPU_INFOS")
96 if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
100 project_info.setInfo("ALL_CPU_TAGS", tag_dict)
101 if "TOOLCHAIN" in info_dict:
102 project_data["TOOLCHAIN"] = info_dict["TOOLCHAIN"]
103 if os.path.exists(project_data["TOOLCHAIN"]["path"]):
104 project_info.setInfo("TOOLCHAIN", project_data["TOOLCHAIN"])
106 raise ToolchainException(project_info)
107 project_info.setInfo("SELECTED_FREQ", project_data["SELECTED_FREQ"])
108 project_info.setInfo("OUTPUT", project_data["OUTPUT"])
109 loadModuleData(project_info, True)
110 setEnabledModules(project_info, project_data["ENABLED_MODULES"])
113 def setEnabledModules(project_info, enabled_modules):
114 modules = project_info.info("MODULES")
116 for module, information in modules.items():
117 information["enabled"] = module in enabled_modules
118 if information["enabled"]:
119 for dependency in information["depends"]:
120 if not dependency in modules:
121 files[dependency] = files.get(dependency, 0) + 1
122 project_info.setInfo("MODULES", modules)
123 project_info.setInfo("FILES", files)
125 def enabledModules(project_info):
127 for name, module in project_info.info("MODULES").items():
128 if module["enabled"]:
129 enabled_modules.append(name)
130 return enabled_modules
132 def mergeSources(srcdir, new_sources, old_sources):
133 # The current mergeSources function provide only a raw copy of the sources in the
136 # TODO: implement the three way merge algorithm
138 shutil.rmtree(srcdir, True)
139 copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
141 def projectFileGenerator(project_info):
142 directory = project_info.info("PROJECT_PATH")
145 for module, information in project_info.info("MODULES").items():
146 if information["enabled"]:
147 enabled_modules.append(module)
148 project_data["ENABLED_MODULES"] = enabled_modules
149 # Use the local BeRTOS version instead of the original one
150 # project_data["SOURCES_PATH"] = project_info.info("SOURCES_PATH")
151 project_data["SOURCES_PATH"] = directory
152 project_data["PROJECT_NAME"] = project_info.info("PROJECT_NAME", os.path.basename(directory))
153 project_data["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
154 project_data["CPU_NAME"] = project_info.info("CPU_NAME")
155 project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
156 project_data["OUTPUT"] = project_info.info("OUTPUT")
157 project_data["WIZARD_VERSION"] = WIZARD_VERSION
158 return pickle.dumps(project_data)
160 def createBertosProject(project_info, edit=False):
161 directory = project_info.info("PROJECT_PATH")
162 sources_dir = project_info.info("SOURCES_PATH")
163 old_sources_dir = project_info.info("OLD_SOURCES_PATH")
165 if os.path.isdir(directory):
166 shutil.rmtree(directory, True)
167 os.makedirs(directory)
168 # Write the project file
169 f = open(directory + "/project.bertos", "w")
170 f.write(projectFileGenerator(project_info))
173 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
174 open(directory + "/VERSION", "w").write(versionFileGenerator(project_info, version_file))
175 # Destination source dir
176 srcdir = directory + "/bertos"
178 # If not in editing mode it copies all the bertos sources in the /bertos subdirectory of the project
179 shutil.rmtree(srcdir, True)
180 copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
181 elif old_sources_dir:
182 # If in editing mode it merges the current bertos sources with the selected ones
183 # TODO: implement the three way merge algotihm
185 mergeSources(srcdir, sources_dir, old_sources_dir)
186 # Destination makefile
187 makefile = directory + "/Makefile"
188 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), 'r').read()
189 makefile = makefileGenerator(project_info, makefile)
190 open(directory + "/Makefile", "w").write(makefile)
191 # Destination project dir
192 # prjdir = directory + "/" + os.path.basename(directory)
193 prjdir = os.path.join(directory, project_info.info("PROJECT_NAME"))
195 shutil.rmtree(prjdir, True)
197 # Destination hw files
198 hwdir = prjdir + "/hw"
200 shutil.rmtree(hwdir, True)
202 # Copy all the hw files
203 for module, information in project_info.info("MODULES").items():
204 for hwfile in information["hw"]:
205 string = open(sources_dir + "/" + hwfile, "r").read()
206 hwfile_path = hwdir + "/" + os.path.basename(hwfile)
207 if not edit or not os.path.exists(hwfile_path):
208 # If not in editing mode it copies all the hw files. If in
209 # editing mode it copies only the files that don't exist yet
210 open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
211 # Destination configurations files
212 cfgdir = prjdir + "/cfg"
214 shutil.rmtree(cfgdir, True)
216 # Set properly the autoenabled parameters
217 for module, information in project_info.info("MODULES").items():
218 if "configuration" in information and information["configuration"] != "":
219 configurations = project_info.info("CONFIGURATIONS")
220 configuration = configurations[information["configuration"]]
221 for start, parameter in configuration["paramlist"]:
222 if "type" in configuration[parameter]["informations"] and configuration[parameter]["informations"]["type"] == "autoenabled":
223 configuration[parameter]["value"] = "1" if information["enabled"] else "0"
224 project_info.setInfo("CONFIGURATIONS", configurations)
225 # Copy all the configuration files
226 for configuration, information in project_info.info("CONFIGURATIONS").items():
227 string = open(sources_dir + "/" + configuration, "r").read()
228 for start, parameter in information["paramlist"]:
229 infos = information[parameter]
230 value = infos["value"]
231 if "unsigned" in infos["informations"] and infos["informations"]["unsigned"]:
233 if "long" in infos["informations"] and infos["informations"]["long"]:
235 string = sub(string, parameter, value)
236 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
240 # Destination user mk file (only on project creation)
241 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
242 # Deadly performances loss was here :(
243 makefile = userMkGenerator(project_info, makefile)
244 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
245 # Destination wizard mk file
246 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template_wiz.mk"), "r").read()
247 makefile = mkGenerator(project_info, makefile)
248 open(prjdir + "/" + os.path.basename(prjdir) + "_wiz.mk", "w").write(makefile)
249 # Destination main.c file
251 main = open(os.path.join(const.DATA_DIR, "srctemplates/main.c"), "r").read()
252 open(prjdir + "/main.c", "w").write(main)
253 # Files for selected plugins
255 for plugin in project_info.info("OUTPUT"):
256 module = loadPlugin(plugin)
257 relevants_files[plugin] = module.createProject(project_info)
258 project_info.setInfo("RELEVANT_FILES", relevants_files)
260 def loadPlugin(plugin):
262 Returns the given plugin module.
264 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
266 def versionFileGenerator(project_info, version_file):
267 version = bertosVersion(project_info.info("SOURCES_PATH"))
268 return version_file.replace('$version', version)
270 def userMkGenerator(project_info, makefile):
272 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
273 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
275 while makefile.find(key) != -1:
276 makefile = makefile.replace(key, mk_data[key])
279 def mkGenerator(project_info, makefile):
281 Generates the mk file for the current project.
284 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
285 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
286 cpu_mk_parameters = []
287 for key, value in project_info.info("CPU_INFOS").items():
288 if key.startswith(const.MK_PARAM_ID):
289 cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
290 mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
291 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
292 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
293 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
294 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
296 while makefile.find(key) != -1:
297 makefile = makefile.replace(key, mk_data[key])
300 def makefileGenerator(project_info, makefile):
302 Generate the Makefile for the current project.
304 # TODO write a general function that works for both the mk file and the Makefile
305 while makefile.find("$pname") != -1:
306 makefile = makefile.replace("$pname", os.path.basename(project_info.info("PROJECT_PATH")))
309 def csrcGenerator(project_info):
310 modules = project_info.info("MODULES")
311 files = project_info.info("FILES")
312 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
316 # file to be included in CSRC variable
318 # file to be included in PCSRC variable
320 # files to be included in CPPASRC variable
322 # files to be included in CXXSRC variable
324 # files to be included in ASRC variable
326 # constants to be included at the beginning of the makefile
328 for module, information in modules.items():
329 module_files = set([])
330 dependency_files = set([])
333 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
334 if information["enabled"]:
335 if "constants" in information:
336 constants.update(information["constants"])
337 cfiles, sfiles = findModuleFiles(module, project_info)
338 module_files |= set(cfiles)
339 asm_files |= set(sfiles)
340 for file in information["hw"]:
341 if file.endswith(".c"):
342 module_files |= set([hwdir + "/" + os.path.basename(file)])
343 for file_dependency in information["depends"] + tuple(files.keys()):
344 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
345 dependency_files |= set(dependencyCFiles)
346 asm_files |= set(dependencySFiles)
347 for file in module_files:
348 if not harvard or information.get("harvard", "both") == "both":
350 if harvard and "harvard" in information:
352 for file in dependency_files:
354 for file in project_info.info("CPU_INFOS")["C_SRC"]:
356 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
358 for file in asm_files:
360 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
362 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
364 for file in project_info.info("CPU_INFOS")["ASRC"]:
367 csrc = " \\\n\t".join(csrc) + " \\"
369 pcsrc = " \\\n\t".join(pcsrc) + " \\"
370 cppasrc = set(cppasrc)
371 cppasrc = " \\\n\t".join(cppasrc) + " \\"
373 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
375 asrc = " \\\n\t".join(asrc) + " \\"
376 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
377 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
379 def findModuleFiles(module, project_info):
380 # Find the files related to the selected module
383 # .c files related to the module and the cpu architecture
384 for filename, path in project_info.searchFiles(module + ".c") + \
385 project_info.searchFiles(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c"):
386 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
387 path = replaceSeparators(path)
388 cfiles.append(path + "/" + filename)
389 # .s files related to the module and the cpu architecture
390 for filename, path in project_info.searchFiles(module + ".s") + \
391 project_info.searchFiles(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s") + \
392 project_info.searchFiles(module + ".S") + \
393 project_info.searchFiles(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S"):
394 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
395 path = replaceSeparators(path)
396 sfiles.append(path + "/" + filename)
397 # .c and .s files related to the module and the cpu tags
398 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
399 for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
400 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
402 path = replaceSeparators(path)
403 cfiles.append(path + "/" + filename)
404 for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
405 project_info.searchFiles(module + "_" + tag + ".S"):
406 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
407 path = replaceSeparators(path)
408 sfiles.append(path + "/" + filename)
409 return cfiles, sfiles
411 def replaceSeparators(path):
413 Replace the separators in the given path with unix standard separator.
416 while path.find(os.sep) != -1:
417 path = path.replace(os.sep, "/")
421 path = os.environ["PATH"]
423 path = path.split(";")
425 path = path.split(":")
428 def findToolchains(path_list):
430 for element in path_list:
431 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
432 toolchains.append(toolchain)
433 return list(set(toolchains))
435 def getToolchainInfo(output):
437 expr = re.compile("Target: .*")
438 target = expr.findall(output)
440 info["target"] = target[0].split("Target: ")[1]
441 expr = re.compile("gcc version [0-9,.]*")
442 version = expr.findall(output)
443 if len(version) == 1:
444 info["version"] = version[0].split("gcc version ")[1]
445 expr = re.compile("gcc version [0-9,.]* \(.*\)")
446 build = expr.findall(output)
448 build = build[0].split("gcc version ")[1]
449 build = build[build.find("(") + 1 : build.find(")")]
450 info["build"] = build
451 expr = re.compile("Configured with: .*")
452 configured = expr.findall(output)
453 if len(configured) == 1:
454 info["configured"] = configured[0].split("Configured with: ")[1]
455 expr = re.compile("Thread model: .*")
456 thread = expr.findall(output)
458 info["thread"] = thread[0].split("Thread model: ")[1]
461 def getToolchainName(toolchain_info):
462 name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
465 def loadCpuInfos(project_info):
467 for definition in project_info.findDefinitions(const.CPU_DEFINITION):
468 cpuInfos.append(getInfos(definition))
471 def getTagSet(cpu_info):
474 tag_set |= set([cpu["CPU_NAME"]])
475 tag_set |= set(cpu["CPU_TAGS"])
476 tag_set |= set([cpu["TOOLCHAIN"]])
480 def getInfos(definition):
482 D.update(const.CPU_DEF)
483 def include(filename, dict = D, directory=definition[1]):
484 execfile(directory + "/" + filename, {}, D)
485 D["include"] = include
486 include(definition[0], D)
487 D["CPU_NAME"] = definition[0].split(".")[0]
488 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
492 def getCommentList(string):
493 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
494 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
497 def loadModuleDefinition(first_comment):
499 module_definition = {}
500 for num, line in enumerate(first_comment):
501 index = line.find("$WIZ$")
505 exec line[index + len("$WIZ$ "):] in {}, module_definition
507 raise ParseError(num, line[index:])
508 elif line.find("\\brief") != -1:
509 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
511 if "module_name" in module_definition:
512 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
513 del module_definition[const.MODULE_DEFINITION["module_name"]]
514 module_dict[module_name] = {}
515 if const.MODULE_DEFINITION["module_depends"] in module_definition:
516 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
517 del module_definition[const.MODULE_DEFINITION["module_depends"]]
518 if type(depends) == str:
520 module_dict[module_name]["depends"] = depends
522 module_dict[module_name]["depends"] = ()
523 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
524 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
525 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
527 module_dict[module_name]["configuration"] = ""
528 if "module_description" in module_definition:
529 module_dict[module_name]["description"] = module_definition["module_description"]
530 del module_definition["module_description"]
531 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
532 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
533 module_dict[module_name]["harvard"] = harvard
534 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
535 if const.MODULE_DEFINITION["module_hw"] in module_definition:
536 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
537 del module_definition[const.MODULE_DEFINITION["module_hw"]]
540 module_dict[module_name]["hw"] = hw
542 module_dict[module_name]["hw"] = ()
543 if const.MODULE_DEFINITION["module_supports"] in module_definition:
544 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
545 del module_definition[const.MODULE_DEFINITION["module_supports"]]
546 module_dict[module_name]["supports"] = supports
547 module_dict[module_name]["constants"] = module_definition
548 module_dict[module_name]["enabled"] = False
549 return to_be_parsed, module_dict
551 def isSupported(project, module=None, property_id=None):
552 if not module and property_id:
553 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
555 item = project.info("MODULES")[module]
556 tag_dict = project.info("ALL_CPU_TAGS")
557 if "supports" in item:
558 support_string = item["supports"]
561 exec "supported = " + support_string in tag_dict, supported
563 raise SupportedException(support_string)
564 return supported["supported"]
568 def loadDefineLists(comment_list):
570 for comment in comment_list:
571 for num, line in enumerate(comment):
572 index = line.find("$WIZ$")
575 exec line[index + len("$WIZ$ "):] in {}, define_list
577 raise ParseError(num, line[index:])
578 for key, value in define_list.items():
579 if type(value) == str:
580 define_list[key] = (value,)
583 def getDescriptionInformations(comment):
585 Take the doxygen comment and strip the wizard informations, returning the tuple
586 (comment, wizard_information)
591 for num, line in enumerate(comment):
592 index = line.find("$WIZ$")
595 brief += line[:index].strip()
597 description += " " + line[:index]
599 exec line[index + len("$WIZ$ "):] in {}, information
601 raise ParseError(num, line[index:])
604 brief += line.strip()
606 description += " " + line
607 description = description.strip()
608 return brief.strip(), description.strip(), information
610 def getDefinitionBlocks(text):
612 Take a text and return a list of tuple (description, name-value).
615 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
616 for match in block_tmp:
617 # Only the first element is needed
618 comment = match.group(1)
619 define = match.group(2)
620 start = match.start()
621 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
622 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
623 comment = match.group(1)
624 define = match.group(2)
625 start = match.start()
626 block.append(([comment], define, start))
627 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
628 comment = match.group(2)
629 define = match.group(1)
630 start = match.start()
631 block.append(([comment], define, start))
634 def loadModuleData(project_info, edit=False):
635 module_info_dict = {}
637 configuration_info_dict = {}
639 for filename, path in project_info.findDefinitions("*.h") + project_info.findDefinitions("*.c") + project_info.findDefinitions("*.s") + project_info.findDefinitions("*.S"):
640 comment_list = getCommentList(open(path + "/" + filename, "r").read())
641 if len(comment_list) > 0:
643 configuration_info = {}
645 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
646 except ParseError, err:
647 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
648 for module, information in module_dict.items():
649 if "depends" not in information:
650 information["depends"] = ()
651 information["depends"] += (filename.split(".")[0],)
652 information["category"] = os.path.basename(path)
653 if "configuration" in information and len(information["configuration"]):
654 configuration = module_dict[module]["configuration"]
656 configuration_info[configuration] = loadConfigurationInfos(project_info.info("SOURCES_PATH") + "/" + configuration)
657 except ParseError, err:
658 raise DefineException.ConfigurationDefineException(project_info.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
661 path = project_info.info("PROJECT_NAME")
662 directory = project_info.info("PROJECT_PATH")
663 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
664 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
665 except ParseError, err:
666 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
667 module_info_dict.update(module_dict)
668 configuration_info_dict.update(configuration_info)
671 list_dict = loadDefineLists(comment_list[1:])
672 list_info_dict.update(list_dict)
673 except ParseError, err:
674 raise DefineException.EnumDefineException(path, err.line_number, err.line)
675 for filename, path in project_info.findDefinitions("*_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".h"):
676 comment_list = getCommentList(open(path + "/" + filename, "r").read())
677 list_info_dict.update(loadDefineLists(comment_list))
678 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
679 for filename, path in project_info.findDefinitions("*_" + tag + ".h"):
680 comment_list = getCommentList(open(path + "/" + filename, "r").read())
681 list_info_dict.update(loadDefineLists(comment_list))
682 project_info.setInfo("MODULES", module_info_dict)
683 project_info.setInfo("LISTS", list_info_dict)
684 project_info.setInfo("CONFIGURATIONS", configuration_info_dict)
685 project_info.setInfo("FILES", file_dict)
687 def formatParamNameValue(text):
689 Take the given string and return a tuple with the name of the parameter in the first position
690 and the value in the second.
692 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
695 def loadConfigurationInfos(path):
697 Return the module configurations found in the given file as a dict with the
698 parameter name as key and a dict containig the fields above as value:
699 "value": the value of the parameter
700 "description": the description of the parameter
701 "informations": a dict containig optional informations:
702 "type": "int" | "boolean" | "enum"
703 "min": the minimum value for integer parameters
704 "max": the maximum value for integer parameters
705 "long": boolean indicating if the num is a long
706 "unsigned": boolean indicating if the num is an unsigned
707 "value_list": the name of the enum for enum parameters
708 "conditional_deps": the list of conditional dependencies for boolean parameters
710 configuration_infos = {}
711 configuration_infos["paramlist"] = []
712 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
713 name, value = formatParamNameValue(define)
714 brief, description, informations = getDescriptionInformations(comment)
715 configuration_infos["paramlist"].append((start, name))
716 configuration_infos[name] = {}
717 configuration_infos[name]["value"] = value
718 configuration_infos[name]["informations"] = informations
719 if not "type" in configuration_infos[name]["informations"]:
720 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
721 if ("type" in configuration_infos[name]["informations"] and
722 configuration_infos[name]["informations"]["type"] == "int" and
723 configuration_infos[name]["value"].find("L") != -1):
724 configuration_infos[name]["informations"]["long"] = True
725 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
726 if ("type" in configuration_infos[name]["informations"] and
727 configuration_infos[name]["informations"]["type"] == "int" and
728 configuration_infos[name]["value"].find("U") != -1):
729 configuration_infos[name]["informations"]["unsigned"] = True
730 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
731 if "conditional_deps" in configuration_infos[name]["informations"]:
732 if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
733 type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
734 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
735 elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
738 configuration_infos[name]["informations"]["conditional_deps"] = ()
739 configuration_infos[name]["description"] = description
740 configuration_infos[name]["brief"] = brief
741 return configuration_infos
743 def updateConfigurationValues(def_conf, user_conf):
744 for param in def_conf["paramlist"]:
745 if param[1] in user_conf and "value" in user_conf[param[1]]:
746 def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
749 def findParameterType(parameter):
750 if "value_list" in parameter["informations"]:
752 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
755 def sub(string, parameter, value):
757 Substitute the given value at the given parameter define in the given string
759 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
761 def isInt(informations):
763 Return True if the value is a simple int.
765 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
770 def isLong(informations):
772 Return True if the value is a long.
774 if "long" in informations and informations["long"] and "unsigned" not in informations:
779 def isUnsigned(informations):
781 Return True if the value is an unsigned.
783 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
788 def isUnsignedLong(informations):
790 Return True if the value is an unsigned long.
792 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
797 class ParseError(Exception):
798 def __init__(self, line_number, line):
799 Exception.__init__(self)
800 self.line_number = line_number
803 class SupportedException(Exception):
804 def __init__(self, support_string):
805 Exception.__init__(self)
806 self.support_string = support_string