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