Skip to main content

cargo/core/compiler/
build_config.rs

1use std::cell::RefCell;
2use std::path::Path;
3
4use serde::ser;
5
6use crate::util::{CargoResult, CargoResultExt, Config, RustfixDiagnosticServer};
7
8/// Configuration information for a rustc build.
9#[derive(Debug)]
10pub struct BuildConfig {
11    /// The target arch triple, defaults to host arch
12    pub requested_target: Option<String>,
13    /// How many rustc jobs to run in parallel
14    pub jobs: u32,
15    /// Whether we are building for release
16    pub release: bool,
17    /// In what mode we are compiling
18    pub mode: CompileMode,
19    /// Whether to print std output in json format (for machine reading)
20    pub message_format: MessageFormat,
21    /// Force cargo to do a full rebuild and treat each target as changed.
22    pub force_rebuild: bool,
23    /// Output a build plan to stdout instead of actually compiling.
24    pub build_plan: bool,
25    /// Use Cargo itself as the wrapper around rustc, only used for `cargo fix`
26    pub cargo_as_rustc_wrapper: bool,
27    /// Extra env vars to inject into rustc commands
28    pub extra_rustc_env: Vec<(String, String)>,
29    /// Extra args to inject into rustc commands
30    pub extra_rustc_args: Vec<String>,
31    pub rustfix_diagnostic_server: RefCell<Option<RustfixDiagnosticServer>>,
32}
33
34impl BuildConfig {
35    /// Parse all config files to learn about build configuration. Currently
36    /// configured options are:
37    ///
38    /// * build.jobs
39    /// * build.target
40    /// * target.$target.ar
41    /// * target.$target.linker
42    /// * target.$target.libfoo.metadata
43    pub fn new(
44        config: &Config,
45        jobs: Option<u32>,
46        requested_target: &Option<String>,
47        mode: CompileMode,
48    ) -> CargoResult<BuildConfig> {
49        let requested_target = match requested_target {
50            &Some(ref target) if target.ends_with(".json") => {
51                let path = Path::new(target).canonicalize().chain_err(|| {
52                    failure::format_err!("Target path {:?} is not a valid file", target)
53                })?;
54                Some(
55                    path.into_os_string()
56                        .into_string()
57                        .map_err(|_| failure::format_err!("Target path is not valid unicode"))?,
58                )
59            }
60            other => other.clone(),
61        };
62        if let Some(ref s) = requested_target {
63            if s.trim().is_empty() {
64                failure::bail!("target was empty")
65            }
66        }
67        let cfg_target = config.get_string("build.target")?.map(|s| s.val);
68        let target = requested_target.or(cfg_target);
69
70        if jobs == Some(0) {
71            failure::bail!("jobs must be at least 1")
72        }
73        if jobs.is_some() && config.jobserver_from_env().is_some() {
74            config.shell().warn(
75                "a `-j` argument was passed to Cargo but Cargo is \
76                 also configured with an external jobserver in \
77                 its environment, ignoring the `-j` parameter",
78            )?;
79        }
80        let cfg_jobs: Option<u32> = config.get("build.jobs")?;
81        let jobs = jobs.or(cfg_jobs).unwrap_or(::num_cpus::get() as u32);
82        Ok(BuildConfig {
83            requested_target: target,
84            jobs,
85            release: false,
86            mode,
87            message_format: MessageFormat::Human,
88            force_rebuild: false,
89            build_plan: false,
90            cargo_as_rustc_wrapper: false,
91            extra_rustc_env: Vec::new(),
92            extra_rustc_args: Vec::new(),
93            rustfix_diagnostic_server: RefCell::new(None),
94        })
95    }
96
97    pub fn json_messages(&self) -> bool {
98        self.message_format == MessageFormat::Json
99    }
100
101    pub fn test(&self) -> bool {
102        self.mode == CompileMode::Test || self.mode == CompileMode::Bench
103    }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum MessageFormat {
108    Human,
109    Json,
110    Short,
111}
112
113/// The general "mode" of what to do.
114/// This is used for two purposes.  The commands themselves pass this in to
115/// `compile_ws` to tell it the general execution strategy.  This influences
116/// the default targets selected.  The other use is in the `Unit` struct
117/// to indicate what is being done with a specific target.
118#[derive(Clone, Copy, PartialEq, Debug, Eq, Hash, PartialOrd, Ord)]
119pub enum CompileMode {
120    /// A target being built for a test.
121    Test,
122    /// Building a target with `rustc` (lib or bin).
123    Build,
124    /// Building a target with `rustc` to emit `rmeta` metadata only. If
125    /// `test` is true, then it is also compiled with `--test` to check it like
126    /// a test.
127    Check { test: bool },
128    /// Used to indicate benchmarks should be built.  This is not used in
129    /// `Target` because it is essentially the same as `Test` (indicating
130    /// `--test` should be passed to rustc) and by using `Test` instead it
131    /// allows some de-duping of Units to occur.
132    Bench,
133    /// A target that will be documented with `rustdoc`.
134    /// If `deps` is true, then it will also document all dependencies.
135    Doc { deps: bool },
136    /// A target that will be tested with `rustdoc`.
137    Doctest,
138    /// A marker for Units that represent the execution of a `build.rs`
139    /// script.
140    RunCustomBuild,
141}
142
143impl ser::Serialize for CompileMode {
144    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
145    where
146        S: ser::Serializer,
147    {
148        use self::CompileMode::*;
149        match *self {
150            Test => "test".serialize(s),
151            Build => "build".serialize(s),
152            Check { .. } => "check".serialize(s),
153            Bench => "bench".serialize(s),
154            Doc { .. } => "doc".serialize(s),
155            Doctest => "doctest".serialize(s),
156            RunCustomBuild => "run-custom-build".serialize(s),
157        }
158    }
159}
160
161impl CompileMode {
162    /// Returns true if the unit is being checked.
163    pub fn is_check(self) -> bool {
164        match self {
165            CompileMode::Check { .. } => true,
166            _ => false,
167        }
168    }
169
170    /// Returns true if this is a doc or doctest. Be careful using this.
171    /// Although both run rustdoc, the dependencies for those two modes are
172    /// very different.
173    pub fn is_doc(self) -> bool {
174        match self {
175            CompileMode::Doc { .. } | CompileMode::Doctest => true,
176            _ => false,
177        }
178    }
179
180    /// Returns true if this is any type of test (test, benchmark, doctest, or
181    /// check-test).
182    pub fn is_any_test(self) -> bool {
183        match self {
184            CompileMode::Test
185            | CompileMode::Bench
186            | CompileMode::Check { test: true }
187            | CompileMode::Doctest => true,
188            _ => false,
189        }
190    }
191
192    /// Returns true if this is the *execution* of a `build.rs` script.
193    pub fn is_run_custom_build(self) -> bool {
194        self == CompileMode::RunCustomBuild
195    }
196
197    /// List of all modes (currently used by `cargo clean -p` for computing
198    /// all possible outputs).
199    pub fn all_modes() -> &'static [CompileMode] {
200        static ALL: [CompileMode; 9] = [
201            CompileMode::Test,
202            CompileMode::Build,
203            CompileMode::Check { test: true },
204            CompileMode::Check { test: false },
205            CompileMode::Bench,
206            CompileMode::Doc { deps: true },
207            CompileMode::Doc { deps: false },
208            CompileMode::Doctest,
209            CompileMode::RunCustomBuild,
210        ];
211        &ALL
212    }
213}