| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2016 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 |
import os |
| 9 |
import sys |
| 10 |
import typing as T |
| 11 |
from collections import defaultdict |
| 12 |
from dataclasses import dataclass |
| 13 |
import itertools |
| 14 |
from pathlib import Path |
| 15 |
|
| 16 |
from .. import mparser, mesonlib, mlog |
| 17 |
from .. import environment |
| 18 |
|
| 19 |
from ..interpreterbase import ( |
| 20 |
MesonInterpreterObject, |
| 21 |
InterpreterBase, |
| 22 |
InvalidArguments, |
| 23 |
BreakRequest, |
| 24 |
ContinueRequest, |
| 25 |
Disabler, |
| 26 |
default_resolve_key, |
| 27 |
is_disabled, |
| 28 |
UnknownValue, |
| 29 |
UndefinedVariable, |
| 30 |
InterpreterObject, |
| 31 |
) |
| 32 |
|
| 33 |
from ..interpreterbase.helpers import flatten |
| 34 |
|
| 35 |
from ..interpreter import ( |
| 36 |
StringHolder, |
| 37 |
BooleanHolder, |
| 38 |
IntegerHolder, |
| 39 |
ArrayHolder, |
| 40 |
DictHolder, |
| 41 |
) |
| 42 |
|
| 43 |
from ..mparser import ( |
| 44 |
ArgumentNode, |
| 45 |
ArithmeticNode, |
| 46 |
ArrayNode, |
| 47 |
AssignmentNode, |
| 48 |
BaseNode, |
| 49 |
EmptyNode, |
| 50 |
IdNode, |
| 51 |
MethodNode, |
| 52 |
NotNode, |
| 53 |
PlusAssignmentNode, |
| 54 |
TernaryNode, |
| 55 |
SymbolNode, |
| 56 |
Token, |
| 57 |
FunctionNode, |
| 58 |
) |
| 59 |
|
| 60 |
if T.TYPE_CHECKING: |
| 61 |
from .visitor import AstVisitor |
| 62 |
from ..interpreter import Interpreter |
| 63 |
from ..interpreterbase import TYPE_var, TYPE_nvar |
| 64 |
from ..mparser import ( |
| 65 |
AndNode, |
| 66 |
ComparisonNode, |
| 67 |
ForeachClauseNode, |
| 68 |
IfClauseNode, |
| 69 |
IndexNode, |
| 70 |
OrNode, |
| 71 |
TestCaseClauseNode, |
| 72 |
UMinusNode, |
| 73 |
) |
| 74 |
from ..mesonlib import SubProject |
| 75 |
|
| 76 |
_T = T.TypeVar('_T') |
| 77 |
_V = T.TypeVar('_V') |
| 78 |
|
| 79 |
def _symbol(val: str) -> SymbolNode: |
| 80 |
return SymbolNode(Token('', '', 0, 0, 0, (0, 0), val)) |
| 81 |
|
| 82 |
# `IntrospectionFile` is to the `IntrospectionInterpreter` what `File` is to the normal `Interpreter`. |
| 83 |
@dataclass |
| 84 |
class IntrospectionFile: |
| 85 |
subdir: str |
| 86 |
rel: str |
| 87 |
|
| 88 |
def to_abs_path(self, root_dir: Path) -> Path: |
| 89 |
return (root_dir / self.subdir / self.rel).resolve() |
| 90 |
|
| 91 |
def __hash__(self) -> int: |
| 92 |
return hash((self.__class__.__name__, self.subdir, self.rel)) |
| 93 |
|
| 94 |
# `IntrospectionDependency` is to the `IntrospectionInterpreter` what `Dependency` is to the normal `Interpreter`. |
| 95 |
@dataclass |
| 96 |
class IntrospectionDependency(MesonInterpreterObject): |
| 97 |
name: T.Union[str, UnknownValue] |
| 98 |
required: T.Union[bool, UnknownValue] |
| 99 |
version: T.Union[T.List[str], UnknownValue] |
| 100 |
has_fallback: bool |
| 101 |
conditional: bool |
| 102 |
node: FunctionNode |
| 103 |
|
| 104 |
# `IntrospectionBuildTarget` is to the `IntrospectionInterpreter` what `BuildTarget` is to the normal `Interpreter`. |
| 105 |
@dataclass |
| 106 |
class IntrospectionBuildTarget(MesonInterpreterObject): |
| 107 |
name: str |
| 108 |
machine: str |
| 109 |
id: str |
| 110 |
typename: str |
| 111 |
defined_in: str |
| 112 |
subdir: str |
| 113 |
build_by_default: T.Union[bool, UnknownValue] |
| 114 |
installed: T.Union[bool, UnknownValue] |
| 115 |
outputs: T.List[str] |
| 116 |
source_nodes: T.List[BaseNode] |
| 117 |
extra_files: BaseNode |
| 118 |
kwargs: T.Dict[str, TYPE_var] |
| 119 |
node: FunctionNode |
| 120 |
|
| 121 |
def is_ignored_edge(src: T.Union[BaseNode, UnknownValue]) -> bool: |
| 122 |
return (isinstance(src, FunctionNode) and src.func_name.value not in {'files', 'get_variable'}) or isinstance(src, MethodNode) |
| 123 |
|
| 124 |
class DataflowDAG: |
| 125 |
src_to_tgts: T.DefaultDict[T.Union[BaseNode, UnknownValue], T.Set[T.Union[BaseNode, UnknownValue]]] |
| 126 |
tgt_to_srcs: T.DefaultDict[T.Union[BaseNode, UnknownValue], T.Set[T.Union[BaseNode, UnknownValue]]] |
| 127 |
|
| 128 |
def __init__(self) -> None: |
| 129 |
self.src_to_tgts = defaultdict(set) |
| 130 |
self.tgt_to_srcs = defaultdict(set) |
| 131 |
|
| 132 |
def add_edge(self, source: T.Union[BaseNode, UnknownValue], target: T.Union[BaseNode, UnknownValue]) -> None: |
| 133 |
self.src_to_tgts[source].add(target) |
| 134 |
self.tgt_to_srcs[target].add(source) |
| 135 |
|
| 136 |
# Returns all nodes in the DAG that are reachable from a node in `srcs`. |
| 137 |
# In other words, A node `a` is part of the returned set exactly if data |
| 138 |
# from `srcs` flows into `a`, directly or indirectly. |
| 139 |
# Certain edges are ignored. |
| 140 |
def reachable(self, srcs: T.Set[T.Union[BaseNode, UnknownValue]], reverse: bool) -> T.Set[T.Union[BaseNode, UnknownValue]]: |
| 141 |
reachable = srcs.copy() |
| 142 |
active = srcs.copy() |
| 143 |
while active: |
| 144 |
new: T.Set[T.Union[BaseNode, UnknownValue]] = set() |
| 145 |
if reverse: |
| 146 |
for tgt in active: |
| 147 |
new.update(src for src in self.tgt_to_srcs[tgt] if not is_ignored_edge(src)) |
| 148 |
else: |
| 149 |
for src in active: |
| 150 |
if is_ignored_edge(src): |
| 151 |
continue |
| 152 |
new.update(tgt for tgt in self.src_to_tgts[src]) |
| 153 |
reachable.update(new) |
| 154 |
active = new |
| 155 |
return reachable |
| 156 |
|
| 157 |
# Returns all paths from src to target. |
| 158 |
# Certain edges are ignored. |
| 159 |
def find_all_paths(self, src: T.Union[BaseNode, UnknownValue], target: T.Union[BaseNode, UnknownValue]) -> T.List[T.List[T.Union[BaseNode, UnknownValue]]]: |
| 160 |
queue = [(src, [src])] |
| 161 |
paths = [] |
| 162 |
while queue: |
| 163 |
cur, path = queue.pop() |
| 164 |
if cur == target: |
| 165 |
paths.append(path) |
| 166 |
if is_ignored_edge(cur): |
| 167 |
continue |
| 168 |
queue.extend((tgt, path + [tgt]) for tgt in self.src_to_tgts[cur]) |
| 169 |
return paths |
| 170 |
|
| 171 |
class AstInterpreter(InterpreterBase): |
| 172 |
def __init__(self, source_root: str, subdir: str, subproject: SubProject, subproject_dir: str, env: environment.Environment, visitors: T.Optional[T.List[AstVisitor]] = None): |
| 173 |
super().__init__(source_root, subdir, subproject, subproject_dir, env) |
| 174 |
self.visitors = visitors if visitors is not None else [] |
| 175 |
self.nesting: T.List[int] = [] |
| 176 |
self.cur_assignments: T.DefaultDict[str, T.List[T.Tuple[T.List[int], T.Union[BaseNode, UnknownValue]]]] = defaultdict(list) |
| 177 |
self.all_assignment_nodes: T.DefaultDict[str, T.List[AssignmentNode]] = defaultdict(list) |
| 178 |
# dataflow_dag is an acyclic directed graph that contains an edge |
| 179 |
# from one instance of `BaseNode` to another instance of `BaseNode` if |
| 180 |
# data flows directly from one to the other. Example: If meson.build |
| 181 |
# contains this: |
| 182 |
# var = 'foo' + '123' |
| 183 |
# executable(var, 'src.c') |
| 184 |
# var = 'bar' |
| 185 |
# dataflow_dag will contain an edge from the IdNode corresponding to |
| 186 |
# 'var' in line 2 to the ArithmeticNode corresponding to 'foo' + '123'. |
| 187 |
# This graph is crucial for e.g. node_to_runtime_value because we have |
| 188 |
# to know that 'var' in line2 is 'foo123' and not 'bar'. |
| 189 |
self.dataflow_dag = DataflowDAG() |
| 190 |
self.funcvals: T.Dict[BaseNode, T.Any] = {} |
| 191 |
self.tainted = False |
| 192 |
self.predefined_vars = { |
| 193 |
'meson': UnknownValue(), |
| 194 |
'host_machine': UnknownValue(), |
| 195 |
'build_machine': UnknownValue(), |
| 196 |
'target_machine': UnknownValue() |
| 197 |
} |
| 198 |
self.funcs.update({'project': self.func_do_nothing, |
| 199 |
'test': self.func_do_nothing, |
| 200 |
'benchmark': self.func_do_nothing, |
| 201 |
'install_headers': self.func_do_nothing, |
| 202 |
'install_man': self.func_do_nothing, |
| 203 |
'install_data': self.func_do_nothing, |
| 204 |
'install_subdir': self.func_do_nothing, |
| 205 |
'install_symlink': self.func_do_nothing, |
| 206 |
'install_emptydir': self.func_do_nothing, |
| 207 |
'configuration_data': self.func_do_nothing, |
| 208 |
'configure_file': self.func_do_nothing, |
| 209 |
'find_program': self.func_do_nothing, |
| 210 |
'include_directories': self.func_do_nothing, |
| 211 |
'add_global_arguments': self.func_do_nothing, |
| 212 |
'add_global_link_arguments': self.func_do_nothing, |
| 213 |
'add_project_arguments': self.func_do_nothing, |
| 214 |
'add_project_dependencies': self.func_do_nothing, |
| 215 |
'add_project_link_arguments': self.func_do_nothing, |
| 216 |
'message': self.func_do_nothing, |
| 217 |
'generator': self.func_do_nothing, |
| 218 |
'error': self.func_do_nothing, |
| 219 |
'run_command': self.func_do_nothing, |
| 220 |
'assert': self.func_do_nothing, |
| 221 |
'subproject': self.func_do_nothing, |
| 222 |
'dependency': self.func_do_nothing, |
| 223 |
'get_option': self.func_do_nothing, |
| 224 |
'join_paths': self.func_do_nothing, |
| 225 |
'environment': self.func_do_nothing, |
| 226 |
'import': self.func_do_nothing, |
| 227 |
'vcs_tag': self.func_do_nothing, |
| 228 |
'add_languages': self.func_do_nothing, |
| 229 |
'declare_dependency': self.func_do_nothing, |
| 230 |
'files': self.func_files, |
| 231 |
'executable': self.func_do_nothing, |
| 232 |
'static_library': self.func_do_nothing, |
| 233 |
'shared_library': self.func_do_nothing, |
| 234 |
'library': self.func_do_nothing, |
| 235 |
'build_target': self.func_do_nothing, |
| 236 |
'custom_target': self.func_do_nothing, |
| 237 |
'run_target': self.func_do_nothing, |
| 238 |
'subdir': self.func_subdir, |
| 239 |
'set_variable': self.func_set_variable, |
| 240 |
'get_variable': self.func_get_variable, |
| 241 |
'unset_variable': self.func_unset_variable, |
| 242 |
'is_disabler': self.func_do_nothing, |
| 243 |
'is_variable': self.func_do_nothing, |
| 244 |
'disabler': self.func_do_nothing, |
| 245 |
'default': self.func_do_nothing, |
| 246 |
'jar': self.func_do_nothing, |
| 247 |
'warning': self.func_do_nothing, |
| 248 |
'shared_module': self.func_do_nothing, |
| 249 |
'option': self.func_do_nothing, |
| 250 |
'both_libraries': self.func_do_nothing, |
| 251 |
'add_test_setup': self.func_do_nothing, |
| 252 |
'subdir_done': self.func_do_nothing, |
| 253 |
'alias_target': self.func_do_nothing, |
| 254 |
'summary': self.func_do_nothing, |
| 255 |
'range': self.func_do_nothing, |
| 256 |
'structured_sources': self.func_do_nothing, |
| 257 |
'debug': self.func_do_nothing, |
| 258 |
}) |
| 259 |
|
| 260 |
def _unholder_args(self, args: T.Any, kwargs: T.Any) -> T.Tuple[T.Any, T.Any]: |
| 261 |
return args, kwargs |
| 262 |
|
| 263 |
def _holderify(self, res: T.Any) -> T.Any: |
| 264 |
return res |
| 265 |
|
| 266 |
def func_do_nothing(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> UnknownValue: |
| 267 |
return UnknownValue() |
| 268 |
|
| 269 |
def load_root_meson_file(self) -> None: |
| 270 |
super().load_root_meson_file() |
| 271 |
for i in self.visitors: |
| 272 |
self.ast.accept(i) |
| 273 |
|
| 274 |
def func_subdir(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> None: |
| 275 |
args = self.flatten_args(args) |
| 276 |
if len(args) != 1 or not isinstance(args[0], str): |
| 277 |
sys.stderr.write(f'Unable to evaluate subdir({args}) in AstInterpreter --> Skipping\n') |
| 278 |
return |
| 279 |
|
| 280 |
subdir, is_new = self._resolve_subdir(self.source_root, args[0]) |
| 281 |
if not is_new: |
| 282 |
sys.stderr.write('Trying to enter {} which has already been visited --> Skipping\n'.format(args[0])) |
| 283 |
return |
| 284 |
|
| 285 |
if not self._evaluate_subdir(self.source_root, subdir, self.visitors): |
| 286 |
buildfilename = os.path.join(subdir, environment.build_filename) |
| 287 |
sys.stderr.write(f'Unable to find build file {buildfilename} --> Skipping\n') |
| 288 |
|
| 289 |
def inner_method_call(self, obj: BaseNode, method_name: str, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Any: |
| 290 |
for arg in itertools.chain(args, kwargs.values()): |
| 291 |
if isinstance(arg, UnknownValue): |
| 292 |
return UnknownValue() |
| 293 |
|
| 294 |
if isinstance(obj, str): |
| 295 |
result = StringHolder(obj, T.cast('Interpreter', self)).method_call(method_name, args, kwargs) |
| 296 |
elif isinstance(obj, bool): |
| 297 |
result = BooleanHolder(obj, T.cast('Interpreter', self)).method_call(method_name, args, kwargs) |
| 298 |
elif isinstance(obj, int): |
| 299 |
result = IntegerHolder(obj, T.cast('Interpreter', self)).method_call(method_name, args, kwargs) |
| 300 |
elif isinstance(obj, list): |
| 301 |
result = ArrayHolder(obj, T.cast('Interpreter', self)).method_call(method_name, args, kwargs) |
| 302 |
elif isinstance(obj, dict): |
| 303 |
result = DictHolder(obj, T.cast('Interpreter', self)).method_call(method_name, args, kwargs) |
| 304 |
else: |
| 305 |
return UnknownValue() |
| 306 |
return result |
| 307 |
|
| 308 |
def method_call(self, node: mparser.MethodNode) -> None: |
| 309 |
invocable = node.source_object |
| 310 |
self.evaluate_statement(invocable) |
| 311 |
obj = self.node_to_runtime_value(invocable) |
| 312 |
method_name = node.name.value |
| 313 |
(args, kwargs) = self.reduce_arguments(node.args) |
| 314 |
if is_disabled(args, kwargs): |
| 315 |
res = Disabler() |
| 316 |
else: |
| 317 |
res = self.inner_method_call(obj, method_name, args, kwargs) |
| 318 |
self.funcvals[node] = res |
| 319 |
|
| 320 |
def evaluate_fstring(self, node: mparser.StringNode) -> None: |
| 321 |
pass |
| 322 |
|
| 323 |
def evaluate_arraystatement(self, cur: mparser.ArrayNode) -> None: |
| 324 |
for arg in cur.args.arguments: |
| 325 |
self.evaluate_statement(arg) |
| 326 |
|
| 327 |
def evaluate_arithmeticstatement(self, cur: ArithmeticNode) -> None: |
| 328 |
self.evaluate_statement(cur.left) |
| 329 |
self.evaluate_statement(cur.right) |
| 330 |
|
| 331 |
def evaluate_uminusstatement(self, cur: UMinusNode) -> None: |
| 332 |
self.evaluate_statement(cur.value) |
| 333 |
|
| 334 |
def evaluate_ternary(self, node: TernaryNode) -> None: |
| 335 |
assert isinstance(node, TernaryNode) |
| 336 |
self.evaluate_statement(node.condition) |
| 337 |
self.evaluate_statement(node.trueblock) |
| 338 |
self.evaluate_statement(node.falseblock) |
| 339 |
|
| 340 |
def evaluate_dictstatement(self, node: mparser.DictNode) -> None: |
| 341 |
for k, v in node.args.kwargs.items(): |
| 342 |
self.evaluate_statement(k) |
| 343 |
self.evaluate_statement(v) |
| 344 |
|
| 345 |
def evaluate_indexing(self, node: IndexNode) -> None: |
| 346 |
self.evaluate_statement(node.iobject) |
| 347 |
self.evaluate_statement(node.index) |
| 348 |
|
| 349 |
def reduce_arguments( |
| 350 |
self, |
| 351 |
args: mparser.ArgumentNode, |
| 352 |
key_resolver: T.Callable[[mparser.BaseNode], str] = default_resolve_key, |
| 353 |
duplicate_key_error: T.Optional[str] = None, |
| 354 |
) -> T.Tuple[T.List[T.Any], T.Any]: |
| 355 |
for arg in args.arguments: |
| 356 |
self.evaluate_statement(arg) |
| 357 |
for value in args.kwargs.values(): |
| 358 |
self.evaluate_statement(value) |
| 359 |
if isinstance(args, ArgumentNode): |
| 360 |
kwargs = {} |
| 361 |
for key, val in args.kwargs.items(): |
| 362 |
kwargs[key_resolver(key)] = val |
| 363 |
if args.incorrect_order(): |
| 364 |
raise InvalidArguments('All keyword arguments must be after positional arguments.') |
| 365 |
return self.flatten_args(args.arguments), kwargs |
| 366 |
else: |
| 367 |
return self.flatten_args(args), {} |
| 368 |
|
| 369 |
def evaluate_comparison(self, node: ComparisonNode) -> None: |
| 370 |
self.evaluate_statement(node.left) |
| 371 |
self.evaluate_statement(node.right) |
| 372 |
|
| 373 |
def evaluate_andstatement(self, cur: AndNode) -> None: |
| 374 |
self.evaluate_statement(cur.left) |
| 375 |
self.evaluate_statement(cur.right) |
| 376 |
|
| 377 |
def evaluate_orstatement(self, cur: OrNode) -> None: |
| 378 |
self.evaluate_statement(cur.left) |
| 379 |
self.evaluate_statement(cur.right) |
| 380 |
|
| 381 |
def evaluate_notstatement(self, cur: NotNode) -> None: |
| 382 |
self.evaluate_statement(cur.value) |
| 383 |
|
| 384 |
def find_potential_writes(self, node: BaseNode) -> T.Set[str]: |
| 385 |
if isinstance(node, mparser.ForeachClauseNode): |
| 386 |
return {el.value for el in node.varnames} | self.find_potential_writes(node.block) |
| 387 |
elif isinstance(node, mparser.CodeBlockNode): |
| 388 |
ret = set() |
| 389 |
for line in node.lines: |
| 390 |
ret.update(self.find_potential_writes(line)) |
| 391 |
return ret |
| 392 |
elif isinstance(node, (AssignmentNode, PlusAssignmentNode)): |
| 393 |
return set([node.var_name.value]) | self.find_potential_writes(node.value) |
| 394 |
elif isinstance(node, IdNode): |
| 395 |
return set() |
| 396 |
elif isinstance(node, ArrayNode): |
| 397 |
ret = set() |
| 398 |
for arg in node.args.arguments: |
| 399 |
ret.update(self.find_potential_writes(arg)) |
| 400 |
return ret |
| 401 |
elif isinstance(node, mparser.DictNode): |
| 402 |
ret = set() |
| 403 |
for k, v in node.args.kwargs.items(): |
| 404 |
ret.update(self.find_potential_writes(k)) |
| 405 |
ret.update(self.find_potential_writes(v)) |
| 406 |
return ret |
| 407 |
elif isinstance(node, FunctionNode): |
| 408 |
ret = set() |
| 409 |
for arg in node.args.arguments: |
| 410 |
ret.update(self.find_potential_writes(arg)) |
| 411 |
for arg in node.args.kwargs.values(): |
| 412 |
ret.update(self.find_potential_writes(arg)) |
| 413 |
return ret |
| 414 |
elif isinstance(node, MethodNode): |
| 415 |
ret = self.find_potential_writes(node.source_object) |
| 416 |
for arg in node.args.arguments: |
| 417 |
ret.update(self.find_potential_writes(arg)) |
| 418 |
for arg in node.args.kwargs.values(): |
| 419 |
ret.update(self.find_potential_writes(arg)) |
| 420 |
return ret |
| 421 |
elif isinstance(node, ArithmeticNode): |
| 422 |
return self.find_potential_writes(node.left) | self.find_potential_writes(node.right) |
| 423 |
elif isinstance(node, (mparser.NumberNode, mparser.StringNode, mparser.BreakNode, mparser.BooleanNode, mparser.ContinueNode)): |
| 424 |
return set() |
| 425 |
elif isinstance(node, mparser.IfClauseNode): |
| 426 |
if isinstance(node.elseblock, EmptyNode): |
| 427 |
ret = set() |
| 428 |
else: |
| 429 |
ret = self.find_potential_writes(node.elseblock.block) |
| 430 |
for i in node.ifs: |
| 431 |
ret.update(self.find_potential_writes(i)) |
| 432 |
return ret |
| 433 |
elif isinstance(node, mparser.IndexNode): |
| 434 |
return self.find_potential_writes(node.iobject) | self.find_potential_writes(node.index) |
| 435 |
elif isinstance(node, mparser.IfNode): |
| 436 |
return self.find_potential_writes(node.condition) | self.find_potential_writes(node.block) |
| 437 |
elif isinstance(node, (mparser.ComparisonNode, mparser.OrNode, mparser.AndNode)): |
| 438 |
return self.find_potential_writes(node.left) | self.find_potential_writes(node.right) |
| 439 |
elif isinstance(node, mparser.NotNode): |
| 440 |
return self.find_potential_writes(node.value) |
| 441 |
elif isinstance(node, mparser.TernaryNode): |
| 442 |
return self.find_potential_writes(node.condition) | self.find_potential_writes(node.trueblock) | self.find_potential_writes(node.falseblock) |
| 443 |
elif isinstance(node, mparser.UMinusNode): |
| 444 |
return self.find_potential_writes(node.value) |
| 445 |
elif isinstance(node, mparser.ParenthesizedNode): |
| 446 |
return self.find_potential_writes(node.inner) |
| 447 |
raise mesonlib.MesonBugException('Unhandled node type') |
| 448 |
|
| 449 |
def evaluate_foreach(self, node: ForeachClauseNode) -> None: |
| 450 |
asses = self.find_potential_writes(node) |
| 451 |
for ass in asses: |
| 452 |
self.cur_assignments[ass].append((self.nesting.copy(), UnknownValue())) |
| 453 |
try: |
| 454 |
self.evaluate_codeblock(node.block) |
| 455 |
except ContinueRequest: |
| 456 |
pass |
| 457 |
except BreakRequest: |
| 458 |
pass |
| 459 |
for ass in asses: |
| 460 |
self.cur_assignments[ass].append((self.nesting.copy(), UnknownValue())) # In case the foreach loops 0 times. |
| 461 |
|
| 462 |
def evaluate_if(self, node: IfClauseNode) -> None: |
| 463 |
self.nesting.append(0) |
| 464 |
for i in node.ifs: |
| 465 |
self.evaluate_codeblock(i.block) |
| 466 |
self.nesting[-1] += 1 |
| 467 |
if not isinstance(node.elseblock, EmptyNode): |
| 468 |
self.evaluate_codeblock(node.elseblock.block) |
| 469 |
self.nesting.pop() |
| 470 |
for var_name in self.cur_assignments: |
| 471 |
potential_values = [] |
| 472 |
oldval = self.get_cur_value_if_defined(var_name) |
| 473 |
if not isinstance(oldval, UndefinedVariable): |
| 474 |
potential_values.append(oldval) |
| 475 |
for nesting, value in self.cur_assignments[var_name]: |
| 476 |
if len(nesting) > len(self.nesting): |
| 477 |
potential_values.append(value) |
| 478 |
self.cur_assignments[var_name] = [(nesting, v) for (nesting, v) in self.cur_assignments[var_name] if len(nesting) <= len(self.nesting)] |
| 479 |
if len(potential_values) > 1 or (len(potential_values) > 0 and isinstance(oldval, UndefinedVariable)): |
| 480 |
uv = UnknownValue() |
| 481 |
for pv in potential_values: |
| 482 |
self.dataflow_dag.add_edge(pv, uv) |
| 483 |
self.cur_assignments[var_name].append((self.nesting.copy(), uv)) |
| 484 |
|
| 485 |
def func_files(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Any: |
| 486 |
ret: T.List[T.Union[IntrospectionFile, UnknownValue]] = [] |
| 487 |
for arg in args: |
| 488 |
if isinstance(arg, str): |
| 489 |
ret.append(IntrospectionFile(self.subdir, arg)) |
| 490 |
elif isinstance(arg, UnknownValue): |
| 491 |
ret.append(UnknownValue()) |
| 492 |
else: |
| 493 |
raise TypeError |
| 494 |
return ret |
| 495 |
|
| 496 |
def get_cur_value_if_defined(self, var_name: str) -> T.Union[BaseNode, UnknownValue, UndefinedVariable]: |
| 497 |
if var_name in self.predefined_vars: |
| 498 |
return self.predefined_vars[var_name] |
| 499 |
for nesting, value in reversed(self.cur_assignments[var_name]): |
| 500 |
if len(self.nesting) >= len(nesting) and self.nesting[:len(nesting)] == nesting: |
| 501 |
return value |
| 502 |
if self.tainted: |
| 503 |
return UnknownValue() |
| 504 |
return UndefinedVariable() |
| 505 |
|
| 506 |
def get_cur_value(self, var_name: str) -> T.Union[BaseNode, UnknownValue]: |
| 507 |
ret = self.get_cur_value_if_defined(var_name) |
| 508 |
if isinstance(ret, UndefinedVariable): |
| 509 |
path = mlog.get_relative_path(Path(self.current_node.filename), Path(os.getcwd())) |
| 510 |
mlog.warning(f"{path}:{self.current_node.lineno}:{self.current_node.colno} will always crash if executed, since a variable named `{var_name}` is not defined") |
| 511 |
# We could add more advanced analysis of code referencing undefined |
| 512 |
# variables, but it is probably not worth the effort and the |
| 513 |
# complexity. So we do the simplest thing, returning an |
| 514 |
# UnknownValue. |
| 515 |
return UnknownValue() |
| 516 |
return ret |
| 517 |
|
| 518 |
# The function `node_to_runtime_value` takes a node of the ast as an |
| 519 |
# argument and tries to return the same thing that would be passed to e.g. |
| 520 |
# `func_message` if you put `message(node)` in your `meson.build` file and |
| 521 |
# run `meson setup`. If this is not possible, `UnknownValue()` is returned. |
| 522 |
# There are 3 Reasons why this is sometimes impossible: |
| 523 |
# 1. Because the meson rewriter is imperfect and has not implemented everything yet |
| 524 |
# 2. Because the value is different on different machines, example: |
| 525 |
# ```meson |
| 526 |
# node = somedep.found() |
| 527 |
# message(node) |
| 528 |
# ``` |
| 529 |
# will print `true` on some machines and `false` on others, so |
| 530 |
# `node_to_runtime_value` does not know whether to return `true` or |
| 531 |
# `false` and will return `UnknownValue()`. |
| 532 |
# 3. Here: |
| 533 |
# ```meson |
| 534 |
# foreach x : [1, 2] |
| 535 |
# node = x |
| 536 |
# message(node) |
| 537 |
# endforeach |
| 538 |
# ``` |
| 539 |
# `node_to_runtime_value` does not know whether to return `1` or `2` and |
| 540 |
# will return `UnknownValue()`. |
| 541 |
# |
| 542 |
# If you have something like |
| 543 |
# ``` |
| 544 |
# node = [123, somedep.found()] |
| 545 |
# ``` |
| 546 |
# `node_to_runtime_value` will return `[123, UnknownValue()]`. |
| 547 |
def node_to_runtime_value(self, node: T.Union[UnknownValue, BaseNode, TYPE_var]) -> T.Any: |
| 548 |
if isinstance(node, (mparser.StringNode, mparser.BooleanNode, mparser.NumberNode)): |
| 549 |
return node.value |
| 550 |
elif isinstance(node, mparser.StringNode): |
| 551 |
if node.is_fstring: |
| 552 |
return UnknownValue() |
| 553 |
else: |
| 554 |
return node.value |
| 555 |
elif isinstance(node, list): |
| 556 |
return [self.node_to_runtime_value(x) for x in node] |
| 557 |
elif isinstance(node, ArrayNode): |
| 558 |
return [self.node_to_runtime_value(x) for x in node.args.arguments] |
| 559 |
elif isinstance(node, mparser.DictNode): |
| 560 |
return {self.node_to_runtime_value(k): self.node_to_runtime_value(v) for k, v in node.args.kwargs.items()} |
| 561 |
elif isinstance(node, IdNode): |
| 562 |
assert len(self.dataflow_dag.tgt_to_srcs[node]) == 1 |
| 563 |
val = next(iter(self.dataflow_dag.tgt_to_srcs[node])) |
| 564 |
return self.node_to_runtime_value(val) |
| 565 |
elif isinstance(node, (MethodNode, FunctionNode)): |
| 566 |
funcval = self.funcvals[node] |
| 567 |
if isinstance(funcval, (dict, str)): |
| 568 |
return funcval |
| 569 |
else: |
| 570 |
return self.node_to_runtime_value(funcval) |
| 571 |
elif isinstance(node, ArithmeticNode): |
| 572 |
left = self.node_to_runtime_value(node.left) |
| 573 |
right = self.node_to_runtime_value(node.right) |
| 574 |
if isinstance(left, list) and isinstance(right, UnknownValue): |
| 575 |
return left + [right] |
| 576 |
if isinstance(right, list) and isinstance(left, UnknownValue): |
| 577 |
return [left] + right |
| 578 |
if isinstance(left, UnknownValue) or isinstance(right, UnknownValue): |
| 579 |
return UnknownValue() |
| 580 |
if node.operation == '+': |
| 581 |
if isinstance(left, dict) and isinstance(right, dict): |
| 582 |
ret = left.copy() |
| 583 |
for k, v in right.items(): |
| 584 |
ret[k] = v |
| 585 |
return ret |
| 586 |
if isinstance(left, list): |
| 587 |
if not isinstance(right, list): |
| 588 |
right = [right] |
| 589 |
return left + right |
| 590 |
return left + right |
| 591 |
elif node.operation == '-': |
| 592 |
return left - right |
| 593 |
elif node.operation == '*': |
| 594 |
return left * right |
| 595 |
elif node.operation == '/': |
| 596 |
if isinstance(left, int) and isinstance(right, int): |
| 597 |
return left // right |
| 598 |
elif isinstance(left, str) and isinstance(right, str): |
| 599 |
return os.path.join(left, right).replace('\\', '/') |
| 600 |
elif node.operation == '%': |
| 601 |
if isinstance(left, int) and isinstance(right, int): |
| 602 |
return left % right |
| 603 |
elif isinstance(node, (UnknownValue, IntrospectionBuildTarget, IntrospectionFile, IntrospectionDependency, str, bool, int)): |
| 604 |
return node |
| 605 |
elif isinstance(node, mparser.IndexNode): |
| 606 |
iobject = self.node_to_runtime_value(node.iobject) |
| 607 |
index = self.node_to_runtime_value(node.index) |
| 608 |
if isinstance(iobject, UnknownValue) or isinstance(index, UnknownValue): |
| 609 |
return UnknownValue() |
| 610 |
return iobject[index] |
| 611 |
elif isinstance(node, mparser.ComparisonNode): |
| 612 |
left = self.node_to_runtime_value(node.left) |
| 613 |
right = self.node_to_runtime_value(node.right) |
| 614 |
if isinstance(left, UnknownValue) or isinstance(right, UnknownValue): |
| 615 |
return UnknownValue() |
| 616 |
if node.ctype == '==': |
| 617 |
return left == right |
| 618 |
elif node.ctype == '!=': |
| 619 |
return left != right |
| 620 |
elif node.ctype == 'in': |
| 621 |
return left in right |
| 622 |
elif node.ctype == 'not in': |
| 623 |
return left not in right |
| 624 |
elif isinstance(node, mparser.TernaryNode): |
| 625 |
cond = self.node_to_runtime_value(node.condition) |
| 626 |
if isinstance(cond, UnknownValue): |
| 627 |
return UnknownValue() |
| 628 |
if cond is True: |
| 629 |
return self.node_to_runtime_value(node.trueblock) |
| 630 |
if cond is False: |
| 631 |
return self.node_to_runtime_value(node.falseblock) |
| 632 |
elif isinstance(node, mparser.OrNode): |
| 633 |
left = self.node_to_runtime_value(node.left) |
| 634 |
right = self.node_to_runtime_value(node.right) |
| 635 |
if isinstance(left, UnknownValue) or isinstance(right, UnknownValue): |
| 636 |
return UnknownValue() |
| 637 |
return left or right |
| 638 |
elif isinstance(node, mparser.AndNode): |
| 639 |
left = self.node_to_runtime_value(node.left) |
| 640 |
right = self.node_to_runtime_value(node.right) |
| 641 |
if isinstance(left, UnknownValue) or isinstance(right, UnknownValue): |
| 642 |
return UnknownValue() |
| 643 |
return left and right |
| 644 |
elif isinstance(node, mparser.UMinusNode): |
| 645 |
val = self.node_to_runtime_value(node.value) |
| 646 |
if isinstance(val, UnknownValue): |
| 647 |
return val |
| 648 |
if isinstance(val, (int, float)): |
| 649 |
return -val |
| 650 |
elif isinstance(node, mparser.NotNode): |
| 651 |
val = self.node_to_runtime_value(node.value) |
| 652 |
if isinstance(val, UnknownValue): |
| 653 |
return val |
| 654 |
if isinstance(val, bool): |
| 655 |
return not val |
| 656 |
elif isinstance(node, mparser.ParenthesizedNode): |
| 657 |
return self.node_to_runtime_value(node.inner) |
| 658 |
raise mesonlib.MesonBugException('Unhandled node type') |
| 659 |
|
| 660 |
def assignment(self, node: AssignmentNode) -> None: |
| 661 |
assert isinstance(node, AssignmentNode) |
| 662 |
self.evaluate_statement(node.value) |
| 663 |
self.cur_assignments[node.var_name.value].append((self.nesting.copy(), node.value)) |
| 664 |
self.all_assignment_nodes[node.var_name.value].append(node) |
| 665 |
|
| 666 |
def evaluate_plusassign(self, node: PlusAssignmentNode) -> None: |
| 667 |
assert isinstance(node, PlusAssignmentNode) |
| 668 |
self.evaluate_statement(node.value) |
| 669 |
lhs = self.get_cur_value(node.var_name.value) |
| 670 |
newval: T.Union[UnknownValue, ArithmeticNode] |
| 671 |
if isinstance(lhs, UnknownValue): |
| 672 |
newval = UnknownValue() |
| 673 |
else: |
| 674 |
newval = mparser.ArithmeticNode(operation='+', left=lhs, operator=_symbol('+'), right=node.value) |
| 675 |
self.cur_assignments[node.var_name.value].append((self.nesting.copy(), newval)) |
| 676 |
self.all_assignment_nodes[node.var_name.value].append(node) |
| 677 |
|
| 678 |
self.dataflow_dag.add_edge(lhs, newval) |
| 679 |
self.dataflow_dag.add_edge(node.value, newval) |
| 680 |
|
| 681 |
def func_set_variable(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> None: |
| 682 |
assert isinstance(node, FunctionNode) |
| 683 |
if bool(node.args.kwargs): |
| 684 |
raise InvalidArguments('set_variable accepts no keyword arguments') |
| 685 |
if len(node.args.arguments) != 2: |
| 686 |
raise InvalidArguments('set_variable requires exactly two positional arguments') |
| 687 |
var_name = args[0] |
| 688 |
value = node.args.arguments[1] |
| 689 |
if isinstance(var_name, UnknownValue): |
| 690 |
self.evaluate_statement(value) |
| 691 |
self.tainted = True |
| 692 |
return |
| 693 |
assert isinstance(var_name, str) |
| 694 |
equiv = AssignmentNode(var_name=IdNode(Token('', '', 0, 0, 0, (0, 0), var_name)), value=value, operator=_symbol('=')) |
| 695 |
equiv.ast_id = str(id(equiv)) |
| 696 |
self.evaluate_statement(equiv) |
| 697 |
|
| 698 |
def func_get_variable(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Any: |
| 699 |
assert isinstance(node, FunctionNode) |
| 700 |
var_name = args[0] |
| 701 |
if isinstance(var_name, UnknownValue): |
| 702 |
val: T.Union[UnknownValue, BaseNode] = UnknownValue() |
| 703 |
else: |
| 704 |
assert isinstance(var_name, str) |
| 705 |
val = self.get_cur_value(var_name) |
| 706 |
self.dataflow_dag.add_edge(val, node) |
| 707 |
return val |
| 708 |
|
| 709 |
def func_unset_variable(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> None: |
| 710 |
assert isinstance(node, FunctionNode) |
| 711 |
if bool(node.args.kwargs): |
| 712 |
raise InvalidArguments('unset_variable accepts no keyword arguments') |
| 713 |
if len(node.args.arguments) != 1: |
| 714 |
raise InvalidArguments('unset_variable requires exactly one positional arguments') |
| 715 |
var_name = args[0] |
| 716 |
assert isinstance(var_name, str) |
| 717 |
self.cur_assignments[var_name].append((self.nesting.copy(), node)) |
| 718 |
|
| 719 |
def nodes_to_pretty_filelist(self, root_path: Path, subdir: str, nodes: T.List[BaseNode]) -> T.List[T.Union[str, UnknownValue]]: |
| 720 |
def src_to_abs(src: T.Union[str, IntrospectionFile, UnknownValue]) -> T.Union[str, UnknownValue]: |
| 721 |
if isinstance(src, str): |
| 722 |
return os.path.normpath(os.path.join(root_path, subdir, src)) |
| 723 |
elif isinstance(src, IntrospectionFile): |
| 724 |
return str(src.to_abs_path(root_path)) |
| 725 |
elif isinstance(src, UnknownValue): |
| 726 |
return src |
| 727 |
else: |
| 728 |
raise TypeError |
| 729 |
|
| 730 |
rtvals: T.List[T.Any] = flatten([self.node_to_runtime_value(sn) for sn in nodes]) |
| 731 |
return [src_to_abs(x) for x in rtvals] |
| 732 |
|
| 733 |
def flatten_args(self, args_raw: T.Union[TYPE_nvar, T.Sequence[TYPE_nvar]], include_unknown_args: bool = False) -> T.List[TYPE_var]: |
| 734 |
# Make sure we are always dealing with lists |
| 735 |
if isinstance(args_raw, list): |
| 736 |
args = args_raw |
| 737 |
else: |
| 738 |
args = [args_raw] |
| 739 |
|
| 740 |
# BaseNode resolves to Any. :/ |
| 741 |
flattened_args: T.List[T.Union[TYPE_var, T.Any]] = [] |
| 742 |
|
| 743 |
# Resolve the contents of args |
| 744 |
for i in args: |
| 745 |
if isinstance(i, BaseNode): |
| 746 |
resolved = self.node_to_runtime_value(i) |
| 747 |
if resolved is not None: |
| 748 |
if not isinstance(resolved, list): |
| 749 |
resolved = [resolved] |
| 750 |
flattened_args += resolved |
| 751 |
elif isinstance(i, (str, bool, int, float, UnknownValue, IntrospectionFile)) or include_unknown_args: |
| 752 |
flattened_args += [i] |
| 753 |
else: |
| 754 |
raise NotImplementedError |
| 755 |
return flattened_args |
| 756 |
|
| 757 |
def evaluate_testcase(self, node: TestCaseClauseNode) -> Disabler | None: |
| 758 |
return Disabler(subproject=self.subproject) |
| 759 |
|
| 760 |
def evaluate_statement(self, cur: mparser.BaseNode) -> T.Optional[InterpreterObject]: |
| 761 |
if hasattr(cur, 'args'): |
| 762 |
for arg in cur.args.arguments: |
| 763 |
self.dataflow_dag.add_edge(arg, cur) |
| 764 |
for k, v in cur.args.kwargs.items(): |
| 765 |
self.dataflow_dag.add_edge(v, cur) |
| 766 |
for attr in ['source_object', 'left', 'right', 'items', 'iobject', 'index', 'condition']: |
| 767 |
if hasattr(cur, attr): |
| 768 |
assert isinstance(getattr(cur, attr), mparser.BaseNode) |
| 769 |
self.dataflow_dag.add_edge(getattr(cur, attr), cur) |
| 770 |
if isinstance(cur, mparser.IdNode): |
| 771 |
self.dataflow_dag.add_edge(self.get_cur_value(cur.value), cur) |
| 772 |
return None |
| 773 |
else: |
| 774 |
return super().evaluate_statement(cur) |
| 775 |
|
| 776 |
def function_call(self, node: mparser.FunctionNode) -> T.Any: |
| 777 |
ret = super().function_call(node) |
| 778 |
if ret is not None: |
| 779 |
self.funcvals[node] = ret |
| 780 |
return ret |