BeRTOS modules accept non-module dependencies (.c or .s files, for examples)
[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
18 import const
19 import codelite_project
20 import DefineException
21
22 def isBertosDir(directory):
23    return os.path.exists(directory + "/VERSION")
24
25 def bertosVersion(directory):
26    return open(directory + "/VERSION").readline().strip()
27
28 def createBertosProject(projectInfo):
29     directory = projectInfo.info("PROJECT_PATH")
30     sourcesDir = projectInfo.info("SOURCES_PATH")
31     if not os.path.isdir(directory):
32         os.mkdir(directory)
33     f = open(directory + "/project.bertos", "w")
34     f.write(repr(projectInfo))
35     f.close()
36     ## Destination source dir
37     srcdir = directory + "/bertos"
38     shutil.rmtree(srcdir, True)
39     shutil.copytree(sourcesDir + "/bertos", srcdir)
40     ## Destination makefile
41     makefile = directory + "/Makefile"
42     if os.path.exists(makefile):
43         os.remove(makefile)
44     makefile = open("mktemplates/Makefile").read()
45     makefile = makefileGenerator(projectInfo, makefile)
46     open(directory + "/Makefile", "w").write(makefile)
47     ## Destination project dir
48     prjdir = directory + "/" + os.path.basename(directory)
49     shutil.rmtree(prjdir, True)
50     os.mkdir(prjdir)
51     ## Destination configurations files
52     cfgdir = prjdir + "/cfg"
53     shutil.rmtree(cfgdir, True)
54     os.mkdir(cfgdir)
55     for key, value in projectInfo.info("CONFIGURATIONS").items():
56         string = open(sourcesDir + "/" + key, "r").read()
57         for parameter, infos in value.items():
58             value = infos["value"]
59             if "type" in infos["informations"] and infos["informations"]["type"] == "autoenabled":
60                 value = "1"
61             if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
62                 value += "U"
63             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
64                 value += "L"
65             string = sub(string, parameter, value)
66         f = open(cfgdir + "/" + os.path.basename(key), "w")
67         f.write(string)
68         f.close()
69     ## Destinatio mk file
70     makefile = open("mktemplates/template.mk", "r").read()
71     makefile = mkGenerator(projectInfo, makefile)
72     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
73     ## Destination main.c file
74     main = open("srctemplates/main.c", "r").read()
75     open(prjdir + "/main.c", "w").write(main)
76     if "codelite" in projectInfo.info("OUTPUT"):
77         workspace = codeliteWorkspaceGenerator(projectInfo)
78         open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
79         project = codeliteProjectGenerator(projectInfo)
80         open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
81
82 def mkGenerator(projectInfo, makefile):
83     """
84     Generates the mk file for the current project.
85     """
86     mkData = {}
87     mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
88     mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CORE_CPU"]
89     mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
90     mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
91     mkData["$csrc"], mkData["$pcsrc"], mkData["$constants"] = csrcGenerator(projectInfo)
92     mkData["$prefix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
93     mkData["$suffix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[1]
94     mkData["$cross"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
95     mkData["$main"] = os.path.basename(projectInfo.info("PROJECT_PATH")) + "/main.c"
96     for key in mkData:
97         while makefile.find(key) != -1:
98             makefile = makefile.replace(key, mkData[key])
99     return makefile
100
101 def makefileGenerator(projectInfo, 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(projectInfo.info("PROJECT_PATH")))
108     return makefile
109
110 def csrcGenerator(projectInfo):
111     modules = projectInfo.info("MODULES")
112     files = projectInfo.info("FILES")
113     if "harvard" in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
114         harvard = True
115     else:
116         harvard = False
117     csrc = []
118     pcsrc = []
119     constants = {}
120     moduleFiles = set([])
121     for module, information in modules.items():
122         if information["enabled"]:
123             if "constants" in information:
124                 constants.update(information["constants"])
125             moduleFiles |= set(findModuleFiles(module, projectInfo))
126             for fileDependency in information["depends"]:
127                 if fileDependency in files:
128                     moduleFiles |= set(findModuleFiles(fileDependency, projectInfo))
129             for file in moduleFiles:
130                 if not harvard or "harvard" not in information or information["harvard"] == "both":
131                     csrc.append(file)
132                 if harvard and "harvard" in information:
133                     pcsrc.append(file)
134     csrc = " \\\n\t".join(csrc) + " \\"
135     pcsrc = " \\\n\t".join(pcsrc) + " \\"
136     constants = "\n".join([os.path.basename(projectInfo.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
137     return csrc, pcsrc, constants
138     
139 def findModuleFiles(module, projectInfo):
140     files = []
141     for filename, path in findDefinitions(module + ".c", projectInfo):
142         path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
143         files.append(path + "/" + filename)
144     for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
145         path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
146         files.append(path + "/" + filename)
147     for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
148         for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
149             path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
150             files.append(path + "/" + filename)
151     return files
152
153 def codeliteProjectGenerator(projectInfo):
154     template = open("cltemplates/bertos.project").read()
155     filelist = "\n".join(codelite_project.clFiles(codelite_project.findSources(projectInfo.info("PROJECT_PATH")), projectInfo.info("PROJECT_PATH")))
156     while template.find("$filelist") != -1:
157         template = template.replace("$filelist", filelist)
158     projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
159     while template.find("$project") != -1:
160         template = template.replace("$project", projectName)
161     return template
162
163 def codeliteWorkspaceGenerator(projectInfo):
164     template = open("cltemplates/bertos.workspace").read()
165     projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
166     while template.find("$project") != -1:
167         template = template.replace("$project", projectName)
168     return template
169     
170 def getSystemPath():
171     path = os.environ["PATH"]
172     if os.name == "nt":
173         path = path.split(";")
174     else:
175         path = path.split(":")
176     return path
177
178 def findToolchains(pathList):
179     toolchains = []
180     for element in pathList:
181         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
182             toolchains.append(toolchain)
183     return list(set(toolchains))
184
185 def getToolchainInfo(output):
186     info = {}
187     expr = re.compile("Target: .*")
188     target = expr.findall(output)
189     if len(target) == 1:
190         info["target"] = target[0].split("Target: ")[1]
191     expr = re.compile("gcc version [0-9,.]*")
192     version = expr.findall(output)
193     if len(version) == 1:
194         info["version"] = version[0].split("gcc version ")[1]
195     expr = re.compile("gcc version [0-9,.]* \(.*\)")
196     build = expr.findall(output)
197     if len(build) == 1:
198         build = build[0].split("gcc version ")[1]
199         build = build[build.find("(") + 1 : build.find(")")]
200         info["build"] = build
201     expr = re.compile("Configured with: .*")
202     configured = expr.findall(output)
203     if len(configured) == 1:
204         info["configured"] = configured[0].split("Configured with: ")[1]
205     expr = re.compile("Thread model: .*")
206     thread = expr.findall(output)
207     if len(thread) == 1:
208         info["thread"] = thread[0].split("Thread model: ")[1]
209     return info
210
211 def loadSourceTree(project):
212     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
213     project.setInfo("FILE_LIST", fileList)
214
215 def findDefinitions(ftype, project):
216     L = project.info("FILE_LIST")
217     definitions = []
218     for element in L:
219         for filename in element[2]:
220             if fnmatch.fnmatch(filename, ftype):
221                 definitions.append((filename, element[0]))
222     return definitions
223
224 def loadCpuInfos(project):
225     cpuInfos = []
226     for definition in findDefinitions(const.CPU_DEFINITION, project):
227         cpuInfos.append(getInfos(definition))
228     return cpuInfos
229
230 def getInfos(definition):
231     D = {}
232     D.update(const.CPU_DEF)
233     def include(filename, dict = D, directory=definition[1]):
234         execfile(directory + "/" + filename, {}, D)
235     D["include"] = include
236     include(definition[0], D)
237     D["CPU_NAME"] = definition[0].split(".")[0]
238     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
239     del D["include"]
240     return D
241
242 def getCommentList(string):
243     commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
244     commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
245     return commentList
246
247 def loadModuleDefinition(first_comment):
248     toBeParsed = False
249     moduleDefinition = {}
250     for num, line in enumerate(first_comment):
251         index = line.find("$WIZ$")
252         if index != -1:
253             toBeParsed = True
254             try:
255                 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
256             except:
257                 raise ParseError(num, line[index:])
258         elif line.find("\\brief") != -1:
259             moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
260     moduleDict = {}
261     if "module_name" in moduleDefinition.keys():
262         moduleName = moduleDefinition[const.MODULE_DEFINITION["module_name"]]
263         del moduleDefinition[const.MODULE_DEFINITION["module_name"]]
264         moduleDict[moduleName] = {}
265         if const.MODULE_DEFINITION["module_depends"] in moduleDefinition.keys():
266             if type(moduleDefinition[const.MODULE_DEFINITION["module_depends"]]) == str:
267                 moduleDefinition[const.MODULE_DEFINITION["module_depends"]] = (moduleDefinition[const.MODULE_DEFINITION["module_depends"]],)
268             moduleDict[moduleName]["depends"] = moduleDefinition[const.MODULE_DEFINITION["module_depends"]]
269             del moduleDefinition[const.MODULE_DEFINITION["module_depends"]]
270         else:
271             moduleDict[moduleName]["depends"] = ()
272         if const.MODULE_DEFINITION["module_configuration"] in moduleDefinition.keys():
273             moduleDict[moduleName]["configuration"] = moduleDefinition[const.MODULE_DEFINITION["module_configuration"]]
274             del moduleDefinition[const.MODULE_DEFINITION["module_configuration"]]
275         else:
276             moduleDict[moduleName]["configuration"] = ""
277         if "module_description" in moduleDefinition.keys():
278             moduleDict[moduleName]["description"] = moduleDefinition["module_description"]
279             del moduleDefinition["module_description"]
280         if const.MODULE_DEFINITION["module_harvard"] in moduleDefinition.keys():
281             harvard = moduleDefinition[const.MODULE_DEFINITION["module_harvard"]]
282             if harvard == "both" or harvard == "pgm_memory":
283                 moduleDict[moduleName]["harvard"] = harvard
284             del moduleDefinition[const.MODULE_DEFINITION["module_harvard"]]
285         moduleDict[moduleName]["constants"] = moduleDefinition
286         moduleDict[moduleName]["enabled"] = False
287     return toBeParsed, moduleDict
288
289 def loadDefineLists(commentList):
290     defineList = {}
291     for comment in commentList:
292         for num, line in enumerate(comment):
293             index = line.find("$WIZ$")
294             if index != -1:
295                 try:
296                     exec line[index + len("$WIZ$ "):] in {}, defineList
297                 except:
298                     raise ParseError(num, line[index:])
299     for key, value in defineList.items():
300         if type(value) == str:
301             defineList[key] = (value,)
302     return defineList
303
304 def getDescriptionInformations(comment): 
305     """ 
306     Take the doxygen comment and strip the wizard informations, returning the tuple 
307     (comment, wizard_information) 
308     """
309     brief = ""
310     description = ""
311     information = {}
312     for num, line in enumerate(comment):
313         index = line.find("$WIZ$")
314         if index != -1:
315             if len(brief) == 0:
316                 brief += line[:index].strip()
317             else:
318                 description += " " + line[:index]
319             try:
320                 exec line[index + len("$WIZ$ "):] in {}, information
321             except:
322                 raise ParseError(num, line[index:])
323         else:
324             if len(brief) == 0:
325                 brief += line.strip()
326             else:
327                 description += " " + line
328                 description = description.strip()
329     return brief.strip(), description.strip(), information
330
331 def getDefinitionBlocks(text):
332     """
333     Take a text and return a list of tuple (description, name-value).
334     """
335     block = []
336     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
337     for comment, define in block_tmp:
338         # Only the first element is needed
339         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
340     for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
341         block.append(([comment], define))
342     for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
343         block.append(([comment], define))
344     return block
345
346 def loadModuleData(project):
347     moduleInfoDict = {}
348     listInfoDict = {}
349     configurationInfoDict = {}
350     fileDict = {}
351     for filename, path in findDefinitions("*.h", project):
352         commentList = getCommentList(open(path + "/" + filename, "r").read())
353         if len(commentList) > 0:
354             moduleInfo = {}
355             configurationInfo = {}
356             try:
357                 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
358             except ParseError, err:
359                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
360             for module, information in moduleDict.items():
361                 information["category"] = os.path.basename(path)
362                 if "configuration" in information.keys() and len(information["configuration"]):
363                     configuration = moduleDict[module]["configuration"]
364                     try:
365                         configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
366                     except ParseError, err:
367                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
368             moduleInfoDict.update(moduleDict)
369             configurationInfoDict.update(configurationInfo)
370             if toBeParsed:
371                 try:
372                     listDict = loadDefineLists(commentList[1:])
373                     listInfoDict.update(listDict)
374                 except ParseError, err:
375                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
376     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
377         commentList = getCommentList(open(path + "/" + filename, "r").read())
378         listInfoDict.update(loadDefineLists(commentList))
379     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
380         for filename, path in findDefinitions("*_" + tag + ".h", project):
381             commentList = getCommentList(open(path + "/" + filename, "r").read())
382             listInfoDict.update(loadDefineLists(commentList))
383     project.setInfo("MODULES", moduleInfoDict)
384     project.setInfo("LISTS", listInfoDict)
385     project.setInfo("CONFIGURATIONS", configurationInfoDict)
386     project.setInfo("FILES", fileDict)
387     
388 def formatParamNameValue(text):
389     """
390     Take the given string and return a tuple with the name of the parameter in the first position
391     and the value in the second.
392     """
393     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
394     return block[0]
395
396 def loadConfigurationInfos(path):
397     """
398     Return the module configurations found in the given file as a dict with the
399     parameter name as key and a dict containig the fields above as value:
400         "value": the value of the parameter
401         "description": the description of the parameter
402         "informations": a dict containig optional informations:
403             "type": "int" | "boolean" | "enum"
404             "min": the minimum value for integer parameters
405             "max": the maximum value for integer parameters
406             "long": boolean indicating if the num is a long
407             "value_list": the name of the enum for enum parameters
408     """
409     configurationInfos = {}
410     for comment, define in getDefinitionBlocks(open(path, "r").read()):
411         name, value = formatParamNameValue(define)
412         brief, description, informations = getDescriptionInformations(comment)
413         configurationInfos[name] = {}
414         configurationInfos[name]["value"] = value
415         configurationInfos[name]["informations"] = informations
416         if ("type" in configurationInfos[name]["informations"].keys() and
417                 configurationInfos[name]["informations"]["type"] == "int" and
418                 configurationInfos[name]["value"].find("L") != -1):
419             configurationInfos[name]["informations"]["long"] = True
420             configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
421         if ("type" in configurationInfos[name]["informations"].keys() and
422                 configurationInfos[name]["informations"]["type"] == "int" and
423                 configurationInfos[name]["value"].find("U") != -1):
424             configurationInfos[name]["informations"]["unsigned"] = True
425             configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
426         configurationInfos[name]["description"] = description
427         configurationInfos[name]["brief"] = brief
428     return configurationInfos
429
430 def sub(string, parameter, value):
431     """
432     Substitute the given value at the given parameter define in the given string
433     """
434     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
435
436 def isInt(informations):
437     """
438     Return True if the value is a simple int.
439     """
440     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
441         return True
442     else:
443         return False
444
445 def isLong(informations):
446     """
447     Return True if the value is a long.
448     """
449     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
450         return True
451     else:
452         return False
453
454 def isUnsigned(informations):
455     """
456     Return True if the value is an unsigned.
457     """
458     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
459         return True
460     else:
461         return False
462
463 def isUnsignedLong(informations):
464     """
465     Return True if the value is an unsigned long.
466     """
467     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
468         return True
469     else:
470         return False
471
472 class ParseError(Exception):
473     def __init__(self, line_number, line):
474         Exception.__init__(self)
475         self.line_number = line_number
476         self.line = line