xref: /openbmc/openbmc/poky/bitbake/lib/bb/parse/ast.py (revision 45852739)
1"""
2 AbstractSyntaxTree classes for the Bitbake language
3"""
4
5# Copyright (C) 2003, 2004 Chris Larson
6# Copyright (C) 2003, 2004 Phil Blundell
7# Copyright (C) 2009 Holger Hans Peter Freyther
8#
9# SPDX-License-Identifier: GPL-2.0-only
10#
11
12import bb
13from bb import methodpool
14from bb.parse import logger
15
16class StatementGroup(list):
17    def eval(self, data):
18        for statement in self:
19            statement.eval(data)
20
21class AstNode(object):
22    def __init__(self, filename, lineno):
23        self.filename = filename
24        self.lineno = lineno
25
26class IncludeNode(AstNode):
27    def __init__(self, filename, lineno, what_file, force):
28        AstNode.__init__(self, filename, lineno)
29        self.what_file = what_file
30        self.force = force
31
32    def eval(self, data):
33        """
34        Include the file and evaluate the statements
35        """
36        s = data.expand(self.what_file)
37        logger.debug2("CONF %s:%s: including %s", self.filename, self.lineno, s)
38
39        # TODO: Cache those includes... maybe not here though
40        if self.force:
41            bb.parse.ConfHandler.include(self.filename, s, self.lineno, data, "include required")
42        else:
43            bb.parse.ConfHandler.include(self.filename, s, self.lineno, data, False)
44
45class ExportNode(AstNode):
46    def __init__(self, filename, lineno, var):
47        AstNode.__init__(self, filename, lineno)
48        self.var = var
49
50    def eval(self, data):
51        data.setVarFlag(self.var, "export", 1, op = 'exported')
52
53class UnsetNode(AstNode):
54    def __init__(self, filename, lineno, var):
55        AstNode.__init__(self, filename, lineno)
56        self.var = var
57
58    def eval(self, data):
59        loginfo = {
60            'variable': self.var,
61            'file': self.filename,
62            'line': self.lineno,
63        }
64        data.delVar(self.var,**loginfo)
65
66class UnsetFlagNode(AstNode):
67    def __init__(self, filename, lineno, var, flag):
68        AstNode.__init__(self, filename, lineno)
69        self.var = var
70        self.flag = flag
71
72    def eval(self, data):
73        loginfo = {
74            'variable': self.var,
75            'file': self.filename,
76            'line': self.lineno,
77        }
78        data.delVarFlag(self.var, self.flag, **loginfo)
79
80class DataNode(AstNode):
81    """
82    Various data related updates. For the sake of sanity
83    we have one class doing all this. This means that all
84    this need to be re-evaluated... we might be able to do
85    that faster with multiple classes.
86    """
87    def __init__(self, filename, lineno, groupd):
88        AstNode.__init__(self, filename, lineno)
89        self.groupd = groupd
90
91    def getFunc(self, key, data):
92        if 'flag' in self.groupd and self.groupd['flag'] is not None:
93            return data.getVarFlag(key, self.groupd['flag'], expand=False, noweakdefault=True)
94        else:
95            return data.getVar(key, False, noweakdefault=True, parsing=True)
96
97    def eval(self, data):
98        groupd = self.groupd
99        key = groupd["var"]
100        loginfo = {
101            'variable': key,
102            'file': self.filename,
103            'line': self.lineno,
104        }
105        if "exp" in groupd and groupd["exp"] is not None:
106            data.setVarFlag(key, "export", 1, op = 'exported', **loginfo)
107
108        op = "set"
109        if "ques" in groupd and groupd["ques"] is not None:
110            val = self.getFunc(key, data)
111            op = "set?"
112            if val is None:
113                val = groupd["value"]
114        elif "colon" in groupd and groupd["colon"] is not None:
115            e = data.createCopy()
116            op = "immediate"
117            val = e.expand(groupd["value"], key + "[:=]")
118        elif "append" in groupd and groupd["append"] is not None:
119            op = "append"
120            val = "%s %s" % ((self.getFunc(key, data) or ""), groupd["value"])
121        elif "prepend" in groupd and groupd["prepend"] is not None:
122            op = "prepend"
123            val = "%s %s" % (groupd["value"], (self.getFunc(key, data) or ""))
124        elif "postdot" in groupd and groupd["postdot"] is not None:
125            op = "postdot"
126            val = "%s%s" % ((self.getFunc(key, data) or ""), groupd["value"])
127        elif "predot" in groupd and groupd["predot"] is not None:
128            op = "predot"
129            val = "%s%s" % (groupd["value"], (self.getFunc(key, data) or ""))
130        else:
131            val = groupd["value"]
132
133        if ":append" in key or ":remove" in key or ":prepend" in key:
134            if op in ["append", "prepend", "postdot", "predot", "ques"]:
135                bb.warn(key + " " + groupd[op] + " is not a recommended operator combination, please replace it.")
136
137        flag = None
138        if 'flag' in groupd and groupd['flag'] is not None:
139            flag = groupd['flag']
140        elif groupd["lazyques"]:
141            flag = "_defaultval"
142
143        loginfo['op'] = op
144        loginfo['detail'] = groupd["value"]
145
146        if flag:
147            data.setVarFlag(key, flag, val, **loginfo)
148        else:
149            data.setVar(key, val, parsing=True, **loginfo)
150
151class MethodNode(AstNode):
152    tr_tbl = str.maketrans('/.+-@%&~', '________')
153
154    def __init__(self, filename, lineno, func_name, body, python, fakeroot):
155        AstNode.__init__(self, filename, lineno)
156        self.func_name = func_name
157        self.body = body
158        self.python = python
159        self.fakeroot = fakeroot
160
161    def eval(self, data):
162        text = '\n'.join(self.body)
163        funcname = self.func_name
164        if self.func_name == "__anonymous":
165            funcname = ("__anon_%s_%s" % (self.lineno, self.filename.translate(MethodNode.tr_tbl)))
166            self.python = True
167            text = "def %s(d):\n" % (funcname) + text
168            bb.methodpool.insert_method(funcname, text, self.filename, self.lineno - len(self.body) - 1)
169            anonfuncs = data.getVar('__BBANONFUNCS', False) or []
170            anonfuncs.append(funcname)
171            data.setVar('__BBANONFUNCS', anonfuncs)
172        if data.getVar(funcname, False):
173            # clean up old version of this piece of metadata, as its
174            # flags could cause problems
175            data.delVarFlag(funcname, 'python')
176            data.delVarFlag(funcname, 'fakeroot')
177        if self.python:
178            data.setVarFlag(funcname, "python", "1")
179        if self.fakeroot:
180            data.setVarFlag(funcname, "fakeroot", "1")
181        data.setVarFlag(funcname, "func", 1)
182        data.setVar(funcname, text, parsing=True)
183        data.setVarFlag(funcname, 'filename', self.filename)
184        data.setVarFlag(funcname, 'lineno', str(self.lineno - len(self.body)))
185
186class PythonMethodNode(AstNode):
187    def __init__(self, filename, lineno, function, modulename, body):
188        AstNode.__init__(self, filename, lineno)
189        self.function = function
190        self.modulename = modulename
191        self.body = body
192
193    def eval(self, data):
194        # Note we will add root to parsedmethods after having parse
195        # 'this' file. This means we will not parse methods from
196        # bb classes twice
197        text = '\n'.join(self.body)
198        bb.methodpool.insert_method(self.modulename, text, self.filename, self.lineno - len(self.body) - 1)
199        data.setVarFlag(self.function, "func", 1)
200        data.setVarFlag(self.function, "python", 1)
201        data.setVar(self.function, text, parsing=True)
202        data.setVarFlag(self.function, 'filename', self.filename)
203        data.setVarFlag(self.function, 'lineno', str(self.lineno - len(self.body) - 1))
204
205class ExportFuncsNode(AstNode):
206    def __init__(self, filename, lineno, fns, classname):
207        AstNode.__init__(self, filename, lineno)
208        self.n = fns.split()
209        self.classname = classname
210
211    def eval(self, data):
212
213        for func in self.n:
214            calledfunc = self.classname + "_" + func
215
216            if data.getVar(func, False) and not data.getVarFlag(func, 'export_func', False):
217                continue
218
219            if data.getVar(func, False):
220                data.setVarFlag(func, 'python', None)
221                data.setVarFlag(func, 'func', None)
222
223            for flag in [ "func", "python" ]:
224                if data.getVarFlag(calledfunc, flag, False):
225                    data.setVarFlag(func, flag, data.getVarFlag(calledfunc, flag, False))
226            for flag in [ "dirs" ]:
227                if data.getVarFlag(func, flag, False):
228                    data.setVarFlag(calledfunc, flag, data.getVarFlag(func, flag, False))
229            data.setVarFlag(func, "filename", "autogenerated")
230            data.setVarFlag(func, "lineno", 1)
231
232            if data.getVarFlag(calledfunc, "python", False):
233                data.setVar(func, "    bb.build.exec_func('" + calledfunc + "', d)\n", parsing=True)
234            else:
235                if "-" in self.classname:
236                   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))
237                data.setVar(func, "    " + calledfunc + "\n", parsing=True)
238            data.setVarFlag(func, 'export_func', '1')
239
240class AddTaskNode(AstNode):
241    def __init__(self, filename, lineno, func, before, after):
242        AstNode.__init__(self, filename, lineno)
243        self.func = func
244        self.before = before
245        self.after = after
246
247    def eval(self, data):
248        bb.build.addtask(self.func, self.before, self.after, data)
249
250class DelTaskNode(AstNode):
251    def __init__(self, filename, lineno, tasks):
252        AstNode.__init__(self, filename, lineno)
253        self.tasks = tasks
254
255    def eval(self, data):
256        tasks = data.expand(self.tasks).split()
257        for task in tasks:
258            bb.build.deltask(task, data)
259
260class BBHandlerNode(AstNode):
261    def __init__(self, filename, lineno, fns):
262        AstNode.__init__(self, filename, lineno)
263        self.hs = fns.split()
264
265    def eval(self, data):
266        bbhands = data.getVar('__BBHANDLERS', False) or []
267        for h in self.hs:
268            bbhands.append(h)
269            data.setVarFlag(h, "handler", 1)
270        data.setVar('__BBHANDLERS', bbhands)
271
272class InheritNode(AstNode):
273    def __init__(self, filename, lineno, classes):
274        AstNode.__init__(self, filename, lineno)
275        self.classes = classes
276
277    def eval(self, data):
278        bb.parse.BBHandler.inherit(self.classes, self.filename, self.lineno, data)
279
280def handleInclude(statements, filename, lineno, m, force):
281    statements.append(IncludeNode(filename, lineno, m.group(1), force))
282
283def handleExport(statements, filename, lineno, m):
284    statements.append(ExportNode(filename, lineno, m.group(1)))
285
286def handleUnset(statements, filename, lineno, m):
287    statements.append(UnsetNode(filename, lineno, m.group(1)))
288
289def handleUnsetFlag(statements, filename, lineno, m):
290    statements.append(UnsetFlagNode(filename, lineno, m.group(1), m.group(2)))
291
292def handleData(statements, filename, lineno, groupd):
293    statements.append(DataNode(filename, lineno, groupd))
294
295def handleMethod(statements, filename, lineno, func_name, body, python, fakeroot):
296    statements.append(MethodNode(filename, lineno, func_name, body, python, fakeroot))
297
298def handlePythonMethod(statements, filename, lineno, funcname, modulename, body):
299    statements.append(PythonMethodNode(filename, lineno, funcname, modulename, body))
300
301def handleExportFuncs(statements, filename, lineno, m, classname):
302    statements.append(ExportFuncsNode(filename, lineno, m.group(1), classname))
303
304def handleAddTask(statements, filename, lineno, m):
305    func = m.group("func")
306    before = m.group("before")
307    after = m.group("after")
308    if func is None:
309        return
310
311    statements.append(AddTaskNode(filename, lineno, func, before, after))
312
313def handleDelTask(statements, filename, lineno, m):
314    func = m.group(1)
315    if func is None:
316        return
317
318    statements.append(DelTaskNode(filename, lineno, func))
319
320def handleBBHandlers(statements, filename, lineno, m):
321    statements.append(BBHandlerNode(filename, lineno, m.group(1)))
322
323def handleInherit(statements, filename, lineno, m):
324    classes = m.group(1)
325    statements.append(InheritNode(filename, lineno, classes))
326
327def runAnonFuncs(d):
328    code = []
329    for funcname in d.getVar("__BBANONFUNCS", False) or []:
330        code.append("%s(d)" % funcname)
331    bb.utils.better_exec("\n".join(code), {"d": d})
332
333def finalize(fn, d, variant = None):
334    saved_handlers = bb.event.get_handlers().copy()
335    try:
336        # Found renamed variables. Exit immediately
337        if d.getVar("_FAILPARSINGERRORHANDLED", False) == True:
338            raise bb.BBHandledException()
339
340        for var in d.getVar('__BBHANDLERS', False) or []:
341            # try to add the handler
342            handlerfn = d.getVarFlag(var, "filename", False)
343            if not handlerfn:
344                bb.fatal("Undefined event handler function '%s'" % var)
345            handlerln = int(d.getVarFlag(var, "lineno", False))
346            bb.event.register(var, d.getVar(var, False), (d.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln, data=d)
347
348        bb.event.fire(bb.event.RecipePreFinalise(fn), d)
349
350        bb.data.expandKeys(d)
351
352        bb.event.fire(bb.event.RecipePostKeyExpansion(fn), d)
353
354        runAnonFuncs(d)
355
356        tasklist = d.getVar('__BBTASKS', False) or []
357        bb.event.fire(bb.event.RecipeTaskPreProcess(fn, list(tasklist)), d)
358        bb.build.add_tasks(tasklist, d)
359
360        bb.parse.siggen.finalise(fn, d, variant)
361
362        d.setVar('BBINCLUDED', bb.parse.get_file_depends(d))
363
364        bb.event.fire(bb.event.RecipeParsed(fn), d)
365    finally:
366        bb.event.set_handlers(saved_handlers)
367
368def _create_variants(datastores, names, function, onlyfinalise):
369    def create_variant(name, orig_d, arg = None):
370        if onlyfinalise and name not in onlyfinalise:
371            return
372        new_d = bb.data.createCopy(orig_d)
373        function(arg or name, new_d)
374        datastores[name] = new_d
375
376    for variant in list(datastores.keys()):
377        for name in names:
378            if not variant:
379                # Based on main recipe
380                create_variant(name, datastores[""])
381            else:
382                create_variant("%s-%s" % (variant, name), datastores[variant], name)
383
384def multi_finalize(fn, d):
385    appends = (d.getVar("__BBAPPEND") or "").split()
386    for append in appends:
387        logger.debug("Appending .bbappend file %s to %s", append, fn)
388        bb.parse.BBHandler.handle(append, d, True)
389
390    onlyfinalise = d.getVar("__ONLYFINALISE", False)
391
392    safe_d = d
393    d = bb.data.createCopy(safe_d)
394    try:
395        finalize(fn, d)
396    except bb.parse.SkipRecipe as e:
397        d.setVar("__SKIPPED", e.args[0])
398    datastores = {"": safe_d}
399
400    extended = d.getVar("BBCLASSEXTEND") or ""
401    if extended:
402        # the following is to support bbextends with arguments, for e.g. multilib
403        # an example is as follows:
404        #   BBCLASSEXTEND = "multilib:lib32"
405        # it will create foo-lib32, inheriting multilib.bbclass and set
406        # BBEXTENDCURR to "multilib" and BBEXTENDVARIANT to "lib32"
407        extendedmap = {}
408        variantmap = {}
409
410        for ext in extended.split():
411            eext = ext.split(':', 2)
412            if len(eext) > 1:
413                extendedmap[ext] = eext[0]
414                variantmap[ext] = eext[1]
415            else:
416                extendedmap[ext] = ext
417
418        pn = d.getVar("PN")
419        def extendfunc(name, d):
420            if name != extendedmap[name]:
421                d.setVar("BBEXTENDCURR", extendedmap[name])
422                d.setVar("BBEXTENDVARIANT", variantmap[name])
423            else:
424                d.setVar("PN", "%s-%s" % (pn, name))
425            bb.parse.BBHandler.inherit(extendedmap[name], fn, 0, d)
426
427        safe_d.setVar("BBCLASSEXTEND", extended)
428        _create_variants(datastores, extendedmap.keys(), extendfunc, onlyfinalise)
429
430    for variant in datastores.keys():
431        if variant:
432            try:
433                if not onlyfinalise or variant in onlyfinalise:
434                    finalize(fn, datastores[variant], variant)
435            except bb.parse.SkipRecipe as e:
436                datastores[variant].setVar("__SKIPPED", e.args[0])
437
438    datastores[""] = d
439    return datastores
440