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