| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2018 The Meson development team |
| 3 |
# Copyright © 2024-2025 Intel Corporation |
| 4 |
|
| 5 |
# This class contains the basic functionality needed to run any interpreter |
| 6 |
# or an interpreter-based tool |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
import os |
| 10 |
import typing as T |
| 11 |
|
| 12 |
from .. import compilers, environment, mesonlib |
| 13 |
from ..build import Executable, Jar, SharedLibrary, SharedModule, StaticLibrary, BuildProject |
| 14 |
from ..compilers import detect_compiler_for |
| 15 |
from ..interpreterbase import InvalidArguments, UnknownValue, Feature |
| 16 |
from ..interpreter import type_checking |
| 17 |
from ..mesonlib import MachineChoice, SubProject |
| 18 |
from ..options import OptionKey |
| 19 |
from ..mparser import BaseNode, ArrayNode, ElementaryNode, IdNode, FunctionNode, StringNode |
| 20 |
from .interpreter import AstInterpreter, IntrospectionBuildTarget, IntrospectionDependency |
| 21 |
|
| 22 |
if T.TYPE_CHECKING: |
| 23 |
from ..build import BuildTarget, BuildTargetKeywordArguments |
| 24 |
from ..compilers.compilers import Language |
| 25 |
from ..interpreterbase import TYPE_var |
| 26 |
from .visitor import AstVisitor |
| 27 |
|
| 28 |
|
| 29 |
_TARGET_KWARGS: T.Mapping[str, set[str]] = { |
| 30 |
'executable': {s.name for s in type_checking.EXECUTABLE_KWS}, |
| 31 |
'jar': {s.name for s in type_checking.JAR_KWS}, |
| 32 |
'library': {s.name for s in type_checking.LIBRARY_KWS}, |
| 33 |
'shared library': {s.name for s in type_checking.SHARED_LIB_KWS}, |
| 34 |
'shared module': {s.name for s in type_checking.SHARED_MOD_KWS}, |
| 35 |
'static library': {s.name for s in type_checking.STATIC_LIB_KWS}, |
| 36 |
'both libraries': {s.name for s in type_checking.LIBRARY_KWS}, |
| 37 |
} |
| 38 |
|
| 39 |
# TODO: it would be nice to not have to duplicate this |
| 40 |
BUILD_TARGET_FUNCTIONS = [ |
| 41 |
'executable', 'jar', 'library', 'shared_library', 'shared_module', |
| 42 |
'static_library', 'both_libraries' |
| 43 |
] |
| 44 |
|
| 45 |
class IntrospectionHelper: |
| 46 |
# mimic an argparse namespace |
| 47 |
def __init__(self, cross_file: T.Optional[str]): |
| 48 |
self.cross_file = [cross_file] if cross_file is not None else [] |
| 49 |
self.native_file: T.List[str] = [] |
| 50 |
self.cmd_line_options: T.Dict[OptionKey, str] = {} |
| 51 |
self.builtin_keys: T.Set[OptionKey] = set() |
| 52 |
self.d_keys: T.Set[OptionKey] = set() |
| 53 |
self.projectoptions: T.List[str] = [] |
| 54 |
|
| 55 |
def __eq__(self, other: object) -> bool: |
| 56 |
return NotImplemented |
| 57 |
|
| 58 |
class IntrospectionInterpreter(AstInterpreter): |
| 59 |
# If you run `meson setup ...` the `Interpreter`-class walks over the AST. |
| 60 |
# If you run `meson rewrite ...` and `meson introspect meson.build ...`, |
| 61 |
# the `AstInterpreter`-class walks over the AST. |
| 62 |
# Works without a build directory. |
| 63 |
# Most of the code is stolen from interpreter.Interpreter . |
| 64 |
def __init__(self, |
| 65 |
source_root: str, |
| 66 |
subdir: str, |
| 67 |
backend: str, |
| 68 |
visitors: T.Optional[T.List[AstVisitor]] = None, |
| 69 |
cross_file: T.Optional[str] = None, |
| 70 |
subproject: SubProject = mesonlib.ROOT_SUBPROJECT, |
| 71 |
subproject_dir: str = 'subprojects', |
| 72 |
env: T.Optional[environment.Environment] = None): |
| 73 |
options = IntrospectionHelper(cross_file) |
| 74 |
env_ = env or environment.Environment(source_root, None, options) |
| 75 |
super().__init__(source_root, subdir, subproject, subproject_dir, env_, visitors=visitors) |
| 76 |
|
| 77 |
self.cross_file = cross_file |
| 78 |
self.backend = backend |
| 79 |
self.build_project = BuildProject(subproject, '', subproject, MachineChoice.HOST, MachineChoice.HOST) |
| 80 |
self.project_data: T.Dict[str, T.Any] = {} |
| 81 |
self.targets: T.List[IntrospectionBuildTarget] = [] |
| 82 |
self.dependencies: T.List[IntrospectionDependency] = [] |
| 83 |
self.project_node: FunctionNode = None |
| 84 |
|
| 85 |
self.funcs.update({ |
| 86 |
'add_languages': self.func_add_languages, |
| 87 |
'dependency': self.func_dependency, |
| 88 |
'executable': self.func_executable, |
| 89 |
'jar': self.func_jar, |
| 90 |
'library': self.func_library, |
| 91 |
'project': self.func_project, |
| 92 |
'shared_library': self.func_shared_lib, |
| 93 |
'shared_module': self.func_shared_module, |
| 94 |
'static_library': self.func_static_lib, |
| 95 |
'both_libraries': self.func_both_lib, |
| 96 |
}) |
| 97 |
|
| 98 |
def func_project(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> None: |
| 99 |
if self.project_node: |
| 100 |
raise InvalidArguments('Second call to project()') |
| 101 |
assert isinstance(node, FunctionNode) |
| 102 |
self.project_node = node |
| 103 |
if len(args) < 1: |
| 104 |
raise InvalidArguments('Not enough arguments to project(). Needs at least the project name.') |
| 105 |
|
| 106 |
def _str_list(node: T.Any) -> T.Optional[T.List[str]]: |
| 107 |
if isinstance(node, ArrayNode): |
| 108 |
r = [] |
| 109 |
for v in node.args.arguments: |
| 110 |
if not isinstance(v, StringNode): |
| 111 |
return None |
| 112 |
r.append(v.value) |
| 113 |
return r |
| 114 |
if isinstance(node, StringNode): |
| 115 |
return [node.value] |
| 116 |
return None |
| 117 |
|
| 118 |
proj_name = args[0] |
| 119 |
proj_vers = kwargs.get('version', 'undefined') |
| 120 |
if isinstance(proj_vers, ElementaryNode): |
| 121 |
proj_vers = proj_vers.value |
| 122 |
if not isinstance(proj_vers, str): |
| 123 |
proj_vers = 'undefined' |
| 124 |
proj_langs = self.flatten_args(args[1:]) |
| 125 |
# Match the value returned by ``meson.project_license()`` when |
| 126 |
# no ``license`` argument is specified in the ``project()`` call. |
| 127 |
proj_license = _str_list(kwargs.get('license', None)) or ['unknown'] |
| 128 |
proj_license_files = _str_list(kwargs.get('license_files', None)) or [] |
| 129 |
self.project_data = {'descriptive_name': proj_name, 'version': proj_vers, 'license': proj_license, 'license_files': proj_license_files} |
| 130 |
|
| 131 |
self._load_option_file() |
| 132 |
|
| 133 |
if not self.is_subproject() and 'subproject_dir' in kwargs: |
| 134 |
spdirname = kwargs['subproject_dir'] |
| 135 |
if isinstance(spdirname, StringNode): |
| 136 |
assert isinstance(spdirname.value, str) |
| 137 |
self.subproject_dir = spdirname.value |
| 138 |
if not self.is_subproject(): |
| 139 |
self.project_data['subprojects'] = [] |
| 140 |
subprojects_dir = os.path.join(self.source_root, self.subproject_dir) |
| 141 |
if os.path.isdir(subprojects_dir): |
| 142 |
for i in os.listdir(subprojects_dir): |
| 143 |
if os.path.isdir(os.path.join(subprojects_dir, i)): |
| 144 |
self.do_subproject(SubProject(i)) |
| 145 |
|
| 146 |
self.environment.init_backend_options(self.backend) |
| 147 |
|
| 148 |
self._add_languages(proj_langs, True, MachineChoice.HOST) |
| 149 |
self._add_languages(proj_langs, True, MachineChoice.BUILD) |
| 150 |
|
| 151 |
def do_subproject(self, dirname: SubProject) -> None: |
| 152 |
subdir = os.path.join(self.environment.source_dir, self.subproject_dir, dirname) |
| 153 |
try: |
| 154 |
subi = IntrospectionInterpreter(self.source_root, subdir, self.backend, cross_file=self.cross_file, subproject=dirname, subproject_dir=self.subproject_dir, env=self.environment, visitors=self.visitors) |
| 155 |
subi.analyze() |
| 156 |
subi.project_data['name'] = dirname |
| 157 |
self.project_data['subprojects'] += [subi.project_data] |
| 158 |
except (mesonlib.MesonException, RuntimeError): |
| 159 |
pass |
| 160 |
|
| 161 |
def func_add_languages(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> UnknownValue: |
| 162 |
kwargs = self.flatten_kwargs(kwargs) |
| 163 |
required = kwargs.get('required', True) |
| 164 |
assert isinstance(required, (bool, Feature, UnknownValue)), 'for mypy' |
| 165 |
if isinstance(required, Feature): |
| 166 |
required = required.is_enabled() |
| 167 |
if 'native' in kwargs: |
| 168 |
native = kwargs.get('native', False) |
| 169 |
self._add_languages(args, required, MachineChoice.BUILD if native else MachineChoice.HOST) |
| 170 |
else: |
| 171 |
for for_machine in [MachineChoice.BUILD, MachineChoice.HOST]: |
| 172 |
self._add_languages(args, required, for_machine) |
| 173 |
return UnknownValue() |
| 174 |
|
| 175 |
def _add_languages(self, raw_langs: T.List[TYPE_var], required: T.Union[bool, UnknownValue], for_machine: MachineChoice) -> None: |
| 176 |
langs: T.List[Language] = [] |
| 177 |
for l in self.flatten_args(raw_langs): |
| 178 |
# we need to call .lower() here because `project('foo', 'CpP')` is valid. |
| 179 |
if isinstance(l, str): |
| 180 |
langs.append(T.cast('Language', l.lower())) |
| 181 |
elif isinstance(l, StringNode): |
| 182 |
langs.append(T.cast('Language', l.value.lower())) |
| 183 |
|
| 184 |
for lang in sorted(langs, key=compilers.sort_clink): |
| 185 |
if lang not in self.coredata.compilers[for_machine]: |
| 186 |
try: |
| 187 |
comp = detect_compiler_for(self.environment, lang, for_machine, True, self.subproject) |
| 188 |
except mesonlib.MesonException: |
| 189 |
# All code paths are evaluated regardless of conditionals, |
| 190 |
# so always ignore compiler detection failures. |
| 191 |
continue |
| 192 |
if comp: |
| 193 |
self.coredata.process_compiler_options(lang, comp, self.subproject) |
| 194 |
|
| 195 |
def func_dependency(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Optional[IntrospectionDependency]: |
| 196 |
assert isinstance(node, FunctionNode) |
| 197 |
args = self.flatten_args(args) |
| 198 |
kwargs = self.flatten_kwargs(kwargs) |
| 199 |
if not args: |
| 200 |
return None |
| 201 |
name = args[0] |
| 202 |
assert isinstance(name, (str, UnknownValue)) |
| 203 |
has_fallback = 'fallback' in kwargs |
| 204 |
required = kwargs.get('required', True) |
| 205 |
version = kwargs.get('version', []) |
| 206 |
if not isinstance(version, list): |
| 207 |
version = [version] |
| 208 |
if any(isinstance(el, UnknownValue) for el in version): |
| 209 |
version = UnknownValue() |
| 210 |
else: |
| 211 |
assert all(isinstance(el, str) for el in version) |
| 212 |
version = T.cast(T.List[str], version) |
| 213 |
assert isinstance(required, (bool, UnknownValue)) |
| 214 |
newdep = IntrospectionDependency( |
| 215 |
name=name, |
| 216 |
required=required, |
| 217 |
version=version, |
| 218 |
has_fallback=has_fallback, |
| 219 |
conditional=node.condition_level > 0, |
| 220 |
node=node) |
| 221 |
if not isinstance(name, UnknownValue): |
| 222 |
self.dependencies += [newdep] |
| 223 |
return newdep |
| 224 |
|
| 225 |
def build_target(self, node: BaseNode, args: T.List[TYPE_var], kwargs_raw: T.Dict[str, TYPE_var], targetclass: T.Type[BuildTarget]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 226 |
assert isinstance(node, FunctionNode) |
| 227 |
args = self.flatten_args(args) |
| 228 |
if not args or not isinstance(args[0], str): |
| 229 |
return UnknownValue() |
| 230 |
name = args[0] |
| 231 |
srcqueue: T.List[BaseNode] = [node] |
| 232 |
extra_queue = [] |
| 233 |
|
| 234 |
# Process the sources BEFORE flattening the kwargs, to preserve the original nodes |
| 235 |
if 'sources' in kwargs_raw: |
| 236 |
srcqueue += mesonlib.listify(kwargs_raw['sources']) |
| 237 |
|
| 238 |
if 'extra_files' in kwargs_raw: |
| 239 |
extra_queue += mesonlib.listify(kwargs_raw['extra_files']) |
| 240 |
|
| 241 |
kwargs = self.flatten_kwargs(kwargs_raw, True) |
| 242 |
|
| 243 |
oldlen = len(node.args.arguments) |
| 244 |
source_nodes = node.args.arguments[1:] |
| 245 |
for k, v in node.args.kwargs.items(): |
| 246 |
assert isinstance(k, IdNode) |
| 247 |
if k.value == 'sources': |
| 248 |
source_nodes.append(v) |
| 249 |
assert oldlen == len(node.args.arguments) |
| 250 |
|
| 251 |
extraf_nodes = None |
| 252 |
for k, v in node.args.kwargs.items(): |
| 253 |
assert isinstance(k, IdNode) |
| 254 |
if k.value == 'extra_files': |
| 255 |
assert extraf_nodes is None |
| 256 |
extraf_nodes = v |
| 257 |
|
| 258 |
for_machine = MachineChoice.BUILD if kwargs.get('native', False) else MachineChoice.HOST |
| 259 |
|
| 260 |
# Make sure nothing can crash when creating the build class |
| 261 |
_kwargs_reduced = {k: v for k, v in kwargs.items() if k in _TARGET_KWARGS[targetclass.typename] and k in {'install', 'build_by_default', 'build_always', 'name_prefix'}} |
| 262 |
_kwargs_reduced = {k: v.value if isinstance(v, ElementaryNode) else v for k, v in _kwargs_reduced.items()} |
| 263 |
_kwargs_reduced = {k: v for k, v in _kwargs_reduced.items() if not isinstance(v, (BaseNode, UnknownValue))} |
| 264 |
_kwargs_reduced['native'] = for_machine |
| 265 |
kwargs_reduced = T.cast('BuildTargetKeywordArguments', _kwargs_reduced) |
| 266 |
objects: T.List[T.Any] = [] |
| 267 |
empty_sources: T.List[T.Any] = [] |
| 268 |
# Passing the unresolved sources list causes errors |
| 269 |
kwargs_reduced['_allow_no_sources'] = True |
| 270 |
target = targetclass(name, self.subdir, for_machine, empty_sources, None, objects, |
| 271 |
self.environment, self.coredata.compilers[for_machine], |
| 272 |
self.build_project, kwargs_reduced) |
| 273 |
target.process_compilers_late() |
| 274 |
|
| 275 |
build_by_default: T.Union[UnknownValue, bool] = target.build_by_default |
| 276 |
if 'build_by_default' in kwargs and isinstance(kwargs['build_by_default'], UnknownValue): |
| 277 |
build_by_default = kwargs['build_by_default'] |
| 278 |
|
| 279 |
install: T.Union[UnknownValue, bool] = target.should_install() |
| 280 |
if 'install' in kwargs and isinstance(kwargs['install'], UnknownValue): |
| 281 |
install = kwargs['install'] |
| 282 |
|
| 283 |
new_target = IntrospectionBuildTarget( |
| 284 |
name=target.get_basename(), |
| 285 |
machine=target.for_machine.get_lower_case_name(), |
| 286 |
id=target.get_id(), |
| 287 |
typename=target.get_typename(), |
| 288 |
defined_in=os.path.normpath(os.path.join(self.source_root, self.subdir, environment.build_filename)), |
| 289 |
subdir=self.subdir, |
| 290 |
build_by_default=build_by_default, |
| 291 |
installed=install, |
| 292 |
outputs=target.get_outputs(), |
| 293 |
source_nodes=source_nodes, |
| 294 |
extra_files=extraf_nodes, |
| 295 |
kwargs=kwargs, |
| 296 |
node=node) |
| 297 |
|
| 298 |
self.targets += [new_target] |
| 299 |
return new_target |
| 300 |
|
| 301 |
def build_library(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 302 |
default_library = self.coredata.optstore.get_value_for(OptionKey('default_library', subproject=self.subproject)) |
| 303 |
if default_library == 'shared': |
| 304 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 305 |
elif default_library == 'static': |
| 306 |
return self.build_target(node, args, kwargs, StaticLibrary) |
| 307 |
elif default_library == 'both': |
| 308 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 309 |
return None |
| 310 |
|
| 311 |
def func_executable(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 312 |
return self.build_target(node, args, kwargs, Executable) |
| 313 |
|
| 314 |
def func_static_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 315 |
return self.build_target(node, args, kwargs, StaticLibrary) |
| 316 |
|
| 317 |
def func_shared_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 318 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 319 |
|
| 320 |
def func_both_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 321 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 322 |
|
| 323 |
def func_shared_module(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 324 |
return self.build_target(node, args, kwargs, SharedModule) |
| 325 |
|
| 326 |
def func_library(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 327 |
return self.build_library(node, args, kwargs) |
| 328 |
|
| 329 |
def func_jar(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 330 |
return self.build_target(node, args, kwargs, Jar) |
| 331 |
|
| 332 |
def func_build_target(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]: |
| 333 |
if 'target_type' not in kwargs: |
| 334 |
return None |
| 335 |
target_type = kwargs.pop('target_type') |
| 336 |
if isinstance(target_type, ElementaryNode): |
| 337 |
target_type = target_type.value |
| 338 |
if target_type == 'executable': |
| 339 |
return self.build_target(node, args, kwargs, Executable) |
| 340 |
elif target_type == 'shared_library': |
| 341 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 342 |
elif target_type == 'static_library': |
| 343 |
return self.build_target(node, args, kwargs, StaticLibrary) |
| 344 |
elif target_type == 'both_libraries': |
| 345 |
return self.build_target(node, args, kwargs, SharedLibrary) |
| 346 |
elif target_type == 'library': |
| 347 |
return self.build_library(node, args, kwargs) |
| 348 |
elif target_type == 'jar': |
| 349 |
return self.build_target(node, args, kwargs, Jar) |
| 350 |
return None |
| 351 |
|
| 352 |
def is_subproject(self) -> bool: |
| 353 |
return self.subproject != '' |
| 354 |
|
| 355 |
def analyze(self) -> None: |
| 356 |
self.load_root_meson_file() |
| 357 |
self.sanity_check_ast() |
| 358 |
self.parse_project() |
| 359 |
self.run() |
| 360 |
|
| 361 |
def extract_subproject_dir(self) -> T.Optional[str]: |
| 362 |
'''Fast path to extract subproject_dir kwarg. |
| 363 |
This is faster than self.parse_project() which also initialize options |
| 364 |
and also calls parse_project() on every subproject. |
| 365 |
''' |
| 366 |
if not self.ast.lines: |
| 367 |
return None |
| 368 |
project = self.ast.lines[0] |
| 369 |
# first line is always project() |
| 370 |
if not isinstance(project, FunctionNode): |
| 371 |
return None |
| 372 |
for kw, val in project.args.kwargs.items(): |
| 373 |
assert isinstance(kw, IdNode), 'for mypy' |
| 374 |
if kw.value == 'subproject_dir': |
| 375 |
# mypy does not understand "and isinstance" |
| 376 |
if isinstance(val, StringNode): |
| 377 |
return val.value |
| 378 |
return None |
| 379 |
|
| 380 |
def flatten_kwargs(self, kwargs: T.Dict[str, TYPE_var], include_unknown_args: bool = False) -> T.Dict[str, TYPE_var]: |
| 381 |
flattened_kwargs = {} |
| 382 |
for key, val in kwargs.items(): |
| 383 |
if isinstance(val, BaseNode): |
| 384 |
resolved = self.node_to_runtime_value(val) |
| 385 |
if resolved is not None: |
| 386 |
flattened_kwargs[key] = resolved |
| 387 |
elif isinstance(val, (str, bool, int, float)) or include_unknown_args: |
| 388 |
flattened_kwargs[key] = val |
| 389 |
return flattened_kwargs |