Move OptionKey in the option source file.

uniquefilenames
Jussi Pakkanen 9 months ago
parent c2552527fb
commit 0d7bb776e2
  1. 3
      mesonbuild/ast/introspection.py
  2. 6
      mesonbuild/backend/backends.py
  3. 3
      mesonbuild/backend/ninjabackend.py
  4. 3
      mesonbuild/backend/vs2010backend.py
  5. 3
      mesonbuild/backend/xcodebackend.py
  6. 4
      mesonbuild/build.py
  7. 3
      mesonbuild/cargo/interpreter.py
  8. 3
      mesonbuild/cmake/common.py
  9. 3
      mesonbuild/cmake/executor.py
  10. 3
      mesonbuild/cmake/interpreter.py
  11. 3
      mesonbuild/compilers/asm.py
  12. 4
      mesonbuild/compilers/compilers.py
  13. 3
      mesonbuild/compilers/cuda.py
  14. 3
      mesonbuild/compilers/d.py
  15. 2
      mesonbuild/compilers/mixins/arm.py
  16. 2
      mesonbuild/compilers/mixins/clang.py
  17. 3
      mesonbuild/compilers/mixins/elbrus.py
  18. 2
      mesonbuild/compilers/mixins/emscripten.py
  19. 2
      mesonbuild/compilers/mixins/gnu.py
  20. 3
      mesonbuild/compilers/mixins/intel.py
  21. 3
      mesonbuild/compilers/mixins/metrowerks.py
  22. 2
      mesonbuild/compilers/mixins/pgi.py
  23. 5
      mesonbuild/compilers/mixins/visualstudio.py
  24. 2
      mesonbuild/compilers/objc.py
  25. 2
      mesonbuild/compilers/objcpp.py
  26. 3
      mesonbuild/compilers/rust.py
  27. 3
      mesonbuild/compilers/vala.py
  28. 4
      mesonbuild/coredata.py
  29. 4
      mesonbuild/dependencies/base.py
  30. 3
      mesonbuild/dependencies/boost.py
  31. 3
      mesonbuild/dependencies/dub.py
  32. 3
      mesonbuild/dependencies/misc.py
  33. 3
      mesonbuild/dependencies/pkgconfig.py
  34. 7
      mesonbuild/dependencies/python.py
  35. 5
      mesonbuild/dependencies/qt.py
  36. 2
      mesonbuild/dependencies/scalapack.py
  37. 3
      mesonbuild/environment.py
  38. 2
      mesonbuild/interpreter/compiler.py
  39. 3
      mesonbuild/interpreter/dependencyfallbacks.py
  40. 3
      mesonbuild/interpreter/interpreter.py
  41. 3
      mesonbuild/interpreter/kwargs.py
  42. 3
      mesonbuild/interpreter/mesonmain.py
  43. 3
      mesonbuild/interpreter/type_checking.py
  44. 5
      mesonbuild/mcompile.py
  45. 3
      mesonbuild/mconf.py
  46. 3
      mesonbuild/mdevenv.py
  47. 3
      mesonbuild/mdist.py
  48. 3
      mesonbuild/minit.py
  49. 3
      mesonbuild/minstall.py
  50. 2
      mesonbuild/mintro.py
  51. 5
      mesonbuild/modules/__init__.py
  52. 7
      mesonbuild/modules/cmake.py
  53. 3
      mesonbuild/modules/external_project.py
  54. 11
      mesonbuild/modules/gnome.py
  55. 3
      mesonbuild/modules/hotdoc.py
  56. 3
      mesonbuild/modules/i18n.py
  57. 11
      mesonbuild/modules/pkgconfig.py
  58. 7
      mesonbuild/modules/python.py
  59. 11
      mesonbuild/msetup.py
  60. 3
      mesonbuild/mtest.py
  61. 3
      mesonbuild/munstable_coredata.py
  62. 3
      mesonbuild/optinterpreter.py
  63. 238
      mesonbuild/options.py
  64. 2
      mesonbuild/scripts/regen_checker.py
  65. 292
      mesonbuild/utils/universal.py
  66. 3
      run_tests.py
  67. 3
      unittests/allplatformstests.py
  68. 5
      unittests/datatests.py
  69. 3
      unittests/helpers.py
  70. 4
      unittests/internaltests.py
  71. 3
      unittests/linuxliketests.py
  72. 3
      unittests/windowstests.py

@ -15,7 +15,8 @@ from .. import coredata as cdata
from ..build import Executable, Jar, SharedLibrary, SharedModule, StaticLibrary
from ..compilers import detect_compiler_for
from ..interpreterbase import InvalidArguments, SubProject
from ..mesonlib import MachineChoice, OptionKey
from ..mesonlib import MachineChoice
from ..options import OptionKey
from ..mparser import BaseNode, ArithmeticNode, ArrayNode, ElementaryNode, IdNode, FunctionNode, StringNode
from .interpreter import AstInterpreter

@ -27,8 +27,10 @@ from .. import mlog
from ..compilers import LANGUAGES_USING_LDFLAGS, detect
from ..mesonlib import (
File, MachineChoice, MesonException, OrderedSet,
ExecutableSerialisation, classify_unity_sources, OptionKey
ExecutableSerialisation, classify_unity_sources,
)
from ..options import OptionKey
if T.TYPE_CHECKING:
from .._typing import ImmutableListProtocol
@ -1677,7 +1679,7 @@ class Backend:
bindir = Path(prefix, self.environment.get_bindir())
libdir = Path(prefix, self.environment.get_libdir())
incdir = Path(prefix, self.environment.get_includedir())
_ldir = self.environment.coredata.get_option(mesonlib.OptionKey('localedir'))
_ldir = self.environment.coredata.get_option(OptionKey('localedir'))
assert isinstance(_ldir, str), 'for mypy'
localedir = Path(prefix, _ldir)
dest_path = Path(prefix, outdir, Path(fname).name) if outdir else Path(prefix, fname)

@ -31,7 +31,8 @@ from ..mesonlib import (
File, LibType, MachineChoice, MesonBugException, MesonException, OrderedSet, PerMachine,
ProgressBar, quote_arg
)
from ..mesonlib import get_compiler_for_source, has_path_sep, OptionKey
from ..mesonlib import get_compiler_for_source, has_path_sep
from ..options import OptionKey
from .backends import CleanTrees
from ..build import GeneratedList, InvalidArguments

@ -19,8 +19,9 @@ from .. import mlog
from .. import compilers
from .. import mesonlib
from ..mesonlib import (
File, MesonBugException, MesonException, replace_if_different, OptionKey, version_compare, MachineChoice
File, MesonBugException, MesonException, replace_if_different, version_compare, MachineChoice
)
from ..options import OptionKey
from ..environment import Environment, build_filename
from .. import coredata

@ -11,7 +11,8 @@ from .. import build
from .. import mesonlib
from .. import mlog
from ..arglist import CompilerArgs
from ..mesonlib import MesonBugException, MesonException, OptionKey
from ..mesonlib import MesonBugException, MesonException
from ..options import OptionKey
if T.TYPE_CHECKING:
from ..build import BuildTarget

