4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
9 # Author: Lorenzo Berni <duplo@develer.com>
19 import codelite_project
20 import DefineException
22 def isBertosDir(directory):
23 return os.path.exists(directory + "/VERSION")
25 def bertosVersion(directory):
26 return open(directory + "/VERSION").readline().strip()
28 def createBertosProject(project_info):
29 directory = project_info.info("PROJECT_PATH")
30 sources_dir = project_info.info("SOURCES_PATH")
31 if not os.path.isdir(directory):
33 f = open(directory + "/project.bertos", "w")
34 f.write(repr(project_info))
36 ## Destination source dir
37 srcdir = directory + "/bertos"
38 shutil.rmtree(srcdir, True)
39 shutil.copytree(sources_dir + "/bertos", srcdir)
40 ## Destination makefile
41 makefile = directory + "/Makefile"
42 if os.path.exists(makefile):
44 makefile = open("mktemplates/Makefile").read()
45 makefile = makefileGenerator(project_info, makefile)
46 open(directory + "/Makefile", "w").write(makefile)
47 ## Destination project dir
48 prjdir = directory + "/" + os.path.basename(directory)
49 shutil.rmtree(prjdir, True)
51 ## Destination configurations files
52 cfgdir = prjdir + "/cfg"
53 shutil.rmtree(cfgdir, True)
55 for configuration, information in project_info.info("CONFIGURATIONS").items():
56 string = open(sources_dir + "/" + configuration, "r").read()
57 for start, parameter in information["paramlist"]:
58 infos = information[parameter]
59 value = infos["value"]
60 if "type" in infos["informations"] and infos["informations"]["type"] == "autoenabled":
62 if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
64 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
66 string = sub(string, parameter, value)
67 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
71 makefile = open("mktemplates/template.mk", "r").read()
72 makefile = mkGenerator(project_info, makefile)
73 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
74 ## Destination main.c file
75 main = open("srctemplates/main.c", "r").read()
76 open(prjdir + "/main.c", "w").write(main)
77 if "codelite" in project_info.info("OUTPUT"):
78 workspace = codeliteWorkspaceGenerator(project_info)
79 open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
80 project = codeliteProjectGenerator(project_info)
81 open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
83 def mkGenerator(project_info, makefile):
85 Generates the mk file for the current project.
88 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
89 mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
90 mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
91 mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
92 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$constants"] = csrcGenerator(project_info)
93 mk_data["$prefix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
94 mk_data["$suffix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[1]
95 mk_data["$cross"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
96 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
98 while makefile.find(key) != -1:
99 makefile = makefile.replace(key, mk_data[key])
102 def makefileGenerator(project_info, makefile):
104 Generate the Makefile for the current project.
106 # TODO: write a general function that works for both the mk file and the Makefile
107 while makefile.find("project_name") != -1:
108 makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
111 def csrcGenerator(project_info):
112 modules = project_info.info("MODULES")
113 files = project_info.info("FILES")
114 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
118 ## file to be included in CSRC variable
120 ## file to be included in PCSRC variable
122 ## constants to be included at the beginning of the makefile
124 for module, information in modules.items():
125 module_files = set([])
126 dependency_files = set([])
129 if information["enabled"]:
130 if "constants" in information:
131 constants.update(information["constants"])
132 cfiles, sfiles = findModuleFiles(module, project_info)
133 module_files |= set(cfiles)
134 asm_files |= set(sfiles)
135 for file_dependency in information["depends"]:
136 if file_dependency in files:
137 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
138 dependency_files |= set(dependencyCFiles)
139 asm_files |= set(dependencySFiles)
140 for file in module_files:
141 if not harvard or "harvard" not in information or information["harvard"] == "both":
143 if harvard and "harvard" in information:
145 for file in dependency_files:
147 csrc = " \\\n\t".join(csrc) + " \\"
148 pcsrc = " \\\n\t".join(pcsrc) + " \\"
149 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
150 return csrc, pcsrc, constants
152 def findModuleFiles(module, project_info):
153 ## Find the files related to the selected module
156 ## .c files related to the module and the cpu architecture
157 for filename, path in findDefinitions(module + ".c", project_info) + \
158 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
159 path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
160 cfiles.append(path + "/" + filename)
161 ## .s files related to the module and the cpu architecture
162 for filename, path in findDefinitions(module + ".s", project_info) + \
163 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
164 findDefinitions(module + ".S", project_info) + \
165 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
166 path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
167 sfiles.append(path + "/" + filename)
168 ## .c and .s files related to the module and the cpu tags
169 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
170 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
171 path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
172 cfiles.append(path + "/" + filename)
173 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
174 findDefinitions(module + "_" + tag + ".S", project_info):
175 path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
176 sfiles.append(path + "/" + filename)
177 return cfiles, sfiles
179 def codeliteProjectGenerator(project_info):
180 template = open("cltemplates/bertos.project").read()
181 filelist = "\n".join(codelite_project.clFiles(codelite_project.findSources(project_info.info("PROJECT_PATH")), project_info.info("PROJECT_PATH")))
182 while template.find("$filelist") != -1:
183 template = template.replace("$filelist", filelist)
184 project_name = os.path.basename(project_info.info("PROJECT_PATH"))
185 while template.find("$project") != -1:
186 template = template.replace("$project", project_name)
189 def codeliteWorkspaceGenerator(project_info):
190 template = open("cltemplates/bertos.workspace").read()
191 project_name = os.path.basename(project_info.info("PROJECT_PATH"))
192 while template.find("$project") != -1:
193 template = template.replace("$project", project_name)
197 path = os.environ["PATH"]
199 path = path.split(";")
201 path = path.split(":")
204 def findToolchains(path_list):
206 for element in path_list:
207 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
208 toolchains.append(toolchain)
209 return list(set(toolchains))
211 def getToolchainInfo(output):
213 expr = re.compile("Target: .*")
214 target = expr.findall(output)
216 info["target"] = target[0].split("Target: ")[1]
217 expr = re.compile("gcc version [0-9,.]*")
218 version = expr.findall(output)
219 if len(version) == 1:
220 info["version"] = version[0].split("gcc version ")[1]
221 expr = re.compile("gcc version [0-9,.]* \(.*\)")
222 build = expr.findall(output)
224 build = build[0].split("gcc version ")[1]
225 build = build[build.find("(") + 1 : build.find(")")]
226 info["build"] = build
227 expr = re.compile("Configured with: .*")
228 configured = expr.findall(output)
229 if len(configured) == 1:
230 info["configured"] = configured[0].split("Configured with: ")[1]
231 expr = re.compile("Thread model: .*")
232 thread = expr.findall(output)
234 info["thread"] = thread[0].split("Thread model: ")[1]
237 def loadSourceTree(project):
238 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
239 project.setInfo("FILE_LIST", fileList)
241 def findDefinitions(ftype, project):
242 L = project.info("FILE_LIST")
245 for filename in element[2]:
246 if fnmatch.fnmatch(filename, ftype):
247 definitions.append((filename, element[0]))
250 def loadCpuInfos(project):
252 for definition in findDefinitions(const.CPU_DEFINITION, project):
253 cpuInfos.append(getInfos(definition))
256 def getInfos(definition):
258 D.update(const.CPU_DEF)
259 def include(filename, dict = D, directory=definition[1]):
260 execfile(directory + "/" + filename, {}, D)
261 D["include"] = include
262 include(definition[0], D)
263 D["CPU_NAME"] = definition[0].split(".")[0]
264 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
268 def getCommentList(string):
269 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
270 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
273 def loadModuleDefinition(first_comment):
275 module_definition = {}
276 for num, line in enumerate(first_comment):
277 index = line.find("$WIZ$")
281 exec line[index + len("$WIZ$ "):] in {}, module_definition
283 raise ParseError(num, line[index:])
284 elif line.find("\\brief") != -1:
285 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
287 if "module_name" in module_definition.keys():
288 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
289 del module_definition[const.MODULE_DEFINITION["module_name"]]
290 module_dict[module_name] = {}
291 if const.MODULE_DEFINITION["module_depends"] in module_definition.keys():
292 if type(module_definition[const.MODULE_DEFINITION["module_depends"]]) == str:
293 module_definition[const.MODULE_DEFINITION["module_depends"]] = (module_definition[const.MODULE_DEFINITION["module_depends"]],)
294 module_dict[module_name]["depends"] = module_definition[const.MODULE_DEFINITION["module_depends"]]
295 del module_definition[const.MODULE_DEFINITION["module_depends"]]
297 module_dict[module_name]["depends"] = ()
298 if const.MODULE_DEFINITION["module_configuration"] in module_definition.keys():
299 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
300 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
302 module_dict[module_name]["configuration"] = ""
303 if "module_description" in module_definition.keys():
304 module_dict[module_name]["description"] = module_definition["module_description"]
305 del module_definition["module_description"]
306 if const.MODULE_DEFINITION["module_harvard"] in module_definition.keys():
307 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
308 if harvard == "both" or harvard == "pgm_memory":
309 module_dict[module_name]["harvard"] = harvard
310 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
311 module_dict[module_name]["constants"] = module_definition
312 module_dict[module_name]["enabled"] = False
313 return to_be_parsed, module_dict
315 def loadDefineLists(comment_list):
317 for comment in comment_list:
318 for num, line in enumerate(comment):
319 index = line.find("$WIZ$")
322 exec line[index + len("$WIZ$ "):] in {}, define_list
324 raise ParseError(num, line[index:])
325 for key, value in define_list.items():
326 if type(value) == str:
327 define_list[key] = (value,)
330 def getDescriptionInformations(comment):
332 Take the doxygen comment and strip the wizard informations, returning the tuple
333 (comment, wizard_information)
338 for num, line in enumerate(comment):
339 index = line.find("$WIZ$")
342 brief += line[:index].strip()
344 description += " " + line[:index]
346 exec line[index + len("$WIZ$ "):] in {}, information
348 raise ParseError(num, line[index:])
351 brief += line.strip()
353 description += " " + line
354 description = description.strip()
355 return brief.strip(), description.strip(), information
357 def getDefinitionBlocks(text):
359 Take a text and return a list of tuple (description, name-value).
362 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
363 for match in block_tmp:
364 # Only the first element is needed
365 comment = match.group(1)
366 define = match.group(2)
367 start = match.start()
368 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
369 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
370 comment = match.group(1)
371 define = match.group(2)
372 start = match.start()
373 block.append(([comment], define, start))
374 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
375 comment = match.group(2)
376 define = match.group(1)
377 start = match.start()
378 block.append(([comment], define, start))
381 def loadModuleData(project):
382 module_info_dict = {}
384 configuration_info_dict = {}
386 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
387 comment_list = getCommentList(open(path + "/" + filename, "r").read())
388 if len(comment_list) > 0:
390 configuration_info = {}
392 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
393 except ParseError, err:
394 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
395 for module, information in module_dict.items():
396 information["category"] = os.path.basename(path)
397 if "configuration" in information.keys() and len(information["configuration"]):
398 configuration = module_dict[module]["configuration"]
400 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
401 except ParseError, err:
402 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
403 module_info_dict.update(module_dict)
404 configuration_info_dict.update(configuration_info)
407 list_dict = loadDefineLists(comment_list[1:])
408 list_info_dict.update(list_dict)
409 except ParseError, err:
410 raise DefineException.EnumDefineException(path, err.line_number, err.line)
411 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
412 comment_list = getCommentList(open(path + "/" + filename, "r").read())
413 list_info_dict.update(loadDefineLists(comment_list))
414 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
415 for filename, path in findDefinitions("*_" + tag + ".h", project):
416 comment_list = getCommentList(open(path + "/" + filename, "r").read())
417 list_info_dict.update(loadDefineLists(comment_list))
418 project.setInfo("MODULES", module_info_dict)
419 project.setInfo("LISTS", list_info_dict)
420 project.setInfo("CONFIGURATIONS", configuration_info_dict)
421 project.setInfo("FILES", file_dict)
423 def formatParamNameValue(text):
425 Take the given string and return a tuple with the name of the parameter in the first position
426 and the value in the second.
428 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
431 def loadConfigurationInfos(path):
433 Return the module configurations found in the given file as a dict with the
434 parameter name as key and a dict containig the fields above as value:
435 "value": the value of the parameter
436 "description": the description of the parameter
437 "informations": a dict containig optional informations:
438 "type": "int" | "boolean" | "enum"
439 "min": the minimum value for integer parameters
440 "max": the maximum value for integer parameters
441 "long": boolean indicating if the num is a long
442 "unsigned": boolean indicating if the num is an unsigned
443 "value_list": the name of the enum for enum parameters
445 configuration_infos = {}
446 configuration_infos["paramlist"] = []
447 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
448 name, value = formatParamNameValue(define)
449 brief, description, informations = getDescriptionInformations(comment)
450 configuration_infos["paramlist"].append((start, name))
451 configuration_infos[name] = {}
452 configuration_infos[name]["value"] = value
453 configuration_infos[name]["informations"] = informations
454 if not "type" in configuration_infos[name]["informations"]:
455 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
456 if ("type" in configuration_infos[name]["informations"].keys() and
457 configuration_infos[name]["informations"]["type"] == "int" and
458 configuration_infos[name]["value"].find("L") != -1):
459 configuration_infos[name]["informations"]["long"] = True
460 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
461 if ("type" in configuration_infos[name]["informations"].keys() and
462 configuration_infos[name]["informations"]["type"] == "int" and
463 configuration_infos[name]["value"].find("U") != -1):
464 configuration_infos[name]["informations"]["unsigned"] = True
465 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
466 configuration_infos[name]["description"] = description
467 configuration_infos[name]["brief"] = brief
468 return configuration_infos
470 def findParameterType(parameter):
471 if "value_list" in parameter["informations"]:
473 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
476 def sub(string, parameter, value):
478 Substitute the given value at the given parameter define in the given string
480 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
482 def isInt(informations):
484 Return True if the value is a simple int.
486 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
491 def isLong(informations):
493 Return True if the value is a long.
495 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
500 def isUnsigned(informations):
502 Return True if the value is an unsigned.
504 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
509 def isUnsignedLong(informations):
511 Return True if the value is an unsigned long.
513 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
518 class ParseError(Exception):
519 def __init__(self, line_number, line):
520 Exception.__init__(self)
521 self.line_number = line_number