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