@ -23,9 +23,11 @@ from .mesonlib import (
File, MesonException, MachineChoice, PerMachine, OrderedSet, listify,
extract_as_list, typeslistify, stringlistify, classify_unity_sources,
get_filenames_templates_dict, substitute_values, has_path_sep,
OptionKey, PerMachineDefaultable,
PerMachineDefaultable,
MesonBugException, EnvironmentVariables, pickle_load,
)
from .options import OptionKey
from .compilers import (
is_header, is_object, is_source, clink_langs, sort_clink, all_languages,
is_known_suffix, detect_static_linker

@ -23,7 +23,8 @@ import typing as T
from . import builder
from . import version
from ..mesonlib import MesonException, Popen_safe, OptionKey
from ..mesonlib import MesonException, Popen_safe
from ..options import OptionKey
from .. import coredata, options, mlog
from ..wrap.wrap import PackageDefinition

@ -3,7 +3,8 @@
from __future__ import annotations
from ..mesonlib import MesonException, OptionKey
from ..mesonlib import MesonException
from ..options import OptionKey
from .. import mlog
from pathlib import Path
import typing as T

@ -10,7 +10,8 @@ import re
import os
from .. import mlog
from ..mesonlib import PerMachine, Popen_safe, version_compare, is_windows, OptionKey
from ..mesonlib import PerMachine, Popen_safe, version_compare, is_windows
from ..options import OptionKey
from ..programs import find_external_program, NonExistingExternalProgram
if T.TYPE_CHECKING:

@ -18,7 +18,8 @@ from .toolchain import CMakeToolchain, CMakeExecScope
from .traceparser import CMakeTraceParser
from .tracetargets import resolve_cmake_trace_targets
from .. import mlog, mesonlib
from ..mesonlib import MachineChoice, OrderedSet, path_is_in_root, relative_to_if_possible, OptionKey
from ..mesonlib import MachineChoice, OrderedSet, path_is_in_root, relative_to_if_possible
from ..options import OptionKey
from ..mesondata import DataFile
from ..compilers.compilers import assembler_suffixes, lang_suffixes, header_suffixes, obj_suffixes, lib_suffixes, is_header
from ..programs import ExternalProgram

@ -3,7 +3,8 @@ from __future__ import annotations
import os
import typing as T
from ..mesonlib import EnvironmentException, OptionKey, get_meson_command
from ..mesonlib import EnvironmentException, get_meson_command
from ..options import OptionKey
from .compilers import Compiler
from .mixins.metrowerks import MetrowerksCompiler, mwasmarm_instruction_set_args, mwasmeppc_instruction_set_args

@ -19,9 +19,11 @@ from .. import options
from ..mesonlib import (
HoldableObject,
EnvironmentException, MesonException,
Popen_safe_logged, LibType, TemporaryDirectoryWinProof, OptionKey,
Popen_safe_logged, LibType, TemporaryDirectoryWinProof,
)
from ..options import OptionKey
from ..arglist import CompilerArgs
if T.TYPE_CHECKING:

@ -13,8 +13,9 @@ from .. import options
from .. import mlog
from ..mesonlib import (
EnvironmentException, Popen_safe,
is_windows, LibType, version_compare, OptionKey
is_windows, LibType, version_compare
)
from ..options import OptionKey
from .compilers import Compiler
if T.TYPE_CHECKING:

@ -12,8 +12,9 @@ from .. import mesonlib
from ..arglist import CompilerArgs
from ..linkers import RSPFileSyntax
from ..mesonlib import (
EnvironmentException, version_compare, OptionKey, is_windows
EnvironmentException, version_compare, is_windows
)
from ..options import OptionKey
from . import compilers
from .compilers import (

@ -10,7 +10,7 @@ import typing as T
from ... import mesonlib
from ...linkers.linkers import ArmClangDynamicLinker
from ...mesonlib import OptionKey
from ...options import OptionKey
from ..compilers import clike_debug_args
from .clang import clang_color_args

@ -12,7 +12,7 @@ import typing as T
from ... import mesonlib
from ...linkers.linkers import AppleDynamicLinker, ClangClDynamicLinker, LLVMDynamicLinker, GnuGoldDynamicLinker, \
MoldDynamicLinker, MSVCDynamicLinker
from ...mesonlib import OptionKey
from ...options import OptionKey
from ..compilers import CompileCheckMode
from .gnu import GnuLikeCompiler

@ -13,7 +13,8 @@ import re
from .gnu import GnuLikeCompiler
from .gnu import gnu_optimization_args
from ...mesonlib import Popen_safe, OptionKey
from ...mesonlib import Popen_safe
from ...options import OptionKey
if T.TYPE_CHECKING:
from ...environment import Environment

@ -11,7 +11,7 @@ import typing as T
from ... import coredata
from ... import options
from ... import mesonlib
from ...mesonlib import OptionKey
from ...options import OptionKey
from ...mesonlib import LibType
from mesonbuild.compilers.compilers import CompileCheckMode

@ -16,7 +16,7 @@ import typing as T
from ... import mesonlib
from ... import mlog
from ...mesonlib import OptionKey
from ...options import OptionKey
from mesonbuild.compilers.compilers import CompileCheckMode
if T.TYPE_CHECKING:

@ -18,6 +18,7 @@ from ... import mesonlib
from ..compilers import CompileCheckMode
from .gnu import GnuLikeCompiler
from .visualstudio import VisualStudioLikeCompiler
from ...options import OptionKey
if T.TYPE_CHECKING:
from ...environment import Environment
@ -66,7 +67,7 @@ class IntelGnuLikeCompiler(GnuLikeCompiler):
# It does have IPO, which serves much the same purpose as LOT, but
# there is an unfortunate rule for using IPO (you can't control the
# name of the output file) which break assumptions meson makes
self.base_options = {mesonlib.OptionKey(o) for o in [
self.base_options = {OptionKey(o) for o in [
'b_pch', 'b_lundef', 'b_asneeded', 'b_pgo', 'b_coverage',
'b_ndebug', 'b_staticpic', 'b_pie']}
self.lang_header = 'none'

@ -8,7 +8,8 @@ from __future__ import annotations
import os
import typing as T
from ...mesonlib import EnvironmentException, OptionKey
from ...mesonlib import EnvironmentException
from ...options import OptionKey
if T.TYPE_CHECKING:
from ...envconfig import MachineInfo

@ -10,7 +10,7 @@ import os
from pathlib import Path
from ..compilers import clike_debug_args, clike_optimization_args
from ...mesonlib import OptionKey
from ...options import OptionKey
if T.TYPE_CHECKING:
from ...environment import Environment

@ -15,6 +15,7 @@ from ... import arglist
from ... import mesonlib
from ... import mlog
from mesonbuild.compilers.compilers import CompileCheckMode
from ...options import OptionKey
if T.TYPE_CHECKING:
from ...environment import Environment
@ -110,7 +111,7 @@ class VisualStudioLikeCompiler(Compiler, metaclass=abc.ABCMeta):
INVOKES_LINKER = False
def __init__(self, target: str):
self.base_options = {mesonlib.OptionKey(o) for o in ['b_pch', 'b_ndebug', 'b_vscrt']} # FIXME add lto, pgo and the like
self.base_options = {OptionKey(o) for o in ['b_pch', 'b_ndebug', 'b_vscrt']} # FIXME add lto, pgo and the like
self.target = target
self.is_64 = ('x64' in target) or ('x86_64' in target)
# do some canonicalization of target machine
@ -125,7 +126,7 @@ class VisualStudioLikeCompiler(Compiler, metaclass=abc.ABCMeta):
else:
self.machine = target
if mesonlib.version_compare(self.version, '>=19.28.29910'): # VS 16.9.0 includes cl 19.28.29910
self.base_options.add(mesonlib.OptionKey('b_sanitize'))
self.base_options.add(OptionKey('b_sanitize'))
assert self.linker is not None
self.linker.machine = self.machine

@ -7,7 +7,7 @@ import typing as T
from .. import coredata
from .. import options
from ..mesonlib import OptionKey
from ..options import OptionKey
from .compilers import Compiler
from .mixins.clike import CLikeCompiler

@ -7,7 +7,7 @@ import typing as T
from .. import coredata
from .. import options
from ..mesonlib import OptionKey
from ..options import OptionKey
from .mixins.clike import CLikeCompiler
from .compilers import Compiler

@ -10,7 +10,8 @@ import re
import typing as T
from .. import options
from ..mesonlib import EnvironmentException, MesonException, Popen_safe_logged, OptionKey
from ..mesonlib import EnvironmentException, MesonException, Popen_safe_logged
from ..options import OptionKey
from .compilers import Compiler, clike_debug_args
if T.TYPE_CHECKING:

@ -8,7 +8,8 @@ import typing as T
from .. import mlog
from .. import mesonlib
from ..mesonlib import EnvironmentException, version_compare, LibType, OptionKey
from ..mesonlib import EnvironmentException, version_compare, LibType
from ..options import OptionKey
from .compilers import CompileCheckMode, Compiler
from ..arglist import CompilerArgs

@ -18,10 +18,12 @@ from .mesonlib import (
MesonBugException,
MesonException, MachineChoice, PerMachine,
PerMachineDefaultable,
OptionKey, OptionType, stringlistify,
stringlistify,
pickle_load
)
from .options import OptionKey, OptionType
from .machinefile import CmdLineFileParser
import ast

@ -14,8 +14,8 @@ from enum import Enum
from .. import mlog, mesonlib
from ..compilers import clib_langs
from ..mesonlib import LibType, MachineChoice, MesonException, HoldableObject, OptionKey
from ..mesonlib import version_compare_many
from ..mesonlib import LibType, MachineChoice, MesonException, HoldableObject, version_compare_many
from ..options import OptionKey
#from ..interpreterbase import FeatureDeprecated, FeatureNew
if T.TYPE_CHECKING:

@ -11,6 +11,7 @@ from pathlib import Path
from .. import mlog
from .. import mesonlib
from ..options import OptionKey
from .base import DependencyException, SystemDependency
from .detect import packages
@ -340,7 +341,7 @@ class BoostLibraryFile():
class BoostDependency(SystemDependency):
def __init__(self, environment: Environment, kwargs: T.Dict[str, T.Any]) -> None:
super().__init__('boost', environment, kwargs, language='cpp')
buildtype = environment.coredata.get_option(mesonlib.OptionKey('buildtype'))
buildtype = environment.coredata.get_option(OptionKey('buildtype'))
assert isinstance(buildtype, str)
self.debug = buildtype.startswith('debug')
self.multithreading = kwargs.get('threading', 'multi') == 'multi'

@ -5,7 +5,8 @@ from __future__ import annotations
from .base import ExternalDependency, DependencyException, DependencyTypeName
from .pkgconfig import PkgConfigDependency
from ..mesonlib import (Popen_safe, OptionKey, join_args, version_compare)
from ..mesonlib import (Popen_safe, join_args, version_compare)
from ..options import OptionKey
from ..programs import ExternalProgram
from .. import mlog
import re

@ -17,6 +17,7 @@ from .configtool import ConfigToolDependency
from .detect import packages
from .factory import DependencyFactory, factory_methods
from .pkgconfig import PkgConfigDependency
from ..options import OptionKey
if T.TYPE_CHECKING:
from ..environment import Environment
@ -541,7 +542,7 @@ def shaderc_factory(env: 'Environment',
shared_libs = ['shaderc']
static_libs = ['shaderc_combined', 'shaderc_static']
if kwargs.get('static', env.coredata.get_option(mesonlib.OptionKey('prefer_static'))):
if kwargs.get('static', env.coredata.get_option(OptionKey('prefer_static'))):
c = [functools.partial(PkgConfigDependency, name, env, kwargs)
for name in static_libs + shared_libs]
else:

@ -6,7 +6,8 @@ from __future__ import annotations
from pathlib import Path
from .base import ExternalDependency, DependencyException, sort_libpaths, DependencyTypeName
from ..mesonlib import EnvironmentVariables, OptionKey, OrderedSet, PerMachine, Popen_safe, Popen_safe_logged, MachineChoice, join_args
from ..mesonlib import EnvironmentVariables, OrderedSet, PerMachine, Popen_safe, Popen_safe_logged, MachineChoice, join_args
from ..options import OptionKey
from ..programs import find_external_program, ExternalProgram
from .. import mlog
from pathlib import PurePath

@ -16,6 +16,7 @@ from .framework import ExtraFrameworkDependency
from .pkgconfig import PkgConfigDependency
from ..environment import detect_cpu_family
from ..programs import ExternalProgram
from ..options import OptionKey
if T.TYPE_CHECKING:
from typing_extensions import TypedDict
@ -240,13 +241,13 @@ class _PythonDependencyBase(_Base):
# Python itself (except with pybind11, which has an ugly
# hack to work around this) - so emit a warning to explain
# the cause of the expected link error.
buildtype = self.env.coredata.get_option(mesonlib.OptionKey('buildtype'))
buildtype = self.env.coredata.get_option(OptionKey('buildtype'))
assert isinstance(buildtype, str)
debug = self.env.coredata.get_option(mesonlib.OptionKey('debug'))
debug = self.env.coredata.get_option(OptionKey('debug'))
# `debugoptimized` buildtype may not set debug=True currently, see gh-11645
is_debug_build = debug or buildtype == 'debug'
vscrt_debug = False
if mesonlib.OptionKey('b_vscrt') in self.env.coredata.optstore:
if OptionKey('b_vscrt') in self.env.coredata.optstore:
vscrt = self.env.coredata.optstore.get_value('b_vscrt')
if vscrt in {'mdd', 'mtd', 'from_buildtype', 'static_from_buildtype'}:
vscrt_debug = True

@ -19,6 +19,7 @@ from .pkgconfig import PkgConfigDependency
from .factory import DependencyFactory
from .. import mlog
from .. import mesonlib
from ..options import OptionKey
if T.TYPE_CHECKING:
from ..compilers import Compiler
@ -296,8 +297,8 @@ class QmakeQtDependency(_QtBase, ConfigToolDependency, metaclass=abc.ABCMeta):
# Use the buildtype by default, but look at the b_vscrt option if the
# compiler supports it.
is_debug = self.env.coredata.get_option(mesonlib.OptionKey('buildtype')) == 'debug'
if mesonlib.OptionKey('b_vscrt') in self.env.coredata.optstore:
is_debug = self.env.coredata.get_option(OptionKey('buildtype')) == 'debug'
if OptionKey('b_vscrt') in self.env.coredata.optstore:
if self.env.coredata.optstore.get_value('b_vscrt') in {'mdd', 'mtd'}:
is_debug = True
modules_lib_suffix = _get_modules_lib_suffix(self.version, self.env.machines[self.for_machine], is_debug)

@ -8,7 +8,7 @@ import functools
import os
import typing as T
from ..mesonlib import OptionKey
from ..options import OptionKey
from .base import DependencyMethods
from .cmake import CMakeDependency
from .detect import packages

@ -17,9 +17,10 @@ CmdLineFileParser = machinefile.CmdLineFileParser
from .mesonlib import (
MesonException, MachineChoice, Popen_safe, PerMachine,
PerMachineDefaultable, PerThreeMachineDefaultable, split_args, quote_arg, OptionKey,
PerMachineDefaultable, PerThreeMachineDefaultable, split_args, quote_arg,
search_version, MesonBugException
)
from .options import OptionKey
from . import mlog
from .programs import ExternalProgram

@ -22,7 +22,7 @@ from ..interpreterbase import (ObjectHolder, noPosargs, noKwargs,
FeatureNew, FeatureNewKwargs, disablerIfNotFound,
InterpreterException)
from ..interpreterbase.decorators import ContainerTypeInfo, typed_kwargs, KwargInfo, typed_pos_args
from ..mesonlib import OptionKey
from ..options import OptionKey
from .interpreterobjects import (extract_required_kwarg, extract_search_dirs)
from .type_checking import REQUIRED_KW, in_set_validator, NoneType

@ -5,7 +5,8 @@ from .. import mlog
from .. import dependencies
from .. import build
from ..wrap import WrapMode
from ..mesonlib import OptionKey, extract_as_list, stringlistify, version_compare_many, listify
from ..mesonlib import extract_as_list, stringlistify, version_compare_many, listify
from ..options import OptionKey
from ..dependencies import Dependency, DependencyException, NotFoundDependency
from ..interpreterbase import (MesonInterpreterObject, FeatureNew,
InterpreterException, InvalidArguments)

@ -19,8 +19,9 @@ from .. import envconfig
from ..wrap import wrap, WrapMode
from .. import mesonlib
from ..mesonlib import (EnvironmentVariables, ExecutableSerialisation, MesonBugException, MesonException, HoldableObject,
FileMode, MachineChoice, OptionKey, listify,
FileMode, MachineChoice, listify,
extract_as_list, has_path_sep, path_is_in_root, PerMachine)
from ..options import OptionKey
from ..programs import ExternalProgram, NonExistingExternalProgram
from ..dependencies import Dependency
from ..depfile import DepFile

@ -13,7 +13,8 @@ from .. import build
from .. import options
from ..compilers import Compiler
from ..dependencies.base import Dependency
from ..mesonlib import EnvironmentVariables, MachineChoice, File, FileMode, FileOrString, OptionKey
from ..mesonlib import EnvironmentVariables, MachineChoice, File, FileMode, FileOrString
from ..options import OptionKey
from ..modules.cmake import CMakeSubprojectOptions
from ..programs import ExternalProgram
from .type_checking import PkgConfigDefineType, SourcesVarargsType

@ -11,7 +11,8 @@ from .. import dependencies
from .. import build
from .. import mlog, coredata
from ..mesonlib import MachineChoice, OptionKey
from ..mesonlib import MachineChoice
from ..options import OptionKey
from ..programs import OverrideProgram, ExternalProgram
from ..interpreter.type_checking import ENV_KW, ENV_METHOD_KW, ENV_SEPARATOR_KW, env_convertor_with_method
from ..interpreterbase import (MesonInterpreterObject, FeatureNew, FeatureDeprecated,

@ -15,7 +15,8 @@ from ..options import UserFeatureOption
from ..dependencies import Dependency, InternalDependency
from ..interpreterbase.decorators import KwargInfo, ContainerTypeInfo
from ..mesonlib import (File, FileMode, MachineChoice, listify, has_path_sep,
OptionKey, EnvironmentVariables)
EnvironmentVariables)
from ..options import OptionKey
from ..programs import ExternalProgram
# Helper definition for type checks that are `Optional[T]`

@ -16,6 +16,7 @@ from pathlib import Path
from . import mlog
from . import mesonlib
from .options import OptionKey
from .mesonlib import MesonException, RealPathAction, join_args, listify_array_value, setup_vsenv
from mesonbuild.environment import detect_ninja
from mesonbuild import build
@ -354,14 +355,14 @@ def run(options: 'argparse.Namespace') -> int:
b = build.load(options.wd)
cdata = b.environment.coredata
need_vsenv = T.cast('bool', cdata.get_option(mesonlib.OptionKey('vsenv')))
need_vsenv = T.cast('bool', cdata.get_option(OptionKey('vsenv')))
if setup_vsenv(need_vsenv):
mlog.log(mlog.green('INFO:'), 'automatically activated MSVC compiler environment')
cmd: T.List[str] = []
env: T.Optional[T.Dict[str, str]] = None
backend = cdata.get_option(mesonlib.OptionKey('backend'))
backend = cdata.get_option(OptionKey('backend'))
assert isinstance(backend, str)
mlog.log(mlog.green('INFO:'), 'autodetecting backend as', backend)
if backend == 'ninja':

@ -20,7 +20,8 @@ from . import mesonlib
from . import mintro
from . import mlog
from .ast import AstIDGenerator, IntrospectionInterpreter
from .mesonlib import MachineChoice, OptionKey
from .mesonlib import MachineChoice
from .options import OptionKey
from .optinterpreter import OptionInterpreter
if T.TYPE_CHECKING:

@ -9,8 +9,9 @@ import typing as T
from pathlib import Path
from . import build, minstall
from .mesonlib import (EnvironmentVariables, MesonException, is_windows, setup_vsenv, OptionKey,
from .mesonlib import (EnvironmentVariables, MesonException, is_windows, setup_vsenv,
get_wine_shortpath, MachineChoice, relpath)
from .options import OptionKey
from . import mlog

@ -23,7 +23,8 @@ from glob import glob
from pathlib import Path
from mesonbuild.environment import Environment, detect_ninja
from mesonbuild.mesonlib import (MesonException, RealPathAction, get_meson_command, quiet_git,
windows_proof_rmtree, setup_vsenv, OptionKey)
windows_proof_rmtree, setup_vsenv)
from .options import OptionKey
from mesonbuild.msetup import add_arguments as msetup_argparse
from mesonbuild.wrap import wrap
from mesonbuild import mlog, build, coredata

@ -20,6 +20,7 @@ from mesonbuild.coredata import FORBIDDEN_TARGET_NAMES
from mesonbuild.environment import detect_ninja
from mesonbuild.templates.mesontemplates import create_meson_build
from mesonbuild.templates.samplefactory import sample_generator
from mesonbuild.options import OptionKey
if T.TYPE_CHECKING:
import argparse
@ -192,7 +193,7 @@ def run(options: Arguments) -> int:
raise SystemExit
b = build.load(options.builddir)
need_vsenv = T.cast('bool', b.environment.coredata.get_option(mesonlib.OptionKey('vsenv')))
need_vsenv = T.cast('bool', b.environment.coredata.get_option(OptionKey('vsenv')))
vsenv_active = mesonlib.setup_vsenv(need_vsenv)
if vsenv_active:
mlog.log(mlog.green('INFO:'), 'automatically activated MSVC compiler environment')

@ -18,7 +18,8 @@ import re
from . import build, environment
from .backend.backends import InstallData
from .mesonlib import (MesonException, Popen_safe, RealPathAction, is_windows,
is_aix, setup_vsenv, pickle_load, is_osx, OptionKey)
is_aix, setup_vsenv, pickle_load, is_osx)
from .options import OptionKey
from .scripts import depfixer, destdir_join
from .scripts.meson_exe import run_exe
try:

@ -25,7 +25,7 @@ from .backend import backends
from .dependencies import Dependency
from . import environment
from .interpreterbase import ObjectHolder
from .mesonlib import OptionKey
from .options import OptionKey
from .mparser import FunctionNode, ArrayNode, ArgumentNode, StringNode
if T.TYPE_CHECKING:

@ -8,6 +8,7 @@ import dataclasses
import typing as T
from .. import build, mesonlib
from ..options import OptionKey
from ..build import IncludeDirs
from ..interpreterbase.decorators import noKwargs, noPosargs
from ..mesonlib import relpath, HoldableObject, MachineChoice
@ -134,13 +135,13 @@ class ModuleState:
machine: MachineChoice = MachineChoice.HOST,
lang: T.Optional[str] = None,
module: T.Optional[str] = None) -> T.Union[T.List[str], str, int, bool]:
return self.environment.coredata.get_option(mesonlib.OptionKey(name, subproject, machine, lang, module))
return self.environment.coredata.get_option(OptionKey(name, subproject, machine, lang, module))
def is_user_defined_option(self, name: str, subproject: str = '',
machine: MachineChoice = MachineChoice.HOST,
lang: T.Optional[str] = None,
module: T.Optional[str] = None) -> bool:
key = mesonlib.OptionKey(name, subproject, machine, lang, module)
key = OptionKey(name, subproject, machine, lang, module)
return key in self._interpreter.user_defined_options.cmd_line_options
def process_include_dirs(self, dirs: T.Iterable[T.Union[str, IncludeDirs]]) -> T.Iterable[IncludeDirs]:

@ -10,6 +10,7 @@ import typing as T
from . import ExtensionModule, ModuleReturnValue, ModuleObject, ModuleInfo
from .. import build, mesonlib, mlog, dependencies
from ..options import OptionKey
from ..cmake import TargetOptions, cmake_defines_to_args
from ..interpreter import SubprojectHolder
from ..interpreter.type_checking import REQUIRED_KW, INSTALL_DIR_KW, NoneType, in_set_validator
@ -299,7 +300,7 @@ class CmakeModule(ExtensionModule):
pkgroot = pkgroot_name = kwargs['install_dir']
if pkgroot is None:
pkgroot = os.path.join(state.environment.coredata.get_option(mesonlib.OptionKey('libdir')), 'cmake', name)
pkgroot = os.path.join(state.environment.coredata.get_option(OptionKey('libdir')), 'cmake', name)
pkgroot_name = os.path.join('{libdir}', 'cmake', name)
template_file = os.path.join(self.cmake_root, 'Modules', f'BasicConfigVersion-{compatibility}.cmake.in')
@ -370,14 +371,14 @@ class CmakeModule(ExtensionModule):
install_dir = kwargs['install_dir']
if install_dir is None:
install_dir = os.path.join(state.environment.coredata.get_option(mesonlib.OptionKey('libdir')), 'cmake', name)
install_dir = os.path.join(state.environment.coredata.get_option(OptionKey('libdir')), 'cmake', name)
conf = kwargs['configuration']
if isinstance(conf, dict):
FeatureNew.single_use('cmake.configure_package_config_file dict as configuration', '0.62.0', state.subproject, location=state.current_node)
conf = build.ConfigurationData(conf)
prefix = state.environment.coredata.get_option(mesonlib.OptionKey('prefix'))
prefix = state.environment.coredata.get_option(OptionKey('prefix'))
abs_install_dir = install_dir
if not os.path.isabs(abs_install_dir):
abs_install_dir = os.path.join(prefix, install_dir)

@ -19,7 +19,8 @@ from ..interpreterbase import FeatureNew
from ..interpreter.type_checking import ENV_KW, DEPENDS_KW
from ..interpreterbase.decorators import ContainerTypeInfo, KwargInfo, typed_kwargs, typed_pos_args
from ..mesonlib import (EnvironmentException, MesonException, Popen_safe, MachineChoice,
get_variable_regex, do_replacement, join_args, OptionKey)
get_variable_regex, do_replacement, join_args)
from ..options import OptionKey
if T.TYPE_CHECKING:
from typing_extensions import TypedDict

@ -31,6 +31,7 @@ from ..interpreterbase.decorators import typed_pos_args
from ..mesonlib import (
MachineChoice, MesonException, OrderedSet, Popen_safe, join_args, quote_arg
)
from ..options import OptionKey
from ..programs import OverrideProgram
from ..scripts.gettext import read_linguas
@ -516,7 +517,7 @@ class GnomeModule(ExtensionModule):
if gresource: # Only one target for .gresource files
return ModuleReturnValue(target_c, [target_c])
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(mesonlib.OptionKey('includedir'))
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(OptionKey('includedir'))
assert isinstance(install_dir, str), 'for mypy'
target_h = GResourceHeaderTarget(
f'{target_name}_h',
@ -905,7 +906,7 @@ class GnomeModule(ExtensionModule):
cflags += state.global_args[lang]
if state.project_args.get(lang):
cflags += state.project_args[lang]
if mesonlib.OptionKey('b_sanitize') in compiler.base_options:
if OptionKey('b_sanitize') in compiler.base_options:
sanitize = state.environment.coredata.optstore.get_value('b_sanitize')
cflags += compiler.sanitizer_compile_args(sanitize)
sanitize = sanitize.split(',')
@ -1642,7 +1643,7 @@ class GnomeModule(ExtensionModule):
targets = []
install_header = kwargs['install_header']
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(mesonlib.OptionKey('includedir'))
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(OptionKey('includedir'))
assert isinstance(install_dir, str), 'for mypy'
output = namebase + '.c'
@ -1954,7 +1955,7 @@ class GnomeModule(ExtensionModule):
) -> build.CustomTarget:
real_cmd: T.List[T.Union[str, 'ToolType']] = [self._find_tool(state, 'glib-mkenums')]
real_cmd.extend(cmd)
_install_dir = install_dir or state.environment.coredata.get_option(mesonlib.OptionKey('includedir'))
_install_dir = install_dir or state.environment.coredata.get_option(OptionKey('includedir'))
assert isinstance(_install_dir, str), 'for mypy'
return CustomTarget(
@ -2166,7 +2167,7 @@ class GnomeModule(ExtensionModule):
cmd.append(gir_file)
vapi_output = library + '.vapi'
datadir = state.environment.coredata.get_option(mesonlib.OptionKey('datadir'))
datadir = state.environment.coredata.get_option(OptionKey('datadir'))
assert isinstance(datadir, str), 'for mypy'
install_dir = kwargs['install_dir'] or os.path.join(datadir, 'vala', 'vapi')

@ -20,6 +20,7 @@ from ..interpreter.interpreterobjects import _CustomTargetHolder
from ..interpreter.type_checking import NoneType
from ..mesonlib import File, MesonException
from ..programs import ExternalProgram
from ..options import OptionKey
if T.TYPE_CHECKING:
from typing_extensions import TypedDict
@ -330,7 +331,7 @@ class HotdocTargetBuilder:
for path in self.include_paths:
self.cmd.extend(['--include-path', path])
if self.state.environment.coredata.get_option(mesonlib.OptionKey('werror', subproject=self.state.subproject)):
if self.state.environment.coredata.get_option(OptionKey('werror', subproject=self.state.subproject)):
self.cmd.append('--fatal-warnings')
self.generate_hotdoc_config()

@ -10,6 +10,7 @@ import typing as T
from . import ExtensionModule, ModuleReturnValue, ModuleInfo
from .. import build
from .. import mesonlib
from ..options import OptionKey
from .. import mlog
from ..interpreter.type_checking import CT_BUILD_BY_DEFAULT, CT_INPUT_KW, INSTALL_TAG_KW, OUTPUT_KW, INSTALL_DIR_KW, INSTALL_KW, NoneType, in_set_validator
from ..interpreterbase import FeatureNew, InvalidArguments
@ -277,7 +278,7 @@ class I18nModule(ExtensionModule):
targets.append(pottarget)
install = kwargs['install']
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(mesonlib.OptionKey('localedir'))
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(OptionKey('localedir'))
assert isinstance(install_dir, str), 'for mypy'
if not languages:
languages = read_linguas(path.join(state.environment.source_dir, state.subdir))

@ -13,6 +13,7 @@ from . import ModuleReturnValue
from .. import build
from .. import dependencies
from .. import mesonlib
from ..options import OptionKey
from .. import mlog
from ..options import BUILTIN_DIR_OPTIONS
from ..dependencies.pkgconfig import PkgConfigDependency, PkgConfigInterface
@ -482,7 +483,7 @@ class PkgConfigModule(NewExtensionModule):
srcdir = PurePath(state.environment.get_source_dir())
else:
outdir = state.environment.scratch_dir
prefix = PurePath(_as_str(coredata.get_option(mesonlib.OptionKey('prefix'))))
prefix = PurePath(_as_str(coredata.get_option(OptionKey('prefix'))))
if pkgroot:
pkgroot_ = PurePath(pkgroot)
if not pkgroot_.is_absolute():
@ -499,7 +500,7 @@ class PkgConfigModule(NewExtensionModule):
if optname == 'prefix':
ofile.write('prefix={}\n'.format(self._escape(prefix)))
else:
dirpath = PurePath(_as_str(coredata.get_option(mesonlib.OptionKey(optname))))
dirpath = PurePath(_as_str(coredata.get_option(OptionKey(optname))))
ofile.write('{}={}\n'.format(optname, self._escape('${prefix}' / dirpath)))
if uninstalled and not dataonly:
ofile.write('srcdir={}\n'.format(self._escape(srcdir)))
@ -694,13 +695,13 @@ class PkgConfigModule(NewExtensionModule):
pkgroot = pkgroot_name = kwargs['install_dir'] or default_install_dir
if pkgroot is None:
if mesonlib.is_freebsd():
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(mesonlib.OptionKey('prefix'))), 'libdata', 'pkgconfig')
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(OptionKey('prefix'))), 'libdata', 'pkgconfig')
pkgroot_name = os.path.join('{prefix}', 'libdata', 'pkgconfig')
elif mesonlib.is_haiku():
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(mesonlib.OptionKey('prefix'))), 'develop', 'lib', 'pkgconfig')
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(OptionKey('prefix'))), 'develop', 'lib', 'pkgconfig')
pkgroot_name = os.path.join('{prefix}', 'develop', 'lib', 'pkgconfig')
else:
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(mesonlib.OptionKey('libdir'))), 'pkgconfig')
pkgroot = os.path.join(_as_str(state.environment.coredata.get_option(OptionKey('libdir'))), 'pkgconfig')
pkgroot_name = os.path.join('{libdir}', 'pkgconfig')
relocatable = state.get_option('relocatable', module='pkgconfig')
self._generate_pkgconfig_file(state, deps, subdirs, name, description, url,

@ -22,7 +22,8 @@ from ..interpreterbase import (
InvalidArguments, typed_pos_args, typed_kwargs, KwargInfo,
FeatureNew, FeatureNewKwargs, disablerIfNotFound
)
from ..mesonlib import MachineChoice, OptionKey
from ..mesonlib import MachineChoice
from ..options import OptionKey
from ..programs import ExternalProgram, NonExistingExternalProgram
if T.TYPE_CHECKING:
@ -112,7 +113,7 @@ class PythonInstallation(_ExternalProgramHolder['PythonExternalProgram']):
def __init__(self, python: 'PythonExternalProgram', interpreter: 'Interpreter'):
_ExternalProgramHolder.__init__(self, python, interpreter)
info = python.info
prefix = self.interpreter.environment.coredata.get_option(mesonlib.OptionKey('prefix'))
prefix = self.interpreter.environment.coredata.get_option(OptionKey('prefix'))
assert isinstance(prefix, str), 'for mypy'
self.variables = info['variables']
self.suffix = info['suffix']
@ -373,7 +374,7 @@ class PythonModule(ExtensionModule):
def _get_install_scripts(self) -> T.List[mesonlib.ExecutableSerialisation]:
backend = self.interpreter.backend
ret = []
optlevel = self.interpreter.environment.coredata.get_option(mesonlib.OptionKey('bytecompile', module='python'))
optlevel = self.interpreter.environment.coredata.get_option(OptionKey('bytecompile', module='python'))
if optlevel == -1:
return ret
if not any(PythonExternalProgram.run_bytecompile.values()):

@ -11,6 +11,7 @@ import typing as T
from . import build, coredata, environment, interpreter, mesonlib, mintro, mlog
from .mesonlib import MesonException
from .options import OptionKey
if T.TYPE_CHECKING:
from typing_extensions import Protocol
@ -320,10 +321,10 @@ def run_genvslite_setup(options: CMDOptions) -> None:
# invoke the appropriate 'meson compile ...' build commands upon the normal visual studio build/rebuild/clean actions, instead of using
# the native VS/msbuild system.
builddir_prefix = options.builddir
genvsliteval = options.cmd_line_options.pop(mesonlib.OptionKey('genvslite'))
genvsliteval = options.cmd_line_options.pop(OptionKey('genvslite'))
# The command line may specify a '--backend' option, which doesn't make sense in conjunction with
# '--genvslite', where we always want to use a ninja back end -
k_backend = mesonlib.OptionKey('backend')
k_backend = OptionKey('backend')
if k_backend in options.cmd_line_options.keys():
if options.cmd_line_options[k_backend] != 'ninja':
raise MesonException('Explicitly specifying a backend option with \'genvslite\' is not necessary '
@ -336,12 +337,12 @@ def run_genvslite_setup(options: CMDOptions) -> None:
for buildtypestr in buildtypes_list:
options.builddir = f'{builddir_prefix}_{buildtypestr}' # E.g. builddir_release
options.cmd_line_options[mesonlib.OptionKey('buildtype')] = buildtypestr
options.cmd_line_options[OptionKey('buildtype')] = buildtypestr
app = MesonApp(options)
vslite_ctx[buildtypestr] = app.generate(capture=True)
#Now for generating the 'lite' solution and project files, which will use these builds we've just set up, above.
options.builddir = f'{builddir_prefix}_vs'
options.cmd_line_options[mesonlib.OptionKey('genvslite')] = genvsliteval
options.cmd_line_options[OptionKey('genvslite')] = genvsliteval
app = MesonApp(options)
app.generate(capture=False, vslite_ctx=vslite_ctx)
@ -357,7 +358,7 @@ def run(options: T.Union[CMDOptions, T.List[str]]) -> int:
# lie
options.pager = False
if mesonlib.OptionKey('genvslite') in options.cmd_line_options.keys():
if OptionKey('genvslite') in options.cmd_line_options.keys():
run_genvslite_setup(options)
else:
app = MesonApp(options)

@ -35,8 +35,9 @@ from . import environment
from . import mlog
from .coredata import MesonVersionMismatchException, major_versions_differ
from .coredata import version as coredata_version
from .mesonlib import (MesonException, OptionKey, OrderedSet, RealPathAction,
from .mesonlib import (MesonException, OrderedSet, RealPathAction,
get_wine_shortpath, join_args, split_args, setup_vsenv)
from .options import OptionKey
from .mintro import get_infodir, load_info_file
from .programs import ExternalProgram
from .backend.backends import TestProtocol, TestSerialisation

@ -5,7 +5,8 @@ from __future__ import annotations
from . import coredata as cdata
from .mesonlib import MachineChoice, OptionKey
from .mesonlib import MachineChoice
from .options import OptionKey
import os.path
import pprint

@ -9,6 +9,7 @@ import typing as T
from . import coredata
from . import options
from . import mesonlib
from .options import OptionKey
from . import mparser
from . import mlog
from .interpreterbase import FeatureNew, FeatureDeprecated, typed_pos_args, typed_kwargs, ContainerTypeInfo, KwargInfo
@ -190,7 +191,7 @@ class OptionInterpreter:
opt_name = args[0]
if optname_regex.search(opt_name) is not None:
raise OptionException('Option names can only contain letters, numbers or dashes.')
key = mesonlib.OptionKey.from_string(opt_name).evolve(subproject=self.subproject)
key = OptionKey.from_string(opt_name).evolve(subproject=self.subproject)
if self.optionstore.is_reserved_name(key):
raise OptionException('Option name %s is reserved.' % opt_name)

@ -3,12 +3,12 @@
from collections import OrderedDict
from itertools import chain
from functools import total_ordering
import argparse
import enum
from .mesonlib import (
HoldableObject,
OptionKey,
OptionType,
default_prefix,
default_datadir,
default_includedir,
@ -21,6 +21,7 @@ from .mesonlib import (
default_sysconfdir,
MesonException,
listify_array_value,
MachineChoice,
)
from . import mlog
@ -38,6 +39,239 @@ genvslitelist = ['vs2022']
buildtypelist = ['plain', 'debug', 'debugoptimized', 'release', 'minsize', 'custom']
class OptionType(enum.IntEnum):
"""Enum used to specify what kind of argument a thing is."""
BUILTIN = 0
BACKEND = 1
BASE = 2
COMPILER = 3
PROJECT = 4
def _classify_argument(key: 'OptionKey') -> OptionType:
"""Classify arguments into groups so we know which dict to assign them to."""
if key.name.startswith('b_'):
return OptionType.BASE
elif key.lang is not None:
return OptionType.COMPILER
elif key.name in _BUILTIN_NAMES or key.module:
return OptionType.BUILTIN
elif key.name.startswith('backend_'):
assert key.machine is MachineChoice.HOST, str(key)
return OptionType.BACKEND
else:
assert key.machine is MachineChoice.HOST, str(key)
return OptionType.PROJECT
# This is copied from coredata. There is no way to share this, because this
# is used in the OptionKey constructor, and the coredata lists are
# OptionKeys...
_BUILTIN_NAMES = {
'prefix',
'bindir',
'datadir',
'includedir',
'infodir',
'libdir',
'licensedir',
'libexecdir',
'localedir',
'localstatedir',
'mandir',
'sbindir',
'sharedstatedir',
'sysconfdir',
'auto_features',
'backend',
'buildtype',
'debug',
'default_library',
'errorlogs',
'genvslite',
'install_umask',
'layout',
'optimization',
'prefer_static',
'stdsplit',
'strip',
'unity',
'unity_size',
'warning_level',
'werror',
'wrap_mode',
'force_fallback_for',
'pkg_config_path',
'cmake_prefix_path',
'vsenv',
}
@total_ordering
class OptionKey:
"""Represents an option key in the various option dictionaries.
This provides a flexible, powerful way to map option names from their
external form (things like subproject:build.option) to something that
internally easier to reason about and produce.
"""
__slots__ = ['name', 'subproject', 'machine', 'lang', '_hash', 'type', 'module']
name: str
subproject: str
machine: MachineChoice
lang: T.Optional[str]
_hash: int
type: OptionType
module: T.Optional[str]
def __init__(self, name: str, subproject: str = '',
machine: MachineChoice = MachineChoice.HOST,
lang: T.Optional[str] = None,
module: T.Optional[str] = None,
_type: T.Optional[OptionType] = None):
# the _type option to the constructor is kinda private. We want to be
# able tos ave the state and avoid the lookup function when
# pickling/unpickling, but we need to be able to calculate it when
# constructing a new OptionKey
object.__setattr__(self, 'name', name)
object.__setattr__(self, 'subproject', subproject)
object.__setattr__(self, 'machine', machine)
object.__setattr__(self, 'lang', lang)
object.__setattr__(self, 'module', module)
object.__setattr__(self, '_hash', hash((name, subproject, machine, lang, module)))
if _type is None:
_type = _classify_argument(self)
object.__setattr__(self, 'type', _type)
def __setattr__(self, key: str, value: T.Any) -> None:
raise AttributeError('OptionKey instances do not support mutation.')
def __getstate__(self) -> T.Dict[str, T.Any]:
return {
'name': self.name,
'subproject': self.subproject,
'machine': self.machine,
'lang': self.lang,
'_type': self.type,
'module': self.module,
}
def __setstate__(self, state: T.Dict[str, T.Any]) -> None:
"""De-serialize the state of a pickle.
This is very clever. __init__ is not a constructor, it's an
initializer, therefore it's safe to call more than once. We create a
state in the custom __getstate__ method, which is valid to pass
splatted to the initializer.
"""
# Mypy doesn't like this, because it's so clever.
self.__init__(**state) # type: ignore
def __hash__(self) -> int:
return self._hash
def _to_tuple(self) -> T.Tuple[str, OptionType, str, str, MachineChoice, str]:
return (self.subproject, self.type, self.lang or '', self.module or '', self.machine, self.name)
def __eq__(self, other: object) -> bool:
if isinstance(other, OptionKey):
return self._to_tuple() == other._to_tuple()
return NotImplemented
def __lt__(self, other: object) -> bool:
if isinstance(other, OptionKey):
return self._to_tuple() < other._to_tuple()
return NotImplemented
def __str__(self) -> str:
out = self.name
if self.lang:
out = f'{self.lang}_{out}'
if self.machine is MachineChoice.BUILD:
out = f'build.{out}'
if self.module:
out = f'{self.module}.{out}'
if self.subproject:
out = f'{self.subproject}:{out}'
return out
def __repr__(self) -> str:
return f'OptionKey({self.name!r}, {self.subproject!r}, {self.machine!r}, {self.lang!r}, {self.module!r}, {self.type!r})'
@classmethod
def from_string(cls, raw: str) -> 'OptionKey':
"""Parse the raw command line format into a three part tuple.
This takes strings like `mysubproject:build.myoption` and Creates an
OptionKey out of them.
"""
try:
subproject, raw2 = raw.split(':')
except ValueError:
subproject, raw2 = '', raw
module = None
for_machine = MachineChoice.HOST
try:
prefix, raw3 = raw2.split('.')
if prefix == 'build':
for_machine = MachineChoice.BUILD
else:
module = prefix
except ValueError:
raw3 = raw2
from .compilers import all_languages
if any(raw3.startswith(f'{l}_') for l in all_languages):
lang, opt = raw3.split('_', 1)
else:
lang, opt = None, raw3
assert ':' not in opt
assert '.' not in opt
return cls(opt, subproject, for_machine, lang, module)
def evolve(self, name: T.Optional[str] = None, subproject: T.Optional[str] = None,
machine: T.Optional[MachineChoice] = None, lang: T.Optional[str] = '',
module: T.Optional[str] = '') -> 'OptionKey':
"""Create a new copy of this key, but with altered members.
For example:
>>> a = OptionKey('foo', '', MachineChoice.Host)
>>> b = OptionKey('foo', 'bar', MachineChoice.Host)
>>> b == a.evolve(subproject='bar')
True
"""
# We have to be a little clever with lang here, because lang is valid
# as None, for non-compiler options
return OptionKey(
name if name is not None else self.name,
subproject if subproject is not None else self.subproject,
machine if machine is not None else self.machine,
lang if lang != '' else self.lang,
module if module != '' else self.module
)
def as_root(self) -> 'OptionKey':
"""Convenience method for key.evolve(subproject='')."""
return self.evolve(subproject='')
def as_build(self) -> 'OptionKey':
"""Convenience method for key.evolve(machine=MachineChoice.BUILD)."""
return self.evolve(machine=MachineChoice.BUILD)
def as_host(self) -> 'OptionKey':
"""Convenience method for key.evolve(machine=MachineChoice.HOST)."""
return self.evolve(machine=MachineChoice.HOST)
def is_project_hack_for_optionsview(self) -> bool:
"""This method will be removed once we can delete OptionsView."""
return self.type is OptionType.PROJECT
class UserOption(T.Generic[_T], HoldableObject):
def __init__(self, name: str, description: str, choices: T.Optional[T.Union[str, T.List[_T]]],
yielding: bool,

@ -8,7 +8,7 @@ import pickle, subprocess
import typing as T
from ..coredata import CoreData
from ..backend.backends import RegenInfo
from ..mesonlib import OptionKey
from ..options import OptionKey
# This could also be used for XCode.

@ -15,7 +15,7 @@ import time
import abc
import platform, subprocess, operator, os, shlex, shutil, re
import collections
from functools import lru_cache, wraps, total_ordering
from functools import lru_cache, wraps
from itertools import tee
from tempfile import TemporaryDirectory, NamedTemporaryFile
import typing as T
@ -67,9 +67,7 @@ __all__ = [
'EnvironmentException',
'FileOrString',
'GitException',
'OptionKey',
'dump_conf_header',
'OptionType',
'OrderedSet',
'PerMachine',
'PerMachineDefaultable',
@ -1981,7 +1979,58 @@ class LibType(enum.IntEnum):
class ProgressBarFallback: # lgtm [py/iter-returns-non-self]
'''
Fallback progress bar implementation when tqdm is not found
Fallback progress bar implementation when tqdm is not foundclass OptionType(enum.IntEnum):
"""Enum used to specify what kind of argument a thing is."""
BUILTIN = 0
BACKEND = 1
BASE = 2
COMPILER = 3
PROJECT = 4
# This is copied from coredata. There is no way to share this, because this
# is used in the OptionKey constructor, and the coredata lists are
# OptionKeys...
_BUILTIN_NAMES = {
'prefix',
'bindir',
'datadir',
'includedir',
'infodir',
'libdir',
'licensedir',
'libexecdir',
'localedir',
'localstatedir',
'mandir',
'sbindir',
'sharedstatedir',
'sysconfdir',
'auto_features',
'backend',
'buildtype',
'debug',
'default_library',
'errorlogs',
'genvslite',
'install_umask',
'layout',
'optimization',
'prefer_static',
'stdsplit',
'strip',
'unity',
'unity_size',
'warning_level',
'werror',
'wrap_mode',
'force_fallback_for',
'pkg_config_path',
'cmake_prefix_path',
'vsenv',
}
Since this class is not an actual iterator, but only provides a minimal
fallback, it is safe to ignore the 'Iterator does not return self from
@ -2157,241 +2206,6 @@ def generate_list(func: T.Callable[..., T.Generator[_T, None, None]]) -> T.Calla
return wrapper
class OptionType(enum.IntEnum):
"""Enum used to specify what kind of argument a thing is."""
BUILTIN = 0
BACKEND = 1
BASE = 2
COMPILER = 3
PROJECT = 4
# This is copied from coredata. There is no way to share this, because this
# is used in the OptionKey constructor, and the coredata lists are
# OptionKeys...
_BUILTIN_NAMES = {
'prefix',
'bindir',
'datadir',
'includedir',
'infodir',
'libdir',
'licensedir',
'libexecdir',
'localedir',
'localstatedir',
'mandir',
'sbindir',
'sharedstatedir',
'sysconfdir',
'auto_features',
'backend',
'buildtype',
'debug',
'default_library',
'errorlogs',
'genvslite',
'install_umask',
'layout',
'optimization',
'prefer_static',
'stdsplit',
'strip',
'unity',
'unity_size',
'warning_level',
'werror',
'wrap_mode',
'force_fallback_for',
'pkg_config_path',
'cmake_prefix_path',
'vsenv',
}
def _classify_argument(key: 'OptionKey') -> OptionType:
"""Classify arguments into groups so we know which dict to assign them to."""
if key.name.startswith('b_'):
return OptionType.BASE
elif key.lang is not None:
return OptionType.COMPILER
elif key.name in _BUILTIN_NAMES or key.module:
return OptionType.BUILTIN
elif key.name.startswith('backend_'):
assert key.machine is MachineChoice.HOST, str(key)
return OptionType.BACKEND
else:
assert key.machine is MachineChoice.HOST, str(key)
return OptionType.PROJECT
@total_ordering
class OptionKey:
"""Represents an option key in the various option dictionaries.
This provides a flexible, powerful way to map option names from their
external form (things like subproject:build.option) to something that
internally easier to reason about and produce.
"""
__slots__ = ['name', 'subproject', 'machine', 'lang', '_hash', 'type', 'module']
name: str
subproject: str
machine: MachineChoice
lang: T.Optional[str]
_hash: int
type: OptionType
module: T.Optional[str]
def __init__(self, name: str, subproject: str = '',
machine: MachineChoice = MachineChoice.HOST,
lang: T.Optional[str] = None,
module: T.Optional[str] = None,
_type: T.Optional[OptionType] = None):
# the _type option to the constructor is kinda private. We want to be
# able tos ave the state and avoid the lookup function when
# pickling/unpickling, but we need to be able to calculate it when
# constructing a new OptionKey
object.__setattr__(self, 'name', name)
object.__setattr__(self, 'subproject', subproject)
object.__setattr__(self, 'machine', machine)
object.__setattr__(self, 'lang', lang)
object.__setattr__(self, 'module', module)
object.__setattr__(self, '_hash', hash((name, subproject, machine, lang, module)))
if _type is None:
_type = _classify_argument(self)
object.__setattr__(self, 'type', _type)
def __setattr__(self, key: str, value: T.Any) -> None:
raise AttributeError('OptionKey instances do not support mutation.')
def __getstate__(self) -> T.Dict[str, T.Any]:
return {
'name': self.name,
'subproject': self.subproject,
'machine': self.machine,
'lang': self.lang,
'_type': self.type,
'module': self.module,
}
def __setstate__(self, state: T.Dict[str, T.Any]) -> None:
"""De-serialize the state of a pickle.
This is very clever. __init__ is not a constructor, it's an
initializer, therefore it's safe to call more than once. We create a
state in the custom __getstate__ method, which is valid to pass
splatted to the initializer.
"""
# Mypy doesn't like this, because it's so clever.
self.__init__(**state) # type: ignore
def __hash__(self) -> int:
return self._hash
def _to_tuple(self) -> T.Tuple[str, OptionType, str, str, MachineChoice, str]:
return (self.subproject, self.type, self.lang or '', self.module or '', self.machine, self.name)
def __eq__(self, other: object) -> bool:
if isinstance(other, OptionKey):
return self._to_tuple() == other._to_tuple()
return NotImplemented
def __lt__(self, other: object) -> bool:
if isinstance(other, OptionKey):
return self._to_tuple() < other._to_tuple()
return NotImplemented
def __str__(self) -> str:
out = self.name
if self.lang:
out = f'{self.lang}_{out}'
if self.machine is MachineChoice.BUILD:
out = f'build.{out}'
if self.module:
out = f'{self.module}.{out}'
if self.subproject:
out = f'{self.subproject}:{out}'
return out
def __repr__(self) -> str:
return f'OptionKey({self.name!r}, {self.subproject!r}, {self.machine!r}, {self.lang!r}, {self.module!r}, {self.type!r})'
@classmethod
def from_string(cls, raw: str) -> 'OptionKey':
"""Parse the raw command line format into a three part tuple.
This takes strings like `mysubproject:build.myoption` and Creates an
OptionKey out of them.
"""
try:
subproject, raw2 = raw.split(':')
except ValueError:
subproject, raw2 = '', raw
module = None
for_machine = MachineChoice.HOST
try:
prefix, raw3 = raw2.split('.')
if prefix == 'build':
for_machine = MachineChoice.BUILD
else:
module = prefix
except ValueError:
raw3 = raw2
from ..compilers import all_languages
if any(raw3.startswith(f'{l}_') for l in all_languages):
lang, opt = raw3.split('_', 1)
else:
lang, opt = None, raw3
assert ':' not in opt
assert '.' not in opt
return cls(opt, subproject, for_machine, lang, module)
def evolve(self, name: T.Optional[str] = None, subproject: T.Optional[str] = None,
machine: T.Optional[MachineChoice] = None, lang: T.Optional[str] = '',
module: T.Optional[str] = '') -> 'OptionKey':
"""Create a new copy of this key, but with altered members.
For example:
>>> a = OptionKey('foo', '', MachineChoice.Host)
>>> b = OptionKey('foo', 'bar', MachineChoice.Host)
>>> b == a.evolve(subproject='bar')
True
"""
# We have to be a little clever with lang here, because lang is valid
# as None, for non-compiler options
return OptionKey(
name if name is not None else self.name,
subproject if subproject is not None else self.subproject,
machine if machine is not None else self.machine,
lang if lang != '' else self.lang,
module if module != '' else self.module
)
def as_root(self) -> 'OptionKey':
"""Convenience method for key.evolve(subproject='')."""
return self.evolve(subproject='')
def as_build(self) -> 'OptionKey':
"""Convenience method for key.evolve(machine=MachineChoice.BUILD)."""
return self.evolve(machine=MachineChoice.BUILD)
def as_host(self) -> 'OptionKey':
"""Convenience method for key.evolve(machine=MachineChoice.HOST)."""
return self.evolve(machine=MachineChoice.HOST)
def is_project_hack_for_optionsview(self) -> bool:
"""This method will be removed once we can delete OptionsView."""
return self.type is OptionType.PROJECT
def pickle_load(filename: str, object_name: str, object_type: T.Type[_PL], suggest_reconfigure: bool = True) -> _PL:
load_fail_msg = f'{object_name} file {filename!r} is corrupted.'
extra_msg = ' Consider reconfiguring the directory with "meson setup --reconfigure".' if suggest_reconfigure else ''

@ -35,7 +35,8 @@ from mesonbuild import mlog
from mesonbuild.environment import Environment, detect_ninja, detect_machine_info
from mesonbuild.coredata import version as meson_version
from mesonbuild.options import backendlist
from mesonbuild.mesonlib import OptionKey, setup_vsenv
from mesonbuild.mesonlib import setup_vsenv
from mesonbuild.options import OptionKey
if T.TYPE_CHECKING:
from mesonbuild.coredata import SharedCMDOptions

@ -31,9 +31,10 @@ from mesonbuild.mesonlib import (
BuildDirLock, MachineChoice, is_windows, is_osx, is_cygwin, is_dragonflybsd,
is_sunos, windows_proof_rmtree, python_command, version_compare, split_args, quote_arg,
relpath, is_linux, git, search_version, do_conf_file, do_conf_str, default_prefix,
MesonException, EnvironmentException, OptionKey,
MesonException, EnvironmentException,
windows_proof_rm
)
from mesonbuild.options import OptionKey
from mesonbuild.programs import ExternalProgram
from mesonbuild.compilers.mixins.clang import ClangCompiler

@ -18,9 +18,8 @@ import mesonbuild.options
import mesonbuild.modules.gnome
from mesonbuild.interpreter import Interpreter
from mesonbuild.ast import AstInterpreter
from mesonbuild.mesonlib import (
MachineChoice, OptionKey
)
from mesonbuild.mesonlib import MachineChoice
from mesonbuild.options import OptionKey
from mesonbuild.compilers import (
detect_c_compiler, detect_cpp_compiler
)

@ -11,9 +11,10 @@ from contextlib import contextmanager
from mesonbuild.compilers import detect_c_compiler, compiler_from_language
from mesonbuild.mesonlib import (
MachineChoice, is_osx, is_cygwin, EnvironmentException, OptionKey, MachineChoice,
MachineChoice, is_osx, is_cygwin, EnvironmentException, MachineChoice,
OrderedSet
)
from mesonbuild.options import OptionKey
from run_tests import get_fake_env

@ -32,9 +32,9 @@ from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments, ObjectH
from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments, typed_kwargs, ContainerTypeInfo, KwargInfo
from mesonbuild.mesonlib import (
LibType, MachineChoice, PerMachine, Version, is_windows, is_osx,
is_cygwin, is_openbsd, search_version, MesonException, OptionKey,
OptionType
is_cygwin, is_openbsd, search_version, MesonException,
)
from mesonbuild.options import OptionKey, OptionType
from mesonbuild.interpreter.type_checking import in_set_validator, NoneType
from mesonbuild.dependencies.pkgconfig import PkgConfigDependency, PkgConfigInterface, PkgConfigCLI
from mesonbuild.programs import ExternalProgram

@ -25,8 +25,9 @@ import mesonbuild.modules.gnome
from mesonbuild.mesonlib import (
MachineChoice, is_windows, is_osx, is_cygwin, is_openbsd, is_haiku,
is_sunos, windows_proof_rmtree, version_compare, is_linux,
OptionKey, EnvironmentException
EnvironmentException
)
from mesonbuild.options import OptionKey
from mesonbuild.compilers import (
detect_c_compiler, detect_cpp_compiler, compiler_from_language,
)

@ -17,8 +17,9 @@ import mesonbuild.coredata
import mesonbuild.modules.gnome
from mesonbuild.mesonlib import (
MachineChoice, is_windows, is_cygwin, python_command, version_compare,
EnvironmentException, OptionKey
EnvironmentException
)
from mesonbuild.options import OptionKey
from mesonbuild.compilers import (
detect_c_compiler, detect_d_compiler, compiler_from_language,
)

Loading…
Cancel
Save