Skip to main content

cargo/core/compiler/
compilation.rs

1use std::collections::{BTreeSet, HashMap, HashSet};
2use std::env;
3use std::ffi::OsStr;
4use std::path::PathBuf;
5
6use semver::Version;
7
8use super::BuildContext;
9use crate::core::{Edition, Package, PackageId, Target, TargetKind};
10use crate::util::{self, join_paths, process, CargoResult, CfgExpr, Config, ProcessBuilder};
11
12pub struct Doctest {
13    /// The package being doctested.
14    pub package: Package,
15    /// The target being tested (currently always the package's lib).
16    pub target: Target,
17    /// Extern dependencies needed by `rustdoc`. The path is the location of
18    /// the compiled lib.
19    pub deps: Vec<(String, PathBuf)>,
20}
21
22/// A structure returning the result of a compilation.
23pub struct Compilation<'cfg> {
24    /// A mapping from a package to the list of libraries that need to be
25    /// linked when working with that package.
26    pub libraries: HashMap<PackageId, HashSet<(Target, PathBuf)>>,
27
28    /// An array of all tests created during this compilation.
29    pub tests: Vec<(Package, TargetKind, String, PathBuf)>,
30
31    /// An array of all binaries created.
32    pub binaries: Vec<PathBuf>,
33
34    /// All directories for the output of native build commands.
35    ///
36    /// This is currently used to drive some entries which are added to the
37    /// LD_LIBRARY_PATH as appropriate.
38    ///
39    /// The order should be deterministic.
40    pub native_dirs: BTreeSet<PathBuf>,
41
42    /// Root output directory (for the local package's artifacts)
43    pub root_output: PathBuf,
44
45    /// Output directory for rust dependencies.
46    /// May be for the host or for a specific target.
47    pub deps_output: PathBuf,
48
49    /// Output directory for the rust host dependencies.
50    pub host_deps_output: PathBuf,
51
52    /// The path to rustc's own libstd
53    pub host_dylib_path: Option<PathBuf>,
54
55    /// The path to libstd for the target
56    pub target_dylib_path: Option<PathBuf>,
57
58    /// Extra environment variables that were passed to compilations and should
59    /// be passed to future invocations of programs.
60    pub extra_env: HashMap<PackageId, Vec<(String, String)>>,
61
62    /// Libraries to test with rustdoc.
63    pub to_doc_test: Vec<Doctest>,
64
65    /// Features per package enabled during this compilation.
66    pub cfgs: HashMap<PackageId, HashSet<String>>,
67
68    /// Flags to pass to rustdoc when invoked from cargo test, per package.
69    pub rustdocflags: HashMap<PackageId, Vec<String>>,
70
71    pub host: String,
72    pub target: String,
73
74    config: &'cfg Config,
75    rustc_process: ProcessBuilder,
76
77    target_runner: Option<(PathBuf, Vec<String>)>,
78}
79
80impl<'cfg> Compilation<'cfg> {
81    pub fn new<'a>(bcx: &BuildContext<'a, 'cfg>) -> CargoResult<Compilation<'cfg>> {
82        // If we're using cargo as a rustc wrapper then we're in a situation
83        // like `cargo fix`. For now just disregard the `RUSTC_WRAPPER` env var
84        // (which is typically set to `sccache` for now). Eventually we'll
85        // probably want to implement `RUSTC_WRAPPER` for `cargo fix`, but we'll
86        // leave that open as a bug for now.
87        let mut rustc = if bcx.build_config.cargo_as_rustc_wrapper {
88            let mut rustc = bcx.rustc.process_no_wrapper();
89            let prog = rustc.get_program().to_owned();
90            rustc.env("RUSTC", prog);
91            rustc.program(env::current_exe()?);
92            rustc
93        } else {
94            bcx.rustc.process()
95        };
96        for (k, v) in bcx.build_config.extra_rustc_env.iter() {
97            rustc.env(k, v);
98        }
99        for arg in bcx.build_config.extra_rustc_args.iter() {
100            rustc.arg(arg);
101        }
102        let srv = bcx.build_config.rustfix_diagnostic_server.borrow();
103        if let Some(server) = &*srv {
104            server.configure(&mut rustc);
105        }
106        Ok(Compilation {
107            libraries: HashMap::new(),
108            native_dirs: BTreeSet::new(), // TODO: deprecated, remove
109            root_output: PathBuf::from("/"),
110            deps_output: PathBuf::from("/"),
111            host_deps_output: PathBuf::from("/"),
112            host_dylib_path: bcx.host_info.sysroot_libdir.clone(),
113            target_dylib_path: bcx.target_info.sysroot_libdir.clone(),
114            tests: Vec::new(),
115            binaries: Vec::new(),
116            extra_env: HashMap::new(),
117            to_doc_test: Vec::new(),
118            cfgs: HashMap::new(),
119            rustdocflags: HashMap::new(),
120            config: bcx.config,
121            rustc_process: rustc,
122            host: bcx.host_triple().to_string(),
123            target: bcx.target_triple().to_string(),
124            target_runner: target_runner(&bcx)?,
125        })
126    }
127
128    /// See `process`.
129    pub fn rustc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
130        let mut p = self.fill_env(self.rustc_process.clone(), pkg, true)?;
131        if target.edition() != Edition::Edition2015 {
132            p.arg(format!("--edition={}", target.edition()));
133        }
134        Ok(p)
135    }
136
137    /// See `process`.
138    pub fn rustdoc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
139        let mut p = self.fill_env(process(&*self.config.rustdoc()?), pkg, false)?;
140        if target.edition() != Edition::Edition2015 {
141            p.arg(format!("--edition={}", target.edition()));
142        }
143        Ok(p)
144    }
145
146    /// See `process`.
147    pub fn host_process<T: AsRef<OsStr>>(
148        &self,
149        cmd: T,
150        pkg: &Package,
151    ) -> CargoResult<ProcessBuilder> {
152        self.fill_env(process(cmd), pkg, true)
153    }
154
155    fn target_runner(&self) -> &Option<(PathBuf, Vec<String>)> {
156        &self.target_runner
157    }
158
159    /// See `process`.
160    pub fn target_process<T: AsRef<OsStr>>(
161        &self,
162        cmd: T,
163        pkg: &Package,
164    ) -> CargoResult<ProcessBuilder> {
165        let builder = if let Some((ref runner, ref args)) = *self.target_runner() {
166            let mut builder = process(runner);
167            builder.args(args);
168            builder.arg(cmd);
169            builder
170        } else {
171            process(cmd)
172        };
173        self.fill_env(builder, pkg, false)
174    }
175
176    /// Prepares a new process with an appropriate environment to run against
177    /// the artifacts produced by the build process.
178    ///
179    /// The package argument is also used to configure environment variables as
180    /// well as the working directory of the child process.
181    fn fill_env(
182        &self,
183        mut cmd: ProcessBuilder,
184        pkg: &Package,
185        is_host: bool,
186    ) -> CargoResult<ProcessBuilder> {
187        let mut search_path = if is_host {
188            let mut search_path = vec![self.host_deps_output.clone()];
189            search_path.extend(self.host_dylib_path.clone());
190            search_path
191        } else {
192            let mut search_path =
193                super::filter_dynamic_search_path(self.native_dirs.iter(), &self.root_output);
194            search_path.push(self.deps_output.clone());
195            search_path.push(self.root_output.clone());
196            search_path.extend(self.target_dylib_path.clone());
197            search_path
198        };
199
200        search_path.extend(util::dylib_path().into_iter());
201        let search_path = join_paths(&search_path, util::dylib_path_envvar())?;
202
203        cmd.env(util::dylib_path_envvar(), &search_path);
204        if let Some(env) = self.extra_env.get(&pkg.package_id()) {
205            for &(ref k, ref v) in env {
206                cmd.env(k, v);
207            }
208        }
209
210        let metadata = pkg.manifest().metadata();
211
212        let cargo_exe = self.config.cargo_exe()?;
213        cmd.env(crate::CARGO_ENV, cargo_exe);
214
215        // When adding new environment variables depending on
216        // crate properties which might require rebuild upon change
217        // consider adding the corresponding properties to the hash
218        // in BuildContext::target_metadata()
219        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
220            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
221            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
222            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
223            .env(
224                "CARGO_PKG_VERSION_PRE",
225                &pre_version_component(pkg.version()),
226            )
227            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
228            .env("CARGO_PKG_NAME", &*pkg.name())
229            .env(
230                "CARGO_PKG_DESCRIPTION",
231                metadata.description.as_ref().unwrap_or(&String::new()),
232            )
233            .env(
234                "CARGO_PKG_HOMEPAGE",
235                metadata.homepage.as_ref().unwrap_or(&String::new()),
236            )
237            .env(
238                "CARGO_PKG_REPOSITORY",
239                metadata.repository.as_ref().unwrap_or(&String::new()),
240            )
241            .env("CARGO_PKG_AUTHORS", &pkg.authors().join(":"))
242            .cwd(pkg.root());
243        Ok(cmd)
244    }
245}
246
247fn pre_version_component(v: &Version) -> String {
248    if v.pre.is_empty() {
249        return String::new();
250    }
251
252    let mut ret = String::new();
253
254    for (i, x) in v.pre.iter().enumerate() {
255        if i != 0 {
256            ret.push('.')
257        };
258        ret.push_str(&x.to_string());
259    }
260
261    ret
262}
263
264fn target_runner(bcx: &BuildContext<'_, '_>) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
265    let target = bcx.target_triple();
266
267    // try target.{}.runner
268    let key = format!("target.{}.runner", target);
269    if let Some(v) = bcx.config.get_path_and_args(&key)? {
270        return Ok(Some(v.val));
271    }
272
273    // try target.'cfg(...)'.runner
274    if let Some(target_cfg) = bcx.target_info.cfg() {
275        if let Some(table) = bcx.config.get_table("target")? {
276            let mut matching_runner = None;
277
278            for key in table.val.keys() {
279                if CfgExpr::matches_key(key, target_cfg) {
280                    let key = format!("target.{}.runner", key);
281                    if let Some(runner) = bcx.config.get_path_and_args(&key)? {
282                        // more than one match, error out
283                        if matching_runner.is_some() {
284                            failure::bail!(
285                                "several matching instances of `target.'cfg(..)'.runner` \
286                                 in `.cargo/config`"
287                            )
288                        }
289
290                        matching_runner = Some(runner.val);
291                    }
292                }
293            }
294
295            return Ok(matching_runner);
296        }
297    }
298
299    Ok(None)
300}