blob: 11db1801b31709aa17119814f5ad50d7587d0cc0 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# ex:ts=4:sw=4:sts=4:et
2# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
3"""
4 AbstractSyntaxTree classes for the Bitbake language
5"""
6
7# Copyright (C) 2003, 2004 Chris Larson
8# Copyright (C) 2003, 2004 Phil Blundell
9# Copyright (C) 2009 Holger Hans Peter Freyther
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License version 2 as
13# published by the Free Software Foundation.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License along
21# with this program; if not, write to the Free Software Foundation, Inc.,
22# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
24from __future__ import absolute_import
25from future_builtins import filter
26import re
27import string
28import logging
29import bb
30import itertools
31from bb import methodpool
32from bb.parse import logger
33
34_bbversions_re = re.compile(r"\[(?P<from>[0-9]+)-(?P<to>[0-9]+)\]")
35
36class StatementGroup(list):
37 def eval(self, data):
38 for statement in self:
39 statement.eval(data)
40
41class AstNode(object):
42 def __init__(self, filename, lineno):
43 self.filename = filename
44 self.lineno = lineno
45
46class IncludeNode(AstNode):
47 def __init__(self, filename, lineno, what_file, force):
48 AstNode.__init__(self, filename, lineno)
49 self.what_file = what_file
50 self.force = force
51
52 def eval(self, data):
53 """
54 Include the file and evaluate the statements
55 """
56 s = data.expand(self.what_file)
57 logger.debug(2, "CONF %s:%s: including %s", self.filename, self.lineno, s)
58
59 # TODO: Cache those includes... maybe not here though
60 if self.force:
61 bb.parse.ConfHandler.include(self.filename, s, self.lineno, data, "include required")
62 else:
63 bb.parse.ConfHandler.include(self.filename, s, self.lineno, data, False)
64
65class ExportNode(AstNode):
66 def __init__(self, filename, lineno, var):
67 AstNode.__init__(self, filename, lineno)
68 self.var = var
69
70 def eval(self, data):
71 data.setVarFlag(self.var, "export", 1, op = 'exported')
72
73class DataNode(AstNode):
74 """
75 Various data related updates. For the sake of sanity
76 we have one class doing all this. This means that all
77 this need to be re-evaluated... we might be able to do
78 that faster with multiple classes.
79 """
80 def __init__(self, filename, lineno, groupd):
81 AstNode.__init__(self, filename, lineno)
82 self.groupd = groupd
83
84 def getFunc(self, key, data):
85 if 'flag' in self.groupd and self.groupd['flag'] != None:
86 return data.getVarFlag(key, self.groupd['flag'], noweakdefault=True)
87 else:
88 return data.getVar(key, False, noweakdefault=True, parsing=True)
89
90 def eval(self, data):
91 groupd = self.groupd
92 key = groupd["var"]
93 loginfo = {
94 'variable': key,
95 'file': self.filename,
96 'line': self.lineno,
97 }
98 if "exp" in groupd and groupd["exp"] != None:
99 data.setVarFlag(key, "export", 1, op = 'exported', **loginfo)
100
101 op = "set"
102 if "ques" in groupd and groupd["ques"] != None:
103 val = self.getFunc(key, data)
104 op = "set?"
105 if val == None:
106 val = groupd["value"]
107 elif "colon" in groupd and groupd["colon"] != None:
108 e = data.createCopy()
109 bb.data.update_data(e)
110 op = "immediate"
111 val = e.expand(groupd["value"], key + "[:=]")
112 elif "append" in groupd and groupd["append"] != None:
113 op = "append"
114 val = "%s %s" % ((self.getFunc(key, data) or ""), groupd["value"])
115 elif "prepend" in groupd and groupd["prepend"] != None:
116 op = "prepend"
117 val = "%s %s" % (groupd["value"], (self.getFunc(key, data) or ""))
118 elif "postdot" in groupd and groupd["postdot"] != None:
119 op = "postdot"
120 val = "%s%s" % ((self.getFunc(key, data) or ""), groupd["value"])
121 elif "predot" in groupd and groupd["predot"] != None:
122 op = "predot"
123 val = "%s%s" % (groupd["value"], (self.getFunc(key, data) or ""))
124 else:
125 val = groupd["value"]
126
127 flag = None
128 if 'flag' in groupd and groupd['flag'] != None:
129 flag = groupd['flag']
130 elif groupd["lazyques"]:
131 flag = "_defaultval"
132
133 loginfo['op'] = op
134 loginfo['detail'] = groupd["value"]
135
136 if flag:
137 data.setVarFlag(key, flag, val, **loginfo)
138 else:
139 data.setVar(key, val, parsing=True, **loginfo)
140
141class MethodNode(AstNode):
142 tr_tbl = string.maketrans('/.+-@%&', '_______')
143
144 def __init__(self, filename, lineno, func_name, body):
145 AstNode.__init__(self, filename, lineno)
146 self.func_name = func_name
147 self.body = body
148
149 def eval(self, data):
150 text = '\n'.join(self.body)
151 if self.func_name == "__anonymous":
152 funcname = ("__anon_%s_%s" % (self.lineno, self.filename.translate(MethodNode.tr_tbl)))
153 text = "def %s(d):\n" % (funcname) + text
154 bb.methodpool.insert_method(funcname, text, self.filename)
155 anonfuncs = data.getVar('__BBANONFUNCS', False) or []
156 anonfuncs.append(funcname)
157 data.setVar('__BBANONFUNCS', anonfuncs)
158 data.setVar(funcname, text, parsing=True)
159 else:
160 data.setVarFlag(self.func_name, "func", 1)
161 data.setVar(self.func_name, text, parsing=True)
162
163class PythonMethodNode(AstNode):
164 def __init__(self, filename, lineno, function, modulename, body):
165 AstNode.__init__(self, filename, lineno)
166 self.function = function
167 self.modulename = modulename
168 self.body = body
169
170 def eval(self, data):
171 # Note we will add root to parsedmethods after having parse
172 # 'this' file. This means we will not parse methods from
173 # bb classes twice
174 text = '\n'.join(self.body)
175 bb.methodpool.insert_method(self.modulename, text, self.filename)
176 data.setVarFlag(self.function, "func", 1)
177 data.setVarFlag(self.function, "python", 1)
178 data.setVar(self.function, text, parsing=True)
179
180class MethodFlagsNode(AstNode):
181 def __init__(self, filename, lineno, key, m):
182 AstNode.__init__(self, filename, lineno)
183 self.key = key
184 self.m = m
185
186 def eval(self, data):
187 if data.getVar(self.key, False):
188 # clean up old version of this piece of metadata, as its
189 # flags could cause problems
190 data.setVarFlag(self.key, 'python', None)
191 data.setVarFlag(self.key, 'fakeroot', None)
192 if self.m.group("py") is not None:
193 data.setVarFlag(self.key, "python", "1")
194 else:
195 data.delVarFlag(self.key, "python")
196 if self.m.group("fr") is not None:
197 data.setVarFlag(self.key, "fakeroot", "1")
198 else:
199 data.delVarFlag(self.key, "fakeroot")
200
201class ExportFuncsNode(AstNode):
202 def __init__(self, filename, lineno, fns, classname):
203 AstNode.__init__(self, filename, lineno)
204 self.n = fns.split()
205 self.classname = classname
206
207 def eval(self, data):
208
209 for func in self.n:
210 calledfunc = self.classname + "_" + func
211
212 if data.getVar(func, False) and not data.getVarFlag(func, 'export_func'):
213 continue
214
215 if data.getVar(func, False):
216 data.setVarFlag(func, 'python', None)
217 data.setVarFlag(func, 'func', None)
218
219 for flag in [ "func", "python" ]:
220 if data.getVarFlag(calledfunc, flag):
221 data.setVarFlag(func, flag, data.getVarFlag(calledfunc, flag))
222 for flag in [ "dirs" ]:
223 if data.getVarFlag(func, flag):
224 data.setVarFlag(calledfunc, flag, data.getVarFlag(func, flag))
225
226 if data.getVarFlag(calledfunc, "python"):
227 data.setVar(func, " bb.build.exec_func('" + calledfunc + "', d)\n", parsing=True)
228 else:
229 if "-" in self.classname:
230 bb.fatal("The classname %s contains a dash character and is calling an sh function %s using EXPORT_FUNCTIONS. Since a dash is illegal in sh function names, this cannot work, please rename the class or don't use EXPORT_FUNCTIONS." % (self.classname, calledfunc))
231 data.setVar(func, " " + calledfunc + "\n", parsing=True)
232 data.setVarFlag(func, 'export_func', '1')
233
234class AddTaskNode(AstNode):
235 def __init__(self, filename, lineno, func, before, after):
236 AstNode.__init__(self, filename, lineno)
237 self.func = func
238 self.before = before
239 self.after = after
240
241 def eval(self, data):
242 bb.build.addtask(self.func, self.before, self.after, data)
243
244class DelTaskNode(AstNode):
245 def __init__(self, filename, lineno, func):
246 AstNode.__init__(self, filename, lineno)
247 self.func = func
248
249 def eval(self, data):
250 bb.build.deltask(self.func, data)
251
252class BBHandlerNode(AstNode):
253 def __init__(self, filename, lineno, fns):
254 AstNode.__init__(self, filename, lineno)
255 self.hs = fns.split()
256
257 def eval(self, data):
258 bbhands = data.getVar('__BBHANDLERS', False) or []
259 for h in self.hs:
260 bbhands.append(h)
261 data.setVarFlag(h, "handler", 1)
262 data.setVar('__BBHANDLERS', bbhands)
263
264class InheritNode(AstNode):
265 def __init__(self, filename, lineno, classes):
266 AstNode.__init__(self, filename, lineno)
267 self.classes = classes
268
269 def eval(self, data):
270 bb.parse.BBHandler.inherit(self.classes, self.filename, self.lineno, data)
271
272def handleInclude(statements, filename, lineno, m, force):
273 statements.append(IncludeNode(filename, lineno, m.group(1), force))
274
275def handleExport(statements, filename, lineno, m):
276 statements.append(ExportNode(filename, lineno, m.group(1)))
277
278def handleData(statements, filename, lineno, groupd):
279 statements.append(DataNode(filename, lineno, groupd))
280
281def handleMethod(statements, filename, lineno, func_name, body):
282 statements.append(MethodNode(filename, lineno, func_name, body))
283
284def handlePythonMethod(statements, filename, lineno, funcname, modulename, body):
285 statements.append(PythonMethodNode(filename, lineno, funcname, modulename, body))
286
287def handleMethodFlags(statements, filename, lineno, key, m):
288 statements.append(MethodFlagsNode(filename, lineno, key, m))
289
290def handleExportFuncs(statements, filename, lineno, m, classname):
291 statements.append(ExportFuncsNode(filename, lineno, m.group(1), classname))
292
293def handleAddTask(statements, filename, lineno, m):
294 func = m.group("func")
295 before = m.group("before")
296 after = m.group("after")
297 if func is None:
298 return
299
300 statements.append(AddTaskNode(filename, lineno, func, before, after))
301
302def handleDelTask(statements, filename, lineno, m):
303 func = m.group("func")
304 if func is None:
305 return
306
307 statements.append(DelTaskNode(filename, lineno, func))
308
309def handleBBHandlers(statements, filename, lineno, m):
310 statements.append(BBHandlerNode(filename, lineno, m.group(1)))
311
312def handleInherit(statements, filename, lineno, m):
313 classes = m.group(1)
314 statements.append(InheritNode(filename, lineno, classes))
315
316def finalize(fn, d, variant = None):
317 all_handlers = {}
318 for var in d.getVar('__BBHANDLERS', False) or []:
319 # try to add the handler
320 bb.event.register(var, d.getVar(var, False), (d.getVarFlag(var, "eventmask", True) or "").split())
321
322 bb.event.fire(bb.event.RecipePreFinalise(fn), d)
323
324 bb.data.expandKeys(d)
325 bb.data.update_data(d)
326 code = []
327 for funcname in d.getVar("__BBANONFUNCS", False) or []:
328 code.append("%s(d)" % funcname)
329 bb.utils.better_exec("\n".join(code), {"d": d})
330 bb.data.update_data(d)
331
332 tasklist = d.getVar('__BBTASKS', False) or []
333 bb.build.add_tasks(tasklist, d)
334
335 bb.parse.siggen.finalise(fn, d, variant)
336
337 d.setVar('BBINCLUDED', bb.parse.get_file_depends(d))
338
339 bb.event.fire(bb.event.RecipeParsed(fn), d)
340
341def _create_variants(datastores, names, function, onlyfinalise):
342 def create_variant(name, orig_d, arg = None):
343 if onlyfinalise and name not in onlyfinalise:
344 return
345 new_d = bb.data.createCopy(orig_d)
346 function(arg or name, new_d)
347 datastores[name] = new_d
348
349 for variant, variant_d in datastores.items():
350 for name in names:
351 if not variant:
352 # Based on main recipe
353 create_variant(name, variant_d)
354 else:
355 create_variant("%s-%s" % (variant, name), variant_d, name)
356
357def _expand_versions(versions):
358 def expand_one(version, start, end):
359 for i in xrange(start, end + 1):
360 ver = _bbversions_re.sub(str(i), version, 1)
361 yield ver
362
363 versions = iter(versions)
364 while True:
365 try:
366 version = next(versions)
367 except StopIteration:
368 break
369
370 range_ver = _bbversions_re.search(version)
371 if not range_ver:
372 yield version
373 else:
374 newversions = expand_one(version, int(range_ver.group("from")),
375 int(range_ver.group("to")))
376 versions = itertools.chain(newversions, versions)
377
378def multi_finalize(fn, d):
379 appends = (d.getVar("__BBAPPEND", True) or "").split()
380 for append in appends:
381 logger.debug(1, "Appending .bbappend file %s to %s", append, fn)
382 bb.parse.BBHandler.handle(append, d, True)
383
384 onlyfinalise = d.getVar("__ONLYFINALISE", False)
385
386 safe_d = d
387 d = bb.data.createCopy(safe_d)
388 try:
389 finalize(fn, d)
390 except bb.parse.SkipRecipe as e:
391 d.setVar("__SKIPPED", e.args[0])
392 datastores = {"": safe_d}
393
394 versions = (d.getVar("BBVERSIONS", True) or "").split()
395 if versions:
396 pv = orig_pv = d.getVar("PV", True)
397 baseversions = {}
398
399 def verfunc(ver, d, pv_d = None):
400 if pv_d is None:
401 pv_d = d
402
403 overrides = d.getVar("OVERRIDES", True).split(":")
404 pv_d.setVar("PV", ver)
405 overrides.append(ver)
406 bpv = baseversions.get(ver) or orig_pv
407 pv_d.setVar("BPV", bpv)
408 overrides.append(bpv)
409 d.setVar("OVERRIDES", ":".join(overrides))
410
411 versions = list(_expand_versions(versions))
412 for pos, version in enumerate(list(versions)):
413 try:
414 pv, bpv = version.split(":", 2)
415 except ValueError:
416 pass
417 else:
418 versions[pos] = pv
419 baseversions[pv] = bpv
420
421 if pv in versions and not baseversions.get(pv):
422 versions.remove(pv)
423 else:
424 pv = versions.pop()
425
426 # This is necessary because our existing main datastore
427 # has already been finalized with the old PV, we need one
428 # that's been finalized with the new PV.
429 d = bb.data.createCopy(safe_d)
430 verfunc(pv, d, safe_d)
431 try:
432 finalize(fn, d)
433 except bb.parse.SkipRecipe as e:
434 d.setVar("__SKIPPED", e.args[0])
435
436 _create_variants(datastores, versions, verfunc, onlyfinalise)
437
438 extended = d.getVar("BBCLASSEXTEND", True) or ""
439 if extended:
440 # the following is to support bbextends with arguments, for e.g. multilib
441 # an example is as follows:
442 # BBCLASSEXTEND = "multilib:lib32"
443 # it will create foo-lib32, inheriting multilib.bbclass and set
444 # BBEXTENDCURR to "multilib" and BBEXTENDVARIANT to "lib32"
445 extendedmap = {}
446 variantmap = {}
447
448 for ext in extended.split():
449 eext = ext.split(':', 2)
450 if len(eext) > 1:
451 extendedmap[ext] = eext[0]
452 variantmap[ext] = eext[1]
453 else:
454 extendedmap[ext] = ext
455
456 pn = d.getVar("PN", True)
457 def extendfunc(name, d):
458 if name != extendedmap[name]:
459 d.setVar("BBEXTENDCURR", extendedmap[name])
460 d.setVar("BBEXTENDVARIANT", variantmap[name])
461 else:
462 d.setVar("PN", "%s-%s" % (pn, name))
463 bb.parse.BBHandler.inherit(extendedmap[name], fn, 0, d)
464
465 safe_d.setVar("BBCLASSEXTEND", extended)
466 _create_variants(datastores, extendedmap.keys(), extendfunc, onlyfinalise)
467
468 for variant, variant_d in datastores.iteritems():
469 if variant:
470 try:
471 if not onlyfinalise or variant in onlyfinalise:
472 finalize(fn, variant_d, variant)
473 except bb.parse.SkipRecipe as e:
474 variant_d.setVar("__SKIPPED", e.args[0])
475
476 if len(datastores) > 1:
477 variants = filter(None, datastores.iterkeys())
478 safe_d.setVar("__VARIANTS", " ".join(variants))
479
480 datastores[""] = d
481 return datastores