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 hw files
55 hwdir = prjdir + "/hw"
56 shutil.rmtree(hwdir, True)
58 # Copy all the hw files
59 for module, information in project_info.info("MODULES").items():
60 for hwfile in information["hw"]:
61 string = open(sources_dir + "/" + hwfile, "r").read()
62 open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
63 # Destination configurations files
64 cfgdir = prjdir + "/cfg"
65 shutil.rmtree(cfgdir, True)
67 # Set to 1 the autoenabled for enabled modules
68 for module, information in project_info.info("MODULES").items():
69 if information["enabled"] and "configuration" in information and information["configuration"] != "":
70 configurations = project_info.info("CONFIGURATIONS")
71 configuration = configurations[information["configuration"]]
72 for start, parameter in configuration["paramlist"]:
73 if "type" in configuration[parameter] and configuration[parameter]["type"] == "autoenabled":
74 configuration[parameter]["value"] = "1"
75 project_info.setInfo("CONFIGURATIONS", configurations)
76 # Copy all the configuration files
77 for configuration, information in project_info.info("CONFIGURATIONS").items():
78 string = open(sources_dir + "/" + configuration, "r").read()
79 for start, parameter in information["paramlist"]:
80 infos = information[parameter]
81 value = infos["value"]
82 if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
84 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
86 string = sub(string, parameter, value)
87 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
91 makefile = open("mktemplates/template.mk", "r").read()
92 makefile = mkGenerator(project_info, makefile)
93 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
94 # Destination main.c file
95 main = open("srctemplates/main.c", "r").read()
96 open(prjdir + "/main.c", "w").write(main)
97 # Codelite project files
98 if "codelite" in project_info.info("OUTPUT"):
99 codelite_project.createProject(project_info)
101 def mkGenerator(project_info, makefile):
103 Generates the mk file for the current project.
106 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
107 mk_data["$cpuflag"] = project_info.info("CPU_INFOS")["CPU_FLAG_NAME"]
108 mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
109 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
110 mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
111 mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
112 mk_data["$cppflags"] = " ".join(project_info.info("CPU_INFOS")["CPP_FLAGS"])
113 mk_data["$cppaflags"] = " ".join(project_info.info("CPU_INFOS")["CPPA_FLAGS"])
114 mk_data["$cxxflags"] = " ".join(project_info.info("CPU_INFOS")["CXX_FLAGS"])
115 mk_data["$asflags"] = " ".join(project_info.info("CPU_INFOS")["AS_FLAGS"])
116 mk_data["$arflags"] = " ".join(project_info.info("CPU_INFOS")["AR_FLAGS"])
117 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
118 mk_data["$prefix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
119 mk_data["$suffix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[1]
120 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
122 while makefile.find(key) != -1:
123 makefile = makefile.replace(key, mk_data[key])
126 def makefileGenerator(project_info, makefile):
128 Generate the Makefile for the current project.
130 # TODO write a general function that works for both the mk file and the Makefile
131 while makefile.find("project_name") != -1:
132 makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
135 def csrcGenerator(project_info):
136 modules = project_info.info("MODULES")
137 files = project_info.info("FILES")
138 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
142 # file to be included in CSRC variable
144 # file to be included in PCSRC variable
146 # files to be included in CPPASRC variable
148 # files to be included in CXXSRC variable
150 # files to be included in ASRC variable
152 # constants to be included at the beginning of the makefile
154 for module, information in modules.items():
155 module_files = set([])
156 dependency_files = set([])
159 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
160 if information["enabled"]:
161 if "constants" in information:
162 constants.update(information["constants"])
163 cfiles, sfiles = findModuleFiles(module, project_info)
164 module_files |= set(cfiles)
165 asm_files |= set(sfiles)
166 for file in information["hw"]:
167 if file.endswith(".c"):
168 module_files |= set([hwdir + "/" + os.path.basename(file)])
169 for file_dependency in information["depends"]:
170 if file_dependency in files:
171 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
172 dependency_files |= set(dependencyCFiles)
173 asm_files |= set(dependencySFiles)
174 for file in module_files:
175 if not harvard or "harvard" not in information or information["harvard"] == "both":
177 if harvard and "harvard" in information:
179 for file in dependency_files:
181 for file in project_info.info("CPU_INFOS")["C_SRC"]:
183 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
185 for file in asm_files:
187 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
189 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
191 for file in project_info.info("CPU_INFOS")["ASRC"]:
193 csrc = " \\\n\t".join(csrc) + " \\"
194 pcsrc = " \\\n\t".join(pcsrc) + " \\"
195 cppasrc = " \\\n\t".join(cppasrc) + " \\"
196 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
197 asrc = " \\\n\t".join(asrc) + " \\"
198 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
199 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
201 def findModuleFiles(module, project_info):
202 # Find the files related to the selected module
205 # .c files related to the module and the cpu architecture
206 for filename, path in findDefinitions(module + ".c", project_info) + \
207 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
208 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
210 path = replaceSeparators(path)
211 cfiles.append(path + "/" + filename)
212 # .s files related to the module and the cpu architecture
213 for filename, path in findDefinitions(module + ".s", project_info) + \
214 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
215 findDefinitions(module + ".S", project_info) + \
216 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
217 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
219 path = replaceSeparators(path)
220 sfiles.append(path + "/" + filename)
221 # .c and .s files related to the module and the cpu tags
222 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
223 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
224 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
226 path = replaceSeparators(path)
227 cfiles.append(path + "/" + filename)
228 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
229 findDefinitions(module + "_" + tag + ".S", project_info):
230 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
232 path = replaceSeparators(path)
233 sfiles.append(path + "/" + filename)
234 return cfiles, sfiles
236 def replaceSeparators(path):
238 Replace the separators in the given path with unix standard separator.
240 while path.find(os.sep) != -1:
241 path = path.replace(os.sep, "/")
245 path = os.environ["PATH"]
247 path = path.split(";")
249 path = path.split(":")
252 def findToolchains(path_list):
254 for element in path_list:
255 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
256 toolchains.append(toolchain)
257 return list(set(toolchains))
259 def getToolchainInfo(output):
261 expr = re.compile("Target: .*")
262 target = expr.findall(output)
264 info["target"] = target[0].split("Target: ")[1]
265 expr = re.compile("gcc version [0-9,.]*")
266 version = expr.findall(output)
267 if len(version) == 1:
268 info["version"] = version[0].split("gcc version ")[1]
269 expr = re.compile("gcc version [0-9,.]* \(.*\)")
270 build = expr.findall(output)
272 build = build[0].split("gcc version ")[1]
273 build = build[build.find("(") + 1 : build.find(")")]
274 info["build"] = build
275 expr = re.compile("Configured with: .*")
276 configured = expr.findall(output)
277 if len(configured) == 1:
278 info["configured"] = configured[0].split("Configured with: ")[1]
279 expr = re.compile("Thread model: .*")
280 thread = expr.findall(output)
282 info["thread"] = thread[0].split("Thread model: ")[1]
285 def loadSourceTree(project):
286 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
287 project.setInfo("FILE_LIST", fileList)
289 def findDefinitions(ftype, project):
290 L = project.info("FILE_LIST")
293 for filename in element[2]:
294 if fnmatch.fnmatch(filename, ftype):
295 definitions.append((filename, element[0]))
298 def loadCpuInfos(project):
300 for definition in findDefinitions(const.CPU_DEFINITION, project):
301 cpuInfos.append(getInfos(definition))
304 def getInfos(definition):
306 D.update(const.CPU_DEF)
307 def include(filename, dict = D, directory=definition[1]):
308 execfile(directory + "/" + filename, {}, D)
309 D["include"] = include
310 include(definition[0], D)
311 D["CPU_NAME"] = definition[0].split(".")[0]
312 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
316 def getCommentList(string):
317 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
318 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
321 def loadModuleDefinition(first_comment):
323 module_definition = {}
324 for num, line in enumerate(first_comment):
325 index = line.find("$WIZ$")
329 exec line[index + len("$WIZ$ "):] in {}, module_definition
331 raise ParseError(num, line[index:])
332 elif line.find("\\brief") != -1:
333 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
335 if "module_name" in module_definition.keys():
336 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
337 del module_definition[const.MODULE_DEFINITION["module_name"]]
338 module_dict[module_name] = {}
339 if const.MODULE_DEFINITION["module_depends"] in module_definition.keys():
340 if type(module_definition[const.MODULE_DEFINITION["module_depends"]]) == str:
341 module_definition[const.MODULE_DEFINITION["module_depends"]] = (module_definition[const.MODULE_DEFINITION["module_depends"]],)
342 module_dict[module_name]["depends"] = module_definition[const.MODULE_DEFINITION["module_depends"]]
343 del module_definition[const.MODULE_DEFINITION["module_depends"]]
345 module_dict[module_name]["depends"] = ()
346 if const.MODULE_DEFINITION["module_configuration"] in module_definition.keys():
347 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
348 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
350 module_dict[module_name]["configuration"] = ""
351 if "module_description" in module_definition.keys():
352 module_dict[module_name]["description"] = module_definition["module_description"]
353 del module_definition["module_description"]
354 if const.MODULE_DEFINITION["module_harvard"] in module_definition.keys():
355 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
356 if harvard == "both" or harvard == "pgm_memory":
357 module_dict[module_name]["harvard"] = harvard
358 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
359 if const.MODULE_DEFINITION["module_hw"] in module_definition.keys():
360 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
361 del module_definition[const.MODULE_DEFINITION["module_hw"]]
364 module_dict[module_name]["hw"] = hw
366 module_dict[module_name]["hw"] = ()
367 module_dict[module_name]["constants"] = module_definition
368 module_dict[module_name]["enabled"] = False
369 return to_be_parsed, module_dict
371 def loadDefineLists(comment_list):
373 for comment in comment_list:
374 for num, line in enumerate(comment):
375 index = line.find("$WIZ$")
378 exec line[index + len("$WIZ$ "):] in {}, define_list
380 raise ParseError(num, line[index:])
381 for key, value in define_list.items():
382 if type(value) == str:
383 define_list[key] = (value,)
386 def getDescriptionInformations(comment):
388 Take the doxygen comment and strip the wizard informations, returning the tuple
389 (comment, wizard_information)
394 for num, line in enumerate(comment):
395 index = line.find("$WIZ$")
398 brief += line[:index].strip()
400 description += " " + line[:index]
402 exec line[index + len("$WIZ$ "):] in {}, information
404 raise ParseError(num, line[index:])
407 brief += line.strip()
409 description += " " + line
410 description = description.strip()
411 return brief.strip(), description.strip(), information
413 def getDefinitionBlocks(text):
415 Take a text and return a list of tuple (description, name-value).
418 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
419 for match in block_tmp:
420 # Only the first element is needed
421 comment = match.group(1)
422 define = match.group(2)
423 start = match.start()
424 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
425 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
426 comment = match.group(1)
427 define = match.group(2)
428 start = match.start()
429 block.append(([comment], define, start))
430 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
431 comment = match.group(2)
432 define = match.group(1)
433 start = match.start()
434 block.append(([comment], define, start))
437 def loadModuleData(project):
438 module_info_dict = {}
440 configuration_info_dict = {}
442 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
443 comment_list = getCommentList(open(path + "/" + filename, "r").read())
444 if len(comment_list) > 0:
446 configuration_info = {}
448 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
449 except ParseError, err:
450 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
451 for module, information in module_dict.items():
452 if "depends" not in information:
453 information["depends"] = ()
454 information["depends"] += (filename.split(".")[0],)
455 information["category"] = os.path.basename(path)
456 if "configuration" in information.keys() and len(information["configuration"]):
457 configuration = module_dict[module]["configuration"]
459 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
460 except ParseError, err:
461 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
462 module_info_dict.update(module_dict)
463 configuration_info_dict.update(configuration_info)
466 list_dict = loadDefineLists(comment_list[1:])
467 list_info_dict.update(list_dict)
468 except ParseError, err:
469 raise DefineException.EnumDefineException(path, err.line_number, err.line)
470 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
471 comment_list = getCommentList(open(path + "/" + filename, "r").read())
472 list_info_dict.update(loadDefineLists(comment_list))
473 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
474 for filename, path in findDefinitions("*_" + tag + ".h", project):
475 comment_list = getCommentList(open(path + "/" + filename, "r").read())
476 list_info_dict.update(loadDefineLists(comment_list))
477 project.setInfo("MODULES", module_info_dict)
478 project.setInfo("LISTS", list_info_dict)
479 project.setInfo("CONFIGURATIONS", configuration_info_dict)
480 project.setInfo("FILES", file_dict)
482 def formatParamNameValue(text):
484 Take the given string and return a tuple with the name of the parameter in the first position
485 and the value in the second.
487 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
490 def loadConfigurationInfos(path):
492 Return the module configurations found in the given file as a dict with the
493 parameter name as key and a dict containig the fields above as value:
494 "value": the value of the parameter
495 "description": the description of the parameter
496 "informations": a dict containig optional informations:
497 "type": "int" | "boolean" | "enum"
498 "min": the minimum value for integer parameters
499 "max": the maximum value for integer parameters
500 "long": boolean indicating if the num is a long
501 "unsigned": boolean indicating if the num is an unsigned
502 "value_list": the name of the enum for enum parameters
504 configuration_infos = {}
505 configuration_infos["paramlist"] = []
506 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
507 name, value = formatParamNameValue(define)
508 brief, description, informations = getDescriptionInformations(comment)
509 configuration_infos["paramlist"].append((start, name))
510 configuration_infos[name] = {}
511 configuration_infos[name]["value"] = value
512 configuration_infos[name]["informations"] = informations
513 if not "type" in configuration_infos[name]["informations"]:
514 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
515 if ("type" in configuration_infos[name]["informations"].keys() and
516 configuration_infos[name]["informations"]["type"] == "int" and
517 configuration_infos[name]["value"].find("L") != -1):
518 configuration_infos[name]["informations"]["long"] = True
519 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
520 if ("type" in configuration_infos[name]["informations"].keys() and
521 configuration_infos[name]["informations"]["type"] == "int" and
522 configuration_infos[name]["value"].find("U") != -1):
523 configuration_infos[name]["informations"]["unsigned"] = True
524 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
525 configuration_infos[name]["description"] = description
526 configuration_infos[name]["brief"] = brief
527 return configuration_infos
529 def findParameterType(parameter):
530 if "value_list" in parameter["informations"]:
532 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
535 def sub(string, parameter, value):
537 Substitute the given value at the given parameter define in the given string
539 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
541 def isInt(informations):
543 Return True if the value is a simple int.
545 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
550 def isLong(informations):
552 Return True if the value is a long.
554 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
559 def isUnsigned(informations):
561 Return True if the value is an unsigned.
563 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
568 def isUnsignedLong(informations):
570 Return True if the value is an unsigned long.
572 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
577 class ParseError(Exception):
578 def __init__(self, line_number, line):
579 Exception.__init__(self)
580 self.line_number = line_number