Debian Codegraph @

mesonbuild/interpreter/interpreterobjects.py

raw
1 from __future__ import annotations
2 import os
3 import shlex
4 import subprocess
5 import copy
6 import textwrap
7 import threading
8 import sys
9
10 from pathlib import Path, PurePath
11
12 from .. import mesonlib
13 from .. import build
14 from .. import mlog
15
16 from ..modules import ModuleReturnValue, ModuleObject, ModuleState, ExtensionModule, NewExtensionModule
17 from ..backend.backends import TestProtocol
18 from ..interpreterbase import (
19 ContainerTypeInfo, KwargInfo, InterpreterObject, MesonOperator,
20 MesonInterpreterObject, ObjectHolder, MutableInterpreterObject,
21 FeatureNew, FeatureDeprecated,
22 typed_pos_args, typed_kwargs, typed_operator,
23 noArgsFlattening, noPosargs, noKwargs, unholder_return,
24 flatten, resolve_second_level_holders, Feature, FeatureValue,
25 InterpreterException, InvalidArguments, InvalidCode)
26 from ..interpreter.type_checking import NoneType, ENV_KW, ENV_SEPARATOR_KW, PKGCONFIG_DEFINE_KW
27 from ..dependencies import Dependency, ExternalLibrary, InternalDependency
28 from ..programs import Program
29 from ..mesonlib import File, HoldableObject, listify, MachineChoice, MesonException
30
31 import typing as T
32
33 if T.TYPE_CHECKING:
34 from . import kwargs
35 from ..cmake.interpreter import CMakeInterpreter
36 from ..dependencies.base import IncludeType
37 from ..envconfig import MachineInfo
38 from ..interpreterbase import FeatureCheckBase, TYPE_var, TYPE_kwargs, TYPE_nvar, TYPE_nkwargs
39 from ..mesonlib import SubProject
40 from .interpreter import Interpreter
41
42 from typing_extensions import Literal, TypedDict
43
44 class EnvironmentSeparatorKW(TypedDict):
45
46 separator: str
47
48 class InternalDependencyAsKW(TypedDict):
49
50 recursive: bool
51
52 _ERROR_MSG_KW: KwargInfo[T.Optional[str]] = KwargInfo('error_message', (str, NoneType))
53
54
55 def extract_required_kwarg(kwargs: 'kwargs.ExtractRequired',
56 subproject: 'SubProject',
57 feature_check: T.Optional[FeatureCheckBase] = None,
58 default: bool = True
59 ) -> T.Union[T.Tuple[Literal[True], bool, str],
60 T.Tuple[Literal[False], bool, None]]:
61 """Check common keyword arguments for required status.
62
63 This handles booleans vs feature option.
64
65 :param kwargs:
66 keyword arguments from the Interpreter, containing a `required` argument
67 :param subproject: The subproject this is
68 :param feature_check:
69 A custom feature check for this use of `required` with a
70 `Feature`, defaults to None.
71 :param default:
72 The default value is `required` is not set in `kwargs`, defaults to
73 True
74 :raises InterpreterException: If the type of `kwargs['required']` is invalid
75 :return:
76 a tuple of `disabled, required, feature_name`. If `disabled` is `True`
77 `feature_name` will be a string, otherwise it is `None`
78 """
79 val = kwargs.get('required', default)
80 required = False
81 feature: T.Optional[str] = None
82 if isinstance(val, Feature):
83 if not feature_check:
84 feature_check = FeatureNew('User option "feature"', '0.47.0')
85 feature_check.use(subproject)
86 feature = val.name
87 if val.is_disabled():
88 return True, required, feature
89 elif val.is_enabled():
90 required = True
91 elif isinstance(val, bool):
92 required = val
93 else:
94 raise InterpreterException('required keyword argument must be boolean or a feature option')
95
96 # Keep boolean value in kwargs to simplify other places where this kwarg is
97 # checked.
98 # TODO: this should be removed, and those callers should learn about FeatureOptions
99 kwargs['required'] = required
100
101 return False, required, None
102
103 def extract_search_dirs(kwargs: 'kwargs.ExtractSearchDirs') -> T.List[str]:
104 search_dirs_str = mesonlib.stringlistify(kwargs.get('dirs', []))
105 search_dirs = [Path(d).expanduser() for d in search_dirs_str]
106 for d in search_dirs:
107 if mesonlib.is_windows() and d.root.startswith('\\'):
108 # a Unix-path starting with `/` that is not absolute on Windows.
109 # discard without failing for end-user ease of cross-platform directory arrays
110 continue
111 if not d.is_absolute():
112 raise InvalidCode(f'Search directory {d} is not an absolute path.')
113 return [str(s) for s in search_dirs]
114
115 class FeatureOptionHolder(ObjectHolder[Feature]):
116 def __init__(self, option: Feature, interpreter: 'Interpreter'):
117 if option.is_auto():
118 auto_value = T.cast('str', interpreter.environment.coredata.optstore.get_value_for('auto_features'))
119 option = option.with_value(FeatureValue(auto_value))
120 super().__init__(option, interpreter)
121
122 @noPosargs
123 @noKwargs
124 @InterpreterObject.method('enabled')
125 def enabled_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
126 return self.held_object.is_enabled()
127
128 @noPosargs
129 @noKwargs
130 @InterpreterObject.method('disabled')
131 def disabled_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
132 return self.held_object.is_disabled()
133
134 @noPosargs
135 @noKwargs
136 @FeatureNew('feature_option.allowed()', '0.59.0')
137 @InterpreterObject.method('allowed')
138 def allowed_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
139 return not self.held_object.is_disabled()
140
141 @noPosargs
142 @noKwargs
143 @InterpreterObject.method('auto')
144 def auto_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
145 return self.held_object.is_auto()
146
147 def _disable_if(self, condition: bool, message: T.Optional[str]) -> Feature:
148 if not condition:
149 return self.held_object
150
151 if self.held_object.is_enabled():
152 err_msg = f'Feature {self.held_object.name} cannot be disabled'
153 if message:
154 err_msg += f': {message}'
155 raise InterpreterException(err_msg)
156 return self.held_object.as_disabled()
157
158 @FeatureNew('feature_option.require()', '0.59.0')
159 @typed_pos_args('feature_option.require', bool)
160 @typed_kwargs(
161 'feature_option.require',
162 _ERROR_MSG_KW,
163 )
164 @InterpreterObject.method('require')
165 def require_method(self, args: T.Tuple[bool], kwargs: 'kwargs.FeatureOptionRequire') -> Feature:
166 return self._disable_if(not args[0], kwargs['error_message'])
167
168 @FeatureNew('feature_option.disable_if()', '1.1.0')
169 @typed_pos_args('feature_option.disable_if', bool)
170 @typed_kwargs(
171 'feature_option.disable_if',
172 _ERROR_MSG_KW,
173 )
174 @InterpreterObject.method('disable_if')
175 def disable_if_method(self, args: T.Tuple[bool], kwargs: 'kwargs.FeatureOptionRequire') -> Feature:
176 return self._disable_if(args[0], kwargs['error_message'])
177
178 @FeatureNew('feature_option.enable_if()', '1.1.0')
179 @typed_pos_args('feature_option.enable_if', bool)
180 @typed_kwargs(
181 'feature_option.enable_if',
182 _ERROR_MSG_KW,
183 )
184 @InterpreterObject.method('enable_if')
185 def enable_if_method(self, args: T.Tuple[bool], kwargs: 'kwargs.FeatureOptionRequire') -> Feature:
186 if not args[0]:
187 return self.held_object
188
189 if self.held_object.is_disabled():
190 err_msg = f'Feature {self.held_object.name} cannot be enabled'
191 if kwargs['error_message']:
192 err_msg += f': {kwargs["error_message"]}'
193 raise InterpreterException(err_msg)
194 return self.held_object.as_enabled()
195
196 @FeatureNew('feature_option.disable_auto_if()', '0.59.0')
197 @noKwargs
198 @typed_pos_args('feature_option.disable_auto_if', bool)
199 @InterpreterObject.method('disable_auto_if')
200 def disable_auto_if_method(self, args: T.Tuple[bool], kwargs: TYPE_kwargs) -> Feature:
201 return self.held_object.as_disabled() if self.held_object.is_auto() and args[0] else self.held_object
202
203 @FeatureNew('feature_option.enable_auto_if()', '1.1.0')
204 @noKwargs
205 @typed_pos_args('feature_option.enable_auto_if', bool)
206 @InterpreterObject.method('enable_auto_if')
207 def enable_auto_if_method(self, args: T.Tuple[bool], kwargs: TYPE_kwargs) -> Feature:
208 return self.held_object.as_enabled() if self.held_object.is_auto() and args[0] else self.held_object
209
210
211 class RunProcess(MesonInterpreterObject):
212
213 def __init__(self,
214 cmd: Program,
215 args: T.List[str],
216 env: mesonlib.EnvironmentVariables,
217 source_dir: str,
218 build_dir: str,
219 subdir: str,
220 mesonintrospect: T.List[str],
221 in_builddir: bool = False,
222 check: bool = False,
223 capture: bool = True,
224 console: bool = False) -> None:
225 super().__init__()
226 self.capture = capture
227 self.console = console
228 self.returncode, self.stdout, self.stderr = self.run_command(cmd, args, env, source_dir, build_dir, subdir, mesonintrospect, in_builddir, check)
229
230 def run_command(self,
231 cmd: Program,
232 args: T.List[str],
233 env: mesonlib.EnvironmentVariables,
234 source_dir: str,
235 build_dir: str,
236 subdir: str,
237 mesonintrospect: T.List[str],
238 in_builddir: bool,
239 check: bool = False) -> T.Tuple[int, str, str]:
240 command_array = cmd.get_command() + args
241 menv = {'MESON_SOURCE_ROOT': source_dir,
242 'MESON_BUILD_ROOT': build_dir,
243 'MESON_SUBDIR': subdir,
244 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in mesonintrospect]),
245 }
246 if in_builddir:
247 cwd = os.path.join(build_dir, subdir)
248 else:
249 cwd = os.path.join(source_dir, subdir)
250 child_env = os.environ.copy()
251 child_env.update(menv)
252 child_env = env.get_env(child_env)
253
254 def proc_output_thread(pipe: T.IO, capture_list: T.List, io_obj: T.TextIO) -> None:
255 while True:
256 line = pipe.readline()
257 if not line:
258 break
259 if self.console:
260 io_obj.write(line.decode('utf-8', errors='replace'))
261 io_obj.flush()
262 if self.capture:
263 capture_list.append(line)
264 pipe.close()
265
266 stdin: T.Union[T.TextIO, int] = sys.stdin if self.console else subprocess.DEVNULL
267 stdout = subprocess.PIPE
268 stderr = subprocess.PIPE
269
270 mlog.debug('Running command:', mesonlib.join_args(command_array))
271 try:
272 p = subprocess.Popen(command_array, stdin=stdin, stdout=stdout, stderr=stderr, env=child_env, cwd=cwd)
273 except FileNotFoundError:
274 raise InterpreterException('Could not execute command `%s`.' % mesonlib.join_args(command_array))
275
276 o_list: T.List = []
277 e_list: T.List = []
278 stdout_thread = threading.Thread(
279 target=proc_output_thread,
280 kwargs={'pipe': p.stdout, 'capture_list': o_list, 'io_obj': sys.stdout}, daemon=True)
281 stderr_thread = threading.Thread(
282 target=proc_output_thread,
283 kwargs={'pipe': p.stderr, 'capture_list': e_list, 'io_obj': sys.stderr}, daemon=True)
284 for t in (stdout_thread, stderr_thread):
285 t.start()
286
287 p.wait()
288 for t in (stdout_thread, stderr_thread):
289 t.join()
290
291 o = b''.join(o_list).decode('utf-8', errors='replace').replace('\r\n', '\n')
292 e = b''.join(e_list).decode('utf-8', errors='replace').replace('\r\n', '\n')
293
294 if self.capture:
295 mlog.debug('--- stdout ---')
296 mlog.debug(o)
297 mlog.debug('--- stderr ---')
298 mlog.debug(e)
299 else:
300 mlog.debug('--- capture output disabled ---')
301 mlog.debug('')
302
303 if check and p.returncode != 0:
304 raise InterpreterException('Command `{}` failed with status {}.'.format(mesonlib.join_args(command_array), p.returncode))
305
306 return p.returncode, o, e
307
308 @noPosargs
309 @noKwargs
310 @InterpreterObject.method('returncode')
311 def returncode_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> int:
312 return self.returncode
313
314 @noPosargs
315 @noKwargs
316 @InterpreterObject.method('stdout')
317 def stdout_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
318 return self.stdout
319
320 @noPosargs
321 @noKwargs
322 @InterpreterObject.method('stderr')
323 def stderr_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
324 return self.stderr
325
326 class EnvironmentVariablesHolder(ObjectHolder[mesonlib.EnvironmentVariables], MutableInterpreterObject):
327
328 def __init__(self, obj: mesonlib.EnvironmentVariables, interpreter: 'Interpreter'):
329 super().__init__(obj, interpreter)
330
331 def __repr__(self) -> str:
332 repr_str = "<{0}: {1}>"
333 return repr_str.format(self.__class__.__name__, self.held_object.envvars)
334
335 def __deepcopy__(self, memo: T.Dict[str, object]) -> 'EnvironmentVariablesHolder':
336 # Avoid trying to copy the interpreter
337 return EnvironmentVariablesHolder(copy.deepcopy(self.held_object), self.interpreter)
338
339 def warn_if_has_name(self, name: str) -> None:
340 # Multiple append/prepend operations was not supported until 0.58.0.
341 if self.held_object.has_name(name):
342 m = f'Overriding previous value of environment variable {name!r} with a new one'
343 FeatureNew(m, '0.58.0').use(self.subproject, self.current_node)
344
345 @typed_pos_args('environment.set', str, varargs=str, min_varargs=1)
346 @typed_kwargs('environment.set', ENV_SEPARATOR_KW)
347 @InterpreterObject.method('set')
348 def set_method(self, args: T.Tuple[str, T.List[str]], kwargs: 'EnvironmentSeparatorKW') -> None:
349 name, values = args
350 self.held_object.set(name, values, kwargs['separator'])
351
352 @FeatureNew('environment.unset', '1.4.0')
353 @typed_pos_args('environment.unset', str)
354 @noKwargs
355 @InterpreterObject.method('unset')
356 def unset_method(self, args: T.Tuple[str], kwargs: TYPE_kwargs) -> None:
357 self.held_object.unset(args[0])
358
359 @typed_pos_args('environment.append', str, varargs=str, min_varargs=1)
360 @typed_kwargs('environment.append', ENV_SEPARATOR_KW)
361 @InterpreterObject.method('append')
362 def append_method(self, args: T.Tuple[str, T.List[str]], kwargs: 'EnvironmentSeparatorKW') -> None:
363 name, values = args
364 self.warn_if_has_name(name)
365 self.held_object.append(name, values, kwargs['separator'])
366
367 @typed_pos_args('environment.prepend', str, varargs=str, min_varargs=1)
368 @typed_kwargs('environment.prepend', ENV_SEPARATOR_KW)
369 @InterpreterObject.method('prepend')
370 def prepend_method(self, args: T.Tuple[str, T.List[str]], kwargs: 'EnvironmentSeparatorKW') -> None:
371 name, values = args
372 self.warn_if_has_name(name)
373 self.held_object.prepend(name, values, kwargs['separator'])
374
375
376 _CONF_DATA_SET_KWS: KwargInfo[T.Optional[str]] = KwargInfo('description', (str, NoneType))
377
378
379 class ConfigurationDataHolder(ObjectHolder[build.ConfigurationData], MutableInterpreterObject):
380
381 def __init__(self, obj: build.ConfigurationData, interpreter: 'Interpreter'):
382 super().__init__(obj, interpreter)
383
384 def __deepcopy__(self, memo: T.Dict) -> 'ConfigurationDataHolder':
385 return ConfigurationDataHolder(copy.deepcopy(self.held_object), self.interpreter)
386
387 def is_used(self) -> bool:
388 return self.held_object.used
389
390 def __check_used(self) -> None:
391 if self.is_used():
392 raise InterpreterException("Can not set values on configuration object that has been used.")
393
394 @typed_pos_args('configuration_data.set', str, (str, int, bool))
395 @typed_kwargs('configuration_data.set', _CONF_DATA_SET_KWS)
396 @InterpreterObject.method('set')
397 def set_method(self, args: T.Tuple[str, T.Union[str, int, bool]], kwargs: 'kwargs.ConfigurationDataSet') -> None:
398 self.__check_used()
399 self.held_object.values[args[0]] = (args[1], kwargs['description'])
400
401 @typed_pos_args('configuration_data.set_quoted', str, str)
402 @typed_kwargs('configuration_data.set_quoted', _CONF_DATA_SET_KWS)
403 @InterpreterObject.method('set_quoted')
404 def set_quoted_method(self, args: T.Tuple[str, str], kwargs: 'kwargs.ConfigurationDataSet') -> None:
405 self.__check_used()
406 escaped_val = '\\"'.join(args[1].split('"'))
407 self.held_object.values[args[0]] = (f'"{escaped_val}"', kwargs['description'])
408
409 @typed_pos_args('configuration_data.set10', str, (int, bool))
410 @typed_kwargs('configuration_data.set10', _CONF_DATA_SET_KWS)
411 @InterpreterObject.method('set10')
412 def set10_method(self, args: T.Tuple[str, T.Union[int, bool]], kwargs: 'kwargs.ConfigurationDataSet') -> None:
413 self.__check_used()
414 # bool is a subclass of int, so we need to check for bool explicitly.
415 # We already have typed_pos_args checking that this is either a bool or
416 # an int.
417 if not isinstance(args[1], bool):
418 mlog.deprecation('configuration_data.set10 with number. The `set10` '
419 'method should only be used with booleans',
420 location=self.interpreter.current_node)
421 if args[1] < 0:
422 mlog.warning('Passing a number that is less than 0 may not have the intended result, '
423 'as meson will treat all non-zero values as true.',
424 location=self.interpreter.current_node)
425 self.held_object.values[args[0]] = (int(args[1]), kwargs['description'])
426
427 @typed_pos_args('configuration_data.has', (str, int, bool))
428 @noKwargs
429 @InterpreterObject.method('has')
430 def has_method(self, args: T.Tuple[T.Union[str, int, bool]], kwargs: TYPE_kwargs) -> bool:
431 return args[0] in self.held_object.values
432
433 @FeatureNew('configuration_data.get()', '0.38.0')
434 @typed_pos_args('configuration_data.get', str, optargs=[(str, int, bool)])
435 @noKwargs
436 @InterpreterObject.method('get')
437 def get_method(self, args: T.Tuple[str, T.Optional[T.Union[str, int, bool]]],
438 kwargs: TYPE_kwargs) -> T.Union[str, int, bool]:
439 name = args[0]
440 if name in self.held_object:
441 return self.held_object.get(name)[0]
442 elif args[1] is not None:
443 return args[1]
444 raise InterpreterException(f'Entry {name} not in configuration data.')
445
446 @FeatureNew('configuration_data.get_unquoted()', '0.44.0')
447 @typed_pos_args('configuration_data.get_unquoted', str, optargs=[(str, int, bool)])
448 @noKwargs
449 @InterpreterObject.method('get_unquoted')
450 def get_unquoted_method(self, args: T.Tuple[str, T.Optional[T.Union[str, int, bool]]],
451 kwargs: TYPE_kwargs) -> T.Union[str, int, bool]:
452 name = args[0]
453 if name in self.held_object:
454 val = self.held_object.get(name)[0]
455 elif args[1] is not None:
456 val = args[1]
457 else:
458 raise InterpreterException(f'Entry {name} not in configuration data.')
459 if isinstance(val, str) and val[0] == '"' and val[-1] == '"':
460 return val[1:-1]
461 return val
462
463 def get(self, name: str) -> T.Tuple[T.Union[str, int, bool], T.Optional[str]]:
464 return self.held_object.values[name]
465
466 @FeatureNew('configuration_data.keys()', '0.57.0')
467 @noPosargs
468 @noKwargs
469 @InterpreterObject.method('keys')
470 def keys_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> T.List[str]:
471 return sorted(self.keys())
472
473 def keys(self) -> T.List[str]:
474 return list(self.held_object.values.keys())
475
476 @typed_pos_args('configuration_data.merge_from', build.ConfigurationData)
477 @noKwargs
478 @InterpreterObject.method('merge_from')
479 def merge_from_method(self, args: T.Tuple[build.ConfigurationData], kwargs: TYPE_kwargs) -> None:
480 from_object = args[0]
481 self.held_object.values.update(from_object.values)
482
483
484 _PARTIAL_DEP_KWARGS = [
485 KwargInfo('compile_args', bool, default=False),
486 KwargInfo('link_args', bool, default=False),
487 KwargInfo('links', bool, default=False),
488 KwargInfo('includes', bool, default=False),
489 KwargInfo('sources', bool, default=False),
490 ]
491
492 class DependencyHolder(ObjectHolder[Dependency]):
493 def __init__(self, dep: Dependency, interpreter: 'Interpreter'):
494 super().__init__(dep, interpreter)
495
496 def found(self) -> bool:
497 return self.found_method([], {})
498
499 @noPosargs
500 @noKwargs
501 @InterpreterObject.method('type_name')
502 def type_name_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
503 return self.held_object.type_name
504
505 @noPosargs
506 @noKwargs
507 @InterpreterObject.method('found')
508 def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
509 if self.held_object.type_name == 'internal':
510 return True
511 return self.held_object.found()
512
513 @noPosargs
514 @noKwargs
515 @InterpreterObject.method('version')
516 def version_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
517 return self.held_object.get_version()
518
519 @noPosargs
520 @noKwargs
521 @InterpreterObject.method('name')
522 def name_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
523 return self.held_object.get_name()
524
525 @FeatureDeprecated('dependency.get_pkgconfig_variable', '0.56.0',
526 'use dependency.get_variable(pkgconfig : ...) instead')
527 @typed_pos_args('dependency.get_pkgconfig_variable', str)
528 @typed_kwargs(
529 'dependency.get_pkgconfig_variable',
530 KwargInfo('default', str, default=''),
531 PKGCONFIG_DEFINE_KW.evolve(name='define_variable')
532 )
533 @InterpreterObject.method('get_pkgconfig_variable')
534 def pkgconfig_method(self, args: T.Tuple[str], kwargs: 'kwargs.DependencyPkgConfigVar') -> str:
535 from ..dependencies.pkgconfig import PkgConfigDependency
536 if not isinstance(self.held_object, PkgConfigDependency):
537 raise InvalidArguments(f'{self.held_object.get_name()!r} is not a pkgconfig dependency')
538 if kwargs['define_variable'] and len(kwargs['define_variable']) > 1:
539 FeatureNew.single_use('dependency.get_pkgconfig_variable keyword argument "define_variable" with more than one pair',
540 '1.3.0', self.subproject, location=self.current_node)
541 return self.held_object.get_variable(
542 pkgconfig=args[0],
543 default_value=kwargs['default'],
544 pkgconfig_define=kwargs['define_variable'],
545 )
546
547 @FeatureNew('dependency.get_configtool_variable', '0.44.0')
548 @FeatureDeprecated('dependency.get_configtool_variable', '0.56.0',
549 'use dependency.get_variable(configtool : ...) instead')
550 @noKwargs
551 @typed_pos_args('dependency.get_config_tool_variable', str)
552 @InterpreterObject.method('get_configtool_variable')
553 def configtool_method(self, args: T.Tuple[str], kwargs: TYPE_kwargs) -> str:
554 from ..dependencies.configtool import ConfigToolDependency
555 if not isinstance(self.held_object, ConfigToolDependency):
556 raise InvalidArguments(f'{self.held_object.get_name()!r} is not a config-tool dependency')
557 return self.held_object.get_variable(
558 configtool=args[0],
559 default_value='',
560 )
561
562 @FeatureNew('dependency.partial_dependency', '0.46.0')
563 @noPosargs
564 @typed_kwargs('dependency.partial_dependency', *_PARTIAL_DEP_KWARGS)
565 @InterpreterObject.method('partial_dependency')
566 def partial_dependency_method(self, args: T.List[TYPE_nvar], kwargs: 'kwargs.DependencyMethodPartialDependency') -> Dependency:
567 pdep = self.held_object.get_partial_dependency(**kwargs)
568 return pdep
569
570 @FeatureNew('dependency.get_variable', '0.51.0')
571 @typed_pos_args('dependency.get_variable', optargs=[str])
572 @typed_kwargs(
573 'dependency.get_variable',
574 KwargInfo('cmake', (str, NoneType)),
575 KwargInfo('pkgconfig', (str, NoneType)),
576 KwargInfo('configtool', (str, NoneType)),
577 KwargInfo('internal', (str, NoneType), since='0.54.0'),
578 KwargInfo('system', (str, NoneType), since='1.6.0'),
579 KwargInfo('default_value', (str, NoneType)),
580 PKGCONFIG_DEFINE_KW,
581 )
582 @InterpreterObject.method('get_variable')
583 def variable_method(self, args: T.Tuple[T.Optional[str]], kwargs: 'kwargs.DependencyGetVariable') -> str:
584 default_varname = args[0]
585 if default_varname is not None:
586 FeatureNew('Positional argument to dependency.get_variable()', '0.58.0').use(self.subproject, self.current_node)
587 if kwargs['pkgconfig_define'] and len(kwargs['pkgconfig_define']) > 1:
588 FeatureNew.single_use('dependency.get_variable keyword argument "pkgconfig_define" with more than one pair',
589 '1.3.0', self.subproject, 'In previous versions, this silently returned a malformed value.',
590 self.current_node)
591 return self.held_object.get_variable(
592 cmake=kwargs['cmake'] or default_varname,
593 pkgconfig=kwargs['pkgconfig'] or default_varname,
594 configtool=kwargs['configtool'] or default_varname,
595 internal=kwargs['internal'] or default_varname,
596 system=kwargs['system'] or default_varname,
597 default_value=kwargs['default_value'],
598 pkgconfig_define=kwargs['pkgconfig_define'],
599 )
600
601 @FeatureNew('dependency.include_type', '0.52.0')
602 @noPosargs
603 @noKwargs
604 @InterpreterObject.method('include_type')
605 def include_type_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
606 return self.held_object.get_include_type()
607
608 @FeatureNew('dependency.as_system', '0.52.0')
609 @noKwargs
610 @typed_pos_args('dependency.as_system', optargs=[str])
611 @InterpreterObject.method('as_system')
612 def as_system_method(self, args: T.Tuple[T.Optional[str]], kwargs: TYPE_kwargs) -> Dependency:
613 include_type: IncludeType
614 if args[0] is None:
615 include_type = 'system'
616 elif args[0] not in {'preserve', 'system', 'non-system'}:
617 raise InvalidArguments(
618 'Dependency.as_system: if an argument is given it must be one '
619 f'of: "preserve", "system", "non-system", not: "{args[0]}"')
620 else:
621 include_type = T.cast('IncludeType', args[0])
622 return self.held_object.generate_system_dependency(include_type)
623
624 @FeatureNew('dependency.as_link_whole', '0.56.0')
625 @noKwargs
626 @noPosargs
627 @InterpreterObject.method('as_link_whole')
628 def as_link_whole_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> Dependency:
629 if not isinstance(self.held_object, InternalDependency):
630 raise InterpreterException('as_link_whole method is only supported on declare_dependency() objects')
631 new_dep = self.held_object.generate_link_whole_dependency()
632 return new_dep
633
634 @FeatureNew('dependency.as_static', '1.6.0')
635 @noPosargs
636 @typed_kwargs(
637 'dependency.as_static',
638 KwargInfo('recursive', bool, default=False),
639 )
640 @InterpreterObject.method('as_static')
641 def as_static_method(self, args: T.List[TYPE_var], kwargs: InternalDependencyAsKW) -> Dependency:
642 if not isinstance(self.held_object, InternalDependency):
643 raise InterpreterException('as_static method is only supported on declare_dependency() objects')
644 return self.held_object.get_as_static(kwargs['recursive'])
645
646 @FeatureNew('dependency.as_shared', '1.6.0')
647 @noPosargs
648 @typed_kwargs(
649 'dependency.as_shared',
650 KwargInfo('recursive', bool, default=False),
651 )
652 @InterpreterObject.method('as_shared')
653 def as_shared_method(self, args: T.List[TYPE_var], kwargs: InternalDependencyAsKW) -> Dependency:
654 if not isinstance(self.held_object, InternalDependency):
655 raise InterpreterException('as_shared method is only supported on declare_dependency() objects')
656 return self.held_object.get_as_shared(kwargs['recursive'])
657
658 _PROG = T.TypeVar('_PROG', bound=Program)
659
660 class ProgramHolder(ObjectHolder[_PROG]):
661 def __init__(self, ep: _PROG, interpreter: 'Interpreter') -> None:
662 super().__init__(ep, interpreter)
663
664 @noPosargs
665 @noKwargs
666 @InterpreterObject.method('found')
667 def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
668 return self.found()
669
670 @noPosargs
671 @noKwargs
672 @FeatureDeprecated('Program.path', '0.55.0',
673 'use Program.full_path() instead')
674 @InterpreterObject.method('path')
675 def path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
676 return self._full_path()
677
678 @noPosargs
679 @noKwargs
680 @FeatureNew('Program.full_path', '0.55.0')
681 @InterpreterObject.method('full_path')
682 def full_path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
683 return self._full_path()
684
685 def _full_path(self) -> str:
686 if not self.found():
687 raise InterpreterException('Unable to get the path of a not-found external program')
688 if not self.held_object.runnable():
689 assert isinstance(self.held_object, build.LocalProgram) and \
690 isinstance(self.held_object.program, (build.BuildTarget, build.CustomTargetIndex))
691 return self.interpreter.backend.get_target_filename_abs(self.held_object.program)
692 return mesonlib.unwrap(self.held_object.get_path())
693
694 @noPosargs
695 @noKwargs
696 @FeatureNew('Program.cmd_array', '1.10.0')
697 @InterpreterObject.method('cmd_array')
698 def cmd_array_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> T.List[str]:
699 if not self.found():
700 raise InterpreterException('Unable to get the path of a not-found external program')
701 if not self.held_object.runnable():
702 return [self._full_path()]
703 return self.held_object.get_command()
704
705 @noPosargs
706 @noKwargs
707 @FeatureNew('Program.version', '0.62.0')
708 @InterpreterObject.method('version')
709 def version_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
710 if isinstance(self.held_object, build.LocalProgram) and isinstance(self.held_object.program, build.Executable):
711 FeatureNew.single_use('Program.version with an executable', '1.9.0', subproject=self.subproject, location=self.current_node)
712 if not self.found():
713 raise InterpreterException('Unable to get the version of a not-found external program')
714 try:
715 return self.held_object.get_version(self.interpreter)
716 except mesonlib.MesonException:
717 return 'unknown'
718
719 def found(self) -> bool:
720 return self.held_object.found()
721
722
723 class ExternalLibraryHolder(ObjectHolder[ExternalLibrary]):
724 def __init__(self, el: ExternalLibrary, interpreter: 'Interpreter'):
725 super().__init__(el, interpreter)
726
727 @noPosargs
728 @noKwargs
729 @InterpreterObject.method('type_name')
730 def type_name_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
731 return self.held_object.type_name
732
733 @noPosargs
734 @noKwargs
735 @InterpreterObject.method('found')
736 def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
737 return self.held_object.found()
738
739 @FeatureNew('dependency.partial_dependency', '0.46.0')
740 @noPosargs
741 @typed_kwargs('dependency.partial_dependency', *_PARTIAL_DEP_KWARGS)
742 @InterpreterObject.method('partial_dependency')
743 def partial_dependency_method(self, args: T.List[TYPE_nvar], kwargs: 'kwargs.DependencyMethodPartialDependency') -> Dependency:
744 pdep = self.held_object.get_partial_dependency(**kwargs)
745 return pdep
746
747 @FeatureNew('dependency.name', '1.5.0')
748 @noPosargs
749 @noKwargs
750 @InterpreterObject.method('name')
751 def name_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
752 return self.held_object.name
753
754
755 # A machine that's statically known from the cross file
756 class MachineHolder(ObjectHolder['MachineInfo']):
757 def __init__(self, machine_info: 'MachineInfo', interpreter: 'Interpreter'):
758 super().__init__(machine_info, interpreter)
759
760 @noPosargs
761 @noKwargs
762 @InterpreterObject.method('cpu_family')
763 def cpu_family_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
764 return self.held_object.cpu_family
765
766 @noPosargs
767 @noKwargs
768 @InterpreterObject.method('cpu')
769 def cpu_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
770 return self.held_object.cpu
771
772 @noPosargs
773 @noKwargs
774 @InterpreterObject.method('system')
775 def system_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
776 return self.held_object.system
777
778 @noPosargs
779 @noKwargs
780 @InterpreterObject.method('endian')
781 def endian_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
782 return self.held_object.endian
783
784 @noPosargs
785 @noKwargs
786 @InterpreterObject.method('kernel')
787 def kernel_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
788 if self.held_object.kernel is not None:
789 return self.held_object.kernel
790 raise InterpreterException('Kernel not defined or could not be autodetected.')
791
792 @noPosargs
793 @noKwargs
794 @InterpreterObject.method('subsystem')
795 def subsystem_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
796 if self.held_object.subsystem is not None:
797 return self.held_object.subsystem
798 raise InterpreterException('Subsystem not defined or could not be autodetected.')
799
800 class IncludeDirsHolder(ObjectHolder[build.IncludeDirs]):
801 @noPosargs
802 @noKwargs
803 @FeatureNew('inc.to_list', '1.12.0')
804 @InterpreterObject.method('to_list')
805 def to_list_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> T.List[str]:
806 if self.held_object.is_system:
807 return self.held_object.incdirs
808 return self.held_object.abs_string_list(self.env.source_dir, self.env.build_dir)
809
810 class FileHolder(ObjectHolder[mesonlib.File]):
811 def __init__(self, file: mesonlib.File, interpreter: 'Interpreter'):
812 super().__init__(file, interpreter)
813
814 @noPosargs
815 @noKwargs
816 @FeatureNew('file.full_path', '1.4.0')
817 @InterpreterObject.method('full_path')
818 def full_path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
819 return self.held_object.absolute_path(self.env.source_dir, self.env.build_dir)
820
821 class HeadersHolder(ObjectHolder[build.Headers]):
822 pass
823
824 class DataHolder(ObjectHolder[build.Data]):
825 pass
826
827 class SymlinkDataHolder(ObjectHolder[build.SymlinkData]):
828 pass
829
830 class InstallDirHolder(ObjectHolder[build.InstallDir]):
831 pass
832
833 class ManHolder(ObjectHolder[build.Man]):
834 pass
835
836 class EmptyDirHolder(ObjectHolder[build.EmptyDir]):
837 pass
838
839 class GeneratedObjectsHolder(ObjectHolder[build.ExtractedObjects]):
840 pass
841
842 class Test(MesonInterpreterObject):
843 def __init__(self, name: str, project: str, suite: T.List[str],
844 exe: T.Union[Program, build.Executable, build.CustomTarget, build.CustomTargetIndex, build.Jar],
845 depends: T.Sequence[kwargs.TargetDepends],
846 is_parallel: bool,
847 cmd_args: T.List[build.CommandTypes],
848 env: mesonlib.EnvironmentVariables,
849 expected_fail: bool, expected_exitcode: int, timeout: int, workdir: T.Optional[str], protocol: str,
850 priority: int, verbose: bool):
851 super().__init__()
852 self.name = name
853 self.suite = listify(suite)
854 self.project_name = project
855 self.exe = exe
856 self.is_parallel = is_parallel
857 self.cmd_args = cmd_args
858 self.env = env
859 self.expected_fail = expected_fail
860 self.expected_exitcode = expected_exitcode
861 self.timeout = timeout
862 self.workdir = workdir
863 self.protocol = TestProtocol.from_str(protocol)
864 self.priority = priority
865 self.verbose = verbose
866
867 self.depends: T.List[build.BuildTargetTypes] = []
868 for d in depends:
869 if isinstance(d, build.GeneratedList):
870 raise MesonException('generated_list not allowed as a dependency for test')
871 if isinstance(d, Program):
872 if not isinstance(d, build.LocalProgram):
873 continue
874 d = d.get_target()
875 if isinstance(d, File):
876 continue
877 self.depends.append(d)
878
879 def get_exe(self) -> T.Union[Program, build.Executable, build.Jar, build.CustomTarget, build.CustomTargetIndex]:
880 return self.exe
881
882 def get_name(self) -> str:
883 return self.name
884
885
886 class Doctest(Test):
887 target: T.Optional[build.BuildTarget] = None
888
889
890 class NullSubprojectInterpreter(HoldableObject):
891 pass
892
893 # TODO: This should really be an `ObjectHolder`, but the additional stuff in this
894 # class prevents this. Thus, this class should be split into a pure
895 # `ObjectHolder` and a class specifically for storing in `Interpreter`.
896 class SubprojectHolder(MesonInterpreterObject):
897
898 def __init__(self, subinterpreter: T.Union['Interpreter', NullSubprojectInterpreter],
899 subdir: str,
900 warnings: int = 0,
901 disabled_feature: T.Optional[str] = None,
902 exception: T.Optional[Exception] = None,
903 callstack: T.Optional[T.List[T.Tuple[str, MachineChoice]]] = None) -> None:
904 super().__init__()
905 self.held_object = subinterpreter
906 self.warnings = warnings
907 self.disabled_feature = disabled_feature
908 self.exception = exception
909 self.subdir = PurePath(subdir).as_posix()
910 self.cm_interpreter: T.Optional[CMakeInterpreter] = None
911 self.callstack = callstack
912
913 @noPosargs
914 @noKwargs
915 @InterpreterObject.method('found')
916 def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
917 return self.found()
918
919 def found(self) -> bool:
920 return not isinstance(self.held_object, NullSubprojectInterpreter)
921
922 @unholder_return
923 def get_variable(self, args: T.Tuple[str, T.Optional[str]], kwargs: TYPE_kwargs) -> T.Union[TYPE_var, InterpreterObject]:
924 if isinstance(self.held_object, NullSubprojectInterpreter): # == not self.found()
925 raise InterpreterException(f'Subproject "{self.subdir}" disabled can\'t get_variable on it.')
926 varname, fallback = args
927 try:
928 return self.held_object.variables[varname]
929 except KeyError:
930 if fallback is not None:
931 return self.held_object._holderify(fallback)
932 ustr = f'Requested variable "{varname}" not found.'
933 from difflib import get_close_matches
934 close_matches = get_close_matches(varname, self.held_object.variables.keys())
935 if close_matches:
936 ustr += f' Did you mean "{close_matches[0]}"?'
937 raise InvalidArguments(ustr)
938
939 @noKwargs
940 @typed_pos_args('subproject.get_variable', str, optargs=[object])
941 @noArgsFlattening
942 @InterpreterObject.method('get_variable')
943 def get_variable_method(self, args: T.Tuple[str, T.Optional[str]], kwargs: TYPE_kwargs) -> T.Union[TYPE_var, InterpreterObject]:
944 return self.get_variable(args, kwargs)
945
946 class ModuleObjectHolder(ObjectHolder[ModuleObject]):
947 def method_call(self, method_name: str, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> TYPE_var:
948 modobj = self.held_object
949 method = modobj.methods.get(method_name)
950 if not method:
951 ustr = f'Unknown method "{method_name}" in object.'
952 from difflib import get_close_matches
953 close_matches = get_close_matches(method_name, modobj.methods.keys())
954 if close_matches:
955 ustr += f' Did you mean "{close_matches[0]}"?'
956 raise InvalidCode(ustr)
957 if not getattr(method, 'no-args-flattening', False):
958 args = flatten(args)
959 if not getattr(method, 'no-second-level-holder-flattening', False):
960 args, kwargs = resolve_second_level_holders(args, kwargs)
961 if not self.interpreter.active_projectname:
962 assert isinstance(modobj, (ExtensionModule, NewExtensionModule)), 'for mypy'
963 full_method_name = f'{modobj.INFO.name}.{method_name}'
964 raise mesonlib.MesonException(f'Module methods ({full_method_name}) cannot be invoked during project declaration.')
965 state = ModuleState(self.interpreter)
966 # Many modules do for example self.interpreter.find_program_impl(),
967 # so we have to ensure they use the current interpreter and not the one
968 # that first imported that module, otherwise it will use outdated
969 # overrides.
970 if isinstance(modobj, ExtensionModule):
971 modobj.interpreter = self.interpreter
972 ret = method(state, args, kwargs)
973 if isinstance(ret, ModuleReturnValue):
974 self.interpreter.process_new_values(ret.new_objects)
975 ret = ret.return_value
976 return ret
977
978 class MutableModuleObjectHolder(ModuleObjectHolder, MutableInterpreterObject):
979 def __deepcopy__(self, memo: T.Dict[int, T.Any]) -> 'MutableModuleObjectHolder':
980 # Deepcopy only held object, not interpreter
981 modobj = copy.deepcopy(self.held_object, memo)
982 return MutableModuleObjectHolder(modobj, self.interpreter)
983
984
985 _BuildTarget = T.TypeVar('_BuildTarget', bound=T.Union[build.BuildTarget, build.BothLibraries])
986
987 class BuildTargetHolder(ObjectHolder[_BuildTarget]):
988 def __init__(self, target: _BuildTarget, interp: 'Interpreter'):
989 super().__init__(target, interp)
990
991 def __repr__(self) -> str:
992 r = '<{} {}: {}>'
993 h = self.held_object
994 assert isinstance(h, build.BuildTarget)
995 return r.format(self.__class__.__name__, h.get_id(), h.filename)
996
997 @property
998 def _target_object(self) -> build.BuildTarget:
999 if isinstance(self.held_object, build.BothLibraries):
1000 return self.held_object.get_default_object()
1001 assert isinstance(self.held_object, build.BuildTarget)
1002 return self.held_object
1003
1004 def is_cross(self) -> bool:
1005 return not self._target_object.environment.machines.matches_build_machine(self._target_object.for_machine)
1006
1007 @noPosargs
1008 @noKwargs
1009 @InterpreterObject.method('found')
1010 @FeatureNew('BuildTarget.found', '0.59.0')
1011 def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool:
1012 return True
1013
1014 @noPosargs
1015 @noKwargs
1016 @InterpreterObject.method('private_dir_include')
1017 def private_dir_include_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> build.IncludeDirs:
1018 return build.IncludeDirs('', [], False, self.interpreter.current_build_project(),
1019 [self.interpreter.backend.get_target_private_dir(self._target_object)])
1020
1021 @noPosargs
1022 @noKwargs
1023 @InterpreterObject.method('full_path')
1024 def full_path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1025 return self.interpreter.backend.get_target_filename_abs(self._target_object)
1026
1027 @noPosargs
1028 @noKwargs
1029 @FeatureDeprecated('BuildTarget.path', '0.55.0', 'Use BuildTarget.full_path instead')
1030 @InterpreterObject.method('path')
1031 def path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1032 return self.interpreter.backend.get_target_filename_abs(self._target_object)
1033
1034 @noPosargs
1035 @noKwargs
1036 @InterpreterObject.method('outdir')
1037 def outdir_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1038 return self.interpreter.backend.get_target_dir(self._target_object)
1039
1040 @noKwargs
1041 @typed_pos_args('extract_objects', varargs=(mesonlib.File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList))
1042 @InterpreterObject.method('extract_objects')
1043 def extract_objects_method(self, args: T.Tuple[T.List[str | build.TargetSources]], kwargs: TYPE_nkwargs) -> build.ExtractedObjects:
1044 if self.subproject != self.held_object.subproject:
1045 raise InterpreterException('Tried to extract objects from a different subproject.')
1046 tobj = self._target_object
1047 unity_value = self.interpreter.coredata.get_option_for_target(tobj, "unity")
1048 is_unity = (unity_value == 'on' or (unity_value == 'subprojects' and tobj.subproject != ''))
1049
1050 obj_src: list[mesonlib.File | build.GeneratedTypes] = []
1051 for raw_src in args[0]:
1052 if isinstance(raw_src, str):
1053 src = File(False, tobj.subdir, raw_src)
1054 else:
1055 if isinstance(raw_src, File):
1056 FeatureNew.single_use('File argument for extract_objects', '0.50.0', self.subproject)
1057 src = raw_src
1058 obj_src.append(src)
1059
1060 return tobj.extract_objects(obj_src, is_unity)
1061
1062 @noPosargs
1063 @typed_kwargs(
1064 'extract_all_objects',
1065 KwargInfo(
1066 'recursive', bool, default=False, since='0.46.0',
1067 not_set_warning=textwrap.dedent('''\
1068 extract_all_objects called without setting recursive
1069 keyword argument. Meson currently defaults to
1070 non-recursive to maintain backward compatibility but
1071 the default will be changed in meson 2.0.
1072 ''')
1073 )
1074 )
1075 @InterpreterObject.method('extract_all_objects')
1076 def extract_all_objects_method(self, args: T.List[TYPE_nvar], kwargs: 'kwargs.BuildTargeMethodExtractAllObjects') -> build.ExtractedObjects:
1077 return self._target_object.extract_all_objects(kwargs['recursive'])
1078
1079 @noPosargs
1080 @noKwargs
1081 @FeatureDeprecated('BuildTarget.get_id', '1.2.0',
1082 'This was never formally documented and does not seem to have a real world use. ' +
1083 'See https://github.com/mesonbuild/meson/pull/6061')
1084 @InterpreterObject.method('get_id')
1085 def get_id_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1086 return self._target_object.get_id()
1087
1088 @FeatureNew('name', '0.54.0')
1089 @noPosargs
1090 @noKwargs
1091 @InterpreterObject.method('name')
1092 def name_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1093 return self._target_object.name
1094
1095 @FeatureNew('vala_header', '1.10.0')
1096 @noPosargs
1097 @noKwargs
1098 @InterpreterObject.method('vala_header')
1099 def vala_header_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> mesonlib.File:
1100 if self._target_object.vala_header is None:
1101 raise mesonlib.MesonException("Attempted to get a Vala header from a target that doesn't generate one")
1102
1103 return mesonlib.File.from_built_file(
1104 self.interpreter.backend.get_target_dir(self._target_object),
1105 self._target_object.vala_header)
1106
1107 @FeatureNew('vala_vapi', '1.10.0')
1108 @noPosargs
1109 @noKwargs
1110 @InterpreterObject.method('vala_vapi')
1111 def vala_vapi_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> mesonlib.File:
1112 if self._target_object.vala_vapi is None:
1113 raise mesonlib.MesonException("Attempted to get a Vala VAPI from a target that doesn't generate one")
1114
1115 return mesonlib.File.from_built_file(
1116 self.interpreter.backend.get_target_dir(self._target_object),
1117 self._target_object.vala_vapi)
1118
1119 @FeatureNew('vala_gir', '1.10.0')
1120 @noPosargs
1121 @noKwargs
1122 @InterpreterObject.method('vala_gir')
1123 def vala_gir_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> mesonlib.File:
1124 if self._target_object.vala_gir is None:
1125 raise mesonlib.MesonException("Attempted to get a Vala GIR from a target that doesn't generate one")
1126
1127 return mesonlib.File.from_built_file(
1128 self.interpreter.backend.get_target_dir(self._target_object),
1129 self._target_object.vala_gir)
1130
1131
1132 class ExecutableHolder(BuildTargetHolder[build.Executable]):
1133 pass
1134
1135 class StaticLibraryHolder(BuildTargetHolder[build.StaticLibrary]):
1136 pass
1137
1138 class SharedLibraryHolder(BuildTargetHolder[build.SharedLibrary]):
1139 pass
1140
1141 class BothLibrariesHolder(BuildTargetHolder[build.BothLibraries]):
1142 def __init__(self, libs: build.BothLibraries, interp: 'Interpreter'):
1143 super().__init__(libs, interp)
1144
1145 def __repr__(self) -> str:
1146 r = '<{} {}: {}, {}: {}>'
1147 h1 = self.held_object.shared
1148 h2 = self.held_object.static
1149 return r.format(self.__class__.__name__, h1.get_id(), h1.filename, h2.get_id(), h2.filename)
1150
1151 @noPosargs
1152 @noKwargs
1153 @InterpreterObject.method('get_shared_lib')
1154 def get_shared_lib_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> build.SharedLibrary:
1155 lib = copy.copy(self.held_object.shared)
1156 lib.both_lib = None
1157 return lib
1158
1159 @noPosargs
1160 @noKwargs
1161 @InterpreterObject.method('get_static_lib')
1162 def get_static_lib_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> build.StaticLibrary:
1163 lib = copy.copy(self.held_object.static)
1164 lib.both_lib = None
1165 return lib
1166
1167 class SharedModuleHolder(BuildTargetHolder[build.SharedModule]):
1168 pass
1169
1170 class JarHolder(BuildTargetHolder[build.Jar]):
1171 pass
1172
1173 class CustomTargetIndexHolder(ObjectHolder[build.CustomTargetIndex]):
1174 def __init__(self, target: build.CustomTargetIndex, interp: 'Interpreter'):
1175 super().__init__(target, interp)
1176
1177 @FeatureNew('custom_target[i].full_path', '0.54.0')
1178 @noPosargs
1179 @noKwargs
1180 @InterpreterObject.method('full_path')
1181 def full_path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1182 return self.interpreter.backend.get_target_filename_abs(self.held_object)
1183
1184 _CT = T.TypeVar('_CT', bound=build.CustomTarget)
1185
1186 class _CustomTargetHolder(ObjectHolder[_CT]):
1187 def __init__(self, target: _CT, interp: 'Interpreter'):
1188 super().__init__(target, interp)
1189
1190 def __repr__(self) -> str:
1191 r = '<{} {}: {}>'
1192 h = self.held_object
1193 return r.format(self.__class__.__name__, h.get_id(), h.command)
1194
1195 @noPosargs
1196 @noKwargs
1197 @InterpreterObject.method('full_path')
1198 def full_path_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
1199 return self.interpreter.backend.get_target_filename_abs(self.held_object)
1200
1201 @FeatureNew('custom_target.to_list', '0.54.0')
1202 @noPosargs
1203 @noKwargs
1204 @InterpreterObject.method('to_list')
1205 def to_list_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> T.List[build.CustomTargetIndex]:
1206 return list(self.held_object)
1207
1208 @noKwargs
1209 @typed_operator(MesonOperator.INDEX, int)
1210 @InterpreterObject.operator(MesonOperator.INDEX)
1211 def op_index(self, other: int) -> build.CustomTargetIndex:
1212 try:
1213 return self.held_object[other]
1214 except IndexError:
1215 raise InvalidArguments(f'Index {other} out of bounds of custom target {self.held_object.name} output of size {len(self.held_object)}.')
1216
1217 class CustomTargetHolder(_CustomTargetHolder[build.CustomTarget]):
1218 pass
1219
1220 class RunTargetHolder(ObjectHolder[build.RunTarget]):
1221 pass
1222
1223 class AliasTargetHolder(ObjectHolder[build.AliasTarget]):
1224 pass
1225
1226 class GeneratedListHolder(ObjectHolder[build.GeneratedList]):
1227 pass
1228
1229 class GeneratorHolder(ObjectHolder[build.Generator]):
1230 def __init__(self, gen: build.Generator, interpreter: 'Interpreter'):
1231 super().__init__(gen, interpreter)
1232
1233 @typed_pos_args('generator.process', min_varargs=1, varargs=(str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList))
1234 @typed_kwargs(
1235 'generator.process',
1236 KwargInfo('preserve_path_from', (str, NoneType), since='0.45.0'),
1237 KwargInfo('extra_args', ContainerTypeInfo(list, str), listify=True, default=[]),
1238 ENV_KW.evolve(since='1.3.0'),
1239 KwargInfo('depends', ContainerTypeInfo(list, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)), listify=True, default=[], since='1.12.0'),
1240 )
1241 @InterpreterObject.method('process')
1242 def process_method(self,
1243 args: T.Tuple[T.List[str | build.TargetSources]],
1244 kwargs: 'kwargs.GeneratorProcess') -> build.GeneratedList:
1245 preserve_path_from = kwargs['preserve_path_from']
1246 if preserve_path_from is not None:
1247 preserve_path_from = os.path.normpath(preserve_path_from)
1248 if not os.path.isabs(preserve_path_from):
1249 # This is a bit of a hack. Fix properly before merging.
1250 raise InvalidArguments('Preserve_path_from must be an absolute path for now. Sorry.')
1251
1252 if any(isinstance(a, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for a in args[0]):
1253 FeatureNew.single_use(
1254 'Calling generator.process with CustomTarget or Index of CustomTarget.',
1255 '0.57.0', self.interpreter.subproject)
1256
1257 sources = self.interpreter.source_strings_to_files(args[0])
1258 gl = self.held_object.process_files(sources, self.interpreter.subdir,
1259 preserve_path_from, extra_args=kwargs['extra_args'], env=kwargs['env'],
1260 extra_depends=kwargs['depends'])
1261
1262 return gl
1263
1264
1265 class StructuredSourcesHolder(ObjectHolder[build.StructuredSources]):
1266
1267 def __init__(self, sources: build.StructuredSources, interp: 'Interpreter'):
1268 super().__init__(sources, interp)