Enable autoenabled parameters only for enabled modules
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
5 # All rights reserved.
6 #
7 # $Id:$
8 #
9 # Author: Lorenzo Berni <duplo@develer.com>
10 #
11
12 import os
13 import fnmatch
14 import glob
15 import re
16 import shutil
17 import pickle
18
19 import const
20 from plugins import codelite_project
21 import DefineException
22
23 def isBertosDir(directory):
24    return os.path.exists(directory + "/VERSION")
25
26 def bertosVersion(directory):
27    return open(directory + "/VERSION").readline().strip()
28
29 def createBertosProject(project_info):
30     directory = project_info.info("PROJECT_PATH")
31     sources_dir = project_info.info("SOURCES_PATH")
32     if not os.path.isdir(directory):
33         os.mkdir(directory)
34     f = open(directory + "/project.bertos", "w")
35     f.write(pickle.dumps(project_info))
36     f.close()
37     # Destination source dir
38     srcdir = directory + "/bertos"
39     shutil.rmtree(srcdir, True)
40     shutil.copytree(sources_dir + "/bertos", srcdir)
41     # Destination makefile
42     makefile = directory + "/Makefile"
43     if os.path.exists(makefile):
44         os.remove(makefile)
45     makefile = open("mktemplates/Makefile").read()
46     makefile = makefileGenerator(project_info, makefile)
47     open(directory + "/Makefile", "w").write(makefile)
48     # Destination project dir
49     prjdir = directory + "/" + os.path.basename(directory)
50     shutil.rmtree(prjdir, True)
51     os.mkdir(prjdir)
52     # Destination configurations files
53     cfgdir = prjdir + "/cfg"
54     shutil.rmtree(cfgdir, True)
55     os.mkdir(cfgdir)
56     # Set to 1 the autoenabled for enabled modules
57     for module, information in project_info.info("MODULES").items():
58         if information["enabled"] and "configuration" in information and information["configuration"] != "":
59             configurations = project_info.info("CONFIGURATIONS")
60             configuration = configurations[information["configuration"]]
61             for start, parameter in configuration["paramlist"]:
62                 if "type" in configuration[parameter] and configuration[parameter]["type"] == "autoenabled":
63                     configuration[parameter]["value"] = "1"
64             project_info.setInfo("CONFIGURATIONS", configurations)
65     # Copy all the configuration files
66     for configuration, information in project_info.info("CONFIGURATIONS").items():
67         string = open(sources_dir + "/" + configuration, "r").read()
68         for start, parameter in information["paramlist"]:
69             infos = information[parameter]
70             value = infos["value"]
71             if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
72                 value += "U"
73             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
74                 value += "L"
75             string = sub(string, parameter, value)
76         f = open(cfgdir + "/" + os.path.basename(configuration), "w")
77         f.write(string)
78         f.close()
79     # Destinatio mk file
80     makefile = open("mktemplates/template.mk", "r").read()
81     makefile = mkGenerator(project_info, makefile)
82     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
83     # Destination main.c file
84     main = open("srctemplates/main.c", "r").read()
85     open(prjdir + "/main.c", "w").write(main)
86     # Codelite project files
87     if "codelite" in project_info.info("OUTPUT"):
88         codelite_project.createProject(project_info)
89
90 def mkGenerator(project_info, makefile):
91     """
92     Generates the mk file for the current project.
93     """
94     mk_data = {}
95     mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
96     mk_data["$cpuflag"] = project_info.info("CPU_INFOS")["CPU_FLAG_NAME"]
97     mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
98     mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
99     mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
100     mk_data["$cppflags"] = " ".join(project_info.info("CPU_INFOS")["CPP_FLAGS"])
101     mk_data["$cppaflags"] = " ".join(project_info.info("CPU_INFOS")["CPPA_FLAGS"])
102     mk_data["$cxxflags"] = " ".join(project_info.info("CPU_INFOS")["CXX_FLAGS"])
103     mk_data["$asflags"] = " ".join(project_info.info("CPU_INFOS")["AS_FLAGS"])
104     mk_data["$arflags"] = " ".join(project_info.info("CPU_INFOS")["AR_FLAGS"])
105     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
106     mk_data["$prefix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
107     mk_data["$suffix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[1]
108     mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
109     for key in mk_data:
110         while makefile.find(key) != -1:
111             makefile = makefile.replace(key, mk_data[key])
112     return makefile
113
114 def makefileGenerator(project_info, makefile):
115     """
116     Generate the Makefile for the current project.
117     """
118     # TODO write a general function that works for both the mk file and the Makefile
119     while makefile.find("project_name") != -1:
120         makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
121     return makefile
122
123 def csrcGenerator(project_info):
124     modules = project_info.info("MODULES")
125     files = project_info.info("FILES")
126     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
127         harvard = True
128     else:
129         harvard = False
130     # file to be included in CSRC variable
131     csrc = []
132     # file to be included in PCSRC variable
133     pcsrc = []
134     # files to be included in CPPASRC variable
135     cppasrc = []
136     # files to be included in CXXSRC variable
137     cxxsrc = []
138     # files to be included in ASRC variable
139     asrc = []
140     # constants to be included at the beginning of the makefile
141     constants = {}
142     for module, information in modules.items():
143         module_files = set([])
144         dependency_files = set([])
145         # assembly sources
146         asm_files = set([])
147         if information["enabled"]:
148             if "constants" in information:
149                 constants.update(information["constants"])
150             cfiles, sfiles = findModuleFiles(module, project_info)
151             module_files |= set(cfiles)
152             asm_files |= set(sfiles)
153             for file_dependency in information["depends"]:
154                 if file_dependency in files:
155                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
156                     dependency_files |= set(dependencyCFiles)
157                     asm_files |= set(dependencySFiles)
158             for file in module_files:
159                 if not harvard or "harvard" not in information or information["harvard"] == "both":
160                     csrc.append(file)
161                 if harvard and "harvard" in information:
162                     pcsrc.append(file)
163             for file in dependency_files:
164                 csrc.append(file)
165             for file in project_info.info("CPU_INFOS")["C_SRC"]:
166                 csrc.append(file)
167             for file in project_info.info("CPU_INFOS")["PC_SRC"]:
168                 pcsrc.append(file)
169             for file in asm_files:
170                 cppasrc.append(file)
171     for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
172         cppasrc.append(file)
173     for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
174         cxxsrc.append(file)
175     for file in project_info.info("CPU_INFOS")["ASRC"]:
176         asrc.append(file)
177     csrc = " \\\n\t".join(csrc) + " \\"
178     pcsrc = " \\\n\t".join(pcsrc) + " \\"
179     cppasrc = " \\\n\t".join(cppasrc) + " \\"
180     cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
181     asrc = " \\\n\t".join(asrc) + " \\"
182     constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
183     return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
184
185 def findModuleFiles(module, project_info):
186     # Find the files related to the selected module
187     cfiles = []
188     sfiles = []
189     # .c files related to the module and the cpu architecture
190     for filename, path in findDefinitions(module + ".c", project_info) + \
191             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
192         path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
193         if os.sep != "/":
194             path = replaceSeparators(path)
195         cfiles.append(path + "/" + filename)
196     # .s files related to the module and the cpu architecture
197     for filename, path in findDefinitions(module + ".s", project_info) + \
198             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
199             findDefinitions(module + ".S", project_info) + \
200             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
201         path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
202         if os.sep != "/":
203             path = replaceSeparators(path)
204         sfiles.append(path + "/" + filename)
205     # .c and .s files related to the module and the cpu tags
206     for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
207         for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
208             path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
209             if os.sep != "/":
210                 path = replaceSeparators(path)
211             cfiles.append(path + "/" + filename)
212         for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
213                 findDefinitions(module + "_" + tag + ".S", project_info):
214             path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
215             if os.sep != "/":
216                 path = replaceSeparators(path)
217             sfiles.append(path + "/" + filename)
218     return cfiles, sfiles
219
220 def replaceSeparators(path):
221     """
222     Replace the separators in the given path with unix standard separator.
223     """
224     while path.find(os.sep) != -1:
225         path = path.replace(os.sep, "/")
226     return path
227
228 def getSystemPath():
229     path = os.environ["PATH"]
230     if os.name == "nt":
231         path = path.split(";")
232     else:
233         path = path.split(":")
234     return path
235
236 def findToolchains(path_list):
237     toolchains = []
238     for element in path_list:
239         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
240             toolchains.append(toolchain)
241     return list(set(toolchains))
242
243 def getToolchainInfo(output):
244     info = {}
245     expr = re.compile("Target: .*")
246     target = expr.findall(output)
247     if len(target) == 1:
248         info["target"] = target[0].split("Target: ")[1]
249     expr = re.compile("gcc version [0-9,.]*")
250     version = expr.findall(output)
251     if len(version) == 1:
252         info["version"] = version[0].split("gcc version ")[1]
253     expr = re.compile("gcc version [0-9,.]* \(.*\)")
254     build = expr.findall(output)
255     if len(build) == 1:
256         build = build[0].split("gcc version ")[1]
257         build = build[build.find("(") + 1 : build.find(")")]
258         info["build"] = build
259     expr = re.compile("Configured with: .*")
260     configured = expr.findall(output)
261     if len(configured) == 1:
262         info["configured"] = configured[0].split("Configured with: ")[1]
263     expr = re.compile("Thread model: .*")
264     thread = expr.findall(output)
265     if len(thread) == 1:
266         info["thread"] = thread[0].split("Thread model: ")[1]
267     return info
268
269 def loadSourceTree(project):
270     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
271     project.setInfo("FILE_LIST", fileList)
272
273 def findDefinitions(ftype, project):
274     L = project.info("FILE_LIST")
275     definitions = []
276     for element in L:
277         for filename in element[2]:
278             if fnmatch.fnmatch(filename, ftype):
279                 definitions.append((filename, element[0]))
280     return definitions
281
282 def loadCpuInfos(project):
283     cpuInfos = []
284     for definition in findDefinitions(const.CPU_DEFINITION, project):
285         cpuInfos.append(getInfos(definition))
286     return cpuInfos
287
288 def getInfos(definition):
289     D = {}
290     D.update(const.CPU_DEF)
291     def include(filename, dict = D, directory=definition[1]):
292         execfile(directory + "/" + filename, {}, D)
293     D["include"] = include
294     include(definition[0], D)
295     D["CPU_NAME"] = definition[0].split(".")[0]
296     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
297     del D["include"]
298     return D
299
300 def getCommentList(string):
301     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
302     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
303     return comment_list
304
305 def loadModuleDefinition(first_comment):
306     to_be_parsed = False
307     module_definition = {}
308     for num, line in enumerate(first_comment):
309         index = line.find("$WIZ$")
310         if index != -1:
311             to_be_parsed = True
312             try:
313                 exec line[index + len("$WIZ$ "):] in {}, module_definition
314             except:
315                 raise ParseError(num, line[index:])
316         elif line.find("\\brief") != -1:
317             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
318     module_dict = {}
319     if "module_name" in module_definition.keys():
320         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
321         del module_definition[const.MODULE_DEFINITION["module_name"]]
322         module_dict[module_name] = {}
323         if const.MODULE_DEFINITION["module_depends"] in module_definition.keys():
324             if type(module_definition[const.MODULE_DEFINITION["module_depends"]]) == str:
325                 module_definition[const.MODULE_DEFINITION["module_depends"]] = (module_definition[const.MODULE_DEFINITION["module_depends"]],)
326             module_dict[module_name]["depends"] = module_definition[const.MODULE_DEFINITION["module_depends"]]
327             del module_definition[const.MODULE_DEFINITION["module_depends"]]
328         else:
329             module_dict[module_name]["depends"] = ()
330         if const.MODULE_DEFINITION["module_configuration"] in module_definition.keys():
331             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
332             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
333         else:
334             module_dict[module_name]["configuration"] = ""
335         if "module_description" in module_definition.keys():
336             module_dict[module_name]["description"] = module_definition["module_description"]
337             del module_definition["module_description"]
338         if const.MODULE_DEFINITION["module_harvard"] in module_definition.keys():
339             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
340             if harvard == "both" or harvard == "pgm_memory":
341                 module_dict[module_name]["harvard"] = harvard
342             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
343         module_dict[module_name]["constants"] = module_definition
344         module_dict[module_name]["enabled"] = False
345     return to_be_parsed, module_dict
346
347 def loadDefineLists(comment_list):
348     define_list = {}
349     for comment in comment_list:
350         for num, line in enumerate(comment):
351             index = line.find("$WIZ$")
352             if index != -1:
353                 try:
354                     exec line[index + len("$WIZ$ "):] in {}, define_list
355                 except:
356                     raise ParseError(num, line[index:])
357     for key, value in define_list.items():
358         if type(value) == str:
359             define_list[key] = (value,)
360     return define_list
361
362 def getDescriptionInformations(comment):
363     """
364     Take the doxygen comment and strip the wizard informations, returning the tuple
365     (comment, wizard_information)
366     """
367     brief = ""
368     description = ""
369     information = {}
370     for num, line in enumerate(comment):
371         index = line.find("$WIZ$")
372         if index != -1:
373             if len(brief) == 0:
374                 brief += line[:index].strip()
375             else:
376                 description += " " + line[:index]
377             try:
378                 exec line[index + len("$WIZ$ "):] in {}, information
379             except:
380                 raise ParseError(num, line[index:])
381         else:
382             if len(brief) == 0:
383                 brief += line.strip()
384             else:
385                 description += " " + line
386                 description = description.strip()
387     return brief.strip(), description.strip(), information
388
389 def getDefinitionBlocks(text):
390     """
391     Take a text and return a list of tuple (description, name-value).
392     """
393     block = []
394     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
395     for match in block_tmp:
396         # Only the first element is needed
397         comment = match.group(1)
398         define = match.group(2)
399         start = match.start()
400         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
401     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
402         comment = match.group(1)
403         define = match.group(2)
404         start = match.start()
405         block.append(([comment], define, start))
406     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
407         comment = match.group(2)
408         define = match.group(1)
409         start = match.start()
410         block.append(([comment], define, start))
411     return block
412
413 def loadModuleData(project):
414     module_info_dict = {}
415     list_info_dict = {}
416     configuration_info_dict = {}
417     file_dict = {}
418     for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
419         comment_list = getCommentList(open(path + "/" + filename, "r").read())
420         if len(comment_list) > 0:
421             module_info = {}
422             configuration_info = {}
423             try:
424                 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
425             except ParseError, err:
426                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
427             for module, information in module_dict.items():
428                 if "depends" not in information:
429                     information["depends"] = ()
430                 information["depends"] += (filename.split(".")[0],)
431                 information["category"] = os.path.basename(path)
432                 if "configuration" in information.keys() and len(information["configuration"]):
433                     configuration = module_dict[module]["configuration"]
434                     try:
435                         configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
436                     except ParseError, err:
437                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
438             module_info_dict.update(module_dict)
439             configuration_info_dict.update(configuration_info)
440             if to_be_parsed:
441                 try:
442                     list_dict = loadDefineLists(comment_list[1:])
443                     list_info_dict.update(list_dict)
444                 except ParseError, err:
445                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
446     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
447         comment_list = getCommentList(open(path + "/" + filename, "r").read())
448         list_info_dict.update(loadDefineLists(comment_list))
449     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
450         for filename, path in findDefinitions("*_" + tag + ".h", project):
451             comment_list = getCommentList(open(path + "/" + filename, "r").read())
452             list_info_dict.update(loadDefineLists(comment_list))
453     project.setInfo("MODULES", module_info_dict)
454     project.setInfo("LISTS", list_info_dict)
455     project.setInfo("CONFIGURATIONS", configuration_info_dict)
456     project.setInfo("FILES", file_dict)
457
458 def formatParamNameValue(text):
459     """
460     Take the given string and return a tuple with the name of the parameter in the first position
461     and the value in the second.
462     """
463     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
464     return block[0]
465
466 def loadConfigurationInfos(path):
467     """
468     Return the module configurations found in the given file as a dict with the
469     parameter name as key and a dict containig the fields above as value:
470         "value": the value of the parameter
471         "description": the description of the parameter
472         "informations": a dict containig optional informations:
473             "type": "int" | "boolean" | "enum"
474             "min": the minimum value for integer parameters
475             "max": the maximum value for integer parameters
476             "long": boolean indicating if the num is a long
477             "unsigned": boolean indicating if the num is an unsigned
478             "value_list": the name of the enum for enum parameters
479     """
480     configuration_infos = {}
481     configuration_infos["paramlist"] = []
482     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
483         name, value = formatParamNameValue(define)
484         brief, description, informations = getDescriptionInformations(comment)
485         configuration_infos["paramlist"].append((start, name))
486         configuration_infos[name] = {}
487         configuration_infos[name]["value"] = value
488         configuration_infos[name]["informations"] = informations
489         if not "type" in configuration_infos[name]["informations"]:
490             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
491         if ("type" in configuration_infos[name]["informations"].keys() and
492                 configuration_infos[name]["informations"]["type"] == "int" and
493                 configuration_infos[name]["value"].find("L") != -1):
494             configuration_infos[name]["informations"]["long"] = True
495             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
496         if ("type" in configuration_infos[name]["informations"].keys() and
497                 configuration_infos[name]["informations"]["type"] == "int" and
498                 configuration_infos[name]["value"].find("U") != -1):
499             configuration_infos[name]["informations"]["unsigned"] = True
500             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
501         configuration_infos[name]["description"] = description
502         configuration_infos[name]["brief"] = brief
503     return configuration_infos
504
505 def findParameterType(parameter):
506     if "value_list" in parameter["informations"]:
507         return "enum"
508     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
509         return "int"
510
511 def sub(string, parameter, value):
512     """
513     Substitute the given value at the given parameter define in the given string
514     """
515     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
516
517 def isInt(informations):
518     """
519     Return True if the value is a simple int.
520     """
521     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
522         return True
523     else:
524         return False
525
526 def isLong(informations):
527     """
528     Return True if the value is a long.
529     """
530     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
531         return True
532     else:
533         return False
534
535 def isUnsigned(informations):
536     """
537     Return True if the value is an unsigned.
538     """
539     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
540         return True
541     else:
542         return False
543
544 def isUnsignedLong(informations):
545     """
546     Return True if the value is an unsigned long.
547     """
548     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
549         return True
550     else:
551         return False
552
553 class ParseError(Exception):
554     def __init__(self, line_number, line):
555         Exception.__init__(self)
556         self.line_number = line_number
557         self.line = line