Debian Codegraph @

mesonbuild/interpreterbase/interpreterbase.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2017 The Meson development team
3
4 # This class contains the basic functionality needed to run any interpreter
5 # or an interpreter-based tool.
6 from __future__ import annotations
7
8 from .. import environment, mparser, mesonlib
9
10 from .baseobjects import (
11 InterpreterObject,
12 MesonInterpreterObject,
13 MutableInterpreterObject,
14 ObjectHolder,
15 IterableObject,
16 ContextManagerObject,
17 DefaultObject,
18
19 HoldableTypes,
20 )
21
22 from .exceptions import (
23 BreakRequest,
24 ContinueRequest,
25 InterpreterException,
26 InvalidArguments,
27 InvalidCode,
28 SubdirDoneRequest,
29 )
30
31 from .. import mlog
32 from . import operator
33 from .decorators import FeatureNew
34 from .disabler import Disabler, is_disabled
35 from .helpers import default_resolve_key, flatten, resolve_second_level_holders, stringifyUserArguments
36 from .operator import MesonOperator
37 from ._unholder import _unholder
38
39 import os, copy, hashlib, re, pathlib
40 import typing as T
41 import textwrap
42
43 if T.TYPE_CHECKING:
44 from .baseobjects import InterpreterObjectTypeVar, TYPE_kwargs, TYPE_var
45 from ..ast import AstVisitor
46 from ..interpreter import Interpreter
47 from ..mesonlib import SubProject
48
49 HolderMapType = T.Dict[
50 T.Union[
51 T.Type[mesonlib.HoldableObject],
52 T.Type[int],
53 T.Type[bool],
54 T.Type[str],
55 T.Type[list],
56 T.Type[dict],
57 ],
58 # For some reason, this has to be a callable and can't just be ObjectHolder[InterpreterObjectTypeVar]
59 T.Callable[[InterpreterObjectTypeVar, 'Interpreter'], ObjectHolder[InterpreterObjectTypeVar]]
60 ]
61
62 FunctionType = T.Dict[
63 str,
64 T.Callable[[mparser.BaseNode, T.List[TYPE_var], T.Dict[str, TYPE_var]], TYPE_var]
65 ]
66
67
68 class InvalidCodeOnVoid(InvalidCode):
69
70 def __init__(self, op_type: str) -> None:
71 super().__init__(f'Cannot perform {op_type!r} operation on void statement.')
72
73
74 class InterpreterBase:
75 def __init__(self, source_root: str, subdir: str, subproject: SubProject, subproject_dir: str, env: environment.Environment):
76 self.source_root = source_root
77 self.funcs: FunctionType = {}
78 self.builtin: T.Dict[str, InterpreterObject] = {}
79 # Holder maps store a mapping from an HoldableObject to a class ObjectHolder
80 self.holder_map: HolderMapType = {}
81 self.bound_holder_map: HolderMapType = {}
82 self.build_def_files: mesonlib.OrderedSet[str] = mesonlib.OrderedSet()
83 self.processed_buildfiles: T.Set[str] = set()
84 self.subdir = subdir
85 self.root_subdir = subdir
86 self.subproject = subproject
87 self.subproject_dir = subproject_dir
88 self.environment = env
89 self.coredata = env.get_coredata()
90 self.variables: T.Dict[str, InterpreterObject] = {}
91 self.argument_depth = 0
92 self.current_lineno = -1
93 # Current node set during a function call. This can be used as location
94 # when printing a warning message during a method call.
95 self.current_node = mparser.BaseNode(-1, -1, 'sentinel')
96 # This is set to `version_string` when this statement is evaluated:
97 # meson.version().compare_version(version_string)
98 # If it was part of a if-clause, it is used to temporally override the
99 # current meson version target within that if-block.
100 self.tmp_meson_version: T.Optional[mesonlib.Range[mesonlib.Version]] = None
101
102 def handle_meson_version_from_ast(self) -> None:
103 # do nothing in an AST interpreter
104 return
105
106 def read_buildfile(self, fname: str, errname: str) -> str:
107 try:
108 with open(fname, encoding='utf-8') as f:
109 return f.read()
110 except UnicodeDecodeError as e:
111 node = mparser.BaseNode(1, 1, errname)
112 raise InvalidCode.from_node(f'Build file failed to parse as unicode: {e}', node=node)
113
114 def load_root_meson_file(self) -> None:
115 build_filename = os.path.join(self.subdir, environment.build_filename)
116 self.build_def_files.add(build_filename)
117 mesonfile = os.path.join(self.source_root, build_filename)
118 if not os.path.isfile(mesonfile):
119 raise InvalidArguments(f'Missing Meson file in {mesonfile}')
120 code = self.read_buildfile(mesonfile, mesonfile)
121 if code.isspace():
122 raise InvalidCode('Builder file is empty.')
123 assert isinstance(code, str)
124 try:
125 self.ast = mparser.Parser(code, mesonfile).parse()
126 self.handle_meson_version_from_ast()
127 except mparser.ParseException as me:
128 me.file = mesonfile
129 if me.ast:
130 # try to detect parser errors from new syntax added by future
131 # meson versions, and just tell the user to update meson
132 self.ast = me.ast
133 self.handle_meson_version_from_ast()
134 raise me
135
136 def parse_project(self) -> None:
137 """
138 Parses project() and initializes languages, compilers etc. Do this
139 early because we need this before we parse the rest of the AST.
140 """
141 self.evaluate_codeblock(self.ast, end=1)
142
143 def sanity_check_ast(self) -> None:
144 def _is_project(ast: mparser.CodeBlockNode) -> object:
145 if not isinstance(ast, mparser.CodeBlockNode):
146 raise InvalidCode('AST is of invalid type. Possibly a bug in the parser.')
147 if not ast.lines:
148 raise InvalidCode('No statements in code.')
149 first = ast.lines[0]
150 return isinstance(first, mparser.FunctionNode) and first.func_name.value == 'project'
151
152 if not _is_project(self.ast):
153 p = pathlib.Path(self.source_root).resolve()
154 found = p
155 for parent in p.parents:
156 if (parent / 'meson.build').is_file():
157 with open(parent / 'meson.build', encoding='utf-8') as f:
158 code = f.read()
159
160 try:
161 ast = mparser.Parser(code, 'empty').parse()
162 except mparser.ParseException:
163 continue
164
165 if _is_project(ast):
166 found = parent
167 break
168 else:
169 break
170
171 error = 'first statement must be a call to project()'
172 if found != p:
173 raise InvalidCode(f'Not the project root: {error}\n\nDid you mean to run meson from the directory: "{found}"?')
174 else:
175 raise InvalidCode(f'Invalid source tree: {error}')
176
177 def run(self) -> None:
178 # Evaluate everything after the first line, which is project() because
179 # we already parsed that in self.parse_project()
180 try:
181 self.evaluate_codeblock(self.ast, start=1)
182 except SubdirDoneRequest:
183 pass
184
185 def evaluate_codeblock(self, node: mparser.CodeBlockNode, start: int = 0, end: T.Optional[int] = None) -> None:
186 if node is None:
187 return
188 if not isinstance(node, mparser.CodeBlockNode):
189 e = InvalidCode('Tried to execute a non-codeblock. Possibly a bug in the parser.')
190 e.lineno = node.lineno
191 e.colno = node.colno
192 raise e
193 statements = node.lines[start:end]
194 i = 0
195 while i < len(statements):
196 cur = statements[i]
197 try:
198 self.evaluate_statement(cur)
199 except Exception as e:
200 if getattr(e, 'lineno', None) is None:
201 # We are doing the equivalent to setattr here and mypy does not like it
202 # NOTE: self.current_node is continually updated during processing
203 e.lineno = self.current_node.lineno # type: ignore
204 e.colno = self.current_node.colno # type: ignore
205 e.file = os.path.join(self.source_root, self.subdir, environment.build_filename) # type: ignore
206 raise e
207 i += 1 # In THE FUTURE jump over blocks and stuff.
208
209 def evaluate_statement(self, cur: mparser.BaseNode) -> T.Optional[InterpreterObject]:
210 self.current_node = cur
211 if isinstance(cur, mparser.FunctionNode):
212 return self.function_call(cur)
213 elif isinstance(cur, mparser.PlusAssignmentNode):
214 self.evaluate_plusassign(cur)
215 elif isinstance(cur, mparser.AssignmentNode):
216 self.assignment(cur)
217 elif isinstance(cur, mparser.MethodNode):
218 return self.method_call(cur)
219 elif isinstance(cur, mparser.StringNode):
220 if cur.is_fstring:
221 if cur.is_multiline:
222 return self.evaluate_multiline_fstring(cur)
223 else:
224 return self.evaluate_fstring(cur)
225 else:
226 return self._holderify(cur.value)
227 elif isinstance(cur, mparser.BooleanNode):
228 return self._holderify(cur.value)
229 elif isinstance(cur, mparser.IfClauseNode):
230 return self.evaluate_if(cur)
231 elif isinstance(cur, mparser.IdNode):
232 return self.get_variable(cur.value)
233 elif isinstance(cur, mparser.ComparisonNode):
234 return self.evaluate_comparison(cur)
235 elif isinstance(cur, mparser.ArrayNode):
236 return self.evaluate_arraystatement(cur)
237 elif isinstance(cur, mparser.DictNode):
238 return self.evaluate_dictstatement(cur)
239 elif isinstance(cur, mparser.NumberNode):
240 return self._holderify(cur.value)
241 elif isinstance(cur, mparser.AndNode):
242 return self.evaluate_andstatement(cur)
243 elif isinstance(cur, mparser.OrNode):
244 return self.evaluate_orstatement(cur)
245 elif isinstance(cur, mparser.NotNode):
246 return self.evaluate_notstatement(cur)
247 elif isinstance(cur, mparser.UMinusNode):
248 return self.evaluate_uminusstatement(cur)
249 elif isinstance(cur, mparser.ArithmeticNode):
250 return self.evaluate_arithmeticstatement(cur)
251 elif isinstance(cur, mparser.ForeachClauseNode):
252 self.evaluate_foreach(cur)
253 elif isinstance(cur, mparser.IndexNode):
254 return self.evaluate_indexing(cur)
255 elif isinstance(cur, mparser.TernaryNode):
256 return self.evaluate_ternary(cur)
257 elif isinstance(cur, mparser.ContinueNode):
258 raise ContinueRequest()
259 elif isinstance(cur, mparser.BreakNode):
260 raise BreakRequest()
261 elif isinstance(cur, mparser.ParenthesizedNode):
262 return self.evaluate_statement(cur.inner)
263 elif isinstance(cur, mparser.TestCaseClauseNode):
264 return self.evaluate_testcase(cur)
265 else:
266 raise InvalidCode("Unknown statement.")
267 return None
268
269 def evaluate_arraystatement(self, cur: mparser.ArrayNode) -> InterpreterObject:
270 (arguments, kwargs) = self.reduce_arguments(cur.args)
271 if len(kwargs) > 0:
272 raise InvalidCode('Keyword arguments are invalid in array construction.')
273 return self._holderify([_unholder(x) for x in arguments])
274
275 @FeatureNew('dict', '0.47.0')
276 def evaluate_dictstatement(self, cur: mparser.DictNode) -> InterpreterObject:
277 def resolve_key(key: mparser.BaseNode) -> str:
278 if not isinstance(key, mparser.StringNode):
279 FeatureNew.single_use('Dictionary entry using non literal key', '0.53.0', self.subproject)
280 key_holder = self.evaluate_statement(key)
281 if key_holder is None:
282 raise InvalidArguments('Key cannot be void.')
283 str_key = _unholder(key_holder)
284 if not isinstance(str_key, str):
285 raise InvalidArguments('Key must be a string')
286 return str_key
287 arguments, kwargs = self.reduce_arguments(cur.args, key_resolver=resolve_key, duplicate_key_error='Duplicate dictionary key: {}')
288 assert not arguments
289 return self._holderify({k: _unholder(v) for k, v in kwargs.items()})
290
291 def evaluate_notstatement(self, cur: mparser.NotNode) -> InterpreterObject:
292 v = self.evaluate_statement(cur.value)
293 if v is None:
294 raise InvalidCodeOnVoid('not')
295 if isinstance(v, Disabler):
296 return v
297 return self._holderify(v.operator_call(MesonOperator.NOT, None))
298
299 def evaluate_if(self, node: mparser.IfClauseNode) -> T.Optional[Disabler]:
300 for i in node.ifs:
301 # Reset self.tmp_meson_version to know if it gets set during this
302 # statement evaluation.
303 self.tmp_meson_version = None
304 result = self.evaluate_statement(i.condition)
305 if result is None:
306 raise InvalidCodeOnVoid('if')
307 if isinstance(result, Disabler):
308 return result
309 if not isinstance(result, InterpreterObject):
310 raise mesonlib.MesonBugException(f'Argument to if ({result}) is not an InterpreterObject but {type(result).__name__}.')
311 res = result.operator_call(MesonOperator.BOOL, None)
312 if not isinstance(res, bool):
313 raise InvalidCode(f'If clause {result!r} does not evaluate to true or false.')
314 prev_meson_version = mesonlib.project_meson_versions[self.subproject]
315 if self.tmp_meson_version and isinstance(prev_meson_version, mesonlib.Range):
316 always = prev_meson_version.always(self.tmp_meson_version)
317 if always is not None:
318 mlog.warning(f"Conditional on version '{self.tmp_meson_version}' always evaluates to {str(always).lower()}",
319 location=self.current_node)
320 mesonlib.project_meson_versions[self.subproject] = prev_meson_version.intersect(self.tmp_meson_version)
321 try:
322 if res:
323 self.evaluate_codeblock(i.block)
324 return None
325 finally:
326 mesonlib.project_meson_versions[self.subproject] = prev_meson_version
327 if not isinstance(node.elseblock, mparser.EmptyNode):
328 self.evaluate_codeblock(node.elseblock.block)
329 return None
330
331 def evaluate_testcase(self, node: mparser.TestCaseClauseNode) -> T.Optional[Disabler]:
332 result = self.evaluate_statement(node.condition)
333 if isinstance(result, Disabler):
334 return result
335 if not isinstance(result, ContextManagerObject):
336 raise InvalidCode(f'testcase clause {result!r} does not evaluate to a context manager.')
337 with result:
338 self.evaluate_codeblock(node.block)
339 return None
340
341 def evaluate_comparison(self, node: mparser.ComparisonNode) -> InterpreterObject:
342 val1 = self.evaluate_statement(node.left)
343 if val1 is None:
344 raise mesonlib.MesonException('Cannot compare a void statement on the left-hand side')
345 if isinstance(val1, Disabler):
346 return val1
347 val2 = self.evaluate_statement(node.right)
348 if val2 is None:
349 raise mesonlib.MesonException('Cannot compare a void statement on the right-hand side')
350 if isinstance(val2, Disabler):
351 return val2
352
353 op = operator.MAPPING[node.ctype]
354
355 # Check if the arguments should be reversed for simplicity (this essentially converts `in` to `contains`)
356 if op in (MesonOperator.IN, MesonOperator.NOT_IN):
357 val1, val2 = val2, val1
358
359 val1.current_node = node
360 return self._holderify(val1.operator_call(op, _unholder(val2)))
361
362 def evaluate_andstatement(self, cur: mparser.AndNode) -> InterpreterObject:
363 l = self.evaluate_statement(cur.left)
364 if l is None:
365 raise mesonlib.MesonException('Cannot compare a void statement on the left-hand side')
366 if isinstance(l, Disabler):
367 return l
368 l_bool = l.operator_call(MesonOperator.BOOL, None)
369 if not l_bool:
370 return self._holderify(l_bool)
371 r = self.evaluate_statement(cur.right)
372 if r is None:
373 raise mesonlib.MesonException('Cannot compare a void statement on the right-hand side')
374 if isinstance(r, Disabler):
375 return r
376 return self._holderify(r.operator_call(MesonOperator.BOOL, None))
377
378 def evaluate_orstatement(self, cur: mparser.OrNode) -> InterpreterObject:
379 l = self.evaluate_statement(cur.left)
380 if l is None:
381 raise mesonlib.MesonException('Cannot compare a void statement on the left-hand side')
382 if isinstance(l, Disabler):
383 return l
384 l_bool = l.operator_call(MesonOperator.BOOL, None)
385 if l_bool:
386 return self._holderify(l_bool)
387 r = self.evaluate_statement(cur.right)
388 if r is None:
389 raise mesonlib.MesonException('Cannot compare a void statement on the right-hand side')
390 if isinstance(r, Disabler):
391 return r
392 return self._holderify(r.operator_call(MesonOperator.BOOL, None))
393
394 def evaluate_uminusstatement(self, cur: mparser.UMinusNode) -> InterpreterObject:
395 v = self.evaluate_statement(cur.value)
396 if v is None:
397 raise InvalidCodeOnVoid('unary minus')
398 if isinstance(v, Disabler):
399 return v
400 v.current_node = cur
401 return self._holderify(v.operator_call(MesonOperator.UMINUS, None))
402
403 def evaluate_arithmeticstatement(self, cur: mparser.ArithmeticNode) -> InterpreterObject:
404 l = self.evaluate_statement(cur.left)
405 if isinstance(l, Disabler):
406 return l
407 r = self.evaluate_statement(cur.right)
408 if isinstance(r, Disabler):
409 return r
410 if l is None or r is None:
411 raise InvalidCodeOnVoid(cur.operation)
412
413 l.current_node = cur
414 res = l.operator_call(operator.MAPPING[cur.operation], _unholder(r))
415 return self._holderify(res)
416
417 def evaluate_ternary(self, node: mparser.TernaryNode) -> T.Optional[InterpreterObject]:
418 result = self.evaluate_statement(node.condition)
419 if result is None:
420 raise mesonlib.MesonException('Cannot use a void statement as condition for ternary operator.')
421 if isinstance(result, Disabler):
422 return result
423 result.current_node = node
424 result_bool = result.operator_call(MesonOperator.BOOL, None)
425 if result_bool:
426 return self.evaluate_statement(node.trueblock)
427 else:
428 return self.evaluate_statement(node.falseblock)
429
430 @FeatureNew('multiline format strings', '0.63.0')
431 def evaluate_multiline_fstring(self, node: mparser.StringNode) -> InterpreterObject:
432 return self.evaluate_fstring(node)
433
434 @FeatureNew('format strings', '0.58.0')
435 def evaluate_fstring(self, node: mparser.StringNode) -> InterpreterObject:
436 def replace(match: T.Match[str]) -> str:
437 var = str(match.group(1))
438 try:
439 val = _unholder(self.variables[var])
440 if isinstance(val, (list, dict)):
441 FeatureNew.single_use('List or dictionary in f-string', '1.3.0', self.subproject, location=self.current_node)
442 try:
443 return stringifyUserArguments(val, self.subproject)
444 except InvalidArguments as e:
445 raise InvalidArguments(f'f-string: {str(e)}')
446 except KeyError:
447 ustr = f'Identifier "{var}" does not name a variable.'
448 from difflib import get_close_matches
449 close_matches = get_close_matches(var, self.variables.keys())
450 if close_matches:
451 ustr += f' Did you mean "{close_matches[0]}"?'
452 raise InvalidCode(ustr)
453
454 res = re.sub(r'@([_a-zA-Z][_0-9a-zA-Z]*)@', replace, node.value)
455 return self._holderify(res)
456
457 def evaluate_foreach(self, node: mparser.ForeachClauseNode) -> None:
458 items = self.evaluate_statement(node.items)
459 if not isinstance(items, IterableObject):
460 raise InvalidArguments('Items of foreach loop do not support iterating')
461
462 tsize = items.iter_tuple_size()
463 if len(node.varnames) != (tsize or 1):
464 raise InvalidArguments(f'Foreach expects exactly {tsize or 1} variables for iterating over objects of type {items.display_name()}')
465
466 for i in items.iter_self():
467 if tsize is None:
468 if isinstance(i, tuple):
469 raise mesonlib.MesonBugException(f'Iteration of {items} returned a tuple even though iter_tuple_size() is None')
470 self.set_variable(node.varnames[0].value, self._holderify(i))
471 else:
472 if not isinstance(i, tuple):
473 raise mesonlib.MesonBugException(f'Iteration of {items} did not return a tuple even though iter_tuple_size() is {tsize}')
474 if len(i) != tsize:
475 raise mesonlib.MesonBugException(f'Iteration of {items} did not return a tuple even though iter_tuple_size() is {tsize}')
476 for j in range(tsize):
477 self.set_variable(node.varnames[j].value, self._holderify(i[j]))
478 try:
479 self.evaluate_codeblock(node.block)
480 except ContinueRequest:
481 continue
482 except BreakRequest:
483 break
484
485 def evaluate_plusassign(self, node: mparser.PlusAssignmentNode) -> None:
486 varname = node.var_name.value
487 addition = self.evaluate_statement(node.value)
488 if addition is None:
489 raise InvalidCodeOnVoid('plus assign')
490
491 # Remember that all variables are immutable. We must always create a
492 # full new variable and then assign it.
493 old_variable = self.get_variable(varname)
494 old_variable.current_node = node
495 new_value = self._holderify(old_variable.operator_call(MesonOperator.PLUS, _unholder(addition)))
496 self.set_variable(varname, new_value)
497
498 def evaluate_indexing(self, node: mparser.IndexNode) -> InterpreterObject:
499 iobject = self.evaluate_statement(node.iobject)
500 if iobject is None:
501 raise InterpreterException('Tried to evaluate indexing on void.')
502 if isinstance(iobject, Disabler):
503 return iobject
504 index_holder = self.evaluate_statement(node.index)
505 if index_holder is None:
506 raise InvalidArguments('Cannot use void statement as index.')
507 index = _unholder(index_holder)
508
509 iobject.current_node = node
510 return self._holderify(iobject.operator_call(MesonOperator.INDEX, index))
511
512 def function_call(self, node: mparser.FunctionNode) -> T.Optional[InterpreterObject]:
513 func_name = node.func_name.value
514 (h_posargs, h_kwargs) = self.reduce_arguments(node.args)
515 (posargs, kwargs) = self._unholder_args(h_posargs, h_kwargs)
516 if is_disabled(posargs, kwargs) and func_name not in {'get_variable', 'set_variable', 'unset_variable', 'is_disabler'}:
517 return Disabler()
518 if func_name in self.funcs:
519 func = self.funcs[func_name]
520 func_args = posargs
521 if not getattr(func, 'no-args-flattening', False):
522 func_args = flatten(posargs)
523 if not getattr(func, 'no-second-level-holder-flattening', False):
524 func_args, kwargs = resolve_second_level_holders(func_args, kwargs)
525 self.current_node = node
526 res = func(node, func_args, kwargs)
527 return self._holderify(res) if res is not None else None
528 else:
529 from difflib import get_close_matches
530 close_matches = get_close_matches(func_name, self.funcs.keys())
531 if close_matches:
532 raise InvalidCode(f'Unknown function "{func_name}". Did you mean "{close_matches[0]}"?')
533 self.unknown_function_called(func_name)
534 return None
535
536 def method_call(self, node: mparser.MethodNode) -> T.Optional[InterpreterObject]:
537 invocable = node.source_object
538 obj: T.Optional[InterpreterObject]
539 if isinstance(invocable, mparser.IdNode):
540 object_display_name = f'variable "{invocable.value}"'
541 obj = self.get_variable(invocable.value)
542 else:
543 object_display_name = invocable.__class__.__name__
544 obj = self.evaluate_statement(invocable)
545 method_name = node.name.value
546 (h_args, h_kwargs) = self.reduce_arguments(node.args)
547 (args, kwargs) = self._unholder_args(h_args, h_kwargs)
548 if is_disabled(args, kwargs):
549 return Disabler()
550 if not isinstance(obj, InterpreterObject):
551 raise InvalidArguments(f'{object_display_name} is not callable.')
552 obj.current_node = self.current_node = node
553 res = obj.method_call(method_name, args, kwargs)
554 return self._holderify(res) if res is not None else None
555
556 def _holderify(self, res: T.Union[TYPE_var, InterpreterObject]) -> InterpreterObject:
557 if isinstance(res, HoldableTypes):
558 # Always check for an exact match first.
559 cls = self.holder_map.get(type(res), None)
560 if cls is not None:
561 # Casts to Interpreter are required here since an assertion would
562 # not work for the `ast` module.
563 return cls(res, T.cast('Interpreter', self))
564 # Try the boundary types next.
565 for typ, cls in self.bound_holder_map.items():
566 if isinstance(res, typ):
567 return cls(res, T.cast('Interpreter', self))
568 raise mesonlib.MesonBugException(f'Object {res} of type {type(res).__name__} is neither in self.holder_map nor self.bound_holder_map.')
569 elif isinstance(res, ObjectHolder):
570 raise mesonlib.MesonBugException(f'Returned object {res} of type {type(res).__name__} is an object holder.')
571 elif isinstance(res, MesonInterpreterObject):
572 return res
573 raise mesonlib.MesonBugException(f'Unknown returned object {res} of type {type(res).__name__} in the parameters.')
574
575 def _unholder_args(self,
576 args: T.List[InterpreterObject],
577 kwargs: T.Dict[str, InterpreterObject]) -> T.Tuple[T.List[TYPE_var], TYPE_kwargs]:
578 return [_unholder(x) for x in args], {k: _unholder(v) for k, v in kwargs.items()}
579
580 def unknown_function_called(self, func_name: str) -> None:
581 raise InvalidCode(f'Unknown function "{func_name}".')
582
583 def reduce_arguments(
584 self,
585 args: mparser.ArgumentNode,
586 key_resolver: T.Callable[[mparser.BaseNode], str] = default_resolve_key,
587 duplicate_key_error: T.Optional[str] = None,
588 ) -> T.Tuple[
589 T.List[InterpreterObject],
590 T.Dict[str, InterpreterObject]
591 ]:
592 if args.incorrect_order():
593 raise InvalidArguments('All keyword arguments must be after positional arguments.')
594 self.argument_depth += 1
595 reduced_pos = [self.evaluate_statement(arg) for arg in args.arguments]
596 if any(x is None for x in reduced_pos):
597 raise InvalidArguments('At least one value in the arguments is void.')
598 reduced_kw: T.Dict[str, InterpreterObject] = {}
599 for key, val in args.kwargs.items():
600 reduced_key = key_resolver(key)
601 assert isinstance(val, mparser.BaseNode)
602 reduced_val = self.evaluate_statement(val)
603 if reduced_val is None:
604 raise InvalidArguments(f'Value of key {reduced_key} is void.')
605 self.current_node = key
606 if duplicate_key_error and reduced_key in reduced_kw:
607 raise InvalidArguments(duplicate_key_error.format(reduced_key))
608 reduced_kw[reduced_key] = reduced_val
609 self.argument_depth -= 1
610 final_kw = self.expand_default_kwargs(reduced_kw)
611 return reduced_pos, final_kw
612
613 def expand_default_kwargs(self, kwargs: T.Dict[str, T.Optional[InterpreterObject]]) -> T.Dict[str, T.Optional[InterpreterObject]]:
614 if 'kwargs' not in kwargs:
615 return kwargs
616
617 kwargs_var = kwargs.pop('kwargs')
618 if isinstance(kwargs_var, DefaultObject):
619 return kwargs
620
621 to_expand = _unholder(kwargs_var)
622 if not isinstance(to_expand, dict):
623 raise InterpreterException('Value of "kwargs" must be dictionary.')
624 if 'kwargs' in to_expand:
625 raise InterpreterException('Kwargs argument must not contain a "kwargs" entry. Points for thinking meta, though. :P')
626 for k, v in to_expand.items():
627 if k in kwargs:
628 raise InterpreterException(f'Entry "{k}" defined both as a keyword argument and in a "kwarg" entry.')
629 kwargs[k] = self._holderify(v)
630 return kwargs
631
632 def assignment(self, node: mparser.AssignmentNode) -> None:
633 if self.argument_depth != 0:
634 raise InvalidArguments(textwrap.dedent('''\
635 Tried to assign values inside an argument list.
636 To specify a keyword argument, use : instead of =.
637 '''))
638 var_name = node.var_name.value
639 if not isinstance(var_name, str):
640 raise InvalidArguments('Tried to assign value to a non-variable.')
641 value = self.evaluate_statement(node.value)
642 # For mutable objects we need to make a copy on assignment
643 if isinstance(value, MutableInterpreterObject):
644 value = copy.deepcopy(value)
645 self.set_variable(var_name, value)
646
647 def set_variable(self, varname: str, variable: T.Union[TYPE_var, InterpreterObject], *, holderify: bool = False) -> None:
648 if variable is None:
649 raise InvalidCode('Can not assign void to variable.')
650 if holderify:
651 variable = self._holderify(variable)
652 else:
653 # Ensure that we are always storing ObjectHolders
654 if not isinstance(variable, InterpreterObject):
655 raise mesonlib.MesonBugException(f'set_variable in InterpreterBase called with a non InterpreterObject {variable} of type {type(variable).__name__}')
656 if not isinstance(varname, str):
657 raise InvalidCode('First argument to set_variable must be a string.')
658 if varname in self.builtin:
659 raise InvalidCode(f'Tried to overwrite internal variable "{varname}"')
660 self.variables[varname] = variable
661
662 def get_variable(self, varname: str) -> InterpreterObject:
663 if varname in self.builtin:
664 return self.builtin[varname]
665 if varname in self.variables:
666 return self.variables[varname]
667 ustr = f'Unknown variable name "{varname}".'
668 from difflib import get_close_matches
669 close_matches = get_close_matches(varname, self.variables.keys())
670 if close_matches:
671 ustr += f' Did you mean "{close_matches[0]}"?'
672 raise InvalidCode(ustr)
673
674 def _load_option_file(self) -> None:
675 from .. import optinterpreter # prevent circular import
676
677 # Load "meson.options" before "meson_options.txt", and produce a warning if
678 # it is being used with an old version. I have added check that if both
679 # exist the warning isn't raised
680 option_file = os.path.join(self.source_root, self.subdir, 'meson.options')
681 old_option_file = os.path.join(self.source_root, self.subdir, 'meson_options.txt')
682
683 if os.path.exists(option_file):
684 if os.path.exists(old_option_file):
685 if os.path.samefile(option_file, old_option_file):
686 mlog.debug("Not warning about meson.options with version minimum < 1.1 because meson_options.txt also exists")
687 else:
688 raise mesonlib.MesonException("meson.options and meson_options.txt both exist, but are not the same file.")
689 else:
690 FeatureNew.single_use('meson.options file', '1.1', self.subproject, 'Use meson_options.txt instead')
691 else:
692 option_file = old_option_file
693 if os.path.exists(option_file):
694 with open(option_file, 'rb') as f:
695 # We want fast not cryptographically secure, this is just to
696 # see if the option file has changed
697 self.coredata.options_files[self.subproject] = (option_file, hashlib.sha1(f.read()).hexdigest())
698 oi = optinterpreter.OptionInterpreter(self.environment.coredata.optstore, self.subproject)
699 oi.process(option_file)
700 self.coredata.optstore.update_project_options(oi.options, self.subproject)
701 self.build_def_files.add(option_file)
702 else:
703 self.coredata.options_files[self.subproject] = None
704
705 def _resolve_subdir(self, rootdir: str, new_subdir: str) -> T.Tuple[str, bool]:
706 subdir = os.path.join(self.subdir, new_subdir)
707 absdir = os.path.join(rootdir, subdir)
708 symlinkless_dir = os.path.realpath(absdir)
709 build_file = os.path.join(symlinkless_dir, environment.build_filename)
710 if build_file in self.processed_buildfiles:
711 return subdir, False
712 self.processed_buildfiles.add(build_file)
713 return subdir, True
714
715 def _evaluate_subdir(self, rootdir: str, subdir: str, visitors: T.Optional[T.Iterable[AstVisitor]] = None) -> bool:
716 buildfilename = os.path.join(subdir, environment.build_filename)
717 self.build_def_files.add(buildfilename)
718
719 absname = os.path.join(rootdir, buildfilename)
720 if not os.path.isfile(absname):
721 return False
722
723 code = self.read_buildfile(absname, buildfilename)
724 try:
725 codeblock = mparser.Parser(code, absname).parse()
726 except mesonlib.MesonException as me:
727 me.file = absname
728 raise me
729 self._evaluate_codeblock(codeblock, subdir, visitors)
730 return True
731
732 def _evaluate_codeblock(self, codeblock: mparser.CodeBlockNode, subdir: str,
733 visitors: T.Optional[T.Iterable[AstVisitor]] = None) -> None:
734 try:
735 prev_subdir = self.subdir
736 self.subdir = subdir
737 if visitors:
738 for visitor in visitors:
739 codeblock.accept(visitor)
740 self.evaluate_codeblock(codeblock)
741 except SubdirDoneRequest:
742 pass
743 finally:
744 self.subdir = prev_subdir