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