Skip to main content

cargo/context/
target.rs

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