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