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::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}
72
73impl ProjectJsonTargetSpec {
74    pub(crate) fn runnable_args(&self, kind: &RunnableKind) -> Option<Runnable> {
75        match kind {
76            RunnableKind::Bin => {
77                for runnable in &self.shell_runnables {
78                    if matches!(runnable.kind, project_model::project_json::RunnableKind::Run) {
79                        return Some(runnable.clone());
80                    }
81                }
82
83                None
84            }
85            RunnableKind::Test { test_id, .. } => {
86                for runnable in &self.shell_runnables {
87                    if matches!(runnable.kind, project_model::project_json::RunnableKind::TestOne) {
88                        let mut runnable = runnable.clone();
89
90                        let replaced_args: Vec<_> = runnable
91                            .args
92                            .iter()
93                            .map(|arg| arg.replace("{test_id}", &test_id.to_string()))
94                            .map(|arg| arg.replace("{label}", &self.label))
95                            .collect();
96                        runnable.args = replaced_args;
97
98                        return Some(runnable);
99                    }
100                }
101
102                None
103            }
104            RunnableKind::TestMod { .. } => None,
105            RunnableKind::Bench { .. } => None,
106            RunnableKind::DocTest { .. } => None,
107        }
108    }
109}
110
111impl CargoTargetSpec {
112    pub(crate) fn runnable_args(
113        snap: &GlobalStateSnapshot,
114        spec: Option<CargoTargetSpec>,
115        kind: &RunnableKind,
116        cfg: &Option<CfgExpr>,
117    ) -> (Vec<String>, Vec<String>) {
118        let config = snap.config.runnables(None);
119        let extra_test_binary_args = config.extra_test_binary_args;
120
121        let mut cargo_args = Vec::new();
122        let mut executable_args = Vec::new();
123
124        match kind {
125            RunnableKind::Test { test_id, attr } => {
126                cargo_args.push("test".to_owned());
127                executable_args.push(test_id.to_string());
128                if let TestId::Path(_) = test_id {
129                    executable_args.push("--exact".to_owned());
130                }
131                executable_args.extend(extra_test_binary_args);
132                if attr.ignore {
133                    executable_args.push("--ignored".to_owned());
134                }
135            }
136            RunnableKind::TestMod { path } => {
137                cargo_args.push("test".to_owned());
138                executable_args.push(path.clone());
139                executable_args.extend(extra_test_binary_args);
140            }
141            RunnableKind::Bench { test_id } => {
142                cargo_args.push("bench".to_owned());
143                executable_args.push(test_id.to_string());
144                if let TestId::Path(_) = test_id {
145                    executable_args.push("--exact".to_owned());
146                }
147                executable_args.extend(extra_test_binary_args);
148            }
149            RunnableKind::DocTest { test_id } => {
150                cargo_args.push("test".to_owned());
151                cargo_args.push("--doc".to_owned());
152                executable_args.push(test_id.to_string());
153                executable_args.extend(extra_test_binary_args);
154            }
155            RunnableKind::Bin => {
156                let subcommand = match spec {
157                    Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => "test",
158                    _ => "run",
159                };
160                cargo_args.push(subcommand.to_owned());
161            }
162        }
163
164        let (allowed_features, target_required_features) = if let Some(mut spec) = spec {
165            let allowed_features = mem::take(&mut spec.features);
166            let required_features = mem::take(&mut spec.required_features);
167            spec.push_to(&mut cargo_args, kind);
168            (allowed_features, required_features)
169        } else {
170            (Default::default(), Default::default())
171        };
172
173        let cargo_config = snap.config.cargo(None);
174
175        match &cargo_config.features {
176            CargoFeatures::All => {
177                cargo_args.push("--all-features".to_owned());
178                for feature in target_required_features {
179                    cargo_args.push("--features".to_owned());
180                    cargo_args.push(feature);
181                }
182            }
183            CargoFeatures::Selected { features, no_default_features } => {
184                let mut feats = Vec::new();
185                if let Some(cfg) = cfg.as_ref() {
186                    required_features(cfg, &mut feats);
187                }
188
189                feats.extend(
190                    features.iter().filter(|&feat| allowed_features.contains(feat)).cloned(),
191                );
192                feats.extend(target_required_features);
193
194                feats.dedup();
195                for feature in feats {
196                    cargo_args.push("--features".to_owned());
197                    cargo_args.push(feature);
198                }
199
200                if *no_default_features {
201                    cargo_args.push("--no-default-features".to_owned());
202                }
203            }
204        }
205        cargo_args.extend(config.cargo_extra_args.iter().cloned());
206        (cargo_args, executable_args)
207    }
208
209    pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
210        buf.push("--package".to_owned());
211        buf.push(self.package);
212
213        // Can't mix --doc with other target flags
214        if let RunnableKind::DocTest { .. } = kind {
215            return;
216        }
217        match self.target_kind {
218            TargetKind::Bin => {
219                buf.push("--bin".to_owned());
220                buf.push(self.target);
221            }
222            TargetKind::Test => {
223                buf.push("--test".to_owned());
224                buf.push(self.target);
225            }
226            TargetKind::Bench => {
227                buf.push("--bench".to_owned());
228                buf.push(self.target);
229            }
230            TargetKind::Example => {
231                buf.push("--example".to_owned());
232                buf.push(self.target);
233            }
234            TargetKind::Lib { is_proc_macro: _ } => {
235                buf.push("--lib".to_owned());
236            }
237            TargetKind::Other | TargetKind::BuildScript => (),
238        }
239    }
240}
241
242/// Fill minimal features needed
243fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
244    match cfg_expr {
245        CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if *key == sym::feature => {
246            features.push(value.to_string())
247        }
248        CfgExpr::All(preds) => {
249            preds.iter().for_each(|cfg| required_features(cfg, features));
250        }
251        CfgExpr::Any(preds) => {
252            for cfg in preds.iter() {
253                let len_features = features.len();
254                required_features(cfg, features);
255                if len_features != features.len() {
256                    break;
257                }
258            }
259        }
260        _ => {}
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    use ide::Edition;
269    use syntax::{
270        SmolStr,
271        ast::{self, AstNode},
272    };
273    use syntax_bridge::{
274        DocCommentDesugarMode,
275        dummy_test_span_utils::{DUMMY, DummyTestSpanMap},
276        syntax_node_to_token_tree,
277    };
278
279    fn check(cfg: &str, expected_features: &[&str]) {
280        let cfg_expr = {
281            let source_file = ast::SourceFile::parse(cfg, Edition::CURRENT).ok().unwrap();
282            let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
283            let tt = syntax_node_to_token_tree(
284                tt.syntax(),
285                &DummyTestSpanMap,
286                DUMMY,
287                DocCommentDesugarMode::Mbe,
288            );
289            CfgExpr::parse(&tt)
290        };
291
292        let mut features = vec![];
293        required_features(&cfg_expr, &mut features);
294
295        let expected_features =
296            expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
297
298        assert_eq!(features, expected_features);
299    }
300
301    #[test]
302    fn test_cfg_expr_minimal_features_needed() {
303        check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
304        check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
305        check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
306        check(r#"#![cfg(foo)]"#, &[]);
307    }
308}