Skip to main content

rust_analyzer/
target_spec.rs

1//! See `TargetSpec`
2
3use std::mem;
4
5use cargo_metadata::PackageId;
6use cfg::{CfgAtom, CfgExpr};
7use hir::sym;
8use ide::{Cancellable, Crate, FileId, RunnableKind, TestId};
9use project_model::project_json::{self, Runnable};
10use project_model::{CargoFeatures, ManifestPath, TargetKind};
11use rustc_hash::FxHashSet;
12use triomphe::Arc;
13use vfs::AbsPathBuf;
14
15use crate::global_state::GlobalStateSnapshot;
16
17/// A target represents a thing we can build or test.
18///
19/// We use it to calculate the CLI arguments required to build, run or
20/// test the target.
21#[derive(Clone, Debug)]
22pub(crate) enum TargetSpec {
23    Cargo(CargoTargetSpec),
24    ProjectJson(ProjectJsonTargetSpec),
25}
26
27impl TargetSpec {
28    pub(crate) fn for_file(
29        global_state_snapshot: &GlobalStateSnapshot,
30        file_id: FileId,
31    ) -> Cancellable<Option<Self>> {
32        let crate_id = match &*global_state_snapshot.analysis.crates_for(file_id)? {
33            &[crate_id, ..] => crate_id,
34            _ => return Ok(None),
35        };
36
37        Ok(global_state_snapshot.target_spec_for_crate(crate_id))
38    }
39
40    pub(crate) fn target_kind(&self) -> TargetKind {
41        match self {
42            TargetSpec::Cargo(cargo) => cargo.target_kind,
43            TargetSpec::ProjectJson(project_json) => project_json.target_kind,
44        }
45    }
46}
47
48/// Abstract representation of Cargo target.
49///
50/// We use it to cook up the set of cli args we need to pass to Cargo to
51/// build/test/run the target.
52#[derive(Clone, Debug)]
53pub(crate) struct CargoTargetSpec {
54    pub(crate) workspace_root: AbsPathBuf,
55    pub(crate) cargo_toml: ManifestPath,
56    pub(crate) package: String,
57    pub(crate) package_id: Arc<PackageId>,
58    pub(crate) target: String,
59    pub(crate) target_kind: TargetKind,
60    pub(crate) crate_id: Crate,
61    pub(crate) required_features: Vec<String>,
62    pub(crate) features: FxHashSet<String>,
63    pub(crate) sysroot_root: Option<vfs::AbsPathBuf>,
64}
65
66#[derive(Clone, Debug)]
67pub(crate) struct ProjectJsonTargetSpec {
68    pub(crate) label: String,
69    pub(crate) target_kind: TargetKind,
70    pub(crate) shell_runnables: Vec<Runnable>,
71    pub(crate) project_root: AbsPathBuf,
72}
73
74impl ProjectJsonTargetSpec {
75    fn find_replace_runnable(
76        &self,
77        kind: project_json::RunnableKind,
78        replacer: &dyn Fn(&Self, &str) -> String,
79    ) -> Option<Runnable> {
80        for runnable in &self.shell_runnables {
81            if runnable.kind == kind {
82                let mut runnable = runnable.clone();
83
84                let replaced_args: Vec<_> =
85                    runnable.args.iter().map(|arg| replacer(self, arg)).collect();
86                runnable.args = replaced_args;
87
88                return Some(runnable);
89            }
90        }
91
92        None
93    }
94
95    pub(crate) fn runnable_args(&self, kind: &RunnableKind) -> Option<Runnable> {
96        match kind {
97            RunnableKind::Bin => self
98                .find_replace_runnable(project_json::RunnableKind::Run, &|this, arg| {
99                    arg.replace("{label}", &this.label)
100                }),
101            RunnableKind::Test { test_id, .. } => {
102                self.find_replace_runnable(project_json::RunnableKind::Run, &|this, arg| {
103                    arg.replace("{label}", &this.label).replace("{test_id}", &test_id.to_string())
104                })
105            }
106            RunnableKind::TestMod { path } => self
107                .find_replace_runnable(project_json::RunnableKind::TestMod, &|this, arg| {
108                    arg.replace("{label}", &this.label).replace("{test_pattern}", path)
109                }),
110            RunnableKind::Bench { test_id } => {
111                self.find_replace_runnable(project_json::RunnableKind::BenchOne, &|this, arg| {
112                    arg.replace("{label}", &this.label).replace("{bench_id}", &test_id.to_string())
113                })
114            }
115            RunnableKind::DocTest { test_id } => {
116                self.find_replace_runnable(project_json::RunnableKind::DocTestOne, &|this, arg| {
117                    arg.replace("{label}", &this.label).replace("{test_id}", &test_id.to_string())
118                })
119            }
120        }
121    }
122}
123
124impl CargoTargetSpec {
125    pub(crate) fn runnable_args(
126        snap: &GlobalStateSnapshot,
127        spec: Option<CargoTargetSpec>,
128        kind: &RunnableKind,
129        cfg: &Option<CfgExpr>,
130    ) -> (Vec<String>, Vec<String>) {
131        let config = snap.config.runnables(None);
132        let extra_test_binary_args = config.extra_test_binary_args;
133
134        let mut cargo_args = Vec::new();
135        let executable_args = Self::executable_args_for(kind, extra_test_binary_args);
136
137        match kind {
138            RunnableKind::Test { .. } => {
139                cargo_args.push(config.test_command);
140            }
141            RunnableKind::TestMod { .. } => {
142                cargo_args.push(config.test_command);
143            }
144            RunnableKind::Bench { .. } => {
145                cargo_args.push(config.bench_command);
146            }
147            RunnableKind::DocTest { .. } => {
148                cargo_args.push("test".to_owned());
149                cargo_args.push("--doc".to_owned());
150            }
151            RunnableKind::Bin => {
152                let subcommand = match spec {
153                    Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => {
154                        config.test_command
155                    }
156                    _ => "run".to_owned(),
157                };
158                cargo_args.push(subcommand);
159            }
160        }
161
162        let (allowed_features, target_required_features) = if let Some(mut spec) = spec {
163            let allowed_features = mem::take(&mut spec.features);
164            let required_features = mem::take(&mut spec.required_features);
165            spec.push_to(&mut cargo_args, kind);
166            (allowed_features, required_features)
167        } else {
168            (Default::default(), Default::default())
169        };
170
171        let cargo_config = snap.config.cargo(None);
172
173        match &cargo_config.features {
174            CargoFeatures::All => {
175                cargo_args.push("--all-features".to_owned());
176                for feature in target_required_features {
177                    cargo_args.push("--features".to_owned());
178                    cargo_args.push(feature);
179                }
180            }
181            CargoFeatures::Selected { features, no_default_features } => {
182                let mut feats = Vec::new();
183                if let Some(cfg) = cfg.as_ref() {
184                    required_features(cfg, &mut feats);
185                }
186
187                feats.extend(
188                    features.iter().filter(|&feat| allowed_features.contains(feat)).cloned(),
189                );
190                feats.extend(target_required_features);
191
192                feats.dedup();
193                for feature in feats {
194                    cargo_args.push("--features".to_owned());
195                    cargo_args.push(feature);
196                }
197
198                if *no_default_features {
199                    cargo_args.push("--no-default-features".to_owned());
200                }
201            }
202        }
203        cargo_args.extend(config.cargo_extra_args.iter().cloned());
204        (cargo_args, executable_args)
205    }
206
207    pub(crate) fn override_command(
208        snap: &GlobalStateSnapshot,
209        spec: Option<CargoTargetSpec>,
210        kind: &RunnableKind,
211    ) -> Option<Vec<String>> {
212        let config = snap.config.runnables(None);
213        let (args, test_name) = match kind {
214            RunnableKind::Test { test_id, .. } => {
215                (config.test_override_command, Some(test_id.to_string()))
216            }
217            RunnableKind::TestMod { path } => (config.test_override_command, Some(path.clone())),
218            RunnableKind::Bench { test_id } => {
219                (config.bench_override_command, Some(test_id.to_string()))
220            }
221            RunnableKind::DocTest { test_id } => {
222                (config.doc_test_override_command, Some(test_id.to_string()))
223            }
224            RunnableKind::Bin => match spec {
225                Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => {
226                    (config.test_override_command, None)
227                }
228                _ => (None, None),
229            },
230        };
231        let test_name = test_name.unwrap_or_default();
232
233        let exact = match kind {
234            RunnableKind::Test { test_id } | RunnableKind::Bench { test_id } => match test_id {
235                TestId::Path(_) => "--exact",
236                TestId::Name(_) => "",
237            },
238            _ => "",
239        };
240        let include_ignored = match kind {
241            RunnableKind::Test { .. } => "--include-ignored",
242            _ => "",
243        };
244
245        let target_arg = |kind| match kind {
246            TargetKind::Bin => "--bin",
247            TargetKind::Test => "--test",
248            TargetKind::Bench => "--bench",
249            TargetKind::Example => "--example",
250            TargetKind::Lib { .. } => "--lib",
251            TargetKind::BuildScript | TargetKind::Other => "",
252        };
253
254        let target = |kind, target| match kind {
255            TargetKind::Bin | TargetKind::Test | TargetKind::Bench | TargetKind::Example => target,
256            _ => "",
257        };
258
259        let replace_placeholders = |arg: String| match &spec {
260            Some(spec) => arg
261                .replace("${package}", &spec.package)
262                .replace("${target_arg}", target_arg(spec.target_kind))
263                .replace("${target}", target(spec.target_kind, &spec.target))
264                .replace("${test_name}", &test_name)
265                .replace("${exact}", exact)
266                .replace("${include_ignored}", include_ignored),
267            _ => arg,
268        };
269
270        let extra_test_binary_args = config.extra_test_binary_args;
271        let executable_args = Self::executable_args_for(kind, extra_test_binary_args);
272
273        args.map(|mut args| {
274            let exec_args_idx = args.iter().position(|a| a == "${executable_args}");
275
276            if let Some(idx) = exec_args_idx {
277                args.splice(idx..idx + 1, executable_args);
278            }
279
280            args.into_iter().map(replace_placeholders).filter(|a| !a.trim().is_empty()).collect()
281        })
282    }
283
284    fn executable_args_for(
285        kind: &RunnableKind,
286        extra_test_binary_args: impl IntoIterator<Item = String>,
287    ) -> Vec<String> {
288        let mut executable_args = Vec::new();
289
290        match kind {
291            RunnableKind::Test { test_id } => {
292                executable_args.push(test_id.to_string());
293                if let TestId::Path(_) = test_id {
294                    executable_args.push("--exact".to_owned());
295                }
296                executable_args.extend(extra_test_binary_args);
297                executable_args.push("--include-ignored".to_owned());
298            }
299            RunnableKind::TestMod { path } => {
300                executable_args.push(path.clone());
301                executable_args.extend(extra_test_binary_args);
302            }
303            RunnableKind::Bench { test_id } => {
304                executable_args.push(test_id.to_string());
305                if let TestId::Path(_) = test_id {
306                    executable_args.push("--exact".to_owned());
307                }
308                executable_args.extend(extra_test_binary_args);
309            }
310            RunnableKind::DocTest { test_id } => {
311                executable_args.push(test_id.to_string());
312                executable_args.extend(extra_test_binary_args);
313            }
314            RunnableKind::Bin => {}
315        }
316
317        executable_args
318    }
319
320    pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
321        buf.push("--package".to_owned());
322        buf.push(self.package);
323
324        // Can't mix --doc with other target flags
325        if let RunnableKind::DocTest { .. } = kind {
326            return;
327        }
328        match self.target_kind {
329            TargetKind::Bin => {
330                buf.push("--bin".to_owned());
331                buf.push(self.target);
332            }
333            TargetKind::Test => {
334                buf.push("--test".to_owned());
335                buf.push(self.target);
336            }
337            TargetKind::Bench => {
338                buf.push("--bench".to_owned());
339                buf.push(self.target);
340            }
341            TargetKind::Example => {
342                buf.push("--example".to_owned());
343                buf.push(self.target);
344            }
345            TargetKind::Lib { is_proc_macro: _ } => {
346                buf.push("--lib".to_owned());
347            }
348            TargetKind::Other | TargetKind::BuildScript => (),
349        }
350    }
351}
352
353/// Fill minimal features needed
354fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
355    match cfg_expr {
356        CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if *key == sym::feature => {
357            features.push(value.to_string())
358        }
359        CfgExpr::All(preds) => {
360            preds.iter().for_each(|cfg| required_features(cfg, features));
361        }
362        CfgExpr::Any(preds) => {
363            for cfg in preds.iter() {
364                let len_features = features.len();
365                required_features(cfg, features);
366                if len_features != features.len() {
367                    break;
368                }
369            }
370        }
371        _ => {}
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    use ide::Edition;
380    use syntax::{
381        SmolStr,
382        ast::{self, AstNode},
383    };
384
385    fn check(cfg: &str, expected_features: &[&str]) {
386        let cfg_expr = {
387            let source_file = ast::SourceFile::parse(cfg, Edition::CURRENT).ok().unwrap();
388            let cfg_predicate =
389                source_file.syntax().descendants().find_map(ast::CfgPredicate::cast).unwrap();
390            CfgExpr::parse_from_ast(cfg_predicate)
391        };
392
393        let mut features = vec![];
394        required_features(&cfg_expr, &mut features);
395
396        let expected_features =
397            expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
398
399        assert_eq!(features, expected_features);
400    }
401
402    #[test]
403    fn test_cfg_expr_minimal_features_needed() {
404        check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
405        check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
406        check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
407        check(r#"#![cfg(foo)]"#, &[]);
408    }
409}