Debian Codegraph @

mesonbuild/interpreter/interpreter.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2021 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import io, sys, traceback
8 import dataclasses
9 import functools
10
11 from .. import mparser
12 from .. import environment
13 from .. import coredata
14 from .. import dependencies
15 from .. import mlog
16 from .. import options
17 from .. import build
18 from .. import compilers
19 from .. import envconfig
20 from ..wrap import wrap, WrapMode
21 from .. import mesonlib
22 from ..mesonlib import (EnvironmentVariables, ExecutableSerialisation, MesonBugException, MesonException, HoldableObject,
23 FileMode, InstallScriptFailure, MachineChoice, PerMachine, PerMachineDefaultable, is_parent_path,
24 listify, has_path_sep, path_has_root, path_is_in_root)
25 from ..options import OptionKey
26 from ..programs import ExternalProgram, NonExistingExternalProgram, Program
27 from ..dependencies import Dependency
28 from ..depfile import DepFile
29 from ..interpreterbase import ContainerTypeInfo, InterpreterBase, KwargInfo, typed_kwargs, typed_pos_args
30 from ..interpreterbase import noPosargs, noKwargs, noArgsFlattening, noSecondLevelHolderResolving, unholder_return
31 from .decorators import apply_machine_map
32 from ..interpreterbase import InterpreterException, InvalidArguments, InvalidCode, SubdirDoneRequest
33 from ..interpreterbase import Disabler, disablerIfNotFound
34 from ..interpreterbase import FeatureNew, FeatureDeprecated, FeatureBroken, FeatureNewKwargs
35 from ..interpreterbase import ObjectHolder, ContextManagerObject, DefaultObject
36 from ..interpreterbase import stringifyUserArguments, Feature, FeatureValue
37 from ..modules import ExtensionModule, ModuleObject, MutableModuleObject, NewExtensionModule, NotFoundExtensionModule, __path__ as modules_path
38 from ..optinterpreter import optname_regex
39
40 from . import interpreterobjects as OBJ
41 from . import compiler as compilerOBJ
42 from .mesonmain import MesonMain
43 from .dependencyfallbacks import DependencyFallbacksHolder
44 from .interpreterobjects import (
45 SubprojectHolder,
46 Test,
47 RunProcess,
48 extract_required_kwarg,
49 extract_search_dirs,
50 NullSubprojectInterpreter,
51 )
52 from .type_checking import (
53 BUILD_TARGET_KWS,
54 COMMAND_KW,
55 CT_BUILD_ALWAYS,
56 CT_BUILD_ALWAYS_STALE,
57 CT_BUILD_BY_DEFAULT,
58 CT_INPUT_KW,
59 CT_INSTALL_DIR_KW,
60 EXCLUSIVE_EXECUTABLE_KWS,
61 EXECUTABLE_KWS,
62 JAR_KWS,
63 LIBRARY_KWS,
64 MULTI_OUTPUT_KW,
65 OUTPUT_KW,
66 DEFAULT_OPTIONS,
67 DEPENDENCIES_KW,
68 DEPENDENCY_KWS,
69 DEPENDS_KW,
70 DEPEND_FILES_KW,
71 DEPFILE_KW,
72 DISABLER_KW,
73 D_MODULE_VERSIONS_KW,
74 ENV_KW,
75 ENV_METHOD_KW,
76 ENV_SEPARATOR_KW,
77 INCLUDE_DIRECTORIES,
78 INSTALL_KW,
79 INSTALL_DIR_KW,
80 INSTALL_MODE_KW,
81 INSTALL_FOLLOW_SYMLINKS,
82 LINK_ARGS_KW,
83 LINK_WITH_KW,
84 LINK_WHOLE_KW,
85 CT_INSTALL_TAG_KW,
86 INSTALL_TAG_KW,
87 LANGUAGE_KW,
88 NATIVE_KW,
89 PRESERVE_PATH_KW,
90 REQUIRED_KW,
91 SHARED_LIB_KWS,
92 SHARED_MOD_KWS,
93 DEPENDENCY_SOURCES_KW,
94 SOURCES_VARARGS,
95 STATIC_LIB_KWS,
96 VARIABLES_KW,
97 TEST_KWS,
98 NoneType,
99 in_set_validator,
100 env_convertor_with_method
101 )
102 from . import primitives as P_OBJ
103
104 from pathlib import Path
105 from enum import Enum
106 import os
107 import shutil
108 import uuid
109 import re
110 import stat
111 import collections
112 import typing as T
113 import textwrap
114 import importlib
115 import itertools
116
117 if T.TYPE_CHECKING:
118 from typing_extensions import Literal
119 import types
120
121 from .. import cargo
122 from . import kwargs as kwtypes
123 from ..backend.backends import Backend
124 from ..compilers.compilers import CompilerDict, Language
125 from ..interpreterbase.baseobjects import InterpreterObject, TYPE_var, TYPE_kwargs
126 from ..options import OptionDict
127 from ..mesonlib import InstallScript, SubProject
128 from ..cmdline import SharedCMDOptions
129 from .type_checking import SourcesVarargsType, FullEnvInitValueType
130
131 # Input source types passed to Targets
132 SourceInputs = T.Union[str, build.TargetSources, build.BuildTarget,
133 build.BothLibraries, build.ExtractedObjects]
134 # Input source types passed to the build.Target classes
135 SourceOutputs = T.Union[build.TargetSources, build.BuildTarget,
136 build.ExtractedObjects, build.StructuredSources]
137 # Sources for custom targets, which can also include ExternalProgram
138 CustomTargetSources = T.Union[build.TargetSources, build.BuildTarget,
139 build.ExtractedObjects, Program]
140
141 BuildTargetSource = T.Union[str, build.TargetSources, build.StructuredSources]
142
143 ProgramVersionFunc = T.Callable[[Program], str]
144
145 TestClass = T.TypeVar('TestClass', bound=Test)
146
147 def _project_version_validator(value: T.Union[T.List, str, mesonlib.File, None]) -> T.Optional[str]:
148 if isinstance(value, list):
149 if len(value) != 1:
150 return 'when passed as array must have a length of 1'
151 elif not isinstance(value[0], mesonlib.File):
152 return 'when passed as array must contain a File'
153 return None
154
155
156 @dataclasses.dataclass
157 class SandboxViolationError(InterpreterException):
158
159 """Exception raised when trying to use files outside of this project
160
161 :param inputtype: The kind of thing, usually "directory" or "file"
162 :param name: The name of the thing being used
163 :param subproject: Is this an attempt to use a file from inside a subproject?
164 """
165
166 inputtype: str
167 name: str
168 subproject: bool = dataclasses.field(default=True, kw_only=True)
169
170 def __str__(self) -> str:
171 if self.subproject:
172 msg = 'a nested subproject'
173 else:
174 msg = 'outside current (sub)project'
175 return f'Sandbox violation: Tried to grab {self.inputtype} {self.name} from {msg}.'
176
177
178 @dataclasses.dataclass
179 class BuiltFileByNameError(InterpreterException):
180
181 name: str
182
183 def __str__(self) -> str:
184 return (f'{self.name!r} is a generated file, and should be passed by reference instead of string name. '
185 'This will become a hard error in Meson 2.0')
186
187
188 class Summary:
189 def __init__(self, project_name: str, project_version: str):
190 self.project_name = project_name
191 self.project_version = project_version
192 self.sections: collections.defaultdict[str, dict[str, tuple[mlog.TV_LoggableList, str | None]]] = collections.defaultdict(dict)
193 self.max_key_len = 0
194
195 def add_section(self, section: str, values: T.Dict[str, mlog.TV_Loggable | mlog.TV_LoggableList], bool_yn: bool,
196 list_sep: T.Optional[str], subproject: SubProject) -> None:
197 for k, v in values.items():
198 if k in self.sections[section]:
199 raise InterpreterException(f'Summary section {section!r} already have key {k!r}')
200 formatted_values: mlog.TV_LoggableList = []
201 for i in listify(v):
202 if isinstance(i, bool):
203 if bool_yn:
204 formatted_values.append(mlog.green('YES') if i else mlog.red('NO'))
205 else:
206 formatted_values.append('true' if i else 'false')
207 elif isinstance(i, (str, int)):
208 formatted_values.append(str(i))
209 elif isinstance(i, (ExternalProgram, Dependency)):
210 FeatureNew.single_use('dependency or external program in summary', '0.57.0', subproject)
211 formatted_values.append(i.summary_value())
212 elif isinstance(i, Disabler):
213 FeatureNew.single_use('disabler in summary', '0.64.0', subproject)
214 formatted_values.append(mlog.red('NO'))
215 elif isinstance(i, Feature):
216 FeatureNew.single_use('feature option in summary', '0.58.0', subproject)
217 formatted_values.append(str(i))
218 else:
219 m = 'Summary value in section {!r}, key {!r}, must be string, integer, boolean, dependency, disabler, or external program'
220 raise InterpreterException(m.format(section, k))
221 self.sections[section][k] = (formatted_values, list_sep)
222 self.max_key_len = max(self.max_key_len, len(k))
223
224 def dump(self) -> None:
225 mlog.log(self.project_name, mlog.normal_cyan(self.project_version))
226 for section, values in self.sections.items():
227 mlog.log('') # newline
228 if section:
229 mlog.log(' ', mlog.bold(section))
230 for k, v in values.items():
231 v, list_sep = v
232 padding = self.max_key_len - len(k)
233 end = ' ' if v else ''
234 mlog.log(' ' * 3, k + ' ' * padding + ':', end=end)
235 indent = self.max_key_len + 6
236 self.dump_value(v, list_sep, indent)
237 mlog.log('') # newline
238
239 def dump_value(self, arr: mlog.TV_LoggableList, list_sep: str | None, indent: int) -> None:
240 lines_sep = '\n' + ' ' * indent
241 if list_sep is None:
242 mlog.log(*arr, sep=lines_sep, display_timestamp=False)
243 return
244 max_len = shutil.get_terminal_size().columns
245 line: mlog.TV_LoggableList = []
246 line_len = indent
247 lines_sep = list_sep.rstrip() + lines_sep
248 for v in arr:
249 v_len = len(str(v)) + len(list_sep)
250 if line and line_len + v_len > max_len:
251 mlog.log(*line, sep=list_sep, end=lines_sep)
252 line_len = indent
253 line = []
254 line.append(v)
255 line_len += v_len
256 mlog.log(*line, sep=list_sep, display_timestamp=False)
257
258
259 class InterpreterRuleRelaxation(Enum):
260 ''' Defines specific relaxations of the Meson rules.
261
262 This is intended to be used for automatically converted
263 projects (CMake subprojects, build system mixing) that
264 generate a Meson AST via introspection, etc.
265 '''
266
267 ALLOW_BUILD_DIR_FILE_REFERENCES = 1
268 CARGO_SUBDIR = 2
269
270 implicit_check_false_warning = """You should add the boolean check kwarg to the run_command call.
271 It currently defaults to false,
272 but it will default to true in meson 2.0.
273 See also: https://github.com/mesonbuild/meson/issues/9300"""
274 class Interpreter(InterpreterBase, HoldableObject):
275
276 backend: mesonlib.late_property[Backend] = mesonlib.late_property()
277
278 def __init__(
279 self,
280 _build: build.Build,
281 backend: T.Optional[Backend] = None,
282 subproject: SubProject = mesonlib.ROOT_SUBPROJECT,
283 subdir: str = '',
284 subproject_dir: str = 'subprojects',
285 invoker_method_default_options: T.Optional[OptionDict] = None,
286 ast: T.Optional[mparser.CodeBlockNode] = None,
287 relaxations: T.Optional[T.Set[InterpreterRuleRelaxation]] = None,
288 user_defined_options: T.Optional[SharedCMDOptions] = None,
289 cargo: T.Optional[cargo.Interpreter] = None,
290 ) -> None:
291 super().__init__(_build.environment.get_source_dir(), subdir, subproject, subproject_dir, _build.environment)
292 self.active_projectname = ''
293 self.build = _build
294 if backend is not None:
295 self.backend = backend
296 self.cargo = cargo
297 self.summary: T.Dict[str, 'Summary'] = {}
298 self.modules: T.Dict[str, NewExtensionModule] = {}
299 self.relaxations = relaxations or set()
300 if ast is None:
301 self.load_root_meson_file()
302 else:
303 self.ast = ast
304 self.sanity_check_ast()
305 self.builtin.update({'meson': MesonMain(self.build, self)})
306 self.validated_cache: T.Set[str] = set()
307 self.project_args_frozen = False
308 self.global_args_frozen = False # implies self.project_args_frozen
309 self.subprojects: PerMachine[T.Dict[str, SubprojectHolder]] = PerMachineDefaultable.default(
310 self.environment.is_cross_build(), {}, {})
311 self.subproject_stack: T.List[T.Tuple[str, MachineChoice]] = []
312 self.configure_file_outputs: T.Dict[str, int] = {}
313 # Passed from the outside, only used in subprojects.
314 if invoker_method_default_options:
315 assert isinstance(invoker_method_default_options, dict)
316 self.invoker_method_default_options = invoker_method_default_options
317 else:
318 self.invoker_method_default_options = {}
319 self.project_default_options: OptionDict = {}
320 self.build_func_dict()
321 self.build_holder_map()
322 self.user_defined_options = user_defined_options
323 # Languages added in the current subproject
324 self.compilers: PerMachine[CompilerDict] = PerMachine({}, {})
325 self.parse_project()
326 self._redetect_machines()
327
328 def __getnewargs_ex__(self) -> T.Tuple[T.Tuple[object], T.Dict[str, object]]:
329 raise MesonBugException('This class is unpicklable')
330
331 def load_root_cargo_lock_file(self) -> None:
332 cargo_lock = os.path.join(self.source_root, self.subdir, 'Cargo.lock')
333 if not os.path.isfile(cargo_lock):
334 return
335 from .. import cargo
336 try:
337 self.cargo = cargo.Interpreter(self.environment, self.subdir, self.subproject_dir)
338 except cargo.TomlImplementationMissing as e:
339 # error delayed to actual usage of a Cargo subproject
340 mlog.warning(f'cannot load Cargo.lock: {e}', fatal=False)
341
342 def _redetect_machines(self) -> None:
343 # Re-initialize machine descriptions. We can do a better job now because we
344 # have the compilers needed to gain more knowledge, so wipe out old
345 # inference and start over.
346 self.build.environment.update_build_machine()
347
348 self.builtin['build_machine'] = \
349 OBJ.MachineHolder(self.build.environment.machines[self.build.machine_map.build], self)
350 self.builtin['host_machine'] = \
351 OBJ.MachineHolder(self.build.environment.machines[self.build.machine_map.host], self)
352 self.builtin['target_machine'] = \
353 OBJ.MachineHolder(self.build.environment.machines[self.build.machine_map.target], self)
354
355 def is_internal_machine(self, for_machine: MachineChoice) -> bool:
356 # Return whether applying the caller's effect to the build and
357 # host machine would duplicate the effect
358 return self.build.machine_map[for_machine] is MachineChoice.BUILD
359
360 def apply_machine_map_to_kwargs(self, kwargs: kwtypes.BaseBuildTarget | kwtypes.MachineMapArgs) -> None:
361 orig_for_machine: MachineChoice | None = kwargs.get('native', None)
362 if orig_for_machine is None:
363 return
364
365 for_machine = self.build.machine_map[orig_for_machine]
366 if for_machine is orig_for_machine:
367 return
368
369 if 'install' in kwargs and for_machine is MachineChoice.BUILD:
370 kwargs['install'] = False
371 kwargs['native'] = for_machine
372
373 def build_func_dict(self) -> None:
374 self.funcs.update({'add_global_arguments': self.func_add_global_arguments,
375 'add_global_link_arguments': self.func_add_global_link_arguments,
376 'add_languages': self.func_add_languages,
377 'add_project_arguments': self.func_add_project_arguments,
378 'add_project_dependencies': self.func_add_project_dependencies,
379 'add_project_link_arguments': self.func_add_project_link_arguments,
380 'add_test_setup': self.func_add_test_setup,
381 'alias_target': self.func_alias_target,
382 'assert': self.func_assert,
383 'benchmark': self.func_benchmark,
384 'both_libraries': self.func_both_lib,
385 'build_target': self.func_build_target,
386 'configuration_data': self.func_configuration_data,
387 'configure_file': self.func_configure_file,
388 'custom_target': self.func_custom_target,
389 'debug': self.func_debug,
390 'declare_dependency': self.func_declare_dependency,
391 'dependency': self.func_dependency,
392 'disabler': self.func_disabler,
393 'default': self.func_default,
394 'environment': self.func_environment,
395 'error': self.func_error,
396 'executable': self.func_executable,
397 'files': self.func_files,
398 'find_program': self.func_find_program,
399 'generator': self.func_generator,
400 'get_option': self.func_get_option,
401 'get_variable': self.func_get_variable,
402 'import': self.func_import,
403 'include_directories': self.func_include_directories,
404 'install_data': self.func_install_data,
405 'install_emptydir': self.func_install_emptydir,
406 'install_headers': self.func_install_headers,
407 'install_man': self.func_install_man,
408 'install_subdir': self.func_install_subdir,
409 'install_symlink': self.func_install_symlink,
410 'is_disabler': self.func_is_disabler,
411 'is_variable': self.func_is_variable,
412 'jar': self.func_jar,
413 'join_paths': self.func_join_paths,
414 'library': self.func_library,
415 'message': self.func_message,
416 'option': self.func_option,
417 'project': self.func_project,
418 'range': self.func_range,
419 'run_command': self.func_run_command,
420 'run_target': self.func_run_target,
421 'set_variable': self.func_set_variable,
422 'structured_sources': self.func_structured_sources,
423 'subdir': self.func_subdir,
424 'shared_library': self.func_shared_lib,
425 'shared_module': self.func_shared_module,
426 'static_library': self.func_static_lib,
427 'subdir_done': self.func_subdir_done,
428 'subproject': self.func_subproject,
429 'summary': self.func_summary,
430 'test': self.func_test,
431 'unset_variable': self.func_unset_variable,
432 'vcs_tag': self.func_vcs_tag,
433 'warning': self.func_warning,
434 })
435 if 'MESON_UNIT_TEST' in os.environ:
436 self.funcs.update({'exception': self.func_exception})
437 if 'MESON_RUNNING_IN_PROJECT_TESTS' in os.environ:
438 self.funcs.update({'expect_error': self.func_expect_error})
439
440 def build_holder_map(self) -> None:
441 '''
442 Build a mapping of `HoldableObject` types to their corresponding
443 `ObjectHolder`s. This mapping is used in `InterpreterBase` to automatically
444 holderify all returned values from methods and functions.
445 '''
446 self.holder_map.update({
447 # Primitives
448 list: P_OBJ.ArrayHolder,
449 dict: P_OBJ.DictHolder,
450 int: P_OBJ.IntegerHolder,
451 bool: P_OBJ.BooleanHolder,
452 str: P_OBJ.StringHolder,
453 P_OBJ.MesonVersionString: P_OBJ.MesonVersionStringHolder,
454 P_OBJ.DependencyVariableString: P_OBJ.DependencyVariableStringHolder,
455 P_OBJ.OptionString: P_OBJ.OptionStringHolder,
456
457 # Meson types
458 mesonlib.File: OBJ.FileHolder,
459 build.SharedLibrary: OBJ.SharedLibraryHolder,
460 build.StaticLibrary: OBJ.StaticLibraryHolder,
461 build.BothLibraries: OBJ.BothLibrariesHolder,
462 build.SharedModule: OBJ.SharedModuleHolder,
463 build.Executable: OBJ.ExecutableHolder,
464 build.Jar: OBJ.JarHolder,
465 build.CustomTarget: OBJ.CustomTargetHolder,
466 build.CustomTargetIndex: OBJ.CustomTargetIndexHolder,
467 build.Generator: OBJ.GeneratorHolder,
468 build.GeneratedList: OBJ.GeneratedListHolder,
469 build.ExtractedObjects: OBJ.GeneratedObjectsHolder,
470 build.RunTarget: OBJ.RunTargetHolder,
471 build.AliasTarget: OBJ.AliasTargetHolder,
472 build.Headers: OBJ.HeadersHolder,
473 build.Man: OBJ.ManHolder,
474 build.EmptyDir: OBJ.EmptyDirHolder,
475 build.Data: OBJ.DataHolder,
476 build.SymlinkData: OBJ.SymlinkDataHolder,
477 build.InstallDir: OBJ.InstallDirHolder,
478 build.IncludeDirs: OBJ.IncludeDirsHolder,
479 mesonlib.EnvironmentVariables: OBJ.EnvironmentVariablesHolder,
480 build.StructuredSources: OBJ.StructuredSourcesHolder,
481 compilers.RunResult: compilerOBJ.TryRunResultHolder,
482 dependencies.ExternalLibrary: OBJ.ExternalLibraryHolder,
483 Feature: OBJ.FeatureOptionHolder,
484 envconfig.MachineInfo: OBJ.MachineHolder,
485 build.ConfigurationData: OBJ.ConfigurationDataHolder,
486 })
487
488 '''
489 Build a mapping of `HoldableObject` base classes to their
490 corresponding `ObjectHolder`s. The difference to `self.holder_map`
491 is that the keys here define an upper bound instead of requiring an
492 exact match.
493
494 The mappings defined here are only used when there was no direct hit
495 found in `self.holder_map`.
496 '''
497 self.bound_holder_map.update({
498 dependencies.Dependency: OBJ.DependencyHolder,
499 Program: OBJ.ProgramHolder,
500 compilers.Compiler: compilerOBJ.CompilerHolder,
501 ModuleObject: OBJ.ModuleObjectHolder,
502 MutableModuleObject: OBJ.MutableModuleObjectHolder,
503 })
504
505 def append_holder_map(self, held_type: T.Type[mesonlib.HoldableObject], holder_type: T.Type[ObjectHolder]) -> None:
506 '''
507 Adds one additional mapping to the `holder_map`.
508
509 The intended use for this function is in the `initialize` method of
510 modules to register custom object holders.
511 '''
512 self.holder_map.update({
513 held_type: holder_type
514 })
515
516 def process_new_values(self, invalues: list[TYPE_var | InstallScript] | list[build.GeneratedTypes | mesonlib.File]) -> None:
517 for v in invalues:
518 if isinstance(v, ObjectHolder):
519 raise InterpreterException('Modules must not return ObjectHolders')
520 if isinstance(v, build.Target):
521 self.add_target(v.name, v)
522 elif isinstance(v, list):
523 self.process_new_values(v)
524 elif isinstance(v, (ExecutableSerialisation, InstallScriptFailure)):
525 v.subproject = self.subproject
526 self.build.install_scripts.append(v)
527 elif isinstance(v, build.Data):
528 self.build.data.append(v)
529 elif isinstance(v, build.SymlinkData):
530 self.build.symlinks.append(v)
531 elif isinstance(v, dependencies.InternalDependency):
532 # FIXME: This is special cased and not ideal:
533 # The first source is our new VapiTarget, the rest are deps
534 self.process_new_values([v.sources[0]])
535 elif isinstance(v, build.InstallDir):
536 self.build.install_dirs.append(v)
537 elif isinstance(v, Test):
538 self.build.tests.append(v)
539 elif isinstance(v, (int, str, bool, Disabler, ObjectHolder, build.GeneratedList,
540 ExternalProgram, build.ConfigurationData)):
541 pass
542 else:
543 raise InterpreterException(f'Module returned a value of unknown type {v!r}.')
544
545 def handle_meson_version(self, pv: str, location: mparser.BaseNode) -> None:
546 if not mesonlib.version_compare(coredata.stable_version, pv):
547 raise InterpreterException.from_node(f'Meson version is {coredata.version} but project requires {pv}', node=location)
548 mesonlib.project_meson_versions[self.subproject] = mesonlib.version_check_to_range([pv])
549
550 def handle_meson_version_from_ast(self) -> None:
551 if not self.ast.lines:
552 return
553 project = self.ast.lines[0]
554 # first line is always project()
555 if not isinstance(project, mparser.FunctionNode):
556 return
557 for kw, val in project.args.kwargs.items():
558 assert isinstance(kw, mparser.IdNode), 'for mypy'
559 if kw.value == 'meson_version':
560 # mypy does not understand "and isinstance"
561 if isinstance(val, mparser.StringNode):
562 self.handle_meson_version(val.value, val)
563
564 def get_build_def_files(self) -> T.List[str]:
565 if self.cargo:
566 self.build_def_files.update(self.cargo.get_build_def_files())
567 return list(self.build_def_files)
568
569 def add_build_def_file(self, f: mesonlib.FileOrString) -> None:
570 # Use relative path for files within source directory, and absolute path
571 # for system files. Skip files within build directory. Also skip not regular
572 # files (e.g. /dev/stdout) Normalize the path to avoid duplicates, this
573 # is especially important to convert '/' to '\' on Windows.
574 if isinstance(f, mesonlib.File):
575 if f.is_built:
576 return
577 f = os.path.normpath(f.relative_name())
578 elif os.path.isfile(f) and not f.startswith('/dev/'):
579 srcdir = Path(self.environment.get_source_dir())
580 builddir = Path(self.environment.get_build_dir())
581 try:
582 f_ = Path(f).resolve()
583 except OSError:
584 f_ = Path(f)
585 s = f_.stat()
586 # Mypy needs the `sys.platform` check to understand that this is
587 # a Windows only path
588 if (sys.platform == 'win32' and
589 s.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT != 0 and
590 s.st_reparse_tag == stat.IO_REPARSE_TAG_APPEXECLINK):
591 # This is a Windows Store link which we can't
592 # resolve, so just do our best otherwise.
593 f_ = f_.parent.resolve() / f_.name
594 else:
595 raise
596 if builddir in f_.parents:
597 return
598 if srcdir in f_.parents:
599 f_ = f_.relative_to(srcdir)
600 f = str(f_)
601 else:
602 return
603 if f not in self.build_def_files:
604 self.build_def_files.add(f)
605
606 def get_variables(self) -> T.Dict[str, InterpreterObject]:
607 return self.variables
608
609 def check_stdlibs(self) -> None:
610 machine_choices = [MachineChoice.HOST]
611 if self.coredata.is_cross_build():
612 machine_choices.append(MachineChoice.BUILD)
613 for for_machine in machine_choices:
614 props = self.build.environment.properties[for_machine]
615 for l in self.coredata.compilers[for_machine].keys():
616 try:
617 di = mesonlib.stringlistify(props.get_stdlib(l))
618 except KeyError:
619 continue
620 if len(di) == 1:
621 FeatureNew.single_use('stdlib without variable name', '0.56.0', self.subproject, location=self.current_node)
622 kwargs: dependencies.base.DependencyObjectKWs = {'native': for_machine}
623 name = l + '_stdlib'
624 df = DependencyFallbacksHolder(self, [name], for_machine)
625 df.set_fallback(di)
626 dep = df.lookup(kwargs, force_fallback=True)
627 self.build.stdlibs[for_machine][l] = dep
628
629 @typed_pos_args('import', str)
630 @typed_kwargs(
631 'import',
632 REQUIRED_KW.evolve(since='0.59.0'),
633 DISABLER_KW.evolve(since='0.59.0'),
634 )
635 @disablerIfNotFound
636 def func_import(self, node: mparser.BaseNode, args: T.Tuple[str],
637 kwargs: 'kwtypes.FuncImportModule') -> T.Union[ExtensionModule, NewExtensionModule, NotFoundExtensionModule]:
638 modname = args[0]
639 disabled, required, _ = extract_required_kwarg(kwargs, self.subproject)
640 if disabled:
641 return NotFoundExtensionModule(modname)
642
643 # Always report implementation detail modules don't exist
644 if modname.startswith('_'):
645 raise InvalidArguments(f'Module "{modname}" does not exist')
646
647 expect_unstable = False
648 # Some tests use "unstable_" instead of "unstable-", and that happens to work because
649 # of implementation details
650 if modname.startswith(('unstable-', 'unstable_')):
651 if modname.startswith('unstable_'):
652 mlog.deprecation(f'Importing unstable modules as "{modname}" instead of "{modname.replace("_", "-", 1)}"',
653 location=node)
654 real_modname = modname[len('unstable') + 1:] # + 1 to handle the - or _
655 expect_unstable = True
656 else:
657 real_modname = modname
658
659 if real_modname in self.modules:
660 return self.modules[real_modname]
661 try:
662 full_module_path = f'mesonbuild.modules.{real_modname}'
663 module = importlib.import_module(full_module_path)
664 except ImportError as e:
665 if e.name != full_module_path:
666 if required:
667 raise e
668
669 mlog.warning(f'Module "{modname}" exists but failed to import.')
670
671 for line in traceback.format_exception(e):
672 mlog.debug(line)
673
674 if required:
675 ustr = f'Module "{modname}" does not exist.'
676 from difflib import get_close_matches
677 from pkgutil import iter_modules
678 modnames = [mod.name for mod in iter_modules(modules_path) if not mod.name.startswith('_')]
679 close_matches = get_close_matches(modname, modnames)
680 if close_matches:
681 ustr += f' Did you mean "{close_matches[0]}"?'
682 raise InvalidArguments(ustr)
683 ext_module = NotFoundExtensionModule(real_modname)
684 else:
685 ext_module = module.initialize(self)
686 assert isinstance(ext_module, (ExtensionModule, NewExtensionModule)), 'for mypy'
687 self.build.modules.add(real_modname)
688 if ext_module.INFO.added:
689 FeatureNew.single_use(f'module {ext_module.INFO.name}', ext_module.INFO.added, self.subproject, location=node)
690 if ext_module.INFO.deprecated:
691 FeatureDeprecated.single_use(f'module {ext_module.INFO.name}', ext_module.INFO.deprecated, self.subproject, location=node)
692 if expect_unstable and not ext_module.INFO.unstable and ext_module.INFO.stabilized is None:
693 raise InvalidArguments(f'Module {ext_module.INFO.name} has never been unstable, remove "unstable-" prefix.')
694 if ext_module.INFO.stabilized is not None:
695 if expect_unstable:
696 FeatureDeprecated.single_use(
697 f'module {ext_module.INFO.name} has been stabilized',
698 ext_module.INFO.stabilized, self.subproject,
699 'drop "unstable-" prefix from the module name',
700 location=node)
701 else:
702 FeatureNew.single_use(
703 f'module {ext_module.INFO.name} as stable module',
704 ext_module.INFO.stabilized, self.subproject,
705 f'Consider either adding "unstable-" to the module name, or updating the meson required version to ">= {ext_module.INFO.stabilized}"',
706 location=node)
707 elif ext_module.INFO.unstable:
708 if not expect_unstable:
709 if required:
710 raise InvalidArguments(f'Module "{ext_module.INFO.name}" has not been stabilized, and must be imported as unstable-{ext_module.INFO.name}')
711 ext_module = NotFoundExtensionModule(real_modname)
712 else:
713 mlog.warning(f'Module {ext_module.INFO.name} has no backwards or forwards compatibility and might not exist in future releases.', location=node, fatal=False)
714
715 self.modules[real_modname] = ext_module
716 return ext_module
717
718 @typed_pos_args('files', varargs=str)
719 @noKwargs
720 def func_files(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'TYPE_kwargs') -> T.List[mesonlib.File]:
721 return self.source_strings_to_files(args[0])
722
723 @noPosargs
724 @typed_kwargs(
725 'declare_dependency',
726 KwargInfo('compile_args', ContainerTypeInfo(list, str), listify=True, default=[]),
727 INCLUDE_DIRECTORIES.evolve(name='d_import_dirs', since='0.62.0'),
728 D_MODULE_VERSIONS_KW.evolve(since='0.62.0'),
729 LINK_ARGS_KW,
730 DEPENDENCIES_KW,
731 INCLUDE_DIRECTORIES.evolve(since_values={ContainerTypeInfo(list, str): '0.50.0'}),
732 LINK_WITH_KW,
733 LINK_WHOLE_KW.evolve(since='0.46.0'),
734 DEPENDENCY_SOURCES_KW,
735 KwargInfo('extra_files', ContainerTypeInfo(list, (mesonlib.File, str)), listify=True, default=[], since='1.2.0'),
736 VARIABLES_KW.evolve(since='0.54.0', since_values={list: '0.56.0'}),
737 KwargInfo('version', (str, NoneType)),
738 KwargInfo('objects', ContainerTypeInfo(list, build.ExtractedObjects), listify=True, default=[], since='1.1.0'),
739 )
740 def func_declare_dependency(self, node: mparser.BaseNode, args: T.List[TYPE_var],
741 kwargs: kwtypes.FuncDeclareDependency) -> dependencies.Dependency:
742 deps = kwargs['dependencies']
743 incs = self.extract_incdirs(kwargs['include_directories'])
744 libs = kwargs['link_with']
745 libs_whole = kwargs['link_whole']
746 objects = kwargs['objects']
747 sources = self.source_strings_to_files(kwargs['sources'])
748 extra_files = self.source_strings_to_files(kwargs['extra_files'])
749 compile_args = kwargs['compile_args']
750 link_args = kwargs['link_args']
751 variables = kwargs['variables']
752 version = kwargs['version']
753 if version is None:
754 version = self.project_version
755 d_module_versions = kwargs['d_module_versions']
756 d_import_dirs = self.extract_incdirs(kwargs['d_import_dirs'], True)
757 srcdir = self.environment.source_dir
758 subproject_dir = os.path.abspath(os.path.join(srcdir, self.subproject_dir))
759 project_root = os.path.abspath(os.path.join(srcdir, self.root_subdir))
760 # convert variables which refer to an -uninstalled.pc style datadir
761 for k, v in variables.items():
762 if not v:
763 FeatureNew.single_use('empty variable value in declare_dependency', '1.4.0', self.subproject, location=node)
764 if path_has_root(v) \
765 and (self.is_subproject() or not is_parent_path(subproject_dir, v)) \
766 and is_parent_path(project_root, v) \
767 and os.path.isdir(v):
768 variables[k] = P_OBJ.DependencyVariableString(v)
769
770 dep = dependencies.InternalDependency(version, incs, compile_args,
771 link_args, libs, libs_whole, sources, extra_files,
772 deps, variables, d_module_versions, d_import_dirs,
773 objects)
774 return dep
775
776 @typed_pos_args('assert', bool, optargs=[str])
777 @noKwargs
778 def func_assert(self, node: mparser.FunctionNode, args: T.Tuple[bool, T.Optional[str]],
779 kwargs: 'TYPE_kwargs') -> None:
780 value, message = args
781 if message is None:
782 FeatureNew.single_use('assert function without message argument', '0.53.0', self.subproject, location=node)
783
784 if not value:
785 if message is None:
786 from ..ast import AstPrinter
787 printer = AstPrinter()
788 node.args.arguments[0].accept(printer)
789 message = printer.result
790 raise InterpreterException('Assert failed: ' + message)
791
792 # Executables aren't actually accepted, but we allow them here to allow for
793 # better error messages when overridden
794 @typed_pos_args(
795 'run_command',
796 (build.Executable, Program, compilers.Compiler, mesonlib.File, str),
797 varargs=(build.Executable, Program, compilers.Compiler, mesonlib.File, str))
798 @typed_kwargs(
799 'run_command',
800 KwargInfo('check', (bool, NoneType), since='0.47.0'),
801 KwargInfo('capture', bool, default=True, since='0.47.0'),
802 KwargInfo('console', bool, default=False, since='1.11.0'),
803 ENV_KW.evolve(since='0.50.0'),
804 )
805 def func_run_command(self, node: mparser.BaseNode,
806 args: T.Tuple[T.Union[build.Executable, Program, compilers.Compiler, mesonlib.File, str],
807 T.List[T.Union[build.Executable, Program, compilers.Compiler, mesonlib.File, str]]],
808 kwargs: 'kwtypes.RunCommand') -> RunProcess:
809 return self.run_command_impl(args, kwargs)
810
811 def _compiled_exe_error(self, cmd: T.Union[Program, build.Executable]) -> T.NoReturn:
812 descr = cmd.name if isinstance(cmd, build.Executable) else cmd.description()
813 for for_machine in MachineChoice:
814 for name, exe in self.build.find_overrides[for_machine].items():
815 if cmd == exe:
816 raise InterpreterException(f'Program {name!r} was overridden with the compiled executable {descr!r} and therefore cannot be used during configuration')
817 raise InterpreterException(f'Program {descr!r} is a compiled executable and therefore cannot be used during configuration')
818
819 def run_command_impl(self,
820 args: T.Tuple[T.Union[build.Executable, Program, compilers.Compiler, mesonlib.File, str],
821 T.List[T.Union[build.Executable, Program, compilers.Compiler, mesonlib.File, str]]],
822 kwargs: 'kwtypes.RunCommand',
823 in_builddir: bool = False) -> RunProcess:
824 cmd, cargs = args
825 env = kwargs['env']
826 srcdir = self.environment.get_source_dir()
827 builddir = self.environment.get_build_dir()
828
829 check = kwargs['check']
830 if check is None:
831 mlog.warning(implicit_check_false_warning, once=True)
832 check = False
833
834 expanded_args: T.List[str] = []
835 if isinstance(cmd, build.Executable):
836 self._compiled_exe_error(cmd)
837 elif isinstance(cmd, Program):
838 if not cmd.found():
839 raise InterpreterException(f'command {cmd.get_name()!r} not found or not executable')
840 if not cmd.runnable():
841 self._compiled_exe_error(cmd)
842 elif isinstance(cmd, compilers.Compiler):
843 expanded_args = cmd.get_exe_args()
844 cmd = cmd.get_exe()
845 prog = ExternalProgram(cmd, silent=True)
846 if not prog.found():
847 raise InterpreterException(f'Program {cmd!r} not found or not executable')
848 cmd = prog
849 else:
850 if isinstance(cmd, mesonlib.File):
851 cmd = cmd.absolute_path(srcdir, builddir)
852 # Prefer scripts in the current source directory
853 search_dir = os.path.join(srcdir, self.subdir)
854 prog = ExternalProgram(cmd, silent=True, search_dirs=[search_dir])
855 if not prog.found():
856 raise InterpreterException(f'Program or command {cmd!r} not found or not executable')
857 cmd = prog
858 for a in cargs:
859 if isinstance(a, str):
860 expanded_args.append(a)
861 elif isinstance(a, mesonlib.File):
862 expanded_args.append(a.absolute_path(srcdir, builddir))
863 elif isinstance(a, Program):
864 if not a.found():
865 raise InterpreterException(f'command {cmd.get_name()!r} not found or not executable')
866 if not a.runnable():
867 self._compiled_exe_error(a)
868 expanded_args.append(a.get_path())
869 elif isinstance(a, compilers.Compiler):
870 FeatureNew.single_use('Compiler object as a variadic argument to `run_command`', '0.61.0', self.subproject, location=self.current_node)
871 prog = ExternalProgram(a.get_exe(), silent=True)
872 if not prog.found():
873 raise InterpreterException(f'Program {cmd!r} not found or not executable')
874 expanded_args.append(prog.get_path())
875 else:
876 self._compiled_exe_error(a)
877
878 # If any file that was used as an argument to the command
879 # changes, we must re-run the configuration step.
880 self.add_build_def_file(cmd.get_path())
881 for a in expanded_args:
882 a = os.path.join(builddir if in_builddir else srcdir, self.subdir, a)
883 self.add_build_def_file(a)
884
885 return RunProcess(cmd, expanded_args, env, srcdir, builddir, self.subdir,
886 self.environment.get_build_command() + ['introspect'],
887 in_builddir=in_builddir, check=check, capture=kwargs['capture'],
888 console=kwargs['console'])
889
890 def func_option(self, nodes: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> T.NoReturn:
891 raise InterpreterException('Tried to call option() in build description file. All options must be in the option file.')
892
893 @typed_pos_args('subproject', str)
894 @typed_kwargs(
895 'subproject',
896 REQUIRED_KW,
897 NATIVE_KW.evolve(since='1.12.0'),
898 DEFAULT_OPTIONS.evolve(since='0.38.0'),
899 KwargInfo('version', ContainerTypeInfo(list, str), default=[], listify=True),
900 )
901 def func_subproject(self, nodes: mparser.BaseNode, args: T.Tuple[SubProject], kwargs: kwtypes.Subproject) -> SubprojectHolder:
902 # note that this does not use @apply_machine_map. 'for_machine'
903 # is only used by _do_subproject_meson to decide between
904 # Build.copy() and Build.copy_for_build_machine(), and copying
905 # a build-only subproject provides the correct result for "native:
906 # false". This is needed so that it takes two *explicit* levels
907 # of "native: true" for the target_machine to become the build_machine.
908 kw: kwtypes.DoSubproject = {
909 'required': kwargs['required'],
910 'default_options': kwargs['default_options'],
911 'version': kwargs['version'],
912 'options': None,
913 'cmake_options': [],
914 'for_machine': kwargs['native'],
915 }
916 return self.do_subproject(args[0], kw)
917
918 def disabled_subproject(self, subp_name: SubProject, disabled_feature: T.Optional[str] = None,
919 exception: T.Optional[Exception] = None,
920 for_machine: MachineChoice = MachineChoice.HOST) -> SubprojectHolder:
921 sub = SubprojectHolder(NullSubprojectInterpreter(), os.path.join(self.subproject_dir, subp_name),
922 disabled_feature=disabled_feature, exception=exception)
923 self.subprojects[for_machine][subp_name] = sub
924 return sub
925
926 def create_build_subdir(self, subdir: str) -> None:
927 os.makedirs(os.path.join(self.build.environment.get_build_dir(), subdir), exist_ok=True)
928
929 @staticmethod
930 def format_subproject_stack(stack: T.List[T.Tuple[str, MachineChoice]], join: str = ' => ') -> str:
931 prefix = ''
932 result = ''
933 for_build = False
934 for subp_name, machine in stack:
935 result += prefix + subp_name
936 if machine is MachineChoice.BUILD and not for_build:
937 result += ' (build)'
938 for_build = True
939 prefix = join
940 return result
941
942 def do_subproject(self, subp_name: SubProject, kwargs: kwtypes.DoSubproject, force_method: T.Optional[wrap.Method] = None,
943 forced_options: T.Optional[OptionDict] = None) -> SubprojectHolder:
944 disabled, required, feature = extract_required_kwarg(kwargs, self.subproject)
945 kwargs.setdefault('for_machine', MachineChoice.HOST)
946 for_machine = self.build.machine_map[kwargs['for_machine']]
947
948 if disabled:
949 mlog.log('Subproject', mlog.bold(subp_name), ':', 'skipped: feature', mlog.bold(feature), 'disabled')
950 return self.disabled_subproject(subp_name, disabled_feature=feature, for_machine=for_machine)
951
952 default_options = kwargs['default_options']
953
954 # This in practice is only used for default_library. forced_options is the
955 # only case in which a meson.build file overrides the machine file or the
956 # command line.
957 if forced_options:
958 for k, v in forced_options.items():
959 # FIXME: this should have no business poking at augments[],
960 # but set_option() does not do what we want
961 self.coredata.optstore.augments[k.evolve(subproject=subp_name)] = v
962 default_options = {**forced_options, **default_options}
963
964 if subp_name == '':
965 raise InterpreterException('Subproject name must not be empty.')
966 if subp_name[0] == '.':
967 raise InterpreterException('Subproject name must not start with a period.')
968 if '..' in subp_name:
969 raise InterpreterException('Subproject name must not contain a ".." path segment.')
970 if path_has_root(subp_name):
971 raise InterpreterException('Subproject name must not be an absolute path.')
972 if has_path_sep(subp_name):
973 mlog.warning('Subproject name has a path separator. This may cause unexpected behaviour.',
974 location=self.current_node)
975 fullstack = self.subproject_stack + [(subp_name, for_machine)]
976 if (subp_name, for_machine) in self.subproject_stack:
977 incpath = self.format_subproject_stack(fullstack)
978 raise InvalidCode(f'Recursive include of subprojects: {incpath}.')
979 if subp_name in self.subprojects[for_machine]:
980 subproject = self.subprojects[for_machine][subp_name]
981 if required and not subproject.found():
982 raise InterpreterException(f'Subproject "{subproject.subdir}" required but not found.')
983 if kwargs['version']:
984 pv = self.build.projects[for_machine][subp_name].version
985 wanted = kwargs['version']
986 if pv == 'undefined' or not mesonlib.version_compare_many(pv, wanted)[0]:
987 raise InterpreterException(f'Subproject {subp_name} version is {pv} but {wanted} required.')
988 return subproject
989
990 r = self.environment.wrap_resolver
991 try:
992 subdir, method = r.resolve(subp_name, force_method)
993 except wrap.WrapException as e:
994 if force_method is not None:
995 prefix = force_method.title() + ' subproject'
996 else:
997 prefix = 'Subproject'
998 msg = [prefix, mlog.bold(subp_name), 'is buildable:', mlog.red('NO')]
999 if not required:
1000 mlog.log(e)
1001 mlog.log(*msg, '(disabling)')
1002 return self.disabled_subproject(subp_name, exception=e)
1003 mlog.error(*msg)
1004 raise e
1005
1006 self.create_build_subdir(subdir)
1007 self.global_args_frozen = True
1008
1009 stack = self.format_subproject_stack(fullstack, ':')
1010 m = ['\nExecuting subproject', mlog.bold(stack)]
1011 if method != 'meson':
1012 m += ['method', mlog.bold(method)]
1013 m.extend(['for machine:', mlog.bold(for_machine.get_lower_case_name())])
1014 mlog.log(*m, '\n', nested=False)
1015
1016 methods_map: T.Dict[wrap.Method, T.Callable[[SubProject, str, OptionDict, kwtypes.DoSubproject],
1017 SubprojectHolder]] = {
1018 'meson': self._do_subproject_meson,
1019 'cmake': self._do_subproject_cmake,
1020 'cargo': self._do_subproject_cargo,
1021 }
1022
1023 try:
1024 return methods_map[method](subp_name, subdir, default_options, kwargs)
1025 # Invalid code is always an error
1026 except InvalidCode:
1027 raise
1028 except Exception as e:
1029 if not required:
1030 with mlog.nested(subp_name):
1031 # Suppress the 'ERROR:' prefix because this exception is not
1032 # fatal and VS CI treat any logs with "ERROR:" as fatal.
1033 mlog.exception(e, prefix=mlog.yellow('Exception:'))
1034 mlog.log('\nSubproject', mlog.bold(subdir), 'is buildable:', mlog.red('NO'), '(disabling)')
1035 return self.disabled_subproject(subp_name, exception=e)
1036 raise e
1037
1038 def _save_ast(self, subdir: str, ast: mparser.CodeBlockNode) -> None:
1039 # Debug print the generated meson file
1040 from ..ast import AstIndentationGenerator, AstPrinter
1041 printer = AstPrinter(update_ast_line_nos=True)
1042 ast.accept(AstIndentationGenerator())
1043 ast.accept(printer)
1044 printer.post_process()
1045 meson_filename = os.path.join(self.build.environment.get_build_dir(), subdir, 'meson.build')
1046 with open(meson_filename, "w", encoding='utf-8') as f:
1047 f.write(printer.result)
1048 mlog.log('Generated Meson AST:', meson_filename)
1049 mlog.cmd_ci_include(meson_filename)
1050
1051 def _do_subproject_meson(self, subp_name: SubProject, subdir: str,
1052 default_options: OptionDict,
1053 kwargs: kwtypes.DoSubproject,
1054 ast: T.Optional[mparser.CodeBlockNode] = None,
1055 build_def_files: T.Optional[T.List[str]] = None,
1056 relaxations: T.Optional[T.Set[InterpreterRuleRelaxation]] = None,
1057 cargo: T.Optional[cargo.Interpreter] = None) -> SubprojectHolder:
1058 for_machine = kwargs['for_machine']
1059 if for_machine is MachineChoice.BUILD:
1060 new_build = self.build.copy_for_build_machine()
1061 else:
1062 new_build = self.build.copy()
1063
1064 with mlog.nested(subp_name):
1065 if ast:
1066 self._save_ast(subdir, ast)
1067
1068 subi = Interpreter(new_build, self.backend, subp_name, subdir, self.subproject_dir,
1069 default_options, ast=ast, relaxations=relaxations,
1070 user_defined_options=self.user_defined_options,
1071 cargo=cargo)
1072 # Those lists are shared by all interpreters. That means that
1073 # even if the subproject fails, any modification that the subproject
1074 # made to those lists will affect the parent project.
1075 subi.subprojects = self.subprojects
1076 subi.modules = self.modules
1077 subi.holder_map = self.holder_map
1078 subi.bound_holder_map = self.bound_holder_map
1079 subi.summary = self.summary
1080
1081 subi.subproject_stack = self.subproject_stack + [(subp_name, for_machine)]
1082 current_active = self.active_projectname
1083 with mlog.nested_warnings():
1084 subi.run()
1085 subi_warnings = mlog.get_warning_count()
1086 mlog.log('Subproject', mlog.bold(subp_name), 'finished.')
1087
1088 mlog.log()
1089
1090 if kwargs['version']:
1091 pv = subi.project_version
1092 wanted = kwargs['version']
1093 if pv == 'undefined' or not mesonlib.version_compare_many(pv, wanted)[0]:
1094 raise InterpreterException(f'Subproject {subp_name} version is {pv} but {wanted} required.')
1095 self.active_projectname = current_active
1096 self.subprojects[for_machine].update(subi.subprojects[for_machine])
1097 self.subprojects[for_machine][subp_name] = SubprojectHolder(
1098 subi, subdir, warnings=subi_warnings, callstack=self.subproject_stack)
1099 # Duplicates are possible when subproject uses files from project root
1100 if build_def_files:
1101 self.build_def_files.update(build_def_files)
1102 # We always need the subi.build_def_files, to propagate sub-sub-projects
1103 self.build_def_files.update(subi.get_build_def_files())
1104 self.build.merge(subi.build)
1105 return self.subprojects[for_machine][subp_name]
1106
1107 def _do_subproject_cmake(self, subp_name: SubProject, subdir: str,
1108 default_options: OptionDict,
1109 kwargs: kwtypes.DoSubproject) -> SubprojectHolder:
1110 from ..cmake import CMakeInterpreter
1111 for_machine = kwargs['for_machine']
1112 with mlog.nested(subp_name):
1113 from ..modules.cmake import CMakeSubprojectOptions
1114 kw_opts = kwargs.get('options') or CMakeSubprojectOptions()
1115 cmake_options = kwargs.get('cmake_options', []) + kw_opts.cmake_options
1116 cm_int = CMakeInterpreter(Path(subdir), self.build.environment, self.backend, for_machine)
1117 cm_int.initialise(cmake_options)
1118 cm_int.analyse()
1119
1120 # Generate a meson ast and execute it with the normal do_subproject_meson
1121 ast = cm_int.pretend_to_be_meson(kw_opts.target_options)
1122 result = self._do_subproject_meson(
1123 subp_name, subdir, default_options,
1124 kwargs, ast,
1125 [str(f) for f in cm_int.bs_files],
1126 relaxations={
1127 InterpreterRuleRelaxation.ALLOW_BUILD_DIR_FILE_REFERENCES,
1128 }
1129 )
1130 result.cm_interpreter = cm_int
1131 return result
1132
1133 def _do_subproject_cargo(self, subp_name: SubProject, subdir: str,
1134 default_options: OptionDict,
1135 kwargs: kwtypes.DoSubproject) -> SubprojectHolder:
1136 from .. import cargo
1137 FeatureNew.single_use('Cargo subproject', '1.3.0', self.subproject, location=self.current_node)
1138 mlog.warning('Cargo subproject is an experimental feature and has no backwards compatibility guarantees.',
1139 once=True, location=self.current_node)
1140 self.add_languages(['rust'], True, MachineChoice.HOST)
1141 self.add_languages(['rust'], True, MachineChoice.BUILD)
1142 with mlog.nested(subp_name):
1143 try:
1144 cargo_int = self.cargo or cargo.Interpreter(self.environment, subdir, self.subproject_dir)
1145 except cargo.TomlImplementationMissing as e:
1146 raise MesonException(f'Failed to load Cargo.lock: {e!s}')
1147
1148 if os.path.exists(os.path.join(self.environment.get_source_dir(), subdir, environment.build_filename)):
1149 ast = None
1150 else:
1151 ast = cargo_int.interpret(subdir)
1152
1153 return self._do_subproject_meson(
1154 subp_name, subdir, default_options, kwargs, ast,
1155 relaxations={InterpreterRuleRelaxation.CARGO_SUBDIR} if ast is not None else None,
1156 cargo=cargo_int)
1157
1158 @typed_pos_args('get_option', str)
1159 @noKwargs
1160 def func_get_option(self, node: mparser.BaseNode, args: T.Tuple[str],
1161 kwargs: TYPE_kwargs) -> T.Union[options.UserOption, 'TYPE_var']:
1162 optname = args[0]
1163
1164 if ':' in optname:
1165 raise InterpreterException('Having a colon in option name is forbidden, '
1166 'projects are not allowed to directly access '
1167 'options of other subprojects.')
1168 if optname_regex.search(optname.split('.', maxsplit=1)[-1]) is not None:
1169 raise InterpreterException(f'Invalid option name {optname!r}')
1170
1171 option_object: T.Optional[options.AnyOptionType]
1172
1173 try:
1174 optkey = options.OptionKey.from_string(optname).evolve(subproject=self.subproject)
1175 option_object, value = self.coredata.optstore.get_option_and_value_for(optkey)
1176 except KeyError:
1177 if self.coredata.optstore.is_base_option(optkey):
1178 # Due to backwards compatibility return the default
1179 # option for base options instead of erroring out.
1180 option_object = options.COMPILER_BASE_OPTIONS[optkey.evolve(subproject=None, machine=MachineChoice.HOST)]
1181 value = option_object.default
1182 else:
1183 if self.subproject:
1184 raise MesonException(f'Option {optname} does not exist for subproject {self.subproject}.')
1185 raise MesonException(f'Option {optname} does not exist.')
1186
1187 if isinstance(option_object, options.UserFeatureOption):
1188 return Feature(optname, FeatureValue(value))
1189 elif optname == 'b_sanitize':
1190 assert isinstance(option_object, options.UserStringArrayOption)
1191 # To ensure backwards compatibility this always returns a string.
1192 # We may eventually want to introduce a new "format" kwarg that
1193 # allows the user to modify this behaviour, but for now this is
1194 # likely good enough for most usecases.
1195 if not value:
1196 return 'none'
1197 assert isinstance(value, list), 'for mypy'
1198 return ','.join(sorted(value))
1199
1200 if isinstance(value, str):
1201 return P_OBJ.OptionString(value, f'{{{optname}}}')
1202 return value
1203
1204 @typed_pos_args('configuration_data', optargs=[dict])
1205 @noKwargs
1206 def func_configuration_data(self, node: mparser.BaseNode, args: T.Tuple[T.Optional[T.Dict[str, T.Any]]],
1207 kwargs: 'TYPE_kwargs') -> build.ConfigurationData:
1208 initial_values = args[0]
1209 if initial_values is not None:
1210 FeatureNew.single_use('configuration_data dictionary', '0.49.0', self.subproject, location=node)
1211 for k, v in initial_values.items():
1212 if not isinstance(v, (str, int, bool)):
1213 raise InvalidArguments(
1214 f'"configuration_data": initial value dictionary key "{k!r}"" must be "str | int | bool", not "{v!r}"')
1215 return build.ConfigurationData(initial_values)
1216
1217 @functools.lru_cache(None)
1218 def set_backend(self) -> None:
1219 from ..backend import backends
1220
1221 if OptionKey('genvslite') in self.user_defined_options.cmd_line_options:
1222 # Use of the '--genvslite vsxxxx' option ultimately overrides any '--backend xxx'
1223 # option the user may specify.
1224 backend_name = self.coredata.optstore.get_value_for(OptionKey('genvslite'))
1225 assert isinstance(backend_name, str), 'for mypy'
1226 self.backend = backends.get_genvslite_backend(backend_name, self.build)
1227 else:
1228 backend_name = self.coredata.optstore.get_value_for(OptionKey('backend'))
1229 assert isinstance(backend_name, str), 'for mypy'
1230 self.backend = backends.get_backend_from_name(backend_name, self.build)
1231
1232 if backend_name != self.backend.name:
1233 if self.backend.name.startswith('vs'):
1234 mlog.log('Auto detected Visual Studio backend:', mlog.bold(self.backend.name))
1235 if not self.environment.first_invocation:
1236 raise MesonBugException(f'Backend changed from {backend_name} to {self.backend.name}')
1237 self.coredata.optstore.set_option(OptionKey('backend'), self.backend.name, first_invocation=True)
1238
1239 self.environment.init_backend_options(backend_name)
1240
1241 def _validate_languages(self, langs: T.List[str], required: bool, node: mparser.BaseNode) -> T.List[Language]:
1242 valid: T.List[Language] = []
1243
1244 for lang in langs:
1245 lang = lang.lower()
1246 if lang in compilers.all_languages:
1247 valid.append(T.cast('Language', lang))
1248 continue
1249
1250 FeatureBroken.single_use(
1251 f'Adding unknown language {lang}', '1.11.0', self.subproject,
1252 'This language cannot be found. It could be: a typo, in which case it can be removed, or, '
1253 'this project might have its Meson version requirements set incorrectly.',
1254 node)
1255 if required:
1256 raise InterpreterException.from_node(
1257 f'Attempted to add language "{lang}", which is not known to this version of Meson.',
1258 node=node)
1259
1260 return valid
1261
1262 @typed_pos_args('project', str, varargs=str)
1263 @typed_kwargs(
1264 'project',
1265 DEFAULT_OPTIONS,
1266 KwargInfo('meson_version', (str, NoneType)),
1267 KwargInfo(
1268 'version',
1269 (str, mesonlib.File, list),
1270 default='undefined',
1271 validator=_project_version_validator,
1272 convertor=lambda x: x[0] if isinstance(x, list) else x,
1273 ),
1274 KwargInfo('license', (ContainerTypeInfo(list, str), NoneType), default=None, listify=True),
1275 KwargInfo('license_files', ContainerTypeInfo(list, str), default=[], listify=True, since='1.1.0'),
1276 KwargInfo('subproject_dir', str, default='subprojects'),
1277 )
1278 def func_project(self, node: mparser.FunctionNode, args: T.Tuple[str, T.List[str]], kwargs: 'kwtypes.Project') -> None:
1279 proj_name, proj_langs_ = args
1280 if ':' in proj_name:
1281 raise InvalidArguments(f"Project name {proj_name!r} must not contain ':'")
1282
1283 proj_langs = self._validate_languages(proj_langs_, True, node)
1284
1285 # This needs to be evaluated as early as possible, as meson uses this
1286 # for things like deprecation testing.
1287 if kwargs['meson_version']:
1288 self.handle_meson_version(kwargs['meson_version'], node)
1289 else:
1290 mesonlib.project_meson_versions[self.subproject] = mesonlib.NoProjectVersion()
1291
1292 self._load_option_file()
1293
1294 self.project_default_options = kwargs['default_options']
1295 if self.environment.first_invocation or (self.subproject != '' and self.subproject not in self.coredata.initialized_subprojects):
1296 if self.subproject == '':
1297 self.coredata.optstore.initialize_from_top_level_project_call(self.project_default_options,
1298 self.user_defined_options.cmd_line_options,
1299 self.environment.options)
1300 else:
1301 self.coredata.optstore.initialize_from_subproject_call(self.subproject,
1302 self.invoker_method_default_options,
1303 self.project_default_options,
1304 self.user_defined_options.cmd_line_options,
1305 self.environment.options)
1306 self.coredata.initialized_subprojects.add(self.subproject)
1307
1308 if not self.is_subproject():
1309 # We have to activate VS before adding languages and before calling
1310 # self.set_backend() otherwise it wouldn't be able to detect which
1311 # vs backend version we need. But after setting default_options in case
1312 # the project sets vs backend by default.
1313 backend = self.coredata.optstore.get_value_for(OptionKey('backend'))
1314 assert backend is None or isinstance(backend, str), 'for mypy'
1315 vsenv = self.coredata.optstore.get_value_for(OptionKey('vsenv'))
1316 assert isinstance(vsenv, bool), 'for mypy'
1317 force_vsenv = vsenv or backend.startswith('vs')
1318 mesonlib.setup_vsenv(force_vsenv)
1319 self.set_backend()
1320
1321 if not self.is_subproject():
1322 self.build.project_name = proj_name
1323 self.active_projectname = proj_name
1324
1325 version = kwargs['version']
1326 if isinstance(version, mesonlib.File):
1327 FeatureNew.single_use('version from file', '0.57.0', self.subproject, location=node)
1328 self.add_build_def_file(version)
1329 ifname = version.absolute_path(self.environment.source_dir,
1330 self.environment.build_dir)
1331 try:
1332 ver_data = Path(ifname).read_text(encoding='utf-8').split('\n')
1333 except FileNotFoundError:
1334 raise InterpreterException('Version file not found.')
1335 if len(ver_data) == 2 and ver_data[1] == '':
1336 ver_data = ver_data[0:1]
1337 if len(ver_data) != 1:
1338 raise InterpreterException('Version file must contain exactly one line of text.')
1339 self.project_version = ver_data[0]
1340 else:
1341 self.project_version = version
1342
1343 if self.build.project_version is None:
1344 self.build.project_version = self.project_version
1345
1346 if kwargs['license'] is None:
1347 proj_license = ['unknown']
1348 if kwargs['license_files']:
1349 raise InvalidArguments('Project `license` name must be specified when `license_files` is set')
1350 else:
1351 proj_license = kwargs['license']
1352 proj_license_files = []
1353 for i in self.source_strings_to_files(kwargs['license_files']):
1354 ifname = i.absolute_path(self.environment.source_dir,
1355 self.environment.build_dir)
1356 proj_license_files.append((ifname, i))
1357 self.build.dep_manifest[proj_name] = build.DepManifest(self.project_version, proj_license,
1358 proj_license_files, self.subproject)
1359
1360 for_machine = self.build.machine_map.host
1361 if self.subproject in self.build.projects[for_machine]:
1362 raise InvalidCode('Second call to project().')
1363
1364 # spdirname is the subproject_dir for this project, relative to self.subdir.
1365 # self.subproject_dir is the subproject_dir for the main project, relative to top source dir.
1366 spdirname = kwargs['subproject_dir']
1367 if not isinstance(spdirname, str):
1368 raise InterpreterException('Subproject_dir must be a string')
1369 if path_has_root(spdirname):
1370 raise InterpreterException('Subproject_dir must not be an absolute path.')
1371 if spdirname.startswith('.'):
1372 raise InterpreterException('Subproject_dir must not begin with a period.')
1373 if '..' in spdirname:
1374 raise InterpreterException('Subproject_dir must not contain a ".." segment.')
1375 if not self.is_subproject():
1376 self.subproject_dir = spdirname
1377 self.build.subproject_dir = self.subproject_dir
1378
1379 # Load wrap files from this (sub)project.
1380 subprojects_dir = os.path.join(self.subdir, spdirname)
1381 if not self.is_subproject():
1382 wrap_mode_s = self.coredata.optstore.get_value_for(OptionKey('wrap_mode'))
1383 assert isinstance(wrap_mode_s, str), 'for mypy'
1384 wrap_mode = WrapMode.from_string(wrap_mode_s)
1385 self.environment.wrap_resolver = wrap.Resolver(self.environment.get_source_dir(), subprojects_dir, self.subproject, wrap_mode)
1386 else:
1387 self.environment.wrap_resolver.load_and_merge(subprojects_dir, self.subproject)
1388
1389 if self.cargo is None:
1390 self.load_root_cargo_lock_file()
1391
1392 build_project = build.BuildProject(proj_name, self.project_version, self.subproject, self.build.for_machine, for_machine)
1393 self.build.projects[for_machine][self.subproject] = build_project
1394
1395 extra_args: T.List[mlog.TV_Loggable] = []
1396 if self.is_subproject() and for_machine is MachineChoice.BUILD:
1397 extra_args.append('(for build machine)')
1398 mlog.log('Project name:', mlog.bold(proj_name), *extra_args)
1399 mlog.log('Project version:', mlog.bold(self.project_version))
1400
1401 self.add_languages(proj_langs, True, MachineChoice.HOST)
1402 self.add_languages(proj_langs, False, MachineChoice.BUILD)
1403
1404 if not self.is_subproject():
1405 self.check_stdlibs()
1406
1407 @typed_kwargs(
1408 'add_languages',
1409 KwargInfo(
1410 'native',
1411 (bool, NoneType),
1412 since='0.54.0',
1413 convertor=lambda x: {None: None, True: MachineChoice.BUILD, False: MachineChoice.HOST}[x],
1414 ),
1415 REQUIRED_KW,
1416 )
1417 @typed_pos_args('add_languages', varargs=str)
1418 def func_add_languages(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'kwtypes.FuncAddLanguages') -> bool:
1419 disabled, required, feature = extract_required_kwarg(kwargs, self.subproject)
1420 for_machine = kwargs['native']
1421
1422 langs = self._validate_languages(args[0], required, node)
1423
1424 if disabled:
1425 for lang in sorted(langs, key=compilers.sort_clink):
1426 mlog.log('Compiler for language', mlog.bold(lang), 'skipped: feature', mlog.bold(feature), 'disabled')
1427 return False
1428 if for_machine is not None:
1429 for_machine = self.build.machine_map[for_machine]
1430 return self.add_languages(langs, required, for_machine)
1431 else:
1432 # absent 'native' means 'both' for backwards compatibility
1433 tv = FeatureNew.get_target_version(self.subproject)
1434 if FeatureNew.check_version(tv, '0.54'):
1435 mlog.warning('add_languages is missing native:, assuming languages are wanted for both host and build.',
1436 location=node)
1437
1438 # If languages were removed as invalid, then return false
1439 success = len(langs) == len(args[0])
1440 success &= self.add_languages(langs, required, MachineChoice.HOST)
1441 success &= self.add_languages(langs, False, MachineChoice.BUILD)
1442 return success
1443
1444 def _stringify_user_arguments(self, args: T.List[TYPE_var], func_name: str) -> list[str]:
1445 try:
1446 return [stringifyUserArguments(i, self.subproject) for i in args]
1447 except InvalidArguments as e:
1448 raise InvalidArguments(f'{func_name}(): {str(e)}')
1449
1450 @noArgsFlattening
1451 @noKwargs
1452 def func_message(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> None:
1453 if len(args) > 1:
1454 FeatureNew.single_use('message with more than one argument', '0.54.0', self.subproject, location=node)
1455 args_str = self._stringify_user_arguments(args, 'message')
1456 self.message_impl(args_str)
1457
1458 def message_impl(self, args: mlog.TV_LoggableList | list[str]) -> None:
1459 mlog.log(mlog.bold('Message:'), *args)
1460
1461 @noArgsFlattening
1462 @FeatureNew('summary', '0.53.0')
1463 @typed_pos_args('summary', (str, dict), optargs=[object])
1464 @typed_kwargs(
1465 'summary',
1466 KwargInfo('section', str, default=''),
1467 KwargInfo('bool_yn', bool, default=False),
1468 KwargInfo('list_sep', (str, NoneType), since='0.54.0')
1469 )
1470 def func_summary(self, node: mparser.BaseNode, args: T.Tuple[T.Union[str, T.Dict[str, T.Any]], T.Optional[T.Any]],
1471 kwargs: 'kwtypes.Summary') -> None:
1472 if args[1] is None:
1473 if not isinstance(args[0], dict):
1474 raise InterpreterException('Summary first argument must be dictionary.')
1475 values = args[0]
1476 else:
1477 if not isinstance(args[0], str):
1478 raise InterpreterException('Summary first argument must be string.')
1479 values = {args[0]: args[1]}
1480 self.summary_impl(values=values, **kwargs)
1481
1482 def summary_impl(self, section: str, values: dict[str, mlog.TV_Loggable | mlog.TV_LoggableList], bool_yn: bool, list_sep: str | None) -> None:
1483 if self.subproject not in self.summary:
1484 self.summary[self.subproject] = Summary(self.active_projectname, self.project_version)
1485 self.summary[self.subproject].add_section(
1486 section, values, bool_yn, list_sep, self.subproject)
1487
1488 def _print_subprojects(self, for_machine: MachineChoice) -> None:
1489 # Add automatic 'Subprojects' section in main project.
1490 all_subprojects: dict[str, mlog.TV_Loggable | mlog.TV_LoggableList] = {}
1491 for name, subp in sorted(self.subprojects[for_machine].items()):
1492 value: mlog.TV_LoggableList = [subp.found()]
1493 if subp.disabled_feature:
1494 value += [f'Feature {subp.disabled_feature!r} disabled']
1495 elif subp.exception:
1496 value += [str(subp.exception)]
1497 elif subp.warnings > 0:
1498 value += [f'{subp.warnings} warnings']
1499 if subp.callstack:
1500 stack = self.format_subproject_stack(subp.callstack)
1501 value += [f'(from {stack})']
1502 all_subprojects[name] = value
1503 if all_subprojects:
1504 self.summary_impl(f'Subprojects (for {for_machine.get_lower_case_name()} machine)', all_subprojects,
1505 bool_yn=True, list_sep=' ')
1506
1507 def _print_summary(self) -> None:
1508 self._print_subprojects(MachineChoice.HOST)
1509 if self.environment.is_cross_build():
1510 self._print_subprojects(MachineChoice.BUILD)
1511 # Add automatic section with all user defined options
1512 if self.user_defined_options:
1513 values: dict[str, mlog.TV_Loggable | mlog.TV_LoggableList] = {}
1514 if self.user_defined_options.cross_file:
1515 values['Cross files'] = self.user_defined_options.cross_file
1516 if self.user_defined_options.native_file:
1517 values['Native files'] = self.user_defined_options.native_file
1518
1519 sorted_options = sorted(self.user_defined_options.cmd_line_options.items(), key=lambda x: x[0].name)
1520 values.update({str(k): v for k, v in sorted_options})
1521 if values:
1522 self.summary_impl('User defined options', values, bool_yn=False, list_sep=None)
1523 # Print all summaries, main project last.
1524 mlog.log('') # newline
1525 main_summary = self.summary.pop('', None)
1526 for subp_name, summary in sorted(self.summary.items()):
1527 if self.subprojects.host[subp_name].found():
1528 summary.dump()
1529 if main_summary:
1530 main_summary.dump()
1531
1532 @noArgsFlattening
1533 @FeatureNew('warning', '0.44.0')
1534 @noKwargs
1535 def func_warning(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> None:
1536 if len(args) > 1:
1537 FeatureNew.single_use('warning with more than one argument', '0.54.0', self.subproject, location=node)
1538 args_str = self._stringify_user_arguments(args, 'warning')
1539 mlog.warning(*args_str, location=node)
1540
1541 @noArgsFlattening
1542 @noKwargs
1543 def func_error(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> T.NoReturn:
1544 if len(args) > 1:
1545 FeatureNew.single_use('error with more than one argument', '0.58.0', self.subproject, location=node)
1546 args_str = self._stringify_user_arguments(args, 'error')
1547 raise InterpreterException('Problem encountered: ' + ' '.join(args_str))
1548
1549 @noArgsFlattening
1550 @FeatureNew('debug', '0.63.0')
1551 @noKwargs
1552 def func_debug(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> None:
1553 args_str = self._stringify_user_arguments(args, 'debug')
1554 mlog.debug('Debug:', *args_str)
1555
1556 @noKwargs
1557 @noPosargs
1558 def func_exception(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> T.NoReturn:
1559 raise RuntimeError('unit test traceback :)')
1560
1561 @typed_pos_args('expect_error', str)
1562 @typed_kwargs(
1563 'expect_error',
1564 KwargInfo('how', str, default='literal', validator=in_set_validator({'literal', 're'})),
1565 )
1566 def func_expect_error(self, node: mparser.BaseNode, args: T.Tuple[str], kwargs: kwtypes.FuncExpectError) -> ContextManagerObject:
1567 class ExpectErrorObject(ContextManagerObject):
1568 def __init__(self, msg: str, how: str, subproject: SubProject) -> None:
1569 super().__init__(subproject)
1570 self.old_stdout = sys.stdout
1571 sys.stdout = self.new_stdout = io.StringIO()
1572 sys.stdout.colorize_console = getattr(self.old_stdout, 'colorize_console', None) # type: ignore[attr-defined]
1573 self.msg = msg
1574 self.how = how
1575
1576 def __exit__(self, exc_type: type[BaseException], exc_val: BaseException, exc_tb: types.TracebackType) -> bool:
1577 sys.stdout = self.old_stdout
1578 for l in self.new_stdout.getvalue().splitlines():
1579 if 'ERROR:' in l:
1580 print(l.replace('ERROR', 'ERROR (msbuild proof)'))
1581 else:
1582 print(l)
1583 if exc_val is None:
1584 raise InterpreterException('Expecting an error but code block succeeded')
1585 if isinstance(exc_val, mesonlib.MesonException):
1586 msg = str(exc_val)
1587 if (self.how == 'literal' and self.msg != msg) or \
1588 (self.how == 're' and not re.match(self.msg, msg)):
1589 raise InterpreterException(f'Expecting error {self.msg!r} but got {msg!r}')
1590 return True
1591 return False
1592 return ExpectErrorObject(args[0], kwargs['how'], self.subproject)
1593
1594 def add_languages(self, args: T.List[Language], required: bool, for_machine: MachineChoice) -> bool:
1595 success = self.add_languages_for(args, required, for_machine)
1596 self._redetect_machines()
1597 return success
1598
1599 def should_skip_sanity_check(self, for_machine: MachineChoice) -> bool:
1600 should = self.environment.properties.host.get('skip_sanity_check', False)
1601 if not isinstance(should, bool):
1602 raise InterpreterException('Option skip_sanity_check must be a boolean.')
1603 if for_machine != MachineChoice.HOST and not should:
1604 return False
1605 if not self.environment.is_cross_build() and not should:
1606 return False
1607 return should
1608
1609 def add_languages_for(self, args: T.List[Language], required: bool, for_machine: MachineChoice) -> bool:
1610 langs = set(self.compilers[for_machine])
1611 langs.update(args)
1612
1613 # Some languages are added only as implementation details of other
1614 # languages. When that happens, we don't want to add those languages to
1615 # the project enabled languages, as they are implementation details, not
1616 # something the user explicitly asked for, and we don't want to be
1617 # forced to keep them forever if the implementation changes.
1618 internal: T.Set[Language] = set()
1619
1620 if 'vala' in langs and 'c' not in langs:
1621 FeatureNew.single_use('Adding Vala language without C', '0.59.0', self.subproject, location=self.current_node)
1622 args.append('c')
1623
1624 # We need to initialize the default cython language here, as we need it
1625 # for sanity checking. We may need to initialize a different language later
1626 # if a target has the `cython_language` overridden. We only want to
1627 # initialize a default if cython is a new language, not if it's an
1628 # existing one from `self.compilers`.
1629 if 'cython' in args:
1630 _lang = self.coredata.optstore.get_pending_value(OptionKey('cython_language', None, for_machine), 'c')
1631 assert isinstance(_lang, str), 'for mypy'
1632 cython_lang = T.cast('Language', _lang)
1633 if cython_lang not in langs:
1634 FeatureNew.single_use(f'Adding Cython language without {cython_lang}', '1.11',
1635 self.subproject, location=self.current_node)
1636 args.append(cython_lang)
1637 internal.add(cython_lang)
1638
1639 if 'cuda' in args and 'cpp' not in langs:
1640 # Cuda requires C++, ensure we initialize that compiler, but don't
1641 # add that to the project compiler list
1642 # No FeatureNew is required here because we always did this, we just
1643 # did it wrong.
1644 args.append('cpp')
1645 internal.add('cpp')
1646
1647 if 'nasm' in langs:
1648 FeatureNew.single_use('Adding NASM language', '0.64.0', self.subproject, location=self.current_node)
1649
1650 success = True
1651 for lang in sorted(args, key=compilers.sort_clink):
1652 if lang in self.compilers[for_machine]:
1653 continue
1654 machine_name = for_machine.get_lower_case_name()
1655 comp = self.coredata.compilers[for_machine].get(lang)
1656 if not comp:
1657 try:
1658 skip_sanity_check = self.should_skip_sanity_check(for_machine)
1659 if skip_sanity_check:
1660 mlog.log('Cross compiler sanity tests disabled via the cross file.', once=True)
1661 comp = compilers.detect_compiler_for(self.environment, lang, for_machine, skip_sanity_check, self.subproject)
1662 if comp is None:
1663 raise InvalidArguments(f'Tried to use unknown language "{lang}".')
1664 except mesonlib.MesonException:
1665 if not required:
1666 mlog.log('Compiler for language',
1667 mlog.bold(lang), 'for the', machine_name,
1668 'machine not found.')
1669 success = False
1670 continue
1671 else:
1672 raise
1673 if lang == 'cuda' and hasattr(self.backend, 'allow_thin_archives'):
1674 # see NinjaBackend.__init__() why we need to disable thin archives for cuda
1675 mlog.debug('added cuda as language, disabling thin archives for {}, since nvcc/nvlink cannot handle thin archives natively'.format(for_machine))
1676 self.backend.allow_thin_archives[for_machine] = False
1677 else:
1678 # update new values from commandline, if it applies
1679 self.coredata.process_compiler_options(lang, comp, self.subproject)
1680
1681 if for_machine == MachineChoice.HOST or self.environment.is_cross_build():
1682 logger_fun = mlog.log
1683 else:
1684 logger_fun = mlog.debug
1685 logger_fun(comp.get_display_language(), 'compiler for the', machine_name, 'machine:',
1686 mlog.bold(' '.join(comp.get_exelist())), comp.get_version_string())
1687 if comp.linker is not None:
1688 logger_fun(comp.get_display_language(), 'linker for the', machine_name, 'machine:',
1689 mlog.bold(' '.join(comp.linker.get_exelist())), comp.linker.id, comp.linker.version)
1690 self.build.ensure_static_linker(comp)
1691 if lang not in internal:
1692 self.compilers[for_machine][lang] = comp
1693
1694 return success
1695
1696 def program_from_file_for(self, for_machine: MachineChoice, prognames: T.List[mesonlib.FileOrString]
1697 ) -> T.Optional[ExternalProgram]:
1698 for p in prognames:
1699 if isinstance(p, mesonlib.File):
1700 continue # Always points to a local (i.e. self generated) file.
1701 if not isinstance(p, str):
1702 raise InterpreterException('Executable name must be a string')
1703 prog = ExternalProgram.from_bin_list(self.environment, for_machine, p)
1704 # if the machine file specified something, it may be a regular
1705 # not-found program but we still want to return that
1706 if not isinstance(prog, NonExistingExternalProgram):
1707 return prog
1708 return None
1709
1710 def program_from_system(self, args: T.List[mesonlib.FileOrString], search_dirs: T.Optional[T.List[str]],
1711 extra_info: T.List[mlog.TV_Loggable]) -> T.Optional[ExternalProgram]:
1712 # Search for scripts relative to current subdir.
1713 # Do not cache found programs because find_program('foobar')
1714 # might give different results when run from different source dirs.
1715 source_dir = os.path.join(self.environment.get_source_dir(), self.subdir)
1716 for exename in args:
1717 if isinstance(exename, mesonlib.File):
1718 if exename.is_built:
1719 search_dir = os.path.join(self.environment.get_build_dir(),
1720 exename.subdir)
1721 else:
1722 search_dir = os.path.join(self.environment.get_source_dir(),
1723 exename.subdir)
1724 exename = exename.fname
1725 search_dirs = [search_dir]
1726 elif isinstance(exename, str):
1727 if search_dirs:
1728 search_dirs = [source_dir] + search_dirs
1729 else:
1730 search_dirs = [source_dir]
1731 else:
1732 raise InvalidArguments(f'find_program only accepts strings and files, not {exename!r}')
1733 extprog = ExternalProgram(exename, search_dirs=search_dirs, silent=True)
1734 if extprog.found():
1735 extra_info.append(f"({' '.join(extprog.get_command())})")
1736 return extprog
1737 return None
1738
1739 def program_from_overrides(self, command_names: T.List[mesonlib.FileOrString],
1740 for_machine: MachineChoice,
1741 extra_info: T.List['mlog.TV_Loggable']
1742 ) -> T.Optional[Program]:
1743 for name in command_names:
1744 if not isinstance(name, str):
1745 continue
1746 if name in self.build.find_overrides[for_machine]:
1747 exe = self.build.find_overrides[for_machine][name]
1748 extra_info.append(mlog.blue('(overridden)'))
1749 return exe
1750 return None
1751
1752 def store_name_lookups(self, command_names: T.List[mesonlib.FileOrString], for_machine: MachineChoice) -> None:
1753 for name in command_names:
1754 if isinstance(name, str):
1755 self.build.searched_programs[for_machine].add(name)
1756
1757 def add_find_program_override(self, name: str, exe: Program, for_machine: MachineChoice) -> None:
1758 if name in self.build.searched_programs[for_machine]:
1759 raise InterpreterException(f'Tried to override finding of executable "{name}" which has already been found.')
1760 if name in self.build.find_overrides[for_machine]:
1761 raise InterpreterException(f'Tried to override executable "{name}" which has already been overridden.')
1762 self.build.find_overrides[for_machine][name] = exe
1763 if name == 'pkg-config' and isinstance(exe, ExternalProgram):
1764 from ..dependencies.pkgconfig import PkgConfigInterface
1765 PkgConfigInterface.set_program_override(exe, for_machine)
1766
1767 def notfound_program(self, args: T.List[mesonlib.FileOrString]) -> ExternalProgram:
1768 return NonExistingExternalProgram(' '.join(
1769 [a if isinstance(a, str) else a.absolute_path(self.environment.source_dir, self.environment.build_dir)
1770 for a in args]))
1771
1772 # TODO update modules to always pass `for_machine`. It is bad-form to assume
1773 # the host machine.
1774 def find_program_impl(self, args: T.List[mesonlib.FileOrString],
1775 for_machine: MachineChoice = MachineChoice.HOST,
1776 default_options: T.Optional[OptionDict] = None,
1777 required: bool = True, silent: bool = True,
1778 wanted: T.Union[str, T.List[str]] = '',
1779 search_dirs: T.Optional[T.List[str]] = None,
1780 version_arg: T.Optional[str] = '',
1781 version_func: T.Optional[ProgramVersionFunc] = None
1782 ) -> Program:
1783 args = mesonlib.listify(args)
1784
1785 extra_info: T.List[mlog.TV_Loggable] = []
1786 progobj = self.program_lookup(args, for_machine, default_options, required, search_dirs, wanted, version_arg, version_func, extra_info)
1787 if progobj is None or not self.check_program_version(progobj, wanted, version_func, for_machine, extra_info):
1788 progobj = self.notfound_program(args)
1789
1790 if isinstance(progobj, ExternalProgram) and not progobj.found():
1791 if not silent:
1792 mlog.log('Program', mlog.bold(progobj.get_name()), 'found:', mlog.red('NO'), *extra_info)
1793 if required:
1794 m = 'Program {!r} not found or not executable'
1795 raise InterpreterException(m.format(progobj.get_name()))
1796 return progobj
1797
1798 # Only store successful lookups
1799 self.store_name_lookups(args, for_machine)
1800 if not silent:
1801 mlog.log('Program', mlog.bold(progobj.name), 'found:', mlog.green('YES'), *extra_info)
1802 return progobj
1803
1804 def program_lookup(self, args: T.List[mesonlib.FileOrString], for_machine: MachineChoice,
1805 default_options: T.Optional[OptionDict],
1806 required: bool,
1807 search_dirs: T.Optional[T.List[str]],
1808 wanted: T.Union[str, T.List[str]],
1809 version_arg: T.Optional[str],
1810 version_func: T.Optional[ProgramVersionFunc],
1811 extra_info: T.List[mlog.TV_Loggable]
1812 ) -> T.Optional[Program]:
1813 progobj = self.program_from_overrides(args, for_machine, extra_info)
1814 if progobj:
1815 return progobj
1816
1817 if args[0] == 'meson':
1818 # Override find_program('meson') to return what we were invoked with
1819 return ExternalProgram('meson', self.environment.get_build_command(), silent=True)
1820
1821 wrap_mode_s = self.coredata.optstore.get_value_for(OptionKey('wrap_mode'))
1822 force_fallback_for = self.coredata.optstore.get_value_for(OptionKey('force_fallback_for'))
1823 assert isinstance(wrap_mode_s, str), 'for mypy'
1824 assert isinstance(force_fallback_for, list), 'for mypy'
1825 wrap_mode = WrapMode.from_string(wrap_mode_s)
1826
1827 fallback: SubProject | None = \
1828 self.environment.wrap_resolver.find_program_provider(args) \
1829 if self.environment.wrap_resolver is not None \
1830 else None
1831 if fallback and (wrap_mode == WrapMode.forcefallback or fallback in force_fallback_for):
1832 return self.find_program_fallback(fallback, args, for_machine, default_options, required, extra_info)
1833
1834 progobj = self.program_from_file_for(for_machine, args)
1835 if progobj is None:
1836 progobj = self.program_from_system(args, search_dirs, extra_info)
1837 if progobj is None and args[0].endswith('python3'):
1838 prog = ExternalProgram('python3', mesonlib.python_command, silent=True)
1839 progobj = prog if prog.found() else None
1840
1841 if isinstance(progobj, ExternalProgram) and version_arg:
1842 progobj.version_arg = version_arg
1843 if progobj and not self.check_program_version(progobj, wanted, version_func, for_machine, extra_info):
1844 progobj = None
1845
1846 if progobj is None and fallback and required:
1847 progobj = self.notfound_program(args)
1848 mlog.log('Program', mlog.bold(progobj.get_name()), 'found:', mlog.red('NO'), *extra_info)
1849 extra_info.clear()
1850 progobj = self.find_program_fallback(fallback, args, for_machine, default_options, required, extra_info)
1851
1852 return progobj
1853
1854 def check_program_version(self, progobj: Program,
1855 wanted: T.Union[str, T.List[str]],
1856 version_func: T.Optional[ProgramVersionFunc],
1857 for_machine: MachineChoice,
1858 extra_info: T.List[mlog.TV_Loggable]) -> bool:
1859 if wanted:
1860 if version_func:
1861 version = version_func(progobj)
1862 elif isinstance(progobj, build.Executable):
1863 if progobj.subproject:
1864 interp = self.subprojects[for_machine][progobj.subproject].held_object
1865 else:
1866 interp = self
1867 assert isinstance(interp, Interpreter), 'for mypy'
1868 version = interp.project_version
1869 else:
1870 version = progobj.get_version(self)
1871 is_found, not_found, _ = mesonlib.version_compare_many(version, wanted)
1872 if not is_found:
1873 extra_info[:0] = ['found', mlog.normal_cyan(version), 'but need:',
1874 mlog.bold(', '.join([f"'{e}'" for e in not_found]))]
1875 return False
1876 extra_info.insert(0, mlog.normal_cyan(version))
1877 return True
1878
1879 def find_program_fallback(self, fallback: SubProject, args: T.List[mesonlib.FileOrString],
1880 for_machine: MachineChoice,
1881 default_options: OptionDict,
1882 required: bool, extra_info: T.List[mlog.TV_Loggable],
1883 ) -> T.Optional[Program]:
1884 mlog.log('Fallback to subproject', mlog.bold(fallback), 'which provides program',
1885 mlog.bold(' '.join(str(a) for a in args)))
1886 sp_kwargs: kwtypes.DoSubproject = {
1887 'required': required,
1888 'default_options': default_options or {},
1889 'version': [],
1890 'cmake_options': [],
1891 'options': None,
1892 'for_machine': for_machine,
1893 }
1894 self.do_subproject(fallback, sp_kwargs)
1895 return self.program_from_overrides(args, for_machine, extra_info)
1896
1897 @typed_pos_args('find_program', varargs=(str, mesonlib.File), min_varargs=1)
1898 @typed_kwargs(
1899 'find_program',
1900 DISABLER_KW.evolve(since='0.49.0'),
1901 NATIVE_KW,
1902 REQUIRED_KW,
1903 KwargInfo('dirs', ContainerTypeInfo(list, str), default=[], listify=True, since='0.53.0'),
1904 KwargInfo('version', ContainerTypeInfo(list, str), default=[], listify=True, since='0.52.0'),
1905 KwargInfo('version_argument', str, default='', since='1.5.0'),
1906 DEFAULT_OPTIONS.evolve(since='1.3.0')
1907 )
1908 @disablerIfNotFound
1909 @apply_machine_map
1910 def func_find_program(self, node: mparser.BaseNode, args: T.Tuple[T.List[mesonlib.FileOrString]],
1911 kwargs: 'kwtypes.FindProgram',
1912 ) -> Program:
1913 disabled, required, feature = extract_required_kwarg(kwargs, self.subproject)
1914 if disabled:
1915 mlog.log('Program', mlog.bold(' '.join(str(a) for a in args[0])), 'skipped: feature', mlog.bold(feature), 'disabled')
1916 return self.notfound_program(args[0])
1917
1918 search_dirs = extract_search_dirs(kwargs)
1919 default_options = kwargs['default_options']
1920 return self.find_program_impl(args[0], kwargs['native'], default_options=default_options, required=required,
1921 silent=False, wanted=kwargs['version'], version_arg=kwargs['version_argument'],
1922 search_dirs=search_dirs)
1923
1924 # When adding kwargs, please check if they make sense in dependencies.get_dep_identifier()
1925 @typed_pos_args('dependency', varargs=str, min_varargs=1)
1926 @typed_kwargs('dependency', *DEPENDENCY_KWS)
1927 @disablerIfNotFound
1928 @apply_machine_map
1929 def func_dependency(self, node: mparser.BaseNode, args: T.Tuple[T.List[str]], kwargs: kwtypes.FuncDependency) -> Dependency:
1930 # Replace '' by empty list of names
1931 names = [n for n in args[0] if n]
1932 if len(names) > 1:
1933 FeatureNew('dependency with more than one name', '0.60.0').use(self.subproject)
1934 default_options = kwargs.get('default_options')
1935 for_machine = kwargs['native']
1936 df = DependencyFallbacksHolder(self, names, for_machine, kwargs['allow_fallback'], default_options)
1937 df.set_fallback(kwargs['fallback'])
1938 not_found_message = kwargs['not_found_message']
1939
1940 disabled, required, feature = extract_required_kwarg(kwargs, self.subproject)
1941 if disabled:
1942 name = names[0]
1943 if kwargs['modules']:
1944 name = name + '(modules: {})'.format(', '.join(kwargs['modules']))
1945 mlog.log('Dependency', mlog.bold(name),
1946 'for', mlog.bold(for_machine.get_lower_case_name()), 'machine',
1947 'skipped: feature', mlog.bold(feature), 'disabled')
1948 return dependencies.NotFoundDependency(names[0], self.environment)
1949
1950 nkwargs = T.cast('dependencies.base.DependencyObjectKWs', kwargs.copy())
1951 nkwargs['required'] = required # to replace a possible Feature with a bool
1952
1953 try:
1954 d = df.lookup(nkwargs)
1955 except Exception:
1956 if not_found_message:
1957 self.message_impl([not_found_message])
1958 raise
1959 assert isinstance(d, Dependency), 'for mypy'
1960 if not d.found() and not_found_message:
1961 self.message_impl([not_found_message])
1962 # Ensure the correct include type
1963 if kwargs['include_type'] != 'preserve':
1964 wanted = kwargs['include_type']
1965 actual = d.get_include_type()
1966 if wanted != actual:
1967 mlog.debug(f'Current include type of {args[0]} is {actual}. Converting to requested {wanted}')
1968 d = d.generate_system_dependency(wanted)
1969 if d.feature_since is not None:
1970 version, extra_msg = d.feature_since
1971 FeatureNew.single_use(f'dep {d.name!r} custom lookup', version, self.subproject, extra_msg, node)
1972 for f in d.featurechecks:
1973 f.use(self.subproject, node)
1974 return d
1975
1976 @FeatureNew('default', '1.12.0')
1977 @noKwargs
1978 @noPosargs
1979 def func_default(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> DefaultObject:
1980 return DefaultObject()
1981
1982 @FeatureNew('disabler', '0.44.0')
1983 @noKwargs
1984 @noPosargs
1985 def func_disabler(self, node: mparser.BaseNode, args: list[TYPE_var], kwargs: TYPE_kwargs) -> Disabler:
1986 return Disabler()
1987
1988 @typed_pos_args('executable', str, varargs=SOURCES_VARARGS)
1989 @typed_kwargs('executable', *EXECUTABLE_KWS)
1990 def func_executable(self, node: mparser.BaseNode,
1991 args: T.Tuple[str, SourcesVarargsType],
1992 kwargs: kwtypes.Executable) -> T.Union[build.Executable, build.SharedLibrary]:
1993 return self.build_target(node, args, kwargs, build.Executable)
1994
1995 @typed_pos_args('static_library', str, varargs=SOURCES_VARARGS)
1996 @typed_kwargs('static_library', *STATIC_LIB_KWS)
1997 def func_static_lib(self, node: mparser.BaseNode,
1998 args: T.Tuple[str, SourcesVarargsType],
1999 kwargs: kwtypes.StaticLibrary) -> build.StaticLibrary:
2000 return self.build_target(node, args, kwargs, build.StaticLibrary)
2001
2002 @typed_pos_args('shared_library', str, varargs=SOURCES_VARARGS)
2003 @typed_kwargs('shared_library', *SHARED_LIB_KWS)
2004 def func_shared_lib(self, node: mparser.BaseNode,
2005 args: T.Tuple[str, SourcesVarargsType],
2006 kwargs: kwtypes.SharedLibrary) -> build.SharedLibrary:
2007 return self.build_target(node, args, kwargs, build.SharedLibrary)
2008
2009 @typed_pos_args('both_libraries', str, varargs=SOURCES_VARARGS)
2010 @typed_kwargs('both_libraries', *LIBRARY_KWS)
2011 @noSecondLevelHolderResolving
2012 def func_both_lib(self, node: mparser.BaseNode,
2013 args: T.Tuple[str, SourcesVarargsType],
2014 kwargs: kwtypes.Library) -> build.BothLibraries:
2015 return self.build_both_libraries(node, args, kwargs)
2016
2017 @FeatureNew('shared_module', '0.37.0')
2018 @typed_pos_args('shared_module', str, varargs=SOURCES_VARARGS)
2019 @typed_kwargs('shared_module', *SHARED_MOD_KWS)
2020 def func_shared_module(self, node: mparser.BaseNode,
2021 args: T.Tuple[str, SourcesVarargsType],
2022 kwargs: kwtypes.SharedModule) -> build.SharedModule:
2023 return self.build_target(node, args, kwargs, build.SharedModule)
2024
2025 @typed_pos_args('library', str, varargs=SOURCES_VARARGS)
2026 @typed_kwargs('library', *LIBRARY_KWS)
2027 @noSecondLevelHolderResolving
2028 def func_library(self, node: mparser.BaseNode,
2029 args: T.Tuple[str, SourcesVarargsType],
2030 kwargs: kwtypes.Library) -> build.StaticLibrary | build.SharedLibrary | build.BothLibraries:
2031 return self.build_library(node, args, kwargs)
2032
2033 @typed_pos_args('jar', str, varargs=(str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList, build.ExtractedObjects, build.BuildTarget))
2034 @typed_kwargs('jar', *JAR_KWS)
2035 def func_jar(self, node: mparser.BaseNode,
2036 args: T.Tuple[str, T.List[str | build.TargetSources]],
2037 kwargs: kwtypes.Jar) -> build.Jar:
2038 return self.build_target(node, T.cast('tuple[str, SourcesVarargsType]', args), kwargs, build.Jar)
2039
2040 @FeatureNewKwargs('build_target', '0.40.0', ['link_whole', 'override_options'])
2041 @typed_pos_args('build_target', str, varargs=SOURCES_VARARGS)
2042 @typed_kwargs('build_target', *BUILD_TARGET_KWS)
2043 def func_build_target(self, node: mparser.BaseNode,
2044 args: T.Tuple[str, SourcesVarargsType],
2045 kwargs: kwtypes.BuildTargetFunc,
2046 ) -> T.Union[build.Executable, build.StaticLibrary, build.SharedLibrary,
2047 build.SharedModule, build.BothLibraries, build.Jar]:
2048 target_type = kwargs['target_type']
2049
2050 if target_type == 'executable':
2051 return self.build_target(node, args, kwargs, build.Executable)
2052 elif target_type == 'shared_library':
2053 return self.build_target(node, args, kwargs, build.SharedLibrary)
2054 elif target_type == 'shared_module':
2055 return self.build_target(node, args, kwargs, build.SharedModule)
2056 elif target_type == 'static_library':
2057 return self.build_target(node, args, kwargs, build.StaticLibrary)
2058 elif target_type == 'both_libraries':
2059 return self.build_both_libraries(node, args, kwargs)
2060 elif target_type == 'library':
2061 return self.build_library(node, args, kwargs)
2062 # We can't avoid the cast here because of the mis-matched sources types
2063 # between Jar and BuildTarget types
2064 return self.build_target(node, args, T.cast('kwtypes.Jar', kwargs), build.Jar)
2065
2066 @noPosargs
2067 @typed_kwargs(
2068 'vcs_tag',
2069 CT_INPUT_KW.evolve(required=True),
2070 MULTI_OUTPUT_KW,
2071 # Cannot use the COMMAND_KW because command is allowed to be empty
2072 KwargInfo(
2073 'command',
2074 ContainerTypeInfo(list, (str, build.BuildTarget, build.CustomTarget, build.CustomTargetIndex, Program, mesonlib.File)),
2075 listify=True,
2076 default=[],
2077 ),
2078 KwargInfo('fallback', (str, NoneType)),
2079 KwargInfo('replace_string', str, default='@VCS_TAG@'),
2080 INSTALL_KW.evolve(since='1.7.0'),
2081 INSTALL_DIR_KW.evolve(since='1.7.0'),
2082 INSTALL_TAG_KW.evolve(since='1.7.0'),
2083 INSTALL_MODE_KW.evolve(since='1.7.0'),
2084 )
2085 @apply_machine_map
2086 def func_vcs_tag(self, node: mparser.BaseNode, args: T.List['TYPE_var'], kwargs: 'kwtypes.VcsTag') -> build.CustomTarget:
2087 if kwargs['fallback'] is None:
2088 FeatureNew.single_use('Optional fallback in vcs_tag', '0.41.0', self.subproject, location=node)
2089 fallback = kwargs['fallback'] or self.project_version
2090 replace_string = kwargs['replace_string']
2091 regex_selector = '(.*)' # default regex selector for custom command: use complete output
2092 vcs_cmd = kwargs['command']
2093 source_dir = os.path.normpath(os.path.join(self.environment.get_source_dir(), self.subdir))
2094 if vcs_cmd:
2095 if isinstance(vcs_cmd[0], (str, mesonlib.File)):
2096 if isinstance(vcs_cmd[0], mesonlib.File):
2097 FeatureNew.single_use('vcs_tag with file as the first argument', '0.62.0', self.subproject, location=node)
2098 maincmd = self.find_program_impl([vcs_cmd[0]], required=False)
2099 if maincmd.found():
2100 vcs_cmd[0] = maincmd
2101 else:
2102 FeatureNew.single_use('vcs_tag with custom_tgt, program, or exe as the first argument', '0.63.0', self.subproject, location=node)
2103 else:
2104 vcs = mesonlib.detect_vcs(source_dir)
2105 if vcs:
2106 mlog.log('Found {} repository at {}'.format(vcs.name, vcs.wc_dir))
2107 vcs_cmd = vcs.get_rev
2108 regex_selector = vcs.rev_regex
2109 else:
2110 vcs_cmd = [' '] # executing this cmd will fail in vcstagger.py and force to use the fallback string
2111 # vcstagger.py parameters: infile, outfile, fallback, source_dir, replace_string, regex_selector, command...
2112
2113 self._validate_custom_target_outputs(len(kwargs['input']) > 1, kwargs['output'], "vcs_tag")
2114
2115 cmd = self.environment.get_build_command() + \
2116 ['--internal',
2117 'vcstagger',
2118 '@INPUT0@',
2119 '@OUTPUT0@',
2120 fallback,
2121 source_dir,
2122 replace_string,
2123 regex_selector] + vcs_cmd
2124
2125 install = kwargs['install']
2126 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2127 install_dir: T.List[T.Union[str, Literal[False]]] = [] if kwargs['install_dir'] is None else [kwargs['install_dir']]
2128 install_tag: T.List[T.Optional[str]] = [] if kwargs['install_tag'] is None else [kwargs['install_tag']]
2129 if install and not install_dir:
2130 raise InvalidArguments('vcs_tag: "install_dir" keyword argument must be set when "install" is true.')
2131
2132 tg = build.CustomTarget(
2133 kwargs['output'][0],
2134 self.subdir,
2135 self.environment,
2136 cmd,
2137 self.source_strings_to_files(kwargs['input']),
2138 kwargs['output'],
2139 self.current_build_project(),
2140 build_by_default=True,
2141 build_always_stale=True,
2142 install=install,
2143 install_dir=install_dir,
2144 install_mode=install_mode,
2145 install_tag=install_tag,
2146 )
2147 self.add_target(tg.name, tg)
2148 return tg
2149
2150 @FeatureNew('subdir_done', '0.46.0')
2151 @noPosargs
2152 @noKwargs
2153 def func_subdir_done(self, node: mparser.BaseNode, args: TYPE_var, kwargs: TYPE_kwargs) -> T.NoReturn:
2154 raise SubdirDoneRequest()
2155
2156 def _validate_custom_target_outputs(self, has_multi_in: bool, outputs: T.Iterable[str], name: str) -> None:
2157 """Checks for additional invalid values in a custom_target output.
2158
2159 This cannot be done with typed_kwargs because it requires the number of
2160 inputs.
2161 """
2162 inregex: T.List[str] = ['@PLAINNAME[0-9]+@', '@BASENAME[0-9]+@']
2163 from ..utils.universal import iter_regexin_iter
2164 for out in outputs:
2165 match = iter_regexin_iter(inregex, [out])
2166 if has_multi_in and ('@PLAINNAME@' in out or '@BASENAME@' in out):
2167 raise InvalidArguments(f'{name}: output cannot contain "@PLAINNAME@" or "@BASENAME@" '
2168 'when there is more than one input (we can\'t know which to use)')
2169 elif match:
2170 FeatureNew.single_use(
2171 f'{match} in output', '1.5.0',
2172 self.subproject)
2173
2174 @typed_pos_args('custom_target', optargs=[str])
2175 @typed_kwargs(
2176 'custom_target',
2177 COMMAND_KW,
2178 CT_BUILD_ALWAYS,
2179 CT_BUILD_ALWAYS_STALE,
2180 CT_BUILD_BY_DEFAULT,
2181 CT_INPUT_KW,
2182 CT_INSTALL_DIR_KW,
2183 CT_INSTALL_TAG_KW,
2184 MULTI_OUTPUT_KW,
2185 DEPENDS_KW,
2186 DEPEND_FILES_KW,
2187 DEPFILE_KW,
2188 ENV_KW.evolve(since='0.57.0'),
2189 INSTALL_KW,
2190 INSTALL_MODE_KW.evolve(since='0.47.0'),
2191 KwargInfo('feed', bool, default=False, since='0.59.0'),
2192 KwargInfo('capture', bool, default=False),
2193 KwargInfo('console', bool, default=False, since='0.48.0'),
2194 KwargInfo('build_subdir', str, default='', since='1.10.0'),
2195 )
2196 @apply_machine_map
2197 def func_custom_target(self, node: mparser.FunctionNode, args: T.Tuple[str],
2198 kwargs: 'kwtypes.CustomTarget') -> build.CustomTarget:
2199 if kwargs['depfile'] and ('@BASENAME@' in kwargs['depfile'] or '@PLAINNAME@' in kwargs['depfile']):
2200 FeatureNew.single_use('substitutions in custom_target depfile', '0.47.0', self.subproject, location=node)
2201 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2202
2203 # Don't mutate the kwargs
2204
2205 build_by_default = kwargs['build_by_default']
2206 build_always_stale = kwargs['build_always_stale']
2207 # Remap build_always to build_by_default and build_always_stale
2208 if kwargs['build_always'] is not None and kwargs['build_always_stale'] is not None:
2209 raise InterpreterException('CustomTarget: "build_always" and "build_always_stale" are mutually exclusive')
2210
2211 if build_by_default is None and kwargs['install']:
2212 build_by_default = True
2213
2214 elif kwargs['build_always'] is not None:
2215 if build_by_default is None:
2216 build_by_default = kwargs['build_always']
2217 build_always_stale = kwargs['build_by_default']
2218
2219 # These are nullable so that we can know whether they're explicitly
2220 # set or not. If they haven't been overwritten, set them to their true
2221 # default
2222 if build_by_default is None:
2223 build_by_default = False
2224 if build_always_stale is None:
2225 build_always_stale = False
2226
2227 name = args[0]
2228 if name is None:
2229 # name will default to first output, but we cannot do that yet because
2230 # they could need substitutions (e.g. @BASENAME@) first. CustomTarget()
2231 # will take care of setting a proper default but name must be an empty
2232 # string in the meantime.
2233 FeatureNew.single_use('custom_target() with no name argument', '0.60.0', self.subproject, location=node)
2234 name = ''
2235 inputs = self.source_strings_to_files(kwargs['input'])
2236 command = kwargs['command']
2237 if command and isinstance(command[0], str):
2238 command[0] = self.find_program_impl([command[0]])
2239
2240 if len(inputs) > 1 and kwargs['feed']:
2241 raise InvalidArguments('custom_target: "feed" keyword argument can only be used with a single input')
2242 if len(kwargs['output']) > 1 and kwargs['capture']:
2243 raise InvalidArguments('custom_target: "capture" keyword argument can only be used with a single output')
2244 if kwargs['capture'] and kwargs['console']:
2245 raise InvalidArguments('custom_target: "capture" and "console" keyword arguments are mutually exclusive')
2246 for c in command:
2247 if kwargs['capture'] and isinstance(c, str) and '@OUTPUT@' in c:
2248 raise InvalidArguments('custom_target: "capture" keyword argument cannot be used with "@OUTPUT@"')
2249 if kwargs['feed'] and isinstance(c, str) and '@INPUT@' in c:
2250 raise InvalidArguments('custom_target: "feed" keyword argument cannot be used with "@INPUT@"')
2251 if kwargs['install'] and not kwargs['install_dir']:
2252 raise InvalidArguments('custom_target: "install_dir" keyword argument must be set when "install" is true.')
2253 if len(kwargs['install_dir']) > 1:
2254 FeatureNew.single_use('multiple install_dir for custom_target', '0.40.0', self.subproject, location=node)
2255 if len(kwargs['install_tag']) not in {0, 1, len(kwargs['output'])}:
2256 raise InvalidArguments('custom_target: install_tag argument must have 0 or 1 outputs, '
2257 'or the same number of elements as the output keyword argument. '
2258 f'(there are {len(kwargs["install_tag"])} install_tags, '
2259 f'and {len(kwargs["output"])} outputs)')
2260
2261 self._validate_custom_target_outputs(len(inputs) > 1, kwargs['output'], "custom_target")
2262
2263 tg = build.CustomTarget(
2264 name,
2265 self.subdir,
2266 self.environment,
2267 command,
2268 inputs,
2269 kwargs['output'],
2270 self.current_build_project(),
2271 build_always_stale=build_always_stale,
2272 build_by_default=build_by_default,
2273 capture=kwargs['capture'],
2274 console=kwargs['console'],
2275 depend_files=self.source_strings_to_files(kwargs['depend_files']),
2276 depfile=kwargs['depfile'],
2277 extra_depends=kwargs['depends'],
2278 env=kwargs['env'],
2279 feed=kwargs['feed'],
2280 install=kwargs['install'],
2281 install_dir=kwargs['install_dir'],
2282 install_mode=install_mode,
2283 install_tag=kwargs['install_tag'],
2284 backend=self.backend,
2285 build_subdir=kwargs['build_subdir'])
2286
2287 subdir = tg.get_builddir()
2288 for t in tg.get_outputs():
2289 self.validate_forbidden_targets(t, not subdir)
2290 self.add_target(tg.name, tg)
2291 return tg
2292
2293 @typed_pos_args('run_target', str)
2294 @typed_kwargs(
2295 'run_target',
2296 COMMAND_KW,
2297 DEPENDS_KW,
2298 ENV_KW.evolve(since='0.57.0'),
2299 )
2300 def func_run_target(self, node: mparser.FunctionNode, args: T.Tuple[str],
2301 kwargs: 'kwtypes.RunTarget') -> build.RunTarget:
2302 all_args = kwargs['command'].copy()
2303
2304 for i in listify(all_args):
2305 if isinstance(i, ExternalProgram) and not i.found():
2306 raise InterpreterException(f'Tried to use non-existing executable {i.name!r}')
2307 if isinstance(all_args[0], str):
2308 all_args[0] = self.find_program_impl([all_args[0]])
2309
2310 if '@DEPFILE@' in all_args:
2311 raise InterpreterException('run_target does not have support for @DEPFILE@')
2312
2313 name = args[0]
2314 tg = build.RunTarget(name, all_args, kwargs['depends'], self.subdir, self.environment,
2315 self.current_build_project(), kwargs['env'])
2316 self.add_target(name, tg)
2317 return tg
2318
2319 @FeatureNew('alias_target', '0.52.0')
2320 @typed_pos_args('alias_target', str, varargs=(build.Target, build.BothLibraries), min_varargs=1)
2321 @noKwargs
2322 def func_alias_target(self, node: mparser.BaseNode, args: T.Tuple[str, T.List[T.Union[build.Target, build.BothLibraries]]],
2323 kwargs: TYPE_kwargs) -> build.AliasTarget:
2324 name, deps = args
2325 if any(isinstance(d, build.RunTarget) for d in deps):
2326 FeatureNew.single_use('alias_target that depends on run_targets', '0.60.0', self.subproject)
2327 real_deps: T.List[build.Target] = []
2328 for d in deps:
2329 if isinstance(d, build.BothLibraries):
2330 real_deps.append(d.shared)
2331 real_deps.append(d.static)
2332 else:
2333 real_deps.append(d)
2334 tg = build.AliasTarget(name, real_deps, self.subdir, self.environment,
2335 self.current_build_project())
2336 self.add_target(name, tg)
2337 return tg
2338
2339 @typed_pos_args('generator', (build.Executable, Program))
2340 @typed_kwargs(
2341 'generator',
2342 KwargInfo('arguments', ContainerTypeInfo(list, str, allow_empty=False), required=True, listify=True),
2343 KwargInfo('output', ContainerTypeInfo(list, str, allow_empty=False), required=True, listify=True),
2344 DEPFILE_KW,
2345 DEPENDS_KW,
2346 KwargInfo('capture', bool, default=False, since='0.43.0'),
2347 )
2348 def func_generator(self, node: mparser.FunctionNode,
2349 args: T.Tuple[T.Union[build.Executable, Program]],
2350 kwargs: 'kwtypes.FuncGenerator') -> build.Generator:
2351 for rule in kwargs['output']:
2352 if '@BASENAME@' not in rule and '@PLAINNAME@' not in rule:
2353 raise InvalidArguments('Every element of "output" must contain @BASENAME@ or @PLAINNAME@.')
2354 if has_path_sep(rule):
2355 raise InvalidArguments('"output" must not contain a directory separator.')
2356 if len(kwargs['output']) > 1:
2357 for o in kwargs['output']:
2358 if '@OUTPUT@' in o:
2359 raise InvalidArguments('Tried to use @OUTPUT@ in a rule with more than one output.')
2360
2361 if isinstance(args[0], build.Executable):
2362 exe_prg = build.LocalProgram(args[0], self.project_version)
2363 else:
2364 exe_prg = args[0]
2365 return build.Generator(self.environment, exe_prg, **kwargs)
2366
2367 @typed_pos_args('benchmark', str, (build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex))
2368 @typed_kwargs('benchmark', *TEST_KWS)
2369 def func_benchmark(self, node: mparser.BaseNode,
2370 args: T.Tuple[str, T.Union[build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex]],
2371 kwargs: 'kwtypes.FuncBenchmark') -> None:
2372 self.add_test(node, args, kwargs, False)
2373
2374 @typed_pos_args('test', str, (build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex))
2375 @typed_kwargs('test', *TEST_KWS, KwargInfo('is_parallel', bool, default=True))
2376 def func_test(self, node: mparser.BaseNode,
2377 args: T.Tuple[str, T.Union[build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex]],
2378 kwargs: 'kwtypes.FuncTest') -> None:
2379 self.add_test(node, args, kwargs, True)
2380
2381 def make_test(self, node: mparser.BaseNode,
2382 args: T.Tuple[str, T.Union[build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex]],
2383 kwargs: kwtypes.FuncTest | kwtypes.FuncBenchmark,
2384 klass: T.Type[TestClass] = Test) -> TestClass: # type: ignore[assignment]
2385 name = args[0]
2386 if ':' in name:
2387 mlog.deprecation(f'":" is not allowed in test name "{name}", it has been replaced with "_"',
2388 location=node)
2389 name = name.replace(':', '_')
2390 exe = args[1]
2391 if isinstance(exe, Program) and not exe.found():
2392 raise InvalidArguments('Tried to use not-found external program as test exe')
2393 elif isinstance(exe, mesonlib.File):
2394 exe = self.find_program_impl([exe])
2395 if isinstance(exe, (build.Executable, build.CustomTarget, build.CustomTargetIndex)):
2396 kwargs.setdefault('depends', []).append(exe.get_target())
2397
2398 if kwargs['timeout'] <= 0:
2399 FeatureNew.single_use('test() timeout <= 0', '0.57.0', self.subproject, location=node)
2400
2401 expected_fail = False
2402 if kwargs['should_fail'] is not None and kwargs['expected_fail'] is not None:
2403 raise InvalidArguments("Tried to use both 'should_fail' and 'expected_fail'")
2404 elif kwargs['should_fail'] is not None:
2405 expected_fail = kwargs['should_fail']
2406 elif kwargs['expected_fail'] is not None:
2407 expected_fail = kwargs['expected_fail']
2408
2409 prj = self.subproject if self.is_subproject() else self.build.project_name
2410
2411 suite: T.List[str] = []
2412 for s in kwargs['suite']:
2413 if s:
2414 s = ':' + s
2415 suite.append(prj.replace(' ', '_').replace(':', '_') + s)
2416
2417 return klass(name,
2418 prj,
2419 suite,
2420 exe,
2421 kwargs['depends'],
2422 T.cast('bool', kwargs.get('is_parallel', False)),
2423 kwargs['args'],
2424 kwargs['env'],
2425 expected_fail,
2426 kwargs['expected_exitcode'],
2427 kwargs['timeout'],
2428 kwargs['workdir'],
2429 kwargs['protocol'],
2430 kwargs['priority'],
2431 kwargs['verbose'])
2432
2433 def add_test(self, node: mparser.BaseNode,
2434 args: T.Tuple[str, T.Union[build.Executable, build.Jar, Program, mesonlib.File, build.CustomTarget, build.CustomTargetIndex]],
2435 kwargs: kwtypes.FuncTest | kwtypes.FuncBenchmark, is_base_test: bool) -> None:
2436 if isinstance(args[1], (build.CustomTarget, build.CustomTargetIndex)):
2437 FeatureNew.single_use('test with CustomTarget as command', '1.4.0', self.subproject)
2438 if any(isinstance(i, ExternalProgram) for i in kwargs['args']):
2439 FeatureNew.single_use('test with program in args', '1.6.0', self.subproject)
2440
2441 t: Test = self.make_test(node, args, kwargs)
2442 if is_base_test:
2443 self.build.tests.append(t)
2444 mlog.debug('Adding test', mlog.bold(t.name, True))
2445 else:
2446 self.build.benchmarks.append(t)
2447 mlog.debug('Adding benchmark', mlog.bold(t.name, True))
2448
2449 @typed_pos_args('install_headers', varargs=(str, mesonlib.File))
2450 @typed_kwargs(
2451 'install_headers',
2452 PRESERVE_PATH_KW,
2453 KwargInfo('subdir', (str, NoneType)),
2454 INSTALL_MODE_KW.evolve(since='0.47.0'),
2455 INSTALL_DIR_KW,
2456 INSTALL_FOLLOW_SYMLINKS,
2457 INSTALL_TAG_KW.evolve(since='1.11.0'),
2458 )
2459 def func_install_headers(self, node: mparser.BaseNode,
2460 args: T.Tuple[T.List['mesonlib.FileOrString']],
2461 kwargs: 'kwtypes.FuncInstallHeaders') -> list[build.Headers]:
2462 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2463 source_files = self.source_strings_to_files(args[0])
2464 install_subdir = kwargs['subdir']
2465 if install_subdir is not None:
2466 if kwargs['install_dir'] is not None:
2467 raise InterpreterException('install_headers: cannot specify both "install_dir" and "subdir". Use only "install_dir".')
2468 if path_has_root(install_subdir):
2469 mlog.deprecation('Subdir keyword must not be an absolute path. This will be a hard error in meson 2.0.')
2470 else:
2471 install_subdir = ''
2472
2473 dirs = collections.defaultdict(list)
2474 ret_headers: list[build.Headers] = []
2475 if kwargs['preserve_path']:
2476 for file in source_files:
2477 dirname = os.path.dirname(file.fname)
2478 dirs[dirname].append(file)
2479 else:
2480 dirs[''].extend(source_files)
2481
2482 for childdir in dirs:
2483 h = build.Headers(dirs[childdir], os.path.join(install_subdir, childdir), kwargs['install_dir'],
2484 install_mode, self.subproject,
2485 follow_symlinks=kwargs['follow_symlinks'],
2486 install_tag=kwargs['install_tag'])
2487 ret_headers.append(h)
2488 if not self.is_internal_machine(MachineChoice.HOST):
2489 self.build.headers.append(h)
2490
2491 return ret_headers
2492
2493 @typed_pos_args('install_man', varargs=(str, mesonlib.File))
2494 @typed_kwargs(
2495 'install_man',
2496 KwargInfo('locale', (str, NoneType), since='0.58.0'),
2497 INSTALL_MODE_KW.evolve(since='0.47.0'),
2498 INSTALL_DIR_KW,
2499 INSTALL_TAG_KW.evolve(since='1.11.0')
2500 )
2501 def func_install_man(self, node: mparser.BaseNode,
2502 args: T.Tuple[T.List['mesonlib.FileOrString']],
2503 kwargs: 'kwtypes.FuncInstallMan') -> build.Man:
2504 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2505 # We just need to narrow this, because the input is limited to files and
2506 # Strings as inputs, so only Files will be returned
2507 sources = self.source_strings_to_files(args[0])
2508 for s in sources:
2509 try:
2510 num = int(s.rsplit('.', 1)[-1])
2511 except (IndexError, ValueError):
2512 num = 0
2513 if not 1 <= num <= 9:
2514 raise InvalidArguments('Man file must have a file extension of a number between 1 and 9')
2515
2516 m = build.Man(sources, kwargs['install_dir'], install_mode,
2517 self.subproject, kwargs['locale'], kwargs['install_tag'])
2518 if not self.is_internal_machine(MachineChoice.HOST):
2519 self.build.man.append(m)
2520
2521 return m
2522
2523 @FeatureNew('install_emptydir', '0.60.0')
2524 @typed_kwargs(
2525 'install_emptydir',
2526 INSTALL_MODE_KW,
2527 KwargInfo('install_tag', (str, NoneType), since='0.62.0')
2528 )
2529 def func_install_emptydir(self, node: mparser.BaseNode, args: T.Tuple[str],
2530 kwargs: kwtypes.FuncInstallEmptyDir) -> build.EmptyDir:
2531 d = build.EmptyDir(args[0], kwargs['install_mode'], self.subproject, kwargs['install_tag'])
2532 if not self.is_internal_machine(MachineChoice.HOST):
2533 self.build.emptydir.append(d)
2534 return d
2535
2536 @FeatureNew('install_symlink', '0.61.0')
2537 @typed_pos_args('symlink_name', str)
2538 @typed_kwargs(
2539 'install_symlink',
2540 KwargInfo('pointing_to', str, required=True),
2541 KwargInfo('install_dir', str, required=True),
2542 INSTALL_TAG_KW,
2543 )
2544 def func_install_symlink(self, node: mparser.BaseNode,
2545 args: T.Tuple[str],
2546 kwargs: kwtypes.FuncInstallSymlink) -> build.SymlinkData:
2547 name = args[0] # Validation while creating the SymlinkData object
2548 target = kwargs['pointing_to']
2549 l = build.SymlinkData(target, name, kwargs['install_dir'],
2550 self.subproject, kwargs['install_tag'])
2551 if not self.is_internal_machine(MachineChoice.HOST):
2552 self.build.symlinks.append(l)
2553 return l
2554
2555 @FeatureNew('structured_sources', '0.62.0')
2556 @typed_pos_args('structured_sources', object, optargs=[dict])
2557 @noKwargs
2558 @noArgsFlattening
2559 def func_structured_sources(
2560 self, node: mparser.BaseNode,
2561 args: T.Tuple[object, T.Optional[T.Dict[str, object]]],
2562 kwargs: 'TYPE_kwargs') -> build.StructuredSources:
2563 valid_types = (str, mesonlib.File, build.GeneratedList, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)
2564 sources: T.DefaultDict[str, T.List[T.Union[build.TargetSources]]] = collections.defaultdict(list)
2565
2566 for arg in mesonlib.listify(args[0]):
2567 if not isinstance(arg, valid_types):
2568 raise InvalidArguments(f'structured_sources: type "{type(arg)}" is not valid')
2569 if isinstance(arg, str):
2570 arg = mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, arg)
2571 sources[''].append(arg)
2572 if args[1]:
2573 if '' in args[1]:
2574 raise InvalidArguments('structured_sources: keys to dictionary argument may not be an empty string.')
2575 for k, v in args[1].items():
2576 for arg in mesonlib.listify(v):
2577 if not isinstance(arg, valid_types):
2578 raise InvalidArguments(f'structured_sources: type "{type(arg)}" is not valid')
2579 if isinstance(arg, str):
2580 arg = mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, arg)
2581 sources[k].append(arg)
2582 return build.StructuredSources(sources)
2583
2584 @typed_pos_args('subdir', str)
2585 @typed_kwargs(
2586 'subdir',
2587 KwargInfo(
2588 'if_found',
2589 ContainerTypeInfo(list, object),
2590 validator=lambda a: 'Objects must have a found() method' if not all(hasattr(x, 'found') for x in a) else None,
2591 since='0.44.0',
2592 default=[],
2593 listify=True,
2594 ),
2595 )
2596 def func_subdir(self, node: mparser.BaseNode, args: T.Tuple[str], kwargs: 'kwtypes.Subdir') -> None:
2597 mesonlib.check_direntry_issues(args)
2598 if '..' in args[0]:
2599 raise InvalidArguments('Subdir contains ..')
2600 if self.subdir == '' and args[0] == self.subproject_dir:
2601 raise InvalidArguments('Must not go into subprojects dir with subdir(), use subproject() instead.')
2602 if self.subdir == '' and args[0].startswith('meson-'):
2603 raise InvalidArguments('The "meson-" prefix is reserved and cannot be used for top-level subdir().')
2604 if args[0] == '':
2605 raise InvalidArguments("The argument given to subdir() is the empty string ''. This is prohibited.")
2606 if path_has_root(args[0]):
2607 raise InvalidArguments('Subdir argument must be a relative path.')
2608 for i in kwargs['if_found']:
2609 if not i.found():
2610 return
2611
2612 subdir, is_new = self._resolve_subdir(self.environment.get_source_dir(), args[0])
2613 if not is_new:
2614 raise InvalidArguments(f'Tried to enter directory "{subdir}", which has already been visited.')
2615
2616 self.create_build_subdir(subdir)
2617
2618 if InterpreterRuleRelaxation.CARGO_SUBDIR in self.relaxations and \
2619 os.path.exists(os.path.join(self.environment.get_source_dir(), subdir, 'Cargo.toml')):
2620 codeblock = self.cargo.interpret(subdir, self.root_subdir)
2621 self._save_ast(subdir, codeblock)
2622 self._evaluate_codeblock(codeblock, subdir)
2623 elif not self._evaluate_subdir(self.environment.get_source_dir(), subdir):
2624 buildfilename = os.path.join(subdir, environment.build_filename)
2625 raise InterpreterException(f"Nonexistent build file '{buildfilename!s}'")
2626
2627 # This is either ignored on basically any OS nowadays, or silently gets
2628 # ignored (Solaris) or triggers an "illegal operation" error (FreeBSD).
2629 # It was likely added "because it exists", but should never be used. In
2630 # theory it is useful for directories, but we never apply modes to
2631 # directories other than in install_emptydir.
2632 def _warn_kwarg_install_mode_sticky(self, mode: FileMode) -> FileMode:
2633 if mode.perms > 0 and mode.perms & stat.S_ISVTX:
2634 mlog.deprecation('install_mode with the sticky bit on a file does not do anything and will '
2635 'be ignored since Meson 0.64.0', location=self.current_node)
2636 perms = stat.filemode(mode.perms - stat.S_ISVTX)[1:]
2637 return FileMode(perms, mode.owner, mode.group)
2638 else:
2639 return mode
2640
2641 @typed_pos_args('install_data', varargs=(str, mesonlib.File))
2642 @typed_kwargs(
2643 'install_data',
2644 KwargInfo('sources', ContainerTypeInfo(list, (str, mesonlib.File)), listify=True, default=[]),
2645 KwargInfo('rename', ContainerTypeInfo(list, str), default=[], listify=True, since='0.46.0'),
2646 INSTALL_MODE_KW.evolve(since='0.38.0'),
2647 INSTALL_TAG_KW.evolve(since='0.60.0'),
2648 INSTALL_DIR_KW,
2649 PRESERVE_PATH_KW.evolve(since='0.64.0'),
2650 INSTALL_FOLLOW_SYMLINKS,
2651 )
2652 def func_install_data(self, node: mparser.BaseNode,
2653 args: T.Tuple[T.List['mesonlib.FileOrString']],
2654 kwargs: 'kwtypes.FuncInstallData') -> list[build.Data]:
2655 sources = self.source_strings_to_files(args[0] + kwargs['sources'])
2656 rename = kwargs['rename'] or None
2657 if rename:
2658 if len(rename) != len(sources):
2659 raise InvalidArguments(
2660 '"rename" and "sources" argument lists must be the same length if "rename" is given. '
2661 f'Rename has {len(rename)} elements and sources has {len(sources)}.')
2662
2663 install_dir = kwargs['install_dir']
2664 if not install_dir:
2665 subdir = self.active_projectname
2666 install_dir = P_OBJ.OptionString(os.path.join(self.environment.get_datadir(), subdir), os.path.join('{datadir}', subdir))
2667 if self.is_subproject():
2668 FeatureNew.single_use('install_data() without install_dir inside of a subproject', '1.3.0', self.subproject,
2669 'This was broken and would install to the project name of the parent project instead',
2670 node)
2671 if kwargs['preserve_path']:
2672 FeatureNew.single_use('install_data() with preserve_path and without install_dir', '1.3.0', self.subproject,
2673 'This was broken and would not add the project name to the install path',
2674 node)
2675
2676 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2677 return self.install_data_impl(sources, install_dir, install_mode, rename, kwargs['install_tag'],
2678 preserve_path=kwargs['preserve_path'],
2679 follow_symlinks=kwargs['follow_symlinks'])
2680
2681 def install_data_impl(self, sources: T.List[mesonlib.File], install_dir: str,
2682 install_mode: FileMode, rename: T.Optional[T.List[str]],
2683 tag: T.Optional[str],
2684 install_data_type: T.Optional[str] = None,
2685 preserve_path: bool = False,
2686 follow_symlinks: T.Optional[bool] = None) -> list[build.Data]:
2687 install_dir_name = install_dir.optname if isinstance(install_dir, P_OBJ.OptionString) else install_dir
2688 dirs = collections.defaultdict(list)
2689 if preserve_path:
2690 for file in sources:
2691 dirname = os.path.dirname(file.fname)
2692 dirs[dirname].append(file)
2693 else:
2694 dirs[''].extend(sources)
2695
2696 ret_data: list[build.Data] = []
2697 for childdir, files in dirs.items():
2698 d = build.Data(files, os.path.join(install_dir, childdir), os.path.join(install_dir_name, childdir),
2699 install_mode, self.subproject, rename, tag, install_data_type,
2700 follow_symlinks)
2701 ret_data.append(d)
2702
2703 if not self.is_internal_machine(MachineChoice.HOST):
2704 self.build.data.extend(ret_data)
2705 return ret_data
2706
2707 @typed_pos_args('install_subdir', str)
2708 @typed_kwargs(
2709 'install_subdir',
2710 KwargInfo('install_dir', str, required=True),
2711 KwargInfo('strip_directory', bool, default=False),
2712 KwargInfo('exclude_files', ContainerTypeInfo(list, str),
2713 default=[], listify=True, since='0.42.0',
2714 validator=lambda x: 'cannot be absolute' if any(path_has_root(d) for d in x) else None),
2715 KwargInfo('exclude_directories', ContainerTypeInfo(list, str),
2716 default=[], listify=True, since='0.42.0',
2717 validator=lambda x: 'cannot be absolute' if any(path_has_root(d) for d in x) else None),
2718 INSTALL_MODE_KW.evolve(since='0.38.0'),
2719 INSTALL_TAG_KW.evolve(since='0.60.0'),
2720 INSTALL_FOLLOW_SYMLINKS,
2721 )
2722 def func_install_subdir(self, node: mparser.BaseNode, args: T.Tuple[str],
2723 kwargs: 'kwtypes.FuncInstallSubdir') -> build.InstallDir:
2724 exclude = (set(kwargs['exclude_files']), set(kwargs['exclude_directories']))
2725
2726 srcdir = os.path.join(self.environment.source_dir, self.subdir, args[0])
2727 if not os.path.isdir(srcdir) or not any(os.listdir(srcdir)):
2728 FeatureNew.single_use('install_subdir with empty directory', '0.47.0', self.subproject, location=node)
2729 FeatureDeprecated.single_use('install_subdir with empty directory', '0.60.0', self.subproject,
2730 'It worked by accident and is buggy. Use install_emptydir instead.', node)
2731 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2732
2733 idir_name = kwargs['install_dir']
2734 if isinstance(idir_name, P_OBJ.OptionString):
2735 idir_name = idir_name.optname
2736
2737 idir = build.InstallDir(
2738 self.subdir,
2739 args[0],
2740 kwargs['install_dir'],
2741 idir_name,
2742 install_mode,
2743 exclude,
2744 kwargs['strip_directory'],
2745 self.subproject,
2746 install_tag=kwargs['install_tag'],
2747 follow_symlinks=kwargs['follow_symlinks'])
2748 if not self.is_internal_machine(MachineChoice.HOST):
2749 self.build.install_dirs.append(idir)
2750 return idir
2751
2752 def validate_build_subdir(self, build_subdir: str, target: str) -> None:
2753 if build_subdir and build_subdir != '.':
2754 if os.path.exists(os.path.join(self.source_root, self.subdir, build_subdir)):
2755 raise InvalidArguments(f'Build subdir "{build_subdir}" in "{target}" exists in source tree.')
2756 if '..' in build_subdir:
2757 raise InvalidArguments(f'Build subdir "{build_subdir}" in "{target}" contains ..')
2758 self.create_build_subdir(os.path.join(self.subdir, build_subdir))
2759
2760 @noPosargs
2761 @typed_kwargs(
2762 'configure_file',
2763 DEPFILE_KW.evolve(since='0.52.0'),
2764 INSTALL_MODE_KW.evolve(since='0.47.0,'),
2765 INSTALL_TAG_KW.evolve(since='0.60.0'),
2766 KwargInfo('capture', bool, default=False, since='0.41.0'),
2767 KwargInfo(
2768 'command',
2769 (ContainerTypeInfo(list, (build.Executable, Program, compilers.Compiler, mesonlib.File, str), allow_empty=False), NoneType),
2770 listify=True,
2771 ),
2772 KwargInfo(
2773 'configuration',
2774 (ContainerTypeInfo(dict, (str, int, bool)), build.ConfigurationData, NoneType),
2775 ),
2776 KwargInfo(
2777 'copy', bool, default=False, since='0.47.0',
2778 ),
2779 KwargInfo('encoding', str, default='utf-8', since='0.47.0'),
2780 KwargInfo('format', str, default='meson', since='0.46.0',
2781 validator=in_set_validator({'meson', 'cmake', 'cmake@'})),
2782 KwargInfo(
2783 'input',
2784 ContainerTypeInfo(list, (mesonlib.File, str)),
2785 listify=True,
2786 default=[],
2787 ),
2788 # Cannot use shared implementation until None backwards compat is dropped
2789 KwargInfo('install', (bool, NoneType), since='0.50.0'),
2790 KwargInfo('install_dir', (str, bool), default='',
2791 validator=lambda x: 'must be `false` if boolean' if x is True else None),
2792 OUTPUT_KW,
2793 KwargInfo('output_format', str, default='c', since='0.47.0', since_values={'json': '1.3.0'},
2794 validator=in_set_validator({'c', 'json', 'nasm'})),
2795 KwargInfo('macro_name', (str, NoneType), default=None, since='1.3.0'),
2796 KwargInfo('build_subdir', str, default='', since='1.10.0'),
2797 )
2798 @apply_machine_map
2799 def func_configure_file(self, node: mparser.BaseNode, args: T.List[TYPE_var],
2800 kwargs: kwtypes.ConfigureFile) -> mesonlib.File:
2801 actions = sorted(x for x in ('configuration', 'command', 'copy')
2802 if kwargs[x] not in [None, False]) # type: ignore[literal-required]
2803 num_actions = len(actions)
2804 if num_actions == 0:
2805 raise InterpreterException('Must specify an action with one of these '
2806 'keyword arguments: \'configuration\', '
2807 '\'command\', or \'copy\'.')
2808 elif num_actions == 2:
2809 raise InterpreterException('Must not specify both {!r} and {!r} '
2810 'keyword arguments since they are '
2811 'mutually exclusive.'.format(*actions))
2812 elif num_actions == 3:
2813 raise InterpreterException('Must specify one of {!r}, {!r}, and '
2814 '{!r} keyword arguments since they are '
2815 'mutually exclusive.'.format(*actions))
2816
2817 if kwargs['capture'] and not kwargs['command']:
2818 raise InvalidArguments('configure_file: "capture" keyword requires "command" keyword.')
2819
2820 install_mode = self._warn_kwarg_install_mode_sticky(kwargs['install_mode'])
2821
2822 fmt = kwargs['format']
2823 output_format = kwargs['output_format']
2824 depfile = kwargs['depfile']
2825
2826 # Validate input
2827 inputs = self.source_strings_to_files(kwargs['input'])
2828 inputs_abs = []
2829 for f in inputs:
2830 if isinstance(f, mesonlib.File):
2831 inputs_abs.append(f.absolute_path(self.environment.source_dir,
2832 self.environment.build_dir))
2833 self.add_build_def_file(f)
2834 else:
2835 raise InterpreterException('Inputs can only be strings or file objects')
2836
2837 # Validate output
2838 output = kwargs['output']
2839 if inputs_abs:
2840 values = mesonlib.get_filenames_templates_dict(inputs_abs, None)
2841 outputs = mesonlib.substitute_values([output], values)
2842 output = outputs[0]
2843 if depfile:
2844 depfile = mesonlib.substitute_values([depfile], values)[0]
2845
2846 # Validate build_subdir
2847 build_subdir = kwargs['build_subdir']
2848 self.validate_build_subdir(build_subdir, output)
2849
2850 ofile_rpath = os.path.join(self.subdir, build_subdir, output)
2851 if ofile_rpath in self.configure_file_outputs:
2852 mesonbuildfile = os.path.join(self.subdir, 'meson.build')
2853 current_call = f"{mesonbuildfile}:{self.current_node.lineno}"
2854 first_call = "{}:{}".format(mesonbuildfile, self.configure_file_outputs[ofile_rpath])
2855 mlog.warning('Output file', mlog.bold(ofile_rpath, True), 'for configure_file() at', current_call, 'overwrites configure_file() output at', first_call)
2856 else:
2857 self.configure_file_outputs[ofile_rpath] = self.current_node.lineno
2858
2859 ofile_path, ofile_fname = os.path.split(ofile_rpath)
2860 ofile_abs = os.path.join(self.environment.build_dir, ofile_rpath)
2861 os.makedirs(os.path.split(ofile_abs)[0], exist_ok=True)
2862
2863 # Perform the appropriate action
2864 if kwargs['configuration'] is not None:
2865 conf = kwargs['configuration']
2866 if isinstance(conf, dict):
2867 FeatureNew.single_use('configure_file.configuration dictionary', '0.49.0', self.subproject, location=node)
2868 for k, v in conf.items():
2869 if not isinstance(v, (str, int, bool)):
2870 raise InvalidArguments(
2871 f'"configuration_data": initial value dictionary key "{k!r}"" must be "str | int | bool", not "{v!r}"')
2872 conf = build.ConfigurationData(conf)
2873 mlog.log('Configuring', mlog.bold(os.path.join(build_subdir, output)), 'using configuration')
2874 if len(inputs) > 1:
2875 raise InterpreterException('At most one input file can given in configuration mode')
2876 if inputs:
2877 file_encoding = kwargs['encoding']
2878 missing_variables, confdata_useless = \
2879 mesonlib.do_conf_file(inputs_abs[0], ofile_abs, conf,
2880 fmt, file_encoding, self.subproject)
2881 if missing_variables:
2882 var_list = ", ".join(repr(m) for m in sorted(missing_variables))
2883 mlog.warning(
2884 f"The variable(s) {var_list} in the input file '{inputs[0]}' are not "
2885 "present in the given configuration data.", location=node)
2886 if confdata_useless:
2887 ifbase = os.path.basename(inputs_abs[0])
2888 tv = FeatureNew.get_target_version(self.subproject)
2889 if FeatureNew.check_version(tv, '0.47'):
2890 mlog.warning('Got an empty configuration_data() object and found no '
2891 f'substitutions in the input file {ifbase!r}. If you want to '
2892 'copy a file to the build dir, use the \'copy:\' keyword '
2893 'argument added in 0.47.0', location=node)
2894 else:
2895 macro_name = kwargs['macro_name']
2896 mesonlib.dump_conf_header(ofile_abs, conf, output_format, macro_name)
2897 conf.used = True
2898 elif kwargs['command'] is not None:
2899 if len(inputs) > 1:
2900 FeatureNew.single_use('multiple inputs in configure_file()', '0.52.0', self.subproject, location=node)
2901 # We use absolute paths for input and output here because the cwd
2902 # that the command is run from is 'unspecified', so it could change.
2903 # Currently it's builddir/subdir for in_builddir else srcdir/subdir.
2904 values = mesonlib.get_filenames_templates_dict(inputs_abs, [ofile_abs])
2905 if depfile:
2906 depfile = os.path.join(self.environment.get_scratch_dir(), depfile)
2907 values['@DEPFILE@'] = depfile
2908 # Substitute @INPUT@, @OUTPUT@, etc here.
2909 _cmd = mesonlib.substitute_values(kwargs['command'], values)
2910 mlog.log('Configuring', mlog.bold(output), 'with command')
2911 cmd, *_args = _cmd
2912 res = self.run_command_impl((cmd, _args),
2913 {'capture': True,
2914 'console': False,
2915 'check': True,
2916 'env': mesonlib.EnvironmentVariables()},
2917 True)
2918 if kwargs['capture']:
2919 dst_tmp = ofile_abs + '~'
2920 file_encoding = kwargs['encoding']
2921 with open(dst_tmp, 'w', encoding=file_encoding) as f:
2922 f.writelines(res.stdout)
2923 if inputs_abs:
2924 shutil.copymode(inputs_abs[0], dst_tmp)
2925 mesonlib.replace_if_different(ofile_abs, dst_tmp)
2926 if depfile:
2927 mlog.log('Reading depfile:', mlog.bold(depfile))
2928 with open(depfile, encoding='utf-8') as f:
2929 df = DepFile(f.readlines())
2930 deps = df.get_all_dependencies(ofile_fname)
2931 for dep in deps:
2932 self.add_build_def_file(dep)
2933
2934 elif kwargs['copy']:
2935 if len(inputs_abs) != 1:
2936 raise InterpreterException('Exactly one input file must be given in copy mode')
2937 self.create_build_subdir(self.subdir)
2938 shutil.copy2(inputs_abs[0], ofile_abs)
2939
2940 # Install file if requested, we check for the empty string
2941 # for backwards compatibility. That was the behaviour before
2942 # 0.45.0 so preserve it.
2943 idir = kwargs['install_dir']
2944 if idir is False:
2945 idir = ''
2946 FeatureDeprecated.single_use('configure_file install_dir: false', '0.50.0',
2947 self.subproject, 'Use the `install:` kwarg instead', location=node)
2948 install = kwargs['install'] if kwargs['install'] is not None else idir != ''
2949 if install:
2950 if not idir:
2951 raise InterpreterException(
2952 '"install_dir" must be specified when "install" in a configure_file is true')
2953 idir_name = idir
2954 if isinstance(idir_name, P_OBJ.OptionString):
2955 idir_name = idir_name.optname
2956 cfile = mesonlib.File.from_built_file(ofile_path, ofile_fname)
2957 install_tag = kwargs['install_tag']
2958 self.build.data.append(build.Data([cfile], idir, idir_name, install_mode, self.subproject,
2959 install_tag=install_tag, data_type='configure'))
2960 return mesonlib.File.from_built_file(self.subdir, output)
2961
2962 def extract_incdirs(self, prospectives: T.List[T.Union[str, build.IncludeDirs]],
2963 is_d_import_dirs: bool = False
2964 ) -> T.List[build.IncludeDirs]:
2965 result: T.List[build.IncludeDirs] = []
2966 for p in prospectives:
2967 if isinstance(p, build.IncludeDirs):
2968 result.append(p)
2969 else:
2970 if is_d_import_dirs and os.path.normpath(p).startswith(self.environment.get_source_dir()):
2971 FeatureDeprecated.single_use('Building absolute path to source dir is not supported',
2972 '0.45', self.subproject,
2973 'Use a relative path instead.',
2974 location=self.current_node)
2975 p = os.path.relpath(p, os.path.join(self.environment.get_source_dir(), self.subdir))
2976 result.append(self.build_incdir_object([p]))
2977 return result
2978
2979 @typed_pos_args('include_directories', varargs=str)
2980 @typed_kwargs('include_directories', KwargInfo('is_system', bool, default=False))
2981 def func_include_directories(self, node: mparser.BaseNode, args: T.Tuple[T.List[str]],
2982 kwargs: 'kwtypes.FuncIncludeDirectories') -> build.IncludeDirs:
2983 return self.build_incdir_object(args[0], kwargs['is_system'])
2984
2985 def build_incdir_object(self, incdir_strings: T.List[str], is_system: bool = False) -> build.IncludeDirs:
2986 if not isinstance(is_system, bool):
2987 raise InvalidArguments('Is_system must be boolean.')
2988 src_root = self.environment.get_source_dir()
2989 build_root = self.environment.get_build_dir()
2990 absbase_src = os.path.join(src_root, self.subdir)
2991 absbase_build = os.path.join(build_root, self.subdir)
2992
2993 for a in incdir_strings:
2994 if path_is_in_root(Path(a), Path(src_root)):
2995 raise InvalidArguments(textwrap.dedent('''\
2996 Tried to form an absolute path to a dir in the source tree.
2997 You should not do that but use relative paths instead, for
2998 directories that are part of your project.
2999
3000 To get include path to any directory relative to the current dir do
3001
3002 incdir = include_directories(dirname)
3003
3004 After this incdir will contain both the current source dir as well as the
3005 corresponding build dir. It can then be used in any subdirectory and
3006 Meson will take care of all the busywork to make paths work.
3007
3008 Dirname can even be '.' to mark the current directory. Though you should
3009 remember that the current source and build directories are always
3010 put in the include directories by default so you only need to do
3011 include_directories('.') if you intend to use the result in a
3012 different subdirectory.
3013
3014 Note that this error message can also be triggered by
3015 external dependencies being installed within your source
3016 tree - it's not recommended to do this.
3017 '''))
3018 else:
3019 try:
3020 self.validate_within_subproject(self.subdir, a)
3021 except InterpreterException:
3022 mlog.warning('include_directories sandbox violation!', location=self.current_node)
3023 print(textwrap.dedent(f'''\
3024 The project is trying to access the directory {a!r} which belongs to a different
3025 subproject. This is a problem as it hardcodes the relative paths of these two projects.
3026 This makes it impossible to compile the project in any other directory layout and also
3027 prevents the subproject from changing its own directory layout.
3028
3029 Instead of poking directly at the internals the subproject should be executed and
3030 it should set a variable that the caller can then use. Something like:
3031
3032 # In subproject
3033 some_dep = declare_dependency(include_directories: include_directories('include'))
3034
3035 # In subproject wrap file
3036 [provide]
3037 some = some_dep
3038
3039 # In parent project
3040 some_dep = dependency('some')
3041 executable(..., dependencies: [some_dep])
3042
3043 This warning will become a hard error in a future Meson release.
3044 '''))
3045 absdir_src = os.path.join(absbase_src, a)
3046 absdir_build = os.path.join(absbase_build, a)
3047 if not os.path.isdir(absdir_src) and not os.path.isdir(absdir_build):
3048 raise InvalidArguments(f'Include dir {a} does not exist.')
3049 i = build.IncludeDirs(self.subdir, incdir_strings, is_system, self.current_build_project())
3050 return i
3051
3052 @typed_pos_args('add_test_setup', str)
3053 @typed_kwargs(
3054 'add_test_setup',
3055 KwargInfo('exe_wrapper', ContainerTypeInfo(list, (str, ExternalProgram)), listify=True, default=[]),
3056 KwargInfo('gdb', bool, default=False),
3057 KwargInfo('timeout_multiplier', int, default=1),
3058 KwargInfo('exclude_suites', ContainerTypeInfo(list, str), listify=True, default=[], since='0.57.0'),
3059 KwargInfo('is_default', bool, default=False, since='0.49.0'),
3060 ENV_KW,
3061 )
3062 def func_add_test_setup(self, node: mparser.BaseNode, args: T.Tuple[str], kwargs: 'kwtypes.AddTestSetup') -> None:
3063 setup_name = args[0]
3064 if re.fullmatch('([_a-zA-Z][_0-9a-zA-Z]*:)?[_a-zA-Z][_0-9a-zA-Z]*', setup_name) is None:
3065 raise InterpreterException('Setup name may only contain alphanumeric characters.')
3066 if ":" not in setup_name:
3067 setup_name = f'{(self.subproject if self.subproject else self.build.project_name)}:{setup_name}'
3068
3069 exe_wrapper: T.List[str] = []
3070 for i in kwargs['exe_wrapper']:
3071 if isinstance(i, str):
3072 exe_wrapper.append(i)
3073 else:
3074 if not i.found():
3075 raise InterpreterException('Tried to use non-found executable.')
3076 exe_wrapper += i.get_command()
3077
3078 timeout_multiplier = kwargs['timeout_multiplier']
3079 if timeout_multiplier <= 0:
3080 FeatureNew('add_test_setup() timeout_multiplier <= 0', '0.57.0').use(self.subproject)
3081
3082 if kwargs['is_default']:
3083 if self.build.test_setup_default_name is not None:
3084 raise InterpreterException(f'{self.build.test_setup_default_name!r} is already set as default. '
3085 'is_default can be set to true only once')
3086 self.build.test_setup_default_name = setup_name
3087 self.build.test_setups[setup_name] = build.TestSetup(exe_wrapper, kwargs['gdb'], timeout_multiplier, kwargs['env'],
3088 kwargs['exclude_suites'])
3089
3090 @typed_pos_args('add_global_arguments', varargs=str)
3091 @typed_kwargs('add_global_arguments', NATIVE_KW, LANGUAGE_KW)
3092 def func_add_global_arguments(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3093 self._add_global_arguments(node, self.build.global_args[kwargs['native']], args[0], kwargs)
3094
3095 @typed_pos_args('add_global_link_arguments', varargs=str)
3096 @typed_kwargs('add_global_link_arguments', NATIVE_KW, LANGUAGE_KW)
3097 def func_add_global_link_arguments(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3098 self._add_global_arguments(node, self.build.global_link_args[kwargs['native']], args[0], kwargs)
3099
3100 @typed_pos_args('add_project_arguments', varargs=str)
3101 @typed_kwargs('add_project_arguments', NATIVE_KW, LANGUAGE_KW)
3102 def func_add_project_arguments(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3103 self._add_project_arguments(node, self.current_build_project().project_args[kwargs['native']],
3104 args[0], kwargs)
3105
3106 @typed_pos_args('add_project_link_arguments', varargs=str)
3107 @typed_kwargs('add_project_link_arguments', NATIVE_KW, LANGUAGE_KW)
3108 def func_add_project_link_arguments(self, node: mparser.FunctionNode, args: T.Tuple[T.List[str]], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3109 self._add_project_arguments(node, self.current_build_project().project_link_args[kwargs['native']],
3110 args[0], kwargs)
3111
3112 def current_build_project(self) -> build.BuildProject:
3113 for_machine = self.build.machine_map.host
3114 return self.build.projects[for_machine][self.subproject]
3115
3116 @FeatureNew('add_project_dependencies', '0.63.0')
3117 @typed_pos_args('add_project_dependencies', varargs=dependencies.Dependency)
3118 @typed_kwargs('add_project_dependencies', NATIVE_KW, LANGUAGE_KW)
3119 def func_add_project_dependencies(self, node: mparser.FunctionNode, args: T.Tuple[T.List[dependencies.Dependency]], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3120 for_machine = kwargs['native']
3121 for lang in kwargs['language']:
3122 if lang not in self.compilers[for_machine]:
3123 raise InvalidCode(f'add_project_dependencies() called before add_language() for language "{lang}"')
3124
3125 for d in dependencies.get_leaf_external_dependencies(args[0]):
3126 compile_args = list(d.get_compile_args())
3127 system_incdir = d.get_include_type() == 'system'
3128 for i in d.get_include_dirs():
3129 for lang in kwargs['language']:
3130 comp = self.coredata.compilers[for_machine][lang]
3131 for idir in i.abs_string_list(self.environment.get_source_dir(), self.environment.get_build_dir()):
3132 compile_args.extend(comp.get_include_args(idir, system_incdir))
3133
3134 self._add_project_arguments(node, self.current_build_project().project_args[for_machine],
3135 compile_args, kwargs)
3136 self._add_project_arguments(node, self.current_build_project().project_link_args[for_machine],
3137 d.get_link_args(), kwargs)
3138
3139 def _warn_about_builtin_args(self, args: T.List[str]) -> None:
3140 # -Wpedantic is deliberately not included, since some people want to use it but not use -Wextra
3141 # see e.g.
3142 # https://github.com/mesonbuild/meson/issues/3275#issuecomment-641354956
3143 # https://github.com/mesonbuild/meson/issues/3742
3144 warnargs = ('/W1', '/W2', '/W3', '/W4', '/Wall', '-Wall', '-Wextra')
3145 optargs = ('-O0', '-O2', '-O3', '-Os', '-Oz', '/O1', '/O2', '/Os')
3146 for arg in args:
3147 if arg in warnargs:
3148 mlog.warning(f'Consider using the built-in warning_level option instead of using "{arg}".',
3149 location=self.current_node)
3150 elif arg in optargs:
3151 mlog.warning(f'Consider using the built-in optimization level instead of using "{arg}".',
3152 location=self.current_node)
3153 elif arg == '-Werror':
3154 mlog.warning(f'Consider using the built-in werror option instead of using "{arg}".',
3155 location=self.current_node)
3156 elif arg == '-g':
3157 mlog.warning(f'Consider using the built-in debug option instead of using "{arg}".',
3158 location=self.current_node)
3159 # Don't catch things like `-fsanitize-recover`
3160 elif arg in {'-fsanitize', '/fsanitize'} or arg.startswith(('-fsanitize=', '/fsanitize=')):
3161 mlog.warning(f'Consider using the built-in option for sanitizers instead of using "{arg}".',
3162 location=self.current_node)
3163 elif arg.startswith('-std=') or arg.startswith('/std:'):
3164 mlog.warning(f'Consider using the built-in option for language standard version instead of using "{arg}".',
3165 location=self.current_node)
3166
3167 def _add_global_arguments(self, node: mparser.FunctionNode, argsdict: T.Dict[Language, T.List[str]],
3168 args: T.List[str], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3169 if self.is_subproject():
3170 msg = f'Function \'{node.func_name.value}\' cannot be used in subprojects because ' \
3171 'there is no way to make that reliable.\nPlease only call ' \
3172 'this if is_subproject() returns false. Alternatively, ' \
3173 'define a variable that\ncontains your language-specific ' \
3174 'arguments and add it to the appropriate *_args kwarg ' \
3175 'in each target.'
3176 raise InvalidCode(msg)
3177 frozen = self.project_args_frozen or self.global_args_frozen
3178 self._add_arguments(node, argsdict, frozen, args, kwargs)
3179
3180 def _add_project_arguments(self, node: mparser.FunctionNode, argsdict: T.Dict[Language, T.List[str]],
3181 args: T.List[str], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3182 self._add_arguments(node, argsdict, self.project_args_frozen, args, kwargs)
3183
3184 def _add_arguments(self, node: mparser.FunctionNode, argsdict: T.Dict[Language, T.List[str]],
3185 args_frozen: bool, args: T.List[str], kwargs: 'kwtypes.FuncAddProjectArgs') -> None:
3186 if args_frozen:
3187 msg = f'Tried to use \'{node.func_name.value}\' after a build target has been declared.\n' \
3188 'This is not permitted. Please declare all arguments before your targets.'
3189 raise InvalidCode(msg)
3190
3191 self._warn_about_builtin_args(args)
3192
3193 for lang in kwargs['language']:
3194 argsdict[lang] = argsdict.get(lang, []) + args
3195
3196 @noArgsFlattening
3197 @typed_pos_args('environment', optargs=[(str, list, dict)])
3198 @typed_kwargs('environment', ENV_METHOD_KW, ENV_SEPARATOR_KW.evolve(since='0.62.0'))
3199 def func_environment(self, node: mparser.FunctionNode, args: T.Tuple[T.Union[None, str, T.List['TYPE_var'], T.Dict[str, 'TYPE_var']]],
3200 kwargs: kwtypes.FuncEnvironment) -> EnvironmentVariables:
3201 init = args[0]
3202 if init is not None:
3203 FeatureNew.single_use('environment positional arguments', '0.52.0', self.subproject, location=node)
3204 msg = ENV_KW.validator(init)
3205 if msg:
3206 raise InvalidArguments(f'"environment": {msg}')
3207 if isinstance(init, dict) and any(i for i in init.values() if isinstance(i, list)):
3208 FeatureNew.single_use('List of string in dictionary value', '0.62.0', self.subproject, location=node)
3209 # the validator call above ensured that we have the correct type
3210 return env_convertor_with_method(T.cast('FullEnvInitValueType', init), kwargs['method'], kwargs['separator'])
3211 return EnvironmentVariables()
3212
3213 @typed_pos_args('join_paths', varargs=str, min_varargs=1)
3214 @noKwargs
3215 def func_join_paths(self, node: mparser.BaseNode, args: T.Tuple[T.List[str]], kwargs: 'TYPE_kwargs') -> str:
3216 parts = args[0]
3217 other = os.path.join('', *parts[1:]).replace('\\', '/')
3218 ret = os.path.join(*parts).replace('\\', '/')
3219 if isinstance(parts[0], P_OBJ.DependencyVariableString) and '..' not in other:
3220 return P_OBJ.DependencyVariableString(ret)
3221 elif isinstance(parts[0], P_OBJ.OptionString):
3222 name = os.path.join(parts[0].optname, other)
3223 return P_OBJ.OptionString(ret, name)
3224 else:
3225 return ret
3226
3227 def run(self) -> None:
3228 super().run()
3229 mlog.log('Build targets in project:', mlog.bold(str(len(self.build.targets))))
3230 FeatureNew.report(self.subproject)
3231 FeatureDeprecated.report(self.subproject)
3232 FeatureBroken.report(self.subproject)
3233 if not self.is_subproject():
3234 self.print_extra_warnings()
3235 self._print_summary()
3236
3237 def print_extra_warnings(self) -> None:
3238 # TODO cross compilation
3239 for c in self.coredata.compilers.host.values():
3240 if c.get_id() == 'clang':
3241 self.check_clang_asan_lundef()
3242 break
3243
3244 def check_clang_asan_lundef(self) -> None:
3245 if OptionKey('b_lundef') not in self.coredata.optstore:
3246 return
3247 if OptionKey('b_sanitize') not in self.coredata.optstore:
3248 return
3249 if (self.coredata.optstore.get_value_for('b_lundef') and
3250 self.coredata.optstore.get_value_for('b_sanitize')):
3251 value = self.coredata.optstore.get_value_for('b_sanitize')
3252 assert isinstance(value, list), 'for mypy'
3253 mlog.warning(textwrap.dedent(f'''\
3254 Trying to use {value} sanitizer on Clang with b_lundef.
3255 This will probably not work.
3256 Try setting b_lundef to false instead.'''),
3257 location=self.current_node) # noqa: E128
3258
3259 # Check that the indicated file is within the same subproject
3260 # as we currently are. This is to stop people doing
3261 # nasty things like:
3262 #
3263 # f = files('../../master_src/file.c')
3264 #
3265 # Note that this is validated only when the file
3266 # object is generated. The result can be used in a different
3267 # subproject than it is defined in (due to e.g. a
3268 # declare_dependency).
3269 def validate_within_subproject(self, subdir: str, fname: str) -> None:
3270 srcdir = self.environment.source_dir
3271 builddir = self.environment.build_dir
3272 if isinstance(fname, P_OBJ.DependencyVariableString):
3273 def validate_installable_file(fpath: Path) -> bool:
3274 installablefiles: T.Set[Path] = set()
3275 for d in self.build.data:
3276 for s in d.sources:
3277 installablefiles.add(Path(s.absolute_path(srcdir, builddir)))
3278 installabledirs = [str(Path(srcdir, s.source_subdir)) for s in self.build.install_dirs]
3279 if fpath in installablefiles:
3280 return True
3281 for d in installabledirs:
3282 if str(fpath).startswith(d):
3283 return True
3284 return False
3285
3286 norm = Path(fname)
3287 # variables built from a dep.get_variable are allowed to refer to
3288 # subproject files, as long as they are scheduled to be installed.
3289 if validate_installable_file(norm):
3290 return
3291
3292 def do_validate_within_subproject(norm: str) -> None:
3293 if os.path.isdir(norm):
3294 inputtype = 'directory'
3295 else:
3296 inputtype = 'file'
3297 if is_parent_path(builddir, norm):
3298 raise BuiltFileByNameError(fname)
3299
3300 if not is_parent_path(srcdir, norm):
3301 # Grabbing files outside the source tree is ok.
3302 # This is for vendor stuff like:
3303 #
3304 # /opt/vendorsdk/src/file_with_license_restrictions.c
3305 return
3306
3307 project_root = os.path.join(srcdir, self.root_subdir)
3308 if not is_parent_path(project_root, norm):
3309 name = os.path.basename(norm)
3310 raise SandboxViolationError(inputtype, name, subproject=False)
3311
3312 subproject_dir = os.path.join(project_root, self.subproject_dir)
3313 if is_parent_path(subproject_dir, norm):
3314 name = os.path.basename(norm)
3315 raise SandboxViolationError(inputtype, name)
3316
3317 fname = os.path.join(subdir, fname)
3318 if fname in self.validated_cache:
3319 return
3320
3321 norm = os.path.abspath(os.path.join(srcdir, fname))
3322 do_validate_within_subproject(norm)
3323 self.validated_cache.add(fname)
3324
3325 @T.overload
3326 def source_strings_to_files(self, sources: list[str]) -> list[mesonlib.File]: ...
3327
3328 @T.overload
3329 def source_strings_to_files(self, sources: list['mesonlib.FileOrString']) -> list['mesonlib.File']: ...
3330
3331 @T.overload
3332 def source_strings_to_files(self, sources: list[T.Union[mesonlib.FileOrString, build.CustomTarget, build.CustomTargetIndex]]) -> list[T.Union[mesonlib.File, build.CustomTarget, build.CustomTargetIndex]]: ...
3333
3334 @T.overload
3335 def source_strings_to_files(self, sources: list[T.Union[mesonlib.FileOrString, build.BuildTargetTypes]]) -> list[T.Union[mesonlib.File, build.BuildTargetTypes]]: ... # type: ignore[overload-overlap]
3336
3337 @T.overload
3338 def source_strings_to_files(self, sources: list[T.Union[str, build.TargetSources]]) -> list[build.TargetSources]: ...
3339
3340 @T.overload
3341 def source_strings_to_files(self, sources: list[kwtypes.CustomTargetInputs]) -> list['CustomTargetSources']: ... # type: ignore[overload-overlap]
3342
3343 @T.overload
3344 def source_strings_to_files(self, sources: list[kwtypes.BuildTargetObjects], # type: ignore[overload-overlap]
3345 ) -> list[T.Union[build.ObjectTypes, build.GeneratedTypes]]: ...
3346
3347 @T.overload
3348 def source_strings_to_files(self, sources: list[T.Union[str, build.TargetSources, build.BuildTargetTypes, build.BothLibraries, build.ExtractedObjects]], # type: ignore[overload-overlap]
3349 ) -> list[T.Union[build.TargetSources, build.BuildTargetTypes, build.BothLibraries, build.ExtractedObjects]]: ...
3350
3351 @T.overload
3352 def source_strings_to_files(self, sources: list[T.Union[str, build.TargetSources, build.StructuredSources]],
3353 ) -> list[T.Union[build.TargetSources, build.StructuredSources]]: ... # noqa: F811
3354
3355 @T.overload
3356 def source_strings_to_files(self, sources: list[SourcesVarargsType]) -> list['SourceOutputs']: ...
3357
3358 @T.overload
3359 def source_strings_to_files(self, sources: list['SourceInputs']) -> list['SourceOutputs']: ... # type: ignore[overload-cannot-match]
3360
3361 def source_strings_to_files(self,
3362 sources: T.Union[
3363 list[str],
3364 list[mesonlib.File | str],
3365 list[mesonlib.File | str | build.CustomTarget | build.CustomTargetIndex],
3366 list[mesonlib.File | str | build.BuildTargetTypes],
3367 list[str | build.TargetSources],
3368 list[str | build.TargetSources | build.StructuredSources],
3369 list[kwtypes.CustomTargetInputs],
3370 list[mesonlib.File | str | build.BuildTargetTypes | build.BothLibraries | build.ExtractedObjects | build.GeneratedTypes],
3371 list[kwtypes.BuildTargetObjects],
3372 list[SourceInputs],
3373 list[SourcesVarargsType],
3374 ]
3375 ) -> T.Union[list[mesonlib.File],
3376 list[mesonlib.File | build.BuildTargetTypes],
3377 list[mesonlib.File | build.CustomTarget | build.CustomTargetIndex],
3378 list[build.TargetSources],
3379 list[build.TargetSources | build.StructuredSources],
3380 list[mesonlib.File | build.BuildTargetTypes | build.BothLibraries | build.ExtractedObjects | build.GeneratedTypes],
3381 list[build.ObjectTypes | build.GeneratedTypes],
3382 list[CustomTargetSources],
3383 list[SourceOutputs]]:
3384 """Lower inputs to a list of Targets and Files, replacing any strings.
3385
3386 :param sources: A raw (Meson DSL) list of inputs (targets, files, and
3387 strings)
3388 :raises InterpreterException: if any of the inputs are of an invalid type
3389 :return: A list of Targets and Files
3390 """
3391 mesonlib.check_direntry_issues(sources)
3392 results: list[build.TargetSources | build.BuildTarget | build.ExtractedObjects | build.StructuredSources | Program] = []
3393
3394 for s in sources:
3395 if isinstance(s, str):
3396 if s.endswith(' '):
3397 raise MesonException(f'{s!r} ends with a space. This is probably an error.')
3398 try:
3399 self.validate_within_subproject(self.subdir, s)
3400 except BuiltFileByNameError as e:
3401 # In Meson 2.0 this should just raise
3402 if InterpreterRuleRelaxation.ALLOW_BUILD_DIR_FILE_REFERENCES not in self.relaxations:
3403 #raise
3404 mlog.warning(str(e), location=self.current_node)
3405 if path_has_root(s):
3406 # A built File's name must be relative to the build
3407 # root, otherwise the absolute fname leaks through
3408 # File.relative_name() and breaks the backend.
3409 # Use join and relpath together to handle paths without
3410 # the drive part.
3411 rel = os.path.relpath(os.path.join(self.environment.build_dir, s),
3412 self.environment.build_dir)
3413 results.append(mesonlib.File.from_built_relative(rel))
3414 else:
3415 results.append(mesonlib.File.from_built_file(self.subdir, s))
3416 else:
3417 results.append(mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, s))
3418 elif isinstance(s, (mesonlib.File, build.GeneratedList, Program,
3419 build.BuildTarget, build.CustomTargetIndex, build.CustomTarget,
3420 build.ExtractedObjects, build.StructuredSources)):
3421 results.append(s)
3422 else:
3423 raise InterpreterException(f'Source item is {s!r} instead of '
3424 'string or File-type object')
3425 return results # type: ignore[return-value]
3426
3427 def source_string_to_file(self, source: str | mesonlib.File | build.CustomTarget | build.CustomTargetIndex | None) -> mesonlib.File | build.CustomTarget | build.CustomTargetIndex:
3428 if source is None:
3429 return None
3430 return self.source_strings_to_files([source])[0]
3431
3432 def validate_forbidden_targets(self, name: str, in_root: bool) -> None:
3433 if name.startswith('meson-internal__'):
3434 raise InvalidArguments("Target names starting with 'meson-internal__' are reserved "
3435 "for Meson's internal use. Please rename.")
3436 if name.startswith('meson-') and '.' not in name:
3437 raise InvalidArguments("Target names starting with 'meson-' and without a file extension "
3438 "are reserved for Meson's internal use. Please rename.")
3439 if name in coredata.FORBIDDEN_TARGET_NAMES:
3440 if in_root:
3441 raise InvalidArguments(f"Target name '{name}' is reserved for Meson's "
3442 "internal use. Please rename.")
3443 else:
3444 FeatureNew.single_use(f"Target name '{name}' reserved in the root build directory, but allowed in subdirectories",
3445 '1.12.0', self.subproject, location=self.current_node)
3446
3447 def add_target(self, name: str, tobj: build.Target) -> None:
3448 if self.backend.name == 'none':
3449 raise InterpreterException('Install-only backend cannot generate target rules, try using `--backend=ninja`.')
3450 if name == '':
3451 raise InterpreterException('Target name must not be empty.')
3452 if name.strip() == '':
3453 raise InterpreterException('Target name must not consist only of whitespace.')
3454 if has_path_sep(name):
3455 pathseg = os.path.join(self.subdir, os.path.split(name)[0])
3456 if os.path.exists(os.path.join(self.source_root, pathseg)):
3457 raise InvalidArguments(textwrap.dedent(f'''\
3458 Target "{name}" has a path segment pointing to directory "{pathseg}". This is an error.
3459 To define a target that builds in that directory you must define it
3460 in the meson.build file in that directory.
3461 '''))
3462
3463 # Make sure build_subdir doesn't exist in the source tree and
3464 # doesn't contain ..
3465 build_subdir = tobj.get_build_subdir()
3466 self.validate_build_subdir(build_subdir, name)
3467
3468 subdir = tobj.get_builddir()
3469 self.validate_forbidden_targets(name, not subdir)
3470
3471 # To permit an executable and a shared library to have the
3472 # same name, such as "foo.exe" and "libfoo.a".
3473 idname = tobj.get_id()
3474 namedir = (name, subdir)
3475
3476 if idname in self.build.targets:
3477 raise InvalidCode(f'Tried to create target "{name}", but a target of that name already exists.')
3478
3479 if isinstance(tobj, build.Executable) and namedir in self.build.targetnames:
3480 FeatureNew.single_use(f'multiple executables with the same name, "{tobj.name}", but different suffixes in the same directory',
3481 '1.3.0', self.subproject, location=self.current_node)
3482
3483 if isinstance(tobj, build.BuildTarget):
3484 # add_languages mutates the `args` parameter, so we need to copy here
3485 self.add_languages(tobj.missing_languages.copy(), True, tobj.for_machine)
3486 tobj.process_compilers_late()
3487 self.add_stdlib_info(tobj)
3488
3489 if tobj.uses_cython():
3490 for gensrc in tobj.get_generated_sources():
3491 # a generator producing a .pyx has always worked; feeding
3492 # anything else from a generator into Cython triggered a bug
3493 # in the ninja backend and was effectively a new feature.
3494 if isinstance(gensrc, build.GeneratedList) and \
3495 any(not o.endswith('.pyx') for o in gensrc.get_outputs()):
3496 FeatureNew.single_use('Generators for non-.pyx Cython sources',
3497 '1.12.0', self.subproject, location=self.current_node)
3498 break
3499
3500 self.build.targets[idname] = tobj
3501 # Only need to add executables to this set
3502 if isinstance(tobj, build.Executable):
3503 self.build.targetnames.update([namedir])
3504 if idname not in self.coredata.target_guids:
3505 self.coredata.target_guids[idname] = str(uuid.uuid4()).upper()
3506
3507 @FeatureNew('both_libraries', '0.46.0')
3508 def build_both_libraries(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType], kwargs: kwtypes.Library) -> build.BothLibraries:
3509 shared_lib = self.build_target(node, args, kwargs, build.SharedLibrary, shared_library_only=False)
3510 static_lib = self.build_target(node, args, kwargs, build.StaticLibrary)
3511 preferred_library = self.coredata.optstore.get_value_for(OptionKey('default_both_libraries', subproject=self.subproject))
3512 assert isinstance(preferred_library, str), 'for mypy'
3513 if preferred_library == 'auto':
3514 preferred_library = self.coredata.optstore.get_value_for(OptionKey('default_library', subproject=self.subproject))
3515 assert isinstance(preferred_library, str), 'for mypy'
3516 if preferred_library == 'both':
3517 preferred_library = 'shared'
3518 assert preferred_library in {'shared', 'static'}
3519 preferred_library = T.cast('Literal["static", "shared"]', preferred_library)
3520
3521 if self.backend.name == 'xcode':
3522 # Xcode is a bit special in that you can't (at least for the moment)
3523 # form a library only from object file inputs. The simple but inefficient
3524 # solution is to use the sources directly. This will lead to them being
3525 # built twice. This is unfortunate and slow, but at least it works.
3526 # Feel free to submit patches to get this fixed if it is an
3527 # issue for you.
3528 reuse_object_files = False
3529 elif shared_lib.uses_rust():
3530 # FIXME: rustc supports generating both libraries in a single invocation,
3531 # but for now compile twice.
3532 reuse_object_files = False
3533 elif any(k.endswith(('static_args', 'shared_args')) and v for k, v in kwargs.items()):
3534 # Ensure not just the keyword arguments exist, but that they are non-empty.
3535 reuse_object_files = False
3536 else:
3537 reuse_object_files = static_lib.pic
3538
3539 if reuse_object_files:
3540 # Replace sources with objects from the shared library to avoid
3541 # building them twice. We post-process the static library instead of
3542 # removing sources from args because sources could also come from
3543 # any InternalDependency, see BuildTarget.add_deps().
3544 static_lib.objects.append(build.ExtractedObjects(shared_lib, shared_lib.sources, shared_lib.generated, []))
3545 static_lib.sources = []
3546 static_lib.generated = []
3547 # Compilers with no corresponding sources confuses the backend.
3548 # Keep only compilers used for linking
3549 static_lib.compilers = {k: v for k, v in static_lib.compilers.items() if k in compilers.clink_langs}
3550
3551 # Cross reference them to implement as_shared() and as_static() methods.
3552 shared_lib.set_static(static_lib)
3553 static_lib.set_shared(shared_lib)
3554
3555 return build.BothLibraries(shared_lib, static_lib, preferred_library)
3556
3557 def build_library(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType], kwargs: kwtypes.Library) -> build.SharedLibrary | build.BothLibraries | build.StaticLibrary:
3558 default_library = self.coredata.optstore.get_value_for(OptionKey('default_library', subproject=self.subproject))
3559 assert isinstance(default_library, str), 'for mypy'
3560 if default_library == 'shared':
3561 # Intentionally pass shared_library_only=False so that dependencies
3562 # end up in Requires.private. Many libraries that refer to their
3563 # dependencies' in their headers expect this so that those dependencies
3564 # are added to the output of 'pkgconfig --cflags'.
3565 return self.build_target(node, args, T.cast('kwtypes.SharedLibrary', kwargs), build.SharedLibrary, shared_library_only=False)
3566 elif default_library == 'static':
3567 return self.build_target(node, args, T.cast('kwtypes.StaticLibrary', kwargs), build.StaticLibrary)
3568 elif default_library == 'both':
3569 return self.build_both_libraries(node, args, kwargs)
3570 else:
3571 raise InterpreterException(f'Unknown default_library value: {default_library}.')
3572
3573 def __convert_file_args(self, raw: T.List[mesonlib.FileOrString]) -> T.Tuple[T.List[mesonlib.File], T.List[str]]:
3574 """Convert raw target arguments from File | str to File.
3575
3576 This removes files from the command line and replaces them with string
3577 values, but adds the files to depends list
3578
3579 :param raw: the raw arguments
3580 :return: A tuple of file dependencies and raw arguments
3581 """
3582 depend_files: T.List[mesonlib.File] = []
3583 args: T.List[str] = []
3584 build_to_source = mesonlib.relpath(self.environment.get_source_dir(),
3585 self.environment.get_build_dir())
3586
3587 for a in raw:
3588 if isinstance(a, mesonlib.File):
3589 depend_files.append(a)
3590 args.append(a.rel_to_builddir(build_to_source))
3591 else:
3592 args.append(a)
3593
3594 return depend_files, args
3595
3596 def __process_language_args(self, kwargs: kwtypes.BaseBuildTarget,
3597 ) -> T.Tuple[T.DefaultDict[Language, T.List[str]], T.List[mesonlib.File]]:
3598 """Convert split language args into a combined dictionary.
3599
3600 The Meson DSL takes arguments in the form `<lang>_args : args`, but in the
3601 build layer we store these in a single dictionary as `{<lang>: args}`.
3602 This function extracts the arguments from the DSL format and prepares
3603 them for the IR.
3604 """
3605 deps: T.List[mesonlib.File] = []
3606 new_args: T.DefaultDict[Language, T.List[str]] = collections.defaultdict(list)
3607
3608 for l in compilers.all_languages:
3609 deps, args = self.__convert_file_args(kwargs[f'{l}_args']) # type: ignore[literal-required]
3610 new_args[l] = args
3611 deps.extend(deps)
3612 return new_args, deps
3613
3614 @staticmethod
3615 def _handle_rust_abi(abi: T.Optional[Literal['c', 'rust']],
3616 crate_type: T.Optional[build.RustCrateType],
3617 default_rust_type: build.RustCrateType,
3618 default_c_type: build.RustCrateType, typename: str,
3619 extra_valid_types: T.Optional[T.Set[build.RustCrateType]] = None,
3620 ) -> build.RustCrateType:
3621 """Handle the interactions between the rust_abi and rust_crate_type keyword arguments.
3622
3623 :param abi: Is this using Rust ABI or C ABI
3624 :param crate_type: Is there an explicit crate type set
3625 :param default_rust_type: The default crate type to use for Rust ABI
3626 :param default_c_type: the default crate type to use for C ABI
3627 :param typename: The name of the type this argument is for
3628 :param extra_valid_types: additional valid crate types, defaults to None
3629 :raises InvalidArguments: If the crate_type argument is set, but not valid
3630 :raises InvalidArguments: If both crate_type and abi are set
3631 :return: The finalized crate type
3632 """
3633 if abi is not None:
3634 if crate_type is not None:
3635 raise InvalidArguments('rust_abi and rust_crate_type are mutually exclusive')
3636 crate_type = default_rust_type if abi == 'rust' else default_c_type
3637 elif crate_type is not None:
3638 if crate_type == 'lib':
3639 crate_type = default_rust_type
3640 valid_types = {default_rust_type, default_c_type} | (extra_valid_types or set())
3641 if crate_type not in valid_types:
3642 choices = ", " .join(f'"{c}"' for c in sorted(valid_types))
3643 raise InvalidArguments(f'Crate type for {typename} must be one of {choices}, but got "{crate_type}"')
3644 else:
3645 crate_type = default_rust_type
3646 return crate_type
3647
3648 def _exe_to_shlib_kwargs(self, kwargs: kwtypes.Executable) -> kwtypes.SharedLibrary:
3649 nkwargs = T.cast('kwtypes.SharedLibrary', kwargs.copy())
3650 for exe_kwarg in EXCLUSIVE_EXECUTABLE_KWS:
3651 del nkwargs[exe_kwarg.name] # type: ignore[misc]
3652 for sh_kwarg in SHARED_LIB_KWS:
3653 nkwargs.setdefault(sh_kwarg.name, sh_kwarg.default) # type: ignore[misc]
3654 nkwargs['rust_abi'] = None
3655 nkwargs['rust_crate_type'] = 'cdylib'
3656 return nkwargs
3657
3658 def __convert_build_target_base_kwargs(self, kwargs: kwtypes.BuildTarget, final: build.BuildTargetKeywordArguments) -> None:
3659 """Convert shared arguments for BuildTargets to the Build layer form.
3660
3661 This takes the raw DSL form, and builds a new dict in the form that the BuildTarget expects
3662
3663 :param kwargs: The arguments in raw DSL form
3664 :param final: A new dictionary to fill in with the Build layer
3665 :raises InvalidArguments: If one the PCH files doesn't exist
3666 """
3667 # copy common arguments directly
3668 for arg in ('build_by_default', 'build_rpath', 'build_subdir', 'c_pch',
3669 'cpp_pch', 'd_debug', 'd_module_versions', 'd_unittest',
3670 'dependencies', 'gnu_symbol_visibility', 'install',
3671 'install_mode', 'install_rpath',
3672 'implicit_include_directories', 'link_args', 'link_early_args',
3673 'link_language', 'link_with', 'link_whole', 'name_prefix',
3674 'name_suffix', 'native', 'resources', 'vala_header',
3675 'vala_gir', 'vala_vapi', 'swift_interoperability_mode',
3676 'swift_module_name', 'rust_crate_type',
3677 'rust_dependency_map', 'override_options'):
3678 final[arg] = kwargs[arg]
3679
3680 # this is not accessable from the DSL, so we need to initialize it
3681 # ourselves
3682 final['depend_files'] = []
3683
3684 # Check for non-existant PCH files
3685 missing: T.List[str] = []
3686 for each in itertools.chain(kwargs['c_pch'] or [], kwargs['cpp_pch'] or []):
3687 if each is not None:
3688 if not os.path.isfile(os.path.join(self.environment.source_dir, self.subdir, each)):
3689 missing.append(os.path.join(self.subdir, each))
3690 if missing:
3691 raise InvalidArguments('The following PCH files do not exist: {}'.format(', '.join(missing)))
3692
3693 final['link_depends'] = self.source_strings_to_files(kwargs['link_depends'])
3694 final['install_tag'] = [kwargs['install_tag']]
3695 final['extra_files'] = mesonlib.unique_list(self.source_strings_to_files(kwargs['extra_files']))
3696
3697 # Convert into IncludeDirs objects
3698 final['include_directories'] = self.extract_incdirs(kwargs['include_directories'])
3699 final['d_import_dirs'] = self.extract_incdirs(kwargs['d_import_dirs'], True)
3700
3701 # Convert language arguments
3702 lang_args, deps = self.__process_language_args(kwargs)
3703 final['language_args'] = lang_args
3704 final['depend_files'].extend(deps)
3705
3706 # Rewrite `install_dir : [main, vala_header, vala_vapi, vala_gir]`
3707 # Into split arguments
3708 vala_keys = ('install_vala_header', 'install_vala_vapi', 'install_vala_gir')
3709 if len(kwargs['install_dir']) > 1:
3710 if any(kwargs[k] is not None for k in vala_keys): # type: ignore[literal-required]
3711 raise InvalidArguments('Passing install_vala_* and more than one argument to install_dir are mutually exclusive')
3712
3713 install_dirs = kwargs['install_dir'].copy()
3714 install_dir = install_dirs.pop(0)
3715
3716 for key in vala_keys:
3717 action = install_dirs.pop(0) if install_dirs else False
3718 if isinstance(action, bool):
3719 final[key] = action # type: ignore[literal-required]
3720 else:
3721 final[key] = True # type: ignore[literal-required]
3722 final[f'{key}_dir'] = action # type: ignore[literal-required]
3723 final['install_dir'] = [install_dir]
3724
3725 # This was previously allowed, and tested, so we need to allow it to keep working.
3726 if final['vala_gir'] is None and final['install_vala_gir']:
3727 final['install_vala_gir'] = False
3728 else:
3729 for key in vala_keys:
3730 action = kwargs[key] # type: ignore[literal-required]
3731 if action is None:
3732 action = False
3733 if isinstance(action, bool):
3734 final[key] = action # type: ignore[literal-required]
3735 else:
3736 final[key] = True # type: ignore[literal-required]
3737 final[f'{key}_dir'] = action # type: ignore[literal-required]
3738 final['install_dir'] = [kwargs['install_dir'][0] if kwargs['install_dir'] else True]
3739
3740 def __convert_executable_kwargs(self, node: mparser.BaseNode, kwargs: kwtypes.Executable) -> build.ExecutableKeywordArguments:
3741 """Convert Executable arguments from DSL form to the build layer form.
3742
3743 :param node: The Node being evaluated
3744 :param kwargs: The DSL keyword arguments
3745 :raises InvalidArguments: If both gui_app and win_subsystem are set
3746 :raises InvalidArguments: If implib is false and export_dynamic is true
3747 :raises InvalidArguments: If the rust_crate_type is set to anything except bin
3748 :return: The keyword arguments as the Build layer expects
3749 """
3750 final: build.ExecutableKeywordArguments = {}
3751 self.__convert_build_target_base_kwargs(kwargs, final)
3752
3753 # Exe exclusive arguments
3754 for exe_arg in ('android_exe_type', 'pie'):
3755 final[exe_arg] = kwargs[exe_arg]
3756 final['vs_module_defs'] = self.source_string_to_file(kwargs['vs_module_defs'])
3757
3758 # rewrite `gui_app` to `win_subsystem`
3759 if kwargs['gui_app'] is not None:
3760 if kwargs['win_subsystem'] is not None:
3761 raise InvalidArguments.from_node(
3762 'Executable got both "gui_app", and "win_subsystem" arguments, which are mutually exclusive',
3763 node=node)
3764 final['win_subsystem'] = 'windows' if kwargs['gui_app'] else 'console'
3765 elif kwargs['win_subsystem'] is not None:
3766 final['win_subsystem'] = kwargs['win_subsystem']
3767 else:
3768 final['win_subsystem'] = 'console'
3769
3770 # handle interactions between implib and export_dynamic
3771 if kwargs['implib']:
3772 if kwargs['export_dynamic'] is False:
3773 FeatureDeprecated.single_use(
3774 'implib overrides explicit export_dynamic off', '1.3.0', self.subproject,
3775 'Do not set ths if want export_dynamic disabled if implib is enabled',
3776 location=node)
3777 kwargs['export_dynamic'] = True
3778 elif kwargs['export_dynamic']:
3779 if kwargs['implib'] is False:
3780 raise InvalidArguments.from_node(
3781 '"implib" keyword" must not be false if "export_dynamic" is set and not false.',
3782 node=node)
3783 if kwargs['export_dynamic'] is None:
3784 kwargs['export_dynamic'] = False
3785 final['export_dynamic'] = kwargs['export_dynamic']
3786
3787 if isinstance(kwargs['implib'], bool):
3788 final['implib'] = None
3789 else:
3790 final['implib'] = kwargs['implib']
3791
3792 # Handle executable speicific rust_crate_type
3793 if kwargs['rust_crate_type'] not in {None, 'bin'}:
3794 raise InvalidArguments.from_node(
3795 'Crate type for executable must be "bin"', node=node)
3796 final['rust_crate_type'] = 'bin'
3797
3798 return final
3799
3800 def __convert_static_library_kwargs(self, node: mparser.BaseNode, kwargs: kwtypes.StaticLibrary) -> build.StaticLibraryKeywordArguments:
3801 """Convert StaticLibrary arguments to the Build format.
3802
3803 :param node: The Node currently be evaluated.
3804 :param kwargs: The DSL form of the keyword arguments.
3805 :return: The arguments in Build layer format.
3806 """
3807 final: build.StaticLibraryKeywordArguments = {}
3808 self.__convert_build_target_base_kwargs(kwargs, final)
3809
3810 for arg in ('pic', 'prelink'):
3811 final[arg] = kwargs[arg]
3812
3813 for lang in compilers.all_languages - {'java'}:
3814 deps, args = self.__convert_file_args(kwargs.get(f'{lang}_static_args', [])) # type: ignore[arg-type]
3815 final['language_args'][lang].extend(args)
3816 final['depend_files'].extend(deps)
3817 final['rust_crate_type'] = self._handle_rust_abi(
3818 kwargs['rust_abi'], kwargs['rust_crate_type'], 'rlib', 'staticlib',
3819 build.StaticLibrary.typename)
3820
3821 return final
3822
3823 def __convert_shared_library_kwargs(self, node: mparser.BaseNode, kwargs: kwtypes.SharedLibrary) -> build.SharedLibraryKeywordArguments:
3824 """Convert SharedLibrary arguments to the Build format.
3825
3826 :param node: The Node currently be evaluated.
3827 :param kwargs: The DSL form of the keyword arguments.
3828 :return: The arguments in Build layer format.
3829 """
3830 final: build.SharedLibraryKeywordArguments = {}
3831 self.__convert_build_target_base_kwargs(kwargs, final)
3832
3833 for arg in ('version', 'soversion', 'darwin_versions', 'shortname'):
3834 final[arg] = kwargs[arg]
3835 final['vs_module_defs'] = self.source_string_to_file(kwargs['vs_module_defs'])
3836
3837 for lang in compilers.all_languages - {'java'}:
3838 deps, args = self.__convert_file_args(kwargs.get(f'{lang}_shared_args', [])) # type: ignore[arg-type]
3839 final['language_args'][lang].extend(args)
3840 final['depend_files'].extend(deps)
3841 final['rust_crate_type'] = self._handle_rust_abi(
3842 kwargs['rust_abi'], kwargs['rust_crate_type'], 'dylib', 'cdylib',
3843 build.SharedLibrary.typename, extra_valid_types={'proc-macro'})
3844
3845 final['win_subsystem'] = kwargs['win_subsystem'] or 'console'
3846
3847 return final
3848
3849 def __convert_shared_module_kwargs(self, node: mparser.BaseNode, kwargs: kwtypes.SharedModule) -> build.SharedModuleKeywordArguments:
3850 """Convert SharedModule arguments to the Build format.
3851
3852 :param node: The Node currently be evaluated.
3853 :param kwargs: The DSL form of the keyword arguments.
3854 :return: The arguments in Build layer format.
3855 """
3856 final: build.SharedModuleKeywordArguments = {}
3857 self.__convert_build_target_base_kwargs(kwargs, final)
3858
3859 final['vs_module_defs'] = self.source_string_to_file(kwargs['vs_module_defs'])
3860
3861 for lang in compilers.all_languages - {'java'}:
3862 deps, args = self.__convert_file_args(kwargs.get(f'{lang}_shared_args', [])) # type: ignore[arg-type]
3863 final['language_args'][lang].extend(args)
3864 final['depend_files'].extend(deps)
3865 final['rust_crate_type'] = self._handle_rust_abi(
3866 kwargs['rust_abi'], kwargs['rust_crate_type'], 'dylib', 'cdylib',
3867 build.SharedModule.typename, extra_valid_types={'proc-macro'})
3868
3869 final['win_subsystem'] = kwargs['win_subsystem'] or 'console'
3870
3871 return final
3872
3873 def __convert_jar_kwargs(self, node: mparser.BaseNode, kwargs: kwtypes.Jar) -> build.JarKeywordArguments:
3874 """Convert Jar arguments to the Build format.
3875
3876 :param node: The Node currently be evaluated.
3877 :param kwargs: The DSL form of the keyword arguments.
3878 :return: The arguments in Build layer format.
3879 """
3880 final: build.JarKeywordArguments = {}
3881
3882 # copy common arguments directly
3883 for arg in ('build_by_default', 'build_subdir', 'dependencies',
3884 'install', 'install_mode', 'implicit_include_directories',
3885 'link_with', 'java_args', 'java_resources', 'main_class',
3886 'native'):
3887 final[arg] = kwargs[arg]
3888
3889 # this is not accessable from the DSL, so we need to initialize it
3890 # ourselves
3891 final['depend_files'] = []
3892
3893 # The build layer and interpreter don't agree here, and it's not clear
3894 # that we're hanlding this correctly
3895 final['install_dir'] = kwargs['install_dir'] # type: ignore[typeddict-item]
3896 final['install_tag'] = [kwargs['install_tag']]
3897 final['extra_files'] = mesonlib.unique_list(self.source_strings_to_files(kwargs['extra_files']))
3898
3899 # Convert into IncludeDirs objects
3900 final['include_directories'] = self.extract_incdirs(kwargs['include_directories'])
3901
3902 # Convert language arguments
3903 lang_args, deps = self.__process_language_args(kwargs)
3904 final['language_args'] = lang_args
3905 final['depend_files'].extend(deps)
3906
3907 return final
3908
3909 @T.overload
3910 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3911 kwargs: kwtypes.Executable, targetclass: T.Type[build.Executable]) -> build.Executable: ...
3912
3913 @T.overload
3914 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3915 kwargs: kwtypes.StaticLibrary, targetclass: T.Type[build.StaticLibrary]) -> build.StaticLibrary: ...
3916
3917 @T.overload
3918 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3919 kwargs: kwtypes.SharedModule, targetclass: T.Type[build.SharedModule]) -> build.SharedModule: ...
3920
3921 @T.overload
3922 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3923 kwargs: kwtypes.SharedLibrary, targetclass: T.Type[build.SharedLibrary],
3924 shared_library_only: bool = True) -> build.SharedLibrary: ...
3925
3926 @T.overload
3927 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3928 kwargs: kwtypes.Jar, targetclass: T.Type[build.Jar]) -> build.Jar: ...
3929
3930 def build_target(self, node: mparser.BaseNode, args: T.Tuple[str, SourcesVarargsType],
3931 kwargs: T.Union[kwtypes.Executable, kwtypes.StaticLibrary, kwtypes.SharedLibrary, kwtypes.SharedModule, kwtypes.Jar],
3932 targetclass: T.Type[T.Union[build.Executable, build.StaticLibrary, build.SharedModule, build.SharedLibrary, build.Jar]],
3933 shared_library_only: bool = True
3934 ) -> T.Union[build.Executable, build.StaticLibrary, build.SharedModule, build.SharedLibrary, build.Jar]:
3935 if targetclass not in {build.Executable, build.SharedLibrary, build.SharedModule, build.StaticLibrary, build.Jar}:
3936 mlog.debug('Unknown target type:', str(targetclass))
3937 raise RuntimeError('Unreachable code')
3938
3939 # preserved for global and project arguments
3940 orig_for_machine = kwargs['native']
3941 self.apply_machine_map_to_kwargs(kwargs)
3942 for_machine = kwargs['native']
3943
3944 if self.environment.is_cross_build() and kwargs.get('rust_crate_type') == 'proc-macro':
3945 # Silently force to native because that's the only sensible value
3946 # and rust_crate_type is deprecated any way.
3947 for_machine = MachineChoice.BUILD
3948
3949 if targetclass is build.Executable and kwargs.get('android_exe_type') == 'application':
3950 m = self.environment.machines[for_machine]
3951 if m.is_android():
3952 # Mypy can't figure this out for some reason
3953 kwargs = T.cast('kwtypes.Executable', kwargs)
3954 return self.build_target(node, args, self._exe_to_shlib_kwargs(kwargs), build.SharedLibrary)
3955
3956 # Because who owns this isn't clear
3957 kwargs = kwargs.copy()
3958 name, raw_sources = args
3959 # Avoid mutating, since there could be other references to sources
3960 raw_sources = raw_sources + T.cast('SourcesVarargsType', kwargs['sources'])
3961 if any(isinstance(s, build.BuildTarget) for s in raw_sources):
3962 FeatureBroken.single_use('passing references to built targets as a source file', '1.1.0', self.subproject,
3963 'Consider using `link_with` or `link_whole` if you meant to link, or dropping them as otherwise they are ignored.',
3964 node)
3965 if any(isinstance(s, build.ExtractedObjects) for s in raw_sources):
3966 FeatureBroken.single_use('passing object files as sources', '1.1.0', self.subproject,
3967 'Pass these to the `objects` keyword instead, they are ignored when passed as sources.',
3968 node)
3969 # Go ahead and drop these here, since they're only allowed through for
3970 # backwards compatibility anyway
3971 sources = self.source_strings_to_files([
3972 s for s in raw_sources if not isinstance(s, (build.BuildTarget, build.ExtractedObjects))])
3973
3974 objs = self.source_strings_to_files(kwargs['objects'])
3975
3976 srcs: T.List[SourceOutputs] = []
3977 struct: T.Optional[build.StructuredSources] = build.StructuredSources()
3978 for s in sources:
3979 if isinstance(s, build.StructuredSources):
3980 struct = struct + s
3981 else:
3982 srcs.append(s)
3983
3984 if not struct:
3985 struct = None
3986 else:
3987 # Validate that we won't end up with two outputs with the same name.
3988 # i.e, don't allow:
3989 # [structured_sources('foo/bar.rs'), structured_sources('bar/bar.rs')]
3990 for v in struct.sources.values():
3991 outputs: T.Set[str] = set()
3992 for f in v:
3993 o: T.List[str]
3994 if isinstance(f, str):
3995 o = [os.path.basename(f)]
3996 elif isinstance(f, mesonlib.File):
3997 o = [f.fname]
3998 else:
3999 o = f.get_outputs()
4000 conflicts = outputs.intersection(o)
4001 if conflicts:
4002 raise InvalidArguments.from_node(
4003 f"Conflicting sources in structured sources: {', '.join(sorted(conflicts))}",
4004 node=node)
4005 outputs.update(o)
4006
4007 if targetclass is not build.Jar:
4008 self.check_for_jar_sources(sources, targetclass)
4009
4010 target: build.BuildTarget
4011 if targetclass is build.Executable:
4012 nkwargs = self.__convert_executable_kwargs(
4013 node, T.cast('kwtypes.Executable', kwargs))
4014 target = build.Executable(name, self.subdir, orig_for_machine, srcs, struct, objs,
4015 self.environment, self.compilers[for_machine], self.current_build_project(), nkwargs)
4016 elif targetclass is build.StaticLibrary:
4017 nkwargs = self.__convert_static_library_kwargs(
4018 node, T.cast('kwtypes.StaticLibrary', kwargs))
4019 target = build.StaticLibrary(name, self.subdir, orig_for_machine, srcs, struct, objs,
4020 self.environment, self.compilers[for_machine], self.current_build_project(), nkwargs)
4021 elif targetclass is build.SharedLibrary:
4022 nkwargs = self.__convert_shared_library_kwargs(
4023 node, T.cast('kwtypes.SharedLibrary', kwargs))
4024 target = build.SharedLibrary(name, self.subdir, orig_for_machine, srcs, struct, objs,
4025 self.environment, self.compilers[for_machine], self.current_build_project(), nkwargs)
4026 target.shared_library_only = shared_library_only
4027 elif targetclass is build.SharedModule:
4028 nkwargs = self.__convert_shared_module_kwargs(
4029 node, T.cast('kwtypes.SharedModule', kwargs))
4030 target = build.SharedModule(name, self.subdir, orig_for_machine, srcs, struct, objs,
4031 self.environment, self.compilers[for_machine], self.current_build_project(), nkwargs)
4032 target.shared_library_only = shared_library_only
4033 else:
4034 nkwargs = self.__convert_jar_kwargs(
4035 node, T.cast('kwtypes.Jar', kwargs))
4036 target = build.Jar(name, self.subdir, orig_for_machine, srcs, struct, objs,
4037 self.environment, self.compilers[for_machine], self.current_build_project(), nkwargs)
4038
4039 if objs and target.uses_rust():
4040 FeatureNew.single_use('objects in Rust targets', '1.8.0', self.subproject)
4041
4042 self.add_target(name, target)
4043 self.project_args_frozen = True
4044 return target
4045
4046 def add_stdlib_info(self, target: build.BuildTarget) -> None:
4047 for l in target.compilers.keys():
4048 dep = self.build.stdlibs[target.for_machine].get(l, None)
4049 if dep:
4050 target.add_deps([dep])
4051
4052 def check_for_jar_sources(self, sources: T.Union[T.List[str], T.Sequence[T.Union[build.TargetSources, build.StructuredSources]]],
4053 targetclass: T.Type[build.BuildTarget]) -> None:
4054 for s in sources:
4055 if isinstance(s, (str, mesonlib.File)) and compilers.is_java(s):
4056 raise InvalidArguments(f'Build target of type "{targetclass.typename}" cannot build java source: "{s}". Use "{build.Jar.typename}" instead.')
4057 elif isinstance(s, build.StructuredSources):
4058 self.check_for_jar_sources(s.as_list(), targetclass)
4059 elif isinstance(s, (build.GeneratedList, build.CustomTarget, build.CustomTargetIndex)):
4060 self.check_for_jar_sources(s.get_outputs(), targetclass)
4061
4062 def is_subproject(self) -> bool:
4063 return self.subproject != ''
4064
4065 @typed_pos_args('set_variable', str, (object, DefaultObject))
4066 @noKwargs
4067 @noArgsFlattening
4068 @noSecondLevelHolderResolving
4069 def func_set_variable(self, node: mparser.BaseNode, args: T.Tuple[str, TYPE_var | InterpreterObject], kwargs: 'TYPE_kwargs') -> None:
4070 varname, value = args
4071 if mparser.IDENT_RE.fullmatch(varname) is None:
4072 raise InvalidCode('Invalid variable name: ' + varname)
4073 self.set_variable(varname, value, holderify=True)
4074
4075 @typed_pos_args('get_variable', (str, Disabler, DefaultObject), optargs=[object])
4076 @noKwargs
4077 @noArgsFlattening
4078 @unholder_return
4079 def func_get_variable(self, node: mparser.BaseNode, args: T.Tuple[T.Union[str, Disabler], T.Optional[TYPE_var | InterpreterObject]],
4080 kwargs: 'TYPE_kwargs') -> TYPE_var | InterpreterObject:
4081 varname, fallback = args
4082 if isinstance(varname, Disabler):
4083 return varname
4084
4085 try:
4086 return self.variables[varname]
4087 except KeyError:
4088 if fallback is not None:
4089 return self._holderify(fallback)
4090 ustr = f'Tried to get unknown variable "{varname}".'
4091 from difflib import get_close_matches
4092 close_matches = get_close_matches(varname, self.variables.keys())
4093 if close_matches:
4094 ustr += f' Did you mean "{close_matches[0]}"?'
4095 raise InterpreterException(ustr)
4096
4097 @typed_pos_args('is_variable', str)
4098 @noKwargs
4099 def func_is_variable(self, node: mparser.BaseNode, args: T.Tuple[str], kwargs: 'TYPE_kwargs') -> bool:
4100 return args[0] in self.variables
4101
4102 @FeatureNew('unset_variable', '0.60.0')
4103 @typed_pos_args('unset_variable', str)
4104 @noKwargs
4105 def func_unset_variable(self, node: mparser.BaseNode, args: T.Tuple[str], kwargs: 'TYPE_kwargs') -> None:
4106 varname = args[0]
4107 try:
4108 del self.variables[varname]
4109 except KeyError:
4110 ustr = f'Tried to unset unknown variable "{varname}".'
4111 from difflib import get_close_matches
4112 close_matches = get_close_matches(varname, self.variables.keys())
4113 if close_matches:
4114 ustr += f' Did you mean "{close_matches[0]}"?'
4115 raise InterpreterException(ustr)
4116
4117 @FeatureNew('is_disabler', '0.52.0')
4118 @typed_pos_args('is_disabler', object)
4119 @noKwargs
4120 def func_is_disabler(self, node: mparser.BaseNode, args: T.Tuple[object], kwargs: 'TYPE_kwargs') -> bool:
4121 return isinstance(args[0], Disabler)
4122
4123 @noKwargs
4124 @FeatureNew('range', '0.58.0')
4125 @typed_pos_args('range', int, optargs=[int, int])
4126 def func_range(self, node: mparser.BaseNode, args: T.Tuple[int, T.Optional[int], T.Optional[int]],
4127 kwargs: TYPE_kwargs) -> P_OBJ.RangeHolder:
4128 start, stop, step = args
4129 # Just like Python's range, we allow range(stop), range(start, stop), or
4130 # range(start, stop, step)
4131 if stop is None:
4132 stop = start
4133 start = 0
4134 if step is None:
4135 step = 1
4136 # This is more strict than Python's range()
4137 if start < 0:
4138 raise InterpreterException('start cannot be negative')
4139 if stop < start:
4140 raise InterpreterException('stop cannot be less than start')
4141 if step < 1:
4142 raise InterpreterException('step must be >=1')
4143 return P_OBJ.RangeHolder(start, stop, step, subproject=self.subproject)