| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright © 2020-2025 Intel Corporation |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
import itertools |
| 6 |
import os |
| 7 |
import re |
| 8 |
import textwrap |
| 9 |
import typing as T |
| 10 |
|
| 11 |
from mesonbuild.interpreterbase.decorators import FeatureNew |
| 12 |
|
| 13 |
from . import ExtensionModule, ModuleReturnValue, ModuleInfo, ModuleObject |
| 14 |
from .. import mesonlib, mlog |
| 15 |
from ..build import (BothLibraries, BuildTarget, CustomTargetIndex, Executable, ExtractedObjects, GeneratedList, |
| 16 |
CustomTarget, InvalidArguments, Jar, StructuredSources, SharedLibrary, StaticLibrary, |
| 17 |
SharedModule) |
| 18 |
from ..compilers.compilers import are_asserts_disabled_for_subproject, lang_suffixes |
| 19 |
from ..compilers.rust import parse_target, RustSystemDependency |
| 20 |
from ..dependencies import Dependency |
| 21 |
from ..interpreter.decorators import apply_machine_map |
| 22 |
from ..interpreter.type_checking import ( |
| 23 |
DEPENDENCIES_KW, LINK_WITH_KW, LINK_WHOLE_KW, SHARED_LIB_KWS, TEST_KWS, TEST_KWS_NO_ARGS, |
| 24 |
OUTPUT_KW, INCLUDE_DIRECTORIES, SOURCES_VARARGS, NATIVE_KW, NoneType, in_set_validator, |
| 25 |
EXECUTABLE_KWS, LIBRARY_KWS, SHARED_MOD_KWS, _BASE_LANG_KW, DEPEND_FILES_KW, INSTALL_DIR_KW, INSTALL_KW, |
| 26 |
) |
| 27 |
from ..interpreterbase import ContainerTypeInfo, InterpreterException, KwargInfo, typed_kwargs, typed_pos_args, noKwargs, noPosargs |
| 28 |
from ..interpreter.interpreterobjects import Doctest |
| 29 |
from ..mesonlib import (is_parent_path, File, MachineChoice, MesonException, PerMachine) |
| 30 |
from ..programs import ExternalProgram, NonExistingExternalProgram |
| 31 |
|
| 32 |
if T.TYPE_CHECKING: |
| 33 |
from . import ModuleState |
| 34 |
from .. import cargo |
| 35 |
from ..build import ExecutableKeywordArguments, GeneratedTypes, IncludeDirs, LinkableTargetTypes, CommandTypes |
| 36 |
from ..cargo.interpreter import RUST_ABI, PackageConfiguration |
| 37 |
from ..compilers.compilers import Language |
| 38 |
from ..compilers.rust import RustCompiler |
| 39 |
from ..dependencies import ExternalLibrary |
| 40 |
from ..interpreter import Interpreter |
| 41 |
from ..interpreter import kwargs as _kwargs |
| 42 |
from ..interpreter.kwargs import TargetDepends |
| 43 |
from ..interpreter.interpreter import SourceOutputs |
| 44 |
from ..interpreter.interpreterobjects import Test |
| 45 |
from ..interpreterbase import TYPE_kwargs |
| 46 |
from ..programs import Program |
| 47 |
from ..interpreter.type_checking import SourcesVarargsType |
| 48 |
from ..utils.universal import FileOrString |
| 49 |
|
| 50 |
from typing_extensions import Literal, TypedDict |
| 51 |
|
| 52 |
ArgsType = T.TypeVar('ArgsType') |
| 53 |
|
| 54 |
class FuncRustTest(_kwargs.BaseTest, T.Generic[ArgsType]): |
| 55 |
args: T.List[ArgsType] |
| 56 |
dependencies: T.List[T.Union[Dependency, ExternalLibrary]] |
| 57 |
is_parallel: bool |
| 58 |
link_with: T.List[LinkableTargetTypes] |
| 59 |
link_whole: T.List[T.Union[StaticLibrary, CustomTarget, CustomTargetIndex]] |
| 60 |
rust_args: T.List[str] |
| 61 |
|
| 62 |
FuncTest = FuncRustTest[CommandTypes] |
| 63 |
FuncDoctest = FuncRustTest[str] |
| 64 |
|
| 65 |
class FuncBindgen(TypedDict): |
| 66 |
|
| 67 |
args: T.List[str] |
| 68 |
c_args: T.List[str] |
| 69 |
include_directories: T.List[IncludeDirs] |
| 70 |
input: T.List[T.Union[File, str, GeneratedTypes, BuildTarget, BothLibraries, ExtractedObjects]] |
| 71 |
output: str |
| 72 |
output_inline_wrapper: str |
| 73 |
dependencies: T.List[T.Union[Dependency, ExternalLibrary]] |
| 74 |
language: T.Optional[Literal['c', 'cpp']] |
| 75 |
bindgen_version: T.List[str] |
| 76 |
|
| 77 |
class FuncCBindgen(TypedDict): |
| 78 |
|
| 79 |
config: str | File | CustomTarget | CustomTargetIndex |
| 80 |
language: T.Literal['c', 'cpp', 'cython'] | None |
| 81 |
depends: list[TargetDepends] |
| 82 |
depend_files: list[FileOrString] |
| 83 |
install: bool |
| 84 |
install_dir: str | None |
| 85 |
|
| 86 |
class FuncSubproject(TypedDict): |
| 87 |
native: MachineChoice |
| 88 |
|
| 89 |
class FuncPackage(TypedDict): |
| 90 |
native: MachineChoice |
| 91 |
|
| 92 |
class FuncWorkspace(TypedDict): |
| 93 |
default_features: T.Optional[bool] |
| 94 |
features: T.List[str] |
| 95 |
extra_members: T.List[str] |
| 96 |
|
| 97 |
class FuncDependency(TypedDict): |
| 98 |
rust_abi: T.Optional[RUST_ABI] |
| 99 |
|
| 100 |
class RustPackageDependencies(TypedDict): |
| 101 |
dependencies: bool |
| 102 |
dev_dependencies: bool |
| 103 |
system_dependencies: bool |
| 104 |
|
| 105 |
class RustPackageExecutable(_kwargs.Executable): |
| 106 |
pass |
| 107 |
|
| 108 |
class RustPackageLibrary(_kwargs.Library): |
| 109 |
pass |
| 110 |
|
| 111 |
RUST_TEST_KWS: T.List[KwargInfo] = [ |
| 112 |
KwargInfo( |
| 113 |
'rust_args', |
| 114 |
ContainerTypeInfo(list, str), |
| 115 |
listify=True, |
| 116 |
default=[], |
| 117 |
since='1.2.0', |
| 118 |
), |
| 119 |
KwargInfo('is_parallel', bool, default=False), |
| 120 |
] |
| 121 |
|
| 122 |
# The native argument should be passed to the "package" method |
| 123 |
EXECUTABLE_KWS_NO_NATIVE = [kwi for kwi in EXECUTABLE_KWS if kwi.name != 'native'] |
| 124 |
LIBRARY_KWS_NO_NATIVE = [kwi for kwi in LIBRARY_KWS if kwi.name != 'native'] |
| 125 |
SHARED_LIB_KWS_NO_NATIVE = [kwi for kwi in SHARED_LIB_KWS if kwi.name != 'native'] |
| 126 |
SHARED_MOD_KWS_NO_NATIVE = [kwi for kwi in SHARED_MOD_KWS if kwi.name != 'native'] |
| 127 |
|
| 128 |
_ALLOWED_PROC_MACRO_KWS = { |
| 129 |
'rust_args', 'rust_dependency_map', 'sources', 'dependencies', |
| 130 |
'extra_files', 'link_args', 'link_depends', 'link_with', 'override_options', |
| 131 |
} |
| 132 |
_PROC_MACRO_KWS = [s for s in SHARED_LIB_KWS if s.name in _ALLOWED_PROC_MACRO_KWS] |
| 133 |
|
| 134 |
|
| 135 |
def no_spaces_validator(arg: T.Optional[T.Union[str, T.List]]) -> T.Optional[str]: |
| 136 |
if any(bool(re.search(r'\s', x)) for x in arg): |
| 137 |
return 'must not contain spaces due to limitations of rustdoc' |
| 138 |
return None |
| 139 |
|
| 140 |
def dep_to_system_dependency(dep: Dependency, depname: str) -> Dependency: |
| 141 |
if not dep.found(): |
| 142 |
return dep |
| 143 |
if not depname: |
| 144 |
if not dep.name: |
| 145 |
raise MesonException("rust.to_system_dependency() called with an unnamed dependency and no explicit name") |
| 146 |
depname = dep.name |
| 147 |
depname = re.sub(r'[^a-zA-Z0-9]', '_', depname) |
| 148 |
rust_args = ['--cfg', f'system_deps_have_{depname}'] |
| 149 |
return RustSystemDependency(dep.version, compile_args=rust_args, ext_deps=[dep], name=dep.name) |
| 150 |
|
| 151 |
class RustWorkspace(ModuleObject): |
| 152 |
"""Represents a Rust workspace, controlling the build of packages |
| 153 |
recorded in a Cargo.lock file.""" |
| 154 |
|
| 155 |
def __init__(self, interpreter: Interpreter, ws: cargo.WorkspaceState) -> None: |
| 156 |
super().__init__() |
| 157 |
self.interpreter = interpreter |
| 158 |
self.ws = ws |
| 159 |
self.methods.update({ |
| 160 |
'packages': self.packages_method, |
| 161 |
'package': self.package_method, |
| 162 |
'subproject': self.subproject_method, |
| 163 |
}) |
| 164 |
|
| 165 |
@property |
| 166 |
def subdir(self) -> str: |
| 167 |
return self.ws.subdir |
| 168 |
|
| 169 |
@noPosargs |
| 170 |
@noKwargs |
| 171 |
def packages_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.List[str]: |
| 172 |
"""Returns list of package names in workspace.""" |
| 173 |
package_names = [pkg.manifest.package.name |
| 174 |
for pkg in self.ws.packages.values() |
| 175 |
if pkg.cfg.host or pkg.cfg.build] |
| 176 |
return sorted(package_names) |
| 177 |
|
| 178 |
@typed_pos_args('workspace.package', optargs=[str]) |
| 179 |
@typed_kwargs( |
| 180 |
'workspace.package', |
| 181 |
NATIVE_KW.evolve(since='1.12.0')) |
| 182 |
def package_method(self, state: 'ModuleState', args: T.List, kwargs: FuncPackage) -> RustPackage: |
| 183 |
"""Returns a package object.""" |
| 184 |
package_name = args[0] if args else None |
| 185 |
return RustPackage(state, self, self.interpreter.cargo.load_package(self.ws, package_name), |
| 186 |
kwargs['native']) |
| 187 |
|
| 188 |
def _do_subproject(self, state: ModuleState, pkg: cargo.PackageState, for_machine: MachineChoice) -> None: |
| 189 |
# Unless the crate builds as both a procedural macro and something else, |
| 190 |
# it can be built just once; the same dependency is used as an override |
| 191 |
# for both the host and the build machine. In that case, always build the |
| 192 |
# subproject for the build machine to ensure that it is not run twice. |
| 193 |
if pkg.manifest.lib.crate_type == ['proc-macro']: |
| 194 |
assert not pkg.has_both_machines() |
| 195 |
for_machine = state.machine_map.build |
| 196 |
|
| 197 |
kw: _kwargs.DoSubproject = { |
| 198 |
'required': True, |
| 199 |
'version': None, |
| 200 |
'options': None, |
| 201 |
'cmake_options': [], |
| 202 |
'default_options': {}, |
| 203 |
'for_machine': for_machine, |
| 204 |
} |
| 205 |
subp_name = pkg.get_subproject_name() |
| 206 |
self.interpreter.do_subproject(subp_name, kw, force_method='cargo') |
| 207 |
|
| 208 |
@typed_pos_args('workspace.subproject', str, optargs=[str]) |
| 209 |
@typed_kwargs( |
| 210 |
'workspace.subproject', |
| 211 |
NATIVE_KW.evolve(since='1.12.0')) |
| 212 |
def subproject_method(self, state: ModuleState, args: T.Tuple[str, T.Optional[str]], kwargs: FuncSubproject) -> RustSubproject: |
| 213 |
"""Returns a package object for a subproject package.""" |
| 214 |
package_name = args[0] |
| 215 |
pkg = self.interpreter.cargo.resolve_package(package_name, args[1] or '') |
| 216 |
if pkg is None: |
| 217 |
if args[1]: |
| 218 |
raise MesonException(f'No version of cargo package "{package_name}" provides API {args[1]}') |
| 219 |
else: |
| 220 |
raise MesonException(f'Cargo package "{package_name}" not available') |
| 221 |
|
| 222 |
self._do_subproject(state, pkg, kwargs['native']) |
| 223 |
return RustSubproject(state, self, pkg, kwargs['native']) |
| 224 |
|
| 225 |
|
| 226 |
class RustCrate(ModuleObject): |
| 227 |
"""Abstract base class for Rust crate representations.""" |
| 228 |
|
| 229 |
def __init__(self, state: ModuleState, rust_ws: RustWorkspace, package: cargo.PackageState, for_machine: MachineChoice) -> None: |
| 230 |
super().__init__() |
| 231 |
|
| 232 |
self.for_machine = state.machine_map[for_machine] |
| 233 |
self.rust_ws = rust_ws |
| 234 |
self.package = package |
| 235 |
self.methods.update({ |
| 236 |
'all_features': self.all_features_method, |
| 237 |
'api': self.api_method, |
| 238 |
'features': self.features_method, |
| 239 |
'name': self.name_method, |
| 240 |
'version': self.version_method, |
| 241 |
'rust_args': self.rust_args_method, |
| 242 |
'env': self.env_method, # type: ignore[dict-item] |
| 243 |
'rust_dependency_map': self.rust_dependency_map_method, # type: ignore[dict-item] |
| 244 |
}) |
| 245 |
|
| 246 |
@property |
| 247 |
def cfg(self) -> PackageConfiguration: |
| 248 |
return self.package.cfg[self.for_machine] |
| 249 |
|
| 250 |
@noPosargs |
| 251 |
@noKwargs |
| 252 |
def name_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> str: |
| 253 |
"""Returns the name of the package.""" |
| 254 |
return self.package.manifest.package.name |
| 255 |
|
| 256 |
@noPosargs |
| 257 |
@noKwargs |
| 258 |
def api_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> str: |
| 259 |
"""Returns the API version of the package.""" |
| 260 |
return self.package.manifest.package.api |
| 261 |
|
| 262 |
@noPosargs |
| 263 |
@noKwargs |
| 264 |
def version_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> str: |
| 265 |
"""Returns the version of the package.""" |
| 266 |
return self.package.manifest.package.version |
| 267 |
|
| 268 |
@noPosargs |
| 269 |
@noKwargs |
| 270 |
def all_features_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.List[str]: |
| 271 |
"""Returns all features for specific package.""" |
| 272 |
return sorted(list(self.package.manifest.features.keys())) |
| 273 |
|
| 274 |
@noPosargs |
| 275 |
@noKwargs |
| 276 |
def features_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.List[str]: |
| 277 |
"""Returns chosen features for specific package.""" |
| 278 |
return sorted(list(self.cfg.features)) |
| 279 |
|
| 280 |
@noPosargs |
| 281 |
@noKwargs |
| 282 |
def rust_args_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.List[str]: |
| 283 |
"""Returns rustc arguments for this package.""" |
| 284 |
return self.package.get_rustc_args(state.environment, state.subdir, self.for_machine) |
| 285 |
|
| 286 |
@noPosargs |
| 287 |
@noKwargs |
| 288 |
def env_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.Dict[str, str]: |
| 289 |
"""Returns environment variables for this package.""" |
| 290 |
return self.package.get_env_dict(state.environment, state.subdir) |
| 291 |
|
| 292 |
@noPosargs |
| 293 |
@noKwargs |
| 294 |
def rust_dependency_map_method(self, state: ModuleState, args: T.List, kwargs: TYPE_kwargs) -> T.Dict[str, str]: |
| 295 |
"""Returns rust dependency mapping for this package.""" |
| 296 |
return self.cfg.get_dependency_map(self.package.manifest) |
| 297 |
|
| 298 |
|
| 299 |
class RustPackage(RustCrate): |
| 300 |
"""Represents a Rust package within a workspace.""" |
| 301 |
|
| 302 |
def __init__(self, state: ModuleState, rust_ws: RustWorkspace, package: cargo.PackageState, for_machine: MachineChoice) -> None: |
| 303 |
super().__init__(state, rust_ws, package, for_machine) |
| 304 |
if not package.cfg[self.for_machine]: |
| 305 |
raise MesonException(f"package {self.package.manifest.package.name}-{self.package.manifest.package.version} not configured for {self.for_machine}") |
| 306 |
|
| 307 |
self.methods.update({ |
| 308 |
'dependencies': self.dependencies_method, |
| 309 |
'library': self.library_method, |
| 310 |
'proc_macro': self.proc_macro_method, |
| 311 |
'shared_module': self.shared_module_method, |
| 312 |
'executable': self.executable_method, |
| 313 |
'override_dependency': self.override_dependency_method, |
| 314 |
}) |
| 315 |
|
| 316 |
def _dependencies_method(self, state: ModuleState, kwargs: RustPackageDependencies, |
| 317 |
for_machine: MachineChoice) -> T.List[Dependency]: |
| 318 |
dependencies: T.List[Dependency] = [] |
| 319 |
cfg = self.package.cfg[for_machine] |
| 320 |
|
| 321 |
if kwargs['dependencies']: |
| 322 |
for dep_key, dep_pkg in cfg.dep_packages.items(): |
| 323 |
if dep_pkg.manifest.lib: |
| 324 |
if dep_pkg.ws_subdir != self.rust_ws.subdir or \ |
| 325 |
is_parent_path(os.path.join(self.rust_ws.subdir, state.subproject_dir), |
| 326 |
dep_pkg.path): |
| 327 |
self.rust_ws._do_subproject(state, dep_pkg, for_machine) |
| 328 |
# Get the dependency name for this package (rust or proc-macro ABI) |
| 329 |
depname = dep_pkg.get_rust_dependency_name() |
| 330 |
dependency = state.overridden_dependency(depname, for_machine) |
| 331 |
dependencies.append(dependency) |
| 332 |
|
| 333 |
if kwargs['dev_dependencies']: |
| 334 |
raise MesonException('dev_dependencies is not implemented yet') |
| 335 |
|
| 336 |
if kwargs['system_dependencies']: |
| 337 |
for name, sys_dep in self.package.manifest.system_dependencies.items(): |
| 338 |
if sys_dep.enabled(cfg.features): |
| 339 |
# System dependencies use the original dependency name from Cargo.toml |
| 340 |
dependency = state.dependency(sys_dep.name, native=(for_machine == MachineChoice.BUILD), |
| 341 |
required=not sys_dep.optional, |
| 342 |
wanted=sys_dep.meson_version) |
| 343 |
dependencies.append(dep_to_system_dependency(dependency, name)) |
| 344 |
|
| 345 |
return dependencies |
| 346 |
|
| 347 |
@noPosargs |
| 348 |
@typed_kwargs('package.dependencies', |
| 349 |
KwargInfo('dependencies', bool, default=True), |
| 350 |
KwargInfo('dev_dependencies', bool, default=False), |
| 351 |
KwargInfo('system_dependencies', bool, default=True)) |
| 352 |
def dependencies_method(self, state: ModuleState, args: T.List, kwargs: RustPackageDependencies) -> T.List[Dependency]: |
| 353 |
"""Returns the dependencies for this package.""" |
| 354 |
return self._dependencies_method(state, kwargs, self.for_machine) |
| 355 |
|
| 356 |
@staticmethod |
| 357 |
def validate_pos_args(name: str, args: T.Tuple[ |
| 358 |
T.Optional[T.Union[str, StructuredSources]], |
| 359 |
T.Optional[StructuredSources]]) -> T.Tuple[T.Optional[str], T.Optional[StructuredSources]]: |
| 360 |
if isinstance(args[0], str): |
| 361 |
return args[0], args[1] |
| 362 |
if args[1] is not None: |
| 363 |
raise MesonException(f"{name} only accepts one StructuredSources parameter") |
| 364 |
return None, args[0] |
| 365 |
|
| 366 |
def merge_kw_args(self, state: ModuleState, kwargs: T.Union[RustPackageExecutable, RustPackageLibrary]) -> None: |
| 367 |
if state.environment.is_cross_build(): |
| 368 |
kwargs.setdefault('native', self.for_machine) |
| 369 |
else: |
| 370 |
# dependent crates are not compiled separately for build and host; |
| 371 |
# do not use 'native: true' to allow linking to them without warnings |
| 372 |
kwargs.setdefault('native', MachineChoice.HOST) |
| 373 |
cfg = self.package.cfg[kwargs['native']] |
| 374 |
if not cfg: |
| 375 |
raise MesonException(f"package {self.package.manifest.package.name}-{self.package.manifest.package.version} not configured for {self.for_machine}") |
| 376 |
|
| 377 |
deps = kwargs['dependencies'] |
| 378 |
kwargs['dependencies'] = self._dependencies_method(state, { |
| 379 |
'dependencies': True, |
| 380 |
'dev_dependencies': False, |
| 381 |
'system_dependencies': True, |
| 382 |
}, kwargs['native']) |
| 383 |
kwargs['dependencies'].extend(deps) |
| 384 |
|
| 385 |
depmap = kwargs['rust_dependency_map'] |
| 386 |
kwargs['rust_dependency_map'] = cfg.get_dependency_map(self.package.manifest) |
| 387 |
kwargs['rust_dependency_map'].update(depmap) |
| 388 |
|
| 389 |
rust_args = kwargs['rust_args'] |
| 390 |
kwargs['rust_args'] = \ |
| 391 |
self.package.get_rustc_args(state.environment, state.subdir, kwargs['native']) |
| 392 |
kwargs['rust_args'].extend(rust_args) |
| 393 |
|
| 394 |
kwargs['override_options'].setdefault('rust_std', self.package.manifest.package.edition) |
| 395 |
|
| 396 |
def _library_method(self, state: ModuleState, args: T.Tuple[ |
| 397 |
T.Optional[T.Union[str, StructuredSources]], |
| 398 |
T.Optional[StructuredSources]], kwargs: RustPackageLibrary, |
| 399 |
static: bool, shared: bool, |
| 400 |
shared_mod: bool = False) -> T.Union[BothLibraries, SharedLibrary, StaticLibrary]: |
| 401 |
tgt_args = self.validate_pos_args('package.library', args) |
| 402 |
if not self.package.manifest.lib: |
| 403 |
raise MesonException("no [lib] section in Cargo package") |
| 404 |
|
| 405 |
self.merge_kw_args(state, kwargs) |
| 406 |
|
| 407 |
sources: T.Union[StructuredSources, str] |
| 408 |
tgt_name, sources = tgt_args |
| 409 |
if not tgt_name: |
| 410 |
rust_abi: RUST_ABI |
| 411 |
if kwargs['rust_crate_type'] is not None: |
| 412 |
rust_abi = 'rust' if kwargs['rust_crate_type'] in {'lib', 'rlib', 'dylib', 'proc-macro'} else 'c' |
| 413 |
else: |
| 414 |
rust_abi = kwargs['rust_abi'] |
| 415 |
tgt_name = self.package.library_name(kwargs['native'], rust_abi) |
| 416 |
if not sources: |
| 417 |
sources = os.path.relpath(os.path.join(self.package.path, self.package.manifest.lib.path), |
| 418 |
state.subdir) |
| 419 |
|
| 420 |
lib_args: T.Tuple[str, SourcesVarargsType] = (tgt_name, [sources]) |
| 421 |
if shared_mod: |
| 422 |
return state._interpreter.build_target(state.current_node, lib_args, |
| 423 |
T.cast('_kwargs.SharedModule', kwargs), |
| 424 |
SharedModule) |
| 425 |
|
| 426 |
if static and shared: |
| 427 |
return state._interpreter.build_both_libraries(state.current_node, lib_args, kwargs) |
| 428 |
elif shared: |
| 429 |
return state._interpreter.build_target(state.current_node, lib_args, |
| 430 |
T.cast('_kwargs.SharedLibrary', kwargs), |
| 431 |
SharedLibrary) |
| 432 |
else: |
| 433 |
return state._interpreter.build_target(state.current_node, lib_args, |
| 434 |
T.cast('_kwargs.StaticLibrary', kwargs), |
| 435 |
StaticLibrary) |
| 436 |
|
| 437 |
def _proc_macro_method(self, state: 'ModuleState', args: T.Tuple[ |
| 438 |
T.Optional[T.Union[str, StructuredSources]], |
| 439 |
T.Optional[StructuredSources]], kwargs: RustPackageLibrary) -> SharedLibrary: |
| 440 |
if state.environment.is_cross_build(): |
| 441 |
kwargs['native'] = MachineChoice.BUILD |
| 442 |
kwargs['rust_abi'] = None |
| 443 |
kwargs['rust_crate_type'] = 'proc-macro' |
| 444 |
kwargs['rust_args'] = kwargs['rust_args'] + ['--extern', 'proc_macro'] |
| 445 |
result = self._library_method(state, args, kwargs, shared=True, static=False) |
| 446 |
return T.cast('SharedLibrary', result) |
| 447 |
|
| 448 |
@typed_pos_args('package.override_dependency', Dependency) |
| 449 |
@typed_kwargs('package.override_dependency', |
| 450 |
KwargInfo('rust_abi', (str, NoneType), default=None, validator=in_set_validator({'rust', 'c', 'proc-macro'}))) |
| 451 |
def override_dependency_method(self, state: ModuleState, args: T.Tuple[Dependency], kwargs: FuncDependency) -> None: |
| 452 |
dep = args[0] |
| 453 |
rust_abi = self.package.abi_resolve_default(kwargs['rust_abi']) |
| 454 |
depname = self.package.get_dependency_name(rust_abi) |
| 455 |
assert rust_abi in self.package.supported_abis() |
| 456 |
|
| 457 |
if state.environment.is_cross_build() and self.package.manifest.lib.crate_type == ['proc-macro']: |
| 458 |
assert not self.package.has_both_machines() |
| 459 |
state.override_dependency(depname, dep, for_machine=MachineChoice.HOST) |
| 460 |
state.override_dependency(depname, dep, static=False, for_machine=MachineChoice.HOST) |
| 461 |
state.override_dependency(depname, dep, for_machine=MachineChoice.BUILD) |
| 462 |
state.override_dependency(depname, dep, static=False, for_machine=MachineChoice.BUILD) |
| 463 |
return |
| 464 |
|
| 465 |
state.override_dependency(depname, dep, for_machine=self.for_machine) |
| 466 |
if self.package.abi_has_static(rust_abi): |
| 467 |
state.override_dependency(depname, dep, static=True, for_machine=self.for_machine) |
| 468 |
if self.package.abi_has_shared(rust_abi): |
| 469 |
state.override_dependency(depname, dep, static=False, for_machine=self.for_machine) |
| 470 |
|
| 471 |
@typed_pos_args('package.library', optargs=[(str, StructuredSources), StructuredSources]) |
| 472 |
@typed_kwargs( |
| 473 |
'package.library', |
| 474 |
*LIBRARY_KWS_NO_NATIVE, |
| 475 |
DEPENDENCIES_KW, |
| 476 |
LINK_WITH_KW, |
| 477 |
LINK_WHOLE_KW, |
| 478 |
_BASE_LANG_KW.evolve(name='rust_args'), |
| 479 |
) |
| 480 |
def library_method(self, state: ModuleState, args: T.Tuple[ |
| 481 |
T.Optional[T.Union[str, StructuredSources]], |
| 482 |
T.Optional[StructuredSources]], kwargs: RustPackageLibrary) -> T.Union[BothLibraries, SharedLibrary, StaticLibrary]: |
| 483 |
if not self.package.manifest.lib: |
| 484 |
raise MesonException("no [lib] section in Cargo package") |
| 485 |
if kwargs['rust_crate_type'] is not None: |
| 486 |
static = kwargs['rust_crate_type'] in {'lib', 'rlib', 'staticlib'} |
| 487 |
shared = kwargs['rust_crate_type'] in {'dylib', 'cdylib', 'proc-macro'} |
| 488 |
else: |
| 489 |
rust_abi = self.package.abi_resolve_default(kwargs['rust_abi']) |
| 490 |
static = self.package.abi_has_static(rust_abi) |
| 491 |
shared = self.package.abi_has_shared(rust_abi) |
| 492 |
if rust_abi == 'proc-macro': |
| 493 |
kwargs['rust_crate_type'] = 'proc-macro' |
| 494 |
kwargs['rust_abi'] = None |
| 495 |
else: |
| 496 |
kwargs['rust_abi'] = rust_abi |
| 497 |
return self._library_method(state, args, kwargs, static=static, shared=shared) |
| 498 |
|
| 499 |
@typed_pos_args('package.proc_macro', optargs=[(str, StructuredSources), StructuredSources]) |
| 500 |
@typed_kwargs( |
| 501 |
'package.proc_macro', |
| 502 |
*SHARED_LIB_KWS_NO_NATIVE, |
| 503 |
DEPENDENCIES_KW, |
| 504 |
LINK_WITH_KW, |
| 505 |
LINK_WHOLE_KW, |
| 506 |
_BASE_LANG_KW.evolve(name='rust_args'), |
| 507 |
) |
| 508 |
def proc_macro_method(self, state: 'ModuleState', args: T.Tuple[ |
| 509 |
T.Optional[T.Union[str, StructuredSources]], |
| 510 |
T.Optional[StructuredSources]], kwargs: RustPackageLibrary) -> SharedLibrary: |
| 511 |
if not self.package.manifest.lib: |
| 512 |
raise MesonException("no [lib] section in Cargo package") |
| 513 |
if 'proc-macro' not in self.package.manifest.lib.crate_type: |
| 514 |
raise MesonException("not a procedural macro crate") |
| 515 |
return self._proc_macro_method(state, args, kwargs) |
| 516 |
|
| 517 |
@typed_pos_args('package.shared_module', optargs=[(str, StructuredSources), StructuredSources]) |
| 518 |
@typed_kwargs( |
| 519 |
'package.shared_module', |
| 520 |
*SHARED_MOD_KWS_NO_NATIVE, |
| 521 |
DEPENDENCIES_KW, |
| 522 |
LINK_WITH_KW, |
| 523 |
LINK_WHOLE_KW, |
| 524 |
_BASE_LANG_KW.evolve(name='rust_args'), |
| 525 |
) |
| 526 |
def shared_module_method(self, state: 'ModuleState', args: T.Tuple[ |
| 527 |
T.Optional[T.Union[str, StructuredSources]], |
| 528 |
T.Optional[StructuredSources]], kwargs: RustPackageLibrary) -> SharedModule: |
| 529 |
if not self.package.manifest.lib: |
| 530 |
raise MesonException("no [lib] section in Cargo package") |
| 531 |
if 'cdylib' not in self.package.manifest.lib.crate_type: |
| 532 |
raise MesonException("not a cdylib crate") |
| 533 |
|
| 534 |
kwargs['rust_abi'] = None |
| 535 |
kwargs['rust_crate_type'] = 'cdylib' |
| 536 |
result = self._library_method(state, args, kwargs, shared=True, static=False, shared_mod=True) |
| 537 |
return T.cast('SharedModule', result) |
| 538 |
|
| 539 |
@typed_pos_args('package.executable', optargs=[(str, StructuredSources), StructuredSources]) |
| 540 |
@typed_kwargs( |
| 541 |
'package.executable', |
| 542 |
*EXECUTABLE_KWS_NO_NATIVE, |
| 543 |
DEPENDENCIES_KW, |
| 544 |
LINK_WITH_KW, |
| 545 |
LINK_WHOLE_KW, |
| 546 |
_BASE_LANG_KW.evolve(name='rust_args'), |
| 547 |
) |
| 548 |
def executable_method(self, state: 'ModuleState', args: T.Tuple[ |
| 549 |
T.Optional[T.Union[str, StructuredSources]], |
| 550 |
T.Optional[StructuredSources]], kwargs: RustPackageExecutable) -> Executable: |
| 551 |
"""Builds executable targets from workspace bins.""" |
| 552 |
tgt_args = self.validate_pos_args('package.executable', args) |
| 553 |
if not self.package.manifest.bin: |
| 554 |
raise MesonException("no [[bin]] section in Cargo package") |
| 555 |
|
| 556 |
sources: T.Union[StructuredSources, str] |
| 557 |
tgt_name, sources = tgt_args |
| 558 |
# If there's more than one binary, the first argument must be specified |
| 559 |
# and must be one of the keys in pkg.bin |
| 560 |
if not tgt_name: |
| 561 |
if len(self.package.manifest.bin) > 1: |
| 562 |
raise MesonException("Package has multiple binaries, you must specify which one to build as the first argument") |
| 563 |
# Single binary, use it |
| 564 |
tgt_name = next(iter(self.package.manifest.bin.keys())) |
| 565 |
else: |
| 566 |
if tgt_name not in self.package.manifest.bin: |
| 567 |
raise MesonException(f"Binary '{tgt_name}' not found.") |
| 568 |
|
| 569 |
if not sources: |
| 570 |
sources = os.path.relpath(os.path.join(self.package.path, self.package.manifest.bin[tgt_name].path), |
| 571 |
state.subdir) |
| 572 |
|
| 573 |
exe_args: T.Tuple[str, SourcesVarargsType] = (tgt_name, [sources]) |
| 574 |
self.merge_kw_args(state, kwargs) |
| 575 |
return state._interpreter.build_target(state.current_node, exe_args, kwargs, Executable) |
| 576 |
|
| 577 |
|
| 578 |
class RustSubproject(RustCrate): |
| 579 |
"""Represents a Cargo subproject.""" |
| 580 |
|
| 581 |
def __init__(self, state: ModuleState, rust_ws: RustWorkspace, package: cargo.PackageState, for_machine: MachineChoice) -> None: |
| 582 |
super().__init__(state, rust_ws, package, for_machine) |
| 583 |
self.methods.update({ |
| 584 |
'dependency': self.dependency_method, |
| 585 |
}) |
| 586 |
|
| 587 |
@noPosargs |
| 588 |
@typed_kwargs('package.dependency', |
| 589 |
KwargInfo('rust_abi', (str, NoneType), default=None, validator=in_set_validator({'rust', 'c', 'proc-macro'}))) |
| 590 |
def dependency_method(self, state: ModuleState, args: T.List, kwargs: FuncDependency) -> Dependency: |
| 591 |
"""Returns dependency for the package with the given ABI.""" |
| 592 |
depname = self.package.get_dependency_name(kwargs['rust_abi']) |
| 593 |
return state.overridden_dependency(depname, for_machine=self.for_machine) |
| 594 |
|
| 595 |
|
| 596 |
def _cbindgen_config_validator(val: str) -> T.Optional[str]: |
| 597 |
if os.path.splitext(val)[1] != '.toml': |
| 598 |
return 'config file must be a .toml file' |
| 599 |
return None |
| 600 |
|
| 601 |
|
| 602 |
class RustModule(ExtensionModule): |
| 603 |
|
| 604 |
"""A module that holds helper functions for rust.""" |
| 605 |
|
| 606 |
INFO = ModuleInfo('rust', '0.57.0', stabilized='1.0.0') |
| 607 |
_bindgen_rust_target: T.Optional[str] |
| 608 |
rustdoc: PerMachine[T.Optional[ExternalProgram]] = PerMachine(None, None) |
| 609 |
|
| 610 |
def __init__(self, interpreter: Interpreter) -> None: |
| 611 |
super().__init__(interpreter) |
| 612 |
self._bindgen_bin: T.Optional[Program] = None |
| 613 |
if 'rust' in interpreter.compilers.host: |
| 614 |
rustc = T.cast('RustCompiler', interpreter.compilers.host['rust']) |
| 615 |
self._bindgen_rust_target = 'nightly' if rustc.is_nightly else rustc.version |
| 616 |
else: |
| 617 |
self._bindgen_rust_target = None |
| 618 |
self._bindgen_set_std = False |
| 619 |
|
| 620 |
self._cbindgen_bin: Program | None = None |
| 621 |
self._cbindgen_has_depfile = False |
| 622 |
|
| 623 |
self.methods.update({ |
| 624 |
'test': self.test, |
| 625 |
'doctest': self.doctest, |
| 626 |
'bindgen': self.bindgen, |
| 627 |
'compiler_target': self.compiler_target, |
| 628 |
'proc_macro': self.proc_macro, |
| 629 |
'to_system_dependency': self.to_system_dependency, |
| 630 |
'workspace': self.workspace, |
| 631 |
'cbindgen': self.cbindgen, |
| 632 |
}) |
| 633 |
|
| 634 |
def test_common(self, funcname: str, state: ModuleState, args: T.Tuple[str, BuildTarget], kwargs: FuncRustTest) -> T.Tuple[Executable, _kwargs.FuncTest]: |
| 635 |
"""Generate a rust test target from a given rust target. |
| 636 |
|
| 637 |
Rust puts its unitests inside its main source files, unlike most |
| 638 |
languages that put them in external files. This means that normally |
| 639 |
you have to define two separate targets with basically the same |
| 640 |
arguments to get tests: |
| 641 |
|
| 642 |
```meson |
| 643 |
rust_lib_sources = [...] |
| 644 |
rust_lib = static_library( |
| 645 |
'rust_lib', |
| 646 |
rust_lib_sources, |
| 647 |
) |
| 648 |
|
| 649 |
rust_lib_test = executable( |
| 650 |
'rust_lib_test', |
| 651 |
rust_lib_sources, |
| 652 |
rust_args : ['--test'], |
| 653 |
) |
| 654 |
|
| 655 |
test( |
| 656 |
'rust_lib_test', |
| 657 |
rust_lib_test, |
| 658 |
protocol : 'rust', |
| 659 |
) |
| 660 |
``` |
| 661 |
|
| 662 |
This is all fine, but not very DRY. This method makes it much easier |
| 663 |
to define rust tests: |
| 664 |
|
| 665 |
```meson |
| 666 |
rust = import('unstable-rust') |
| 667 |
|
| 668 |
rust_lib = static_library( |
| 669 |
'rust_lib', |
| 670 |
[sources], |
| 671 |
) |
| 672 |
|
| 673 |
rust.test('rust_lib_test', rust_lib) |
| 674 |
``` |
| 675 |
""" |
| 676 |
if any(isinstance(t, Jar) for t in kwargs.get('link_with', [])): |
| 677 |
raise InvalidArguments('Rust tests cannot link with Jar targets') |
| 678 |
if any(isinstance(t, Jar) for t in kwargs.get('link_whole', [])): |
| 679 |
raise InvalidArguments('Rust tests cannot link with Jar targets') |
| 680 |
|
| 681 |
name = args[0] |
| 682 |
base_target: BuildTarget = args[1] |
| 683 |
if not base_target.uses_rust(): |
| 684 |
raise InterpreterException(f'Second positional argument to rustmod.{funcname}() must be a rust based target') |
| 685 |
extra_args = kwargs['args'] |
| 686 |
|
| 687 |
# Delete any arguments we don't want passed |
| 688 |
if '--test' in extra_args: |
| 689 |
mlog.warning(f'Do not add --test to rustmod.{funcname}() arguments') |
| 690 |
extra_args.remove('--test') |
| 691 |
if '--format' in extra_args: |
| 692 |
mlog.warning(f'Do not add --format to rustmod.{funcname}() arguments') |
| 693 |
i = extra_args.index('--format') |
| 694 |
# Also delete the argument to --format |
| 695 |
del extra_args[i + 1] |
| 696 |
del extra_args[i] |
| 697 |
for i, a in enumerate(extra_args): |
| 698 |
if isinstance(a, str) and a.startswith('--format='): |
| 699 |
del extra_args[i] |
| 700 |
break |
| 701 |
|
| 702 |
# We need to cast here, as currently these don't have protocol in them, but test itself does. |
| 703 |
tkwargs = T.cast('_kwargs.FuncTest', kwargs.copy()) |
| 704 |
|
| 705 |
tkwargs['args'] = extra_args + ['--test', '--format', 'pretty'] |
| 706 |
tkwargs['protocol'] = 'rust' |
| 707 |
|
| 708 |
new_target_kwargs = T.cast('ExecutableKeywordArguments', base_target.original_kwargs.copy()) |
| 709 |
del new_target_kwargs['rust_crate_type'] |
| 710 |
for kw in ('pic', 'prelink', 'rust_abi', 'version', 'soversion', 'darwin_versions', 'shortname'): |
| 711 |
if kw in new_target_kwargs: |
| 712 |
del new_target_kwargs[kw] # type: ignore[misc] |
| 713 |
|
| 714 |
new_target_kwargs['install'] = False |
| 715 |
new_target_kwargs['dependencies'] = new_target_kwargs.get('dependencies', []) + kwargs['dependencies'] |
| 716 |
new_target_kwargs['link_with'] = new_target_kwargs.get('link_with', []) + kwargs['link_with'] |
| 717 |
new_target_kwargs['link_whole'] = new_target_kwargs.get('link_whole', []) + kwargs['link_whole'] |
| 718 |
|
| 719 |
lang_args = base_target.extra_args.copy() |
| 720 |
lang_args['rust'] = base_target.extra_args['rust'] + kwargs['rust_args'] + ['--test'] |
| 721 |
new_target_kwargs['language_args'] = lang_args |
| 722 |
|
| 723 |
sources = T.cast('T.List[SourceOutputs]', base_target.sources.copy()) |
| 724 |
sources.extend(base_target.generated) |
| 725 |
|
| 726 |
new_target = Executable( |
| 727 |
name, base_target.subdir, base_target.for_machine, |
| 728 |
sources, base_target.structured_sources, |
| 729 |
base_target.objects, base_target.environment, base_target.compilers, |
| 730 |
state.current_build_project, new_target_kwargs |
| 731 |
) |
| 732 |
return new_target, tkwargs |
| 733 |
|
| 734 |
@typed_pos_args('rust.test', str, BuildTarget) |
| 735 |
@typed_kwargs( |
| 736 |
'rust.test', |
| 737 |
*TEST_KWS, |
| 738 |
DEPENDENCIES_KW, |
| 739 |
LINK_WITH_KW.evolve(since='1.2.0'), |
| 740 |
LINK_WHOLE_KW.evolve(since='1.8.0'), |
| 741 |
*RUST_TEST_KWS, |
| 742 |
) |
| 743 |
def test(self, state: ModuleState, args: T.Tuple[str, BuildTarget], kwargs: FuncTest) -> ModuleReturnValue: |
| 744 |
name, _ = args |
| 745 |
new_target, tkwargs = self.test_common('test', state, args, kwargs) |
| 746 |
test: Test = self.interpreter.make_test( |
| 747 |
self.interpreter.current_node, (name, new_target), tkwargs) |
| 748 |
|
| 749 |
return ModuleReturnValue(None, [new_target, test]) |
| 750 |
|
| 751 |
@FeatureNew('rust.doctest', '1.8.0') |
| 752 |
@typed_pos_args('rust.doctest', str, BuildTarget) |
| 753 |
@typed_kwargs( |
| 754 |
'rust.doctest', |
| 755 |
*TEST_KWS_NO_ARGS, |
| 756 |
DEPENDENCIES_KW, |
| 757 |
LINK_WITH_KW, |
| 758 |
LINK_WHOLE_KW, |
| 759 |
*RUST_TEST_KWS, |
| 760 |
KwargInfo( |
| 761 |
'args', |
| 762 |
ContainerTypeInfo(list, str), |
| 763 |
listify=True, |
| 764 |
default=[], |
| 765 |
validator=no_spaces_validator, |
| 766 |
), |
| 767 |
) |
| 768 |
def doctest(self, state: ModuleState, args: T.Tuple[str, T.Union[SharedLibrary, StaticLibrary]], kwargs: FuncDoctest) -> ModuleReturnValue: |
| 769 |
name, base_target = args |
| 770 |
|
| 771 |
if not base_target.uses_rust(): |
| 772 |
raise MesonException('doc tests are only supported for Rust targets') |
| 773 |
if not base_target.uses_rust_abi(): |
| 774 |
raise MesonException("doc tests are not supported for rust_abi: 'c'") |
| 775 |
if state.environment.is_cross_build() and state.environment.need_exe_wrapper(base_target.for_machine): |
| 776 |
mlog.notice('skipping Rust doctests due to cross compilation', once=True) |
| 777 |
return ModuleReturnValue(None, []) |
| 778 |
|
| 779 |
# Link the base target's crate into the tests |
| 780 |
kwargs['link_with'].append(base_target) |
| 781 |
kwargs['depends'].append(base_target) |
| 782 |
workdir = kwargs['workdir'] |
| 783 |
kwargs['workdir'] = None |
| 784 |
new_target, tkwargs = self.test_common('doctest', state, args, kwargs) |
| 785 |
|
| 786 |
# added automatically by rustdoc; keep things simple |
| 787 |
tkwargs['args'].remove('--test') |
| 788 |
|
| 789 |
# --test-args= is "parsed" simply via the Rust function split_whitespace(). |
| 790 |
# This means no quoting nightmares (pfew) but it also means no spaces. |
| 791 |
# Unfortunately it's pretty hard at this point to accept e.g. CustomTarget, |
| 792 |
# because their paths may not be known. This is not a big deal because the |
| 793 |
# user does not control the test harness, so make things easy and allow |
| 794 |
# strings only. |
| 795 |
if tkwargs['args']: |
| 796 |
tkwargs['args'] = ['--test-args=' + ' '.join(T.cast('T.Sequence[str]', tkwargs['args']))] |
| 797 |
if workdir: |
| 798 |
tkwargs['args'].append('--test-run-directory=' + workdir) |
| 799 |
|
| 800 |
if self.rustdoc[base_target.for_machine] is None: |
| 801 |
rustc = T.cast('RustCompiler', base_target.compilers['rust']) |
| 802 |
rustdoc = rustc.get_rustdoc() |
| 803 |
if rustdoc: |
| 804 |
self.rustdoc[base_target.for_machine] = ExternalProgram(rustdoc.get_exe()) |
| 805 |
else: |
| 806 |
self.rustdoc[base_target.for_machine] = NonExistingExternalProgram() |
| 807 |
|
| 808 |
rustdoc_prog = self.rustdoc[base_target.for_machine] |
| 809 |
if not rustdoc_prog.found(): |
| 810 |
raise MesonException(f'could not find rustdoc for {base_target.for_machine} machine') |
| 811 |
|
| 812 |
doctests: Doctest = self.interpreter.make_test( |
| 813 |
self.interpreter.current_node, (name, rustdoc_prog), tkwargs, Doctest) |
| 814 |
|
| 815 |
# Note that the new_target is intentionally not returned, as it |
| 816 |
# is only reached via the base_target and never built by "ninja", |
| 817 |
# so we need to complete its initialization here |
| 818 |
new_target.process_compilers_late() |
| 819 |
doctests.target = new_target |
| 820 |
base_target.doctests = doctests |
| 821 |
return ModuleReturnValue(None, [doctests]) |
| 822 |
|
| 823 |
@noPosargs |
| 824 |
@typed_kwargs( |
| 825 |
'rust.bindgen', |
| 826 |
KwargInfo('c_args', ContainerTypeInfo(list, str), default=[], listify=True), |
| 827 |
KwargInfo('args', ContainerTypeInfo(list, str), default=[], listify=True), |
| 828 |
KwargInfo( |
| 829 |
'input', |
| 830 |
ContainerTypeInfo(list, (File, GeneratedList, BuildTarget, BothLibraries, ExtractedObjects, CustomTargetIndex, CustomTarget, str), allow_empty=False), |
| 831 |
default=[], |
| 832 |
listify=True, |
| 833 |
required=True, |
| 834 |
), |
| 835 |
KwargInfo('language', (str, NoneType), since='1.4.0', validator=in_set_validator({'c', 'cpp'})), |
| 836 |
KwargInfo('bindgen_version', ContainerTypeInfo(list, str), default=[], listify=True, since='1.4.0'), |
| 837 |
INCLUDE_DIRECTORIES.evolve(since_values={ContainerTypeInfo(list, str): '1.0.0'}), |
| 838 |
OUTPUT_KW, |
| 839 |
KwargInfo( |
| 840 |
'output_inline_wrapper', |
| 841 |
str, |
| 842 |
default='', |
| 843 |
since='1.4.0', |
| 844 |
), |
| 845 |
DEPENDENCIES_KW.evolve(since='1.0.0'), |
| 846 |
) |
| 847 |
def bindgen(self, state: ModuleState, args: T.List, kwargs: FuncBindgen) -> ModuleReturnValue: |
| 848 |
"""Wrapper around bindgen to simplify its use. |
| 849 |
|
| 850 |
The main thing this simplifies is the use of `include_directory` |
| 851 |
objects, instead of having to pass a plethora of `-I` arguments. |
| 852 |
""" |
| 853 |
_header, *_deps = kwargs['input'] |
| 854 |
|
| 855 |
if isinstance(_header, (BuildTarget, BothLibraries, ExtractedObjects)): |
| 856 |
raise InterpreterException('bindgen source file must be a C header, not an object or build target') |
| 857 |
header = self.interpreter.source_strings_to_files([_header])[0] |
| 858 |
|
| 859 |
# Split File and Target dependencies to add pass to CustomTarget |
| 860 |
depends: T.List[TargetDepends] = [] |
| 861 |
depend_files: T.List[File] = [] |
| 862 |
for d in self.interpreter.source_strings_to_files(_deps): |
| 863 |
if isinstance(d, File): |
| 864 |
depend_files.append(d) |
| 865 |
elif isinstance(d, BothLibraries): |
| 866 |
depends.append(d.shared) |
| 867 |
depends.append(d.static) |
| 868 |
elif isinstance(d, ExtractedObjects): |
| 869 |
depends.append(d.target) |
| 870 |
else: |
| 871 |
depends.append(d) |
| 872 |
|
| 873 |
# Copy to avoid subsequent calls mutating the original |
| 874 |
# TODO: if we want this to be per-machine we'll need a native kwarg |
| 875 |
clang_args = state.environment.properties.host.get_bindgen_clang_args().copy() |
| 876 |
|
| 877 |
# Look for --target in the rust command itself if there isn't one passed in clang_args |
| 878 |
target_arg = parse_target(clang_args) |
| 879 |
if not target_arg and 'rust' in state._interpreter.compilers.host: |
| 880 |
rust_args = state._interpreter.compilers.host['rust'].get_exe_args() |
| 881 |
target_arg = parse_target(rust_args) |
| 882 |
if target_arg: |
| 883 |
clang_args.append(f'--target={target_arg}') |
| 884 |
|
| 885 |
# Find the first C'ish compiler to fetch the default compiler flags |
| 886 |
# from. Append those to the bindgen flags to ensure we use a compatible |
| 887 |
# environment. |
| 888 |
comp = mesonlib.first( |
| 889 |
# The cast here shouldn't be necessary |
| 890 |
[state.environment.coredata.compilers.host.get(T.cast('Language', l)) |
| 891 |
for l in ('c', 'cpp', 'objc', 'objcpp')], |
| 892 |
lambda x: x is not None, |
| 893 |
) |
| 894 |
if comp: |
| 895 |
clang_args.extend(comp.get_always_args()) |
| 896 |
else: |
| 897 |
mlog.warning(textwrap.dedent('''\ |
| 898 |
Using `rust.bindgen` without configuring C (or a C-like) |
| 899 |
language in Meson will skip compiler detection and can cause |
| 900 |
ABI incompatibilities due to missing crucial compiler flags. |
| 901 |
Consider calling `add_languages('c')` in your Meson build |
| 902 |
files. |
| 903 |
''')) |
| 904 |
|
| 905 |
for i in state.process_include_dirs(kwargs['include_directories']): |
| 906 |
# bindgen always uses clang, so it's safe to hardcode -I here |
| 907 |
clang_args.extend([f'-I{x}' for x in i.abs_string_list( |
| 908 |
state.environment.get_source_dir(), state.environment.get_build_dir())]) |
| 909 |
if are_asserts_disabled_for_subproject(state.subproject, state.environment): |
| 910 |
clang_args.append('-DNDEBUG') |
| 911 |
|
| 912 |
for de in kwargs['dependencies']: |
| 913 |
for i in de.get_include_dirs(): |
| 914 |
clang_args.extend([f'-I{x}' for x in i.abs_string_list( |
| 915 |
state.environment.get_source_dir(), state.environment.get_build_dir())]) |
| 916 |
clang_args.extend(de.get_all_compile_args()) |
| 917 |
for s in de.get_sources(): |
| 918 |
if isinstance(s, File): |
| 919 |
depend_files.append(s) |
| 920 |
elif isinstance(s, CustomTarget): |
| 921 |
depends.append(s) |
| 922 |
|
| 923 |
if self._bindgen_bin is None: |
| 924 |
self._bindgen_bin = state.find_program('bindgen', wanted=kwargs['bindgen_version']) |
| 925 |
if self._bindgen_rust_target is not None: |
| 926 |
_, _, err = mesonlib.Popen_safe(self._bindgen_bin.get_command() + ['--rust-target', self._bindgen_rust_target]) |
| 927 |
# < 0.71: Sometimes this is "invalid Rust target" and |
| 928 |
# sometimes "invalid # rust target" |
| 929 |
# >= 0.71: error: invalid value '...' for '--rust-target <RUST_TARGET>': "..." is not a valid Rust target, accepted values are of the form ... |
| 930 |
# It's also much harder to hit this in 0.71 than in previous versions |
| 931 |
if 'Got an invalid' in err or 'is not a valid Rust target' in err: |
| 932 |
self._bindgen_rust_target = None |
| 933 |
|
| 934 |
self._bindgen_set_std = mesonlib.version_compare(self._bindgen_bin.get_version(), '>= 0.71') |
| 935 |
|
| 936 |
name: str |
| 937 |
if isinstance(header, File): |
| 938 |
name = header.fname |
| 939 |
else: |
| 940 |
name = header.get_outputs()[0] |
| 941 |
|
| 942 |
# bindgen assumes that C++ headers will be called .hpp. We want to |
| 943 |
# ensure that anything Meson considers a C++ header is treated as one. |
| 944 |
language = kwargs['language'] |
| 945 |
if language is None: |
| 946 |
ext = os.path.splitext(name)[1][1:] |
| 947 |
if ext in lang_suffixes['cpp']: |
| 948 |
language = 'cpp' |
| 949 |
elif ext == 'h': |
| 950 |
language = 'c' |
| 951 |
else: |
| 952 |
raise InterpreterException(f'Unknown file type extension for: {name}') |
| 953 |
|
| 954 |
# Mypy can't figure out that if Literal a is a subset of Literal B it's valid |
| 955 |
language = T.cast('Language', language) |
| 956 |
|
| 957 |
# We only want include directories and defines, other things may not be valid |
| 958 |
cargs = state.get_option(f'{language}_args', state.subproject) |
| 959 |
assert isinstance(cargs, list), 'for mypy' |
| 960 |
for a in itertools.chain(state.global_args.get(language, []), state.project_args.get(language, []), cargs): |
| 961 |
if a.startswith(('-I', '/I', '-D', '/D', '-U', '/U')): |
| 962 |
clang_args.append(a) |
| 963 |
|
| 964 |
if language == 'cpp': |
| 965 |
clang_args.extend(['-x', 'c++']) |
| 966 |
|
| 967 |
# Add the C++ standard to the clang arguments. Attempt to translate VS |
| 968 |
# extension versions into the nearest standard version |
| 969 |
std = state.get_option(f'{language}_std') |
| 970 |
assert isinstance(std, str), 'for mypy' |
| 971 |
if std.startswith('vc++'): |
| 972 |
if std.endswith('latest'): |
| 973 |
mlog.warning('Attempting to translate vc++latest into a clang compatible version.', |
| 974 |
'Currently this is hardcoded for c++20', once=True, fatal=False) |
| 975 |
std = 'c++20' |
| 976 |
else: |
| 977 |
mlog.debug('The current C++ standard is a Visual Studio extension version.', |
| 978 |
'bindgen will use a the nearest C++ standard instead') |
| 979 |
std = std[1:] |
| 980 |
|
| 981 |
if std != 'none': |
| 982 |
clang_args.append(f'-std={std}') |
| 983 |
|
| 984 |
inline_wrapper_args: T.List[str] = [] |
| 985 |
outputs = [kwargs['output']] |
| 986 |
if kwargs['output_inline_wrapper']: |
| 987 |
# Todo drop this isinstance once Executable supports version_compare |
| 988 |
if isinstance(self._bindgen_bin, ExternalProgram): |
| 989 |
if mesonlib.version_compare(self._bindgen_bin.get_version(), '< 0.65'): |
| 990 |
raise InterpreterException('\'output_inline_wrapper\' parameter of rust.bindgen requires bindgen-0.65 or newer') |
| 991 |
|
| 992 |
outputs.append(kwargs['output_inline_wrapper']) |
| 993 |
inline_wrapper_args = [ |
| 994 |
'--experimental', '--wrap-static-fns', |
| 995 |
'--wrap-static-fns-path', os.path.join(state.environment.build_dir, '@OUTPUT1@') |
| 996 |
] |
| 997 |
|
| 998 |
cmd = self._bindgen_bin.get_command() + \ |
| 999 |
[ |
| 1000 |
'@INPUT@', '--output', |
| 1001 |
os.path.join(state.environment.build_dir, '@OUTPUT0@') |
| 1002 |
] + \ |
| 1003 |
kwargs['args'] + inline_wrapper_args |
| 1004 |
if self._bindgen_rust_target and '--rust-target' not in cmd: |
| 1005 |
cmd.extend(['--rust-target', self._bindgen_rust_target]) |
| 1006 |
if self._bindgen_set_std and '--rust-edition' not in cmd: |
| 1007 |
try: |
| 1008 |
rust_std = state.environment.coredata.optstore.get_value_for('rust_std') |
| 1009 |
except KeyError: |
| 1010 |
rust_std = 'none' |
| 1011 |
assert isinstance(rust_std, str), 'for mypy' |
| 1012 |
if rust_std != 'none': |
| 1013 |
cmd.extend(['--rust-edition', rust_std]) |
| 1014 |
cmd.append('--') |
| 1015 |
cmd.extend(kwargs['c_args']) |
| 1016 |
cmd.extend(clang_args) |
| 1017 |
cmd.extend(['-MD', '-MQ', '@INPUT@', '-MF', '@DEPFILE@']) |
| 1018 |
|
| 1019 |
target = CustomTarget( |
| 1020 |
f'rustmod-bindgen-{name}'.replace('/', '_'), |
| 1021 |
state.subdir, |
| 1022 |
state.environment, |
| 1023 |
cmd, |
| 1024 |
[header], |
| 1025 |
outputs, |
| 1026 |
state.current_build_project, |
| 1027 |
depfile='@[email protected]', |
| 1028 |
extra_depends=depends, |
| 1029 |
depend_files=depend_files, |
| 1030 |
backend=state.backend, |
| 1031 |
description='Generating bindings for Rust {}', |
| 1032 |
) |
| 1033 |
|
| 1034 |
return ModuleReturnValue(target, [target]) |
| 1035 |
|
| 1036 |
@FeatureNew('rust.compiler_target', '1.11.0') |
| 1037 |
@noPosargs |
| 1038 |
@typed_kwargs('rust.compiler_target', NATIVE_KW) |
| 1039 |
@apply_machine_map |
| 1040 |
def compiler_target(self, state: ModuleState, args: T.List, kwargs: '_kwargs.NativeKW') -> str: |
| 1041 |
"""Returns the Rust target triple for the specified machine's Rust compiler.""" |
| 1042 |
for_machine = kwargs['native'] |
| 1043 |
compilers = state._interpreter.coredata.compilers[for_machine] |
| 1044 |
if 'rust' in compilers: |
| 1045 |
rustc = T.cast('RustCompiler', compilers['rust']) |
| 1046 |
return rustc.get_target_triple() |
| 1047 |
else: |
| 1048 |
raise MesonException(f'No Rust compiler was requested for the {for_machine} machine') |
| 1049 |
|
| 1050 |
@FeatureNew('rust.proc_macro', '1.3.0') |
| 1051 |
@typed_pos_args('rust.proc_macro', str, varargs=SOURCES_VARARGS) |
| 1052 |
@typed_kwargs('rust.proc_macro', *_PROC_MACRO_KWS) |
| 1053 |
def proc_macro(self, state: ModuleState, args: T.Tuple[str, SourcesVarargsType], kwargs: _kwargs.SharedLibrary) -> SharedLibrary: |
| 1054 |
# Silently force to native; rust.proc_macro() has always done |
| 1055 |
# that even when not cross compiling. |
| 1056 |
kwargs['native'] = MachineChoice.BUILD |
| 1057 |
kwargs['rust_crate_type'] = 'proc-macro' |
| 1058 |
kwargs['rust_args'] = kwargs['rust_args'] + ['--extern', 'proc_macro'] |
| 1059 |
|
| 1060 |
# Set any kwargs to default that haven't already been set |
| 1061 |
for s in SHARED_LIB_KWS: |
| 1062 |
if s.name in kwargs: |
| 1063 |
continue |
| 1064 |
kwargs[s.name] = s.default # type: ignore[literal-required] |
| 1065 |
|
| 1066 |
target = state._interpreter.build_target(state.current_node, args, kwargs, SharedLibrary) |
| 1067 |
return target |
| 1068 |
|
| 1069 |
@FeatureNew('rust.to_system_dependency', '1.11.0') |
| 1070 |
@typed_pos_args('rust.to_system_dependency', Dependency, optargs=[str]) |
| 1071 |
@noKwargs |
| 1072 |
def to_system_dependency(self, state: ModuleState, args: T.Tuple[Dependency, T.Optional[str]], kwargs: TYPE_kwargs) -> Dependency: |
| 1073 |
dep, depname = args |
| 1074 |
return dep_to_system_dependency(dep, depname) |
| 1075 |
|
| 1076 |
@FeatureNew('rust.workspace', '1.11.0') |
| 1077 |
@noPosargs |
| 1078 |
@typed_kwargs( |
| 1079 |
'rust.workspace', |
| 1080 |
KwargInfo('default_features', (bool, NoneType), default=None), |
| 1081 |
KwargInfo( |
| 1082 |
'features', |
| 1083 |
(ContainerTypeInfo(list, str), NoneType), |
| 1084 |
default=None, |
| 1085 |
listify=True, |
| 1086 |
), |
| 1087 |
KwargInfo( |
| 1088 |
'extra_members', |
| 1089 |
(ContainerTypeInfo(list, str), NoneType), |
| 1090 |
default=None, |
| 1091 |
listify=True, |
| 1092 |
), |
| 1093 |
) |
| 1094 |
def workspace(self, state: ModuleState, args: T.List, kwargs: FuncWorkspace) -> RustWorkspace: |
| 1095 |
"""Creates a Rust workspace object, controlling the build of |
| 1096 |
all the packages in a Cargo.lock file.""" |
| 1097 |
if self.interpreter.cargo is None: |
| 1098 |
raise MesonException("rust.workspace() requires a Cargo project (Cargo.toml and Cargo.lock)") |
| 1099 |
|
| 1100 |
self.interpreter.add_languages(['rust'], True, MachineChoice.HOST) |
| 1101 |
self.interpreter.add_languages(['rust'], True, MachineChoice.BUILD) |
| 1102 |
|
| 1103 |
default_features = kwargs['default_features'] |
| 1104 |
features = kwargs['features'] |
| 1105 |
if default_features is not None or features is not None: |
| 1106 |
# If custom features are provided, default_features = None should be treated as True |
| 1107 |
if default_features is None: |
| 1108 |
default_features = True |
| 1109 |
|
| 1110 |
cargo_features = ['default'] if default_features else [] |
| 1111 |
if features is not None: |
| 1112 |
cargo_features.extend(features) |
| 1113 |
self.interpreter.cargo.features = cargo_features |
| 1114 |
|
| 1115 |
ws = self.interpreter.cargo.load_workspace(state.root_subdir, kwargs['extra_members']) |
| 1116 |
|
| 1117 |
# Cargo projects may not have a subprojects directory, because |
| 1118 |
# dependencies are declared in Cargo.toml rather than .wrap files. |
| 1119 |
# Create it now so that the wrap resolver can download the crates there |
| 1120 |
os.makedirs(self.interpreter.environment.wrap_resolver.subdir_root, exist_ok=True) |
| 1121 |
|
| 1122 |
return RustWorkspace(self.interpreter, ws) |
| 1123 |
|
| 1124 |
@FeatureNew('rust.cbindgen', '1.12.0') |
| 1125 |
@typed_pos_args('rust.cbindgen', (str, File, CustomTargetIndex, CustomTarget, StructuredSources), str) |
| 1126 |
@typed_kwargs( |
| 1127 |
'rust.cbindgen', |
| 1128 |
KwargInfo('config', (str, File, CustomTarget, CustomTargetIndex), required=True, validator=_cbindgen_config_validator), |
| 1129 |
KwargInfo( |
| 1130 |
'language', |
| 1131 |
(str, NoneType), |
| 1132 |
validator=in_set_validator({'c', 'cpp', 'cython'}), |
| 1133 |
), |
| 1134 |
KwargInfo( |
| 1135 |
'depends', |
| 1136 |
ContainerTypeInfo(list, (CustomTarget, CustomTargetIndex)), |
| 1137 |
default=[], |
| 1138 |
listify=True, |
| 1139 |
), |
| 1140 |
DEPEND_FILES_KW, |
| 1141 |
INSTALL_KW, |
| 1142 |
INSTALL_DIR_KW, |
| 1143 |
) |
| 1144 |
def cbindgen(self, state: ModuleState, |
| 1145 |
args: tuple[FileOrString | CustomTarget | CustomTargetIndex | StructuredSources, str], |
| 1146 |
kwargs: FuncCBindgen) -> ModuleReturnValue: |
| 1147 |
# TODO: should we allow GeneratedList here? |
| 1148 |
|
| 1149 |
if kwargs['install'] and not kwargs['install_dir']: |
| 1150 |
raise InterpreterException.from_node('cbindgen: When `install` is true `install_dir` must be set', |
| 1151 |
node=state.current_node) |
| 1152 |
|
| 1153 |
if self._cbindgen_bin is None: |
| 1154 |
self._cbindgen_bin = state.find_program('cbindgen') |
| 1155 |
self._cbindgen_has_depfile = mesonlib.version_compare( |
| 1156 |
self._cbindgen_bin.get_version(self.interpreter), '>= 0.25') |
| 1157 |
|
| 1158 |
_infile, outfile = args |
| 1159 |
infile = self.interpreter.source_strings_to_files([_infile])[0] |
| 1160 |
depend_files = self.interpreter.source_strings_to_files(kwargs['depend_files']) |
| 1161 |
depends = kwargs['depends'].copy() |
| 1162 |
|
| 1163 |
if isinstance(infile, StructuredSources): |
| 1164 |
infile, *_depends = infile.as_list() |
| 1165 |
if isinstance(infile, GeneratedList): |
| 1166 |
raise MesonException.from_node( |
| 1167 |
'Using a GeneratedList as the main input for cbindgen is unsupported', |
| 1168 |
node=state.current_node) |
| 1169 |
for d in _depends: |
| 1170 |
if isinstance(d, File): |
| 1171 |
depend_files.append(d) |
| 1172 |
else: |
| 1173 |
depends.append(d) |
| 1174 |
|
| 1175 |
if isinstance(infile, File): |
| 1176 |
name = infile.fname |
| 1177 |
else: |
| 1178 |
if len(infile.get_outputs()) != 1: |
| 1179 |
raise mesonlib.MesonException.from_node( |
| 1180 |
'Cannot pass a custom_target generating more than one output to rust.cbindgen, use custom_target[index] to select the output to generate bindings for', |
| 1181 |
node=state.current_node) |
| 1182 |
name = infile.get_outputs()[0] |
| 1183 |
|
| 1184 |
if os.path.dirname(outfile): |
| 1185 |
raise InvalidArguments.from_node( |
| 1186 |
'outfile name must not contain a path segment', node=state.current_node) |
| 1187 |
|
| 1188 |
# Detect langauge from output file extension |
| 1189 |
language = kwargs['language'] |
| 1190 |
if language is None: |
| 1191 |
ext = os.path.splitext(outfile)[1][1:] |
| 1192 |
if ext in lang_suffixes['cpp']: |
| 1193 |
language = 'cpp' |
| 1194 |
elif ext == 'h': |
| 1195 |
language = 'c' |
| 1196 |
else: |
| 1197 |
raise InterpreterException.from_node( |
| 1198 |
f'Unknown file type extension for: {outfile}', node=state.current_node) |
| 1199 |
|
| 1200 |
# Convert Meson's `cpp` to cbindgen's `c++` |
| 1201 |
if language == 'cpp': |
| 1202 |
language = 'c++' |
| 1203 |
|
| 1204 |
# Set the --profile flag based on meson's debug option |
| 1205 |
debug = state.get_option('debug') |
| 1206 |
assert isinstance(debug, bool), 'for mypy' |
| 1207 |
|
| 1208 |
command: list[str | Program] = [ |
| 1209 |
self._cbindgen_bin, '--output', '@OUTPUT@', '--config', |
| 1210 |
'@INPUT0@', '--quiet', '--lang', language, |
| 1211 |
'--profile', 'debug' if debug else 'release', |
| 1212 |
] |
| 1213 |
if language == 'c': |
| 1214 |
command.append('--cpp-compat') |
| 1215 |
if self._cbindgen_has_depfile: |
| 1216 |
command.extend(['--depfile', '@DEPFILE@']) |
| 1217 |
command.extend(['--', '@INPUT1@']) # must be last |
| 1218 |
|
| 1219 |
config_file = self.interpreter.source_strings_to_files([kwargs['config']]) |
| 1220 |
|
| 1221 |
target = CustomTarget( |
| 1222 |
f'rustmod-cbindgen-{outfile}', |
| 1223 |
state.subdir, |
| 1224 |
state.environment, |
| 1225 |
command, |
| 1226 |
[config_file[0], infile], |
| 1227 |
[outfile], |
| 1228 |
state.current_build_project, |
| 1229 |
depfile=f'{name}.d', |
| 1230 |
depend_files=depend_files, |
| 1231 |
extra_depends=depends, |
| 1232 |
install=kwargs['install'], |
| 1233 |
install_dir=[kwargs['install_dir']], |
| 1234 |
install_tag=['devel'], |
| 1235 |
) |
| 1236 |
|
| 1237 |
return ModuleReturnValue(target, [target]) |
| 1238 |
|
| 1239 |
|
| 1240 |
def initialize(interp: Interpreter) -> RustModule: |
| 1241 |
return RustModule(interp) |