Debian Codegraph @

mesonbuild/options.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2024 Contributors to the The Meson project
3 # Copyright © 2019-2025 Intel Corporation
4
5 from __future__ import annotations
6 from collections import OrderedDict
7 from itertools import chain
8 import copy
9 import dataclasses
10 import itertools
11 import os
12 import pathlib
13
14 import typing as T
15
16 from .mesonlib import (
17 HoldableObject,
18 default_prefix,
19 default_datadir,
20 default_includedir,
21 default_infodir,
22 default_libdir,
23 default_libexecdir,
24 default_localedir,
25 default_mandir,
26 default_sbindir,
27 default_sysconfdir,
28 MesonException,
29 MesonBugException,
30 listify_array_value,
31 MachineChoice,
32 )
33 from . import mlog
34
35 if T.TYPE_CHECKING:
36 from typing_extensions import Literal, Final, TypeAlias
37
38 from .envconfig import MachineInfo
39 from .mesonlib import SubProject
40 from .compilers.compilers import Language
41
42 DeprecatedType: TypeAlias = T.Union[bool, str, T.Dict[str, str], T.List[str]]
43 AnyOptionType: TypeAlias = T.Union[
44 'UserBooleanOption', 'UserComboOption', 'UserFeatureOption',
45 'UserIntegerOption', 'UserStdOption', 'UserStringArrayOption',
46 'UserStringOption', 'UserUmaskOption']
47 ElementaryOptionValues: TypeAlias = T.Union[str, int, bool, T.List[str]]
48 MutableKeyedOptionDictType: TypeAlias = T.Dict['OptionKey', AnyOptionType]
49
50 _OptionKeyTuple: TypeAlias = T.Tuple[T.Optional[str], MachineChoice, str]
51
52 DEFAULT_YIELDING = False
53
54 # Can't bind this near the class method it seems, sadly.
55 _T = T.TypeVar('_T')
56
57 backendlist = ['ninja', 'vs', 'vs2010', 'vs2012', 'vs2013', 'vs2015', 'vs2017', 'vs2019', 'vs2022', 'vs2026', 'xcode', 'none']
58 genvslitelist = ['vs2022', 'vs2026']
59 buildtypelist = ['plain', 'debug', 'debugoptimized', 'release', 'minsize', 'custom']
60
61 # This is copied from coredata. There is no way to share this, because this
62 # is used in the OptionKey constructor, and the coredata lists are
63 # OptionKeys...
64 _BUILTIN_NAMES = {
65 'prefix',
66 'bindir',
67 'datadir',
68 'includedir',
69 'infodir',
70 'libdir',
71 'licensedir',
72 'libexecdir',
73 'localedir',
74 'localstatedir',
75 'mandir',
76 'sbindir',
77 'sharedstatedir',
78 'sysconfdir',
79 'auto_features',
80 'backend',
81 'buildtype',
82 'debug',
83 'default_library',
84 'default_both_libraries',
85 'errorlogs',
86 'genvslite',
87 'install_umask',
88 'layout',
89 'optimization',
90 'prefer_static',
91 'stdsplit',
92 'strip',
93 'unity',
94 'unity_size',
95 'warning_level',
96 'werror',
97 'wrap_mode',
98 'force_fallback_for',
99 'pkg_config_path',
100 'cmake_prefix_path',
101 'vsenv',
102 'os2_emxomf',
103 }
104
105 _BAD_VALUE = 'Qwert Zuiopü'
106 _optionkey_cache: T.Dict[_OptionKeyTuple, OptionKey] = {}
107
108
109 class OptionKey:
110
111 """Represents an option key in the various option dictionaries.
112
113 This provides a flexible, powerful way to map option names from their
114 external form (things like subproject:build.option) to something that
115 internally easier to reason about and produce.
116 """
117
118 __slots__ = ('name', 'subproject', 'machine', '_hash')
119
120 name: str
121 subproject: T.Optional[str] # None is global, empty string means top level project
122 machine: MachineChoice
123 _hash: int
124
125 def __new__(cls,
126 name: str = '',
127 subproject: T.Optional[str] = None,
128 machine: MachineChoice = MachineChoice.HOST) -> OptionKey:
129 """The use of the __new__ method allows to add a transparent cache
130 to the OptionKey object creation, without breaking its API.
131 """
132 if not name:
133 return super().__new__(cls) # for unpickling, do not cache now
134
135 tuple_: _OptionKeyTuple = (subproject, machine, name)
136 try:
137 return _optionkey_cache[tuple_]
138 except KeyError:
139 instance = super().__new__(cls)
140 instance._init(name, subproject, machine)
141 _optionkey_cache[tuple_] = instance
142 return instance
143
144 def _init(self, name: str, subproject: T.Optional[str], machine: MachineChoice) -> None:
145 # We don't use the __init__ method, because it would be called after __new__
146 # while we need __new__ to initialise the object before populating the cache.
147
148 if not isinstance(machine, MachineChoice):
149 raise MesonException(f'Internal error, bad machine type: {machine}')
150 if not isinstance(name, str):
151 raise MesonBugException(f'Key name is not a string: {name}')
152 assert ':' not in name
153
154 object.__setattr__(self, 'name', name)
155 object.__setattr__(self, 'subproject', subproject)
156 object.__setattr__(self, 'machine', machine)
157 object.__setattr__(self, '_hash', hash((name, subproject, machine)))
158
159 def __setattr__(self, key: str, value: T.Any) -> None:
160 raise AttributeError('OptionKey instances do not support mutation.')
161
162 def __getstate__(self) -> T.Dict[str, T.Any]:
163 return {
164 'name': self.name,
165 'subproject': self.subproject,
166 'machine': self.machine,
167 }
168
169 def __setstate__(self, state: T.Dict[str, T.Any]) -> None:
170 # Here, the object is created using __new__()
171 self._init(**state)
172 _optionkey_cache[self._to_tuple()] = self
173
174 def __hash__(self) -> int:
175 return self._hash
176
177 def _to_tuple(self) -> _OptionKeyTuple:
178 return (self.subproject, self.machine, self.name)
179
180 def __eq__(self, other: object) -> bool:
181 if isinstance(other, OptionKey):
182 return self._to_tuple() == other._to_tuple()
183 return NotImplemented
184
185 def __ne__(self, other: object) -> bool:
186 if isinstance(other, OptionKey):
187 return self._to_tuple() != other._to_tuple()
188 return NotImplemented
189
190 def __lt__(self, other: object) -> bool:
191 if isinstance(other, OptionKey):
192 if self.subproject is None:
193 return other.subproject is not None
194 elif other.subproject is None:
195 return False
196 return self._to_tuple() < other._to_tuple()
197 return NotImplemented
198
199 def __le__(self, other: object) -> bool:
200 if isinstance(other, OptionKey):
201 if self.subproject is None and other.subproject is not None:
202 return True
203 elif self.subproject is not None and other.subproject is None:
204 return False
205 return self._to_tuple() <= other._to_tuple()
206 return NotImplemented
207
208 def __gt__(self, other: object) -> bool:
209 if isinstance(other, OptionKey):
210 if other.subproject is None:
211 return self.subproject is not None
212 elif self.subproject is None:
213 return False
214 return self._to_tuple() > other._to_tuple()
215 return NotImplemented
216
217 def __ge__(self, other: object) -> bool:
218 if isinstance(other, OptionKey):
219 if self.subproject is None and other.subproject is not None:
220 return False
221 elif self.subproject is not None and other.subproject is None:
222 return True
223 return self._to_tuple() >= other._to_tuple()
224 return NotImplemented
225
226 def __str__(self) -> str:
227 out = self.name
228 if self.machine is MachineChoice.BUILD:
229 out = f'build.{out}'
230 if self.subproject is not None:
231 out = f'{self.subproject}:{out}'
232 return out
233
234 def __repr__(self) -> str:
235 return f'OptionKey({self.name!r}, {self.subproject!r}, {self.machine!r})'
236
237 @classmethod
238 def from_string(cls, raw: str) -> 'OptionKey':
239 """Parse the raw command line format into a three part tuple.
240
241 This takes strings like `mysubproject:build.myoption` and Creates an
242 OptionKey out of them.
243 """
244 assert isinstance(raw, str)
245 try:
246 subproject, raw2 = raw.split(':')
247 except ValueError:
248 subproject, raw2 = None, raw
249
250 for_machine = MachineChoice.HOST
251 try:
252 prefix, raw3 = raw2.split('.')
253 if prefix == 'build':
254 for_machine = MachineChoice.BUILD
255 else:
256 raw3 = raw2
257 except ValueError:
258 raw3 = raw2
259
260 opt = raw3
261 assert ':' not in opt
262 assert opt.count('.') < 2
263
264 return cls(opt, subproject, for_machine)
265
266 def evolve(self,
267 name: T.Optional[str] = None,
268 subproject: T.Optional[str] = _BAD_VALUE,
269 machine: T.Optional[MachineChoice] = None) -> 'OptionKey':
270 """Create a new copy of this key, but with altered members.
271
272 For example:
273 >>> a = OptionKey('foo', '', MachineChoice.Host)
274 >>> b = OptionKey('foo', 'bar', MachineChoice.Host)
275 >>> b == a.evolve(subproject='bar')
276 True
277 """
278 # We have to be a little clever with lang here, because lang is valid
279 # as None, for non-compiler options
280 return OptionKey(name if name is not None else self.name,
281 subproject if subproject != _BAD_VALUE else self.subproject, # None is a valid value so it can'the default value in method declaration.
282 machine if machine is not None else self.machine)
283
284 def as_root(self) -> OptionKey:
285 """Convenience method for key.evolve(subproject='')."""
286 if self.subproject != '':
287 return self.evolve(subproject='')
288 return self
289
290 def as_build(self) -> OptionKey:
291 """Convenience method for key.evolve(machine=MachineChoice.BUILD)."""
292 if self.machine != MachineChoice.BUILD:
293 return self.evolve(machine=MachineChoice.BUILD)
294 return self
295
296 def as_host(self) -> OptionKey:
297 """Convenience method for key.evolve(machine=MachineChoice.HOST)."""
298 if self.machine != MachineChoice.HOST:
299 return self.evolve(machine=MachineChoice.HOST)
300 return self
301
302 def has_module_prefix(self) -> bool:
303 return '.' in self.name
304
305 def get_module_prefix(self) -> T.Optional[str]:
306 if self.has_module_prefix():
307 return self.name.split('.', 1)[0]
308 return None
309
310 def is_for_build(self) -> bool:
311 return self.machine is MachineChoice.BUILD
312
313 if T.TYPE_CHECKING:
314 OptionDict: TypeAlias = T.Dict[OptionKey, ElementaryOptionValues]
315
316 @dataclasses.dataclass
317 class UserOption(T.Generic[_T], HoldableObject):
318
319 name: str
320 description: str
321 value_: dataclasses.InitVar[_T]
322 yielding: bool = DEFAULT_YIELDING
323 deprecated: DeprecatedType = False
324 readonly: bool = dataclasses.field(default=False)
325 parent: T.Optional[UserOption] = None
326
327 def __post_init__(self, value_: _T) -> None:
328 self.value = self.validate_value(value_)
329 # Final isn't technically allowed in a __post_init__ method
330 self.default: Final[_T] = self.value # type: ignore[misc]
331
332 def listify(self, value: ElementaryOptionValues) -> T.List[str]:
333 if isinstance(value, list):
334 return value
335 if isinstance(value, bool):
336 return ['true'] if value else ['false']
337 if isinstance(value, int):
338 return [str(value)]
339 return [value]
340
341 def printable_value(self) -> ElementaryOptionValues:
342 assert isinstance(self.value, (str, int, bool, list))
343 return self.value
344
345 def printable_choices(self) -> T.Optional[T.List[str]]:
346 return None
347
348 # Check that the input is a valid value and return the
349 # "cleaned" or "native" version. For example the Boolean
350 # option could take the string "true" and return True.
351 def validate_value(self, value: object) -> _T:
352 raise RuntimeError('Derived option class did not override validate_value.')
353
354 def set_value(self, newvalue: object) -> bool:
355 oldvalue = self.value
356 self.value = self.validate_value(newvalue)
357 return self.value != oldvalue
358
359 @dataclasses.dataclass
360 class EnumeratedUserOption(UserOption[_T]):
361
362 """A generic UserOption that has enumerated values."""
363
364 choices: T.List[_T] = dataclasses.field(default_factory=list)
365
366 def printable_choices(self) -> T.Optional[T.List[str]]:
367 return [str(c) for c in self.choices]
368
369
370 class UserStringOption(UserOption[str]):
371
372 def validate_value(self, value: object) -> str:
373 if not isinstance(value, str):
374 raise MesonException(f'The value of option "{self.name}" is "{value}", which is not a string.')
375 return value
376
377 @dataclasses.dataclass
378 class UserBooleanOption(EnumeratedUserOption[bool]):
379
380 choices: T.List[bool] = dataclasses.field(default_factory=lambda: [True, False])
381
382 def __bool__(self) -> bool:
383 return self.value
384
385 def validate_value(self, value: object) -> bool:
386 if isinstance(value, bool):
387 return value
388 if not isinstance(value, str):
389 raise MesonException(f'Option "{self.name}" value {value} cannot be converted to a boolean')
390 if value.lower() == 'true':
391 return True
392 if value.lower() == 'false':
393 return False
394 raise MesonException(f'Option "{self.name}" value {value} is not boolean (true or false).')
395
396
397 class _UserIntegerBase(UserOption[_T]):
398
399 min_value: T.Optional[int]
400 max_value: T.Optional[int]
401
402 if T.TYPE_CHECKING:
403 def toint(self, v: str) -> int: ...
404
405 def __post_init__(self, value_: _T) -> None:
406 super().__post_init__(value_)
407 choices: T.List[str] = []
408 if self.min_value is not None:
409 choices.append(f'>= {self.min_value!s}')
410 if self.max_value is not None:
411 choices.append(f'<= {self.max_value!s}')
412 self.__choices: str = ', '.join(choices)
413
414 def printable_choices(self) -> T.Optional[T.List[str]]:
415 return [self.__choices]
416
417 def validate_value(self, value: object) -> _T:
418 if isinstance(value, str):
419 value = T.cast('_T', self.toint(value))
420 if not isinstance(value, int):
421 raise MesonException(f'Value {value!r} for option "{self.name}" is not an integer.')
422 if self.min_value is not None and value < self.min_value:
423 raise MesonException(f'Value {value} for option "{self.name}" is less than minimum value {self.min_value}.')
424 if self.max_value is not None and value > self.max_value:
425 raise MesonException(f'Value {value} for option "{self.name}" is more than maximum value {self.max_value}.')
426 return T.cast('_T', value)
427
428
429 @dataclasses.dataclass
430 class UserIntegerOption(_UserIntegerBase[int]):
431
432 min_value: T.Optional[int] = None
433 max_value: T.Optional[int] = None
434
435 def toint(self, valuestring: str) -> int:
436 try:
437 return int(valuestring)
438 except ValueError:
439 raise MesonException(f'Value string "{valuestring}" for option "{self.name}" is not convertible to an integer.')
440
441
442 class OctalInt(int):
443 # NinjaBackend.get_user_option_args uses str() to converts it to a command line option
444 # UserUmaskOption.toint() uses int(str, 8) to convert it to an integer
445 # So we need to use oct instead of dec here if we do not want values to be misinterpreted.
446 def __str__(self) -> str:
447 return oct(int(self))
448
449
450 @dataclasses.dataclass
451 class UserUmaskOption(_UserIntegerBase[T.Union["Literal['preserve']", OctalInt]]):
452
453 min_value: T.Optional[int] = dataclasses.field(default=0, init=False)
454 max_value: T.Optional[int] = dataclasses.field(default=0o777, init=False)
455
456 def printable_value(self) -> str:
457 if isinstance(self.value, int):
458 return format(self.value, '04o')
459 return self.value
460
461 def validate_value(self, value: object) -> T.Union[Literal['preserve'], OctalInt]:
462 if value == 'preserve':
463 return 'preserve'
464 return OctalInt(super().validate_value(value))
465
466 def toint(self, valuestring: str) -> int:
467 try:
468 return int(valuestring, 8)
469 except ValueError as e:
470 raise MesonException(f'Invalid mode for option "{self.name}" {e}')
471
472
473 @dataclasses.dataclass
474 class UserComboOption(EnumeratedUserOption[str]):
475
476 def validate_value(self, value: object) -> str:
477 if value not in self.choices:
478 if isinstance(value, bool):
479 _type = 'boolean'
480 elif isinstance(value, (int, float)):
481 _type = 'number'
482 else:
483 _type = 'string'
484 optionsstring = ', '.join([f'"{item}"' for item in self.choices])
485 raise MesonException('Value "{}" (of type "{}") for option "{}" is not one of the choices.'
486 ' Possible choices are (as string): {}.'.format(
487 value, _type, self.name, optionsstring))
488
489 assert isinstance(value, str), 'for mypy'
490 return value
491
492 @dataclasses.dataclass
493 class UserArrayOption(UserOption[T.List[_T]]):
494
495 value_: dataclasses.InitVar[T.Union[_T, T.List[_T]]]
496 choices: T.Optional[T.List[_T]] = None
497 split_args: bool = False
498 allow_dups: bool = False
499
500 def extend_value(self, value: T.Union[str, T.List[str]]) -> None:
501 """Extend the value with an additional value."""
502 new = self.validate_value(value)
503 self.set_value(self.value + new)
504
505 def printable_choices(self) -> T.Optional[T.List[str]]:
506 if self.choices is None:
507 return None
508 return [str(c) for c in self.choices]
509
510
511 @dataclasses.dataclass
512 class UserStringArrayOption(UserArrayOption[str]):
513
514 def listify(self, value: object) -> T.List[str]:
515 try:
516 return listify_array_value(value, self.split_args)
517 except MesonException as e:
518 raise MesonException(f'error in option "{self.name}": {e!s}')
519
520 def validate_value(self, value: object) -> T.List[str]:
521 newvalue = self.listify(value)
522
523 if not self.allow_dups and len(set(newvalue)) != len(newvalue):
524 msg = 'Duplicated values in array option is deprecated. ' \
525 'This will become a hard error in meson 2.0.'
526 mlog.deprecation(msg)
527 for i in newvalue:
528 if not isinstance(i, str):
529 raise MesonException(f'String array element "{newvalue!s}" for option "{self.name}" is not a string.')
530 if self.choices:
531 bad = [x for x in newvalue if x not in self.choices]
532 if bad:
533 raise MesonException('Value{} "{}" for option "{}" {} not in allowed choices: "{}"'.format(
534 '' if len(bad) == 1 else 's',
535 ', '.join(bad),
536 self.name,
537 'is' if len(bad) == 1 else 'are',
538 ', '.join(self.choices))
539 )
540 return newvalue
541
542
543 @dataclasses.dataclass
544 class UserFeatureOption(UserComboOption):
545
546 choices: T.List[str] = dataclasses.field(
547 # Ensure we get a copy with the lambda
548 default_factory=lambda: ['enabled', 'disabled', 'auto'], init=False)
549
550
551 _U = T.TypeVar('_U', bound=UserOption)
552
553
554 def choices_are_different(a: _U, b: _U) -> bool:
555 """Are the choices between two options the same?
556
557 :param a: A UserOption[T]
558 :param b: A second UserOption[T]
559 :return: True if the choices have changed, otherwise False
560 """
561 if isinstance(a, EnumeratedUserOption):
562 # We expect `a` and `b` to be of the same type, but can't really annotate it that way.
563 assert isinstance(b, EnumeratedUserOption), 'for mypy'
564 return a.choices != b.choices
565 elif isinstance(a, UserArrayOption):
566 # We expect `a` and `b` to be of the same type, but can't really annotate it that way.
567 assert isinstance(b, UserArrayOption), 'for mypy'
568 return a.choices != b.choices
569 elif isinstance(a, _UserIntegerBase):
570 assert isinstance(b, _UserIntegerBase), 'for mypy'
571 return a.max_value != b.max_value or a.min_value != b.min_value
572
573 return False
574
575
576 class UserStdOption(UserComboOption):
577 '''
578 UserOption specific to c_std and cpp_std options. User can set a list of
579 STDs in preference order and it selects the first one supported by current
580 compiler.
581
582 For historical reasons, some compilers (msvc) allowed setting a GNU std and
583 silently fell back to C std. This is now deprecated. Projects that support
584 both GNU and MSVC compilers should set e.g. c_std=gnu11,c11.
585
586 This is not using self.deprecated mechanism we already have for project
587 options because we want to print a warning if ALL values are deprecated, not
588 if SOME values are deprecated.
589 '''
590 def __init__(self, lang: str, all_stds: T.List[str]) -> None:
591 self.lang = lang.lower()
592 self.all_stds = ['none'] + all_stds
593 # Map a deprecated std to its replacement. e.g. gnu11 -> c11.
594 self.deprecated_stds: T.Dict[str, str] = {}
595 opt_name = 'cpp_std' if lang == 'c++' else f'{lang}_std'
596 super().__init__(opt_name, f'{lang} language standard to use', 'none', choices=['none'])
597
598 def set_versions(self, versions: T.List[str], gnu: bool = False, gnu_deprecated: bool = False) -> None:
599 assert all(std in self.all_stds for std in versions)
600 self.choices += versions
601 if gnu:
602 gnu_stds_map = {f'gnu{std[1:]}': std for std in versions}
603 if gnu_deprecated:
604 self.deprecated_stds.update(gnu_stds_map)
605 else:
606 self.choices += gnu_stds_map.keys()
607
608 def validate_value(self, value: object) -> str:
609 try:
610 candidates = listify_array_value(value)
611 except MesonException as e:
612 raise MesonException(f'error in option "{self.name}": {e!s}')
613 for std in candidates:
614 if not isinstance(std, str):
615 raise MesonException(f'String array element "{candidates!s}" for option "{self.name}" is not a string.')
616 unknown = ','.join(std for std in candidates if std not in self.all_stds)
617 if unknown:
618 raise MesonException(f'Unknown option "{self.name}" value {unknown}. Possible values are {self.all_stds}.')
619 # Check first if any of the candidates are not deprecated
620 for std in candidates:
621 if std in self.choices:
622 return std
623 # Fallback to a deprecated std if any
624 for std in candidates:
625 newstd = self.deprecated_stds.get(std)
626 if newstd is not None:
627 mlog.deprecation(
628 f'None of the values {candidates} are supported by the {self.lang} compiler.\n' +
629 f'However, the deprecated {std} std currently falls back to {newstd}.\n' +
630 'This will be an error in meson 2.0.\n' +
631 'If the project supports both GNU and MSVC compilers, a value such as\n' +
632 '"c_std=gnu11,c11" specifies that GNU is preferred but it can safely fallback to plain c11.', once=True)
633 return newstd
634 raise MesonException(f'None of values {candidates} are supported by the {self.lang.upper()} compiler. ' +
635 f'Possible values for option "{self.name}" are {self.choices}')
636
637
638 def argparse_name_to_arg(name: str) -> str:
639 if name == 'warning_level':
640 return '--warnlevel'
641 return '--' + name.replace('_', '-')
642
643
644 def argparse_prefixed_default(opt: AnyOptionType, name: OptionKey, prefix: str = '') -> ElementaryOptionValues:
645 if isinstance(opt, (UserComboOption, UserIntegerOption, UserUmaskOption)):
646 return T.cast('ElementaryOptionValues', opt.default)
647 try:
648 return BUILTIN_DIR_NOPREFIX_OPTIONS[name][prefix]
649 except KeyError:
650 return T.cast('ElementaryOptionValues', opt.default)
651
652
653 # Update `docs/markdown/Builtin-options.md` after changing the options below
654 # Also update mesonlib._BUILTIN_NAMES. See the comment there for why this is required.
655 # Please also update completion scripts in $MESONSRC/data/shell-completions/
656 BUILTIN_DIR_OPTIONS: T.Mapping[OptionKey, AnyOptionType] = {
657 OptionKey(o.name): o for o in [
658 UserStringOption('prefix', 'Installation prefix', default_prefix()),
659 UserStringOption('bindir', 'Executable directory', 'bin'),
660 UserStringOption('datadir', 'Data file directory', default_datadir()),
661 UserStringOption('includedir', 'Header file directory', default_includedir()),
662 UserStringOption('infodir', 'Info page directory', default_infodir()),
663 UserStringOption('libdir', 'Library directory', default_libdir()),
664 UserStringOption('licensedir', 'Licenses directory', ''),
665 UserStringOption('libexecdir', 'Library executable directory', default_libexecdir()),
666 UserStringOption('localedir', 'Locale data directory', default_localedir()),
667 UserStringOption('localstatedir', 'Localstate data directory', 'var'),
668 UserStringOption('mandir', 'Manual page directory', default_mandir()),
669 UserStringOption('sbindir', 'System executable directory', default_sbindir()),
670 UserStringOption('sharedstatedir', 'Architecture-independent data directory', 'com'),
671 UserStringOption('sysconfdir', 'Sysconf data directory', default_sysconfdir()),
672 ]
673 }
674
675 BUILTIN_CORE_OPTIONS: T.Mapping[OptionKey, AnyOptionType] = {
676 OptionKey(o.name): o for o in T.cast('T.List[AnyOptionType]', [
677 UserFeatureOption('auto_features', "Override value of all 'auto' features", 'auto'),
678 UserComboOption('backend', 'Backend to use', 'ninja', choices=backendlist, readonly=True),
679 UserComboOption(
680 'genvslite',
681 'Setup multiple buildtype-suffixed ninja-backend build directories, '
682 'and a [builddir]_vs containing a Visual Studio meta-backend with multiple configurations that calls into them',
683 'vs2022',
684 choices=genvslitelist
685 ),
686 UserComboOption('buildtype', 'Build type to use', 'debug', choices=buildtypelist),
687 UserBooleanOption('debug', 'Enable debug symbols and other information', True),
688 UserComboOption('default_library', 'Default library type', 'shared', choices=['shared', 'static', 'both']),
689 UserComboOption('default_both_libraries', 'Default library type for both_libraries', 'shared',
690 choices=['shared', 'static', 'auto']),
691 UserBooleanOption('errorlogs', "Whether to print the logs from failing tests", True),
692 UserUmaskOption('install_umask', 'Default umask to apply on permissions of installed files', OctalInt(0o022)),
693 UserComboOption('layout', 'Build directory layout', 'mirror', choices=['mirror', 'flat']),
694 UserComboOption('namingscheme', 'How target file names are formed', 'classic', choices=['platform', 'classic']),
695 UserComboOption('optimization', 'Optimization level', '0', choices=['plain', '0', 'g', '1', '2', '3', 's']),
696 UserBooleanOption('prefer_static', 'Whether to try static linking before shared linking', False),
697 UserBooleanOption('stdsplit', 'Split stdout and stderr in test logs', True),
698 UserBooleanOption('strip', 'Strip targets on install', False),
699 UserComboOption('unity', 'Unity build', 'off', choices=['on', 'off', 'subprojects']),
700 UserIntegerOption('unity_size', 'Unity block size', 4, min_value=2),
701 UserComboOption('warning_level', 'Compiler warning level to use', '1', choices=['0', '1', '2', '3', 'everything']),
702 UserBooleanOption('werror', 'Treat warnings as errors', False),
703 UserComboOption('wrap_mode', 'Wrap mode', 'default', choices=['default', 'nofallback', 'nodownload', 'forcefallback', 'nopromote']),
704 UserStringArrayOption('force_fallback_for', 'Force fallback for those subprojects', []),
705 UserBooleanOption('vsenv', 'Activate Visual Studio environment', False, readonly=True),
706 UserBooleanOption('os2_emxomf', 'Use OMF format on OS/2', False),
707
708 # Pkgconfig module
709 UserBooleanOption('pkgconfig.relocatable', 'Generate pkgconfig files as relocatable', False),
710
711 # Python module
712 UserIntegerOption('python.bytecompile', 'Whether to compile bytecode', 0, min_value=-1, max_value=2),
713 UserComboOption('python.install_env', 'Which python environment to install to', 'prefix',
714 choices=['auto', 'prefix', 'system', 'venv']),
715 UserStringOption('python.platlibdir', 'Directory for site-specific, platform-specific files.', ''),
716 UserStringOption('python.purelibdir', 'Directory for site-specific, non-platform-specific files.', ''),
717 UserBooleanOption('python.allow_limited_api', 'Whether to allow use of the Python Limited API', True),
718 UserStringOption('python.build_config', 'Config file containing the build details for the target Python installation.', ''),
719 ])
720 }
721
722 BUILTIN_OPTIONS = OrderedDict(chain(BUILTIN_DIR_OPTIONS.items(), BUILTIN_CORE_OPTIONS.items()))
723
724 BUILTIN_OPTIONS_PER_MACHINE: T.Mapping[OptionKey, AnyOptionType] = {
725 OptionKey(o.name): o for o in [
726 UserStringArrayOption('pkg_config_path', 'List of additional paths for pkg-config to search', []),
727 UserStringArrayOption('cmake_prefix_path', 'List of additional prefixes for cmake to search', []),
728 ]
729 }
730
731 # Special prefix-dependent defaults for installation directories that reside in
732 # a path outside of the prefix in FHS and common usage.
733 BUILTIN_DIR_NOPREFIX_OPTIONS: T.Dict[OptionKey, T.Dict[str, str]] = {
734 OptionKey('sysconfdir'): {'/usr': '/etc'},
735 OptionKey('localstatedir'): {'/usr': '/var', '/usr/local': '/var/local'},
736 OptionKey('sharedstatedir'): {'/usr': '/var/lib', '/usr/local': '/var/local/lib'},
737 OptionKey('python.platlibdir'): {},
738 OptionKey('python.purelibdir'): {},
739 }
740
741 MSCRT_VALS = ['none', 'md', 'mdd', 'mt', 'mtd']
742
743 COMPILER_BASE_OPTIONS: T.Mapping[OptionKey, AnyOptionType] = {
744 OptionKey(o.name): o for o in T.cast('T.List[AnyOptionType]', [
745 UserBooleanOption('b_pch', 'Use precompiled headers', True),
746 UserBooleanOption('b_lto', 'Use link time optimization', False),
747 UserIntegerOption('b_lto_threads', 'Use multiple threads for Link Time Optimization', 0),
748 UserComboOption('b_lto_mode', 'Select between different LTO modes.', 'default', choices=['default', 'thin']),
749 UserBooleanOption('b_thinlto_cache', 'Use LLVM ThinLTO caching for faster incremental builds', False),
750 UserStringOption('b_thinlto_cache_dir', 'Directory to store ThinLTO cache objects', ''),
751 UserStringArrayOption('b_sanitize', 'Code sanitizer to use', []),
752 UserBooleanOption('b_lundef', 'Use -Wl,--no-undefined when linking', True),
753 UserBooleanOption('b_asneeded', 'Use -Wl,--as-needed when linking', True),
754 UserComboOption(
755 'b_pgo', 'Use profile guided optimization', 'off', choices=['off', 'generate', 'use']),
756 UserBooleanOption('b_coverage', 'Enable coverage tracking.', False),
757 UserComboOption(
758 'b_colorout', 'Use colored output', 'always', choices=['auto', 'always', 'never']),
759 UserComboOption(
760 'b_ndebug', 'Disable asserts', 'false', choices=['true', 'false', 'if-release']),
761 UserBooleanOption('b_staticpic', 'Build static libraries as position independent', True),
762 UserBooleanOption('b_pie', 'Build executables as position independent', False),
763 UserBooleanOption('b_bitcode', 'Generate and embed bitcode (only macOS/iOS/tvOS)', False),
764 UserComboOption(
765 'b_vscrt', 'VS run-time library type to use.', 'from_buildtype',
766 choices=MSCRT_VALS + ['from_buildtype', 'static_from_buildtype']),
767 ])
768 }
769
770 class OptionStore:
771 DEFAULT_DEPENDENTS = {'plain': ('plain', False),
772 'debug': ('0', True),
773 'debugoptimized': ('2', True),
774 'release': ('3', False),
775 'minsize': ('s', True),
776 }
777
778 def __init__(self, is_cross: bool) -> None:
779 self.options: T.Dict['OptionKey', 'AnyOptionType'] = {}
780 self.subprojects: T.Set[str] = set()
781 self.project_options: T.Set[OptionKey] = set()
782 self.module_options: T.Set[OptionKey] = set()
783 from .compilers import all_languages
784 self.all_languages = set(all_languages)
785 self.augments: OptionDict = {}
786 self.is_cross = is_cross
787
788 # Pending options are configuration dependent options that could be
789 # initialized later, such as compiler options
790 self.pending_options: OptionDict = {}
791 # Subproject options from toplevel project()
792 self.pending_subproject_options: OptionDict = {}
793 # Class for host-aware path handling
794 self.pure_path_class: T.Type[pathlib.PurePath] = pathlib.PurePath
795
796 def set_host_machine(self, machine: MachineInfo) -> None:
797 """Use the given MachineInfo for host-aware path handling."""
798 self.pure_path_class = machine.pure_path_class
799
800 def _is_host_absolute(self, path: str) -> bool:
801 """Check if path is absolute according to host machine path semantics."""
802 path_obj = self.pure_path_class(path)
803 if isinstance(path_obj, pathlib.PureWindowsPath) and path_obj.root:
804 # Accept Windows root-relative paths (root but no drive, like /myprog)
805 # so that the same path can be used in cross-compilation setups
806 return True
807 return path_obj.is_absolute()
808
809 def ensure_and_validate_key(self, key: T.Union[OptionKey, str]) -> OptionKey:
810 if isinstance(key, str):
811 return OptionKey(key)
812 # FIXME. When not cross building all "build" options need to fall back
813 # to "host" options due to how the old code worked.
814 #
815 # This is NOT how it should be.
816 #
817 # This needs to be changed to that trying to add or access "build" keys
818 # is a hard error and fix issues that arise.
819 #
820 # I did not do this yet, because it would make this MR even
821 # more massive than it already is. Later then.
822 if not (self.is_cross and self.is_per_machine_option(key)):
823 key = key.as_host()
824 return key
825
826 def get_pending_value(self, key: T.Union[OptionKey, str], default: T.Optional[ElementaryOptionValues] = None) -> ElementaryOptionValues:
827 key = self.ensure_and_validate_key(key)
828 if key in self.options:
829 return self.options[key].value
830 return self.pending_options.get(key, default)
831
832 def __len__(self) -> int:
833 return len(self.options)
834
835 def resolve_option(self, key: 'T.Union[OptionKey, str]') -> AnyOptionType:
836 key = self.ensure_and_validate_key(key)
837 potential = self.options.get(key, None)
838 if self.is_project_option(key):
839 assert key.subproject is not None
840 if potential is None:
841 raise KeyError(f'Tried to access nonexistant project option {key}.')
842 else:
843 if potential is None:
844 parent_key = OptionKey(key.name, subproject=None, machine=key.machine)
845 if parent_key not in self.options:
846 raise KeyError(f'Tried to access nonexistant project parent option {parent_key}.')
847 # This is a global option but it can still have per-project
848 # augment, so return the subproject key.
849 return self.options[parent_key]
850 return potential
851
852 def get_option_and_value_for(self, key: OptionKey) -> T.Tuple[AnyOptionType, ElementaryOptionValues]:
853 key = self.ensure_and_validate_key(key)
854 option_object = self.resolve_option(key)
855 computed_value = option_object.value
856 if key in self.augments:
857 assert key.subproject is not None
858 computed_value = self.augments[key]
859 elif option_object.yielding:
860 computed_value = option_object.parent.value
861 return (option_object, computed_value)
862
863 def option_has_value(self, key: OptionKey, value: ElementaryOptionValues) -> bool:
864 option_object, current_value = self.get_option_and_value_for(key)
865 return option_object.validate_value(value) == current_value
866
867 def get_value_for(self, name: 'T.Union[OptionKey, str]', subproject: T.Optional[str] = None) -> ElementaryOptionValues:
868 if isinstance(name, str):
869 key = OptionKey(name, subproject)
870 else:
871 assert subproject is None
872 key = name
873 _, resolved_value = self.get_option_and_value_for(key)
874 return resolved_value
875
876 def add_system_option(self, key: T.Union[OptionKey, str], valobj: AnyOptionType) -> None:
877 key = self.ensure_and_validate_key(key)
878 if '.' in key.name:
879 raise MesonException(f'Internal error: non-module option has a period in its name {key.name}.')
880 self.add_system_option_internal(key, valobj)
881
882 def add_system_option_internal(self, key: OptionKey, valobj: AnyOptionType) -> None:
883 assert isinstance(valobj, UserOption)
884 if not isinstance(valobj.name, str):
885 assert isinstance(valobj.name, str)
886 if key in self.options:
887 return
888
889 pval = self.pending_options.pop(key, None)
890 if key.subproject:
891 proj_key = key.evolve(subproject=None)
892 self.add_system_option_internal(proj_key, valobj)
893 else:
894 self.options[key] = valobj
895 if pval is not None:
896 self.set_option(key, pval)
897
898 def add_compiler_option(self, language: Language, key: T.Union[OptionKey, str], valobj: AnyOptionType) -> None:
899 key = self.ensure_and_validate_key(key)
900 if not key.name.startswith(language + '_'):
901 raise MesonException(f'Internal error: all compiler option names must start with language prefix. ({key.name} vs {language}_)')
902 self.add_system_option(key, valobj)
903
904 def add_project_option(self, key: T.Union[OptionKey, str], valobj: AnyOptionType) -> None:
905 key = self.ensure_and_validate_key(key)
906 assert key.subproject is not None
907 if key in self.options:
908 raise MesonException(f'Internal error: tried to add a project option {key} that already exists.')
909 if valobj.yielding and key.subproject:
910 parent_key = key.as_root()
911 try:
912 parent_option = self.options[parent_key]
913 # If parent object has different type, do not yield.
914 # This should probably be an error.
915 if type(parent_option) is type(valobj):
916 valobj.parent = parent_option
917 except KeyError:
918 # Subproject is set to yield, but top level
919 # project does not have an option of the same
920 pass
921 valobj.yielding = valobj.parent is not None
922
923 self.options[key] = valobj
924 self.project_options.add(key)
925 assert key not in self.pending_options
926
927 def add_module_option(self, modulename: str, key: T.Union[OptionKey, str], valobj: AnyOptionType) -> None:
928 key = self.ensure_and_validate_key(key)
929 if key.name.startswith('build.'):
930 raise MesonException('FATAL internal error: somebody goofed option handling.')
931 if not key.name.startswith(modulename + '.'):
932 raise MesonException('Internal error: module option name {key.name} does not start with module prefix {modulename}.')
933 self.add_system_option_internal(key, valobj)
934 self.module_options.add(key)
935
936 def add_builtin_option(self, key: OptionKey, opt: AnyOptionType) -> None:
937 # Create a copy of the object, as we're going to mutate it
938 opt = copy.copy(opt)
939 assert key.subproject is None
940 new_value = argparse_prefixed_default(opt, key, default_prefix())
941 opt.set_value(new_value)
942
943 modulename = key.get_module_prefix()
944 if modulename:
945 self.add_module_option(modulename, key, opt)
946 else:
947 self.add_system_option(key, opt)
948
949 def init_builtins(self) -> None:
950 # Create builtin options with default values
951 for key, opt in BUILTIN_OPTIONS.items():
952 self.add_builtin_option(key, opt)
953 for for_machine in iter(MachineChoice):
954 for key, opt in BUILTIN_OPTIONS_PER_MACHINE.items():
955 self.add_builtin_option(key.evolve(machine=for_machine), opt)
956
957 def sanitize_prefix(self, prefix: str) -> str:
958 prefix = os.path.expanduser(prefix)
959 if not self._is_host_absolute(prefix):
960 raise MesonException(f'prefix value {prefix!r} must be an absolute path')
961 if prefix.endswith('/') or prefix.endswith('\\'):
962 # On Windows we need to preserve the trailing slash if the
963 # string is of type 'C:\' because 'C:' is not an absolute path.
964 if len(prefix) == 3 and prefix[1] == ':':
965 pass
966 # If prefix is a single character, preserve it since it is
967 # the root directory.
968 elif len(prefix) == 1:
969 pass
970 else:
971 prefix = prefix[:-1]
972 return prefix
973
974 def sanitize_dir_option_value(self, prefix: str, option: OptionKey, value: T.Any) -> T.Any:
975 '''
976 If the option is an installation directory option, the value is an
977 absolute path and resides within prefix, return the value
978 as a path relative to the prefix. Otherwise, return it as is.
979
980 This way everyone can do f.ex, get_option('libdir') and usually get
981 the library directory relative to prefix, even though it really
982 should not be relied upon.
983 '''
984 try:
985 value = self.pure_path_class(value)
986 except TypeError:
987 return value
988 if option.name.endswith('dir') and value.is_absolute() and \
989 option not in BUILTIN_DIR_NOPREFIX_OPTIONS:
990 try:
991 # Try to relativize the path.
992 value = value.relative_to(prefix)
993 except ValueError:
994 # Path is not relative, let’s keep it as is.
995 pass
996 if '..' in value.parts:
997 raise MesonException(
998 f"The value of the '{option}' option is '{value}' but "
999 "directory options are not allowed to contain '..'.\n"
1000 f"If you need a path outside of the {prefix!r} prefix, "
1001 "please use an absolute path."
1002 )
1003 # .as_posix() keeps the posix-like file separators Meson uses.
1004 return value.as_posix()
1005
1006 def set_option(self, key: OptionKey, new_value: ElementaryOptionValues, first_invocation: bool = False) -> bool:
1007 changed = False
1008 error_key = key
1009 if error_key.subproject == '':
1010 error_key = error_key.evolve(subproject=None)
1011
1012 if key.name == 'prefix':
1013 assert isinstance(new_value, str), 'for mypy'
1014 new_value = self.sanitize_prefix(new_value)
1015 elif self.is_builtin_option(key):
1016 prefix = self.get_value_for('prefix')
1017 assert isinstance(prefix, str), 'for mypy'
1018 new_value = self.sanitize_dir_option_value(prefix, key, new_value)
1019
1020 try:
1021 opt = self.resolve_option(key)
1022 except KeyError:
1023 raise MesonException(f'Unknown option: "{error_key}".')
1024
1025 if opt.deprecated is True:
1026 mlog.deprecation(f'Option "{error_key}" is deprecated')
1027 elif isinstance(opt.deprecated, list):
1028 for v in opt.listify(new_value):
1029 if v in opt.deprecated:
1030 mlog.deprecation(f'Option "{error_key}" value {v!r} is deprecated')
1031 elif isinstance(opt.deprecated, dict):
1032 def replace(v: str) -> str:
1033 assert isinstance(opt.deprecated, dict) # No, Mypy can not tell this from two lines above
1034 newvalue = opt.deprecated.get(v)
1035 if newvalue is not None:
1036 mlog.deprecation(f'Option "{error_key}" value {v!r} is replaced by {newvalue!r}')
1037 return newvalue
1038 return v
1039 valarr = [replace(v) for v in opt.listify(new_value)]
1040 new_value = ','.join(valarr)
1041 elif isinstance(opt.deprecated, str):
1042 mlog.deprecation(f'Option "{error_key}" is replaced by {opt.deprecated!r}')
1043 # Change both this aption and the new one pointed to.
1044 changed |= self.set_option(key.evolve(name=opt.deprecated), new_value, first_invocation)
1045
1046 new_value = opt.validate_value(new_value)
1047 if key in self.options:
1048 old_value = opt.value
1049 opt.set_value(new_value)
1050 opt.yielding = False
1051 else:
1052 assert key.subproject is not None
1053 old_value = self.augments.get(key, opt.value)
1054 self.augments[key] = new_value
1055
1056 changed |= old_value != new_value
1057 if opt.readonly and changed and not first_invocation:
1058 raise MesonException(f'Tried to modify read only option "{error_key}"')
1059
1060 if key.name == 'prefix' and first_invocation and changed:
1061 assert isinstance(old_value, str), 'for mypy'
1062 assert isinstance(new_value, str), 'for mypy'
1063 self.reset_prefixed_options(old_value, new_value)
1064
1065 if changed and key.name == 'buildtype' and new_value != 'custom':
1066 assert isinstance(new_value, str), 'for mypy'
1067 optimization, debug = self.DEFAULT_DEPENDENTS[new_value]
1068 dkey = key.evolve(name='debug')
1069 optkey = key.evolve(name='optimization')
1070 self.set_option(dkey, debug, first_invocation)
1071 self.set_option(optkey, optimization, first_invocation)
1072
1073 return changed
1074
1075 def set_user_option(self, o: OptionKey, new_value: ElementaryOptionValues, first_invocation: bool = False) -> bool:
1076 if not self.is_cross and o.is_for_build():
1077 return False
1078
1079 # This is complicated by the fact that a string can have two meanings:
1080 #
1081 # default_options: 'foo=bar'
1082 #
1083 # can be either
1084 #
1085 # A) a system option in which case the subproject is None
1086 # B) a project option, in which case the subproject is ''
1087 #
1088 # The key parsing function can not handle the difference between the two
1089 # and defaults to A.
1090 if o in self.options:
1091 return self.set_option(o, new_value, first_invocation)
1092
1093 # could also be an augment...
1094 global_option = o.evolve(subproject=None)
1095 if o.subproject is not None and global_option in self.options:
1096 return self.set_option(o, new_value, first_invocation)
1097
1098 if self.accept_as_pending_option(o, first_invocation=first_invocation):
1099 old_value = self.pending_options.get(o, None)
1100 self.pending_options[o] = new_value
1101 return old_value is None or str(old_value) != new_value
1102 elif o.subproject is None:
1103 o = o.as_root()
1104 return self.set_option(o, new_value, first_invocation)
1105 else:
1106 raise MesonException(f'Unknown option: "{o}".')
1107
1108 def set_from_configure_command(self, D_args: T.Dict[OptionKey, T.Optional[str]]) -> bool:
1109 dirty = False
1110 for key, valstr in D_args.items():
1111 if valstr is not None:
1112 dirty |= self.set_user_option(key, valstr)
1113 continue
1114
1115 if key in self.augments:
1116 del self.augments[key]
1117 dirty = True
1118 else:
1119 if key not in self.options:
1120 raise MesonException(f"Unknown option: {key}")
1121
1122 # TODO: For project options, "dropping an augment" means going
1123 # back to the superproject's value. However, it's confusing
1124 # that -U does not simply remove the option from the stored
1125 # cmd_line_options. This may cause "meson setup --wipe" to
1126 # have surprising behavior. For this to work, UserOption
1127 # should only store the default value and the option values
1128 # should be stored with their source (project(), subproject(),
1129 # machine file, command line). This way the effective value
1130 # can be easily recomputed.
1131 opt = self.get_value_object(key)
1132 dirty |= not opt.yielding and bool(opt.parent)
1133 opt.yielding = bool(opt.parent)
1134 return dirty
1135
1136 def reset_prefixed_options(self, old_prefix: str, new_prefix: str) -> None:
1137 for optkey, prefix_mapping in BUILTIN_DIR_NOPREFIX_OPTIONS.items():
1138 valobj = self.options[optkey]
1139 new_value = valobj.value
1140 if new_prefix not in prefix_mapping:
1141 new_value = BUILTIN_OPTIONS[optkey].default
1142 else:
1143 if old_prefix in prefix_mapping:
1144 # Only reset the value if it has not been changed from the default.
1145 if prefix_mapping[old_prefix] == valobj.value:
1146 new_value = prefix_mapping[new_prefix]
1147 else:
1148 new_value = prefix_mapping[new_prefix]
1149 valobj.set_value(new_value)
1150
1151 def get_value_object(self, key: T.Union[OptionKey, str]) -> AnyOptionType:
1152 key = self.ensure_and_validate_key(key)
1153 return self.options[key]
1154
1155 def remove(self, key: OptionKey) -> None:
1156 del self.options[key]
1157 try:
1158 self.project_options.remove(key)
1159 except KeyError:
1160 pass
1161
1162 def __contains__(self, key: T.Union[str, OptionKey]) -> bool:
1163 key = self.ensure_and_validate_key(key)
1164 return key in self.options
1165
1166 def __repr__(self) -> str:
1167 return repr(self.options)
1168
1169 def keys(self) -> T.KeysView[OptionKey]:
1170 return self.options.keys()
1171
1172 def values(self) -> T.ValuesView[AnyOptionType]:
1173 return self.options.values()
1174
1175 def items(self) -> T.ItemsView['OptionKey', 'AnyOptionType']:
1176 return self.options.items()
1177
1178 def is_project_option(self, key: OptionKey) -> bool:
1179 """Convenience method to check if this is a project option."""
1180 return key in self.project_options
1181
1182 def is_per_machine_option(self, optname: OptionKey) -> bool:
1183 if optname.evolve(subproject=None, machine=MachineChoice.HOST) in BUILTIN_OPTIONS_PER_MACHINE:
1184 return True
1185 return self.is_compiler_option(optname)
1186
1187 def is_reserved_name(self, key: OptionKey) -> bool:
1188 if key.name in _BUILTIN_NAMES:
1189 return True
1190 if '_' not in key.name:
1191 return False
1192 prefix = key.name.split('_')[0]
1193 # Pylint seems to think that it is faster to build a set object
1194 # and all related work just to test whether a string has one of two
1195 # values. It is not, thank you very much.
1196 if prefix in ('b', 'backend'): # pylint: disable=R6201
1197 return True
1198 if prefix in self.all_languages:
1199 return True
1200 return False
1201
1202 def is_builtin_option(self, key: OptionKey) -> bool:
1203 """Convenience method to check if this is a builtin option."""
1204 return key.name in _BUILTIN_NAMES or self.is_module_option(key)
1205
1206 def is_base_option(self, key: OptionKey) -> bool:
1207 """Convenience method to check if this is a base option."""
1208 # The "startswith" check is just an optimization
1209 return key.name.startswith('b_') and key.evolve(subproject=None, machine=MachineChoice.HOST) in COMPILER_BASE_OPTIONS
1210
1211 def is_backend_option(self, key: OptionKey) -> bool:
1212 """Convenience method to check if this is a backend option."""
1213 if isinstance(key, str):
1214 name: str = key
1215 else:
1216 name = key.name
1217 return name.startswith('backend_')
1218
1219 def is_compiler_option(self, key: OptionKey) -> bool:
1220 """Convenience method to check if this is a compiler option."""
1221
1222 # FIXME, duplicate of is_reserved_name above. Should maybe store a cache instead.
1223 if '_' not in key.name:
1224 return False
1225 prefix = key.name.split('_')[0]
1226 if prefix in self.all_languages:
1227 return True
1228 return False
1229
1230 def is_module_option(self, key: OptionKey) -> bool:
1231 return key in self.module_options
1232
1233 def prefix_split_options(self, coll: dict[OptionKey, _T]) -> T.Tuple[str | None, dict[OptionKey, _T]]:
1234 prefix = None
1235 others_d: dict[OptionKey, _T] = {}
1236 for k, v in coll.items():
1237 if k.name == 'prefix':
1238 if not isinstance(v, str):
1239 raise MesonException('Incorrect type for prefix option (expected string)')
1240 prefix = v
1241 else:
1242 others_d[k] = v
1243 return (prefix, others_d)
1244
1245 def first_handle_prefix(self,
1246 project_default_options: OptionDict,
1247 cmd_line_options: dict[OptionKey, str | None],
1248 machine_file_options: OptionDict) \
1249 -> T.Tuple[OptionDict, dict[OptionKey, str | None], OptionDict]:
1250 # Copy to avoid later mutation
1251 nopref_machine_file_options = copy.copy(machine_file_options)
1252
1253 prefix = None
1254 (possible_prefix, nopref_project_default_options) = self.prefix_split_options(project_default_options)
1255 prefix = prefix if possible_prefix is None else possible_prefix
1256
1257 possible_prefixv = nopref_machine_file_options.pop(OptionKey('prefix'), None)
1258 assert possible_prefixv is None or isinstance(possible_prefixv, str), 'mypy: prefix from machine file was not a string?'
1259 prefix = prefix if possible_prefixv is None else possible_prefixv
1260
1261 (possible_prefix, nopref_cmd_line_options) = self.prefix_split_options(cmd_line_options)
1262 prefix = prefix if possible_prefix is None else possible_prefix
1263
1264 if prefix is not None:
1265 self.hard_reset_from_prefix(prefix)
1266 return (nopref_project_default_options, nopref_cmd_line_options, nopref_machine_file_options)
1267
1268 def hard_reset_from_prefix(self, prefix: str) -> None:
1269 prefix = self.sanitize_prefix(prefix)
1270 for optkey, prefix_mapping in BUILTIN_DIR_NOPREFIX_OPTIONS.items():
1271 valobj = self.options[optkey]
1272 if prefix in prefix_mapping:
1273 new_value = prefix_mapping[prefix]
1274 else:
1275 _v = BUILTIN_OPTIONS[optkey].default
1276 assert isinstance(_v, str), 'for mypy'
1277 new_value = _v
1278 valobj.set_value(new_value)
1279 self.options[OptionKey('prefix')].set_value(prefix)
1280
1281 def initialize_from_top_level_project_call(self,
1282 project_default_options_in: OptionDict,
1283 cmd_line_options_in: dict[OptionKey, str | None],
1284 machine_file_options_in: OptionDict) -> None:
1285 (project_default_options, cmd_line_options, machine_file_options) = self.first_handle_prefix(project_default_options_in,
1286 cmd_line_options_in,
1287 machine_file_options_in)
1288 for key, valstr in project_default_options.items():
1289 # Due to backwards compatibility we ignore build-machine options
1290 # when building natively.
1291 if not self.is_cross and key.is_for_build():
1292 continue
1293 if key.subproject:
1294 # Subproject options from toplevel project() have low priority
1295 # and will be processed when the subproject is found
1296 self.pending_subproject_options[key] = valstr
1297 else:
1298 # Setting a project option with default_options
1299 # should arguably be a hard error; the default
1300 # value of project option should be set in the option
1301 # file, not in the project call.
1302 self.set_user_option(key, valstr, True)
1303
1304 # ignore subprojects for now for machine file and command line
1305 # options; they are applied later
1306 for key, valstr in itertools.chain(machine_file_options.items(), cmd_line_options.items()):
1307 # Due to backwards compatibility we ignore all build-machine options
1308 # when building natively.
1309 if not self.is_cross and key.is_for_build():
1310 continue
1311 if not key.subproject:
1312 self.set_user_option(key, valstr, True)
1313
1314 def accept_as_pending_option(self, key: OptionKey, first_invocation: bool = False) -> bool:
1315 # Some base options (sanitizers etc) might get added later.
1316 # Permitting them all is not strictly correct.
1317 if self.is_compiler_option(key):
1318 return True
1319 if first_invocation and self.is_backend_option(key):
1320 return True
1321 return self.is_base_option(key)
1322
1323 def initialize_from_subproject_call(self,
1324 subproject: str,
1325 spcall_default_options: OptionDict,
1326 project_default_options: OptionDict,
1327 cmd_line_options: dict[OptionKey, str | None],
1328 machine_file_options: OptionDict) -> None:
1329
1330 options: OptionDict = {}
1331
1332 # project() default_options
1333 for key, valstr in project_default_options.items():
1334 if key.subproject == subproject:
1335 without_subp = key.evolve(subproject=None)
1336 raise MesonException(f'subproject name not needed in default_options; use "{without_subp}" instead of "{key}"')
1337
1338 if key.subproject is None:
1339 key = key.evolve(subproject=subproject)
1340 options[key] = valstr
1341
1342 # then global settings from machine file and command line
1343 # **but not if they are toplevel project options**
1344 for key, valstr in itertools.chain(machine_file_options.items(), cmd_line_options.items()):
1345 if key.subproject is None and not self.is_project_option(key.as_root()):
1346 subp_key = key.evolve(subproject=subproject)
1347 # just leave in place the value that was set for the toplevel project
1348 options.pop(subp_key, None)
1349
1350 # augments from the toplevel project() default_options
1351 for key, valstr in self.pending_subproject_options.items():
1352 if key.subproject == subproject:
1353 options[key] = valstr
1354
1355 # subproject() default_options
1356 for key, valstr in spcall_default_options.items():
1357 if key.subproject == subproject:
1358 without_subp = key.evolve(subproject=None)
1359 raise MesonException(f'subproject name not needed in default_options; use "{without_subp}" instead of "{key}"')
1360
1361 if key.subproject is None:
1362 key = key.evolve(subproject=subproject)
1363 options[key] = valstr
1364
1365 # then finally per project augments from machine file and command line
1366 for key, valstr in itertools.chain(machine_file_options.items(), cmd_line_options.items()):
1367 if key.subproject == subproject:
1368 options[key] = valstr
1369
1370 # merge everything that has been computed above, while giving self.augments priority
1371 for key, valstr in options.items():
1372 if key.subproject != subproject:
1373 if key.subproject in self.subprojects and not self.option_has_value(key, valstr):
1374 mlog.warning(f'option {key} is set in subproject {subproject} but has already been processed')
1375 continue
1376
1377 # Subproject options from project() will be processed when the subproject is found
1378 self.pending_subproject_options[key] = valstr
1379 continue
1380
1381 self.pending_subproject_options.pop(key, None)
1382 self.pending_options.pop(key, None)
1383 if key not in self.augments:
1384 self.set_user_option(key, valstr, True)
1385
1386 self.subprojects.add(subproject)
1387
1388 def update_project_options(self, project_options: MutableKeyedOptionDictType, subproject: SubProject) -> None:
1389 for key, value in project_options.items():
1390 assert key.machine is MachineChoice.HOST
1391 if key not in self.options:
1392 self.add_project_option(key, value)
1393 continue
1394 if key.subproject != subproject:
1395 raise MesonBugException(f'Tried to set an option for subproject {key.subproject} from {subproject}!')
1396
1397 oldval = self.get_value_object(key)
1398 if type(oldval) is not type(value):
1399 self.set_option(key, value.value)
1400 elif choices_are_different(oldval, value):
1401 # If the choices have changed, use the new value, but attempt
1402 # to keep the old options. If they are not valid keep the new
1403 # defaults but warn.
1404 self.options[key] = value
1405 try:
1406 value.set_value(oldval.value)
1407 except MesonException:
1408 mlog.warning(f'Old value(s) of {key} are no longer valid, resetting to default ({value.value}).',
1409 fatal=False)
1410
1411 # Find any extranious keys for this project and remove them
1412 potential_removed_keys = self.options.keys() - project_options.keys()
1413 for key in potential_removed_keys:
1414 if self.is_project_option(key) and key.subproject == subproject:
1415 self.remove(key)