Skip to main content

cargo/util/context/
target.rs

1use super::{CV, ConfigKey, ConfigRelativePath, GlobalContext, OptValue, PathAndArgs, StringList};
2use crate::core::compiler::{BuildOutput, LibraryPath, LinkArgTarget};
3use crate::util::CargoResult;
4use crate::util::data_structures::HashMap;
5use serde::Deserialize;
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::rc::Rc;
9
10/// Config definition of a `[target.'cfg(…)']` table.
11///
12/// This is a subset of `TargetConfig`.
13#[derive(Debug, Deserialize)]
14pub struct TargetCfgConfig {
15    pub runner: OptValue<PathAndArgs>,
16    pub rustflags: OptValue<StringList>,
17    pub rustdocflags: OptValue<StringList>,
18    pub linker: OptValue<ConfigRelativePath>,
19    // This is here just to ignore fields from normal `TargetConfig` because
20    // all `[target]` tables are getting deserialized, whether they start with
21    // `cfg(` or not.
22    #[serde(flatten)]
23    pub other: BTreeMap<String, toml::Value>,
24}
25
26/// Config definition of a `[target]` table or `[host]`.
27#[derive(Debug, Clone, Default)]
28pub struct TargetConfig {
29    /// Process to run as a wrapper for `cargo run`, `test`, and `bench` commands.
30    pub runner: OptValue<PathAndArgs>,
31    /// Additional rustc flags to pass.
32    pub rustflags: OptValue<StringList>,
33    /// Additional rustdoc flags to pass.
34    pub rustdocflags: OptValue<StringList>,
35    /// The path of the linker for this target.
36    pub linker: OptValue<ConfigRelativePath>,
37    /// Build script override for the given library name.
38    ///
39    /// Any package with a `links` value for the given library name will skip
40    /// running its build script and instead use the given output from the
41    /// config file.
42    pub links_overrides: Rc<BTreeMap<String, BuildOutput>>,
43}
44
45/// Loads all of the `target.'cfg()'` tables.
46pub(super) fn load_target_cfgs(
47    gctx: &GlobalContext,
48) -> CargoResult<Vec<(String, TargetCfgConfig)>> {
49    // Load all [target] tables, filter out the cfg() entries.
50    let mut result = Vec::new();
51    // Use a BTreeMap so the keys are sorted. This is important for
52    // deterministic ordering of rustflags, which affects fingerprinting and
53    // rebuilds. We may perhaps one day wish to ensure a deterministic
54    // ordering via the order keys were defined in files perhaps.
55    let target: BTreeMap<String, TargetCfgConfig> = gctx.get("target")?;
56    tracing::debug!("Got all targets {:#?}", target);
57    for (key, cfg) in target {
58        if let Ok(platform) = key.parse::<cargo_platform::Platform>() {
59            let mut warnings = Vec::new();
60            platform.check_cfg_keywords(&mut warnings, &Path::new(".cargo/config.toml"));
61            for w in warnings {
62                gctx.shell().warn(w)?;
63            }
64        }
65        if key.starts_with("cfg(") {
66            // Unfortunately this is not able to display the location of the
67            // unused key. Using config::Value<toml::Value> doesn't work. One
68            // solution might be to create a special "Any" type, but I think
69            // that will be quite difficult with the current design.
70            for other_key in cfg.other.keys() {
71                gctx.shell().warn(format!(
72                    "unused key `{}` in [target] config table `{}`",
73                    other_key, key
74                ))?;
75            }
76            result.push((key, cfg));
77        }
78    }
79    Ok(result)
80}
81
82/// Returns true if the `[target]` table should be applied to host targets.
83pub(super) fn get_target_applies_to_host(gctx: &GlobalContext) -> CargoResult<bool> {
84    if gctx.cli_unstable().target_applies_to_host {
85        if let Ok(target_applies_to_host) = gctx.get::<bool>("target-applies-to-host") {
86            Ok(target_applies_to_host)
87        } else {
88            Ok(!gctx.cli_unstable().host_config)
89        }
90    } else if gctx.cli_unstable().host_config {
91        anyhow::bail!(
92            "the -Zhost-config flag requires the -Ztarget-applies-to-host flag to be set"
93        );
94    } else {
95        Ok(true)
96    }
97}
98
99/// Loads a single `[host]` table for the given triple.
100pub(super) fn load_host_triple(gctx: &GlobalContext, triple: &str) -> CargoResult<TargetConfig> {
101    if gctx.cli_unstable().host_config {
102        let host_triple_prefix = format!("host.{}", triple);
103        let host_triple_key = ConfigKey::from_str(&host_triple_prefix);
104        let host_prefix = match gctx.get_cv(&host_triple_key)? {
105            Some(_) => host_triple_prefix,
106            None => "host".to_string(),
107        };
108        load_config_table(gctx, &host_prefix)
109    } else {
110        Ok(TargetConfig::default())
111    }
112}
113
114/// Loads a single `[target]` table for the given triple.
115pub(super) fn load_target_triple(gctx: &GlobalContext, triple: &str) -> CargoResult<TargetConfig> {
116    load_config_table(gctx, &format!("target.{}", triple))
117}
118
119/// Loads a single table for the given prefix.
120fn load_config_table(gctx: &GlobalContext, prefix: &str) -> CargoResult<TargetConfig> {
121    // This needs to get each field individually because it cannot fetch the
122    // struct all at once due to `links_overrides`. Can't use `serde(flatten)`
123    // because it causes serde to use `deserialize_map` which means the config
124    // deserializer does not know which keys to deserialize, which means
125    // environment variables would not work.
126    let runner: OptValue<PathAndArgs> = gctx.get(&format!("{prefix}.runner"))?;
127    let rustflags: OptValue<StringList> = gctx.get(&format!("{prefix}.rustflags"))?;
128    let rustdocflags: OptValue<StringList> = gctx.get(&format!("{prefix}.rustdocflags"))?;
129    let linker: OptValue<ConfigRelativePath> = gctx.get(&format!("{prefix}.linker"))?;
130    // Links do not support environment variables.
131    let target_key = ConfigKey::from_str(prefix);
132    let links_overrides = match gctx.get_table(&target_key)? {
133        Some(links) => parse_links_overrides(&target_key, links.val)?,
134        None => BTreeMap::new(),
135    };
136    Ok(TargetConfig {
137        runner,
138        rustflags,
139        rustdocflags,
140        linker,
141        links_overrides: Rc::new(links_overrides),
142    })
143}
144
145fn parse_links_overrides(
146    target_key: &ConfigKey,
147    links: HashMap<String, CV>,
148) -> CargoResult<BTreeMap<String, BuildOutput>> {
149    let mut links_overrides = BTreeMap::new();
150
151    for (lib_name, value) in links {
152        // Skip these keys, it shares the namespace with `TargetConfig`.
153        match lib_name.as_str() {
154            // `ar` is a historical thing.
155            "ar" | "linker" | "runner" | "rustflags" | "rustdocflags" => continue,
156            _ => {}
157        }
158        let mut output = BuildOutput::default();
159        let table = value.table(&format!("{}.{}", target_key, lib_name))?.0;
160        // We require deterministic order of evaluation, so we must sort the pairs by key first.
161        let mut pairs = Vec::new();
162        for (k, value) in table {
163            pairs.push((k, value));
164        }
165        pairs.sort_by_key(|p| p.0);
166        for (key, value) in pairs {
167            match key.as_str() {
168                "rustc-flags" => {
169                    let flags = value.string(key)?;
170                    let whence = format!("target config `{}.{}` (in {})", target_key, key, flags.1);
171                    let (paths, links) = BuildOutput::parse_rustc_flags(flags.0, &whence)?;
172                    output
173                        .library_paths
174                        .extend(paths.into_iter().map(LibraryPath::External));
175                    output.library_links.extend(links);
176                }
177                "rustc-link-lib" => {
178                    let list = value.string_list(key)?;
179                    output
180                        .library_links
181                        .extend(list.iter().map(|v| v.0.clone()));
182                }
183                "rustc-link-search" => {
184                    let list = value.string_list(key)?;
185                    output.library_paths.extend(
186                        list.iter()
187                            .map(|v| PathBuf::from(&v.0))
188                            .map(LibraryPath::External),
189                    );
190                }
191                "rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
192                    let args = extra_link_args(LinkArgTarget::Cdylib, key, value)?;
193                    output.linker_args.extend(args);
194                }
195                "rustc-link-arg-bins" => {
196                    let args = extra_link_args(LinkArgTarget::Bin, key, value)?;
197                    output.linker_args.extend(args);
198                }
199                "rustc-link-arg" => {
200                    let args = extra_link_args(LinkArgTarget::All, key, value)?;
201                    output.linker_args.extend(args);
202                }
203                "rustc-link-arg-tests" => {
204                    let args = extra_link_args(LinkArgTarget::Test, key, value)?;
205                    output.linker_args.extend(args);
206                }
207                "rustc-link-arg-benches" => {
208                    let args = extra_link_args(LinkArgTarget::Bench, key, value)?;
209                    output.linker_args.extend(args);
210                }
211                "rustc-link-arg-examples" => {
212                    let args = extra_link_args(LinkArgTarget::Example, key, value)?;
213                    output.linker_args.extend(args);
214                }
215                "rustc-cfg" => {
216                    let list = value.string_list(key)?;
217                    output.cfgs.extend(list.iter().map(|v| v.0.clone()));
218                }
219                "rustc-check-cfg" => {
220                    let list = value.string_list(key)?;
221                    output.check_cfgs.extend(list.iter().map(|v| v.0.clone()));
222                }
223                "rustc-env" => {
224                    for (name, val) in value.table(key)?.0 {
225                        let val = val.string(name)?.0;
226                        output.env.push((name.clone(), val.to_string()));
227                    }
228                }
229                "warning" | "rerun-if-changed" | "rerun-if-env-changed" => {
230                    anyhow::bail!("`{}` is not supported in build script overrides", key);
231                }
232                _ => {
233                    let val = value.string(key)?.0;
234                    output.metadata.push((key.clone(), val.to_string()));
235                }
236            }
237        }
238        links_overrides.insert(lib_name, output);
239    }
240    Ok(links_overrides)
241}
242
243fn extra_link_args(
244    link_type: LinkArgTarget,
245    key: &str,
246    value: &CV,
247) -> CargoResult<Vec<(LinkArgTarget, String)>> {
248    let args = value.string_list(key)?;
249    Ok(args.into_iter().map(|v| (link_type.clone(), v.0)).collect())
250}