Skip to content

Commit

Permalink
cargo: Add support for target specific dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
xclaesse committed Oct 25, 2024
1 parent 8676322 commit 763172c
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 5 deletions.
30 changes: 27 additions & 3 deletions mesonbuild/cargo/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@
import urllib.parse
import typing as T

from . import builder
from . import version
from ..mesonlib import MesonException, Popen_safe
from . import builder, version, cfg
from ..mesonlib import MesonException, Popen_safe, MachineChoice
from .. import coredata, mlog
from ..wrap.wrap import PackageDefinition

Expand All @@ -34,6 +33,7 @@
from .. import mparser
from ..environment import Environment
from ..interpreterbase import SubProject
from ..compilers.rust import RustCompiler

# tomllib is present in python 3.11, before that it is a pypi module called tomli,
# we try to import tomllib, then tomli,
Expand Down Expand Up @@ -458,10 +458,13 @@ class PackageKey:
class Interpreter:
def __init__(self, env: Environment) -> None:
self.environment = env
self.host_rustc = T.cast('RustCompiler', self.environment.coredata.compilers[MachineChoice.HOST]['rust'])
# Map Cargo.toml's subdir to loaded manifest.
self.manifests: T.Dict[str, Manifest] = {}
# Map of cargo package (name + api) to its state
self.packages: T.Dict[PackageKey, PackageState] = {}
# Rustc's config
self.cfgs = self._get_cfgs()

def interpret(self, subdir: str) -> mparser.CodeBlockNode:
manifest = self._load_manifest(subdir)
Expand Down Expand Up @@ -505,6 +508,10 @@ def _fetch_package(self, package_name: str, api: str) -> T.Tuple[PackageState, b
manifest = self._load_manifest(subdir)
pkg = PackageState(manifest)
self.packages[key] = pkg
# Merge target specific dependencies that are enabled
for condition, dependencies in manifest.target.items():
if cfg.eval_cfg(condition, self.cfgs):
manifest.dependencies.update(dependencies)
# Fetch required dependencies recursively.
for depname, dep in manifest.dependencies.items():
if not dep.optional:
Expand Down Expand Up @@ -572,6 +579,23 @@ def _enable_feature(self, pkg: PackageState, feature: str) -> None:
else:
self._enable_feature(pkg, f)

def _get_cfgs(self) -> T.Dict[str, str]:
cfgs = self.host_rustc.get_cfgs().copy()
rustflags = self.environment.coredata.get_external_args(MachineChoice.HOST, 'rust')
rustflags_i = iter(rustflags)
for i in rustflags_i:
if i == '--cfg':
cfgs.append(next(rustflags_i))
return dict(self._split_cfg(i) for i in cfgs)

@staticmethod
def _split_cfg(cfg: str) -> T.Tuple[str, str]:
pair = cfg.split('=', maxsplit=1)
value = pair[1] if len(pair) > 1 else ''
if value and value[0] == '"':
value = value[1:-1]
return pair[0], value

def _create_project(self, pkg: PackageState, build: builder.Builder) -> T.List[mparser.BaseNode]:
"""Create the project() function call
Expand Down
8 changes: 6 additions & 2 deletions mesonbuild/compilers/rust.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,16 +142,20 @@ def _native_static_libs(self, work_dir: str, source_name: str) -> None:
def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
return ['--dep-info', outfile]

@functools.lru_cache(maxsize=None)
def get_sysroot(self) -> str:
cmd = self.get_exelist(ccache=False) + ['--print', 'sysroot']
p, stdo, stde = Popen_safe_logged(cmd)
return stdo.split('\n', maxsplit=1)[0]

@functools.lru_cache(maxsize=None)
def get_crt_static(self) -> bool:
def get_cfgs(self) -> T.List[str]:
cmd = self.get_exelist(ccache=False) + ['--print', 'cfg']
p, stdo, stde = Popen_safe_logged(cmd)
return bool(re.search('^target_feature="crt-static"$', stdo, re.MULTILINE))
return stdo.splitlines()

def get_crt_static(self) -> bool:
return 'target_feature="crt-static"' in self.get_cfgs()

def get_debug_args(self, is_debug: bool) -> T.List[str]:
return clike_debug_args[is_debug]
Expand Down
1 change: 1 addition & 0 deletions mesonbuild/interpreter/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1046,6 +1046,7 @@ def _do_subproject_cargo(self, subp_name: str, subdir: str,
mlog.warning('Cargo subproject is an experimental feature and has no backwards compatibility guarantees.',
once=True, location=self.current_node)
if self.environment.cargo is None:
self.add_languages(['rust'], True, MachineChoice.HOST)
self.environment.cargo = cargo.Interpreter(self.environment)
with mlog.nested(subp_name):
ast = self.environment.cargo.interpret(subdir)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ features = ["f1"]
[dependencies.libname]
version = "1"

[target."cfg(unix)".dependencies.unixdep]
version = "0.1"

[features]
default = ["f1"]
f1 = ["f2", "f3"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ extern "C" {
#[cfg(feature = "foo")]
#[no_mangle]
pub extern "C" fn rust_func() -> i32 {
if cfg!(unix) {
extern crate unixdep;
assert!(unixdep::only_on_unix() == 0);
}
assert!(common::common_func() == 0);
assert!(libothername::stuff() == 42);
let v: i32;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[wrap-file]
method = cargo
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "unixdep"
version = "0.1"
edition = "2021"

[lib]
path = "lib.rs"
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pub fn only_on_unix() -> i32 {
0
}

#[cfg(not(unix))]
pub fn broken() -> i32 {
plop
}

0 comments on commit 763172c

Please sign in to comment.