Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize the OptionKey class more #14248

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions mesonbuild/ast/introspection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2018 The Meson development team
# Copyright © 2024 Intel Corporation
# Copyright © 2024-2025 Intel Corporation

# This class contains the basic functionality needed to run any interpreter
# or an interpreter-based tool
Expand Down Expand Up @@ -66,7 +66,7 @@ def __init__(self,
self.subproject_dir = subproject_dir
self.coredata = self.environment.get_coredata()
self.backend = backend
self.default_options = {OptionKey('backend'): self.backend}
self.default_options = {OptionKey.factory('backend'): self.backend}
self.project_data: T.Dict[str, T.Any] = {}
self.targets: T.List[T.Dict[str, T.Any]] = []
self.dependencies: T.List[T.Dict[str, T.Any]] = []
Expand Down Expand Up @@ -312,7 +312,7 @@ def traverse_nodes(inqueue: T.List[BaseNode]) -> T.List[BaseNode]:
return new_target

def build_library(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Optional[T.Dict[str, T.Any]]:
default_library = self.coredata.get_option(OptionKey('default_library'))
default_library = self.coredata.get_option(OptionKey.factory('default_library'))
if default_library == 'shared':
return self.build_target(node, args, kwargs, SharedLibrary)
elif default_library == 'static':
Expand Down
28 changes: 14 additions & 14 deletions mesonbuild/backend/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ def get_target_dir(self, target: T.Union[build.Target, build.CustomTargetIndex])
if isinstance(target, build.RunTarget):
# this produces no output, only a dummy top-level name
dirname = ''
elif self.environment.coredata.get_option(OptionKey('layout')) == 'mirror':
elif self.environment.coredata.get_option(OptionKey.factory('layout')) == 'mirror':
dirname = target.get_subdir()
else:
dirname = 'meson-out'
Expand Down Expand Up @@ -424,7 +424,7 @@ def generate_unity_files(self, target: build.BuildTarget, unity_src: str) -> T.L
abs_files: T.List[str] = []
result: T.List[mesonlib.File] = []
compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
unity_size = target.get_option(OptionKey('unity_size'))
unity_size = target.get_option(OptionKey.factory('unity_size'))
assert isinstance(unity_size, int), 'for mypy'

def init_language_file(suffix: str, unity_file_number: int) -> T.TextIO:
Expand Down Expand Up @@ -818,7 +818,7 @@ def rpaths_for_non_system_absolute_shared_libraries(self, target: build.BuildTar
def determine_rpath_dirs(self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]
) -> T.Tuple[str, ...]:
result: OrderedSet[str]
if self.environment.coredata.get_option(OptionKey('layout')) == 'mirror':
if self.environment.coredata.get_option(OptionKey.factory('layout')) == 'mirror':
# Need a copy here
result = OrderedSet(target.get_link_dep_subdirs())
else:
Expand Down Expand Up @@ -878,7 +878,7 @@ def object_filename_from_source(self, target: build.BuildTarget, compiler: Compi
object_suffix = machine.get_object_suffix()
# For the TASKING compiler, in case of LTO or prelinking the object suffix has to be .mil
if compiler.get_id() == 'tasking':
if target.get_option(OptionKey('b_lto')) or (isinstance(target, build.StaticLibrary) and target.prelink):
if target.get_option(OptionKey.factory('b_lto')) or (isinstance(target, build.StaticLibrary) and target.prelink):
if not source.rsplit('.', 1)[1] in lang_suffixes['c']:
if isinstance(target, build.StaticLibrary) and not target.prelink:
raise EnvironmentException('Tried using MIL linking for a static library with a assembly file. This can only be done if the static library is prelinked or disable \'b_lto\'.')
Expand Down Expand Up @@ -928,7 +928,7 @@ def _determine_ext_objs(self, extobj: 'build.ExtractedObjects') -> T.List[str]:
if extobj.target.is_unity:
compsrcs = classify_unity_sources(extobj.target.compilers.values(), sources)
sources = []
unity_size = extobj.target.get_option(OptionKey('unity_size'))
unity_size = extobj.target.get_option(OptionKey.factory('unity_size'))
assert isinstance(unity_size, int), 'for mypy'

for comp, srcs in compsrcs.items():
Expand Down Expand Up @@ -981,7 +981,7 @@ def create_msvc_pch_implementation(self, target: build.BuildTarget, lang: str, p

def target_uses_pch(self, target: build.BuildTarget) -> bool:
try:
return T.cast('bool', target.get_option(OptionKey('b_pch')))
return T.cast('bool', target.get_option(OptionKey.factory('b_pch')))
except (KeyError, AttributeError):
return False

Expand Down Expand Up @@ -1015,22 +1015,22 @@ def generate_basic_compiler_args(self, target: build.BuildTarget, compiler: 'Com
# Add things like /NOLOGO or -pipe; usually can't be overridden
commands += compiler.get_always_args()
# warning_level is a string, but mypy can't determine that
commands += compiler.get_warn_args(T.cast('str', target.get_option(OptionKey('warning_level'))))
commands += compiler.get_warn_args(T.cast('str', target.get_option(OptionKey.factory('warning_level'))))
# Add -Werror if werror=true is set in the build options set on the
# command-line or default_options inside project(). This only sets the
# action to be done for warnings if/when they are emitted, so it's ok
# to set it after or get_warn_args().
if target.get_option(OptionKey('werror')):
if target.get_option(OptionKey.factory('werror')):
commands += compiler.get_werror_args()
# Add compile args for c_* or cpp_* build options set on the
# command-line or default_options inside project().
commands += compiler.get_option_compile_args(copt_proxy)

optimization = target.get_option(OptionKey('optimization'))
optimization = target.get_option(OptionKey.factory('optimization'))
assert isinstance(optimization, str), 'for mypy'
commands += compiler.get_optimization_args(optimization)

debug = target.get_option(OptionKey('debug'))
debug = target.get_option(OptionKey.factory('debug'))
assert isinstance(debug, bool), 'for mypy'
commands += compiler.get_debug_args(debug)

Expand Down Expand Up @@ -1336,7 +1336,7 @@ def construct_target_rel_paths(self, t: T.Union[build.Target, build.CustomTarget
def generate_depmf_install(self, d: InstallData) -> None:
depmf_path = self.build.dep_manifest_name
if depmf_path is None:
option_dir = self.environment.coredata.get_option(OptionKey('licensedir'))
option_dir = self.environment.coredata.get_option(OptionKey.factory('licensedir'))
assert isinstance(option_dir, str), 'for mypy'
if option_dir:
depmf_path = os.path.join(option_dir, 'depmf.json')
Expand Down Expand Up @@ -1667,7 +1667,7 @@ def create_install_data(self) -> InstallData:
# TODO go through all candidates, like others
strip_bin = [detect.defaults['strip'][0]]

umask = self.environment.coredata.get_option(OptionKey('install_umask'))
umask = self.environment.coredata.get_option(OptionKey.factory('install_umask'))
assert isinstance(umask, (str, int)), 'for mypy'

d = InstallData(self.environment.get_source_dir(),
Expand Down Expand Up @@ -1699,7 +1699,7 @@ def guess_install_tag(self, fname: str, outdir: T.Optional[str] = None) -> T.Opt
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(OptionKey('localedir'))
_ldir = self.environment.coredata.get_option(OptionKey.factory('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)
Expand Down Expand Up @@ -1755,7 +1755,7 @@ def generate_target_install(self, d: InstallData) -> None:
# TODO: Create GNUStrip/AppleStrip/etc. hierarchy for more
# fine-grained stripping of static archives.
can_strip = not isinstance(t, build.StaticLibrary)
should_strip = can_strip and t.get_option(OptionKey('strip'))
should_strip = can_strip and t.get_option(OptionKey.factory('strip'))
assert isinstance(should_strip, bool), 'for mypy'
# Install primary build output (library/executable/jar, etc)
# Done separately because of strip/aliases/rpath
Expand Down
34 changes: 17 additions & 17 deletions mesonbuild/backend/ninjabackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ def generate(self, capture: bool = False, vslite_ctx: T.Optional[T.Dict] = None)
# so no harm in catching and reporting something unexpected.
raise MesonBugException('We do not expect the ninja backend to be given a valid \'vslite_ctx\'')
ninja = environment.detect_ninja_command_and_version(log=True)
if self.environment.coredata.get_option(OptionKey('vsenv')):
if self.environment.coredata.get_option(OptionKey.factory('vsenv')):
builddir = Path(self.environment.get_build_dir())
try:
# For prettier printing, reduce to a relative path. If
Expand Down Expand Up @@ -670,7 +670,7 @@ def generate(self, capture: bool = False, vslite_ctx: T.Optional[T.Dict] = None)
mlog.log_timestamp("Install generated")
self.generate_dist()
mlog.log_timestamp("Dist generated")
key = OptionKey('b_coverage')
key = OptionKey.factory('b_coverage')
if (key in self.environment.coredata.optstore and
self.environment.coredata.optstore.get_value(key)):
gcovr_exe, gcovr_version, lcov_exe, lcov_version, genhtml_exe, llvm_cov_exe = environment.find_coverage_tools(self.environment.coredata)
Expand Down Expand Up @@ -1117,7 +1117,7 @@ def should_use_dyndeps_for_target(self, target: 'build.BuildTarget') -> bool:
cpp = target.compilers['cpp']
if cpp.get_id() != 'msvc':
return False
cppversion = target.get_option(OptionKey('cpp_std', machine=target.for_machine))
cppversion = target.get_option(OptionKey.factory('cpp_std', machine=target.for_machine))
if cppversion not in ('latest', 'c++latest', 'vc++latest'):
return False
if not mesonlib.current_vs_supports_modules():
Expand Down Expand Up @@ -1337,9 +1337,9 @@ def generate_install(self) -> None:
def generate_tests(self) -> None:
self.serialize_tests()
cmd = self.environment.get_build_command(True) + ['test', '--no-rebuild']
if not self.environment.coredata.get_option(OptionKey('stdsplit')):
if not self.environment.coredata.get_option(OptionKey.factory('stdsplit')):
cmd += ['--no-stdsplit']
if self.environment.coredata.get_option(OptionKey('errorlogs')):
if self.environment.coredata.get_option(OptionKey.factory('errorlogs')):
cmd += ['--print-errorlogs']
elem = self.create_phony_target('test', 'CUSTOM_COMMAND', ['all', 'meson-test-prereq', 'PHONY'])
elem.add_item('COMMAND', cmd)
Expand Down Expand Up @@ -1725,7 +1725,7 @@ def generate_vala_compile(self, target: build.BuildTarget) -> \
valac_outputs.append(vala_c_file)

args = self.generate_basic_compiler_args(target, valac)
args += valac.get_colorout_args(target.get_option(OptionKey('b_colorout')))
args += valac.get_colorout_args(target.get_option(OptionKey.factory('b_colorout')))
# Tell Valac to output everything in our private directory. Sadly this
# means it will also preserve the directory components of Vala sources
# found inside the build tree (generated sources).
Expand Down Expand Up @@ -1803,14 +1803,14 @@ def generate_cython_transpile(self, target: build.BuildTarget) -> \

args: T.List[str] = []
args += cython.get_always_args()
args += cython.get_debug_args(target.get_option(OptionKey('debug')))
args += cython.get_optimization_args(target.get_option(OptionKey('optimization')))
args += cython.get_debug_args(target.get_option(OptionKey.factory('debug')))
args += cython.get_optimization_args(target.get_option(OptionKey.factory('optimization')))
args += cython.get_option_compile_args(target.get_options())
args += self.build.get_global_args(cython, target.for_machine)
args += self.build.get_project_args(cython, target.subproject, target.for_machine)
args += target.get_extra_args('cython')

ext = target.get_option(OptionKey('cython_language', machine=target.for_machine))
ext = target.get_option(OptionKey.factory('cython_language', machine=target.for_machine))

pyx_sources = [] # Keep track of sources we're adding to build

Expand Down Expand Up @@ -2017,8 +2017,8 @@ def generate_rust_target(self, target: build.BuildTarget) -> None:
# https://github.com/rust-lang/rust/issues/39016
if not isinstance(target, build.StaticLibrary):
try:
buildtype = target.get_option(OptionKey('buildtype'))
crt = target.get_option(OptionKey('b_vscrt'))
buildtype = target.get_option(OptionKey.factory('buildtype'))
crt = target.get_option(OptionKey.factory('b_vscrt'))
args += rustc.get_crt_link_args(crt, buildtype)
except (KeyError, AttributeError):
pass
Expand Down Expand Up @@ -3064,7 +3064,7 @@ def generate_single_compile(self, target: build.BuildTarget, src,
# If TASKING compiler family is used and MIL linking is enabled for the target,
# then compilation rule name is a special one to output MIL files
# instead of object files for .c files
key = OptionKey('b_lto')
key = OptionKey.factory('b_lto')
if compiler.get_id() == 'tasking':
if ((isinstance(target, build.StaticLibrary) and target.prelink) or target.get_option(key)) and src.rsplit('.', 1)[1] in compilers.lang_suffixes['c']:
compiler_name = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine)
Expand Down Expand Up @@ -3522,9 +3522,9 @@ def generate_link(self, target: build.BuildTarget, outname, obj_list, linker: T.
# Add things like /NOLOGO; usually can't be overridden
commands += linker.get_linker_always_args()
# Add buildtype linker args: optimization level, etc.
commands += linker.get_optimization_link_args(target.get_option(OptionKey('optimization')))
commands += linker.get_optimization_link_args(target.get_option(OptionKey.factory('optimization')))
# Add /DEBUG and the pdb filename when using MSVC
if target.get_option(OptionKey('debug')):
if target.get_option(OptionKey.factory('debug')):
commands += self.get_link_debugfile_args(linker, target)
debugfile = self.get_link_debugfile_name(linker, target)
if debugfile is not None:
Expand Down Expand Up @@ -3611,7 +3611,7 @@ def generate_link(self, target: build.BuildTarget, outname, obj_list, linker: T.
elem = NinjaBuildElement(self.all_outputs, outname, linker_rule, obj_list, implicit_outs=implicit_outs)
elem.add_dep(dep_targets + custom_target_libraries)
if linker.get_id() == 'tasking':
if len([x for x in dep_targets + custom_target_libraries if x.endswith('.ma')]) > 0 and not target.get_option(OptionKey('b_lto')):
if len([x for x in dep_targets + custom_target_libraries if x.endswith('.ma')]) > 0 and not target.get_option(OptionKey.factory('b_lto')):
raise MesonException(f'Tried to link the target named \'{target.name}\' with a MIL archive without LTO enabled! This causes the compiler to ignore the archive.')

# Compiler args must be included in TI C28x linker commands.
Expand Down Expand Up @@ -3731,7 +3731,7 @@ def generate_clangtool(self, name: str, extra_arg: T.Optional[str] = None) -> No
target_name += f'-{extra_arg}'
extra_args.append(f'--{extra_arg}')
colorout = self.environment.coredata.optstore.get_value('b_colorout') \
if OptionKey('b_colorout') in self.environment.coredata.optstore else 'always'
if OptionKey.factory('b_colorout') in self.environment.coredata.optstore else 'always'
extra_args.extend(['--color', colorout])
if not os.path.exists(os.path.join(self.environment.source_dir, '.clang-' + name)) and \
not os.path.exists(os.path.join(self.environment.source_dir, '_clang-' + name)):
Expand Down Expand Up @@ -3826,7 +3826,7 @@ def generate_ending(self) -> None:
if ctlist:
elem.add_dep(self.generate_custom_target_clean(ctlist))

if OptionKey('b_coverage') in self.environment.coredata.optstore and \
if OptionKey.factory('b_coverage') in self.environment.coredata.optstore and \
self.environment.coredata.optstore.get_value('b_coverage'):
self.generate_gcov_clean()
elem.add_dep('clean-gcda')
Expand Down
Loading
Loading