4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
9 # Author: Lorenzo Berni <duplo@develer.com>
17 # Use custom copytree function
22 from plugins import codelite_project
23 import DefineException
25 def isBertosDir(directory):
26 return os.path.exists(directory + "/VERSION")
28 def bertosVersion(directory):
29 return open(directory + "/VERSION").readline().strip()
31 def createBertosProject(project_info):
32 directory = project_info.info("PROJECT_PATH")
33 sources_dir = project_info.info("SOURCES_PATH")
34 if not os.path.isdir(directory):
36 f = open(directory + "/project.bertos", "w")
37 f.write(pickle.dumps(project_info))
39 # Destination source dir
40 srcdir = directory + "/bertos"
41 shutil.rmtree(srcdir, True)
42 copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
43 # Destination makefile
44 makefile = directory + "/Makefile"
45 if os.path.exists(makefile):
47 makefile = open("mktemplates/Makefile").read()
48 makefile = makefileGenerator(project_info, makefile)
49 open(directory + "/Makefile", "w").write(makefile)
50 # Destination project dir
51 prjdir = directory + "/" + os.path.basename(directory)
52 shutil.rmtree(prjdir, True)
54 # Destination configurations files
55 cfgdir = prjdir + "/cfg"
56 shutil.rmtree(cfgdir, True)
58 # Set to 1 the autoenabled for enabled modules
59 for module, information in project_info.info("MODULES").items():
60 if information["enabled"] and "configuration" in information and information["configuration"] != "":
61 configurations = project_info.info("CONFIGURATIONS")
62 configuration = configurations[information["configuration"]]
63 for start, parameter in configuration["paramlist"]:
64 if "type" in configuration[parameter] and configuration[parameter]["type"] == "autoenabled":
65 configuration[parameter]["value"] = "1"
66 project_info.setInfo("CONFIGURATIONS", configurations)
67 # Copy all the configuration files
68 for configuration, information in project_info.info("CONFIGURATIONS").items():
69 string = open(sources_dir + "/" + configuration, "r").read()
70 for start, parameter in information["paramlist"]:
71 infos = information[parameter]
72 value = infos["value"]
73 if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
75 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
77 string = sub(string, parameter, value)
78 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
82 makefile = open("mktemplates/template.mk", "r").read()
83 makefile = mkGenerator(project_info, makefile)
84 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
85 # Destination main.c file
86 main = open("srctemplates/main.c", "r").read()
87 open(prjdir + "/main.c", "w").write(main)
88 # Codelite project files
89 if "codelite" in project_info.info("OUTPUT"):
90 codelite_project.createProject(project_info)
92 def mkGenerator(project_info, makefile):
94 Generates the mk file for the current project.
97 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
98 mk_data["$cpuflag"] = project_info.info("CPU_INFOS")["CPU_FLAG_NAME"]
99 mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
100 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
101 mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
102 mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
103 mk_data["$cppflags"] = " ".join(project_info.info("CPU_INFOS")["CPP_FLAGS"])
104 mk_data["$cppaflags"] = " ".join(project_info.info("CPU_INFOS")["CPPA_FLAGS"])
105 mk_data["$cxxflags"] = " ".join(project_info.info("CPU_INFOS")["CXX_FLAGS"])
106 mk_data["$asflags"] = " ".join(project_info.info("CPU_INFOS")["AS_FLAGS"])
107 mk_data["$arflags"] = " ".join(project_info.info("CPU_INFOS")["AR_FLAGS"])
108 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
109 mk_data["$prefix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
110 mk_data["$suffix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[1]
111 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
113 while makefile.find(key) != -1:
114 makefile = makefile.replace(key, mk_data[key])
117 def makefileGenerator(project_info, makefile):
119 Generate the Makefile for the current project.
121 # TODO write a general function that works for both the mk file and the Makefile
122 while makefile.find("project_name") != -1:
123 makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
126 def csrcGenerator(project_info):
127 modules = project_info.info("MODULES")
128 files = project_info.info("FILES")
129 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
133 # file to be included in CSRC variable
135 # file to be included in PCSRC variable
137 # files to be included in CPPASRC variable
139 # files to be included in CXXSRC variable
141 # files to be included in ASRC variable
143 # constants to be included at the beginning of the makefile
145 for module, information in modules.items():
146 module_files = set([])
147 dependency_files = set([])
150 if information["enabled"]:
151 if "constants" in information:
152 constants.update(information["constants"])
153 cfiles, sfiles = findModuleFiles(module, project_info)
154 module_files |= set(cfiles)
155 asm_files |= set(sfiles)
156 for file_dependency in information["depends"]:
157 if file_dependency in files:
158 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
159 dependency_files |= set(dependencyCFiles)
160 asm_files |= set(dependencySFiles)
161 for file in module_files:
162 if not harvard or "harvard" not in information or information["harvard"] == "both":
164 if harvard and "harvard" in information:
166 for file in dependency_files:
168 for file in project_info.info("CPU_INFOS")["C_SRC"]:
170 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
172 for file in asm_files:
174 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
176 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
178 for file in project_info.info("CPU_INFOS")["ASRC"]:
180 csrc = " \\\n\t".join(csrc) + " \\"
181 pcsrc = " \\\n\t".join(pcsrc) + " \\"
182 cppasrc = " \\\n\t".join(cppasrc) + " \\"
183 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
184 asrc = " \\\n\t".join(asrc) + " \\"
185 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
186 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
188 def findModuleFiles(module, project_info):
189 # Find the files related to the selected module
192 # .c files related to the module and the cpu architecture
193 for filename, path in findDefinitions(module + ".c", project_info) + \
194 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
195 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
197 path = replaceSeparators(path)
198 cfiles.append(path + "/" + filename)
199 # .s files related to the module and the cpu architecture
200 for filename, path in findDefinitions(module + ".s", project_info) + \
201 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
202 findDefinitions(module + ".S", project_info) + \
203 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
204 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
206 path = replaceSeparators(path)
207 sfiles.append(path + "/" + filename)
208 # .c and .s files related to the module and the cpu tags
209 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
210 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
211 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
213 path = replaceSeparators(path)
214 cfiles.append(path + "/" + filename)
215 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
216 findDefinitions(module + "_" + tag + ".S", project_info):
217 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
219 path = replaceSeparators(path)
220 sfiles.append(path + "/" + filename)
221 return cfiles, sfiles
223 def replaceSeparators(path):
225 Replace the separators in the given path with unix standard separator.
227 while path.find(os.sep) != -1:
228 path = path.replace(os.sep, "/")
232 path = os.environ["PATH"]
234 path = path.split(";")
236 path = path.split(":")
239 def findToolchains(path_list):
241 for element in path_list:
242 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
243 toolchains.append(toolchain)
244 return list(set(toolchains))
246 def getToolchainInfo(output):
248 expr = re.compile("Target: .*")
249 target = expr.findall(output)
251 info["target"] = target[0].split("Target: ")[1]
252 expr = re.compile("gcc version [0-9,.]*")
253 version = expr.findall(output)
254 if len(version) == 1:
255 info["version"] = version[0].split("gcc version ")[1]
256 expr = re.compile("gcc version [0-9,.]* \(.*\)")
257 build = expr.findall(output)
259 build = build[0].split("gcc version ")[1]
260 build = build[build.find("(") + 1 : build.find(")")]
261 info["build"] = build
262 expr = re.compile("Configured with: .*")
263 configured = expr.findall(output)
264 if len(configured) == 1:
265 info["configured"] = configured[0].split("Configured with: ")[1]
266 expr = re.compile("Thread model: .*")
267 thread = expr.findall(output)
269 info["thread"] = thread[0].split("Thread model: ")[1]
272 def loadSourceTree(project):
273 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
274 project.setInfo("FILE_LIST", fileList)
276 def findDefinitions(ftype, project):
277 L = project.info("FILE_LIST")
280 for filename in element[2]:
281 if fnmatch.fnmatch(filename, ftype):
282 definitions.append((filename, element[0]))
285 def loadCpuInfos(project):
287 for definition in findDefinitions(const.CPU_DEFINITION, project):
288 cpuInfos.append(getInfos(definition))
291 def getInfos(definition):
293 D.update(const.CPU_DEF)
294 def include(filename, dict = D, directory=definition[1]):
295 execfile(directory + "/" + filename, {}, D)
296 D["include"] = include
297 include(definition[0], D)
298 D["CPU_NAME"] = definition[0].split(".")[0]
299 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
303 def getCommentList(string):
304 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
305 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
308 def loadModuleDefinition(first_comment):
310 module_definition = {}
311 for num, line in enumerate(first_comment):
312 index = line.find("$WIZ$")
316 exec line[index + len("$WIZ$ "):] in {}, module_definition
318 raise ParseError(num, line[index:])
319 elif line.find("\\brief") != -1:
320 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
322 if "module_name" in module_definition.keys():
323 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
324 del module_definition[const.MODULE_DEFINITION["module_name"]]
325 module_dict[module_name] = {}
326 if const.MODULE_DEFINITION["module_depends"] in module_definition.keys():
327 if type(module_definition[const.MODULE_DEFINITION["module_depends"]]) == str:
328 module_definition[const.MODULE_DEFINITION["module_depends"]] = (module_definition[const.MODULE_DEFINITION["module_depends"]],)
329 module_dict[module_name]["depends"] = module_definition[const.MODULE_DEFINITION["module_depends"]]
330 del module_definition[const.MODULE_DEFINITION["module_depends"]]
332 module_dict[module_name]["depends"] = ()
333 if const.MODULE_DEFINITION["module_configuration"] in module_definition.keys():
334 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
335 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
337 module_dict[module_name]["configuration"] = ""
338 if "module_description" in module_definition.keys():
339 module_dict[module_name]["description"] = module_definition["module_description"]
340 del module_definition["module_description"]
341 if const.MODULE_DEFINITION["module_harvard"] in module_definition.keys():
342 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
343 if harvard == "both" or harvard == "pgm_memory":
344 module_dict[module_name]["harvard"] = harvard
345 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
346 module_dict[module_name]["constants"] = module_definition
347 module_dict[module_name]["enabled"] = False
348 return to_be_parsed, module_dict
350 def loadDefineLists(comment_list):
352 for comment in comment_list:
353 for num, line in enumerate(comment):
354 index = line.find("$WIZ$")
357 exec line[index + len("$WIZ$ "):] in {}, define_list
359 raise ParseError(num, line[index:])
360 for key, value in define_list.items():
361 if type(value) == str:
362 define_list[key] = (value,)
365 def getDescriptionInformations(comment):
367 Take the doxygen comment and strip the wizard informations, returning the tuple
368 (comment, wizard_information)
373 for num, line in enumerate(comment):
374 index = line.find("$WIZ$")
377 brief += line[:index].strip()
379 description += " " + line[:index]
381 exec line[index + len("$WIZ$ "):] in {}, information
383 raise ParseError(num, line[index:])
386 brief += line.strip()
388 description += " " + line
389 description = description.strip()
390 return brief.strip(), description.strip(), information
392 def getDefinitionBlocks(text):
394 Take a text and return a list of tuple (description, name-value).
397 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
398 for match in block_tmp:
399 # Only the first element is needed
400 comment = match.group(1)
401 define = match.group(2)
402 start = match.start()
403 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
404 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
405 comment = match.group(1)
406 define = match.group(2)
407 start = match.start()
408 block.append(([comment], define, start))
409 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
410 comment = match.group(2)
411 define = match.group(1)
412 start = match.start()
413 block.append(([comment], define, start))
416 def loadModuleData(project):
417 module_info_dict = {}
419 configuration_info_dict = {}
421 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
422 comment_list = getCommentList(open(path + "/" + filename, "r").read())
423 if len(comment_list) > 0:
425 configuration_info = {}
427 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
428 except ParseError, err:
429 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
430 for module, information in module_dict.items():
431 if "depends" not in information:
432 information["depends"] = ()
433 information["depends"] += (filename.split(".")[0],)
434 information["category"] = os.path.basename(path)
435 if "configuration" in information.keys() and len(information["configuration"]):
436 configuration = module_dict[module]["configuration"]
438 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
439 except ParseError, err:
440 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
441 module_info_dict.update(module_dict)
442 configuration_info_dict.update(configuration_info)
445 list_dict = loadDefineLists(comment_list[1:])
446 list_info_dict.update(list_dict)
447 except ParseError, err:
448 raise DefineException.EnumDefineException(path, err.line_number, err.line)
449 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
450 comment_list = getCommentList(open(path + "/" + filename, "r").read())
451 list_info_dict.update(loadDefineLists(comment_list))
452 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
453 for filename, path in findDefinitions("*_" + tag + ".h", project):
454 comment_list = getCommentList(open(path + "/" + filename, "r").read())
455 list_info_dict.update(loadDefineLists(comment_list))
456 project.setInfo("MODULES", module_info_dict)
457 project.setInfo("LISTS", list_info_dict)
458 project.setInfo("CONFIGURATIONS", configuration_info_dict)
459 project.setInfo("FILES", file_dict)
461 def formatParamNameValue(text):
463 Take the given string and return a tuple with the name of the parameter in the first position
464 and the value in the second.
466 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
469 def loadConfigurationInfos(path):
471 Return the module configurations found in the given file as a dict with the
472 parameter name as key and a dict containig the fields above as value:
473 "value": the value of the parameter
474 "description": the description of the parameter
475 "informations": a dict containig optional informations:
476 "type": "int" | "boolean" | "enum"
477 "min": the minimum value for integer parameters
478 "max": the maximum value for integer parameters
479 "long": boolean indicating if the num is a long
480 "unsigned": boolean indicating if the num is an unsigned
481 "value_list": the name of the enum for enum parameters
483 configuration_infos = {}
484 configuration_infos["paramlist"] = []
485 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
486 name, value = formatParamNameValue(define)
487 brief, description, informations = getDescriptionInformations(comment)
488 configuration_infos["paramlist"].append((start, name))
489 configuration_infos[name] = {}
490 configuration_infos[name]["value"] = value
491 configuration_infos[name]["informations"] = informations
492 if not "type" in configuration_infos[name]["informations"]:
493 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
494 if ("type" in configuration_infos[name]["informations"].keys() and
495 configuration_infos[name]["informations"]["type"] == "int" and
496 configuration_infos[name]["value"].find("L") != -1):
497 configuration_infos[name]["informations"]["long"] = True
498 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
499 if ("type" in configuration_infos[name]["informations"].keys() and
500 configuration_infos[name]["informations"]["type"] == "int" and
501 configuration_infos[name]["value"].find("U") != -1):
502 configuration_infos[name]["informations"]["unsigned"] = True
503 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
504 configuration_infos[name]["description"] = description
505 configuration_infos[name]["brief"] = brief
506 return configuration_infos
508 def findParameterType(parameter):
509 if "value_list" in parameter["informations"]:
511 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
514 def sub(string, parameter, value):
516 Substitute the given value at the given parameter define in the given string
518 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
520 def isInt(informations):
522 Return True if the value is a simple int.
524 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
529 def isLong(informations):
531 Return True if the value is a long.
533 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
538 def isUnsigned(informations):
540 Return True if the value is an unsigned.
542 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
547 def isUnsignedLong(informations):
549 Return True if the value is an unsigned long.
551 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
556 class ParseError(Exception):
557 def __init__(self, line_number, line):
558 Exception.__init__(self)
559 self.line_number = line_number